Скажу сразу, что я не программист, а скорее любитель, поэтому не ругайте строго.
Сделал апплет, который каждые полчаса должен показывать сообщение используя убунтовские всплывающее сообщения.
Отсчетом времени занимается signal.setitimer
Если запустить апплет в режиме обычного окна, то все работает, а вот в режиме аплета, нотиф появляется, только после того как наведешь мышкой на сам аплет, я так понимаю это событие называется on_enter.
Подскажите, как сделать чтоб нотиф в режиме аплета, сам появлялся по истечении таймера?
вот сам код
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Sample applet for gnome
import pygtk
pygtk.require('2.0')
import sys
import gtk
import gnome.ui
import gnomeapplet
import os.path
import signal
import urllib
import xml.dom.minidom
import codecs
import pynotify
import datetime
#config env
path = ‘/home/vanuch/Documents/python/forismatic/’ #folder with files
time=30*60 #period between quotes(min*60sec)
class GnomeAppletSkeleton(gnomeapplet.Applet):
“”“Simple applet skeleton”“”
def __init__(self, applet, iid):
“”“Create applet for proxy”“”
self.applet = applet
self.__init_core_widgets()
self.init_additional_widgets()
self.init_ppmenu()
self.__connect_events()
self.applet.connect(“destroy”, self._cleanup)
self.after_init()
self.applet.show_all()
def __init_core_widgets(self):
“”“Create internal widgets”“”
# making internal widgets
self.tooltip = gtk.Tooltip() #self.tooltips = gtk.Tooltips()
self.hbox = gtk.HBox()
self.ev_box = gtk.EventBox()
# making widgets' ierarchy
self.applet.add(self.hbox)
self.hbox.add(self.ev_box)
def init_additional_widgets(self):
“”“Create additional widgets”“”
self.image=gtk.Image()
self.cur_dir=os.path.abspath(path)
self.icon_path=os.path.join(self.cur_dir,'forismatic_icon_16.png')
self.image.set_from_file(self.icon_path)
self.ev_box.add(self.image)
def init_ppmenu(self):
“”“Create popup menu for properties”“”
self.ppmenu_xml = “”“
<popup name=”button3“>
<menuitem name=”About Item“ verb=”About“ stockid=”gtk-about“/>
</popup>
”“”
self.ppmenu_verbs = [(“About”, self.on_ppm_about),
]
def __connect_events(self):
“”“Connect applet's events to callbacks”“”
self.ev_box.connect(“button-press-event”, self.on_button)
self.ev_box.connect(“enter-notify-event”, self.on_enter)
self.button_actions = {
1: lambda: None,
2: lambda: None,
3: self._show_ppmenu,
}
def after_init(self):
“”“After-init hook”“”
pass
def _cleanup(self, event):
“”“Cleanup callback (on destroy)”“”
del self.applet
def on_button(self, widget, event):
“”“Action on pressing button in applet”“”
if event.type == gtk.gdk.BUTTON_PRESS:
self.button_actions()
def _show_ppmenu(self):
“”“Show popup menu”“”
print self.applet.setup_menu.__doc__
self.applet.setup_menu(self.ppmenu_xml,
self.ppmenu_verbs,
None)
def on_enter(self, widget,event):
“”“Action on entering mouse to widget”“”
try:
self.int_time=signal.getitimer(signal.ITIMER_REAL)
self.time_norm=datetime.timedelta(seconds=self.int_time)
self.info= datetime.timedelta(seconds=self.time_norm.seconds)
self.info=“Next quote after \n %s” %self.info
except :
self.info = “Forismatic”
self.ev_box.set_tooltip_text(str(self.info))
def on_ppm_about(self, event, data=None):
“”“Action on chose ‘about’ in pop-up menu”“”
gnome.ui.About(“Forismatic Notify”, “0.1”,
“GNU General Public License v.2”,
“Forismatic applet for Python powered GNOME applet”,
,
).show()
class Forismatic:
“”“Return random quote form www.forismatic.com”“”
def get_quote(self):
cur_dir=os.path.abspath(path)
saved_quote_path=os.path.join(cur_dir, ‘forismatic’)
logo_path=os.path.join(cur_dir,'forismatic_logo48x48.png')
#0) read file with saved quote
with codecs.open(saved_quote_path,encoding='utf-8',mode='r') as file_r:
quote = file_r.readlines()
file_r.closed
quote=u“”.join(quote)
#print quote
#0.5) print Notify
title='Forismatic'
body=quote
icon='file://'+logo_path
notif = pynotify.Notification (title, body, icon);
notif.show ()
#1)get quote form forismatic
#TODO: add check of bad response
params = urllib.urlencode({'method': ‘getQuote’, ‘format’: ‘xml’, ‘lang’: ‘ru’})
f = urllib.urlopen("http://www.forismatic.com/api/1.0/" , params)
quote_xml = f.read()
#2)parseQuote:
with codecs.open(saved_quote_path, encoding='utf-8',mode='w') as file_w:
quote=xml.dom.minidom.parseString(quote_xml)
text = quote.getElementsByTagName('quoteText')
for node in text.childNodes:
if node.nodeType == node.TEXT_NODE:
quoteText=node.data
file_w.write(quoteText)
text = quote.getElementsByTagName('quoteAuthor')
for node in text.childNodes:
if node.nodeType == node.TEXT_NODE:
quoteAuthor =node.data
quoteAuthor = “–”+ quoteAuthor
quoteAuthor = quoteAuthor.rjust(30,“ ”)
file_w.write(“\n”+quoteAuthor)
file_w.closed
class GnomeForismaticApplet(GnomeAppletSkeleton):
def after_init(self):
self.quote=Forismatic()
self.button_actions=self.show_quote
self.timer()
#print signal.getitimer(signal.ITIMER_REAL)
def handler(self,signum,frame):
self.quote.get_quote()
def timer(self):
signal.signal(signal.SIGALRM, self.handler)
signal.setitimer(signal.ITIMER_REAL, time, time)
def show_quote(self):
#print ‘show quote’
self.quote.get_quote()
signal.setitimer(signal.ITIMER_REAL, time, time)
#print signal.getitimer(signal.ITIMER_REAL)
def applet_factory(applet, iid):
GnomeForismaticApplet(applet, iid)
return True
def run_in_panel():
gnomeapplet.bonobo_factory(“OAFIID:GNOME_ForismaticNotify_Factory”,
GnomeForismaticApplet.__gtype__,
“Applet Forismatic Notify”,
“0”,
applet_factory)
def run_in_window():
main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
main_window.set_title(“GNOME Applet Forismatic”)
main_window.connect(“destroy”, gtk.main_quit)
app = gnomeapplet.Applet()
applet_factory(app, None)
app.reparent(main_window)
main_window.show_all()
gtk.main()
sys.exit()
def main(args):
if len(args) == 2 and args == “run-in-window”:
run_in_window()
else:
run_in_panel()
if __name__ == ‘__main__’:
main(sys.argv)