clutterxp 1.1.0__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.
Files changed (84) hide show
  1. clutterxp/__init__.py +4 -0
  2. clutterxp/cli/__init__.py +7 -0
  3. clutterxp/cli/app.py +251 -0
  4. clutterxp/cli/cmd_config.py +250 -0
  5. clutterxp/cli/cmd_doctor.py +449 -0
  6. clutterxp/cli/cmd_duplicates.py +253 -0
  7. clutterxp/cli/cmd_gui.py +22 -0
  8. clutterxp/cli/cmd_history.py +233 -0
  9. clutterxp/cli/cmd_init.py +76 -0
  10. clutterxp/cli/cmd_organize.py +226 -0
  11. clutterxp/cli/cmd_rules.py +540 -0
  12. clutterxp/cli/cmd_scan.py +109 -0
  13. clutterxp/cli/cmd_service.py +130 -0
  14. clutterxp/cli/cmd_undo.py +180 -0
  15. clutterxp/cli/cmd_watch.py +147 -0
  16. clutterxp/cli/errors.py +166 -0
  17. clutterxp/cli/render.py +390 -0
  18. clutterxp/config/__init__.py +40 -0
  19. clutterxp/config/jsonschema.py +12 -0
  20. clutterxp/config/loader.py +212 -0
  21. clutterxp/config/placeholders.py +79 -0
  22. clutterxp/config/runtime.py +30 -0
  23. clutterxp/config/schema.py +166 -0
  24. clutterxp/config/validate.py +226 -0
  25. clutterxp/config/writer.py +248 -0
  26. clutterxp/config.example.yaml +76 -0
  27. clutterxp/duplicates/__init__.py +22 -0
  28. clutterxp/duplicates/detector.py +438 -0
  29. clutterxp/duplicates/hashcache.py +149 -0
  30. clutterxp/duplicates/namenorm.py +45 -0
  31. clutterxp/duplicates/quarantine.py +196 -0
  32. clutterxp/duplicates/report.py +110 -0
  33. clutterxp/gui/__init__.py +1 -0
  34. clutterxp/gui/api.py +494 -0
  35. clutterxp/gui/app.py +205 -0
  36. clutterxp/gui/models_qt.py +544 -0
  37. clutterxp/gui/views/__init__.py +21 -0
  38. clutterxp/gui/views/dashboard.py +253 -0
  39. clutterxp/gui/views/duplicates.py +404 -0
  40. clutterxp/gui/views/folders.py +354 -0
  41. clutterxp/gui/views/history.py +281 -0
  42. clutterxp/gui/views/preview.py +277 -0
  43. clutterxp/gui/views/rules.py +527 -0
  44. clutterxp/gui/views/settings.py +172 -0
  45. clutterxp/gui/workers.py +147 -0
  46. clutterxp/history/__init__.py +23 -0
  47. clutterxp/history/db.py +174 -0
  48. clutterxp/history/pathcodec.py +42 -0
  49. clutterxp/history/recovery.py +318 -0
  50. clutterxp/history/schema.sql +43 -0
  51. clutterxp/history/service.py +493 -0
  52. clutterxp/history/undo.py +373 -0
  53. clutterxp/interfaces.py +164 -0
  54. clutterxp/locking.py +113 -0
  55. clutterxp/logging_setup.py +73 -0
  56. clutterxp/models.py +266 -0
  57. clutterxp/mover/__init__.py +26 -0
  58. clutterxp/mover/collision.py +46 -0
  59. clutterxp/mover/fsops.py +191 -0
  60. clutterxp/mover/safe_move.py +741 -0
  61. clutterxp/organizer.py +388 -0
  62. clutterxp/packaging/clutterxp.service +15 -0
  63. clutterxp/paths.py +112 -0
  64. clutterxp/planner.py +339 -0
  65. clutterxp/py.typed +0 -0
  66. clutterxp/rules/__init__.py +16 -0
  67. clutterxp/rules/engine.py +374 -0
  68. clutterxp/rules/matcher.py +222 -0
  69. clutterxp/rules/template.py +171 -0
  70. clutterxp/rules/tokenizer.py +118 -0
  71. clutterxp/safety.py +111 -0
  72. clutterxp/scanner.py +196 -0
  73. clutterxp/service_install.py +208 -0
  74. clutterxp/units.py +59 -0
  75. clutterxp/watch/__init__.py +37 -0
  76. clutterxp/watch/debounce.py +84 -0
  77. clutterxp/watch/events.py +259 -0
  78. clutterxp/watch/ignore.py +77 -0
  79. clutterxp/watch/service.py +662 -0
  80. clutterxp/watch/settle.py +170 -0
  81. clutterxp-1.1.0.dist-info/METADATA +149 -0
  82. clutterxp-1.1.0.dist-info/RECORD +84 -0
  83. clutterxp-1.1.0.dist-info/WHEEL +4 -0
  84. clutterxp-1.1.0.dist-info/entry_points.txt +6 -0
@@ -0,0 +1,527 @@
1
+ """Rules view and editor dialog with live filename trace.
2
+
3
+ Allows managing organization rules (add, edit, remove, enable/disable) and
4
+ features a live 'Test Filename' trace evaluator showing real-time rule matching.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+ from typing import Any, ClassVar
13
+
14
+ from PySide6.QtCore import (
15
+ QAbstractTableModel,
16
+ QModelIndex,
17
+ QPersistentModelIndex,
18
+ Qt,
19
+ )
20
+ from PySide6.QtWidgets import (
21
+ QComboBox,
22
+ QDialog,
23
+ QDialogButtonBox,
24
+ QFormLayout,
25
+ QGroupBox,
26
+ QHBoxLayout,
27
+ QHeaderView,
28
+ QLabel,
29
+ QLineEdit,
30
+ QMessageBox,
31
+ QPushButton,
32
+ QSpinBox,
33
+ QSplitter,
34
+ QTableView,
35
+ QVBoxLayout,
36
+ QWidget,
37
+ )
38
+
39
+ from clutterxp.config.placeholders import validate_destination_template
40
+ from clutterxp.config.schema import Conditions, RuleSpec
41
+ from clutterxp.gui.api import GuiApi
42
+ from clutterxp.gui.models_qt import RulesTableModel
43
+ from clutterxp.gui.workers import run_in_worker
44
+ from clutterxp.models import (
45
+ CollisionPolicy,
46
+ ConfigError,
47
+ CreateDestinations,
48
+ MatchMode,
49
+ RuleTrace,
50
+ )
51
+
52
+ _EMPTY_INDEX = QModelIndex()
53
+
54
+
55
+ class TraceTableModel(QAbstractTableModel):
56
+ """Table model displaying real-time rule trace results."""
57
+
58
+ COLUMNS: ClassVar[tuple[str, ...]] = (
59
+ "Rule Name",
60
+ "Matched",
61
+ "Priority",
62
+ "Reasons",
63
+ )
64
+
65
+ def __init__(self, traces: Sequence[RuleTrace] | None = None) -> None:
66
+ super().__init__()
67
+ self._traces: list[RuleTrace] = list(traces) if traces is not None else []
68
+
69
+ def set_traces(self, traces: Sequence[RuleTrace]) -> None:
70
+ self.beginResetModel()
71
+ self._traces = list(traces)
72
+ self.endResetModel()
73
+
74
+ def rowCount(self, parent: QModelIndex | QPersistentModelIndex = _EMPTY_INDEX) -> int:
75
+ if parent.isValid():
76
+ return 0
77
+ return len(self._traces)
78
+
79
+ def columnCount(self, parent: QModelIndex | QPersistentModelIndex = _EMPTY_INDEX) -> int:
80
+ if parent.isValid():
81
+ return 0
82
+ return len(self.COLUMNS)
83
+
84
+ def data(
85
+ self,
86
+ index: QModelIndex | QPersistentModelIndex,
87
+ role: int = Qt.ItemDataRole.DisplayRole,
88
+ ) -> Any:
89
+ if not index.isValid() or index.row() >= len(self._traces):
90
+ return None
91
+
92
+ trace = self._traces[index.row()]
93
+ col = index.column()
94
+
95
+ if role == Qt.ItemDataRole.DisplayRole:
96
+ if col == 0:
97
+ return trace.rule_name
98
+ elif col == 1:
99
+ return "MATCH" if trace.matched else "NO MATCH"
100
+ elif col == 2:
101
+ return trace.priority
102
+ elif col == 3:
103
+ return "; ".join(trace.reasons)
104
+
105
+ return None
106
+
107
+ def headerData(
108
+ self,
109
+ section: int,
110
+ orientation: Qt.Orientation,
111
+ role: int = Qt.ItemDataRole.DisplayRole,
112
+ ) -> Any:
113
+ if (
114
+ orientation == Qt.Orientation.Horizontal
115
+ and role == Qt.ItemDataRole.DisplayRole
116
+ and 0 <= section < len(self.COLUMNS)
117
+ ):
118
+ return self.COLUMNS[section]
119
+ return None
120
+
121
+
122
+ class RuleEditorDialog(QDialog):
123
+ """Dialog to create or edit an organization rule."""
124
+
125
+ def __init__(
126
+ self,
127
+ rule: RuleSpec | None = None,
128
+ parent: QWidget | None = None,
129
+ ) -> None:
130
+ super().__init__(parent)
131
+ self.is_edit = rule is not None
132
+ self.original_name = rule.name if rule is not None else ""
133
+ self.setWindowTitle("Edit Rule" if self.is_edit else "Add New Rule")
134
+ self.resize(560, 520)
135
+
136
+ self._init_ui(rule)
137
+ self._update_dest_preview()
138
+
139
+ def _init_ui(self, rule: RuleSpec | None) -> None:
140
+ layout = QVBoxLayout(self)
141
+ form = QFormLayout()
142
+
143
+ self.name_edit = QLineEdit(rule.name if rule else "")
144
+ self.name_edit.setPlaceholderText("e.g. Invoices, Receipts, Photos")
145
+ form.addRow("Rule Name:", self.name_edit)
146
+
147
+ self.priority_spin = QSpinBox()
148
+ self.priority_spin.setRange(0, 100_000)
149
+ self.priority_spin.setValue(rule.priority if rule else 100)
150
+ form.addRow("Priority (lower runs first):", self.priority_spin)
151
+
152
+ self.keywords_edit = QLineEdit(", ".join(rule.keywords) if rule else "")
153
+ self.keywords_edit.setPlaceholderText("e.g. invoice, bill, receipt, statement")
154
+ form.addRow("Keywords (comma-separated):", self.keywords_edit)
155
+
156
+ self.extensions_edit = QLineEdit(", ".join(rule.extensions) if rule else "")
157
+ self.extensions_edit.setPlaceholderText("e.g. pdf, png, jpg (without dots)")
158
+ form.addRow("Extensions:", self.extensions_edit)
159
+
160
+ # Match mode
161
+ self.match_combo = QComboBox()
162
+ self.match_combo.addItem("Default (inherit from settings)", None)
163
+ self.match_combo.addItem("Token (exact word boundary)", MatchMode.TOKEN)
164
+ self.match_combo.addItem("Prefix (word starts with keyword)", MatchMode.PREFIX)
165
+ self.match_combo.addItem("Substring (anywhere in filename)", MatchMode.SUBSTRING)
166
+ if rule and rule.match:
167
+ idx = self.match_combo.findData(rule.match)
168
+ if idx >= 0:
169
+ self.match_combo.setCurrentIndex(idx)
170
+ form.addRow("Match Mode:", self.match_combo)
171
+
172
+ # Destination template & helpers
173
+ dest_box = QVBoxLayout()
174
+ self.dest_edit = QLineEdit(rule.destination if rule else "~/Documents/{year}/{month}")
175
+ self.dest_edit.textChanged.connect(self._update_dest_preview)
176
+ dest_box.addWidget(self.dest_edit)
177
+
178
+ # Template helper chips/buttons
179
+ chips_layout = QHBoxLayout()
180
+ chips_layout.addWidget(QLabel("Insert template:"))
181
+ for placeholder in ["{year}", "{month}", "{day}", "{ext}", "{rule}"]:
182
+ btn = QPushButton(placeholder)
183
+ btn.setMaximumWidth(60)
184
+ btn.clicked.connect(lambda _, ph=placeholder: self._insert_placeholder(ph))
185
+ chips_layout.addWidget(btn)
186
+ chips_layout.addStretch()
187
+ dest_box.addLayout(chips_layout)
188
+
189
+ self.dest_preview_label = QLabel()
190
+ self.dest_preview_label.setStyleSheet("color: #2b7a0b; font-style: italic;")
191
+ dest_box.addWidget(self.dest_preview_label)
192
+
193
+ form.addRow("Destination:", dest_box)
194
+
195
+ # Conditions
196
+ self.min_size_edit = QLineEdit(
197
+ str(rule.conditions.min_size) if rule and rule.conditions.min_size else ""
198
+ )
199
+ self.min_size_edit.setPlaceholderText("e.g. 10KB, 1MB (optional)")
200
+ form.addRow("Min Size:", self.min_size_edit)
201
+
202
+ self.max_size_edit = QLineEdit(
203
+ str(rule.conditions.max_size) if rule and rule.conditions.max_size else ""
204
+ )
205
+ self.max_size_edit.setPlaceholderText("e.g. 50MB (optional)")
206
+ form.addRow("Max Size:", self.max_size_edit)
207
+
208
+ # Collision & Destination creation
209
+ self.collision_combo = QComboBox()
210
+ self.collision_combo.addItem("Default (inherit from settings)", None)
211
+ self.collision_combo.addItem("Skip (leave in place)", CollisionPolicy.SKIP)
212
+ self.collision_combo.addItem("Rename (add ' (1)', ' (2)')", CollisionPolicy.RENAME)
213
+ if rule and rule.collision:
214
+ idx = self.collision_combo.findData(rule.collision)
215
+ if idx >= 0:
216
+ self.collision_combo.setCurrentIndex(idx)
217
+ form.addRow("Collision Policy:", self.collision_combo)
218
+
219
+ self.create_combo = QComboBox()
220
+ self.create_combo.addItem("Default (inherit from settings)", None)
221
+ self.create_combo.addItem("Leaf (create leaf directory only)", CreateDestinations.LEAF)
222
+ self.create_combo.addItem("All (create all parent directories)", CreateDestinations.ALL)
223
+ self.create_combo.addItem("Never (destination must exist)", CreateDestinations.NEVER)
224
+ if rule and rule.create_destinations:
225
+ idx = self.create_combo.findData(rule.create_destinations)
226
+ if idx >= 0:
227
+ self.create_combo.setCurrentIndex(idx)
228
+ form.addRow("Create Destination:", self.create_combo)
229
+
230
+ layout.addLayout(form)
231
+
232
+ button_box = QDialogButtonBox(
233
+ QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel
234
+ )
235
+ button_box.accepted.connect(self._on_save)
236
+ button_box.rejected.connect(self.reject)
237
+ layout.addWidget(button_box)
238
+
239
+ def _insert_placeholder(self, placeholder: str) -> None:
240
+ self.dest_edit.insert(placeholder)
241
+
242
+ def _update_dest_preview(self) -> None:
243
+ dest_text = self.dest_edit.text()
244
+ now = datetime.now(timezone.utc)
245
+ sample = dest_text.replace("{year}", str(now.year))
246
+ sample = sample.replace("{month}", f"{now.month:02d}")
247
+ sample = sample.replace("{day}", f"{now.day:02d}")
248
+ sample = sample.replace("{ext}", "pdf")
249
+ sample = sample.replace("{rule}", self.name_edit.text().strip() or "MyRule")
250
+ try:
251
+ expanded = str(Path(sample).expanduser())
252
+ self.dest_preview_label.setText(f"Preview: {expanded}")
253
+ except Exception:
254
+ self.dest_preview_label.setText(f"Preview: {sample}")
255
+
256
+ def _on_save(self) -> None:
257
+ name = self.name_edit.text().strip()
258
+ if not name:
259
+ QMessageBox.warning(self, "Validation Error", "Rule Name cannot be empty.")
260
+ return
261
+
262
+ destination = self.dest_edit.text().strip()
263
+ if not destination:
264
+ QMessageBox.warning(self, "Validation Error", "Destination cannot be empty.")
265
+ return
266
+
267
+ p_errors = validate_destination_template(destination)
268
+ if p_errors:
269
+ QMessageBox.warning(
270
+ self,
271
+ "Invalid Destination Template",
272
+ "Destination template has errors:\n• " + "\n• ".join(p_errors),
273
+ )
274
+ return
275
+
276
+ keywords = [k.strip() for k in self.keywords_edit.text().split(",") if k.strip()]
277
+ extensions = [
278
+ e.strip().lstrip(".").lower()
279
+ for e in self.extensions_edit.text().split(",")
280
+ if e.strip()
281
+ ]
282
+
283
+ min_sz = self.min_size_edit.text().strip() or None
284
+ max_sz = self.max_size_edit.text().strip() or None
285
+ conditions = Conditions(min_size=min_sz, max_size=max_sz)
286
+
287
+ if not (keywords or extensions or conditions.any_set()):
288
+ QMessageBox.warning(
289
+ self,
290
+ "Validation Error",
291
+ "Rule must have at least one keyword, extension, or size condition.",
292
+ )
293
+ return
294
+
295
+ try:
296
+ self.rule_spec = RuleSpec(
297
+ name=name,
298
+ priority=self.priority_spin.value(),
299
+ destination=destination,
300
+ keywords=keywords,
301
+ extensions=extensions,
302
+ match=self.match_combo.currentData(),
303
+ conditions=conditions,
304
+ collision=self.collision_combo.currentData(),
305
+ create_destinations=self.create_combo.currentData(),
306
+ )
307
+ self.accept()
308
+ except Exception as exc:
309
+ QMessageBox.warning(self, "Invalid Rule Specification", str(exc))
310
+
311
+ def get_rule_spec(self) -> RuleSpec:
312
+ return self.rule_spec
313
+
314
+
315
+ class RulesView(QWidget):
316
+ """Rules view with editor and real-time live test trace evaluation."""
317
+
318
+ def __init__(self, api: GuiApi, parent: QWidget | None = None) -> None:
319
+ super().__init__(parent)
320
+ self.api = api
321
+ self._rules_model = RulesTableModel()
322
+ self._trace_model = TraceTableModel()
323
+ self._init_ui()
324
+ self.refresh()
325
+
326
+ def _init_ui(self) -> None:
327
+ main_layout = QVBoxLayout(self)
328
+ main_layout.setContentsMargins(16, 16, 16, 16)
329
+ main_layout.setSpacing(12)
330
+
331
+ splitter = QSplitter(Qt.Orientation.Vertical)
332
+
333
+ # Top section: Rules Table and Management
334
+ rules_container = QWidget()
335
+ rules_layout = QVBoxLayout(rules_container)
336
+ rules_layout.setContentsMargins(0, 0, 0, 0)
337
+
338
+ header_row = QHBoxLayout()
339
+ title_label = QLabel("Rules")
340
+ title_font = title_label.font()
341
+ title_font.setPointSize(16)
342
+ title_font.setBold(True)
343
+ title_label.setFont(title_font)
344
+ header_row.addWidget(title_label)
345
+ header_row.addStretch()
346
+ rules_layout.addLayout(header_row)
347
+
348
+ self.rules_table = QTableView()
349
+ self.rules_table.setModel(self._rules_model)
350
+ self.rules_table.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
351
+ self.rules_table.setSelectionMode(QTableView.SelectionMode.SingleSelection)
352
+ self.rules_table.horizontalHeader().setSectionResizeMode(
353
+ QHeaderView.ResizeMode.ResizeToContents
354
+ )
355
+ self.rules_table.horizontalHeader().setStretchLastSection(True)
356
+ self._rules_model.rule_toggled.connect(self._on_rule_toggled)
357
+ rules_layout.addWidget(self.rules_table)
358
+
359
+ btn_row = QHBoxLayout()
360
+ self.add_btn = QPushButton("Add Rule...")
361
+ self.add_btn.clicked.connect(self._on_add_rule)
362
+ btn_row.addWidget(self.add_btn)
363
+
364
+ self.edit_btn = QPushButton("Edit Rule...")
365
+ self.edit_btn.clicked.connect(self._on_edit_rule)
366
+ btn_row.addWidget(self.edit_btn)
367
+
368
+ self.remove_btn = QPushButton("Remove Rule")
369
+ self.remove_btn.clicked.connect(self._on_remove_rule)
370
+ btn_row.addWidget(self.remove_btn)
371
+
372
+ self.toggle_enable_btn = QPushButton("Toggle Enable")
373
+ self.toggle_enable_btn.clicked.connect(self._on_toggle_enable)
374
+ btn_row.addWidget(self.toggle_enable_btn)
375
+
376
+ btn_row.addStretch()
377
+
378
+ self.refresh_btn = QPushButton("Refresh")
379
+ self.refresh_btn.clicked.connect(self.refresh)
380
+ btn_row.addWidget(self.refresh_btn)
381
+
382
+ rules_layout.addLayout(btn_row)
383
+ splitter.addWidget(rules_container)
384
+
385
+ # Bottom section: Live Test Filename Trace
386
+ trace_group = QGroupBox("Test Filename (Live Trace)")
387
+ trace_layout = QVBoxLayout(trace_group)
388
+
389
+ input_row = QHBoxLayout()
390
+ input_row.addWidget(QLabel("Test Filename:"))
391
+ self.test_input = QLineEdit()
392
+ self.test_input.setPlaceholderText("Type a filename or path to see real-time trace...")
393
+ self.test_input.textChanged.connect(self.evaluate_trace)
394
+ input_row.addWidget(self.test_input)
395
+ trace_layout.addLayout(input_row)
396
+
397
+ self.trace_table = QTableView()
398
+ self.trace_table.setModel(self._trace_model)
399
+ self.trace_table.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
400
+ self.trace_table.horizontalHeader().setSectionResizeMode(
401
+ QHeaderView.ResizeMode.ResizeToContents
402
+ )
403
+ self.trace_table.horizontalHeader().setStretchLastSection(True)
404
+ trace_layout.addWidget(self.trace_table)
405
+
406
+ splitter.addWidget(trace_group)
407
+ main_layout.addWidget(splitter)
408
+
409
+ def refresh(self) -> None:
410
+ """Fetch and reload rules."""
411
+
412
+ def _fetch() -> list[RuleSpec]:
413
+ cfg = self.api.get_runtime_config(force_reload=True)
414
+ return list(cfg.all_rules)
415
+
416
+ def _apply(rules: list[RuleSpec]) -> None:
417
+ self._rules_model.set_rules(rules)
418
+ self.evaluate_trace(self.test_input.text())
419
+
420
+ run_in_worker(_fetch, on_result=_apply)
421
+
422
+ def evaluate_trace(self, text: str) -> None:
423
+ """Run live trace for text string."""
424
+ raw_text = text.strip()
425
+ if not raw_text:
426
+ self._trace_model.set_traces([])
427
+ return
428
+
429
+ traces = self.api.rules_trace(raw_text)
430
+ self._trace_model.set_traces(traces)
431
+
432
+ def _on_rule_toggled(self, rule_name: str, enabled: bool) -> None:
433
+ def _do() -> None:
434
+ if enabled:
435
+ self.api.config_enable_rule(rule_name)
436
+ else:
437
+ self.api.config_disable_rule(rule_name)
438
+
439
+ run_in_worker(_do, on_result=lambda _: self.refresh())
440
+
441
+ def _on_toggle_enable(self) -> None:
442
+ selected_indexes = self.rules_table.selectionModel().selectedRows()
443
+ if not selected_indexes:
444
+ return
445
+ row = selected_indexes[0].row()
446
+ rule = self._rules_model.get_rule(row)
447
+ if rule:
448
+ self._on_rule_toggled(rule.name, not rule.enabled)
449
+
450
+ def _on_add_rule(self) -> None:
451
+ dialog = RuleEditorDialog(None, self)
452
+ if dialog.exec() == QDialog.DialogCode.Accepted:
453
+ rule_spec = dialog.get_rule_spec()
454
+
455
+ def _do_add() -> None:
456
+ self.api.config_save_rule(rule_spec, is_new=True)
457
+
458
+ def _on_err(exc: Exception) -> None:
459
+ msg = str(exc)
460
+ if isinstance(exc, ConfigError) and exc.problems:
461
+ msg += ":\n\n• " + "\n• ".join(exc.problems)
462
+ QMessageBox.critical(self, "Error Adding Rule", msg)
463
+
464
+ run_in_worker(_do_add, on_result=lambda _: self.refresh(), on_error=_on_err)
465
+
466
+ def _on_edit_rule(self) -> None:
467
+ selected_indexes = self.rules_table.selectionModel().selectedRows()
468
+ if not selected_indexes:
469
+ QMessageBox.information(self, "Selection Required", "Please select a rule to edit.")
470
+ return
471
+
472
+ row = selected_indexes[0].row()
473
+ rule = self._rules_model.get_rule(row)
474
+ if not rule:
475
+ return
476
+
477
+ dialog = RuleEditorDialog(rule, self)
478
+ if dialog.exec() == QDialog.DialogCode.Accepted:
479
+ rule_spec = dialog.get_rule_spec()
480
+
481
+ def _do_edit() -> None:
482
+ self.api.config_save_rule(rule_spec, is_new=False)
483
+
484
+ def _on_err(exc: Exception) -> None:
485
+ msg = str(exc)
486
+ if isinstance(exc, ConfigError) and exc.problems:
487
+ msg += ":\n\n• " + "\n• ".join(exc.problems)
488
+ QMessageBox.critical(self, "Error Editing Rule", msg)
489
+
490
+ run_in_worker(_do_edit, on_result=lambda _: self.refresh(), on_error=_on_err)
491
+
492
+ def _on_remove_rule(self) -> None:
493
+ selected_indexes = self.rules_table.selectionModel().selectedRows()
494
+ if not selected_indexes:
495
+ QMessageBox.information(self, "Selection Required", "Please select a rule to remove.")
496
+ return
497
+
498
+ row = selected_indexes[0].row()
499
+ rule = self._rules_model.get_rule(row)
500
+ if not rule:
501
+ return
502
+
503
+ reply = QMessageBox.question(
504
+ self,
505
+ "Confirm Deletion",
506
+ f"Remove rule '{rule.name}' permanently from configuration?",
507
+ QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
508
+ )
509
+ if reply == QMessageBox.StandardButton.Yes:
510
+
511
+ def _do_del() -> None:
512
+ self.api.config_remove_rule(rule.name)
513
+
514
+ def _on_err(exc: Exception) -> None:
515
+ msg = str(exc)
516
+ if isinstance(exc, ConfigError) and exc.problems:
517
+ msg += ":\n\n• " + "\n• ".join(exc.problems)
518
+ QMessageBox.critical(self, "Error Removing Rule", msg)
519
+
520
+ run_in_worker(_do_del, on_result=lambda _: self.refresh(), on_error=_on_err)
521
+
522
+
523
+ __all__ = [
524
+ "RuleEditorDialog",
525
+ "RulesView",
526
+ "TraceTableModel",
527
+ ]
@@ -0,0 +1,172 @@
1
+ """Settings view for global configuration, editor launch, and live validation.
2
+
3
+ Displays global settings values, config file path, provides an 'Open in Editor' shortcut,
4
+ and runs live config validation displaying errors and warnings.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from PySide6.QtCore import Qt, QUrl
10
+ from PySide6.QtGui import QDesktopServices
11
+ from PySide6.QtWidgets import (
12
+ QFormLayout,
13
+ QGroupBox,
14
+ QHBoxLayout,
15
+ QLabel,
16
+ QListWidget,
17
+ QListWidgetItem,
18
+ QPushButton,
19
+ QVBoxLayout,
20
+ QWidget,
21
+ )
22
+
23
+ from clutterxp.config.runtime import RuntimeConfig
24
+ from clutterxp.gui.api import GuiApi
25
+ from clutterxp.gui.workers import run_in_worker
26
+
27
+
28
+ class SettingsView(QWidget):
29
+ """View displaying global settings and live validation feedback."""
30
+
31
+ def __init__(self, api: GuiApi, parent: QWidget | None = None) -> None:
32
+ super().__init__(parent)
33
+ self.api = api
34
+ self._init_ui()
35
+ self.refresh()
36
+
37
+ def _init_ui(self) -> None:
38
+ main_layout = QVBoxLayout(self)
39
+ main_layout.setContentsMargins(16, 16, 16, 16)
40
+ main_layout.setSpacing(16)
41
+
42
+ # Title
43
+ title_label = QLabel("Settings & Configuration")
44
+ title_font = title_label.font()
45
+ title_font.setPointSize(16)
46
+ title_font.setBold(True)
47
+ title_label.setFont(title_font)
48
+ main_layout.addWidget(title_label)
49
+
50
+ # Config File Card
51
+ file_box = QGroupBox("Configuration File")
52
+ file_layout = QHBoxLayout(file_box)
53
+
54
+ self.path_label = QLabel(str(self.api.config_path))
55
+ self.path_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
56
+ file_layout.addWidget(self.path_label, stretch=1)
57
+
58
+ self.open_editor_btn = QPushButton("Open in Text Editor")
59
+ self.open_editor_btn.clicked.connect(self._on_open_editor)
60
+ file_layout.addWidget(self.open_editor_btn)
61
+
62
+ self.reload_btn = QPushButton("Reload")
63
+ self.reload_btn.clicked.connect(self.refresh)
64
+ file_layout.addWidget(self.reload_btn)
65
+
66
+ main_layout.addWidget(file_box)
67
+
68
+ # Global Settings Summary Box
69
+ settings_box = QGroupBox("Global Settings (from config.yaml)")
70
+ form = QFormLayout(settings_box)
71
+
72
+ self.collision_label = QLabel()
73
+ form.addRow("Collision Policy:", self.collision_label)
74
+
75
+ self.create_label = QLabel()
76
+ form.addRow("Create Destinations:", self.create_label)
77
+
78
+ self.match_label = QLabel()
79
+ form.addRow("Default Match Mode:", self.match_label)
80
+
81
+ self.settle_label = QLabel()
82
+ form.addRow("Settle Time:", self.settle_label)
83
+
84
+ self.threshold_label = QLabel()
85
+ form.addRow("Confirmation Threshold:", self.threshold_label)
86
+
87
+ self.hidden_label = QLabel()
88
+ form.addRow("Skip Hidden Files:", self.hidden_label)
89
+
90
+ main_layout.addWidget(settings_box)
91
+
92
+ # Live Validation Panel
93
+ val_box = QGroupBox("Configuration Validation Panel")
94
+ val_layout = QVBoxLayout(val_box)
95
+
96
+ status_row = QHBoxLayout()
97
+ self.val_status_label = QLabel("Status: Checking...")
98
+ status_font = self.val_status_label.font()
99
+ status_font.setBold(True)
100
+ self.val_status_label.setFont(status_font)
101
+ status_row.addWidget(self.val_status_label)
102
+
103
+ status_row.addStretch()
104
+
105
+ self.revalidate_btn = QPushButton("Re-validate Now")
106
+ self.revalidate_btn.clicked.connect(self._run_validation)
107
+ status_row.addWidget(self.revalidate_btn)
108
+ val_layout.addLayout(status_row)
109
+
110
+ self.issues_list = QListWidget()
111
+ val_layout.addWidget(self.issues_list)
112
+
113
+ main_layout.addWidget(val_box, stretch=1)
114
+
115
+ def refresh(self) -> None:
116
+ """Fetch and reload settings and validation."""
117
+
118
+ def _fetch() -> tuple[RuntimeConfig, tuple[list[str], list[str]]]:
119
+ cfg = self.api.reload_config()
120
+ val_res = self.api.config_validate()
121
+ return cfg, val_res
122
+
123
+ def _apply(res: tuple[RuntimeConfig, tuple[list[str], list[str]]]) -> None:
124
+ cfg, val_res = res
125
+ errors, warnings = val_res
126
+
127
+ # Update settings labels
128
+ s = cfg.settings
129
+ self.collision_label.setText(str(s.collision.value))
130
+ self.create_label.setText(str(s.create_destinations.value))
131
+ self.match_label.setText(str(s.match.value))
132
+ self.settle_label.setText(f"{s.settle_seconds}s")
133
+ self.threshold_label.setText(f"{s.confirm_threshold} files")
134
+ self.hidden_label.setText("Yes" if s.skip_hidden else "No")
135
+
136
+ # Update validation panel
137
+ self.issues_list.clear()
138
+ if errors:
139
+ self.val_status_label.setText(
140
+ f"Configuration Invalid ({len(errors)} error(s), {len(warnings)} warning(s))"
141
+ )
142
+ self.val_status_label.setStyleSheet("color: #b30000;")
143
+ elif warnings:
144
+ self.val_status_label.setText(
145
+ f"Configuration Valid with {len(warnings)} Warning(s)"
146
+ )
147
+ self.val_status_label.setStyleSheet("color: #b37400;")
148
+ else:
149
+ self.val_status_label.setText("Configuration is Valid (No issues detected)")
150
+ self.val_status_label.setStyleSheet("color: #2b7a0b;")
151
+
152
+ for err in errors:
153
+ item = QListWidgetItem(f"[ERROR] {err}")
154
+ item.setForeground(QLabel().palette().color(QLabel().foregroundRole()))
155
+ self.issues_list.addItem(item)
156
+
157
+ for warn in warnings:
158
+ item = QListWidgetItem(f"[WARNING] {warn}")
159
+ self.issues_list.addItem(item)
160
+
161
+ run_in_worker(_fetch, on_result=_apply)
162
+
163
+ def _run_validation(self) -> None:
164
+ self.refresh()
165
+
166
+ def _on_open_editor(self) -> None:
167
+ cfg_path = self.api.config_path
168
+ if cfg_path.exists():
169
+ QDesktopServices.openUrl(QUrl.fromLocalFile(str(cfg_path)))
170
+
171
+
172
+ __all__ = ["SettingsView"]