@hnode/tidy 0.18.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,175 @@
1
+ import {spawn, spawnSync} from 'node:child_process';
2
+ import {cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync} from 'node:fs';
3
+ import {homedir} from 'node:os';
4
+ import {delimiter, dirname, join, relative, sep} from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+
7
+ const sourceRoot = dirname(dirname(fileURLToPath(import.meta.url)));
8
+ const readJSON = path => { try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; } };
9
+
10
+ function npmScript(env) {
11
+ const candidates = [env.npm_execpath, join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),
12
+ join(dirname(process.execPath), '../lib/node_modules/npm/bin/npm-cli.js')];
13
+ for (const directory of (env.PATH || '').split(delimiter)) {
14
+ if (directory) candidates.push(join(directory, 'npm'), join(directory, 'node_modules/npm/bin/npm-cli.js'));
15
+ }
16
+ return candidates.filter(Boolean).filter(existsSync).map(path => realpathSync(path))
17
+ .find(path => path.endsWith('.js'));
18
+ }
19
+
20
+ export function desktopPaths(home = homedir()) {
21
+ const base = join(home, 'Library', 'Application Support', 'Tidy');
22
+ const install = join(base, 'desktop');
23
+ return {base, install, config: join(base, 'config'), status: join(base, 'status.json')};
24
+ }
25
+
26
+ export function launchSpec(install) {
27
+ const binary = join(install, 'Tidy.app', 'Contents', 'MacOS', 'Electron');
28
+ // LaunchServices gives Tidy its own macOS permission identity instead of
29
+ // attributing Accessibility requests to the terminal that ran the CLI.
30
+ return {executable: '/usr/bin/open', binary, args: ['-n', '-a', join(install, 'Tidy.app'), '--args']};
31
+ }
32
+
33
+ export function desktopCommand(command, {platform = process.platform, env = process.env, packageRoot = sourceRoot,
34
+ run = spawnSync, launch = spawn, out = console.log, error = console.error, paths = desktopPaths()} = {}) {
35
+ const options = {env, encoding: 'utf8'};
36
+ const checked = (executable, args, extra = {}) => {
37
+ const result = run(executable, args, {...options, ...extra});
38
+ if (result.error || result.status !== 0)
39
+ throw new Error(result.error?.message || result.stderr?.trim() || `${executable} failed (${result.status}).`);
40
+ return result.stdout?.trim() ?? '';
41
+ };
42
+ const open = (install, flag) => {
43
+ const spec = launchSpec(install);
44
+ if (!existsSync(spec.binary)) throw new Error('Desktop runtime is missing. Run tidy install again.');
45
+ // Never inherit ELECTRON_RUN_AS_NODE from a terminal/editor environment.
46
+ const childEnv = {...env, TIDY_DATA_DIR: paths.base};
47
+ delete childEnv.ELECTRON_RUN_AS_NODE;
48
+ const child = launch(spec.executable, [...spec.args, flag], {env: childEnv, detached: true, stdio: 'ignore'});
49
+ child.on('error', e => error(e.message));
50
+ child.unref();
51
+ return child;
52
+ };
53
+ const alive = () => {
54
+ const state = readJSON(paths.status);
55
+ if (!state || Date.now() - state.updated > 10000) return false;
56
+ try { process.kill(state.pid, 0); return true; } catch { return false; }
57
+ };
58
+ const stop = () => {
59
+ if (!alive()) return;
60
+ const pid = readJSON(paths.status).pid;
61
+ const processAlive = () => { try { process.kill(pid, 0); return true; } catch { return false; } };
62
+ open(paths.install, '--quit');
63
+ const deadline = Date.now() + 10000;
64
+ while (processAlive() && Date.now() < deadline) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
65
+ if (processAlive()) throw new Error('Quit Tidy from its menu bar icon, then retry.');
66
+ };
67
+ const waitStarted = since => {
68
+ const deadline = Date.now() + 30000;
69
+ do {
70
+ const state = readJSON(paths.status);
71
+ if (state?.updated >= since) {
72
+ if (state.error && state.trusted === undefined) throw new Error(state.error);
73
+ if (alive()) return;
74
+ }
75
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
76
+ } while (Date.now() < deadline);
77
+ throw new Error('Tidy did not start. Check tidy status and your desktop session.');
78
+ };
79
+ try {
80
+ if (platform !== 'darwin') throw new Error('The desktop app requires macOS. Use the GNOME extension on Linux.');
81
+ if (command === 'status') {
82
+ if (!existsSync(join(paths.install, 'installed.json'))) throw new Error('Tidy is not installed. Run tidy install first.');
83
+ out(JSON.stringify({installed: readJSON(join(paths.install, 'installed.json')), running: alive(),
84
+ runtime: readJSON(paths.status), config: paths.config}, null, 2));
85
+ return 0;
86
+ }
87
+ if (command === 'prefs') {
88
+ if (!existsSync(join(paths.install, 'installed.json'))) throw new Error('Tidy is not installed. Run tidy install first.');
89
+ open(paths.install, '--settings');
90
+ return 0;
91
+ }
92
+ if (command === 'uninstall') {
93
+ if (!existsSync(paths.install)) { out('Tidy is not installed.'); return 0; }
94
+ // The running app removes its own login item before exiting.
95
+ const spec = launchSpec(paths.install);
96
+ const childEnv = {...env, TIDY_DATA_DIR: paths.base};
97
+ delete childEnv.ELECTRON_RUN_AS_NODE;
98
+ checked(spec.executable, ['-W', ...spec.args, '--uninstall'], {env: childEnv, timeout: 20000});
99
+ stop();
100
+ rmSync(paths.install, {recursive: true, force: true, maxRetries: 20, retryDelay: 250});
101
+ rmSync(paths.status, {force: true});
102
+ out('Tidy removed. Settings are preserved for reinstallation.');
103
+ return 0;
104
+ }
105
+ const node = process.versions.node.split('.').map(Number);
106
+ if (node[0] < 22 || (node[0] === 22 && node[1] < 12))
107
+ throw new Error('macOS installation requires Node.js 22.12 or later.');
108
+ checked('xcrun', ['--find', 'swiftc']);
109
+ if (command === 'doctor') {
110
+ out('Swift compiler and Node.js are available. Grant Tidy Accessibility permission after installation.');
111
+ out(`Installation: ${paths.install}`);
112
+ return 0;
113
+ }
114
+ mkdirSync(paths.base, {recursive: true});
115
+ const stage = mkdtempSync(join(paths.base, 'desktop-next-'));
116
+ const backup = join(paths.base, 'desktop-previous');
117
+ try {
118
+ const runtime = join(stage, 'runtime');
119
+ mkdirSync(runtime);
120
+ const desktopManifest = readJSON(join(packageRoot, 'desktop', 'package.json'));
121
+ writeFileSync(join(runtime, 'package.json'), JSON.stringify({private: true, dependencies: desktopManifest.dependencies}));
122
+ cpSync(join(packageRoot, 'desktop', 'package-lock.json'), join(runtime, 'package-lock.json'));
123
+ out('Downloading the desktop runtime…');
124
+ // Invoke npm through Node with literal arguments, including paths with spaces.
125
+ const npmCLI = npmScript(env);
126
+ if (!npmCLI) throw new Error('npm was not found. Run npx @hnode/tidy install or reinstall Node.js with npm.');
127
+ checked(process.execPath, [npmCLI, 'ci', '--prefix', runtime, '--no-audit', '--no-fund', '--ignore-scripts'], {stdio: 'inherit'});
128
+ checked(process.execPath, [join(runtime, 'node_modules', 'electron', 'install.js')], {stdio: 'inherit'});
129
+ renameSync(join(runtime, 'node_modules', 'electron', 'dist', 'Electron.app'), join(stage, 'Tidy.app'));
130
+ const appRoot = join(stage, 'Tidy.app', 'Contents', 'Resources', 'app');
131
+ mkdirSync(join(appRoot, 'lib'), {recursive: true});
132
+ const desktopSource = join(packageRoot, 'desktop');
133
+ cpSync(desktopSource, join(appRoot, 'desktop'), {recursive: true,
134
+ filter: path => !relative(desktopSource, path).split(sep).includes('node_modules')});
135
+ for (const name of ['layouts.js', 'i18nCore.js', 'translations.json'])
136
+ cpSync(join(packageRoot, 'lib', name), join(appRoot, 'lib', name));
137
+ for (const name of ['LICENSE', 'NOTICE']) cpSync(join(packageRoot, name), join(appRoot, name));
138
+ const version = readJSON(join(packageRoot, 'package.json')).version;
139
+ writeFileSync(join(appRoot, 'package.json'), JSON.stringify({name: 'tidy', productName: 'Tidy', version,
140
+ type: 'module', main: 'desktop/main.js'}));
141
+ const helper = join(appRoot, 'desktop', 'native', 'tidy-native');
142
+ checked('xcrun', ['swiftc', '-O', join(appRoot, 'desktop', 'native', 'macos.swift'), '-o', helper]);
143
+ checked('codesign', ['--force', '--sign', '-', '--identifier', 'local.tidy.window-helper', helper]);
144
+ const plist = join(stage, 'Tidy.app', 'Contents', 'Info.plist');
145
+ for (const [key, value] of [['CFBundleIdentifier', 'local.tidy.desktop'], ['CFBundleName', 'Tidy'],
146
+ ['CFBundleDisplayName', 'Tidy'], ['CFBundleShortVersionString', version], ['CFBundleVersion', version]]) {
147
+ const result = run('/usr/libexec/PlistBuddy', ['-c', `Set :${key} ${value}`, plist], options);
148
+ if (result.status !== 0) checked('/usr/libexec/PlistBuddy', ['-c', `Add :${key} string ${value}`, plist]);
149
+ }
150
+ checked('codesign', ['--force', '--deep', '--sign', '-', '--preserve-metadata=entitlements', join(stage, 'Tidy.app')]);
151
+ writeFileSync(join(stage, 'installed.json'), JSON.stringify({version, platform, installed: new Date().toISOString()}));
152
+ stop();
153
+ rmSync(backup, {recursive: true, force: true});
154
+ if (existsSync(paths.install)) renameSync(paths.install, backup);
155
+ try { renameSync(stage, paths.install); }
156
+ catch (e) { if (existsSync(backup)) renameSync(backup, paths.install); throw e; }
157
+ let child;
158
+ try {
159
+ const since = Date.now();
160
+ child = open(paths.install, '--settings');
161
+ if (!child.pid) throw new Error('Could not start the desktop runtime.');
162
+ waitStarted(since);
163
+ } catch (failure) {
164
+ child?.kill();
165
+ rmSync(paths.status, {force: true});
166
+ rmSync(paths.install, {recursive: true, force: true, maxRetries: 20, retryDelay: 250});
167
+ if (existsSync(backup)) { renameSync(backup, paths.install); open(paths.install, '--background'); }
168
+ throw failure;
169
+ }
170
+ rmSync(backup, {recursive: true, force: true, maxRetries: 20, retryDelay: 250});
171
+ out('Tidy installed and started. Use the menu bar icon to choose layouts and settings.');
172
+ } finally { rmSync(stage, {recursive: true, force: true}); }
173
+ return 0;
174
+ } catch (e) { error(e.message); return 1; }
175
+ }
@@ -0,0 +1,110 @@
1
+ import AppKit
2
+ import ApplicationServices
3
+
4
+ // Keep AX references alive so choosing a picker cell never retargets another window.
5
+ var windows: [String: AXUIElement] = [:]
6
+ var windowOrder: [String] = []
7
+ let application = NSApplication.shared
8
+ application.setActivationPolicy(.prohibited)
9
+
10
+ enum NativeError: Error { case message(String) }
11
+ func attribute(_ element: AXUIElement, _ key: String) -> CFTypeRef? {
12
+ var value: CFTypeRef?
13
+ guard AXUIElementCopyAttributeValue(element, key as CFString, &value) == .success else { return nil }
14
+ return value
15
+ }
16
+ func rectOf(_ window: AXUIElement) -> [String: Double]? {
17
+ guard let p = attribute(window, kAXPositionAttribute), let s = attribute(window, kAXSizeAttribute),
18
+ CFGetTypeID(p) == AXValueGetTypeID(), CFGetTypeID(s) == AXValueGetTypeID() else { return nil }
19
+ var point = CGPoint.zero
20
+ var size = CGSize.zero
21
+ guard AXValueGetValue(unsafeBitCast(p, to: AXValue.self), .cgPoint, &point),
22
+ AXValueGetValue(unsafeBitCast(s, to: AXValue.self), .cgSize, &size) else { return nil }
23
+ // AX uses a top-left origin in points, matching Electron on macOS.
24
+ return ["x": point.x, "y": point.y, "width": size.width, "height": size.height]
25
+ }
26
+ func snapshot(_ ignorePid: Int32) -> [String: Any] {
27
+ var result: [String: Any] = ["window": NSNull(), "mouseDown": CGEventSource.buttonState(.combinedSessionState, button: .left),
28
+ "trusted": AXIsProcessTrusted()]
29
+ guard AXIsProcessTrusted(), let front = NSWorkspace.shared.frontmostApplication,
30
+ front.processIdentifier != ignorePid else { return result }
31
+ let app = AXUIElementCreateApplication(front.processIdentifier)
32
+ AXUIElementSetMessagingTimeout(app, 0.25)
33
+ guard let value = attribute(app, kAXFocusedWindowAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() else { return result }
34
+ let window = unsafeBitCast(value, to: AXUIElement.self)
35
+ guard let rect = rectOf(window) else { return result }
36
+ let id = "\(front.processIdentifier):\(CFHash(window))"
37
+ if windows[id] == nil { windowOrder.append(id) }
38
+ windows[id] = window
39
+ if windowOrder.count > 256 { windows.removeValue(forKey: windowOrder.removeFirst()) }
40
+ var movable = DarwinBoolean(false), sizable = DarwinBoolean(false)
41
+ AXUIElementIsAttributeSettable(window, kAXPositionAttribute as CFString, &movable)
42
+ AXUIElementIsAttributeSettable(window, kAXSizeAttribute as CFString, &sizable)
43
+ result["window"] = ["id": id, "pid": front.processIdentifier, "rect": rect,
44
+ "resizable": movable.boolValue && sizable.boolValue,
45
+ "fullscreen": (attribute(window, "AXFullScreen") as? Bool) ?? false]
46
+ return result
47
+ }
48
+ func place(_ request: [String: Any]) throws -> [String: Double] {
49
+ guard AXIsProcessTrusted() else {
50
+ throw NativeError.message("Allow Tidy in System Settings > Privacy & Security > Accessibility, then restart Tidy.")
51
+ }
52
+ guard let target = request["window"] as? [String: Any], let id = target["id"] as? String,
53
+ let expectedPid = target["pid"] as? Int32, let window = windows[id],
54
+ let rect = request["rect"] as? [String: Double], let x = rect["x"], let y = rect["y"],
55
+ let width = rect["width"], let height = rect["height"], width > 0, height > 0 else {
56
+ throw NativeError.message("The selected window has closed or its size is invalid.")
57
+ }
58
+ var pid: pid_t = 0
59
+ guard AXUIElementGetPid(window, &pid) == .success, pid == expectedPid else {
60
+ throw NativeError.message("The selected window has closed.")
61
+ }
62
+ guard (attribute(window, "AXFullScreen") as? Bool) != true else {
63
+ throw NativeError.message("Leave fullscreen before arranging this window.")
64
+ }
65
+ var point = CGPoint(x: x, y: y), size = CGSize(width: width, height: height)
66
+ let position = AXValueCreate(.cgPoint, &point)!
67
+ let dimensions = AXValueCreate(.cgSize, &size)!
68
+ // Some apps constrain position using the old size; repeat position after resize.
69
+ AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, position)
70
+ let resize = AXUIElementSetAttributeValue(window, kAXSizeAttribute as CFString, dimensions)
71
+ let move = AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, position)
72
+ guard resize == .success, move == .success else {
73
+ throw NativeError.message("This app refused to move or resize (AX error \(move.rawValue)/\(resize.rawValue)).")
74
+ }
75
+ AXUIElementPerformAction(window, kAXRaiseAction as CFString)
76
+ NSRunningApplication(processIdentifier: pid)?.activate(options: [])
77
+ guard let actual = rectOf(window) else { throw NativeError.message("Could not read the resized window.") }
78
+ return actual
79
+ }
80
+ func respond(_ line: String) -> [String: Any] {
81
+ var id: Any = NSNull()
82
+ do {
83
+ guard let data = line.data(using: .utf8),
84
+ let request = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
85
+ throw NativeError.message("Invalid request.")
86
+ }
87
+ id = request["id"] ?? NSNull()
88
+ let result: Any
89
+ switch request["op"] as? String {
90
+ case "snapshot": result = snapshot((request["ignorePid"] as? Int32) ?? 0)
91
+ case "place": result = try place(request)
92
+ case "permissions":
93
+ let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: request["prompt"] as? Bool ?? false]
94
+ result = ["trusted": AXIsProcessTrustedWithOptions(options as CFDictionary)]
95
+ default: throw NativeError.message("Unknown native operation.")
96
+ }
97
+ return ["id": id, "result": result]
98
+ } catch NativeError.message(let message) { return ["id": id, "error": message] }
99
+ catch { return ["id": id, "error": error.localizedDescription] }
100
+ }
101
+ while let line = readLine() {
102
+ autoreleasepool {
103
+ let response = respond(line)
104
+ if let data = try? JSONSerialization.data(withJSONObject: response, options: [.sortedKeys]),
105
+ let text = String(data: data, encoding: .utf8) {
106
+ print(text)
107
+ fflush(stdout)
108
+ }
109
+ }
110
+ }
@@ -0,0 +1,67 @@
1
+ import {spawn} from 'node:child_process';
2
+ import {createInterface} from 'node:readline';
3
+ import {join} from 'node:path';
4
+
5
+ export class NativeBridge {
6
+ constructor(directory, {launch = spawn, ignorePid = process.pid} = {}) {
7
+ this.ignorePid = ignorePid;
8
+ this.pending = new Map();
9
+ this.sequence = 0;
10
+ this.child = launch(join(directory, 'tidy-native'), [], {stdio: ['pipe', 'pipe', 'pipe']});
11
+ this.failure = null;
12
+ this.stderr = '';
13
+ this.child.stderr.on('data', data => { this.stderr = (this.stderr + data).slice(-4000); });
14
+ createInterface({input: this.child.stdout}).on('line', line => {
15
+ let response;
16
+ try { response = JSON.parse(line); } catch { return; }
17
+ const pending = this.pending.get(response.id);
18
+ if (!pending) return;
19
+ clearTimeout(pending.timer);
20
+ this.pending.delete(response.id);
21
+ if (response.error) pending.reject(new Error(response.error));
22
+ else pending.resolve(response.result);
23
+ });
24
+ const fail = error => {
25
+ this.failure = error;
26
+ for (const pending of this.pending.values()) {
27
+ clearTimeout(pending.timer);
28
+ pending.reject(error);
29
+ }
30
+ this.pending.clear();
31
+ };
32
+ this.child.on('error', fail);
33
+ this.child.stdin.on('error', fail);
34
+ this.child.on('exit', () => fail(new Error(`Native window helper stopped. ${this.stderr}`)));
35
+ }
36
+
37
+ request(op, values = {}) {
38
+ if (this.failure) return Promise.reject(this.failure);
39
+ const id = ++this.sequence;
40
+ return new Promise((resolve, reject) => {
41
+ const timer = setTimeout(() => {
42
+ this.pending.delete(id);
43
+ reject(new Error('Native window helper timed out.'));
44
+ }, 15000);
45
+ this.pending.set(id, {resolve, reject, timer});
46
+ this.child.stdin.write(`${JSON.stringify({id, op, ignorePid: this.ignorePid, ...values})}\n`);
47
+ });
48
+ }
49
+
50
+ snapshot() { return this.request('snapshot'); }
51
+
52
+ place(window, rect) {
53
+ return this.request('place', {window: {id: window.id, pid: window.pid}, rect});
54
+ }
55
+
56
+ close() {
57
+ if (this.closing) return this.closing;
58
+ this.closing = new Promise(resolve => {
59
+ if (this.failure) { resolve(); return; }
60
+ const timer = setTimeout(() => { this.child.kill(); resolve(); }, 5000);
61
+ this.child.once('exit', () => { clearTimeout(timer); resolve(); });
62
+ // Let the native helper finish its requests before exiting on EOF.
63
+ this.child.stdin.end();
64
+ });
65
+ return this.closing;
66
+ }
67
+ }
@@ -0,0 +1,161 @@
1
+ {
2
+ "name": "tidy-desktop",
3
+ "version": "0.20.0",
4
+ "lockfileVersion": 3,
5
+ "requires": true,
6
+ "packages": {
7
+ "": {
8
+ "name": "tidy-desktop",
9
+ "version": "0.20.0",
10
+ "dependencies": {
11
+ "electron": "45.2.3"
12
+ }
13
+ },
14
+ "node_modules/@electron-internal/extract-zip": {
15
+ "version": "1.0.8",
16
+ "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.8.tgz",
17
+ "integrity": "sha512-8iajeLFbzNwM0m3AsQZSZgYREWglAImyGvvFSWU34FgMW8sHlzdwj9QKvv9dgN7jMP591EFUF/sLOC3Jl9YIjQ==",
18
+ "license": "MIT",
19
+ "engines": {
20
+ "node": ">=22.12.0"
21
+ }
22
+ },
23
+ "node_modules/@electron/get": {
24
+ "version": "5.1.0",
25
+ "resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
26
+ "integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
27
+ "license": "MIT",
28
+ "dependencies": {
29
+ "debug": "^4.1.1",
30
+ "env-paths": "^3.0.0",
31
+ "graceful-fs": "^4.2.11",
32
+ "progress": "^2.0.3",
33
+ "semver": "^7.6.3",
34
+ "sumchecker": "^3.0.1"
35
+ },
36
+ "engines": {
37
+ "node": ">=22.12.0"
38
+ },
39
+ "optionalDependencies": {
40
+ "undici": "^7.24.4"
41
+ }
42
+ },
43
+ "node_modules/@types/node": {
44
+ "version": "24.19.2",
45
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz",
46
+ "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==",
47
+ "license": "MIT",
48
+ "dependencies": {
49
+ "undici-types": ">=7.24.0 <7.24.7"
50
+ }
51
+ },
52
+ "node_modules/debug": {
53
+ "version": "4.4.3",
54
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
55
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
56
+ "license": "MIT",
57
+ "dependencies": {
58
+ "ms": "^2.1.3"
59
+ },
60
+ "engines": {
61
+ "node": ">=6.0"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "supports-color": {
65
+ "optional": true
66
+ }
67
+ }
68
+ },
69
+ "node_modules/electron": {
70
+ "version": "45.2.3",
71
+ "resolved": "https://registry.npmjs.org/electron/-/electron-45.2.3.tgz",
72
+ "integrity": "sha512-Vurzu5UOA5nTGT4LqIwXD16QFGrOZdiXxF+1UP4KNsAOo/YtDcT3/u0jhP4WSwNJ0iLrLDi85hzBJ0arnGDhyw==",
73
+ "license": "MIT",
74
+ "dependencies": {
75
+ "@electron-internal/extract-zip": "^1.0.1",
76
+ "@electron/get": "^5.0.0",
77
+ "@types/node": "^24.9.0"
78
+ },
79
+ "bin": {
80
+ "electron": "cli.js",
81
+ "install-electron": "install.js"
82
+ },
83
+ "engines": {
84
+ "node": ">= 22.12.0"
85
+ }
86
+ },
87
+ "node_modules/env-paths": {
88
+ "version": "3.0.0",
89
+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
90
+ "integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
91
+ "license": "MIT",
92
+ "engines": {
93
+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"
94
+ },
95
+ "funding": {
96
+ "url": "https://github.com/sponsors/sindresorhus"
97
+ }
98
+ },
99
+ "node_modules/graceful-fs": {
100
+ "version": "4.2.11",
101
+ "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
102
+ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
103
+ "license": "ISC"
104
+ },
105
+ "node_modules/ms": {
106
+ "version": "2.1.3",
107
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
108
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
109
+ "license": "MIT"
110
+ },
111
+ "node_modules/progress": {
112
+ "version": "2.0.3",
113
+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
114
+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
115
+ "license": "MIT",
116
+ "engines": {
117
+ "node": ">=0.4.0"
118
+ }
119
+ },
120
+ "node_modules/semver": {
121
+ "version": "7.8.6",
122
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
123
+ "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
124
+ "license": "ISC",
125
+ "bin": {
126
+ "semver": "bin/semver.js"
127
+ },
128
+ "engines": {
129
+ "node": ">=10"
130
+ }
131
+ },
132
+ "node_modules/sumchecker": {
133
+ "version": "3.0.1",
134
+ "resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",
135
+ "integrity": "sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==",
136
+ "license": "Apache-2.0",
137
+ "dependencies": {
138
+ "debug": "^4.1.0"
139
+ },
140
+ "engines": {
141
+ "node": ">= 8.0"
142
+ }
143
+ },
144
+ "node_modules/undici": {
145
+ "version": "7.30.1",
146
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz",
147
+ "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==",
148
+ "license": "MIT",
149
+ "optional": true,
150
+ "engines": {
151
+ "node": ">=20.18.1"
152
+ }
153
+ },
154
+ "node_modules/undici-types": {
155
+ "version": "7.24.6",
156
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
157
+ "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
158
+ "license": "MIT"
159
+ }
160
+ }
161
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "tidy-desktop",
3
+ "version": "0.20.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "main.js",
7
+ "dependencies": {
8
+ "electron": "45.2.3"
9
+ }
10
+ }
@@ -0,0 +1,11 @@
1
+ const {contextBridge, ipcRenderer} = require('electron');
2
+ contextBridge.exposeInMainWorld('tidy', {
3
+ state: () => ipcRenderer.invoke('tidy:state'),
4
+ save: value => ipcRenderer.invoke('tidy:save', value),
5
+ permissions: () => ipcRenderer.invoke('tidy:permissions'),
6
+ choose: zone => ipcRenderer.send('tidy:choose', zone),
7
+ regions: regions => ipcRenderer.send('tidy:regions', regions),
8
+ close: () => ipcRenderer.send('tidy:close'),
9
+ hover: callback => ipcRenderer.on('hover', (_event, zone) => callback(zone)),
10
+ changed: callback => ipcRenderer.on('changed', () => callback()),
11
+ });
@@ -0,0 +1,115 @@
1
+ const mode = new URLSearchParams(location.search).get('mode');
2
+ const root = document.querySelector('#app');
3
+ document.body.className = mode;
4
+ if (mode === 'preview') document.documentElement.style.background = 'transparent';
5
+ else {
6
+ const state = await window.tidy.state();
7
+ document.documentElement.lang = state.language;
8
+ const ko = state.language === 'ko';
9
+ const text = (en, korean) => ko ? korean : en;
10
+ const element = (tag, content, className) => {
11
+ const node = document.createElement(tag);
12
+ if (content) node.textContent = content;
13
+ if (className) node.className = className;
14
+ return node;
15
+ };
16
+ if (mode === 'picker') {
17
+ root.append(element('div', text('Choose a layout · Esc to close', '배치를 고르세요 · Esc로 닫기'), 'hint'));
18
+ const layouts = element('div', '', 'layouts');
19
+ for (const layout of state.layouts) {
20
+ const card = element('div');
21
+ card.append(element('div', state.labels[layout.name] ?? layout.name, 'layout-label'));
22
+ const diagram = element('div', '', 'diagram');
23
+ for (const zone of layout.zones) {
24
+ const [x, y, width, height] = state.zones[zone];
25
+ const button = element('button', '', 'zone');
26
+ button.dataset.zone = zone;
27
+ button.setAttribute('aria-label', `${state.labels[layout.name] ?? layout.name}: ${zone}`);
28
+ Object.assign(button.style, {left: `${x * 100}%`, top: `${y * 100}%`, width: `${width * 100}%`, height: `${height * 100}%`});
29
+ button.addEventListener('click', () => window.tidy.choose(zone));
30
+ diagram.append(button);
31
+ }
32
+ card.append(diagram);
33
+ layouts.append(card);
34
+ }
35
+ root.append(layouts);
36
+ const regions = () => window.tidy.regions([...document.querySelectorAll('.zone')].map(node => {
37
+ const {x, y, width, height} = node.getBoundingClientRect();
38
+ return {zone: node.dataset.zone, x, y, width, height};
39
+ }));
40
+ // Prepare hit regions before the picker is shown; a hidden window may
41
+ // not receive its first ResizeObserver notification until it paints.
42
+ regions();
43
+ new ResizeObserver(regions).observe(root);
44
+ window.tidy.hover(zone => document.querySelectorAll('.zone').forEach(node => node.classList.toggle('selected', node.dataset.zone === zone)));
45
+ document.addEventListener('keydown', event => { if (event.key === 'Escape') window.tidy.close(); });
46
+ } else {
47
+ root.append(element('h1', state.labels['Tidy Settings']));
48
+ root.append(element('p', text('Use the menu bar icon or a shortcut to arrange the active window.', '메뉴 막대 아이콘이나 단축키로 현재 창을 배치합니다.')));
49
+ const message = element('p', '', 'message');
50
+ const refresh = async () => {
51
+ const current = await window.tidy.state();
52
+ message.textContent = [current.lastError, current.shortcutFailures.length ?
53
+ `${text('Unavailable shortcuts', '사용할 수 없는 단축키')}: ${current.shortcutFailures.join(', ')}` : '',
54
+ !current.trusted ? text('Allow Tidy in System Settings → Privacy & Security → Accessibility, then restart Tidy.',
55
+ '시스템 설정 → 개인정보 보호 및 보안 → 손쉬운 사용에서 Tidy를 허용한 후 다시 실행하세요.') : ''].filter(Boolean).join('\n');
56
+ };
57
+ root.append(message);
58
+ await refresh();
59
+ window.tidy.changed(refresh);
60
+ if (!state.trusted) {
61
+ const permission = element('button', text('Open Accessibility permission', '손쉬운 사용 권한 요청'));
62
+ permission.onclick = async () => { await window.tidy.permissions(); await refresh(); };
63
+ root.append(permission);
64
+ }
65
+ const fields = {};
66
+ for (const [key, title, type] of [
67
+ ['gap', text('Window gap (px)', '창 사이 간격 (px)'), 'number'],
68
+ ['dragPicker', text('Show picker when dragging to the top', '상단으로 끌어 배치 선택기 열기'), 'checkbox'],
69
+ ['edgeSnap', text('Snap at screen edges', '화면 가장자리 배치'), 'checkbox'],
70
+ ['openAtLogin', text('Start at login', '로그인 시 자동 실행'), 'checkbox'],
71
+ ]) {
72
+ const label = element('label', title, 'setting');
73
+ const input = element('input');
74
+ input.type = type;
75
+ input.name = key;
76
+ if (type === 'number') { input.min = 0; input.max = 64; input.value = state.settings[key]; }
77
+ else input.checked = state.settings[key];
78
+ fields[key] = input;
79
+ label.append(input); root.append(label);
80
+ }
81
+ root.append(element('p', text('Shortcuts use Electron key names (e.g. Control+Alt+Left). Leave blank to disable.',
82
+ '단축키는 Control+Alt+Left 형식으로 입력합니다. 비워 두면 사용하지 않습니다.')));
83
+ const shortcuts = {};
84
+ for (const action of state.actions) {
85
+ const label = element('label', action.title, 'setting');
86
+ const input = element('input', '', 'shortcut');
87
+ input.type = 'text'; input.value = state.settings.shortcuts[action.id];
88
+ input.spellcheck = false;
89
+ shortcuts[action.id] = input;
90
+ label.append(input); root.append(label);
91
+ }
92
+ const buttons = element('div', '', 'buttons');
93
+ const save = element('button', text('Save', '저장'));
94
+ save.onclick = async () => {
95
+ try {
96
+ save.disabled = true;
97
+ await window.tidy.save({gap: Number(fields.gap.value), dragPicker: fields.dragPicker.checked,
98
+ edgeSnap: fields.edgeSnap.checked, openAtLogin: fields.openAtLogin.checked,
99
+ shortcuts: Object.fromEntries(Object.entries(shortcuts).map(([key, input]) => [key, input.value.trim()]))});
100
+ message.textContent = text('Saved.', '저장했습니다.');
101
+ } catch (error) { message.textContent = error.message; }
102
+ finally { save.disabled = false; }
103
+ window.scrollTo(0, 0);
104
+ };
105
+ const reset = element('button', text('Restore defaults', '기본값 불러오기'));
106
+ reset.onclick = () => {
107
+ for (const [key, input] of Object.entries(fields)) {
108
+ if (input.type === 'checkbox') input.checked = state.defaults[key];
109
+ else input.value = state.defaults[key];
110
+ }
111
+ for (const [key, input] of Object.entries(shortcuts)) input.value = state.defaults.shortcuts[key];
112
+ };
113
+ buttons.append(save, reset); root.append(buttons);
114
+ }
115
+ }