refactor: rewrite QueryService with Swift#1043
Merged
Conversation
This commit migrates the EZServiceTypes registry class from Objective-C to Swift as part of the project's ongoing Swift migration efforts. Key changes: - Replaces EZServiceTypes.h/.m with ServiceTypes.swift - Maintains API compatibility with existing Objective-C code using @objc attributes - Preserves singleton pattern and all public methods - Updates all import statements across the codebase - Modernizes implementation using Swift type safety and best practices The new Swift implementation provides identical functionality while enabling better integration with Swift services and improved type safety. The migration maintains full compatibility with existing Objective-C consumers.
… code This commit removes the deprecated EZDeepLTranslationAPI enumeration and all its related constants that were no longer being used in the codebase. The following items have been removed: - EZDeepLTranslationAPIKey constant - EZDeepLTranslationAPI enum with its values (WebFirst, OfficialFirst, OnlyOfficicial) - References to EZDeepLTranslationAPIKey from EZSchemeParser This cleanup helps reduce code complexity and removes dead code that was contributing to technical debt.
This commit refactors the EZAppModel class from Objective-C to Swift as part of the active migration effort to modernize the codebase. The Swift implementation provides enhanced type safety, proper documentation, and NSSecureCoding support. Key changes: - Migrated EZAppModel.h/m from objc/Legacy/ to Swift/Model/ - Added comprehensive documentation comments for all properties and methods - Implemented NSSecureCoding protocol for secure archiving - Added convenient dictionary conversion helpers for UserDefaults persistence - Maintained @objcMembers annotation to ensure Objective-C interoperability - Updated EZLocalStorage to use new Swift-based helper methods - Removed legacy MJExtension/KVC dependencies in favor of native Swift methods The refactoring maintains full backward compatibility while providing a cleaner, more maintainable Swift implementation that aligns with the project's migration goals.
This commit refactors class names to improve code clarity and follow Swift naming conventions. Key changes: - Renamed EZAppModel to AppTriggerConfig for more descriptive naming - Renamed ServiceTypes to QueryServiceFactory to better reflect its factory pattern - Updated all references across Swift and Objective-C files - Maintained @objc compatibility for Objective-C interoperability - Updated method signatures and type annotations consistently These renames make the codebase more self-documenting and align with Swift naming conventions where type names should clearly describe their purpose.
This commit migrates two critical storage classes from Objective-C to Swift, improving type safety and maintainability as part of the ongoing Swift migration effort. Key changes: - Migrated EZServiceInfo from Objective-C to Swift with Codable support - Migrated EZLocalStorage from Objective-C to Swift with modern property accessors - Added comprehensive documentation for all properties and methods - Maintained @objcMembers annotation for Objective-C interoperability - Updated bridging header to remove no longer needed imports - Moved Appearance-related utilities from Feature to Utility folder for better organization - Created EZAppModel.swift to bridge compatibility during the transition The Swift implementations provide enhanced type safety, better memory management, and improved maintainability while preserving full backward compatibility with existing Objective-C code.
…ing work This commit documents the significant progress made in December 2024 and December 2025 regarding the Swift migration effort. The documentation now reflects the completion of several major milestones. Key updates: - Added records for storage layer migration (EZServiceInfo, EZLocalStorage) completed on 2025-12-17 - Documented EZAppModel migration with NSSecureCoding support - Recorded ServiceTypes migration maintaining API compatibility - Updated infrastructure layer statistics to 100% completion (10/10 components) - Added class naming standardization and DeepL API cleanup records - Updated migration plan to reflect completed tasks - Updated last modified date to current date (2025-12-18)
…C to Swift This major refactoring migrates two critical core components from Objective-C to Swift, significantly advancing the project's Swift migration goals. QueryService Migration: - Created new QueryService.swift as the Swift base class for all translation services - Maintained @objcMembers annotation for seamless Objective-C interoperability - Preserved all public APIs and abstract methods for service implementations - Updated all 18+ service implementations to inherit from the new Swift base class - Removed old EZQueryService.h/.m files after successful migration BaiduService Migration: - Migrated EZBaiduTranslate from Objective-C to modern Swift implementation - Maintained complete feature parity including authentication, translation, and OCR - Improved code organization with clear MARK comments and documentation - Preserved complex MD5 sign generation and token acquisition logic - Updated configuration views to work with the new Swift service The refactoring eliminates 822 lines of Objective-C code while adding 786 lines of Swift, improving maintainability, type safety, and paving the way for future SwiftUI adoption.
This commit fixes various compiler warnings to improve code quality and maintainability. BaiduService improvements: - Fixed optional binding warnings in parseDictionaryResult method - Extracted complex dictionary parsing logic into separate helper methods: - appendTags(_:to:) for handling word tags - buildPhonetics(from:language:queryText:) for phonetic information - buildTranslateParts(from:) for translation parts - buildExchanges(from:) for word exchanges - buildSimpleWords(from:) for simplified related words - Improved code readability and maintainability by reducing method complexity - Fixed language code mapping warning with proper optional chaining QueryService improvements: - Added @discardableResult attribute to resetServiceResult() method to silence unused result warning Localization updates: - Updated extraction states for multiple localized strings in Localizable.xcstrings - Marked grammar-related strings (comparative, past_participle, plural, present_participle, root, singular, superlative) as "stale" for future extraction review These changes eliminate all compiler warnings while maintaining the exact same functionality, making the codebase cleaner and easier to maintain.
…flow This commit fixes a critical crash that could occur in the Apple Dictionary service when the `result` property is nil during text detection operations. Root cause: - The `detectText` method may call `queryEntryHTMLs(_:inDictionary:language:)` without setting the `result` property beforehand - The original code unconditionally assigned to `result?.innerTexts`, which could crash if result was nil Fix: - Added a safety check to ensure `result` is not nil before accessing its properties - Added clear documentation comment explaining why this check is necessary - This prevents the crash while maintaining the same functionality when result is properly initialized The change is minimal but critical for app stability, especially during edge cases in the text detection workflow.
…de length warning This commit addresses the Xcode code length warning by refactoring the large BaiduService class into smaller, more manageable files using Swift extensions. Refactoring details: - Created BaiduService+OCR.swift (113 lines) - Extracted OCR-related functionality including: - OCR request handling and response parsing - Image preprocessing and format conversion - OCR result processing and error handling - Created BaiduService+Parser.swift (193 lines) - Extracted dictionary parsing logic including: - Dictionary result parsing methods - Word phonetics, parts, and exchanges building - HTML and translation result handling - Reduced main BaiduService.swift from 786 to 472 lines (-314 lines) - Added all new files to the Xcode project Benefits: - Eliminates Xcode's "file too long" warning - Improves code organization and maintainability - Makes it easier to navigate and understand specific functionality - Follows Swift best practices for organizing large classes - Maintains all existing functionality without any behavioral changes The refactoring uses Swift's extension mechanism to logically separate concerns while keeping the API unchanged from external callers' perspective.
This commit fixes a compiler warning about the potentially uninitialized 'prehandled' variable in the QueryService+Request.swift file. The refactoring simplifies the control flow by: - Renaming 'prehandled' to 'isHandled' for clarity - Directly returning (true, result) in the completion handler instead of setting a flag - Using explicit boolean values (true/false) instead of the variable in the return statements This eliminates the "Variable 'prehandled' was possibly used uninitialized" warning while maintaining the same functionality.
This commit removes the deprecated Baidu web translation API implementation and streamlines the BaiduService architecture. Key changes: - Delete JavaScript files (baidu-translate-sign.js, bd.js) used for web API signature generation - Remove Objective-C response models (EZBaiduTranslateResponse.h/m) - Delete BaiduService+Parser.swift as it's no longer needed for the simplified API - Move BaiduApiResponse.swift and BaiduApiTranslate.swift from objc to Swift directory - Simplify BaiduService.swift by removing web translation logic and JSContext dependencies This refactor reduces code complexity by ~1000+ lines and removes dependency on web scraping techniques in favor of the official API approach.
This commit removes the API type picker from the Baidu Translate service configuration view. Since the recent refactor removed the wild web translation API and streamlined the service to use only the official API, the API type selection option is no longer necessary. This simplifies the user interface by removing a redundant configuration option. The change removes the StaticPickerCell that displayed ServiceAPIType.allCases options, making the configuration cleaner and more straightforward for users.
This commit fixes a crash that could occur when validating services in the settings page by ensuring the queryModel property is properly initialized and synchronized. The fix: - Changes queryModel from a stored property to a computed property with didSet observer - Automatically creates a new EZQueryModel instance when result is set but queryModel is nil - Synchronizes queryModel between result and the service instance This prevents nil queryModel crashes during service validation and ensures the service state remains consistent.
This commit modernizes the BaiduService by replacing the legacy AFNetworking library with the more modern Alamofire library. Key changes: - Replace AFHTTPSessionManager with AF.request and AF.upload methods - Use modern Alamofire syntax with .validate() and .responseJSON handlers - Implement proper multipart form data uploading for OCR functionality - Remove AFNetworking dependency in favor of Swift-native Alamofire This refactor improves code maintainability, type safety, and aligns with modern Swift networking practices while maintaining the same functionality.
…ling This commit replaces manual JSON parsing with Alamofire's type-safe decodable response handlers to resolve compiler warnings. Key changes: - Replace responseJSON with responseDecodable for type-safe JSON parsing - Add BaiduOcrResponse and BaiduOcrData structs for OCR API responses - Add BaiduDetectResponse struct for language detection API responses - Leverage Swift's Decodable protocol instead of manual dictionary casting This modernizes the codebase, eliminates compiler warnings, and improves type safety when handling API responses.
This commit modernizes the Baidu service by replacing completion handler-based asynchronous patterns with Swift's modern async/await syntax for OCR and language detection features. Changes: - Converted OCR text recognition from AF.upload response handlers to async/await - Converted language detection from AF.request response handlers to async/await - Improved error handling with proper do-catch blocks and typed error propagation - Enhanced code readability and maintainability by eliminating nested callback blocks - Added comprehensive error logging for decoding errors The refactoring maintains backward compatibility by preserving the existing completion handler-based public APIs while internally leveraging async/await for cleaner implementation.
This commit modernizes the BaiduApiTranslate implementation by replacing callback-based networking with async/await patterns. The changes include: - Replaced .responseDecodable completion handler with Task-based async implementation - Introduced .serializingDecodable for cleaner response handling - Added proper MainActor.run for UI updates from background tasks - Improved error handling with async/await do-catch blocks This migration improves code readability, reduces callback complexity, and aligns with modern Swift concurrency patterns.
This refactoring consolidates configuration UI logic by moving configurationListItems methods from separate ConfigurableService extensions back into their respective service classes. The changes include: - Moved configurationListItems implementations from 10 separate ConfigurableService extensions into their main service classes - Removed all ConfigurableService extension files (AliService+, BaiduTranslate+, etc.) - Updated QueryService base class to maintain consistent default implementation - Added proper Swift imports (SwiftUI) to service files for configuration views This consolidation improves code organization, reduces file fragmentation, and keeps configuration logic co-located with service implementations.
This commit adds ServiceTests to provide integration testing for all translation services in the Easydict app. The test suite includes: - A comprehensive suite that validates every registered translation service - Integration tests tagged for easy identification and running - Async validation support for modern Swift concurrency patterns - Special handling for AppleDictionary service with dictionary-specific validation - Continuation-based callback handling for services using legacy completion handlers The tests ensure that: - All services can be instantiated successfully - Each service performs basic translation without errors - Service validation catches common failures early - Test failures include detailed error messages for debugging
This commit modernizes the ServiceTests by replacing guard let statements with #require for cleaner test code. The changes include: - Replaced guard let pattern with #require for service instantiation - Removed manual error handling with Issue.record calls - Simplified validation logic while maintaining test coverage - Leveraged Testing framework's built-in failure handling This refactor makes the test code more concise and leverages Swift's modern testing features for better error reporting.
This commit fixes the exception handling issue in ServiceTests by properly using async throws pattern with try #require. The changes include: - Added 'throws' keyword to test function declaration for proper exception propagation - Wrapped service validation with try await to handle potential failures - Used try #require to properly handle service instantiation failures - Maintained test coverage while ensuring proper error handling This fix ensures that test failures are properly reported and exceptions don't cause silent test failures.
This commit updates the default endpoint URL for GitHub Models service to use the correct GitHub domain. The change includes: - Updated defaultEndpoint from `https://models.inference.ai.azure.com/chat/completions` to `https://models.github.ai/inference/chat/completions` - Ensures the service uses the official GitHub AI Models endpoint instead of the old Azure-based URL This fix ensures the GitHub Models service connects to the correct endpoint for AI model inference.
This commit updates Swift package dependencies to their latest compatible versions. The changes include: - AXSwift: Updated from version 0.3.4 to 0.3.6 - SelectedTextKit: Updated from branch main (commit f6c1574) to version 2.6.2 - Changed package requirement from branch-based to version-based for SelectedTextKit - Updated Xcode project references to match new dependency versions These updates ensure the project uses the latest stable versions of dependencies while maintaining compatibility.
This commit completes a major migration by replacing the Objective-C EZQueryResult with a modern Swift implementation, improving type safety and maintainability. Key changes include: - New Swift QueryResult class replacing EZQueryResult.h/.m - Migration of all service classes to use QueryResult instead of EZQueryResult - Updated bridging header to remove EZQueryResult.h import - Renamed and reorganized service models into Service/Model/ directory - Type signature updates across all translation services - Updated HTTP server integration to use new QueryResult type - Removed Objective-C QueryResult files (.h/.m) - Updated test suite to work with new QueryResult type This refactor eliminates the Objective-C dependency for query results, provides better Swift integration, and sets the foundation for future Swift-only development.
This commit reorganizes the EasydictTests directory structure for better code organization and maintainability. Key changes include: - Created logical directory hierarchy: Feature/, Service/, Utility/, Support/, Resources/ - Moved OCR tests to Feature/OCR/ with support files in Feature/OCR/Support/ - Organized service tests into Service/ directory (AppleLanguageDetectorTests, AppleServiceTests, ServiceTests) - Consolidated utility tests into Utility/ with subdirectories for String, Regex, and Extensions - Moved OCR test images to Resources/OCRImages/ with README.md documentation - Reorganized support files into Support/ directory - Updated Xcode project references to reflect new file locations - Renamed test groups to match new structure (StringTests -> String/) This reorganization improves test discoverability, groups related functionality, and provides a cleaner separation of concerns in the test suite.
This commit modernizes the translation services by replacing completion-based translate methods with Swift async/await pattern. Key changes include: - Replaced completion handlers in translate methods with async throws -> QueryResult - Updated all service implementations (Ali, Apple, Baidu, Bing, Caiyun, Google, NiuTrans, Tencent, Volcano) - Modified HTTP server extensions to use new async translate methods - Added async versions of detectText and ocr methods where needed - Maintained Objective-C compatibility by keeping original methods marked with @objc - Used withCheckedThrowingContinuation for seamless async/await conversion This refactor improves code readability, eliminates callback complexity, and enables better error handling with Swift's modern concurrency features.
This commit modernizes the test service validation by replacing completion-based translation with direct async calls. The changes include: - Updated validationResult(for:) to use the new async translate method instead of withCheckedContinuation - Simplified error handling by using Swift's async/await syntax - Removed manual continuation management and callback wrapping - Maintained test coverage while improving code clarity - Added proper error propagation for failed translations This refactor eliminates callback complexity, reduces test code verbosity, and aligns with the new async-based service architecture.
Add a new agent configuration file for generating Angular-style git commit messages. This agent guides the commit message generation process with clear steps for analyzing staged changes, drafting messages, and requesting user approval.
Remove `prehandleQueryText` and `translate` methods that are no longer needed. These methods provided Objective-C compatibility wrappers around the modern async/await implementation and are not used by any callers.
Refactor Ali, Caiyun, Tencent, and Volcano translation services to use async/await with Alamofire's `serializingDecodable` instead of the deprecated `responseDecodable` completion callback. This modernizes the service layer to leverage Swift's concurrency model and Alamofire 5.9+ async capabilities.
… services This commit completes the async migration by replacing completion-based method signatures with async equivalents across remaining service implementations. Key changes include: - Updated completion parameter names to completionHandler for better clarity - Removed wrapper methods in QueryService that converted async to completion - Simplified detectText implementations to use direct async calls - Updated Objective-C callers to use completionHandler naming convention - Reduced code complexity by eliminating Task bridges for simple methods - Maintained compatibility by preserving @objc markers on async methods This cleanup reduces method duplication, eliminates unnecessary Task wrappers, and completes the migration to Swift's native async/await pattern throughout the codebase.
…ecessary code - Remove duplicate textToAudio method implementations - Remove commented withCheckedThrowingContinuation code - Consolidate audio generation functionality - Clean up code structure and reduce redundancy
- Update variable declarations from 'var' to 'let' for immutable values in error handling - Fix unused comment removal in QueryService.swift - Add proper documentation for @unchecked Sendable in AppleDictionary - Improve code safety and eliminate compiler warnings
- Remove redundant 'dynamic' keywords from properties and methods - Clean up variable declarations while maintaining required dynamic behavior - Simplify code structure where dynamic dispatch is not required - Improve Swift performance by using static dispatch where possible
- Add @mainactor attribute to ServiceTabViewModel to ensure thread safety - Replace @published with explicit @mainactor for better actor isolation - Add proper Task wrapper for @onchange callbacks to prevent race conditions - Remove manual Task wrapping in .onReceive since @onchange handles it automatically - Eliminate SwiftUI publish change warnings by following proper actor patterns
- Add explicit GCD dispatch to main queue for UI property updates - Ensure UI modifications always happen on the main thread to avoid racing conditions - Wrap self.isPlaying assignment in proper queue dispatching - Resolve compiler warnings about background thread UI updates
- Add completion-based startQueryStream method to QueryService base class - Implement proper async-to-continuation bridging with MainActor dispatch - Remove duplicate cancelStream methods from service implementations - Update EZBaseQueryViewController to use startQueryStream for UI updates - Fix GeminiService and DoubaoService missing proper cancelStream overrides - Ensure streaming results are properly delivered to the main thread
- Replace deprecated EZServiceTypeKey with UserInfoKey.serviceType in all files - Remove unused EZServiceTypeKey declaration from Objective-C headers - Update ServiceTab and ServiceConfigurationSecretSectionView to use consistent key - Update EZBaseQueryViewController to use unified UserInfoKey - Eliminate key naming inconsistencies between Swift and Objective-C
This commit reorganizes the storage layer by moving storage-related files from the Objective-C ViewController directory to the Swift Service/Storage directory for better architecture alignment. Changes made: - Renamed EZLocalStorage.swift to LocalStorage.swift - Renamed EZServiceInfo.swift to QueryServiceConfiguration.swift - Renamed QueryServiceRecord.swift (already in correct location) - Updated QueryService.swift to use new class names - Updated all references in UI and configuration components - Modified Xcode project file to reflect file renames and new paths
…am services This commit fixes an issue where AutoCopy was being triggered multiple times during stream translations by ensuring it only executes when the stream has finished. The problem occurred because the completion handler was called multiple times during streaming, but AutoCopy should only happen once when the final result is available. The fix adds a condition to check if the service is not a stream service OR if the stream has finished before triggering AutoCopy.
This commit completes the migration of logging and device system utilities from Objective-C to Swift, improving type safety and maintainability while preserving Objective-C compatibility. Key changes: - Added Swift implementations in `Swift/Utility/Logging/` and `Swift/Utility/DeviceInfo/` - Removed legacy Objective-C source files from build phase - Updated all import statements to use `Easydict-Swift.h` bridge - Maintained `@objcMembers` decorators for existing API compatibility - Updated project configuration and migration documentation
This commit renames logging utility from EZLog to AnalyticsService to better reflect its primary purpose and improve code clarity. The changes include: - Renamed EZLog.swift to AnalyticsService.swift with class name AnalyticsService - Updated all Swift and Objective-C call sites to use the new name - Maintained @objc(EZAnalyticsService) for Objective-C compatibility - Updated project configuration and build references - Preserved all existing functionality while improving naming consistency
This commit completes the migration of the core query model from Objective-C to Swift, improving type safety and maintainability while preserving full API compatibility. Key changes: - Added Swift implementation in `Swift/Model/QueryModel.swift` with @objc(EZQueryModel) - Removed legacy Objective-C source files (EZQueryModel.h/.m) - Updated all header files to use forward declarations for cleaner imports - Maintained all existing properties, methods, and behavior - Integrated with Defaults publisher for language preference observation - Improved code structure with better property organization and documentation
This commit renames the core query model class from EZQueryModel to QueryModel as part of the Swift migration cleanup. The change affects the class name and its usage across all translation services, query service base classes, HTTP server routes, and the Xcode project configuration. This removes the legacy "EZ" prefix from the model name, making it consistent with other Swift model classes in the codebase. No functional changes are introduced, only the class name has been updated to maintain clean Swift conventions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
I continued to rewrite this project using Swift. This PR is further work on #1035, with the main changes being:
QueryServiceandQueryResultin Swift.I wrote a simple unit test, and it passed.
I also manually tested all query services via the UI, and they seem fine.
Most of the code was written by Codex +
gpt-5.1-codex-max/gpt-5.2-codex.This is currently my favorite AI programming way. I found Codex to be very suitable for writing Swift, recommend everyone to try it.