sqlalign 1.0.1__py3-none-any.whl

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.
sqlalign/gui.py ADDED
@@ -0,0 +1,721 @@
1
+ """`sqlalign --gui` — a settings panel next to a live preview.
2
+
3
+ Nineteen knobs is more than anyone will read about. The fastest way to learn what
4
+ one does is to change it and watch the SQL move, which is what this is for: every
5
+ control re-runs the REAL engine on the text in the pane, so what you see is what
6
+ the CLI would write.
7
+
8
+ Tkinter rather than the local web page the original spec called for. The web
9
+ version means a server, a port, a browser tab and a second language in the
10
+ repository, to draw a settings panel next to a text box. Tkinter is in the
11
+ standard library, so this costs zero new dependencies and ships with the same
12
+ `pip install`, which matters more than usual for a tool whose install story is
13
+ "one dependency".
14
+
15
+ Everything above the Tk layer is plain data and pure functions: `CONTROLS`,
16
+ `style_from`, `settings_from`, so the part that can be wrong is testable
17
+ without a display. The widget wiring underneath is deliberately thin.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import pathlib
22
+ import queue
23
+ import threading
24
+
25
+ from sqlalign.config import Width
26
+ from sqlalign.formatter import format_sql
27
+ from sqlalign.style import ALIGN_TARGETS, ALL_ALIGN_TARGETS, PRESETS, Style, preset_style
28
+
29
+ # `aliases` is the union of `column_aliases` and `table_aliases`, kept as a name
30
+ # so committed configs that use it keep working. A panel that offered all three
31
+ # would present two real choices as three checkboxes, and unchecking the parent
32
+ # would appear to do nothing: the enabled kinds are a union, so the children
33
+ # still cover it. The panel therefore offers the LEAF targets only, and expands
34
+ # a loaded `aliases` into them.
35
+ _UNION_TARGETS = {
36
+ name: frozenset(
37
+ leaf for leaf, kinds in ALIGN_TARGETS.items()
38
+ if leaf != name and kinds < ALIGN_TARGETS[name])
39
+ for name in ALIGN_TARGETS
40
+ }
41
+ PANEL_TARGETS = tuple(sorted(t for t in ALL_ALIGN_TARGETS if not _UNION_TARGETS[t]))
42
+
43
+
44
+ def _expand(targets):
45
+ """A style's targets as the leaf set the panel shows."""
46
+ out = set()
47
+ for name in targets:
48
+ out |= _UNION_TARGETS[name] or {name}
49
+ return out
50
+
51
+ # One entry per Style field, in the order the panel shows them. `kind` picks the
52
+ # widget: choice -> combobox, flag -> checkbox, number -> spinbox, targets -> a
53
+ # column of checkboxes. A test asserts this covers every field, so a new knob
54
+ # cannot quietly go missing from the panel the way it would from a hand-kept list.
55
+ #
56
+ # `needs` marks a control that only does anything when another is set a
57
+ # particular way: the select indent means nothing while the list is inline, the
58
+ # river gutter means nothing while the keywords are flush left, and no alignment
59
+ # target means anything with alignment off. Those are greyed out rather than
60
+ # left live, because a spinbox you can change that changes nothing is a lie
61
+ # about what the setting does.
62
+ CONTROLS: tuple[dict, ...] = (
63
+ {"name": "keyword_case", "kind": "choice", "choices": ("upper", "lower"),
64
+ "label": "Keyword case"},
65
+ {"name": "align", "kind": "flag", "label": "Align columns"},
66
+ {"name": "align_targets", "kind": "targets", "label": "Aligned columns",
67
+ "needs": ("align", True)},
68
+ {"name": "comma_position", "kind": "choice", "choices": ("leading", "trailing"),
69
+ "label": "Comma position"},
70
+ {"name": "boolean_operator_position", "kind": "choice",
71
+ "choices": ("leading", "trailing"), "label": "AND / OR position"},
72
+ {"name": "select_placement", "kind": "choice", "choices": ("inline", "own_line"),
73
+ "label": "SELECT list"},
74
+ {"name": "select_indent", "kind": "number", "range": (1, 12), "label": "…indent",
75
+ "needs": ("select_placement", "own_line")},
76
+ {"name": "on_placement", "kind": "choice", "choices": ("inline", "own_line"),
77
+ "label": "JOIN ON"},
78
+ {"name": "clause_keyword_align", "kind": "choice", "choices": ("left", "river"),
79
+ "label": "Clause keywords"},
80
+ {"name": "river_gutter", "kind": "number", "range": (2, 20), "label": "…river gutter",
81
+ "needs": ("clause_keyword_align", "river")},
82
+ {"name": "table_alias_style", "kind": "choice", "choices": ("bare", "as"),
83
+ "label": "Table aliases"},
84
+ {"name": "neq_style", "kind": "choice", "choices": ("!=", "<>"), "label": "Not-equal"},
85
+ {"name": "decimal_style", "kind": "choice", "choices": ("NUMERIC", "DECIMAL"),
86
+ "label": "Decimal type"},
87
+ {"name": "width", "kind": "number", "range": (0, 200), "label": "Width (0 = off)"},
88
+ {"name": "body_blank_lines", "kind": "number", "range": (0, 4), "label": "$$ body blanks"},
89
+ {"name": "blank_lines_between_statements", "kind": "number", "range": (-1, 4),
90
+ "label": "Between statements (-1 = auto)"},
91
+ {"name": "format_dollar_bodies", "kind": "flag", "label": "Format $$ bodies"},
92
+ {"name": "protect_templating", "kind": "flag", "label": "Mask Jinja / dbt"},
93
+ )
94
+
95
+ # Exercises most of the surface at once: a stacked select list with aliases, a
96
+ # multi-table FROM with a join condition, a boolean continuation, a GROUP BY and
97
+ # an ORDER BY. Changing almost any control moves something visible here, and in
98
+ # the context of the other knobs rather than in isolation.
99
+ SAMPLES = {
100
+ "postgres": (
101
+ "select cust.customer_id, cust.email, sum(ord.total) as lifetime_value\n"
102
+ "from customers cust\n"
103
+ "inner join orders ord on ord.customer_id = cust.customer_id\n"
104
+ "left join shipping_addresses addr on addr.order_id = ord.order_id\n"
105
+ "where ord.order_date >= '2026-07-01' and cust.segment = 'enterprise'\n"
106
+ "group by cust.customer_id, cust.email\n"
107
+ "order by lifetime_value desc;\n"
108
+ ),
109
+ "tsql": (
110
+ "select top 10 cust.customer_id, cust.email\n"
111
+ "from customers cust\n"
112
+ "inner join orders ord on ord.customer_id = cust.customer_id\n"
113
+ "where ord.total > 0;\n"
114
+ ),
115
+ }
116
+ SAMPLES["redshift"] = SAMPLES["postgres"]
117
+
118
+ # Above this many characters, formatting moves off the Tk thread. Measured at
119
+ # roughly 2ms a statement (~250 chars), so this is about 90ms of work: under
120
+ # the debounce, and well under the point where a freeze is perceptible.
121
+ _ASYNC_CHARS = 4000
122
+
123
+
124
+ # Shown in the preset box once the settings no longer match any preset. The
125
+ # box is a starting point, not a mode, but left showing "house" after you have
126
+ # changed three things it claims a style that is not in effect.
127
+ CUSTOM = "(custom)"
128
+
129
+
130
+ def preset_named(values: dict) -> str:
131
+ """The preset these settings ARE, or `CUSTOM`.
132
+
133
+ Compared on formatted OUTPUT rather than on Style equality: the panel offers
134
+ only the leaf align targets, so a preset built from the `aliases` union comes
135
+ back as its two children: a different frozenset that formats identically.
136
+ """
137
+ from sqlalign.formatter import format_sql
138
+
139
+ try:
140
+ mine = format_sql(SAMPLES["postgres"], "postgres", style_from(values)).text
141
+ except ValueError:
142
+ return CUSTOM
143
+ for name in sorted(PRESETS):
144
+ if format_sql(SAMPLES["postgres"], "postgres", preset_style(name)).text == mine:
145
+ return name
146
+ return CUSTOM
147
+
148
+
149
+ def default_settings() -> dict:
150
+ """The panel's starting values, read off `Style`'s own defaults."""
151
+ house = Style()
152
+ values = {}
153
+ for control in CONTROLS:
154
+ name = control["name"]
155
+ if name == "width":
156
+ values[name] = house.width.width
157
+ elif name == "align_targets":
158
+ values[name] = _expand(house.align_targets)
159
+ elif name == "blank_lines_between_statements":
160
+ # The panel has no "unset"; -1 stands for it, which is why the label
161
+ # says so. A spinbox that could be blank would be worse.
162
+ values[name] = -1 if house.blank_lines_between_statements is None else \
163
+ house.blank_lines_between_statements
164
+ else:
165
+ values[name] = getattr(house, name)
166
+ return values
167
+
168
+
169
+ def settings_from(style: Style) -> dict:
170
+ """Panel values for an existing `Style` — used when a preset is picked or a
171
+ config file is loaded, so the controls show what is actually in effect."""
172
+ values = default_settings()
173
+ for control in CONTROLS:
174
+ name = control["name"]
175
+ if name == "width":
176
+ values[name] = style.width.width
177
+ elif name == "align_targets":
178
+ values[name] = _expand(style.align_targets)
179
+ elif name == "blank_lines_between_statements":
180
+ values[name] = -1 if style.blank_lines_between_statements is None else \
181
+ style.blank_lines_between_statements
182
+ else:
183
+ values[name] = getattr(style, name)
184
+ return values
185
+
186
+
187
+ def style_from(values: dict) -> Style:
188
+ """A `Style` from panel values. Raises ValueError on an invalid combination,
189
+ which the panel reports rather than swallowing."""
190
+ kwargs = {}
191
+ for control in CONTROLS:
192
+ name = control["name"]
193
+ value = values[name]
194
+ if name == "width":
195
+ kwargs["width"] = Width(width=int(value))
196
+ elif name == "align_targets":
197
+ kwargs["align_targets"] = frozenset(value)
198
+ elif name == "blank_lines_between_statements":
199
+ kwargs[name] = None if int(value) < 0 else int(value)
200
+ elif control["kind"] == "number":
201
+ kwargs[name] = int(value)
202
+ else:
203
+ kwargs[name] = value
204
+ return Style(**kwargs)
205
+
206
+
207
+ def preview(sql: str, values: dict, dialect: str) -> tuple[str, str]:
208
+ """`(formatted, status)` for the preview pane.
209
+
210
+ Never raises: an invalid setting or an engine failure becomes a status line,
211
+ because a GUI that disappears when a spinbox is mid-edit is unusable.
212
+ """
213
+ try:
214
+ style = style_from(values)
215
+ except ValueError as e:
216
+ return "", f"invalid setting — {e}"
217
+ try:
218
+ result = format_sql(sql, dialect, style)
219
+ except Exception as e: # pragma: no cover - defence only
220
+ return "", f"{type(e).__name__}: {e}"
221
+ declined = len(result.declines)
222
+ plural = "" if result.statements == 1 else "s"
223
+ status = (f"{result.statements} statement{plural}, "
224
+ f"{result.statements - declined} formatted")
225
+ if declined:
226
+ causes = ", ".join(sorted({d.reason for d in result.declines}))
227
+ status += f" — {declined} declined ({causes})"
228
+ return result.text, status
229
+
230
+
231
+ def as_toml(values: dict) -> str:
232
+ """The panel's settings as a `.sqlalign.toml` — the same text
233
+ `--show-config` prints, so what the GUI saves is what the CLI reads."""
234
+ from sqlalign.configfile import describe
235
+ return describe(style_from(values)) + "\n"
236
+
237
+
238
+ def run(dialect: str = "postgres") -> int: # pragma: no cover - needs a display
239
+ """Open the window. Returns a process exit code."""
240
+ try:
241
+ import tkinter as tk
242
+ except ImportError:
243
+ print("sqlalign: --gui needs tkinter, which is missing from this Python.\n"
244
+ " On Debian/Ubuntu: apt install python3-tk\n"
245
+ " On macOS with pyenv: install a Python built against Tcl/Tk.")
246
+ return 2
247
+
248
+ root = tk.Tk()
249
+ build(root, dialect)
250
+ root.mainloop()
251
+ return 0
252
+
253
+
254
+ def build(root, dialect: str = "postgres") -> dict:
255
+ """Populate `root` with the whole interface, and return its parts.
256
+
257
+ Separate from `run` so a test can construct the real widget tree and check it
258
+ without entering the event loop, which is the only part of this file a test
259
+ genuinely cannot drive.
260
+ """
261
+ import tkinter as tk
262
+ from tkinter import filedialog, messagebox, ttk
263
+
264
+ root.title("sqlalign")
265
+ root.geometry("1180x760")
266
+
267
+ values = default_settings()
268
+ state = {"dialect": dialect, "job": None, "seq": 0, "pump": None, "quiet": False,
269
+ "path": None,
270
+ "done": queue.Queue(), "want": queue.Queue()}
271
+
272
+ def close():
273
+ if state["pump"] is not None:
274
+ root.after_cancel(state["pump"])
275
+ root.destroy()
276
+ # Nothing to shut down: the worker is a daemon, so a format still in
277
+ # flight cannot hold the process open. A ThreadPoolExecutor could and
278
+ # did: `shutdown(wait=False)` does not cancel RUNNING work, and the
279
+ # interpreter joins the pool's threads at exit regardless, so closing
280
+ # the window part-way through a large file left the app alive, with no
281
+ # window, for as long as the format took.
282
+
283
+ root.protocol("WM_DELETE_WINDOW", close)
284
+
285
+ outer = ttk.Frame(root, padding=8)
286
+ outer.pack(fill="both", expand=True)
287
+
288
+ # The settings column scrolls. Eighteen controls plus the target checkboxes
289
+ # need ~900px, which is taller than the window on any laptop: without this
290
+ # without it the last few controls are unreachable.
291
+ side = ttk.Frame(outer)
292
+ side.pack(side="left", fill="y", padx=(0, 8))
293
+ # The actions pin to the bottom of the column, OUTSIDE the scrolling area.
294
+ # They were inside it, which put every button below the fold at any normal
295
+ # window height: the primary actions were the hardest things to reach.
296
+ action_bar = ttk.Frame(side)
297
+ action_bar.pack(side="bottom", fill="x", pady=(8, 0))
298
+ tray = tk.Canvas(side, highlightthickness=0, borderwidth=0)
299
+ rail = ttk.Scrollbar(side, orient="vertical", command=tray.yview)
300
+ tray.configure(yscrollcommand=rail.set)
301
+ rail.pack(side="right", fill="y")
302
+ tray.pack(side="left", fill="both", expand=True)
303
+ panel = ttk.Frame(tray)
304
+ slot = tray.create_window((0, 0), window=panel, anchor="nw")
305
+
306
+ def _fit(_=None):
307
+ tray.configure(scrollregion=tray.bbox("all"), width=panel.winfo_reqwidth())
308
+
309
+ panel.bind("<Configure>", _fit)
310
+ tray.bind("<Configure>", lambda e: tray.itemconfigure(slot, width=e.width))
311
+
312
+ def _wheel(event):
313
+ # Tk reports wheel deltas differently per platform; normalise to lines.
314
+ step = -1 if event.delta > 0 else 1
315
+ if event.num == 4:
316
+ step = -1
317
+ elif event.num == 5:
318
+ step = 1
319
+ tray.yview_scroll(step, "units")
320
+
321
+ for sequence in ("<MouseWheel>", "<Button-4>", "<Button-5>"):
322
+ tray.bind_all(sequence, _wheel, add="+")
323
+
324
+ panes = ttk.Frame(outer)
325
+ panes.pack(side="left", fill="both", expand=True)
326
+
327
+ # ---- panes -----------------------------------------------------------
328
+ split = ttk.PanedWindow(panes, orient="vertical")
329
+ split.pack(fill="both", expand=True)
330
+ mono = ("Menlo", 12) if root.tk.call("tk", "windowingsystem") == "aqua" else ("TkFixedFont", 10)
331
+
332
+ def scrolled(parent, **options):
333
+ """A Text with both scrollbars. `wrap="none"` keeps the columns intact,
334
+ which makes a horizontal scrollbar mandatory rather than optional: a
335
+ long line is otherwise just cut off with no way to reach the rest."""
336
+ holder = ttk.Frame(parent)
337
+ # Matched chrome on both panes. Left to Tk's defaults the editable one
338
+ # draws a heavy focus border and the read-only one draws none, so two
339
+ # widgets that should read as siblings looked like different kinds of
340
+ # thing.
341
+ text = tk.Text(holder, wrap="none", font=mono, relief="solid",
342
+ borderwidth=1, highlightthickness=0, **options)
343
+ down = ttk.Scrollbar(holder, orient="vertical", command=text.yview)
344
+ across = ttk.Scrollbar(holder, orient="horizontal", command=text.xview)
345
+ text.configure(yscrollcommand=down.set, xscrollcommand=across.set)
346
+ text.grid(row=0, column=0, sticky="nsew")
347
+ down.grid(row=0, column=1, sticky="ns")
348
+ across.grid(row=1, column=0, sticky="ew")
349
+ holder.rowconfigure(0, weight=1)
350
+ holder.columnconfigure(0, weight=1)
351
+ return holder, text
352
+
353
+ in_frame = ttk.Labelframe(split, text="Input", padding=4)
354
+ holder, source = scrolled(in_frame, undo=True, height=12)
355
+ holder.pack(fill="both", expand=True)
356
+ split.add(in_frame, weight=1)
357
+
358
+ # The read-only pane takes the THEME's window background rather than a
359
+ # literal colour. A hardcoded light grey pairs with `systemTextColor`, which
360
+ # is dynamic, so in dark mode it was light text on a light background.
361
+ # Window-background against default text is the pairing every ttk.Label
362
+ # already uses, so it is legible in both by construction.
363
+ read_only_bg = ttk.Style().lookup("TFrame", "background") or None
364
+ out_frame = ttk.Labelframe(split, text="Formatted", padding=4)
365
+ holder, output = scrolled(out_frame, height=16, state="disabled",
366
+ **({"background": read_only_bg} if read_only_bg else {}))
367
+ holder.pack(fill="both", expand=True)
368
+ split.add(out_frame, weight=1)
369
+
370
+ status = ttk.Label(panes, text="", anchor="w")
371
+ status.pack(fill="x", pady=(6, 0))
372
+
373
+ def show(text, note):
374
+ output.configure(state="normal")
375
+ output.delete("1.0", "end")
376
+ output.insert("1.0", text)
377
+ output.configure(state="disabled")
378
+ status.configure(text=note)
379
+
380
+ def render(*_):
381
+ """Reformat and show the result.
382
+
383
+ Formatting is linear in file size: about 2ms a statement, so ~380ms for
384
+ 1400 lines and near a second for 3500. On the Tk thread that is a visible
385
+ freeze every time typing pauses, in exactly the case "Open SQL…" invites.
386
+ Above `_ASYNC_CHARS` it moves to a worker; below it the round trip would
387
+ cost more than the work, and staying synchronous keeps small edits (and
388
+ the tests) immediate.
389
+
390
+ `format_sql` is safe to call off-thread: it carries style on a contextvar,
391
+ which is per-thread, verified under concurrent mixed-style runs.
392
+ """
393
+ sql, dialect = source.get("1.0", "end-1c"), state["dialect"]
394
+ if len(sql) < _ASYNC_CHARS:
395
+ show(*preview(sql, values, dialect))
396
+ return
397
+
398
+ state["seq"] += 1
399
+ seq = state["seq"]
400
+ snapshot = dict(values)
401
+ status.configure(text="formatting…")
402
+
403
+ state["want"].put((seq, sql, snapshot, dialect))
404
+
405
+ def schedule(*_):
406
+ """Coalesce keystrokes: reformatting on every character makes typing
407
+ feel heavy on a large paste."""
408
+ if state["job"] is not None:
409
+ root.after_cancel(state["job"])
410
+ state["job"] = root.after(150, render)
411
+
412
+ source.bind("<KeyRelease>", schedule)
413
+
414
+ def worker():
415
+ """One long-lived daemon thread, formatting the most recent request.
416
+
417
+ Results go back through a queue, NOT through `root.after`: Tk methods
418
+ must not be called from another thread at all, `after` included, and
419
+ doing so silently never dispatches: the preview simply stopped updating
420
+ for any file past the threshold, which is worse than the freeze it
421
+ replaced.
422
+
423
+ Requests overtaken while it was busy are dropped rather than formatted
424
+ and thrown away, so typing does not queue one format per keystroke
425
+ burst.
426
+ """
427
+ while True:
428
+ seq, sql, snapshot, dialect = state["want"].get()
429
+ if seq == state["seq"]:
430
+ state["done"].put((seq, preview(sql, snapshot, dialect)))
431
+
432
+ threading.Thread(target=worker, name="sqlalign-fmt", daemon=True).start()
433
+
434
+ def pump():
435
+ """Drain finished background formats, on the Tk thread where it is safe
436
+ to touch widgets. Results older than the latest request are dropped --
437
+ they describe text the user has already typed past."""
438
+ try:
439
+ while True:
440
+ job, result = state["done"].get_nowait()
441
+ if job == state["seq"]:
442
+ show(*result)
443
+ except queue.Empty:
444
+ pass
445
+ state["pump"] = root.after(60, pump)
446
+
447
+ pump()
448
+
449
+ # ---- controls --------------------------------------------------------
450
+ def row(parent, label):
451
+ line = ttk.Frame(parent)
452
+ line.pack(fill="x", pady=1)
453
+ ttk.Label(line, text=label, width=22, anchor="w").pack(side="left")
454
+ return line
455
+
456
+ top = ttk.Labelframe(panel, text="Start from", padding=6)
457
+ top.pack(fill="x")
458
+
459
+ dialect_var = tk.StringVar(value=dialect)
460
+
461
+ def on_dialect(*_):
462
+ state["dialect"] = dialect_var.get()
463
+ current = source.get("1.0", "end-1c").strip()
464
+ if current in {s.strip() for s in SAMPLES.values()}:
465
+ source.delete("1.0", "end")
466
+ source.insert("1.0", SAMPLES[state["dialect"]])
467
+ render()
468
+
469
+ line = row(top, "Dialect")
470
+ box = ttk.Combobox(line, textvariable=dialect_var, values=["postgres", "redshift", "tsql"],
471
+ state="readonly", width=12)
472
+ box.pack(side="left", fill="x", expand=True)
473
+ dialect_var.trace_add("write", on_dialect)
474
+
475
+ widgets: dict = {}
476
+ boxes: dict = {} # name -> the actual widgets, for enabling/disabling
477
+
478
+ def refresh_enabled():
479
+ """Grey out every control whose `needs` is not currently satisfied."""
480
+ for control in CONTROLS:
481
+ need = control.get("needs")
482
+ if need is None:
483
+ continue
484
+ depends_on, wanted = need
485
+ state = "normal" if values[depends_on] == wanted else "disabled"
486
+ for widget in boxes.get(control["name"], ()):
487
+ widget.configure(state=state if state == "normal"
488
+ or control["kind"] != "choice" else "disabled")
489
+
490
+ def refresh_widgets():
491
+ """Push `values` back into the controls, after a preset or a file load."""
492
+ for control in CONTROLS:
493
+ name = control["name"]
494
+ if control["kind"] == "targets":
495
+ for target, var in widgets[name].items():
496
+ var.set(target in values[name])
497
+ else:
498
+ widgets[name].set(values[name])
499
+ refresh_enabled()
500
+
501
+ preset_var = tk.StringVar(value="house")
502
+
503
+ def on_preset(*_):
504
+ if state["quiet"] or preset_var.get() == CUSTOM:
505
+ return
506
+ values.update(settings_from(preset_style(preset_var.get())))
507
+ refresh_widgets()
508
+ render()
509
+
510
+ line = row(top, "Preset")
511
+ ttk.Combobox(line, textvariable=preset_var, values=[*sorted(PRESETS), CUSTOM],
512
+ state="readonly", width=12).pack(side="left", fill="x", expand=True)
513
+ preset_var.trace_add("write", on_preset)
514
+
515
+ settings = ttk.Labelframe(panel, text="Settings", padding=6)
516
+ settings.pack(fill="both", expand=True, pady=(8, 0))
517
+
518
+ def resync_preset():
519
+ """Keep the preset box honest as individual settings are changed."""
520
+ name = preset_named(values)
521
+ if preset_var.get() != name:
522
+ state["quiet"] = True # not a user pick; do not re-apply it
523
+ preset_var.set(name)
524
+ state["quiet"] = False
525
+
526
+ def bind(name, var):
527
+ def changed(*_):
528
+ values[name] = var.get()
529
+ refresh_enabled()
530
+ resync_preset()
531
+ render()
532
+ var.trace_add("write", changed)
533
+
534
+ for control in CONTROLS:
535
+ name, kind = control["name"], control["kind"]
536
+ if kind == "flag":
537
+ var = tk.BooleanVar(value=values[name])
538
+ box = ttk.Checkbutton(settings, text=control["label"], variable=var)
539
+ box.pack(anchor="w", pady=1)
540
+ boxes[name] = [box]
541
+ bind(name, var)
542
+ elif kind == "choice":
543
+ var = tk.StringVar(value=values[name])
544
+ line = row(settings, control["label"])
545
+ box = ttk.Combobox(line, textvariable=var, values=list(control["choices"]),
546
+ state="readonly", width=12)
547
+ box.pack(side="left", fill="x", expand=True)
548
+ boxes[name] = [box]
549
+ bind(name, var)
550
+ elif kind == "number":
551
+ var = tk.IntVar(value=values[name])
552
+ line = row(settings, control["label"])
553
+ low, high = control["range"]
554
+ box = ttk.Spinbox(line, from_=low, to=high, textvariable=var, width=10)
555
+ box.pack(side="left", fill="x", expand=True)
556
+ boxes[name] = [box]
557
+ bind(name, var)
558
+ elif kind == "targets":
559
+ heading = ttk.Label(settings, text=control["label"])
560
+ heading.pack(anchor="w", pady=(6, 0))
561
+ group: dict = {}
562
+ boxes[name] = []
563
+ for target in PANEL_TARGETS:
564
+ var = tk.BooleanVar(value=target in values[name])
565
+ box = ttk.Checkbutton(settings, text=f" {target}", variable=var)
566
+ box.pack(anchor="w")
567
+ boxes[name].append(box)
568
+
569
+ # `key` is bound here, not read from the enclosing loop: the
570
+ # callback fires long after the loop has moved on.
571
+ def changed(*_, key=name, t=target, v=var):
572
+ values[key] = set(values[key]) | {t} if v.get() else \
573
+ set(values[key]) - {t}
574
+ render()
575
+ var.trace_add("write", changed)
576
+ group[target] = var
577
+ widgets[name] = group
578
+ continue
579
+ widgets[name] = var
580
+
581
+ # ---- actions ---------------------------------------------------------
582
+ def report(action, error):
583
+ """Every file action goes through here. Without it an unreadable file, an
584
+ unwritable path or a non-UTF-8 SQL dump raised into Tk's handler: a
585
+ traceback on stderr that nobody sees, and a window that appears to ignore
586
+ the click entirely."""
587
+ messagebox.showerror("sqlalign", f"Could not {action}.\n\n{error}")
588
+
589
+ def read_text(path):
590
+ """SQL dumps are not always UTF-8 — latin-1 is common in older exports,
591
+ and failing on one byte is not a reason to refuse the file. Decode
592
+ strictly first so a genuinely UTF-8 file is never mangled, and fall back
593
+ only when it is not one."""
594
+ raw = pathlib.Path(path).read_bytes()
595
+ try:
596
+ return raw.decode("utf-8")
597
+ except UnicodeDecodeError:
598
+ return raw.decode("latin-1")
599
+
600
+ def retitle():
601
+ """macOS convention: the window is named for the document it holds.
602
+
603
+ Without this the title read `sqlalign` forever, so a window that had a
604
+ file open looked exactly like one holding the built-in sample, and the
605
+ only way to tell which file you were formatting was to recognise its
606
+ contents.
607
+ """
608
+ root.title(f"sqlalign — {pathlib.Path(state['path']).name}"
609
+ if state["path"] else "sqlalign")
610
+
611
+ def open_file():
612
+ path = filedialog.askopenfilename(filetypes=[("SQL", "*.sql"), ("All", "*.*")])
613
+ if not path:
614
+ return
615
+ try:
616
+ text = read_text(path)
617
+ except OSError as e:
618
+ report("open that file", e)
619
+ return
620
+ source.delete("1.0", "end")
621
+ source.insert("1.0", text)
622
+ # A fresh document, so the previous file's undo history is not this
623
+ # file's: one Cmd+Z should not resurrect the last file's text.
624
+ source.edit_reset()
625
+ state["path"] = path
626
+ retitle()
627
+ render()
628
+
629
+ def save_output():
630
+ # Defaulted to the file that was opened, because formatting a file in
631
+ # place is what the CLI does and what the button is nearly always for.
632
+ # Defaulted, not silent: the dialog still asks before overwriting.
633
+ here = pathlib.Path(state["path"]) if state["path"] else None
634
+ path = filedialog.asksaveasfilename(
635
+ defaultextension=".sql", filetypes=[("SQL", "*.sql")],
636
+ **({"initialdir": str(here.parent), "initialfile": here.name} if here else {}))
637
+ if not path:
638
+ return
639
+ try:
640
+ pathlib.Path(path).write_text(output.get("1.0", "end-1c"))
641
+ except OSError as e:
642
+ report("save there", e)
643
+ return
644
+ state["path"] = path
645
+ retitle()
646
+
647
+ def save_config():
648
+ path = filedialog.asksaveasfilename(initialfile=".sqlalign.toml")
649
+ if not path:
650
+ return
651
+ try:
652
+ pathlib.Path(path).write_text(as_toml(values))
653
+ except OSError as e:
654
+ report("save there", e)
655
+
656
+ def load_config():
657
+ from sqlalign import configfile
658
+ path = filedialog.askopenfilename(filetypes=[("TOML", "*.toml"), ("All", "*.*")])
659
+ if not path:
660
+ return
661
+ try:
662
+ settings_data, _ = configfile.load_settings(path)
663
+ values.update(settings_from(configfile.build_style(settings_data)))
664
+ except Exception as e:
665
+ report("load that config", e)
666
+ return
667
+ refresh_widgets()
668
+ resync_preset()
669
+ render()
670
+
671
+ def copy_output():
672
+ root.clipboard_clear()
673
+ root.clipboard_append(output.get("1.0", "end-1c"))
674
+
675
+ # The output pane is read-only, so selecting it by hand to copy is the one
676
+ # thing every user will want to do and the one thing the widget makes least
677
+ # obvious. Give it a button AND a shortcut.
678
+ aqua = root.tk.call("tk", "windowingsystem") == "aqua"
679
+ mod, shown = ("Command", "⌘") if aqua else ("Control", "Ctrl+")
680
+
681
+ # Copy-formatted is SHIFT-modified deliberately. Binding plain Cmd/Ctrl+C
682
+ # globally stomps ordinary copy: select a word in the input pane, press it,
683
+ # and you get the whole formatted output instead of your selection.
684
+ actions = action_bar
685
+ bound: dict = {}
686
+ for label, key, command in (
687
+ (f"Copy formatted {shown}⇧C" if aqua else f"Copy formatted {shown}Shift+C",
688
+ "Shift-C", copy_output),
689
+ (f"Open SQL… {shown}O", "o", open_file),
690
+ (f"Save formatted… {shown}S", "s", save_output),
691
+ ("Load config…", None, load_config),
692
+ ("Save config…", None, save_config),
693
+ ):
694
+ ttk.Button(actions, text=label, command=command).pack(fill="x", pady=1)
695
+ if key:
696
+ # bind_all so the shortcut works wherever focus happens to be. Note
697
+ # "all" is the LAST bindtag, so a binding here runs AFTER the Text
698
+ # class binding, which is exactly why plain Cmd/Ctrl+C would have
699
+ # overwritten an ordinary copy rather than being shadowed by it.
700
+ sequence = f"<{mod}-{key}>"
701
+ root.bind_all(sequence, lambda _e, fn=command: (fn(), "break")[1])
702
+ bound[sequence] = command
703
+
704
+ # Below this the panes stop being usable: the settings column alone needs
705
+ # ~360px, and a preview narrower than the sample is not a preview.
706
+ root.update_idletasks()
707
+ root.minsize(side.winfo_reqwidth() + 520, 420)
708
+
709
+ refresh_enabled()
710
+ source.insert("1.0", SAMPLES[dialect])
711
+ render()
712
+ # Type immediately rather than having to click the pane first.
713
+ source.focus_set()
714
+ return {"source": source, "output": output, "status": status, "values": values,
715
+ "widgets": widgets, "render": render, "panel": panel, "preset": preset_var,
716
+ "tray": tray,
717
+ "state": state, "retitle": retitle,
718
+ "actions": {"copy": copy_output, "open": open_file, "save": save_output,
719
+ "load_config": load_config, "save_config": save_config,
720
+ "read_text": read_text},
721
+ "accelerators": bound}