├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── Makefile ├── Package.resolved ├── Package.swift ├── README.md ├── Sources ├── AlfredEudicCLI │ ├── AlfredEudicApp.swift │ ├── Command │ │ ├── Command+Search.swift │ │ ├── Command+Update.swift │ │ └── Command.swift │ └── CommonTools.swift └── SimpleDictionaryCore │ ├── DictionaryManager.swift │ ├── Extension │ ├── Array.swift │ └── String.swift │ ├── PersistenceManager.swift │ ├── Resources │ └── words_alpha.txt │ ├── StardictDatabase.swift │ └── StardictEntry.swift ├── Tests └── AlfredEudicTests │ └── test.swift ├── icon.png ├── img ├── config-database.png ├── ecdict-search.png ├── hot-key-settings.png ├── search-selected.gif ├── simple-completion-search.png └── toggle-to-input.gif ├── info.plist └── src ├── main.rs ├── search_eudic.sh └── speak_eudic.sh /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | .DS_Store 3 | /target 4 | .idea 5 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "alfred-eudic-workflow" 7 | version = "0.1.0" 8 | dependencies = [ 9 | "serde", 10 | "serde_json", 11 | ] 12 | 13 | [[package]] 14 | name = "itoa" 15 | version = "1.0.14" 16 | source = "registry+https://github.com/rust-lang/crates.io-index" 17 | checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" 18 | 19 | [[package]] 20 | name = "memchr" 21 | version = "2.7.4" 22 | source = "registry+https://github.com/rust-lang/crates.io-index" 23 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 24 | 25 | [[package]] 26 | name = "proc-macro2" 27 | version = "1.0.92" 28 | source = "registry+https://github.com/rust-lang/crates.io-index" 29 | checksum = "37d3544b3f2748c54e147655edb5025752e2303145b5aefb3c3ea2c78b973bb0" 30 | dependencies = [ 31 | "unicode-ident", 32 | ] 33 | 34 | [[package]] 35 | name = "quote" 36 | version = "1.0.37" 37 | source = "registry+https://github.com/rust-lang/crates.io-index" 38 | checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" 39 | dependencies = [ 40 | "proc-macro2", 41 | ] 42 | 43 | [[package]] 44 | name = "ryu" 45 | version = "1.0.18" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" 48 | 49 | [[package]] 50 | name = "serde" 51 | version = "1.0.215" 52 | source = "registry+https://github.com/rust-lang/crates.io-index" 53 | checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" 54 | dependencies = [ 55 | "serde_derive", 56 | ] 57 | 58 | [[package]] 59 | name = "serde_derive" 60 | version = "1.0.215" 61 | source = "registry+https://github.com/rust-lang/crates.io-index" 62 | checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" 63 | dependencies = [ 64 | "proc-macro2", 65 | "quote", 66 | "syn", 67 | ] 68 | 69 | [[package]] 70 | name = "serde_json" 71 | version = "1.0.133" 72 | source = "registry+https://github.com/rust-lang/crates.io-index" 73 | checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" 74 | dependencies = [ 75 | "itoa", 76 | "memchr", 77 | "ryu", 78 | "serde", 79 | ] 80 | 81 | [[package]] 82 | name = "syn" 83 | version = "2.0.90" 84 | source = "registry+https://github.com/rust-lang/crates.io-index" 85 | checksum = "919d3b74a5dd0ccd15aeb8f93e7006bd9e14c295087c9896a110f490752bcf31" 86 | dependencies = [ 87 | "proc-macro2", 88 | "quote", 89 | "unicode-ident", 90 | ] 91 | 92 | [[package]] 93 | name = "unicode-ident" 94 | version = "1.0.14" 95 | source = "registry+https://github.com/rust-lang/crates.io-index" 96 | checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83" 97 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "alfred-eudic-workflow" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [dependencies] 7 | serde = { version = "1.0", features = ["derive"] } 8 | serde_json = "1.0" 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2020 HanleyLee 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL:=/usr/bin/env bash 2 | ALFRED_EUDIC_WORKFLOW="/Users/hanley/Library/Mobile Documents/com~apple~CloudDocs/ihanley/config/Alfred/Alfred.alfredpreferences/workflows/user.workflow.800F5D55-E73C-4C91-B86B-0A6D37216D19" 3 | 4 | .PHONY: all build install run clean 5 | all: build run 6 | 7 | build: 8 | # swift build -c release --build-path ".build" --target alfred-qsirch 9 | swift build -c release --build-path ".build" 10 | build-multiple-arch: 11 | swift build -c release --build-path ".build" --arch arm64 12 | swift build -c release --build-path ".build" --arch x86_64 13 | lipo -create -output ".build/release/alfred-eudic" ".build/arm64-apple-macosx/release/alfred-eudic" ".build/x86_64-apple-macosx/release/alfred-eudic" 14 | install: 15 | @install -D -m 755 .build/release/alfred-eudic $(ALFRED_EUDIC_WORKFLOW)/bin/alfred-eudic 16 | run: 17 | swift run --build-path .build alfred-qsirch search example 18 | clean: 19 | @rm -rf .build .swiftpm 20 | a: 21 | @echo "a is $$0" 22 | b: 23 | @echo "b is $$0" 24 | -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "originHash" : "624c705d658ddcb0cb3eabf6cd51cdc809b48eaf1f36722b222d2922347e9bda", 3 | "pins" : [ 4 | { 5 | "identity" : "sqlite.swift", 6 | "kind" : "remoteSourceControl", 7 | "location" : "https://github.com/stephencelis/SQLite.swift.git", 8 | "state" : { 9 | "revision" : "a95fc6df17d108bd99210db5e8a9bac90fe984b8", 10 | "version" : "0.15.3" 11 | } 12 | }, 13 | { 14 | "identity" : "swift-argument-parser", 15 | "kind" : "remoteSourceControl", 16 | "location" : "https://github.com/apple/swift-argument-parser.git", 17 | "state" : { 18 | "revision" : "41982a3656a71c768319979febd796c6fd111d5c", 19 | "version" : "1.5.0" 20 | } 21 | } 22 | ], 23 | "version" : 3 24 | } 25 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.10 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let isLocalDebug = true 7 | 8 | let dependency_AlfredWorkflowUtils: Package.Dependency = isLocalDebug ? 9 | .package(path: "../alfred-workflow-utils") : 10 | .package(url: "https://github.com/hanleylee/alfred-workflow-utils.git", .upToNextMajor(from: "0.0.1")) 11 | 12 | let package = Package( 13 | name: "alfred-eudic-workflow", 14 | platforms: [ 15 | .macOS(.v13), 16 | ], 17 | products: [ 18 | .executable(name: "alfred-eudic", targets: ["AlfredEudicCLI"]), 19 | ], 20 | dependencies: [ 21 | .package(url: "https://github.com/apple/swift-argument-parser.git", .upToNextMajor(from: "1.5.0")), 22 | .package(url: "https://github.com/stephencelis/SQLite.swift.git", from: "0.15.3"), 23 | dependency_AlfredWorkflowUtils, 24 | ], 25 | targets: [ 26 | .executableTarget( 27 | name: "AlfredEudicCLI", 28 | dependencies: [ 29 | "SimpleDictionaryCore", 30 | .product(name: "AlfredWorkflowUpdater", package: "alfred-workflow-utils"), 31 | .product(name: "AlfredWorkflowScriptFilter", package: "alfred-workflow-utils"), 32 | .product(name: "ArgumentParser", package: "swift-argument-parser"), 33 | ], 34 | path: "Sources/AlfredEudicCLI" 35 | ), 36 | .target( 37 | name: "SimpleDictionaryCore", 38 | dependencies: [ 39 | .product(name: "AlfredWorkflowUpdater", package: "alfred-workflow-utils"), 40 | .product(name: "SQLite", package: "SQLite.swift"), 41 | ], 42 | path: "Sources/SimpleDictionaryCore", 43 | resources: [ 44 | .process("Resources"), 45 | ] 46 | 47 | ), 48 | 49 | // MARK: - TEST - 50 | 51 | .testTarget( 52 | name: "AlfredEudicTests", 53 | dependencies: [ 54 | "SimpleDictionaryCore", 55 | ], 56 | path: "Tests/AlfredEudicTests" 57 | ), 58 | ] 59 | ) 60 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # alfred-eudic-workflow 2 | 3 | ![GitHub last commit](https://img.shields.io/github/last-commit/hanleylee/alfred-eudic-workflow) 4 | ![GitHub release (latest by date)](https://img.shields.io/github/v/release/hanleylee/alfred-eudic-workflow) 5 | ![GitHub](https://img.shields.io/github/license/hanleylee/alfred-eudic-workflow) 6 | 7 | 通过 **Alfred** + [ECDICT][ECDICT] + **Eudic** 快速查询 **当前已选择单词** 或 **搜索单词** 8 | 9 | ## 目标群体 10 | 11 | 同时使用 **Eudic** 及 **Alfred Power Pack** 的用户 12 | 13 | ## 安装 14 | 15 | 1. 进入 [Releases](https://github.com/hanleylee/alfred-eudic-workflow/releases) 界面下载最新版本的 `EudicSearch.alfredworkflow` 文件 16 | 2. 双击 `EudicSearch.alfredworkflow` 文件导入 Alfred 17 | 3. 进入`Alfred Preference` → `Workflow` → `Eudic Search`, 双击 `Hotkey` 设置启动本 Workflow 的快捷键, 建议设置为 `双击 ⌥ 键` 18 | 19 | ![hot-key](img/hot-key-settings.png) 20 | 21 | 4. 安装完成 22 | 23 | ## 使用 24 | 25 | ### 查询释义 26 | 27 | 1. **双击 ⌥ 键, 在有选择文本情况下直接使用选择文本进行查询, 无选择文本情况下进入自定义搜索界面** 28 | 29 | ![search-selected](img/search-selected.gif) 30 | 31 | 2. `Alfred` 搜索框中输入关键字 `e` 进行搜索 32 | 33 | ![toggle](img/toggle-to-input.gif) 34 | 35 | ### 朗读发音 36 | 37 | 搜索框激活情况下按下 `⌘ ⏎` 将由 `Eudic` 朗读单词发音 38 | 39 | ### 搜索列表 40 | 41 | 默认支持 *轻量搜索* - 使用内置轻量单词列表将前缀匹配项列出 42 | 43 | ![simple-completion-search](img/simple-completion-search.png) 44 | 45 | 同时支持用户配置 [ECDICT][ECDICT] 的 Sqlite 数据库替代默认 *轻量搜索*. 启用方式: 在 [Releases](https://github.com/hanleylee/alfred-eudic-workflow/releases) 界面下载 *ecdict.db* 文件, 并在 workflow 中配置 *Database* 值为该文件的本地路径 46 | 47 | ![config-database](img/config-database.png) 48 | 49 | ![ecdict-search](img/ecdict-search.png) 50 | 51 | ## Feature 52 | 53 | - [x] 支持 App Store 版本的 Lite 版本 (目前支持 **官网版本** 与 **App Store 专业版**) 54 | - [x] 支持内置单词列表进行前缀模糊匹配 55 | - [x] 支持配置 ECDICT 进行模糊匹配并实时展示解释 56 | - [x] 设置自动更新 57 | 58 | ## 参考 59 | 60 | - [wensonsmith/YoudaoTranslate](https://github.com/wensonsmith/YoudaoTranslate) 61 | - [ECDICT][ECDICT] 62 | 63 | ## 开源许可 64 | 65 | 本仓库的所有代码基于 [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) 进行分发与使用. 协议全文见 66 | [LICENSE](https://github.com/hanleylee/alfred-eudic-workflow/blob/master/LICENSE) 文件. 67 | 68 | Copyright 2021 HanleyLee 69 | 70 | --- 71 | 72 | 欢迎使用, 有任何 bug, 希望给我提 issues. 如果对你有用的话请标记一颗星星 ⭐️ 73 | 74 | [ECDICT]: https://github.com/skywind3000/ECDICT 75 | -------------------------------------------------------------------------------- /Sources/AlfredEudicCLI/AlfredEudicApp.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import QuartzCore 3 | 4 | @main 5 | struct AlfredEudicApp { 6 | static func main() async { 7 | await Command.main() 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Sources/AlfredEudicCLI/Command/Command+Search.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SearchCommand.swift 3 | // alfred-eudic-workflow 4 | // 5 | // Created by Hanley Lee on 2024/12/5. 6 | // 7 | 8 | import AlfredCore 9 | import AlfredWorkflowScriptFilter 10 | import AlfredWorkflowUpdaterCore 11 | import AppKit 12 | import ArgumentParser 13 | import Foundation 14 | import QuartzCore 15 | import SimpleDictionaryCore 16 | 17 | struct SearchCommand: AsyncParsableCommand { 18 | static let configuration = CommandConfiguration(commandName: "search", abstract: "Perform a search query", discussion: "") 19 | 20 | @Option(help: ArgumentHelp("The file used for provide completeion item")) 21 | var completionFile: String = ProcessInfo.processInfo.environment["ALFRED_EUDIC_COMPLETION_FILE"] ?? "" 22 | 23 | @Option(help: ArgumentHelp("The database file used for provide explaination")) 24 | var dbFile: String? = ProcessInfo.processInfo.environment["ALFRED_EUDIC_DATABASE_FILE"] 25 | 26 | @Argument(help: "Spell of the word you want to query") 27 | var spell: String = "are" 28 | 29 | let limit: Int = 30 30 | 31 | func validate() throws {} 32 | 33 | func run() async throws { 34 | guard spell.count > 1 else { 35 | ScriptFilter.item(Item(title: "Input more than one letter")) 36 | AlfredUtils.output(ScriptFilter.output()) 37 | return 38 | } 39 | 40 | let t1 = CACurrentMediaTime() 41 | let config = DictionaryConfig( 42 | completionFile: completionFile, 43 | dbFile: dbFile 44 | ) 45 | let dictionaryManager = DictionaryManager(config: config) 46 | 47 | var items: [Item] = [] 48 | 49 | items.insert(Item(title: spell).arg(spell).subtitle("Type enter to check in Eudic"), at: 0) 50 | 51 | if let dbFile = config.dbFile, !dbFile.isEmpty { // query database 52 | if FileManager.default.fileExists(atPath: dbFile) { 53 | let matches = dictionaryManager.findMatchesInDB(spells: spell.split(separator: " ").map { String($0) }, limit: limit) 54 | for entry in matches { 55 | let explainations = (entry.translation ?? entry.definition)?.components(separatedBy: .newlines).joined(separator: "; ") ?? "" 56 | let phonetic = entry.phonetic ?? "" 57 | let collinsRate = String(repeating: "⭐️", count: entry.collins ?? 0) 58 | var importanceInfo: [String] = [] 59 | if let collins = entry.collins { 60 | importanceInfo.append("COLLINS: \(collinsRate)") 61 | } 62 | if let _ = entry.oxford { 63 | importanceInfo.append("OXFORD 3000") 64 | } 65 | if let bnc = entry.bnc, bnc != 0 { 66 | importanceInfo.append("BNC: \(bnc)") 67 | } 68 | if let frq = entry.frq, frq != 0 { 69 | importanceInfo.append("COCA: \(frq)") 70 | } 71 | if let tagInfo = entry.tagInfo { 72 | importanceInfo.append(tagInfo) 73 | } 74 | let title = WorkflowUtils.alignedText(left: entry.word, right: "\(collinsRate)", component: .title) 75 | let subtitle = WorkflowUtils.alignedText(left: explainations, right: "\(phonetic)", component: .subtitle) 76 | items.append( 77 | Item(title: title) 78 | .subtitle(subtitle) 79 | .arg(entry.word) 80 | .mods( 81 | Cmd().subtitle(entry.exchangeInfo ?? ""), 82 | Alt().subtitle(importanceInfo.joined(separator: "; ")) 83 | ) 84 | ) 85 | } 86 | } else { 87 | items.append(Item(title: "dbFile not exist: \(dbFile)")) 88 | } 89 | } else { // query completion list 90 | let matches = await dictionaryManager.findMatchesInCompletion(spell: spell, limit: limit) 91 | 92 | for word in matches { 93 | items.append( 94 | Item(title: word) 95 | .arg(word) 96 | ) 97 | } 98 | } 99 | // if items.isEmpty || !items.contains(where: { $0.title.lowercased() == spell.lowercased() }) { 100 | // } 101 | items.forEach { ScriptFilter.item($0) } 102 | 103 | let t2 = CACurrentMediaTime() 104 | AlfredUtils.log("search time duration: \(t2 - t1)") 105 | 106 | let updater = Updater(githubRepo: CommonTools.githubRepo, workflowAssetName: CommonTools.workflowAssetName, checkInterval: 60*60*24) 107 | 108 | if let release = updater.latestReleaseInfo, let currentVersion = AlfredConst.workflowVersion { 109 | if currentVersion.compare(release.tagName, options: .numeric) == .orderedAscending { 110 | ScriptFilter.item( 111 | Item(title: "New version available on GitHub, type [Enter] to update") 112 | .subtitle("current version: \(currentVersion), remote version: \(release.tagName)") 113 | .arg("update") 114 | .variable(.init(name: "HAS_UPDATE", value: "1")) 115 | ) 116 | } 117 | } 118 | 119 | AlfredUtils.output(ScriptFilter.output()) 120 | 121 | if !updater.cacheValid() { 122 | AlfredUtils.log("cache invalid") 123 | checkForUpdateSilently() 124 | } 125 | } 126 | } 127 | 128 | extension SearchCommand { 129 | func checkForUpdateSilently() { 130 | do { 131 | let process = Process() 132 | let executablePath = CommandLine.arguments[0] 133 | // child process will exit if parent process exited, so we must use nohup to execute external command 134 | process.executableURL = URL(fileURLWithPath: "/usr/bin/nohup") 135 | process.arguments = [executablePath, "update", "--action", "check"] 136 | 137 | process.standardOutput = FileHandle(forWritingAtPath: "/dev/null") 138 | process.standardError = FileHandle(forWritingAtPath: "/dev/null") 139 | 140 | try process.run() 141 | // process.waitUntilExit() 142 | AlfredUtils.log("Update check completed in the background") 143 | } catch { 144 | AlfredUtils.log("Failed to start update process: \(error)") 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /Sources/AlfredEudicCLI/Command/Command+Update.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Command+Update.swift 3 | // alfred-eudic-workflow 4 | // 5 | // Created by Hanley Lee on 2024/12/10. 6 | // 7 | 8 | import Foundation 9 | import ArgumentParser 10 | import AlfredWorkflowUpdaterCore 11 | import AlfredWorkflowScriptFilter 12 | import AlfredCore 13 | 14 | struct UpdateCommand: AsyncParsableCommand { 15 | enum Action: String, ExpressibleByArgument { 16 | case check 17 | case open 18 | case download 19 | case update 20 | } 21 | 22 | static let configuration = CommandConfiguration(commandName: "update", abstract: "Update workflow", discussion: "") 23 | 24 | func run() async throws { 25 | let updater = Updater(githubRepo: CommonTools.githubRepo, workflowAssetName: CommonTools.workflowAssetName, checkInterval: 0) 26 | switch action { 27 | case .check: 28 | if let release = try await updater.check() { 29 | ScriptFilter.item( 30 | Item(title: "Latest version: \(release.tagName)") 31 | .subtitle("Current version is \(AlfredConst.workflowVersion ?? "None")") 32 | ) 33 | } 34 | case .open: 35 | try await updater.openLatestReleasePage() 36 | case .download: 37 | try await updater.downloadLatestRelease() 38 | case .update: 39 | try await updater.updateToLatest() 40 | } 41 | AlfredUtils.output(ScriptFilter.output()) 42 | } 43 | 44 | @Option(help: ArgumentHelp("Action used to update subcommand", valueName: "check|open|download|update")) 45 | var action: Action = .check 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Sources/AlfredEudicCLI/Command/Command.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Command.swift 3 | // alfred-eudic-workflow 4 | // 5 | // Created by Hanley Lee on 2024/12/5. 6 | // 7 | 8 | import ArgumentParser 9 | import SimpleDictionaryCore 10 | 11 | struct Command: AsyncParsableCommand { 12 | @OptionGroup() 13 | var options: Options 14 | 15 | static let configuration = CommandConfiguration( 16 | commandName: "alfred-eudic", 17 | abstract: "Tool used to quickly search matched words by partial query", 18 | discussion: "", 19 | subcommands: [ 20 | SearchCommand.self, 21 | UpdateCommand.self, 22 | ] 23 | ) 24 | 25 | func run() async throws { 26 | print("Main command run!") 27 | } 28 | } 29 | 30 | extension Command { 31 | struct Options: ParsableArguments { 32 | // MARK: - Package Loading 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Sources/AlfredEudicCLI/CommonTools.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CommonTools.swift 3 | // alfred-eudic-workflow 4 | // 5 | // Created by Hanley Lee on 2024/12/10. 6 | // 7 | 8 | struct CommonTools { 9 | static let githubRepo = "hanleylee/alfred-eudic-workflow" 10 | static let workflowAssetName = "EudicSearch.alfredworkflow" 11 | } 12 | -------------------------------------------------------------------------------- /Sources/SimpleDictionaryCore/DictionaryManager.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import QuartzCore 3 | import AlfredCore 4 | 5 | public struct DictionaryConfig { 6 | public let completionFile: String 7 | public let dbFile: String? 8 | public init(completionFile: String, dbFile: String?) { 9 | self.completionFile = completionFile 10 | self.dbFile = dbFile 11 | } 12 | } 13 | public class DictionaryManager { 14 | 15 | private let config: DictionaryConfig 16 | private var database: StardictDatabase? 17 | 18 | public init(config: DictionaryConfig) { 19 | self.config = config 20 | if let dbFile = config.dbFile, FileManager.default.fileExists(atPath: dbFile) { 21 | self.database = StardictDatabase(databasePath: dbFile) 22 | } 23 | } 24 | 25 | // MARK: - Must be invoked before call any other function 26 | 27 | public func findMatchesInDB(spells: [String], limit: Int = 10) -> [StardictEntry] { 28 | AlfredUtils.log("database file: \(config.dbFile ?? "")") 29 | guard let database else { return [] } 30 | let res = database.searchWord(spells, limit: limit) 31 | return res 32 | } 33 | 34 | public func findMatchesInCompletion(spell: String, limit: Int = 10) async -> [String] { 35 | AlfredUtils.log("completion file: \(config.completionFile)") 36 | let completionFileURL = URL(filePath: config.completionFile) 37 | let completionData = try! Data(contentsOf: completionFileURL) 38 | let completionContent = String(data: completionData, encoding: .utf8)! 39 | let completionWords = await completionContent.splitConcurrently() 40 | 41 | guard let beginIndex = completionWords.binarySearchMatchPrefix(target: spell) else { return [] } 42 | 43 | let prefixLen = spell.count 44 | // 从找到的位置向后最多查找 `capacity` 个元素 45 | var result: [String] = [] 46 | result.reserveCapacity(limit) // 提前分配空间 47 | 48 | for i in beginIndex ..< completionWords.endIndex { 49 | if completionWords[i].prefix(prefixLen) == spell { 50 | result.append(completionWords[i]) 51 | } 52 | if result.count == limit { 53 | return result 54 | } 55 | } 56 | return result 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /Sources/SimpleDictionaryCore/Extension/Array.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Array.swift 3 | // alfred-eudic-workflow 4 | // 5 | // Created by Hanley Lee on 2024/12/7. 6 | // 7 | 8 | extension Array where Element == String { 9 | // 二分查找匹配的索引 10 | func binarySearchMatchPrefix(target: String) -> Int? { 11 | var low = 0 12 | var high = count 13 | let prefixLen = target.count 14 | 15 | while low < high { 16 | let mid = (low + high) / 2 17 | let midStrPrefix = self[mid].prefix(prefixLen) 18 | 19 | if midStrPrefix == target { 20 | high = mid // 继续向左搜索 21 | } else if midStrPrefix < target { 22 | low = mid + 1 23 | } else if midStrPrefix > target { 24 | high = mid 25 | } 26 | } 27 | 28 | return low 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Sources/SimpleDictionaryCore/Extension/String.swift: -------------------------------------------------------------------------------- 1 | // 2 | // String.swift 3 | // alfred-eudic-workflow 4 | // 5 | // Created by Hanley Lee on 2024/12/7. 6 | // 7 | 8 | // 扩展:将字符串分块 9 | extension String { 10 | // FIXME: some words will lost because the boundary of chunk may break a completed word 11 | func splitConcurrently(chunkSize: Int = 10_000) async -> [String] { 12 | // 将输入字符串分割为小块 13 | let chunks = self.split(intoChunksOf: chunkSize) 14 | 15 | // 使用 Task 并发处理每个小块 16 | let results = await withTaskGroup(of: (Int, [String]).self) { group -> [String] in 17 | for (index, chunk) in chunks.enumerated() { 18 | group.addTask { 19 | // this place can't use parameter from outside, otherwise will be very slow 20 | (index, chunk.components(separatedBy: .newlines)) 21 | } 22 | } 23 | 24 | // 收集所有结果(带索引) 25 | var combinedResults: [(Int, [String])] = [] 26 | for await result in group { 27 | combinedResults.append(result) 28 | } 29 | 30 | // 按索引排序以确保顺序 31 | combinedResults.sort(by: { $0.0 < $1.0 }) 32 | 33 | // 合并排序后的结果 34 | return combinedResults.flatMap { $0.1 } 35 | } 36 | 37 | return results 38 | } 39 | 40 | func split(intoChunksOf chunkSize: Int) -> [String] { 41 | var chunks: [String] = [] 42 | var startIndex = self.startIndex 43 | 44 | while startIndex < self.endIndex { 45 | let endIndex = self.index(startIndex, offsetBy: chunkSize, limitedBy: self.endIndex) ?? self.endIndex 46 | let chunk = String(self[startIndex ..< endIndex]) 47 | chunks.append(chunk) 48 | startIndex = endIndex 49 | } 50 | 51 | return chunks 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Sources/SimpleDictionaryCore/PersistenceManager.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PersistenceManager.swift 3 | // alfred-eudic-workflow 4 | // 5 | // Created by Hanley Lee on 2024/12/7. 6 | // 7 | 8 | import AlfredCore 9 | import AlfredWorkflowUpdaterCore 10 | import CryptoKit 11 | import Foundation 12 | import QuartzCore 13 | 14 | public class PersistenceManager { 15 | public private(set) var allWords: [String] = [] 16 | private let config: DictionaryConfig 17 | 18 | private init(config: DictionaryConfig) { 19 | self.config = config 20 | let completionFileURL = URL(filePath: config.completionFile) 21 | let completionData = try! Data(contentsOf: completionFileURL) 22 | let completionContent = String(data: completionData, encoding: .utf8)! 23 | let completionWords = completionContent.components(separatedBy: .newlines) 24 | 25 | allWords = completionWords 26 | 27 | if hasCache() { 28 | allWords = wordsFromCache() 29 | } else { 30 | allWords = makeWordsCache() 31 | } 32 | // let newData = try! Data(contentsOf: URL(filePath: cachePath())) 33 | // let newWords: [String] = convert_to_array(from: newData) 34 | // let t2 = CACurrentMediaTime() 35 | // print("config time duration: \(t2 - t1)") 36 | 37 | #if DEBUG 38 | 39 | // let data1 = convert_to_data(from: self.allWords) 40 | // let t1 = CACurrentMediaTime() 41 | // let newWors: [String] = convert_to_array(from: data1, capacity: allWords.count) 42 | // print(newWors.count) 43 | // let t2 = CACurrentMediaTime() 44 | // print("duration of split string: \(t2 - t1)") 45 | #endif 46 | } 47 | 48 | func cachePath() -> String { 49 | let cacheRoot = URL(fileURLWithPath: AlfredConst.workflowCache!) 50 | var cacheFilename = "completion_cache_\(calculateFileMD5(at: config.completionFile)!)" 51 | if let dbFile = config.dbFile { 52 | cacheFilename.append("_db_cache_\(calculateFileMD5(at: dbFile)!)") 53 | } 54 | return cacheRoot.appendingPathComponent(cacheFilename).path 55 | } 56 | 57 | // func cacheSizeKey() -> String { 58 | // return "SIZE_\(cachePath())" 59 | // } 60 | // 61 | func hasCache() -> Bool { 62 | let cachePath = cachePath() 63 | return FileManager.default.fileExists(atPath: cachePath) 64 | } 65 | 66 | func makeWordsCache() -> [String] { 67 | let completionFileURL = URL(filePath: config.completionFile) 68 | let completionData = try! Data(contentsOf: completionFileURL) 69 | let completionContent = String(data: completionData, encoding: .utf8)! 70 | // FIXME: if array's string length greater than 15, it can't serialize to file 71 | let completionWords = completionContent.components(separatedBy: .newlines).map { String($0.prefix(16)) } 72 | let cachePath = cachePath() 73 | 74 | if let dbFile = config.dbFile { 75 | let database = StardictDatabase(databasePath: dbFile) 76 | let databaseAllWords = database.fetchAllWords().map { $0.sw } 77 | let allWords = (completionWords + databaseAllWords) 78 | let cacheData = convert_to_data(from: allWords) 79 | // let newWors: [String] = convert_to_array(from: cacheData, capacity: allWords.count) 80 | try! cacheData.write(to: URL(filePath: cachePath)) 81 | return allWords 82 | } else { 83 | let cacheData = convert_to_data(from: completionWords) 84 | try! cacheData.write(to: URL(filePath: cachePath)) 85 | return completionWords 86 | } 87 | } 88 | 89 | func wordsFromCache() -> [String] { 90 | let cachePath = cachePath() 91 | let cacheURL = URL(filePath: cachePath) 92 | let cacheData = try! Data(contentsOf: cacheURL) 93 | // let t1 = CACurrentMediaTime() 94 | let words: [String] = convert_to_array(from: cacheData) 95 | // let words = deserializeStringArray(from: cacheData) 96 | 97 | // let t2 = CACurrentMediaTime() 98 | // print("convert data to array: \(t2 - t1)") 99 | return words 100 | } 101 | 102 | /// 计算文件的 MD5 哈希值 103 | /// - Parameter filePath: 文件的路径 104 | /// - Returns: 文件的 MD5 值(十六进制字符串),如果文件不存在则返回 `nil` 105 | func calculateFileMD5(at filePath: String) -> String? { 106 | let fileURL = URL(fileURLWithPath: filePath) 107 | 108 | // 确保文件存在 109 | guard FileManager.default.fileExists(atPath: filePath) else { 110 | print("File does not exist at path: \(filePath)") 111 | return nil 112 | } 113 | 114 | do { 115 | // 读取文件数据 116 | let fileData = try Data(contentsOf: fileURL) 117 | 118 | // 使用 CryptoKit 计算 MD5 哈希值 119 | let hash = Insecure.MD5.hash(data: fileData) 120 | 121 | // 转换为十六进制字符串 122 | return hash.map { String(format: "%02hhx", $0) }.joined() 123 | } catch { 124 | print("Failed to read file or calculate MD5: \(error)") 125 | return nil 126 | } 127 | } 128 | } 129 | 130 | extension PersistenceManager { 131 | func convert_to_data(from array: [T]) -> Data { 132 | var p: UnsafeBufferPointer? = nil 133 | array.withUnsafeBufferPointer { p = $0 } 134 | guard p != nil else { 135 | return Data() 136 | } 137 | return Data(buffer: p!) 138 | } 139 | 140 | func convert_to_array(from data: Data) -> [T] { 141 | // let array = data.withUnsafeBytes { 142 | // (pointer: UnsafePointer) -> [T] in 143 | // let buffer = UnsafeBufferPointer(start: pointer, 144 | // count: data.count/MemoryLayout.size) 145 | // return Array(buffer) 146 | // } 147 | // return array 148 | 149 | let capacity = data.count / MemoryLayout.size 150 | let result = [T](unsafeUninitializedCapacity: capacity) { pointer, copied_count in 151 | let length_written = data.copyBytes(to: pointer) 152 | copied_count = length_written / MemoryLayout.size 153 | assert(copied_count == capacity) 154 | } 155 | return result 156 | } 157 | // 158 | // func serializeStringArray(_ array: [String]) -> Data { 159 | // var data = Data() 160 | // 161 | // // 写入字符串数组的长度 162 | // var count = UInt32(array.count) 163 | // data.append(UnsafeBufferPointer(start: &count, count: 1)) 164 | // 165 | // // 写入每个字符串的长度和内容 166 | // for string in array { 167 | // guard let utf8Data = string.data(using: .utf8) else { continue } 168 | // 169 | // var length = UInt32(utf8Data.count) 170 | // data.append(UnsafeBufferPointer(start: &length, count: 1)) 171 | // data.append(utf8Data) 172 | // } 173 | // 174 | // return data 175 | // } 176 | // 177 | //// func convert_to_array(from data: Data) -> [T] { 178 | //// let count = data.count / MemoryLayout.size 179 | //// var array = [T](repeating: T.init(), count: count) 180 | //// data.copyBytes(to: UnsafeMutableBufferPointer(start: &array, count: count)) 181 | //// return array 182 | //// } 183 | // 184 | //// func deserializeStringArray(from data: Data) -> [String] { 185 | //// var result: [String] = [] 186 | //// var offset = 0 187 | //// 188 | //// // 读取数组长度 189 | //// let count: UInt32 = data.withUnsafeBytes { 190 | //// $0.load(fromByteOffset: offset, as: UInt32.self) 191 | //// } 192 | //// offset += MemoryLayout.size 193 | //// 194 | //// // 读取每个字符串 195 | //// for _ in 0...size 201 | //// 202 | //// // 读取字符串内容 203 | //// let stringData = data.subdata(in: offset..("id") 17 | private let word = Expression("word") 18 | private let sw = Expression("sw") 19 | private let phonetic = Expression("phonetic") 20 | private let definition = Expression("definition") 21 | private let translation = Expression("translation") 22 | private let pos = Expression("pos") 23 | private let collins = Expression("collins") 24 | private let oxford = Expression("oxford") 25 | private let tag = Expression("tag") 26 | private let bnc = Expression("bnc") 27 | private let frq = Expression("frq") 28 | private let exchange = Expression("exchange") 29 | private let detail = Expression("detail") 30 | private let audio = Expression("audio") 31 | 32 | init(databasePath: String) { 33 | do { 34 | db = try Connection(databasePath) 35 | AlfredUtils.log("Connected to database at \(databasePath)") 36 | } catch { 37 | AlfredUtils.log("Unable to connect to database: \(error)") 38 | } 39 | } 40 | 41 | /// Fetch all words from the stardict table 42 | func fetchAllWords() -> [StardictEntry] { 43 | var results: [StardictEntry] = [] 44 | 45 | do { 46 | for row in try db!.prepare(stardict) { 47 | let entry = StardictEntry( 48 | id: row[id], 49 | word: row[word], 50 | sw: row[sw], 51 | phonetic: row[phonetic], 52 | definition: row[definition], 53 | translation: row[translation], 54 | pos: row[pos], 55 | collins: row[collins], 56 | oxford: row[oxford], 57 | tag: row[tag], 58 | bnc: row[bnc], 59 | frq: row[frq], 60 | exchange: row[exchange], 61 | detail: row[detail], 62 | audio: row[audio] 63 | ) 64 | results.append(entry) 65 | } 66 | } catch { 67 | AlfredUtils.log("Failed to fetch words: \(error)") 68 | } 69 | 70 | return results 71 | } 72 | 73 | /// Search for a word in the stardict table 74 | func searchWord(_ spells: [String], limit: Int) -> [StardictEntry] { 75 | guard !spells.isEmpty else { return [] } 76 | var results: [Row] = [] 77 | 78 | var searchQuery: Table = stardict.limit(limit) 79 | 80 | if spells.count == 1 { // only get items which begin with spell when spell doesn't contain space 81 | searchQuery = searchQuery.filter(sw.like("\(spells[0])%")) 82 | } else { 83 | spells.forEach { searchQuery = searchQuery.filter(sw.like("%\($0)%")) } 84 | } 85 | 86 | do { 87 | results += try db!.prepare(searchQuery) 88 | } catch { 89 | AlfredUtils.log("Failed to fetch prefix results: \(error)") 90 | } 91 | 92 | // if results.count < limit, spells.count == 1 { 93 | // let remainingCount = limit - results.count 94 | // 95 | // let finalQuery = stardict.filter(sw.like("%\(searchQuery)%")).limit(remainingCount) 96 | // do { 97 | // results += try db!.prepare(finalQuery) 98 | // } catch { 99 | // fputs("Failed to fetch prefix results: \(error)\n", stderr) 100 | // } 101 | // } 102 | 103 | var entries: [StardictEntry] = [] 104 | for row in results { 105 | let entry = StardictEntry( 106 | id: row[id], 107 | word: row[word], 108 | sw: row[sw], 109 | phonetic: row[phonetic], 110 | definition: row[definition], 111 | translation: row[translation], 112 | pos: row[pos], 113 | collins: row[collins], 114 | oxford: row[oxford], 115 | tag: row[tag], 116 | bnc: row[bnc], 117 | frq: row[frq], 118 | exchange: row[exchange], 119 | detail: row[detail], 120 | audio: row[audio] 121 | ) 122 | entries.append(entry) 123 | } 124 | 125 | return entries 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /Sources/SimpleDictionaryCore/StardictEntry.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Untitled.swift 3 | // alfred-eudic-workflow 4 | // 5 | // Created by Hanley Lee on 2024/12/7. 6 | // 7 | 8 | /// A structure to represent a single row in the `stardict` table 9 | public struct StardictEntry { 10 | public let id: Int 11 | public let word: String 12 | public let sw: String 13 | public let phonetic: String? 14 | public let definition: String? 15 | public let translation: String? 16 | public let pos: String? 17 | public let collins: Int? 18 | public let oxford: Int? 19 | public let tag: String? 20 | public let bnc: Int? 21 | public let frq: Int? 22 | public let exchange: String? 23 | public let detail: String? 24 | public let audio: String? 25 | } 26 | 27 | extension StardictEntry { 28 | /// parse exchange field, the format like `d:perceived/p:perceived/3:perceives/i:perceiving` 29 | public var exchangeInfo: String? { 30 | guard let exchange else { return nil } 31 | var infos: [String] = [] 32 | let pairs = exchange.split(separator: "/") 33 | for pair in pairs { 34 | let keyValue = pair.split(separator: ":") 35 | let (key, value) = (keyValue[0], keyValue[1]) 36 | switch key { 37 | case "p": infos.append("过去式: \(value)") 38 | case "d": infos.append("过去分词: \(value)") 39 | case "i": infos.append("现在分词: \(value)") 40 | case "3": infos.append("第三人称单数: \(value)") 41 | case "r": infos.append("形容词比较级: \(value)") 42 | case "t": infos.append("形容词最高级: \(value)") 43 | case "s": infos.append("名词复数形式: \(value)") 44 | case "0": infos.append("lemma: \(value)") 45 | case "1": infos.append("lemma transform: \(value)") 46 | default: break 47 | } 48 | } 49 | return infos.joined(separator: "; ") 50 | } 51 | 52 | public var tagInfo: String? { 53 | guard let tag else { return nil } 54 | let infos: [String] = tag.split(separator: " ").map { t in 55 | switch t { 56 | case "zk": return "中考" 57 | case "gk": return "高考" 58 | case "cet4": return "CET4" 59 | case "cet6": return "CET6" 60 | case "ky": return "考研" 61 | case "gre": return "GRE" 62 | case "toefl": return "TOEFL" 63 | case "ielts": return "IELTS" 64 | default: return "Unknown" 65 | } 66 | } 67 | 68 | return infos.joined(separator: "/") 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Tests/AlfredEudicTests/test.swift: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanleylee/alfred-eudic-workflow/cecb226b9f7e04dd11514505453f4b845b991336/Tests/AlfredEudicTests/test.swift -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanleylee/alfred-eudic-workflow/cecb226b9f7e04dd11514505453f4b845b991336/icon.png -------------------------------------------------------------------------------- /img/config-database.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanleylee/alfred-eudic-workflow/cecb226b9f7e04dd11514505453f4b845b991336/img/config-database.png -------------------------------------------------------------------------------- /img/ecdict-search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanleylee/alfred-eudic-workflow/cecb226b9f7e04dd11514505453f4b845b991336/img/ecdict-search.png -------------------------------------------------------------------------------- /img/hot-key-settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanleylee/alfred-eudic-workflow/cecb226b9f7e04dd11514505453f4b845b991336/img/hot-key-settings.png -------------------------------------------------------------------------------- /img/search-selected.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanleylee/alfred-eudic-workflow/cecb226b9f7e04dd11514505453f4b845b991336/img/search-selected.gif -------------------------------------------------------------------------------- /img/simple-completion-search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanleylee/alfred-eudic-workflow/cecb226b9f7e04dd11514505453f4b845b991336/img/simple-completion-search.png -------------------------------------------------------------------------------- /img/toggle-to-input.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hanleylee/alfred-eudic-workflow/cecb226b9f7e04dd11514505453f4b845b991336/img/toggle-to-input.gif -------------------------------------------------------------------------------- /info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | bundleid 6 | com.hanleylee.alfred-eudic-workflow 7 | category 8 | Productivity 9 | connections 10 | 11 | 138977FA-CDC3-4EA1-BFD6-97D2A311A279 12 | 13 | 14 | destinationuid 15 | 4F8275E3-7428-4CD8-95B7-867E906FB913 16 | modifiers 17 | 0 18 | modifiersubtext 19 | 20 | vitoclose 21 | 22 | 23 | 24 | 13EFA1A7-63E6-4CA5-A26B-D9A55C022DE9 25 | 26 | 27 | destinationuid 28 | EB8E8B57-E059-4F7D-BFC2-A555F9599BD5 29 | modifiers 30 | 0 31 | modifiersubtext 32 | 33 | vitoclose 34 | 35 | 36 | 37 | 422E2CC4-6F3A-4B69-B7ED-74EB1D2F6699 38 | 39 | 40 | destinationuid 41 | 9F015075-8754-4F33-B048-825D70D02947 42 | modifiers 43 | 0 44 | modifiersubtext 45 | 46 | sourceoutputuid 47 | 3C4D248D-11B5-4624-A4C1-114E06E04301 48 | vitoclose 49 | 50 | 51 | 52 | destinationuid 53 | FDDDC5DB-C1F9-46B9-A3F1-3B4FF2BED8C3 54 | modifiers 55 | 0 56 | modifiersubtext 57 | 58 | vitoclose 59 | 60 | 61 | 62 | 99F00F03-5A09-41BC-B609-D3E0EBED741F 63 | 64 | 65 | destinationuid 66 | 422E2CC4-6F3A-4B69-B7ED-74EB1D2F6699 67 | modifiers 68 | 0 69 | modifiersubtext 70 | 71 | vitoclose 72 | 73 | 74 | 75 | 9F015075-8754-4F33-B048-825D70D02947 76 | 77 | 78 | destinationuid 79 | B6D08E60-8060-4098-BB0F-33A8F4A94614 80 | modifiers 81 | 0 82 | modifiersubtext 83 | 84 | vitoclose 85 | 86 | 87 | 88 | destinationuid 89 | 551B6DD5-E891-46CF-8692-243A4AE4CBED 90 | modifiers 91 | 1048576 92 | modifiersubtext 93 | Speak 94 | vitoclose 95 | 96 | 97 | 98 | B6D08E60-8060-4098-BB0F-33A8F4A94614 99 | 100 | EAD07727-8ECB-4390-85F2-3B1F5FCC780C 101 | 102 | 103 | destinationuid 104 | 138977FA-CDC3-4EA1-BFD6-97D2A311A279 105 | modifiers 106 | 0 107 | modifiersubtext 108 | 109 | vitoclose 110 | 111 | 112 | 113 | EB8E8B57-E059-4F7D-BFC2-A555F9599BD5 114 | 115 | 116 | destinationuid 117 | EAD07727-8ECB-4390-85F2-3B1F5FCC780C 118 | modifiers 119 | 0 120 | modifiersubtext 121 | 122 | vitoclose 123 | 124 | 125 | 126 | 127 | createdby 128 | Hanley Lee 129 | description 130 | Search Eudic Translation 131 | disabled 132 | 133 | name 134 | EudicSearch 135 | objects 136 | 137 | 138 | config 139 | 140 | argumenttype 141 | 0 142 | keyword 143 | e 144 | subtext 145 | Search Eudic for “{query}...” 146 | text 147 | Search Eudic 148 | withspace 149 | 150 | 151 | type 152 | alfred.workflow.input.keyword 153 | uid 154 | 9F015075-8754-4F33-B048-825D70D02947 155 | version 156 | 1 157 | 158 | 159 | config 160 | 161 | concurrently 162 | 163 | escaping 164 | 102 165 | script 166 | ./src/search_eudic.sh "{query}" 167 | scriptargtype 168 | 0 169 | scriptfile 170 | 171 | type 172 | 0 173 | 174 | type 175 | alfred.workflow.action.script 176 | uid 177 | B6D08E60-8060-4098-BB0F-33A8F4A94614 178 | version 179 | 2 180 | 181 | 182 | config 183 | 184 | action 185 | 0 186 | argument 187 | 1 188 | focusedappvariable 189 | 190 | focusedappvariablename 191 | 192 | hotkey 193 | 49 194 | hotmod 195 | 524288 196 | hotstring 197 | Space 198 | leftcursor 199 | 200 | modsmode 201 | 0 202 | relatedAppsMode 203 | 0 204 | 205 | type 206 | alfred.workflow.trigger.hotkey 207 | uid 208 | 99F00F03-5A09-41BC-B609-D3E0EBED741F 209 | version 210 | 2 211 | 212 | 213 | config 214 | 215 | conditions 216 | 217 | 218 | inputstring 219 | 220 | matchcasesensitive 221 | 222 | matchmode 223 | 0 224 | matchstring 225 | 226 | outputlabel 227 | e 228 | uid 229 | 3C4D248D-11B5-4624-A4C1-114E06E04301 230 | 231 | 232 | elselabel 233 | else 234 | 235 | type 236 | alfred.workflow.utility.conditional 237 | uid 238 | 422E2CC4-6F3A-4B69-B7ED-74EB1D2F6699 239 | version 240 | 1 241 | 242 | 243 | config 244 | 245 | concurrently 246 | 247 | escaping 248 | 102 249 | script 250 | ./src/search_eudic.sh "{query}" 251 | scriptargtype 252 | 0 253 | scriptfile 254 | 255 | type 256 | 0 257 | 258 | type 259 | alfred.workflow.action.script 260 | uid 261 | FDDDC5DB-C1F9-46B9-A3F1-3B4FF2BED8C3 262 | version 263 | 2 264 | 265 | 266 | config 267 | 268 | concurrently 269 | 270 | escaping 271 | 102 272 | script 273 | ./src/speak_eudic.sh "{query}" 274 | scriptargtype 275 | 0 276 | scriptfile 277 | 278 | type 279 | 0 280 | 281 | type 282 | alfred.workflow.action.script 283 | uid 284 | 551B6DD5-E891-46CF-8692-243A4AE4CBED 285 | version 286 | 2 287 | 288 | 289 | config 290 | 291 | alfredfiltersresults 292 | 293 | alfredfiltersresultsmatchmode 294 | 0 295 | argumenttreatemptyqueryasnil 296 | 297 | argumenttrimmode 298 | 0 299 | argumenttype 300 | 2 301 | escaping 302 | 102 303 | queuedelaycustom 304 | 3 305 | queuedelayimmediatelyinitially 306 | 307 | queuedelaymode 308 | 0 309 | queuemode 310 | 1 311 | runningsubtext 312 | Fetching Github Release 313 | script 314 | <?php 315 | 316 | require('src/Updater.php'); 317 | 318 | $version = '1.0.0'; 319 | 320 | $updater = new Updater($version); 321 | 322 | echo $updater->fetchReleases(); 323 | 324 | ?> 325 | scriptargtype 326 | 1 327 | scriptfile 328 | 329 | subtext 330 | 331 | title 332 | Looking for latest version... 333 | type 334 | 1 335 | withspace 336 | 337 | 338 | type 339 | alfred.workflow.input.scriptfilter 340 | uid 341 | EB8E8B57-E059-4F7D-BFC2-A555F9599BD5 342 | version 343 | 3 344 | 345 | 346 | config 347 | 348 | openwith 349 | 350 | sourcefile 351 | ~/Downloads/EudicSearch.alfredworkflow 352 | 353 | type 354 | alfred.workflow.action.openfile 355 | uid 356 | 4F8275E3-7428-4CD8-95B7-867E906FB913 357 | version 358 | 3 359 | 360 | 361 | config 362 | 363 | browser 364 | 365 | spaces 366 | 367 | url 368 | {query} 369 | utf8 370 | 371 | 372 | type 373 | alfred.workflow.action.openurl 374 | uid 375 | EAD07727-8ECB-4390-85F2-3B1F5FCC780C 376 | version 377 | 1 378 | 379 | 380 | config 381 | 382 | argumenttype 383 | 2 384 | keyword 385 | update 386 | subtext 387 | Press Enter to Confirm 388 | text 389 | Update EudicSearch Workflow 390 | withspace 391 | 392 | 393 | type 394 | alfred.workflow.input.keyword 395 | uid 396 | 13EFA1A7-63E6-4CA5-A26B-D9A55C022DE9 397 | version 398 | 1 399 | 400 | 401 | config 402 | 403 | seconds 404 | 5 405 | 406 | type 407 | alfred.workflow.utility.delay 408 | uid 409 | 138977FA-CDC3-4EA1-BFD6-97D2A311A279 410 | version 411 | 1 412 | 413 | 414 | readme 415 | 通过 Alfred 与 Eudic 快速查询 当前已选择单词 或 搜索单词 416 | uidata 417 | 418 | 138977FA-CDC3-4EA1-BFD6-97D2A311A279 419 | 420 | xpos 421 | 660 422 | ypos 423 | 385 424 | 425 | 13EFA1A7-63E6-4CA5-A26B-D9A55C022DE9 426 | 427 | xpos 428 | 10 429 | ypos 430 | 355 431 | 432 | 422E2CC4-6F3A-4B69-B7ED-74EB1D2F6699 433 | 434 | xpos 435 | 230 436 | ypos 437 | 135 438 | 439 | 4F8275E3-7428-4CD8-95B7-867E906FB913 440 | 441 | xpos 442 | 780 443 | ypos 444 | 355 445 | 446 | 551B6DD5-E891-46CF-8692-243A4AE4CBED 447 | 448 | xpos 449 | 640 450 | ypos 451 | 165 452 | 453 | 99F00F03-5A09-41BC-B609-D3E0EBED741F 454 | 455 | xpos 456 | 10 457 | ypos 458 | 115 459 | 460 | 9F015075-8754-4F33-B048-825D70D02947 461 | 462 | xpos 463 | 360 464 | ypos 465 | 10 466 | 467 | B6D08E60-8060-4098-BB0F-33A8F4A94614 468 | 469 | xpos 470 | 590 471 | ypos 472 | 10 473 | 474 | EAD07727-8ECB-4390-85F2-3B1F5FCC780C 475 | 476 | xpos 477 | 430 478 | ypos 479 | 355 480 | 481 | EB8E8B57-E059-4F7D-BFC2-A555F9599BD5 482 | 483 | xpos 484 | 210 485 | ypos 486 | 355 487 | 488 | FDDDC5DB-C1F9-46B9-A3F1-3B4FF2BED8C3 489 | 490 | xpos 491 | 340 492 | ypos 493 | 160 494 | 495 | 496 | variablesdontexport 497 | 498 | version 499 | 1.4.0 500 | webaddress 501 | https://www.hanleylee.com 502 | 503 | 504 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | use serde::Deserialize; 2 | use std::collections::HashMap; 3 | use std::fs; 4 | 5 | #[derive(Debug, Deserialize)] 6 | struct AllWordsDictionary(HashMap>); 7 | 8 | fn main() { 9 | // JSON 文件路径 10 | let file_path = "all_words_dictionary.json"; 11 | 12 | // 读取 JSON 文件 13 | let json_data = fs::read_to_string(file_path).expect("Failed to read the JSON file"); 14 | 15 | // 反序列化 JSON 数据到 HashMap 16 | let dictionary: HashMap> = 17 | serde_json::from_str(&json_data).expect("Failed to parse JSON"); 18 | 19 | // 打印反序列化后的数据 20 | println!("Deserialized dictionary: {:?}", dictionary); 21 | 22 | // 示例:访问某个 key 的值 23 | if let Some(words) = dictionary.get("example_key") { 24 | println!("Words for 'example_key': {:?}", words); 25 | } else { 26 | println!("Key 'example_key' not found in the dictionary"); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/search_eudic.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | Eudic_ID=$(osascript -e 'id of app "Eudb_en_free"' 2>/dev/null) || \ 4 | Eudic_ID=$(osascript -e 'id of app "Eudb_en"' 2>/dev/null) || \ 5 | Eudic_ID=$(osascript -e 'id of app "Eudic"' 2>/dev/null) 6 | 7 | if [[ -z "$Eudic_ID" ]]; then 8 | osascript </dev/null) || \ 3 | Eudic_ID=$(osascript -e 'id of app "Eudb_en"' 2>/dev/null) || \ 4 | Eudic_ID=$(osascript -e 'id of app "Eudic"' 2>/dev/null) 5 | 6 | if [[ -z "$Eudic_ID" ]]; then 7 | osascript <