~gtg-contributors/gtg/tracks

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
366
#!/usr/bin/env python
# -*- coding:utf-8 -*-

'''Command line user interface for manipulating tasks in gtg.

Copyright (C) 2010 Bryce W. Harrington

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.  See http://www.gnu.org/copyleft/gpl.html for
the full text of the license.
'''

import re
import sys
import os
import dbus
import cgi
import getopt
import textwrap
from datetime import datetime, date, timedelta
from string import split

def _(text):
    return text

def usage():
    f = "  %-30s %s\n"
    progname = sys.argv[0]

    text = _("gtcli -- a command line interface to gtg\n")
    text += "\n"

    text += _("Options:\n")
    text += f%( "-h, --help", _("This help") )
    text += "\n"

    text += _("Basic commands:\n")
    text += f%( "gtcli new", _("Create a new task") )
    text += f%( "gtcli show <tid>", _("Display detailed information on given task id") )
    text += f%( "gtcli edit <tid>", _("Opens the GUI editor for the given task id") )
    text += f%( "gtcli delete <tid>", _("Removes task identified by tid") )
    text += f%( "gtcli list [all|today|<filter>|<tag>]...", _("List tasks") )
    text += f%( "gtcli count [all|today|<filter>|<tag>]...", _("Number of tasks") )
    text += f%( "gtcli summary [all|today|<filter>|<tag>]...", _("Report how many tasks starting/due each day") )
    text += f%( "gtcli postpone <tid> <date>", _("Updates the start date of task") )
    text += f%( "gtcli close <tid>", _("Sets state of task identified by tid to closed") )
    text += f%( "gtcli browse [hide|show]", _("Hides or shows the task browser window"))

    text += "\n"
    text += "http://gtg.fritalk.com/\n"
    sys.stderr.write( text )

def die(code=1, err=None):
    if err:
        sys.stderr.write(str(err))
    sys.exit(code)

def connect_to_gtg():
    try:
        bus = dbus.SessionBus()
    except dbus.exceptions.DBusException, e:
        if "X11 initialization failed" in e.get_dbus_message():
            os.environ['DISPLAY'] = ":0"
            bus = dbus.SessionBus()
        else:
            print "dbus exception: '%s'" %(err)
            raise

    liste = bus.list_names()
    busname = "org.gnome.GTG"
    remote_object = bus.get_object(busname,"/org/gnome/GTG")
    return dbus.Interface(remote_object,dbus_interface="org.gnome.GTG")

def new_task(title, body):
    """ Retrieve task via dbus """
    timi = connect_to_gtg()
    timi.NewTask("Active", title, '', '', '', [], body, [])

def delete_task(tid):
    """ Remove a task via dbus """
    timi = connect_to_gtg()
    timi.DeleteTask(tid)

def close_task(tid):
    """ Marks a task closed """
    timi = connect_to_gtg()
    task_data = timi.GetTask(tid)
    task_data['status'] = "Done"
    timi.ModifyTask(tid, task_data)

def show_task(tid):
    """ Displays a given task """
    timi = connect_to_gtg()
    task_data = timi.GetTask(tid)
    content_regex = re.compile(r"<content>(.+)</content>", re.DOTALL)

    content = task_data['text'] + "\n(unknown)"
    m = content_regex.match(task_data['text'])
    if m:
        content = m.group(1)

    print task_data['title']
    if len(task_data['tags'])>0:
        print " %-12s %s" %('tags:', task_data['tags'][0])
    for k in ['id', 'startdate', 'duedate', 'status']:
        print " %-12s %s" %(k+":", task_data[k])
    if len(task_data['parents'])>0:
        print " %-12s %s" %('parents:', task_data['parents'][0])
    print
    print content

def postpone(identifier, startdate):
    """ Change the start date of a task """
    timi = connect_to_gtg()
    
    tasks = []
    if identifier[0] == '@':
        filters = _criteria_to_filters(identifier)
        filters.extend(['active','workview'])
        timi = connect_to_gtg()
        tasks = timi.GetTasksFiltered(filters)
    else:
        tasks = [ timi.GeTask(identifier) ]

    for task in tasks:
        task['startdate'] = startdate
        print "%-12s %-20s %s" %(task['id'], ", ".join(task['tags']), task['title'])
        timi.ModifyTask(task['id'], task)

def open_task_editor(tid):
    """ Load task in the task editor gui """
    timi = connect_to_gtg()
    task_data = timi.OpenTaskEditor(tid)

def toggle_browser_visibility(state):
    """ Cause the task browser to be displayed """
    timi = connect_to_gtg()
    if state == "hide":
        timi.HideTaskBrowser()
    elif state == "minimize" or state == "iconify":
        if not timi.IsTaskBrowserVisible():
            timi.ShowTaskBrowser()
        timi.IconifyTaskBrowser()
    else:
        timi.ShowTaskBrowser()

def _criteria_to_filters(criteria):
    if not criteria:
        filters = ['active']
    else:
        filters = split(criteria, ' ')
    
    # Special case 'today' filter
    if 'today' in filters:
        filters.extend(['active', 'workview'])
        filters.remove('today')
    return filters

def count_tasks(criteria):
    """ Print a simple count of tasks matching criteria """

    filters = _criteria_to_filters(criteria)
    timi = connect_to_gtg()
    tasks = timi.GetTasksFiltered(filters)

    total = 0
    for task in tasks:
        if 'title' not in task:
            continue
        total += 1

    print total
    return total

def summary_of_tasks(criteria):
    """ Print report showing number of tasks starting and due each day """

    if not criteria:
        criteria = 'workable'

    filters = _criteria_to_filters(criteria)
    filters.append('active')
    timi = connect_to_gtg()
    tasks = timi.GetTasksFiltered(filters)

    report = { }
    for t in tasks:
        if not t['startdate']:
            startdate = 'unscheduled'
        elif datetime.strptime(t['startdate'], "%Y-%m-%d") < datetime.today():
            startdate = date.today().strftime("%Y-%m-%d")
        else:
            startdate = t['startdate']

        if startdate not in report:
            report[startdate] = { 'starting':0, 'due':0 }
        report[startdate]['starting'] += 1

        duedate = t['duedate'] or 'never'
        if duedate not in report:
            report[duedate] = { 'starting':0, 'due':0 }
        report[duedate]['due'] += 1

    day = date.today()
    print "%-20s %5s %5s" %("", "Start", "Due")
    if report.has_key('unscheduled'):
        print "%-20s %5d %5d" %('unscheduled', 
                                report['unscheduled']['starting'],
                                report['unscheduled']['due'])
    num_days = 22
    fmt = "%a  %-m-%-d"
    if criteria and 'today' in criteria:
        num_days = 1
    for i in range(0, num_days):
        d = day + timedelta(i)
        dstr = str(d)
        if dstr in report:
            print "%-20s %5d %5d" %(d.strftime(fmt),
                                    report[dstr]['starting'],
                                    report[dstr]['due'])
        else:
            print "%-20s %5d %5d" %(d.strftime(fmt), 0, 0)
            

def list_tasks(criteria, count_only=False):
    """ Display a listing of tasks 
    
    Accepts any filter or combination of filters or tags to limit the
    set of tasks shown.  If multiple tags specified, it lists only tasks
    that have all the tags.  If no filters or tags are specified,
    defaults to showing all active tasks.
    """

    filters = _criteria_to_filters(criteria)
    timi = connect_to_gtg()
    tasks = timi.GetTasksFiltered(filters)

    tasks_tree = { }
    notag = '@__notag'
    for task in tasks:
        if 'title' not in task:
            continue
        if not task['tags'] or len(task['tags']) == 0:
            if notag not in tasks_tree:
                tasks_tree[notag] = []
            tasks_tree[notag].append(task)
        else:
            tags = []
            for tag in list(task['tags']):
                tags.append(tag)
                if tag not in tasks_tree:
                    tasks_tree[tag] = []
                tasks_tree[tag].append(task)

    # If any tags were specified, use only those as the categories
    keys = [t for t in filters if t[0]=='@']
    if not keys:
        keys = tasks_tree.keys()
        keys.sort()

    for key in keys:
        if key not in tasks_tree:
            continue
        if key != notag:
            print "%s:" %(key[1:])
        for task in tasks_tree[key]:
            text = textwrap.fill(task['title'], 
                                 initial_indent='',
                                 subsequent_indent='                                        ')
            print "  %-36s  %s" %(task['id'], text)

if __name__ == '__main__':
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], "h", ["help"])
    except getopt.GetoptError, err:
        sys.stderr.write("Error: " + str(err) + "\n\n")
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        else:
            assert False, "unhandled option"

    if len(args) < 1:
        usage()
        sys.exit(2)

    command = args[0]

    if command == "new" or command == "add":
        subject_regex = re.compile("^Subject: (.*)$", re.M | re.I)

        title = " ".join(args[1:])
        body = sys.stdin.read()
        if subject_regex.search(body):
            subject = subject_regex.findall(body)[0]
            title = title + ": " + subject

        new_task(title, cgi.escape(body))

    elif command == "list":
        criteria = None
        if len(args)>1:
            criteria = ' '.join(args[1:])
        list_tasks(criteria, False)

    elif command == "count":
        criteria = None
        if len(args)>1:
            criteria = ' '.join(args[1:])
        count_tasks(criteria)

    elif command == "summary":
        criteria = None
        if len(args)>1:
            criteria = ' '.join(args[1:])
        summary_of_tasks(criteria)

    elif command == "rm" or command == "delete":
        if len(args)<2:
            usage()
            sys.exit(1)
        for tid in args[1:]:
            delete_task(tid)

    elif command == "close":
        if len(args)<2:
            usage()
            sys.exit(1)
        for tid in args[1:]:
            close_task(tid)

    elif command == "postpone":
        if len(args)<3:
            usage()
            sys.exit(1)
        postpone(args[1], args[2])

    elif command == "show":
        if len(args)<2:
            usage()
            sys.exit(1)
        for tid in args[1:]:
            show_task(tid)

    elif command == "edit":
        if len(args)<2:
            usage()
            sys.exit(1)
        for tid in args[1:]:
            open_task_editor(tid)

    elif command == "browse":
        state = None
        if len(args)>1:
            state = args[1]
        toggle_browser_visibility(state)

    else:
        die("Unknown command '%s'\n" %(command))