Skip to content

Commit eb161d1

Browse files
authored
Merge pull request openvanilla#662 from zonble/master
Add copilot instruction
2 parents 358d5b5 + 6156593 commit eb161d1

1 file changed

Lines changed: 369 additions & 0 deletions

File tree

.copilot-instructions.md

Lines changed: 369 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,369 @@
1+
# McBopomofo Copilot Instructions
2+
3+
## What's the Project For
4+
5+
McBopomofo (小麥注音輸入法) is a Traditional Chinese input method engine (IME) for macOS. It allows users to input Traditional Chinese characters using the Bopomofo phonetic system (注音符號), which is the standard phonetic notation system used in Taiwan.
6+
7+
The project is part of the OpenVanilla framework and provides:
8+
- Smart phonetic-to-character conversion
9+
- User-customizable phrase dictionaries
10+
- Associated phrase suggestions
11+
- Multi-candidate selection
12+
- Support for custom user phrases and exclusions
13+
14+
## System Requirements
15+
16+
### Runtime Requirements
17+
- macOS 10.15 (Catalina) or later
18+
19+
### Development Requirements
20+
- macOS 14.7 or later
21+
- Xcode 15.3 or later
22+
- Python 3.9 (available through Xcode or homebrew)
23+
24+
## Build Process
25+
26+
The project uses Xcode as its primary build system:
27+
28+
1. **Open Project**: Open `McBopomofo.xcodeproj` in Xcode
29+
2. **Select Target**: Choose "McBopomofoInstaller" target
30+
3. **Build**: Build the project (⌘+B)
31+
4. **Install**: Run the installer directly to install McBopomofo
32+
5. **Reinstall**: For subsequent updates, repeat the process
33+
34+
### Important Notes
35+
- macOS may limit the number of times an input method process can be killed in a single login session
36+
- If installation issues occur after multiple installs, log out and log back in
37+
- The installer automatically kills and restarts the input method process
38+
39+
## Project Components
40+
41+
### Architecture Overview
42+
```
43+
McBopomofo/
44+
├── Source/ # Main application source
45+
│ ├── Engine/ # C++ core engine
46+
│ │ ├── Mandarin/ # Bopomofo processing
47+
│ │ ├── gramambular2/ # Text segmentation library
48+
│ │ └── McBopomofoLM.* # Language model
49+
│ ├── InputState.swift # State machine implementation
50+
│ ├── InputMethodController.swift # Main controller
51+
│ └── Data/ # Language model data files
52+
├── McBopomofoTests/ # Test suite
53+
└── Packages/ # Swift Package dependencies
54+
```
55+
56+
### Technology Stack
57+
- **Swift**: UI layer, input method controller, state management
58+
- **Objective-C++**: Bridge between Swift and C++ components
59+
- **C++**: Core engine, language processing, data structures
60+
- **Xcode**: Build system and development environment
61+
62+
### Framework Foundation
63+
McBopomofo is built on Apple's native input method frameworks:
64+
65+
#### Cocoa Framework
66+
- **UI Components**: Native macOS user interface elements
67+
- **Event Handling**: Keyboard and mouse event processing
68+
- **Window Management**: Candidate window and preference panels
69+
- **Integration**: Seamless integration with macOS applications
70+
71+
#### Input Method Kit (IMK)
72+
- **IMKInputController**: Base class for input method controllers
73+
- `McBopomofoInputMethodController` extends `IMKInputController`
74+
- Handles input events and text processing
75+
- Manages communication with client applications
76+
- **IMKServer**: Input method server infrastructure
77+
- Manages input method instances
78+
- Handles system-level input method operations
79+
- **IMKCandidateController**: Candidate selection interface
80+
- **Protocol Compliance**: Implements IMK protocols for proper system integration
81+
82+
### Key Files
83+
- `Source/InputMethodController.swift`: Main input method logic
84+
- `Source/InputState.swift`: State machine implementation
85+
- `Source/Engine/McBopomofoLM.h` and `Source/Engine/McBopomofoLM.cpp`: Language model management
86+
- `Source/Engine/Mandarin/Mandarin.h` and `Source/Engine/Mandarin/Mandarin.cpp`: Bopomofo processing
87+
- `Source/Engine/gramambular2/`: Text segmentation algorithms
88+
89+
## Design of Input States
90+
91+
McBopomofo implements a finite state machine with multiple distinct states to handle various input scenarios:
92+
93+
### Core Input States
94+
95+
1. **Deactivated**: User hasn't activated McBopomofo
96+
2. **Empty**: McBopomofo is active but no input yet, or user just committed text
97+
3. **Inputting**: User is typing Bopomofo keys; input buffer is visible
98+
4. **Committing**: Sending text to client applications
99+
5. **Marking**: User is selecting text in buffer to create custom phrase
100+
6. **ChoosingCandidate**: Candidate window is open for user selection
101+
102+
### Extended States
103+
104+
The system includes additional specialized states:
105+
106+
- **SelectingFeature**: User accessing special features menu
107+
- **SelectingDateMacro**: Date/time macro selection
108+
- **ChineseNumber**: Chinese numeral conversion
109+
- **Big5**: Big5 encoding conversion
110+
- **EnclosedNumber**: Circled/parenthesized number conversion
111+
- **AssociatedPhrases**: Associated phrase suggestions
112+
- **SelectingDictionary**: Dictionary lookup mode
113+
- **ShowingCharInfo**: Character information display
114+
- **CustomMenu**: Custom menu operations
115+
116+
### State Properties
117+
- **Immutable**: States are immutable objects; transitions create new state instances
118+
- **One-way data flow**: UI and text output follow single data source
119+
- **Context-specific data**: Each state contains only relevant data (e.g., candidate list only exists in Choosing Candidate state)
120+
121+
### Implementation Details
122+
- Base class: `InputState`
123+
- State-specific subclasses: `Deactivated`, `Empty`, `Inputting`, `Committing`, `Marking`, `ChoosingCandidate`
124+
- Controller creates new state objects instead of modifying existing ones
125+
126+
## Design of Mandarin Package
127+
128+
The Mandarin package handles Bopomofo phonetic input processing and conversion.
129+
130+
### Core Classes
131+
132+
#### BopomofoSyllable (BPMF)
133+
- **Purpose**: Represents a complete Bopomofo syllable
134+
- **Storage**: 16-bit integer with bit masks for components
135+
- **Components**: Consonant, Middle Vowel, Vowel, Tone Marker
136+
- **Features**:
137+
- Conversion to/from Hanyu Pinyin
138+
- Composed string representation
139+
- Component validation and extraction
140+
- Overlap detection between syllables
141+
142+
#### BopomofoKeyboardLayout
143+
- **Purpose**: Maps keyboard keys to Bopomofo components
144+
- **Key Functions**:
145+
- `syllableFromKeySequence()`: Converts key sequence to syllable
146+
- `keySequenceFromSyllable()`: Converts syllable back to keys
147+
- **Layout Support**: Different keyboard layouts for Bopomofo input
148+
- **Validation**: Ensures valid key combinations (e.g., J/Q/X require I or UE vowels)
149+
150+
#### BopomofoReadingBuffer
151+
- **Purpose**: Manages user input during syllable composition
152+
- **Features**:
153+
- Key combination and validation
154+
- Pinyin mode support
155+
- Buffer clearing and state management
156+
- Integration with keyboard layouts
157+
158+
### Key Algorithms
159+
160+
#### Syllable Construction
161+
1. Process each key in input sequence
162+
2. Check for valid key combinations
163+
3. Apply tone markers correctly
164+
4. Validate final syllable composition
165+
166+
#### Component Mapping
167+
- Bit-masked representation for efficient storage
168+
- Separate masks for consonants, vowels, and tones
169+
- Support for multiple components per key
170+
171+
## Keyboard Layouts
172+
173+
McBopomofo supports multiple Bopomofo keyboard layouts to accommodate different user preferences and typing habits:
174+
175+
### Standard Layout
176+
- **Description**: Traditional Bopomofo layout used in Taiwan
177+
- **Characteristics**: Direct mapping of Bopomofo symbols to QWERTY keys
178+
- **Usage**: Most common layout for Bopomofo input
179+
- **Implementation**: `BopomofoKeyboardLayout::StandardLayout()`
180+
181+
### ETen Layout
182+
- **Description**: ETen Traditional layout
183+
- **Characteristics**: Alternative key mapping optimized for certain typing patterns
184+
- **Usage**: Popular among users familiar with ETen input systems
185+
- **Implementation**: `BopomofoKeyboardLayout::ETenLayout()`
186+
187+
### Hsu Layout (許氏鍵盤)
188+
- **Description**: Hsu keyboard layout invented by Dr. Wen-Lian Hsu.
189+
- **Characteristics**:
190+
- Optimized for faster typing with fewer keystrokes
191+
- Special heuristics for vowel combinations
192+
- Automatic correction rules (e.g., GI/GUE → JI/JUE)
193+
- **Usage**: Preferred by advanced users for speed typing
194+
- **Implementation**: `BopomofoKeyboardLayout::HsuLayout()`
195+
196+
### ETen26 Layout
197+
- **Description**: ETen 26-key layout variant
198+
- **Characteristics**: Extended ETen layout with additional key combinations
199+
- **Usage**: Enhanced version of ETen layout
200+
- **Implementation**: `BopomofoKeyboardLayout::ETen26Layout()`
201+
202+
### Layout Architecture
203+
- **Key-to-Component Mapping**: Each layout defines mappings from keyboard keys to Bopomofo components
204+
- **Syllable Construction**: Layouts handle complex rules for syllable formation
205+
- **Special Rules**: Each layout can implement specific typing optimizations and corrections
206+
- **Runtime Switching**: Users can switch between layouts in preferences
207+
208+
## Design of Language Model (McBopomofoLM)
209+
210+
The language model manages text conversion, user customization, and phrase suggestions.
211+
212+
### Architecture
213+
214+
#### McBopomofoLM Class
215+
- **Inheritance**: Extends `Formosa::Gramambular2::LanguageModel`
216+
- **Purpose**: Central hub for all language processing
217+
- **Integration**: Combines multiple data sources and processing layers
218+
219+
### Data Processing Pipeline
220+
221+
When processing unigrams (single-character/phrase entries):
222+
223+
1. **Original Unigrams**: Retrieve from primary language model
224+
2. **Exclusion Filtering**: Remove user-excluded phrases
225+
3. **Phrase Replacement**: Apply user-defined replacements
226+
4. **External Conversion**: Transform via external converter (if enabled)
227+
5. **Deduplication**: Remove duplicate entries
228+
6. **Return Results**: Provide final candidate list
229+
230+
### Key Components
231+
232+
#### Primary Language Model
233+
- **ParselessLM**: Main language model for character/phrase data
234+
- **Unigram-based**: Uses single-token probability model
235+
- **File-based**: Loads from bundled data files
236+
237+
#### User Customization
238+
- **UserPhrasesLM**: User-defined custom phrases
239+
- **Exclusion List**: User-blocked phrases
240+
- **Replacement Map**: User-defined phrase substitutions
241+
- **Associated Phrases**: Context-based phrase suggestions
242+
243+
#### External Processing
244+
- **Macro Converter**: Handles text macros and shortcuts
245+
- **External Converter**: Traditional/Simplified Chinese character conversion (OpenCC-based)
246+
- **Runtime Configuration**: Enable/disable features dynamically
247+
248+
### File Management
249+
- **User Data Folder**: Configurable location for user files
250+
- **Template System**: Automatic creation of empty user files
251+
- **Atomic Updates**: Safe file writing and reloading
252+
253+
## Algorithm of Gramambular2
254+
255+
Gramambular2 is the core segmentation and input method library using statistical models.
256+
257+
### Theoretical Foundation
258+
259+
#### Hidden Markov Model (HMM)
260+
- **Observations**: Input characters or Bopomofo syllables
261+
- **Hidden States**: Possible character/phrase groupings
262+
- **Goal**: Find most likely segmentation given input sequence
263+
264+
#### Naive Bayes Classification
265+
- **Approach**: Simplified probabilistic classification
266+
- **Assumptions**: Independence between features
267+
- **Efficiency**: Fast computation suitable for real-time input
268+
269+
### Core Algorithm
270+
271+
#### Segmentation Process
272+
1. **Input Sequence**: Receive series of observations (syllables/characters)
273+
2. **State Generation**: Generate possible hidden states (character combinations)
274+
3. **Probability Calculation**: Compute likelihood using unigram model
275+
4. **Path Selection**: Choose most probable segmentation path
276+
5. **Output Generation**: Return most likely character sequence
277+
278+
#### Language Model Integration
279+
- **Unigram Model**: Simple single-token probability model
280+
- **Frequency-based**: Probabilities derived from corpus frequency
281+
- **Extensible**: Support for custom language models
282+
283+
### Implementation Details
284+
285+
#### Reading Grid
286+
- **Purpose**: Manages candidate generation and selection
287+
- **Structure**: Grid of possible readings and conversions
288+
- **Optimization**: Efficient storage and retrieval of candidates
289+
290+
#### Language Model Interface
291+
- **Abstract Base**: `LanguageModel` interface for pluggable models
292+
- **Standard Methods**: `hasUnigrams()`, `getUnigrams()` for data access
293+
- **Extensibility**: Support for custom language model implementations
294+
295+
### Performance Characteristics
296+
- **Real-time**: Optimized for interactive input method use
297+
- **Memory Efficient**: Minimal memory footprint
298+
- **Scalable**: Handles large dictionaries efficiently
299+
- **Fast Lookup**: Quick candidate generation and ranking
300+
301+
### Use Cases
302+
1. **Input Method**: Convert Bopomofo sequences to Chinese characters
303+
2. **Text Segmentation**: Break Chinese text into meaningful units
304+
3. **Candidate Ranking**: Order possible conversions by probability
305+
4. **Context Awareness**: Consider surrounding text for better suggestions
306+
307+
## Development Guidelines
308+
309+
### Code Organization
310+
- **Swift**: Use for UI, state management, and application logic
311+
- **C++**: Use for performance-critical algorithms and data processing
312+
- **Objective-C++**: Use for bridging between Swift and C++
313+
314+
### Testing
315+
McBopomofo employs a comprehensive testing strategy with both C++ and Swift test suites:
316+
317+
#### C++ Engine Tests
318+
Located in `Source/Engine/`, these tests validate core algorithms and data structures:
319+
320+
- **Unit Tests**: Individual component testing using Google Test framework
321+
- **Test Files**:
322+
- `MandarinTest.cpp`: Bopomofo syllable and keyboard layout tests
323+
- `McBopomofoLMTest.cpp`: Language model functionality tests
324+
- `ParselessLMTest.cpp`: Language model parsing and data structure tests
325+
- `UTF8HelperTest.cpp`: UTF-8 string processing tests
326+
- `UserPhrasesLMTest.cpp`: User-defined phrase management tests
327+
- `PhraseReplacementMapTest.cpp`: Phrase replacement logic tests
328+
- `KeyValueBlobReaderTest.cpp`: Data file reading tests
329+
- `MemoryMappedFileTest.cpp`: Memory-mapped file operations tests
330+
- `AssociatedPhrasesV2Test.cpp`: Associated phrase suggestion tests
331+
- `UserOverrideModelTest.cpp`: User override functionality tests
332+
- **Coverage**: Core engine components, data structures, algorithms
333+
- **Build**: Integrated with CMake build system
334+
335+
#### Swift Application Tests
336+
Located in `McBopomofoTests/`, these tests validate application logic and UI integration:
337+
338+
- **Test Framework**: XCTest framework for Swift testing
339+
- **Test Files**:
340+
- `KeyHandlerBopomofoTests.swift`: Input processing and key handling tests
341+
- `KeyHandlerPlainBopomofoTests.swift`: Plain Bopomofo input tests
342+
- `PreferencesTests.swift`: User preferences and configuration tests
343+
- `DictionaryServiceTests.swift`: Dictionary lookup service tests
344+
- `ServiceProviderTests.swift`: Input method service provider tests
345+
- `AssociatedPhrasesTests.swift`: Associated phrase functionality tests
346+
- `InputMacroTests.swift`: Text macro processing tests
347+
- `VersionUpdateTests.swift`: Version management and update tests
348+
- **Integration**: Tests complete input workflows and state management
349+
- **UI Testing**: Validates user interface components and interactions
350+
351+
#### Mixed Language Tests
352+
- **UTF8HelperTest.mm**: Objective-C++ test bridging Swift and C++ components
353+
- **Bridging Header**: `McBopomofoTests-Bridging-Header.h` enables Swift-C++ interop in tests
354+
355+
#### Testing Approach
356+
- **Isolated Testing**: C++ tests focus on algorithmic correctness
357+
- **Integration Testing**: Swift tests validate complete user workflows
358+
- **Cross-Language Testing**: Objective-C++ tests ensure proper bridging
359+
- **Continuous Validation**: Both test suites run during development cycles
360+
361+
### Debugging
362+
- **State Inspection**: Monitor InputState transitions
363+
- **Language Model**: Verify unigram processing pipeline
364+
- **Syllable Processing**: Check Bopomofo key handling
365+
366+
### Performance Considerations
367+
- **Memory Management**: Careful handling of large language model data
368+
- **Real-time Constraints**: Input method must be responsive
369+
- **Battery Usage**: Optimize for minimal system impact

0 commit comments

Comments
 (0)