@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.
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
- Windows의 Snap Layouts와 macOS의 Magnet에서 익숙한 창 배치를 Ubuntu GNOME에서 사용할 수 있습니다.
8
+ Ubuntu GNOME 확장과 macOS 데스크톱 앱으로 창을 나누고 정렬합니다.
9
9
 
10
10
  ![GNOME](https://img.shields.io/badge/GNOME-46%E2%80%9350-4a86cf)
11
11
  ![Session](https://img.shields.io/badge/session-Wayland-555555)
@@ -17,7 +17,7 @@ Windows의 Snap Layouts와 macOS의 Magnet에서 익숙한 창 배치를 Ubuntu
17
17
 
18
18
  ## Overview
19
19
 
20
- Tidy는 GNOME Shell에서 실행되는 창 배치 확장입니다. 여러 모니터를 사용할 때도 화면 상단 안쪽에서 배치 선택기를 열고, 그림으로 표시된 칸에 창을 놓을 수 있습니다.
20
+ Tidy는 Ubuntu GNOME과 macOS에서 창을 배치합니다. GNOME에서는 Shell 확장으로, macOS에서는 별도 데스크톱 앱으로 실행됩니다. 여러 모니터를 사용할 때도 화면 상단 안쪽에서 배치 선택기를 열고, 그림으로 표시된 칸에 창을 놓을 수 있습니다.
21
21
 
22
22
  <img src="docs/preview.png" alt="무채색 배치 그림으로 구성된 Tidy 상단 선택기" width="760">
23
23
 
@@ -25,16 +25,23 @@ Tidy는 GNOME Shell에서 실행되는 창 배치 확장입니다. 여러 모니
25
25
 
26
26
  ## Features
27
27
 
28
+ 아래 표는 GNOME판의 기능입니다. macOS판은 배치 선택기, 상단 드래그·가장자리 배치, 단축키, 다중 모니터, 최대화·복귀와 창 간격을 제공합니다. 기능 범위와 설치 방법은 [macOS 안내](docs/MACOS.md)를 참고하세요.
29
+
28
30
  | 기능 | 동작 |
29
31
  | --- | --- |
30
- | 상단 배치 선택기 | 창을 상단 중앙으로 끌어 원하는 칸에 놓습니다. 7가지 레이아웃을 제공합니다. |
32
+ | 상단 배치 선택기 | 창을 상단 중앙으로 끌어 원하는 칸에 놓습니다. 6가지 배치를 한 행으로 표시합니다. |
33
+ | 최대화 버튼 선택기 | 최대화·복원 버튼에 마우스를 잠시 올리면 3열 × 2행 선택기가 열립니다. 설정에서 켜고 끌 수 있습니다. |
31
34
  | 가장자리 배치 | 중앙 외 상단은 최대화, 왼쪽·오른쪽 가장자리는 절반 배치로 동작합니다. |
32
- | 창·앱 보기 연동 | Super로 기존 창·앱 보기와 선택기를 함께 열고, 창 미리보기를 배치 칸에 끌어 놓습니다. |
35
+ | 창 보기 연동 | Super로 창 보기와 한 행 선택기를 함께 엽니다. 창 미리보기를 배치 칸에 끌어 놓습니다. Super+A 앱 목록에서는 선택기를 숨깁니다. |
33
36
  | 사용자 지정 단축키 | Super+Alt 조합으로 절반·¼·⅓·⅔ 배치를 지정하고 단축키를 바꿀 수 있습니다. |
34
37
  | 다중 모니터 | 같은 방향키를 반복하면 해당 방향의 모니터로 이동합니다. 선택기 크기도 모니터에 맞춰 조절합니다. |
35
38
  | 함께 크기 조절 | 타일 창의 공유 경계를 끌면 맞닿은 창을 함께 조절합니다. 기본값은 켬입니다. |
36
39
  | 남은 공간 채우기 | 빈 영역에 실행 중인 앱 아이콘을 표시해 다음 창을 고릅니다. 기본값은 끔입니다. |
37
- | 크기와 간격 설정 | 일반 선택기와 창·앱 보기 선택기의 크기, 창 사이 간격을 조절합니다. |
40
+ | 크기와 간격 설정 | 일반 선택기와 창 보기 선택기의 크기, 창 사이 간격을 조절합니다. |
41
+
42
+ 선택기의 100%는 이전 버전의 115% 크기입니다. 기존에 저장한 크기는 새 기준으로 환산합니다. 상하 분할과 전체화면 카드는 제거하고, 동일한 너비의 3열 오른쪽에 **¼ · ½ · ¼** 배치를 제공합니다. 최대화 단축키와 화면 상단 가장자리의 최대화 동작은 계속 사용할 수 있습니다. 자동 크기 조절은 16인치 내장 화면의 기준 크기를 유지하며, 32인치 외장 화면에서는 이전 자동 크기의 약 80%를 새 100%로 사용합니다.
43
+
44
+ 최대화 버튼 선택기는 약 0.35초 대기 후 열리며, 칸을 클릭하면 해당 창을 배치합니다. 바깥으로 마우스를 옮기거나 Esc를 누르면 닫힙니다. 실제 버튼의 접근성 정보를 사용하므로, 버튼 정보를 제공하지 않는 자체 제목 표시줄에서는 표시되지 않습니다. 영어·한국어 최대화·복원 버튼을 지원하며, Brave의 ‘복구’ 버튼과 중첩된 제목 표시줄도 감지합니다.
38
45
 
39
46
  ## Platform Support
40
47
 
@@ -43,12 +50,15 @@ Tidy는 GNOME Shell에서 실행되는 창 배치 확장입니다. 여러 모니
43
50
  | Ubuntu 26.04 · GNOME 50.1 · Wayland | 독립 GNOME 세션의 실제 Wayland 창과 가상 모니터 2개로 검증 |
44
51
  | GNOME 46–49 | 호환 버전으로 선언되어 있으나 실기 검증 전 |
45
52
  | X11 | 실기 검증 전 |
46
- | KDE · Xfce · Windows · macOS | 지원 대상 아님 |
53
+ | macOS 13 이상 · Intel/Apple Silicon | Accessibility 기반 데스크톱 앱 추가 · 실기 검증 전 |
54
+ | KDE · Xfce | 지원 대상 아님 |
47
55
 
48
- 실행에는 시스템 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와 손쉬운 사용 권한이 필요합니다.
49
57
 
50
58
  ## Install
51
59
 
60
+ macOS도 `tidy install`로 설치합니다. 설치 후 즉시 실행되며 로그인 자동 실행을 등록합니다. 소스에서는 `node bin/tidy.js install`을 사용하세요. 권한 설정과 필수 도구는 [macOS 안내](docs/MACOS.md)에 설명되어 있습니다. 아래의 로그아웃·재로그인 및 Python 설치 절차는 GNOME판에 해당합니다.
61
+
52
62
  ### npm
53
63
 
54
64
  패키지 이름은 **`@hnode/tidy`**, 실행 명령은 **`tidy`**입니다. npm 공개 후 다음 명령으로 패키지와 GNOME 확장을 설치합니다.
@@ -86,13 +96,15 @@ Git 대신 [Download ZIP](https://github.com/hojin-v/Tidy/archive/refs/heads/mai
86
96
 
87
97
  ## Quick Start
88
98
 
99
+ 아래의 Super·창 보기 연동은 GNOME판 기능입니다. macOS에서는 메뉴 막대 아이콘이나 배치 선택기 단축키를 사용하며, 상단으로 창을 끌어 배치할 수도 있습니다.
100
+
89
101
  1. 창의 제목 표시줄을 잡으면 상단에 선택기 인식 영역이 얇게 나타납니다.
90
102
  2. 그 영역으로 끌면 선택기가 펼쳐지고 창이 작은 미리보기로 줄어듭니다. 원하는 배치 칸으로 포인터를 옮깁니다.
91
103
  3. 마우스를 놓으면 창을 배치합니다. 빈 곳에서 놓으면 취소합니다.
92
104
 
93
- **Super**를 누르면 기존 창·앱 보기와 배치 선택기가 함께 열립니다. 창 미리보기를 원하는 칸에 끌어 놓거나, 칸을 클릭해 원래 포커스된 창을 배치할 수 있습니다. 검색은 글자를 입력할 때 나타납니다.
105
+ **Super**를 누르면 창 보기와 한 행 배치 선택기가 함께 열립니다. **Super+A**로 앱 목록을 열면 선택기와 배치 미리보기를 숨기고, 창 보기로 돌아오면 다시 표시합니다. 창 미리보기를 원하는 칸에 끌어 놓거나, 칸을 클릭해 원래 포커스된 창을 배치할 수 있습니다. 검색은 글자를 입력할 때 나타납니다.
94
106
 
95
- 창·앱 보기에서는 창 미리보기와 앱 아이콘을 잡고 움직이는 즉시 작아지며, 놓거나 취소하면 원래 크기로 돌아옵니다. 선택기 표시를 꺼도 이 모션은 동작합니다. 배치 칸에 놓으면 작은 미리보기에서 배치 위치로 이어집니다.
107
+ 창 보기에서는 창 미리보기를 잡고 움직이는 즉시 작아지며, 놓거나 취소하면 원래 크기로 돌아옵니다. 배치 칸에 놓으면 작은 미리보기에서 배치 위치로 이어집니다.
96
108
 
97
109
  남은 공간의 창 선택 옵션을 켰다면 빈 영역의 앱 아이콘을 선택하세요. 현재 창이나 다른 영역을 클릭하거나 Esc를 누르면 추가 배치 없이 마칩니다.
98
110
 
@@ -102,12 +114,14 @@ Git 대신 [Download ZIP](https://github.com/hojin-v/Tidy/archive/refs/heads/mai
102
114
 
103
115
  ## Shortcuts
104
116
 
117
+ macOS판은 아래 배치 동작에 **Control+Option**을 사용합니다. 단독 Super와 Super+A의 창 보기 연동은 GNOME판 기능입니다. macOS의 기본 타일링과 시스템 단축키 설정은 변경하지 않습니다. [macOS 단축키 안내](docs/MACOS.md#shortcuts-and-settings)를 참고하세요.
118
+
105
119
  배치 단축키는 **Super+Alt** 조합으로 통일되어 있습니다. 설정의 **단축키** 탭에서 바꿀 수 있습니다.
106
120
 
107
121
  | 단축키 | 동작 |
108
122
  | --- | --- |
109
- | Super | 기존 창·앱 보기와 배치 선택기 열기 / 닫기 |
110
- | Super + A | GNOME 앱 목록 전환 |
123
+ | Super | 창 보기와 배치 선택기 열기 / 닫기 |
124
+ | Super + A | GNOME 앱 목록 전환 · 배치 선택기는 숨김 |
111
125
  | Super + Alt + ← / → | 왼쪽 / 오른쪽 절반 배치. 같은 방향 반복 시 다음 모니터로 이동하며 양 끝에서는 반대편 끝으로 순환 |
112
126
  | Super + Alt + ↑ / ↓ | 위쪽 / 아래쪽 절반 배치. 같은 방향 반복 시 위·아래 모니터로 이동하며 양 끝에서는 반대편 끝으로 순환 |
113
127
  | Super + Alt + Enter | 최대화 / 이전 크기·배치로 복귀 |
@@ -124,13 +138,16 @@ Git 대신 [Download ZIP](https://github.com/hojin-v/Tidy/archive/refs/heads/mai
124
138
 
125
139
  ## Settings
126
140
 
141
+ macOS에서는 `tidy prefs` 또는 메뉴 막대 아이콘으로 설정을 엽니다. 설정 범위는 [macOS 안내](docs/MACOS.md#shortcuts-and-settings)를 참고하세요. 아래 옵션은 GNOME판 기준입니다.
142
+
127
143
  앱 목록의 **Tidy** 또는 **상단 격자 아이콘 → 설정 및 단축키…**에서 변경합니다. 설정은 즉시 반영됩니다.
128
144
 
129
145
  - **기존 Super+방향키 창 배치 끄기**: GNOME 기본 배치 단축키를 끕니다. 해제하거나 Tidy를 종료하면 기존 단축키를 복원합니다.
130
146
  - **모니터에 맞춰 선택기 크기 자동 조절**: 내장 화면을 기준으로 큰 외장 모니터의 선택기를 적당히 키웁니다. 기본값은 켬입니다.
131
- - **배치 선택기 크기 / 창·앱 보기 선택기 크기**: 기본 크기는 같으며, 창·앱 보기의 크기를 별도로 조절할 수 있습니다.
147
+ - **배치 선택기 크기 / 창 보기 선택기 크기**: 기본 크기는 같으며, 창 보기의 크기를 별도로 조절할 수 있습니다.
132
148
  - **선택기 너비에 인식 범위 맞추기**: 기본값은 켬입니다. 모니터별 선택기 너비에 맞춰 인식 영역과 드래그 안내를 조절합니다. 끄면 기존 사용자 지정 너비를 사용합니다.
133
149
  - **남은 공간의 창 선택**: 배치 후 빈 영역에 앱 아이콘을 표시합니다. 기본값은 끔입니다.
150
+ - **최대화 버튼에 마우스를 올리면 배치 선택기 표시**: 최대화·복원 버튼에서 선택기를 엽니다. 기본값은 켬이며 상단 드래그 선택기와 별도로 끌 수 있습니다.
134
151
 
135
152
  CLI에서도 설정이나 상태를 확인할 수 있습니다.
136
153
 
@@ -184,11 +201,14 @@ CLI가 없어도 어느 폴더에서든 설치된 도구로 제거할 수 있습
184
201
 
185
202
  확장과 앱 실행기를 제거하고, 변경했던 GNOME 설정과 기존 타일링 확장 상태를 복원합니다. Tidy의 사용자 설정과 단축키는 재설치를 위해 보관합니다.
186
203
 
204
+ 기존 타일링 확장의 사용자 설치본을 삭제하여 현재 세션에서 인식되지 않는 경우, 남아 있는 시스템 원본을 다음 로그인에 활성화하도록 설정하고 Tidy 제거를 완료합니다. 이 경우 출력 안내에 따라 다시 로그인하세요. 이전 확장이 시스템에서도 제거됐다면 재설치하지 않습니다.
205
+
187
206
  경로의 `winubun`은 기존 설정과 고정한 실행기의 호환성을 위해 유지한 내부 이름입니다.
188
207
 
189
208
  ## Notes
190
209
 
191
210
  - **Ubuntu Tiling Assistant**가 켜져 있으면 설치 도구가 원래 상태를 기록하고 비활성화합니다. `uninstall` 시 복원합니다. 확장 앱에서 Tidy만 끄면 Tiling Assistant는 중지 상태로 남습니다.
211
+ - 확장 관리자의 X는 확장 오류를 뜻합니다. `gnome-extensions info tiling-assistant@ubuntu.com`과 Shell 로그로 실제 상태를 확인하세요. Ubuntu Tiling Assistant의 중복 초기화나 해제 실패로 남은 동작은 해당 확장의 복구가 필요합니다. Tidy와 동시에 켜지 않도록 관리하세요.
192
212
  - 앱이 요구하는 최소 창 크기나 터미널의 크기 단위 때문에 작은 칸에 정확히 맞지 않을 수 있습니다. 전체 화면 앱과 이동·크기 변경을 허용하지 않는 창은 배치 대상에서 제외합니다.
193
213
  - 문제를 신고할 때는 GNOME 버전, Wayland/X11 여부, 모니터 배치와 재현 순서를 [Issues](https://github.com/hojin-v/Tidy/issues)에 남겨 주세요.
194
214
 
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 GNOME\n\nUsage: tidy <command>\n\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 the installed extension status\n doctor Check system requirements\n\nInstall: npx @hnode/tidy@latest install\nAfter installation, log out and back in once.'));
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 requires Linux with GNOME Shell 46–50.'));
36
+ error(_('Tidy supports Linux with GNOME Shell 46–50 and macOS.'));
34
37
  return 1;
35
38
  }
36
39
  const command = args[0];
@@ -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>
@@ -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
+ });