~gtg-user/gtg/bugfix-516392

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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!/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.
# -----------------------------------------------------------------------------

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

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

from GTG import _

MSG_ERROR_TASK_ID_INVALID = '[Error] Task ID Invalid'


def usage():
    """ Print usage info """
    spaces = "  %-30s %s\n"

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

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

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

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


def connect_to_gtg():
    """ Connect and return GTG DBus interface.

    This function handles possible errors while connecting to GTG """
    try:
        bus = dbus.SessionBus()
    except dbus.exceptions.DBusException, err:
        if "X11 initialization failed" in err.get_dbus_message():
            os.environ['DISPLAY'] = ":0"
            bus = dbus.SessionBus()
        else:
            print "dbus exception: '%s'" % err
            raise

    proxy = bus.get_object("org.gnome.GTG", "/org/gnome/GTG")
    return dbus.Interface(proxy, "org.gnome.GTG")


def new_task(title):
    """ Create a new task with given title

    Body of the new task is read from stdin. If it contains Subject:,
    add it to the title.
    (It is handy, when forwarding e-mail to this script). """

    subject_regex = re.compile("^Subject: (.*)$", re.M | re.I)
    body = sys.stdin.read()
    if subject_regex.search(body):
        subject = subject_regex.findall(body)[0]
        title = title + ": " + subject

    gtg = connect_to_gtg()
    gtg.NewTask("Active", title, '', '', '', [], cgi.escape(body), [])


def delete_tasks(task_ids):
    """ Delete tasks from GTG """
    gtg = connect_to_gtg()
    for task_id in task_ids.split():
        gtg.DeleteTask(task_id)


def close_tasks(task_ids):
    """ Marks tasks as closed """
    gtg = connect_to_gtg()
    for task_id in task_ids.split():
        task = gtg.GetTask(task_id)
        if task:
            task['status'] = "Done"
            gtg.ModifyTask(task_id, task)
        else:
            print MSG_ERROR_TASK_ID_INVALID
            sys.exit(1)


def show_tasks(task_ids):
    """ Displays information about tasks """
    gtg = connect_to_gtg()
    for task_id in task_ids.split():
        task = gtg.GetTask(task_id)
        if task:
            content_regex = re.compile(r"<content>(.+)</content>", re.DOTALL)

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

            print task['title']
            if len(task['tags'])>0:
                print " %-12s %s" % ('tags:', task['tags'][0])
            for k in ['id', 'startdate', 'duedate', 'status']:
                print " %-12s %s" % (k + ":", task[k])
            if len(task['parents'])>0:
                print " %-12s %s" % ('parents:', task['parents'][0])
            print
            print content
            print
        else:
            print MSG_ERROR_TASK_ID_INVALID
            sys.exit(1)


def postpone(args):
    """ Change the start date of a task """
    gtg = connect_to_gtg()
    identifier, startdate = args.split()[:2]

    tasks = []
    if identifier[0] == '@':
        filters = _criteria_to_filters(identifier)
        filters.extend(['active', 'workview'])
        gtg = connect_to_gtg()
        tasks = gtg.GetTasksFiltered(filters)
    else:
        tasks = [gtg.GetTask(identifier)]

    for task in tasks:
        if task:
            task['startdate'] = startdate
            tags = ", ".join(task['tags'])
            print "%-12s %-20s %s" % (task['id'], tags, task['title'])
            gtg.ModifyTask(task['id'], task)
        else:
            print MSG_ERROR_TASK_ID_INVALID
            sys.exit(1)


def edit_tasks(task_ids):
    """ Open tasks in the task editor GUI """
    gtg = connect_to_gtg()
    for task in task_ids.split():
        gtg.OpenTaskEditor(task)


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


def _criteria_to_filters(criteria):
    """ Convert user input for filtering into GTG filters """
    criteria = criteria
    if criteria in ['', 'all']:
        filters = ['active']
    else:
        filters = criteria.split()

    # 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)
    gtg = connect_to_gtg()
    tasks = gtg.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 criteria in ['', 'all']:
        criteria = 'workable'

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

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


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

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

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


def list_tasks(criteria):
    """ 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)
    gtg = connect_to_gtg()
    tasks = gtg.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 = [fname for fname in filters if fname.startswith('@')]
    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=' ' * 40)
            print "  %-36s  %s" % (task['id'], text)


def search_tasks(expression):
    """ Search Tasks according to expression"""
    gtg = connect_to_gtg()
    tasks = gtg.SearchTasks(expression)
    for task in tasks:
        text = textwrap.fill(task['title'],
                             initial_indent='',
                             subsequent_indent=' ' * 40)
        print "  %-36s  %s" % (task['id'], text)


def run_command(args):
    """ Run command and check for its minimal required arguments """

    def minimal_args(count):
        """ Check the minimal required arguments """
        if len(args) < count + 1:
            usage()
            sys.exit(1)

    minimal_args(0)
    commands = [
      (("new", "add"), 0, new_task),
      (("list"), 0, list_tasks),
      (("count"), 0, count_tasks),
      (("summary"), 0, summary_of_tasks),
      (("rm", "delete"), 1, delete_tasks),
      (("close"), 1, close_tasks),
      (("postpone"), 2, postpone),
      (("show"), 1, show_tasks),
      (("edit"), 1, edit_tasks),
      (("browser"), 0, toggle_browser_visibility),
      (("search"), 1, search_tasks),
    ]

    for aliases, min_args, command in commands:
        if args[0] in aliases:
            minimal_args(min_args)
            criteria = " ".join(args[1:]).strip()
            return command(criteria)

    sys.stderr.write("Unknown command '%s'\n" % args[0])
    usage()
    sys.exit(1)


def main():
    """ Parse arguments and launch command """
    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 opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit(0)
        else:
            assert False, "unhandled option %s=%s" % (opt, arg)

    run_command(args)


if __name__ == '__main__':
    main()