|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Launchpad: create category folders from third-party apps. |
| 3 | +Called by macrift/customize/launchpad.sh — not standalone.""" |
| 4 | + |
| 5 | +import subprocess |
| 6 | +import sqlite3 |
| 7 | +import os |
| 8 | +import uuid |
| 9 | +import sys |
| 10 | +from collections import Counter, defaultdict |
| 11 | + |
| 12 | +CATEGORY_OVERRIDES = { |
| 13 | + "dev.zed.Zed": "Developer Tools", |
| 14 | + "com.rogueamoeba.soundsource": "Utilities", |
| 15 | + "com.crystalidea.macsfancontrol": "Utilities", |
| 16 | + "com.image-line.fl-cloud-plugins": "Music", |
| 17 | + "com.image-line.flstudio": "Music", |
| 18 | + "com.anthropic.claude-code-url-handler": "Developer Tools", |
| 19 | + "com.logi.pluginservice": "Utilities", |
| 20 | +} |
| 21 | + |
| 22 | +MIN_CATEGORY_SIZE = 2 |
| 23 | + |
| 24 | +TRIGGERS_SQL = """ |
| 25 | +CREATE TRIGGER update_items_order BEFORE UPDATE OF ordering ON items WHEN new.ordering > old.ordering AND 0 == (SELECT value FROM dbinfo WHERE key='ignore_items_update_triggers') |
| 26 | +BEGIN |
| 27 | + UPDATE dbinfo SET value=1 WHERE key='ignore_items_update_triggers'; |
| 28 | + UPDATE items SET ordering = ordering - 1 WHERE parent_id = old.parent_id AND ordering BETWEEN old.ordering and new.ordering; |
| 29 | + UPDATE dbinfo SET value=0 WHERE key='ignore_items_update_triggers'; |
| 30 | +END; |
| 31 | +CREATE TRIGGER update_items_order_backwards BEFORE UPDATE OF ordering ON items WHEN new.ordering < old.ordering AND 0 == (SELECT value FROM dbinfo WHERE key='ignore_items_update_triggers') |
| 32 | +BEGIN |
| 33 | + UPDATE dbinfo SET value=1 WHERE key='ignore_items_update_triggers'; |
| 34 | + UPDATE items SET ordering = ordering + 1 WHERE parent_id = old.parent_id AND ordering BETWEEN new.ordering and old.ordering; |
| 35 | + UPDATE dbinfo SET value=0 WHERE key='ignore_items_update_triggers'; |
| 36 | +END; |
| 37 | +CREATE TRIGGER update_item_parent AFTER UPDATE OF parent_id ON items WHEN 0 == (SELECT value FROM dbinfo WHERE key='ignore_items_update_triggers') |
| 38 | +BEGIN |
| 39 | + UPDATE dbinfo SET value=1 WHERE key='ignore_items_update_triggers'; |
| 40 | + UPDATE items SET ordering = (SELECT ifnull(MAX(ordering),0)+1 FROM items WHERE parent_id=new.parent_id AND ROWID!=old.rowid) WHERE ROWID=old.rowid; |
| 41 | + UPDATE items SET ordering = ordering - 1 WHERE parent_id = old.parent_id and ordering > old.ordering; |
| 42 | + UPDATE dbinfo SET value=0 WHERE key='ignore_items_update_triggers'; |
| 43 | +END; |
| 44 | +CREATE TRIGGER insert_item AFTER INSERT on items WHEN 0 == (SELECT value FROM dbinfo WHERE key='ignore_items_update_triggers') |
| 45 | +BEGIN |
| 46 | + UPDATE dbinfo SET value=1 WHERE key='ignore_items_update_triggers'; |
| 47 | + UPDATE items SET ordering = (SELECT ifnull(MAX(ordering),0)+1 FROM items WHERE parent_id=new.parent_id) WHERE ROWID=new.rowid; |
| 48 | + UPDATE dbinfo SET value=0 WHERE key='ignore_items_update_triggers'; |
| 49 | +END; |
| 50 | +CREATE TRIGGER app_inserted AFTER INSERT ON items WHEN new.type = 4 OR new.type = 5 |
| 51 | +BEGIN |
| 52 | + INSERT INTO image_cache VALUES (new.rowid,0,0,NULL,NULL); |
| 53 | +END; |
| 54 | +CREATE TRIGGER app_deleted AFTER DELETE ON items WHEN old.type = 4 OR old.type = 5 |
| 55 | +BEGIN |
| 56 | + DELETE FROM image_cache WHERE item_id=old.rowid; |
| 57 | +END; |
| 58 | +CREATE TRIGGER item_deleted AFTER DELETE ON items |
| 59 | +BEGIN |
| 60 | + DELETE FROM apps WHERE rowid=old.rowid; |
| 61 | + DELETE FROM groups WHERE item_id=old.rowid; |
| 62 | + DELETE FROM downloading_apps WHERE item_id=old.rowid; |
| 63 | + UPDATE dbinfo SET value=1 WHERE key='ignore_items_update_triggers'; |
| 64 | + UPDATE items SET ordering = ordering - 1 WHERE old.parent_id = parent_id AND ordering > old.ordering; |
| 65 | + UPDATE dbinfo SET value=0 WHERE key='ignore_items_update_triggers'; |
| 66 | +END; |
| 67 | +""" |
| 68 | + |
| 69 | +def run(cmd): |
| 70 | + return subprocess.run(cmd, shell=True, capture_output=True, text=True).stdout.strip() |
| 71 | + |
| 72 | +def build_category_map(): |
| 73 | + result = {} |
| 74 | + for entry in os.scandir("/Applications"): |
| 75 | + if entry.name.endswith(".app") and entry.is_dir(follow_symlinks=True): |
| 76 | + bid = run(f'mdls -name kMDItemCFBundleIdentifier -raw "{entry.path}"') |
| 77 | + if not bid or bid == "(null)": |
| 78 | + continue |
| 79 | + if bid in CATEGORY_OVERRIDES: |
| 80 | + result[bid] = CATEGORY_OVERRIDES[bid] |
| 81 | + else: |
| 82 | + cat = run(f'mdls -name kMDItemAppStoreCategory -raw "{entry.path}"') |
| 83 | + if cat and cat != "(null)": |
| 84 | + result[bid] = cat |
| 85 | + return result |
| 86 | + |
| 87 | +def main(): |
| 88 | + mode = sys.argv[1] if len(sys.argv) > 1 else "apply" |
| 89 | + darwin_dir = run("getconf DARWIN_USER_DIR") |
| 90 | + lp_db = os.path.join(darwin_dir, "com.apple.dock.launchpad", "db", "db") |
| 91 | + |
| 92 | + if not os.path.exists(lp_db): |
| 93 | + print("ERROR: DB not found", file=sys.stderr) |
| 94 | + sys.exit(1) |
| 95 | + |
| 96 | + conn = sqlite3.connect(lp_db) |
| 97 | + conn.execute("PRAGMA busy_timeout = 5000") |
| 98 | + cur = conn.cursor() |
| 99 | + |
| 100 | + cat_map = build_category_map() |
| 101 | + |
| 102 | + # Find pages to modify (skip Apple-only) |
| 103 | + cur.execute(""" |
| 104 | + SELECT rowid FROM items |
| 105 | + WHERE type=3 AND parent_id=1 AND uuid NOT LIKE 'HOLDING%' |
| 106 | + ORDER BY ordering |
| 107 | + """) |
| 108 | + all_pages = [r[0] for r in cur.fetchall()] |
| 109 | + |
| 110 | + sort_pages = [] |
| 111 | + for pid in all_pages: |
| 112 | + cur.execute("SELECT COUNT(*) FROM apps a JOIN items i ON a.item_id=i.rowid WHERE i.parent_id=? AND a.bundleid NOT LIKE 'com.apple.%'", (pid,)) |
| 113 | + non_apple = cur.fetchone()[0] |
| 114 | + cur.execute("SELECT COUNT(*) FROM items WHERE type=4 AND parent_id=?", (pid,)) |
| 115 | + total = cur.fetchone()[0] |
| 116 | + if total > 0 and non_apple == 0: |
| 117 | + continue |
| 118 | + sort_pages.append(pid) |
| 119 | + |
| 120 | + # Collect apps |
| 121 | + apps = [] |
| 122 | + for pid in sort_pages: |
| 123 | + cur.execute("SELECT a.item_id, a.bundleid, a.title FROM apps a JOIN items i ON a.item_id=i.rowid WHERE i.parent_id=?", (pid,)) |
| 124 | + apps.extend(cur.fetchall()) |
| 125 | + |
| 126 | + # Assign categories, merge small |
| 127 | + app_data = [(iid, t, cat_map.get(bid, "Other")) for iid, bid, t in apps] |
| 128 | + cat_counts = Counter(c for _, _, c in app_data) |
| 129 | + small = {c for c, n in cat_counts.items() if n < MIN_CATEGORY_SIZE and c != "Other"} |
| 130 | + app_data = [(iid, t, "Other" if c in small else c) for iid, t, c in app_data] |
| 131 | + |
| 132 | + # Group |
| 133 | + groups = defaultdict(list) |
| 134 | + for iid, t, c in app_data: |
| 135 | + groups[c].append((iid, t)) |
| 136 | + for c in groups: |
| 137 | + groups[c].sort(key=lambda x: (x[1] or "").lower()) |
| 138 | + |
| 139 | + # Preview mode — just print and exit |
| 140 | + if mode == "preview": |
| 141 | + for c in sorted(groups): |
| 142 | + print(f"{c}|{len(groups[c])}") |
| 143 | + conn.close() |
| 144 | + sys.exit(0) |
| 145 | + |
| 146 | + # Apply |
| 147 | + if not sort_pages: |
| 148 | + print("ERROR: No pages with third-party apps", file=sys.stderr) |
| 149 | + conn.close() |
| 150 | + sys.exit(1) |
| 151 | + |
| 152 | + target_page = sort_pages[0] |
| 153 | + |
| 154 | + # Drop triggers (executescript auto-commits — safe, no data changes yet) |
| 155 | + drop_sql = "\n".join(f"DROP TRIGGER IF EXISTS {t};" for t in [ |
| 156 | + "update_items_order", "update_items_order_backwards", "update_item_parent", |
| 157 | + "insert_item", "app_inserted", "app_deleted", "item_deleted"]) |
| 158 | + cur.executescript(drop_sql) |
| 159 | + |
| 160 | + # Data mutations in a single transaction |
| 161 | + cur.execute("BEGIN IMMEDIATE") |
| 162 | + |
| 163 | + # Delete extra pages (+ manual groups cleanup since triggers are dropped) |
| 164 | + for pid in sort_pages[1:]: |
| 165 | + cur.execute("DELETE FROM groups WHERE item_id=?", (pid,)) |
| 166 | + cur.execute("DELETE FROM items WHERE rowid=?", (pid,)) |
| 167 | + |
| 168 | + # Next rowid |
| 169 | + cur.execute("SELECT MAX(rowid) FROM items") |
| 170 | + next_id = cur.fetchone()[0] + 1 |
| 171 | + |
| 172 | + # Create folders |
| 173 | + for folder_order, cat in enumerate(sorted(groups)): |
| 174 | + folder_id = next_id |
| 175 | + next_id += 1 |
| 176 | + inner_page_id = next_id |
| 177 | + next_id += 1 |
| 178 | + |
| 179 | + cur.execute("INSERT INTO items (rowid,uuid,flags,type,parent_id,ordering) VALUES (?,?,1,2,?,?)", |
| 180 | + (folder_id, str(uuid.uuid4()).upper(), target_page, folder_order)) |
| 181 | + cur.execute("INSERT INTO groups (item_id,category_id,title) VALUES (?,NULL,?)", (folder_id, cat)) |
| 182 | + |
| 183 | + cur.execute("INSERT INTO items (rowid,uuid,flags,type,parent_id,ordering) VALUES (?,?,0,3,?,0)", |
| 184 | + (inner_page_id, str(uuid.uuid4()).upper(), folder_id)) |
| 185 | + cur.execute("INSERT INTO groups (item_id,category_id,title) VALUES (?,NULL,'')", (inner_page_id,)) |
| 186 | + |
| 187 | + for app_order, (iid, _) in enumerate(groups[cat]): |
| 188 | + cur.execute("UPDATE items SET parent_id=?,ordering=? WHERE rowid=?", (inner_page_id, app_order, iid)) |
| 189 | + |
| 190 | + cur.execute("COMMIT") |
| 191 | + |
| 192 | + # Restore triggers (executescript auto-commits — safe, data already committed) |
| 193 | + cur.executescript(TRIGGERS_SQL) |
| 194 | + |
| 195 | + conn.close() |
| 196 | + |
| 197 | + run("killall Dock") |
| 198 | + print(f"OK|{len(groups)}") |
| 199 | + |
| 200 | +if __name__ == "__main__": |
| 201 | + main() |
0 commit comments