diff --git a/include/bolt/collaboration/collaboration_protocol.hpp b/include/bolt/collaboration/collaboration_protocol.hpp index 8246daac..d953b7a0 100644 --- a/include/bolt/collaboration/collaboration_protocol.hpp +++ b/include/bolt/collaboration/collaboration_protocol.hpp @@ -1,17 +1,18 @@ -#ifndef COLLABORATION_PROTOCOL_HPP -#define COLLABORATION_PROTOCOL_HPP +#ifndef BOLT_COLLABORATION_COLLABORATION_PROTOCOL_HPP_ +#define BOLT_COLLABORATION_COLLABORATION_PROTOCOL_HPP_ -#include "collaborative_session.hpp" -#include "document_operation.hpp" -#include "../network/websocket_server.hpp" -#include +#include +#include +#include #include -#include #include #include -#include -#include -#include +#include +#include + +#include "bolt/collaboration/collaborative_session.hpp" +#include "bolt/collaboration/document_operation.hpp" +#include "bolt/network/websocket_server.hpp" namespace bolt { namespace collaboration { @@ -27,56 +28,70 @@ enum class MessageType { ERROR_MESSAGE }; +namespace detail { + +// Escapes quotes, backslashes and control characters for embedding in a JSON string value. +inline std::string escapeJsonString(const std::string& str) { + 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; + } + return result; +} + +// Reads the integer value of "key" from a flat JSON object; returns 0 when the key is absent. +inline int extractJsonInt(const std::string& data, const std::string& key) { + auto pos = data.find("\"" + key + "\":"); + if (pos == std::string::npos) + return 0; + pos = data.find(":", pos) + 1; + auto end = data.find_first_of(",}", pos); + return std::stoi(data.substr(pos, end - pos)); +} + +} // namespace detail + struct ProtocolMessage { MessageType type; std::string documentId; std::string userId; std::string data; - + std::string serialize() const { std::string result = "{"; result += "\"type\":" + std::to_string(static_cast(type)) + ","; result += "\"documentId\":\"" + documentId + "\","; result += "\"userId\":\"" + userId + "\","; - result += "\"data\":\"" + escapeString(data) + "\""; + result += "\"data\":\"" + detail::escapeJsonString(data) + "\""; result += "}"; return result; } - + static ProtocolMessage deserialize(const std::string& json) { ProtocolMessage msg; - msg.type = static_cast(extractInt(json, "type")); + msg.type = static_cast(detail::extractJsonInt(json, "type")); msg.documentId = extractString(json, "documentId"); msg.userId = extractString(json, "userId"); msg.data = extractString(json, "data"); return msg; } -private: - 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; - } - 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; - pos = data.find(":", pos) + 1; - auto end = data.find_first_of(",}", pos); - return std::stoi(data.substr(pos, end - pos)); - } - + private: 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; auto end = data.find("\"", pos); return data.substr(pos, end - pos); @@ -84,79 +99,73 @@ struct ProtocolMessage { }; class CollaborationProtocol { -public: + public: static CollaborationProtocol& getInstance() { static CollaborationProtocol instance; return instance; } - + void initialize(int port = 8081) { auto& wsServer = WebSocketServer::getInstance(); - + // Set up WebSocket callbacks - wsServer.onConnect([this](WebSocketConnection* conn) { - handleConnection(conn); - }); - - wsServer.onDisconnect([this](WebSocketConnection* conn) { - handleDisconnection(conn); - }); - + wsServer.onConnect([this](WebSocketConnection* conn) { handleConnection(conn); }); + + wsServer.onDisconnect([this](WebSocketConnection* conn) { handleDisconnection(conn); }); + wsServer.onMessage([this](const std::string& message, WebSocketConnection* conn, bool binary) { if (!binary) { handleMessage(message, conn); } }); - + // Set up collaborative session callbacks auto& session = CollaborativeSession::getInstance(); - - session.onOperation([this](const DocumentOperation& op, const std::string& docId) { - broadcastOperation(op, docId); - }); - - session.onUserJoin([this](const UserSession& user, const std::string& docId) { - broadcastUserJoined(user, docId); - }); - - session.onUserLeave([this](const std::string& userId, const std::string& docId) { - broadcastUserLeft(userId, docId); - }); - + + session.onOperation( + [this](const DocumentOperation& op, const std::string& docId) { broadcastOperation(op, docId); }); + + session.onUserJoin( + [this](const UserSession& user, const std::string& docId) { broadcastUserJoined(user, docId); }); + + session.onUserLeave( + [this](const std::string& userId, const std::string& docId) { broadcastUserLeft(userId, docId); }); + session.onCursorUpdate([this](const std::string& userId, const Position& pos, const std::string& docId) { broadcastCursorUpdate(userId, pos, docId); }); - + // Start WebSocket server wsServer.start(port); } - + void shutdown() { auto& wsServer = WebSocketServer::getInstance(); wsServer.stop(); - + std::lock_guard lock(connectionsMutex_); connections_.clear(); userConnections_.clear(); } - + // Send document state to specific user void sendDocumentState(const std::string& userId, const std::string& documentId) { auto& session = CollaborativeSession::getInstance(); std::string content = session.getDocumentContent(documentId); auto users = session.getActiveUsers(documentId); - + ProtocolMessage msg; msg.type = MessageType::DOCUMENT_STATE; msg.documentId = documentId; msg.userId = userId; - + // Create document state data std::string stateData = "{"; - stateData += "\"content\":\"" + escapeString(content) + "\","; + stateData += "\"content\":\"" + detail::escapeJsonString(content) + "\","; stateData += "\"users\":["; for (size_t i = 0; i < users.size(); ++i) { - if (i > 0) stateData += ","; + if (i > 0) + stateData += ","; stateData += "{\"userId\":\"" + users[i].userId + "\","; stateData += "\"userName\":\"" + users[i].userName + "\","; stateData += "\"cursorLine\":" + std::to_string(users[i].cursorPosition.line) + ","; @@ -164,21 +173,21 @@ class CollaborationProtocol { } stateData += "]}"; msg.data = stateData; - + sendToUser(userId, msg.serialize()); } -private: + private: CollaborationProtocol() = default; - + void handleConnection(WebSocketConnection* conn) { std::lock_guard lock(connectionsMutex_); connections_.insert(conn); } - + void handleDisconnection(WebSocketConnection* conn) { std::lock_guard lock(connectionsMutex_); - + // Find and remove user from all documents std::string disconnectedUserId; for (auto it = userConnections_.begin(); it != userConnections_.end(); ++it) { @@ -188,9 +197,9 @@ class CollaborationProtocol { break; } } - + connections_.erase(conn); - + // Remove user from all collaborative sessions if (!disconnectedUserId.empty()) { auto& session = CollaborativeSession::getInstance(); @@ -200,11 +209,11 @@ class CollaborationProtocol { // For now, we'll let the cleanup routine handle inactive users } } - + void handleMessage(const std::string& message, WebSocketConnection* conn) { try { ProtocolMessage msg = ProtocolMessage::deserialize(message); - + switch (msg.type) { case MessageType::JOIN_DOCUMENT: handleJoinDocument(msg, conn); @@ -226,21 +235,21 @@ class CollaborationProtocol { sendError(conn, "Failed to parse message: " + std::string(e.what())); } } - + void handleJoinDocument(const ProtocolMessage& msg, WebSocketConnection* conn) { auto& session = CollaborativeSession::getInstance(); - + // Associate user with connection { std::lock_guard lock(connectionsMutex_); userConnections_[msg.userId] = conn; } - + // Create document if it doesn't exist if (session.getDocumentLines(msg.documentId).empty()) { session.createDocument(msg.documentId); } - + // Add user to document bool success = session.joinDocument(msg.userId, msg.userId, msg.documentId); if (success) { @@ -250,17 +259,17 @@ class CollaborationProtocol { sendError(conn, "Failed to join document"); } } - + void handleLeaveDocument(const ProtocolMessage& msg, WebSocketConnection* conn) { auto& session = CollaborativeSession::getInstance(); session.leaveDocument(msg.userId, msg.documentId); } - + void handleDocumentOperation(const ProtocolMessage& msg, WebSocketConnection* conn) { try { auto operation = DocumentOperation::deserialize(msg.data); auto& session = CollaborativeSession::getInstance(); - + bool success = session.applyOperation(*operation, msg.documentId); if (!success) { sendError(conn, "Failed to apply operation"); @@ -269,12 +278,12 @@ class CollaborationProtocol { sendError(conn, "Invalid operation: " + std::string(e.what())); } } - + void handleCursorUpdate(const ProtocolMessage& msg, WebSocketConnection* conn) { try { // Parse cursor position from data Position pos = parseCursorPosition(msg.data); - + DocumentOperation cursorOp(OperationType::CURSOR_MOVE, msg.userId, pos); auto& session = CollaborativeSession::getInstance(); session.applyOperation(cursorOp, msg.documentId); @@ -282,52 +291,51 @@ class CollaborationProtocol { sendError(conn, "Invalid cursor update: " + std::string(e.what())); } } - + void broadcastOperation(const DocumentOperation& op, const std::string& documentId) { ProtocolMessage msg; msg.type = MessageType::DOCUMENT_OPERATION; msg.documentId = documentId; msg.userId = op.getUserId(); msg.data = op.serialize(); - + broadcastToDocument(documentId, msg.serialize(), op.getUserId()); } - + void broadcastUserJoined(const UserSession& user, const std::string& documentId) { ProtocolMessage msg; msg.type = MessageType::USER_JOINED; msg.documentId = documentId; msg.userId = user.userId; msg.data = user.userName; - + broadcastToDocument(documentId, msg.serialize(), user.userId); } - + void broadcastUserLeft(const std::string& userId, const std::string& documentId) { ProtocolMessage msg; msg.type = MessageType::USER_LEFT; msg.documentId = documentId; msg.userId = userId; - + broadcastToDocument(documentId, msg.serialize(), userId); } - + void broadcastCursorUpdate(const std::string& userId, const Position& pos, const std::string& documentId) { ProtocolMessage msg; msg.type = MessageType::CURSOR_UPDATE; msg.documentId = documentId; msg.userId = userId; - msg.data = "{\"line\":" + std::to_string(pos.line) + - ",\"character\":" + std::to_string(pos.character) + "}"; - + msg.data = "{\"line\":" + std::to_string(pos.line) + ",\"character\":" + std::to_string(pos.character) + "}"; + broadcastToDocument(documentId, msg.serialize(), userId); } - - void broadcastToDocument(const std::string& documentId, const std::string& message, - const std::string& excludeUserId = "") { + + void broadcastToDocument(const std::string& documentId, const std::string& message, + const std::string& excludeUserId = "") { auto& session = CollaborativeSession::getInstance(); auto users = session.getActiveUsers(documentId); - + std::lock_guard lock(connectionsMutex_); for (const auto& user : users) { if (user.userId != excludeUserId) { @@ -338,7 +346,7 @@ class CollaborationProtocol { } } } - + void sendToUser(const std::string& userId, const std::string& message) { std::lock_guard lock(connectionsMutex_); auto it = userConnections_.find(userId); @@ -346,47 +354,26 @@ class CollaborationProtocol { it->second->send(message); } } - + void sendError(WebSocketConnection* conn, const std::string& error) { ProtocolMessage msg; msg.type = MessageType::ERROR_MESSAGE; msg.data = error; conn->send(msg.serialize()); } - + Position parseCursorPosition(const std::string& data) { - int line = extractInt(data, "line"); - int character = extractInt(data, "character"); + int line = detail::extractJsonInt(data, "line"); + int character = detail::extractJsonInt(data, "character"); return Position(line, character); } - - static int extractInt(const std::string& data, const std::string& key) { - auto pos = data.find("\"" + key + "\":"); - if (pos == std::string::npos) return 0; - pos = data.find(":", pos) + 1; - auto end = data.find_first_of(",}", pos); - return std::stoi(data.substr(pos, end - pos)); - } - - 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; - } - return result; - } - + std::mutex connectionsMutex_; std::set connections_; std::map userConnections_; }; -} // namespace collaboration -} // namespace bolt +} // namespace collaboration +} // namespace bolt -#endif \ No newline at end of file +#endif // BOLT_COLLABORATION_COLLABORATION_PROTOCOL_HPP_ diff --git a/include/bolt/collaboration/collaborative_session.hpp b/include/bolt/collaboration/collaborative_session.hpp index f5ad2a38..b90cbf17 100644 --- a/include/bolt/collaboration/collaborative_session.hpp +++ b/include/bolt/collaboration/collaborative_session.hpp @@ -1,17 +1,19 @@ -#ifndef COLLABORATIVE_SESSION_HPP -#define COLLABORATIVE_SESSION_HPP +#ifndef BOLT_COLLABORATION_COLLABORATIVE_SESSION_HPP_ +#define BOLT_COLLABORATION_COLLABORATIVE_SESSION_HPP_ +#include +#include #include - -#include "document_operation.hpp" -#include "operational_transform.hpp" -#include +#include #include -#include #include #include #include -#include -#include +#include +#include +#include + +#include "bolt/collaboration/document_operation.hpp" +#include "bolt/collaboration/operational_transform.hpp" namespace bolt { namespace collaboration { @@ -22,12 +24,15 @@ struct UserSession { Position cursorPosition; std::chrono::steady_clock::time_point lastActivity; bool isActive; - + UserSession() : cursorPosition(0, 0), lastActivity(std::chrono::steady_clock::now()), isActive(true) {} - + UserSession(const std::string& id, const std::string& name) - : userId(id), userName(name), cursorPosition(0, 0), - lastActivity(std::chrono::steady_clock::now()), isActive(true) {} + : userId(id), + userName(name), + cursorPosition(0, 0), + lastActivity(std::chrono::steady_clock::now()), + isActive(true) {} }; struct DocumentState { @@ -36,123 +41,121 @@ struct DocumentState { std::vector> operationHistory; std::map activeUsers; uint64_t lastSequence; - - DocumentState(const std::string& id) - : documentId(id), lastSequence(0) { - lines.push_back(""); // Start with one empty line + + explicit DocumentState(const std::string& id) : documentId(id), lastSequence(0) { + lines.push_back(""); // Start with one empty line } }; class CollaborativeSession { -public: + public: using OperationCallback = std::function; using UserJoinCallback = std::function; using UserLeaveCallback = std::function; using CursorUpdateCallback = std::function; - + static CollaborativeSession& getInstance() { static CollaborativeSession instance; return instance; } - + // Document management bool createDocument(const std::string& documentId, const std::string& initialContent = "") { - std::lock_guard lock(documentsMutex_); - + std::lock_guard lock(documentsMutex_); + if (documents_.find(documentId) != documents_.end()) { - return false; // Document already exists + return false; // Document already exists } - + auto doc = std::make_unique(documentId); if (!initialContent.empty()) { doc->lines = splitLines(initialContent); } - + documents_[documentId] = std::move(doc); return true; } - + bool removeDocument(const std::string& documentId) { - std::lock_guard lock(documentsMutex_); - + std::lock_guard lock(documentsMutex_); + auto it = documents_.find(documentId); if (it == documents_.end()) { return false; } - + // Notify all users in this document for (const auto& [userId, session] : it->second->activeUsers) { if (userLeaveCallback_) { userLeaveCallback_(userId, documentId); } } - + documents_.erase(it); return true; } - + // User management - bool joinDocument(const std::string& userId, const std::string& userName, - const std::string& documentId) { - std::lock_guard lock(documentsMutex_); - - auto docIt = documents_.find(documentId); - if (docIt == documents_.end()) { - return false; // Document doesn't exist + bool joinDocument(const std::string& userId, const std::string& userName, const std::string& documentId) { + std::lock_guard lock(documentsMutex_); + + DocumentState* docPtr = findDocumentLocked(documentId); + if (docPtr == nullptr) { + return false; // Document doesn't exist } - - auto& doc = *docIt->second; - + + auto& doc = *docPtr; + // Add user to document UserSession session(userId, userName); doc.activeUsers[userId] = session; - + // Notify other users if (userJoinCallback_) { userJoinCallback_(session, documentId); } - + return true; } - + bool leaveDocument(const std::string& userId, const std::string& documentId) { - std::lock_guard lock(documentsMutex_); - - auto docIt = documents_.find(documentId); - if (docIt == documents_.end()) { + std::lock_guard lock(documentsMutex_); + + DocumentState* docPtr = findDocumentLocked(documentId); + if (docPtr == nullptr) { return false; } - - auto& doc = *docIt->second; + + auto& doc = *docPtr; auto userIt = doc.activeUsers.find(userId); if (userIt == doc.activeUsers.end()) { return false; } - + doc.activeUsers.erase(userIt); - + // Notify other users if (userLeaveCallback_) { userLeaveCallback_(userId, documentId); } - + return true; } - + // Operation handling bool applyOperation(const DocumentOperation& operation, const std::string& documentId) { - std::lock_guard lock(documentsMutex_); - - auto docIt = documents_.find(documentId); - if (docIt == documents_.end()) { + std::lock_guard lock(documentsMutex_); + + DocumentState* docPtr = findDocumentLocked(documentId); + if (docPtr == nullptr) { return false; } - - auto& doc = *docIt->second; - + + auto& doc = *docPtr; + // Create a copy of the operation for transformation auto transformedOp = std::make_unique(operation); - + // Transform against all operations that have occurred since this operation was created for (const auto& historyOp : doc.operationHistory) { if (historyOp->getSequence() > operation.getSequence()) { @@ -160,53 +163,52 @@ class CollaborativeSession { transformedOp = std::move(temp); } } - + // Apply the transformed operation bool success = transformedOp->apply(doc.lines); if (success) { // Add to history - doc.operationHistory.push_back( - std::make_unique(*transformedOp)); + doc.operationHistory.push_back(std::make_unique(*transformedOp)); doc.lastSequence = transformedOp->getSequence(); - + // Update user cursor if it's a cursor move operation if (transformedOp->getType() == OperationType::CURSOR_MOVE) { auto userIt = doc.activeUsers.find(transformedOp->getUserId()); if (userIt != doc.activeUsers.end()) { userIt->second.cursorPosition = transformedOp->getPosition(); userIt->second.lastActivity = std::chrono::steady_clock::now(); - + if (cursorUpdateCallback_) { - cursorUpdateCallback_(transformedOp->getUserId(), - transformedOp->getPosition(), documentId); + cursorUpdateCallback_(transformedOp->getUserId(), transformedOp->getPosition(), documentId); } } } - + // Notify listeners if (operationCallback_) { operationCallback_(*transformedOp, documentId); } } - + return success; } - + // Get document state std::vector getDocumentLines(const std::string& documentId) const { - std::lock_guard lock(documentsMutex_); - + std::lock_guard lock(documentsMutex_); + auto it = documents_.find(documentId); if (it != documents_.end()) { return it->second->lines; } return {}; } - + std::string getDocumentContent(const std::string& documentId) const { auto lines = getDocumentLines(documentId); - if (lines.empty()) return ""; - + if (lines.empty()) + return ""; + std::string content; for (size_t i = 0; i < lines.size(); ++i) { content += lines[i]; @@ -216,11 +218,11 @@ class CollaborativeSession { } return content; } - + // Get active users in document std::vector getActiveUsers(const std::string& documentId) const { - std::lock_guard lock(documentsMutex_); - + std::lock_guard lock(documentsMutex_); + std::vector users; auto it = documents_.find(documentId); if (it != documents_.end()) { @@ -230,30 +232,22 @@ class CollaborativeSession { } return users; } - + // Callback registration - void onOperation(OperationCallback callback) { - operationCallback_ = callback; - } - - void onUserJoin(UserJoinCallback callback) { - userJoinCallback_ = callback; - } - - void onUserLeave(UserLeaveCallback callback) { - userLeaveCallback_ = callback; - } - - void onCursorUpdate(CursorUpdateCallback callback) { - cursorUpdateCallback_ = callback; - } - + void onOperation(OperationCallback callback) { operationCallback_ = callback; } + + void onUserJoin(UserJoinCallback callback) { userJoinCallback_ = callback; } + + void onUserLeave(UserLeaveCallback callback) { userLeaveCallback_ = callback; } + + void onCursorUpdate(CursorUpdateCallback callback) { cursorUpdateCallback_ = callback; } + // Maintenance void cleanupInactiveUsers(std::chrono::seconds inactiveThreshold = std::chrono::seconds(300)) { - std::lock_guard lock(documentsMutex_); - + std::lock_guard lock(documentsMutex_); + auto now = std::chrono::steady_clock::now(); - + for (auto& [docId, doc] : documents_) { auto userIt = doc->activeUsers.begin(); while (userIt != doc->activeUsers.end()) { @@ -268,31 +262,37 @@ class CollaborativeSession { } } } - + // Get statistics struct SessionStats { size_t totalDocuments; size_t totalActiveUsers; size_t totalOperations; }; - + SessionStats getStats() const { - std::lock_guard lock(documentsMutex_); - + std::lock_guard lock(documentsMutex_); + SessionStats stats = {0, 0, 0}; stats.totalDocuments = documents_.size(); - + for (const auto& [docId, doc] : documents_) { stats.totalActiveUsers += doc->activeUsers.size(); stats.totalOperations += doc->operationHistory.size(); } - + return stats; } -private: + private: CollaborativeSession() = default; - + + // Returns the state of documentId, or nullptr if unknown. The caller must hold documentsMutex_. + DocumentState* findDocumentLocked(const std::string& documentId) { + auto docIt = documents_.find(documentId); + return docIt == documents_.end() ? nullptr : docIt->second.get(); + } + std::vector splitLines(const std::string& content) const { std::vector lines; std::string line; @@ -304,20 +304,23 @@ class CollaborativeSession { line += c; } } - lines.push_back(line); // Add last line + lines.push_back(line); // Add last line return lines; } - - mutable std::mutex documentsMutex_; + + // Recursive on purpose: the user callbacks are invoked with this lock held, + // and the ones CollaborationProtocol installs call back into this class + // (getActiveUsers) on the same thread. + mutable std::recursive_mutex documentsMutex_; std::map> documents_; - + OperationCallback operationCallback_; UserJoinCallback userJoinCallback_; UserLeaveCallback userLeaveCallback_; CursorUpdateCallback cursorUpdateCallback_; }; -} // namespace collaboration -} // namespace bolt +} // namespace collaboration +} // namespace bolt -#endif +#endif // BOLT_COLLABORATION_COLLABORATIVE_SESSION_HPP_ diff --git a/include/bolt/core/editor_store.hpp b/include/bolt/core/editor_store.hpp index ab97eefc..e9a93c89 100644 --- a/include/bolt/core/editor_store.hpp +++ b/include/bolt/core/editor_store.hpp @@ -1,17 +1,17 @@ +#ifndef BOLT_CORE_EDITOR_STORE_HPP_ +#define BOLT_CORE_EDITOR_STORE_HPP_ -#ifndef EDITOR_STORE_HPP -#define EDITOR_STORE_HPP - -#include +#include #include #include +#include #include -#include +#include #include -#include -#include "bolt/gui_components.hpp" -#include "bolt/editor/code_folding.hpp" + #include "bolt/core/error_handling.hpp" +#include "bolt/editor/code_folding.hpp" +#include "bolt/gui_components.hpp" namespace bolt { @@ -21,12 +21,12 @@ struct EditorDocument { struct ScrollPosition { int line = 0; int character = 0; - + void validate() const { if (line < 0 || character < 0) { throw EditorException(ErrorCode::INVALID_PARAMETER, - "Scroll position cannot be negative: line=" + std::to_string(line) + - ", character=" + std::to_string(character)); + "Scroll position cannot be negative: line=" + std::to_string(line) + + ", character=" + std::to_string(character)); } } } scroll; @@ -36,30 +36,30 @@ struct EditorDocument { } cursor; // Code folding state std::vector foldingRanges; - + void validateDocument() const { if (filePath.empty()) { throw EditorException(ErrorCode::INVALID_PARAMETER, "Document file path cannot be empty"); } if (filePath.length() > MAX_FILE_PATH_LENGTH) { throw EditorException(ErrorCode::INVALID_PARAMETER, - "File path too long: " + std::to_string(filePath.length()) + - " > " + std::to_string(MAX_FILE_PATH_LENGTH)); + "File path too long: " + std::to_string(filePath.length()) + " > " + + std::to_string(MAX_FILE_PATH_LENGTH)); } if (value.length() > MAX_DOCUMENT_SIZE) { - throw EditorException(ErrorCode::INVALID_PARAMETER, - "Document too large: " + std::to_string(value.length()) + - " > " + std::to_string(MAX_DOCUMENT_SIZE)); + throw EditorException( + ErrorCode::INVALID_PARAMETER, + "Document too large: " + std::to_string(value.length()) + " > " + std::to_string(MAX_DOCUMENT_SIZE)); } scroll.validate(); } - + static constexpr size_t MAX_FILE_PATH_LENGTH = 2048; - static constexpr size_t MAX_DOCUMENT_SIZE = 50 * 1024 * 1024; // 50MB + static constexpr size_t MAX_DOCUMENT_SIZE = 50 * 1024 * 1024; // 50MB }; class EditorStore { -public: + public: static EditorStore& getInstance() { static EditorStore instance; return instance; @@ -68,69 +68,57 @@ class EditorStore { void setDocument(const std::string& path, const EditorDocument& doc) { ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty"); doc.validateDocument(); - + std::lock_guard lock(mutex_); - + if (documents_.size() >= MAX_OPEN_DOCUMENTS && documents_.find(path) == documents_.end()) { throw EditorException(ErrorCode::EDITOR_OPERATION_FAILED, - "Too many open documents: " + std::to_string(documents_.size()) + - " >= " + std::to_string(MAX_OPEN_DOCUMENTS)); + "Too many open documents: " + std::to_string(documents_.size()) + + " >= " + std::to_string(MAX_OPEN_DOCUMENTS)); } - + documents_[path] = doc; notifyListeners(); } void updateScrollPosition(const std::string& path, int line, int character) { ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty"); - + std::lock_guard lock(mutex_); - - auto it = documents_.find(path); - if (it == documents_.end()) { - throw EditorException(ErrorCode::EDITOR_DOCUMENT_INVALID, - "Document not found: " + path); - } - + + auto it = findDocumentOrThrowLocked(path, "Document not found: "); + EditorDocument::ScrollPosition pos{line, character}; pos.validate(); - + it->second.scroll = pos; notifyListeners(); } void updateFoldingRanges(const std::string& path, const std::vector& ranges) { ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty"); - + std::lock_guard lock(mutex_); - - auto it = documents_.find(path); - if (it == documents_.end()) { - throw EditorException(ErrorCode::EDITOR_DOCUMENT_INVALID, - "Document not found: " + path); - } - + + auto it = findDocumentOrThrowLocked(path, "Document not found: "); + if (ranges.size() > MAX_FOLDING_RANGES) { throw EditorException(ErrorCode::EDITOR_FOLDING_ERROR, - "Too many folding ranges: " + std::to_string(ranges.size()) + - " > " + std::to_string(MAX_FOLDING_RANGES)); + "Too many folding ranges: " + std::to_string(ranges.size()) + " > " + + std::to_string(MAX_FOLDING_RANGES)); } - + it->second.foldingRanges = ranges; notifyListeners(); } void toggleFold(const std::string& path, size_t line) { ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty"); - + std::lock_guard lock(mutex_); - - auto it = documents_.find(path); - if (it == documents_.end()) { - throw EditorException(ErrorCode::EDITOR_DOCUMENT_INVALID, - "Document not found: " + path); - } - + + auto it = findDocumentOrThrowLocked(path, "Document not found: "); + auto& ranges = it->second.foldingRanges; bool found = false; for (auto& range : ranges) { @@ -141,18 +129,18 @@ class EditorStore { break; } } - + if (!found) { throw EditorException(ErrorCode::EDITOR_FOLDING_ERROR, - "No foldable range found at line " + std::to_string(line) + " in " + path); + "No foldable range found at line " + std::to_string(line) + " in " + path); } } std::vector getFoldingRanges(const std::string& path) const { ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty"); - + std::lock_guard lock(mutex_); - + auto it = documents_.find(path); if (it != documents_.end()) { return it->second.foldingRanges; @@ -162,7 +150,7 @@ class EditorStore { EditorDocument* getCurrentDocument() { std::lock_guard lock(mutex_); - + if (!selectedFile_.empty() && documents_.count(selectedFile_)) { return &documents_[selectedFile_]; } @@ -172,9 +160,9 @@ class EditorStore { void setSelectedFile(const std::string& path) { if (!path.empty()) { ErrorHandler::validateParameter(path.length() <= EditorDocument::MAX_FILE_PATH_LENGTH, - "File path too long: " + std::to_string(path.length())); + "File path too long: " + std::to_string(path.length())); } - + std::lock_guard lock(mutex_); selectedFile_ = path; notifyListeners(); @@ -187,53 +175,60 @@ class EditorStore { void addListener(std::function listener) { ErrorHandler::validateParameter(listener != nullptr, "Listener cannot be null"); - + std::lock_guard lock(mutex_); - + if (listeners_.size() >= MAX_LISTENERS) { - throw EditorException(ErrorCode::STORE_STATE_INVALID, - "Too many listeners: " + std::to_string(listeners_.size()) + - " >= " + std::to_string(MAX_LISTENERS)); + throw EditorException( + ErrorCode::STORE_STATE_INVALID, + "Too many listeners: " + std::to_string(listeners_.size()) + " >= " + std::to_string(MAX_LISTENERS)); } - + listeners_.push_back(listener); } - + size_t getDocumentCount() const { std::lock_guard lock(mutex_); return documents_.size(); } - + bool hasDocument(const std::string& path) const { ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty"); std::lock_guard lock(mutex_); return documents_.find(path) != documents_.end(); } - + void closeDocument(const std::string& path) { ErrorHandler::validateParameter(!path.empty(), "Document path cannot be empty"); - + std::lock_guard lock(mutex_); - - auto it = documents_.find(path); - if (it == documents_.end()) { - throw EditorException(ErrorCode::EDITOR_DOCUMENT_INVALID, - "Cannot close document that is not open: " + path); - } - + + auto it = findDocumentOrThrowLocked(path, "Cannot close document that is not open: "); + documents_.erase(it); - + // Clear selection if this was the selected file if (selectedFile_ == path) { selectedFile_.clear(); } - + notifyListeners(); } -private: + private: EditorStore() {} + // Finds the open document at path, or throws EDITOR_DOCUMENT_INVALID with notFoundPrefix + path. + // The caller must already hold mutex_. + std::map::iterator findDocumentOrThrowLocked(const std::string& path, + const char* notFoundPrefix) { + auto it = documents_.find(path); + if (it == documents_.end()) { + throw EditorException(ErrorCode::EDITOR_DOCUMENT_INVALID, notFoundPrefix + path); + } + return it; + } + void notifyListeners() { // Note: mutex should already be locked when this is called for (auto& listener : listeners_) { @@ -252,12 +247,12 @@ class EditorStore { std::map documents_; std::vector> listeners_; mutable std::mutex mutex_; - + static constexpr size_t MAX_OPEN_DOCUMENTS = 50; static constexpr size_t MAX_FOLDING_RANGES = 10000; static constexpr size_t MAX_LISTENERS = 100; }; -} // namespace bolt +} // namespace bolt -#endif +#endif // BOLT_CORE_EDITOR_STORE_HPP_ diff --git a/include/bolt/gui/widgets.hpp b/include/bolt/gui/widgets.hpp index c8020605..d2673993 100644 --- a/include/bolt/gui/widgets.hpp +++ b/include/bolt/gui/widgets.hpp @@ -1,7 +1,12 @@ #pragma once -#include "bolt/gui/widget_framework.hpp" #include +#include +#include +#include +#include + +#include "bolt/gui/widget_framework.hpp" #ifdef BOLT_HAVE_IMGUI #include @@ -14,26 +19,26 @@ namespace gui { * Button widget - clickable button with text/icon */ class Button : public Widget { -public: + public: explicit Button(const std::string& id = "", const std::string& text = "Button"); - + const std::string& getText() const { return text_; } void setText(const std::string& text) { text_ = text; } - + const std::string& getIcon() const { return icon_; } void setIcon(const std::string& icon) { icon_ = icon; } - + void setOnClick(std::function callback) { onClickCallback_ = callback; } - + bool isPressed() const { return pressed_; } bool isHovered() const { return hovered_; } - -protected: + + protected: void onRender() override; void onEvent(const WidgetEvent& event) override; Size calculatePreferredSize() const override; - -private: + + private: std::string text_; std::string icon_; bool pressed_; @@ -45,106 +50,96 @@ class Button : public Widget { * Label widget - non-interactive text display */ class Label : public Widget { -public: + public: explicit Label(const std::string& id = "", const std::string& text = ""); - + const std::string& getText() const { return text_; } void setText(const std::string& text) { text_ = text; } - - enum class Alignment { - Left, - Center, - Right - }; - + + enum class Alignment { Left, Center, Right }; + Alignment getAlignment() const { return alignment_; } void setAlignment(Alignment alignment) { alignment_ = alignment; } - + bool getWordWrap() const { return wordWrap_; } void setWordWrap(bool wrap) { wordWrap_ = wrap; } - -protected: + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: + + private: std::string text_; Alignment alignment_; bool wordWrap_; }; /** - * TextInput widget - single-line text input field + * TextEntryWidget - state shared by the editable text widgets (TextInput and TextArea): + * the current text, the placeholder, the read-only flag and the text-changed callback */ -class TextInput : public Widget { -public: - explicit TextInput(const std::string& id = "", const std::string& placeholder = ""); - +class TextEntryWidget : public Widget { + public: const std::string& getText() const { return text_; } - void setText(const std::string& text) { text_ = text; } - + const std::string& getPlaceholder() const { return placeholder_; } void setPlaceholder(const std::string& placeholder) { placeholder_ = placeholder; } - + bool isReadOnly() const { return readOnly_; } void setReadOnly(bool readOnly) { readOnly_ = readOnly; } - + + void setOnTextChanged(std::function callback) { onTextChangedCallback_ = callback; } + + protected: + TextEntryWidget(const std::string& id, const std::string& placeholder) + : Widget(id), placeholder_(placeholder), readOnly_(false) {} + + std::string text_; + std::string placeholder_; + bool readOnly_; + std::function onTextChangedCallback_; +}; + +/** + * TextInput widget - single-line text input field + */ +class TextInput : public TextEntryWidget { + public: + explicit TextInput(const std::string& id = "", const std::string& placeholder = ""); + + void setText(const std::string& text) { text_ = text; } + bool isPassword() const { return password_; } void setPassword(bool password) { password_ = password; } - - void setOnTextChanged(std::function callback) { - onTextChangedCallback_ = callback; - } - - void setOnEnterPressed(std::function callback) { - onEnterPressedCallback_ = callback; - } - -protected: + + void setOnEnterPressed(std::function callback) { onEnterPressedCallback_ = callback; } + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: - std::string text_; - std::string placeholder_; - bool readOnly_; + + private: bool password_; char textBuffer_[1024]; - std::function onTextChangedCallback_; std::function onEnterPressedCallback_; }; /** * TextArea widget - multi-line text input field */ -class TextArea : public Widget { -public: +class TextArea : public TextEntryWidget { + public: explicit TextArea(const std::string& id = "", const std::string& placeholder = ""); - - const std::string& getText() const { return text_; } + void setText(const std::string& text); - - const std::string& getPlaceholder() const { return placeholder_; } - void setPlaceholder(const std::string& placeholder) { placeholder_ = placeholder; } - - bool isReadOnly() const { return readOnly_; } - void setReadOnly(bool readOnly) { readOnly_ = readOnly; } - - void setOnTextChanged(std::function callback) { - onTextChangedCallback_ = callback; - } - -protected: + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: - std::string text_; - std::string placeholder_; - bool readOnly_; + + private: std::vector textBuffer_; - std::function onTextChangedCallback_; - + void ensureBufferSize(size_t minSize); }; @@ -152,24 +147,22 @@ class TextArea : public Widget { * Checkbox widget - boolean toggle with label */ class Checkbox : public Widget { -public: + public: explicit Checkbox(const std::string& id = "", const std::string& label = "", bool checked = false); - + bool isChecked() const { return checked_; } void setChecked(bool checked) { checked_ = checked; } - + const std::string& getLabel() const { return label_; } void setLabel(const std::string& label) { label_ = label; } - - void setOnStateChanged(std::function callback) { - onStateChangedCallback_ = callback; - } - -protected: + + void setOnStateChanged(std::function callback) { onStateChangedCallback_ = callback; } + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: + + private: bool checked_; std::string label_; std::function onStateChangedCallback_; @@ -179,33 +172,31 @@ class Checkbox : public Widget { * RadioButton widget - mutually exclusive selection */ class RadioButton : public Widget { -public: - explicit RadioButton(const std::string& id = "", const std::string& label = "", - const std::string& group = "", bool selected = false); - + public: + explicit RadioButton(const std::string& id = "", const std::string& label = "", const std::string& group = "", + bool selected = false); + bool isSelected() const { return selected_; } void setSelected(bool selected); - + const std::string& getLabel() const { return label_; } void setLabel(const std::string& label) { label_ = label; } - + const std::string& getGroup() const { return group_; } void setGroup(const std::string& group) { group_ = group; } - - void setOnStateChanged(std::function callback) { - onStateChangedCallback_ = callback; - } - -protected: + + void setOnStateChanged(std::function callback) { onStateChangedCallback_ = callback; } + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: + + private: bool selected_; std::string label_; std::string group_; std::function onStateChangedCallback_; - + void deselectOthersInGroup(); static std::unordered_map> radioGroups_; }; @@ -214,30 +205,30 @@ class RadioButton : public Widget { * ComboBox widget - dropdown selection */ class ComboBox : public Widget { -public: + public: explicit ComboBox(const std::string& id = ""); - + void addItem(const std::string& item, const std::any& userData = {}); void removeItem(const std::string& item); void clearItems(); - + int getSelectedIndex() const { return selectedIndex_; } void setSelectedIndex(int index); - + const std::string& getSelectedItem() const; void setSelectedItem(const std::string& item); - + const std::vector& getItems() const { return items_; } - - void setOnSelectionChanged(std::function callback) { - onSelectionChangedCallback_ = callback; + + void setOnSelectionChanged(std::function callback) { + onSelectionChangedCallback_ = callback; } - -protected: + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: + + private: std::vector items_; std::vector itemData_; int selectedIndex_; @@ -248,27 +239,25 @@ class ComboBox : public Widget { * Slider widget - numeric value selection with draggable handle */ class Slider : public Widget { -public: + public: explicit Slider(const std::string& id = "", float minValue = 0.0f, float maxValue = 100.0f, float value = 0.0f); - + float getValue() const { return value_; } void setValue(float value); - + float getMinValue() const { return minValue_; } void setMinValue(float minValue) { minValue_ = minValue; } - + float getMaxValue() const { return maxValue_; } void setMaxValue(float maxValue) { maxValue_ = maxValue; } - - void setOnValueChanged(std::function callback) { - onValueChangedCallback_ = callback; - } - -protected: + + void setOnValueChanged(std::function callback) { onValueChangedCallback_ = callback; } + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: + + private: float value_; float minValue_; float maxValue_; @@ -279,24 +268,24 @@ class Slider : public Widget { * ProgressBar widget - shows progress of an operation */ class ProgressBar : public Widget { -public: + public: explicit ProgressBar(const std::string& id = "", float progress = 0.0f); - + float getProgress() const { return progress_; } - void setProgress(float progress); // 0.0 to 1.0 - + void setProgress(float progress); // 0.0 to 1.0 + const std::string& getText() const { return text_; } void setText(const std::string& text) { text_ = text; } - + bool isIndeterminate() const { return indeterminate_; } void setIndeterminate(bool indeterminate) { indeterminate_ = indeterminate; } - -protected: + + protected: void onRender() override; void onUpdate(float deltaTime) override; Size calculatePreferredSize() const override; - -private: + + private: float progress_; std::string text_; bool indeterminate_; @@ -307,26 +296,26 @@ class ProgressBar : public Widget { * Panel widget - container with border and background */ class Panel : public WidgetContainer { -public: + public: explicit Panel(const std::string& id = "", const std::string& title = ""); - + const std::string& getTitle() const { return title_; } void setTitle(const std::string& title) { title_ = title; } - + bool isCollapsible() const { return collapsible_; } void setCollapsible(bool collapsible) { collapsible_ = collapsible; } - + bool isCollapsed() const { return collapsed_; } void setCollapsed(bool collapsed) { collapsed_ = collapsed; } - + bool hasScrollbars() const { return scrollbars_; } void setScrollbars(bool scrollbars) { scrollbars_ = scrollbars; } - -protected: + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: + + private: std::string title_; bool collapsible_; bool collapsed_; @@ -337,42 +326,38 @@ class Panel : public WidgetContainer { * TabContainer widget - tabbed interface */ class TabContainer : public WidgetContainer { -public: + public: explicit TabContainer(const std::string& id = ""); - + struct TabInfo { std::string title; std::string icon; bool closable; std::shared_ptr content; - - TabInfo(const std::string& t = "", const std::string& i = "", bool c = false) + + explicit TabInfo(const std::string& t = "", const std::string& i = "", bool c = false) : title(t), icon(i), closable(c) {} }; - - void addTab(const std::string& title, std::shared_ptr content, - const std::string& icon = "", bool closable = false); + + void addTab(const std::string& title, std::shared_ptr content, const std::string& icon = "", + bool closable = false); void removeTab(int index); void removeTab(const std::string& title); - + int getActiveTab() const { return activeTab_; } void setActiveTab(int index); - + const std::vector& getTabs() const { return tabs_; } - - void setOnTabChanged(std::function callback) { - onTabChangedCallback_ = callback; - } - - void setOnTabClosed(std::function callback) { - onTabClosedCallback_ = callback; - } - -protected: + + void setOnTabChanged(std::function callback) { onTabChangedCallback_ = callback; } + + void setOnTabClosed(std::function callback) { onTabClosedCallback_ = callback; } + + protected: void onRender() override; Size calculatePreferredSize() const override; - -private: + + private: std::vector tabs_; int activeTab_; std::function onTabChangedCallback_; @@ -383,32 +368,29 @@ class TabContainer : public WidgetContainer { * Splitter widget - resizable split container */ class Splitter : public WidgetContainer { -public: - enum class Orientation { - Horizontal, - Vertical - }; - + public: + enum class Orientation { Horizontal, Vertical }; + explicit Splitter(const std::string& id = "", Orientation orientation = Orientation::Horizontal); - + Orientation getOrientation() const { return orientation_; } void setOrientation(Orientation orientation) { orientation_ = orientation; } - + float getSplitRatio() const { return splitRatio_; } - void setSplitRatio(float ratio); // 0.0 to 1.0 - + void setSplitRatio(float ratio); // 0.0 to 1.0 + void setFirstWidget(std::shared_ptr widget); void setSecondWidget(std::shared_ptr widget); - + std::shared_ptr getFirstWidget() const { return firstWidget_; } std::shared_ptr getSecondWidget() const { return secondWidget_; } - -protected: + + protected: void onRender() override; void onLayout() override; Size calculatePreferredSize() const override; - -private: + + private: Orientation orientation_; float splitRatio_; std::shared_ptr firstWidget_; @@ -416,5 +398,5 @@ class Splitter : public WidgetContainer { float splitterThickness_; }; -} // namespace gui -} // namespace bolt \ No newline at end of file +} // namespace gui +} // namespace bolt diff --git a/include/bolt/test_framework.hpp b/include/bolt/test_framework.hpp index 2edb72cc..93d0f2e8 100644 --- a/include/bolt/test_framework.hpp +++ b/include/bolt/test_framework.hpp @@ -1,19 +1,19 @@ -#ifndef BOLT_TEST_FRAMEWORK_HPP -#define BOLT_TEST_FRAMEWORK_HPP +#ifndef BOLT_TEST_FRAMEWORK_HPP_ +#define BOLT_TEST_FRAMEWORK_HPP_ -#include -#include -#include +#include +#include #include +#include #include -#include -#include +#include +#include namespace bolt { namespace test { class TestFailure : public std::exception { -public: + public: TestFailure(const std::string& message, const std::string& file, int line) : message_(message), file_(file), line_(line) { std::stringstream ss; @@ -21,15 +21,13 @@ class TestFailure : public std::exception { full_message_ = ss.str(); } - const char* what() const noexcept override { - return full_message_.c_str(); - } + const char* what() const noexcept override { return full_message_.c_str(); } const std::string& getMessage() const { return message_; } const std::string& getFile() const { return file_; } int getLine() const { return line_; } -private: + private: std::string message_; std::string file_; int line_; @@ -37,7 +35,7 @@ class TestFailure : public std::exception { }; class TestSuite { -public: + public: struct TestCase { std::string name; std::function test_func; @@ -70,46 +68,7 @@ class TestSuite { } for (const auto& test : tests_) { - if (verbose) { - std::cout << "[" << test.suite_name << "] " << test.name << " ... "; - std::cout.flush(); - } - - auto start = std::chrono::high_resolution_clock::now(); - TestResult result; - result.name = test.name; - result.suite_name = test.suite_name; - - try { - test.test_func(); - result.passed = true; - passed++; - if (verbose) { - std::cout << "PASS" << std::endl; - } - } catch (const TestFailure& e) { - result.passed = false; - result.error_message = e.what(); - failed++; - if (verbose) { - std::cout << "FAIL" << std::endl; - std::cout << " " << e.what() << std::endl; - } - } catch (const std::exception& e) { - result.passed = false; - result.error_message = "Unexpected exception: " + std::string(e.what()); - failed++; - if (verbose) { - std::cout << "ERROR" << std::endl; - std::cout << " " << result.error_message << std::endl; - } - } - - auto end = std::chrono::high_resolution_clock::now(); - auto duration = std::chrono::duration_cast(end - start); - result.duration_ms = duration.count() / 1000.0; - - results_.push_back(result); + runSingleTest(test, verbose, passed, failed); } if (verbose) { @@ -144,48 +103,10 @@ class TestSuite { } for (const auto& test : tests_) { - if (test.suite_name != suite_name) continue; - - if (verbose) { - std::cout << "[" << test.suite_name << "] " << test.name << " ... "; - std::cout.flush(); - } + if (test.suite_name != suite_name) + continue; - auto start = std::chrono::high_resolution_clock::now(); - TestResult result; - result.name = test.name; - result.suite_name = test.suite_name; - - try { - test.test_func(); - result.passed = true; - passed++; - if (verbose) { - std::cout << "PASS" << std::endl; - } - } catch (const TestFailure& e) { - result.passed = false; - result.error_message = e.what(); - failed++; - if (verbose) { - std::cout << "FAIL" << std::endl; - std::cout << " " << e.what() << std::endl; - } - } catch (const std::exception& e) { - result.passed = false; - result.error_message = "Unexpected exception: " + std::string(e.what()); - failed++; - if (verbose) { - std::cout << "ERROR" << std::endl; - std::cout << " " << result.error_message << std::endl; - } - } - - auto end = std::chrono::high_resolution_clock::now(); - auto duration = std::chrono::duration_cast(end - start); - result.duration_ms = duration.count() / 1000.0; - - results_.push_back(result); + runSingleTest(test, verbose, passed, failed); } if (verbose) { @@ -196,9 +117,7 @@ class TestSuite { return failed; } - const std::vector& getResults() const { - return results_; - } + const std::vector& getResults() const { return results_; } void listTests() const { std::cout << "Available tests:\n" << std::endl; @@ -214,10 +133,54 @@ class TestSuite { std::cout << "Total: " << tests_.size() << " tests" << std::endl; } -private: + private: std::vector tests_; std::vector results_; + // Runs one test case, prints its outcome when verbose, updates the pass/fail counters and records the result. + void runSingleTest(const TestCase& test, bool verbose, int& passed, int& failed) { + if (verbose) { + std::cout << "[" << test.suite_name << "] " << test.name << " ... "; + std::cout.flush(); + } + + auto start = std::chrono::high_resolution_clock::now(); + TestResult result; + result.name = test.name; + result.suite_name = test.suite_name; + + try { + test.test_func(); + result.passed = true; + passed++; + if (verbose) { + std::cout << "PASS" << std::endl; + } + } catch (const TestFailure& e) { + result.passed = false; + result.error_message = e.what(); + failed++; + if (verbose) { + std::cout << "FAIL" << std::endl; + std::cout << " " << e.what() << std::endl; + } + } catch (const std::exception& e) { + result.passed = false; + result.error_message = "Unexpected exception: " + std::string(e.what()); + failed++; + if (verbose) { + std::cout << "ERROR" << std::endl; + std::cout << " " << result.error_message << std::endl; + } + } + + auto end = std::chrono::high_resolution_clock::now(); + auto duration = std::chrono::duration_cast(end - start); + result.duration_ms = duration.count() / 1000.0; + + results_.push_back(result); + } + void printSummary(int passed, int failed) { std::cout << "Test Results:" << std::endl; std::cout << " Passed: " << passed << std::endl; @@ -234,83 +197,86 @@ class TestSuite { // Test registration helper class TestRegistrar { -public: + public: TestRegistrar(const std::string& suite_name, const std::string& test_name, std::function test_func) { TestSuite::getInstance().addTest(suite_name, test_name, test_func); } }; // Assertion macros -#define BOLT_ASSERT(condition) \ - do { \ - if (!(condition)) { \ +#define BOLT_ASSERT(condition) \ + do { \ + if (!(condition)) { \ throw bolt::test::TestFailure("Assertion failed: " #condition, __FILE__, __LINE__); \ - } \ + } \ } while (0) -#define BOLT_ASSERT_EQ(expected, actual) \ - do { \ - if ((expected) != (actual)) { \ - std::stringstream ss; \ +#define BOLT_ASSERT_EQ(expected, actual) \ + do { \ + if ((expected) != (actual)) { \ + std::stringstream ss; \ ss << "Expected '" << (expected) << "', but got '" << (actual) << "'"; \ - throw bolt::test::TestFailure(ss.str(), __FILE__, __LINE__); \ - } \ + throw bolt::test::TestFailure(ss.str(), __FILE__, __LINE__); \ + } \ } while (0) -#define BOLT_ASSERT_NE(expected, actual) \ - do { \ - if ((expected) == (actual)) { \ - std::stringstream ss; \ +#define BOLT_ASSERT_NE(expected, actual) \ + do { \ + if ((expected) == (actual)) { \ + std::stringstream ss; \ ss << "Expected values to be different, but both were '" << (actual) << "'"; \ - throw bolt::test::TestFailure(ss.str(), __FILE__, __LINE__); \ - } \ + throw bolt::test::TestFailure(ss.str(), __FILE__, __LINE__); \ + } \ } while (0) #define BOLT_ASSERT_TRUE(condition) BOLT_ASSERT(condition) -#define BOLT_ASSERT_FALSE(condition) \ - do { \ - if (condition) { \ +#define BOLT_ASSERT_FALSE(condition) \ + do { \ + if (condition) { \ throw bolt::test::TestFailure("Expected false, but got true: " #condition, __FILE__, __LINE__); \ - } \ + } \ } while (0) -#define BOLT_ASSERT_NULL(ptr) \ - do { \ - if ((ptr) != nullptr) { \ +#define BOLT_ASSERT_NULL(ptr) \ + do { \ + if ((ptr) != nullptr) { \ throw bolt::test::TestFailure("Expected null pointer, but got non-null", __FILE__, __LINE__); \ - } \ + } \ } while (0) -#define BOLT_ASSERT_NOT_NULL(ptr) \ - do { \ - if ((ptr) == nullptr) { \ +#define BOLT_ASSERT_NOT_NULL(ptr) \ + do { \ + if ((ptr) == nullptr) { \ throw bolt::test::TestFailure("Expected non-null pointer, but got null", __FILE__, __LINE__); \ - } \ + } \ } while (0) -#define BOLT_ASSERT_THROWS(exception_type, code) \ - do { \ - bool threw_expected = false; \ - try { \ - code; \ - } catch (const exception_type&) { \ - threw_expected = true; \ - } catch (...) { \ - throw bolt::test::TestFailure("Expected " #exception_type " but caught different exception", __FILE__, __LINE__); \ - } \ - if (!threw_expected) { \ - throw bolt::test::TestFailure("Expected " #exception_type " but no exception was thrown", __FILE__, __LINE__); \ - } \ +#define BOLT_ASSERT_THROWS(exception_type, code) \ + do { \ + bool threw_expected = false; \ + try { \ + code; \ + } catch (const exception_type&) { \ + threw_expected = true; \ + } catch (...) { \ + throw bolt::test::TestFailure("Expected " #exception_type " but caught different exception", __FILE__, \ + __LINE__); \ + } \ + if (!threw_expected) { \ + throw bolt::test::TestFailure("Expected " #exception_type " but no exception was thrown", __FILE__, \ + __LINE__); \ + } \ } while (0) // Test case registration macro -#define BOLT_TEST(suite_name, test_name) \ - void test_##suite_name##_##test_name(); \ - static bolt::test::TestRegistrar registrar_##suite_name##_##test_name(#suite_name, #test_name, test_##suite_name##_##test_name); \ +#define BOLT_TEST(suite_name, test_name) \ + void test_##suite_name##_##test_name(); \ + static bolt::test::TestRegistrar registrar_##suite_name##_##test_name(#suite_name, #test_name, \ + test_##suite_name##_##test_name); \ void test_##suite_name##_##test_name() -} // namespace test -} // namespace bolt +} // namespace test +} // namespace bolt -#endif // BOLT_TEST_FRAMEWORK_HPP \ No newline at end of file +#endif // BOLT_TEST_FRAMEWORK_HPP_ diff --git a/include/bolt/utils/tensor_utils.hpp b/include/bolt/utils/tensor_utils.hpp index 2c659a09..98d4aa5e 100644 --- a/include/bolt/utils/tensor_utils.hpp +++ b/include/bolt/utils/tensor_utils.hpp @@ -1,15 +1,14 @@ - -#ifndef TENSOR_UTILS_HPP -#define TENSOR_UTILS_HPP -#include - -#include -#include +#ifndef BOLT_UTILS_TENSOR_UTILS_HPP_ +#define BOLT_UTILS_TENSOR_UTILS_HPP_ #include #include -#include -#include +#include #include +#include +#include +#include +#include + #include "bolt/ai/ggml.hpp" namespace bolt { @@ -17,7 +16,7 @@ namespace bolt { #ifdef BOLT_HAVE_GGML class TensorUtils { -public: + public: static void serializeTensor(FILE* f, ggml_tensor* tensor) { fwrite(&tensor->type, sizeof(tensor->type), 1, f); int n_dims = ggml_n_dims(tensor); @@ -46,8 +45,10 @@ class TensorUtils { } static ggml_tensor* quantizeTensor(ggml_context* ctx, ggml_tensor* tensor, enum ggml_type target_type) { - if (!tensor) return nullptr; - if (tensor->type == target_type) return ggml_dup_tensor(ctx, tensor); + if (!tensor) + return nullptr; + if (tensor->type == target_type) + return ggml_dup_tensor(ctx, tensor); int64_t n_elements = ggml_nelements(tensor); std::vector src_data(n_elements); @@ -56,7 +57,7 @@ class TensorUtils { std::copy(data, data + n_elements, src_data.begin()); } else if (tensor->type == GGML_TYPE_F16) { for (int64_t i = 0; i < n_elements; i++) { - src_data[i] = ggml_fp16_to_fp32(((ggml_fp16_t*)tensor->data)[i]); + src_data[i] = ggml_fp16_to_fp32(static_cast(tensor->data)[i]); } } else { return ggml_dup_tensor(ctx, tensor); @@ -68,18 +69,17 @@ class TensorUtils { float* dst = ggml_get_data_f32(quantized); std::copy(src_data.begin(), src_data.end(), dst); } else if (target_type == GGML_TYPE_F16) { - ggml_fp16_t* dst = (ggml_fp16_t*)quantized->data; + ggml_fp16_t* dst = static_cast(quantized->data); for (int64_t i = 0; i < n_elements; i++) { dst[i] = ggml_fp32_to_fp16(src_data[i]); } - } else if (target_type == GGML_TYPE_Q4_0 || target_type == GGML_TYPE_Q4_1 || - target_type == GGML_TYPE_Q8_0) { + } else if (target_type == GGML_TYPE_Q4_0 || target_type == GGML_TYPE_Q4_1 || target_type == GGML_TYPE_Q8_0) { size_t qk = ggml_blck_size(target_type); size_t n_blocks = (n_elements + qk - 1) / qk; std::vector padded_data = src_data; padded_data.resize(n_blocks * qk, 0.0f); - ggml_quantize_chunk(target_type, padded_data.data(), quantized->data, - 0, static_cast(n_blocks), static_cast(qk), nullptr); + ggml_quantize_chunk(target_type, padded_data.data(), quantized->data, 0, static_cast(n_blocks), + static_cast(qk), nullptr); } else { memcpy(quantized->data, tensor->data, std::min(ggml_nbytes(tensor), ggml_nbytes(quantized))); } @@ -87,14 +87,8 @@ class TensorUtils { } static float calculateQuantizationError(ggml_tensor* original, ggml_tensor* quantized) { - if (!original || !quantized) throw std::runtime_error("Null tensor provided"); - int64_t n_orig = ggml_nelements(original); - int64_t n_quant = ggml_nelements(quantized); - if (n_orig != n_quant) throw std::runtime_error("Tensor dimensions mismatch"); - - std::vector orig_data(n_orig), quant_data(n_quant); - extractFloatData(original, orig_data); - extractFloatData(quantized, quant_data); + std::vector orig_data, quant_data; + int64_t n_orig = extractComparableData(original, quantized, orig_data, quant_data); double mse = 0.0; for (int64_t i = 0; i < n_orig; i++) { @@ -109,44 +103,42 @@ class TensorUtils { } static float calculateMAE(ggml_tensor* original, ggml_tensor* quantized) { - if (!original || !quantized) throw std::runtime_error("Null tensor provided"); - int64_t n = ggml_nelements(original); - if (n != ggml_nelements(quantized)) throw std::runtime_error("Tensor dimensions mismatch"); - - std::vector orig_data(n), quant_data(n); - extractFloatData(original, orig_data); - extractFloatData(quantized, quant_data); + std::vector orig_data, quant_data; + int64_t n = extractComparableData(original, quantized, orig_data, quant_data); double mae = 0.0; - for (int64_t i = 0; i < n; i++) mae += std::fabs(orig_data[i] - quant_data[i]); + for (int64_t i = 0; i < n; i++) + mae += std::fabs(orig_data[i] - quant_data[i]); return static_cast(mae / n); } static float calculateMaxError(ggml_tensor* original, ggml_tensor* quantized) { - if (!original || !quantized) throw std::runtime_error("Null tensor provided"); - int64_t n = ggml_nelements(original); - if (n != ggml_nelements(quantized)) throw std::runtime_error("Tensor dimensions mismatch"); - - std::vector orig_data(n), quant_data(n); - extractFloatData(original, orig_data); - extractFloatData(quantized, quant_data); + std::vector orig_data, quant_data; + int64_t n = extractComparableData(original, quantized, orig_data, quant_data); float max_err = 0.0f; for (int64_t i = 0; i < n; i++) { float err = std::fabs(orig_data[i] - quant_data[i]); - if (err > max_err) max_err = err; + if (err > max_err) + max_err = err; } return max_err; } struct TensorStats { - float min = 0; float max = 0; float mean = 0; float std = 0; - int64_t n_elements = 0; int64_t n_zero = 0; float sparsity = 0; + float min = 0; + float max = 0; + float mean = 0; + float std = 0; + int64_t n_elements = 0; + int64_t n_zero = 0; + float sparsity = 0; }; static TensorStats getTensorStats(ggml_tensor* tensor) { TensorStats stats; - if (!tensor) return stats; + if (!tensor) + return stats; int64_t n = ggml_nelements(tensor); stats.n_elements = n; std::vector data(n); @@ -157,10 +149,13 @@ class TensorUtils { stats.n_zero = 0; for (int64_t i = 0; i < n; i++) { float val = data[i]; - if (val < stats.min) stats.min = val; - if (val > stats.max) stats.max = val; + if (val < stats.min) + stats.min = val; + if (val > stats.max) + stats.max = val; sum += val; - if (val == 0.0f) stats.n_zero++; + if (val == 0.0f) + stats.n_zero++; } stats.mean = static_cast(sum / n); stats.sparsity = static_cast(stats.n_zero) / static_cast(n); @@ -173,34 +168,57 @@ class TensorUtils { return stats; } -private: + private: + // Checks that both tensors are non-null and hold the same number of elements, reads their values as floats + // into orig_data and quant_data, and returns that element count. + static int64_t extractComparableData(ggml_tensor* original, ggml_tensor* quantized, std::vector& orig_data, + std::vector& quant_data) { + if (!original || !quantized) + throw std::runtime_error("Null tensor provided"); + int64_t n = ggml_nelements(original); + if (n != ggml_nelements(quantized)) + throw std::runtime_error("Tensor dimensions mismatch"); + + orig_data.resize(n); + quant_data.resize(n); + extractFloatData(original, orig_data); + extractFloatData(quantized, quant_data); + return n; + } + static void extractFloatData(ggml_tensor* tensor, std::vector& out) { int64_t n = ggml_nelements(tensor); if (tensor->type == GGML_TYPE_F32) { float* data = ggml_get_data_f32(tensor); std::copy(data, data + n, out.begin()); } else if (tensor->type == GGML_TYPE_F16) { - ggml_fp16_t* data = (ggml_fp16_t*)tensor->data; - for (int64_t i = 0; i < n; i++) out[i] = ggml_fp16_to_fp32(data[i]); + ggml_fp16_t* data = static_cast(tensor->data); + for (int64_t i = 0; i < n; i++) + out[i] = ggml_fp16_to_fp32(data[i]); } else { std::fill(out.begin(), out.end(), 0.0f); } } }; -#else // !BOLT_HAVE_GGML +#else // !BOLT_HAVE_GGML // Stub TensorUtils when GGML is not available class TensorUtils { -public: + public: struct TensorStats { - float min = 0; float max = 0; float mean = 0; float std = 0; - int64_t n_elements = 0; int64_t n_zero = 0; float sparsity = 0; + float min = 0; + float max = 0; + float mean = 0; + float std = 0; + int64_t n_elements = 0; + int64_t n_zero = 0; + float sparsity = 0; }; }; -#endif // BOLT_HAVE_GGML +#endif // BOLT_HAVE_GGML -} // namespace bolt +} // namespace bolt -#endif // TENSOR_UTILS_HPP +#endif // BOLT_UTILS_TENSOR_UTILS_HPP_ diff --git a/src/bolt/core/plugin_system.cpp b/src/bolt/core/plugin_system.cpp index b9c966cb..41d24049 100644 --- a/src/bolt/core/plugin_system.cpp +++ b/src/bolt/core/plugin_system.cpp @@ -1,18 +1,42 @@ #include "bolt/core/plugin_system.hpp" -#include "bolt/core/editor_store.hpp" -#include "bolt/editor/integrated_editor.hpp" -#include + #include +#include #include +#include "bolt/core/editor_store.hpp" +#include "bolt/editor/integrated_editor.hpp" + namespace bolt { +namespace { + +// Appends the plugins of every bucket of a keyed registry map to out, in map order. +template +void appendAllBuckets(const PluginMap& pluginMap, PluginList& out) { + for (const auto& [type, typePlugins] : pluginMap) { + out.insert(out.end(), typePlugins.begin(), typePlugins.end()); + } +} + +// Removes the plugin called name from every bucket of a keyed registry map. +template +void erasePluginFromBuckets(PluginMap& plugins, const std::string& name) { + for (auto& [type, typePlugins] : plugins) { + typePlugins.erase(std::remove_if(typePlugins.begin(), typePlugins.end(), + [&](const auto& plugin) { return plugin->getMetadata().name == name; }), + typePlugins.end()); + } +} + +} // namespace + // PluginLoader implementation std::unique_ptr PluginLoader::loadPlugin(const std::string& filePath) { if (!std::filesystem::exists(filePath)) { throw std::runtime_error("Plugin file not found: " + filePath); } - + #ifdef _WIN32 // Windows-specific dynamic library loading HMODULE handle = LoadLibraryA(filePath.c_str()); @@ -20,13 +44,11 @@ std::unique_ptr PluginLoader::loadPlugin(const std:: DWORD error = GetLastError(); throw std::runtime_error("Failed to load plugin: Error code " + std::to_string(error)); } - + // Get the plugin creation function typedef IPlugin* (*create_plugin_t)(); - create_plugin_t createPlugin = reinterpret_cast( - GetProcAddress(handle, "createPlugin") - ); - + create_plugin_t createPlugin = reinterpret_cast(GetProcAddress(handle, "createPlugin")); + if (!createPlugin) { DWORD error = GetLastError(); FreeLibrary(handle); @@ -38,20 +60,18 @@ std::unique_ptr PluginLoader::loadPlugin(const std:: if (!handle) { throw std::runtime_error("Failed to load plugin: " + std::string(dlerror())); } - + // Get the plugin creation function typedef IPlugin* (*create_plugin_t)(); - create_plugin_t createPlugin = reinterpret_cast( - dlsym(handle, "createPlugin") - ); - + create_plugin_t createPlugin = reinterpret_cast(dlsym(handle, "createPlugin")); + const char* dlsym_error = dlerror(); if (dlsym_error) { dlclose(handle); throw std::runtime_error("Cannot load symbol 'createPlugin': " + std::string(dlsym_error)); } #endif - + // Create plugin instance IPlugin* plugin = createPlugin(); if (!plugin) { @@ -62,7 +82,7 @@ std::unique_ptr PluginLoader::loadPlugin(const std:: #endif throw std::runtime_error("Failed to create plugin instance"); } - + // Validate plugin if (!validatePlugin(plugin)) { delete plugin; @@ -73,13 +93,13 @@ std::unique_ptr PluginLoader::loadPlugin(const std:: #endif throw std::runtime_error("Plugin validation failed"); } - + auto loadedPlugin = std::make_unique(); loadedPlugin->handle = handle; loadedPlugin->plugin = std::shared_ptr(plugin); loadedPlugin->metadata = plugin->getMetadata(); loadedPlugin->filePath = filePath; - + return loadedPlugin; } @@ -87,40 +107,37 @@ bool PluginLoader::unloadPlugin(LoadedPlugin* plugin) { if (!plugin || !plugin->handle) { return false; } - + // Get the plugin destruction function typedef void (*destroy_plugin_t)(IPlugin*); #ifdef _WIN32 - destroy_plugin_t destroyPlugin = reinterpret_cast( - GetProcAddress(static_cast(plugin->handle), "destroyPlugin") - ); + destroy_plugin_t destroyPlugin = + reinterpret_cast(GetProcAddress(static_cast(plugin->handle), "destroyPlugin")); #else - destroy_plugin_t destroyPlugin = reinterpret_cast( - dlsym(plugin->handle, "destroyPlugin") - ); + destroy_plugin_t destroyPlugin = reinterpret_cast(dlsym(plugin->handle, "destroyPlugin")); #endif - + if (destroyPlugin) { destroyPlugin(plugin->plugin.get()); } - + #ifdef _WIN32 FreeLibrary(static_cast(plugin->handle)); #else dlclose(plugin->handle); #endif plugin->handle = nullptr; - + return true; } std::vector PluginLoader::discoverPlugins(const std::string& directory) { std::vector plugins; - + if (!std::filesystem::exists(directory)) { return plugins; } - + for (const auto& entry : std::filesystem::directory_iterator(directory)) { if (entry.is_regular_file()) { const std::string& path = entry.path().string(); @@ -132,7 +149,7 @@ std::vector PluginLoader::discoverPlugins(const std::string& direct } } } - + return plugins; } @@ -140,15 +157,14 @@ bool PluginLoader::validatePlugin(IPlugin* plugin) { if (!plugin) { return false; } - + PluginMetadata metadata = plugin->getMetadata(); return metadata.isValid(); } // PluginContextImpl implementation PluginContextImpl::PluginContextImpl(EditorStore* editorStore, IntegratedEditor* integratedEditor) - : editorStore_(editorStore), integratedEditor_(integratedEditor) { -} + : editorStore_(editorStore), integratedEditor_(integratedEditor) {} void PluginContextImpl::subscribeToEvent(PluginEventType eventType, std::function handler) { eventHandlers_[eventType].push_back(handler); @@ -212,16 +228,12 @@ std::vector> PluginContextImpl::getPlugins() { // PluginSystem implementation void PluginSystem::initialize(EditorStore* editorStore, IntegratedEditor* integratedEditor) { context_ = std::make_unique(editorStore, integratedEditor); - + // Set up plugin getters for context - context_->setPluginGetter([this](const std::string& name) { - return getPlugin(name); - }); - - context_->setAllPluginsGetter([this]() { - return getPlugins(); - }); - + context_->setPluginGetter([this](const std::string& name) { return getPlugin(name); }); + + context_->setAllPluginsGetter([this]() { return getPlugins(); }); + // Add default plugin directories addPluginDirectory("./plugins"); addPluginDirectory("/usr/local/lib/bolt/plugins"); @@ -231,7 +243,7 @@ void PluginSystem::initialize(EditorStore* editorStore, IntegratedEditor* integr void PluginSystem::shutdown() { // Cleanup all plugins cleanupAll(); - + // Unload modern plugins loadedPlugins_.write([](auto& plugins) { for (auto& [name, plugin] : plugins) { @@ -241,11 +253,9 @@ void PluginSystem::shutdown() { } plugins.clear(); }); - - activePlugins_.write([](auto& plugins) { - plugins.clear(); - }); - + + activePlugins_.write([](auto& plugins) { plugins.clear(); }); + // Clear registries editorPlugins_.write([](auto& plugins) { plugins.clear(); }); languagePlugins_.write([](auto& plugins) { plugins.clear(); }); @@ -255,9 +265,7 @@ void PluginSystem::shutdown() { // Legacy plugin support void PluginSystem::registerPlugin(Plugin plugin) { - legacyPlugins_.write([&](auto& plugs) { - plugs.push_back(std::move(plugin)); - }); + legacyPlugins_.write([&](auto& plugs) { plugs.push_back(std::move(plugin)); }); } void PluginSystem::initializeAll() { @@ -289,39 +297,35 @@ bool PluginSystem::loadPlugin(const std::string& filePath) { try { auto loadedPlugin = PluginLoader::loadPlugin(filePath); std::string name = loadedPlugin->metadata.name; - + // Check if plugin is already loaded if (isPluginLoaded(name)) { handlePluginError(name, "Plugin already loaded"); return false; } - + // Check API compatibility if (!validatePluginCompatibility(loadedPlugin->metadata)) { handlePluginError(name, "Plugin API version incompatible"); return false; } - + // Initialize plugin if (!loadedPlugin->plugin->initialize(context_.get())) { handlePluginError(name, "Plugin initialization failed"); return false; } - + // Store loaded plugin - loadedPlugins_.write([&](auto& plugins) { - plugins[name] = std::move(loadedPlugin); - }); - + loadedPlugins_.write([&](auto& plugins) { plugins[name] = std::move(loadedPlugin); }); + // Add to active plugins auto plugin = getPlugin(name); if (plugin) { registerPluginByType(plugin); - activePlugins_.write([&](auto& plugins) { - plugins[name] = plugin; - }); + activePlugins_.write([&](auto& plugins) { plugins[name] = plugin; }); } - + return true; } catch (const std::exception& e) { handlePluginError(filePath, e.what()); @@ -333,44 +337,42 @@ bool PluginSystem::loadPlugin(std::shared_ptr plugin) { if (!plugin) { return false; } - + PluginMetadata metadata = plugin->getMetadata(); std::string name = metadata.name; - + // Check if plugin is already loaded if (isPluginLoaded(name)) { handlePluginError(name, "Plugin already loaded"); return false; } - + // Check API compatibility if (!validatePluginCompatibility(metadata)) { handlePluginError(name, "Plugin API version incompatible"); return false; } - + // Initialize plugin if (!plugin->initialize(context_.get())) { handlePluginError(name, "Plugin initialization failed"); return false; } - + // Create a LoadedPlugin wrapper for in-memory plugins auto loadedPlugin = std::make_unique(); loadedPlugin->handle = nullptr; // No dynamic library handle for in-memory plugins loadedPlugin->plugin = plugin; loadedPlugin->metadata = metadata; loadedPlugin->filePath = ""; // Mark as in-memory plugin - + // Store in loadedPlugins_ so isPluginLoaded() works correctly - loadedPlugins_.write([&](auto& plugins) { - plugins[name] = std::move(loadedPlugin); - }); - + loadedPlugins_.write([&](auto& plugins) { plugins[name] = std::move(loadedPlugin); }); + // Register plugin by type but don't add to activePlugins yet // Plugins must be explicitly activated via activatePlugin() registerPluginByType(plugin); - + return true; } @@ -389,11 +391,11 @@ bool PluginSystem::unloadPlugin(const std::string& name) { wasActive = true; } }); - + if (wasActive) { unregisterPluginByType(name); } - + // Remove from loaded plugins bool wasLoaded = false; loadedPlugins_.write([&](auto& plugins) { @@ -403,13 +405,13 @@ bool PluginSystem::unloadPlugin(const std::string& name) { wasLoaded = true; } }); - + return wasActive || wasLoaded; } void PluginSystem::reloadPlugin(const std::string& name) { std::string filePath; - + // Get the file path before unloading loadedPlugins_.read([&](const auto& plugins) { auto it = plugins.find(name); @@ -417,7 +419,7 @@ void PluginSystem::reloadPlugin(const std::string& name) { filePath = it->second->filePath; } }); - + if (!filePath.empty()) { unloadPlugin(name); loadPlugin(filePath); @@ -466,14 +468,14 @@ std::vector PluginSystem::getLoadedPluginNames() const { std::shared_ptr PluginSystem::getPlugin(const std::string& name) const { std::shared_ptr result; - + activePlugins_.read([&](const auto& plugins) { auto it = plugins.find(name); if (it != plugins.end()) { result = it->second; } }); - + if (!result) { loadedPlugins_.read([&](const auto& plugins) { auto it = plugins.find(name); @@ -482,7 +484,7 @@ std::shared_ptr PluginSystem::getPlugin(const std::string& name) const } }); } - + return result; } @@ -499,49 +501,42 @@ std::vector> PluginSystem::getPlugins() const { std::vector PluginSystem::getPluginMetadata() const { std::vector metadata; - + loadedPlugins_.read([&](const auto& plugins) { metadata.reserve(plugins.size()); for (const auto& [name, plugin] : plugins) { metadata.push_back(plugin->metadata); } }); - + return metadata; } // Type-specific plugin access std::vector> PluginSystem::getEditorPlugins() const { std::vector> plugins; - editorPlugins_.read([&](const auto& pluginMap) { - for (const auto& [type, typePlugins] : pluginMap) { - plugins.insert(plugins.end(), typePlugins.begin(), typePlugins.end()); - } - }); + editorPlugins_.read([&](const auto& pluginMap) { appendAllBuckets(pluginMap, plugins); }); return plugins; } -std::vector> PluginSystem::getLanguagePluginsForFile(const std::string& filePath) const { +std::vector> PluginSystem::getLanguagePluginsForFile( + const std::string& filePath) const { std::string extension = getFileExtension(filePath); std::vector> plugins; - + languagePlugins_.read([&](const auto& pluginMap) { auto it = pluginMap.find(extension); if (it != pluginMap.end()) { plugins = it->second; } }); - + return plugins; } std::vector> PluginSystem::getUIPlugins() const { std::vector> plugins; - uiPlugins_.read([&](const auto& pluginMap) { - for (const auto& [type, typePlugins] : pluginMap) { - plugins.insert(plugins.end(), typePlugins.begin(), typePlugins.end()); - } - }); + uiPlugins_.read([&](const auto& pluginMap) { appendAllBuckets(pluginMap, plugins); }); return plugins; } @@ -559,17 +554,13 @@ std::shared_ptr PluginSystem::getActiveThemePlugin() const { // Plugin state management bool PluginSystem::isPluginLoaded(const std::string& name) const { bool loaded = false; - loadedPlugins_.read([&](const auto& plugins) { - loaded = plugins.find(name) != plugins.end(); - }); + loadedPlugins_.read([&](const auto& plugins) { loaded = plugins.find(name) != plugins.end(); }); return loaded; } bool PluginSystem::isPluginActive(const std::string& name) const { bool active = false; - activePlugins_.read([&](const auto& plugins) { - active = plugins.find(name) != plugins.end(); - }); + activePlugins_.read([&](const auto& plugins) { active = plugins.find(name) != plugins.end(); }); return active; } @@ -587,9 +578,7 @@ bool PluginSystem::activatePlugin(const std::string& name) { try { plugin->activate(); // Add to active plugins after successful activation - activePlugins_.write([&](auto& plugins) { - plugins[name] = plugin; - }); + activePlugins_.write([&](auto& plugins) { plugins[name] = plugin; }); return true; } catch (const std::exception& e) { handlePluginError(name, "Activation failed: " + std::string(e.what())); @@ -604,9 +593,7 @@ bool PluginSystem::deactivatePlugin(const std::string& name) { try { plugin->deactivate(); // Remove from active plugins after deactivation - activePlugins_.write([&](auto& plugins) { - plugins.erase(name); - }); + activePlugins_.write([&](auto& plugins) { plugins.erase(name); }); return true; } catch (const std::exception& e) { handlePluginError(name, "Deactivation failed: " + std::string(e.what())); @@ -634,7 +621,8 @@ std::unordered_map PluginSystem::getPluginConfiguration(c try { return plugin->getConfiguration(); } catch (const std::exception& e) { - const_cast(this)->handlePluginError(name, "Failed to get configuration: " + std::string(e.what())); + const_cast(this)->handlePluginError(name, + "Failed to get configuration: " + std::string(e.what())); } } return {}; @@ -646,7 +634,7 @@ void PluginSystem::publishEvent(const PluginEvent& event) { if (context_) { context_->publishEvent(event); } - + // Publish to all plugins publishEventToPlugins(event); } @@ -657,7 +645,8 @@ void PluginSystem::publishEventToPlugins(const PluginEvent& event) { try { plugin->onEvent(event); } catch (const std::exception& e) { - const_cast(this)->handlePluginError(name, "Error handling event: " + std::string(e.what())); + const_cast(this)->handlePluginError(name, + "Error handling event: " + std::string(e.what())); } } }); @@ -667,7 +656,7 @@ void PluginSystem::publishEventToPlugins(const PluginEvent& event) { void PluginSystem::handlePluginError(const std::string& pluginName, const std::string& error) { std::string errorMsg = pluginName + ": " + error; std::cerr << "[PLUGIN ERROR] " << errorMsg << std::endl; - + pluginErrors_.write([&](auto& errors) { errors.push_back(errorMsg); // Keep only last 100 errors @@ -679,16 +668,12 @@ void PluginSystem::handlePluginError(const std::string& pluginName, const std::s std::vector PluginSystem::getPluginErrors() const { std::vector errors; - pluginErrors_.read([&](const auto& err) { - errors = err; - }); + pluginErrors_.read([&](const auto& err) { errors = err; }); return errors; } void PluginSystem::clearPluginErrors() { - pluginErrors_.write([](auto& errors) { - errors.clear(); - }); + pluginErrors_.write([](auto& errors) { errors.clear(); }); } // Internal helpers @@ -703,11 +688,9 @@ std::string PluginSystem::getFileExtension(const std::string& filePath) const { void PluginSystem::registerPluginByType(std::shared_ptr plugin) { // Register by type if (auto editorPlugin = std::dynamic_pointer_cast(plugin)) { - editorPlugins_.write([&](auto& plugins) { - plugins["editor"].push_back(editorPlugin); - }); + editorPlugins_.write([&](auto& plugins) { plugins["editor"].push_back(editorPlugin); }); } - + if (auto langPlugin = std::dynamic_pointer_cast(plugin)) { languagePlugins_.write([&](auto& plugins) { for (const auto& ext : langPlugin->getSupportedExtensions()) { @@ -715,52 +698,27 @@ void PluginSystem::registerPluginByType(std::shared_ptr plugin) { } }); } - + if (auto uiPlugin = std::dynamic_pointer_cast(plugin)) { - uiPlugins_.write([&](auto& plugins) { - plugins["ui"].push_back(uiPlugin); - }); + uiPlugins_.write([&](auto& plugins) { plugins["ui"].push_back(uiPlugin); }); } - + if (auto themePlugin = std::dynamic_pointer_cast(plugin)) { - themePlugins_.write([&](auto& plugins) { - plugins[themePlugin->getThemeName()] = themePlugin; - }); + themePlugins_.write([&](auto& plugins) { plugins[themePlugin->getThemeName()] = themePlugin; }); } } void PluginSystem::unregisterPluginByType(const std::string& name) { // Remove from all type registries - editorPlugins_.write([&](auto& plugins) { - for (auto& [type, typePlugins] : plugins) { - typePlugins.erase( - std::remove_if(typePlugins.begin(), typePlugins.end(), - [&](const auto& plugin) { return plugin->getMetadata().name == name; }), - typePlugins.end()); - } - }); - - languagePlugins_.write([&](auto& plugins) { - for (auto& [ext, typePlugins] : plugins) { - typePlugins.erase( - std::remove_if(typePlugins.begin(), typePlugins.end(), - [&](const auto& plugin) { return plugin->getMetadata().name == name; }), - typePlugins.end()); - } - }); - - uiPlugins_.write([&](auto& plugins) { - for (auto& [type, typePlugins] : plugins) { - typePlugins.erase( - std::remove_if(typePlugins.begin(), typePlugins.end(), - [&](const auto& plugin) { return plugin->getMetadata().name == name; }), - typePlugins.end()); - } - }); - + editorPlugins_.write([&](auto& plugins) { erasePluginFromBuckets(plugins, name); }); + + languagePlugins_.write([&](auto& plugins) { erasePluginFromBuckets(plugins, name); }); + + uiPlugins_.write([&](auto& plugins) { erasePluginFromBuckets(plugins, name); }); + themePlugins_.write([&](auto& plugins) { auto it = std::find_if(plugins.begin(), plugins.end(), - [&](const auto& pair) { return pair.second->getMetadata().name == name; }); + [&](const auto& pair) { return pair.second->getMetadata().name == name; }); if (it != plugins.end()) { plugins.erase(it); } @@ -772,4 +730,4 @@ bool PluginSystem::validatePluginCompatibility(const PluginMetadata& metadata) c return currentAPI.isCompatible(metadata.apiVersion); } -} // namespace bolt \ No newline at end of file +} // namespace bolt diff --git a/src/bolt/drawkern/ai_integration.cpp b/src/bolt/drawkern/ai_integration.cpp index 7b4163f1..4df4471b 100644 --- a/src/bolt/drawkern/ai_integration.cpp +++ b/src/bolt/drawkern/ai_integration.cpp @@ -1,28 +1,50 @@ #include "bolt/drawkern/ai_integration.hpp" + +#include +#include +#include +#include +#include + #include "bolt/drawkern/dis_vm.hpp" #include "bolt/drawkern/styx_protocol.hpp" #include "bolt/drawkern/yacc_grammar.hpp" -#include -#include -#include -#include -#include namespace bolt { namespace drawkern { -// AIModel base class implementation -AIModel::AIModel(const AIModelConfig& config) : config_(config) { +namespace { + +// Stamps the elapsed time since start_time and the rough token counts on a response, and marks it successful. +void finish_successful_inference(AIInferenceResponse& response, const AIInferenceRequest& request, + std::chrono::high_resolution_clock::time_point start_time) { + auto end_time = std::chrono::high_resolution_clock::now(); + response.inference_time_ms = std::chrono::duration(end_time - start_time).count(); + response.tokens_generated = response.response.length() / 4; // Rough estimate + response.tokens_processed = request.prompt.length() / 4; + response.success = true; } +// Builds the failed response returned when model_id is not registered with the manager. +AIInferenceResponse model_not_found_response(const std::string& model_id) { + AIInferenceResponse error_response; + error_response.error = "Model not found: " + model_id; + error_response.success = false; + return error_response; +} + +} // namespace + +// AIModel base class implementation +AIModel::AIModel(const AIModelConfig& config) : config_(config) {} + AIModel::~AIModel() { // Don't call pure virtual in destructor loaded_ = false; } // GGMLModel implementation -GGMLModel::GGMLModel(const AIModelConfig& config) : AIModel(config) { -} +GGMLModel::GGMLModel(const AIModelConfig& config) : AIModel(config) {} GGMLModel::~GGMLModel() { unload(); @@ -32,21 +54,21 @@ bool GGMLModel::load() { if (loaded_) { return true; } - + std::cout << "Loading GGML model: " << config_.model_path << std::endl; - + // For demonstration, we'll simulate model loading // In a real implementation, this would use the GGML library - + std::ifstream file(config_.model_path); if (!file.good()) { std::cerr << "Model file not found: " << config_.model_path << std::endl; return false; } - + // Simulate loading time std::this_thread::sleep_for(std::chrono::milliseconds(500)); - + loaded_ = true; std::cout << "GGML model loaded successfully" << std::endl; return true; @@ -56,18 +78,18 @@ void GGMLModel::unload() { if (!loaded_) { return; } - + // Clean up GGML resources if (ggml_context_) { // ggml_free(ggml_context_); ggml_context_ = nullptr; } - + if (model_data_) { // Free model-specific data model_data_ = nullptr; } - + loaded_ = false; std::cout << "GGML model unloaded" << std::endl; } @@ -76,31 +98,26 @@ AIInferenceResponse GGMLModel::generate(const AIInferenceRequest& request) { AIInferenceResponse response; response.vm_id = request.vm_id; response.session_id = request.session_id; - + if (!loaded_) { response.error = "Model not loaded"; response.success = false; return response; } - + auto start_time = std::chrono::high_resolution_clock::now(); - + // Get parameters from request or use defaults std::map params; - params["temperature"] = request.parameters.count("temperature") ? - request.parameters.at("temperature") : config_.temperature; - params["top_p"] = request.parameters.count("top_p") ? - request.parameters.at("top_p") : config_.top_p; - + params["temperature"] = + request.parameters.count("temperature") ? request.parameters.at("temperature") : config_.temperature; + params["top_p"] = request.parameters.count("top_p") ? request.parameters.at("top_p") : config_.top_p; + // Perform inference (simplified simulation) response.response = tokenize_and_generate(request.prompt, params); - - auto end_time = std::chrono::high_resolution_clock::now(); - response.inference_time_ms = std::chrono::duration(end_time - start_time).count(); - response.tokens_generated = response.response.length() / 4; // Rough estimate - response.tokens_processed = request.prompt.length() / 4; - response.success = true; - + + finish_successful_inference(response, request, start_time); + return response; } @@ -109,9 +126,9 @@ AIInferenceResponse GGMLModel::chat(const std::string& message, const std::strin request.prompt = "Human: " + message + "\nAI:"; request.context = context; request.task_type = "chat"; - + AIInferenceResponse response = generate(request); - + // Clean up the response to remove the prompt prefix if (response.success && response.response.find("AI:") != std::string::npos) { size_t ai_pos = response.response.find("AI:"); @@ -119,7 +136,7 @@ AIInferenceResponse GGMLModel::chat(const std::string& message, const std::strin response.response = response.response.substr(ai_pos + 3); } } - + return response; } @@ -127,7 +144,7 @@ AIInferenceResponse GGMLModel::complete_code(const std::string& code, const std: AIInferenceRequest request; request.prompt = "// Complete this " + language + " code:\n" + code + "\n// Completion:"; request.task_type = "completion"; - + return generate(request); } @@ -149,19 +166,25 @@ std::vector GGMLModel::get_capabilities() const { std::string GGMLModel::tokenize_and_generate(const std::string& input, const std::map& params) { // Simplified generation for demo // In a real implementation, this would use GGML for tokenization and generation - + std::string response; - + if (input.find("code") != std::string::npos || input.find("function") != std::string::npos) { - response = "```cpp\n// AI-generated code completion\nvoid example_function() {\n std::cout << \"Hello from AI!\" << std::endl;\n}\n```"; + response = + "```cpp\n// AI-generated code completion\nvoid example_function() {\n std::cout << \"Hello from AI!\" " + "<< std::endl;\n}\n```"; } else if (input.find("Human:") != std::string::npos) { response = "AI: Hello! I'm an AI assistant running in a DrawKern VM. How can I help you today?"; } else if (input.find("explain") != std::string::npos || input.find("analyze") != std::string::npos) { - response = "This appears to be a request for code analysis. The code looks well-structured and follows good practices."; + response = + "This appears to be a request for code analysis. The code looks well-structured and follows good " + "practices."; } else { - response = "AI: I understand you're working with DrawKern! This is a powerful system for deploying AI workbenches as VM glyphs. What would you like to know?"; + response = + "AI: I understand you're working with DrawKern! This is a powerful system for deploying AI workbenches as " + "VM glyphs. What would you like to know?"; } - + return response; } @@ -186,8 +209,7 @@ std::string GGMLModel::detokenize(const std::vector& tokens) { } // RWKVModel implementation -RWKVModel::RWKVModel(const AIModelConfig& config) : AIModel(config) { -} +RWKVModel::RWKVModel(const AIModelConfig& config) : AIModel(config) {} RWKVModel::~RWKVModel() { unload(); @@ -197,18 +219,18 @@ bool RWKVModel::load() { if (loaded_) { return true; } - + std::cout << "Loading RWKV model: " << config_.model_path << std::endl; - + std::ifstream file(config_.model_path); if (!file.good()) { std::cerr << "RWKV model file not found: " << config_.model_path << std::endl; return false; } - + // Simulate RWKV model loading std::this_thread::sleep_for(std::chrono::milliseconds(700)); - + loaded_ = true; std::cout << "RWKV model loaded successfully" << std::endl; return true; @@ -218,17 +240,17 @@ void RWKVModel::unload() { if (!loaded_) { return; } - + if (rwkv_context_) { // Free RWKV context rwkv_context_ = nullptr; } - + if (rwkv_state_) { // Free RWKV state rwkv_state_ = nullptr; } - + loaded_ = false; std::cout << "RWKV model unloaded" << std::endl; } @@ -237,27 +259,23 @@ AIInferenceResponse RWKVModel::generate(const AIInferenceRequest& request) { AIInferenceResponse response; response.vm_id = request.vm_id; response.session_id = request.session_id; - + if (!loaded_) { response.error = "RWKV model not loaded"; response.success = false; return response; } - + auto start_time = std::chrono::high_resolution_clock::now(); - + std::map params; - params["temperature"] = request.parameters.count("temperature") ? - request.parameters.at("temperature") : config_.temperature; - + params["temperature"] = + request.parameters.count("temperature") ? request.parameters.at("temperature") : config_.temperature; + response.response = generate_with_rwkv(request.prompt, params); - - auto end_time = std::chrono::high_resolution_clock::now(); - response.inference_time_ms = std::chrono::duration(end_time - start_time).count(); - response.tokens_generated = response.response.length() / 4; - response.tokens_processed = request.prompt.length() / 4; - response.success = true; - + + finish_successful_inference(response, request, start_time); + return response; } @@ -266,7 +284,7 @@ AIInferenceResponse RWKVModel::chat(const std::string& message, const std::strin request.prompt = "User: " + message + "\n\nAssistant:"; request.context = context; request.task_type = "chat"; - + return generate(request); } @@ -274,7 +292,7 @@ AIInferenceResponse RWKVModel::complete_code(const std::string& code, const std: AIInferenceRequest request; request.prompt = "Complete this " + language + " code:\n" + code; request.task_type = "completion"; - + return generate(request); } @@ -295,17 +313,25 @@ std::vector RWKVModel::get_capabilities() const { std::string RWKVModel::generate_with_rwkv(const std::string& input, const std::map& params) { // Simplified RWKV generation std::string response; - + if (input.find("DrawKern") != std::string::npos || input.find("VM") != std::string::npos) { - response = "RWKV: DrawKern is revolutionary! It allows you to deploy entire AI workbenches as glyphs that can be rendered anywhere. The DIS VM integration makes it incredibly portable."; + response = + "RWKV: DrawKern is revolutionary! It allows you to deploy entire AI workbenches as glyphs that can be " + "rendered anywhere. The DIS VM integration makes it incredibly portable."; } else if (input.find("code") != std::string::npos) { - response = "```\n// RWKV-generated completion\nauto result = ai_model.generate(request);\nif (result.success) {\n std::cout << result.response << std::endl;\n}\n```"; + response = + "```\n// RWKV-generated completion\nauto result = ai_model.generate(request);\nif (result.success) {\n " + "std::cout << result.response << std::endl;\n}\n```"; } else if (input.find("User:") != std::string::npos || input.find("Human:") != std::string::npos) { - response = "Assistant: Hello! I'm running as an RWKV model in a DrawKern VM. I can help with coding, explanations, and analysis. What would you like to explore?"; + response = + "Assistant: Hello! I'm running as an RWKV model in a DrawKern VM. I can help with coding, explanations, " + "and analysis. What would you like to explore?"; } else { - response = "RWKV: This is an RWKV model responding from within the DrawKern system. The state-based architecture makes me very efficient for ongoing conversations!"; + response = + "RWKV: This is an RWKV model responding from within the DrawKern system. The state-based architecture " + "makes me very efficient for ongoing conversations!"; } - + return response; } @@ -320,13 +346,12 @@ void RWKVModel::update_state(const std::vector& tokens) { // Update RWKV state with new tokens for (int32_t token : tokens) { // Process token through RWKV state update - (void)token; // Suppress unused parameter warning + (void)token; // Suppress unused parameter warning } } // DrawKernAIManager implementation -DrawKernAIManager::DrawKernAIManager() { -} +DrawKernAIManager::DrawKernAIManager() {} DrawKernAIManager::~DrawKernAIManager() { // Unload all models @@ -340,16 +365,16 @@ bool DrawKernAIManager::load_model(const std::string& model_id, const AIModelCon std::cout << "Model " << model_id << " already loaded" << std::endl; return true; } - + auto model = create_model(config); if (!model || !model->load()) { std::cerr << "Failed to load model: " << model_id << std::endl; return false; } - + models_[model_id] = std::move(model); model_stats_[model_id] = ModelStats{model_id}; - + std::cout << "Loaded model: " << model_id << " (type: " << config.model_type << ")" << std::endl; return true; } @@ -359,11 +384,11 @@ bool DrawKernAIManager::unload_model(const std::string& model_id) { if (it == models_.end()) { return false; } - + it->second->unload(); models_.erase(it); model_stats_.erase(model_id); - + std::cout << "Unloaded model: " << model_id << std::endl; return true; } @@ -376,32 +401,27 @@ bool DrawKernAIManager::is_model_loaded(const std::string& model_id) const { AIInferenceResponse DrawKernAIManager::generate(const std::string& model_id, const AIInferenceRequest& request) { auto it = models_.find(model_id); if (it == models_.end()) { - AIInferenceResponse error_response; - error_response.error = "Model not found: " + model_id; - error_response.success = false; - return error_response; + return model_not_found_response(model_id); } - + AIInferenceResponse response = it->second->generate(request); update_stats(model_id, response); - + // Broadcast to VM if handler is registered if (!request.vm_id.empty() && vm_handlers_.count(request.vm_id)) { vm_handlers_[request.vm_id](response); } - + return response; } -AIInferenceResponse DrawKernAIManager::chat(const std::string& model_id, const std::string& message, const std::string& session_id) { +AIInferenceResponse DrawKernAIManager::chat(const std::string& model_id, const std::string& message, + const std::string& session_id) { auto it = models_.find(model_id); if (it == models_.end()) { - AIInferenceResponse error_response; - error_response.error = "Model not found: " + model_id; - error_response.success = false; - return error_response; + return model_not_found_response(model_id); } - + // Get session context std::string context; if (!session_id.empty() && session_history_.count(session_id)) { @@ -410,41 +430,40 @@ AIInferenceResponse DrawKernAIManager::chat(const std::string& model_id, const s context += msg + "\n"; } } - + AIInferenceResponse response = it->second->chat(message, context); update_stats(model_id, response); - + // Update session history if (!session_id.empty() && response.success) { session_history_[session_id].push_back("Human: " + message); session_history_[session_id].push_back("AI: " + response.response); - + // Keep only last 10 exchanges auto& history = session_history_[session_id]; if (history.size() > 20) { history.erase(history.begin(), history.begin() + (history.size() - 20)); } } - + return response; } -AIInferenceResponse DrawKernAIManager::complete_code(const std::string& model_id, const std::string& code, const std::string& language) { +AIInferenceResponse DrawKernAIManager::complete_code(const std::string& model_id, const std::string& code, + const std::string& language) { auto it = models_.find(model_id); if (it == models_.end()) { - AIInferenceResponse error_response; - error_response.error = "Model not found: " + model_id; - error_response.success = false; - return error_response; + return model_not_found_response(model_id); } - + AIInferenceResponse response = it->second->complete_code(code, language); update_stats(model_id, response); - + return response; } -void DrawKernAIManager::register_vm_ai_handler(const std::string& vm_id, std::function handler) { +void DrawKernAIManager::register_vm_ai_handler(const std::string& vm_id, + std::function handler) { vm_handlers_[vm_id] = handler; std::cout << "Registered AI handler for VM: " << vm_id << std::endl; } @@ -490,7 +509,7 @@ std::vector DrawKernAIManager::list_available_model_types() const { AIModelConfig DrawKernAIManager::get_default_config(const std::string& model_type) { AIModelConfig config; config.model_type = model_type; - + if (model_type == "rwkv") { config.model_name = "RWKV Model"; config.context_length = 4096; @@ -504,7 +523,7 @@ AIModelConfig DrawKernAIManager::get_default_config(const std::string& model_typ config.n_embd = 4096; config.temperature = 0.7f; } - + return config; } @@ -522,7 +541,7 @@ std::unique_ptr DrawKernAIManager::create_model(const AIModelConfig& co } else if (config.model_type == "ggml" || config.model_type == "llama") { return std::make_unique(config); } - + std::cerr << "Unknown model type: " << config.model_type << std::endl; return nullptr; } @@ -530,13 +549,14 @@ std::unique_ptr DrawKernAIManager::create_model(const AIModelConfig& co void DrawKernAIManager::update_stats(const std::string& model_id, const AIInferenceResponse& response) { auto& stats = model_stats_[model_id]; stats.total_requests++; - + if (response.success) { stats.successful_requests++; stats.total_tokens_generated += response.tokens_generated; - + // Update rolling average of inference time - float total_time = stats.average_inference_time_ms * (stats.successful_requests - 1) + response.inference_time_ms; + float total_time = + stats.average_inference_time_ms * (stats.successful_requests - 1) + response.inference_time_ms; stats.average_inference_time_ms = total_time / stats.successful_requests; } } @@ -547,7 +567,7 @@ AIModelConfig AIModelFactory::create_rwkv_config(const std::string& model_path, config.model_type = "rwkv"; config.model_path = model_path; config.model_name = "RWKV-" + size; - + // Set parameters based on model size if (size == "14b" || size == "14B") { config.n_layers = 40; @@ -565,16 +585,16 @@ AIModelConfig AIModelFactory::create_rwkv_config(const std::string& model_path, config.context_length = 2048; config.n_threads = 4; } - + config.temperature = 0.8f; config.top_p = 0.9f; - + return config; } AIModelConfig AIModelFactory::create_drawkern_workbench_config(const std::string& model_path) { AIModelConfig config = create_rwkv_config(model_path, "7b"); - + // Optimize for DrawKern workbench use config.model_name = "DrawKern AI Workbench"; config.max_tokens = 512; @@ -582,7 +602,7 @@ AIModelConfig AIModelFactory::create_drawkern_workbench_config(const std::string config.enable_chat = true; config.enable_completion = true; config.enable_analysis = true; - + return config; } @@ -591,7 +611,7 @@ AIModelConfig AIModelFactory::create_lightweight_config(const std::string& model config.model_type = "ggml"; config.model_path = model_path; config.model_name = "Lightweight Model"; - + // Minimal resource usage config.n_layers = 12; config.n_embd = 768; @@ -600,7 +620,7 @@ AIModelConfig AIModelFactory::create_lightweight_config(const std::string& model config.max_tokens = 128; config.use_mmap = true; config.use_mlock = false; - + return config; } @@ -609,79 +629,79 @@ bool AIModelFactory::validate_model_config(const AIModelConfig& config) { std::cerr << "Model path cannot be empty" << std::endl; return false; } - + if (config.context_length <= 0 || config.context_length > 32768) { std::cerr << "Invalid context length: " << config.context_length << std::endl; return false; } - + if (config.n_threads <= 0 || config.n_threads > 32) { std::cerr << "Invalid thread count: " << config.n_threads << std::endl; return false; } - + return true; } // Integration functions namespace Integration { - - void setup_dis_vm_ai_integration(DISVM& vm, DrawKernAIManager& ai_manager, const std::string& model_id) { - // Set up AI handler for the DIS VM - auto ai_handler = [&ai_manager, model_id](const std::string& prompt, const std::string& context) -> std::string { - AIInferenceRequest request; - request.prompt = prompt; - request.context = context; - request.task_type = "chat"; - - AIInferenceResponse response = ai_manager.generate(model_id, request); - return response.success ? response.response : "AI Error: " + response.error; - }; - - vm.set_ai_handler(ai_handler); - std::cout << "Set up AI integration for DIS VM with model: " << model_id << std::endl; - } - - void setup_styx_ai_integration(StyxServer& server, DrawKernAIManager& ai_manager) { - // Register AI handlers for Styx server - auto ai_handler = [&ai_manager](const std::string& request) { - // Parse AI request from Styx message - // For demo, assume default model - auto models = ai_manager.list_models(); - if (!models.empty()) { - AIInferenceRequest ai_request; - ai_request.prompt = request; - ai_request.task_type = "chat"; - - AIInferenceResponse response = ai_manager.generate(models[0], ai_request); - std::cout << "Styx AI Response: " << response.response << std::endl; - } - }; - - server.register_glyph_handler(ai_handler); - std::cout << "Set up AI integration for Styx server" << std::endl; - } - - bool setup_ai_workbench(const AIWorkbenchConfig& config, DrawKernAIManager& ai_manager) { - std::cout << "Setting up AI workbench: " << config.workbench_id << std::endl; - - // Load all specified models - for (const auto& model_id : config.model_ids) { - if (!ai_manager.is_model_loaded(model_id)) { - std::cout << "Warning: Model not loaded: " << model_id << std::endl; - } + +void setup_dis_vm_ai_integration(DISVM& vm, DrawKernAIManager& ai_manager, const std::string& model_id) { + // Set up AI handler for the DIS VM + auto ai_handler = [&ai_manager, model_id](const std::string& prompt, const std::string& context) -> std::string { + AIInferenceRequest request; + request.prompt = prompt; + request.context = context; + request.task_type = "chat"; + + AIInferenceResponse response = ai_manager.generate(model_id, request); + return response.success ? response.response : "AI Error: " + response.error; + }; + + vm.set_ai_handler(ai_handler); + std::cout << "Set up AI integration for DIS VM with model: " << model_id << std::endl; +} + +void setup_styx_ai_integration(StyxServer& server, DrawKernAIManager& ai_manager) { + // Register AI handlers for Styx server + auto ai_handler = [&ai_manager](const std::string& request) { + // Parse AI request from Styx message + // For demo, assume default model + auto models = ai_manager.list_models(); + if (!models.empty()) { + AIInferenceRequest ai_request; + ai_request.prompt = request; + ai_request.task_type = "chat"; + + AIInferenceResponse response = ai_manager.generate(models[0], ai_request); + std::cout << "Styx AI Response: " << response.response << std::endl; } - - // Create workbench session - if (!config.model_ids.empty()) { - ai_manager.create_session(config.workbench_id, config.model_ids[0]); + }; + + server.register_glyph_handler(ai_handler); + std::cout << "Set up AI integration for Styx server" << std::endl; +} + +bool setup_ai_workbench(const AIWorkbenchConfig& config, DrawKernAIManager& ai_manager) { + std::cout << "Setting up AI workbench: " << config.workbench_id << std::endl; + + // Load all specified models + for (const auto& model_id : config.model_ids) { + if (!ai_manager.is_model_loaded(model_id)) { + std::cout << "Warning: Model not loaded: " << model_id << std::endl; } - - std::cout << "AI workbench setup complete" << std::endl; - return true; } - -} // namespace Integration -} // namespace drawkern -} // namespace bolt \ No newline at end of file + // Create workbench session + if (!config.model_ids.empty()) { + ai_manager.create_session(config.workbench_id, config.model_ids[0]); + } + + std::cout << "AI workbench setup complete" << std::endl; + return true; +} + +} // namespace Integration + +} // namespace drawkern +} // namespace bolt diff --git a/src/bolt/drawkern/yacc_grammar.cpp b/src/bolt/drawkern/yacc_grammar.cpp index f07ac026..b869b82e 100644 --- a/src/bolt/drawkern/yacc_grammar.cpp +++ b/src/bolt/drawkern/yacc_grammar.cpp @@ -1,30 +1,67 @@ #include "bolt/drawkern/yacc_grammar.hpp" -#include "bolt/drawkern/drawkern.hpp" -#include "bolt/drawkern/dis_vm.hpp" -#include -#include + #include #include +#include +#include + +#include "bolt/drawkern/dis_vm.hpp" +#include "bolt/drawkern/drawkern.hpp" namespace bolt { namespace drawkern { +namespace { + +// Tokenizes and parses a glyph description, leaving the lexer and parser it creates in the given owners +// (so their errors can be collected afterwards), and returns the parsed program. +std::unique_ptr lex_and_parse(const std::string& description, std::unique_ptr& lexer, + std::unique_ptr& parser) { + lexer = std::make_unique(description); + auto tokens = lexer->tokenize(); + + parser = std::make_unique(tokens); + return parser->parse(); +} + +} // namespace + // ASTNode implementation std::string ASTNode::to_string() const { std::string result; switch (type) { - case ASTNodeType::PROGRAM: result = "Program"; break; - case ASTNodeType::VM_DECL: result = "VMDecl"; break; - case ASTNodeType::GLYPH_DECL: result = "GlyphDecl"; break; - case ASTNodeType::PROPERTY: result = "Property"; break; - case ASTNodeType::BLOCK: result = "Block"; break; - case ASTNodeType::EXPRESSION: result = "Expression"; break; - case ASTNodeType::IDENTIFIER: result = "Identifier"; break; - case ASTNodeType::LITERAL: result = "Literal"; break; - case ASTNodeType::LIST: result = "List"; break; - case ASTNodeType::CALL: result = "Call"; break; - } - + case ASTNodeType::PROGRAM: + result = "Program"; + break; + case ASTNodeType::VM_DECL: + result = "VMDecl"; + break; + case ASTNodeType::GLYPH_DECL: + result = "GlyphDecl"; + break; + case ASTNodeType::PROPERTY: + result = "Property"; + break; + case ASTNodeType::BLOCK: + result = "Block"; + break; + case ASTNodeType::EXPRESSION: + result = "Expression"; + break; + case ASTNodeType::IDENTIFIER: + result = "Identifier"; + break; + case ASTNodeType::LITERAL: + result = "Literal"; + break; + case ASTNodeType::LIST: + result = "List"; + break; + case ASTNodeType::CALL: + result = "Call"; + break; + } + if (!attributes.empty()) { result += " {"; for (const auto& [key, value] : attributes) { @@ -32,91 +69,108 @@ std::string ASTNode::to_string() const { } result += " }"; } - + return result; } // GlyphLexer implementation -GlyphLexer::GlyphLexer(const std::string& input) - : input_(input), pos_(0), line_(1), column_(1) { -} +GlyphLexer::GlyphLexer(const std::string& input) : input_(input), pos_(0), line_(1), column_(1) {} -GlyphLexer::~GlyphLexer() { -} +GlyphLexer::~GlyphLexer() {} std::vector GlyphLexer::tokenize() { std::vector tokens; errors_.clear(); - + while (pos_ < input_.length()) { Token token = next_token(); if (token.type != TokenType::UNKNOWN) { tokens.push_back(token); } - + if (token.type == TokenType::END_OF_FILE) { break; } } - + return tokens; } Token GlyphLexer::next_token() { skip_whitespace(); - + if (pos_ >= input_.length()) { return Token(TokenType::END_OF_FILE, "", line_, column_); } - + char ch = current_char(); - + // Comments if (ch == '/' && peek_char() == '/') { skip_comment(); return next_token(); } - + // Single character tokens switch (ch) { - case '=': advance(); return Token(TokenType::ASSIGN, "=", line_, column_ - 1); - case ';': advance(); return Token(TokenType::SEMICOLON, ";", line_, column_ - 1); - case ',': advance(); return Token(TokenType::COMMA, ",", line_, column_ - 1); - case '{': advance(); return Token(TokenType::LBRACE, "{", line_, column_ - 1); - case '}': advance(); return Token(TokenType::RBRACE, "}", line_, column_ - 1); - case '(': advance(); return Token(TokenType::LPAREN, "(", line_, column_ - 1); - case ')': advance(); return Token(TokenType::RPAREN, ")", line_, column_ - 1); - case '[': advance(); return Token(TokenType::LBRACKET, "[", line_, column_ - 1); - case ']': advance(); return Token(TokenType::RBRACKET, "]", line_, column_ - 1); - } - + case '=': + advance(); + return Token(TokenType::ASSIGN, "=", line_, column_ - 1); + case ';': + advance(); + return Token(TokenType::SEMICOLON, ";", line_, column_ - 1); + case ',': + advance(); + return Token(TokenType::COMMA, ",", line_, column_ - 1); + case '{': + advance(); + return Token(TokenType::LBRACE, "{", line_, column_ - 1); + case '}': + advance(); + return Token(TokenType::RBRACE, "}", line_, column_ - 1); + case '(': + advance(); + return Token(TokenType::LPAREN, "(", line_, column_ - 1); + case ')': + advance(); + return Token(TokenType::RPAREN, ")", line_, column_ - 1); + case '[': + advance(); + return Token(TokenType::LBRACKET, "[", line_, column_ - 1); + case ']': + advance(); + return Token(TokenType::RBRACKET, "]", line_, column_ - 1); + } + // String literals if (ch == '"') { return read_string(); } - + // Numbers if (is_digit(ch)) { return read_number(); } - + // Identifiers and keywords if (is_alpha(ch) || ch == '_') { return read_identifier(); } - + add_error("Unexpected character: " + std::string(1, ch)); advance(); return Token(TokenType::UNKNOWN, std::string(1, ch), line_, column_ - 1); } char GlyphLexer::current_char() { - if (pos_ >= input_.length()) return '\0'; + if (pos_ >= input_.length()) + return '\0'; return input_[pos_]; } char GlyphLexer::peek_char() { - if (pos_ + 1 >= input_.length()) return '\0'; + if (pos_ + 1 >= input_.length()) + return '\0'; return input_[pos_ + 1]; } @@ -148,26 +202,37 @@ Token GlyphLexer::read_identifier() { size_t start_line = line_; size_t start_column = column_; std::string value; - + while (pos_ < input_.length() && (is_alnum(current_char()) || current_char() == '_')) { value += current_char(); advance(); } - + // Check for keywords TokenType type = TokenType::IDENTIFIER; - if (value == "vm") type = TokenType::VM; - else if (value == "glyph") type = TokenType::GLYPH; - else if (value == "workbench") type = TokenType::WORKBENCH; - else if (value == "dis") type = TokenType::DIS; - else if (value == "native") type = TokenType::NATIVE; - else if (value == "wasm") type = TokenType::WASM; - else if (value == "render") type = TokenType::RENDER; - else if (value == "ai") type = TokenType::AI; - else if (value == "model") type = TokenType::MODEL; - else if (value == "tools") type = TokenType::TOOLS; - else if (value == "namespace") type = TokenType::NAMESPACE; - + if (value == "vm") + type = TokenType::VM; + else if (value == "glyph") + type = TokenType::GLYPH; + else if (value == "workbench") + type = TokenType::WORKBENCH; + else if (value == "dis") + type = TokenType::DIS; + else if (value == "native") + type = TokenType::NATIVE; + else if (value == "wasm") + type = TokenType::WASM; + else if (value == "render") + type = TokenType::RENDER; + else if (value == "ai") + type = TokenType::AI; + else if (value == "model") + type = TokenType::MODEL; + else if (value == "tools") + type = TokenType::TOOLS; + else if (value == "namespace") + type = TokenType::NAMESPACE; + return Token(type, value, start_line, start_column); } @@ -175,33 +240,45 @@ Token GlyphLexer::read_string() { size_t start_line = line_; size_t start_column = column_; std::string value; - - advance(); // Skip opening quote - + + advance(); // Skip opening quote + while (pos_ < input_.length() && current_char() != '"') { if (current_char() == '\\' && peek_char() != '\0') { advance(); char escaped = current_char(); switch (escaped) { - case 'n': value += '\n'; break; - case 't': value += '\t'; break; - case 'r': value += '\r'; break; - case '\\': value += '\\'; break; - case '"': value += '"'; break; - default: value += escaped; break; + case 'n': + value += '\n'; + break; + case 't': + value += '\t'; + break; + case 'r': + value += '\r'; + break; + case '\\': + value += '\\'; + break; + case '"': + value += '"'; + break; + default: + value += escaped; + break; } } else { value += current_char(); } advance(); } - + if (current_char() == '"') { - advance(); // Skip closing quote + advance(); // Skip closing quote } else { add_error("Unterminated string literal"); } - + return Token(TokenType::STRING, value, start_line, start_column); } @@ -209,12 +286,12 @@ Token GlyphLexer::read_number() { size_t start_line = line_; size_t start_column = column_; std::string value; - + while (pos_ < input_.length() && (is_digit(current_char()) || current_char() == '.')) { value += current_char(); advance(); } - + return Token(TokenType::NUMBER, value, start_line, start_column); } @@ -235,26 +312,23 @@ void GlyphLexer::add_error(const std::string& message) { } // GlyphParser implementation -GlyphParser::GlyphParser(const std::vector& tokens) - : tokens_(tokens), pos_(0) { -} +GlyphParser::GlyphParser(const std::vector& tokens) : tokens_(tokens), pos_(0) {} -GlyphParser::~GlyphParser() { -} +GlyphParser::~GlyphParser() {} std::unique_ptr GlyphParser::parse() { errors_.clear(); pos_ = 0; - + auto program = std::make_unique(); - + while (pos_ < tokens_.size() && current_token().type != TokenType::END_OF_FILE) { auto statement = parse_statement(); if (statement) { program->add_child(std::move(statement)); } } - + return program; } @@ -308,20 +382,20 @@ std::unique_ptr GlyphParser::parse_vm_declaration() { if (!consume(TokenType::VM)) { return nullptr; } - + if (!match(TokenType::IDENTIFIER)) { add_error("Expected VM name"); return nullptr; } - + std::string vm_id = current_token().value; advance(); - + if (!consume(TokenType::ASSIGN)) { add_error("Expected ':' after VM name"); return nullptr; } - + std::string vm_type; if (match(TokenType::DIS)) { vm_type = "dis"; @@ -336,61 +410,61 @@ std::unique_ptr GlyphParser::parse_vm_declaration() { add_error("Expected VM type (dis, native, wasm)"); return nullptr; } - + auto vm_node = std::make_unique(vm_id, vm_type); - + if (consume(TokenType::LBRACE)) { auto block = parse_block(); if (block) { vm_node->add_child(std::move(block)); } } - + return vm_node; } std::unique_ptr GlyphParser::parse_glyph_declaration() { bool is_workbench = match(TokenType::WORKBENCH); - + if (!(consume(TokenType::GLYPH) || consume(TokenType::WORKBENCH))) { return nullptr; } - + if (!match(TokenType::IDENTIFIER)) { add_error("Expected glyph name"); return nullptr; } - + std::string glyph_id = current_token().value; advance(); - + // Expect 'on' keyword (simplified - using identifier) if (!match(TokenType::IDENTIFIER) || current_token().value != "on") { add_error("Expected 'on' after glyph name"); return nullptr; } advance(); - + if (!match(TokenType::IDENTIFIER)) { add_error("Expected VM name after 'on'"); return nullptr; } - + std::string base_vm = current_token().value; advance(); - + auto glyph_node = std::make_unique(glyph_id, base_vm); if (is_workbench) { glyph_node->set_attribute("type", "workbench"); } - + if (consume(TokenType::LBRACE)) { auto block = parse_block(); if (block) { glyph_node->add_child(std::move(block)); } } - + return glyph_node; } @@ -398,15 +472,15 @@ std::unique_ptr GlyphParser::parse_property() { if (!match(TokenType::IDENTIFIER)) { return nullptr; } - + std::string name = current_token().value; advance(); - + if (!consume(TokenType::ASSIGN)) { add_error("Expected '=' after property name"); return nullptr; } - + std::string value; if (match(TokenType::STRING) || match(TokenType::NUMBER) || match(TokenType::IDENTIFIER)) { value = current_token().value; @@ -430,24 +504,24 @@ std::unique_ptr GlyphParser::parse_property() { add_error("Expected property value"); return nullptr; } - - consume(TokenType::SEMICOLON); // Optional semicolon - + + consume(TokenType::SEMICOLON); // Optional semicolon + return std::make_unique(name, value); } std::unique_ptr GlyphParser::parse_block() { auto block = std::make_unique(ASTNodeType::BLOCK); - + while (!match(TokenType::RBRACE) && !match(TokenType::END_OF_FILE)) { auto statement = parse_statement(); if (statement) { block->add_child(std::move(statement)); } else { - advance(); // Skip problematic tokens + advance(); // Skip problematic tokens } } - + consume(TokenType::RBRACE); return block; } @@ -455,53 +529,52 @@ std::unique_ptr GlyphParser::parse_block() { std::unique_ptr GlyphParser::parse_expression() { // Simplified expression parsing auto expr = std::make_unique(ASTNodeType::EXPRESSION); - + if (match(TokenType::IDENTIFIER) || match(TokenType::STRING) || match(TokenType::NUMBER)) { expr->set_attribute("value", current_token().value); advance(); } - + return expr; } std::unique_ptr GlyphParser::parse_list() { auto list = std::make_unique(ASTNodeType::LIST); - + if (!consume(TokenType::LBRACKET)) { return nullptr; } - + while (!match(TokenType::RBRACKET) && !match(TokenType::END_OF_FILE)) { auto expr = parse_expression(); if (expr) { list->add_child(std::move(expr)); } - + if (!consume(TokenType::COMMA)) { break; } } - + consume(TokenType::RBRACKET); return list; } void GlyphParser::add_error(const std::string& message) { Token token = current_token(); - errors_.push_back("Line " + std::to_string(token.line) + ", Column " + std::to_string(token.column) + ": " + message); + errors_.push_back("Line " + std::to_string(token.line) + ", Column " + std::to_string(token.column) + ": " + + message); } // GlyphCodeGenerator implementation -GlyphCodeGenerator::GlyphCodeGenerator() { -} +GlyphCodeGenerator::GlyphCodeGenerator() {} -GlyphCodeGenerator::~GlyphCodeGenerator() { -} +GlyphCodeGenerator::~GlyphCodeGenerator() {} VMGlyph GlyphCodeGenerator::generate_vm_glyph(const ASTNode& ast) { errors_.clear(); VMGlyph glyph; - + // Set defaults glyph.vm_type = "dis"; glyph.architecture = "portable"; @@ -510,7 +583,7 @@ VMGlyph GlyphCodeGenerator::generate_vm_glyph(const ASTNode& ast) { glyph.render.background_color = 0x1e1e1e; glyph.render.interactive = true; glyph.render.ai_enabled = false; - + // Process AST nodes for (const auto& child : ast.children) { if (child->type == ASTNodeType::VM_DECL) { @@ -523,7 +596,7 @@ VMGlyph GlyphCodeGenerator::generate_vm_glyph(const ASTNode& ast) { for (const auto& prop_child : grandchild->children) { if (prop_child->type == ASTNodeType::PROPERTY) { const PropertyNode* prop = static_cast(prop_child.get()); - + if (prop->name == "width") { glyph.render.width = std::stoi(prop->value); } else if (prop->name == "height") { @@ -539,47 +612,47 @@ VMGlyph GlyphCodeGenerator::generate_vm_glyph(const ASTNode& ast) { } } } - + return glyph; } AIWorkbenchGlyph GlyphCodeGenerator::generate_ai_workbench(const ASTNode& ast) { AIWorkbenchGlyph workbench; - + workbench.workbench_id = "generated_workbench"; workbench.ai_model = "ggml-rwkv"; workbench.tools = {"completion", "chat"}; workbench.styx_address = "tcp!*!9999"; - + // Generate host VM workbench.host_vm = generate_vm_glyph(ast); workbench.host_vm.render.ai_enabled = true; - + return workbench; } DISProgram GlyphCodeGenerator::generate_dis_program(const ASTNode& ast) { DISProgram program; - + // Generate a simple AI workbench program program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("🤖 AI Workbench starting...\n"))); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - + program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("ggml-rwkv"))); program.add_instruction(DISInstruction(DISOpcode::AI_INIT)); - + program.add_instruction(DISInstruction(DISOpcode::NEWSTR, DISValue("Hello from generated workbench!"))); program.add_instruction(DISInstruction(DISOpcode::AI_CHAT)); program.add_instruction(DISInstruction(DISOpcode::PRINT)); - + program.add_instruction(DISInstruction(DISOpcode::HALT)); - + return program; } std::string GlyphCodeGenerator::generate_cpp_code(const ASTNode& ast) { std::ostringstream code; - + code << "#include \"bolt/drawkern/drawkern.hpp\"\n"; code << "#include \"bolt/drawkern/dis_vm.hpp\"\n\n"; code << "using namespace bolt::drawkern;\n\n"; @@ -598,13 +671,13 @@ std::string GlyphCodeGenerator::generate_cpp_code(const ASTNode& ast) { code << " \n"; code << " return workbench;\n"; code << "}\n"; - + return code.str(); } std::string GlyphCodeGenerator::generate_json(const ASTNode& ast) { std::ostringstream json; - + json << "{\n"; json << " \"workbench_id\": \"generated_workbench\",\n"; json << " \"ai_model\": \"ggml-rwkv\",\n"; @@ -619,13 +692,13 @@ std::string GlyphCodeGenerator::generate_json(const ASTNode& ast) { json << " }\n"; json << " }\n"; json << "}\n"; - + return json.str(); } std::string GlyphCodeGenerator::generate_yaml(const ASTNode& ast) { std::ostringstream yaml; - + yaml << "workbench_id: generated_workbench\n"; yaml << "ai_model: ggml-rwkv\n"; yaml << "tools:\n"; @@ -638,7 +711,7 @@ std::string GlyphCodeGenerator::generate_yaml(const ASTNode& ast) { yaml << " width: 1200\n"; yaml << " height: 800\n"; yaml << " ai_enabled: true\n"; - + return yaml.str(); } @@ -647,53 +720,39 @@ void GlyphCodeGenerator::add_error(const std::string& message) { } // YaccGrammarSystem implementation -YaccGrammarSystem::YaccGrammarSystem() { -} +YaccGrammarSystem::YaccGrammarSystem() {} -YaccGrammarSystem::~YaccGrammarSystem() { -} +YaccGrammarSystem::~YaccGrammarSystem() {} VMGlyph YaccGrammarSystem::parse_vm_glyph(const std::string& description) { clear_errors(); - - lexer_ = std::make_unique(description); - auto tokens = lexer_->tokenize(); - - parser_ = std::make_unique(tokens); - auto ast = parser_->parse(); - + + auto ast = lex_and_parse(description, lexer_, parser_); + generator_ = std::make_unique(); VMGlyph glyph = generator_->generate_vm_glyph(*ast); - + collect_errors(); return glyph; } AIWorkbenchGlyph YaccGrammarSystem::parse_ai_workbench(const std::string& description) { clear_errors(); - - lexer_ = std::make_unique(description); - auto tokens = lexer_->tokenize(); - - parser_ = std::make_unique(tokens); - auto ast = parser_->parse(); - + + auto ast = lex_and_parse(description, lexer_, parser_); + generator_ = std::make_unique(); AIWorkbenchGlyph workbench = generator_->generate_ai_workbench(*ast); - + collect_errors(); return workbench; } bool YaccGrammarSystem::validate_description(const std::string& description) { clear_errors(); - - lexer_ = std::make_unique(description); - auto tokens = lexer_->tokenize(); - - parser_ = std::make_unique(tokens); - auto ast = parser_->parse(); - + + auto ast = lex_and_parse(description, lexer_, parser_); + collect_errors(); return errors_.empty(); } @@ -704,30 +763,26 @@ std::vector YaccGrammarSystem::get_validation_errors() const { std::string YaccGrammarSystem::generate_cpp_code(const std::string& description) { clear_errors(); - - lexer_ = std::make_unique(description); - auto tokens = lexer_->tokenize(); - - parser_ = std::make_unique(tokens); - auto ast = parser_->parse(); - + + auto ast = lex_and_parse(description, lexer_, parser_); + generator_ = std::make_unique(); std::string code = generator_->generate_cpp_code(*ast); - + collect_errors(); return code; } std::string YaccGrammarSystem::generate_deployment_script(const std::string& description) { std::ostringstream script; - + script << "#!/bin/bash\n"; script << "# Generated DrawKern deployment script\n\n"; script << "echo \"Deploying DrawKern workbench...\"\n"; script << "./drawkern_server --port 9999 &\n"; script << "sleep 2\n"; script << "./drawkern_client localhost:9999\n"; - + return script.str(); } @@ -748,8 +803,8 @@ std::vector YaccGrammarSystem::get_supported_vm_types() { } std::vector YaccGrammarSystem::get_supported_properties() { - return {"width", "height", "background", "font", "interactive", "ai_enabled", - "model", "tools", "architecture", "capabilities"}; + return {"width", "height", "background", "font", "interactive", + "ai_enabled", "model", "tools", "architecture", "capabilities"}; } std::string YaccGrammarSystem::get_grammar_documentation() { @@ -796,17 +851,17 @@ void YaccGrammarSystem::collect_errors() { auto lexer_errors = lexer_->get_errors(); errors_.insert(errors_.end(), lexer_errors.begin(), lexer_errors.end()); } - + if (parser_ && parser_->has_errors()) { auto parser_errors = parser_->get_errors(); errors_.insert(errors_.end(), parser_errors.begin(), parser_errors.end()); } - + if (generator_ && generator_->has_errors()) { auto generator_errors = generator_->get_errors(); errors_.insert(errors_.end(), generator_errors.begin(), generator_errors.end()); } } -} // namespace drawkern -} // namespace bolt \ No newline at end of file +} // namespace drawkern +} // namespace bolt diff --git a/src/bolt/gui/widget_registration.cpp b/src/bolt/gui/widget_registration.cpp index 6dce31c0..d3e35723 100644 --- a/src/bolt/gui/widget_registration.cpp +++ b/src/bolt/gui/widget_registration.cpp @@ -1,5 +1,7 @@ #include "bolt/gui/widget_registration.hpp" +#include + #ifdef BOLT_HAVE_IMGUI #include #endif @@ -7,32 +9,120 @@ namespace bolt { namespace gui { +#ifdef BOLT_HAVE_IMGUI +namespace { + +// The per-widget colors and metrics in which a built-in theme differs from its base style. +struct BuiltInWidgetStyles { + ImVec4 buttonBackground; + ImVec4 buttonHover; + ImVec4 buttonActive; + float buttonCornerRadius = 0.0f; + ImVec2 buttonPadding; + ImVec4 inputBackground; + ImVec4 inputBorder; + float inputCornerRadius = 0.0f; + ImVec2 inputPadding; + std::optional controlBorderWidth; // Button and text input border; unset keeps the base style's width + ImVec4 panelBackground; + ImVec4 panelBorder; + float panelBorderWidth = 0.0f; + float panelCornerRadius = 0.0f; + ImVec2 panelPadding; + ImVec2 labelPadding; +}; + +// The accent-colored button states, corner radii and paddings that the Dark and Light themes have in common; +// the surface colors are left for the theme to fill in. +BuiltInWidgetStyles createStandardWidgetStyles() { + BuiltInWidgetStyles styles; + styles.buttonHover = ImVec4(0.26f, 0.59f, 0.98f, 1.00f); + styles.buttonActive = ImVec4(0.06f, 0.53f, 0.98f, 1.00f); + styles.buttonCornerRadius = 3.0f; + styles.buttonPadding = ImVec2(8.0f, 4.0f); + styles.inputCornerRadius = 2.0f; + styles.inputPadding = ImVec2(6.0f, 3.0f); + styles.panelBorderWidth = 1.0f; + styles.panelCornerRadius = 4.0f; + styles.panelPadding = ImVec2(10.0f, 10.0f); + styles.labelPadding = ImVec2(2.0f, 2.0f); + return styles; +} + +// Makes baseStyle the default style of a built-in theme, then registers its Button, TextInput/TextArea, Panel and +// Label styles, each derived from baseStyle. +void applyBuiltInThemeStyles(WidgetTheme& theme, const WidgetStyle& baseStyle, const BuiltInWidgetStyles& styles) { + theme.setDefaultStyle(baseStyle); + + // Button specific styling + WidgetStyle buttonStyle = baseStyle; + buttonStyle.backgroundColor = styles.buttonBackground; + buttonStyle.hoverColor = styles.buttonHover; + buttonStyle.activeColor = styles.buttonActive; + buttonStyle.cornerRadius = styles.buttonCornerRadius; + buttonStyle.padding = styles.buttonPadding; + if (styles.controlBorderWidth) { + buttonStyle.borderWidth = styles.controlBorderWidth; + } + theme.setWidgetStyle("Button", buttonStyle); + + // TextInput specific styling + WidgetStyle textInputStyle = baseStyle; + textInputStyle.backgroundColor = styles.inputBackground; + textInputStyle.borderColor = styles.inputBorder; + textInputStyle.cornerRadius = styles.inputCornerRadius; + textInputStyle.padding = styles.inputPadding; + if (styles.controlBorderWidth) { + textInputStyle.borderWidth = styles.controlBorderWidth; + } + theme.setWidgetStyle("TextInput", textInputStyle); + theme.setWidgetStyle("TextArea", textInputStyle); + + // Panel specific styling + WidgetStyle panelStyle = baseStyle; + panelStyle.backgroundColor = styles.panelBackground; + panelStyle.borderColor = styles.panelBorder; + panelStyle.borderWidth = styles.panelBorderWidth; + panelStyle.cornerRadius = styles.panelCornerRadius; + panelStyle.padding = styles.panelPadding; + theme.setWidgetStyle("Panel", panelStyle); + + // Label styling + WidgetStyle labelStyle = baseStyle; + labelStyle.padding = styles.labelPadding; + theme.setWidgetStyle("Label", labelStyle); +} + +} // namespace +#endif + // Static member initialization bool WidgetRegistration::registered_ = false; bool WidgetFrameworkInit::initialized_ = false; // WidgetRegistration implementation void WidgetRegistration::registerAllWidgets() { - if (registered_) return; - + if (registered_) + return; + registerCoreWidgets(); registerInputWidgets(); registerDisplayWidgets(); registerContainerWidgets(); - + registered_ = true; } void WidgetRegistration::registerCoreWidgets() { auto& factory = WidgetFactory::getInstance(); - + factory.registerWidget("Widget"); factory.registerWidget("WidgetContainer"); } void WidgetRegistration::registerInputWidgets() { auto& factory = WidgetFactory::getInstance(); - + factory.registerWidget