gtk3-theme-prefs.py 12.2 KB
Newer Older
Colomban Wendling's avatar
Colomban Wendling committed
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
#!/usr/bin/env python
#
#  Copyright (C) 2013 Colomban Wendling <ban@herbesfolles.org>
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are
#  met:
#
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above
#    copyright notice, this list of conditions and the following disclaimer
#    in the documentation and/or other materials provided with the
#    distribution.
#  * Neither the name of the author nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#


33 34
import math
from gi.repository import Gtk, Gdk, Gio, GObject
Colomban Wendling's avatar
Colomban Wendling committed
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


class RGBA(Gdk.RGBA):
    def __init__(self, arg=None):
        Gdk.RGBA.__init__(self)

        if isinstance(arg, str):
            self.parse(arg)
        elif isinstance(arg, Gdk.RGBA):
            self.red = arg.red
            self.green = arg.green
            self.blue = arg.blue
            self.alpha = arg.alpha

    def to_string(self, alpha=False):
        if alpha:
            return '#%.2x%.2x%.2x%.2x' % (self.red * 0xff,
                                          self.green * 0xff,
                                          self.blue * 0xff,
                                          self.alpha * 0xff)
        else:
            return '#%.2x%.2x%.2x' % (self.red * 0xff,
                                      self.green * 0xff,
                                      self.blue * 0xff)

60 61 62 63
    # for some reason the __ne__ operator of Gdk.RGBA is broken
    def __ne__(self, other):
        return not (self == other)

Colomban Wendling's avatar
Colomban Wendling committed
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
class CellRendererColor(Gtk.CellRenderer):
    __gproperties__ = {
        'color': (GObject.TYPE_STRING, 'color', 'displayed color', '',
                  GObject.PARAM_READWRITE)
    }
    _property_names = __gproperties__.keys()

    color = '#000000'

    def do_set_property(self, prop, value):
        if prop.name not in self._property_names:
            raise AttributeError('No property %s in %s' % (prop.name, self))
        self.__dict__[prop.name] = value

    def do_get_property(self, prop):
        if prop.name not in self._property_names:
            raise AttributeError('No property %s in %s' % (prop.name, self))
        return self.__dict__[prop.name]

    def do_get_preferred_width(self, width):
        xpad = self.get_padding()[0]
        return xpad * 2 + 16, xpad * 2 + 32

    def do_get_preferred_height(self, width):
        ypad = self.get_padding()[1]
        return ypad * 2 + 16, ypad * 2 + 24

    def _rounded_rectangle(self, cr, x, y, w, h, r):
        cr.move_to(x + r, y)
        cr.arc(x + w - r, y + r, r, -math.pi/2.0, 0)
        cr.arc(x + w - r, y + h - r, r, 0, math.pi/2.0)
        cr.arc(x + r, y + h - r, r, math.pi/2.0, -math.pi)
        cr.arc(x + r, y + r, r, -math.pi, -math.pi/2.0)
        cr.close_path()

    def do_render(self, cr, widget, background_area, cell_area, flags):
        xpad, ypad = self.get_padding()
        r = min(cell_area.width/4, cell_area.height/4)
        x, y = cell_area.x + xpad, cell_area.y + ypad
        w, h = cell_area.width - xpad * 2, cell_area.height - ypad * 2

        # background
        Gdk.cairo_set_source_rgba(cr, RGBA(self.color))
        self._rounded_rectangle(cr, x, y, w, h, r)
        cr.fill()
        # border
        cr.set_line_width(1)
        cr.set_source_rgba(0, 0, 0, 0.3)
        self._rounded_rectangle(cr, x+0.5, y+0.5, w-1, h-1, r)
        cr.stroke()


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
class UndoStack(object):
    def __init__(self):
        self._items = []
        self._current = -1

    def push(self, data):
        while len(self._items) - 1 > self._current:
            self._items.pop()
        self._current += 1
        self._items.append(data)
        assert(len(self._items) - 1 == self._current)

    def can_undo(self):
        return self._current > 0

    def undo(self):
        if self.can_undo():
            self._current -= 1
            return self._items[self._current]
        else:
            return None

    def can_redo(self):
        return self._current + 1 < len(self._items)

    def redo(self):
        if self.can_redo():
            self._current += 1
            return self._items[self._current]
        else:
            return None

    def get(self):
        if self._current >= 0 and self._current < len(self._items):
            return self._items[self._current]
        else:
            return None


# FIXME: only save the changed rows, not the whole store
class UndoableStore(Gtk.ListStore):
158 159 160 161
    __gsignals__ = {
        'changed': (GObject.SIGNAL_RUN_LAST, None, ())
    }

162 163 164
    def __init__(self, *args, **kwargs):
        self._stack = UndoStack()
        self._freeze = False
165
        Gtk.ListStore.__init__(self, *args, **kwargs)
166 167
        self._save()

168
        def on_model_changed(model, path, iter=None, data=None):
169 170 171
            if not self._freeze:
                self._save()
                self.emit('changed')
172 173 174
        self.connect('row-changed', on_model_changed)
        self.connect('row-deleted', on_model_changed)
        self.connect('row-inserted', on_model_changed)
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190

    def _save(self):
        # don't save state when restoring it
        if self._freeze:
            return

        data = [[col for col in row] for row in self]
        self._stack.push(data)

    def _update(self):
        data = self._stack.get()
        self._freeze = True
        self.clear()
        for row in data:
            self.append(row)
        self._freeze = False
191
        self.emit('changed')
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    def can_undo(self):
        return self._stack.can_undo()

    def can_redo(self):
        return self._stack.can_redo()

    def undo(self):
        if self.can_undo():
            self._stack.undo()
            self._update()

    def redo(self):
        if self.can_redo():
            self._stack.redo()
            self._update()

    def clear_undo_stack(self):
        self._stack = UndoStack()
        self._save()


214
class AppWindow(Gtk.ApplicationWindow):
Colomban Wendling's avatar
Colomban Wendling committed
215 216 217
    ROW_KEY = 0
    ROW_COLOR = 1

218 219
    def __init__(self, app):
        Gtk.ApplicationWindow.__init__(self, application=app)
Colomban Wendling's avatar
Colomban Wendling committed
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
        self.set_default_size(400, 300)
        self.set_title("GTK3 Theme Pref")
        self.set_icon_name("gtk-preferences")

        builder = Gtk.Builder()
        builder.add_from_file("window.ui")

        uimanager = builder.get_object('uimanager1')
        self.add_accel_group(uimanager.get_accel_group())

        vbox = builder.get_object("box")
        self.add(vbox)

        quit = builder.get_object('quit')
        quit.connect('activate', lambda s: self.destroy())
        add = builder.get_object('add')
        add.connect('activate', self.on_add_activate)
        remove = builder.get_object('remove')
        remove.connect('activate', self.on_remove_activate)
239 240 241 242
        undo = builder.get_object('undo')
        undo.connect('activate', self.on_undo_activate)
        redo = builder.get_object('redo')
        redo.connect('activate', self.on_redo_activate)
Colomban Wendling's avatar
Colomban Wendling committed
243 244 245 246

        self.view = builder.get_object('treeview1')
        self.view.connect('row-activated', self.on_row_activated)

247 248 249
        self.store = UndoableStore(str, str)
        self.view.set_model(self.store)

250 251 252 253 254
        column = builder.get_object('treeviewcolumn2')
        renderer = CellRendererColor()
        column.pack_start(renderer, True)
        column.add_attribute(renderer, 'color', self.ROW_COLOR)

255 256 257 258 259
        def on_key_cell_edited(cell, path, new_text, data=None):
            iter = self.store.get_iter(path)
            old_text = self.store.get(iter, self.ROW_KEY)[0]
            if old_text != new_text:
                self.store.set(iter, self.ROW_KEY, new_text)
Colomban Wendling's avatar
Colomban Wendling committed
260 261 262 263 264 265 266
        cell = builder.get_object('cellrenderertext1')
        cell.connect('edited', on_key_cell_edited)

        self.settings = Gio.Settings.new('org.gnome.desktop.interface')

        self.load()

267 268 269 270
        self.store.clear_undo_stack()
        undo.set_sensitive(self.store.can_undo())
        redo.set_sensitive(self.store.can_redo())

271
        def on_model_changed(model, data=None):
272 273
            undo.set_sensitive(self.store.can_undo())
            redo.set_sensitive(self.store.can_redo())
Colomban Wendling's avatar
Colomban Wendling committed
274
            self.update_theme()
275
        self.store.connect('changed', on_model_changed)
Colomban Wendling's avatar
Colomban Wendling committed
276 277 278

    def on_row_activated(self, view, path, column, data=None):
        iter = self.store.get_iter(path)
279
        old_rgba = RGBA(self.store.get(iter, self.ROW_COLOR)[0])
Colomban Wendling's avatar
Colomban Wendling committed
280 281 282

        dialog = Gtk.ColorChooserDialog()
        dialog.set_transient_for(self)
283
        dialog.set_rgba(old_rgba)
Colomban Wendling's avatar
Colomban Wendling committed
284 285 286 287 288 289 290 291 292 293 294
        answer = dialog.run()
        if answer == Gtk.ResponseType.ACCEPT or \
           answer == Gtk.ResponseType.APPLY or \
           answer == Gtk.ResponseType.OK or \
           answer == Gtk.ResponseType.YES:
            try:
                rgba = RGBA(dialog.get_rgba())
            except:
                # Apparently old GI was broken...
                rgba = RGBA()
                dialog.get_rgba(rgba)
295 296
            if old_rgba != rgba:
                self.store.set(iter, self.ROW_COLOR, rgba.to_string())
Colomban Wendling's avatar
Colomban Wendling committed
297 298 299 300 301 302 303 304 305 306 307 308 309
        dialog.destroy()

    def on_add_activate(self, action, data=None):
        iter = self.store.append()
        self.store.set(iter, self.ROW_KEY, 'key', self.ROW_COLOR, '#000')
        self.view.set_cursor(self.store.get_path(iter), None, True)

    def on_remove_activate(self, action, data=None):
        sel = self.view.get_selection()
        model, iter = sel.get_selected()
        if iter is not None:
            model.remove(iter)

310 311 312 313 314 315
    def on_undo_activate(self, action, data=None):
        self.store.undo()

    def on_redo_activate(self, action, data=None):
        self.store.redo()

Colomban Wendling's avatar
Colomban Wendling committed
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
    def load(self):
        scheme = self.settings.get_string('gtk-color-scheme').strip()
        n = 0
        for entry in scheme.split(';'):
            entry = entry.strip()
            if len(entry) < 1:
                continue
            k, v = entry.split(':')
            iter = self.store.append()
            self.store.set(iter, self.ROW_KEY, k, self.ROW_COLOR, v)
            n += 1

        if n == 0:
            for k, v in [('base_color',          '#ffffff'),
                         ('bg_color',            '#ededed'),
                         ('tooltip_bg_color',    '#343434'),
                         ('selected_bg_color',   '#4a90d9'),
                         ('text_color',          '#2e3436'),
                         ('fg_color',            '#2e3436'),
                         ('tooltip_fg_color',    '#ffffff'),
                         ('selected_fg_color',   '#ffffff')]:
                iter = self.store.append()
                self.store.set(iter, self.ROW_KEY, k, self.ROW_COLOR, v)

    def update_theme(self):
        values = []

        iter = self.store.get_iter_first()
        while iter is not None:
            key, color = self.store.get(iter, self.ROW_KEY, self.ROW_COLOR)
            values.append('%s:%s' % (key, color))
            iter = self.store.iter_next(iter)
        value = ';'.join(values)
        #print(value)
        scheme = self.settings.set_string('gtk-color-scheme', value)


class App(Gtk.Application):
    def __init__(self):
        Gtk.Application.__init__(self, application_id="apps.gtk_theme_prefs")

    def do_activate(self):
358
        window = AppWindow(self)
Colomban Wendling's avatar
Colomban Wendling committed
359 360 361 362 363 364 365 366 367
        window.show_all()
        self.add_window(window)


if __name__ == '__main__':
    import sys

    app = App()
    app.run(sys.argv)