1
# -*- coding: utf-8 -*-
4
from monajat import Monajat
5
from utils import init_dbus
15
from functools import cmp_to_key
18
# in gnome3 ['actions', 'action-icons', 'body', 'body-markup', 'icon-static', 'persistence']
19
# in gnome2 ['actions', 'body', 'body-hyperlinks', 'body-markup', 'icon-static', 'sound']
23
def __init__(self, fn=None, change_play_status=None):
26
self.change_play_status=change_play_status
27
self.gst_player = gst.element_factory_make("playbin2", "player")
28
self.gst_player.set_property("uri", "file://" + fn)
29
bus = self.gst_player.get_bus()
30
bus.add_signal_watch()
31
bus.connect("message", self.on_message)
35
if fn and os.path.isfile(fn):
36
self.gst_player.set_state(gst.STATE_PLAYING)
39
self.gst_player.set_state(gst.STATE_NULL)
41
def set_filename(self,fn):
44
self.gst_player.set_property("uri", "file://" + fn)
46
def on_message(self, bus, message):
49
if t == gst.MESSAGE_EOS:
50
if self.change_play_status: self.change_play_status()
51
self.gst_player.set_state(gst.STATE_NULL)
52
elif t == gst.MESSAGE_ERROR:
53
self.gst_player.set_state(gst.STATE_NULL)
54
err, debug = message.parse_error()
55
print "Error: %s" % err, debug
58
class ConfigDlg(gtk.Dialog):
59
def __init__(self, applet):
60
gtk.Dialog.__init__(self)
63
self.set_size_request(300,400)
64
self.set_resizable(False) # FIXME: reconsider this
65
self.connect('delete-event', lambda w,*a: w.hide() or True)
66
self.connect('response', lambda w,*a: w.hide() or True)
67
self.set_title(_('Monajat Configuration'))
68
self.add_button(_('Cancel'), gtk.RESPONSE_CANCEL)
69
self.add_button(_('Save'), gtk.RESPONSE_OK)
71
self.get_content_area().add(tabs)
73
tabs.append_page(vb, gtk.Label(_('Generic')))
74
self.auto_start = b = gtk.CheckButton(_("Auto start"))
75
self.auto_start.set_active(not os.path.exists(self.applet.skip_auto_fn))
76
vb.pack_start(b, False, False, 2)
77
self.show_merits = b = gtk.CheckButton(_("Show merits"))
78
self.show_merits.set_active(self.applet.conf['show_merits'])
79
vb.pack_start(b, False, False, 2)
81
vb.pack_start(hb, False, False, 2)
82
hb.pack_start(gtk.Label(_('Language:')), False, False, 2)
83
self.lang = b = gtk.combo_box_new_text()
84
hb.pack_start(b, False, False, 2)
86
for i,j in enumerate(self.applet.m.langs):
88
if self.m.lang==j: selected=i
89
b.set_active(selected)
92
vb.pack_start(hb, False, False, 2)
93
hb.pack_start(gtk.Label(_('Time:')), False, False, 2)
94
hb.pack_start(gtk.HBox(), True, True, 2)
95
self.timeout = b = gtk.SpinButton(gtk.Adjustment(5, 0, 90, 5, 5))
96
b.set_value(self.applet.conf['minutes'])
97
hb.pack_start(b, False, False, 2)
98
hb.pack_start(gtk.Label(_('minutes')), False, False, 2)
101
tabs.append_page(vb, gtk.Label(_('Location')))
104
vb.pack_start(hb, False, False, 2)
106
e.connect('activate', self._city_search_cb)
107
hb.pack_start(e, False, False, 2)
109
s = gtk.TreeStore(str, bool, int) # label, is_city, id
110
self.cities_tree=tree=gtk.TreeView(s)
111
col=gtk.TreeViewColumn('Location', gtk.CellRendererText(), text=0)
112
col.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE)
113
tree.insert_column(col, -1)
114
tree.set_enable_search(True)
115
tree.set_search_column(0)
116
tree.set_headers_visible(False)
117
tree.set_tooltip_column(0)
119
scroll=gtk.ScrolledWindow()
120
scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
122
vb.pack_start(scroll, True, True, 2)
124
self.sound_player = SoundPlayer(self.applet.conf['athan_media_file'], self.change_play_status)
126
tabs.append_page(vb, gtk.Label(_('Notification')))
128
vb.pack_start(hb, False, True, 3)
129
hb.pack_start(gtk.Label(_('Sound:')), False, True, 2)
130
self.sound_file = b = gtk.FileChooserButton(_('Choose Athan media file'))
131
self.sound_file.set_filename(self.applet.conf['athan_media_file'])
133
ff.set_name(_('Sound Files'))
134
ff.add_pattern('*.ogg')
135
ff.add_pattern('*.mp3')
138
ff.set_name(_('All files'))
141
self.play_b=pb=gtk.Button(_('Play'))
142
pb.connect('clicked', self.play_cb)
143
hb.pack_end(pb, False, False, 2)
144
hb.pack_end(b, True, True, 5)
147
vb.pack_start(hb, False, False, 3)
148
self.notify_before_b = b = gtk.CheckButton(_("Notify before"))
149
self.notify_before_t = t = gtk.SpinButton(gtk.Adjustment(5, 5, 20, 5, 5))
150
b.set_active(self.applet.conf['notify_before_min']!=0)
151
t.set_value(self.applet.conf['notify_before_min'])
152
hb.pack_start(b,True,True,2)
153
hb.pack_start(t,False,False,2)
154
hb.pack_start(gtk.Label(_('minutes')),False,False,2)
158
def change_play_status(self, status=None):
159
if status==None: status=self.sound_player.gst_player.get_state()
160
if status==gst.STATE_PLAYING:
161
self.sound_file.set_sensitive(False)
162
self.play_b.set_property('label', _('Stop'))
164
self.sound_file.set_sensitive(True)
165
self.play_b.set_property('label', _('Play'))
167
def play_cb(self, b):
168
fn=self.sound_file.get_filename()
170
if b.get_label() == _('Play'):
171
if not os.path.isfile(fn): return
172
self.change_play_status(gst.STATE_PLAYING)
173
self.sound_player.set_filename(fn)
174
self.sound_player.play()
176
self.change_play_status(gst.STATE_NULL)
177
self.sound_player.stop()
179
def _city_search_cb(self, e):
180
# FIXME: if same as last successful search text don't update first_match_path
181
# FIXME: and if self.city_found same as first_match_path highlight in red
182
txt=e.get_text().strip()
183
e.modify_base(gtk.STATE_NORMAL, None)
184
tree=self.cities_tree
185
store, p=tree.get_selection().get_selected_rows()
189
def tree_walk_cb(model, path, i):
190
if current and path<=current: return False
191
if limit and path>=limit: return True
192
if txt in store.get_value(i,0):
193
tree.expand_to_path(path)
194
tree.scroll_to_cell(path)
195
tree.get_selection().select_iter(i)
199
store.foreach(tree_walk_cb)
200
if not self.city_found:
203
store.foreach(tree_walk_cb)
204
if not self.city_found:
205
e.modify_base(gtk.STATE_NORMAL, gtk.gdk.color_parse("#FFCCCC"))
207
def _fill_cities(self):
208
tree=self.cities_tree
210
rows=self.m.cities_c.execute('SELECT * FROM cities')
211
country, country_i = None, None
212
state, state_i=None, None
216
if country!=r['country']:
217
country_i=s.append(None,(r['country'], False, 0))
218
if state!=r['state']:
219
state_i=s.append(country_i,(r['state'], False, 0))
222
city=u'%s - %s' % (r['name'], r['locale_name'])
224
city_i=s.append(state_i,(city, True, r['id']))
225
if self.applet.conf.get('city_id',None)==r['id']: city_path=s.get_path(city_i)
227
tree.expand_to_path(city_path)
228
tree.get_selection().select_path(city_path)
229
tree.scroll_to_cell(city_path)
231
def run(self, *a, **kw):
232
self.auto_start.set_active(not os.path.exists(self.applet.skip_auto_fn))
233
return gtk.Dialog.run(self, *a, **kw)
235
class applet(object):
236
skip_auto_fn=os.path.expanduser('~/.monajat-applet-skip-auto')
239
self.chngbody=time.time()
240
self.minutes_counter=0
241
self.m=Monajat() # you may pass width like 20 chars
242
self.sound_player=SoundPlayer()
245
kw=self.conf_to_prayer_args()
246
self.prayer=itl.PrayerTimes(**kw)
247
l=filter(lambda i: i.startswith('ar_') and "_" in i and '.' not in i, locale.locale_alias.keys())
249
l,c=l[0].split('_',1)
250
l=l+"_"+c.upper()+".UTF-8"
251
os.environ['LC_MESSAGES']=l
252
locale.setlocale(locale.LC_MESSAGES, l)
253
ld=os.path.join(self.m.get_prefix(),'..','locale')
254
gettext.install('monajat', ld, unicode=0)
255
self.ptnames=[_("Fajr"), _("Sunrise"), _("Dhuhr"), _("Asr"), _("Maghrib"), _("Isha'a")]
256
self.clip1=gtk.Clipboard(selection="CLIPBOARD")
257
self.clip2=gtk.Clipboard(selection="PRIMARY")
258
self.init_about_dialog()
260
#self.s=gtk.status_icon_new_from_file(os.path.join(self.m.get_prefix(),'monajat.svg'))
261
#self.s.connect('popup-menu',self.popup_cb)
262
#self.s.connect('activate',self.next_cb)
263
pynotify.init('MonajatApplet')
264
self.notifycaps = pynotify.get_server_caps ()
265
print self.notifycaps
266
self.notify=pynotify.Notification("MonajatApplet")
267
self.notify.set_property('icon-name','monajat')
268
self.notify.set_property('summary', _("Monajat") )
269
if 'actions' in self.notifycaps:
270
self.notify.add_action("previous", _("previous"), self.notify_cb)
271
self.notify.add_action("next", _("next"), self.notify_cb)
272
self.notify.add_action("copy", _("copy"), self.notify_cb)
273
self.notify.set_timeout(5000)
274
#self.notify.set_urgency(pynotify.URGENCY_LOW)
275
self.notify.set_hint('resident', True)
276
#self.notify.set_hint('transient', True)
278
self.statusicon = gtk.StatusIcon ()
279
#self.notify.attach_to_status_icon(self.statusicon)
280
self.statusicon.connect('popup-menu',self.popup_cb)
281
self.statusicon.connect('activate',self.next_cb)
282
self.statusicon.set_title(_("Monajat"))
283
self.statusicon.set_from_file(os.path.join(self.m.get_prefix(),'monajat.svg'))
285
self.notif_last_athan=-1
286
self.next_athan_delta=-1
290
self.first_notif_done=False
291
self.start_time=time.time()
292
glib.timeout_add_seconds(1, self.timer_cb)
294
def config_cb(self, *a):
295
if self.conf_dlg==None:
296
self.conf_dlg=ConfigDlg(self)
297
self.conf_dlg.show_all()
298
r=self.conf_dlg.run()
299
if r==gtk.RESPONSE_OK:
300
self.save_auto_start()
303
def default_conf(self):
305
self.conf['show_merits']='1'
306
self.conf['lang']=self.m.lang
307
self.conf['minutes']='10'
308
self.conf['athan_media_file']=os.path.join(self.m.prefix, 'athan.ogg')
309
self.conf['notify_before_min']='10'
311
def conf_to_prayer_args(self):
313
if not self.conf.has_key('city_id'): return kw
315
try: c_id=int(self.conf['city_id'])
316
except ValueError: return kw
317
except TypeError: return kw
318
r=c.execute('SELECT * FROM cities AS c LEFT JOIN dst AS d ON d.i=dst_id WHERE c.id=?', (c_id,)).fetchone()
319
# FIXME: if not r: defaults to Makka
321
if "alt" not in kw or not kw["alt"]: kw["alt"]=0.0
323
# NOTE: get DST from machine local setting
324
kw["dst"]=time.daylight
325
# FIXME: dst should have the following 3 options
326
# a. auto from system, b. auto from algorithm, c. specified to 0/1 by user
328
#if not dst: kw["dst"]=0
330
# # FIXME: add DST logic here
333
#lat=21.43, lon=39.77, tz=3.0, dst=0, alt=0, pressure=1010, temp=10
337
def parse_conf(self, s):
339
l1=map(lambda k: k.split('=',1), filter(lambda j: j,map(lambda i: i.strip(),s.splitlines())) )
340
l2=map(lambda a: (a[0].strip(),a[1].strip()),filter(lambda j: len(j)==2,l1))
342
self.conf.update(dict(l2))
343
return len(l1)==len(l2)
347
fn=os.path.expanduser('~/.monajat-applet.rc')
348
if os.path.exists(fn):
349
try: s=open(fn,'rt').read()
352
if self.conf.has_key('city_id'):
353
# make sure city_id is set using the same db
354
if not self.conf.has_key('cities_db_ver') or \
355
self.conf['cities_db_ver']!=self.m.cities_db_ver:
356
del self.conf['city_id']
357
# make sure it's integer
358
try: c_id=int(self.conf['city_id'])
359
except ValueError: del self.conf['city_id']
360
except TypeError: del self.conf['city_id']
361
else: self.conf['city_id']=c_id
362
# set athan media file exists
363
self.sound_player.set_filename(self.conf['athan_media_file'])
365
try: self.conf['minutes']=math.ceil(float(self.conf['minutes'])/5.0)*5
366
except ValueError: self.conf['minutes']=0
367
try: self.conf['show_merits']=int(self.conf['show_merits'])
368
except ValueError: self.conf['show_merits']=1
369
try: self.conf['notify_before_min']=int(float(self.conf['notify_before_min']))
370
except ValueError: self.conf['notify_before_min']=10
371
self.m.set_lang(self.conf['lang'])
374
def apply_conf(self):
375
kw=self.conf_to_prayer_args()
376
self.prayer=itl.PrayerTimes(**kw)
378
self.sound_player.set_filename(self.conf['athan_media_file'])
380
self.m.set_lang(self.conf['lang'])
381
self.render_body(self.m.go_forward())
384
self.conf['cities_db_ver']=self.m.cities_db_ver
385
self.conf['show_merits']=int(self.conf_dlg.show_merits.get_active())
386
self.conf['lang']=self.conf_dlg.lang.get_active_text()
387
self.conf['minutes']=int(self.conf_dlg.timeout.get_value())
388
self.conf['athan_media_file']=self.conf_dlg.sound_file.get_filename()
389
self.conf['notify_before_min']=int(self.conf_dlg.notify_before_b.get_active() and self.conf_dlg.notify_before_t.get_value())
390
m, p=self.conf_dlg.cities_tree.get_selection().get_selected_rows()
393
if city_id: self.conf['city_id']=city_id
394
print "** saving conf", self.conf
395
fn=os.path.expanduser('~/.monajat-applet.rc')
396
s='\n'.join(map(lambda k: "%s=%s" % (k,str(self.conf[k])), self.conf.keys()))
397
try: open(fn,'wt').write(s)
401
def athan_show_notif(self):
402
self.last_time=time.time()
403
self.first_notif_done=True
404
s=self.ptnames[self.last_athan]
405
self.notify.set_property('body', _('''It's now time for %s prayer''') % s)
408
def athan_notif_cb(self):
409
i, t, dt=self.prayer.get_next_time_stamp()
413
self.next_athan_delta=dt
415
if dt<30 and i!=self.last_athan:
416
print "it's time for prayer number:", i
418
self.sound_player.play()
419
self.athan_show_notif()
423
def timer_cb(self, *args):
424
dt=int(time.time()-self.last_time)
425
if self.prayer.update():
427
if self.athan_notif_cb(): return True
428
if not self.first_notif_done:
429
if int(time.time()-self.start_time)>=10:
432
if self.conf['notify_before_min'] and self.next_athan_delta<=self.conf['notify_before_min']*60 and self.next_athan_i!=self.notif_last_athan:
433
self.notif_last_athan=self.next_athan_i
435
elif self.conf['minutes'] and dt>=self.conf['minutes']*60:
439
def hide_cb(self, w, *args): w.hide(); return True
441
def fuzzy_delta(self):
442
if self.next_athan_i<0: return ""
443
t=max(int(self.next_athan_delta),0)
444
d={"prayer":self.ptnames[self.next_athan_i]}
450
r=_("""%(hours)d hours till %(prayer)s prayer""") % d
452
r=_("""%(hours)d hours and %(minutes)d minutes till %(prayer)s prayer""") % d
453
elif d["minutes"]>=2:
454
r=_("""less than %(minutes)d minutes till %(prayer)s prayer""") % d
456
r=_("""less than a minute till %(prayer)s prayer""") % d
457
if "body-markup" in self.notifycaps:
458
return "<b>%s</b>\n\n" % cgi.escape(r)
461
def render_body(self, m):
463
if not self.conf['show_merits']: merits=None
464
if "body-markup" in self.notifycaps:
465
body=cgi.escape(m['text'])
466
if merits: body+="""\n\n<b>%s</b>: %s""" % (_("Its Merits"),cgi.escape(merits))
469
if merits: body+="""\n\n** %s **: %s""" % (_("Its Merits"),merits)
471
if "body-hyperlinks" in self.notifycaps:
473
links=m.get('links',u'').split(u'\n')
476
url=cgi.escape(ll[0])
477
if len(ll)>1: t=cgi.escape(ll[1])
479
L.append(u"""<a href='%s'>%s</a>""" % (url,t))
482
body=self.fuzzy_delta()+body
483
#timeNP,isnear, istime = self.nextprayer_note(self.get_nextprayer(self.prayer.get_prayers()))
484
#if not isnear: body+=timeNP
485
#else: body=timeNP+body
486
self.notify.set_property('body', body)
489
def dbus_cb(self, *args):
490
self.minutes_counter=1
494
def next_cb(self,*args):
495
self.last_time=time.time()
496
self.first_notif_done=True
497
try: self.notify.close()
498
except glib.GError: pass
499
self.render_body(self.m.go_forward())
503
def prev_cb(self, *args):
504
self.last_time=time.time()
505
try: self.notify.close()
506
except glib.GError: pass
507
self.render_body(self.m.go_back())
510
def copy_cb(self,*args):
511
r=self.m.get_current()
512
self.clip1.set_text(r['text'])
513
self.clip2.set_text(r['text'])
515
def init_about_dialog(self):
516
# FIXME: please add more the authors
517
self.about_dlg=gtk.AboutDialog()
518
self.about_dlg.set_default_response(gtk.RESPONSE_CLOSE)
519
self.about_dlg.connect('delete-event', self.hide_cb)
520
self.about_dlg.connect('response', self.hide_cb)
521
try: self.about_dlg.set_program_name("Monajat")
523
self.about_dlg.set_name(_("Monajat"))
524
#self.about_dlg.set_version(version)
525
self.about_dlg.set_copyright("Copyright © 2009 sabily.org")
526
self.about_dlg.set_comments(_("Monajat supplications"))
527
self.about_dlg.set_license("""\
528
This program is free software; you can redistribute it and/or modify
529
it under the terms of the GNU General Public License as published by
530
the Free Software Foundation; either version 2 of the License, or
531
(at your option) any later version.
533
This program is distributed in the hope that it will be useful,
534
but WITHOUT ANY WARRANTY; without even the implied warranty of
535
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
536
GNU General Public License for more details.
538
self.about_dlg.set_website("https://launchpad.net/monajat")
539
self.about_dlg.set_website_label("Monajat web site")
540
self.about_dlg.set_authors(["Fadi al-katout <cutout33@gmail.com>",
541
"Muayyad Saleh Alsadi <alsadi@ojuba.org>",
542
"Ehab El-Gedawy <ehabsas@gmail.com>",
543
"Mahyuddin Susanto <udienz@ubuntu.com>",
544
"عبدالرحيم دوبيلار <abdulrahiem@sabi.li>",
545
"أحمد المحمودي (Ahmed El-Mahmoudy) <aelmahmoudy@sabily.org>"])
546
def save_auto_start(self):
547
b=self.conf_dlg.auto_start.get_active()
548
if b and os.path.exists(self.skip_auto_fn):
549
try: os.unlink(self.skip_auto_fn)
552
open(self.skip_auto_fn,'wt').close()
554
def update_prayer(self):
555
if not self.prayer_items: return
556
pt=self.prayer.get_prayers()
558
ptn=list(self.ptnames)
560
for p,t in zip(ptn, pt):
563
self.prayer_items[j].set_label(u"%-10s %s" % (p, t.format(),))
567
self.menu = gtk.Menu()
568
i = gtk.ImageMenuItem(gtk.STOCK_COPY)
569
i.set_always_show_image(True)
570
i.connect('activate', self.copy_cb)
573
i = gtk.ImageMenuItem(gtk.STOCK_GO_FORWARD)
574
i.set_always_show_image(True)
575
i.connect('activate', self.next_cb)
578
i = gtk.ImageMenuItem(gtk.STOCK_GO_BACK)
579
i.set_always_show_image(True)
580
i.connect('activate', self.prev_cb)
583
self.menu.add(gtk.SeparatorMenuItem())
587
i = gtk.MenuItem("-")
588
self.prayer_items.append(i)
592
self.menu.add(gtk.SeparatorMenuItem())
594
i = gtk.MenuItem(_("Configure"))
595
i.connect('activate', self.config_cb)
598
self.menu.add(gtk.SeparatorMenuItem())
600
i = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
601
i.set_always_show_image(True)
602
i.connect('activate', lambda *args: self.about_dlg.run())
605
i = gtk.ImageMenuItem(gtk.STOCK_QUIT)
606
i.set_always_show_image(True)
607
i.connect('activate', gtk.main_quit)
612
def popup_cb(self, s, button, time):
613
self.menu.popup(None, None, gtk.status_icon_position_menu, button, time, s)
615
def time_set_cb(self, m, t):
616
self.conf['minutes']=t
617
self.minutes_counter=1
620
def lang_cb(self, m, l):
621
if not m.get_active(): return
625
def notify_cb(self,notify,action):
626
try: self.notify.close()
627
except glib.GError: pass
628
if action=="exit": gtk.main_quit()
629
elif action=="copy": self.copy_cb()
630
elif action=="next": self.next_cb()
631
elif action=="previous": self.prev_cb()
634
gtk.window_set_default_icon_name('monajat')
639
if __name__ == "__main__":