~mjz/awn-extras/to-do-two

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
# Copyright (c) 2010 Sharkbaitbobby <sharkbaitbobby+awn@gmail.com>
#
# 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 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., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
# To-Do List Applet
# Backends File

import os
import sys
from xml.dom import minidom

import gio

from awn.extras import _

config_dir = os.path.expanduser('~/.config/awn/applets')


class FileBackend:
    def __init__(self):
        self.path = os.path.expanduser('~/.config/awn/applets/to-do.xml')
        self.current_id = '-1'

        if not os.path.exists(config_dir):
            os.makedirs(config_dir)

        self.__lists_monitor = gio.File(self.path).monitor_file()

        def lists_changed_cb(monitor, file, other_file, event):
            if event == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
                self.load_lists()

        self.__lists_monitor.connect('changed', lists_changed_cb)

        self.lists = {}
        self.__getitem__ = self.lists.__getitem__
        self.__setitem__ = self.lists.__setitem__
        self.__iter__ = self.lists.__iter__

        self.load_lists()

    def load_lists(self):
        if os.path.isfile(self.path):
            fp = open(self.path)
            content = fp.read()
            fp.close()

            try:
                self.doc = minidom.parseString(content)
    
                for node in self.doc.documentElement.childNodes:
                    if isinstance(node, minidom.Element):
                        li = List(node)
                        if li['id'] != self.current_id:
                            li.xml = content
                            li.backend = self
                            self[li['id']] = li

            except:
                pass

    def create_list(self):
        _id = 0

        for li in self.lists.values():
            if int(li['id']) > _id:
                _id = int(li['id'])

        li = List({'id': str(_id + 1)})

        self[str(_id + 1)] = li

        return li

    def write(self):
        s = '<?xml version="1.0" encoding="UTF-8"?>\n<todo>'

        for _id, li in self.lists.items():
            p = ''

            for key, val in li.items():
                p += '\n%s=%s' % (key, ncd(str(val)))

            s += '<list>\n<attributes><![CDATA[id=%s%s]]></attributes>\n' % (_id, p)

            for child in li:
                if isinstance(child, Group):
                    p = ''
                    for key, val in child.items():
                        if p == '':
                            p += '%s=%s' % (key, ncd(str(val)))
                        else:
                            p += '\n%s=%s' % (key, ncd(str(val)))

                    s += '<group>\n<attributes><![CDATA[' + p + ']]></attributes>\n'

                    for item in child:
                        p = ''
                        for key, val in item.items():
                            if p == '':
                                p += '%s=%s' % (key, ncd(str(val)))
                            else:
                                p += '\n%s=%s' % (key, ncd(str(val)))

                        s += '<item><![CDATA[%s]]></item>' % p

                    s += '</group>\n'

                else:
                    p = ''
                    for key, val in child.items():
                        if p == '':
                            p += '%s=%s' % (key, ncd(str(val)))
                        else:
                            p += '\n%s=%s' % (key, ncd(str(val)))

                    s += '<item><![CDATA[%s]]></item>' % p

            s += '</list>'

        s += '</todo>'

        fp = open(self.path, 'w+')
        fp.write(s)
        fp.close()

class List:
    def __init__(self, data):
        self.xml = ''
        self.attributes = {}
        self.__getitem__ = self.attributes.__getitem__
        self.__setitem__ = self.attributes.__setitem__
        self.items = self.attributes.items

        self.children = []
        self.__iter__ = self.children.__iter__
        self.__str__ = self.children.__str__

        self.groups = []

        if isinstance(data, minidom.Element):
            self.parse_minidom(data)

        elif isinstance(data, dict):
            self.parse_dict(data)

    def parse_minidom(self, data):
        for node in data.childNodes:
            if isinstance(node, minidom.Element):
                if node.tagName == 'attributes':
                    self.attributes.update(parse_kv(node.childNodes[0].wholeText))

                elif node.tagName == 'group':
                    group = Group(node)
                    self.children.append(group)
                    self.groups.append(group)

                elif node.tagName == 'item':
                    self.children.append(Item(node))

    def parse_dict(self, data):
        for k, v in data.items():
            self[k] = v

        defaults = {'name': _("To-Do List"), 'icon_colors': '000000;444444;888888;FFFFFF',
                    'priority_colors': '008800;FFFFFF;FFFF00;000000;FF0000;FFFFFF',
                    'icon_mode': '0', 'confirm': '3', 'width': '250', 'use_width': '1',
                    'alpha': '100'}

        for k, v in defaults.items():
            if k not in self.attributes:
                self[k] = v

    def add(self, item):
        self.children.append(item)

        if isinstance(item, Group):
            self.groups.append(item)

    def __len__(self):
        num = 0
        for child in self.children:
            if isinstance(child, Group):
                num += len(child.children)
            else:
                num += 1

        return num

    def remove(self, child):
        if isinstance(child, Group):
            self.groups.remove(child)

        self.children.remove(child)

        del child

    def write(self):
        self.backend.write()

class Group:
    def __init__(self, data):
        self.attributes = {}
        self.__getitem__ = self.attributes.__getitem__
        self.__setitem__ = self.attributes.__setitem__
        self.items = self.attributes.items

        self.children = []
        self.__iter__ = self.children.__iter__
        self.__len__ = self.children.__len__
        self.__str__ = self.children.__str__
        self.add = self.children.append

        if isinstance(data, minidom.Element):
            self.parse_minidom(data)

        elif isinstance(data, dict):
            self.parse_dict(data)

    def parse_minidom(self, data):
        for node in data.childNodes:
            if isinstance(node, minidom.Element):
                if node.tagName == 'attributes':
                    self.attributes.update(parse_kv(node.childNodes[0].wholeText))

                elif node.tagName == 'item':
                    self.children.append(Item(node, self))

    def parse_dict(self, data):
        defaults = {'name': '', 'expanded': '1', 'details': ''}
        self.attributes.update(defaults)
        self.attributes.update(data)

    def remove(self, item):
        self.children.remove(item)

        del item

class Item:
    def __init__(self, data, group=None):
        self.attributes = {}
        self.group = group

        if isinstance(data, minidom.Element):
            self.parse_minidom(data)

        elif isinstance(data, dict):
            self.parse_dict(data)

        self.__getitem__ = self.attributes.__getitem__
        self.__setitem__ = self.attributes.__setitem__
        self.__str__ = self.attributes.__str__
        self.items = self.attributes.items

    def parse_minidom(self, data):
        for node in data.childNodes:
            if isinstance(node, minidom.CDATASection):
                self.attributes.update(parse_kv(node.wholeText))

    def parse_dict(self, data):
        defaults = {'name': '', 'priority': '0', 'progress': '0', 'details': ''}
        self.attributes.update(defaults)
        self.attributes.update(data)

def parse_kv(data):
    d = {}
    in_details = False
    for line in data.split('\n'):
        if line.strip() != '':
            if in_details:
                d['details'] += '\n' + line
            else:
                d[line.split('=')[0]] = line.split('=')[1]
                if line.split('=')[0] == 'details':
                    in_details = True

    return d

def ncd(s):
    while ']]>' in s:
      s =  s.replace(']]>', ']>')

    return s

FileBackend()