Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 3 migration, #153 fix #174

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.textile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ for everyday use. For stable versions check out "releases":https://github.com/pr

h1. Requires most recent stable gtk3 (3.10)

Version of gtk required is 3.10 because of the use of HeaderBar and other bits.
Version of gtk required is 3.10 because of the use of HeaderBar and other bits.
Sorry and get up to date!


Expand All @@ -26,6 +26,9 @@ pre. killall hamster-service && killall hamster-windows-service

Now restart your panels/dockies and you should be able to add hamster to your panel!

To allow immidiate focus on hamster window, in Ubuntu go to
CompizConfig->General->Focus & Raise Behavior and add hamster to exceprions:
!(class=Polkit-gnome-authentication-agent-1 | class=Hamster-windows-service)

h1. hamster-applet -> hamster-time-tracker clean up

Expand All @@ -36,4 +39,3 @@ the applet is long gone, the paths and file names have changed to
pre. git checkout d140d45f105d4ca07d4e33bcec1fae30143959fe
./waf configure build --prefix=/usr
sudo ./waf uninstall

2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
import distutils
import os
from distutils.core import setup
Expand Down
59 changes: 29 additions & 30 deletions src/hamster-cli
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# - coding: utf-8 -

# Copyright (C) 2010 Matías Ribecky <matias at mribecky.com.ar>
Expand Down Expand Up @@ -32,7 +32,7 @@ from hamster.lib import Fact, stuff


def word_wrap(line, max_len):
"""primitive word wrapper"""
"""A primitive word wrapper."""
lines = []
cur_line, cur_len = "", 0
for word in line.split():
Expand Down Expand Up @@ -84,7 +84,7 @@ _DATETIME_PATTERN = ('^((?P<relative>-\d.+)?|('
'(?P<rest>\D.+)?$')
_DATETIME_REGEX = re.compile(_DATETIME_PATTERN)
def parse_datetime_range(arg):
'''Parse a date and time.'''
'''Parse a date and a time.'''
match = _DATETIME_REGEX.match(arg)
if not match:
return None, None
Expand Down Expand Up @@ -142,7 +142,7 @@ class HamsterClient(object):
"/org/gnome/Hamster/WindowServer")
getattr(server, window_name)()
else:
print "Running in devel mode"
print("Running in devel mode")
from gi.repository import Gtk as gtk
from hamster.lib.configuration import dialogs
getattr(dialogs, window_name).show()
Expand Down Expand Up @@ -173,30 +173,29 @@ class HamsterClient(object):
formats = "html tsv xml ical".split()
chosen = sys.argv[-1]
formats = [f for f in formats if not chosen or f.startswith(chosen)]
print "\n".join(formats)
print("\n".join(formats))


def toggle(self):
self.storage.toggle()

def track(self, *args):
"""same as start"""
"""Same as start."""
self.start(*args)


def start(self, *args):
'''Start a new activity.'''
if not args:
print "Error: please specify activity"
print("Error: please specify an activity.")
return

activity = args[0]
start_time, end_time = parse_datetime_range(" ".join(args[1:]))
start_time = start_time or dt.datetime.now()

self.storage.add_fact(Fact(activity,
start_time = start_time,
end_time = end_time))
self.storage.add_fact(
Fact(activity, start_time = start_time, end_time = end_time))


def stop(self, *args):
Expand All @@ -216,7 +215,7 @@ class HamsterClient(object):
facts = self.storage.get_facts(start_time, end_time)

writer = reports.simple(facts, start_time, end_time, export_format)
print writer.export()
print(writer.export())


def _activities(self, search=""):
Expand All @@ -225,24 +224,24 @@ class HamsterClient(object):
activity, category = search.split("@")
for cat in self.storage.get_categories():
if not category or cat['name'].lower().startswith(category.lower()):
print "%s@%s" % (activity.encode("utf8"), cat['name'].encode("utf8"))
print("%s@%s" % (activity, cat['name']))
else:
for activity in self.storage.get_activities(search):
print activity['name'].encode('utf8')
print(activity['name'])
if activity['category']:
print '%s@%s' % (activity['name'].encode('utf8'), activity['category'].encode('utf8'))
print('%s@%s' % (activity['name'], activity['category']))


def activities(self, *args):
'''Print the names of all the activities.'''
search = args[0] if args else ""
for activity in self.storage.get_activities(search):
print '%s@%s' % (activity['name'].encode('utf8'), activity['category'].encode('utf8'))
print('%s@%s' % (activity['name'], activity['category']))

def categories(self, *args):
'''Print the names of all the categories.'''
for category in self.storage.get_categories():
print category['name'].encode('utf8')
print(category['name'])


def list(self, *times):
Expand All @@ -258,10 +257,10 @@ class HamsterClient(object):
"""prints current activity. kinda minimal right now"""
facts = self.storage.get_todays_facts()
if facts and not facts[-1].end_time:
print "%s %s" % (unicode(facts[-1]).encode("utf-8").strip(),
stuff.format_duration(facts[-1].delta, human=False))
print("%s %s" % (str(facts[-1]).strip(),
stuff.format_duration(facts[-1].delta, human=False)))
else:
print _("No activity")
print(_("No activity"))


def search(self, *args):
Expand Down Expand Up @@ -309,9 +308,9 @@ class HamsterClient(object):

row_width = sum([val + 3 for val in widths.values()])

print
print fact_line.format(**headers)
print "-" * min(row_width, 80)
print()
print(fact_line.format(**headers))
print("-" * min(row_width, 80))

by_cat = {}
for fact in facts:
Expand All @@ -320,26 +319,26 @@ class HamsterClient(object):
by_cat[cat] += fact.delta

pretty_fact = fact_dict(fact, print_with_date)
print fact_line.format(**pretty_fact)
print(fact_line.format(**pretty_fact))

if pretty_fact['description']:
for line in word_wrap(pretty_fact['description'], 76):
print " %s" % line
print(" %s" % line)

if pretty_fact['tags']:
for line in word_wrap(pretty_fact['tags'], 76):
print " %s" % line
print(" %s" % line)

print "-" * min(row_width, 80)
print("-" * min(row_width, 80))

cats = []
for cat, duration in sorted(by_cat.iteritems(), key=lambda x: x[1], reverse=True):
for cat, duration in sorted(by_cat.items(), key=lambda x: x[1], reverse=True):
cats.append("%s: %s" % (cat, "%.1fh" % (stuff.duration_minutes(duration) / 60.0)))

for line in word_wrap(", ".join(cats), 80):
print line
print(line)

print
print()



Expand All @@ -362,7 +361,7 @@ Actions:
* activities: List all the activities names, one per line.
* categories: List all the categories names, one per line.

* overview / statistics / about: launch specific window
* overview / statistics / about / add : launch specific window

Time formats:
* 'YYYY-MM-DD hh:mm:ss': If date is missing, it will default to today.
Expand Down
14 changes: 7 additions & 7 deletions src/hamster-service
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
#!/usr/bin/python
# nicked off gwibber
#!/usr/bin/env python3

from gi.repository import GObject as gobject
from gi.repository import GLib as glib
from gi.repository import Gio as gio

import dbus, dbus.service
from dbus.mainloop.glib import DBusGMainLoop
import datetime as dt
from calendar import timegm
from gi.repository import Gio as gio

DBusGMainLoop(set_as_default=True)
loop = gobject.MainLoop()
loop = glib.MainLoop()

if "org.gnome.Hamster" in dbus.SessionBus().list_names():
print "Found hamster-service already running, exiting"
print("Found hamster-service already running, exiting")
quit()

from hamster.lib import i18n
Expand Down Expand Up @@ -89,7 +89,7 @@ class Storage(db.Storage, dbus.service.Object):
# anyway. should make updating simpler
def _on_us_change(self, monitor, gio_file, event_uri, event):
if event == gio.FileMonitorEvent.CHANGES_DONE_HINT:
print "`%s` has changed. Quitting!" % __file__
print("`%s` has changed. Quitting!" % __file__)
self.Quit()

@dbus.service.signal("org.gnome.Hamster")
Expand Down Expand Up @@ -303,6 +303,6 @@ class Storage(db.Storage, dbus.service.Object):


if __name__ == '__main__':
print "hamster-service up"
print("hamster-service up")
storage = Storage(loop)
loop.run()
14 changes: 6 additions & 8 deletions src/hamster-windows-service
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
#!/usr/bin/python
# nicked off hamster-service

#!/usr/bin/env python3
from gi.repository import GObject as gobject
import dbus, dbus.service
import glib
from gi.repository import GLib as glib
from dbus.mainloop.glib import DBusGMainLoop

DBusGMainLoop(set_as_default=True)
loop = gobject.MainLoop()
loop = glib.MainLoop()

if "org.gnome.Hamster.WindowServer" in dbus.SessionBus().list_names():
print "Found hamster-window-service already running, exiting"
print("Found hamster-window-service already running, exiting")
quit()


Expand Down Expand Up @@ -50,11 +48,11 @@ if __name__ == '__main__':
from hamster.lib import i18n
i18n.setup_i18n()

glib.set_prgname(unicode(_("hamster-windows-service")).encode("utf-8"))
glib.set_prgname("hamster-windows-service")

from hamster.lib.configuration import runtime, dialogs, conf, load_ui_file
window_server = WindowServer(loop)

print "hamster-window-service up"
print("hamster-window-service up")

loop.run()
2 changes: 1 addition & 1 deletion src/hamster.bash
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ _hamster()
#
# The basic options we'll complete.
#
opts="activities categories current export list search start stop "
opts="activities categories current export list search start stop add overview"


#
Expand Down
4 changes: 2 additions & 2 deletions src/hamster/about.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ def __init__(self, parent = None):
"program-name" : _("Time Tracker"),
"name" : _("Time Tracker"), #this should be deprecated in gtk 2.10
"version" : runtime.version,
"comments" : _(u"Project Hamster — track your time"),
"copyright" : _(u"Copyright © 2007–2010 Toms Bauģis and others"),
"comments" : _("Project Hamster — track your time"),
"copyright" : _("Copyright © 2007–2014 Toms Bauģis and others"),
"website" : "http://projecthamster.wordpress.com/",
"website-label" : _("Project Hamster Website"),
"title": _("About Time Tracker"),
Expand Down
9 changes: 4 additions & 5 deletions src/hamster/edit_activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@
""" TODO: hook into notifications and refresh our days if some evil neighbour
edit fact window has dared to edit facts
"""
import widgets
from . import widgets
from hamster.lib.configuration import runtime, conf, load_ui_file
from lib import Fact
from .lib import Fact

class CustomFactController(gobject.GObject):
__gsignals__ = {
Expand All @@ -49,7 +49,7 @@ def __init__(self, parent=None, fact_date=None, fact_id=None):
self.get_widget("activity_box").add(self.activity)

day_start = conf.get("day_start_minutes")
self.day_start = dt.time(day_start / 60, day_start % 60)
self.day_start = dt.time(day_start // 60, day_start % 60)

self.date = fact_date
if not self.date:
Expand Down Expand Up @@ -111,8 +111,7 @@ def show(self):

def figure_description(self):
buf = self.get_widget('description').get_buffer()
description = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), 0)\
.decode("utf-8")
description = buf.get_text(buf.get_start_iter(), buf.get_end_iter(), 0)
return description.strip()


Expand Down
2 changes: 1 addition & 1 deletion src/hamster/external.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,6 @@ def get_eds_tasks():
if task.get_status() in [ecal.ICAL_STATUS_NONE, ecal.ICAL_STATUS_INPROCESS]:
tasks.append({'name': task.get_summary(), 'category' : category})
return tasks
except Exception, e:
except Exception as e:
logging.warn(e)
return []
10 changes: 5 additions & 5 deletions src/hamster/lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ def figure_time(str_time):
# strip everything non-numeric and consider hours to be first number
# and minutes - second number
numbers = re.split("\D", str_time)
numbers = filter(lambda x: x!="", numbers)
numbers = [x for x in numbers if x != ""]

hours, minutes = None, None

Expand Down Expand Up @@ -48,7 +48,7 @@ def __init__(self, activity, category = "", description = "", tags = "",
self.date = date
self.activity_id = activity_id

for key, val in parse_fact(activity).iteritems():
for key, val in parse_fact(activity).items():
setattr(self, key, val)


Expand All @@ -66,10 +66,10 @@ def __iter__(self):
'activity': self.activity,
'category': self.category,
'description': self.description,
'tags': [tag.encode("utf-8").strip() for tag in self.tags],
'tags': [tag.strip() for tag in self.tags],
'date': calendar.timegm(self.date.timetuple()) if self.date else "",
'start_time': self.start_time if isinstance(self.start_time, basestring) else calendar.timegm(self.start_time.timetuple()),
'end_time': self.end_time if isinstance(self.end_time, basestring) else calendar.timegm(self.end_time.timetuple()) if self.end_time else "",
'start_time': self.start_time if isinstance(self.start_time, str) else calendar.timegm(self.start_time.timetuple()),
'end_time': self.end_time if isinstance(self.end_time, str) else calendar.timegm(self.end_time.timetuple()) if self.end_time else "",
'delta': self.delta.seconds + self.delta.days * 24 * 60 * 60 if self.delta else "" #duration in seconds
}
return iter(keys.items())
Expand Down
2 changes: 1 addition & 1 deletion src/hamster/lib/charting.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from gi.repository import Pango as pango
import datetime as dt
import time
import graphics, stuff
from . import graphics, stuff
import locale

class Bar(graphics.Sprite):
Expand Down
Loading