Added ability to set options for ussdqueru.py in widget
[ussd-widget] / ussd-widget / src / usr / lib / hildon-desktop / ussd-widget.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 import gobject
4 import gtk
5 import hildon
6 import hildondesktop
7 import os
8 import cairo
9 import pango
10 import time
11 import re
12 import gettext
13 import fcntl
14 from subprocess import *
15
16 try :
17         t = gettext.translation('ussd-widget', '/usr/share/locale')
18         _ = t.ugettext
19 except IOError:
20         print "Translation file for your language not found"
21         def retme(arg):
22                 return arg
23         _ = retme
24
25 ussd_languages = ["German", "English", "Italian", "French", "Spanish", "Dutch", "Swedish", "Danish", "Portuguese", "Finnish", "Norwegian", "Greek", "Turkish", "Reserved1", "Reserved2", "Unspecified"]
26
27 # TODO Cutt off too long messages and show them in separate dialog
28 # how TODO widget vertical minimum size policy
29 # TODO interface for queryng from scripts. For example query from one widget can change color of another widget 
30
31 class USSD_Controller:
32         def __init__( self, widget ) :
33                 self.widget = widget
34                 # number, parser, chain, interval, regexp, width, execute_at_start, retry pattern, font, name, language, show_message_box, message_box_parser, additional arguments 
35                 self.default_config = ["", "", "", 0, "", 0, True, [], pango.FontDescription("Nokia Sans 18"), _("Click to update"), 15, False, "", ""]
36                 self.config = self.default_config
37                 self.timeout_version = 0
38                 self.retry_version = 0
39                 self.retry_state = 0
40
41         def save_config( self ) :
42                 configname = os.getenv("HOME")+"/.ussdWidget.conf"
43                 # Aquire lock
44                 lockf = open(configname+".lock", 'a')
45                 fcntl.flock(lockf,fcntl.LOCK_EX)
46
47                 oldconfig=""
48                 try:
49                         fconfig = open(configname,"r")
50                         #Read configuration of other instances
51                         my_section = False
52                         for line in fconfig :
53                                 if line[0] == '%':
54                                         my_section = line[1:].strip() == self.id
55                                 if not my_section:
56                                         oldconfig += line
57                         fconfig.close()
58                 except:
59                         print _("Couldn't read previous config")
60
61                 fconfig = open(configname,"w")
62                 fconfig.seek(0)
63                 fconfig.write(oldconfig)
64                 fconfig.write("%"+self.id+"\n");
65                 fconfig.writelines(["# USSD query to be run by widget\n", "number="+self.config[0], "\n"])
66                 fconfig.writelines(["#Parser command for widget\n", "parser="+self.config[1], "\n"])
67                 fconfig.writelines(["#Parser command for banner\n", "parser_box="+self.config[12], "\n"])
68                 fconfig.writelines(["#Chain command\n", "chain="+self.config[2], "\n"])
69                 fconfig.writelines(["#Update interval in minutes\n", "interval="+str(self.config[3]), "\n"])
70                 fconfig.writelines(["#RegExp pattern\n", "regexp="+self.config[4], "\n"])
71                 fconfig.writelines(["#Widget width\n", "width="+str(self.config[5]), "\n"])
72                 fconfig.writelines(["#Execute query at start\n", "query_at_start="+str(self.config[6]), "\n"])
73                 fconfig.writelines(["#Retry pattern\n"])
74                 fconfig.write("retry=")
75                 first = True
76                 for i in self.config[7]:
77                         if not first:
78                                 fconfig.write ("-")
79                         fconfig.write(str(i))
80                         first = False
81                 fconfig.write("\n")
82                 fconfig.writelines(["#Font description\n", "font="+self.config[8].to_string(), "\n"])
83                 fconfig.writelines(["#Font color\n", "text_color="+self.widget.get_text_color().to_string(), "\n"])
84                 fconfig.writelines(["#Background color\n", "bg_color="+self.widget.get_bg_color().to_string(), "\n"])
85                 fconfig.writelines(["#Widget name\n", "name="+self.config[9], "\n"])
86                 fconfig.writelines(["#Show banner\n", "show_box="+str(self.config[11]), "\n"])
87                 fconfig.writelines(["#USSD reply language\n", "language="+str(self.config[10]), "\n"])
88                 fconfig.writelines(["#Additional ussdquery.py arguments\n", "args="+self.config[13], "\n"])
89                 fconfig.close()
90
91                 fcntl.flock(lockf,fcntl.LOCK_UN)
92                 lockf.close()
93
94         def get_config(self):
95                 return self.config
96
97         def read_config( self, id ):
98                 try :
99                         self.id = id
100                         config = open(os.getenv("HOME")+"/.ussdWidget.conf","r")
101
102                         error = False
103                         i = 0
104                         my_section = False
105                         for line in config :
106                                 i += 1 
107                                 if line[0] == '#':
108                                         continue
109                                 if line[0] == '%':
110                                         my_section = line[1:].strip() == id
111                                         continue
112
113                                 if not my_section:
114                                         # This is config for another instace
115                                         continue
116
117                                 line=line.split('=', 1)
118                                 
119                                 if len(line) != 2 :
120                                         error = True
121                                         print _("Error reading config on line %(line)d. = or # expected.")%{"line":i}
122                                         continue
123                                 if line[0] == "number" :
124                                         self.config[0] = line[1].strip()
125                                 elif line[0] == "parser" :
126                                         self.config[1] = line[1].strip()
127                                 elif line[0] == "parser_box" :
128                                         self.config[12] = line[1].strip()
129                                 elif line[0] == "chain" :
130                                         self.config[2] = line[1].strip()
131                                 elif line[0] == "interval" :
132                                         try:
133                                                 self.config[3] = int(line[1].strip())
134                                         except:
135                                                 error = True
136                                                 print _("Error reading config on line %(line)d. Integer expected.")%{"line":i}
137                                                 continue
138                                 elif line[0] == "regexp" :
139                                         self.config[4] = line[1].strip()
140                                 elif line[0] == "width" :
141                                         try:
142                                                 self.config[5] = int(line[1].strip())
143                                         except:
144                                                 error = True
145                                                 print _("Error reading config on line %(line)d. Integer expected.")%{"line":i}
146                                                 continue
147                                 elif line[0] == "query_at_start" :
148                                         if line[1].strip() == "True" :
149                                                 self.config[6] = True
150                                         else :
151                                                 self.config[6] = False
152                                 elif line[0] == "retry" :
153                                         line[1] = line[1].strip()
154                                         if line[1] != "":
155                                                 line[1] = line[1].split("-")
156                                                 i = 0
157                                                 while i < len(line[1]) :
158                                                         try:
159                                                                 line[1][i] = int(line[1][i])
160                                                         except:
161                                                                 error = True
162                                                                 print _("Error reading config on line %(line)d. Integer expected.")%{"line":i}
163                                                         i += 1
164                                                 self.config[7] = line[1]
165                                         else:
166                                                 self.config[7] = []
167                                                 continue
168                                 elif line[0] == "font" :
169                                         try:
170                                                 self.config[8] = pango.FontDescription(line[1].strip())
171                                         except:
172                                                 error = True
173                                                 print _("Error reading config on line %(line)d. Pango font description expected.")%{"line":i}
174                                                 continue
175                                 elif line[0] == "bg_color" :
176                                         try:
177                                                 self.widget.set_bg_color(gtk.gdk.color_parse(line[1].strip()))
178                                         except:
179                                                 error = True
180                                                 print _("Error reading config on line %(line)d. Expected color definition.")%{"line":i}
181                                 elif line[0] == "text_color" :
182                                         try:
183                                                 self.widget.set_text_color(gtk.gdk.color_parse(line[1].strip()))
184                                         except:
185                                                 error = True
186                                                 print _("Error reading config on line %(line)d. Expected color definition.")%{"line":i}
187                                 elif line[0] == "name" :
188                                         self.config[9] = line[1].strip()
189                                 elif line[0] == "show_box" :
190                                         if line[1].strip() == "True" :
191                                                 self.config[11] = True
192                                         else :
193                                                 self.config[11] = False
194                                 elif line[0] == "language" :
195                                         try:
196                                                 if int(line[1].strip()) >=0 and int(line[1].strip()) < len(ussd_languages):
197                                                         self.config[10] = int(line[1].strip())
198                                                 else:
199                                                         error = True
200                                                         print _("Error reading config on line %(line)d. Unknown language code.")%{"line":i}
201                                         except:
202                                                 error = True
203                                                 print _("Error reading config on line %(line)d. Integer expected.")%{"line":i}
204                                 elif line[0] == "args" :
205                                         self.config[13] = line[1].strip()
206                                 else :
207                                         error = True
208                                         print _("Error reading config on line %(line)d. Unexpected variable: ")%{"line":i}+line[0]
209                                         continue 
210
211                         config.close()
212
213                         if error :
214                                 self.widget.error = 1
215                                 self.widget.set_text (_("Config error"), 5000)  
216
217                         return self.config
218                 except  IOError:
219                         self.widget.error = 1
220                         self.widget.set_text (_("Config error"), 0)
221                         print _("IO error while reading config")
222
223                         return self.default_config
224
225         def on_show_settings( self, widget ) :
226                 dialog = UssdConfigDialog(self.config, self.widget.get_bg_color(), self.widget.get_text_color())
227
228                 while True:
229                         if dialog.run() != gtk.RESPONSE_OK :
230                                 dialog.destroy()
231                                 return
232
233                         test = check_regexp(dialog.regexp.get_text()) 
234                         if test :
235                                 dialog.on_error_regexp(test)
236                                 continue
237
238                         # Check, that we have ussd number
239                         if not check_number(dialog.ussdNumber.get_text()):
240                                 dialog.on_error_ussd_number()
241                                 continue
242
243                         # Parse retry pattern
244                         retry = dialog.retryEdit.get_text().strip()
245                         if retry != "" :
246                                 retry = retry.split("-")
247                                 i = 0
248                                 while i < len(retry) :
249                                         try:
250                                                 retry[i] = int(retry[i])
251                                         except:
252                                                 dialog.on_error_retry_pattern()
253                                                 break 
254                                         i += 1
255                         
256                                 if i < len(retry):
257                                         continue
258                         else :
259                                 retry = []
260
261                         break
262
263                 self.config = [
264                         dialog.ussdNumber.get_text(), 
265                         dialog.parser.get_text(), 
266                         dialog.chain.get_text(), 
267                         dialog.update_interval.get_value(), 
268                         dialog.regexp.get_text(),
269                         dialog.widthEdit.get_value(),
270                         dialog.query_at_start.get_active(),
271                         retry,
272                         dialog.font,
273                         dialog.wname.get_text(),
274                         dialog.language.get_active(),
275                         dialog.show_box.get_active(),
276                         dialog.b_parser.get_text(),
277                         dialog.args.get_text()
278                 ]
279
280                 widget.set_bg_color(dialog.bg_color)
281                 widget.set_text_color(dialog.text_color)
282
283                 self.save_config()
284
285                 widget.set_width(self.config[5])        
286                 self.reset_timed_renew()
287                 self.widget.label.modify_font(self.config[8])
288
289                 dialog.destroy()
290
291                 # Before running this function widget wasn't configured
292                 if self.config == self.default_config:
293                         self.widget.set_text(_("Click to update"))
294                 return
295
296         def callback_ussd_data( self, source, condition ):
297                 if condition == gobject.IO_IN or condition == gobject.IO_PRI :
298                         data = source.read( )
299                         if len( data ) > 0 :
300                                 self.cb_reply += data
301                                 return True
302                         else :
303                                 self.cb_ready = 1
304                                 return False
305
306                 elif condition == gobject.IO_HUP or condition == gobject.IO_ERR :
307                         self.cb_ready = 1
308                         self.process_reply()
309                         return False
310
311                 print (_("serious problems in program logic"))
312                 # This will force widget to show error message
313                 self.cb_reply = ""
314                 self.cb_ready = 1
315                 self.process_reply()
316                 return False
317
318
319         def call_external_script( self, ussd_code, language ):
320                 self.cb_ready = 0
321                 self.cb_reply = "";
322                 p = Popen(['/usr/bin/ussdquery.py', ussd_code, "-l", ussd_languages[language]] + smart_split_string(self.config[13],"%"), stdout=PIPE)
323                 gobject.io_add_watch( p.stdout, gobject.IO_IN | gobject.IO_PRI | gobject.IO_HUP | gobject.IO_ERR , self.callback_ussd_data )
324
325         def ussd_renew(self, widget, event):
326                 if self.widget.processing == 0:
327                         if self.config :
328                                 widget.processing = 1
329                                 widget.set_text(_("Processing"), 0)
330                                 self.call_external_script( self.config[0], self.config[10] )
331                         else :
332                                 widget.processing = 0
333                                 widget.error = 1
334                                 widget.set_text(_("No config"), 0)
335
336         def process_reply( self ):
337                 reply = self.cb_reply.strip()
338                 
339                 if reply == "" :
340                         self.widget.error = 1
341                         self.widget.set_text (_("Error"), 5000)
342                         if self.retry_state == len(self.config[7]):
343                                 self.retry_version += 1
344                                 self.retry_state = 0
345                         else :
346                                 self.retry_timer = gobject.timeout_add (1000*self.config[7][self.retry_state], self.retry_renew, self.retry_version)
347                                 self.retry_state += 1
348                 else :
349                         self.widget.error = 0
350                         # Apply regexp
351                         if self.config[4] != "":
352                                 try :
353                                         reply = re.match( self.config[4], reply ).group( 1 )
354                                 except Exception, e:
355                                         self.widget.error = 1
356                                         reply = _("Regexp Error: ") + str( e ) + "\n" + reply
357                         w_reply = b_reply = reply
358                         if self.widget.error == 0:
359                                 # Pass to box parser
360                                 if self.config[12] != "" and self.config[11]:
361                                         try:
362                                                 p = Popen(smart_split_string(self.config[12], reply), stdout=PIPE)
363                                                 b_reply = p.communicate()[0].strip()
364                                         except Exception, e:
365                                                 print _("Couldn't exec banner parser:")+str(e)
366                                                 self.widget.error = 1
367                                 # Pass to widget parser
368                                 if self.config[1] != "":
369                                         try:
370                                                 p = Popen(smart_split_string(self.config[1], reply), stdout=PIPE)
371                                                 w_reply = p.communicate()[0].strip()
372                                         except Exception, e:
373                                                 print _("Couldn't exec widget parser:")+str(e)
374                                                 self.widget.error = 1
375                                 # Pass to chain
376                                 if self.config[2] != "":
377                                         try:
378                                                 p = Popen(smart_split_string(self.config[2], reply))
379                                         except Exception, e:
380                                                 print _("Couldn't exec chain:")+str(e)
381                                                 self.widget.error = 1
382                         if self.config[11]:
383                                 banner = hildon.hildon_banner_show_information (self.widget, "", b_reply)
384                                 banner.set_timeout (5000)
385                                 b_reply
386                         self.widget.set_text(w_reply)
387                 self.widget.processing = 0
388
389         def timed_renew(self, version):
390                 if version < self.timeout_version :
391                         return False
392                 self.ussd_renew(self.widget, None)
393                 return True
394
395         def retry_renew(self,version):
396                 if self.widget.error == 0 or self.widget.processing == 1 or version < self.retry_version :
397                         return False
398                 self.ussd_renew(self.widget, None)
399                 return False
400
401         def reset_timed_renew (self) :
402                 self.timeout_version += 1
403                 if self.config[3] != 0 :
404                         self.timer = gobject.timeout_add (60000*self.config[3], self.timed_renew, self.timeout_version)
405
406 class pHelpDialog(gtk.Dialog):
407         def __init__(self, heading, text):
408                 gtk.Dialog.__init__(self, heading, None,
409                         gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR,
410                         (_("OK").encode("utf-8"), gtk.RESPONSE_OK))
411                 label = gtk.Label(text)
412                 label.set_line_wrap (True)
413                 self.vbox.add(label)
414                 self.show_all()
415                 self.parent
416
417 class UssdConfigDialog(gtk.Dialog):
418         def __init__(self, config, bg_color, text_color):
419                 gtk.Dialog.__init__(self, _("USSD widget"), None, 
420                         gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR,
421                         (_("Save").encode("utf-8"), gtk.RESPONSE_OK))
422
423                 self.font = config[8]
424                 self.bg_color = bg_color
425                 self.text_color = text_color
426
427                 self.set_size_request(-1, 400)
428                 self.ussdNumber = hildon.Entry(gtk.HILDON_SIZE_AUTO)
429                 self.ussdNumber.set_text(config[0])
430                 self.parser = hildon.Entry(gtk.HILDON_SIZE_AUTO)
431                 self.parser.set_text(config[1])
432                 self.b_parser = hildon.Entry(gtk.HILDON_SIZE_AUTO)
433                 self.b_parser.set_text(config[12])
434
435                 self.chain = hildon.Entry(gtk.HILDON_SIZE_AUTO)
436                 self.chain.set_text(config[2])
437                 self.update_interval = hildon.NumberEditor(0, 9999)
438                 self.update_interval.set_value(config[3])
439                 self.regexp = hildon.Entry(gtk.HILDON_SIZE_AUTO)
440                 self.regexp.set_text(config[4])
441                 self.widthEdit = hildon.NumberEditor(0, 1000)
442                 self.widthEdit.set_value(config[5])
443                 self.retryEdit = hildon.Entry(gtk.HILDON_SIZE_AUTO)
444                 self.args = hildon.Entry(gtk.HILDON_SIZE_AUTO)
445                 self.args.set_text(config[13])
446
447                 selector = hildon.TouchSelector(text=True)
448                 for i in ussd_languages:
449                         selector.append_text(i)
450                 self.language = hildon.PickerButton(gtk.HILDON_SIZE_AUTO, hildon.BUTTON_ARRANGEMENT_HORIZONTAL)
451                 self.language.set_selector(selector)
452                 self.language.set_active(config[10])
453                 self.language.set_title(_("USSD reply language"))
454                 self.language.set_size_request(-1, -1)
455
456                 self.wname = hildon.Entry(gtk.HILDON_SIZE_AUTO)
457                 self.wname.set_text(config[9])
458                 self.show_box = gtk.CheckButton(_("Enable banner. Parser:"))
459                 self.show_box.set_active(config[11])
460
461                 text = ""
462                 for i in config[7]:
463                         if text != "":
464                                 text += "-"
465                         text += str(i)
466                 self.retryEdit.set_text(text)
467
468                 self.query_at_start = gtk.CheckButton(_("Execute query on start"))
469                 self.query_at_start.set_active(config[6])
470
471                 self.fontButton = gtk.Button(_("Font"))
472                 self.fontButton.connect("clicked", self.on_show_font_selection)
473
474                 self.colorButton = gtk.Button(_("Background color"))
475                 self.colorButton.connect("clicked", self.on_show_color_selection)
476                 self.textColorButton = gtk.Button(_("Text color"))
477                 self.textColorButton.connect("clicked", self.on_show_text_color_selection)
478                 
479                 phelp = gtk.Button("?")
480                 phelp.connect("clicked", self.on_show_phelp)
481                 
482                 bphelp = gtk.Button("?")
483                 bphelp.connect("clicked", self.on_show_bphelp)
484
485                 chelp = gtk.Button("?")
486                 chelp.connect("clicked", self.on_show_chelp)
487
488                 reghelp = gtk.Button("?")
489                 reghelp.connect("clicked", self.on_show_reghelp)
490
491                 retryhelp = gtk.Button("?")
492                 retryhelp.connect("clicked", self.on_show_retryhelp)
493                 
494                 numberhelp = gtk.Button("?")
495                 numberhelp.connect("clicked", self.on_show_number_help)
496
497                 area = hildon.PannableArea()
498                 self.vbox.add(area)
499                 vbox = gtk.VBox()
500                 area.add_with_viewport(vbox)
501                 
502                 numberBox = gtk.HBox()
503                 numberLabel = gtk.Label(_("USSD number"))
504                 numberLabel.set_alignment(0,0.6)
505                 numberLabel.set_size_request(100, -1)
506                 numberhelp.set_size_request(1, -1)
507                 self.ussdNumber.set_size_request(200, -1)
508                 numberBox.add(numberLabel)
509                 numberBox.add(numberhelp)
510                 numberBox.add(self.ussdNumber)
511                 vbox.add(numberBox)
512
513                 vbox.add(self.language)
514
515                 vbox.add(self.query_at_start)
516
517                 nameBox = gtk.HBox()
518                 nameLabel = gtk.Label(_("Name"))
519                 nameLabel.set_alignment(0,0.6)
520                 nameLabel.set_size_request(100, -1)
521                 self.wname.set_size_request(200, -1)
522                 nameBox.add(nameLabel)
523                 nameBox.add(self.wname)
524                 vbox.add(nameBox)
525
526                 parserBox = gtk.HBox()
527                 parserLabel = gtk.Label(_("Parser for widget"))
528                 parserLabel.set_alignment(0,0.6)
529                 parserLabel.set_size_request(200, -1)
530                 phelp.set_size_request(10, -1)
531                 parserBox.add(parserLabel)
532                 parserBox.add(phelp)
533                 vbox.add(parserBox)
534                 vbox.add(self.parser)
535                 
536                 b_parserBox = gtk.HBox()
537                 self.show_box.set_size_request(200, -1)
538                 bphelp.set_size_request(10, -1)
539                 b_parserBox.add(self.show_box)
540                 b_parserBox.add(bphelp)
541                 vbox.add(b_parserBox)
542                 vbox.add(self.b_parser)
543
544                 chainBox = gtk.HBox()
545                 chainLabel = gtk.Label(_("Chain"))
546                 chainLabel.set_alignment(0,0.6)
547                 chainLabel.set_size_request(200, -1)
548                 chelp.set_size_request(10, -1)
549                 chainBox.add(chainLabel)
550                 chainBox.add(chelp)
551                 vbox.add(chainBox)
552                 vbox.add(self.chain)
553
554                 regexpBox = gtk.HBox()
555                 regexpLabel = gtk.Label(_("RegExp"))
556                 regexpLabel.set_alignment(0,0.6)
557                 regexpLabel.set_size_request(200, -1)
558                 reghelp.set_size_request(10, -1)
559                 regexpBox.add(regexpLabel)
560                 regexpBox.add(reghelp)
561                 vbox.add(regexpBox)
562                 vbox.add(self.regexp)           
563
564                 widthBox = gtk.HBox()
565                 widthLabel = gtk.Label(_("Max. width"))
566                 widthLabel.set_alignment(0,0.6)
567                 symbolsLabel = gtk.Label(_("symbols"))
568                 widthLabel.set_size_request(140, -1)
569                 self.widthEdit.set_size_request(50, -1)
570                 symbolsLabel.set_size_request(40,-1)
571                 widthBox.add(widthLabel)
572                 widthBox.add(self.widthEdit)
573                 widthBox.add(symbolsLabel)
574                 vbox.add(widthBox)
575
576                 updateBox = gtk.HBox()
577                 updateLabel = gtk.Label(_("Update every"))
578                 updateLabel.set_alignment(0,0.6)
579                 minutesLabel = gtk.Label(_("minutes"))
580                 updateLabel.set_size_request(140, -1)
581                 self.update_interval.set_size_request(50, -1)
582                 minutesLabel.set_size_request(40, -1)
583                 updateBox.add(updateLabel)
584                 updateBox.add(self.update_interval)
585                 updateBox.add(minutesLabel)
586                 vbox.add(updateBox)
587
588                 retryBox = gtk.HBox()
589                 retryLabel = gtk.Label(_("Retry pattern"))
590                 retryLabel.set_alignment(0,0.6)
591                 retryLabel.set_size_request(200, -1)
592                 retryhelp.set_size_request(10, -1)
593                 retryBox.add(retryLabel)
594                 retryBox.add(retryhelp)
595                 vbox.add(retryBox)
596                 vbox.add(self.retryEdit)                
597                 
598                 argsLabel = gtk.Label(_("Additional ussdquery.py options"))
599                 argsLabel.set_alignment(0,0.6)
600                 vbox.add(argsLabel)
601                 vbox.add(self.args)             
602                 
603                 viewBox = gtk.HBox()
604                 viewBox.add(self.fontButton)
605                 viewBox.add(self.textColorButton)
606                 viewBox.add(self.colorButton)
607                 vbox.add(viewBox)
608
609                 self.show_all()
610                 self.parent
611
612         #============ Dialog helper functions =============
613         def on_show_phelp(self, widget):
614                 dialog = pHelpDialog(_("Format help"), _("Reply would be passed to specified utility, output of utility would be shown to you on widget.\n       Format:\n% would be replaced by reply\n\\ invalidates special meaming of following symbol\n\" and ' work as usual\nspace delimits command line parameters of utility\n      Hint: use echo \"Your string %\" to prepend your string to reply."))
615                 dialog.run()
616                 dialog.destroy()
617
618         def on_show_bphelp(self, widget):
619                 dialog = pHelpDialog(_("Format help"), _("Reply would be passed to specified utility, output of utility would be shown to you on banner.\n       Format:\n% would be replaced by reply\n\\ invalidates special meaming of following symbol\n\" and ' work as usual\nspace delimits command line parameters of utility\n      Hint: use echo \"Your string %\" to prepend your string to reply."))
620                 dialog.run()
621                 dialog.destroy()
622         
623         def on_show_chelp(self, widget):
624                 dialog = pHelpDialog(_("Format help"), _("Reply would be passed to specified utility after parser utility. May be used for logging, statistics etc.\n       Format:\n% would be replaced by reply\n\\ invalidates special meaning of following symbol\n\" and ' work as usual\nspace delimits command line parameters of utility"))
625                 dialog.run()
626                 dialog.destroy()
627
628         def on_show_reghelp(self, widget):
629                 dialog = pHelpDialog(_("Format help"), _("Standard python regexps. Use\n (.+?[\d\,\.]+)\n to delete everything after first number."))
630                 dialog.run()
631                 dialog.destroy()
632
633         def on_show_retryhelp(self, widget):
634                 dialog = pHelpDialog(_("Format help"), _("Pauses between attemps (in seconds), delimited by -. For example 15-15-300 means \"In case of failure wait 15 seconds, try again, on failure wait 15 more secodns and try again, on failure make last attempt after 5 minutes\""))
635                 dialog.run()
636                 dialog.destroy()
637         
638         def on_show_number_help(self, widget):
639                 dialog = pHelpDialog(_("Format help"), _("USSD number. To perform USSD menu navigation divide queries vith spacebars. For xample '*100# 1' means 1st entry in *100# menu."))
640                 dialog.run()
641                 dialog.destroy()
642         
643         def on_error_regexp(self, error):
644                 dialog = pHelpDialog(_("Regexp syntax error"), error )
645                 dialog.run()
646                 dialog.destroy()
647
648         def on_error_ussd_number(self):
649                 dialog = pHelpDialog(_("Incorrect USSD number"), _("USSD number should contain only digits, +, * or #") )
650                 dialog.run()
651                 dialog.destroy()
652
653         def on_error_retry_pattern(self):
654                 dialog = pHelpDialog(_("Incorrect retry pattern"), _("Retry pattern should contain only numbers, delimited by -") )
655                 dialog.run()
656                 dialog.destroy()
657
658         def on_show_color_selection (self, event):
659                 colorDialog = gtk.ColorSelectionDialog(_("Choose background color"))
660                 colorDialog.colorsel.set_current_color(self.bg_color)
661                 if colorDialog.run() == gtk.RESPONSE_OK :
662                         self.bg_color = colorDialog.colorsel.get_current_color()
663                 colorDialog.destroy()
664
665         def on_show_text_color_selection (self, event):
666                 colorDialog = gtk.ColorSelectionDialog(_("Choose text color"))
667                 colorDialog.colorsel.set_current_color(self.text_color)
668                 if colorDialog.run() == gtk.RESPONSE_OK :
669                         self.text_color = colorDialog.colorsel.get_current_color()
670                 colorDialog.destroy()
671         
672         def on_show_font_selection (self, event):
673                 fontDialog = gtk.FontSelectionDialog(_("Choose a font"))
674                 fontDialog.set_font_name(self.font.to_string())
675
676                 if fontDialog.run() != gtk.RESPONSE_OK :
677                         fontDialog.destroy()
678                         return
679
680                 self.font = pango.FontDescription (fontDialog.get_font_name())
681                 fontDialog.destroy()
682
683 def smart_split_string (str, query) :
684         word = ""
685         result = []
686         # Is simbol backslashed?
687         bs = 0
688         # Quotes: 1 - ", 2 - ', 0 - no quotes
689         qs = 0
690         for i in range(len(str)) :
691           if bs == 0 and (str[i] == '"' and qs == 1 or str[i] == "'" and qs == 2) :
692                   qs = 0
693           elif bs == 0 and qs == 0 and (str[i] == '"' or str[i] == "'") :
694                   if str[i] == '"':
695                           qs = 1
696                   else :
697                           qs = 2
698           elif bs == 0 and str[i] == '\\' :
699                   bs = 1
700           elif bs == 0 and str[i] == '%' :
701                   word += query
702                   ws = 0
703           else :
704                   if bs == 1 and str[i] != '\\' and str[i] != '"' and str[i] != "'" :
705                           word += "\\"
706                   if qs == 0 and (str[i] == " " or str[i] == "\t") :
707                           if word != "" :
708                                   result.append(word)
709                                   word = ""
710                   else :
711                           word += str[i]
712                   bs = 0 
713         if word != "" :
714                 result.append(word)
715         return result 
716
717 def check_regexp(regexp):
718         try :
719                 re.compile( regexp )
720         except Exception, e:
721                         return str(e)
722         return False
723
724 def check_number(number):
725         for s in number :
726                 if not (s in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "*", "#", " "]) :
727                         return False
728         return True
729
730 #=============== The widget itself ================
731
732 def get_color(logicalcolorname):
733         settings = gtk.settings_get_default()
734         color_style = gtk.rc_get_style_by_paths(settings, 'GtkButton', 'osso-logical-colors', gtk.Button)
735         return color_style.lookup_color(logicalcolorname)
736
737 class UssdWidgetPlugin(hildondesktop.HomePluginItem):
738         def __init__(self):
739                 hildondesktop.HomePluginItem.__init__(self)
740         
741                 self.processing = 0
742                 self.bg_color=gtk.gdk.color_parse('#000000')
743                 self.text_color=gtk.gdk.color_parse('#ffffff')
744                 self.error = 0
745                 self.timeout_version = 0
746
747                 colormap = self.get_screen().get_rgba_colormap()
748                 self.set_colormap (colormap)
749
750                 self.controller = USSD_Controller(self)
751                  
752 # TODO Click event would be better
753                 self.connect("button-press-event", self.controller.ussd_renew)
754
755                 self.vbox = gtk.HBox()
756                 self.add(self.vbox)
757
758                 self.set_settings(True)
759                 self.connect("show-settings", self.controller.on_show_settings)
760                 self.label = gtk.Label("")
761                 
762                 self.vbox.add(self.label)
763                 self.vbox.set_child_packing(self.label, False, False, 0, gtk.PACK_START)
764                 self.label.set_padding(15, 10)
765                 self.label.set_size_request(-1,-1)
766                 self.set_size_request(-1,-1)
767                 self.label.set_line_wrap (True)
768
769                 self.vbox.show_all()
770
771         def do_show(self):
772                 config = self.controller.read_config(self.get_applet_id())
773                 self.set_width(config[5])
774                 self.set_text(config[9])                
775                 if config[6]:
776                         self.controller.ussd_renew(self, None)
777
778                 self.label.modify_font(config[8])
779                 self.controller.reset_timed_renew()
780                 hildondesktop.HomePluginItem.do_show(self)
781         
782         def error_return (self):
783                 if self.error == 1 and self.processing == 0:
784                         self.set_text(self.text)
785                 return False
786
787         # showfor =
788         #       -1 - This is a permanent text message
789         #       0  - This is service message, but it shouldn't be hidden automatically
790         #       >0 - This is service message, show permament message after showfor milliseconds
791         def set_text(self, text, showfor=-1):
792                 if showfor > 0 :
793                         # Show previous text after 5 seconds
794                         gobject.timeout_add (showfor, self.error_return)
795                 else :
796                         if showfor == -1 :
797                                 self.text = text
798                 
799                 config = self.controller.get_config()
800                 self.label.set_text(text)
801
802         def get_text(self):
803                 return self.text
804
805         def set_width(self, width):
806                 if width != 0:
807                         self.label.set_width_chars (width)
808                 else :
809                         self.label.set_width_chars(-1)
810
811         def set_bg_color(self, color):
812                 self.bg_color = color
813
814         def get_bg_color(self):
815                 return self.bg_color
816
817         def set_text_color(self, color):
818                 self.label.modify_fg(gtk.STATE_NORMAL, color)           
819                 self.text_color = color
820
821         def get_text_color(self):
822                 return self.text_color
823
824         def _expose(self, event):
825                 cr = self.window.cairo_create()
826
827                 # draw rounded rect
828                 width, height = self.label.allocation[2], self.label.allocation[3]
829
830                 #/* a custom shape, that could be wrapped in a function */
831                 x0 = 0   #/*< parameters like cairo_rectangle */
832                 y0 = 0
833
834                 radius = min(15, width/2, height/2)  #/*< and an approximate curvature radius */
835
836                 x1 = x0 + width
837                 y1 = y0 + height
838
839                 cr.move_to  (x0, y0 + radius)
840                 cr.arc (x0 + radius, y0 + radius, radius, 3.14, 1.5 * 3.14)
841                 cr.line_to (x1 - radius, y0)
842                 cr.arc (x1 - radius, y0 + radius, radius, 1.5 * 3.14, 0.0)
843                 cr.line_to (x1 , y1 - radius)
844                 cr.arc (x1 - radius, y1 - radius, radius, 0.0, 0.5 * 3.14)
845                 cr.line_to (x0 + radius, y1)
846                 cr.arc (x0 + radius, y1 - radius, radius, 0.5 * 3.14, 3.14)
847
848                 cr.close_path ()
849
850                 fg_color = get_color("ActiveTextColor")
851
852                 if self.processing :
853                         bg_color=fg_color
854                 else :
855                         bg_color=self.bg_color
856
857                 cr.set_source_rgba (bg_color.red / 65535.0, bg_color.green/65535.0, bg_color.blue/65535.0, 0.7)
858                 cr.fill_preserve ()
859
860                 if self.error :
861                         cr.set_source_rgba (1.0, 0.0, 0.0, 0.5)
862                 else :
863                         cr.set_source_rgba (fg_color.red / 65535.0, fg_color.green / 65535.0, fg_color.blue / 65535.0, 0.7)
864                 cr.stroke ()
865
866         def do_expose_event(self, event):
867                 self.chain(event)
868                 self._expose (event)
869                 self.vbox.do_expose_event (self, event)
870
871 hd_plugin_type = UssdWidgetPlugin
872
873 # The code below is just for testing purposes.
874 # It allows to run the widget as a standalone process.
875 if __name__ == "__main__":
876         import gobject
877         gobject.type_register(hd_plugin_type)
878         obj = gobject.new(hd_plugin_type, plugin_id="plugin_id")
879         obj.show_all()
880         gtk.main()