Repository navigation
Expand file tree
/
Copy pathcopy-android-scaffolding.mjs
More file actions
465 lines (434 loc) · 15.8 KB
/
Copy pathcopy-android-scaffolding.mjs
File metadata and controls
465 lines (434 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#!/usr/bin/env node
import {
copyFileSync,
existsSync,
mkdirSync,
readdirSync,
rmSync,
readFileSync,
statSync,
writeFileSync,
} from 'node:fs';
import { dirname, join } from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
const appRoot = fileURLToPath(new URL('..', import.meta.url));
const kotlinRoot = join(appRoot, 'android/kotlin');
const kotlinTestRoot = join(kotlinRoot, 'test');
const kotlinAndroidTestRoot = join(kotlinRoot, 'androidTest');
const manifestsRoot = join(appRoot, 'android/manifests');
const androidIconRoot = join(appRoot, 'src-tauri/icons/android');
const aidlRoot = join(appRoot, 'android/aidl');
const androidAssetsRoot = join(appRoot, 'android/assets');
const androidAppRoot = join(appRoot, 'src-tauri/gen/android/app');
const genRoot = join(appRoot, 'src-tauri/gen/android/app/src/main');
const kotlinDest = join(genRoot, 'java/com/openless/app');
const mainActivityPath = join(kotlinDest, 'MainActivity.kt');
const kotlinTestDest = join(androidAppRoot, 'src/test/java/com/openless/app');
const kotlinAndroidTestDest = join(androidAppRoot, 'src/androidTest/java/com/openless/app');
const androidAppGradle = join(androidAppRoot, 'build.gradle.kts');
const resDest = join(genRoot, 'res');
const resXmlDest = join(genRoot, 'res/xml');
const aidlDest = join(genRoot, 'aidl');
const assetsDest = join(genRoot, 'assets');
const KOTLIN_FILES = [
'OpenLessAppContext.kt',
'OpenLessNative.kt',
'OpenLessPermissionBridge.kt',
'MicrophonePermissionActivity.kt',
'OpenLessAndroidPreferences.kt',
'OpenLessCredentialCipher.kt',
'OpenLessCredentialVault.kt',
'OpenLessApplication.kt',
'OpenLessOverlayService.kt',
'OpenLessOverlayBridge.kt',
'OpenLessAccessibilityService.kt',
'OpenLessAccessibilitySelection.kt',
'OpenLessAccessibilityResult.kt',
'OpenLessAccessibilityTarget.kt',
'OpenLessPasteVerification.kt',
'OpenLessAccessibilityComponentIds.kt',
'OpenLessShizukuBridge.kt',
'OpenLessShizukuUserService.kt',
'OpenLessShizukuUserServiceClient.kt',
'ShizukuPermissionActivity.kt',
'OpenLessAccessibilityCommandReceiver.kt',
'OpenLessVocabularyReceiver.kt',
'OverlayPermissionActivity.kt',
'OpenLessUpdateInstaller.kt',
'OpenLessContentReader.kt',
'OpenLessContentWriter.kt',
'OpenLessMigrationBundlePolicy.kt',
'OpenLessMigrationState.kt',
'OpenLessImeService.kt',
'ImeLearningPolicy.kt',
'DictationSpan.kt',
'ImePrivacyPolicy.kt',
'ImeDraftReplacement.kt',
'StrokeInputController.kt',
'StrokeInput.kt',
'OpenLessRime.kt',
'RimePinyinController.kt',
'LegacyPinyinBackup.kt',
'OpenLessSettingsExport.kt',
'StrokePhraseRepository.kt',
'StrokeUserFrequency.kt',
'EnglishCandidateProvider.kt',
'EnglishUserFrequency.kt',
'OpenLessRuntimeService.kt',
'OpenLessBackendWarmupActivity.kt',
'OpenLessClipboardHistory.kt',
'CloudNoteDelivery.kt',
'OpenLessKeyboardSettingsActivity.kt',
'OpenLessLocalMigrationActivity.kt',
'OpenLessProcessRestartStats.kt',
'OpenLessBuildInfo.kt',
];
const KOTLIN_TEST_FILES = [
'ImeLearningPolicyTest.kt',
'CloudNoteDeliveryTest.kt',
'DictationSpanTest.kt',
'ImePrivacyPolicyTest.kt',
'ImeDraftReplacementTest.kt',
'LatinInputModeTest.kt',
'OpenLessContentReaderTest.kt',
'OpenLessMigrationBundleContractTest.kt',
'OpenLessCredentialCipherTest.kt',
'OpenLessShizukuBridgeTest.kt',
'OpenLessAccessibilityResultTest.kt',
'OpenLessAccessibilitySelectionTest.kt',
'OpenLessOverlayStateTest.kt',
'OpenLessAccessibilityTargetTest.kt',
'OpenLessPasteVerificationTest.kt',
'OpenLessAccessibilityComponentIdsTest.kt',
];
const KOTLIN_ANDROID_TEST_FILES = [
'OpenLessClipboardHistoryInstrumentedTest.kt',
'OpenLessCredentialVaultInstrumentedTest.kt',
'ImeLearningMigrationTest.kt',
'OpenLessMigrationBundleInstrumentedTest.kt',
'RimeEngineIntegrationTest.kt',
];
const XML_FILES = [
['res/xml/openless_accessibility_config.xml', 'openless_accessibility_config.xml'],
['res/xml/openless_ime_method.xml', 'openless_ime_method.xml'],
];
const GENERATED_ACCESSIBILITY_CONFIG = `<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeWindowStateChanged|typeWindowsChanged"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagRetrieveInteractiveWindows"
android:canRetrieveWindowContent="true"
android:description="@string/openless_accessibility_description"
android:notificationTimeout="100"
android:settingsActivity="com.openless.app.MainActivity" />
`;
const GENERATED_STRINGS_SNIPPET = `
<string name="openless_accessibility_description">OpenLess uses accessibility to detect the keyboard and paste dictation results without switching your current keyboard.</string>
<string name="openless_ime_label">OpenLess Voice</string>
`;
export const SHIZUKU_STRINGS_BY_LOCALE = {
values: {
openless_shizuku_permission_rationale:
'OpenLess needs Shizuku authorization to optionally recover accessibility when OEM settings block manual toggles.',
openless_shizuku_permission_blocked:
'Shizuku authorization was denied. Open Shizuku and allow OpenLess manually.',
openless_shizuku_open_manager: 'Open Shizuku',
},
'values-zh-rCN': {
openless_shizuku_permission_rationale:
'OpenLess 需要 Shizuku 授权,以便在部分机型无法手动开启无障碍时尝试恢复。',
openless_shizuku_permission_blocked:
'Shizuku 授权已被拒绝。请打开 Shizuku 并手动允许 OpenLess。',
openless_shizuku_open_manager: '打开 Shizuku',
},
'values-zh-rTW': {
openless_shizuku_permission_rationale:
'OpenLess 需要 Shizuku 授權,以便在部分機型無法手動開啟無障礙時嘗試恢復。',
openless_shizuku_permission_blocked:
'Shizuku 授權已被拒絕。請開啟 Shizuku 並手動允許 OpenLess。',
openless_shizuku_open_manager: '開啟 Shizuku',
},
'values-ja': {
openless_shizuku_permission_rationale:
'OEM 設定で手動切り替えが難しい場合にアクセシビリティを復旧するため、OpenLess には Shizuku 権限が必要です。',
openless_shizuku_permission_blocked:
'Shizuku 権限が拒否されました。Shizuku を開いて OpenLess を手動で許可してください。',
openless_shizuku_open_manager: 'Shizuku を開く',
},
'values-ko': {
openless_shizuku_permission_rationale:
'OEM 설정에서 접근성을 수동으로 켜기 어려울 때 복구하려면 OpenLess에 Shizuku 권한이 필요합니다.',
openless_shizuku_permission_blocked:
'Shizuku 권한이 거부되었습니다. Shizuku를 열어 OpenLess를 수동으로 허용하세요.',
openless_shizuku_open_manager: 'Shizuku 열기',
},
};
export function formatStringResource(name, value) {
return ` <string name="${name}">${value}</string>`;
}
export function hasStringResource(xml, name) {
return new RegExp(`<string\\s+name="${name}"`).test(xml);
}
export function mergeMissingStringResources(xml, stringsByName) {
let content = xml;
let changed = false;
for (const [name, value] of Object.entries(stringsByName)) {
if (hasStringResource(content, name)) {
continue;
}
if (!content.includes('</resources>')) {
throw new Error('strings.xml is missing </resources>');
}
content = content.replace('</resources>', `${formatStringResource(name, value)}\n</resources>`);
changed = true;
}
return { content, changed };
}
function buildStringsSnippet(stringsByName) {
return `\n${Object.entries(stringsByName)
.map(([name, value]) => formatStringResource(name, value))
.join('\n')}\n`;
}
function printHelp() {
console.log(`Usage: node scripts/copy-android-scaffolding.mjs [options]
Copy Kotlin scaffolding and XML resources into gen/android after \`tauri android init\`.
Options:
--dry-run Print planned copies without writing
--help Show this help text
`);
}
function parseArgs(argv) {
let dryRun = false;
for (const arg of argv) {
if (arg === '--help' || arg === '-h') {
printHelp();
process.exit(0);
}
if (arg === '--dry-run') {
dryRun = true;
continue;
}
throw new Error(`Unknown argument: ${arg}`);
}
return { dryRun };
}
function ensureDir(path, dryRun) {
if (dryRun || existsSync(path)) {
return;
}
mkdirSync(path, { recursive: true });
}
function mergeStringsXml(dryRun) {
const stringsPath = join(genRoot, 'res/values/strings.xml');
if (!existsSync(stringsPath)) {
const content = `<?xml version="1.0" encoding="utf-8"?>
<resources>${GENERATED_STRINGS_SNIPPET}${buildStringsSnippet(SHIZUKU_STRINGS_BY_LOCALE.values)}
</resources>
`;
if (dryRun) {
console.log(`[dry-run] Would create ${stringsPath}`);
return;
}
ensureDir(dirname(stringsPath), dryRun);
writeFileSync(stringsPath, content, 'utf8');
console.log(`Created ${stringsPath}`);
} else {
let existing = readFileSync(stringsPath, 'utf8');
const generatedStrings = mergeMissingStringResources(existing, {
openless_accessibility_description:
'OpenLess uses accessibility to detect the keyboard and paste dictation results without switching your current keyboard.',
openless_ime_label: 'OpenLess Voice',
});
const merged = mergeMissingStringResources(
generatedStrings.content,
SHIZUKU_STRINGS_BY_LOCALE.values,
);
if (!dryRun) {
writeFileSync(stringsPath, merged.content, 'utf8');
console.log(`Merged OpenLess strings into ${stringsPath}`);
}
}
for (const [localeDir, stringsByName] of Object.entries(SHIZUKU_STRINGS_BY_LOCALE)) {
if (localeDir === 'values') {
continue;
}
mergeLocaleStringsXml(localeDir, stringsByName, dryRun);
}
}
function mergeLocaleStringsXml(localeDir, stringsByName, dryRun) {
const stringsPath = join(genRoot, 'res', localeDir, 'strings.xml');
if (!existsSync(stringsPath)) {
const content = `<?xml version="1.0" encoding="utf-8"?>
<resources>${buildStringsSnippet(stringsByName)}
</resources>
`;
if (dryRun) {
console.log(`[dry-run] Would create ${stringsPath}`);
return;
}
ensureDir(dirname(stringsPath), dryRun);
writeFileSync(stringsPath, content, 'utf8');
console.log(`Created ${stringsPath}`);
return;
}
const existing = readFileSync(stringsPath, 'utf8');
const merged = mergeMissingStringResources(existing, stringsByName);
if (!merged.changed) {
console.log(`Shizuku strings already present in ${stringsPath}; skipping.`);
return;
}
if (dryRun) {
console.log(`[dry-run] Would merge Shizuku strings into ${stringsPath}`);
return;
}
writeFileSync(stringsPath, merged.content, 'utf8');
console.log(`Merged Shizuku strings into ${stringsPath}`);
}
function copyDirectoryContents(srcRoot, destRoot, dryRun) {
if (!existsSync(srcRoot)) {
throw new Error(`Missing Android icon resources: ${srcRoot}`);
}
ensureDir(destRoot, dryRun);
for (const entry of readdirSync(srcRoot)) {
const src = join(srcRoot, entry);
const dest = join(destRoot, entry);
if (statSync(src).isDirectory()) {
copyDirectoryContents(src, dest, dryRun);
continue;
}
if (dryRun) {
console.log(`[dry-run] Would copy ${src} -> ${dest}`);
continue;
}
ensureDir(dirname(dest), dryRun);
copyFileSync(src, dest);
console.log(`Copied ${dest}`);
}
}
function copyNamedFiles(files, srcRoot, destRoot, dryRun) {
ensureDir(destRoot, dryRun);
for (const file of files) {
const src = join(srcRoot, file);
const dest = join(destRoot, file);
if (!existsSync(src)) {
throw new Error(`Missing scaffolding file: ${src}`);
}
if (dryRun) {
console.log(`[dry-run] Would copy ${src} -> ${dest}`);
continue;
}
copyFileSync(src, dest);
console.log(`Copied ${file}`);
}
}
function ensureInstrumentationRunner(dryRun) {
if (!existsSync(androidAppGradle)) {
throw new Error(`Missing generated Android Gradle file: ${androidAppGradle}`);
}
const existing = readFileSync(androidAppGradle, 'utf8');
if (existing.includes('testInstrumentationRunner')) {
console.log(`Android instrumentation runner already present in ${androidAppGradle}; skipping.`);
return;
}
const defaultConfig = /^(\s*)defaultConfig\s*\{\s*$/m;
const match = existing.match(defaultConfig);
if (!match) {
throw new Error(`defaultConfig block not found in ${androidAppGradle}`);
}
const runner =
`${match[0]}\n${match[1]} ` +
'testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"';
const updated = existing.replace(defaultConfig, runner);
if (dryRun) {
console.log(`[dry-run] Would add testInstrumentationRunner to ${androidAppGradle}`);
return;
}
writeFileSync(androidAppGradle, updated, 'utf8');
console.log(`Added Android instrumentation runner to ${androidAppGradle}`);
}
function ensureMainActivityOpen(dryRun) {
if (!existsSync(mainActivityPath)) return;
const existing = readFileSync(mainActivityPath, 'utf8');
const updated = existing.replace(
/(?:open\s+)*class MainActivity\s*:/,
'open class MainActivity:',
);
if (updated === existing) return;
if (dryRun) {
console.log(`[dry-run] Would make MainActivity inheritable for background warmup`);
return;
}
writeFileSync(mainActivityPath, updated, 'utf8');
console.log(`Made MainActivity inheritable for background warmup`);
}
function main() {
const { dryRun } = parseArgs(process.argv.slice(2));
if (!existsSync(join(appRoot, 'src-tauri/gen/android'))) {
throw new Error(
`Generated Android project not found under src-tauri/gen/android.\nRun "npm run tauri -- android init --ci" first.`,
);
}
ensureDir(kotlinDest, dryRun);
ensureDir(kotlinTestDest, dryRun);
ensureDir(kotlinAndroidTestDest, dryRun);
ensureDir(resXmlDest, dryRun);
if (existsSync(aidlRoot)) {
copyDirectoryContents(aidlRoot, aidlDest, dryRun);
}
copyDirectoryContents(androidIconRoot, resDest, dryRun);
if (existsSync(androidAssetsRoot)) {
copyDirectoryContents(androidAssetsRoot, assetsDest, dryRun);
}
// Generated projects survive upgrades. Retire only known obsolete files so
// an incremental build cannot keep packaging the removed pinyin engine.
for (const name of [
'LitePinyinController.kt',
'LitePinyinRepository.kt',
'LitePinyinUserFrequency.kt',
'LitePinyinLearnedPhrases.kt',
]) {
const path = join(kotlinDest, name);
if (dryRun) console.log(`[dry-run] Would remove retired source ${path}`);
else rmSync(path, { force: true });
}
for (const name of [
'pinyin_chars.tsv',
'pinyin_phrases.tsv',
'pinyin_chars.LICENSE.txt',
'pinyin_phrases.LICENSE.txt',
'pinyin_dictionary_meta.json',
]) {
const path = join(assetsDest, name);
if (dryRun) console.log(`[dry-run] Would remove retired asset ${path}`);
else rmSync(path, { force: true });
}
copyNamedFiles(KOTLIN_FILES, kotlinRoot, kotlinDest, dryRun);
ensureMainActivityOpen(dryRun);
copyNamedFiles(KOTLIN_TEST_FILES, kotlinTestRoot, kotlinTestDest, dryRun);
copyNamedFiles(KOTLIN_ANDROID_TEST_FILES, kotlinAndroidTestRoot, kotlinAndroidTestDest, dryRun);
ensureInstrumentationRunner(dryRun);
for (const [relSrc, destName] of XML_FILES) {
const src = join(manifestsRoot, relSrc);
const dest = join(resXmlDest, destName);
const content = existsSync(src) ? readFileSync(src, 'utf8') : GENERATED_ACCESSIBILITY_CONFIG;
if (dryRun) {
console.log(`[dry-run] Would write ${dest}`);
continue;
}
writeFileSync(dest, content, 'utf8');
console.log(`Wrote ${destName}`);
}
mergeStringsXml(dryRun);
}
try {
const isDirectRun = Boolean(
process.argv[1]?.replace(/\\/g, '/').endsWith('copy-android-scaffolding.mjs'),
);
if (isDirectRun) {
main();
}
} catch (error) {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
}