summaryrefslogtreecommitdiff
path: root/lib/extensions/output.py
blob: f3bb0a8028de2c56283df2559a476a9fd377f7fa (plain)
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
import sys
import traceback
import os
import inkex
import tempfile

from .base import InkstitchExtension
from ..i18n import _
from ..output import write_embroidery_file
from ..stitch_plan import patches_to_stitch_plan
from ..svg import render_stitch_plan, PIXELS_PER_MM
from ..utils.io import save_stdout

class Output(InkstitchExtension):
    def __init__(self, *args, **kwargs):
        InkstitchExtension.__init__(self)
        self.OptionParser.add_option("-c", "--collapse_len_mm",
                                     action="store", type="float",
                                     dest="collapse_length_mm", default=3.0,
                                     help="max collapse length (mm)")
        self.OptionParser.add_option("-f", "--format",
                                     dest="file_extension",
                                     help="file extension to output (example: DST)")

    def effect(self):
        if not self.get_elements():
            return

        patches = self.elements_to_patches(self.elements)
        stitch_plan = patches_to_stitch_plan(patches, self.options.collapse_length_mm * PIXELS_PER_MM)

        temp_file = tempfile.NamedTemporaryFile(suffix=".%s" % self.options.file_extension, delete=False)

        # in windows, failure to close here will keep the file locked
        temp_file.close()

        write_embroidery_file(temp_file.name, stitch_plan, self.document.getroot())

        if sys.platform == "win32":
            import msvcrt
            msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

        # inkscape will read the file contents from stdout and copy
        # to the destination file that the user chose
        with open(temp_file.name, "rb") as output_file:
            sys.stdout.write(output_file.read())
            sys.stdout.flush()

        # clean up the temp file
        os.remove(temp_file.name)

        # don't let inkex output the SVG!
        sys.exit(0)