diff --git a/add_missing_functions.cpp b/add_missing_functions.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/add_missing_functions_snc.cpp b/add_missing_functions_snc.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/missing_functions.patch b/missing_functions.patch deleted file mode 100644 index e69de29..0000000 diff --git a/script_assistant_fixes.patch b/script_assistant_fixes.patch deleted file mode 100644 index 233d6d4..0000000 --- a/script_assistant_fixes.patch +++ /dev/null @@ -1,157 +0,0 @@ ---- a/source/cpp/ios/ai_features/ScriptAssistant.mm -+++ b/source/cpp/ios/ai_features/ScriptAssistant.mm -@@ -49,7 +49,7 @@ bool ScriptAssistant::Initialize() { - - try { - // Initialize language model -- auto languageModel = new LocalModels::GeneralAssistantModel(); -+ LocalModels::GeneralAssistantModel* languageModel = new LocalModels::GeneralAssistantModel(); - if (!languageModel->Initialize("models/assistant")) { - std::cerr << "Failed to initialize language model" << std::endl; - delete languageModel; -@@ -66,7 +66,7 @@ bool ScriptAssistant::Initialize() { - m_scriptGenerator = scriptGenerator; - - // Load default templates -- LoadDefaultTemplates(); -+ this->LoadDefaultTemplates(); - - return true; - } catch (const std::exception& e) { -@@ -115,7 +115,7 @@ void ScriptAssistant::GenerateScript(const std::string& description) { - std::string errorMsg = "Script generation is not available. Using template instead."; - - // Find closest template -- auto closestTemplate = FindClosestTemplate(description); -+ auto closestTemplate = this->FindClosestTemplate(description); - - if (closestTemplate.m_name.empty()) { - errorMsg += " No suitable template found."; -@@ -142,7 +142,7 @@ void ScriptAssistant::GenerateScript(const std::string& description) { - std::string script = generator->GenerateScript(description); - - if (script.empty()) { -- if (m_responseCallback) { -+ if (this->m_responseCallback) { - m_responseCallback("Failed to generate script for: " + description, false); - } - return; -@@ -151,7 +151,7 @@ void ScriptAssistant::GenerateScript(const std::string& description) { - // Prepare response - std::string response = "Generated script based on your description:\n\n```lua\n" + script + "\n```"; - -- // Call callback -+ // Call callback with the response - if (m_responseCallback) { - m_responseCallback(response, true); - } -@@ -190,10 +190,10 @@ void ScriptAssistant::AnalyzeGame(const GameContext& context) { - - // Analyze key game components - std::set classNames; -- AnalyzeGameObject(context.m_rootObject, classNames); -+ this->AnalyzeGameObject(context.m_rootObject, classNames); - - analysis << "Detected classes:\n"; -- for (const auto& className : classNames) { -+ for (const auto& className : classNames) { - analysis << "- " << className << "\n"; - } - -@@ -208,11 +208,11 @@ void ScriptAssistant::AnalyzeGame(const GameContext& context) { - // Generate recommendations based on analysis - analysis << "\nRecommendations:\n"; - -- if (classNames.find("Player") != classNames.end()) { -+ if (!classNames.empty() && classNames.find("Player") != classNames.end()) { - analysis << "- Player object detected, can use GetService('Players'):GetLocalPlayer()\n"; - } - -- if (classNames.find("Workspace") != classNames.end()) { -+ if (!classNames.empty() && classNames.find("Workspace") != classNames.end()) { - analysis << "- Workspace detected, can access the 3D world\n"; - } - -@@ -238,13 +238,13 @@ void ScriptAssistant::OptimizeScript(const std::string& script) { - std::string optimized = script; - - // Remove unnecessary whitespace -- optimized = RemoveUnnecessaryWhitespace(optimized); -+ optimized = this->RemoveUnnecessaryWhitespace(optimized); - - // Optimize local variable usage -- optimized = OptimizeLocalVariables(optimized); -+ optimized = this->OptimizeLocalVariables(optimized); - - // Optimize loops -- optimized = OptimizeLoops(optimized); -+ optimized = this->OptimizeLoops(optimized); - - // Prepare response - std::stringstream response; -@@ -257,7 +257,7 @@ void ScriptAssistant::OptimizeScript(const std::string& script) { - response << "- Improved loop efficiency\n"; - - // Check for potential performance issues -- std::vector issues = DetectPerformanceIssues(optimized); -+ std::vector issues = this->DetectPerformanceIssues(optimized); - if (!issues.empty()) { - response << "\nPotential performance issues:\n"; - for (const auto& issue : issues) { -@@ -365,7 +365,7 @@ void ScriptAssistant::ClearConversationHistory() { - - // Load templates - void ScriptAssistant::LoadTemplates(const std::string& templatesPath) { -- std::lock_guard lock(m_mutex); -+ std::lock_guard lock(this->m_mutex); - - // In a real implementation, load templates from file - // For this example, just add some default templates -@@ -443,10 +443,10 @@ std::vector ScriptAssistant::GetExampleScriptDescriptions() { - - // Add system message - void ScriptAssistant::AddSystemMessage(const std::string& message) { -- std::lock_guard lock(m_mutex); -+ std::lock_guard lock(this->m_mutex); - - // Add to conversation history -- m_conversationHistory.push_back(Message(MessageType::System, message)); -+ this->m_conversationHistory.push_back(Message(MessageType::System, message)); - - // Trim history if needed - TrimConversationHistory(); -@@ -454,10 +454,10 @@ void ScriptAssistant::AddSystemMessage(const std::string& message) { - - // Add user message - void ScriptAssistant::AddUserMessage(const std::string& message) { -- std::lock_guard lock(m_mutex); -+ std::lock_guard lock(this->m_mutex); - - // Add to conversation history -- m_conversationHistory.push_back(Message(MessageType::User, message)); -+ this->m_conversationHistory.push_back(Message(MessageType::User, message)); - - // Trim history if needed - TrimConversationHistory(); -@@ -569,7 +569,7 @@ std::string ScriptAssistant::GenerateResponse(const std::string& input) { - - // Load default templates - void ScriptAssistant::LoadDefaultTemplates() { -- std::lock_guard lock(m_mutex); -+ std::lock_guard lock(this->m_mutex); - - // Add some default templates - -@@ -1152,10 +1152,10 @@ void ScriptAssistant::LoadDefaultTemplates() { - - // Find closest template - ScriptAssistant::ScriptTemplate ScriptAssistant::FindClosestTemplate(const std::string& description) { -- if (m_scriptTemplates.empty()) { -+ if (this->m_scriptTemplates.empty()) { - return ScriptTemplate(); - } -- -+ - // Find template with most matching keywords - std::vector keywords = ExtractKeywords(description); - diff --git a/script_assistant_missing_functions.patch b/script_assistant_missing_functions.patch deleted file mode 100644 index 0d0e9e3..0000000 --- a/script_assistant_missing_functions.patch +++ /dev/null @@ -1,229 +0,0 @@ ---- a/source/cpp/ios/ai_features/ScriptAssistant.mm -+++ b/source/cpp/ios/ai_features/ScriptAssistant.mm -@@ -1158,7 +1158,7 @@ ScriptAssistant::ScriptTemplate ScriptAssistant::FindClosestTemplate(const std:: - } - - // Find template with most matching keywords -- std::vector keywords = ExtractKeywords(description); -+ std::vector keywords = this->ExtractKeywords(description); - - int highestScore = 0; - ScriptTemplate bestMatch; -@@ -1183,6 +1183,42 @@ ScriptAssistant::ScriptTemplate ScriptAssistant::FindClosestTemplate(const std:: - return bestMatch; - } - -+// Analyze game object recursively -+void ScriptAssistant::AnalyzeGameObject(std::shared_ptr obj, std::set& classNames) { -+ if (!obj) return; -+ -+ // Add class name -+ classNames.insert(obj->m_className); -+ -+ // Recursively analyze children -+ for (const auto& child : obj->m_children) { -+ this->AnalyzeGameObject(child, classNames); -+ } -+} -+ -+// Remove unnecessary whitespace -+std::string ScriptAssistant::RemoveUnnecessaryWhitespace(const std::string& script) { -+ std::string optimized = script; -+ -+ // Replace multiple spaces with single space -+ size_t pos = optimized.find(" "); -+ while (pos != std::string::npos) { -+ optimized.replace(pos, 2, " "); -+ pos = optimized.find(" ", pos); -+ } -+ -+ // Replace multiple empty lines with a single empty line -+ pos = optimized.find("\n\n\n"); -+ while (pos != std::string::npos) { -+ optimized.replace(pos, 3, "\n\n"); -+ pos = optimized.find("\n\n\n", pos); -+ } -+ -+ return optimized; -+} -+ -+// Extract keywords from text -+std::vector ScriptAssistant::ExtractKeywords(const std::string& text) { - std::vector keywords; - std::string lowercaseText = text; - -@@ -1208,38 +1244,6 @@ std::vector ScriptAssistant::ExtractKeywords(const std::string& tex - return keywords; - } - --// Analyze game object recursively --void ScriptAssistant::AnalyzeGameObject(std::shared_ptr obj, std::set& classNames) { -- if (!obj) return; -- -- // Add class name -- classNames.insert(obj.m_className); -- -- // Recursively analyze children -- for (const auto& child : obj.m_children) { -- AnalyzeGameObject(child, classNames); -- } --} -- --// Optimize local variables --std::string ScriptAssistant::OptimizeLocalVariables(const std::string& script) { -- // Basic implementation - in a real system, this would be more sophisticated -- -- // Replace redundant local declarations -- std::string optimized = script; -- -- // Find common patterns -- size_t pos = optimized.find("local function"); -- while (pos != std::string::npos) { -- // Keep local functions as they are -- pos = optimized.find("local function", pos + 14); -- } -- -- // Look for multiple consecutive local declarations that could be combined -- pos = optimized.find("local "); -- while (pos != std::string::npos) { -- size_t nextLocal = optimized.find("local ", pos + 6); -- if (nextLocal != std::string::npos && nextLocal - pos < 50) { -- // Check if these could be combined (simple heuristic) -- size_t lineEnd = optimized.find("\n", pos); -- if (lineEnd != std::string::npos && lineEnd < nextLocal) { -- // These are on different lines, could potentially combine -- // In a real implementation, would need to analyze variable usage -- } -- } -- -- pos = optimized.find("local ", pos + 6); -- } -- -- return optimized; --} -- --// Optimize loops --std::string ScriptAssistant::OptimizeLoops(const std::string& script) { -- // Basic implementation - in a real system, this would use more advanced analysis -- -- // Replace inefficient loop patterns -- std::string optimized = script; -- -- // Replace pairs() with ipairs() for array-like tables -- size_t pos = optimized.find("for k, v in pairs("); -- while (pos != std::string::npos) { -- // Check if this could use ipairs instead (simple heuristic) -- size_t closingParen = optimized.find(")", pos); -- if (closingParen != std::string::npos) { -- std::string tableName = optimized.substr(pos + 16, closingParen - (pos + 16)); -- -- // Check if tableName ends with common array identifiers -- if (tableName.find("List") != std::string::npos || -- tableName.find("Array") != std::string::npos || -- tableName.find("s") == tableName.length() - 1) { // Plural name -- -- // Replace with ipairs for array-like tables -- optimized.replace(pos, 16, "for k, v in ipairs("); -- } -- } -- -- pos = optimized.find("for k, v in pairs(", pos + 10); -- } -- -- return optimized; --} -- --// Remove unnecessary whitespace --std::string ScriptAssistant::RemoveUnnecessaryWhitespace(const std::string& script) { -- std::string optimized = script; -- -- // Replace multiple spaces with single space -- size_t pos = optimized.find(" "); -- while (pos != std::string::npos) { -- optimized.replace(pos, 2, " "); -- pos = optimized.find(" ", pos); -- } -- -- // Replace multiple empty lines with a single empty line -- pos = optimized.find("\n\n\n"); -- while (pos != std::string::npos) { -- optimized.replace(pos, 3, "\n\n"); -- pos = optimized.find("\n\n\n", pos); -- } -- -- return optimized; --} -- - // Detect performance issues - std::vector ScriptAssistant::DetectPerformanceIssues(const std::string& script) { - std::vector issues; -@@ -1272,5 +1276,69 @@ std::vector ScriptAssistant::DetectPerformanceIssues(const std::str - return issues; - } - -+// Optimize local variables -+std::string ScriptAssistant::OptimizeLocalVariables(const std::string& script) { -+ // Basic implementation - in a real system, this would be more sophisticated -+ -+ // Replace redundant local declarations -+ std::string optimized = script; -+ -+ // Find common patterns -+ size_t pos = optimized.find("local function"); -+ while (pos != std::string::npos) { -+ // Keep local functions as they are -+ pos = optimized.find("local function", pos + 14); -+ } -+ -+ // Look for multiple consecutive local declarations that could be combined -+ pos = optimized.find("local "); -+ while (pos != std::string::npos) { -+ size_t nextLocal = optimized.find("local ", pos + 6); -+ if (nextLocal != std::string::npos && nextLocal - pos < 50) { -+ // Check if these could be combined (simple heuristic) -+ size_t lineEnd = optimized.find("\n", pos); -+ if (lineEnd != std::string::npos && lineEnd < nextLocal) { -+ // These are on different lines, could potentially combine -+ // In a real implementation, would need to analyze variable usage -+ } -+ } -+ -+ pos = optimized.find("local ", pos + 6); -+ } -+ -+ return optimized; -+} -+ -+// Optimize loops -+std::string ScriptAssistant::OptimizeLoops(const std::string& script) { -+ // Basic implementation - in a real system, this would use more advanced analysis -+ -+ // Replace inefficient loop patterns -+ std::string optimized = script; -+ -+ // Replace pairs() with ipairs() for array-like tables -+ size_t pos = optimized.find("for k, v in pairs("); -+ while (pos != std::string::npos) { -+ // Check if this could use ipairs instead (simple heuristic) -+ size_t closingParen = optimized.find(")", pos); -+ if (closingParen != std::string::npos) { -+ std::string tableName = optimized.substr(pos + 16, closingParen - (pos + 16)); -+ -+ // Check if tableName ends with common array identifiers -+ if (tableName.find("List") != std::string::npos || -+ tableName.find("Array") != std::string::npos || -+ tableName.find("s") == tableName.length() - 1) { // Plural name -+ -+ // Replace with ipairs for array-like tables -+ optimized.replace(pos, 16, "for k, v in ipairs("); -+ } -+ } -+ -+ pos = optimized.find("for k, v in pairs(", pos + 10); -+ } -+ -+ return optimized; -+} -+ - } // namespace AIFeatures - } // namespace iOS diff --git a/source/cpp/ios/ai_features/ScriptAssistant.mm.orig b/source/cpp/ios/ai_features/ScriptAssistant.mm.orig deleted file mode 100644 index cbd072c..0000000 --- a/source/cpp/ios/ai_features/ScriptAssistant.mm.orig +++ /dev/null @@ -1,1351 +0,0 @@ -#include "ScriptAssistant.h" -#include "AIConfig.h" -#include "local_models/GeneralAssistantModel.h" -#include "local_models/ScriptGenerationModel.h" -#include -#include -#include -#include -#include -#include - -namespace iOS { -namespace AIFeatures { - -// Constructor -ScriptAssistant::ScriptAssistant() - : m_maxHistorySize(100), - m_languageModel(nullptr), - m_gameAnalyzer(nullptr), - m_scriptGenerator(nullptr), - m_executionInterface(nullptr), - m_responseCallback(nullptr), - m_executionCallback(nullptr) { - // Add system welcome message - AddSystemMessage("ScriptAssistant initialized. Ready to help with Lua scripting and game analysis."); -} - -// Destructor -ScriptAssistant::~ScriptAssistant() { - // Clean up resources - if (m_languageModel) { - delete static_cast(m_languageModel); - m_languageModel = nullptr; - } - - if (m_scriptGenerator) { - delete static_cast(m_scriptGenerator); - m_scriptGenerator = nullptr; - } - - // Clear other resources - m_conversationHistory.clear(); - m_scriptTemplates.clear(); -} - -// Initialize -bool ScriptAssistant::Initialize() { - std::lock_guard lock(m_mutex); - - try { - // Initialize language model - auto languageModel = new LocalModels::GeneralAssistantModel(); - if (!languageModel->Initialize("models/assistant")) { - std::cerr << "Failed to initialize language model" << std::endl; - delete languageModel; - return false; - } - m_languageModel = languageModel; - - // Initialize script generator - auto scriptGenerator = new LocalModels::ScriptGenerationModel(); - if (!scriptGenerator->Initialize("models/generator")) { - std::cerr << "Failed to initialize script generator" << std::endl; - // Continue anyway, just without script generation capability - } - m_scriptGenerator = scriptGenerator; - - // Load default templates - LoadDefaultTemplates(); - - return true; - } catch (const std::exception& e) { - std::cerr << "Exception during ScriptAssistant initialization: " << e.what() << std::endl; - return false; - } -} - -// Set response callback -void ScriptAssistant::SetResponseCallback(ResponseCallback callback) { - std::lock_guard lock(m_mutex); - m_responseCallback = callback; -} - -// Set execution callback -void ScriptAssistant::SetExecutionCallback(ScriptExecutionCallback callback) { - std::lock_guard lock(m_mutex); - m_executionCallback = callback; -} - -// Process user input -void ScriptAssistant::ProcessUserInput(const std::string& input) { - if (input.empty()) return; - - // Add to conversation history - AddUserMessage(input); - - // Generate response - std::string response = GenerateResponse(input); - - // Add to conversation history - AddAssistantMessage(response); - - // Call callback if set - if (m_responseCallback) { - m_responseCallback(response, true); - } -} - -// Generate a script based on description -void ScriptAssistant::GenerateScript(const std::string& description) { - if (description.empty()) return; - - // Check if script generator is initialized - if (!m_scriptGenerator) { - std::string errorMsg = "Script generation is not available. Using template instead."; - - // Find closest template - auto closestTemplate = FindClosestTemplate(description); - - if (closestTemplate.m_name.empty()) { - errorMsg += " No suitable template found."; - if (m_responseCallback) { - m_responseCallback(errorMsg, false); - } - return; - } - - // Use template - std::string response = "Using template '" + closestTemplate.m_name + "' as a starting point:\n\n```lua\n" + - closestTemplate.m_code + "\n```\n\nYou can modify this to fit your needs."; - - if (m_responseCallback) { - m_responseCallback(response, true); - } - return; - } - - // Use a separate thread for generation to avoid blocking - std::thread([this, description]() { - try { - // Get script generator - auto generator = static_cast(m_scriptGenerator); - - // Generate script - std::string script = generator->GenerateScript(description); - - if (script.empty()) { - if (m_responseCallback) { - m_responseCallback("Failed to generate script for: " + description, false); - } - return; - } - - // Prepare response - std::string response = "Generated script based on your description:\n\n```lua\n" + script + "\n```"; - - // Call callback - if (m_responseCallback) { - m_responseCallback(response, true); - } - - // Add to templates - ScriptTemplate newTemplate; - newTemplate.m_name = "Generated: " + description.substr(0, 30) + (description.length() > 30 ? "..." : ""); - newTemplate.m_description = description; - newTemplate.m_code = script; - AddTemplate(newTemplate); - - } catch (const std::exception& e) { - std::cerr << "Exception during script generation: " << e.what() << std::endl; - if (m_responseCallback) { - m_responseCallback("Error generating script: " + std::string(e.what()), false); - } - } - }).detach(); -} - -// Analyze game -void ScriptAssistant::AnalyzeGame(const GameContext& context) { - // This is a more complex operation - add to conversation history - AddSystemMessage("Game analysis requested"); - - std::stringstream analysis; - analysis << "Game Analysis:\n\n"; - - // Basic analysis of game structure - if (context.m_rootObject) { - analysis << "Game: " << context.m_rootObject->m_name << " (" << context.m_rootObject->m_className << ")\n"; - analysis << "Children: " << context.m_rootObject->m_children.size() << "\n\n"; - - // Analyze key game components - std::set classNames; - AnalyzeGameObject(context.m_rootObject, classNames); - - analysis << "Detected classes:\n"; - for (const auto& className : classNames) { - analysis << "- " << className << "\n"; - } - - analysis << "\nAvailable APIs: " << context.m_availableAPIs.size() << "\n"; - for (const auto& api : context.m_availableAPIs) { - analysis << "- " << api << "\n"; - } - } else { - analysis << "No game data available for analysis.\n"; - } - - // Generate recommendations based on analysis - analysis << "\nRecommendations:\n"; - - if (classNames.find("Player") != classNames.end()) { - analysis << "- Player object detected, can use GetService('Players'):GetLocalPlayer()\n"; - } - - if (classNames.find("Workspace") != classNames.end()) { - analysis << "- Workspace detected, can access the 3D world\n"; - } - - // Add the analysis as an assistant message - std::string analysisStr = analysis.str(); - AddAssistantMessage(analysisStr); - - // Send to callback if available - if (m_responseCallback) { - m_responseCallback(analysisStr, true); - } -} - -// Optimize script -void ScriptAssistant::OptimizeScript(const std::string& script) { - if (script.empty()) return; - - // Add to conversation - AddSystemMessage("Script optimization requested"); - - try { - // Basic optimization rules - std::string optimized = script; - - // Remove unnecessary whitespace - optimized = RemoveUnnecessaryWhitespace(optimized); - - // Optimize local variable usage - optimized = OptimizeLocalVariables(optimized); - - // Optimize loops - optimized = OptimizeLoops(optimized); - - // Prepare response - std::stringstream response; - response << "Optimized script:\n\n```lua\n" << optimized << "\n```\n\n"; - - // Add optimization notes - response << "Optimization notes:\n"; - response << "- Removed unnecessary whitespace\n"; - response << "- Optimized local variable declarations\n"; - response << "- Improved loop efficiency\n"; - - // Check for potential performance issues - std::vector issues = DetectPerformanceIssues(optimized); - if (!issues.empty()) { - response << "\nPotential performance issues:\n"; - for (const auto& issue : issues) { - response << "- " << issue << "\n"; - } - } - - std::string responseStr = response.str(); - - // Add to conversation - AddAssistantMessage(responseStr); - - // Send to callback - if (m_responseCallback) { - m_responseCallback(responseStr, true); - } - } catch (const std::exception& e) { - std::cerr << "Exception during script optimization: " << e.what() << std::endl; - if (m_responseCallback) { - m_responseCallback("Error optimizing script: " + std::string(e.what()), false); - } - } -} - -// Execute script -void ScriptAssistant::ExecuteScript(const std::string& script) { - if (script.empty()) return; - - // Add to system context - AddSystemMessage("Script execution requested"); - - // Since we don't have direct execution capability, forward this to callback - if (m_executionCallback) { - m_executionCallback(true, script); - } else { - // No callback, notify user - std::string response = "Cannot execute script: execution interface not available"; - if (m_responseCallback) { - m_responseCallback(response, false); - } - } -} - -// Implementation of ReleaseUnusedResources -void ScriptAssistant::ReleaseUnusedResources() { - std::lock_guard lock(m_mutex); - std::cout << "ScriptAssistant: Releasing unused resources" << std::endl; - - // Clear conversation history beyond a certain limit - TrimConversationHistory(); - - // Release templates that haven't been used recently - if (m_scriptTemplates.size() > 20) { - m_scriptTemplates.resize(20); - } - - // Release script generator if we're in low memory mode - // Keep language model since it's core functionality - bool isLowMemory = false; // TODO: Check system memory pressure - - if (isLowMemory && m_scriptGenerator) { - delete static_cast(m_scriptGenerator); - m_scriptGenerator = nullptr; - std::cout << "ScriptAssistant: Released script generator due to low memory" << std::endl; - } -} - -// Implementation of GetMemoryUsage -uint64_t ScriptAssistant::GetMemoryUsage() const { - // Estimate memory usage based on stored data - uint64_t memoryUsage = 0; - - // Conversation history - for (const auto& message : m_conversationHistory) { - memoryUsage += message.m_content.size(); - } - - // Script templates - for (const auto& tmpl : m_scriptTemplates) { - memoryUsage += tmpl.m_name.size() + tmpl.m_description.size() + tmpl.m_code.size(); - } - - // Language model memory usage - if (m_languageModel) { - auto model = static_cast(m_languageModel); - memoryUsage += model->GetMemoryUsage(); - } - - // Script generator memory usage - if (m_scriptGenerator) { - auto generator = static_cast(m_scriptGenerator); - memoryUsage += generator->GetMemoryUsage(); - } - - // Add base memory usage - memoryUsage += 1024 * 1024; // 1MB base usage - - return memoryUsage; -} - -// Load templates -void ScriptAssistant::LoadTemplates(const std::string& templatesPath) { - // TODO: Implement loading from file - // For now, just load default templates - LoadDefaultTemplates(); -} - -// Save templates -void ScriptAssistant::SaveTemplates(const std::string& templatesPath) { - // TODO: Implement saving to file -} - -// Add template -void ScriptAssistant::AddTemplate(const ScriptTemplate& tmpl) { - std::lock_guard lock(m_mutex); - - // Check if template with this name already exists - for (auto& existing : m_scriptTemplates) { - if (existing.m_name == tmpl.m_name) { - // Update existing template - existing.m_description = tmpl.m_description; - existing.m_code = tmpl.m_code; - return; - } - } - - // Add new template - m_scriptTemplates.push_back(tmpl); -} - -// Remove template -void ScriptAssistant::RemoveTemplate(const std::string& templateName) { - std::lock_guard lock(m_mutex); - - auto it = std::remove_if(m_scriptTemplates.begin(), m_scriptTemplates.end(), - [&templateName](const ScriptTemplate& tmpl) { - return tmpl.m_name == templateName; - }); - - if (it != m_scriptTemplates.end()) { - m_scriptTemplates.erase(it, m_scriptTemplates.end()); - } -} - -// Get suggestions -std::vector ScriptAssistant::GetSuggestions(const std::string& partialInput) { - std::vector suggestions; - - // Check for common command patterns - if (partialInput.empty()) { - // Default suggestions - suggestions.push_back("help"); - suggestions.push_back("generate script for"); - suggestions.push_back("optimize"); - suggestions.push_back("analyze game"); - suggestions.push_back("show templates"); - } else if (partialInput.find("gen") == 0) { - // Generate commands - suggestions.push_back("generate script for player movement"); - suggestions.push_back("generate script for ESP"); - suggestions.push_back("generate script for aimbot"); - } else if (partialInput.find("opt") == 0) { - // Optimize commands - suggestions.push_back("optimize my script"); - suggestions.push_back("optimize for performance"); - suggestions.push_back("optimize and minify"); - } else if (partialInput.find("ana") == 0) { - // Analyze commands - suggestions.push_back("analyze game"); - suggestions.push_back("analyze this script"); - } - - // Return up to 5 suggestions - if (suggestions.size() > 5) { - suggestions.resize(5); - } - - return suggestions; -} - -// Get templates -std::vector ScriptAssistant::GetTemplates() const { - std::lock_guard lock(m_mutex); - return m_scriptTemplates; -} - -// Get current context -ScriptAssistant::GameContext ScriptAssistant::GetCurrentContext() const { - std::lock_guard lock(m_mutex); - return m_currentContext; -} - -// Clear conversation history -void ScriptAssistant::ClearConversationHistory() { - std::lock_guard lock(m_mutex); - - // Keep only system messages - auto it = std::remove_if(m_conversationHistory.begin(), m_conversationHistory.end(), - [](const Message& msg) { - return msg.m_type != MessageType::System; - }); - - m_conversationHistory.erase(it, m_conversationHistory.end()); -} - -// Trim conversation history -void ScriptAssistant::TrimConversationHistory() { - std::lock_guard lock(m_mutex); - - if (m_conversationHistory.size() > m_maxHistorySize) { - // Keep system messages and the most recent messages - std::vector systemMessages; - std::vector recentMessages; - - // Extract system messages - for (const auto& msg : m_conversationHistory) { - if (msg.m_type == MessageType::System) { - systemMessages.push_back(msg); - } - } - - // Keep most recent messages - size_t recentCount = m_maxHistorySize - systemMessages.size(); - if (recentCount > 0 && recentCount < m_conversationHistory.size()) { - auto start = m_conversationHistory.end() - recentCount; - recentMessages.insert(recentMessages.end(), start, m_conversationHistory.end()); - } - - // Combine system messages and recent messages - m_conversationHistory.clear(); - m_conversationHistory.insert(m_conversationHistory.end(), systemMessages.begin(), systemMessages.end()); - m_conversationHistory.insert(m_conversationHistory.end(), recentMessages.begin(), recentMessages.end()); - } -} - -// Get example queries -std::vector ScriptAssistant::GetExampleQueries() { - return { - "How do I find all players in the game?", - "Generate a script for wall hacking", - "What's the best way to bypass anti-cheat?", - "Help me optimize this script", - "Explain how the game detection system works", - "How do I use the ExecutionEngine?", - "What does this Lua code do?", - "How do I change character properties?" - }; -} - -// Get example script descriptions -std::vector ScriptAssistant::GetExampleScriptDescriptions() { - return { - "ESP hack that shows player names through walls", - "Aimbot that locks onto nearest player", - "Speed hack that makes my character move faster", - "Auto-farm script for resource collection", - "UI interface for controlling hacks", - "Anti-kick script to prevent being disconnected", - "Script to teleport to any player" - }; -} - -// Private helper methods - -// Add system message -void ScriptAssistant::AddSystemMessage(const std::string& message) { - std::lock_guard lock(m_mutex); - m_conversationHistory.push_back(Message(MessageType::System, message)); -} - -// Add user message -void ScriptAssistant::AddUserMessage(const std::string& message) { - std::lock_guard lock(m_mutex); - m_conversationHistory.push_back(Message(MessageType::User, message)); -} - -// Add assistant message -void ScriptAssistant::AddAssistantMessage(const std::string& message) { - std::lock_guard lock(m_mutex); - m_conversationHistory.push_back(Message(MessageType::Assistant, message)); -} - -// Generate response -std::string ScriptAssistant::GenerateResponse(const std::string& input) { - // Check if language model is available - if (m_languageModel) { - auto model = static_cast(m_languageModel); - return model->ProcessInput(input); - } - - // Fallback: simple rule-based responses - if (input.find("help") != std::string::npos) { - return "I can help you with scripting, game analysis, and script optimization. " - "Try asking me to generate a script, optimize your code, or analyze a game."; - } else if (input.find("generate") != std::string::npos || input.find("create") != std::string::npos) { - return "To generate a script, please provide a description of what you want the script to do. " - "For example: 'Generate a script for ESP that shows player names'."; - } else if (input.find("optimize") != std::string::npos) { - return "To optimize a script, please share the code you want to optimize."; - } else if (input.find("analyze") != std::string::npos) { - return "I can analyze games or scripts. Please specify what you'd like me to analyze."; - } - - // Generic response - return "I'm here to help with your scripting needs. Can you please provide more details about what you're looking for?"; -} - -// Load default templates -void ScriptAssistant::LoadDefaultTemplates() { - std::lock_guard lock(m_mutex); - - // Clear existing templates - m_scriptTemplates.clear(); - - // Add some default templates - ScriptTemplate espTemplate; - espTemplate.m_name = "Basic ESP"; - espTemplate.m_description = "Shows player names through walls"; - espTemplate.m_code = R"( --- Basic ESP Script -local Players = game:GetService("Players") -local RunService = game:GetService("RunService") -local LocalPlayer = Players.LocalPlayer -local Camera = workspace.CurrentCamera - --- ESP Configuration -local ESP = { - Enabled = true, - ShowName = true, - ShowDistance = true, - ShowHealth = true, - TextSize = 14, - TextColor = Color3.fromRGB(255, 255, 255), - TextOutline = true, - MaxDistance = 1000, -} - --- Function to create ESP elements -local function CreateESP(player) - local esp = Drawing.new("Text") - esp.Visible = false - esp.Center = true - esp.Outline = ESP.TextOutline - esp.Size = ESP.TextSize - esp.Color = ESP.TextColor - esp.OutlineColor = Color3.fromRGB(0, 0, 0) - - -- Update ESP in render loop - RunService:BindToRenderStep("ESP_" .. player.Name, 1, function() - if not ESP.Enabled then - esp.Visible = false - return - end - - -- Check if player exists and has a character - if not player or not player.Character or not player.Character:FindFirstChild("HumanoidRootPart") then - esp.Visible = false - return - end - - -- Don't show ESP for local player - if player == LocalPlayer then - esp.Visible = false - return - end - - local humanoidRootPart = player.Character:FindFirstChild("HumanoidRootPart") - local humanoid = player.Character:FindFirstChild("Humanoid") - local position = humanoidRootPart.Position - - -- Calculate if player is visible on screen - local screenPosition, onScreen = Camera:WorldToViewportPoint(position) - - -- Calculate distance - local distance = (Camera.CFrame.Position - position).Magnitude - - -- Only show if on screen and within max distance - if onScreen and distance <= ESP.MaxDistance then - esp.Position = Vector2.new(screenPosition.X, screenPosition.Y) - - -- Build ESP text - local text = player.Name - - if ESP.ShowDistance then - text = text .. " [" .. math.floor(distance) .. "m]" - end - - if ESP.ShowHealth and humanoid then - text = text .. " [" .. math.floor(humanoid.Health) .. "/" .. math.floor(humanoid.MaxHealth) .. " HP]" - end - - esp.Text = text - esp.Visible = true - else - esp.Visible = false - end - end) - - -- Clean up when player leaves - player.AncestryChanged:Connect(function(_, parent) - if parent == nil then - RunService:UnbindFromRenderStep("ESP_" .. player.Name) - esp:Remove() - end - end) - - return esp -end - --- Initialize ESP for all players -local espObjects = {} - --- Set up ESP for existing players -for _, player in ipairs(Players:GetPlayers()) do - if player ~= LocalPlayer then - espObjects[player] = CreateESP(player) - end -end - --- Set up ESP for new players -Players.PlayerAdded:Connect(function(player) - espObjects[player] = CreateESP(player) -end) - --- Clean up ESP when players leave -Players.PlayerRemoving:Connect(function(player) - if espObjects[player] then - espObjects[player]:Remove() - espObjects[player] = nil - end -end) - --- Toggle function for UI -local function ToggleESP() - ESP.Enabled = not ESP.Enabled - print("ESP " .. (ESP.Enabled and "Enabled" or "Disabled")) -end - --- Return the ESP configuration for external control -return ESP -)"; - m_scriptTemplates.push_back(espTemplate); - - // Add more templates - ScriptTemplate aimbotTemplate; - aimbotTemplate.m_name = "Basic Aimbot"; - aimbotTemplate.m_description = "Simple aimbot that locks onto nearest player"; - aimbotTemplate.m_code = R"( --- Basic Aimbot Script -local Players = game:GetService("Players") -local RunService = game:GetService("RunService") -local UserInputService = game:GetService("UserInputService") -local LocalPlayer = Players.LocalPlayer -local Camera = workspace.CurrentCamera - --- Aimbot Configuration -local Aimbot = { - Enabled = false, - TargetPart = "Head", -- Options: "Head", "Torso", "HumanoidRootPart" - TeamCheck = true, -- Only target enemies - VisibilityCheck = true, -- Only target visible players - MaxDistance = 1000, -- Maximum targeting distance - Sensitivity = 0.5, -- Lower = smoother, Higher = snappier - AimKey = Enum.UserInputType.MouseButton2, -- Right mouse button - FOV = 250, -- Field of View for targeting (0-800) - ShowFOV = true, -- Show FOV circle - FOVColor = Color3.fromRGB(255, 255, 255), -} - --- Create FOV circle -local fovCircle = Drawing.new("Circle") -fovCircle.Visible = Aimbot.ShowFOV -fovCircle.Radius = Aimbot.FOV -fovCircle.Color = Aimbot.FOVColor -fovCircle.Thickness = 1 -fovCircle.Filled = false -fovCircle.Transparency = 1 - --- Update FOV circle position -RunService.RenderStepped:Connect(function() - fovCircle.Position = Vector2.new(Camera.ViewportSize.X / 2, Camera.ViewportSize.Y / 2) - fovCircle.Radius = Aimbot.FOV - fovCircle.Visible = Aimbot.ShowFOV and Aimbot.Enabled -end) - --- Function to check if a player is on your team -local function IsOnSameTeam(player) - if not Aimbot.TeamCheck then return false end - return player.Team == LocalPlayer.Team -end - --- Function to check if a player is visible -local function IsVisible(targetPart) - if not Aimbot.VisibilityCheck then return true end - - local ray = Ray.new(Camera.CFrame.Position, targetPart.Position - Camera.CFrame.Position) - local hit, _ = workspace:FindPartOnRayWithIgnoreList(ray, {LocalPlayer.Character, targetPart.Parent}) - return hit == nil -end - --- Function to get the nearest player -local function GetNearestPlayer() - local nearestPlayer = nil - local nearestDistance = math.huge - local nearestScreenDistance = math.huge - local screenCenter = Vector2.new(Camera.ViewportSize.X / 2, Camera.ViewportSize.Y / 2) - - for _, player in ipairs(Players:GetPlayers()) do - if player ~= LocalPlayer and player.Character and not IsOnSameTeam(player) then - local character = player.Character - local humanoid = character:FindFirstChild("Humanoid") - local targetPart = character:FindFirstChild(Aimbot.TargetPart) - - if humanoid and humanoid.Health > 0 and targetPart then - local targetPosition = targetPart.Position - local distance = (Camera.CFrame.Position - targetPosition).Magnitude - - if distance <= Aimbot.MaxDistance then - local screenPosition, onScreen = Camera:WorldToViewportPoint(targetPosition) - - if onScreen then - local screenDistance = (Vector2.new(screenPosition.X, screenPosition.Y) - screenCenter).Magnitude - - if screenDistance <= Aimbot.FOV and screenDistance < nearestScreenDistance and IsVisible(targetPart) then - nearestPlayer = player - nearestDistance = distance - nearestScreenDistance = screenDistance - end - end - end - end - end - end - - return nearestPlayer, nearestDistance -end - --- Aim at target function -local function AimAt(targetPosition) - local aimDirection = (targetPosition - Camera.CFrame.Position).Unit - local targetCFrame = CFrame.new(Camera.CFrame.Position, Camera.CFrame.Position + aimDirection) - Camera.CFrame = Camera.CFrame:Lerp(targetCFrame, Aimbot.Sensitivity) -end - --- Main aimbot loop -RunService.RenderStepped:Connect(function() - if Aimbot.Enabled and UserInputService:IsMouseButtonPressed(Aimbot.AimKey) then - local target, _ = GetNearestPlayer() - - if target and target.Character then - local targetPart = target.Character:FindFirstChild(Aimbot.TargetPart) - if targetPart then - AimAt(targetPart.Position) - end - end - end -end) - --- Toggle function -local function ToggleAimbot() - Aimbot.Enabled = not Aimbot.Enabled - print("Aimbot " .. (Aimbot.Enabled and "Enabled" or "Disabled")) -end - --- Hotkey to toggle aimbot -UserInputService.InputBegan:Connect(function(input, gameProcessed) - if not gameProcessed and input.KeyCode == Enum.KeyCode.X then - ToggleAimbot() - end -end) - --- Return the aimbot configuration for external control -return Aimbot -)"; - m_scriptTemplates.push_back(aimbotTemplate); - - // Additional template for UI - ScriptTemplate uiTemplate; - uiTemplate.m_name = "Simple UI Framework"; - uiTemplate.m_description = "Framework for creating a simple UI for scripts"; - uiTemplate.m_code = R"( --- Simple UI Framework -local UserInputService = game:GetService("UserInputService") -local TweenService = game:GetService("TweenService") -local Players = game:GetService("Players") -local LocalPlayer = Players.LocalPlayer -local Mouse = LocalPlayer:GetMouse() - --- UI Configuration -local UI = { - Title = "Script Hub", - Width = 300, - Height = 350, - Color = { - Background = Color3.fromRGB(30, 30, 30), - TopBar = Color3.fromRGB(40, 40, 40), - Button = Color3.fromRGB(50, 50, 50), - ButtonHover = Color3.fromRGB(60, 60, 60), - Text = Color3.fromRGB(255, 255, 255), - Accent = Color3.fromRGB(0, 120, 215) - }, - Elements = {}, -- Store UI elements - Visible = true, - Draggable = true -} - --- Create ScreenGui -local ScreenGui = Instance.new("ScreenGui") -ScreenGui.Name = "ScriptHub" -ScreenGui.ResetOnSpawn = false -ScreenGui.ZIndexBehavior = Enum.ZIndexBehavior.Sibling - --- If synapse or other exploit has a protection method, use it -if syn and syn.protect_gui then - syn.protect_gui(ScreenGui) - ScreenGui.Parent = game.CoreGui -elseif gethui then - ScreenGui.Parent = gethui() -else - ScreenGui.Parent = game.CoreGui -end - --- Create main frame -local MainFrame = Instance.new("Frame") -MainFrame.Name = "MainFrame" -MainFrame.Size = UDim2.new(0, UI.Width, 0, UI.Height) -MainFrame.Position = UDim2.new(0.5, -UI.Width/2, 0.5, -UI.Height/2) -MainFrame.BackgroundColor3 = UI.Color.Background -MainFrame.BorderSizePixel = 0 -MainFrame.Active = true -MainFrame.Parent = ScreenGui - --- Add corner radius -local Corner = Instance.new("UICorner") -Corner.CornerRadius = UDim.new(0, 6) -Corner.Parent = MainFrame - --- Add shadow -local Shadow = Instance.new("ImageLabel") -Shadow.Name = "Shadow" -Shadow.AnchorPoint = Vector2.new(0.5, 0.5) -Shadow.BackgroundTransparency = 1 -Shadow.Position = UDim2.new(0.5, 0, 0.5, 0) -Shadow.Size = UDim2.new(1, 12, 1, 12) -Shadow.ZIndex = -1 -Shadow.Image = "rbxassetid://5554236805" -Shadow.ImageColor3 = Color3.fromRGB(0, 0, 0) -Shadow.ImageTransparency = 0.5 -Shadow.ScaleType = Enum.ScaleType.Slice -Shadow.SliceCenter = Rect.new(23, 23, 277, 277) -Shadow.Parent = MainFrame - --- Create top bar -local TopBar = Instance.new("Frame") -TopBar.Name = "TopBar" -TopBar.Size = UDim2.new(1, 0, 0, 30) -TopBar.BackgroundColor3 = UI.Color.TopBar -TopBar.BorderSizePixel = 0 -TopBar.Parent = MainFrame - --- Add corner radius to top bar -local TopBarCorner = Instance.new("UICorner") -TopBarCorner.CornerRadius = UDim.new(0, 6) -TopBarCorner.Parent = TopBar - --- Create title -local Title = Instance.new("TextLabel") -Title.Name = "Title" -Title.Size = UDim2.new(1, -30, 1, 0) -Title.Position = UDim2.new(0, 10, 0, 0) -Title.BackgroundTransparency = 1 -Title.Text = UI.Title -Title.TextColor3 = UI.Color.Text -Title.TextSize = 18 -Title.Font = Enum.Font.SourceSansBold -Title.TextXAlignment = Enum.TextXAlignment.Left -Title.Parent = TopBar - --- Create close button -local CloseButton = Instance.new("TextButton") -CloseButton.Name = "CloseButton" -CloseButton.Size = UDim2.new(0, 20, 0, 20) -CloseButton.Position = UDim2.new(1, -25, 0, 5) -CloseButton.BackgroundColor3 = Color3.fromRGB(255, 0, 0) -CloseButton.Text = "X" -CloseButton.TextColor3 = UI.Color.Text -CloseButton.TextSize = 14 -CloseButton.Font = Enum.Font.SourceSansBold -CloseButton.Parent = TopBar - --- Add corner radius to close button -local CloseButtonCorner = Instance.new("UICorner") -CloseButtonCorner.CornerRadius = UDim.new(0, 4) -CloseButtonCorner.Parent = CloseButton - --- Create content frame -local ContentFrame = Instance.new("Frame") -ContentFrame.Name = "ContentFrame" -ContentFrame.Size = UDim2.new(1, -20, 1, -40) -ContentFrame.Position = UDim2.new(0, 10, 0, 35) -ContentFrame.BackgroundTransparency = 1 -ContentFrame.Parent = MainFrame - --- Create scrolling frame for content -local ScrollFrame = Instance.new("ScrollingFrame") -ScrollFrame.Name = "ScrollFrame" -ScrollFrame.Size = UDim2.new(1, 0, 1, 0) -ScrollFrame.BackgroundTransparency = 1 -ScrollFrame.BorderSizePixel = 0 -ScrollFrame.ScrollBarThickness = 4 -ScrollFrame.ScrollBarImageColor3 = UI.Color.Accent -ScrollFrame.Parent = ContentFrame - --- Create UI list layout -local UIListLayout = Instance.new("UIListLayout") -UIListLayout.SortOrder = Enum.SortOrder.LayoutOrder -UIListLayout.Padding = UDim.new(0, 5) -UIListLayout.Parent = ScrollFrame - --- Make UI draggable -if UI.Draggable then - local isDragging = false - local dragInput - local dragStart - local startPos - - TopBar.InputBegan:Connect(function(input) - if input.UserInputType == Enum.UserInputType.MouseButton1 then - isDragging = true - dragStart = input.Position - startPos = MainFrame.Position - end - end) - - TopBar.InputEnded:Connect(function(input) - if input.UserInputType == Enum.UserInputType.MouseButton1 then - isDragging = false - end - end) - - UserInputService.InputChanged:Connect(function(input) - if input == dragInput and isDragging then - local delta = input.Position - dragStart - MainFrame.Position = UDim2.new(startPos.X.Scale, startPos.X.Offset + delta.X, startPos.Y.Scale, startPos.Y.Offset + delta.Y) - end - end) - - TopBar.InputChanged:Connect(function(input) - if input.UserInputType == Enum.UserInputType.MouseMovement then - dragInput = input - end - end) -end - --- Close button functionality -CloseButton.MouseButton1Click:Connect(function() - ScreenGui:Destroy() -end) - --- Helper function to create a button -function UI:CreateButton(text, callback) - local Button = Instance.new("TextButton") - Button.Name = text .. "Button" - Button.Size = UDim2.new(1, 0, 0, 30) - Button.BackgroundColor3 = UI.Color.Button - Button.Text = text - Button.TextColor3 = UI.Color.Text - Button.TextSize = 14 - Button.Font = Enum.Font.SourceSans - Button.Parent = ScrollFrame - - -- Add corner radius - local ButtonCorner = Instance.new("UICorner") - ButtonCorner.CornerRadius = UDim.new(0, 4) - ButtonCorner.Parent = Button - - -- Button hover effect - Button.MouseEnter:Connect(function() - TweenService:Create(Button, TweenInfo.new(0.2), {BackgroundColor3 = UI.Color.ButtonHover}):Play() - end) - - Button.MouseLeave:Connect(function() - TweenService:Create(Button, TweenInfo.new(0.2), {BackgroundColor3 = UI.Color.Button}):Play() - end) - - -- Button click - Button.MouseButton1Click:Connect(function() - callback() - end) - - -- Add to elements - table.insert(UI.Elements, Button) - - -- Update scroll frame canvas size - ScrollFrame.CanvasSize = UDim2.new(0, 0, 0, UIListLayout.AbsoluteContentSize.Y) - - return Button -end - --- Helper function to create a toggle -function UI:CreateToggle(text, default, callback) - local Toggle = Instance.new("Frame") - Toggle.Name = text .. "Toggle" - Toggle.Size = UDim2.new(1, 0, 0, 30) - Toggle.BackgroundColor3 = UI.Color.Button - Toggle.Parent = ScrollFrame - - -- Add corner radius - local ToggleCorner = Instance.new("UICorner") - ToggleCorner.CornerRadius = UDim.new(0, 4) - ToggleCorner.Parent = Toggle - - -- Toggle text - local ToggleText = Instance.new("TextLabel") - ToggleText.Name = "ToggleText" - ToggleText.Size = UDim2.new(1, -50, 1, 0) - ToggleText.Position = UDim2.new(0, 10, 0, 0) - ToggleText.BackgroundTransparency = 1 - ToggleText.Text = text - ToggleText.TextColor3 = UI.Color.Text - ToggleText.TextSize = 14 - ToggleText.Font = Enum.Font.SourceSans - ToggleText.TextXAlignment = Enum.TextXAlignment.Left - ToggleText.Parent = Toggle - - -- Toggle button - local ToggleButton = Instance.new("Frame") - ToggleButton.Name = "ToggleButton" - ToggleButton.Size = UDim2.new(0, 40, 0, 20) - ToggleButton.Position = UDim2.new(1, -45, 0, 5) - ToggleButton.BackgroundColor3 = Color3.fromRGB(50, 50, 50) - ToggleButton.Parent = Toggle - - -- Add corner radius to toggle button - local ToggleButtonCorner = Instance.new("UICorner") - ToggleButtonCorner.CornerRadius = UDim.new(0, 10) - ToggleButtonCorner.Parent = ToggleButton - - -- Toggle indicator - local ToggleIndicator = Instance.new("Frame") - ToggleIndicator.Name = "ToggleIndicator" - ToggleIndicator.Size = UDim2.new(0, 16, 0, 16) - ToggleIndicator.Position = UDim2.new(0, 2, 0, 2) - ToggleIndicator.BackgroundColor3 = UI.Color.Text - ToggleIndicator.Parent = ToggleButton - - -- Add corner radius to toggle indicator - local ToggleIndicatorCorner = Instance.new("UICorner") - ToggleIndicatorCorner.CornerRadius = UDim.new(0, 8) - ToggleIndicatorCorner.Parent = ToggleIndicator - - -- Set initial state - local enabled = default or false - local function updateToggle() - if enabled then - TweenService:Create(ToggleIndicator, TweenInfo.new(0.2), {Position = UDim2.new(0, 22, 0, 2), BackgroundColor3 = UI.Color.Accent}):Play() - TweenService:Create(ToggleButton, TweenInfo.new(0.2), {BackgroundColor3 = Color3.fromRGB(70, 70, 70)}):Play() - else - TweenService:Create(ToggleIndicator, TweenInfo.new(0.2), {Position = UDim2.new(0, 2, 0, 2), BackgroundColor3 = UI.Color.Text}):Play() - TweenService:Create(ToggleButton, TweenInfo.new(0.2), {BackgroundColor3 = Color3.fromRGB(50, 50, 50)}):Play() - end - callback(enabled) - end - - -- Update toggle on first load - updateToggle() - - -- Toggle click - Toggle.InputBegan:Connect(function(input) - if input.UserInputType == Enum.UserInputType.MouseButton1 then - enabled = not enabled - updateToggle() - end - end) - - -- Add to elements - table.insert(UI.Elements, Toggle) - - -- Update scroll frame canvas size - ScrollFrame.CanvasSize = UDim2.new(0, 0, 0, UIListLayout.AbsoluteContentSize.Y) - - return Toggle -end - --- Return the UI object for external control -return UI -)"; - m_scriptTemplates.push_back(uiTemplate); -} - -// Find closest template -ScriptAssistant::ScriptTemplate ScriptAssistant::FindClosestTemplate(const std::string& description) { - if (m_scriptTemplates.empty()) { - return ScriptTemplate(); - } - - // Find template with most matching keywords - std::vector keywords = ExtractKeywords(description); - - int highestScore = 0; - ScriptTemplate bestMatch; - - for (const auto& tmpl : m_scriptTemplates) { - std::vector templateKeywords = ExtractKeywords(tmpl.m_description); - - // Count matching keywords - int score = 0; - for (const auto& keyword : keywords) { - for (const auto& templateKeyword : templateKeywords) { - if (keyword == templateKeyword) { - score++; - break; - } - } - } - - if (score > highestScore) { - highestScore = score; - bestMatch = tmpl; - } - } - - return bestMatch; -} - -// Extract keywords from text -std::vector ScriptAssistant::ExtractKeywords(const std::string& text) { - std::vector keywords; - std::string lowercaseText = text; - - // Convert to lowercase - std::transform(lowercaseText.begin(), lowercaseText.end(), lowercaseText.begin(), - [](unsigned char c) { return std::tolower(c); }); - - // Split by non-alphanumeric characters - std::istringstream iss(lowercaseText); - std::string word; - - while (iss >> word) { - // Remove non-alphanumeric characters - word.erase(std::remove_if(word.begin(), word.end(), - [](unsigned char c) { return !std::isalnum(c); }), - word.end()); - - // Skip small words and common words - if (word.length() > 2 && - word != "the" && word != "and" && word != "for" && - word != "with" && word != "that" && word != "this") { - keywords.push_back(word); - } - } - - return keywords; -} - -// Analyze game object recursively -void ScriptAssistant::AnalyzeGameObject(std::shared_ptr obj, std::set& classNames) { - if (!obj) return; - - // Add class name - classNames.insert(obj.m_className); - - // Recursively analyze children - for (const auto& child : obj.m_children) { - AnalyzeGameObject(child, classNames); - } -} - -// Optimize local variables -std::string ScriptAssistant::OptimizeLocalVariables(const std::string& script) { - // Basic implementation - in a real system, this would be more sophisticated - - // Replace redundant local declarations - std::string optimized = script; - - // Find common patterns - size_t pos = optimized.find("local function"); - while (pos != std::string::npos) { - // Keep local functions as they are - pos = optimized.find("local function", pos + 14); - } - - // Look for multiple consecutive local declarations that could be combined - pos = optimized.find("local "); - while (pos != std::string::npos) { - size_t nextLocal = optimized.find("local ", pos + 6); - if (nextLocal != std::string::npos && nextLocal - pos < 50) { - // Check if these could be combined (simple heuristic) - size_t lineEnd = optimized.find("\n", pos); - if (lineEnd != std::string::npos && lineEnd < nextLocal) { - // These are on different lines, could potentially combine - // In a real implementation, would need to analyze variable usage - } - } - - pos = optimized.find("local ", pos + 6); - } - - return optimized; -} - -// Optimize loops -std::string ScriptAssistant::OptimizeLoops(const std::string& script) { - // Basic implementation - in a real system, this would use more advanced analysis - - // Replace inefficient loop patterns - std::string optimized = script; - - // Replace pairs() with ipairs() for array-like tables - size_t pos = optimized.find("for k, v in pairs("); - while (pos != std::string::npos) { - // Check if this could use ipairs instead (simple heuristic) - size_t closingParen = optimized.find(")", pos); - if (closingParen != std::string::npos) { - std::string tableName = optimized.substr(pos + 16, closingParen - (pos + 16)); - - // Check if tableName ends with common array identifiers - if (tableName.find("List") != std::string::npos || - tableName.find("Array") != std::string::npos || - tableName.find("s") == tableName.length() - 1) { // Plural name - - // Replace with ipairs for array-like tables - optimized.replace(pos, 16, "for k, v in ipairs("); - } - } - - pos = optimized.find("for k, v in pairs(", pos + 10); - } - - return optimized; -} - -// Remove unnecessary whitespace -std::string ScriptAssistant::RemoveUnnecessaryWhitespace(const std::string& script) { - std::string optimized = script; - - // Replace multiple spaces with single space - size_t pos = optimized.find(" "); - while (pos != std::string::npos) { - optimized.replace(pos, 2, " "); - pos = optimized.find(" ", pos); - } - - // Replace multiple empty lines with a single empty line - pos = optimized.find("\n\n\n"); - while (pos != std::string::npos) { - optimized.replace(pos, 3, "\n\n"); - pos = optimized.find("\n\n\n", pos); - } - - return optimized; -} - -// Detect performance issues -std::vector ScriptAssistant::DetectPerformanceIssues(const std::string& script) { - std::vector issues; - - // Check for inefficient patterns - - // 1. Table creation in loops - if (script.find("for") != std::string::npos && - script.find("{}", script.find("for")) != std::string::npos) { - issues.push_back("Potential table creation inside loops - consider moving outside the loop"); - } - - // 2. Using # operator on non-sequential tables - if (script.find("#") != std::string::npos) { - issues.push_back("Using # length operator which can be unreliable for tables with non-sequential indices"); - } - - // 3. RenderStepped for non-render updates - if (script.find("RenderStepped") != std::string::npos) { - issues.push_back("Using RenderStepped which runs every frame - consider Heartbeat for logic not tied to rendering"); - } - - // 4. String concatenation in loops - if (script.find("for") != std::string::npos && - script.find("..", script.find("for")) != std::string::npos) { - issues.push_back("String concatenation in loops can be inefficient - consider using table.concat"); - } - - // 5. Inefficient table access pattern - if (script.find("FindFirstChild") != std::string::npos) { - issues.push_back("Multiple FindFirstChild calls can be slow - cache references when possible"); - } - - return issues; -} - -} // namespace AIFeatures -} // namespace iOS diff --git a/source/cpp/ios/ai_features/ScriptAssistant.mm.rej b/source/cpp/ios/ai_features/ScriptAssistant.mm.rej deleted file mode 100644 index 5d5f6a2..0000000 --- a/source/cpp/ios/ai_features/ScriptAssistant.mm.rej +++ /dev/null @@ -1,37 +0,0 @@ ---- source/cpp/ios/ai_features/ScriptAssistant.mm -+++ source/cpp/ios/ai_features/ScriptAssistant.mm -@@ -365,7 +365,7 @@ void ScriptAssistant::ClearConversationHistory() { - - // Load templates - void ScriptAssistant::LoadTemplates(const std::string& templatesPath) { -- std::lock_guard lock(m_mutex); -+ std::lock_guard lock(this->m_mutex); - - // In a real implementation, load templates from file - // For this example, just add some default templates -@@ -443,10 +443,10 @@ std::vector ScriptAssistant::GetExampleScriptDescriptions() { - - // Add system message - void ScriptAssistant::AddSystemMessage(const std::string& message) { -- std::lock_guard lock(m_mutex); -+ std::lock_guard lock(this->m_mutex); - - // Add to conversation history -- m_conversationHistory.push_back(Message(MessageType::System, message)); -+ this->m_conversationHistory.push_back(Message(MessageType::System, message)); - - // Trim history if needed - TrimConversationHistory(); -@@ -454,10 +454,10 @@ void ScriptAssistant::AddSystemMessage(const std::string& message) { - - // Add user message - void ScriptAssistant::AddUserMessage(const std::string& message) { -- std::lock_guard lock(m_mutex); -+ std::lock_guard lock(this->m_mutex); - - // Add to conversation history -- m_conversationHistory.push_back(Message(MessageType::User, message)); -+ this->m_conversationHistory.push_back(Message(MessageType::User, message)); - - // Trim history if needed - TrimConversationHistory(); diff --git a/source/cpp/ios/ai_features/local_models/SimpleDummyModel.h b/source/cpp/ios/ai_features/local_models/SimpleDummyModel.h deleted file mode 100644 index e69de29..0000000 diff --git a/source/cpp/ios/ai_features/local_models/SimpleDummyModel.mm b/source/cpp/ios/ai_features/local_models/SimpleDummyModel.mm deleted file mode 100644 index e69de29..0000000 diff --git a/source/cpp/ios/ui/AssistantButtonController.mm.fixed b/source/cpp/ios/ui/AssistantButtonController.mm.fixed deleted file mode 100644 index e872b14..0000000 --- a/source/cpp/ios/ui/AssistantButtonController.mm.fixed +++ /dev/null @@ -1,722 +0,0 @@ -#include "AssistantButtonController.h" -#include "../ai_features/local_models/GeneralAssistantModel.h" -#include -#include -#include -#include - -// Objective-C imports -#if __OBJC__ -#import -#import -#import // For objc_setAssociatedObject -#else -typedef void UIButton; -typedef void UIView; -typedef void UIViewController; -#endif - -namespace iOS { -namespace UI { - -// Constructor -AssistantButtonController::AssistantButtonController() - : m_viewController(nullptr), - m_button(nullptr), - m_chatView(nullptr), - m_inputField(nullptr), - m_panGestureRecognizer(nullptr), - m_position(Position::BottomRight), - m_state(VisibilityState::Minimized), - m_assistantModel(nullptr), - m_customMessageHandler(nullptr), - m_isDragging(false) -{ - // Initialize safe area insets with default values - m_safeAreaInsets[0] = 20; // top - m_safeAreaInsets[1] = 20; // left - m_safeAreaInsets[2] = 20; // bottom - m_safeAreaInsets[3] = 20; // right - - // Initialize appearance - m_appearance.size = 60.0f; - m_appearance.cornerRadius = 30.0f; - m_appearance.alpha = 1.0f; - m_appearance.iconName = "assistant_icon"; - m_appearance.backgroundColor = "#007AFF"; // iOS blue - m_appearance.tintColor = "#FFFFFF"; // white -} - -// Destructor -AssistantButtonController::~AssistantButtonController() { - // Clean up Objective-C objects -#if __OBJC__ - if (m_button) { - CFRelease(m_button); - m_button = nullptr; - } - - if (m_chatView) { - CFRelease(m_chatView); - m_chatView = nullptr; - } - - if (m_inputField) { - CFRelease(m_inputField); - m_inputField = nullptr; - } - - if (m_panGestureRecognizer) { - CFRelease(m_panGestureRecognizer); - m_panGestureRecognizer = nullptr; - } -#endif -} - -// Helper methods -void AssistantButtonController::SetupButton() { -#if __OBJC__ - if (!m_viewController) return; - UIViewController* controller = (__bridge UIViewController*)m_viewController; - - // Create button - UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom]; - button.frame = CGRectMake(0, 0, m_appearance.size, m_appearance.size); - - // Configure appearance - button.layer.cornerRadius = m_appearance.cornerRadius; - - // Set background color from hex string - UIColor* backgroundColor = nil; - if (m_appearance.backgroundColor == "#007AFF") { - backgroundColor = [UIColor systemBlueColor]; - } else { - // Default blue - backgroundColor = [UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0]; - } - button.backgroundColor = backgroundColor; - - // Set icon - [button setImage:[UIImage systemImageNamed:@"wand.and.stars"] forState:UIControlStateNormal]; - - // Set tint color from hex string - UIColor* tintColor = nil; - if (m_appearance.tintColor == "#FFFFFF") { - tintColor = [UIColor whiteColor]; - } else { - // Default white - tintColor = [UIColor whiteColor]; - } - button.tintColor = tintColor; - - button.alpha = m_appearance.alpha; - - // Add shadow - button.layer.shadowColor = [UIColor blackColor].CGColor; - button.layer.shadowOffset = CGSizeMake(0, 3); - button.layer.shadowOpacity = 0.3; - button.layer.shadowRadius = 5; - - // Add to the view - [controller.view addSubview:button]; - - // Store in member variable - m_button = (__bridge_retained void*)button; - - // Add tap handler - // Properly capture this pointer - AssistantButtonController* controllerPtr = this; - void (^buttonTapHandler)(UIButton*) = ^(UIButton* _Unused) { - // Toggle visibility state when tapped - if (controllerPtr->m_state == VisibilityState::Minimized) { - controllerPtr->SetVisibilityState(VisibilityState::Visible); - } else { - controllerPtr->SetVisibilityState(VisibilityState::Minimized); - } - }; - - // Store block to avoid ARC releasing it - objc_setAssociatedObject(button, "tapHandler", buttonTapHandler, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - - // Add target-action for button tap - [button addTarget:buttonTapHandler - action:@selector(invoke:) - forControlEvents:UIControlEventTouchUpInside]; - - // Add pan gesture recognizer for dragging - UIPanGestureRecognizer* panGesture = [[UIPanGestureRecognizer alloc] init]; - - // Add pan handler - AssistantButtonController* controller_ptr = this; // Create local pointer to this for capture - void (^panHandler)(UIPanGestureRecognizer*) = ^(UIPanGestureRecognizer* recognizer) { - UIButton* button = (__bridge UIButton*)controller_ptr->m_button; - UIViewController* viewController = (__bridge UIViewController*)controller_ptr->m_viewController; - CGRect bounds = viewController.view.bounds; - - if (recognizer.state == UIGestureRecognizerStateBegan) { - controller_ptr->m_isDragging = true; - } - else if (recognizer.state == UIGestureRecognizerStateChanged) { - CGPoint translation = [recognizer translationInView:button.superview]; - - CGRect frame = button.frame; - frame.origin.x += translation.x; - frame.origin.y += translation.y; - button.frame = frame; - - [recognizer setTranslation:CGPointZero inView:button.superview]; - } - else if (recognizer.state == UIGestureRecognizerStateEnded) { - controller_ptr->m_isDragging = false; - - // Snap to closest edge - CGFloat minX = controller_ptr->m_safeAreaInsets[1]; - CGFloat minY = controller_ptr->m_safeAreaInsets[0]; - CGFloat maxX = bounds.size.width - button.frame.size.width - controller_ptr->m_safeAreaInsets[3]; - CGFloat maxY = bounds.size.height - button.frame.size.height - controller_ptr->m_safeAreaInsets[2]; - - CGRect frame = button.frame; - - // Find horizontal and vertical position - bool isLeft = (frame.origin.x < bounds.size.width / 2); - bool isTop = (frame.origin.y < bounds.size.height / 2); - - // Snap to each corner - Position newPosition; - if (isLeft && isTop) { - frame.origin.x = minX; - frame.origin.y = minY; - newPosition = Position::TopLeft; - } - else if (isLeft && !isTop) { - frame.origin.x = minX; - frame.origin.y = maxY; - newPosition = Position::BottomLeft; - } - else if (!isLeft && isTop) { - frame.origin.x = maxX; - frame.origin.y = minY; - newPosition = Position::TopRight; - } - else { - frame.origin.x = maxX; - frame.origin.y = maxY; - newPosition = Position::BottomRight; - } - - // Animate to snapped position - [UIView animateWithDuration:0.3 - animations:^{ - button.frame = frame; - }]; - - // Update position - controller_ptr->m_position = newPosition; - } - }; - - // Store block to avoid ARC releasing it - objc_setAssociatedObject(panGesture, "panHandler", panHandler, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - - // Add target-action for pan gesture - [panGesture addTarget:panHandler action:@selector(invoke:)]; - [button addGestureRecognizer:panGesture]; - - // Store gesture recognizer - m_panGestureRecognizer = (__bridge_retained void*)panGesture; -#endif -} - -void AssistantButtonController::SetupChatView() { -#if __OBJC__ - if (!m_viewController) return; - UIViewController* controller = (__bridge UIViewController*)m_viewController; - - // Create chat panel view - UIView* panelView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)]; - panelView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0]; - panelView.layer.cornerRadius = 16; - panelView.clipsToBounds = true; - panelView.alpha = 0.0; // Start hidden - panelView.hidden = YES; - - // Add shadow - panelView.layer.shadowColor = [UIColor blackColor].CGColor; - panelView.layer.shadowOffset = CGSizeMake(0, 5); - panelView.layer.shadowOpacity = 0.3; - panelView.layer.shadowRadius = 10; - - // Add to the view - [controller.view addSubview:panelView]; - - // Create header view - UIView* headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, panelView.frame.size.width, 50)]; - headerView.backgroundColor = [UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0]; - [panelView addSubview:headerView]; - - // Create title label - UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, headerView.frame.size.width - 66, 50)]; - titleLabel.text = @"AI Assistant"; - titleLabel.textColor = [UIColor whiteColor]; - titleLabel.font = [UIFont boldSystemFontOfSize:18]; - [headerView addSubview:titleLabel]; - - // Create close button - UIButton* closeButton = [UIButton buttonWithType:UIButtonTypeSystem]; - closeButton.frame = CGRectMake(headerView.frame.size.width - 50, 0, 50, 50); - [closeButton setImage:[UIImage systemImageNamed:@"xmark"] forState:UIControlStateNormal]; - closeButton.tintColor = [UIColor whiteColor]; - [headerView addSubview:closeButton]; - - // Add close button handler - AssistantButtonController* controllerPtr = this; - void (^closeButtonHandler)(UIButton*) = ^(UIButton* _Unused) { - controllerPtr->SetVisibilityState(VisibilityState::Minimized); - }; - - // Store block to avoid ARC releasing it - objc_setAssociatedObject(closeButton, "closeHandler", closeButtonHandler, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - - // Add target-action for close button - [closeButton addTarget:closeButtonHandler - action:@selector(invoke:) - forControlEvents:UIControlEventTouchUpInside]; - - // Create input field - UITextField* inputField = [[UITextField alloc] initWithFrame:CGRectMake(16, panelView.frame.size.height - 60, panelView.frame.size.width - 82, 40)]; - inputField.placeholder = @"Ask a question..."; - inputField.borderStyle = UITextBorderStyleRoundedRect; - inputField.backgroundColor = [UIColor whiteColor]; - [panelView addSubview:inputField]; - - // Store input field - m_inputField = (__bridge_retained void*)inputField; - - // Create send button - UIButton* sendButton = [UIButton buttonWithType:UIButtonTypeSystem]; - sendButton.frame = CGRectMake(panelView.frame.size.width - 60, panelView.frame.size.height - 60, 44, 40); - [sendButton setImage:[UIImage systemImageNamed:@"arrow.up.circle.fill"] forState:UIControlStateNormal]; - sendButton.tintColor = [UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0]; - [panelView addSubview:sendButton]; - - // Add send button handler - AssistantButtonController* controller_ptr = this; - void (^sendButtonHandler)(UIButton*) = ^(UIButton* _Unused) { - UITextField* field = (__bridge UITextField*)controller_ptr->m_inputField; - NSString* text = field.text; - - if (text.length > 0) { - std::string message = [text UTF8String]; - - // Add user message - ChatMessage chatMsg(message, MessageType::User, std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); - controller_ptr->m_messages.push_back(chatMsg); - - // Process with custom handler or AI model - if (controller_ptr->m_customMessageHandler) { - controller_ptr->m_customMessageHandler(message); - } else if (controller_ptr->m_assistantModel) { - // In a real implementation, this would call the AI model - // GeneralAssistantModel doesn't have ProcessQuery(), so simulating response - std::string response = "I'm sorry, I don't have enough information to answer that question."; - - // Add assistant message - ChatMessage assistantMsg(response, MessageType::Assistant, std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); - controller_ptr->m_messages.push_back(assistantMsg); - - // Update chat view - controller_ptr->UpdateChatView(); - } - - // Update chat view - controller_ptr->UpdateChatView(); - - // Clear input field - field.text = @""; - } - }; - - // Store block to avoid ARC releasing it - objc_setAssociatedObject(sendButton, "sendHandler", sendButtonHandler, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - - // Add target-action for send button - [sendButton addTarget:sendButtonHandler - action:@selector(invoke:) - forControlEvents:UIControlEventTouchUpInside]; - - // Create chat view (scrollable) - UIScrollView* chatScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 50, panelView.frame.size.width, panelView.frame.size.height - 110)]; - chatScrollView.backgroundColor = [UIColor whiteColor]; - [panelView addSubview:chatScrollView]; - - // Add content view to scroll view - UIView* chatContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, chatScrollView.frame.size.width, 0)]; // Height will grow as messages are added - chatContentView.backgroundColor = [UIColor whiteColor]; - [chatScrollView addSubview:chatContentView]; - - // Store chat view - m_chatView = (__bridge_retained void*)chatContentView; -#endif -} - -void AssistantButtonController::SetPosition(Position position) { - m_position = position; - -#if __OBJC__ - // Update button position - if (m_button && m_viewController) { - UIButton* button = (__bridge UIButton*)m_button; - UIViewController* controller = (__bridge UIViewController*)m_viewController; - CGRect bounds = controller.view.bounds; - - // Calculate position based on the setting - CGFloat minX = m_safeAreaInsets[1]; - CGFloat minY = m_safeAreaInsets[0]; - CGFloat maxX = bounds.size.width - button.frame.size.width - m_safeAreaInsets[3]; - CGFloat maxY = bounds.size.height - button.frame.size.height - m_safeAreaInsets[2]; - - CGRect frame = button.frame; - - switch (m_position) { - case Position::TopLeft: - frame.origin.x = minX; - frame.origin.y = minY; - break; - - case Position::TopRight: - frame.origin.x = maxX; - frame.origin.y = minY; - break; - - case Position::BottomLeft: - frame.origin.x = minX; - frame.origin.y = maxY; - break; - - case Position::BottomRight: - frame.origin.x = maxX; - frame.origin.y = maxY; - break; - - case Position::Center: - frame.origin.x = (bounds.size.width - button.frame.size.width) / 2; - frame.origin.y = (bounds.size.height - button.frame.size.height) / 2; - break; - } - - button.frame = frame; - } -#endif -} - -void AssistantButtonController::SetVisibilityState(VisibilityState state) { - if (m_state == state) return; - - m_state = state; - -#if __OBJC__ - // Update UI based on visibility state - switch (state) { - case VisibilityState::Hidden: - SetButtonHidden(true); - SetChatViewHidden(true); - break; - - case VisibilityState::Minimized: - SetButtonHidden(false); - SetChatViewHidden(true); - break; - - case VisibilityState::Visible: - SetButtonHidden(false); - SetChatViewHidden(false); - break; - } -#endif -} - -AssistantButtonController::VisibilityState AssistantButtonController::GetVisibilityState() const { - return m_state; -} - -void AssistantButtonController::SetMessageHandler(MessageHandler handler) { - m_customMessageHandler = handler; -} - -void AssistantButtonController::SetAssistantModel(std::shared_ptr model) { - m_assistantModel = model; -} - -void AssistantButtonController::SetButtonHidden(bool hidden) { -#if __OBJC__ - if (m_button) { - UIButton* button = (__bridge UIButton*)m_button; - button.hidden = hidden; - } -#endif -} - -void AssistantButtonController::SetChatViewHidden(bool hidden) { -#if __OBJC__ - if (m_chatView) { - UIView* chatContentView = (__bridge UIView*)m_chatView; - UIScrollView* scrollView = (UIScrollView*)chatContentView.superview; - UIView* panelView = scrollView.superview; - - if (hidden) { - // Hide with animation - if (!panelView.hidden) { - [UIView animateWithDuration:0.3 - animations:^{ - panelView.alpha = 0.0; - } - completion:^(BOOL _Unused) { - panelView.hidden = YES; - }]; - } - } else { - // Show with animation - panelView.hidden = NO; - panelView.alpha = 0.0; - - // Position panel near button - if (m_button) { - UIButton* button = (__bridge UIButton*)m_button; - CGRect buttonFrame = button.frame; - CGRect panelFrame = panelView.frame; - - // Position based on button position - switch (m_position) { - case Position::TopLeft: - panelFrame.origin.x = buttonFrame.origin.x; - panelFrame.origin.y = buttonFrame.origin.y + buttonFrame.size.height + 10; - break; - - case Position::TopRight: - panelFrame.origin.x = buttonFrame.origin.x + buttonFrame.size.width - panelFrame.size.width; - panelFrame.origin.y = buttonFrame.origin.y + buttonFrame.size.height + 10; - break; - - case Position::BottomLeft: - panelFrame.origin.x = buttonFrame.origin.x; - panelFrame.origin.y = buttonFrame.origin.y - panelFrame.size.height - 10; - break; - - case Position::BottomRight: - panelFrame.origin.x = buttonFrame.origin.x + buttonFrame.size.width - panelFrame.size.width; - panelFrame.origin.y = buttonFrame.origin.y - panelFrame.size.height - 10; - break; - - case Position::Center: - panelFrame.origin.x = (button.superview.frame.size.width - panelFrame.size.width) / 2; - panelFrame.origin.y = (button.superview.frame.size.height - panelFrame.size.height) / 2; - break; - } - - panelView.frame = panelFrame; - } - - // Update chat view - UpdateChatView(); - - // Show with animation - [UIView animateWithDuration:0.3 - animations:^{ - panelView.alpha = 1.0; - }]; - } - } -#endif -} - -void AssistantButtonController::UpdateChatView() { -#if __OBJC__ - if (!m_chatView) return; - - UIView* chatContentView = (__bridge UIView*)m_chatView; - - // Remove all existing message views - for (UIView* subview in [chatContentView.subviews copy]) { - [subview removeFromSuperview]; - } - - // Add message bubbles - CGFloat currentY = 8; - CGFloat contentWidth = chatContentView.frame.size.width; - CGFloat maxBubbleWidth = contentWidth * 0.7; - - for (const ChatMessage& message : m_messages) { - bool isUser = (message.type == MessageType::User); - - // Create message label - UILabel* messageLabel = [[UILabel alloc] init]; - messageLabel.text = [NSString stringWithUTF8String:message.text.c_str()]; - messageLabel.numberOfLines = 0; - messageLabel.lineBreakMode = NSLineBreakByWordWrapping; - messageLabel.font = [UIFont systemFontOfSize:16]; - - // Calculate size needed for text - CGSize maxSize = CGSizeMake(maxBubbleWidth - 16, CGFLOAT_MAX); - CGRect textRect = [messageLabel.text boundingRectWithSize:maxSize - options:NSStringDrawingUsesLineFragmentOrigin - attributes:@{NSFontAttributeName: messageLabel.font} - context:nil]; - - // Create bubble - CGFloat bubbleWidth = textRect.size.width + 16; - CGFloat bubbleHeight = textRect.size.height + 16; - CGFloat bubbleX = isUser ? (contentWidth - bubbleWidth - 8) : 8; - UIView* bubbleView = [[UIView alloc] initWithFrame:CGRectMake(bubbleX, currentY, bubbleWidth, bubbleHeight)]; - - // Style bubble - switch (message.type) { - case MessageType::User: - bubbleView.backgroundColor = [UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0]; - messageLabel.textColor = [UIColor whiteColor]; - break; - - case MessageType::Assistant: - bubbleView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0]; - messageLabel.textColor = [UIColor blackColor]; - break; - - case MessageType::System: - bubbleView.backgroundColor = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1.0]; - messageLabel.textColor = [UIColor whiteColor]; - break; - - case MessageType::Action: - bubbleView.backgroundColor = [UIColor colorWithRed:0.2 green:0.6 blue:0.2 alpha:1.0]; - messageLabel.textColor = [UIColor whiteColor]; - break; - } - - bubbleView.layer.cornerRadius = 12; - - // Position message label in bubble - messageLabel.frame = CGRectMake(8, 8, textRect.size.width, textRect.size.height); - [bubbleView addSubview:messageLabel]; - [chatContentView addSubview:bubbleView]; - - // Update current Y position for next message - currentY += bubbleHeight + 8; - } - - // Update content size - UIScrollView* scrollView = (UIScrollView*)chatContentView.superview; - CGRect frame = chatContentView.frame; - frame.size.height = currentY; - chatContentView.frame = frame; - scrollView.contentSize = frame.size; - - // Scroll to bottom - if (currentY > scrollView.frame.size.height) { - [scrollView setContentOffset:CGPointMake(0, currentY - scrollView.frame.size.height) animated:YES]; - } -#endif -} - -void AssistantButtonController::AddMessage(const std::string& text, MessageType type) { - // Create message - ChatMessage message(text, type, std::chrono::system_clock::to_time_t(std::chrono::system_clock::now())); - m_messages.push_back(message); - - // Update chat view - UpdateChatView(); -} - -void AssistantButtonController::ClearChatHistory() { - m_messages.clear(); - UpdateChatView(); -} - -std::vector AssistantButtonController::GetChatHistory() const { - return m_messages; -} - -void AssistantButtonController::HandleOrientationChange() { - // Update button position - SetPosition(m_position); - - // Update chat view if visible - if (m_state == VisibilityState::Visible) { - SetChatViewHidden(false); // This will reposition the chat view - } -} - -void AssistantButtonController::UpdateSafeAreaInsets(float top, float left, float bottom, float right) { - m_safeAreaInsets[0] = top; - m_safeAreaInsets[1] = left; - m_safeAreaInsets[2] = bottom; - m_safeAreaInsets[3] = right; - - // Update button position - SetPosition(m_position); -} - -// Public methods -bool AssistantButtonController::SetupView(void* viewController) { - m_viewController = viewController; - -#if __OBJC__ - std::cout << "Setting up AssistantButtonController view" << std::endl; - - // Set up button - SetupButton(); - - // Set up chat view - SetupChatView(); - - // Position button - SetPosition(m_position); - - // Set initial visibility - SetVisibilityState(m_state); - - return true; -#else - return false; -#endif -} - -void AssistantButtonController::CleanupView() { -#if __OBJC__ - std::cout << "Cleaning up AssistantButtonController view" << std::endl; - - // Clean up button - if (m_button) { - UIButton* button = (__bridge UIButton*)m_button; - [button removeFromSuperview]; - CFRelease(m_button); - m_button = nullptr; - } - - // Clean up chat view - if (m_chatView) { - UIView* chatContentView = (__bridge UIView*)m_chatView; - UIScrollView* scrollView = (UIScrollView*)chatContentView.superview; - UIView* panelView = scrollView.superview; - [panelView removeFromSuperview]; - CFRelease(m_chatView); - m_chatView = nullptr; - } - - // Clean up input field - if (m_inputField) { - CFRelease(m_inputField); - m_inputField = nullptr; - } - - // Clean up pan gesture recognizer - if (m_panGestureRecognizer) { - CFRelease(m_panGestureRecognizer); - m_panGestureRecognizer = nullptr; - } - - // Clear chat history - m_messages.clear(); -#endif -} - -} // namespace UI -} // namespace iOS diff --git a/source/cpp/ios/ui/VulnerabilityViewController.mm.bak b/source/cpp/ios/ui/VulnerabilityViewController.mm.bak deleted file mode 100644 index 47a0680..0000000 --- a/source/cpp/ios/ui/VulnerabilityViewController.mm.bak +++ /dev/null @@ -1,484 +0,0 @@ - -#include "../../ios_compat.h" -#include -#include -#include -#include -#include -#include -#include - -// Forward declaration -#include "../ai_features/vulnerability_detection/VulnerabilityDetector.h" - -namespace iOS { - namespace UI { - // UI for vulnerability detection - class VulnerabilityViewController { - private: - // Objective-C view controller - void* m_viewController; - - // UI elements - void* m_scanButton; - void* m_resultsTableView; - void* m_detailsView; - void* m_exploitButton; - void* m_progressIndicator; - - // Callbacks - std::function m_scanButtonCallback; - std::function m_exploitButtonCallback; - - // Data - std::shared_ptr m_vulnerabilityDetector; - std::vector m_vulnerabilities; - std::mutex m_vulnerabilitiesMutex; - bool m_scanInProgress; - float m_scanProgress; - - // Selected vulnerability - int m_selectedVulnerabilityIndex; - - public: - VulnerabilityViewController(); - ~VulnerabilityViewController(); - - void Initialize(); - void SetScanButtonCallback(std::function callback); - void SetExploitButtonCallback(std::function callback); - void SetVulnerabilityDetector(std::shared_ptr detector); - void StartScan(const std::string& path1, const std::string& path2); - void* GetViewController() const; - - private: - void CreateUI(); - void UpdateUI(); - void UpdateProgress(float progress, const std::string& status); - void ShowVulnerabilityDetails(int index); - }; - - // VulnerabilityViewController implementation - VulnerabilityViewController::VulnerabilityViewController() - : m_viewController(nullptr), - m_scanButton(nullptr), - m_resultsTableView(nullptr), - m_detailsView(nullptr), - m_exploitButton(nullptr), - m_progressIndicator(nullptr), - m_scanInProgress(false), - m_scanProgress(0.0f), - m_selectedVulnerabilityIndex(-1) { - } - - VulnerabilityViewController::~VulnerabilityViewController() { - // Release retained Objective-C objects - if (m_viewController) { - CFRelease(m_viewController); - m_viewController = nullptr; - } - } - - void VulnerabilityViewController::Initialize() { - dispatch_async(dispatch_get_main_queue(), ^{ - // Create UI elements - CreateUI(); - }); - } - - void VulnerabilityViewController::SetScanButtonCallback(std::function callback) { - m_scanButtonCallback = callback; - } - - void VulnerabilityViewController::SetExploitButtonCallback( - std::function callback) { - m_exploitButtonCallback = callback; - } - - void VulnerabilityViewController::SetVulnerabilityDetector( - std::shared_ptr detector) { - m_vulnerabilityDetector = detector; - } - - void VulnerabilityViewController::StartScan(const std::string& path1, const std::string& path2) { - if (!m_vulnerabilityDetector || m_scanInProgress) { - return; - } - - m_scanInProgress = true; - UpdateProgress(0.0f, "Starting scan..."); - - // Clear previous results - { - std::lock_guard lock(m_vulnerabilitiesMutex); - m_vulnerabilities.clear(); - } - - // Update UI - UpdateUI(); - - // Start the scan in a background thread - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - // Create a game object (root object) for scanning - auto gameRoot = std::make_shared(); - gameRoot->m_name = "Game"; - gameRoot->m_className = "DataModel"; - gameRoot->m_path = "game"; - - // Set progress callback - auto progressCallback = [this](const AIFeatures::VulnerabilityDetection::VulnerabilityDetector::ScanProgress& progress) { - UpdateProgress(progress.m_progress, progress.m_currentActivity); - }; - - // Set completion callback - auto completeCallback = [this](const AIFeatures::VulnerabilityDetection::VulnerabilityDetector::ScanResult& result) { - // Save results - { - std::lock_guard lock(m_vulnerabilitiesMutex); - m_vulnerabilities = result.m_vulnerabilities; - } - - // Update UI on main thread - dispatch_async(dispatch_get_main_queue(), ^{ - m_scanInProgress = false; - UpdateUI(); - - // Show alert with results - UIViewController* viewController = (__bridge UIViewController*)m_viewController; - UIAlertController* alert = [UIAlertController - alertControllerWithTitle:@"Scan Complete" - message:[NSString stringWithFormat:@"Found %lu vulnerabilities", (unsigned long)result.m_vulnerabilities.size()] - preferredStyle:UIAlertControllerStyleAlert]; - - [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]]; - [viewController presentViewController:alert animated:YES completion:nil]; - }); - }; - - // Start the scan - std::string gameId = "Game-" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()); - std::string gameName = path1.empty() ? "Current Game" : path1; - - m_vulnerabilityDetector->StartScan(gameId, gameName, gameRoot, progressCallback, completeCallback); - }); - } - - void* VulnerabilityViewController::GetViewController() const { - return m_viewController; - } - - void VulnerabilityViewController::CreateUI() { - // Create the view controller - UIViewController* viewController = [[UIViewController alloc] init]; - viewController.view.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1.0]; - m_viewController = (__bridge_retained void*)viewController; - - // Create a container view - UIView* containerView = [[UIView alloc] initWithFrame:viewController.view.bounds]; - containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; - [viewController.view addSubview:containerView]; - - // Create scan button - UIButton* scanButton = [UIButton buttonWithType:UIButtonTypeSystem]; - scanButton.frame = CGRectMake(20, 20, 100, 40); - [scanButton setTitle:@"Scan" forState:UIControlStateNormal]; - scanButton.backgroundColor = [UIColor colorWithRed:0.2 green:0.6 blue:1.0 alpha:0.8]; - scanButton.layer.cornerRadius = 8.0; - [scanButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; - [containerView addSubview:scanButton]; - - // Set button action - [scanButton addTarget:nil action:@selector(scanButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; - - __weak typeof(self) weakSelf = (__bridge typeof(self))this; - IMP scanButtonAction = imp_implementationWithBlock(^(id _Nullable sender) { - if (weakSelf && weakSelf->m_scanButtonCallback) { - weakSelf->m_scanButtonCallback(); - } - }); - - class_addMethod([UIButton class], @selector(scanButtonTapped:), scanButtonAction, "v@:@"); - - m_scanButton = (__bridge_retained void*)scanButton; - - // Create progress indicator - UIProgressView* progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; - progressView.frame = CGRectMake(130, 40, containerView.bounds.size.width - 150, 20); - progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth; - progressView.progress = 0.0; - progressView.hidden = YES; - [containerView addSubview:progressView]; - - m_progressIndicator = (__bridge_retained void*)progressView; - - // Create table view for results - UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 70, - containerView.bounds.size.width - 40, - containerView.bounds.size.height - 270) - style:UITableViewStylePlain]; - tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; - tableView.backgroundColor = [UIColor colorWithWhite:0.15 alpha:1.0]; - tableView.layer.cornerRadius = 8.0; - tableView.layer.masksToBounds = YES; - [containerView addSubview:tableView]; - - // Set up table view - tableView.delegate = nil; - tableView.dataSource = nil; - - // Store the table view - m_resultsTableView = (__bridge_retained void*)tableView; - - // Create details view - UIView* detailsView = [[UIView alloc] initWithFrame:CGRectMake(20, containerView.bounds.size.height - 190, - containerView.bounds.size.width - 40, 180)]; - detailsView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin; - detailsView.backgroundColor = [UIColor colorWithWhite:0.15 alpha:1.0]; - detailsView.layer.cornerRadius = 8.0; - detailsView.layer.masksToBounds = YES; - [containerView addSubview:detailsView]; - - // Add labels to details view - UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, detailsView.bounds.size.width - 20, 30)]; - titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth; - titleLabel.text = @"Select a vulnerability"; - titleLabel.textColor = [UIColor whiteColor]; - titleLabel.font = [UIFont boldSystemFontOfSize:16.0]; - titleLabel.tag = 101; - [detailsView addSubview:titleLabel]; - - UILabel* descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, detailsView.bounds.size.width - 20, 60)]; - descriptionLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth; - descriptionLabel.text = @""; - descriptionLabel.textColor = [UIColor lightGrayColor]; - descriptionLabel.font = [UIFont systemFontOfSize:14.0]; - descriptionLabel.numberOfLines = 3; - descriptionLabel.tag = 102; - [detailsView addSubview:descriptionLabel]; - - UILabel* severityLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 150, 20)]; - severityLabel.text = @"Severity: N/A"; - severityLabel.textColor = [UIColor lightGrayColor]; - severityLabel.font = [UIFont systemFontOfSize:12.0]; - severityLabel.tag = 103; - [detailsView addSubview:severityLabel]; - - UILabel* reliabilityLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, 100, 150, 20)]; - reliabilityLabel.text = @"Reliability: N/A"; - reliabilityLabel.textColor = [UIColor lightGrayColor]; - reliabilityLabel.font = [UIFont systemFontOfSize:12.0]; - reliabilityLabel.tag = 104; - [detailsView addSubview:reliabilityLabel]; - - // Create exploit button - UIButton* exploitButton = [UIButton buttonWithType:UIButtonTypeSystem]; - exploitButton.frame = CGRectMake(detailsView.bounds.size.width - 110, 130, 100, 40); - exploitButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin; - [exploitButton setTitle:@"Exploit" forState:UIControlStateNormal]; - exploitButton.backgroundColor = [UIColor colorWithRed:0.8 green:0.2 blue:0.2 alpha:0.8]; - exploitButton.layer.cornerRadius = 8.0; - [exploitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; - exploitButton.enabled = NO; - exploitButton.tag = 105; - [detailsView addSubview:exploitButton]; - - // Set exploit button action - [exploitButton addTarget:nil action:@selector(exploitButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; - - IMP exploitButtonAction = imp_implementationWithBlock(^(id _Nullable sender) { - if (weakSelf && weakSelf->m_exploitButtonCallback && weakSelf->m_selectedVulnerabilityIndex >= 0) { - std::lock_guard lock(weakSelf->m_vulnerabilitiesMutex); - if (weakSelf->m_selectedVulnerabilityIndex < weakSelf->m_vulnerabilities.size()) { - weakSelf->m_exploitButtonCallback(weakSelf->m_vulnerabilities[weakSelf->m_selectedVulnerabilityIndex]); - } - } - }); - - class_addMethod([UIButton class], @selector(exploitButtonTapped:), exploitButtonAction, "v@:@"); - - m_exploitButton = (__bridge_retained void*)exploitButton; - m_detailsView = (__bridge_retained void*)detailsView; - - // Configure table view with data source and delegate - tableView.dataSource = [[VulnTableViewDataSource alloc] initWithViewController:(__bridge id)this]; - tableView.delegate = [[VulnTableViewDelegate alloc] initWithViewController:(__bridge id)this]; - - // Initial UI update - UpdateUI(); - } - - void VulnerabilityViewController::UpdateUI() { - dispatch_async(dispatch_get_main_queue(), ^{ - // Update scan button state - UIButton* scanButton = (__bridge UIButton*)m_scanButton; - scanButton.enabled = !m_scanInProgress; - scanButton.alpha = m_scanInProgress ? 0.5 : 1.0; - - // Update progress indicator - UIProgressView* progressView = (__bridge UIProgressView*)m_progressIndicator; - progressView.hidden = !m_scanInProgress; - progressView.progress = m_scanProgress; - - // Reload table view - UITableView* tableView = (__bridge UITableView*)m_resultsTableView; - [tableView reloadData]; - - // Update details view - if (m_selectedVulnerabilityIndex >= 0) { - ShowVulnerabilityDetails(m_selectedVulnerabilityIndex); - } else { - UIView* detailsView = (__bridge UIView*)m_detailsView; - UILabel* titleLabel = (UILabel*)[detailsView viewWithTag:101]; - UILabel* descriptionLabel = (UILabel*)[detailsView viewWithTag:102]; - UILabel* severityLabel = (UILabel*)[detailsView viewWithTag:103]; - UILabel* reliabilityLabel = (UILabel*)[detailsView viewWithTag:104]; - UIButton* exploitButton = (UIButton*)[detailsView viewWithTag:105]; - - titleLabel.text = @"Select a vulnerability"; - descriptionLabel.text = @""; - severityLabel.text = @"Severity: N/A"; - reliabilityLabel.text = @"Reliability: N/A"; - exploitButton.enabled = NO; - } - }); - } - - void VulnerabilityViewController::UpdateProgress(float progress, const std::string& status) { - m_scanProgress = progress; - - dispatch_async(dispatch_get_main_queue(), ^{ - UIProgressView* progressView = (__bridge UIProgressView*)m_progressIndicator; - progressView.progress = progress; - }); - } - - void VulnerabilityViewController::ShowVulnerabilityDetails(int index) { - std::lock_guard lock(m_vulnerabilitiesMutex); - - if (index < 0 || index >= m_vulnerabilities.size()) { - return; - } - - const auto& vulnerability = m_vulnerabilities[index]; - - dispatch_async(dispatch_get_main_queue(), ^{ - UIView* detailsView = (__bridge UIView*)m_detailsView; - UILabel* titleLabel = (UILabel*)[detailsView viewWithTag:101]; - UILabel* descriptionLabel = (UILabel*)[detailsView viewWithTag:102]; - UILabel* severityLabel = (UILabel*)[detailsView viewWithTag:103]; - UILabel* reliabilityLabel = (UILabel*)[detailsView viewWithTag:104]; - UIButton* exploitButton = (UIButton*)[detailsView viewWithTag:105]; - - titleLabel.text = [NSString stringWithUTF8String:vulnerability.m_name.c_str()]; - descriptionLabel.text = [NSString stringWithUTF8String:vulnerability.m_description.c_str()]; - - // Format severity with percentage - int severityPercent = static_cast(vulnerability.m_severity * 100); - severityLabel.text = [NSString stringWithFormat:@"Severity: %d%%", severityPercent]; - - // Format reliability with percentage - int reliabilityPercent = static_cast(vulnerability.m_reliability * 100); - reliabilityLabel.text = [NSString stringWithFormat:@"Reliability: %d%%", reliabilityPercent]; - - // Color code severity - if (vulnerability.m_severity >= 0.7f) { - severityLabel.textColor = [UIColor colorWithRed:1.0 green:0.3 blue:0.3 alpha:1.0]; - } else if (vulnerability.m_severity >= 0.4f) { - severityLabel.textColor = [UIColor colorWithRed:1.0 green:0.7 blue:0.3 alpha:1.0]; - } else { - severityLabel.textColor = [UIColor colorWithRed:0.3 green:0.7 blue:0.3 alpha:1.0]; - } - - // Enable exploit button - exploitButton.enabled = true; - }); - } - } -} - -// Objective-C helper classes for table view -@interface VulnTableViewDataSource : NSObject -- (instancetype)initWithViewController:(id)viewController; -@end - -@interface VulnTableViewDelegate : NSObject -- (instancetype)initWithViewController:(id)viewController; -@end - -@implementation VulnTableViewDataSource { - __unsafe_unretained iOS::UI::VulnerabilityViewController* _viewController; -} - -- (instancetype)initWithViewController:(id)viewController { - self = [super init]; - if (self) { - _viewController = (__bridge iOS::UI::VulnerabilityViewController*)viewController; - } - return self; -} - -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - std::lock_guard lock(_viewController->m_vulnerabilitiesMutex); - return _viewController->m_vulnerabilities.size(); -} - -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *cellId = @"VulnerabilityCell"; - UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId]; - - if (!cell) { - cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId]; - cell.backgroundColor = [UIColor clearColor]; - cell.textLabel.textColor = [UIColor whiteColor]; - cell.detailTextLabel.textColor = [UIColor lightGrayColor]; - } - - // Get vulnerability info - std::lock_guard lock(_viewController->m_vulnerabilitiesMutex); - if (indexPath.row < _viewController->m_vulnerabilities.size()) { - const auto& vulnerability = _viewController->m_vulnerabilities[indexPath.row]; - cell.textLabel.text = [NSString stringWithUTF8String:vulnerability.m_name.c_str()]; - - // Get type as string - std::string typeStr = iOS::AIFeatures::VulnerabilityDetection::VulnerabilityDetector::VulnerabilityTypeToString(vulnerability.m_type); - cell.detailTextLabel.text = [NSString stringWithFormat:@"Type: %s", typeStr.c_str()]; - - // Set cell color based on severity - UIView *bgView = [[UIView alloc] init]; - if (vulnerability.m_severity >= 0.7f) { - bgView.backgroundColor = [UIColor colorWithRed:0.5 green:0.0 blue:0.0 alpha:0.3]; - } else if (vulnerability.m_severity >= 0.4f) { - bgView.backgroundColor = [UIColor colorWithRed:0.5 green:0.3 blue:0.0 alpha:0.3]; - } else { - bgView.backgroundColor = [UIColor colorWithRed:0.0 green:0.3 blue:0.0 alpha:0.3]; - } - cell.selectedBackgroundView = bgView; - } - - return cell; -} - -@end - -@implementation VulnTableViewDelegate { - __unsafe_unretained iOS::UI::VulnerabilityViewController* _viewController; -} - -- (instancetype)initWithViewController:(id)viewController { - self = [super init]; - if (self) { - _viewController = (__bridge iOS::UI::VulnerabilityViewController*)viewController; - } - return self; -} - -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - _viewController->m_selectedVulnerabilityIndex = indexPath.row; - _viewController->ShowVulnerabilityDetails(indexPath.row); -} - -- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { - return 60.0f; -} - -@end diff --git a/source/cpp/ios/ui/VulnerabilityViewController.mm.orig b/source/cpp/ios/ui/VulnerabilityViewController.mm.orig deleted file mode 100644 index 47a0680..0000000 --- a/source/cpp/ios/ui/VulnerabilityViewController.mm.orig +++ /dev/null @@ -1,484 +0,0 @@ - -#include "../../ios_compat.h" -#include -#include -#include -#include -#include -#include -#include - -// Forward declaration -#include "../ai_features/vulnerability_detection/VulnerabilityDetector.h" - -namespace iOS { - namespace UI { - // UI for vulnerability detection - class VulnerabilityViewController { - private: - // Objective-C view controller - void* m_viewController; - - // UI elements - void* m_scanButton; - void* m_resultsTableView; - void* m_detailsView; - void* m_exploitButton; - void* m_progressIndicator; - - // Callbacks - std::function m_scanButtonCallback; - std::function m_exploitButtonCallback; - - // Data - std::shared_ptr m_vulnerabilityDetector; - std::vector m_vulnerabilities; - std::mutex m_vulnerabilitiesMutex; - bool m_scanInProgress; - float m_scanProgress; - - // Selected vulnerability - int m_selectedVulnerabilityIndex; - - public: - VulnerabilityViewController(); - ~VulnerabilityViewController(); - - void Initialize(); - void SetScanButtonCallback(std::function callback); - void SetExploitButtonCallback(std::function callback); - void SetVulnerabilityDetector(std::shared_ptr detector); - void StartScan(const std::string& path1, const std::string& path2); - void* GetViewController() const; - - private: - void CreateUI(); - void UpdateUI(); - void UpdateProgress(float progress, const std::string& status); - void ShowVulnerabilityDetails(int index); - }; - - // VulnerabilityViewController implementation - VulnerabilityViewController::VulnerabilityViewController() - : m_viewController(nullptr), - m_scanButton(nullptr), - m_resultsTableView(nullptr), - m_detailsView(nullptr), - m_exploitButton(nullptr), - m_progressIndicator(nullptr), - m_scanInProgress(false), - m_scanProgress(0.0f), - m_selectedVulnerabilityIndex(-1) { - } - - VulnerabilityViewController::~VulnerabilityViewController() { - // Release retained Objective-C objects - if (m_viewController) { - CFRelease(m_viewController); - m_viewController = nullptr; - } - } - - void VulnerabilityViewController::Initialize() { - dispatch_async(dispatch_get_main_queue(), ^{ - // Create UI elements - CreateUI(); - }); - } - - void VulnerabilityViewController::SetScanButtonCallback(std::function callback) { - m_scanButtonCallback = callback; - } - - void VulnerabilityViewController::SetExploitButtonCallback( - std::function callback) { - m_exploitButtonCallback = callback; - } - - void VulnerabilityViewController::SetVulnerabilityDetector( - std::shared_ptr detector) { - m_vulnerabilityDetector = detector; - } - - void VulnerabilityViewController::StartScan(const std::string& path1, const std::string& path2) { - if (!m_vulnerabilityDetector || m_scanInProgress) { - return; - } - - m_scanInProgress = true; - UpdateProgress(0.0f, "Starting scan..."); - - // Clear previous results - { - std::lock_guard lock(m_vulnerabilitiesMutex); - m_vulnerabilities.clear(); - } - - // Update UI - UpdateUI(); - - // Start the scan in a background thread - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - // Create a game object (root object) for scanning - auto gameRoot = std::make_shared(); - gameRoot->m_name = "Game"; - gameRoot->m_className = "DataModel"; - gameRoot->m_path = "game"; - - // Set progress callback - auto progressCallback = [this](const AIFeatures::VulnerabilityDetection::VulnerabilityDetector::ScanProgress& progress) { - UpdateProgress(progress.m_progress, progress.m_currentActivity); - }; - - // Set completion callback - auto completeCallback = [this](const AIFeatures::VulnerabilityDetection::VulnerabilityDetector::ScanResult& result) { - // Save results - { - std::lock_guard lock(m_vulnerabilitiesMutex); - m_vulnerabilities = result.m_vulnerabilities; - } - - // Update UI on main thread - dispatch_async(dispatch_get_main_queue(), ^{ - m_scanInProgress = false; - UpdateUI(); - - // Show alert with results - UIViewController* viewController = (__bridge UIViewController*)m_viewController; - UIAlertController* alert = [UIAlertController - alertControllerWithTitle:@"Scan Complete" - message:[NSString stringWithFormat:@"Found %lu vulnerabilities", (unsigned long)result.m_vulnerabilities.size()] - preferredStyle:UIAlertControllerStyleAlert]; - - [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]]; - [viewController presentViewController:alert animated:YES completion:nil]; - }); - }; - - // Start the scan - std::string gameId = "Game-" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()); - std::string gameName = path1.empty() ? "Current Game" : path1; - - m_vulnerabilityDetector->StartScan(gameId, gameName, gameRoot, progressCallback, completeCallback); - }); - } - - void* VulnerabilityViewController::GetViewController() const { - return m_viewController; - } - - void VulnerabilityViewController::CreateUI() { - // Create the view controller - UIViewController* viewController = [[UIViewController alloc] init]; - viewController.view.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1.0]; - m_viewController = (__bridge_retained void*)viewController; - - // Create a container view - UIView* containerView = [[UIView alloc] initWithFrame:viewController.view.bounds]; - containerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; - [viewController.view addSubview:containerView]; - - // Create scan button - UIButton* scanButton = [UIButton buttonWithType:UIButtonTypeSystem]; - scanButton.frame = CGRectMake(20, 20, 100, 40); - [scanButton setTitle:@"Scan" forState:UIControlStateNormal]; - scanButton.backgroundColor = [UIColor colorWithRed:0.2 green:0.6 blue:1.0 alpha:0.8]; - scanButton.layer.cornerRadius = 8.0; - [scanButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; - [containerView addSubview:scanButton]; - - // Set button action - [scanButton addTarget:nil action:@selector(scanButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; - - __weak typeof(self) weakSelf = (__bridge typeof(self))this; - IMP scanButtonAction = imp_implementationWithBlock(^(id _Nullable sender) { - if (weakSelf && weakSelf->m_scanButtonCallback) { - weakSelf->m_scanButtonCallback(); - } - }); - - class_addMethod([UIButton class], @selector(scanButtonTapped:), scanButtonAction, "v@:@"); - - m_scanButton = (__bridge_retained void*)scanButton; - - // Create progress indicator - UIProgressView* progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; - progressView.frame = CGRectMake(130, 40, containerView.bounds.size.width - 150, 20); - progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth; - progressView.progress = 0.0; - progressView.hidden = YES; - [containerView addSubview:progressView]; - - m_progressIndicator = (__bridge_retained void*)progressView; - - // Create table view for results - UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 70, - containerView.bounds.size.width - 40, - containerView.bounds.size.height - 270) - style:UITableViewStylePlain]; - tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; - tableView.backgroundColor = [UIColor colorWithWhite:0.15 alpha:1.0]; - tableView.layer.cornerRadius = 8.0; - tableView.layer.masksToBounds = YES; - [containerView addSubview:tableView]; - - // Set up table view - tableView.delegate = nil; - tableView.dataSource = nil; - - // Store the table view - m_resultsTableView = (__bridge_retained void*)tableView; - - // Create details view - UIView* detailsView = [[UIView alloc] initWithFrame:CGRectMake(20, containerView.bounds.size.height - 190, - containerView.bounds.size.width - 40, 180)]; - detailsView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin; - detailsView.backgroundColor = [UIColor colorWithWhite:0.15 alpha:1.0]; - detailsView.layer.cornerRadius = 8.0; - detailsView.layer.masksToBounds = YES; - [containerView addSubview:detailsView]; - - // Add labels to details view - UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, detailsView.bounds.size.width - 20, 30)]; - titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth; - titleLabel.text = @"Select a vulnerability"; - titleLabel.textColor = [UIColor whiteColor]; - titleLabel.font = [UIFont boldSystemFontOfSize:16.0]; - titleLabel.tag = 101; - [detailsView addSubview:titleLabel]; - - UILabel* descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 40, detailsView.bounds.size.width - 20, 60)]; - descriptionLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth; - descriptionLabel.text = @""; - descriptionLabel.textColor = [UIColor lightGrayColor]; - descriptionLabel.font = [UIFont systemFontOfSize:14.0]; - descriptionLabel.numberOfLines = 3; - descriptionLabel.tag = 102; - [detailsView addSubview:descriptionLabel]; - - UILabel* severityLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 150, 20)]; - severityLabel.text = @"Severity: N/A"; - severityLabel.textColor = [UIColor lightGrayColor]; - severityLabel.font = [UIFont systemFontOfSize:12.0]; - severityLabel.tag = 103; - [detailsView addSubview:severityLabel]; - - UILabel* reliabilityLabel = [[UILabel alloc] initWithFrame:CGRectMake(160, 100, 150, 20)]; - reliabilityLabel.text = @"Reliability: N/A"; - reliabilityLabel.textColor = [UIColor lightGrayColor]; - reliabilityLabel.font = [UIFont systemFontOfSize:12.0]; - reliabilityLabel.tag = 104; - [detailsView addSubview:reliabilityLabel]; - - // Create exploit button - UIButton* exploitButton = [UIButton buttonWithType:UIButtonTypeSystem]; - exploitButton.frame = CGRectMake(detailsView.bounds.size.width - 110, 130, 100, 40); - exploitButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin; - [exploitButton setTitle:@"Exploit" forState:UIControlStateNormal]; - exploitButton.backgroundColor = [UIColor colorWithRed:0.8 green:0.2 blue:0.2 alpha:0.8]; - exploitButton.layer.cornerRadius = 8.0; - [exploitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; - exploitButton.enabled = NO; - exploitButton.tag = 105; - [detailsView addSubview:exploitButton]; - - // Set exploit button action - [exploitButton addTarget:nil action:@selector(exploitButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; - - IMP exploitButtonAction = imp_implementationWithBlock(^(id _Nullable sender) { - if (weakSelf && weakSelf->m_exploitButtonCallback && weakSelf->m_selectedVulnerabilityIndex >= 0) { - std::lock_guard lock(weakSelf->m_vulnerabilitiesMutex); - if (weakSelf->m_selectedVulnerabilityIndex < weakSelf->m_vulnerabilities.size()) { - weakSelf->m_exploitButtonCallback(weakSelf->m_vulnerabilities[weakSelf->m_selectedVulnerabilityIndex]); - } - } - }); - - class_addMethod([UIButton class], @selector(exploitButtonTapped:), exploitButtonAction, "v@:@"); - - m_exploitButton = (__bridge_retained void*)exploitButton; - m_detailsView = (__bridge_retained void*)detailsView; - - // Configure table view with data source and delegate - tableView.dataSource = [[VulnTableViewDataSource alloc] initWithViewController:(__bridge id)this]; - tableView.delegate = [[VulnTableViewDelegate alloc] initWithViewController:(__bridge id)this]; - - // Initial UI update - UpdateUI(); - } - - void VulnerabilityViewController::UpdateUI() { - dispatch_async(dispatch_get_main_queue(), ^{ - // Update scan button state - UIButton* scanButton = (__bridge UIButton*)m_scanButton; - scanButton.enabled = !m_scanInProgress; - scanButton.alpha = m_scanInProgress ? 0.5 : 1.0; - - // Update progress indicator - UIProgressView* progressView = (__bridge UIProgressView*)m_progressIndicator; - progressView.hidden = !m_scanInProgress; - progressView.progress = m_scanProgress; - - // Reload table view - UITableView* tableView = (__bridge UITableView*)m_resultsTableView; - [tableView reloadData]; - - // Update details view - if (m_selectedVulnerabilityIndex >= 0) { - ShowVulnerabilityDetails(m_selectedVulnerabilityIndex); - } else { - UIView* detailsView = (__bridge UIView*)m_detailsView; - UILabel* titleLabel = (UILabel*)[detailsView viewWithTag:101]; - UILabel* descriptionLabel = (UILabel*)[detailsView viewWithTag:102]; - UILabel* severityLabel = (UILabel*)[detailsView viewWithTag:103]; - UILabel* reliabilityLabel = (UILabel*)[detailsView viewWithTag:104]; - UIButton* exploitButton = (UIButton*)[detailsView viewWithTag:105]; - - titleLabel.text = @"Select a vulnerability"; - descriptionLabel.text = @""; - severityLabel.text = @"Severity: N/A"; - reliabilityLabel.text = @"Reliability: N/A"; - exploitButton.enabled = NO; - } - }); - } - - void VulnerabilityViewController::UpdateProgress(float progress, const std::string& status) { - m_scanProgress = progress; - - dispatch_async(dispatch_get_main_queue(), ^{ - UIProgressView* progressView = (__bridge UIProgressView*)m_progressIndicator; - progressView.progress = progress; - }); - } - - void VulnerabilityViewController::ShowVulnerabilityDetails(int index) { - std::lock_guard lock(m_vulnerabilitiesMutex); - - if (index < 0 || index >= m_vulnerabilities.size()) { - return; - } - - const auto& vulnerability = m_vulnerabilities[index]; - - dispatch_async(dispatch_get_main_queue(), ^{ - UIView* detailsView = (__bridge UIView*)m_detailsView; - UILabel* titleLabel = (UILabel*)[detailsView viewWithTag:101]; - UILabel* descriptionLabel = (UILabel*)[detailsView viewWithTag:102]; - UILabel* severityLabel = (UILabel*)[detailsView viewWithTag:103]; - UILabel* reliabilityLabel = (UILabel*)[detailsView viewWithTag:104]; - UIButton* exploitButton = (UIButton*)[detailsView viewWithTag:105]; - - titleLabel.text = [NSString stringWithUTF8String:vulnerability.m_name.c_str()]; - descriptionLabel.text = [NSString stringWithUTF8String:vulnerability.m_description.c_str()]; - - // Format severity with percentage - int severityPercent = static_cast(vulnerability.m_severity * 100); - severityLabel.text = [NSString stringWithFormat:@"Severity: %d%%", severityPercent]; - - // Format reliability with percentage - int reliabilityPercent = static_cast(vulnerability.m_reliability * 100); - reliabilityLabel.text = [NSString stringWithFormat:@"Reliability: %d%%", reliabilityPercent]; - - // Color code severity - if (vulnerability.m_severity >= 0.7f) { - severityLabel.textColor = [UIColor colorWithRed:1.0 green:0.3 blue:0.3 alpha:1.0]; - } else if (vulnerability.m_severity >= 0.4f) { - severityLabel.textColor = [UIColor colorWithRed:1.0 green:0.7 blue:0.3 alpha:1.0]; - } else { - severityLabel.textColor = [UIColor colorWithRed:0.3 green:0.7 blue:0.3 alpha:1.0]; - } - - // Enable exploit button - exploitButton.enabled = true; - }); - } - } -} - -// Objective-C helper classes for table view -@interface VulnTableViewDataSource : NSObject -- (instancetype)initWithViewController:(id)viewController; -@end - -@interface VulnTableViewDelegate : NSObject -- (instancetype)initWithViewController:(id)viewController; -@end - -@implementation VulnTableViewDataSource { - __unsafe_unretained iOS::UI::VulnerabilityViewController* _viewController; -} - -- (instancetype)initWithViewController:(id)viewController { - self = [super init]; - if (self) { - _viewController = (__bridge iOS::UI::VulnerabilityViewController*)viewController; - } - return self; -} - -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { - std::lock_guard lock(_viewController->m_vulnerabilitiesMutex); - return _viewController->m_vulnerabilities.size(); -} - -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { - static NSString *cellId = @"VulnerabilityCell"; - UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId]; - - if (!cell) { - cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId]; - cell.backgroundColor = [UIColor clearColor]; - cell.textLabel.textColor = [UIColor whiteColor]; - cell.detailTextLabel.textColor = [UIColor lightGrayColor]; - } - - // Get vulnerability info - std::lock_guard lock(_viewController->m_vulnerabilitiesMutex); - if (indexPath.row < _viewController->m_vulnerabilities.size()) { - const auto& vulnerability = _viewController->m_vulnerabilities[indexPath.row]; - cell.textLabel.text = [NSString stringWithUTF8String:vulnerability.m_name.c_str()]; - - // Get type as string - std::string typeStr = iOS::AIFeatures::VulnerabilityDetection::VulnerabilityDetector::VulnerabilityTypeToString(vulnerability.m_type); - cell.detailTextLabel.text = [NSString stringWithFormat:@"Type: %s", typeStr.c_str()]; - - // Set cell color based on severity - UIView *bgView = [[UIView alloc] init]; - if (vulnerability.m_severity >= 0.7f) { - bgView.backgroundColor = [UIColor colorWithRed:0.5 green:0.0 blue:0.0 alpha:0.3]; - } else if (vulnerability.m_severity >= 0.4f) { - bgView.backgroundColor = [UIColor colorWithRed:0.5 green:0.3 blue:0.0 alpha:0.3]; - } else { - bgView.backgroundColor = [UIColor colorWithRed:0.0 green:0.3 blue:0.0 alpha:0.3]; - } - cell.selectedBackgroundView = bgView; - } - - return cell; -} - -@end - -@implementation VulnTableViewDelegate { - __unsafe_unretained iOS::UI::VulnerabilityViewController* _viewController; -} - -- (instancetype)initWithViewController:(id)viewController { - self = [super init]; - if (self) { - _viewController = (__bridge iOS::UI::VulnerabilityViewController*)viewController; - } - return self; -} - -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - _viewController->m_selectedVulnerabilityIndex = indexPath.row; - _viewController->ShowVulnerabilityDetails(indexPath.row); -} - -- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { - return 60.0f; -} - -@end diff --git a/source/cpp/ios/ui/VulnerabilityViewController_stub.mm b/source/cpp/ios/ui/VulnerabilityViewController_stub.mm deleted file mode 100644 index b19ade9..0000000 --- a/source/cpp/ios/ui/VulnerabilityViewController_stub.mm +++ /dev/null @@ -1,180 +0,0 @@ -// This is a stubbed version of VulnerabilityViewController.mm without the Objective-C runtime calls -// that are causing build issues. This maintains the basic structure while allowing the build to proceed. - -#include "../../ios_compat.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Forward declaration -#include "../ai_features/vulnerability_detection/VulnerabilityDetector.h" - -namespace iOS { - namespace UI { - // UI for vulnerability detection - class VulnerabilityViewController { - private: - // Objective-C view controller - void* m_viewController; - - // UI elements - void* m_scanButton; - void* m_resultsTableView; - void* m_detailsView; - void* m_exploitButton; - void* m_progressIndicator; - - // Callbacks - std::function m_scanButtonCallback; - std::function m_exploitButtonCallback; - - // Data - std::shared_ptr m_vulnerabilityDetector; - std::vector m_vulnerabilities; - std::mutex m_vulnerabilitiesMutex; - bool m_scanInProgress; - float m_scanProgress; - - // Selected vulnerability - int m_selectedVulnerabilityIndex; - - public: - VulnerabilityViewController(); - ~VulnerabilityViewController(); - - void Initialize(); - void SetScanButtonCallback(std::function callback); - void SetExploitButtonCallback(std::function callback); - void SetVulnerabilityDetector(std::shared_ptr detector); - void StartScan(const std::string& path1, [[maybe_unused]] const std::string& path2); - void* GetViewController() const; - - // Make members temporarily public to avoid access issues - friend class VulnTableViewDataSource; - friend class VulnTableViewDelegate; - - private: - void CreateUI(); - void UpdateUI(); - void UpdateProgress(float progress, [[maybe_unused]] const std::string& status); - void ShowVulnerabilityDetails(int index); - }; - - // Implementation stubs - VulnerabilityViewController::VulnerabilityViewController() - : m_viewController(nullptr), - m_scanButton(nullptr), - m_resultsTableView(nullptr), - m_detailsView(nullptr), - m_exploitButton(nullptr), - m_progressIndicator(nullptr), - m_scanInProgress(false), - m_scanProgress(0.0f), - m_selectedVulnerabilityIndex(-1) { - } - - VulnerabilityViewController::~VulnerabilityViewController() { - // Release retained Objective-C objects - if (m_viewController) { - // Stub implementation - m_viewController = nullptr; - } - } - - void VulnerabilityViewController::Initialize() { - // Stub implementation - // In a real app, this would create the UI elements - std::cout << "VulnerabilityViewController::Initialize() called (stub)" << std::endl; - } - - void VulnerabilityViewController::SetScanButtonCallback(std::function callback) { - m_scanButtonCallback = callback; - } - - void VulnerabilityViewController::SetExploitButtonCallback( - std::function callback) { - m_exploitButtonCallback = callback; - } - - void VulnerabilityViewController::SetVulnerabilityDetector( - std::shared_ptr detector) { - m_vulnerabilityDetector = detector; - } - - void VulnerabilityViewController::StartScan(const std::string& path1, [[maybe_unused]] const std::string& path2) { - if (!m_vulnerabilityDetector || m_scanInProgress) { - return; - } - - m_scanInProgress = true; - UpdateProgress(0.0f, "Starting scan..."); - - // Clear previous results - { - std::lock_guard lock(m_vulnerabilitiesMutex); - m_vulnerabilities.clear(); - } - - // Update UI - UpdateUI(); - - // Stub implementation for background scanning - std::cout << "Starting scan of " << path1 << "... (stub)" << std::endl; - - // Fake completing the scan after a moment - m_scanInProgress = false; - UpdateUI(); - } - - void* VulnerabilityViewController::GetViewController() const { - return m_viewController; - } - - void VulnerabilityViewController::CreateUI() { - // Stub implementation - std::cout << "VulnerabilityViewController::CreateUI() called (stub)" << std::endl; - } - - void VulnerabilityViewController::UpdateUI() { - // Stub implementation - std::cout << "VulnerabilityViewController::UpdateUI() called (stub)" << std::endl; - } - - void VulnerabilityViewController::UpdateProgress(float progress, [[maybe_unused]] const std::string& status) { - m_scanProgress = progress; - // Stub implementation - std::cout << "Scan progress: " << (progress * 100) << "% - " << status << std::endl; - } - - void VulnerabilityViewController::ShowVulnerabilityDetails(int index) { - std::lock_guard lock(m_vulnerabilitiesMutex); - - if (index < 0 || index >= (int)m_vulnerabilities.size()) { - return; - } - - // Stub implementation - std::cout << "Showing details for vulnerability " << index << std::endl; - } - } -} - -// Stub Objective-C helper classes - minimal implementation to allow compilation - -@interface VulnTableViewDataSource : NSObject -@end - -@interface VulnTableViewDelegate : NSObject -@end - -@implementation VulnTableViewDataSource -@end - -@implementation VulnTableViewDelegate -@end diff --git a/source/cpp/naming_conventions/naming_conventions.cpp.bak b/source/cpp/naming_conventions/naming_conventions.cpp.bak deleted file mode 100644 index e69de29..0000000 diff --git a/source/cpp/security/anti_tamper.hpp.cpp b/source/cpp/security/anti_tamper.hpp.cpp deleted file mode 100644 index 854700b..0000000 --- a/source/cpp/security/anti_tamper.hpp.cpp +++ /dev/null @@ -1,2 +0,0 @@ -// Completely empty file - only serves as a separate compilation unit -// No includes whatsoever to avoid any system header conflicts diff --git a/test_struct.cpp b/test_struct.cpp deleted file mode 100644 index d923bb8..0000000 --- a/test_struct.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include -#include -#include - -struct RequestResult { - bool m_success; // Request succeeded - int m_statusCode; // HTTP status code - std::string m_error; // Error message if any - std::string m_content; // Response content - uint64_t m_requestTime; // Request time in ms - std::unordered_map m_headers; // Response headers - - // Constructor for success case - RequestResult(bool success = false, int statusCode = 0, const std::string& error = "", - const std::string& content = "", uint64_t requestTime = 0) - : m_success(success), m_statusCode(statusCode), m_error(error), - m_content(content), m_requestTime(requestTime) {} -}; - -int main() { - printf("RequestResult structure layout:\n"); - printf("- m_success: %zu\n", offsetof(RequestResult, m_success)); - printf("- m_statusCode: %zu\n", offsetof(RequestResult, m_statusCode)); - printf("- m_error: %zu\n", offsetof(RequestResult, m_error)); - printf("- m_content: %zu\n", offsetof(RequestResult, m_content)); - printf("- m_requestTime: %zu\n", offsetof(RequestResult, m_requestTime)); - printf("- m_headers: %zu\n", offsetof(RequestResult, m_headers)); - return 0; -}