Clipboard.py 7.44 KB
Newer Older
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
# -*- coding: utf-8 -*-
"""
$Id$

Copyright 2011 Lars Kruse <devel@sumpfralle.de>

This file is part of PyCAM.

PyCAM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

PyCAM is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with PyCAM.  If not, see <http://www.gnu.org/licenses/>.
"""

import StringIO
# imported later (on demand)
#import gtk

import pycam.Plugins
from pycam.Utils.locations import get_all_program_locations


CLIPBOARD_TARGETS = {
        "dxf": ("image/vnd.dxf", ),
        "ps": ("application/postscript", ),
        "stl": ("application/sla", ),
        "svg": ("image/x-inkscape-svg", "image/svg+xml"),
}


class Clipboard(pycam.Plugins.PluginBase):

    UI_FILE = "clipboard.ui"
    DEPENDS = ["Models"]
43
    CATEGORIES = ["System"]
44 45 46 47 48

    def setup(self):
        if self.gui:
            import gtk
            self._gtk = gtk
49
            self._gtk_handlers = []
50 51
            self.clipboard = self._gtk.clipboard_get()
            self.core.set("clipboard-set", self._copy_text_to_clipboard)
52 53
            self._gtk_handlers.append((self.clipboard, "owner-change",
                    self._update_clipboard_widget))
54
            # menu item and shortcut
55
            self.copy_action = self.gui.get_object("CopyModelToClipboard")
56 57
            self._gtk_handlers.append((self.copy_action, "activate",
                    self.copy_model_to_clipboard))
58 59
            self.register_gtk_accelerator("clipboard", self.copy_action,
                    "<Control>c", "CopyModelToClipboard")
60 61
            self.core.register_ui("edit_menu", "CopyModelToClipboard",
                    self.copy_action, 20)
62
            self.paste_action = self.gui.get_object("PasteModelFromClipboard")
63 64
            self._gtk_handlers.append((self.paste_action, "activate",
                    self.paste_model_from_clipboard))
65 66
            self.register_gtk_accelerator("clipboard", self.paste_action,
                    "<Control>v", "PasteModelFromClipboard")
67 68
            self.core.register_ui("edit_menu", "PasteModelFromClipboard",
                    self.paste_action, 25)
69 70 71 72
            self._event_handlers = (("model-selection-changed",
                    self._update_clipboard_widget), )
            self.register_event_handlers(self._event_handlers)
            self.register_gtk_handlers(self._gtk_handlers)
73 74 75
            self._update_clipboard_widget()
        return True

76 77 78
    def teardown(self):
        if self.gui:
            self.unregister_gtk_accelerator("clipboard", self.copy_action)
79
            self.core.unregister_ui("edit_menu", self.copy_action)
80
            self.unregister_gtk_accelerator("clipboard", self.paste_action)
81
            self.core.unregister_ui("edit_menu", self.paste_action)
82 83
            self.unregister_event_handlers(self._event_handlers)
            self.unregister_gtk_handlers(self._gtk_handlers)
84 85
            self.core.set("clipboard-set", None)

86 87 88 89
    def _get_exportable_models(self):
        models = self.core.get("models").get_selected()
        exportable = []
        for model in models:
90
            if model.model.is_export_supported():
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
                exportable.append(model)
        return exportable

    def _update_clipboard_widget(self, widget=None, data=None):
        models = self._get_exportable_models()
        # copy button
        self.gui.get_object("CopyModelToClipboard").set_sensitive(
                len(models) > 0)
        data, importer = self._get_data_and_importer_from_clipboard()
        paste_button = self.gui.get_object("PasteModelFromClipboard")
        paste_button.set_sensitive(not data is None)

    def _copy_text_to_clipboard(self, text, targets=None):
        if targets is None:
            self.clipboard.set_text(text)
        else:
            if targets in CLIPBOARD_TARGETS:
                targets = CLIPBOARD_TARGETS[targets]
            clip_targets = [(key, self._gtk.TARGET_OTHER_WIDGET, index)
                    for index, key in enumerate(targets)]
            def get_func(clipboard, selectiondata, info, (text, clip_type)):
                selectiondata.set(clip_type, 8, text)
            if "svg" in "".join(targets).lower():
                # Inkscape for Windows strictly requires the BITMAP type
                clip_type = self._gtk.gdk.SELECTION_TYPE_BITMAP
            else:
                clip_type = self._gtk.gdk.SELECTION_TYPE_STRING
            result = self.clipboard.set_with_data(clip_targets, get_func,
                    lambda *args: None, (text, clip_type))
            self.clipboard.store()

    def copy_model_to_clipboard(self, widget=None):
        models = self._get_exportable_models()
        if not models:
            return
        text_buffer = StringIO.StringIO()
        # TODO: use a better way to discover the "merge" ability
        def same_type(m1, m2):
            return isinstance(m1, pycam.Geometry.Model.ContourModel) == \
                    isinstance(m2, pycam.Geometry.Model.ContourModel)
131
        merged_model = models.pop(0).model
132 133
        for model in models:
            # merge only 3D _or_ 2D models (don't mix them)
134 135
            if same_type(merged_model, model.model):
                merged_model += model.model
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
        # TODO: add "comment=get_meta_data()" here
        merged_model.export(unit=self.core.get("unit")).write(text_buffer)
        text_buffer.seek(0)
        is_contour = isinstance(merged_model, pycam.Geometry.Model.ContourModel)
        # TODO: this should not be decided here
        if is_contour:
            targets = CLIPBOARD_TARGETS["svg"]
        else:
            targets = CLIPBOARD_TARGETS["stl"]
        self._copy_text_to_clipboard(text_buffer.read(), targets)

    def _get_data_and_importer_from_clipboard(self):
        for targets, filename in ((CLIPBOARD_TARGETS["svg"], "foo.svg"),
               (CLIPBOARD_TARGETS["stl"], "foo.stl"),
               (CLIPBOARD_TARGETS["ps"], "foo.ps"),
               (CLIPBOARD_TARGETS["dxf"], "foo.dxf")):
            for target in targets:
                data = self.clipboard.wait_for_contents(target)
                if not data is None:
                    importer = pycam.Importers.detect_file_type(filename)[1]
                    return data, importer
        return None, None

    def paste_model_from_clipboard(self, widget=None):
        data, importer = self._get_data_and_importer_from_clipboard()
        progress = self.core.get("progress")
        if data:
            progress.update(text="Loading model from clipboard")
            text_buffer = StringIO.StringIO(data.data)
            model = importer(text_buffer,
                    program_locations=get_all_program_locations(self.core),
                    unit=self.core.get("unit"),
                    fonts_cache=self.core.get("fonts"),
                    callback=progress.update)
            if model:
171
                models = self.core.get("models")
172
                self.log.info("Loaded a model from clipboard")
173
                models.add_model(model, name_template="Pasted model #%d")
174 175 176 177 178 179
            else:
                self.log.warn("Failed to load a model from clipboard")
        else:
            self.log.warn("The clipboard does not contain suitable data")
        progress.finish()