Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added support for ChromeOS remap, fix: typo local genKlc #7

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ Modify, and generate keyboard layout from single JSON file. Built with TypeScrip
- `.klc` (Windows)
- `.kcm` (Android Physical keyboard)
- XKB (Linux)
- remap extension for Chrome OS (Manifest V3) (icons must be added manually / alphanumeric-shortcut keys will not work.)
20 changes: 20 additions & 0 deletions cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { generateKeylayout } from "./generateKeylayout"
import { generateKlc } from "./generateKlc"
import { generateXkb } from "./generateXkb"
import { generateKcm } from "./generateKcm"
import { generateChr_background } from "./generateChr_background"
import { generateChr_manifest } from "./generateChr_manifest"
import { fixUnicode } from "./utils"

// eslint-disable-next-line @typescript-eslint/no-var-requires
Expand Down Expand Up @@ -94,4 +96,22 @@ const choices = filenames.map((filename) => ({
console.error(e)
process.exit(1)
}

// Chr___OS
try {
const layoutName = response.input.split(".").slice(0, -1).join(".")
const dir = `output/${layoutName}/${jsonInput.os.windows.installerName.toLowerCase()}`
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
const outputManifest = dir+`/manifest.json`
await generateChr_manifest(jsonInput, outputManifest)
console.log(`Output : ${outputManifest}`)
const outputBackground = dir+`/background.js`
await generateChr_background(jsonInput, outputBackground)
console.log(`Output : ${outputBackground}`)
} catch (e) {
console.error(e)
process.exit(1)
}
})()
192 changes: 192 additions & 0 deletions generateChr_background.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
import {
plainToClass
} from "class-transformer"
import {
validate
} from "class-validator"
import fs from "fs"
import {
Layout,
WindowsAttributes
} from "./main"

export async function generateChr_background(
content: Record < string, unknown > ,
outputPath: string,
): Promise < void > {
const layout = plainToClass(Layout, content)
const errors = await validate(layout)

if (errors.length) {
throw new Error(errors.map((e) => e.toString()).join(", "))
}

const windowsErrors = await validate(
plainToClass(WindowsAttributes, layout.os.windows),
)

if (windowsErrors.length) {
throw new Error(windowsErrors.map((e) => e.toString()).join(", "))
}

function toCheck(str: string) {
// let hex, i
// let result = ""
// for (i = 0; i < str.length; i++) {
// hex = str.charCodeAt(i).toString(16)
// result += "\\u" + ("0000" + hex).slice(-4)
// }
return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}

const klfDefaultLayout = {
"1": "Digit1",
"2": "Digit2",
"3": "Digit3",
"4": "Digit4",
"5": "Digit5",
"6": "Digit6",
"7": "Digit7",
"8": "Digit8",
"9": "Digit9",
"0": "Digit0",
"-": "Minus",
"=": "Equal",
"`": "Backquote",
q: "KeyQ",
w: "KeyW",
e: "KeyE",
r: "KeyR",
t: "KeyT",
y: "KeyY",
u: "KeyU",
i: "KeyI",
o: "KeyO",
p: "KeyP",
"[": "BracketLeft",
"]": "BracketRight",
a: "KeyA",
s: "KeyS",
d: "KeyD",
f: "KeyF",
g: "KeyG",
h: "KeyH",
j: "KeyJ",
k: "KeyK",
l: "KeyL",
";": "Semicolon",
"'": "Quote",
"\\": "Backslash",
z: "KeyZ",
x: "KeyX",
c: "KeyC",
v: "KeyV",
b: "KeyB",
n: "KeyN",
m: "KeyM",
",": "Comma",
".": "Period",
"/": "Slash",
" ": "Space",
KPDL: "NumpadDecimal",
}

const lines = `/*# License: ${layout.license}
Generated via github.com/Manoonchai/kiimo
*/
var AltGr = { PLAIN: "plain", ALTERNATE: "alternate" };
var Shift = { PLAIN: "plain", SHIFTED: "shifted" };

var contextID = -1;
var altGrState = AltGr.PLAIN;
var shiftState = Shift.PLAIN;
var lastRemappedKeyEvent = undefined;

var lut = {`

const endLines = `
};


chrome.input.ime.onFocus.addListener(function(context) {
contextID = context.contextID;
});

function updateAltGrState(keyData) {
altGrState = (keyData.code == "AltRight") ? ((keyData.type == "keydown") ? AltGr.ALTERNATE : AltGr.PLAIN)
: altGrState;
}

function updateShiftState(keyData) {
shiftState = ((keyData.shiftKey && !(keyData.capsLock)) || (!(keyData.shiftKey) && keyData.capsLock)) ?
Shift.SHIFTED : Shift.PLAIN;
}

function isPureModifier(keyData) {
return (keyData.key == "Shift") || (keyData.key == "Ctrl") || (keyData.key == "Alt");
}

function isRemappedEvent(keyData) {
// hack, should check for a sender ID (to be added to KeyData)
return lastRemappedKeyEvent != undefined &&
(lastRemappedKeyEvent.key == keyData.key &&
lastRemappedKeyEvent.code == keyData.code &&
lastRemappedKeyEvent.type == keyData.type
); // requestID would be different so we are not checking for it
}


chrome.input.ime.onKeyEvent.addListener(
function(engineID, keyData) {
var handled = false;

if (isRemappedEvent(keyData)) {
lastRemappedKeyEvent = undefined;
return handled;
}

updateAltGrState(keyData);
updateShiftState(keyData);

if (lut[keyData.code]) {
//avoid hell key:process loop
if (keyData.ctrlKey === true && keyData.code != "Space") {
return;
}
var remappedKeyData = keyData;
remappedKeyData.key = lut[keyData.code][altGrState][shiftState];
remappedKeyData.code = lut[keyData.code].code;

if (chrome.input.ime.sendKeyEvents != undefined) {
chrome.input.ime.sendKeyEvents({"contextID": contextID, "keyData": [remappedKeyData]});
handled = true;
lastRemappedKeyEvent = remappedKeyData;
} else if (keyData.type == "keydown" && !isPureModifier(keyData)) {
chrome.input.ime.commitText({"contextID": contextID, "text": remappedKeyData.key});
handled = true;
}
}

return handled;
});
`

const layoutLines = [""]
Object.entries(klfDefaultLayout).forEach(([key, value]) => {
const extensions =
`: { "plain": {"plain": "${toCheck(layout.keys[key][0])}"` +
`, "shifted": "${toCheck(layout.keys[key][1])}"}` +
`, "alternate": {"plain": "${toCheck(layout.keys[key][3])}"` +
`, "shifted":"${toCheck(layout.keys[key][5])}"}, ` +
`"code": "${value}"},`

layoutLines.push([`"${value}"`, ...extensions].join(""))
})

fs.writeFileSync(
outputPath,
[lines, layoutLines.join("\n"),endLines].join(""), {
encoding: "utf8",
},
)
}
67 changes: 67 additions & 0 deletions generateChr_manifest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { plainToClass } from "class-transformer"
import { validate } from "class-validator"
import fs from "fs"
import { Layout, WindowsAttributes } from "./main"

export async function generateChr_manifest(
content: Record<string, unknown>,
outputPath: string,
): Promise<void> {
const layout = plainToClass(Layout, content)
const errors = await validate(layout)

if (errors.length) {
throw new Error(errors.map((e) => e.toString()).join(", "))
}

const windowsErrors = await validate(
plainToClass(WindowsAttributes, layout.os.windows),
)

if (windowsErrors.length) {
throw new Error(windowsErrors.map((e) => e.toString()).join(", "))
}

const chrLocales = {
Thai: "th",
Lao: "la",
}

const lines =
`{
"name": "${layout.language} ${layout.name} v${layout.version}",
"version": "${layout.version}",
"manifest_version": 3,
"description": "${layout.language} ${layout.name} v${layout.version}",
"background": {
"service_worker": "background.js"
},
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
},
"permissions": [
"input"
],
"input_components": [
{
"name": "${layout.language} ${layout.name} v${layout.version}",
"type": "ime",
"id": "${chrLocales[layout.language as keyof typeof chrLocales]}_${layout.name.toLowerCase()}_remap",
"description": "${layout.language} ${layout.name} v${layout.version}",
"language": "${chrLocales[layout.language as keyof typeof chrLocales]}",
"layouts": ["la(stea)"]
}
]
}`
//"layouts": ["la(stea)"] due all embed-thai-layout lack of "level3(ralt_switch)", use laos instead.

fs.writeFileSync(
outputPath,
lines,
{
encoding: "utf8",
},
)
}
6 changes: 3 additions & 3 deletions input/Manoonchai_Laos.json → input/Manoonchai_Lao.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"name": "Manoonchai Laos Pali",
"name": "Manoonchai Lao-Pali",
"version": "1.0",
"language": "Laos",
"language": "Lao",
"layers": ["Base", "Shift", "Command", "AltGr", "Control", "ShiftAltGr"],
"license": "MIT",
"os": {
"windows": {
"installerName": "LaosMnc",
"installerName": "LaoMnc",
"company": "Manoonchai",
"localeId": "00000454"
}
Expand Down
Loading
Loading