def exportDocument(self, document, directory):
        if document is not None:
            self.json = {
                "skeleton": {
                    "images": directory
                },
                "bones": [{
                    "name": "root"
                }],
                "slots": [],
                "skins": {
                    "default": {}
                },
                "animations": {}
            }
            self.spineBones = self.json['bones']
            self.spineSlots = self.json['slots']
            self.spineSkins = self.json['skins']['default']

            Krita.instance().setBatchmode(True)
            self.document = document
            self._export(document.rootNode(), directory)
            Krita.instance().setBatchmode(False)
            with open('{0}/{1}'.format(directory, 'spine.json'),
                      'w') as outfile:
                json.dump(self.json, outfile, indent=2)
        else:
            self._alert("Please select a Document")
    def exportDocument(self):
        document = Krita.instance().activeDocument()

        if document is not None:
            if not self.directory:
                self.directory = os.path.dirname(document.fileName()) if document.fileName() else os.path.expanduser("~")
            self.directory = QFileDialog.getExistingDirectory(None, "Select a folder", self.directory, QFileDialog.ShowDirsOnly)

            if not self.directory:
                self._alert('Abort!')
                return

            self.json = {
                "skeleton": {"images": self.directory},
                "bones": [{"name": "root"}],
                "slots": [],
                "skins": {"default": {}},
                "animations": {}
            }
            self.spineBones = self.json['bones']
            self.spineSlots = self.json['slots']
            self.spineDefaultSkin = self.json['skins']['default']

            Krita.instance().setBatchmode(True)
            self.document = document
            self._export(document.rootNode(), self.directory)
            Krita.instance().setBatchmode(False)
            with open('{0}/{1}'.format(self.directory, 'spine.json'), 'w') as outfile:
                json.dump(self.json, outfile, indent=2)
            self._alert("Export Successful")
        else:
            self._alert("Please select a Document")
Пример #3
0
def _active_document():
    """
    Returns the current document.
    """
    if not Krita.instance():
        return None

    if not Krita.instance().documents():
        return None

    return Krita.instance().activeDocument()
Пример #4
0
    def __initialiseDoc(self):
        """Initialise temporary document"""
        self.__calculateBounds()

        # The __tmpDoc contain a flatened copy of current document
        self.__tmpDoc = Krita.instance().createDocument(
            self.__boundsSource.width(), self.__boundsSource.height(),
            "Jpeg Export - Temporary preview", self.__doc.colorModel(),
            self.__doc.colorDepth(), self.__doc.colorProfile(),
            self.__doc.resolution())
        self.__tmpDocTgtNode = self.__tmpDoc.createNode(
            "Preview", "paintlayer")
        #self.__tmpDocTgtNode.setPixelData(self.__doc.pixelData(self.__boundsSource.x(), self.__boundsSource.y(), self.__boundsSource.width(), self.__boundsSource.height()), 0, 0, self.__boundsSource.width(), self.__boundsSource.height() )
        self.__tmpDoc.rootNode().addChildNode(self.__tmpDocTgtNode, None)
        self.__tmpDoc.setBatchmode(True)
        # force jpeg export
        self.timerEvent(None)

        # The __tmpDocPreview contain the Jpeg file for preview
        self.__tmpDocPreview = Krita.instance().createDocument(
            self.__boundsSource.width(), self.__boundsSource.height(),
            "Jpeg Export - Temporary preview", self.__doc.colorModel(),
            self.__doc.colorDepth(), self.__doc.colorProfile(),
            self.__doc.resolution())
        # add original document content, as reference for diff
        self.__tmpDocPreviewSrcNode = self.__tmpDocPreview.createNode(
            "Source", "paintlayer")
        #self.__tmpDocPreviewSrcNode.setPixelData(self.__doc.pixelData(self.__boundsSource.x(), self.__boundsSource.y(), self.__boundsSource.width(), self.__boundsSource.height()), 0, 0, self.__boundsSource.width(), self.__boundsSource.height() )
        self.__tmpDocPreview.rootNode().addChildNode(
            self.__tmpDocPreviewSrcNode, None)
        # add file layer linked to exported jpeg document, to see preview
        self.__tmpDocPreviewFileNode = self.__tmpDocPreview.createFileLayer(
            "Preview", self.__tmpExportFile, "None")
        self.__tmpDocPreview.rootNode().addChildNode(
            self.__tmpDocPreviewFileNode, None)
        self.__tmpDocPreview.setBatchmode(True)
        self.__tmpDocPreview.setFileName(self.__tmpExportPreviewFile)

        Krita.instance().activeWindow().addView(
            self.__tmpDocPreview)  # shows it in the application

        #self.lblDocDimension.setText(i18n(f"Dimensions: {self.__tmpDoc.width()}x{self.__tmpDoc.height()}"))

        scrollbars = EKritaWindow.scrollbars()
        if scrollbars:
            self.__viewScrollbarH, self.__viewScrollbarV = scrollbars
            self.__viewScrollbarH.sliderMoved.connect(self.__updatePosition)
            self.__viewScrollbarV.sliderMoved.connect(self.__updatePosition)
            self.__updatePosition()

        self.__updateDoc()
        self.__renderModeChanged()
Пример #5
0
    def setup(self):
        """Is executed at Krita's startup"""
        @pyqtSlot()
        def windowCreated():
            # the best place to initialise controller (just after main window is created)
            self.__initUiController(True)

        if not self.__isKritaVersionOk:
            return

        if checkKritaVersion(5, 0, 0):
            # windowCreated signal has been implemented with krita 5.0.0
            Krita.instance().notifier().windowCreated.connect(windowCreated)
Пример #6
0
    def __windowCreated(self):
        """Main window has been created"""
        def aboutToShowFileMenu():
            self.__action.setEnabled(
                len(Krita.instance().activeWindow().views()) > 0)

        menuFile = None
        actionRef = None

        # search for menu 'File'
        menuFile = Krita.instance().activeWindow().qwindow().findChild(
            QMenu, 'file')

        if isinstance(menuFile, QMenu):
            # search for 'Export Advanced...' action
            actionRef = Krita.instance().action('file_export_advanced')

            if actionRef:
                # move action to right place
                menuFile.removeAction(self.__action)
                menuFile.insertAction(actionRef, self.__action)
            else:
                # not found??
                # fallback
                actionRef = Krita.instance().action('file_export_file')

                getNext = False
                for action in menuFile.actions():
                    if action.objectName() == 'file_export_file':
                        getNext = True
                    elif getNext:
                        actionRef = action
                        break

            if actionRef:
                # move action to right place
                menuFile.removeAction(self.__action)
                menuFile.insertAction(actionRef, self.__action)
            else:
                qError(
                    'Unable to find <file_export_advanced> neither <file_export_file>!'
                )

            # update icon
            self.__action.setIcon(QIcon(actionRef.icon()))

            # by default, set menu disabled
            self.__action.setEnabled(False)

            menuFile.aboutToShow.connect(aboutToShowFileMenu)
Пример #7
0
    def __init__(self, parent=None):
        super(KBRotationSlider, self).__init__(0, 360, parent)
        self.view = Krita.instance().activeWindow().activeView()
        self.setAffixes('Canvas Rotation: ', '°')
        legacySupportedVersion = 428
        currentVersion = int(Krita.instance().version().replace('.', '')[:3])
        setRotation = None

        if currentVersion > legacySupportedVersion:
            setRotation = lambda: self.view.canvas().setRotation(self.value()) 
        else: 
            # prior to Krita 4.2.9 the API had a bug which made 'setRotation' function as 'rotateCanvas'
            setRotation = lambda: self.view.canvas().setRotation(self.value() - self.view.canvas().rotation())

        self.connectValueChanged(setRotation)
    def set_frame_range(self, in_frame=None, out_frame=None, **kwargs):
        """
        set_frame_range will set the frame range using `in_frame` and `out_frame`
        :param int in_frame: in_frame for the current context
            (e.g. the current shot, current asset etc)
        :param int out_frame: out_frame for the current context
            (e.g. the current shot, current asset etc)
        """

        krita_app = Krita.instance()
        active_doc = Krita.instance().activeDocument()

        if active_doc:
            active_doc.setFullClipRangeStartTime(int(in_frame))
            active_doc.setFullClipRangeEndTime(int(out_frame))
Пример #9
0
def create_sgtk_disabled_menu(menu_name):
    """
    Render a special "shotgun is disabled" menu
    """
    win = Krita.instance().window().qwindow()

    # Find the shotgun menu
    menuBar = win.menuBar()
    sg_menu = None
    for action in menuBar.actions():
        if action.objectName == "shotgun":
            sg_menu = action.menu()
            break

    if sg_menu:
        # Clear all the actions before adding our item
        sg_menu.clear()
    else:
        # we need to create a new shotgun menu
        sg_menu = QtGui.QMenu("Shotgun", menuBar)
        sg_menu.setObjectName("shotgun")
        menu_action = menuBar.addMenu(sg_menu)
        menu_action.setObjectName("shotgun")

    # add the disabled action to our menu
    disabled_action = QtGui.QAction("Sgtk is disabled.")
    disabled_action.triggered.connect(sgtk_disabled_message)
    disabled_action.setObjectName("shotgun_disabled")
Пример #10
0
 def initCanvasOptions(self, config, data):
     for entry in config:
         if config.getboolean(entry):
             self.canvasOptions.loadButton(
                 data[entry],
                 Krita.instance().action(data[entry]['id']).trigger
                 )
Пример #11
0
    def _import_animation_frames(self, path, sg_publish_data):
        krita_app = Krita.instance()
        doc = krita_app.activeDocument()
        if not doc:
            return False

        app = self.parent
        template = app.sgtk.template_from_path(path)
        fields = template.get_fields(path)

        images = app.sgtk.paths_from_template(template, fields, skip_keys=[SEQUENCE_FIELD])

        # a quick way to get the images sorted by frame, as this matters when
        # we insert them in the layer
        frame_images = []
        for image in images:
            fields = template.get_fields(image)
            frame = int(fields[SEQUENCE_FIELD])
            bisect.insort(frame_images, (frame, image))

        sorted_images = [frame_image[1] for frame_image in frame_images]

        # current time
        t = doc.currentTime()

        # insert from the current time onwards
        doc.importAnimation(sorted_images, t, 1)
        doc.waitForDone()
Пример #12
0
    def __init__(self, parent):
        super(KBTitleBar, self).__init__(parent)
        self.parent = parent
        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(2, 1, 2, 1)
        self.pressing = False

        self.title = QLabel("KanvasBuddy")
        font = self.font()
        font.setPixelSize(9)
        self.title.setFont(font)
        self.title.setStyleSheet("""
            color: grey;
        """)

        self.btn_close = QToolButton()
        self.btn_close.setFixedSize(10, 10)
        self.btn_close.setIconSize(QSize(7,7))
        self.btn_close.clicked.connect(self.parent.close)
        self.btn_close.setIcon(parent.style().standardIcon(QStyle.SP_DockWidgetCloseButton))
        self.btn_close.setFocusPolicy(Qt.NoFocus)

        self.btn_pinned_mode = QToolButton()
        self.btn_pinned_mode.setCheckable(True)
        self.btn_pinned_mode.setToolTip("Toggle pinned panel mode")
        self.btn_pinned_mode.setFixedSize(10, 10)
        self.btn_pinned_mode.setIconSize(QSize(7,7))
        self.btn_pinned_mode.clicked.connect(self.parent.togglePinnedMode)
        self.btn_pinned_mode.setIcon(Krita.instance().icon('light_krita_tool_reference_images.svg'))
        self.btn_pinned_mode.setFocusPolicy(Qt.NoFocus)

        self.layout.addWidget(self.title)
        self.layout.addWidget(self.btn_pinned_mode)
        self.layout.addWidget(self.btn_close)
        self.setLayout(self.layout)
Пример #13
0
    def _open_as_layer(self, path, sg_publish_data):
        krita_app = Krita.instance()
        doc = krita_app.activeDocument()
        if not doc:
            return False

        filename_file = os.path.basename(path)
        filename_filename, _ = os.path.splitext(filename_file)
        layer_name = filename_filename
        layer_node = doc.createNode(layer_name, "paintlayer")
        doc.rootNode().addChildNode(layer_node, None)

        # load as a different doc
        layer_doc = krita_app.openDocument(path)
        layer_doc.waitForDone()
        pixel_data = layer_doc.pixelData(0, 0, layer_doc.width(), layer_doc.height())

        # paste pixel info
        layer_node.setPixelData(pixel_data, 0, 0, layer_doc.width(), layer_doc.height())
        doc.waitForDone()

        doc.setActiveNode(layer_node)
        doc.refreshProjection()
        doc.waitForDone()

        # no need anymore
        layer_doc.close()
Пример #14
0
    def execute(self, operation, file_path, **kwargs):
        """
        Main hook entry point

        :operation: String
                    Scene operation to perform

        :file_path: String
                    File path to use if the operation
                    requires it (e.g. open)

        :returns:   Depends on operation:
                    'current_path' - Return the current scene
                                     file path as a String
                    all others     - None
        """
        krita_app = Krita.instance()
        active_doc = krita_app.activeDocument()

        if operation == "current_path":
            current_project_filename = None
            if active_doc:
                current_project_filename = active_doc.fileName()

            return current_project_filename

        elif operation == "open":
            doc = krita_app.openDocument(file_path)
            krita_app.activeWindow().addView(doc)
            doc.waitForDone()

        elif operation == "save":
            if active_doc:
                active_doc.save()
                active_doc.waitForDone()
Пример #15
0
 def setup(self):
     """
     This is where most of the setup takes place!
     """
     qDebug("Hello Setup")
     action = Krita.instance().createAction("hello_python", "hello")
     action.triggered.connect(hello)
Пример #16
0
 def __init__(self, parent=None):
     super(KBPanelCloseButton, self).__init__(parent)
     self.setIcon(Krita.instance().action('move_layer_up').icon())
     self.setIconSize(QSize(10, 10))
     self.setFixedHeight(12)
     self.clicked.connect(
         lambda: self.parentWidget().parentWidget().setCurrentIndex(0))
Пример #17
0
    def __init__(self, parent):
        """"""
        super().__init__(parent)

        self.kritaInstance = Krita.instance()
        self.actions = []
        self.popupframe = None
Пример #18
0
def _session_document():
    """
    Return the current active document
    :return:
    """
    krita_app = Krita.instance()
    active_doc = krita_app.activeDocument()
    return active_doc
Пример #19
0
def get_active_node():
    """
    common shorthand.
    """
    app = Krita.instance()
    document = app.activeDocument()
    if document is not None:
        return document.activeNode()
Пример #20
0
 def __init__(self, parent=None):
     super(KBFlowSlider, self).__init__(parent=parent)
     self.view = Krita.instance().activeWindow().activeView()
     self.setAffixes('Flow: ', '%')
     self.connectValueChanged(
         lambda: 
             self.view.setPaintingFlow(self.value()/100)
         )
Пример #21
0
    def write_settings(self):
        main_program = Krita.instance()
        setting = ';'.join([
            self.color_to_settings(line.left) + '|' +
            self.color_to_settings(line.right) for line in self.sliders
        ])

        main_program.writeSetting("", "MixerSliderColors", setting)
    def get_frame_range(self, **kwargs):
        """
        get_frame_range will return a tuple of (in_frame, out_frame)
        :returns: Returns the frame range in the form (in_frame, out_frame)
        :rtype: tuple[int, int]
        """

        krita_app = Krita.instance()
        active_doc = Krita.instance().activeDocument()

        current_in = 0
        current_out = 0

        if active_doc:
            current_in = int(active_doc.fullClipRangeStartTime())
            current_out = int(active_doc.fullClipRangeEndTime())

        return (current_in, current_out)
Пример #23
0
def find_document_for(node):
    """
    Missing method:
        document = krita.Node.document(self)
    """
    app = Krita.instance()
    for document in app.documents():
        for n, _ in walk_nodes([document.rootNode()]):
            if n == node:
                return document
Пример #24
0
def keep_active_document(new_document=None):
    app = Krita.instance()
    old_document = app.activeDocument()
    try:
        if new_document is not None:
            set_active_document(new_document)
        yield app.activeDocument()
    finally:
        if old_document is not None:
            set_active_document(old_document)
Пример #25
0
def keep_batch_mode(new_batch_mode=None):
    app = Krita.instance()
    old_batch_mode = app.batchMode()
    try:
        if new_batch_mode is not None:
            app.setBatchMode(new_batch_mode)
        yield app.batchMode()
    finally:
        if old_batch_mode is not None:
            app.setBatchMode(old_batch_mode)
Пример #26
0
    def __initUiController(self, kritaIsStarting=False):
        """Initialise UI controller

        `kritaIsStarting` set to True if UiConbtroller is intialised during Krita's startup,
        otherwise set to False (initialised on first manual execution)
        """
        @pyqtSlot('QString')
        def opened(document):
            # a document has been created: if filename is set, document has been opened
            if document.fileName() != '':
                self.__uiController.commandGoLastDocsOpenedAdd(
                    document.fileName())

        @pyqtSlot('QString')
        def saved(fileName):
            # a document has been saved
            if fileName != '':
                self.__uiController.commandGoLastDocsSavedAdd(fileName)

        try:
            Krita.instance().notifier().imageCreated.disconnect()
        except Exception as e:
            pass

        try:
            Krita.instance().notifier().imageSaved.disconnect()
        except Exception as e:
            pass

        try:
            Krita.instance().notifier().applicationClosing.disconnect()
        except Exception as e:
            pass

        if self.__uiController is None:
            # no controller, create it
            # (otherwise, with Krita 5.0.0, can be triggered more than once time - on each new window)
            Krita.instance().notifier().imageCreated.connect(opened)
            Krita.instance().notifier().imageSaved.connect(saved)

            self.__uiController = BCUIController(PLUGIN_MENU_ENTRY,
                                                 PLUGIN_VERSION,
                                                 kritaIsStarting)
Пример #27
0
    def init_engine(self):
        """
        Initializes the Krita engine.
        """
        self.logger.debug("%s: Initializing...", self)

        self._kritaInstance = Krita.instance()

        # default menu name is Shotgun but this can be overriden
        # in the configuration to be Sgtk in case of conflicts
        self._menu_name = "Shotgun"
Пример #28
0
def sgtk_disabled_message():
    """
    Explain why sgtk is disabled.
    """
    msg = (
        "Shotgun integration is disabled because it cannot recognize "
        "the currently opened file.  Try opening another file or restarting "
        "Krita.")

    win = Krita.instance().window().qwindow()
    QtGui.QMessageBox.information(win, "Sgtk is disabled.", msg)
Пример #29
0
def _batch_mode(state):
    """
    A handy context for running things in Krita in batch mode
    """
    krita_app = Krita.instance()
    current_state = krita_app.batchmode()
    krita_app.setBatchmode(state)

    try:
        yield
    finally:
        krita_app.setBatchmode(current_state)
Пример #30
0
    def __init__(self, parent):
        # Default options

        # Always initialise the superclass.
        # This is necessary to create the underlying C++ object
        super(JpegExport, self).__init__(parent)
        self.parent = parent
        self.__uiController = None
        self.__isKritaVersionOk = checkKritaVersion(*REQUIRED_KRITA_VERSION)
        self.__dlgParentWidget = QWidget()
        self.__action = None
        self.__notifier = Krita.instance().notifier()