-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathsettings_custom.py
237 lines (175 loc) · 7.7 KB
/
settings_custom.py
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# -*- coding: utf-8 -*-
"""Custom setting classes specific to the plug-in."""
from __future__ import absolute_import, division, print_function, unicode_literals
from future.builtins import *
import collections
import os
import types
import gimp
from export_layers import pygimplib as pg
from export_layers import renamer as renamer_
class FilenamePatternEntryPresenter(pg.setting.presenters_gtk.ExtendedEntryPresenter):
"""`pygimplib.setting.Presenter` subclass for
`pygimplib.gui.FilenamePatternEntry` elements.
Value: Text in the entry.
"""
def _create_gui_element(self, setting):
return pg.gui.FilenamePatternEntry(renamer_.get_field_descriptions(renamer_.FIELDS))
class FilenamePatternSetting(pg.setting.StringSetting):
_ALLOWED_GUI_TYPES = [
FilenamePatternEntryPresenter,
pg.SettingGuiTypes.extended_entry,
pg.SettingGuiTypes.entry,
]
def _assign_value(self, value):
if not value:
self._value = self._default_value
else:
self._value = value
class ImagesAndGimpItemsSetting(pg.setting.Setting):
"""Class for settings representing a mapping of (GIMP image ID, GIMP item IDs)
pairs.
The mapping is implemented as `collections.defaultdict(set)`.
A GIMP item ID can be represented as an integer or an (ID, FOLDER_KEY) tuple,
where `FOLDER_KEY` is a string literal defined in `pygimplib.itemtree`.
When storing this setting to a persistent source, images are stored as file
paths and items are stored as (item class name, item path) or (item class
name, item path, FOLDER_KEY) tuples. Item class name and item path are
described in `pygimplib.pdbutils.get_item_from_image_and_item_path()`.
Default value: `collections.defaultdict(set)`
"""
_ALLOWED_PDB_TYPES = []
_ALLOWED_GUI_TYPES = []
_DEFAULT_DEFAULT_VALUE = lambda self: collections.defaultdict(set)
def _raw_to_value(self, raw_value):
if isinstance(raw_value, dict):
value = collections.defaultdict(set)
for key, items in raw_value.items():
if isinstance(key, types.StringTypes):
image = pg.pdbutils.find_image_by_filepath(key)
else:
image = pg.pdbutils.find_image_by_id(key)
if image is None:
continue
image_id = image.ID
if not isinstance(items, collections.Iterable) or isinstance(items, types.StringTypes):
raise TypeError('expected a list-like, found {}'.format(items))
processed_items = set()
for item in items:
if isinstance(item, (list, tuple)):
if len(item) not in [2, 3]:
raise ValueError(
'list-likes representing items must contain exactly 2 or 3 elements'
' (has {})'.format(len(item)))
if isinstance(item[0], int): # (item ID, item type)
item_object = gimp.Item.from_id(item[0])
if item_object is not None:
processed_items.add(tuple(item))
else:
if len(item) == 3:
item_type = item[2]
item_class_name_and_path = item[:2]
else:
item_type = None
item_class_name_and_path = item
item_object = pg.pdbutils.get_item_from_image_and_item_path(
image, *item_class_name_and_path)
if item_object is not None:
if item_type is None:
processed_items.add(item_object.ID)
else:
processed_items.add((item_object.ID, item_type))
else:
item_object = gimp.Item.from_id(item)
if item_object is not None:
processed_items.add(item)
value[image_id] = processed_items
else:
value = raw_value
return value
def _value_to_raw(self, value, source_type):
raw_value = {}
if source_type == 'session':
for image_id, item_ids in value.items():
raw_value[image_id] = list(
item_id if isinstance(item_id, int) else list(item_id) for item_id in item_ids)
else:
for image_id, item_ids in value.items():
image = pg.pdbutils.find_image_by_id(image_id)
if image is None or image.filename is None:
continue
image_filepath = pg.utils.safe_decode_gimp(image.filename)
raw_value[image_filepath] = []
for item_id in item_ids:
if isinstance(item_id, (list, tuple)):
if len(item_id) != 2:
raise ValueError(
'list-likes representing items must contain exactly 2 elements'
' (has {})'.format(len(item_id)))
item = gimp.Item.from_id(item_id[0])
item_type = item_id[1]
else:
item = gimp.Item.from_id(item_id)
item_type = None
if item is None:
continue
item_as_path = pg.pdbutils.get_item_as_path(item, include_image=False)
if item_as_path is not None:
if item_type is None:
raw_value[image_filepath].append(item_as_path)
else:
raw_value[image_filepath].append(item_as_path + [item_type])
return raw_value
def _init_error_messages(self):
self.error_messages['value_must_be_dict'] = _('Value must be a dictionary.')
def _validate(self, value):
if not isinstance(value, dict):
raise pg.setting.SettingValueError(
pg.setting.value_to_str_prefix(value) + self.error_messages['value_must_be_dict'])
class ImageIdsAndDirectoriesSetting(pg.setting.Setting):
"""Class for settings the list of currently opened images and their import
directory paths.
The setting value is a dictionary of (image ID, import directory path) pairs.
The import directory path is `None` if the image does not have any.
This setting cannot be registered to the PDB as no corresponding PDB type
exists.
Default value: `{}`
"""
_DEFAULT_DEFAULT_VALUE = {}
@property
def value(self):
# Return a copy to prevent modifying the dictionary indirectly by assigning
# to individual items (`setting.value[image.ID] = dirpath`).
return dict(self._value)
def update_image_ids_and_dirpaths(self):
"""Removes all (image ID, import directory path) pairs for images no longer
opened in GIMP. Adds (image ID, import directory path) pairs for new images
opened in GIMP.
"""
current_images, current_image_ids = self._get_currently_opened_images()
self._filter_images_no_longer_opened(current_image_ids)
self._add_new_opened_images(current_images)
def update_dirpath(self, image_id, dirpath):
"""Assigns a new directory path to the specified image ID.
If the image ID does not exist in the setting, `KeyError` is raised.
"""
if image_id not in self._value:
raise KeyError(image_id)
self._value[image_id] = dirpath
def _get_currently_opened_images(self):
current_images = gimp.image_list()
current_image_ids = set([image.ID for image in current_images])
return current_images, current_image_ids
def _filter_images_no_longer_opened(self, current_image_ids):
self._value = {
image_id: self._value[image_id] for image_id in self._value
if image_id in current_image_ids}
def _add_new_opened_images(self, current_images):
for image in current_images:
if image.ID not in self._value:
self._value[image.ID] = self._get_image_import_dirpath(image)
def _get_image_import_dirpath(self, image):
if image.filename is not None:
return os.path.dirname(pg.utils.safe_decode_gimp(image.filename))
else:
return None