@hnode/tidy 0.0.0-stage → 0.18.1

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,59 @@
1
+ # npm release
2
+
3
+ Tidy는 **@hnode/tidy**라는 공개 npm 패키지로 배포합니다. `tidy` CLI와 미리 빌드한 GNOME 확장 ZIP을 포함하며 런타임 npm 의존성은 없습니다. 확장 ZIP에는 GPL 소스와 복구 도구가 포함됩니다.
4
+
5
+ ## Prepare
6
+
7
+ Node.js 18 이상과 시스템 Python/PyGObject, GJS, GTK 4/libadwaita, `glib-compile-schemas`가 필요합니다.
8
+
9
+ ```bash
10
+ npm test
11
+ npm run check
12
+ /usr/bin/python3 -m unittest discover -s tests -p 'test_*.py'
13
+ npm run test:package
14
+ npm pack --dry-run
15
+ npm pack --pack-destination dist
16
+ node tests/npm-package-smoke.js dist/hnode-tidy-0.18.1.tgz
17
+ ```
18
+
19
+ `prepack`이 최신 소스로 확장 ZIP을 다시 빌드합니다. 공개 파일은 `package.json`의 `files` 목록으로 제한합니다. 로그, 테스트, `.npmrc`, 캐시가 포함되지 않는지 확인하세요. npm 패키지 설치 자체는 데스크톱 설정을 바꾸지 않으며 `postinstall`은 사용하지 않습니다.
20
+
21
+ 패키지 테스트는 임시 npm 전역 경로와 XDG 디렉터리를 사용합니다. 실제 tarball에서 명령을 설치한 뒤 읽기 전용 패키지, 한국어·영어 도움말, 의존성 진단과 설치된 복구 도구 호출을 확인합니다. 데스크톱 작업은 격리된 대역으로 호출을 검사합니다. Python 테스트는 실제 ZIP 설치·설정 복구를 수행하고 Shell 통신만 대체합니다.
22
+
23
+ 창 동작을 바꿨다면 별도 GNOME 세션에서도 확인합니다.
24
+
25
+ ```bash
26
+ /usr/bin/python3 scripts/test-shell.py
27
+ ```
28
+
29
+ ## Publish
30
+
31
+ `@hnode` 사용자 계정 또는 해당 조직에 패키지를 게시할 권한이 필요합니다. 검증한 tarball을 그대로 게시합니다.
32
+
33
+ ```bash
34
+ npm login --registry=https://registry.npmjs.org/
35
+ npm whoami --registry=https://registry.npmjs.org/
36
+ npm publish ./dist/hnode-tidy-0.18.1.tgz --access public --tag latest
37
+ npm view @hnode/tidy version dist-tags --json
38
+ ```
39
+
40
+ npm이 요청하는 브라우저 로그인·2FA를 완료하세요. 같은 버전이 이미 게시되었으면 `package.json`의 버전을 올리고 다시 검증합니다. GNOME 런타임 JavaScript가 바뀌면 `metadata.json`의 확장 버전도 올립니다. npm CLI·Python 설치 도구·문서만 바뀌면 Shell 버전을 유지할 수 있습니다.
41
+
42
+ ## User commands
43
+
44
+ ```bash
45
+ npm install -g @hnode/tidy
46
+ tidy install
47
+ tidy doctor
48
+ tidy prefs
49
+ tidy status
50
+ ```
51
+
52
+ 최초 설치·확장 코드 업데이트 후에는 한 번 다시 로그인합니다. `npx @hnode/tidy@latest install`도 지원합니다. npm 패키지와 캐시를 삭제해도 설치된 GNOME 확장은 유지됩니다.
53
+
54
+ ```bash
55
+ tidy uninstall
56
+ npm uninstall -g @hnode/tidy
57
+ ```
58
+
59
+ 확장을 먼저 제거해야 변경했던 GNOME 설정과 기존 타일링 확장을 복원할 수 있습니다. npm 패키지만 지우는 명령은 데스크톱 설정을 변경하지 않습니다. CLI가 없어도 README에 나온 설치된 Python 관리 도구로 제거할 수 있습니다.
Binary file
Binary file
@@ -0,0 +1,15 @@
1
+ // English source strings are the fallback for languages without a catalog.
2
+ export function languageFor(languages) {
3
+ for (const language of languages) {
4
+ const base = language.toLowerCase().split(/[_@.\-]/)[0];
5
+ if (base === 'ko') return 'ko';
6
+ if (base === 'en' || base === 'c' || base === 'posix') return 'en';
7
+ }
8
+ return 'en';
9
+ }
10
+
11
+ export function createTranslator(catalogs, languages) {
12
+ const catalog = catalogs[languageFor(languages)] ?? {};
13
+ return (message, values = {}) => (catalog[message] ?? message).replace(/\{(\w+)\}/g,
14
+ (placeholder, key) => Object.hasOwn(values, key) ? String(values[key]) : placeholder);
15
+ }
@@ -0,0 +1,120 @@
1
+ {
2
+ "ko": {
3
+ "Unassigned": "미지정",
4
+ "Tidy Settings": "Tidy 설정",
5
+ "Window tiling": "창 배치",
6
+ "Drag a window to the top of the screen and drop it into a layout. Settings take effect immediately.": "창을 화면 위쪽으로 끌어 원하는 칸에 놓으세요. 모든 설정은 즉시 적용됩니다.",
7
+ "Resize tiled windows together": "타일 창 크기 함께 조절",
8
+ "Drag a shared boundary to resize adjacent windows together. Default: on.": "맞닿은 경계를 드래그하면 이웃 창의 크기도 함께 바뀝니다. 기본값: 켬",
9
+ "Show layouts in the window and app overview": "창·앱 보기에 상단 배치 선택기 표시",
10
+ "Disable native Super+arrow tiling": "기존 Super+방향키 창 배치 끄기",
11
+ "Disable GNOME Super+arrow tiling, maximize and restore shortcuts. Super+Alt and edge dragging remain available. Turn this option off to restore the original shortcuts.": "GNOME의 Super+방향키 배치·최대화·복원을 끕니다. Super+Alt와 마우스 가장자리 배치는 계속 사용할 수 있습니다. 끄면 원래 단축키를 복원합니다.",
12
+ "Top-center layout picker": "상단 중앙 배치 선택기",
13
+ "While dragging, the picker opens at the top center. Other top edges maximize; left and right edges tile halves.": "드래그할 때 상단 중앙에서만 열립니다. 나머지 상단은 최대화, 좌우 가장자리는 절반 배치입니다.",
14
+ "Choose windows for the remaining space": "남은 공간의 창 선택",
15
+ "Dragging and spacing": "드래그와 간격",
16
+ "Match activation width to picker": "선택기 너비에 인식 범위 맞추기",
17
+ "The top activation area and drag hint follow the picker width on each monitor. Turn off to use a custom width. Default: on.": "상단 인식 범위와 드래그 안내의 너비를 모니터별 선택기 너비에 맞춥니다. 끄면 직접 너비를 정할 수 있습니다. 기본값: 켬",
18
+ "A small hint appears while dragging. Move into the top-center area to reveal layouts and shrink the dragged window. Other top edges and side edges tile directly.": "창을 드래그하면 상단에 안내가 살짝 나타납니다. 상단 중앙으로 가져가면 선택기가 펼쳐지고 잡고 있는 창이 작아집니다. 중앙 외 상단과 좌우 가장자리는 바로 배치합니다.",
19
+ "Pause near the top center to open layouts. Other top edges and side edges tile directly.": "상단 중앙 영역에 잠시 머물면 선택기가 열립니다. 중앙 외 상단과 좌우 가장자리는 바로 배치합니다.",
20
+ "Activation area height": "중앙 감지 높이",
21
+ "Distance from the top of the monitor work area, in logical pixels": "모니터 작업 영역 위쪽에서의 거리 (논리 픽셀)",
22
+ "Activation area width": "중앙 감지 너비",
23
+ "Width around the top center, in logical pixels": "상단 정중앙을 기준으로 한 너비 (논리 픽셀)",
24
+ "Picker delay": "선택기를 여는 대기 시간",
25
+ "Milliseconds · helps prevent accidental activation": "밀리초 · 실수로 열리는 것을 줄입니다.",
26
+ "Window gap": "창 사이 간격",
27
+ "Logical pixels · does not apply to maximized windows": "논리 픽셀 · 최대화에는 적용하지 않습니다.",
28
+ "Shortcuts": "단축키",
29
+ "Customize your layouts": "내 방식대로 배치하기",
30
+ "All layout shortcuts use Super+Alt. Click a button and press a new combination. Backspace: clear · Esc: cancel.": "모든 단축키는 Super+Alt 조합입니다. 오른쪽 버튼을 누른 뒤 새 조합을 입력하세요. Backspace: 해제 · Esc: 취소.",
31
+ "Restore default shortcuts": "단축키 기본값 복원",
32
+ "Restore defaults": "기본값 복원",
33
+ "Usage": "사용 안내",
34
+ "Super + Alt + Arrow: tile to that half\nRepeat an arrow to move to the monitor in that direction; outer edges wrap to the opposite monitor\nSuper + Alt + Enter: maximize / restore previous layout\nSuper + Alt + Space: layout picker\nSuper + Alt + N: next monitor\n\nUbuntu Tiling Assistant may conflict with tiling and shortcuts. The installer disables it and restores its original state on uninstall.\nApp minimum window sizes may prevent an exact fit.": "Super + Alt + 방향키: 해당 방향 절반 배치\n같은 방향키를 한 번 더 누르면 해당 방향 모니터로 이동 · 상하좌우 끝에서는 반대쪽 끝으로 순환\nSuper + Alt + Enter: 최대화 / 이전 배치 복원\nSuper + Alt + Space: 배치 선택기\nSuper + Alt + N: 다음 모니터\n\nUbuntu Tiling Assistant와 동시에 사용하면 배치 및 단축키가 충돌할 수 있습니다. 설치 도구가 기존 확장을 중지하고 제거 시 원래 상태를 복원합니다.\n앱이 요구하는 최소 창 크기보다 작은 칸에는 정확히 맞지 않을 수 있습니다.",
35
+ "Set shortcut": "단축키 지정",
36
+ "Press your new key combination": "원하는 키 조합을 눌러주세요",
37
+ "Backspace to clear · Esc to cancel": "Backspace로 해제 · Esc로 취소",
38
+ "Include both Super and Alt in the shortcut.": "Super와 Alt를 모두 포함한 조합을 입력하세요.",
39
+ "Tidy · Choose layout": "Tidy · 배치 선택",
40
+ "Settings and shortcuts…": "설정 및 단축키…",
41
+ "Cancel": "취소",
42
+ "Choose an open window or press Esc to skip.": "열려 있는 창을 선택하거나 Esc로 건너뛰세요.",
43
+ "Skip": "건너뛰기",
44
+ "Window": "창",
45
+ "Tidy settings schema was not found. Please reinstall.": "Tidy 설정 스키마를 찾을 수 없습니다. 다시 설치하세요.",
46
+ "Halves": "반으로",
47
+ "Wide": "넓게",
48
+ "Three columns": "세 칸",
49
+ "Focus": "집중",
50
+ "Four quarters": "네 칸",
51
+ "Top and bottom": "위아래",
52
+ "Maximize": "전체",
53
+ "Left half / left monitor": "왼쪽 절반 / 왼쪽 모니터",
54
+ "Right half / right monitor": "오른쪽 절반 / 오른쪽 모니터",
55
+ "Maximize / restore previous layout": "최대화 / 이전 배치 복원",
56
+ "Top half": "위쪽 절반",
57
+ "Bottom half": "아래쪽 절반",
58
+ "Top-left quarter": "왼쪽 위 ¼",
59
+ "Top-right quarter": "오른쪽 위 ¼",
60
+ "Bottom-left quarter": "왼쪽 아래 ¼",
61
+ "Bottom-right quarter": "오른쪽 아래 ¼",
62
+ "Left third": "왼쪽 ⅓",
63
+ "Center third": "가운데 ⅓",
64
+ "Right third": "오른쪽 ⅓",
65
+ "Left two-thirds": "왼쪽 ⅔",
66
+ "Right two-thirds": "오른쪽 ⅔",
67
+ "Centered three-quarter size": "가운데 ¾ 크기",
68
+ "Open layout picker": "배치 선택기 열기",
69
+ "Move to next monitor": "다음 모니터로 이동",
70
+ "Already used for “{action}”. Clear that shortcut first.": "이미 “{action}”에 사용 중입니다. 먼저 해당 단축키를 해제하세요.",
71
+ "Conflicts with the system shortcut “{shortcut}”. Choose another combination.": "시스템 단축키 “{shortcut}”와 겹칩니다. 다른 조합을 입력하세요.",
72
+ "Fill remaining space · {count} slots": "남은 공간 채우기 · {count}칸",
73
+ "Could not restore the previous extension. Run uninstall again.": "기존 확장 복원 실패. uninstall을 다시 실행하세요.",
74
+ "The previous Tidy did not stop. The update was cancelled.": "기존 Tidy가 중지되지 않아 업데이트를 멈췄습니다.",
75
+ "The new version is installed. GNOME cannot reload cached JavaScript during the current session.": "새 버전 설치 완료. GNOME은 현재 로그인에서 읽은 JavaScript를 다시 불러올 수 없습니다.",
76
+ "Log out and log back in once to activate the new Tidy automatically.": "한 번 로그아웃하고 다시 로그인하면 새 Tidy가 자동으로 활성화됩니다.",
77
+ "The previous Tidy has been stopped for this session.": "현재 세션에서는 이전 Tidy를 중지해 잘못 표시되는 패널을 제거했습니다.",
78
+ "Install Tidy, then log out and log back in.": "Tidy를 설치한 다음 로그아웃하고 다시 로그인하세요.",
79
+ "New Tidy code is installed. Please log out and log back in to apply it automatically.": "새 Tidy 코드가 설치됐습니다. 한 번 로그아웃하고 다시 로그인하면 자동 적용됩니다.",
80
+ "The previous tiling extension did not stop.": "기존 배치 확장이 중지되지 않았습니다.",
81
+ "Tidy extension error: ": "Tidy 확장 오류: ",
82
+ "Tidy activation failed. Restoring the previous tiling configuration.\n": "Tidy 활성화 실패. 기존 배치 기능을 복원합니다.\n",
83
+ "Tidy is active. Use the grid icon in the top bar → Settings and shortcuts…": "Tidy 활성화 완료. 상단 패널의 격자 아이콘 → 설정 및 단축키…",
84
+ "Status: gnome-extensions info ": "상태 확인: gnome-extensions info ",
85
+ "GNOME has not registered Tidy yet. Launch Tidy from the app list.": "GNOME이 Tidy를 아직 등록하지 않았습니다. 앱 목록에서 Tidy를 실행하세요.",
86
+ "The extension is not registered in this session. Checking settings recovery.": "현재 세션에 확장이 등록되지 않았습니다. 설정 복구를 확인합니다.",
87
+ "Tidy was removed and previous tiling settings were restored. Your custom shortcuts have been kept.": "Tidy 제거 및 기존 배치 설정 복원 완료. 사용자 단축키 설정은 보관됩니다.",
88
+ "The extension is not registered in the current session.": "확장이 현재 세션에 등록되지 않았습니다.",
89
+ "Tidy launch error": "Tidy 실행 오류",
90
+ "GNOME Shell communication failed ({method}): {error}": "GNOME Shell 통신 실패 ({method}): {error}",
91
+ "GNOME could not find the extension: {uuid}": "GNOME이 확장을 찾지 못했습니다: {uuid}",
92
+ "Built: {path}": "빌드 완료: {path}",
93
+ "GNOME {version} is not supported. Supported versions: 46–50": "GNOME {version}은 지원 대상이 아닙니다. 지원 버전: 46–50",
94
+ "Manage symlink installations manually: {path}": "심볼릭 링크 설치는 수동으로 관리하세요: {path}",
95
+ "Remove symlink installations manually: {path}": "심볼릭 링크 설치는 수동으로 제거하세요: {path}",
96
+ "Unknown error": "알 수 없는 오류",
97
+ "Press Super to open the overview and layouts together. Drag a window thumbnail onto a layout cell. Search appears only when you type. Default: on.": "Super로 창·앱 보기와 배치 선택기를 함께 엽니다. 창 썸네일을 배치 칸으로 끌어 놓으세요. 검색란은 글자를 입력할 때만 표시합니다. 기본값: 켬",
98
+ "Show running app icons inside empty layout regions. Select an icon to tile its window, or click elsewhere or press Esc to finish. Default: off.": "빈 배치 영역 안에 실행 중인 앱 아이콘을 표시합니다. 아이콘을 선택하면 창을 배치하고, 다른 곳을 클릭하거나 Esc를 누르면 마무리합니다. 기본값: 끔",
99
+ "Layout picker size": "배치 선택기 크기",
100
+ "Overview picker size": "창·앱 보기 선택기 크기",
101
+ "Percent of the normal picker size. 100% keeps both the same size.": "일반 선택기 크기에 대한 비율입니다. 100%이면 두 화면에서 같은 크기로 표시합니다.",
102
+ "Percent. Sizes are limited to fit the monitor.": "퍼센트. 모니터에 맞게 최대 크기를 제한합니다.",
103
+ "Adapt picker size to each monitor": "모니터에 맞춰 선택기 크기 자동 조절",
104
+ "Keep the built-in display size and gently enlarge the picker on larger external displays. Your size settings remain the baseline. Default: on.": "내장 화면의 크기는 유지하고, 큰 외장 모니터에서는 선택기를 적당히 키웁니다. 지정한 크기를 기준으로 조절합니다. 기본값: 켬",
105
+ "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.": "Tidy · GNOME 창 배치\n\n사용법: tidy <명령>\n\n install 현재 사용자에게 Tidy 설치\n update 현재 npm 패키지 버전으로 Tidy 갱신\n uninstall Tidy 제거 및 데스크톱 설정 복원\n prefs 설정 및 단축키 열기\n status 설치한 확장 상태 확인\n doctor 시스템 요구 사항 확인\n\n설치: npx @hnode/tidy@latest install\n설치 후 한 번 로그아웃하고 다시 로그인하세요.",
106
+ "Unknown command. Run tidy --help.": "알 수 없는 명령입니다. tidy --help를 실행하세요.",
107
+ "Tidy requires Linux with GNOME Shell 46–50.": "Tidy는 GNOME Shell 46–50을 사용하는 Linux에서 실행할 수 있습니다.",
108
+ "Run Tidy as your desktop user, without sudo.": "sudo 없이 현재 데스크톱 사용자로 Tidy를 실행하세요.",
109
+ "System Python with PyGObject is required. For installation and settings, GTK 4 and libadwaita are also required.": "시스템 Python과 PyGObject가 필요합니다. 설치와 설정에는 GTK 4와 libadwaita도 필요합니다.",
110
+ "Tidy requires GJS and GNOME Shell 46–50. Run this command in your GNOME desktop session.": "GJS와 GNOME Shell 46–50이 필요합니다. GNOME 데스크톱 세션에서 실행하세요.",
111
+ "System requirements are available.": "시스템 요구 사항을 충족합니다.",
112
+ "Tidy is not installed. Run tidy install first.": "Tidy가 설치되어 있지 않습니다. 먼저 tidy install을 실행하세요.",
113
+ "The bundled extension is missing. Reinstall @hnode/tidy, or run npm run build from the source checkout.": "확장 설치 파일이 없습니다. @hnode/tidy를 다시 설치하거나 소스 폴더에서 npm run build를 실행하세요.",
114
+ "Tidy was interrupted.": "Tidy 실행이 중단되었습니다.",
115
+ "The bundled extension does not match this installer. Download Tidy again.": "확장 설치 파일과 설치 도구의 버전이 다릅니다. Tidy를 다시 다운로드하세요.",
116
+ "Install a prebuilt extension ZIP without writing to the package directory": "패키지 폴더에 파일을 쓰지 않고 미리 빌드한 확장 ZIP으로 설치합니다.",
117
+ "Top half / upper monitor": "위쪽 절반 / 위쪽 모니터",
118
+ "Bottom half / lower monitor": "아래쪽 절반 / 아래쪽 모니터"
119
+ }
120
+ }
package/metadata.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "uuid": "winubun@winubun.local",
3
+ "name": "Tidy",
4
+ "description": "Top layout picker, optional snap assist, and customizable window tiling shortcuts",
5
+ "shell-version": [
6
+ "46",
7
+ "47",
8
+ "48",
9
+ "49",
10
+ "50"
11
+ ],
12
+ "settings-schema": "org.gnome.shell.extensions.winubun",
13
+ "version": 18,
14
+ "url": "https://github.com/hojin-v/Tidy"
15
+ }
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@hnode/tidy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.18.1",
4
+ "description": "Window tiling for Ubuntu GNOME with a top layout picker, custom shortcuts and multi-monitor support",
5
+ "type": "module",
6
+ "bin": {
7
+ "tidy": "bin/tidy.js"
8
+ },
9
+ "files": [
10
+ "bin/tidy.js",
11
+ "lib/i18nCore.js",
12
+ "lib/translations.json",
13
+ "metadata.json",
14
+ "scripts/manage.py",
15
+ "scripts/i18n.py",
16
+ "scripts/recover.js",
17
+ "dist/winubun@winubun.local.shell-extension.zip",
18
+ "docs/README.en.md",
19
+ "docs/DEVELOPMENT.md",
20
+ "docs/RELEASING.md",
21
+ "docs/preview.png",
22
+ "docs/assist-preview.png",
23
+ "LICENSE",
24
+ "NOTICE"
25
+ ],
26
+ "os": ["linux"],
27
+ "engines": {
28
+ "node": ">=18"
29
+ },
30
+ "keywords": ["gnome", "ubuntu", "tiling", "window-manager", "snap-layouts", "multi-monitor"],
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org/"
34
+ },
35
+ "scripts": {
36
+ "test": "node --test tests/*.test.js",
37
+ "check": "python3 scripts/check.py",
38
+ "test:shell": "python3 scripts/test-shell.py",
39
+ "build": "python3 scripts/manage.py build",
40
+ "prepack": "/usr/bin/python3 scripts/manage.py build >&2",
41
+ "test:package": "node tests/npm-package-smoke.js",
42
+ "install-extension": "python3 scripts/manage.py install",
43
+ "uninstall-extension": "python3 scripts/manage.py uninstall"
44
+ },
45
+ "license": "GPL-3.0-or-later",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/hojin-v/Tidy.git"
49
+ },
50
+ "homepage": "https://github.com/hojin-v/Tidy#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/hojin-v/Tidy/issues"
53
+ }
54
+ }
@@ -0,0 +1,23 @@
1
+ """Share the application's catalogs and GLib locale precedence with the CLI."""
2
+ import json
3
+ from pathlib import Path
4
+ import re
5
+ from gi.repository import GLib
6
+
7
+ CATALOGS = json.loads((Path(__file__).resolve().parent.parent / 'lib/translations.json').read_text())
8
+
9
+
10
+ def language_for(languages):
11
+ for language in languages:
12
+ base = re.split(r'[_@.\-]', language.lower())[0]
13
+ if base == 'ko':
14
+ return 'ko'
15
+ if base in ('en', 'c', 'posix'):
16
+ return 'en'
17
+ return 'en'
18
+
19
+
20
+ def _(message, **values):
21
+ catalog = CATALOGS.get(language_for(GLib.get_language_names()), {})
22
+ return re.sub(r'\{(\w+)\}', lambda match: str(values.get(match[1], match[0])),
23
+ catalog.get(message, message))
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env python3
2
+ """Build/install Tidy with a recoverable Ubuntu extension handover."""
3
+ import argparse
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ import time
11
+ import zipfile
12
+ from gi.repository import Gio, GLib
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
14
+ from i18n import _
15
+
16
+ ROOT = Path(__file__).resolve().parent.parent
17
+ UUID = 'winubun@winubun.local'
18
+ DATA = Path(os.environ.get('XDG_DATA_HOME', Path.home() / '.local/share'))
19
+ STATE = Path(os.environ.get('XDG_STATE_HOME', Path.home() / '.local/state')) / 'winubun'
20
+ DEST = DATA / 'gnome-shell/extensions' / UUID
21
+ ARCHIVE = ROOT / 'dist' / f'{UUID}.shell-extension.zip'
22
+ AUTOSTART = Path(os.environ.get('XDG_CONFIG_HOME', Path.home() / '.config')) / 'autostart/winubun-update.desktop'
23
+ COMPETITORS = ['tiling-assistant@ubuntu.com', 'tiling-assistant@leleat-on-github']
24
+ RUNTIME_SCRIPTS = ('manage.py', 'i18n.py', 'recover.js')
25
+
26
+
27
+ def shell_call(method, signature=None, values=()):
28
+ """Talk to the compositor without starting the prefs/portal service."""
29
+ bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
30
+ try:
31
+ result = bus.call_sync('org.gnome.Shell', '/org/gnome/Shell',
32
+ 'org.gnome.Shell.Extensions', method,
33
+ GLib.Variant(signature, values) if signature else None,
34
+ None, Gio.DBusCallFlags.NONE, 5000, None)
35
+ return result.unpack()
36
+ except GLib.Error as error:
37
+ raise RuntimeError(_('GNOME Shell communication failed ({method}): {error}', method=method, error=error.message)) from error
38
+
39
+
40
+ def extension_info(uuid=UUID):
41
+ return shell_call('GetExtensionInfo', '(s)', (uuid,))[0]
42
+
43
+
44
+ def set_enabled(uuid, enabled):
45
+ result = shell_call('EnableExtension' if enabled else 'DisableExtension', '(s)', (uuid,))
46
+ if not result[0]:
47
+ raise RuntimeError(_('GNOME could not find the extension: {uuid}', uuid=uuid))
48
+
49
+
50
+ def open_preferences():
51
+ STATE.mkdir(parents=True, exist_ok=True)
52
+ with (STATE / 'preferences.log').open('a') as log:
53
+ subprocess.Popen(['/usr/bin/gjs', '-m', str(DEST / 'lib/preferencesApp.js')],
54
+ stdout=log, stderr=log, start_new_session=True)
55
+
56
+
57
+ def schedule_update(version):
58
+ STATE.mkdir(parents=True, exist_ok=True)
59
+ (STATE / 'pending-update.json').write_text(json.dumps({'version': version}))
60
+ AUTOSTART.parent.mkdir(parents=True, exist_ok=True)
61
+ script = str(DEST / 'scripts/manage.py').replace('\\', '\\\\').replace('"', '\\"').replace('`', '\\`').replace('$', '\\$').replace('%', '%%')
62
+ AUTOSTART.write_text('[Desktop Entry]\nType=Application\nName=Tidy update\n'
63
+ f'Exec=/usr/bin/python3 "{script}" apply-update\nTerminal=false\nNoDisplay=true\n')
64
+
65
+
66
+ def finish_update():
67
+ (STATE / 'pending-update.json').unlink(missing_ok=True)
68
+ AUTOSTART.unlink(missing_ok=True)
69
+
70
+
71
+ def run(*args, check=True):
72
+ return subprocess.run(args, check=check, text=True, capture_output=True,
73
+ env=dict(os.environ, LC_ALL='C'))
74
+
75
+
76
+ def install_launcher():
77
+ path = DATA / 'applications/winubun.desktop'
78
+ path.parent.mkdir(parents=True, exist_ok=True)
79
+ # Desktop-entry quoting follows the Exec key spec, not shell quoting.
80
+ script = str(DEST / 'scripts/manage.py').replace('\\', '\\\\').replace('"', '\\"').replace('`', '\\`').replace('$', '\\$').replace('%', '%%')
81
+ path.write_text('[Desktop Entry]\nType=Application\nName=Tidy\n'
82
+ 'Comment=Window tiling settings and shortcuts\nComment[ko]=창 배치 설정 및 단축키\nIcon=view-grid-symbolic\n'
83
+ f'Exec=/usr/bin/python3 "{script}" launch\nTerminal=false\nCategories=Utility;Settings;\n')
84
+
85
+
86
+ def build():
87
+ run('glib-compile-schemas', '--strict', str(ROOT / 'schemas'))
88
+ ARCHIVE.parent.mkdir(exist_ok=True)
89
+ with zipfile.ZipFile(ARCHIVE, 'w', zipfile.ZIP_DEFLATED) as archive:
90
+ for name in ['LICENSE', 'NOTICE', 'metadata.json', 'extension.js', 'prefs.js', 'stylesheet.css']:
91
+ archive.write(ROOT / name, name)
92
+ for directory in ['lib', 'schemas']:
93
+ for path in sorted((ROOT / directory).glob('*')):
94
+ if path.is_file():
95
+ archive.write(path, path.relative_to(ROOT))
96
+ for name in RUNTIME_SCRIPTS:
97
+ archive.write(ROOT / 'scripts' / name, f'scripts/{name}')
98
+ print(_('Built: {path}', path=ARCHIVE))
99
+ return ARCHIVE
100
+
101
+
102
+ def enabled_extensions():
103
+ return {uuid for uuid, info in shell_call('ListExtensions')[0].items()
104
+ if info.get('enabled') or info.get('state') == 1}
105
+
106
+
107
+ def restore_competitors():
108
+ path = STATE / 'handover.json'
109
+ if path.exists():
110
+ pending = json.loads(path.read_text())
111
+ failed = []
112
+ for uuid in pending:
113
+ try:
114
+ set_enabled(uuid, True)
115
+ except RuntimeError as error:
116
+ failed.append(uuid)
117
+ print(error, file=sys.stderr)
118
+ if failed:
119
+ path.write_text(json.dumps(failed))
120
+ raise RuntimeError(_('Could not restore the previous extension. Run uninstall again.'))
121
+ path.unlink()
122
+
123
+
124
+ def install(archive=None):
125
+ version = run('gnome-shell', '--version').stdout.split()[-1].split('.')[0]
126
+ metadata = json.loads((ROOT / 'metadata.json').read_text())
127
+ if version not in metadata['shell-version']:
128
+ raise RuntimeError(_('GNOME {version} is not supported. Supported versions: 46–50', version=version))
129
+ archive = Path(archive) if archive is not None else build()
130
+ with zipfile.ZipFile(archive) as package:
131
+ bundled = json.loads(package.read('metadata.json'))
132
+ if any(bundled.get(key) != metadata.get(key) for key in ['uuid', 'version', 'shell-version']):
133
+ raise RuntimeError(_('The bundled extension does not match this installer. Download Tidy again.'))
134
+ if DEST.is_symlink():
135
+ raise RuntimeError(_('Manage symlink installations manually: {path}', path=DEST))
136
+ # The session may need to discover a first installation at the next login.
137
+ # Keep the original tiler active until Tidy is actually available.
138
+ registered = extension_info()
139
+ if registered:
140
+ set_enabled(UUID, False)
141
+ for attempt in range(50):
142
+ if extension_info().get('state') in (2, 6):
143
+ break
144
+ time.sleep(0.1)
145
+ else:
146
+ raise RuntimeError(_('The previous Tidy did not stop. The update was cancelled.'))
147
+ DEST.mkdir(parents=True, exist_ok=True)
148
+ with zipfile.ZipFile(archive) as package:
149
+ package.extractall(DEST)
150
+ install_launcher()
151
+ if not registered or registered.get('version') != metadata['version']:
152
+ schedule_update(metadata['version'])
153
+ print(_('The new version is installed. GNOME cannot reload cached JavaScript during the current session.'))
154
+ print(_('Log out and log back in once to activate the new Tidy automatically.'))
155
+ print(_('The previous Tidy has been stopped for this session.'))
156
+ return
157
+ activate()
158
+
159
+
160
+ def activate():
161
+ registered = extension_info()
162
+ if not registered:
163
+ raise RuntimeError(_('Install Tidy, then log out and log back in.'))
164
+ expected = json.loads((DEST / 'metadata.json').read_text())['version']
165
+ if registered.get('version') != expected:
166
+ raise RuntimeError(_('New Tidy code is installed. Please log out and log back in to apply it automatically.'))
167
+ STATE.mkdir(parents=True, exist_ok=True)
168
+ handover = STATE / 'handover.json'
169
+ previous = json.loads(handover.read_text()) if handover.exists() else []
170
+ enabled = enabled_extensions()
171
+ competitors = [uuid for uuid in COMPETITORS if uuid in enabled]
172
+ handover.write_text(json.dumps(sorted(set(previous + competitors))))
173
+ try:
174
+ for uuid in competitors:
175
+ set_enabled(uuid, False)
176
+ for attempt in range(50):
177
+ if all(extension_info(uuid).get('state') != 1 for uuid in competitors):
178
+ break
179
+ time.sleep(0.1)
180
+ else:
181
+ raise RuntimeError(_('The previous tiling extension did not stop.'))
182
+ set_enabled(UUID, True)
183
+ for attempt in range(50):
184
+ info = extension_info()
185
+ if info.get('state') == 1:
186
+ break
187
+ if info.get('state') == 3:
188
+ raise RuntimeError(_('Tidy extension error: ') + info.get('error', _('Unknown error')))
189
+ time.sleep(0.1)
190
+ else:
191
+ raise RuntimeError(_('Tidy activation failed. Restoring the previous tiling configuration.\n') + json.dumps(info, ensure_ascii=False))
192
+ except Exception:
193
+ set_enabled(UUID, False)
194
+ restore_competitors()
195
+ raise
196
+ print(_('Tidy is active. Use the grid icon in the top bar → Settings and shortcuts…'))
197
+ print(_('Status: gnome-extensions info ') + UUID)
198
+ finish_update()
199
+
200
+
201
+ def apply_update():
202
+ for attempt in range(50):
203
+ if extension_info():
204
+ activate()
205
+ return
206
+ time.sleep(0.2)
207
+ raise RuntimeError(_('GNOME has not registered Tidy yet. Launch Tidy from the app list.'))
208
+
209
+
210
+ def uninstall():
211
+ if DEST.is_symlink():
212
+ raise RuntimeError(_('Remove symlink installations manually: {path}', path=DEST))
213
+ if extension_info():
214
+ set_enabled(UUID, False)
215
+ elif DEST.exists():
216
+ print(_('The extension is not registered in this session. Checking settings recovery.'))
217
+ # Also recover settings if a Shell crash prevented disable() from running.
218
+ schema_dir = DEST / 'schemas'
219
+ if schema_dir.exists():
220
+ env = dict(os.environ, GSETTINGS_SCHEMA_DIR=str(schema_dir))
221
+ subprocess.run(['gjs', '-m', str(DEST / 'scripts/recover.js')], env=env, check=True)
222
+ restore_competitors()
223
+ finish_update()
224
+ if DEST.exists():
225
+ shutil.rmtree(DEST)
226
+ (DATA / 'applications/winubun.desktop').unlink(missing_ok=True)
227
+ print(_('Tidy was removed and previous tiling settings were restored. Your custom shortcuts have been kept.'))
228
+
229
+
230
+ def main():
231
+ parser = argparse.ArgumentParser(description=__doc__)
232
+ parser.add_argument('command', choices=['build', 'install', 'activate', 'uninstall', 'prefs', 'status', 'launch', 'apply-update'])
233
+ parser.add_argument('--archive', type=Path, help=_('Install a prebuilt extension ZIP without writing to the package directory'))
234
+ args = parser.parse_args()
235
+ if args.archive is not None and args.command != 'install':
236
+ parser.error('--archive requires install')
237
+ if args.command == 'install':
238
+ install(args.archive)
239
+ elif args.command == 'apply-update':
240
+ apply_update()
241
+ elif args.command == 'launch':
242
+ activate()
243
+ open_preferences()
244
+ elif args.command == 'prefs':
245
+ open_preferences()
246
+ elif args.command == 'status':
247
+ info = extension_info()
248
+ print(json.dumps(info, ensure_ascii=False, indent=2) if info else _('The extension is not registered in the current session.'))
249
+ else:
250
+ globals()[args.command]()
251
+
252
+
253
+ if __name__ == '__main__':
254
+ try:
255
+ main()
256
+ except (subprocess.CalledProcessError, RuntimeError, OSError, zipfile.BadZipFile) as error:
257
+ message = getattr(error, 'stderr', '') or str(error)
258
+ print(message, file=sys.stderr)
259
+ if len(sys.argv) > 1 and sys.argv[1] == 'launch':
260
+ STATE.mkdir(parents=True, exist_ok=True)
261
+ (STATE / 'launcher.log').write_text(message + '\n')
262
+ subprocess.run(['notify-send', _('Tidy launch error'), message], check=False)
263
+ sys.exit(1)
@@ -0,0 +1,6 @@
1
+ import Gio from 'gi://Gio';
2
+ import {SettingsLease} from '../lib/overrides.js';
3
+
4
+ new SettingsLease(new Gio.Settings({schema_id: 'org.gnome.shell.extensions.winubun'}));
5
+ Gio.Settings.sync();
6
+ print('데스크톱 설정 복구 완료');