-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli_validator.py
More file actions
959 lines (817 loc) · 36 KB
/
cli_validator.py
File metadata and controls
959 lines (817 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
"""
CLI Validator - Validates kicad-cli parameter combinations before execution.
This module checks for incompatible parameter combinations and provides
clear error messages to prevent render failures.
"""
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
from enum import Enum
import os
# Import rotation geometry functions - handle both package and standalone import
try:
from .rotation_geometry import (
calculate_rotation_expansion,
calculate_safe_zoom,
calculate_safe_zoom_for_animation
)
except ImportError:
from rotation_geometry import (
calculate_rotation_expansion,
calculate_safe_zoom,
calculate_safe_zoom_for_animation
)
class ValidationLevel(Enum):
"""Severity level for validation messages."""
ERROR = "error" # Will cause render to fail
WARNING = "warning" # May cause unexpected results
INFO = "info" # Informational only
@dataclass
class ValidationResult:
"""Result of a single validation check."""
level: ValidationLevel
message: str
param: str = ""
suggestion: str = ""
class CLIValidator:
"""
Validates kicad-cli PCB export image parameters.
Usage:
validator = CLIValidator()
results = validator.validate(params)
if validator.has_errors(results):
# Show errors and abort
else:
# Proceed with render
"""
# Valid values for enumerated parameters
VALID_SIDES = {"top", "bottom", "left", "right", "front", "back"}
VALID_BACKGROUNDS = {"transparent", "opaque", "default"}
VALID_QUALITIES = {"basic", "high", "user", "job_settings"}
VALID_OUTPUT_FORMATS = {"png", "jpg", "jpeg"} # kicad-cli supported formats
VALID_PRESETS = {"follow_pcb_editor", "follow_plot_settings"} # kicad-cli presets
# Default values (kicad-cli defaults)
DEFAULTS = {
"side": "top",
"width": 1600,
"height": 900,
"zoom": 1.0,
"background": "opaque",
"quality": "basic",
"perspective": False,
"floor": False,
"light_top": 0.5,
"light_bottom": 0.1,
"light_side": 0.3,
"light_camera": 0.2,
"light_side_elevation": 60,
}
def __init__(self):
"""Initialize the validator."""
self._validation_rules = [
self._check_required_params,
self._check_input_file,
self._check_output_path,
self._check_output_format,
self._check_side_value,
self._check_background_value,
self._check_quality_value,
self._check_preset_value,
self._check_dimensions,
self._check_zoom,
self._check_rotate_format,
self._check_pan_format,
self._check_pivot_format,
self._check_rotate_zoom_clipping,
self._check_lighting_values,
self._check_side_elevation,
]
def validate(self, params: Dict) -> List[ValidationResult]:
"""
Validate all parameters and return list of validation results.
Args:
params: Dictionary of CLI parameters
Returns:
List of ValidationResult objects (may be empty if all valid)
"""
results = []
for rule in self._validation_rules:
try:
rule_results = rule(params)
if rule_results:
results.extend(rule_results)
except Exception as e:
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"Validation rule failed: {e}",
param="",
suggestion="Check parameter values"
))
return results
def has_errors(self, results: List[ValidationResult]) -> bool:
"""Check if any results are errors."""
return any(r.level == ValidationLevel.ERROR for r in results)
def has_warnings(self, results: List[ValidationResult]) -> bool:
"""Check if any results are warnings."""
return any(r.level == ValidationLevel.WARNING for r in results)
def get_errors(self, results: List[ValidationResult]) -> List[ValidationResult]:
"""Get only error-level results."""
return [r for r in results if r.level == ValidationLevel.ERROR]
def get_warnings(self, results: List[ValidationResult]) -> List[ValidationResult]:
"""Get only warning-level results."""
return [r for r in results if r.level == ValidationLevel.WARNING]
def format_results(self, results: List[ValidationResult]) -> str:
"""Format results as a human-readable string."""
if not results:
return "✓ All parameters valid"
lines = []
for r in results:
prefix = {
ValidationLevel.ERROR: "❌ ERROR",
ValidationLevel.WARNING: "⚠️ WARNING",
ValidationLevel.INFO: "ℹ️ INFO"
}.get(r.level, "?")
line = f"{prefix}: {r.message}"
if r.param:
line += f" (param: {r.param})"
if r.suggestion:
line += f"\n → {r.suggestion}"
lines.append(line)
return "\n".join(lines)
# ========== Validation Rules ==========
def _check_required_params(self, params: Dict) -> List[ValidationResult]:
"""Check that required parameters are present."""
results = []
# Side is always required for kicad-cli pcb export image
if "side" not in params or not params.get("side"):
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message="Missing required parameter: side",
param="side",
suggestion="Add --side with value: top, bottom, left, right, front, or back"
))
return results
def _check_input_file(self, params: Dict) -> List[ValidationResult]:
"""Validate that input file exists and is a valid KiCad PCB file."""
results = []
input_file = params.get("input_file") or params.get("input") or params.get("board")
if not input_file:
# Input file might be provided separately, skip if not in params
return []
# Check if file exists
if not os.path.exists(input_file):
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Input file does not exist: '{input_file}'",
param="input_file",
suggestion="Check the file path and ensure the .kicad_pcb file exists"
))
return results # No point checking further if file doesn't exist
# Check if it's a file (not a directory)
if not os.path.isfile(input_file):
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Input path is not a file: '{input_file}'",
param="input_file",
suggestion="Provide a path to a .kicad_pcb file, not a directory"
))
return results
# Check file extension
_, ext = os.path.splitext(input_file)
if ext.lower() != ".kicad_pcb":
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"Input file has unexpected extension: '{ext}'",
param="input_file",
suggestion="Expected .kicad_pcb file for KiCad PCB rendering"
))
return results
def _check_output_path(self, params: Dict) -> List[ValidationResult]:
"""Validate that output path/folder exists and is writable."""
results = []
output = params.get("output") or params.get("output_file") or params.get("output_path")
if not output:
# Output might be provided separately, skip if not in params
return []
# Get the directory part of the output path
output_dir = os.path.dirname(output)
# If no directory specified, it's current dir which should be fine
if not output_dir:
return []
# Check if output directory exists
if not os.path.exists(output_dir):
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Output directory does not exist: '{output_dir}'",
param="output",
suggestion="Create the output directory first or use an existing path"
))
return results
# Check if it's a directory
if not os.path.isdir(output_dir):
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Output path parent is not a directory: '{output_dir}'",
param="output",
suggestion="Ensure the output path points to a valid directory"
))
return results
# Check if directory is writable
if not os.access(output_dir, os.W_OK):
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Output directory is not writable: '{output_dir}'",
param="output",
suggestion="Check write permissions on the output directory"
))
return results
def _check_output_format(self, params: Dict) -> List[ValidationResult]:
"""Validate output format/extension."""
results = []
# Video formats for animations - not validated by CLI validator
VIDEO_FORMATS = {"mp4", "gif", "webm", "avi"}
# Check explicit format parameter
fmt = params.get("format") or params.get("output_format")
if fmt:
fmt_lower = fmt.lower().lstrip('.')
# Skip validation for video formats (used by animation templates)
if fmt_lower in VIDEO_FORMATS:
return results
if fmt_lower not in self.VALID_OUTPUT_FORMATS:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Invalid output format: '{fmt}'",
param="format",
suggestion=f"Use one of: {', '.join(sorted(self.VALID_OUTPUT_FORMATS))}"
))
return results
# Also check output file extension if provided
output = params.get("output") or params.get("output_file")
if output:
_, ext = os.path.splitext(output)
ext = ext.lower().lstrip('.')
if ext and ext not in self.VALID_OUTPUT_FORMATS:
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"Output file has unsupported extension: '.{ext}'",
param="output",
suggestion=f"kicad-cli supports: {', '.join(sorted(self.VALID_OUTPUT_FORMATS))}"
))
# Check for transparency with JPG format
bg = params.get("background", "")
if fmt:
check_fmt = fmt.lower().lstrip('.')
elif output:
_, ext = os.path.splitext(output)
check_fmt = ext.lower().lstrip('.')
else:
check_fmt = ""
if check_fmt in ("jpg", "jpeg") and bg == "transparent":
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message="JPG format does not support transparency",
param="background",
suggestion="Use PNG format for transparent background, or change to opaque"
))
return results
def _check_side_value(self, params: Dict) -> List[ValidationResult]:
"""Validate side parameter value."""
side = params.get("side", "")
if side and side.lower() not in self.VALID_SIDES:
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Invalid side value: '{side}'",
param="side",
suggestion=f"Use one of: {', '.join(sorted(self.VALID_SIDES))}"
)]
return []
def _check_background_value(self, params: Dict) -> List[ValidationResult]:
"""Validate background parameter value."""
bg = params.get("background", "")
if bg and bg.lower() not in self.VALID_BACKGROUNDS:
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Invalid background value: '{bg}'",
param="background",
suggestion=f"Use one of: {', '.join(sorted(self.VALID_BACKGROUNDS))}"
)]
return []
def _check_quality_value(self, params: Dict) -> List[ValidationResult]:
"""Validate quality parameter value."""
quality = params.get("quality", "")
if quality and quality.lower() not in self.VALID_QUALITIES:
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Invalid quality value: '{quality}'",
param="quality",
suggestion=f"Use one of: {', '.join(sorted(self.VALID_QUALITIES))}"
)]
return []
def _check_preset_value(self, params: Dict) -> List[ValidationResult]:
"""Validate preset parameter value."""
preset = params.get("preset", "")
if not preset:
return []
# Allow custom preset names (user-defined presets)
preset_lower = preset.lower()
if preset_lower in self.VALID_PRESETS:
return []
# Warn about non-standard presets (might be user-defined)
return [ValidationResult(
level=ValidationLevel.INFO,
message=f"Using custom preset: '{preset}'",
param="preset",
suggestion=f"Standard presets are: {', '.join(sorted(self.VALID_PRESETS))}"
)]
def _check_lighting_values(self, params: Dict) -> List[ValidationResult]:
"""
Validate lighting parameter values.
Lighting can be:
- Single float 0.0-1.0 for intensity
- RGB format "R,G,B" with values 0.0-1.0
"""
results = []
light_params = ["light_top", "light_bottom", "light_side", "light_camera"]
for param in light_params:
value = params.get(param)
if value is None or value == "":
continue
value_str = str(value)
# Check if it's RGB format (contains comma)
if "," in value_str:
parts = value_str.split(",")
if len(parts) != 3:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"{param} RGB must have 3 values: '{value_str}'",
param=param,
suggestion="Format: R,G,B (e.g., '0.5,0.5,0.5')"
))
continue
for i, part in enumerate(parts):
try:
v = float(part.strip())
if v < 0 or v > 1:
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"{param} RGB value {v} outside 0-1 range",
param=param,
suggestion="RGB values should be between 0.0 and 1.0"
))
except ValueError:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"{param} RGB value '{part}' is not a number",
param=param,
suggestion="RGB values must be numbers"
))
else:
# Single intensity value
try:
v = float(value_str)
if v < 0 or v > 1:
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"{param} value {v} outside 0-1 range",
param=param,
suggestion="Intensity should be between 0.0 and 1.0"
))
except ValueError:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"{param} value '{value_str}' is not a number",
param=param,
suggestion="Use a number 0.0-1.0 or RGB format 'R,G,B'"
))
return results
def _check_side_elevation(self, params: Dict) -> List[ValidationResult]:
"""Validate side light elevation angle."""
elevation = params.get("light_side_elevation")
if elevation is None or elevation == "":
return []
try:
v = float(elevation)
if v < 0 or v > 90:
return [ValidationResult(
level=ValidationLevel.WARNING,
message=f"Side elevation {v}° outside 0-90 range",
param="light_side_elevation",
suggestion="Elevation should be between 0° and 90°"
)]
except ValueError:
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Side elevation '{elevation}' is not a number",
param="light_side_elevation",
suggestion="Provide an angle in degrees (0-90)"
)]
return []
def _check_dimensions(self, params: Dict) -> List[ValidationResult]:
"""Validate width and height parameters."""
results = []
for dim in ["width", "height"]:
val = params.get(dim)
if val is not None:
try:
val = int(val)
if val < 1:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"{dim} must be positive: {val}",
param=dim,
suggestion=f"Use a positive integer for {dim}"
))
elif val < 100:
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"{dim} is very small: {val}px",
param=dim,
suggestion="Consider using at least 100px for usable output"
))
elif val > 16000:
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"{dim} is very large: {val}px",
param=dim,
suggestion="Large dimensions may cause memory issues or slow rendering"
))
except (ValueError, TypeError):
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"{dim} must be an integer: '{val}'",
param=dim,
suggestion=f"Provide an integer value for {dim}"
))
return results
def _check_zoom(self, params: Dict) -> List[ValidationResult]:
"""Validate zoom parameter."""
zoom = params.get("zoom")
if zoom is not None:
try:
zoom = float(zoom)
if zoom <= 0:
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Zoom must be positive: {zoom}",
param="zoom",
suggestion="Use a positive value like 1.0 (100%)"
)]
elif zoom < 0.1:
return [ValidationResult(
level=ValidationLevel.WARNING,
message=f"Zoom is very small: {zoom}",
param="zoom",
suggestion="Board may be too small to see at this zoom level"
)]
elif zoom > 10:
return [ValidationResult(
level=ValidationLevel.WARNING,
message=f"Zoom is very large: {zoom}",
param="zoom",
suggestion="Board may be cropped at this zoom level"
)]
except (ValueError, TypeError):
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Zoom must be a number: '{zoom}'",
param="zoom",
suggestion="Provide a decimal value like 1.0"
)]
return []
def _check_rotate_format(self, params: Dict) -> List[ValidationResult]:
"""Validate rotate parameter format (x,y,z degrees)."""
rotate = params.get("rotate", "")
if not rotate:
return []
parts = str(rotate).split(",")
if len(parts) != 3:
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Rotate must have 3 values (x,y,z): '{rotate}'",
param="rotate",
suggestion="Format: x,y,z (e.g., '0,0,45' for 45° Z rotation)"
)]
results = []
for i, part in enumerate(parts):
try:
val = float(part.strip())
if abs(val) > 360:
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"Rotate value {val}° exceeds 360°",
param="rotate",
suggestion="Values are in degrees, typically 0-360"
))
except ValueError:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Rotate value '{part}' is not a number",
param="rotate",
suggestion="All rotate values must be numbers"
))
return results
def _check_pan_format(self, params: Dict) -> List[ValidationResult]:
"""Validate pan parameter format (x,y,z)."""
pan = params.get("pan", "")
if not pan:
return []
parts = str(pan).split(",")
if len(parts) != 3:
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Pan must have 3 values (x,y,z): '{pan}'",
param="pan",
suggestion="Format: x,y,z (e.g., '10,5,0' to pan right and forward)"
)]
results = []
has_negative = False
for part in parts:
try:
val = float(part.strip())
if val < 0:
has_negative = True
except ValueError:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Pan value '{part}' is not a number",
param="pan",
suggestion="Pan values must be numbers"
))
# kicad-cli bug: can't parse values starting with '-'
if has_negative and not results:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Pan contains negative values: '{pan}'",
param="pan",
suggestion="kicad-cli cannot parse negative pan values (bug). Use positive values only."
))
return results
def _check_pivot_format(self, params: Dict) -> List[ValidationResult]:
"""Validate pivot parameter format (x,y,z)."""
pivot = params.get("pivot", "")
if not pivot:
return []
parts = str(pivot).split(",")
if len(parts) != 3:
return [ValidationResult(
level=ValidationLevel.ERROR,
message=f"Pivot must have 3 values (x,y,z): '{pivot}'",
param="pivot",
suggestion="Format: x,y,z (e.g., '0,0,0' for board center)"
)]
results = []
has_negative = False
for part in parts:
try:
val = float(part.strip())
if val < 0:
has_negative = True
except ValueError:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Pivot value '{part}' is not a number",
param="pivot",
suggestion="Pivot values must be numbers"
))
# kicad-cli bug: can't parse values starting with '-'
if has_negative and not results:
results.append(ValidationResult(
level=ValidationLevel.ERROR,
message=f"Pivot contains negative values: '{pivot}'",
param="pivot",
suggestion="kicad-cli cannot parse negative pivot values (bug). Use positive values only."
))
return results
def _check_rotate_zoom_clipping(self, params: Dict) -> List[ValidationResult]:
"""
Check if rotation + zoom combination will cause corner clipping.
When a rectangle is rotated, its bounding box grows:
- W_new = W × |cos(θ)| + H × |sin(θ)|
- H_new = W × |sin(θ)| + H × |cos(θ)|
If zoom is too high, corners will be clipped.
"""
rotate = params.get("rotate", "")
if not rotate:
return []
zoom = params.get("zoom", 1.0)
try:
zoom = float(zoom)
except (ValueError, TypeError):
return [] # Let other validator catch this
# Parse rotation angles
parts = str(rotate).split(",")
if len(parts) != 3:
return [] # Let other validator catch this
try:
rot_x = float(parts[0].strip())
rot_y = float(parts[1].strip())
rot_z = float(parts[2].strip())
except ValueError:
return [] # Let other validator catch this
# Get board aspect ratio (default to 1.5:1 if not provided)
board_width = params.get("board_width", 150.0)
board_height = params.get("board_height", 100.0)
try:
board_width = float(board_width)
board_height = float(board_height)
except (ValueError, TypeError):
board_width, board_height = 150.0, 100.0
# Get component height (mm) - for tall connectors, caps, heatsinks
component_height = params.get("component_height", 10)
try:
component_height = float(component_height)
except (ValueError, TypeError):
component_height = 10.0
# Get safety margin (%)
safety_margin = params.get("safety_margin", 5)
try:
margin = float(safety_margin) / 100.0
except (ValueError, TypeError):
margin = 0.05
# Calculate expansion factor from rotation (includes component height)
expansion = calculate_rotation_expansion(board_width, board_height, rot_x, rot_y, rot_z, component_height)
# Calculate safe zoom with margin
safe_zoom = (1.0 / expansion) * (1.0 - margin)
results = []
# Check if current zoom will cause clipping (5% tolerance on top of margin)
if zoom > safe_zoom * 1.05:
results.append(ValidationResult(
level=ValidationLevel.WARNING,
message=f"Zoom {zoom:.2f} may clip corners at rotation {rotate}",
param="zoom",
suggestion=f"For this rotation, use zoom ≤ {safe_zoom:.2f} to avoid clipping (expansion factor: {expansion:.2f}x)"
))
return results
# ============== NORMALIZATION FUNCTIONS ==============
# Normalize parameter values before passing to kicad-cli
def normalize_params(params: Dict) -> Tuple[Dict, List[str]]:
"""
Normalize all CLI parameters to valid values.
This handles:
- Rotation angles: normalize to 0-359 range (fixes kicad-cli negative number bug)
- Choice values: lowercase
- Boolean values: convert strings to bool
- Numeric values: clamp to valid ranges
Args:
params: Dictionary of CLI parameters
Returns:
Tuple of (normalized_params, log_messages)
- normalized_params: New dict with normalized values
- log_messages: List of changes made for logging
"""
normalized = params.copy()
logs = []
# Normalize rotation angles (0-359 range)
if "rotate" in normalized and normalized["rotate"]:
original = normalized["rotate"]
normalized["rotate"], changed = _normalize_angles(str(original))
if changed:
logs.append(f"Rotation normalized: {original} → {normalized['rotate']}")
# Note: pan and pivot are NOT normalized - negative values will be caught by validator
# kicad-cli has a bug where it can't parse values starting with '-'
# Normalize choice values to lowercase
for param in ["side", "background", "quality"]:
if param in normalized and normalized[param]:
original = normalized[param]
normalized[param] = str(original).lower()
if normalized[param] != original:
logs.append(f"{param} lowercased: {original} → {normalized[param]}")
# Normalize boolean values
for param in ["perspective"]:
if param in normalized:
original = normalized[param]
normalized[param] = _to_bool(original)
if normalized[param] != original and not isinstance(original, bool):
logs.append(f"{param} converted to bool: {original} → {normalized[param]}")
# Normalize dimensions (must be positive integers)
for param in ["width", "height"]:
if param in normalized and normalized[param] is not None:
original = normalized[param]
try:
val = abs(int(float(original)))
if val < 1:
val = 1
normalized[param] = val
if normalized[param] != original:
logs.append(f"{param} normalized: {original} → {normalized[param]}")
except (ValueError, TypeError):
pass # Let validator catch this error
# Normalize zoom (must be positive)
if "zoom" in normalized and normalized["zoom"] is not None:
original = normalized["zoom"]
try:
val = abs(float(original))
if val <= 0:
val = 1.0
normalized["zoom"] = val
if normalized["zoom"] != original:
logs.append(f"zoom normalized: {original} → {normalized['zoom']}")
except (ValueError, TypeError):
pass
# Auto-adjust zoom for rotation if enabled
if normalized.get("auto_safe_zoom", False) and normalized.get("rotate"):
original_zoom = normalized.get("zoom", 1.0)
board_w = normalized.get("board_width", 150.0)
board_h = normalized.get("board_height", 100.0)
component_height = normalized.get("component_height", 10.0)
safety_margin = normalized.get("safety_margin", 5) / 100.0
# Debug logging
logs.append(f"[DEBUG] auto_safe_zoom: board={board_w}x{board_h}mm, rotate={normalized.get('rotate')}, zoom={original_zoom}")
rotate_str = str(normalized["rotate"])
parts = rotate_str.split(",")
if len(parts) == 3:
try:
rx, ry, rz = float(parts[0]), float(parts[1]), float(parts[2])
# Calculate expansion factor for debugging (with component height)
expansion = calculate_rotation_expansion(board_w, board_h, rx, ry, rz, component_height)
safe = calculate_safe_zoom(board_w, board_h, rx, ry, rz, component_height, safety_margin)
logs.append(f"[DEBUG] expansion={expansion:.3f}x, safe_zoom={safe:.3f}, comp_h={component_height}mm, margin={safety_margin*100:.0f}%")
if original_zoom > safe:
normalized["zoom"] = safe
logs.append(f"zoom auto-adjusted for rotation: {original_zoom} → {safe:.2f} (prevents clipping)")
else:
logs.append(f"[DEBUG] zoom {original_zoom} <= safe {safe:.2f}, no adjustment needed")
except ValueError:
pass
elif normalized.get("auto_safe_zoom", False):
logs.append(f"[DEBUG] auto_safe_zoom enabled but no rotate param found")
return normalized, logs
def _normalize_angles(rotate_str: str) -> Tuple[str, bool]:
"""
Normalize rotation angles to 0-359 range.
Args:
rotate_str: "x,y,z" format string
Returns:
Tuple of (normalized_string, was_changed)
"""
if not rotate_str:
return rotate_str, False
parts = rotate_str.split(",")
if len(parts) != 3:
return rotate_str, False
changed = False
fixed_parts = []
for p in parts:
p = p.strip()
try:
val = float(p)
original_val = val
# Normalize to 0-359 range using modulo
val = val % 360
if val != original_val:
changed = True
# Keep as int if no decimal
if val == int(val):
fixed_parts.append(str(int(val)))
else:
fixed_parts.append(str(val))
except ValueError:
fixed_parts.append(p)
return ",".join(fixed_parts), changed
def _to_bool(value) -> bool:
"""Convert various types to boolean."""
if isinstance(value, bool):
return value
if isinstance(value, str):
return value.lower() in ("true", "1", "yes", "on")
return bool(value)
def validate_and_normalize(params: Dict) -> Tuple[Dict, bool, List[ValidationResult], List[str]]:
"""
Normalize parameters and then validate them.
This is the recommended single entry point for parameter processing.
Args:
params: Dictionary of CLI parameters
Returns:
Tuple of (normalized_params, is_valid, validation_results, normalization_logs)
"""
# First normalize
normalized, norm_logs = normalize_params(params)
# Then validate the normalized params
validator = CLIValidator()
results = validator.validate(normalized)
is_valid = not validator.has_errors(results)
return normalized, is_valid, results, norm_logs
def validate_cli_params(params: Dict) -> Tuple[bool, List[ValidationResult]]:
"""
Convenience function to validate CLI parameters.
Args:
params: Dictionary of CLI parameters
Returns:
Tuple of (is_valid, results)
- is_valid: True if no errors (warnings are OK)
- results: List of all validation results
"""
validator = CLIValidator()
results = validator.validate(params)
is_valid = not validator.has_errors(results)
return is_valid, results
def get_validation_summary(params: Dict) -> str:
"""
Get a formatted validation summary string.
Args:
params: Dictionary of CLI parameters
Returns:
Formatted string with validation results
"""
validator = CLIValidator()
results = validator.validate(params)
return validator.format_results(results)