1# Gimp-Python - allows the writing of Gimp plugins in Python. 2# Copyright (C) 1997 James Henstridge <james@daa.com.au> 3# 4# This program is free software: you can redistribute it and/or modify 5# it under the terms of the GNU General Public License as published by 6# the Free Software Foundation; either version 3 of the License, or 7# (at your option) any later version. 8# 9# This program is distributed in the hope that it will be useful, 10# but WITHOUT ANY WARRANTY; without even the implied warranty of 11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12# GNU General Public License for more details. 13# 14# You should have received a copy of the GNU General Public License 15# along with this program. If not, see <https://www.gnu.org/licenses/>. 16 17# gimpshelf.py -- a simple module to help gimp modules written in Python 18# store persistent data. 19# 20# Copyright (C) 1997, James Henstridge 21# 22# The gimp module provides a basic method for storing information that persists 23# for a whole gimp session, but only allows for the storage of strings. This 24# is because other Python types usually have pointers to other Python objects, 25# making it difficult to work out what to save. This module gives an interface 26# to the gimp module's primitive interface, which resembles the shelve module. 27 28# use cPickle and cStringIO if available 29 30try: 31 import cPickle as pickle 32except ImportError: 33 import pickle 34 35try: 36 import cStringIO as StringIO 37except ImportError: 38 import StringIO 39 40import gimp 41 42import copy_reg 43 44def _image_id(obj): 45 return gimp._id2image, (obj.ID,) 46 47def _drawable_id(obj): 48 return gimp._id2drawable, (obj.ID,) 49 50def _display_id(obj): 51 return gimp._id2display, (obj.ID,) 52 53def _vectors_id(obj): 54 return gimp._id2vectors, (int(obj.ID),) 55 56copy_reg.pickle(gimp.Image, _image_id, gimp._id2image) 57copy_reg.pickle(gimp.Layer, _drawable_id, gimp._id2drawable) 58copy_reg.pickle(gimp.GroupLayer, _drawable_id, gimp._id2drawable) 59copy_reg.pickle(gimp.Channel, _drawable_id, gimp._id2drawable) 60copy_reg.pickle(gimp.Display, _display_id, gimp._id2display) 61copy_reg.pickle(gimp.Vectors, _vectors_id, gimp._id2vectors) 62 63del copy_reg, _image_id, _drawable_id, _display_id, _vectors_id 64 65class Gimpshelf: 66 def has_key(self, key): 67 try: 68 s = gimp.get_data(key) 69 return 1 70 except gimp.error: 71 return 0 72 73 def __getitem__(self, key): 74 try: 75 s = gimp.get_data(key) 76 except gimp.error: 77 raise KeyError, key 78 79 f = StringIO.StringIO(s) 80 return pickle.Unpickler(f).load() 81 82 def __setitem__(self, key, value): 83 f = StringIO.StringIO() 84 p = pickle.Pickler(f) 85 p.dump(value) 86 gimp.set_data(key, f.getvalue()) 87 88 def __delitem__(self, key): 89 gimp.set_data(key, '') 90 91shelf = Gimpshelf() 92del Gimpshelf 93