File: palette-export-as-kpl.py

package info (click to toggle)
gimp 3.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 222,880 kB
  • sloc: ansic: 870,914; python: 10,965; lisp: 10,857; cpp: 7,355; perl: 4,536; sh: 1,753; xml: 972; yacc: 609; lex: 348; javascript: 150; makefile: 42
file content (197 lines) | stat: -rw-r--r-- 7,637 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#   Allows exporting Krita's .kpl palettes
#
#   This program 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.
#
#   This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.

import gi
gi.require_version('Gimp', '3.0')
from gi.repository import Gimp
from gi.repository import GObject
from gi.repository import GLib
from gi.repository import Gio
import os, sys, tempfile, zipfile
import xml.etree.ElementTree as ET

def N_(message): return message
def _(message): return GLib.dgettext(None, message)

# Taken from file-openraster.py
def write_file_str(zfile, fname, data):
    # work around a permission bug in the zipfile library:
    # http://bugs.python.org/issue3394
    zi = zipfile.ZipInfo(fname)
    zi.external_attr = int("100644", 8) << 16
    zfile.writestr(zi, data)

def palette_kpl_export(procedure, config, data):
    success = True
    runmode = config.get_property("run-mode")

    if runmode == Gimp.RunMode.INTERACTIVE:
        gi.require_version('GimpUi', '3.0')
        from gi.repository import GimpUi
        gi.require_version('Gtk', '3.0')
        from gi.repository import Gtk

        GimpUi.init('python-fu-palette-export-as-kpl')
        dialog = GimpUi.ProcedureDialog(procedure=procedure, config=config)

        # Fill the dialog.
        config.set_property("palette", None)
        config.set_property("file", None)

        dialog.get_label ("options-label", _("Options"), False, False)
        hbox = dialog.fill_box ("options-box", ["comment", "read-only"])
        dialog.fill_frame("options-frame", "options-label", False, "options-box")

        dialog.fill (["palette", "file", "options-frame"])
        dialog.set_ok_label (_("_Export"))

        if not dialog.run():
            dialog.destroy()
            return procedure.new_return_values(Gimp.PDBStatusType.CANCEL, GLib.Error())

    palette   = config.get_property("palette")
    file      = config.get_property("file")
    comment   = config.get_property("comment")
    read_only = config.get_property("read-only")

    if file is None or file.peek_path() is None:
        error = 'No file given'
        return procedure.new_return_values(Gimp.PDBStatusType.CALLING_ERROR,
                                           GLib.Error(error))

    tempdir = tempfile.mkdtemp('python-fu-palette-export-as-kpl')

    kplfile = zipfile.ZipFile(file.peek_path() + '.tmpsave', 'w', compression=zipfile.ZIP_STORED)

    write_file_str(kplfile, 'mimetype', 'application/x-krita-palette') # must be the first file written

    # Filling in palette
    xml_palette = ET.Element('ColorSet')
    a = xml_palette.attrib
    if comment != "":
        a['comment'] = comment
    a['name'] = palette.get_name()
    a['version'] = "1.0"
    a['readonly'] = "true" if read_only == True else "false"
    columns = palette.get_columns()
    if columns == 0:
        columns = 16
    a['columns'] = str(columns)

    count = palette.get_color_count()

    row = 0
    col = 0
    for i in range(count):
        entry = ET.Element('ColorSetEntry')
        xml_palette.append(entry)

        success, name = palette.get_entry_name(i)
        if success:
            a = entry.attrib
            a['name'] = name
            a['id'] = str(i + 1)
            # TODO: Add options for different bit-depths
            a['bitdepth'] = "F32"
            a['spot'] = "false"

            color = palette.get_entry_color(i)
            # TODO: Allow for other color spaces
            pal = ET.Element('RGB')
            entry.append(pal)
            a = pal.attrib

            r, g, b, alpha = color.get_rgba()
            a['r'] = str(r)
            a['g'] = str(g)
            a['b'] = str(b)

            pos = ET.Element('Position')
            entry.append(pos)
            a = pos.attrib
            a['row'] = str(row)
            a['column'] = str(col)

            col += 1
            if col >= columns:
                col = 0
                row += 1
        else:
            break;

    if success:
        # Write everything to file
        xml = ET.tostring(xml_palette, encoding='UTF-8')
        write_file_str(kplfile, 'colorset.xml', xml)

        kplfile.close()
        os.rmdir(tempdir)
        if os.path.exists(file.peek_path()):
            os.remove(file.peek_path()) # win32 needs that
        os.rename(file.peek_path() + '.tmpsave', file.peek_path())

        return procedure.new_return_values(Gimp.PDBStatusType.SUCCESS, GLib.Error())
    else:
        kplfile.close()
        os.rmdir(tempdir)
        return procedure.new_return_values(Gimp.PDBStatusType.EXECUTION_ERROR,
                                           GLib.Error('File exporting failed: {}'.format(file.get_path())))

class PaletteExportAsKPL (Gimp.PlugIn):
    ## GimpPlugIn virtual methods ##
    def do_set_i18n(self, procname):
        return True, 'gimp30-python', None

    def do_query_procedures(self):
        return [ 'python-fu-palette-export-as-kpl' ]

    def do_create_procedure(self, name):
        procedure = Gimp.Procedure.new(self, name,
                                       Gimp.PDBProcType.PLUGIN,
                                       palette_kpl_export, None)
        if name == 'python-fu-palette-export-as-kpl':
            procedure.set_documentation (_("Export palette as Krita .kpl"),
                                         _("Export palette as Krita .kpl"),
                                         name)
            procedure.set_menu_label(_("_Krita palette..."))
            procedure.set_attribution("Alx Sa",
                                      "(c) GPL V3.0 or later",
                                      "2025")
            procedure.add_menu_path('<Palettes>/Palettes Menu/Export as')

            procedure.add_enum_argument ("run-mode", _("Run mode"),
                                         _("The run mode"), Gimp.RunMode,
                                         Gimp.RunMode.NONINTERACTIVE,
                                         GObject.ParamFlags.READWRITE)
            procedure.add_palette_argument ("palette", _("_Palette to export"),
                                             "", True,
                                             None, True, # Default to context.
                                             GObject.ParamFlags.READWRITE)
            procedure.add_file_argument ("file", _("_File (.kpl)"), "",
                                         Gimp.FileChooserAction.SAVE,
                                         False, None, GObject.ParamFlags.READWRITE)
            procedure.add_string_argument ("comment", _("Commen_t"),
                                           _("Optional comment"), "",
                                           GObject.ParamFlags.READWRITE)
            procedure.add_boolean_argument ("read-only",
                                            _("Re_ad only"),
                                            _("The palette will be locked on import"),
                                            False, GObject.ParamFlags.READWRITE)
        return procedure

Gimp.main(PaletteExportAsKPL.__gtype__, sys.argv)