@hnode/tidy 0.19.4 → 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.
- package/README.md +16 -5
- package/bin/tidy.js +6 -3
- package/desktop/core.js +112 -0
- package/desktop/index.html +11 -0
- package/desktop/main.js +328 -0
- package/desktop/manage.js +175 -0
- package/desktop/native/macos.swift +110 -0
- package/desktop/native-bridge.js +67 -0
- package/desktop/package-lock.json +161 -0
- package/desktop/package.json +10 -0
- package/desktop/preload.cjs +11 -0
- package/desktop/renderer.js +115 -0
- package/desktop/style.css +25 -0
- package/dist/winubun@winubun.local.shell-extension.zip +0 -0
- package/docs/DEVELOPMENT.md +6 -2
- package/docs/MACOS.md +69 -0
- package/docs/README.en.md +18 -5
- package/docs/RELEASING.md +43 -6
- package/lib/layouts.js +132 -0
- package/lib/translations.json +4 -2
- package/package.json +18 -8
- package/scripts/manage.py +2 -0
package/README.md
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
[한국어](README.md) · [English](docs/README.en.md)
|
|
4
4
|
|
|
5
|
-
Window tiling for GNOME
|
|
5
|
+
Window tiling for GNOME and macOS
|
|
6
6
|
|
|
7
7
|
창을 화면 위로 끌어 배치를 고르고, 단축키로 모니터 사이를 이동하세요.
|
|
8
|
-
Ubuntu GNOME
|
|
8
|
+
Ubuntu GNOME 확장과 macOS 데스크톱 앱으로 창을 나누고 정렬합니다.
|
|
9
9
|
|
|
10
10
|

|
|
11
11
|

|
|
@@ -17,7 +17,7 @@ Ubuntu GNOME에서 창을 나누고 정렬하는 확장입니다.
|
|
|
17
17
|
|
|
18
18
|
## Overview
|
|
19
19
|
|
|
20
|
-
Tidy는 GNOME
|
|
20
|
+
Tidy는 Ubuntu GNOME과 macOS에서 창을 배치합니다. GNOME에서는 Shell 확장으로, macOS에서는 별도 데스크톱 앱으로 실행됩니다. 여러 모니터를 사용할 때도 화면 상단 안쪽에서 배치 선택기를 열고, 그림으로 표시된 칸에 창을 놓을 수 있습니다.
|
|
21
21
|
|
|
22
22
|
<img src="docs/preview.png" alt="무채색 배치 그림으로 구성된 Tidy 상단 선택기" width="760">
|
|
23
23
|
|
|
@@ -25,6 +25,8 @@ Tidy는 GNOME Shell에서 실행되는 창 배치 확장입니다. 여러 모니
|
|
|
25
25
|
|
|
26
26
|
## Features
|
|
27
27
|
|
|
28
|
+
아래 표는 GNOME판의 기능입니다. macOS판은 배치 선택기, 상단 드래그·가장자리 배치, 단축키, 다중 모니터, 최대화·복귀와 창 간격을 제공합니다. 기능 범위와 설치 방법은 [macOS 안내](docs/MACOS.md)를 참고하세요.
|
|
29
|
+
|
|
28
30
|
| 기능 | 동작 |
|
|
29
31
|
| --- | --- |
|
|
30
32
|
| 상단 배치 선택기 | 창을 상단 중앙으로 끌어 원하는 칸에 놓습니다. 6가지 배치를 한 행으로 표시합니다. |
|
|
@@ -48,12 +50,15 @@ Tidy는 GNOME Shell에서 실행되는 창 배치 확장입니다. 여러 모니
|
|
|
48
50
|
| Ubuntu 26.04 · GNOME 50.1 · Wayland | 독립 GNOME 세션의 실제 Wayland 창과 가상 모니터 2개로 검증 |
|
|
49
51
|
| GNOME 46–49 | 호환 버전으로 선언되어 있으나 실기 검증 전 |
|
|
50
52
|
| X11 | 실기 검증 전 |
|
|
51
|
-
|
|
|
53
|
+
| macOS 13 이상 · Intel/Apple Silicon | Accessibility 기반 데스크톱 앱 추가 · 실기 검증 전 |
|
|
54
|
+
| KDE · Xfce | 지원 대상 아님 |
|
|
52
55
|
|
|
53
|
-
실행에는 시스템 Python 3와 PyGObject, GJS, GTK 4/libadwaita가 필요합니다. npm 명령에는 Node.js 18 이상이 필요하며, 소스에서 직접 빌드할 때는 `glib-compile-schemas`도 필요합니다. 설치된 GNOME 확장은 Node.js나 npm 프로세스를 띄우지 않습니다.
|
|
56
|
+
GNOME판 실행에는 시스템 Python 3와 PyGObject, GJS, GTK 4/libadwaita가 필요합니다. GNOME용 npm 명령에는 Node.js 18 이상이 필요하며, 소스에서 직접 빌드할 때는 `glib-compile-schemas`도 필요합니다. 설치된 GNOME 확장은 Node.js나 npm 프로세스를 띄우지 않습니다. macOS 설치에는 Node.js 22.12 이상과 npm, Xcode Command Line Tools와 손쉬운 사용 권한이 필요합니다.
|
|
54
57
|
|
|
55
58
|
## Install
|
|
56
59
|
|
|
60
|
+
macOS도 `tidy install`로 설치합니다. 설치 후 즉시 실행되며 로그인 자동 실행을 등록합니다. 소스에서는 `node bin/tidy.js install`을 사용하세요. 권한 설정과 필수 도구는 [macOS 안내](docs/MACOS.md)에 설명되어 있습니다. 아래의 로그아웃·재로그인 및 Python 설치 절차는 GNOME판에 해당합니다.
|
|
61
|
+
|
|
57
62
|
### npm
|
|
58
63
|
|
|
59
64
|
패키지 이름은 **`@hnode/tidy`**, 실행 명령은 **`tidy`**입니다. npm 공개 후 다음 명령으로 패키지와 GNOME 확장을 설치합니다.
|
|
@@ -91,6 +96,8 @@ Git 대신 [Download ZIP](https://github.com/hojin-v/Tidy/archive/refs/heads/mai
|
|
|
91
96
|
|
|
92
97
|
## Quick Start
|
|
93
98
|
|
|
99
|
+
아래의 Super·창 보기 연동은 GNOME판 기능입니다. macOS에서는 메뉴 막대 아이콘이나 배치 선택기 단축키를 사용하며, 상단으로 창을 끌어 배치할 수도 있습니다.
|
|
100
|
+
|
|
94
101
|
1. 창의 제목 표시줄을 잡으면 상단에 선택기 인식 영역이 얇게 나타납니다.
|
|
95
102
|
2. 그 영역으로 끌면 선택기가 펼쳐지고 창이 작은 미리보기로 줄어듭니다. 원하는 배치 칸으로 포인터를 옮깁니다.
|
|
96
103
|
3. 마우스를 놓으면 창을 배치합니다. 빈 곳에서 놓으면 취소합니다.
|
|
@@ -107,6 +114,8 @@ Git 대신 [Download ZIP](https://github.com/hojin-v/Tidy/archive/refs/heads/mai
|
|
|
107
114
|
|
|
108
115
|
## Shortcuts
|
|
109
116
|
|
|
117
|
+
macOS판은 아래 배치 동작에 **Control+Option**을 사용합니다. 단독 Super와 Super+A의 창 보기 연동은 GNOME판 기능입니다. macOS의 기본 타일링과 시스템 단축키 설정은 변경하지 않습니다. [macOS 단축키 안내](docs/MACOS.md#shortcuts-and-settings)를 참고하세요.
|
|
118
|
+
|
|
110
119
|
배치 단축키는 **Super+Alt** 조합으로 통일되어 있습니다. 설정의 **단축키** 탭에서 바꿀 수 있습니다.
|
|
111
120
|
|
|
112
121
|
| 단축키 | 동작 |
|
|
@@ -129,6 +138,8 @@ Git 대신 [Download ZIP](https://github.com/hojin-v/Tidy/archive/refs/heads/mai
|
|
|
129
138
|
|
|
130
139
|
## Settings
|
|
131
140
|
|
|
141
|
+
macOS에서는 `tidy prefs` 또는 메뉴 막대 아이콘으로 설정을 엽니다. 설정 범위는 [macOS 안내](docs/MACOS.md#shortcuts-and-settings)를 참고하세요. 아래 옵션은 GNOME판 기준입니다.
|
|
142
|
+
|
|
132
143
|
앱 목록의 **Tidy** 또는 **상단 격자 아이콘 → 설정 및 단축키…**에서 변경합니다. 설정은 즉시 반영됩니다.
|
|
133
144
|
|
|
134
145
|
- **기존 Super+방향키 창 배치 끄기**: GNOME 기본 배치 단축키를 끕니다. 해제하거나 Tidy를 종료하면 기존 단축키를 복원합니다.
|
package/bin/tidy.js
CHANGED
|
@@ -5,6 +5,7 @@ import {homedir} from 'node:os';
|
|
|
5
5
|
import {dirname, join} from 'node:path';
|
|
6
6
|
import {fileURLToPath} from 'node:url';
|
|
7
7
|
import {createTranslator} from '../lib/i18nCore.js';
|
|
8
|
+
import {desktopCommand} from '../desktop/manage.js';
|
|
8
9
|
|
|
9
10
|
const root = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
10
11
|
const metadata = JSON.parse(readFileSync(join(root, 'metadata.json'), 'utf8'));
|
|
@@ -13,10 +14,10 @@ const catalogs = JSON.parse(readFileSync(join(root, 'lib/translations.json'), 'u
|
|
|
13
14
|
const commands = ['install', 'update', 'uninstall', 'prefs', 'status', 'doctor'];
|
|
14
15
|
|
|
15
16
|
export function main({args = process.argv.slice(2), env = process.env, platform = process.platform,
|
|
16
|
-
uid = process.getuid?.(), packageRoot = root, run = spawnSync, out = console.log, error = console.error} = {}) {
|
|
17
|
+
uid = process.getuid?.(), packageRoot = root, run = spawnSync, desktop = desktopCommand, out = console.log, error = console.error} = {}) {
|
|
17
18
|
const languages = env.LANGUAGE?.split(':') ?? [env.LC_ALL || env.LC_MESSAGES || env.LANG || 'C'];
|
|
18
19
|
const _ = createTranslator(catalogs, languages);
|
|
19
|
-
const help = () => out(_('Tidy · Window tiling for
|
|
20
|
+
const help = () => out(_('Tidy · Window tiling for Linux and macOS\n\nUsage: tidy <command>\n tidy [options]\n\nCommands:\n install Install Tidy for the current user\n update Install this package version of Tidy\n uninstall Remove Tidy and restore desktop settings\n prefs Open settings and shortcuts\n status Show installation and runtime status\n doctor Check system requirements\n\nOptions:\n -h, --help Show this help\n -v, --version Show package version\n\nGNOME: log out and back in once. macOS: starts immediately.'));
|
|
20
21
|
if (!args.length || args[0] === 'help' || args.includes('--help') || args.includes('-h')) {
|
|
21
22
|
help();
|
|
22
23
|
return 0;
|
|
@@ -29,8 +30,10 @@ export function main({args = process.argv.slice(2), env = process.env, platform
|
|
|
29
30
|
error(_('Unknown command. Run tidy --help.'));
|
|
30
31
|
return 2;
|
|
31
32
|
}
|
|
33
|
+
if (platform === 'darwin')
|
|
34
|
+
return desktop(args[0], {platform, env, packageRoot, run, out, error});
|
|
32
35
|
if (platform !== 'linux') {
|
|
33
|
-
error(_('Tidy
|
|
36
|
+
error(_('Tidy supports Linux with GNOME Shell 46–50 and macOS.'));
|
|
34
37
|
return 1;
|
|
35
38
|
}
|
|
36
39
|
const command = args[0];
|
package/desktop/core.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import {ACTIONS, directionalMonitor, zoneRect, ZONES} from '../lib/layouts.js';
|
|
2
|
+
|
|
3
|
+
export function defaultSettings() {
|
|
4
|
+
const keys = {Left: 'Left', Right: 'Right', Up: 'Up', Down: 'Down', Return: 'Enter', space: 'Space'};
|
|
5
|
+
return {gap: 8, dragPicker: true, edgeSnap: true, openAtLogin: true,
|
|
6
|
+
shortcuts: Object.fromEntries(ACTIONS.map(([id, , , accelerator]) => {
|
|
7
|
+
const key = accelerator.replace('<Super><Alt>', '');
|
|
8
|
+
return [id, `Control+Alt+${keys[key] ?? key.toUpperCase()}`];
|
|
9
|
+
}))};
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function validateSettings(value) {
|
|
13
|
+
const defaults = defaultSettings();
|
|
14
|
+
if (!value || !Number.isInteger(value.gap) || value.gap < 0 || value.gap > 64)
|
|
15
|
+
throw new Error('Gap must be an integer between 0 and 64.');
|
|
16
|
+
for (const key of ['dragPicker', 'edgeSnap', 'openAtLogin'])
|
|
17
|
+
if (typeof value[key] !== 'boolean') throw new Error(`Invalid setting: ${key}`);
|
|
18
|
+
const shortcuts = {};
|
|
19
|
+
for (const id of Object.keys(defaults.shortcuts)) {
|
|
20
|
+
const accelerator = value.shortcuts?.[id];
|
|
21
|
+
if (typeof accelerator !== 'string' || accelerator.length > 100 ||
|
|
22
|
+
(accelerator !== '' && !/^(?:(?:Control|Ctrl|Alt|Option|Shift|Super|Command|Cmd|CommandOrControl)\+)+(?:[A-Z0-9]|Left|Right|Up|Down|Enter|Space|Tab|F(?:[1-9]|1[0-9]|2[0-4]))$/i.test(accelerator)))
|
|
23
|
+
throw new Error(`Invalid shortcut: ${id}`);
|
|
24
|
+
shortcuts[id] = accelerator;
|
|
25
|
+
}
|
|
26
|
+
const enabled = Object.values(shortcuts).filter(Boolean).map(key => key.toLowerCase());
|
|
27
|
+
if (new Set(enabled).size !== enabled.length) throw new Error('Shortcuts must be unique.');
|
|
28
|
+
return {gap: value.gap, dragPicker: value.dragPicker, edgeSnap: value.edgeSnap,
|
|
29
|
+
openAtLogin: value.openAtLogin, shortcuts};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function sameRect(a, b, tolerance = 3) {
|
|
33
|
+
return !!a && !!b && ['x', 'y', 'width', 'height'].every(key => Math.abs(a[key] - b[key]) <= tolerance);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function monitorFor(rect, monitors) {
|
|
37
|
+
let best = 0;
|
|
38
|
+
let score = -Infinity;
|
|
39
|
+
monitors.forEach((monitor, index) => {
|
|
40
|
+
const intersection = Math.max(0, Math.min(rect.x + rect.width, monitor.x + monitor.width) - Math.max(rect.x, monitor.x)) *
|
|
41
|
+
Math.max(0, Math.min(rect.y + rect.height, monitor.y + monitor.height) - Math.max(rect.y, monitor.y));
|
|
42
|
+
const distance = Math.hypot(rect.x + rect.width / 2 - monitor.x - monitor.width / 2,
|
|
43
|
+
rect.y + rect.height / 2 - monitor.y - monitor.height / 2);
|
|
44
|
+
const value = intersection > 0 ? intersection : -distance;
|
|
45
|
+
if (value > score) { best = index; score = value; }
|
|
46
|
+
});
|
|
47
|
+
return best;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Coordinates use logical pixels, matching macOS accessibility points.
|
|
51
|
+
export class TilingController {
|
|
52
|
+
placements = new Map();
|
|
53
|
+
|
|
54
|
+
plan(window, action, monitors, gap = 8, destination = null) {
|
|
55
|
+
if (!window || !window.resizable || window.fullscreen || !monitors.length)
|
|
56
|
+
throw new Error('Select a movable, resizable window first.');
|
|
57
|
+
const key = `${window.pid}:${window.id}`;
|
|
58
|
+
const saved = this.placements.get(key);
|
|
59
|
+
const previous = sameRect(window.rect, saved?.rect) ? saved : null;
|
|
60
|
+
let monitor = destination ?? monitorFor(window.rect, monitors);
|
|
61
|
+
if (!monitors[monitor]) throw new Error('The selected monitor is no longer connected.');
|
|
62
|
+
let zone = action;
|
|
63
|
+
if (action === 'toggle-maximize') {
|
|
64
|
+
if (previous?.zone === 'maximize')
|
|
65
|
+
return {window, rect: previous.restore, zone: null, key, restore: previous.restore};
|
|
66
|
+
zone = 'maximize';
|
|
67
|
+
} else if (action === 'next-monitor') {
|
|
68
|
+
monitor = (monitor + 1) % monitors.length;
|
|
69
|
+
zone = previous?.zone ?? 'center';
|
|
70
|
+
} else if (destination === null && previous?.zone === action && ['left', 'right', 'top', 'bottom'].includes(action)) {
|
|
71
|
+
const direction = {top: 'up', bottom: 'down'}[action] ?? action;
|
|
72
|
+
const next = directionalMonitor(monitors, monitor, direction);
|
|
73
|
+
if (next) {
|
|
74
|
+
monitor = next.monitor;
|
|
75
|
+
zone = {left: 'right', right: 'left', top: 'bottom', bottom: 'top'}[action];
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (!Object.hasOwn(ZONES, zone)) throw new Error('Unknown layout.');
|
|
79
|
+
const area = monitors[monitor].workArea ?? monitors[monitor];
|
|
80
|
+
return {window, rect: zoneRect(area, zone, zone === 'maximize' ? 0 : gap), zone, key,
|
|
81
|
+
restore: previous?.zone === 'maximize' ? previous.restore : window.rect};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
commit(plan, actualRect = plan.rect) {
|
|
85
|
+
if (this.placements.size > 256) this.placements.delete(this.placements.keys().next().value);
|
|
86
|
+
this.placements.set(plan.key, {...plan, rect: actualRect});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// A mouse press alone is insufficient: only a moving window starts a drag.
|
|
91
|
+
export class DragTracker {
|
|
92
|
+
previous = null;
|
|
93
|
+
dragging = null;
|
|
94
|
+
|
|
95
|
+
update(snapshot) {
|
|
96
|
+
const old = this.previous;
|
|
97
|
+
this.previous = snapshot;
|
|
98
|
+
if (!snapshot.mouseDown) {
|
|
99
|
+
const released = this.dragging;
|
|
100
|
+
this.dragging = null;
|
|
101
|
+
return released ? {type: 'release', window: released} : null;
|
|
102
|
+
}
|
|
103
|
+
const window = snapshot.window;
|
|
104
|
+
if (!window || !window.resizable || window.fullscreen) return null;
|
|
105
|
+
if (old?.mouseDown && old.window?.id === window.id && old.window.pid === window.pid &&
|
|
106
|
+
!sameRect(old.window.rect, window.rect, 0) &&
|
|
107
|
+
Math.abs(old.window.rect.width - window.rect.width) <= 3 &&
|
|
108
|
+
Math.abs(old.window.rect.height - window.rect.height) <= 3)
|
|
109
|
+
this.dragging = window;
|
|
110
|
+
return this.dragging ? {type: 'drag', window: this.dragging} : null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'none'; img-src 'self' data:">
|
|
6
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
7
|
+
<title>Tidy</title>
|
|
8
|
+
<link rel="stylesheet" href="style.css">
|
|
9
|
+
</head>
|
|
10
|
+
<body><main id="app"></main><script src="renderer.js" type="module"></script></body>
|
|
11
|
+
</html>
|
package/desktop/main.js
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import {app, BrowserWindow, globalShortcut, ipcMain, Menu, nativeImage, screen, Tray} from 'electron';
|
|
2
|
+
import {existsSync, mkdirSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
|
|
3
|
+
import {dirname, join} from 'node:path';
|
|
4
|
+
import {fileURLToPath} from 'node:url';
|
|
5
|
+
import {ACTIONS, contains, dragIntent, LAYOUTS, ZONES} from '../lib/layouts.js';
|
|
6
|
+
import {createTranslator} from '../lib/i18nCore.js';
|
|
7
|
+
import {defaultSettings, DragTracker, TilingController, validateSettings} from './core.js';
|
|
8
|
+
import {desktopPaths} from './manage.js';
|
|
9
|
+
import {NativeBridge} from './native-bridge.js';
|
|
10
|
+
|
|
11
|
+
const directory = dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
const paths = desktopPaths();
|
|
13
|
+
const base = process.env.TIDY_DATA_DIR || paths.base;
|
|
14
|
+
const configDirectory = join(base, 'config');
|
|
15
|
+
mkdirSync(configDirectory, {recursive: true});
|
|
16
|
+
app.setName('Tidy');
|
|
17
|
+
app.setPath('userData', configDirectory);
|
|
18
|
+
const command = process.argv.includes('--uninstall') ? 'uninstall' : process.argv.includes('--quit') ? 'quit' :
|
|
19
|
+
process.argv.includes('--settings') ? 'settings' : 'background';
|
|
20
|
+
const primary = app.requestSingleInstanceLock({command});
|
|
21
|
+
if (!primary) app.quit();
|
|
22
|
+
else {
|
|
23
|
+
app.on('second-instance', (_event, _argv, _cwd, data) => dispatch(data.command));
|
|
24
|
+
app.whenReady().then(start).catch(error => {
|
|
25
|
+
console.error(error);
|
|
26
|
+
writeFileSync(join(base, 'status.json'), JSON.stringify({pid: process.pid, updated: Date.now(), error: error.message}));
|
|
27
|
+
app.exit(1);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let bridge, tray, picker, preferences, preview, timer;
|
|
32
|
+
let settings = defaultSettings();
|
|
33
|
+
let translate = message => message;
|
|
34
|
+
let shortcutFailures = [];
|
|
35
|
+
let lastError = '';
|
|
36
|
+
let trusted = false;
|
|
37
|
+
let lastWindow = null;
|
|
38
|
+
let pickerTarget = null;
|
|
39
|
+
let pickerDisplay = null;
|
|
40
|
+
let dragMode = false;
|
|
41
|
+
let hitRegions = [];
|
|
42
|
+
let selection = null;
|
|
43
|
+
let pollBusy = false;
|
|
44
|
+
let actionQueue = Promise.resolve();
|
|
45
|
+
let quitting = false;
|
|
46
|
+
let requestedSettings = false;
|
|
47
|
+
let readyForUI = false;
|
|
48
|
+
let lastHeartbeat = 0;
|
|
49
|
+
let shutdownComplete = false;
|
|
50
|
+
const controller = new TilingController();
|
|
51
|
+
const drag = new DragTracker();
|
|
52
|
+
const settingsFile = join(configDirectory, 'settings.json');
|
|
53
|
+
const statusFile = join(base, 'status.json');
|
|
54
|
+
const monitors = () => screen.getAllDisplays().map(display => ({...display.bounds, id: display.id, workArea: display.workArea}));
|
|
55
|
+
|
|
56
|
+
function report(error) {
|
|
57
|
+
lastError = error.message;
|
|
58
|
+
console.error(error);
|
|
59
|
+
updateTray();
|
|
60
|
+
preferences?.webContents.send('changed');
|
|
61
|
+
}
|
|
62
|
+
function enqueue(action) {
|
|
63
|
+
actionQueue = actionQueue.then(action).catch(report);
|
|
64
|
+
return actionQueue;
|
|
65
|
+
}
|
|
66
|
+
function loginItem(openAtLogin) {
|
|
67
|
+
app.setLoginItemSettings({openAtLogin, path: process.execPath, args: ['--background'], name: 'Tidy'});
|
|
68
|
+
}
|
|
69
|
+
function dispatch(action) {
|
|
70
|
+
if (action === 'uninstall') { loginItem(false); app.quit(); }
|
|
71
|
+
else if (action === 'quit') app.quit();
|
|
72
|
+
else if (action === 'settings') {
|
|
73
|
+
if (readyForUI) showPreferences().catch(report);
|
|
74
|
+
else requestedSettings = true;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function start() {
|
|
79
|
+
if (command === 'uninstall') { loginItem(false); app.quit(); return; }
|
|
80
|
+
if (command === 'quit') { app.quit(); return; }
|
|
81
|
+
if (process.platform !== 'darwin') throw new Error('The desktop app requires macOS. Use the GNOME extension on Linux.');
|
|
82
|
+
app.dock?.hide();
|
|
83
|
+
const catalogs = JSON.parse(readFileSync(join(directory, '../lib/translations.json'), 'utf8'));
|
|
84
|
+
translate = createTranslator(catalogs, [app.getLocale()]);
|
|
85
|
+
if (existsSync(settingsFile)) {
|
|
86
|
+
try { settings = validateSettings(JSON.parse(readFileSync(settingsFile, 'utf8'))); }
|
|
87
|
+
catch (error) { lastError = error.message; }
|
|
88
|
+
}
|
|
89
|
+
bridge = new NativeBridge(join(directory, 'native'));
|
|
90
|
+
trusted = (await bridge.request('permissions', {prompt: false})).trusted;
|
|
91
|
+
const bitmap = Buffer.alloc(24 * 24 * 4);
|
|
92
|
+
for (let y = 4; y < 20; y++) {
|
|
93
|
+
for (let x = 3; x < 21; x++) {
|
|
94
|
+
if (x >= 11 && x < 13 || x >= 13 && y >= 11 && y < 13) continue;
|
|
95
|
+
bitmap.set([136, 136, 136, 255], (y * 24 + x) * 4);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const icon = nativeImage.createFromBitmap(bitmap, {width: 24, height: 24});
|
|
99
|
+
icon.setTemplateImage(true);
|
|
100
|
+
tray = new Tray(icon);
|
|
101
|
+
tray.setToolTip('Tidy');
|
|
102
|
+
tray.on('click', () => showPreferences().catch(report));
|
|
103
|
+
registerShortcuts(settings);
|
|
104
|
+
loginItem(settings.openAtLogin);
|
|
105
|
+
updateTray();
|
|
106
|
+
ipcMain.handle('tidy:state', event => {
|
|
107
|
+
checkSender(event);
|
|
108
|
+
return {settings, defaults: defaultSettings(), layouts: LAYOUTS, zones: ZONES,
|
|
109
|
+
actions: ACTIONS.map(([id, title]) => ({id, title: translate(title)})), trusted, shortcutFailures, lastError,
|
|
110
|
+
labels: Object.fromEntries(['Tidy Settings', 'Settings and shortcuts…', 'Halves', 'Wide', 'Focus', 'Three columns',
|
|
111
|
+
'Wide center', 'Four quarters'].map(text => [text, translate(text)])),
|
|
112
|
+
language: app.getLocale().startsWith('ko') ? 'ko' : 'en'};
|
|
113
|
+
});
|
|
114
|
+
ipcMain.handle('tidy:save', (event, value) => {
|
|
115
|
+
checkSender(event, preferences);
|
|
116
|
+
const next = validateSettings(value);
|
|
117
|
+
const previous = settings;
|
|
118
|
+
registerShortcuts(next);
|
|
119
|
+
if (shortcutFailures.length) {
|
|
120
|
+
const failed = shortcutFailures.join(', ');
|
|
121
|
+
registerShortcuts(previous);
|
|
122
|
+
throw new Error(`Shortcut unavailable: ${failed}`);
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
loginItem(next.openAtLogin);
|
|
126
|
+
writeFileSync(settingsFile, JSON.stringify(next, null, 2));
|
|
127
|
+
} catch (error) {
|
|
128
|
+
registerShortcuts(previous);
|
|
129
|
+
loginItem(previous.openAtLogin);
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
settings = next;
|
|
133
|
+
lastError = '';
|
|
134
|
+
return true;
|
|
135
|
+
});
|
|
136
|
+
ipcMain.handle('tidy:permissions', async event => {
|
|
137
|
+
checkSender(event, preferences);
|
|
138
|
+
trusted = (await bridge.request('permissions', {prompt: true})).trusted;
|
|
139
|
+
return trusted;
|
|
140
|
+
});
|
|
141
|
+
ipcMain.on('tidy:choose', (event, zone) => {
|
|
142
|
+
checkSender(event, picker);
|
|
143
|
+
const target = pickerTarget;
|
|
144
|
+
const displayId = pickerDisplay;
|
|
145
|
+
if (Object.hasOwn(ZONES, zone) && target)
|
|
146
|
+
enqueue(() => execute(zone, target, displayId));
|
|
147
|
+
hidePicker();
|
|
148
|
+
});
|
|
149
|
+
ipcMain.on('tidy:regions', (event, regions) => {
|
|
150
|
+
checkSender(event, picker);
|
|
151
|
+
if (Array.isArray(regions)) hitRegions = regions.filter(region => Object.hasOwn(ZONES, region.zone) &&
|
|
152
|
+
['x', 'y', 'width', 'height'].every(key => Number.isFinite(region[key])));
|
|
153
|
+
});
|
|
154
|
+
ipcMain.on('tidy:close', event => { checkSender(event, picker); hidePicker(); });
|
|
155
|
+
app.on('window-all-closed', () => {});
|
|
156
|
+
app.on('activate', () => showPreferences().catch(report));
|
|
157
|
+
readyForUI = true;
|
|
158
|
+
timer = setInterval(poll, 100);
|
|
159
|
+
await poll();
|
|
160
|
+
if (command === 'settings' || requestedSettings || !trusted || shortcutFailures.length || lastError) await showPreferences();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function checkSender(event, window) {
|
|
164
|
+
if (window ? event.sender !== window.webContents :
|
|
165
|
+
![picker, preferences].some(item => item && event.sender === item.webContents)) throw new Error('Invalid sender.');
|
|
166
|
+
}
|
|
167
|
+
function registerShortcuts(value) {
|
|
168
|
+
globalShortcut.unregisterAll();
|
|
169
|
+
shortcutFailures = [];
|
|
170
|
+
for (const [id, , action] of ACTIONS) {
|
|
171
|
+
const accelerator = value.shortcuts[id];
|
|
172
|
+
if (!accelerator) continue;
|
|
173
|
+
try {
|
|
174
|
+
if (globalShortcut.register(accelerator, () => enqueue(async () => {
|
|
175
|
+
const snapshot = await bridge.snapshot();
|
|
176
|
+
if (action === 'picker') await showPicker(snapshot.window, false);
|
|
177
|
+
else await execute(action, snapshot.window);
|
|
178
|
+
}))) continue;
|
|
179
|
+
} catch { /* Display malformed or OS-reserved accelerators in settings. */ }
|
|
180
|
+
shortcutFailures.push(accelerator);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function updateTray() {
|
|
184
|
+
if (!tray) return;
|
|
185
|
+
tray.setContextMenu(Menu.buildFromTemplate([
|
|
186
|
+
{label: 'Tidy', enabled: false},
|
|
187
|
+
...(lastError ? [{label: lastError.slice(0, 100), enabled: false}] : []),
|
|
188
|
+
{label: translate('Open layout picker'), click: () => enqueue(() => showPicker(lastWindow, false))},
|
|
189
|
+
{label: translate('Settings and shortcuts…'), click: () => showPreferences().catch(report)},
|
|
190
|
+
{type: 'separator'}, {label: translate('Quit'), click: () => app.quit()},
|
|
191
|
+
]));
|
|
192
|
+
}
|
|
193
|
+
function windowOptions() {
|
|
194
|
+
return {show: false, autoHideMenuBar: true, backgroundColor: '#252529',
|
|
195
|
+
webPreferences: {preload: join(directory, 'preload.cjs'), nodeIntegration: false, contextIsolation: true, sandbox: true}};
|
|
196
|
+
}
|
|
197
|
+
function protect(window) {
|
|
198
|
+
window.webContents.setWindowOpenHandler(() => ({action: 'deny'}));
|
|
199
|
+
window.webContents.on('will-navigate', event => event.preventDefault());
|
|
200
|
+
}
|
|
201
|
+
async function showPreferences() {
|
|
202
|
+
if (preferences) { preferences.show(); preferences.focus(); return; }
|
|
203
|
+
preferences = new BrowserWindow({...windowOptions(), width: 660, height: 740, title: translate('Tidy Settings')});
|
|
204
|
+
protect(preferences);
|
|
205
|
+
preferences.on('closed', () => { preferences = null; });
|
|
206
|
+
await preferences.loadFile(join(directory, 'index.html'), {query: {mode: 'settings'}});
|
|
207
|
+
preferences.show();
|
|
208
|
+
}
|
|
209
|
+
async function showPicker(target, dragging, displayId = null) {
|
|
210
|
+
if (!target) throw new Error('Select a movable, resizable window first.');
|
|
211
|
+
const displays = screen.getAllDisplays();
|
|
212
|
+
const display = displays.find(item => item.id === displayId) ?? screen.getDisplayMatching(target.rect);
|
|
213
|
+
const area = display.workArea;
|
|
214
|
+
if (!picker) {
|
|
215
|
+
picker = new BrowserWindow({...windowOptions(), width: 820, height: 142, frame: false, resizable: false,
|
|
216
|
+
alwaysOnTop: true, skipTaskbar: true, focusable: !dragging, roundedCorners: true});
|
|
217
|
+
protect(picker);
|
|
218
|
+
picker.on('blur', () => { if (!dragMode) hidePicker(); });
|
|
219
|
+
picker.on('closed', () => { picker = null; });
|
|
220
|
+
await picker.loadFile(join(directory, 'index.html'), {query: {mode: 'picker'}});
|
|
221
|
+
}
|
|
222
|
+
pickerTarget = target;
|
|
223
|
+
pickerDisplay = display.id;
|
|
224
|
+
dragMode = dragging;
|
|
225
|
+
const width = Math.min(820, area.width);
|
|
226
|
+
picker.setBounds({x: Math.round(area.x + (area.width - width) / 2), y: area.y + 12, width, height: Math.min(142, area.height)});
|
|
227
|
+
picker.setFocusable(!dragging);
|
|
228
|
+
picker.setIgnoreMouseEvents(dragging);
|
|
229
|
+
if (dragging) picker.showInactive();
|
|
230
|
+
else { picker.show(); picker.focus(); }
|
|
231
|
+
}
|
|
232
|
+
function hidePicker() {
|
|
233
|
+
picker?.hide();
|
|
234
|
+
preview?.hide();
|
|
235
|
+
dragMode = false;
|
|
236
|
+
selection = null;
|
|
237
|
+
picker?.webContents.send('hover', null);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function execute(action, target, displayId = null) {
|
|
241
|
+
const list = monitors();
|
|
242
|
+
const destination = displayId === null ? null : list.findIndex(item => item.id === displayId);
|
|
243
|
+
const plan = controller.plan(target, action, list, settings.gap, destination);
|
|
244
|
+
const actual = await bridge.place(plan.window, plan.rect);
|
|
245
|
+
controller.commit(plan, actual);
|
|
246
|
+
lastError = '';
|
|
247
|
+
hidePicker();
|
|
248
|
+
}
|
|
249
|
+
async function showPreview(rect) {
|
|
250
|
+
if (!preview) {
|
|
251
|
+
preview = new BrowserWindow({...windowOptions(), frame: false, transparent: true, backgroundColor: '#00000000',
|
|
252
|
+
alwaysOnTop: true, focusable: false, skipTaskbar: true, resizable: false});
|
|
253
|
+
preview.setIgnoreMouseEvents(true);
|
|
254
|
+
await preview.loadFile(join(directory, 'index.html'), {query: {mode: 'preview'}});
|
|
255
|
+
}
|
|
256
|
+
preview.setBounds(rect);
|
|
257
|
+
preview.showInactive();
|
|
258
|
+
// Keep the picker above its placement preview.
|
|
259
|
+
if (picker?.isVisible()) picker.moveTop();
|
|
260
|
+
}
|
|
261
|
+
async function poll() {
|
|
262
|
+
if (pollBusy || quitting) return;
|
|
263
|
+
pollBusy = true;
|
|
264
|
+
try {
|
|
265
|
+
const snapshot = await bridge.snapshot();
|
|
266
|
+
trusted = snapshot.trusted;
|
|
267
|
+
if (snapshot.window) lastWindow = snapshot.window;
|
|
268
|
+
const event = drag.update(snapshot);
|
|
269
|
+
const pointer = screen.getCursorScreenPoint();
|
|
270
|
+
if (event?.type === 'drag' && !preferences?.isFocused()) {
|
|
271
|
+
const display = screen.getDisplayNearestPoint(pointer);
|
|
272
|
+
let intent = dragIntent(display.bounds, display.workArea, pointer.x, pointer.y, {picker: settings.dragPicker});
|
|
273
|
+
if (picker?.isVisible() && dragMode && pickerDisplay === display.id && contains(picker.getBounds(), pointer.x, pointer.y))
|
|
274
|
+
intent = {type: 'picker'};
|
|
275
|
+
if (intent?.type === 'picker' && settings.dragPicker) {
|
|
276
|
+
await showPicker(event.window, true, display.id);
|
|
277
|
+
const bounds = picker.getBounds();
|
|
278
|
+
const hit = hitRegions.find(region => contains(region, pointer.x - bounds.x, pointer.y - bounds.y));
|
|
279
|
+
selection = hit ? {zone: hit.zone, window: event.window, displayId: display.id} : null;
|
|
280
|
+
picker.webContents.send('hover', hit?.zone ?? null);
|
|
281
|
+
} else {
|
|
282
|
+
hidePicker();
|
|
283
|
+
if (intent?.type === 'tile' && settings.edgeSnap)
|
|
284
|
+
selection = {zone: intent.zone, window: event.window, displayId: display.id};
|
|
285
|
+
}
|
|
286
|
+
if (selection) {
|
|
287
|
+
const list = monitors();
|
|
288
|
+
const plan = controller.plan(selection.window, selection.zone, list, settings.gap,
|
|
289
|
+
list.findIndex(item => item.id === selection.displayId));
|
|
290
|
+
await showPreview(plan.rect);
|
|
291
|
+
} else preview?.hide();
|
|
292
|
+
} else if (event?.type === 'release') {
|
|
293
|
+
const chosen = selection;
|
|
294
|
+
hidePicker();
|
|
295
|
+
if (chosen) await enqueue(() => execute(chosen.zone, chosen.window, chosen.displayId));
|
|
296
|
+
}
|
|
297
|
+
} catch (error) {
|
|
298
|
+
if (lastError !== error.message) report(error);
|
|
299
|
+
} finally {
|
|
300
|
+
if (!quitting && Date.now() - lastHeartbeat > 2000) {
|
|
301
|
+
lastHeartbeat = Date.now();
|
|
302
|
+
writeFileSync(statusFile, JSON.stringify({pid: process.pid, updated: Date.now(), trusted,
|
|
303
|
+
shortcutFailures, error: lastError}));
|
|
304
|
+
}
|
|
305
|
+
pollBusy = false;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
app.on('before-quit', event => {
|
|
310
|
+
if (!primary || shutdownComplete) return;
|
|
311
|
+
event.preventDefault();
|
|
312
|
+
if (quitting) return;
|
|
313
|
+
quitting = true;
|
|
314
|
+
clearInterval(timer);
|
|
315
|
+
globalShortcut.unregisterAll();
|
|
316
|
+
(async () => {
|
|
317
|
+
// Finish native requests before shutting down the desktop app.
|
|
318
|
+
await bridge?.close();
|
|
319
|
+
rmSync(statusFile, {force: true});
|
|
320
|
+
shutdownComplete = true;
|
|
321
|
+
app.quit();
|
|
322
|
+
})().catch(error => {
|
|
323
|
+
report(error);
|
|
324
|
+
quitting = false;
|
|
325
|
+
if (readyForUI) { registerShortcuts(settings); timer = setInterval(poll, 100); }
|
|
326
|
+
else app.exit(1);
|
|
327
|
+
});
|
|
328
|
+
});
|