-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy pathsendto_silhouette.py
More file actions
1310 lines (1182 loc) · 59.3 KB
/
Copy pathsendto_silhouette.py
File metadata and controls
1310 lines (1182 loc) · 59.3 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
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# coding=utf-8
#
# Inkscape extension for driving a silhouette cameo
# (C) 2013 jw@suse.de. Licensed under CC-BY-SA-3.0 or GPL-2.0 at your choice.
# (C) 2014 - 2023 juewei@fabmail.org and contributors
__version__ = "1.29" # Keep in sync with sendto_silhouette.inx ca line 179
__author__ = "Juergen Weigert <juergen@fabmail.org> and contributors"
import sys, os, time, math, operator, re, subprocess
# we sys.path.append() the directory where this script lives.
sys.path.append(os.path.dirname(os.path.abspath(sys.argv[0])))
sys_platform = sys.platform.lower()
if sys_platform.startswith("win"):
sys.path.append(r"C:\Program Files\Inkscape\share\inkscape\extensions")
elif sys_platform.startswith("darwin"):
sys.path.append("/Applications/Inkscape.app/Contents/Resources/share/inkscape/extensions")
else: # linux
sys.path.append("/usr/share/inkscape/extensions")
# We will use the inkex module with the predefined Effect base class.
# As of Inkscape 1.1, inkex cannot be loaded if stdout is closed,
# which it might be if we are coming here via silhouette_multi.
# This manipulation of sys.stdout should be removed if the issue
# https://gitlab.com/inkscape/extensions/-/issues/412
# is resolved in a future version.
dummy_stdout=False
if not sys.stdout:
sys.stdout=os.fdopen(os.open(os.devnull, os.O_WRONLY|os.O_APPEND), 'w')
dummy_stdout=True
if dummy_stdout:
sys.stdout.close()
sys.stdout=None
import inkex
from inkex.extensions import EffectExtension
from inkex import Boolean, Path, ShapeElement, PathElement, Rectangle, Circle, Ellipse, Line, Polyline, Polygon, Group, Use, TextElement, Image, BaseElement, SvgDocumentElement
from inkex.transforms import Transform
from inkex.units import convert_unit
from inkex.bezier import subdiv
from gettext import gettext
from optparse import SUPPRESS_HELP
from tempfile import NamedTemporaryFile, gettempdir
from silhouette.Graphtec import SilhouetteCameo, CAMEO_MATS
from silhouette.Strategy import MatFree
from silhouette.convert2dashes import convert2dash
import silhouette.StrategyMinTraveling
import silhouette.read_dump
from silhouette.Geometry import dist_sq, XY_a
# Temporary Monkey Backport Patches to support functions that exist only after v1.2
# TODO: If support for Inkscape v1.1 is dropped then this backport can be removed
if not hasattr(inkex, "__version__") or inkex.__version__[0:3] < "1.2":
from inkex import BaseElement, SvgDocumentElement, paths
import re
# backport https://gitlab.com/inkscape/extensions/-/issues/367
BaseElement.uutounit = lambda self, v, *kwargs: float(v)
# backport https://gitlab.com/inkscape/extensions/-/merge_requests/433
Line.get_path = lambda self: 'M{0[x1]},{0[y1]} L{0[x2]},{0[y2]}'.format(self.attrib)
# backport @ matmul operator
Transform.__matmul__ = Transform.__mul__
SvgDocumentElement.viewport_width = property(lambda self: convert_unit(self.get("width"), "px") or self.get_viewbox()[2])
SvgDocumentElement.viewport_height = property(lambda self: convert_unit(self.get("height"), "px") or self.get_viewbox()[3])
SvgDocumentElement._base_scale = lambda self, unit="px": (convert_unit(1, unit) or 1.0) if not all(self.get_viewbox()[2:]) else max([convert_unit(self.viewport_width, unit) / self.get_viewbox()[2], convert_unit(self.viewport_height, unit) / self.get_viewbox()[3]]) or convert_unit(1, unit) or 1.0
BaseElement.to_dimensional = staticmethod(lambda value, to_unit="px": convert_unit(value, to_unit))
BaseElement.to_dimensionless = staticmethod(lambda value: convert_unit(value, "px"))
BaseElement.viewport_to_unit = lambda self, value, unit="px": self.to_dimensional(self.to_dimensionless(value) / self.root._base_scale(), unit)
BaseElement.unit_to_viewport = lambda self, value, unit="px": self.to_dimensional(self.to_dimensionless(value) * self.root._base_scale(), unit)
BaseElement.set_sensitive = lambda self, sensitive="true": self.set("sodipodi:insensitive", ["true", None][sensitive])
paths.strargs = lambda string, kind=float: [kind(val) for val in re.compile(r"(?:[+-]?(?:(?:(?:[0-9]+)?\.(?:[0-9]+)|(?:[0-9]+)\.)(?:[eE][+-]?(?:[0-9]+))?|(?:[0-9]+)(?:[eE][+-]?(?:[0-9]+)))|[+-]?(?:[0-9]+))").findall(string)]
# Default Logfile Filename
LOGFILE_DEFAULT_NAME = "silhouette.log"
# Autogenerated Registration Mark SVG IDs
REGMARK_LAYERNAME = 'Regmarks'
REGMARK_LAYER_ID = 'regmark'
REGMARK_TOP_LEFT_ID = 'regmark-tl'
REGMARK_TOP_RIGHT_ID = 'regmark-tr'
REGMARK_BOTTOM_LEFT_ID = 'regmark-bl'
REGMARK_SAFE_AREA_ID = 'regmark-safe-area'
REGMARK_NOTES_ID = 'regmark-notes'
class teeFile:
def __init__(self, f1, f2):
self.f1 = f1
self.f2 = f2
def __del__(self, *args):
self.close()
def write(self, content):
self.f1.write(content)
self.f2.write(content)
def close(self):
self.f1.close()
self.f2.close()
class SendtoSilhouette(EffectExtension):
"""
Inkscape Extension to send to a Silhouette Cameo
"""
# pretend no changes to skip `save()` in `InkscapeExtension.save_raw()`
has_changed = lambda *x: False
def __init__(self):
# Call the base class constructor.
EffectExtension.__init__(self)
self.warnings = {}
self.pathcount = 0
self.paths = []
self.path_page_indices = []
self.docTransform = Transform()
self.cmdfile = None
self.caffeinate_process = None
self.document_pages = None
self.active_page_indices = []
self.media_width_mm = None
self.media_height_mm = None
self.doc_reg_x = 0
self.doc_reg_y = 0
self.doc_reg_width = 0
self.doc_reg_length = 0
self.reg_origin_X = 0
self.reg_origin_Y = 0
self.reg_width = 0
self.reg_length = 0
try:
self.tty = open("/dev/tty", "w")
except:
self.tty = None
self.log = self.tty
self.default_logfile_path = os.path.join(gettempdir(), LOGFILE_DEFAULT_NAME)
def __del__(self, *args):
self.stop_macos_sleep_inhibitor()
if self.log:
self.log.close() # will always close tty if there is one
if self.cmdfile:
self.cmdfile.close() # will always try to close cmdfile
def report_sleep_inhibitor(self, message):
"""Log sleep-inhibitor messages without affecting the cutting job."""
try:
self.report(message, "log")
except Exception:
pass
def start_macos_sleep_inhibitor(self):
"""Keep macOS awake until cutting finishes or this process exits."""
if (not sys_platform.startswith("darwin") or
self.options.dry_run or self.caffeinate_process is not None):
return False
try:
self.caffeinate_process = subprocess.Popen(
["/usr/bin/caffeinate", "-i", "-w", str(os.getpid())],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except OSError as error:
self.report_sleep_inhibitor(
"Could not prevent macOS sleep: %s" % error)
return False
self.report_sleep_inhibitor("Preventing macOS sleep while cutting.")
return True
def stop_macos_sleep_inhibitor(self):
"""Stop only the caffeinate process started by this extension."""
process = self.caffeinate_process
self.caffeinate_process = None
if process is None:
return
try:
if process.poll() is None:
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=2)
except Exception as error:
self.report_sleep_inhibitor(
"Could not stop macOS sleep prevention: %s" % error)
def add_arguments(self, pars):
pars.add_argument("--active-tab", dest = "active_tab",
help=SUPPRESS_HELP)
pars.add_argument("-d", "--dashes",
dest = "dashes", type = Boolean, default = False,
help="convert paths with dashed strokes to separate subpaths for perforated cuts")
pars.add_argument("-a", "--autocrop",
dest = "autocrop", type = Boolean, default = False,
help="trim away top and left margin (before adding offsets)")
pars.add_argument("-b", "--bbox", "--bbox-only", "--bbox_only",
dest = "bboxonly", type = Boolean, default = False,
help="draft the objects bounding box instead of the objects")
pars.add_argument("-c", "--bladediameter",
dest = "bladediameter", type = float, default = 0.9,
help="[0..2.3] diameter of the used blade [mm], default = 0.9")
pars.add_argument("-C", "--cuttingmat",
choices=list(CAMEO_MATS.keys()), dest = "cuttingmat",
default = "cameo_12x12", help="Use cutting mat")
pars.add_argument("-D", "--depth",
dest = "depth", type = int, default = -1,
help="[0..10], or -1 for media default")
pars.add_argument("--log_paths",
dest = "dump_paths", type = Boolean, default = False,
help="Include final cut paths in log")
pars.add_argument("--append_logs",
dest = "append_logs", type = Boolean, default = False,
help="Append to log and dump files rather than overwriting")
pars.add_argument("--dry_run",
dest = "dry_run", type = Boolean, default = False,
help="Do not send commands to device (queries allowed)")
pars.add_argument("-g", "--strategy",
dest = "strategy", default = "mintravel",
choices=("mintravel", "mintravelfull", "mintravelfwd", "matfree", "zorder"),
help="Cutting Strategy: mintravel, mintravelfull, mintravelfwd, matfree or zorder")
pars.add_argument("--orient_paths",
dest = "orient_paths", default = "natural",
choices=("natural","desy","ascy","desx","ascx"),
help="Pre-orient paths: natural (as in svg), or [des(cending)|asc(ending)][y|x]")
pars.add_argument("--fuse_paths",
dest = "fuse_paths", type = Boolean, default = True,
help="Merge any path with predecessor that ends at its start.")
pars.add_argument("-l", "--sw_clipping",
dest = "sw_clipping", type = Boolean, default = True,
help="Enable software clipping")
pars.add_argument("-m", "--media", "--media-id", "--media_id",
dest = "media", default = "132",
choices=("100", "101", "102", "106", "111", "112", "113",
"120", "121", "122", "123", "124", "125", "126", "127", "128", "129", "130",
"131", "132", "133", "134", "135", "136", "137", "138", "300"),
help="113 = pen, 132 = printer paper, 300 = custom")
pars.add_argument("-o", "--overcut",
dest = "overcut", type = float, default = 0.5,
help="overcut on circular paths. [mm]")
pars.add_argument("-M", "--multipass",
dest = "multipass", type = int, default = 1,
help="[1..8], cut/draw each path object multiple times.")
pars.add_argument("-p", "--pressure",
dest = "pressure", type = int, default = 10,
help="[1..18], or 0 for media default")
pars.add_argument("-P", "--sharpencorners",
dest = "sharpencorners", type = Boolean, default = False,
help="Lift head at sharp corners")
pars.add_argument("--sharpencorners_start",
dest = "sharpencorners_start", type = float, default = 0.1,
help="Sharpen Corners - Start Ext. [mm]")
pars.add_argument("--sharpencorners_end",
dest = "sharpencorners_end", type = float, default = 0.1,
help="Sharpen Corners - End Ext. [mm]")
pars.add_argument("-r", "--reversetoggle",
dest = "reversetoggle", type = Boolean, default = False,
help="Cut each path the other direction. Affects every second pass when multipass.")
pars.add_argument("-s", "--speed",
dest = "speed", type = int, default = 10,
help="[1..10], or 0 for media default")
pars.add_argument("-S", "--smoothness", type = float,
dest="smoothness", default=.05, help="Smoothness of curves")
pars.add_argument("-t", "--tool",
choices=("autoblade", "cut", "pen", "default"), dest = "tool", default = None, help="Optimize for pen or knive")
pars.add_argument("-T", "--toolholder",
choices=("1", "2"), dest = "toolholder", default = None, help="[1..2]")
pars.add_argument("--preview",
dest = "preview", type = Boolean, default = True,
help="show cut pattern graphically before sending")
pars.add_argument("-V", "--version",
dest = "version", action = "version", version=__version__,
help="print the version number and exit")
pars.add_argument("-w", "--wait", "--wait-done", "--wait_done",
dest = "wait_done", type = Boolean, default = False,
help="After sending wait til device reports ready")
pars.add_argument("-x", "--x-off", "--x_off",
type = float, dest = "x_off", default = 0.0, help="X-Offset [mm]")
pars.add_argument("-y", "--y-off", "--y_off",
type = float, dest = "y_off", default = 0.0, help="Y-Offset [mm]")
pars.add_argument("-R", "--regmark",
dest = "regmark", type = Boolean, default = False,
help="The document has registration marks.")
pars.add_argument("--regsearch",
dest = "regsearch", type = Boolean, default = False,
help="Search for the registration marks.")
pars.add_argument("-Q", "--quadregmarks",
dest = "quadregmarks", type = Boolean, default = False,
help="Use 4 registration marks.")
pars.add_argument("-X", "--reg-x", "--regwidth",
type = float, dest = "regwidth", default = 0.0, help="X mark to mark distance [mm]")
pars.add_argument("-Y", "--reg-y", "--reglength",
type = float, dest = "reglength", default = 0.0, help="Y mark to mark distance [mm]")
pars.add_argument("--rego-x", "--regoriginx",
type = float, dest = "regoriginx", default = 0.0, help="X mark origin from left [mm]")
pars.add_argument("--rego-y", "--regoriginy",
type = float, dest = "regoriginy", default = 0.0, help="X mark origin from top [mm]")
pars.add_argument("-e", "--endposition", "--end-postition",
"--end_position", choices=("start", "below"),
dest = "endposition", default = "below", help="Position of head after cutting: start or below")
pars.add_argument("--end_offset", type = float,
dest = "end_offset", default = 0.0,
help="Adjustment to the position after cutting")
pars.add_argument("--logfile",
dest = "logfile", default = None,
help="Name of file in which to save log messages.")
pars.add_argument("--cmdfile",
dest = "cmdfile", default = None,
help="Name of file to save transcript of cutter commands.")
pars.add_argument("--inc_queries",
dest = "inc_queries", type = Boolean, default = False,
help="Include queries in cutter command transcript")
pars.add_argument("--force_hardware",
dest = "force_hardware", default = None,
help = "Override hardware model of cutting device.")
pars.add_argument("--connection_type",
choices=("usb", "bluetooth", "ble"),
dest = "connection_type", default = "usb",
help = "Connection type: usb, bluetooth (Classic/RFCOMM), or ble.")
pars.add_argument("--bluetooth_addr",
dest = "bluetooth_addr", default = None,
help = "Connect over Bluetooth to this MAC address (e.g. 00:1B:41:33:44:55) instead of USB. Use --bluetooth_scan to discover addresses.")
pars.add_argument("--bluetooth_channel",
dest = "bluetooth_channel", type = int, default = None,
help = "RFCOMM channel for the Bluetooth connection (default: standard channel).")
pars.add_argument("--bluetooth_scan",
dest = "bluetooth_scan", type = Boolean, default = False,
help = "List Bluetooth devices visible through the selected connection type, then stop.")
pars.add_argument("--bluetooth_name",
dest = "bluetooth_name", default = "CAMEO",
help = "Connect over BLE to this advertised device name (default: CAMEO).")
pars.add_argument("--bluetooth_identifier",
dest = "bluetooth_identifier", default = None,
help = "Optional platform-local BLE identifier (a CoreBluetooth UUID on macOS, not a portable MAC address).")
# For Multi-Action
pars.add_argument("--skip_init",
dest = "skip_init", type = Boolean, default = False,
help = "Skip any setup, such as regmark searching (for Multi-Action).")
pars.add_argument("--skip_reset",
dest = "skip_reset", type = Boolean, default = False,
help = "Skip resetting to home at the end (for Multi-Action).")
# Can't set up the log here because arguments have not yet been parsed;
# defer that to the top of the effect() method, which is where all
# of the real activity happens.
def report(self, message, level):
"""
Display `message` to the appropriate output stream(s).
Each of the following `level` values encompasses all of the later ones:
error - display to standard error
log - record in logfile if there is one
tty - write to tty and flush if there is one
"""
if level == 'tty':
if self.tty:
print(message, file=self.tty)
self.tty.flush()
return
if level == 'log' or level == 'error':
if self.log:
print(message, file=self.log)
# That handles the tty also, because of the tee, but
# we have to flush the tty:
if self.tty:
self.tty.flush()
if level == 'log':
return
print(message, file=sys.stderr)
if level != 'error':
# oops accidentally used an invalid level
print(f" ... WARNING: message issued at invalid level {level}",
file=sys.stderr)
def report_bluetooth_scan(self):
"""List devices for the selected Bluetooth transport.
Discovery is deliberately unfiltered so users can verify that scanning
works even when no Silhouette cutter is nearby.
"""
connection_type = self.options.connection_type
heading = "Bluetooth LE" if connection_type == "ble" else "Bluetooth Classic"
try:
if connection_type == "ble":
from silhouette.BLETransport import BLETransport
if not BLETransport.is_available():
self.report("Bluetooth LE scanning requires the optional 'bleak' package.", 'error')
return
devices = BLETransport.discover(name_filter=None)
identifier_label = "local identifier"
else:
from silhouette.Transport import BluetoothTransport
if not BluetoothTransport.is_available():
self.report("Bluetooth Classic is not supported by this Python build/platform.", 'error')
return
devices = BluetoothTransport.discover(name_filter=None)
identifier_label = "MAC address"
except Exception as e:
self.report("%s scan failed: %s" % (heading, e), 'error')
return
if not devices:
self.report("No %s devices found." % heading, 'error')
return
lines = ["Found %d %s device(s):" % (len(devices), heading)]
for identifier, name in devices:
lines.append(" %s %s" % (identifier, name or "(unnamed)"))
lines.append("")
if connection_type == "ble":
lines.append("Use the advertised name for portable BLE selection, or copy the %s for this computer only."
% identifier_label)
else:
lines.append("Copy the %s of the cutter into the Bluetooth MAC address field."
% identifier_label)
self.report("\n".join(lines), 'error')
def require_media_loaded(self, dev):
"""Return cutter status or fail before setup when media is absent.
A cutter without media must not receive setup or geometry commands.
Close the transport immediately so Bluetooth devices can resume
advertising and a corrected job can reconnect promptly.
"""
transport = getattr(dev, "transport", None)
try:
state = dev.status()
except Exception as error:
if transport is not None:
transport.close()
raise ValueError(
"Could not query cutter status before starting: %s" % error
) from error
self.report("status=%s" % state, 'log')
if state in ("ready", "moving"):
return state
if transport is not None:
transport.close()
if state == "unloaded":
raise ValueError(
"No media is loaded. Load media into the cutter and try again."
)
raise ValueError(
"Cannot determine whether media is loaded (status=%s). Job aborted."
% state
)
def plotPath(self, path: Path, page_index=None):
"""
Plot the path after smoothing curves to straights
"""
# convert into a cubicsuperpath (list of beziers)...
p = path.to_superpath()
# p is now a list of lists of cubic beziers [control pt1, control pt2, endpoint]
# where the start-point is the last point in the previous segment.
for sp in p:
# subdivide beziers into smooth curved parts
subdiv(sp, self.options.smoothness)
# extract path
if len(sp) > 1:
self.paths.append([tuple(csp[1]) for csp in sp])
self.path_page_indices.append(page_index)
def get_document_pages(self):
"""Return Inkscape page rectangles in document viewport coordinates."""
if self.document_pages is not None:
return self.document_pages
pages = []
namedview = getattr(self.svg, "namedview", None)
if namedview is not None and hasattr(namedview, "get_pages"):
page_elements = namedview.get_pages()
elif namedview is not None:
page_elements = [
node for node in namedview
if isinstance(node.tag, str) and node.tag.endswith("}page")
]
else:
page_elements = []
for page in page_elements:
pages.append({
"id": page.get("id"),
"x": float(getattr(page, "x", page.get("x", 0))),
"y": float(getattr(page, "y", page.get("y", 0))),
"width": float(getattr(page, "width", page.get("width", 0))),
"height": float(getattr(page, "height", page.get("height", 0))),
})
if not pages:
viewbox = self.svg.get_viewbox()
if viewbox[2] and viewbox[3]:
pages.append({
"id": None,
"x": viewbox[0],
"y": viewbox[1],
"width": viewbox[2],
"height": viewbox[3],
})
else:
# Inkex 1.1 and 1.2 report a zero-sized viewBox for legacy
# documents that specify only width and height.
pages.append({
"id": None,
"x": 0,
"y": 0,
"width": self.svg.viewport_width,
"height": self.svg.viewport_height,
"width_mm": self.svg.to_dimensional(
self.svg.viewport_width, "mm"
),
"height_mm": self.svg.to_dimensional(
self.svg.viewport_height, "mm"
),
})
self.document_pages = pages
return pages
def page_index_for_bbox(self, bbox):
"""Find the page containing a document-coordinate bounding box."""
if bbox is None:
return None
left, right = bbox.left, bbox.right
top, bottom = bbox.top, bbox.bottom
center_x = (left + right) / 2
center_y = (top + bottom) / 2
pages = self.get_document_pages()
# The center is stable for paths touching a page edge or having no area.
for index, page in enumerate(pages):
if (page["x"] <= center_x <= page["x"] + page["width"] and
page["y"] <= center_y <= page["y"] + page["height"]):
return index
# For an object crossing a page edge, use the page with the largest
# intersection. Objects entirely on the canvas remain document-global.
best_index = None
best_overlap = 0
for index, page in enumerate(pages):
overlap_x = max(0, min(right, page["x"] + page["width"]) -
max(left, page["x"]))
overlap_y = max(0, min(bottom, page["y"] + page["height"]) -
max(top, page["y"]))
overlap = overlap_x * overlap_y
if overlap > best_overlap:
best_index = index
best_overlap = overlap
return best_index
def sync_page_settings(self):
"""Select media geometry from the pages containing the cut paths."""
pages = self.get_document_pages()
used = sorted({index for index in self.path_page_indices
if index is not None})
if not used:
used = [0]
self.active_page_indices = used
sizes = [(
pages[index]["width_mm"]
if "width_mm" in pages[index]
else self.svg.unit_to_viewport(pages[index]["width"], "mm"),
pages[index]["height_mm"]
if "height_mm" in pages[index]
else self.svg.unit_to_viewport(pages[index]["height"], "mm"),
) for index in used]
first_width, first_height = sizes[0]
if any(abs(width - first_width) > 0.01 or
abs(height - first_height) > 0.01
for width, height in sizes[1:]):
raise ValueError(
"Selected paths span pages with different sizes. "
"Send one page size at a time."
)
self.media_width_mm = first_width
self.media_height_mm = first_height
page_names = ", ".join(
pages[index]["id"] or str(index + 1) for index in used
)
self.report(
f"Using page-local coordinates for page(s) {page_names}: "
f"{first_width:g} x {first_height:g} mm", "log"
)
def recursivelyTraverseSvg(self, aNodeList,
parent_visibility="visible",
parent_transform: Transform=None):
"""
Recursively traverse the svg file to plot out all of the
paths. The function keeps track of the composite transformation
that should be applied to each path.
This function handles path, group, line, rect, polyline, polygon,
circle, ellipse and use (clone) elements. Notable elements not
handled include text. Unhandled elements should be converted to
paths in Inkscape.
"""
for node in aNodeList:
# Ignore invisible nodes
if isinstance(node, BaseElement):
# try:
# # Inkex 1.2: `cascaded_style()` considers CSS (has bad performance!!)
# get = node.cascaded_style().get
# except:
get = lambda attr, default: node.style.get(attr, node.get(attr, default))
if get("display", "inline") == "none":
continue
if not float(get("opacity", 1.0)):
continue
v = get("visibility", parent_visibility)
if v == "inherit":
v = parent_visibility
# NOTE: inkex 1.1 has composed_transform only on ShapeElement
if isinstance(node, ShapeElement):
if parent_transform==None:
# init my_transform // needed for selection by `--id` param
my_transform = node.composed_transform()
else:
# NOTE: <<< transforms operate from right (detail) to left (whole)
my_transform = parent_transform @ node.transform
if isinstance(node, Group):
# Check if layer name is referring to cutting mat, registration mark or print layer
if node.label:
if "cuttingmat" in node.label.lower():
self.report(f"layer '{node.label}' is a cutting mat layer - skipped", 'log')
continue
if "regmark" in node.label.lower():
self.report(f"layer '{node.label}' is a registration mark layer - skipped", 'log')
continue
if "print" in node.label.lower():
self.report(f"layer '{node.label}' is a print layer - skipped", 'log')
continue
self.recursivelyTraverseSvg(node, parent_visibility=v, parent_transform=my_transform)
elif isinstance(node, Use):
# A <use> element refers to another element via href="#blah" attribute.
# We then recursively process the referenced element.
#
# Notes:
# . Even if the <use> element has visibility="hidden", SVG still calls
# for processing the referenced element. The referenced element is
# hidden only if its visibility is "inherit" or "hidden".
refnode = node.href
if refnode is not None:
# apply any necessary (x, y) translation
x = float(node.get("x", 0.0))
y = float(node.get("y", 0.0))
# NOTE: <<< transforms operate from right (detail) to left (whole)
my_transform = my_transform @ Transform(translate=(x, y))
self.recursivelyTraverseSvg([refnode], parent_visibility=v, parent_transform=my_transform)
elif isinstance(node, (PathElement, Rectangle, Circle, Ellipse, Line, Polyline, Polygon)):
if v == "hidden" or v == "collapse":
continue
# convert element to path
node = node.to_path_element()
# apply dashed style
if self.options.dashes:
convert2dash(node)
# Resolve the page after applying the element's complete SVG
# transform, but before converting viewport units to mm. In a
# multi-page Inkscape document, page 2+ objects retain their
# canvas offset unless it is explicitly removed here.
document_path = node.path.transform(my_transform)
page_index = self.page_index_for_bbox(document_path.bounding_box())
page_transform = Transform()
if page_index is not None:
page = self.get_document_pages()[page_index]
page_transform = Transform(
translate=(-page["x"], -page["y"])
)
# NOTE: <<< transforms operate from right (detail) to left (whole)
transform = self.docTransform @ page_transform
self.pathcount += 1
self.plotPath(document_path.transform(transform), page_index)
elif isinstance(node, TextElement):
texts = []
plaintext = ""
for tnode in node.iterfind(".//"): # all subtree
if tnode is not None and tnode.text is not None:
texts.append(tnode.text)
if len(texts):
if "text" not in self.warnings:
inkex.errormsg(gettext("Warning: unable to draw text; " +
"please convert it to a path first. Or consider using the " +
"Hershey Text extension which can be installed in the " +
"'Render' category of extensions."))
self.warnings["text"] = 1
plaintext = "', '".join(texts)
self.report(f"Text ignored: '{plaintext}'", 'error')
elif isinstance(node, Image):
if "image" not in self.warnings:
inkex.errormsg(gettext("Warning: unable to draw bitmap images; " +
"please convert them to line art first. Consider using the 'Trace bitmap...' " +
"tool of the 'Path' menu. Mac users please note that some X11 settings may " +
"cause cut-and-paste operations to paste in bitmap copies."))
self.warnings["image"] = 1
elif isinstance(node, BaseElement):
# This is another known subclass of `BaseElement`
pass
elif not isinstance(node.tag, str):
# This is likely an XML processing instruction such as an XML
# comment. lxml uses a function reference for such node tags
# and as such the node tag is likely not a printable string.
# Further, converting it to a printable string likely won't
# be very useful.
pass
else:
if str(node.tag) not in self.warnings:
t = str(node.tag).split("}")
self.report(gettext(
f"Warning: unable to draw <{str(t[-1])}> object,"
f"please convert it to a path first."),
'error')
self.warnings[str(node.tag)] = 1
def initDocScale(self):
"""
Set up the document-wide transform in the event that the document has an SVG viewbox
"""
self.report(f"7 svg.viewport_height = {self.svg.viewport_height}", 'tty')
self.report(f"8 svg.viewport_width = {self.svg.viewport_width}", 'tty')
self.docTransform = Transform(scale=(self.svg._base_scale("mm")))
def regmark_settings_from_group(self, group, page_index):
"""Read and validate renderer metadata from one page's regmark layer."""
notes = " ".join(
"".join(node.itertext())
for node in group.iter()
if isinstance(node, TextElement)
)
match = re.search(
r"Left\s*=\s*([-+0-9.eE]+)\s*mm.*?"
r"Top\s*=\s*([-+0-9.eE]+)\s*mm.*?"
r"X\s*=\s*([-+0-9.eE]+)\s*mm.*?"
r"Y\s*=\s*([-+0-9.eE]+)\s*mm",
notes,
re.DOTALL,
)
if match is None:
return None
settings = tuple(float(value) for value in match.groups())
page = self.get_document_pages()[page_index]
marker_boxes = []
marker_types = (PathElement, Rectangle, Circle, Ellipse,
Line, Polyline, Polygon)
for node in group.iter():
if not isinstance(node, marker_types):
continue
bbox = node.bounding_box(transform=True)
if bbox is None:
continue
left = self.svg.unit_to_viewport(bbox.left - page["x"], "mm")
right = self.svg.unit_to_viewport(bbox.right - page["x"], "mm")
top = self.svg.unit_to_viewport(bbox.top - page["y"], "mm")
bottom = self.svg.unit_to_viewport(bbox.bottom - page["y"], "mm")
# Exclude the large safe-area shape, which touches every corner.
if right - left <= 40 and bottom - top <= 40:
marker_boxes.append((left, right, top, bottom))
origin_x, origin_y, width, length = settings
required_points = (
(origin_x, origin_y),
(origin_x + width, origin_y),
(origin_x, origin_y + length),
)
tolerance = 1.0
for x, y in required_points:
if not any(
left - tolerance <= x <= right + tolerance and
top - tolerance <= y <= bottom + tolerance
for left, right, top, bottom in marker_boxes
):
return None
return settings
def page_regmark_settings(self, page_index):
"""Find registration marks belonging to a specific Inkscape page."""
for group in self.svg.iter():
if not isinstance(group, Group):
continue
if not group.label or "regmark" not in group.label.lower():
continue
if (group.get("id") == REGMARK_LAYER_ID and any(
child.get("id", "").startswith(REGMARK_LAYER_ID + "-page-")
for child in group)):
# Multi-page marks live in page-specific groups inside this
# common layer; inspect the page group, not their union.
continue
parent = group.getparent()
parent_transform = (
parent.composed_transform()
if hasattr(parent, "composed_transform") else Transform()
)
if self.page_index_for_bbox(group.bounding_box(parent_transform)) != page_index:
continue
settings = self.regmark_settings_from_group(group, page_index)
if settings is not None:
return settings
# Compatibility fallback for older generated files without notes.
top_left = self.svg.getElementById(REGMARK_TOP_LEFT_ID)
top_right = self.svg.getElementById(REGMARK_TOP_RIGHT_ID)
bottom_left = self.svg.getElementById(REGMARK_BOTTOM_LEFT_ID)
if top_left is None or top_right is None or bottom_left is None:
return None
tl_bbox = top_left.bounding_box(transform=True)
tr_bbox = top_right.bounding_box(transform=True)
bl_bbox = bottom_left.bounding_box(transform=True)
if self.page_index_for_bbox(tl_bbox) != page_index:
return None
page = self.get_document_pages()[page_index]
origin_x = self.svg.unit_to_viewport(tl_bbox.left - page["x"], "mm")
origin_y = self.svg.unit_to_viewport(tl_bbox.top - page["y"], "mm")
width = self.svg.unit_to_viewport(tr_bbox.right - page["x"], "mm") - origin_x
length = self.svg.unit_to_viewport(bl_bbox.bottom - page["y"], "mm") - origin_y
return origin_x, origin_y, width, length
def detect_doc_regmark(self):
"""
This scans the svg document for svg element relating to an autogenerated registration mark
that can be created by a seperate registration mark renderer in this extention.
From there the registration mark setting can be derived from it's offset.
"""
# Reset detected regmark offsets
self.doc_reg_x = 0
self.doc_reg_y = 0
self.doc_reg_width = 0
self.doc_reg_length = 0
page_indices = self.active_page_indices or [0]
page_settings = []
for page_index in page_indices:
settings = self.page_regmark_settings(page_index)
if settings is None:
return
page_settings.append(settings)
first = page_settings[0]
if any(any(abs(actual - expected) > 0.01
for actual, expected in zip(settings, first))
for settings in page_settings[1:]):
raise ValueError(
"Selected Print & Cut paths span pages with different "
"registration-mark geometry. Send one page at a time."
)
(self.doc_reg_x, self.doc_reg_y,
self.doc_reg_width, self.doc_reg_length) = first
self.report(f"Detected Existing Registration Mark:: mark distance from document: Left={self.doc_reg_x}mm, Top={self.doc_reg_y}mm; mark to mark distance: X={self.doc_reg_width}mm, Y={self.doc_reg_length}mm;", 'log')
def sync_regmark_settings(self):
"""
Syncronise regmark settings.
Settings is prioritised based first on user input, existing regmarks in document then page derived values
"""
self.detect_doc_regmark()
self.reg_origin_X = self.options.regoriginx or self.doc_reg_x
self.reg_origin_Y = self.options.regoriginy or self.doc_reg_y
media_width = self.media_width_mm or convert_unit(self.svg.viewport_width, "mm")
media_height = self.media_height_mm or convert_unit(self.svg.viewport_height, "mm")
self.reg_width = self.options.regwidth or self.doc_reg_width or media_width - self.reg_origin_X * 2
self.reg_length = self.options.reglength or self.doc_reg_length or media_height - self.reg_origin_Y * 2
self.report(f"Using Registration Mark:: mark distance from document: Left={self.reg_origin_X}mm, Top={self.reg_origin_Y}mm; mark to mark distance: X={self.reg_width}mm, Y={self.reg_length}mm;", 'log')
@staticmethod
def is_closed_path(path) -> bool:
"""Is this path closed?"""
return dist_sq(XY_a(path[0]), XY_a(path[-1])) < 0.01
def logEnvironment(self):
"""Log the specific environment conditions"""
try: # inkex < 1.2 has no version definition and no command
# log environment information
self.report(inkex.command.inkscape('--version').rstrip(), 'log') # Inkscape version
self.report("Inkex: %s" % (inkex.__version__), 'log')
except:
pass
finally:
self.report("Inkscape-Silhouette: %s" % (__version__), 'log') # Plugin version
self.report("Path: %s" % (__file__), 'log')
self.report("Python: %s" % (sys.executable), 'log')
self.report("Version: %s" % (sys.version), 'log')
self.report("Platform: %s" % (sys.platform), 'log')
self.report("Arguments: %s" % (" ".join(sys.argv)), 'log')
def writeProgress(self, done, total, msg):
"""Show the current progress"""
if "write_start_tstamp" not in self.__dict__:
self.write_start_tstamp = time.time()
self.device_buffer_perc = 0.0
perc = 100.*done/total
if time.time() - self.write_start_tstamp < 1.0:
self.device_buffer_perc = perc
buf = ""
if self.device_buffer_perc > 1.0:
buf = " (+%d%%)" % (self.device_buffer_perc+.5)
self.report("%d%%%s %s\r" % (perc-self.device_buffer_perc+.5,
buf, msg),
'tty')
@staticmethod
def preorientPaths(paths, index, ordered) -> list:
"""Reorder paths along X or Y axis, ascending or descending"""
oldpaths = paths
paths = []
oldpaths.reverse() # Since popping from old and appending to new will
# itself reverse
while oldpaths:
curpath = oldpaths.pop()
if ordered(curpath[0][index], curpath[-1][index]):
curpath.reverse()
newpath = [curpath.pop()]
while curpath:
if ordered(newpath[-1][index],curpath[-1][index]):
newpath.append(curpath.pop())
else:
if len(newpath) == 1:
# Have to make some progress:
newpath = [curpath[-1], newpath[0]]
# Don't leave behind an orphan
if len(curpath) == 1:
curpath = []
else:
# Have to put end of newpath back onto curpath to
# keep the segment between it and rest of curpath:
curpath.append(newpath[-1])
break # stop collecting an ordered segment of curpath
if curpath: # Some of curpath is left because it was out of order
oldpaths.append(curpath)
paths.append(newpath)
return paths
def multipassOvercut(self, paths, multipass, reversetoggle, overcut):
"""Handle multipass & overcut"""
cut = []
for path in paths:
multipath = []
multipath.extend(path)
for i in range(1, multipass):
# if reverse continue path without lifting, instead turn with rotating knife
if (reversetoggle):
path = list(reversed(path))
multipath.extend(path[1:])
# if closed path (end = start) continue path without lifting
elif self.is_closed_path(path):
multipath.extend(path[1:])
# else start a new path
else:
cut.append(path)
# on a closed path some overlapping doesn't harm, limited to a maximum of one additional round
overcut = overcut
if (overcut > 0) and self.is_closed_path(path):
precut = overcut
pfrom = path[-1]
for pprev in reversed(path[:-1]):