Skip to content

Commit

Permalink
Renovation & Change license to LGPLv3.
Browse files Browse the repository at this point in the history
Remove dedicated StableSort API.

- Swift 5 and 6 always stable-sort things by default. According to Xcode documentation: "The sorting algorithm is guaranteed to be stable. A stable sort preserves the relative order of elements for which areInIncreasingOrder does not establish an order."

P.S.: The C# version (TekkonNT) still keeps the dedicated stable-sort API since its default sorting API only stable-sorts for dotNET 5 and later.

Node // Optimize .contextRange().

SpanUnit // Drop unused APIs.

Compositor // Use a final class instead.

Compositor // Simplify .clear().

Update .gitignore

Compositor // Trim useless APIs.

Compositor // Fix an issue with copy.

Compositor // Fixing unit tests.

Make maxSpanLength thread-safe.

Compositor // Mark theSeparator as `nonisolated`.

CompositorConfig // Add .clear().

Compositor // Content consolidation.

CompositorConfig // Drop invalid notes after changing maxSpanLength.

Optimize the use of ranges.

CompositorConfig // Update documentation.

Compositor // Fix update(updateExisting: true).

Compositor // Deprecating LangModelRanked.

CompositorConfig // Conforming to Equatable.

Repo // Update Hashable conformation.

Unit Tests // Renovation.

Fix LICENSE format.
  • Loading branch information
ShikiSuen committed Feb 18, 2025
1 parent 29f91ad commit 6df1b89
Show file tree
Hide file tree
Showing 18 changed files with 1,481 additions and 1,259 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,4 @@ _TeamCity*
_UpgradeReport_Files/
__pycache__/
~$*
.index-build/
23 changes: 23 additions & 0 deletions CUSTOM_LGPLv3_EXCEPTION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Custom Exception to LGPLv3 for Swift Package

This Swift package is licensed under the GNU Lesser General Public License version 3 (LGPLv3) with the following additional permission:

### Additional Permission under LGPLv3 Section 7

Notwithstanding any other provision of the LGPLv3, you have permission to link or combine this Swift package ("Package") with other modules to produce an executable, regardless of the code signing requirements imposed by Apple Inc. Specifically, if you use this Package in an Xcode project, you are not required to designate a paid Apple Developer ID to sign the resulting dynamic library when building and distributing the executable.

You are still required to comply with all other terms of the LGPLv3 in all respects for all of the code used other than the Package. If you modify this Package, you may extend this exception to your version of the Package, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version.

This Additional Permission applies only to the code released with this Package under LGPLv3 and does not extend to any other code or libraries it interacts with.

### How to Apply This Exception

To apply this exception, you must include a copy of this document and ensure that it is referenced in your project's licensing documentation. This ensures that users of your Swift package and any derivative works are aware of the additional permission granted by this exception.

### Example Usage

Include the following notice in your project’s documentation:

```
This project includes a Swift package licensed under LGPLv3 with an additional permission granted to allow linking and combining with other modules without requiring a paid Apple Developer ID for code signing. For details, see the CUSTOM_LGPLv3_EXCEPTION.md file included with this project.
```
187 changes: 165 additions & 22 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,22 +1,165 @@
MIT License

Copyright (c) 2022 and onwards Lukhnos Liu for upstream contents.
Copyright (c) 2022 and onwards The vChewing Project for Megrez-specific changes.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007

Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.


This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.

0. Additional Definitions.

As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.

"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.

An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.

A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".

The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.

The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.

1. Exception to Section 3 of the GNU GPL.

You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.

2. Conveying Modified Versions.

If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:

a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or

b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.

3. Object Code Incorporating Material from Library Header Files.

The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:

a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.

b) Accompany the object code with a copy of the GNU GPL and this license
document.

4. Combined Works.

You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:

a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.

b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.

c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.

d) Do one of the following:

0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.

1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.

e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)

5. Combined Libraries.

You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:

a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.

b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.

6. Revised Versions of the GNU Lesser General Public License.

The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.

If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
130 changes: 13 additions & 117 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,129 +5,25 @@

> 該引擎已經實裝於基於純 Swift 語言完成的 **威注音輸入法** 內,歡迎好奇者嘗試:[GitHub](https://github.com/vChewing/vChewing-macOS ) | [Gitee](https://gitee.com/vchewing/vChewing-macOS )
天權星引擎是用來處理輸入法語彙庫的一個模組。該倉庫乃威注音專案的弒神行動(Operation Longinus)的一部分。
天權星引擎是用來處理輸入法語彙庫的一個模組。

Megrez Engine is a module made for processing lingual data of an input method. This repository is part of Operation Longinus of The vChewing Project.
Megrez Engine is a module made for processing lingual data of an input method.

## 與 Gramambular 2 的區別
## 專案特色

敝專案一開始是 Gramambular 2 (Lukhnos Liu 著,MIT License) 的 Swift 實作,但經歷了大量修改。主要區別如下:

- 原生 Swift 實作,擁有完備的 Swift 5.3 ~ 5.9 支援、也可以用作任何 Swift 6 專案的相依套件(需使用者自行處理對跨執行緒安全性的需求)
- API 經過重新設計,以陣列的形式處理輸入的 key。而且,在獲取候選字詞內容的時候,也可以徹底篩除橫跨游標的詞
- 爬軌算法(Walking Algorithm)改為 Dijkstra 的算法,且經過效能最佳化處理、擁有比 DAG-Relax 算法更優的效能。
- 原生 Swift 實作,擁有完備的 Swift 5.3 ~ 5.9 支援、也可以用作任何 Swift 6 專案的相依套件。
- 注意:`Megrez.Compositor.theSeparator` **沒有多執行緒安全性**。對該 API 的保留乃是出於相容性之考量。新專案請避免使用該 static API。
- 以陣列的形式處理輸入的 key
- 在獲取候選字詞內容的時候,不會出現橫跨游標的詞
- 使用經過效能最佳化處理的 Dijkstra 的算法,擁有比 DAG-Relax 算法更優的效能。

## 使用說明

### §1. 初期化

在你的 IMKInputController 或者 InputHandler 內初期化一份 Megrez.Compositor 組字器副本(這裡將該副本命名為「`compositor`」)。由於 Megrez.Compositor 的型別是 Struct 型別(為了讓 Compositor 可以 deep copy),所以其副本可以用 var 來宣告。

以 InputHandler 為例:
```swift
class InputHandler {
// 先設定好變數
var compositor: Megrez.Compositor = .init()
...
}
```

以 IMKInputController 為例:
```swift
@objc(IMKMyInputController) // 根據 info.plist 內的情況來確定型別的命名
class IMKMyInputController: IMKInputController {
// 先設定好變數
var compositor: Megrez.Compositor = .init()
...
}
```

由於 Swift 會在某個大副本(InputHandler 或者 IMKInputController 副本)被銷毀的時候自動銷毀其中的全部副本,所以 Megrez.Compositor 的副本初期化沒必要寫在 init() 當中。但你很可能會想在 init() 時指定 Tekkon.Composer 所對接的語言模組型別、以及其可以允許的最大詞長。

這裡就需要在 init() 時使用參數:
```swift
/// 組字器。
/// - Parameters:
/// - lm: 語言模型。可以是任何基於 Megrez.LangModel 的衍生型別。
/// - length: 指定該組字器內可以允許的最大詞長,預設為 10 字。
/// - separator: 多字讀音鍵當中用以分割漢字讀音的記號,預設為空。
var compositor: Megrez.Compositor = .init(lm: lmTest, length: 13, separator: "-")
```

### §2. 使用範例

請結合 MegrezTests.swift 檔案來學習。這裡只是給個概述。

#### // 1. 準備用作語言模型的專用型別

首先,Megrez 內建的 LangModel 型別是遠遠不夠用的,只能說是個類似於 protocol 一樣的存在。你需要自己單獨寫一個新的衍生型別:

```swift
class ExampleLM: Megrez.LangModel {
...
override func unigramsFor(keyArray: [String]) -> [Megrez.Unigram] {
...
}
...
}
```

這個型別需要下述兩個函式能夠針對給定的鍵回饋對應的資料值、或其存無狀態:
- unigramsFor(keyArray: [String]) -> [Megrez.Unigram]
- hasUnigramsFor(keyArray: [String]) -> Bool

MegrezTests.swift 檔案內的 SimpleLM 可以作為範例。

至於該檔案內的 FiniteStateMachine 則是一個「一次性讀取檔案/大字串且分析資料」的範例。

如果需要更實戰的範例的話,可以洽威注音專案的倉庫內的 LMInstantiator.swift 及其關聯檔案。

#### // 2. 怎樣與 compositor 互動:

這裡只講幾個常用函式:

- 游標位置 `compositor.cursorIndex` 是可以賦值與取值的動態變數,且會在賦值內容為超出位置範圍的數值時自動修正。初期值為 0。
- `compositor.insertKey("gao1")` 可以在當前的游標位置插入讀音「gao1」。
- `compositor.dropKey(direction: .front)` 的作用是:朝著往文字輸入方向、砍掉一個與游標相鄰的讀音。反之,`dropKey(direction: .rear)` 則朝著與文字輸入方向相反的方向、砍掉一個與游標相鄰的讀音。
- 在威注音的術語體系當中,「文字輸入方向」為向前(Front)、與此相反的方向為向後(Rear)。
- `compositor.overrideCandidate(.init(keyArray: ["讀音"], value: "候選字"), at: 游標位置, overrideType: 覆寫模式)` 用來根據輸入法選中的候選字詞、據此更新當前游標位置選中的候選字詞節點當中的候選字詞。

輸入完內容之後,可以聲明一個用來接收結果的變數:

```swift
/// 對已給定的軌格按照給定的位置與條件進行正向爬軌。
var walked = compositor.walk()
```

MegrezTests.swift 是輸入了很多內容之後再 walk 的。實際上一款輸入法會在你每次插入讀音或刪除讀音的時候都重新 walk。那些處於候選字詞鎖定狀態的節點不會再受到之後的 walk 的行為的影響,但除此之外的節點會因為每次 walk 而可能各自的候選字詞會出現自動變化。如果給了 nodesLimit 一個非零的數值的話,則 walk 的範圍外的節點不會受到影響。

walk 之後的取值的方法及利用方法可以有很多種。這裡有其中的一個:

```swift
var composed: [String] = walked.map(\.value)
print(composed)
```

類似於:

```swift
for phrase in walked {
composed.append(phrase.value)
}
print(composed)
```

上述 print 結果就是 compositor 目前的組句,是這種陣列格式(以吳宗憲的詩句為例):
```swift
["八月", "中秋", "山林", "", "風吹", "大地", "草枝", ""]
```

自己看 MegrezTests.swift 慢慢研究吧。
`MegrezTests.swift` 展示了詳細的使用方法。

## 著作權 (Credits)

- Swiftified and further development by (c) 2022 and onwards The vChewing Project (MIT License).
- Swift programmer: Shiki Suen
- Was initially rebranded from (c) Lukhnos Liu's C++ library "Gramambular 2" (MIT License).
- Walking algorithm (Dijkstra) implemented by (c) 2025 and onwards The vChewing Project (MIT License).
- Swift programmer: Shiki Suen
- (c) 2022 and onwards The vChewing Project (LGPL v3.0 License or later).
- The unit tests utilizes certain contents extracted from libvchewing-data by (c) 2022 and onwards The vChewing Project (BSD-3-Clause).

敝專案採雙授權發佈措施。除了 LGPLv3 以外,對商業使用者也提供不同的授權條款(比如允許閉源使用等)。詳情請[電郵聯絡作者]([email protected])
6 changes: 2 additions & 4 deletions Sources/Megrez/0_Megrez.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
// Swiftified and further development by (c) 2022 and onwards The vChewing Project (MIT License).
// Was initially rebranded from (c) Lukhnos Liu's C++ library "Gramambular 2" (MIT License).
// Walking algorithm (Dijkstra) implemented by (c) 2025 and onwards The vChewing Project (MIT License).
// (c) 2022 and onwards The vChewing Project (LGPL v3.0 License or later).
// ====================
// This code is released under the MIT license (SPDX-License-Identifier: MIT)
// This code is released under the SPDX-License-Identifier: `LGPL-3.0-or-later`.

/// The namespace for this package.
public enum Megrez {}
Expand Down
Loading

0 comments on commit 6df1b89

Please sign in to comment.