~seadog/maemo-stopwatch/trunk

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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#!/usr/bin/python2.5
# -*- coding: utf-8 -*-

# 
# Copyright (c) 2007-2008 INdT.
# This program 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 3 of the License, or
# (at your option) any later version.
#
#  This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
#

# ============================================================================
# Name        : stopwatch.py
# Author      : Giorgos Logiotatidis
# Version     : 0.1
# Description : Stopwatch and countdown timer from maemo 5
# ============================================================================


import gtk 
import gobject
import hildon
import sys
import pygame
from time import strftime
from datetime import datetime, timedelta

from portrait import FremantleRotation

STOPWATCH = 1
COUNTDOWN = 2

class StopwatchApp(hildon.Program):
    def __init__(self):
        hildon.Program.__init__(self)
        
        self.running = False
        self.startTime = None
        self.stopTime = None
        
        self.stopButton = None
        self.startButton = None
        self.checkpointButton = None
        self.clearButton = None   
        self.hourButton = None
        self.minuteButton = None
        self.secondButton = None
        self.mode = STOPWATCH
        self.cleared = True    
        self.savedTimings = []
      
        gtk.set_application_name("Stopwatch")

        self.rotation = FremantleRotation('Stopwatch', None, '0.1', 0)

        self.window = hildon.StackableWindow()
        self.window.connect("delete_event", self.quit)  
        self.window.get_screen().connect("size-changed", self.drawUI)

        self.add_window(self.window)
       
        # create buttons
        self.create_buttons()
        
        # create label        
        self.timeLabel = gtk.Label()
        self.clear_time()
        
        # load beep
        pygame.mixer.init()
        self.sound = pygame.mixer.Sound("/usr/share/sounds/ui-default_beep.wav")
        
        self.drawUI()
        menu = self.create_menu(None)
        self.window.set_app_menu(menu)
   
    def create_buttons(self):
        # buttons        
        # stop button
        self.stopButton = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.stopButton.connect("clicked", self.menu_button_clicked, None)
        self.stopButton.set_label("Stop")
        image = gtk.image_new_from_stock(gtk.STOCK_NO, gtk.ICON_SIZE_BUTTON)
        self.stopButton.set_image(image)
        self.stopButton.set_image_position(gtk.POS_LEFT)    
        self.stopButton.set_sensitive(False)
            
        # start button
        self.startButton = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.startButton.connect("clicked", self.menu_button_clicked, None)        
        self.startButton.set_label("Go")
        image = gtk.image_new_from_stock(gtk.STOCK_YES, gtk.ICON_SIZE_BUTTON)
        self.startButton.set_image(image)
        self.startButton.set_image_position(gtk.POS_LEFT)
        self.startButton.set_sensitive(True)

        # checkList button
        self.checkpointButton = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.checkpointButton.connect("clicked", self.menu_button_clicked, None)        
        self.checkpointButton.set_label("Checkpoint")
        image = gtk.image_new_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON)
        self.checkpointButton.set_image(image)
        self.checkpointButton.set_image_position(gtk.POS_LEFT)
        self.checkpointButton.set_sensitive(False)

        # clear button
        self.clearButton = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        self.clearButton.connect("clicked", self.menu_button_clicked, None)        
        self.clearButton.set_label("Clear")
        image = gtk.image_new_from_stock(gtk.STOCK_CLEAR, gtk.ICON_SIZE_BUTTON)
        self.clearButton.set_image(image)
        self.clearButton.set_image_position(gtk.POS_LEFT)
        self.clearButton.set_sensitive(False)
        
        r = []
        for i in range(59):
            r.append("%s" % i) 
        # hour button
        self.hourButton = hildon.PickerButton(gtk.HILDON_SIZE_AUTO,hildon.BUTTON_ARRANGEMENT_VERTICAL)      
        self.hourButton.set_label("Hours")
        self.hourButton.set_title("Hours")
        self.hourButton.set_selector(self.create_customized_selector(r))    
        self.hourButton.set_value("0")   

        # minute button
        self.minuteButton = hildon.PickerButton(gtk.HILDON_SIZE_AUTO,hildon.BUTTON_ARRANGEMENT_VERTICAL)      
        self.minuteButton.set_label("Minutes")
        self.minuteButton.set_title("Minutes")
        self.minuteButton.set_selector(self.create_customized_selector(r))    
        self.minuteButton.set_value("0")   
        
        # second button
        self.secondButton = hildon.PickerButton(gtk.HILDON_SIZE_AUTO,hildon.BUTTON_ARRANGEMENT_VERTICAL)      
        self.secondButton.set_label("Seconds")
        self.secondButton.set_title("Seconds")
        self.secondButton.set_selector(self.create_customized_selector(r))    
        self.secondButton.set_value("0")   
                
    def create_customized_selector(self, data):
        # Create a touch selector 
        selector = hildon.TouchSelector(text=True)
                       
        for item in data:
            selector.append_text(item)
        return selector
     
    def drawUI(self, a=None):      
        # clear everything
        def clearGtkTree(item):
            if (type(item) is gtk.EventBox) or (type(item) is hildon.GtkButton) or (type(item) is hildon.PickerButton):
                return
            try:
                for child in item.get_children():            
                    clearGtkTree(child)
                    item.remove(child)
            except AttributeError:
                return  
            
        clearGtkTree(self.window)
            
        if (self.rotation._orientation) == "portrait":
            # buttons vbox
            if self.mode == STOPWATCH:
                bvbox = gtk.VBox(True, 0)
                bvbox.add(self.startButton)
                bvbox.add(self.stopButton)
                bvbox.add(self.checkpointButton)
                bvbox.add(self.clearButton)
            else:
                bvbox = gtk.VBox(True, 0)
                bvbox.add(self.startButton)
                bvbox.add(self.stopButton)
                bvbox.add(self.hourButton)
                bvbox.add(self.minuteButton)
                bvbox.add(self.secondButton)
            
            vbox = gtk.VBox(False, 10)
            vbox.add(self.timeLabel)
            vbox.add(bvbox)
            
            self.window.add(vbox)
            
        else:
            if self.mode == STOPWATCH:
                # buttons hbox
                bhbox = gtk.HBox(True, 0)
                
                bvbox = gtk.VBox(True, 0)
                bvbox.add(self.startButton)
                bvbox.add(self.checkpointButton)
                bhbox.add(bvbox)
                bvbox = gtk.VBox(True, 0)
                bvbox.add(self.stopButton)
                bvbox.add(self.clearButton)
                bhbox.add(bvbox)
                vbox = gtk.VBox(False, 10)
                vbox.add(self.timeLabel)
                vbox.add(bhbox)
                
                self.window.add(vbox)
                
            elif self.mode == COUNTDOWN:
                vhbox = gtk.VBox(True, 0)
                bhbox = gtk.HBox(True, 0)
                bhbox.add(self.startButton)
                bhbox.add(self.stopButton)
                
                vhbox.add(bhbox)
                bhbox = gtk.HBox(True, 0)             
                bhbox.add(self.hourButton)
                bhbox.add(self.minuteButton)
                bhbox.add(self.secondButton)
                vhbox.add(bhbox)

                vbox = gtk.VBox(False, 10)
                vbox.add(self.timeLabel)
                vbox.add(vhbox)
            
                self.window.add(vbox)

          
        self.update_time()  
        self.window.show_all()
         
    def update_time(self):                      
        if self.running:
            now = datetime.now()
        else:
            now = self.stopTime          
        
        try:
            if self.mode == STOPWATCH:
                timeString = str(now - self.startTime)
            else:
                timeString = str(self.stopTime - now)
                
        except TypeError:
            timeString = "0:00:00.000000"
            
        fontSize = self.get_font_size()
        self.timeLabel.set_markup("<span font_size='%s' font_weight='bold'>%s</span><span font_size=\"%s\" color=\"grey\">%s</span>" % (fontSize[0], timeString[:-7], fontSize[1], timeString[-7:-4]))
        
        if self.running:
            gobject.timeout_add(50, self.update_time)
            
    def checkCountdown(self):
        now = datetime.now()
        
        if self.stopTime == None:
            return
        
        if now >= self.stopTime:
#            self.player.set_state(gst.STATE_PLAYING)
            self.sound.play()
            self.running = False
            hildon.hildon_banner_show_information(self.window, "", "Timer finished at %s" % str(now)[:-7])
            self.stopButton.set_sensitive(False)
            self.startButton.set_sensitive(True)
            self.hourButton.set_sensitive(True)
            self.minuteButton.set_sensitive(True)
            self.secondButton.set_sensitive(True)
            self.startTime = None
            self.stopTime = None
            
            
        else:
            gobject.timeout_add(10, self.checkCountdown)
 
    def clear_time(self):
        fontSize = self.get_font_size()
        timeString = "0:00:00.000000"
        self.timeLabel.set_markup("<span font_size='%s' font_weight='bold'>%s</span><span font_size=\"%s\" color=\"grey\">%s</span>" % (fontSize[0], timeString[:-7], fontSize[1], timeString[-7:-4]))
        
        self.savedTimings = []
        self.cleared = True
        self.startTime = None
        self.stopTime = None
        
        self.checkpointButton.set_sensitive(False)
        self.clearButton.set_sensitive(False)

    def get_font_size(self):
        if self.rotation._orientation == "portrait":
            return (75000, 35000)
        else:
            return (125000, 50000)
        
              
    def set_checkpoint_button(self):
        self.checkpointButton.set_label("Checkpoint")
        image = gtk.image_new_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_BUTTON)
        self.checkpointButton.set_image(image)
        self.checkpointButton.set_image_position(gtk.POS_LEFT)
        self.checkpointButton.set_sensitive(True)

    def set_checkpointlist_button(self):
        self.checkpointButton.set_label("Checkpoint List")
        image = gtk.image_new_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_BUTTON)
        self.checkpointButton.set_image(image)
        self.checkpointButton.set_image_position(gtk.POS_LEFT)
        self.checkpointButton.set_sensitive(True)

    def quit(self, *args):
        gtk.main_quit()
        
    def run(self):     
        self.window.show_all()
        gtk.main() 

    def menu_button_clicked(self, button, lbale):        
        label = button.get_label()
        if label == "Go":
            if self.mode == STOPWATCH:
                if self.running == False:
                    self.running = True
                    if self.cleared == True:
                        self.startTime = datetime.now()   
                    else:
                        self.startTime = datetime.now() - (self.stopTime - self.startTime)                                  
                    
                    self.update_time()                
                    self.stopButton.set_sensitive(True)
                    self.set_checkpoint_button()
                    self.clearButton.set_sensitive(False)
                    self.startButton.set_sensitive(False)
                    self.cleared = False
                    self.running = True
                elif self.running == True:
                    self.clearButton.set_sensitive(False)
            
            elif self.mode == COUNTDOWN:
                
                hour = int(self.hourButton.get_value())
                minute = int(self.minuteButton.get_value())
                second = int(self.secondButton.get_value())
                
                countdownDelta = timedelta(hours = hour, minutes = minute, seconds = second)
                
                self.stopButton.set_sensitive(True)
                self.hourButton.set_sensitive(False)
                self.minuteButton.set_sensitive(False)
                self.secondButton.set_sensitive(False)
                self.startButton.set_sensitive(False)
                self.running = True
                self.startTime = datetime.now()
                self.stopTime = self.startTime + countdownDelta
                self.update_time()
                self.checkCountdown()
                
        
        elif label == "Stop":
            self.running = False  
            
            if self.mode == STOPWATCH:
                self.stopTime = datetime.now()
                self.update_time()
                self.clearButton.set_sensitive(True)
                self.startButton.set_sensitive(True)
                self.stopButton.set_sensitive(False)
                self.set_checkpointlist_button()
            elif self.mode == COUNTDOWN:
                self.hourButton.set_sensitive(True)
                self.minuteButton.set_sensitive(True)
                self.secondButton.set_sensitive(True)
                self.stopButton.set_sensitive(False)
                self.startButton.set_sensitive(True)
                self.stopTime = None
                
                
        elif label == "Clear":
            self.clear_time()
            
        elif label == "Checkpoint":
            self.add_checkpoint()
            
        elif label == "Checkpoint List":
            self.list_checkpoints()      
            
        elif label == "Stopwatch":
            self.window.set_title("Stopwatch")
            self.mode = STOPWATCH
            self.clear_time()
            self.drawUI()
            
        elif label == "Countdown":
            self.window.set_title("Countdown")
            self.mode = COUNTDOWN
            self.clear_time()
            self.drawUI()
            
        elif label == "Set":
            pass
        
    def add_checkpoint(self):
        now = datetime.now()
        self.savedTimings.append(now-self.startTime)            
        hildon.hildon_banner_show_information(self.window, "", "Saved time: %s" % str(now-self.startTime)[:-4])
        
    def list_checkpoints(self):     
        list = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING)
        
        counter = 1
        for i in self.savedTimings:
            niter = list.append()
            list.set(niter, 0, "# %d -" % counter, 1, str(i)[:-4])
            counter += 1
        
        win = hildon.StackableWindow()
        win.set_title("Saved Times")  
        vbox = gtk.VBox()
        parea = hildon.PannableArea()
        
        #Define the recipe list treeview with multiple selections, search, etc.
        self.checkpoint_tv = hildon.GtkTreeView(gtk.HILDON_UI_MODE_EDIT)
        selection = self.checkpoint_tv.get_selection()
        self.checkpoint_tv.set_model(list)

        parea.add(self.checkpoint_tv)
        # add columns to the tree view
        self.add_columns_to_checkpoint_list(self.checkpoint_tv)
        vbox.pack_start(parea, True, True, 0)
        win.add(vbox)          
        win.show_all()

    def add_columns_to_checkpoint_list(self, treeview):
        model = treeview.get_model()

        # column for ID
        column = gtk.TreeViewColumn('ID', gtk.CellRendererText(), text=0)
        column.set_visible(True)
        treeview.append_column(column)

        # column for title
        renderer = gtk.CellRendererText()
        renderer.set_property('wrap-mode', gtk.WRAP_WORD)
        renderer.set_property('wrap-width', 780)
        column = gtk.TreeViewColumn('Recipe title', renderer, text=1)
        column.set_sort_column_id(1)
        column.set_property("expand", True)
        treeview.append_column(column)
        
               
    def create_menu(self,label):
        menu = hildon.AppMenu()
                
        button = hildon.GtkRadioButton(gtk.HILDON_SIZE_AUTO, None)
        button.set_label("Stopwatch")
        button.connect("clicked", self.menu_button_clicked, label)
        menu.append(button)
        button.set_mode(False)
        
        button = hildon.GtkRadioButton(gtk.HILDON_SIZE_AUTO, button)
        button.set_label("Countdown")
        button.connect("clicked", self.menu_button_clicked, label)
        menu.append(button)
        button.set_mode(False)
        
        # about button
        button = hildon.GtkButton(gtk.HILDON_SIZE_AUTO)
        button.set_label("About")
        button.connect("clicked", self.on_about_button_clicked)
        menu.append(button)

        menu.show_all()
        
        return menu
    
    def on_about_button_clicked(self, widget):
        about = gtk.AboutDialog()
        about.set_name("stopwatch")
        about.set_comments("A stopwatch and countdown timer")
        about.set_version("0.1")
        about.set_copyright("Giorgos Logiotatidis")
        about.set_website("https://launchpad.net/maemo-stopwatch")
        about.set_logo_icon_name("stopwatch")
        about.connect("response", lambda x, y: x.destroy())
        about.show()
        



if __name__ == "__main__":  
    app = StopwatchApp() 
    app.run()