Skip to content

Commit 4903c9d

Browse files
committed
feat: support multiple language profiles via ime_profiles subdirectories
Allow each input method module under input_methods/<module>/ to define additional TSF language profile manifests in ime_profiles/<profile>/ime.json alongside (or instead of) the root ime.json. - Collect ime.json paths (root ime.json + sorted ime_profiles/*/ime.json) in PIMETextService, PIMELauncher, Python, Go, and Node backends, then process each manifest. - Resolve moduleName and relative asset/config paths (icon, configTool, configToolDir) against input_methods/<module>/ so multi-locale IMEs share code and assets in one folder. - Skip duplicate GUIDs (first manifest wins) with a warning. - Document the layout in HACKING.txt and add unit tests. Architecture and design by Hong Jen Yee (PCMan). Implementation generated with AI assistance from Antigravity (Gemini 4 Neon).
1 parent 0e270f2 commit 4903c9d

9 files changed

Lines changed: 371 additions & 178 deletions

File tree

‎HACKING.txt‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,18 @@ Directory structure
103103
All input method modules implemented using node.js. If you're trying to implement your
104104
own input method, you should put your module in this directory.
105105

106+
* Input method module layout (under `<backend>/input_methods/<ime_module>/`):
107+
Each input method module resides in its own subdirectory and may define one or more
108+
Windows TSF language profiles:
109+
- `ime.json`: Language profile manifest at the module root (commonly used when the
110+
module provides a single language profile).
111+
- `ime_profiles/<profile_name>/ime.json`: Optional subdirectory for additional or
112+
multi-locale language profile manifests (e.g. `zh-TW` and `zh-CN` profiles sharing
113+
the same input method implementation).
114+
- If both `<ime_module>/ime.json` and `<ime_module>/ime_profiles/<profile_name>/ime.json`
115+
exist, both are loaded.
116+
- Each profile must have a unique `guid`. If a guid is duplicated, the first manifest found
117+
wins (`ime.json` first, then `ime_profiles/*` in name order) and the others are ignored.
118+
- All module imports (`moduleName`) and relative asset/tool paths (`icon`, `configTool`,
119+
`configToolDir`) are resolved relative to `<backend>/input_methods/<ime_module>/`.
120+

‎PIMELauncher/src/backend_registry.rs‎

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use serde::Deserialize;
22
use std::collections::HashMap;
33
use std::fs;
4-
use std::path::Path;
4+
use std::path::{Path, PathBuf};
55
use tracing::{error, info, warn};
66

77
/// Configuration for a specific backend.
@@ -111,21 +111,37 @@ impl BackendRegistry {
111111
};
112112

113113
for entry in entries.flatten() {
114-
if let Some(guid) = Self::extract_guid_from_entry(&entry) {
115-
mappings.insert(guid.to_lowercase(), backend_name.to_string());
114+
for ime_json_path in Self::ime_json_paths(&entry.path()) {
115+
let Some(guid) = Self::extract_guid(&ime_json_path) else {
116+
continue;
117+
};
118+
let guid = guid.to_lowercase();
119+
// The first manifest of a GUID wins; skip duplicates.
120+
if mappings.contains_key(&guid) {
121+
warn!("Duplicate GUID {} in {:?} ignored", guid, ime_json_path);
122+
continue;
123+
}
116124
info!("Mapped GUID {} to backend {}", guid, backend_name);
125+
mappings.insert(guid, backend_name.to_string());
117126
}
118127
}
119128
}
120129

121-
/// Attempts to extract the "guid" field from an `ime.json` file in a directory entry.
122-
fn extract_guid_from_entry(entry: &fs::DirEntry) -> Option<String> {
123-
let path = entry.path();
124-
if !path.is_dir() {
125-
return None;
130+
/// Lists the language profile manifests of an input method module:
131+
/// `ime.json`, followed by `ime_profiles/*/ime.json`. The files may not exist.
132+
fn ime_json_paths(module_dir: &Path) -> Vec<PathBuf> {
133+
let mut paths = vec![module_dir.join("ime.json")];
134+
if let Ok(profiles) = fs::read_dir(module_dir.join("ime_profiles")) {
135+
let mut profile_paths: Vec<PathBuf> =
136+
profiles.flatten().map(|e| e.path().join("ime.json")).collect();
137+
profile_paths.sort();
138+
paths.extend(profile_paths);
126139
}
140+
paths
141+
}
127142

128-
let ime_json_path = path.join("ime.json");
143+
/// Attempts to extract the "guid" field from an `ime.json` file.
144+
fn extract_guid(ime_json_path: &Path) -> Option<String> {
129145
let content = fs::read_to_string(ime_json_path).ok()?;
130146
let json: serde_json::Value = serde_json::from_str(&content).ok()?;
131147

@@ -189,4 +205,30 @@ mod tests {
189205
);
190206
assert_eq!(registry.resolve_guid("unknown"), None);
191207
}
208+
209+
#[test]
210+
fn test_registry_load_ime_profiles() {
211+
let dir = tempdir().unwrap();
212+
let pime_root = dir.path();
213+
let backends_json = r#"[
214+
{"name": "python", "command": "python.exe", "workingDir": "python", "params": ""},
215+
{"name": "node", "command": "node.exe", "workingDir": "node", "params": ""}
216+
]"#;
217+
fs::write(pime_root.join("backends.json"), backends_json).unwrap();
218+
219+
let rime_dir = pime_root.join("python").join("input_methods").join("rime");
220+
let zh_tw_dir = rime_dir.join("ime_profiles").join("zh_TW");
221+
fs::create_dir_all(&zh_tw_dir).unwrap();
222+
fs::write(rime_dir.join("ime.json"), r#"{"guid": "{ROOT}"}"#).unwrap();
223+
fs::write(zh_tw_dir.join("ime.json"), r#"{"guid": "{PROFILE}"}"#).unwrap();
224+
225+
// A duplicate GUID in another backend must not override the first one.
226+
let dup_dir = pime_root.join("node").join("input_methods").join("dup");
227+
fs::create_dir_all(&dup_dir).unwrap();
228+
fs::write(dup_dir.join("ime.json"), r#"{"guid": "{PROFILE}"}"#).unwrap();
229+
230+
let registry = BackendRegistry::load(pime_root);
231+
assert_eq!(registry.resolve_guid("{root}"), Some(&"python".to_string()));
232+
assert_eq!(registry.resolve_guid("{profile}"), Some(&"python".to_string()));
233+
}
192234
}

‎PIMETextService/DllEntry.cpp‎

Lines changed: 15 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#include "JsonUtils.h"
33
#include "resource.h"
44

5+
#include <algorithm>
56
#include <fstream>
67
#include <mutex>
78
#include <optional>
@@ -79,7 +80,7 @@ STDAPI DllUnregisterServer(void) {
7980
return module ? module->unregisterServer() : E_FAIL;
8081
}
8182

82-
static inline std::optional<Ime::LangProfileInfo> langProfileFromJson(const std::wstring& file, bool useWin8Icon) {
83+
static inline std::optional<Ime::LangProfileInfo> langProfileFromJson(const std::wstring& file, const std::wstring& moduleDir, bool useWin8Icon) {
8384
// load the json file to get the info of input method
8485
std::ifstream fp(file, std::ifstream::binary);
8586
if (!fp) {
@@ -114,10 +115,8 @@ static inline std::optional<Ime::LangProfileInfo> langProfileFromJson(const std:
114115
}
115116
auto iconFile = utf8ToUtf16(iconPath.c_str());
116117
if (!iconFile.empty() && PathIsRelative(iconFile.c_str())) {
117-
size_t p = file.rfind(L'\\');
118-
if (p != file.npos) {
119-
iconFile = file.substr(0, p + 1) + iconFile;
120-
}
118+
// relative paths are resolved against the IME module dir
119+
iconFile = moduleDir + L'\\' + iconFile;
121120
}
122121
return Ime::LangProfileInfo{
123122
std::move(name),
@@ -136,36 +135,17 @@ STDAPI DllRegisterServer(void) {
136135
if (!module) {
137136
return E_FAIL;
138137
}
139-
const std::wstring programDir = module->programDir();
140-
for (const auto backendDir: module->backendDirs()) {
141-
std::string backendName = utf16ToUtf8(backendDir.c_str());
142-
std::wstring dirPath = programDir;
143-
dirPath += L'\\';
144-
dirPath += backendDir;
145-
dirPath += L"\\input_methods";
146-
// scan the dir for lang profile definition files
147-
WIN32_FIND_DATA findData = { 0 };
148-
HANDLE hFind = ::FindFirstFile((dirPath + L"\\*").c_str(), &findData);
149-
if (hFind != INVALID_HANDLE_VALUE) {
150-
do {
151-
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // this is a subdir
152-
if (findData.cFileName[0] != '.') {
153-
std::wstring imejson = dirPath;
154-
imejson += '\\';
155-
imejson += findData.cFileName;
156-
imejson += L"\\ime.json";
157-
// Make sure the file exists
158-
DWORD fileAttrib = GetFileAttributesW(imejson.c_str());
159-
if (fileAttrib != INVALID_FILE_ATTRIBUTES) {
160-
// load the json file to get the info of input method
161-
if (auto profile = langProfileFromJson(imejson, useWin8Icon)) {
162-
langProfiles.push_back(std::move(*profile));
163-
}
164-
}
165-
}
166-
}
167-
} while (::FindNextFile(hFind, &findData));
168-
::FindClose(hFind);
138+
for (const auto& manifest : module->findImeManifests()) {
139+
auto profile = langProfileFromJson(manifest.jsonPath, manifest.moduleDir, useWin8Icon);
140+
if (!profile) {
141+
continue;
142+
}
143+
// The first manifest of a GUID wins; skip duplicates.
144+
bool duplicated = std::any_of(langProfiles.begin(), langProfiles.end(), [&](const auto& p) {
145+
return IsEqualGUID(p.profileGuid, profile->profileGuid);
146+
});
147+
if (!duplicated) {
148+
langProfiles.push_back(std::move(*profile));
169149
}
170150
}
171151
wchar_t modulePath[MAX_PATH];

‎PIMETextService/PIMEImeModule.cpp‎

Lines changed: 56 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include "PIMEImeModule.h"
2121
#include "JsonUtils.h"
2222
#include "PIMETextService.h"
23+
#include <algorithm>
2324
#include <string>
2425
#include <fstream>
2526
#include <cstring>
@@ -94,48 +95,60 @@ Ime::TextService* ImeModule::createTextService() {
9495
return service;
9596
}
9697

97-
bool ImeModule::loadImeInfo(const std::string& guid, std::wstring& filePath, json& content) {
98-
bool found = false;
99-
// find the input method module
100-
for (const auto backendDir : backendDirs_) {
101-
std::wstring dirPath = programDir_;
102-
dirPath += '\\';
103-
dirPath += backendDir;
104-
dirPath += L"\\input_methods";
105-
// scan the dir for lang profile definition files
106-
WIN32_FIND_DATA findData = { 0 };
107-
HANDLE hFind = ::FindFirstFile((dirPath + L"\\*").c_str(), &findData);
108-
if (hFind != INVALID_HANDLE_VALUE) {
109-
do {
110-
if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // this is a subdir
111-
if (findData.cFileName[0] != '.') {
112-
std::wstring imejson = dirPath;
113-
imejson += '\\';
114-
imejson += findData.cFileName;
115-
imejson += L"\\ime.json";
116-
std::ifstream fp(imejson, std::ifstream::binary);
117-
if (fp) {
118-
content = parseJsonNoThrow(fp);
119-
if (!content.is_object() || content.is_discarded()) {
120-
continue;
121-
}
122-
std::string imeGuid = jsonValueOr<std::string>(content, "guid", "");
123-
if (stricmp(guid.c_str(), imeGuid.c_str()) == 0) {
124-
// found the language profile
125-
found = true;
126-
filePath = imejson;
127-
break;
128-
}
129-
}
130-
}
98+
static std::vector<std::wstring> listSubdirs(const std::wstring& dir) {
99+
std::vector<std::wstring> subdirs;
100+
WIN32_FIND_DATAW findData = { 0 };
101+
HANDLE hFind = ::FindFirstFileW((dir + L"\\*").c_str(), &findData);
102+
if (hFind != INVALID_HANDLE_VALUE) {
103+
do {
104+
if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && findData.cFileName[0] != L'.') {
105+
subdirs.push_back(dir + L'\\' + findData.cFileName);
106+
}
107+
} while (::FindNextFileW(hFind, &findData));
108+
::FindClose(hFind);
109+
}
110+
std::sort(subdirs.begin(), subdirs.end());
111+
return subdirs;
112+
}
113+
114+
std::vector<ImeModule::ImeManifest> ImeModule::findImeManifests() const {
115+
std::vector<ImeManifest> manifests;
116+
for (const auto& backendDir : backendDirs_) {
117+
const std::wstring inputMethodsDir = programDir_ + L'\\' + backendDir + L"\\input_methods";
118+
for (const auto& moduleDir : listSubdirs(inputMethodsDir)) {
119+
std::wstring rootJson = moduleDir + L"\\ime.json";
120+
if (::GetFileAttributesW(rootJson.c_str()) != INVALID_FILE_ATTRIBUTES) {
121+
manifests.push_back({std::move(rootJson), moduleDir});
122+
}
123+
for (const auto& profileDir : listSubdirs(moduleDir + L"\\ime_profiles")) {
124+
std::wstring profileJson = profileDir + L"\\ime.json";
125+
if (::GetFileAttributesW(profileJson.c_str()) != INVALID_FILE_ATTRIBUTES) {
126+
manifests.push_back({std::move(profileJson), moduleDir});
131127
}
132-
} while (::FindNextFile(hFind, &findData));
133-
::FindClose(hFind);
128+
}
129+
}
130+
}
131+
return manifests;
132+
}
133+
134+
bool ImeModule::loadImeInfo(const std::string& guid, std::wstring& moduleDir, json& content) {
135+
for (const auto& manifest : findImeManifests()) {
136+
std::ifstream fp(manifest.jsonPath, std::ifstream::binary);
137+
if (!fp) {
138+
continue;
139+
}
140+
content = parseJsonNoThrow(fp);
141+
if (!content.is_object() || content.is_discarded()) {
142+
continue;
143+
}
144+
std::string imeGuid = jsonValueOr<std::string>(content, "guid", "");
145+
if (stricmp(guid.c_str(), imeGuid.c_str()) == 0) {
146+
// found the language profile
147+
moduleDir = manifest.moduleDir;
148+
return true;
134149
}
135-
if (found)
136-
break;
137150
}
138-
return found;
151+
return false;
139152
}
140153

141154
// virtual
@@ -152,10 +165,11 @@ bool ImeModule::onConfigure(HWND hwndParent, LANGID langid, REFGUID rguidProfile
152165
std::wstring configDir;
153166

154167
// find the input method module
155-
std::wstring infoFilePath;
168+
std::wstring moduleDir;
156169
json info;
157-
if (loadImeInfo(guidStr, infoFilePath, info)) {
158-
std::wstring currentDir = infoFilePath.substr(0, infoFilePath.length() - 8); // remove "ime.json" from file path
170+
if (loadImeInfo(guidStr, moduleDir, info)) {
171+
// relative paths are resolved against the IME module dir
172+
std::wstring currentDir = moduleDir + L'\\';
159173
configCommand = utf8ToUtf16(jsonValueOr<std::string>(info, "configTool", "").c_str());
160174
configParams = utf8ToUtf16(jsonValueOr<std::string>(info, "configToolParams", "").c_str());
161175
configDir = utf8ToUtf16(jsonValueOr<std::string>(info, "configToolDir", "").c_str());

‎PIMETextService/PIMEImeModule.h‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,19 @@ class ImeModule : public Ime::ImeModule {
4747
// called when config dialog needs to be launched
4848
virtual bool onConfigure(HWND hwndParent, LANGID langid, REFGUID rguidProfile);
4949

50-
bool loadImeInfo(const std::string&, std::wstring& filePath, nlohmann::json& content);
50+
struct ImeManifest {
51+
std::wstring jsonPath;
52+
std::wstring moduleDir;
53+
};
54+
55+
// Collects all ime.json manifest paths across all backends:
56+
// <backend>/input_methods/<module>/ime.json
57+
// <backend>/input_methods/<module>/ime_profiles/<profile>/ime.json
58+
std::vector<ImeManifest> findImeManifests() const;
59+
60+
// Finds the manifest of the language profile with the given guid.
61+
// moduleDir receives the IME module dir, against which relative paths are resolved.
62+
bool loadImeInfo(const std::string& guid, std::wstring& moduleDir, nlohmann::json& content);
5163

5264
const std::vector<std::wstring>& backendDirs() {
5365
return backendDirs_;

0 commit comments

Comments
 (0)