From e5a8d777b6f25e93ce87cced013fb8794fefd55b Mon Sep 17 00:00:00 2001 From: mfrasca <> Date: Thu, 24 May 2007 12:17:10 +0000 Subject: [PATCH] 1723946: weekday is not updated correctly I've almost completely rewritten the program, cleaned up most stuff which has become useless in the object oriented framework. the strings are not any more centered, this has not yet been programmed in the library. --- MANIFEST | 5 + examples/pywmdatetime.py | 348 ++++++++++++++------------------------- examples/pywmradio.py | 1 - wmdocklib/wmoo.py | 16 +- 4 files changed, 142 insertions(+), 228 deletions(-) diff --git a/MANIFEST b/MANIFEST index 2bc690b..e405fea 100644 --- a/MANIFEST +++ b/MANIFEST @@ -21,20 +21,25 @@ wmdocklib/4x6.xpm wmdocklib/4x7.xpm wmdocklib/5x7-aa.xpm wmdocklib/5x7.xpm +wmdocklib/5x8-utf-8.xpm wmdocklib/5x8.xpm wmdocklib/5x9.xpm wmdocklib/6(3)x8-7seg.xpm +wmdocklib/6x11-utf-8.xpm wmdocklib/6x12.xpm wmdocklib/6x8-7seg.xpm wmdocklib/6x8.xpm wmdocklib/6x8orig.xpm wmdocklib/6x8slant.xpm wmdocklib/7x12-41c.xpm +wmdocklib/7x14-utf-8.xpm wmdocklib/7x8zx.xpm wmdocklib/8x12-41c.xpm +wmdocklib/8x13-utf-8.xpm wmdocklib/8x8-cholo.xpm wmdocklib/8x8.xpm wmdocklib/8x8zx.xpm +wmdocklib/9x18-utf-8.xpm wmdocklib/README wmdocklib/__init__.py wmdocklib/pywmgeneral.c diff --git a/examples/pywmdatetime.py b/examples/pywmdatetime.py index 5d4dc42..59e8631 100755 --- a/examples/pywmdatetime.py +++ b/examples/pywmdatetime.py @@ -26,30 +26,12 @@ Added event handling for graceful shutdown 2003-06-16 Kristoffer Erlandsson First workingish version """ -usage = """pywmdatetime.py [options] -Available options are: --h, --help print this help --f, --foreground set the foreground color --b, --background set the background color --F, --font set the font name --t, --timeformat set the time format --d, --dateformat set the date format --y, --weekdayformat set the weekday format --e, --weekformat set the week format --r, --rgbfile set the rgb file to get color codes from --c, --configfile set the config file to use ---debug shows the pixmap - -The formats are the same as Python's strftime() accept. See the sample -rc-file for more information about this. -""" import sys import time -import getopt import os -import wmdocklib +from wmdocklib import wmoo, readConfigFile width = 64 height = 64 @@ -57,163 +39,6 @@ height = 64 xOffset = 4 yOffset = 4 -timeDefaultFormat = '%H:%M:%S' -dateDefaultFormat = '%d-%m-%y' -dayDefaultFormat = '%A' -weekDefaultFormat = 'wk %q' # %q added by Kristoffer for different week calculation. - -defaultConfigFile = '~/.pywmdatetimerc' -maxCharsPerLine = None - -def addString(s, x, y): - try: - wmdocklib.addString(s, x, y, xOffset, yOffset, - width, height) - except ValueError, e: - sys.stderr.write('Error when painting string:\n' + str(e) + '\n') - sys.stderr.write('test %s' % ((s, x, y, xOffset, yOffset, - width, height),)) - raise - sys.exit(3) - -def addTimeString(s, x, y): - for c in s: - charW = 7 - charX = (ord(c) - ord('0')) * 7 - charY = 64 - if not c.isdigit(): - charX = 70 - charW = 3 - wmdocklib.copyXPMArea(charX, charY, charW, 10, x+xOffset+1, y+yOffset) - x += charW - -def clearLine(y): - '''Clear a line of text at position y.''' - wmdocklib.copyXPMArea(73, yOffset, width - 2 * xOffset, char_height, - xOffset, y + yOffset) - -def getCenterStartPos(s): - return wmdocklib.getCenterStartPos(s, width, xOffset) - -def getVertSpacing(numLines, margin): - return wmdocklib.getVertSpacing(numLines, margin-1, height, yOffset) + 1 - -def calculateWeek(localTime): - """Calculate the week number as we do, for example in Sweden. - - That is, add one to the %W format if the year didn't start on a monday.""" - day = int(time.strftime('%j', localTime)) - weekDay = int(time.strftime('%w')) - 1 - if weekDay == -1: - weekDay = 6 - lastMonday = day - weekDay - if lastMonday % 7 == 0: - return int(time.strftime('%W')) - return int(time.strftime('%W')) + 1 - -def parseCommandLine(argv): - """Parse the commandline. Return a dictionary with options and values.""" - shorts = 'hf:b:t:d:e:y:r:c:F:a' - longs = ['antialiased', 'help', 'foreground=', 'background=', - 'timeformat=', 'dateformat=', 'debug', - 'weekdayformat=', 'weekformat=', 'rgbfile=', 'configfile=', 'font='] - try: - opts, nonOptArgs = getopt.getopt(argv[1:], shorts, longs) - except getopt.GetoptError, e: - sys.stderr.write('Error when parsing commandline: ' + str(e) + '\n') - sys.stderr.write(usage) - sys.exit(2) - d = {} - - for o, a in opts: - if o in ('-h', '--help'): - sys.stdout.write(usage) - sys.exit(0) - if o in ('-a', '--antialiased'): - d['antialiased'] = True - if o in ('-f', '--foreground'): - d['foreground'] = a - if o in ('-F', '--font'): - d['font'] = a - if o in ('-b', '--background'): - d['background'] = a - if o in ('-t', '--timeformat'): - d['timeformat'] = a - if o in ('-d', '--dateformat'): - d['dateformat'] = a - if o in ('-y', '--weekdayformat'): - d['weekdayformat'] = a - if o in ('-e', '--weekformat'): - d['weekformat'] = a - if o in ('-r', '--rgbfile'): - d['rgbfile'] = a - if o in ('-c', '--configfile'): - d['configfile'] = a - if o in ('--debug'): - d['debug'] = True - return d - -def checkForEvents(): - event = wmdocklib.getEvent() - while not event is None: - if event['type'] == 'destroynotify': - sys.exit(0) - event = wmdocklib.getEvent() - -def mainLoop(timeFmt, dateFmt, dayFmt, weekFmt): - recalcWeek = weekFmt.find('%q') + 1 # True if we found %q. - newWeekFmt = weekFmt - counter = -1 - lastStrs = [''] * 4 - while 1: - counter += 1 - checkForEvents() - lt = time.localtime() - timeStr = time.strftime(timeFmt, lt)[:maxCharsPerLine] - timeX = 3 - if antialiased: - margin = 6 - spacing = getVertSpacing(4, margin) - if lastStrs[0] != timeStr: - addTimeString(timeStr, timeX, margin-4) - margin += 3 - else: - margin = 4 - spacing = getVertSpacing(4, margin) - if lastStrs[0] != timeStr: - addString(timeStr, timeX, margin) - lastStrs[0] = timeStr - if counter % 100 == 0: - # We only perform the date/week checks/updates once every 100th - # iteration. We will maybe lag behind a couple of seconds when - # switching, but switching occurs seldom and it will be alot of - # unnecessary checks :). - dateStr = time.strftime(dateFmt, lt)[:maxCharsPerLine] - if recalcWeek: - week = calculateWeek(lt) - newWeekFmt = weekFmt.replace('%q', str(week)) - weekStr = time.strftime(newWeekFmt, lt)[:maxCharsPerLine] - dayStr = time.strftime(dayFmt, lt)[:maxCharsPerLine] - dateX = getCenterStartPos(dateStr) - weekX = getCenterStartPos(weekStr) - dayX = getCenterStartPos(dayStr) - if lastStrs[1] != dateStr: - clearLine(margin + spacing + char_width) - addString(dateStr, dateX, margin + spacing + char_width) - lastStrs[1] = dateStr - if lastStrs[2] != dayStr: - clearLine(margin + 2 * (spacing + char_width)) - addString(dayStr, dayX, margin + 2 * (spacing + char_width)) - lastStrs[2] = dayStr - if lastStrs[3] != weekStr: - clearLine(margin + 3 * (spacing + char_width)) - addString(weekStr, weekX, margin + 3 * (spacing + char_width)) - lastStrs[3] = weekStr - if counter == 999999: - counter = -1 - wmdocklib.redraw() - time.sleep(0.1) - patterns = [ ".+@@+.....#@...#@@#...#@@#....$@%...@@@@+..+=@%..+@@@@@..%@@+...&@@#.....", "$@==@$...+@@..&@--@&.*@--@&...#@%..*@-%%*.$==-@&.*%%%@=.#@-=@*.*@=-@&....", @@ -239,55 +64,136 @@ palette = { "-":"#CFCF04", } -def main(): - clConfig = parseCommandLine(sys.argv) - configFile = clConfig.get('configfile', defaultConfigFile) - configFile = os.path.expanduser(configFile) - fileConfig = wmdocklib.readConfigFile(configFile, sys.stderr) - # Merge the two configs, let the commandline options overwrite those in the - # configuration file. - config = fileConfig - for i in clConfig.iteritems(): - config[i[0]] = i[1] +timeDefaultFormat = '%H:%M:%S' +dateDefaultFormat = '%d-%m-%y' +dayDefaultFormat = '%A' +weekDefaultFormat = 'wk %q' # %q added by Kristoffer for different week calculation. - timeFmt = config.get('timeformat', timeDefaultFormat) - dateFmt = config.get('dateformat', dateDefaultFormat) - dayFmt = config.get('weekdayformat', dayDefaultFormat) - weekFmt = config.get('weekformat', weekDefaultFormat) - # openXwindow sets the window title to the program name. If we get the - # program name with a path, split it so we only name the window with the - # filename. - try: - programName = sys.argv[0].split(os.sep)[-1] - except IndexError: # Should only happen when using the interpreter. - programName = '' - sys.argv[0] = programName +defaultConfigFile = '~/.pywmdatetimerc' - palette[0] = clConfig.get('background', 'black') - palette[2] = clConfig.get('foreground', 'cyan3') - - font = clConfig.get('font', '6x8orig') +class Application(wmoo.Application): - if clConfig.get('antialiased'): - background = [((6,3),(57,19)), - ((3,22),(60,60))] - else: - background = [((3,3),(59,60))] + def __init__(self): - debug = clConfig.get('debug') - - global char_width, char_height, maxCharsPerLine, antialiased - char_width, char_height = wmdocklib.initPixmap(patterns=patterns, - font_name=font, - bg=0, fg=2, palette=palette, - background=background, - debug=debug) - maxCharsPerLine = (width-2*xOffset) / char_width - antialiased = clConfig.get('antialiased', False) + from optparse import OptionParser - wmdocklib.openXwindow(sys.argv, width, height) - mainLoop(timeFmt, dateFmt, dayFmt, weekFmt) + parser = OptionParser() + parser.add_option('-a', '--antialiased', dest='antialiased', + action="store_true", default=False) + parser.add_option('-f', '--foreground', type='string', default='cyan3') + parser.add_option('-F', '--font', type='string', default='6x8orig') + parser.add_option('-b', '--background', type='string', default='black') + parser.add_option('-t', '--timeformat', type='string', default=timeDefaultFormat) + parser.add_option('-d', '--dateformat', default=dateDefaultFormat) + parser.add_option('-y', '--weekdayformat', default=dayDefaultFormat) + parser.add_option('-e', '--weekformat', default=weekDefaultFormat) + parser.add_option('-r', '--rgbfile') + #parser.add_option('-c', '--configfile', default=defaultConfigFile) + parser.add_option('--debug', action='store_true', default=False) + + configFile = os.path.expanduser("~/.pywmdatetimerc") + # Merge the two configs, let the commandline options overwrite those in the + # configuration file. + config = readConfigFile(configFile, sys.stderr) + parser.set_defaults(**config) + + (options, args) = parser.parse_args() + + palette[0] = options.background + palette[2] = options.foreground + + if options.antialiased: + background = [((6,3),(57,19)), + ((3,22),(60,60))] + else: + background = [((3,3),(59,60))] + + wmoo.Application.__init__(self, + patterns=patterns, + font_name=options.font, + bg=0, fg=2, palette=palette, + background=background, + debug=options.debug) + + if options.antialiased: + self.addLabel('date', orig=(5,24), size=(54,10), align=wmoo.CENTRE) + self.addLabel('day', orig=(5,36), size=(54,10), align=wmoo.CENTRE) + self.addLabel('week', orig=(5,48), size=(54,10), align=wmoo.CENTRE) + else: + self.addLabel('time', orig=(5, 5), size=(54,10), align=wmoo.CENTRE) + self.addLabel('time2', orig=(5,16), size=(54,10), align=wmoo.CENTRE) + self.addLabel('date', orig=(5,27), size=(54,10), align=wmoo.CENTRE) + self.addLabel('day', orig=(5,38), size=(54,10), align=wmoo.CENTRE) + self.addLabel('week', orig=(5,49), size=(54,10), align=wmoo.CENTRE) + + self.timeFmt = options.timeformat + self.dateFmt = options.dateformat + self.dayFmt = options.weekdayformat + self.weekFmt = options.weekformat + self.antialiased = options.antialiased + self.debug = options.debug + + self.recalcWeek = self.weekFmt.find('%q') + 1 # True if we found %q. + self.counter = -1 + self.lastStrs = [''] * 4 + + pass + + def calculateWeek(self, localTime): + """Calculate the week number as we do, for example in Sweden. + + That is, add one to the %W format if the year didn't start on a monday.""" + day = int(time.strftime('%j', localTime)) + weekDay = int(time.strftime('%w')) - 1 + if weekDay == -1: + weekDay = 6 + lastMonday = day - weekDay + if lastMonday % 7 == 0: + return int(time.strftime('%W')) + return int(time.strftime('%W')) + 1 + + def updateTimeString(self, s): + if self.antialiased: + x, y = 8, 6 + for c in s: + charW = 7 + charX = (ord(c) - ord('0')) * 7 + if not c.isdigit(): + charX = 70 + charW = 3 + self.putPattern(charX, 0, charW, 10, x, y) + x += charW + else: + self.setLabelText('time', s) + + def update(self): + self.counter += 1 + lt = time.localtime() + timeStr = time.strftime(self.timeFmt, lt) + self.updateTimeString(timeStr) + self.lastStrs[0] = timeStr + if self.counter % 100 == 0: + # We only perform the date/week checks/updates once every 100th + # iteration. We will maybe lag behind a couple of seconds when + # switching, but switching occurs seldom and it will be alot of + # unnecessary checks :). + dateStr = time.strftime(self.dateFmt, lt) + newWeekFmt = self.weekFmt + if self.recalcWeek: + week = calculateWeek(lt) + newWeekFmt = self.weekFmt.replace('%q', str(week)) + weekStr = time.strftime(newWeekFmt, lt) + dayStr = time.strftime(self.dayFmt, lt) + if self.lastStrs[1] != dateStr: + self.setLabelText('date', dateStr) + self.lastStrs[1] = dateStr + if self.lastStrs[2] != dayStr: + self.setLabelText('day', dayStr) + self.lastStrs[2] = dayStr + if self.lastStrs[3] != weekStr: + self.setLabelText('week', weekStr) + self.lastStrs[3] = weekStr if __name__ == '__main__': - main() - + app = Application() + app.run() diff --git a/examples/pywmradio.py b/examples/pywmradio.py index 79f1c21..9572a5a 100755 --- a/examples/pywmradio.py +++ b/examples/pywmradio.py @@ -164,7 +164,6 @@ class Application(wmoo.Application): self.putPattern(54, 0, 5, 1, 54, 58-i) def update(self): - wmoo.Application.update(self) self._count += 1 if self._count <= 3: return diff --git a/wmdocklib/wmoo.py b/wmdocklib/wmoo.py index 5972a4f..7508eee 100644 --- a/wmdocklib/wmoo.py +++ b/wmdocklib/wmoo.py @@ -3,6 +3,10 @@ import pywmhelpers debug = 0 +LEFT = 0 +CENTRE = 1 +RIGHT = 2 + class Application: def __init__(self, *args, **kwargs): """initializes the object @@ -34,17 +38,18 @@ class Application: pywmhelpers.copyXPMArea(sourceX, sourceY+64, width, height, targetX, targetY) - def addLabel(self, labelId, orig, size=None, text=None): + def addLabel(self, labelId, orig, size=None, text='', align=LEFT): """a label is a tuple with a text: string; mutable viewport: (orig: int, int, size: int, int); inmutable pixmap: drawable; not user mutable, large enough to contain the text + align: one of LEFT, CENTRE, RIGHT if size is not given, it is inferred from text. """ if size is None: size = (self._char_width * len(text), self._char_height) - pixmapwidth = self._char_width * len(text) + pixmapwidth = max(self._char_width * len(text), size[0]) import pywmgeneral labelPixmap = pywmgeneral.Drawable(pixmapwidth, self._char_height) self._elements[labelId] = [orig, size, pixmapwidth, 0, labelPixmap] @@ -95,6 +100,9 @@ class Application: pywmhelpers.copyXPMArea(patternOrig[0], patternOrig[1] + 64, w, h, x, y) def update(self): + pass + + def redraw(self): for labelId in self._elements: (orig_x,orig_y), (size_x, size_y), width, offset, pixmap = self._elements[labelId] if size_x < width: @@ -104,10 +112,6 @@ class Application: else: offset += 1 self._elements[labelId][3] = offset - - pass - - def redraw(self): self.update() pywmhelpers.redraw()