forked from wjt/shell-chat-account-groups
-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit-groups
executable file
·365 lines (291 loc) · 12 KB
/
edit-groups
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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
358
359
360
361
362
363
364
365
#!/usr/bin/env python
# vim: set fileencoding=utf-8 sts=4 sw=4 et :
#
# Copyright © 2012–2013 Will Thompson <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import sys
import os
import errno
import json
from gi.repository import Gtk, GObject, GLib, TelepathyGLib
class ModelError(Exception):
pass
class GroupModel(Gtk.TreeStore, Gtk.TreeDragSource, Gtk.TreeDragDest):
__gtype_name__ = "ChatAccountGroupModel"
__gsignals__ = {
'loaded': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE,
()),
'save-error': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE,
(object,)),
}
COL_IS_GROUP = 0
COL_NAME = 1
COL_OBJECT_PATH = 2
COL_IS_REMAINDER = 3
DRAGGING_GROUP = 1
DRAGGING_ACCOUNT = 2
def __init__(self):
Gtk.TreeStore.__init__(self)
self.set_column_types([bool, str, str, bool])
self.accounts = {}
self.save_timeout = None
self.am = TelepathyGLib.AccountManager.dup()
self.am.prepare_async([], self.am_ready_cb, None)
self.dragging = None
def am_ready_cb(self, am, result, user_data):
am.prepare_finish(result)
for account in am.get_valid_accounts():
self.accounts[account.get_path_suffix()] = account
self.load()
def get_group_file_dir(self):
return os.path.join(
GLib.get_user_config_dir(),
"shell-chat-account-groups")
def get_group_file_path(self):
return os.path.join(
self.get_group_file_dir(),
"groups.2.json")
def get_old_group_file_path(self):
return os.path.join(
self.get_group_file_dir(),
"groups.json")
def add_group(self):
first_iter = self.get_iter_first()
return self.insert_before(None, first_iter, (True, "New group…", '', False))
def iter_is_removable(self, tree_iter):
is_group, is_remainder = self.get(tree_iter,
self.COL_IS_GROUP, self.COL_IS_REMAINDER)
# Only allow removing empty groups.
return is_group and \
not is_remainder and \
self.iter_children(tree_iter) is None
def do_row_draggable(self, path):
is_group, is_remainder = self.get(self.get_iter(path),
self.COL_IS_GROUP, self.COL_IS_REMAINDER)
if not is_group:
self.dragging = self.DRAGGING_ACCOUNT
return True
elif is_remainder:
self.dragging = None
return False
else:
self.dragging = self.DRAGGING_GROUP
return True
def do_row_drop_possible(self, path, data):
if self.dragging == self.DRAGGING_ACCOUNT:
return path.get_depth() == 2
elif self.dragging == self.DRAGGING_GROUP:
# FIXME: Don't allow dropping below remainder
return path.get_depth() == 1
else:
return False
def try_load_legacy(self):
try:
with open(self.get_old_group_file_path(), 'r') as f:
data = json.load(f)
new_data = []
for group_name, paths in data.iteritems():
new_data.append(
{ "name": group_name,
"accounts": paths,
})
# Schedule a save to write out in the new format
self.schedule_save_cb()
return new_data
except IOError as e:
return []
def load(self):
remainder = set(self.accounts.keys())
try:
with open(self.get_group_file_path(), 'r') as f:
data = json.load(f)
except IOError as e:
# No groups yet I guess
data = self.try_load_legacy()
except ValueError as e:
print ("hrm: %s" % e)
data = []
for group_dict in data:
group_name = group_dict["name"]
paths = group_dict["accounts"]
group_iter = self.append(None, (True, group_name, '', False))
for path in paths:
try:
account = self.accounts[path]
remainder.discard(path)
display = account.get_display_name()
except KeyError:
display = '%s not found' % path
self.append(group_iter, (False, display, path, False))
if remainder:
group_name = "Ungrouped accounts"
group_iter = self.append(None, (True, group_name, '', True))
for path in remainder:
account = self.accounts[path]
self.append(group_iter, (False, account.get_display_name(), path, True))
self.connect('row-inserted', self.schedule_save_cb)
self.connect('row-changed', self.schedule_save_cb)
self.connect('row-deleted', self.schedule_save_cb)
self.emit("loaded")
def schedule_save_cb(self, *args):
if self.save_timeout is None:
def save_me(*args):
self.save_timeout = None
try:
self.save()
except Exception as e:
self.emit('save-error', e)
return False
self.save_timeout = GLib.idle_add(save_me)
def save(self):
in_group = None
in_remainder = False
data = []
for row in self:
if not row[GroupModel.COL_IS_GROUP]:
raise ModelError("Account '%s' at the top level, not in any group"
% row[GroupModel.COL_NAME])
if row[GroupModel.COL_IS_REMAINDER]:
continue
paths = []
for child in row.iterchildren():
if child[GroupModel.COL_IS_GROUP]:
raise ModelError("Group '%s' nested within group '%s'"
% (child[GroupModel.COL_NAME], row[GroupModel.COL_NAME]))
path = child[GroupModel.COL_OBJECT_PATH]
if not path:
raise ModelError("Account '%s' has no associated object path"
% child[GroupModel.COL_NAME])
paths.append(path)
data.append({
"name": row[GroupModel.COL_NAME],
"accounts": paths,
})
try:
os.makedirs(self.get_group_file_dir())
except OSError as e:
if e.errno != errno.EEXIST:
raise
with open(self.get_group_file_path(), 'w') as f:
json.dump(data, f, indent=4)
class GroupView(Gtk.TreeView):
def __init__(self, **kwargs):
Gtk.TreeView.__init__(self, **kwargs)
self.set_reorderable(True)
self.set_headers_visible(False)
self.renderer = Gtk.CellRendererText()
self.renderer.connect('edited', self.group_name_edited_cb)
self.column = Gtk.TreeViewColumn()
self.column.set_title("Chat account groups")
self.column.pack_start(self.renderer, True)
self.column.set_cell_data_func(self.renderer, self.data_func)
self.append_column(self.column)
def data_func(self, column, cell, model, tree_iter, data):
is_group, name = model.get(tree_iter,
GroupModel.COL_IS_GROUP, GroupModel.COL_NAME)
if is_group:
cell.set_property('markup', '<b>%s</b>' % GLib.markup_escape_text(name))
#cell.set_property('background', '#eeeeee')
cell.set_property('background-set', True)
cell.set_property('editable', True)
else:
cell.set_property('text', name)
cell.set_property('background-set', False)
cell.set_property('editable', False)
def group_name_edited_cb(self, renderer, path, new_text):
model = self.get_model()
model.set(model.get_iter(path), model.COL_NAME, new_text)
class Window(Gtk.Window):
GOLDEN_RATIO = 1.61803399
DEFAULT_WIDTH = 300
DEFAULT_HEIGHT = DEFAULT_WIDTH * GOLDEN_RATIO
TITLE = 'Edit chat account groups'
def __init__(self):
Gtk.Window.__init__(self)
self.set_default_size(Window.DEFAULT_WIDTH, Window.DEFAULT_HEIGHT)
self.set_position(Gtk.WindowPosition.CENTER)
self.set_border_width(6)
self.set_icon_name('avatar-default-symbolic')
self.set_title(Window.TITLE)
# This convinces GNOME Shell to put our title in the top bar.
self.set_wmclass(GLib.get_prgname(), Window.TITLE)
self.store = GroupModel()
self.view = GroupView(model=self.store)
self.store.connect('loaded', lambda store: self.view.expand_all())
self.store.connect('save-error', self.save_error_cb)
self.sw = Gtk.ScrolledWindow(hscrollbar_policy=Gtk.PolicyType.NEVER)
self.sw.add(self.view)
self.sw.set_hexpand(True)
self.sw.set_vexpand(True)
self.sw.set_shadow_type(Gtk.ShadowType.IN)
toolbar = Gtk.Toolbar()
toolbar.set_icon_size(Gtk.IconSize.MENU)
self.remove_button = Gtk.ToolButton()
self.remove_button.set_icon_name('list-remove-symbolic')
toolbar.insert(self.remove_button, 0)
self.view.get_selection().connect('changed', self.selection_changed_cb)
self.remove_button.set_sensitive(False)
self.remove_button.connect('clicked', self.remove_clicked_cb)
add = Gtk.ToolButton()
add.set_icon_name('list-add-symbolic')
toolbar.insert(add, 0)
add.connect('clicked', self.add_clicked_cb)
grid = Gtk.Grid()
grid.attach(self.sw, 0, 0, 1, 1)
self.sw.get_style_context().set_junction_sides(Gtk.JunctionSides.BOTTOM)
grid.attach(toolbar, 0, 1, 1, 1)
sc = toolbar.get_style_context()
sc.add_class('inline-toolbar')
sc.set_junction_sides(Gtk.JunctionSides.TOP)
self.add(grid)
def add_clicked_cb(self, add):
tree_iter = self.store.add_group()
self.view.grab_focus()
self.view.set_cursor(self.store.get_path(tree_iter), self.view.column, True)
def selection_changed_cb(self, selection):
model, tree_iter = selection.get_selected()
self.remove_button.set_sensitive(
tree_iter is not None and
model.iter_is_removable(tree_iter))
def remove_clicked_cb(self, remove):
model, tree_iter = self.view.get_selection().get_selected()
model.remove(tree_iter)
def save_error_cb(self, model, exception):
dialog = Gtk.MessageDialog(parent=self,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.CLOSE,
message_format="Could not save your account groups")
dialog.format_secondary_markup(
"""Please <a href='https://extensions.gnome.org/errors/report/579'>report a bug</a> and include the following message:
<i>%s</i>""" % GLib.markup_escape_text(str(exception)))
dialog.run()
dialog.destroy()
class Application(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self,
application_id="uk.me.wjt.ChatAccountGroups",
flags=0)
self.window = None
self.connect('activate', Application.activate)
GLib.set_application_name(Window.TITLE)
def activate(self):
if not self.window:
self.window = Window()
self.window.show_all()
self.add_window(self.window)
self.window.present()
if __name__ == '__main__':
Application().run(sys.argv)