117605dcfa724232797c8a8f136636cc13d6ff8b
[vuplus_dvbapp] / lib / python / Plugins / Extensions / HbbTV / plugin.py
1 from Plugins.Plugin import PluginDescriptor
2
3 from Screens.Screen import Screen
4 from Screens.InfoBar import InfoBar
5 from Screens.ChoiceBox import ChoiceBox
6 from Screens.MessageBox import MessageBox
7 from Screens.InfoBarGenerics import InfoBarNotifications
8 from Screens.VirtualKeyBoard import VirtualKeyBoard
9 from Screens.HelpMenu import HelpableScreen
10 from Screens.ChannelSelection import service_types_tv
11
12 from Components.Language import language
13 from Components.PluginComponent import plugins
14 from Components.Button import Button
15 from Components.Sources.StaticText import StaticText
16 from Components.ActionMap import NumberActionMap, ActionMap, HelpableActionMap
17 from Components.ServiceEventTracker import ServiceEventTracker
18 from Components.MenuList import MenuList
19 from Components.Label import Label, MultiColorLabel
20 from Components.ConfigList import ConfigListScreen
21 from Components.VolumeControl import VolumeControl
22 from Components.Pixmap import Pixmap
23 from Components.config import config, ConfigYesNo, ConfigSubsection, ConfigPosition, getConfigListEntry, ConfigBoolean, ConfigInteger, ConfigText, ConfigSelection, configfile
24
25 from enigma import eTimer, eConsoleAppContainer, getDesktop, eServiceReference, iPlayableService, iServiceInformation, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, RT_VALIGN_CENTER, getPrevAsciiCode, eRCInput, fbClass, eServiceCenter
26
27 from bookmark import BookmarkManager, BookmarkData, CategoryData
28
29 import os, struct, threading, stat, select, time, socket, select
30
31 from __init__ import _
32
33 strIsEmpty = lambda x: x is None or len(x) == 0
34
35 HBBTVAPP_PATH = "/usr/local/hbb-browser"
36 COMMAND_PATH = '/tmp/.sock.hbbtv.cmd'
37
38 _g_helper = None
39
40 class GlobalValues:
41         command_util   = None
42         command_server = None
43
44         before_service = None
45
46         channel_info_sid   = None
47         channel_info_onid  = None
48         channel_info_tsid  = None
49         channel_info_name  = None
50         channel_info_orgid = None
51
52         hbbtv_handelr = None
53
54         packet_m  = 0xBBADBEE
55         packet_h  = '!IIII'
56         packet_hl = struct.calcsize(packet_h)
57
58         need_restart = False
59         plugin_browser = None
60
61         resX = 0
62         resY = 0
63         def UpdateInfoBar(self):
64                 if self.resX == 1024 and self.resY == 720:
65                         return
66                 try:
67                         infobar = InfoBar.instance
68                         if infobar._InfoBarShowHide__state != 3:
69                                 return
70                         infobar.doTimerHide()
71                         infobar.serviceStarted()
72                 except: pass
73         
74 __gval__ = GlobalValues()
75
76 def setDefaultResolution(x, y):
77         global __gval__
78         __gval__.resX = x
79         __gval__.resY = y
80
81 def setResolution(xres, yres):
82         global __gval__
83         if __gval__.resX == 1280 and __gval__.resY == 720:
84                 return
85         from enigma import gMainDC
86         gMainDC.getInstance().setResolution(xres, yres)
87
88 def restoreResolution():
89         global __gval__
90         setResolution(1280, 720)
91         setResolution(__gval__.resX, __gval__.resY)
92
93         if __gval__.resX == 1280 and __gval__.resY == 720:
94                 return
95         __gval__.UpdateInfoBar()
96
97 def setPluginBrowser(browser=None):
98         global __gval__
99         __gval__.plugin_browser = browser
100 def getPluginBrowser():
101         global __gval__
102         return __gval__.plugin_browser
103
104 def getPacketHeaders():
105         global __gval__
106         return (__gval__.packet_m, __gval__.packet_h, __gval__.packet_hl)
107
108 def setChannelInfo(sid, onid, tsid, name, orgid):
109         if sid is None:   sid   = 0;
110         if onid is None:  onid  = 0;
111         if tsid is None:  tsid  = 0;
112         if name is None:  name  = "";
113         if orgid is None: orgid = 0;
114         global __gval__
115         __gval__.channel_info_sid   = sid
116         __gval__.channel_info_onid  = onid
117         __gval__.channel_info_tsid  = tsid
118         __gval__.channel_info_name  = name
119         __gval__.channel_info_orgid = orgid
120         print "Set Channel Info >> sid : %X, onid : %X, tsid : %X, name : %s, orgid : %d " % (sid, onid, tsid, name, orgid)
121 def getChannelInfos():
122         global __gval__
123         print "Get Channel Info >> sid : %X, onid : %X, tsid : %X, name : %s, orgid : %d " % (__gval__.channel_info_sid, 
124                 __gval__.channel_info_onid, __gval__.channel_info_tsid, __gval__.channel_info_name, __gval__.channel_info_orgid)
125         return (__gval__.channel_info_sid, 
126                 __gval__.channel_info_onid, 
127                 __gval__.channel_info_tsid, 
128                 __gval__.channel_info_name, 
129                 __gval__.channel_info_orgid)
130
131 def isNeedRestart():
132         global __gval__
133         print "Need Restart(GET) : ", __gval__.need_restart
134         return __gval__.need_restart
135 def setNeedRestart(n):
136         global __gval__
137         __gval__.need_restart = n
138         print "Need Restart(SET) : ", __gval__.need_restart
139
140 def getCommandUtil():
141         global __gval__
142         return __gval__.command_util
143 def getCommandServer():
144         global __gval__
145         return __gval__.command_server
146
147 def setBeforeService(s):
148         global __gval__
149         __gval__.before_service = s
150 def getBeforeService():
151         global __gval__
152         return __gval__.before_service
153
154 def _unpack(packed_data):
155         (mg, h, hlen) = getPacketHeaders()
156
157         if strIsEmpty(packed_data):
158                 return None
159         (m, o, l, s) = struct.unpack(h, packed_data[:hlen])
160         if m != mg:
161                 return None
162         d = 0
163         if l > 0:
164                 d = packed_data[hlen:hlen+l]
165         return (o,d,s)
166
167 def _pack(opcode, params=None, reserved=0):
168         (m, h, hlen) = getPacketHeaders()
169         if strIsEmpty(params):
170                 params = ''
171         packed_data = struct.pack(h, m, opcode, len(params), reserved)
172         return packed_data + params
173
174 class OpCodeSet:
175         def __init__(self):
176                 self._opcode_ = {
177                          "OP_UNKNOWN"                   : 0x0000
178                         ,"OP_HBBTV_EXIT"                : 0x0001
179                         ,"OP_HBBTV_OPEN_URL"            : 0x0002
180                         ,"OP_HBBTV_LOAD_AIT"            : 0x0003
181                         ,"OP_HBBTV_UNLOAD_AIT"          : 0x0004
182                         ,"OP_HBBTV_FULLSCREEN"          : 0x0005
183                         ,"OP_HBBTV_TITLE"               : 0x0006
184                         ,"OP_HBBTV_RETRY_OPEN_URL"      : 0x0009
185                         ,"OP_HBBTV_CHANGE_CHANNEL"      : 0x000A
186                         ,"OP_OIPF_GET_CHANNEL_INFO_URL" : 0x0101
187                         ,"OP_OIPF_GET_CHANNEL_INFO_AIT" : 0x0102
188                         ,"OP_OIPF_GET_CHANNEL_INFO_LIST": 0x0103
189                         ,"OP_VOD_URI"                   : 0x0201
190                         ,"OP_VOD_PLAY"                  : 0x0202
191                         ,"OP_VOD_STOP"                  : 0x0203
192                         ,"OP_VOD_PAUSE"                 : 0x0204
193                         ,"OP_VOD_STATUS"                : 0x0205
194                         ,"OP_VOD_FORBIDDEN"             : 0x0206
195                         ,"OP_VOD_STOPED"                : 0x0207
196                         ,"OP_VOD_SPEED_CTRL"            : 0x0208
197                         ,"OP_VOD_SEEK_CTRL"             : 0x0209
198                         ,"OP_BROWSER_OPEN_URL"          : 0x0301
199                         ,"OP_BROWSER_VKBD_REQ"          : 0x0309
200                         ,"OP_BROWSER_VKBD_RES"          : 0x030A
201                         ,"OP_BROWSER_VKBD_PASTE_REQ"    : 0x030B
202                         ,"OP_BROWSER_VKBD_PASTE_KEY"    : 0x030C
203                         ,"OP_BROWSER_VKBD_PASTE_MOUSE"  : 0x030D
204                         ,"OP_BROWSER_MENU_REQ"          : 0x030E
205                         ,"OP_BROWSER_MENU_RES"          : 0x030F
206                         ,"OP_BROWSER_NEED_RELOAD_KEYMAP": 0x0313
207                         ,"OP_DVBAPP_VOL_UP"             : 0x0401
208                         ,"OP_DVBAPP_VOL_DOWN"           : 0x0402
209                         ,"OP_DVBAPP_SET_VOL"            : 0x0403
210                         ,"OP_SYSTEM_OUT_OF_MEMORY"      : 0x0501
211                         ,"OP_SYSTEM_NOTIFY_MY_PID"      : 0x0502
212                         ,"OP_VIDEOBACKEND_ENABLE"       : 0x0601
213                         ,"OP_VIDEOBACKEND_DISABLE"      : 0x0602
214                         ,"OP_BROWSER_OPEN_YOUTUBETV"    : 0x0603
215                 }
216                 self._opstr_ = {
217                          0x0000 : "OP_UNKNOWN"
218                         ,0x0001 : "OP_HBBTV_EXIT"
219                         ,0x0002 : "OP_HBBTV_OPEN_URL"
220                         ,0x0003 : "OP_HBBTV_LOAD_AIT"
221                         ,0x0004 : "OP_HBBTV_UNLOAD_AIT"
222                         ,0x0005 : "OP_HBBTV_FULLSCREEN"
223                         ,0x0006 : "OP_HBBTV_TITLE"
224                         ,0x0009 : "OP_HBBTV_RETRY_OPEN_URL"
225                         ,0x000A : "OP_HBBTV_CHANGE_CHANNEL"
226                         ,0x0101 : "OP_OIPF_GET_CHANNEL_INFO_URL"
227                         ,0x0102 : "OP_OIPF_GET_CHANNEL_INFO_AIT"
228                         ,0x0103 : "OP_OIPF_GET_CHANNEL_INFO_LIST"
229                         ,0x0201 : "OP_VOD_URI"
230                         ,0x0202 : "OP_VOD_PLAY"
231                         ,0x0203 : "OP_VOD_STOP"
232                         ,0x0204 : "OP_VOD_PAUSE"
233                         ,0x0205 : "OP_VOD_STATUS"
234                         ,0x0206 : "OP_VOD_FORBIDDEN"
235                         ,0x0207 : "OP_VOD_STOPED"
236                         ,0x0208 : "OP_VOD_SPEED_CTRL"
237                         ,0x0209 : "OP_VOD_SEEK_CTRL"
238                         ,0x0301 : "OP_BROWSER_OPEN_URL"
239                         ,0x0309 : "OP_BROWSER_VKBD_REQ"
240                         ,0x030A : "OP_BROWSER_VKBD_RES"
241                         ,0x030B : "OP_BROWSER_VKBD_PASTE_REQ"
242                         ,0x030C : "OP_BROWSER_VKBD_PASTE_KEY"
243                         ,0x030D : "OP_BROWSER_VKBD_PASTE_MOUSE"
244                         ,0x030E : "OP_BROWSER_MENU_REQ"
245                         ,0x030F : "OP_BROWSER_MENU_RES"
246                         ,0x0313 : "OP_BROWSER_NEED_RELOAD_KEYMAP"
247                         ,0x0401 : "OP_DVBAPP_VOL_UP"
248                         ,0x0402 : "OP_DVBAPP_VOL_DOWN"
249                         ,0x0403 : "OP_DVBAPP_SET_VOL"
250                         ,0x0501 : "OP_SYSTEM_OUT_OF_MEMORY"
251                         ,0x0502 : "OP_SYSTEM_NOTIFY_MY_PID"
252                         ,0x0601 : "OP_VIDEOBACKEND_ENABLE"
253                         ,0x0602 : "OP_VIDEOBACKEND_DISABLE"
254                         ,0x0603 : "OP_BROWSER_OPEN_YOUTUBETV"
255                 }
256
257         def get(self, opstr):
258                 try:
259                         return self._opcode_[opstr]
260                 except: pass
261                 return self._opcode_["OP_UNKNOWN"]
262
263         def what(self, opcode):
264                 try:
265                         return self._opstr_[opcode]
266                 except: pass
267                 return self._opstr_["0x0000"]
268
269 class SocketParams:
270         def __init__(self):
271                 self.protocol = None
272                 self.type     = None
273                 self.addr     = None
274                 self.buf_size = 4096
275                 self.handler  = None
276                 self.timeout  = 5
277                 self.destroy  = None
278
279 class StreamServer:
280         def __init__(self, params):
281                 self._protocol = params.protocol
282                 self._type     = params.type
283                 self._addr     = params.addr
284                 self._buf_size = params.buf_size
285                 self._handler  = params.handler
286                 self._timeout  = params.timeout
287                 self._destroy  = params.destroy
288
289                 self._terminated = False
290                 self._server_thread = None
291
292                 self.onHbbTVCloseCB = []
293                 self.onSetPageTitleCB = []
294
295         def __del__(self):
296                 if self._destroy is not None:
297                         self._destroy(self._addr)
298
299         def stop(self):
300                 self._terminated = True
301                 if self._server_thread is not None:
302                         self._server_thread.join()
303                         self._server_thread = None
304
305         def start(self):
306                 self._socket = socket.socket(self._protocol, self._type)
307                 self._socket.settimeout(self._timeout)
308                 self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
309                 self._socket.bind(self._addr)
310                 self._socket.listen(True)
311
312                 self._server_thread = threading.Thread(target=self._listen)
313                 self._server_thread.start()
314
315         def _listen(self):
316                 select_list = [self._socket]
317                 def _accept():
318                         try:
319                                 conn, addr = self._socket.accept()
320                                 self._client(conn, addr)
321                         except Exception, ErrMsg:
322                                 print "ServerSocket Error >>", ErrMsg
323                                 pass
324
325                 while not self._terminated:
326                         readable, writable, errored = select.select(select_list, [], [], self._timeout)
327                         for s in readable:
328                                 if s is self._socket:
329                                         _accept()
330
331         def _client(self, conn, addr):
332                 try:
333                         send_data     = ''
334                         received_data = conn.recv(self._buf_size)
335                         if self._handler is not None and not strIsEmpty(received_data):
336                                 send_data = self._handler.doHandle(received_data, self.onHbbTVCloseCB, self.onSetPageTitleCB)
337                         self._send(conn, send_data)
338                 except Exception, ErrMsg: 
339                         try: conn.close()
340                         except:pass
341                         if self._handler is not None:
342                                 self._handler.printError(ErrMsg)
343         def _send(self, conn, data) :
344                 conn.send(data)
345                 conn.close()
346
347 class ServerFactory:
348         def doListenUnixTCP(self, name, handler):
349                 def destroy(name):
350                         import os
351                         try:
352                                 if os.path.exists(name):
353                                         os.unlink(name)
354                                         print "Removed ", name
355                         except: pass
356                 destroy(name)
357
358                 params = SocketParams()
359                 params.protocol = socket.AF_UNIX
360                 params.type     = socket.SOCK_STREAM
361                 params.addr     = name
362                 params.handler  = handler
363                 params.destroy  = destroy
364
365                 streamServer = StreamServer(params)
366                 streamServer.start()
367                 return streamServer
368
369         def doListenInetTCP(self, ip, port, handler):
370                 print "Not implemented yet!!"
371         def doListenUnixDGRAM(self, name, handler):
372                 print "Not implemented yet!!"
373         def doListenInetDGRAM(self, ip, port, handler):
374                 print "Not implemented yet!!"
375
376 class Handler:
377         def doUnpack(self, data):
378                 return _unpack(data)
379
380         def doPack(self, opcode, params, reserved=0):
381                 return _pack(opcode, params, reserved)
382
383         def doHandle(self, data, onCloseCB):
384                 opcode, params = 0x0, 'Invalid Request!!'
385                 return _pack(opcode, params)
386
387         def printError(self, reason):
388                 print reason
389
390 class BrowserCommandUtil(OpCodeSet):
391         def __init__(self):
392                 self._fd = None
393                 OpCodeSet.__init__(self)
394
395         def isConnected(self):
396                 if self._fd is None:
397                         return False
398                 return True
399
400         def doConnect(self, filename):
401                 if not os.path.exists(filename):
402                         print "File not exists :", filename
403                         return False
404                 try:
405                         self._fd = os.open(filename, os.O_WRONLY|os.O_NONBLOCK)
406                         if self._fd is None:
407                                 print "Fail to open file :", filename
408                                 return False
409                 except Exception, ErrMsg:
410                         print ErrMsg
411                         self._fd = None
412                         return False
413                 return True
414
415         def doDisconnect(self):
416                 if self._fd is None:
417                         return
418                 os.close(self._fd)
419                 self._fd = None
420
421         def doSend(self, command, params=None, reserved=0):
422                 if self._fd is None:
423                         print "No found pipe!!"
424                         return False
425                 data = ''
426                 try:
427                         data = _pack(self.get(command), params, reserved)
428                         if data is None:
429                                 return False
430                         os.write(self._fd, data)
431                         print "Send OK!! :", command
432                 except: return False
433                 return True
434
435         def sendCommand(self, command, params=None, reserved=0):
436                 if not self.isConnected():
437                         global COMMAND_PATH
438                         self.doConnect(COMMAND_PATH)
439                 result = self.doSend(command, params, reserved)
440                 self.doDisconnect()
441                 return result
442
443 class HandlerHbbTV(Handler):
444         _vod_service = None
445         def __init__(self, session):
446                 self._session = session
447                 self.opcode = OpCodeSet()
448                 self.handle_map = {
449                          0x0001 : self._cb_handleCloseHbbTVBrowser
450                         ,0x0006 : self._cb_handleSetPageTitle
451                         ,0x0009 : self._cb_handleHbbTVRetryOpen
452                         ,0x000A : self._cb_handleHbbTVChangeChannel
453                         ,0x0101 : self._cb_handleGetChannelInfoForUrl
454                         ,0x0102 : self._cb_handleGetChannelInfoForAIT
455                         ,0x0103 : self._cb_handleGetChannelInfoList
456                         ,0x0201 : self._cb_handleVODPlayerURI
457                         ,0x0202 : self._cb_handleVODPlayerPlay
458                         ,0x0203 : self._cb_handleVODPlayerStop
459                         ,0x0204 : self._cb_handleVODPlayerPlayPause
460                         ,0x0401 : self._cb_handleDVBAppVolUp
461                         ,0x0402 : self._cb_handleDVBAppVolDown
462                         ,0x0403 : self._cb_handleDVBAppSetVol
463                         ,0x0208 : self._cb_handleVODSpeedCtrl
464                         ,0x0209 : self._cb_handleVODSeekCtrl
465                         ,0x0501 : self._cb_handleSystemOutOfMemory
466                         ,0x0502 : self._cb_handleSystemNotufyMyPID
467                         ,0x0309 : self._cb_handleShowVirtualKeyboard
468                         ,0x030B : self._cb_handlePasteVirtualKeyboard
469                         ,0x030E : self._cb_handleBrowserMenuReq
470                         ,0x0601 : self._cb_handleVideobackendEnable
471                         ,0x0602 : self._cb_handleVideobackendDisable
472                 }
473                 self._on_close_cb = None
474                 self._on_set_title_cb = None
475
476                 self._vod_uri = None
477
478                 self._retry_open_url = None
479                 self._timer_retry_open = eTimer()
480                 self._timer_paste_vkbd = eTimer()
481                 self._curren_title = None
482
483         def _handle_dump(self, handle, opcode, data=None):
484                 if True: return
485                 print str(handle)
486                 try:
487                         print "    - opcode : ", self.opcode.what(opcode)
488                 except: pass
489                 print "    - data   : ", data
490
491         def doHandle(self, data, onCloseCB, onSetPageTitleCB):
492                 opcode, params, reserved = None, None, 0
493                 self._on_close_cb = onCloseCB
494                 self._on_set_title_cb = onSetPageTitleCB
495                 try:
496                         datas  = self.doUnpack(data)
497                 except Exception, ErrMsg:
498                         print "Unpacking packet ERR :", ErrMsg
499                         params = 'fail to unpack packet!!'
500                         opcode = self.opcode.get("OP_UNKNOWN")
501                         return self.doPack(opcode, params)
502                 else:
503                         opcode = datas[0]
504                         params = datas[1]
505                 self.opcode.what(opcode)
506
507                 try:
508                         #print self.handle_map[opcode]
509                         (reserved, params) = self.handle_map[opcode](opcode, params)
510                 except Exception, ErrMsg:
511                         print "Handling packet ERR :", ErrMsg
512                         params = 'fail to handle packet!!'
513                         opcode = self.opcode.get("OP_UNKNOWN")
514                         return self.doPack(opcode, params)
515                 self._on_close_cb = None
516                 self._on_set_title_cb = None
517                 return self.doPack(opcode, params, reserved)
518
519         def _cb_handleVideobackendEnable(self, opcode, data):
520                 self._handle_dump(self._cb_handleVideobackendEnable, opcode, data)
521                 service = self._session.nav.getCurrentlyPlayingServiceReference()
522                 setBeforeService(service)
523                 self._session.nav.stopService()
524                 return (0, "OK")
525
526         def _cb_handleVideobackendDisable(self, opcode, data):
527                 self._handle_dump(self._cb_handleVideobackendDisable, opcode, data)
528                 before_service = getBeforeService()
529                 self._session.nav.playService(before_service)
530                 return (0, "OK")
531
532         def _cb_handleHbbTVChangeChannel(self, opcode, data):
533                 self._handle_dump(self._cb_handleHbbTVChangeChannel, opcode, data)
534                 global _g_helper
535                 if _g_helper is None: 
536                         return (0, "NOK")
537                 dataItems = data.split(":")
538                 sid  = dataItems[0]
539                 tsid = dataItems[1]
540                 if not _g_helper.doChangeChannel(sid, tsid):
541                         return (0, "NOK")
542                 return (0, "OK")
543
544         def _cb_handleBrowserMenuReq(self, opcode, data):
545                 self._handle_dump(self._cb_handleBrowserMenuReq, opcode, data)
546                 #restoreResolution()
547                 fbClass.getInstance().unlock()
548                 eRCInput.getInstance().unlock()
549                 browser = getPluginBrowser()
550                 if browser is not None:
551                         browser.setCurrentPageUrl(data, self._curren_title)
552                 return (0, "OK")
553
554         def _cb_handlePasteVirtualKeyboard(self, opcode, data):
555                 self._handle_dump(self._cb_handlePasteVirtualKeyboard, opcode, data)
556                 def _cb_PasteRefocusVirtualKeyboard():
557                         self._timer_paste_vkbd.stop()
558                         command_util = getCommandUtil()
559                         command_util.sendCommand('OP_BROWSER_VKBD_PASTE_MOUSE')
560                         try:
561                                 self._timer_paste_vkbd.callback.remove(_cb_PasteMouseVirtualKeyboard)
562                         except: pass
563                 def _cb_PasteKeyVirtualKeyboard():
564                         self._timer_paste_vkbd.stop()
565                         command_util = getCommandUtil()
566                         command_util.sendCommand('OP_BROWSER_VKBD_PASTE_KEY')
567                         try:
568                                 self._timer_paste_vkbd.callback.remove(_cb_PasteKeyVirtualKeyboard)
569                         except: pass
570                         self._timer_paste_vkbd.callback.append(_cb_PasteRefocusVirtualKeyboard)
571                         self._timer_paste_vkbd.start(100)
572                 def _cb_PasteMouseVirtualKeyboard():
573                         self._timer_paste_vkbd.stop()
574                         command_util = getCommandUtil()
575                         command_util.sendCommand('OP_BROWSER_VKBD_PASTE_MOUSE')
576                         #time.sleep(1)
577                         #command_util.sendCommand('OP_BROWSER_VKBD_PASTE_MOUSE')
578                         try:
579                                 self._timer_paste_vkbd.callback.remove(_cb_PasteMouseVirtualKeyboard)
580                         except: pass
581                         #self._timer_paste_vkbd.callback.append(_cb_PasteKeyVirtualKeyboard)
582                         #self._timer_paste_vkbd.start(1000)
583                 self._timer_paste_vkbd.callback.append(_cb_PasteMouseVirtualKeyboard)
584                 self._timer_paste_vkbd.start(50)
585                 return (0, "OK")
586
587         def _cb_virtualKeyboardClosed(self, data=None):
588                 fbClass.getInstance().lock()
589                 eRCInput.getInstance().lock()
590                 #setResolution(1280, 720)
591                 command_util = getCommandUtil()
592                 command_util.sendCommand('OP_BROWSER_VKBD_RES', data)
593
594         def _cb_handleShowVirtualKeyboard(self, opcode, data):
595                 self._handle_dump(self._cb_handleShowVirtualKeyboard, opcode, data)
596                 #restoreResolution()
597                 fbClass.getInstance().unlock()
598                 eRCInput.getInstance().unlock()
599                 if data == 0 or strIsEmpty(data):
600                         data = ""
601                 self._session.openWithCallback(self._cb_virtualKeyboardClosed, VirtualKeyBoard, title=("Please enter URL here"), text=data)
602                 return (0, "OK")
603
604         def _cb_handleVODSeekCtrl(self, opcode, data):
605                 self._handle_dump(self._cb_handleVODSeekCtrl, opcode, data)
606                 headLen = struct.calcsize('!I')
607                 unpackedData = struct.unpack('!I', data[:headLen])
608                 seekTime = unpackedData[0]
609                 service = self._session.nav.getCurrentService()
610                 seekable = service.seek()
611                 if seekable is None or not seekable.isCurrentlySeekable():
612                         raise Exception("This stream is not support manual seek.")
613                 pts = seekTime
614                 seekable.seekRelative(pts<0 and -1 or 1, abs(pts))
615                 return (0, "OK")
616
617         def _cb_handleHbbTVRetryOpen(self, opcode, data):
618                 def _cb_HbbTVRetryOpenURL():
619                         self._timer_retry_open.stop()
620                         if self._retry_open_url is not None:
621                                 command_util = getCommandUtil()
622                                 command_util.sendCommand('OP_HBBTV_RETRY_OPEN_URL', params=self._retry_open_url)
623                         self._retry_open_url = None
624                         try:
625                                 self._timer_retry_open.callback.remove(_cb_HbbTVRetryOpenURL)
626                         except: pass
627                 self._handle_dump(self._cb_handleHbbTVRetryOpen, opcode, data)
628                 headLen = struct.calcsize('!I')
629                 unpackedData = struct.unpack('!I', data[:headLen])
630                 delayTime = unpackedData[0]
631                 restartUrl = data[headLen:]
632
633                 self._retry_open_url = restartUrl.strip()
634                 self._timer_retry_open.callback.append(_cb_HbbTVRetryOpenURL)
635                 self._timer_retry_open.start(delayTime*1000)
636                 return (0, "OK")
637
638         def _cb_handleSystemNotufyMyPID(self, opcode, data):
639                 self._handle_dump(self._cb_handleSystemNotufyMyPID, opcode, data)
640                 return (0, "OK")
641
642         def _cb_handleSystemOutOfMemory(self, opcode, data):
643                 self._handle_dump(self._cb_handleSystemOutOfMemory, opcode, data)
644                 setNeedRestart(True)
645                 return (0, "OK")
646
647         def _cb_handleVODSpeedCtrl(self, opcode, data):
648                 self._handle_dump(self._cb_handleVODSpeedCtrl, opcode, data)
649                 headLen = struct.calcsize('!I')
650                 unpackedData = struct.unpack('!I', data[:headLen])
651                 playSpeed = unpackedData[0]
652                 service = self._session.nav.getCurrentService()
653                 pauseable = service.pause()
654                 if playSpeed > 2:
655                         playSpeed = 2
656                 if pauseable.setFastForward(playSpeed) == -1:
657                         pauseable.setFastForward(1)
658                         raise Exception("This stream is not support trick play.")
659                 return (0, "OK")
660
661         def _cb_handleDVBAppVolUp(self, opcode, data):
662                 self._handle_dump(self._cb_handleDVBAppVolUp, opcode, data)
663                 vcm = VolumeControl.instance
664                 vcm.volUp()
665                 return (0, "OK")
666
667         def _cb_handleDVBAppVolDown(self, opcode, data):
668                 self._handle_dump(self._cb_handleDVBAppVolDown, opcode, data)
669                 vcm = VolumeControl.instance
670                 vcm.volDown()
671                 return (0, "OK")
672
673         def _cb_handleDVBAppSetVol(self, opcode, data):
674                 self._handle_dump(self._cb_handleDVBAppSetVol, opcode, data)
675                 v = int(data)
676                 VolumeControl.instance.volctrl.setVolume(v, v)
677                 return (0, "OK")
678
679         def _cb_handleGetChannelInfoForUrl(self, opcode, data):
680                 self._handle_dump(self._cb_handleGetChannelInfoForUrl, opcode, data)
681                 (sid, onid, tsid, name, orgid) = getChannelInfos()
682                 namelen = len(name)
683                 return (0, struct.pack('!IIII', sid, onid, tsid, namelen) + name)
684
685         def _cb_handleGetChannelInfoForAIT(self, opcode, data):
686                 self._handle_dump(self._cb_handleGetChannelInfoForAIT, opcode, data)
687                 (sid, onid, tsid, name, orgid) = getChannelInfos()
688                 namelen = len(name)
689                 return (0, struct.pack('!IIIII', orgid, sid, onid, tsid, namelen) + name)
690
691         def _cb_handleGetChannelInfoList(self, opcode, data):
692                 self._handle_dump(self._cb_handleGetChannelInfoList, opcode, data)
693                 (sid, onid, tsid, name, orgid) = getChannelInfos()
694                 namelen = len(name)
695                 channel_list_size = 1
696                 return (channel_list_size, struct.pack('!IIII', sid, onid, tsid, namelen) + name)
697
698         def _cb_handleSetPageTitle(self, opcode, data):
699                 self._handle_dump(self._cb_handleSetPageTitle, opcode, data)
700                 if data.startswith('file://') or data.startswith('http://'):
701                         return "OK"
702                 if self._on_set_title_cb is not None:
703                         for x in self._on_set_title_cb:
704                                 try:
705                                         x(data)
706                                         self._curren_title = data
707                                 except Exception, ErrMsg:
708                                         if x in self._on_set_title_cb:
709                                                 self._on_set_title_cb.remove(x)
710                 return (0, "OK")
711
712         def _cb_handleCloseHbbTVBrowser(self, opcode, data):
713                 self._timer_retry_open.stop()
714                 try:
715                         self._timer_retry_open.callback.remove(_cb_HbbTVRetryOpenURL)
716                 except: pass
717                 self._handle_dump(self._cb_handleCloseHbbTVBrowser, opcode, data)
718
719                 if self._on_close_cb:
720                         for x in self._on_close_cb:
721                                 try:
722                                         x()
723                                 except Exception, ErrMsg:
724                                         if x in self._on_close_cb:
725                                                 self._on_close_cb.remove(x)
726
727                 command_util = getCommandUtil()
728                 command_util.sendCommand('OP_HBBTV_FULLSCREEN', None)
729
730                 before_service = getBeforeService()
731                 if before_service is not None:
732                         self._session.nav.playService(before_service)
733                         self._vod_uri = None
734
735                 #restoreResolution()
736                 return (0, "OK")
737
738         def _cb_handleVODPlayerURI(self, opcode, data):
739                 self._vod_uri = None
740                 hl = struct.calcsize('!II')
741                 datas = struct.unpack('!II', data[:hl])
742                 uriLength = datas[1]
743                 vodUri = data[hl:hl+uriLength]
744                 self._handle_dump(self._cb_handleVODPlayerURI, opcode, vodUri)
745                 self._vod_uri = vodUri
746                 return (0, "OK")
747
748         def doStop(self, restoreBeforeService=True, needStop=True):
749                 if needStop == True:
750                         self._session.nav.stopService()
751                 if self._vod_service is not None and restoreBeforeService:
752                         before_service = getBeforeService()
753                         self._session.nav.playService(before_service)
754                         self._vod_uri = None
755                 self._vod_service = None
756
757         def getUrl(self):
758                 return self._vod_uri
759
760         def doRetryOpen(self, url):
761                 if url is None:
762                         return False
763                 for ii in range(5):
764                         self._vod_service = None
765                         try:
766                                 #print "Try to open vod [%d] : %s" % (ii, url)
767                                 print "Try to open vod"
768                                 self._vod_service = eServiceReference(4097, 0, url)
769                                 self._session.nav.playService(self._vod_service)
770                                 if self._vod_service is not None:
771                                         return True
772                         except Exception, ErrMsg: 
773                                 print "OpenVOD ERR :", ErrMsg
774                         time.sleep(1)
775                 return False
776
777         def _cb_handleVODPlayerPlay(self, opcode, data):
778                 self._handle_dump(self._cb_handleVODPlayerPlay, opcode, data)
779                 self.doStop(restoreBeforeService=False)
780                 if self.doRetryOpen(url=self._vod_uri) == False:
781                         self.doStop()
782                 return (0, "OK")
783
784         def _cb_handleVODPlayerStop(self, opcode, data):
785                 self._handle_dump(self._cb_handleVODPlayerStop, opcode, data)
786                 self.doStop()   
787                 return (0, "OK")
788
789         def _cb_handleVODPlayerPlayPause(self, opcode, data):
790                 self._handle_dump(self._cb_handleVODPlayerPlayPause, opcode, data)
791                 service = self._session.nav.getCurrentService()
792                 try:
793                         pauseFlag = data[0]
794                         servicePause = service.pause()
795                         if pauseFlag == 'U':
796                                 servicePause.unpause()
797                         elif pauseFlag == 'P':
798                                 servicePause.pause()
799                 except Exception, ErrMsg:
800                         print "onPause ERR :", ErrMsg
801                 return (0, "OK")
802
803 from libshm import SimpleSharedMemory
804 _g_ssm_ = None
805 class HbbTVWindow(Screen, InfoBarNotifications):
806         skin =  """
807                 <screen name="HbbTVWindow" position="0,0" size="1280,720" backgroundColor="transparent" flags="wfNoBorder" title="HbbTV Plugin">
808                 </screen>
809                 """
810         def __init__(self, session, url=None, cbf=None, useAIT=False, profile=0):
811                 self._session = session
812                 setResolution(1280, 720)
813                 fbClass.getInstance().lock()
814                 eRCInput.getInstance().lock()
815
816                 Screen.__init__(self, session)
817                 InfoBarNotifications.__init__(self)
818                 self.__event_tracker = ServiceEventTracker(screen = self, eventmap = {
819                         iPlayableService.evStart: self._serviceStarted,
820                         iPlayableService.evEOF: self._serviceEOF,
821                 })
822
823                 self._url = url
824                 self._use_ait = useAIT
825                 self._profile = profile
826                 self._cb_closed_func = cbf
827                 self.onLayoutFinish.append(self._layoutFinished)
828
829                 command_server = getCommandServer()
830                 if self._cb_set_page_title not in command_server.onSetPageTitleCB:
831                         command_server.onSetPageTitleCB.append(self._cb_set_page_title)
832
833                 if self._cb_close_window not in command_server.onHbbTVCloseCB:
834                         command_server.onHbbTVCloseCB.append(self._cb_close_window)
835
836                 self._closeTimer = eTimer()
837                 self._closeTimer.callback.append(self._do_close)
838
839                 self._currentServicePositionTimer = eTimer()
840                 self._currentServicePositionTimer.callback.append(self._cb_currentServicePosition)
841                 self._vodLength = 0
842
843                 global _g_ssm_
844                 self._ssm = _g_ssm_
845                 self._vod_length = 0
846
847         def getVodPlayTime(self):
848                 try:
849                         service = self._session.nav.getCurrentService()
850                         seek = service and service.seek()
851                         l = seek.getLength()
852                         p = seek.getPlayPosition()
853                         if(not l[0] and not p[0]):
854                                 return (p[1], l[1])
855                         return (90000,90000)
856                 except: pass
857                 return (-1,-1)
858
859         def _cb_currentServicePosition(self):
860                 def getTimeString(t):
861                         t = time.localtime(t/90000)
862                         return "%2d:%02d:%02d" % (t.tm_hour, t.tm_min, t.tm_sec)
863                 position,length = 0,0
864                 try:
865                         (position,length) = self.getVodPlayTime()
866                         self._vod_length = length
867                         if position == -1 and length == -1:
868                                 raise Exception("Can't get play status")
869                         #print getTimeString(position), "/", getTimeString(length)
870                         self._ssm.setStatus(position, length, 1)
871                 except Exception, ErrMsg:
872                         print ErrMsg
873                         self._serviceEOF()
874
875         def _serviceStarted(self):
876                 try:
877                         self._ssm.setStatus(0, 0, 0)
878                         self._currentServicePositionTimer.start(1000)
879                 except Exception, ErrMsg:
880                         print ErrMsg
881
882         def _serviceEOF(self):
883                 (position,length) = self.getVodPlayTime()
884                 self._ssm.setStatus(length, length, 1)
885                 print "service EOF"
886                 self._currentServicePositionTimer.stop()
887
888         def _layoutFinished(self):
889                 self.setTitle(_('HbbTV Plugin'))
890                 command_util = getCommandUtil()
891                 profile = self._profile
892                 (sid, onid, tsid, name, orgid) = getChannelInfos()
893                 params  = struct.pack('!IIIIII', orgid, profile, sid, onid, tsid, len(name)) + name
894                 if self._use_ait:
895                         command_util.sendCommand('OP_HBBTV_UNLOAD_AIT')
896                         time.sleep(1)
897                         command_util.sendCommand('OP_HBBTV_LOAD_AIT', params, 1)
898                         return
899                 command_util.sendCommand('OP_HBBTV_LOAD_AIT', params)
900                 time.sleep(1)
901                 command_util.sendCommand('OP_HBBTV_OPEN_URL', self._url)
902
903         def _cb_close_window(self):
904                 self._closeTimer.start(1000)
905
906         def _do_close(self):
907                 self._closeTimer.stop()
908                 command_server = getCommandServer()
909                 try:
910                         if self._cb_set_page_title in command_server.onSetPageTitleCB:
911                                 command_server.onSetPageTitleCB.remove(self._cb_set_page_title)
912                 except Exception, ErrMsg: pass
913                 try:
914                         if self._cb_close_window in command_server.onHbbTVCloseCB:
915                                         command_server.onHbbTVCloseCB.remove(self._cb_close_window)
916                 except Exception, ErrMsg: pass
917                 try:
918                         if self._cb_closed_func is not None:
919                                 self._cb_closed_func()
920                 except: pass
921                 restoreResolution()
922                 fbClass.getInstance().unlock()
923                 eRCInput.getInstance().unlock()
924                 self.close()
925
926         def _cb_set_page_title(self, title=None):
927                 print "page title :",title
928                 if title is None:
929                         return
930                 self.setTitle(title)
931
932 class HbbTVHelper(Screen, InfoBarNotifications):
933         skin =  """<screen name="HbbTVHelper" position="0,0" size="0,0" backgroundColor="transparent" flags="wfNoBorder" title=" "></screen>"""
934         def __init__(self, session):
935                 global __gval__
936                 __gval__.hbbtv_handelr = HandlerHbbTV(session)
937                 __gval__.command_server = ServerFactory().doListenUnixTCP('/tmp/.sock.hbbtv.url', __gval__.hbbtv_handelr)
938
939                 Screen.__init__(self, session)
940                 InfoBarNotifications.__init__(self)
941
942                 self._session = session
943
944                 self._restart_opera()
945
946                 self._timer_infobar = eTimer()
947                 self._timer_infobar.callback.append(self._cb_registrate_infobar)
948                 self._timer_infobar.start(1000)
949
950                 self._excuted_browser = False
951                 self._profile = 0
952
953                 __gval__.command_util = BrowserCommandUtil()
954
955                 global _g_ssm_
956                 if _g_ssm_ is None:
957                         _g_ssm_ = SimpleSharedMemory()
958                         _g_ssm_.doConnect()
959
960                 self._callbackStartStop = None
961
962                 self.__et = ServiceEventTracker(screen=self, eventmap={
963                                 iPlayableService.evHBBTVInfo: self._cb_detectedAIT,
964                                 iPlayableService.evUpdatedInfo: self._cb_updateInfo
965                         })
966                 self._applicationList = None
967
968                 self.mVuplusBox = False
969                 issue = open("/etc/issue").read()
970                 if(issue.startswith("Vuplus")):
971                         self.mVuplusBox = True
972
973         def _cb_detectedAIT(self):
974                 name = self._cb_ready_for_ait()
975                 if name is not None and self.mVuplusBox:
976                         from Screens.InfoBarGenerics import gHbbtvApplication
977                         gHbbtvApplication.setApplicationName(str(name))
978
979         def _cb_updateInfo(self):
980                 if not self._excuted_browser:
981                         command_util = getCommandUtil()
982                         command_util.sendCommand('OP_HBBTV_UNLOAD_AIT')
983                 if self.mVuplusBox:
984                         from Screens.InfoBarGenerics import gHbbtvApplication
985                         gHbbtvApplication.setApplicationName("")
986                 #self._applicationList = None
987
988         def _cb_registrate_infobar(self):
989                 if InfoBar.instance:
990                         self._timer_infobar.stop()
991                         if self._cb_hbbtv_activated not in InfoBar.instance.onHBBTVActivation:
992                                 InfoBar.instance.onHBBTVActivation.append(self._cb_hbbtv_activated)
993
994         def _cb_ready_for_ait(self):
995                 setChannelInfo(None, None, None, None, None)
996
997                 service = self._session.nav.getCurrentService()
998                 info = service and service.info()
999                 if info is not None:
1000                         sid  = info.getInfo(iServiceInformation.sSID)
1001                         onid = info.getInfo(iServiceInformation.sONID)
1002                         tsid = info.getInfo(iServiceInformation.sTSID)
1003                         name = info.getName()
1004                         if name is None:
1005                                 name = ""
1006
1007                         pmtid = info.getInfo(iServiceInformation.sPMTPID)
1008                         demux = info.getInfoString(iServiceInformation.sLiveStreamDemuxId)
1009
1010                         from aitreader import eAITSectionReader
1011                         reader = eAITSectionReader(demux, pmtid, sid)
1012                         if reader.doOpen(info, self.mVuplusBox):
1013                                 reader.doParseApplications()
1014                                 reader.doDump()
1015                         else:   print "no data!!"
1016
1017                         try:
1018                                 self._applicationList = reader.getApplicationList()
1019                                 if len(self._applicationList) > 0:
1020                                         orgid = int(self._applicationList[0]["orgid"])
1021                                         setChannelInfo(sid, onid, tsid, name, orgid)
1022                                         return self._applicationList[0]["name"]
1023                         except: pass
1024                 return None
1025
1026         def _cb_hbbtv_activated(self, title=None, url=None):
1027                 if not self._is_browser_running():
1028                         message = _("HbbTV Browser was not running.\nPlease running browser before start HbbTV Application.")
1029                         self._session.open(MessageBox, message, MessageBox.TYPE_INFO)
1030                         return
1031                 service = self._session.nav.getCurrentlyPlayingServiceReference()
1032                 setBeforeService(service)
1033                 self._start_hbbtv_application(title, url)
1034
1035         def _start_hbbtv_application(self, title, url):
1036                 use_ait = False
1037                 tmp_url = self.getStartHbbTVUrl()
1038                 if url is None:
1039                         url = tmp_url
1040                 if strIsEmpty(url):
1041                         print "can't get url of hbbtv!!"
1042                         return
1043                 print "success to get url of hbbtv!! >>", url
1044                 if self._excuted_browser:
1045                         print "already excuted opera browser!!"
1046                         return
1047
1048                 if isNeedRestart():
1049                         self._restart_opera()
1050                         time.sleep(2)
1051                         setNeedRestart(False)
1052
1053                 for x in self._applicationList:
1054                         control_code = int(x["control"])
1055                         tmp_url = x["url"]
1056                         if tmp_url == url and control_code == 1:
1057                                 use_ait = True
1058                 self._excuted_browser = True
1059                 self._session.open(HbbTVWindow, url, self._cb_closed_browser, use_ait, self._profile)
1060
1061         def _cb_closed_browser(self):
1062                 self._excuted_browser = False
1063
1064         def _start_opera(self):
1065                 if not self._is_browser_running():
1066                         global HBBTVAPP_PATH
1067                         global __gval__
1068                         start_command = '%s/launcher start %d %d'%(HBBTVAPP_PATH, __gval__.resX, __gval__.resY)
1069                         os.system(start_command)
1070                 return True
1071
1072         def _stop_opera(self):
1073                 global HBBTVAPP_PATH
1074                 try:    os.system('%s/launcher stop'%(HBBTVAPP_PATH))
1075                 except: pass
1076
1077         def _restart_opera(self):
1078                 global HBBTVAPP_PATH
1079                 global __gval__
1080                 try:    os.system('%s/launcher restart %d %d'%(HBBTVAPP_PATH, __gval__.resX, __gval__.resY))
1081                 except: pass
1082                 return True
1083
1084         def getStartHbbTVUrl(self):
1085                 url, self._profile = None, 0
1086                 if self._applicationList is not None:
1087                         self._profile = self._applicationList[0]["profile"]
1088                         url = self._applicationList[0]["url"]
1089                 if url is None:
1090                         service = self._session.nav.getCurrentService()
1091                         info = service and service.info()
1092                         url = info.getInfoString(iServiceInformation.sHBBTVUrl)
1093                 return url
1094
1095         def showApplicationSelectionBox(self):
1096                 applications = []
1097
1098                 if self.getStartHbbTVUrl():
1099                         for x in self._applicationList:
1100                                 applications.append((x["name"], x))
1101                 else: applications.append((_("No detected HbbTV applications."), None))
1102                 self._session.openWithCallback(self._application_selected, ChoiceBox, title=_("Please choose an HbbTV application."), list=applications)
1103
1104         def _application_selected(self, selected):
1105                 print selected
1106                 try:
1107                         if selected[1] is None: return
1108                         self._cb_hbbtv_activated(selected[1]["name"], selected[1]["url"])
1109                 except Exception, ErrMsg: print ErrMsg
1110
1111         def showBrowserConfigBox(self, callback=None):
1112                 start_stop_mode = []
1113                 self._callbackStartStop = callback
1114                 if self._is_browser_running():
1115                         start_stop_mode.append((_('Stop'),'Stop'))
1116                 else:   start_stop_mode.append((_('Start'),'Start'))
1117                 self._session.openWithCallback(self._browser_config_selected, ChoiceBox, title=_("Please choose one."), list=start_stop_mode)
1118
1119         def _browser_config_selected(self, selected):
1120                 if selected is None:
1121                         return
1122                 if self._callbackStartStop is not None:
1123                         self._callbackStartStop()
1124                 try:
1125                         mode = selected[1]
1126                         if mode == 'Start':
1127                                 if not self._is_browser_running():
1128                                         self._start_opera()
1129                         elif mode == 'Stop':
1130                                 self._stop_opera()
1131                 except Exception, ErrMsg: print "Config ERR :", ErrMsg
1132
1133         def _is_browser_running(self):
1134                 try:
1135                         global HBBTVAPP_PATH
1136                         ret = os.popen('%s/launcher check'%(HBBTVAPP_PATH)).read()
1137                         return ret.strip() != "0"
1138                 except Exception, ErrMsg:
1139                         print "Check Browser Running ERR :", ErrMsg
1140                 return False
1141
1142         def doChangeChannel(self, _sid, _tsid):
1143                 root = eServiceReference(service_types_tv)
1144                 if root is None:
1145                         return False
1146                 serviceList = eServiceCenter.getInstance().list(root)
1147                 if serviceList is None:
1148                         return False    
1149                 while True:
1150                         service = serviceList.getNext()
1151                         if service is None or not service.valid():
1152                                 break
1153
1154                         #1:0:19:2840:3FB:1:C00000:0:0:0:
1155                         serviceRef = service.toString()
1156                         if strIsEmpty(serviceRef):
1157                                 continue
1158                         serviceRefItems = serviceRef.split(":")
1159                         if len(serviceRefItems) < 5:
1160                                 continue
1161
1162                         sid  = serviceRefItems[3]
1163                         tsid = serviceRefItems[4]
1164                         if sid == _sid and tsid == _tsid:
1165                                 self._session.nav.playService(eServiceReference(serviceRef))
1166                                 service = self._session.nav.getCurrentlyPlayingServiceReference()
1167                                 setBeforeService(service)
1168                                 return True
1169                 return False
1170
1171 class OperaBrowserSetting:
1172         def __init__(self):
1173                 self._settingFileName = '/usr/local/hbb-browser/home/setting.ini'
1174                 self._start = None
1175                 self._type  = None
1176                 self._keymap = None
1177                 self._read()
1178         def _read(self):
1179                 f = open(self._settingFileName)
1180                 for line in f.readlines():
1181                         if line.startswith('start='):
1182                                 tmp = line[6:len(line)-1].split()
1183                                 self._start = tmp[0]
1184                                 if len(tmp) > 1:
1185                                         self._type = int(tmp[1])
1186                                 else:   self._type = 0
1187                         elif line.startswith('keymap='):
1188                                 self._keymap = line[7:len(line)-1]
1189                 f.close()
1190         def _write(self):
1191                 tmpstr = []
1192                 tmpstr.append('start=%s %d\n' % (self._start, self._type))
1193                 tmpstr.append('keymap=%s\n' % (self._keymap))
1194                 f = open(self._settingFileName, 'w')
1195                 f.writelines(tmpstr)
1196                 f.close()
1197         def setData(self, start, types=0, keymap="us-rc"):
1198                 self._start = start
1199                 self._type = types
1200                 self._keymap = keymap
1201                 self._write()
1202         def getData(self):
1203                 return {
1204                         'start':self._start,
1205                         'type':self._type,
1206                         'keymap':self._keymap,
1207                 }
1208
1209 class OperaBrowserPreferenceWindow(ConfigListScreen, Screen):
1210         skin=   """
1211                 <screen position="center,120" size="600,350" title="Preference">
1212                         <widget name="url" position="5,0" size="590,100" valign="center" font="Regular;20" />
1213                         <widget name="config" position="0,100" size="600,200" scrollbarMode="showOnDemand" />
1214
1215                         <ePixmap pixmap="skin_default/buttons/red.png" position="310,310" size="140,40" alphatest="on" />
1216                         <ePixmap pixmap="skin_default/buttons/green.png" position="150,310" size="140,40" alphatest="on" />
1217
1218                         <widget source="key_red" render="Label" position="310,310" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
1219                         <widget source="key_green" render="Label" position="150,310" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
1220                 </screen>
1221                 """
1222         def __init__(self, session, currentUrl): 
1223                 self.session = session
1224                 Screen.__init__(self, session)
1225
1226                 self.menulist = []
1227                 ConfigListScreen.__init__(self, self.menulist)
1228
1229                 self["actions"] = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions", ], {
1230                         "red"    : self.keyRed,
1231                         "green"  : self.keyGreen,
1232                         "ok"     : self.keyOK,
1233                         "cancel" : self.keyRed
1234                 }, -2)
1235                 self["key_red"]   = StaticText(_("Cancel"))
1236                 self["key_green"] = StaticText(_("Save"))
1237                 self["url"]       = Label()
1238
1239                 self._currentPageUrl = currentUrl
1240                 if self._currentPageUrl is None:
1241                         self._currentPageUrl = ''
1242                 self._startPageUrl   = None
1243                 self._keymapType = None
1244                 self.makeMenuEntry()
1245                 self.onLayoutFinish.append(self.layoutFinished)
1246
1247         def layoutFinished(self):
1248                 self.setTitle(_('Preference'))
1249
1250         def updateStartPageUrl(self):
1251                 if self.menuItemStartpage.value == "startpage":
1252                         self["url"].setText(self._startPageUrl)
1253                 elif self.menuItemStartpage.value == "current":
1254                         self["url"].setText(self._currentPageUrl)
1255                 elif self.menuItemStartpage.value == "direct":
1256                         self["url"].setText('')
1257
1258         def keyGreen(self):
1259                 url = self["url"].getText()
1260                 if strIsEmpty(url):
1261                         self.session.open(MessageBox, _('Invalid URL!!(Empty)\nPlease, Input to the URL.'), type = MessageBox.TYPE_INFO)
1262                         return
1263                 mode = 0
1264                 if url.find('/usr/local/manual') > 0:
1265                         mode = 1
1266                 self._keymapType = self.menuItemKeyboardLayout.value
1267                 OperaBrowserSetting().setData(url, mode, self._keymapType)
1268                 command_util = getCommandUtil()
1269                 command_util.sendCommand('OP_BROWSER_NEED_RELOAD_KEYMAP')
1270                 self.close()
1271
1272         def keyRed(self):
1273                 self.close()
1274
1275         def keyOK(self):
1276                 def _cb_directInputUrl(data):
1277                         if strIsEmpty(data):
1278                                 return
1279                         self["url"].setText(data)
1280                 if self.menuItemStartpage.value == "direct":
1281                         self.session.openWithCallback(_cb_directInputUrl, VirtualKeyBoard, title=(_("Please enter URL here")), text='http://')
1282
1283         def keyLeft(self):
1284                 ConfigListScreen.keyLeft(self)
1285                 self.updateStartPageUrl()
1286
1287         def keyRight(self):
1288                 ConfigListScreen.keyRight(self)
1289                 self.updateStartPageUrl()
1290
1291         def getKeymapTypeList(self):
1292                 types = []
1293                 for f in os.listdir("/usr/local/hbb-browser/keymap"):
1294                         filesplit = f.split('.')
1295                         if len(filesplit) < 2:
1296                                 continue
1297                         types.append((filesplit[1], filesplit[1]))
1298                 types.sort()
1299                 return types
1300
1301         def makeMenuEntry(self):
1302                 l = []
1303                 l.append(("startpage", _("Start Page")))
1304                 if not strIsEmpty(self._currentPageUrl):
1305                         l.append(("current", _("Current Page")))
1306                 l.append(("direct", _("Direct Input")))
1307                 self.menuItemStartpage  = ConfigSelection(default="startpage", choices = l)
1308                 self.menuEntryStartpage = getConfigListEntry(_("Startpage"), self.menuItemStartpage)
1309
1310                 kl = self.getKeymapTypeList()
1311
1312                 try:
1313                         d = OperaBrowserSetting().getData()
1314                         self._startPageUrl = d['start']
1315                         self._keymapType = d['keymap']
1316                         #d['type']
1317                 except: self._startPageUrl = 'http://vuplus.com'
1318                 self.updateStartPageUrl()
1319
1320                 if self._keymapType is None or len(self._keymapType) == 0:
1321                         self._keymapType = "us-rc"
1322                 self.menuItemKeyboardLayout = ConfigSelection(default=self._keymapType, choices = kl)
1323                 self.menuEntryKeyboardLayout = getConfigListEntry(_("Keyboard Layout"), self.menuItemKeyboardLayout)
1324                 self.resetMenuList()
1325
1326         def resetMenuList(self):
1327                 self.menulist = []
1328                 self.menulist.append(self.menuEntryStartpage)
1329                 self.menulist.append(self.menuEntryKeyboardLayout)
1330
1331                 self["config"].list = self.menulist
1332                 self["config"].l.setList(self.menulist)
1333
1334 class BookmarkEditWindow(ConfigListScreen, Screen):
1335         CATEGORY,BOOKMARK = 0,1
1336         skin=   """
1337                 <screen position="center,center" size="600,140" title="Bookmark Edit">
1338                         <widget name="config" position="0,0" size="600,100" scrollbarMode="showOnDemand" />
1339
1340                         <ePixmap pixmap="skin_default/buttons/red.png" position="310,100" size="140,40" alphatest="on" />
1341                         <ePixmap pixmap="skin_default/buttons/green.png" position="150,100" size="140,40" alphatest="on" />
1342
1343                         <widget source="key_red" render="Label" position="310,100" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
1344                         <widget source="key_green" render="Label" position="150,100" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
1345
1346                         <widget name="VKeyIcon" pixmap="skin_default/buttons/key_text.png" position="0,100" zPosition="10" size="35,25" transparent="1" alphatest="on" />
1347
1348                 </screen>
1349                 """
1350         def __init__(self, session, _mode, _type, _data, _bm):
1351                 self.mMode = _mode
1352                 self.mType = _type
1353                 self.mData = _data
1354                 self.mSession = session
1355                 self.mBookmarkManager = _bm
1356
1357                 if _data is not None:
1358                         print _data.mId
1359
1360                 Screen.__init__(self, session)
1361
1362                 self.menulist = []
1363                 ConfigListScreen.__init__(self, self.menulist)
1364
1365                 self["actions"] = ActionMap(["OkCancelActions", "ColorActions",], {
1366                         "ok"     : self.keyGreen,
1367                         "green"  : self.keyGreen,
1368                         "red"    : self.keyRed,
1369                         "cancel" : self.keyRed,
1370                 }, -2)
1371
1372                 self["VKeyIcon"]  = Pixmap()
1373                 self["key_red"]   = StaticText(_("Cancel"))
1374                 self["key_green"] = StaticText(_("Save"))
1375
1376                 self.menuItemTitle = None
1377                 self.menuItemUrl   = None
1378                 self.menuItemName  = None
1379
1380                 self.menuEntryName = None
1381                 self.menuEntryTitle = None
1382                 self.menuEntryUrl = None
1383
1384                 self.makeConfigList()
1385                 self.onLayoutFinish.append(self.layoutFinished)
1386
1387         def layoutFinished(self):
1388                 self.setTitle(_('Bookmark') + ' ' + self.mMode)
1389
1390         def selectedItem(self):
1391                 currentPosition = self["config"].getCurrent()
1392                 if self.mType == BookmarkEditWindow.CATEGORY:
1393                         return (_("Name"), self.menuItemName)
1394                 else:
1395                         if currentPosition == self.menuEntryTitle:
1396                                 return (_("Title"), self.menuItemTitle)
1397                         elif currentPosition == self.menuEntryUrl:
1398                                 return (_("Url"), self.menuItemUrl)
1399                 return None
1400
1401         def showMessageBox(self, text):
1402                 msg = _("Invalid ") + text + _("!!(Empty)\nPlease, Input to the ") + text + "."
1403                 self.mSession.openWithCallback(self.showVKeyWindow, MessageBox, msg, MessageBox.TYPE_INFO)
1404                 return False
1405
1406         def showVKeyWindow(self, data=None):
1407                 itemTitle = ""
1408                 itemValue = ""
1409                 selected = self.selectedItem()
1410                 if selected is not None:
1411                         itemValue = selected[1].value
1412                         if strIsEmpty(itemValue):
1413                                 itemValue = ""
1414                         itemTitle = selected[0]
1415
1416                 self.session.openWithCallback(self.cbVKeyWindow, VirtualKeyBoard, title=itemTitle, text=itemValue)
1417
1418         def cbVKeyWindow(self, data=None):
1419                 if data is not None:
1420                         selected = self.selectedItem()
1421                         if selected is not None:
1422                                 selected[1].setValue(data)
1423
1424         def saveData(self):
1425                 if self.mType == BookmarkEditWindow.CATEGORY:
1426                         if self.mMode == _('Add'):
1427                                 categoryName = self.menuItemName.value
1428                                 if strIsEmpty(categoryName):
1429                                         return self.showMessageBox(_("Category Name"))
1430                                 self.mBookmarkManager.addCategory(categoryName)
1431                         else:
1432                                 if strIsEmpty(self.menuItemName.value):
1433                                         return self.showMessageBox(_("Category Name"))
1434                                 self.mData.mName = self.menuItemName.value
1435                                 self.mBookmarkManager.updateCategory(self.mData)
1436                 else:
1437                         if self.mMode == _('Add'):
1438                                 bookmarkTitle = self.menuItemTitle.value
1439                                 bookmarkUrl   = self.menuItemUrl.value
1440                                 if strIsEmpty(bookmarkTitle):
1441                                         self["config"].setCurrentIndex(0)
1442                                         return self.showMessageBox(_("Bookmark Title"))
1443                                 if strIsEmpty(bookmarkUrl):
1444                                         self["config"].setCurrentIndex(1)
1445                                         return self.showMessageBox(_("Bookmark URL"))
1446                                 self.mBookmarkManager.addBookmark(bookmarkTitle, bookmarkUrl, self.mData.mParent, 0)
1447                         else:
1448                                 if strIsEmpty(self.menuItemTitle.value):
1449                                         self["config"].setCurrentIndex(0)
1450                                         return self.showMessageBox(_("Bookmark Title"))
1451                                 if strIsEmpty(self.menuItemUrl.value):
1452                                         self["config"].setCurrentIndex(1)
1453                                         return self.showMessageBox(_("Bookmark URL"))
1454                                 self.mData.mTitle = self.menuItemTitle.value
1455                                 self.mData.mUrl   = self.menuItemUrl.value
1456                                 self.mBookmarkManager.updateBookmark(self.mData)
1457                 return True
1458
1459         def keyGreen(self):
1460                 if not self.saveData():
1461                         return
1462                 self.close(True)
1463         def keyRed(self):
1464                 self.close(False)
1465         def keyLeft(self):
1466                 ConfigListScreen.keyLeft(self)
1467         def keyRight(self):
1468                 ConfigListScreen.keyRight(self)
1469         def makeConfigList(self):
1470                 self.menulist = []
1471
1472                 if self.mType == BookmarkEditWindow.CATEGORY:
1473                         self.menuItemName = ConfigText(default=self.mData.mName, visible_width=65, fixed_size=False)
1474
1475                         self.menuEntryName  = getConfigListEntry(_("Name"), self.menuItemName)
1476
1477                         self.menulist.append(self.menuEntryName)
1478                 else:
1479                         self.menuItemTitle = ConfigText(default=self.mData.mTitle, visible_width=65, fixed_size=False)
1480                         self.menuItemUrl   = ConfigText(default=self.mData.mUrl, visible_width=65, fixed_size=False)
1481
1482                         self.menuEntryTitle = getConfigListEntry(_("Title"), self.menuItemTitle)
1483                         self.menuEntryUrl   = getConfigListEntry(_("Url"), self.menuItemUrl)
1484
1485                         self.menulist.append(self.menuEntryTitle)
1486                         self.menulist.append(self.menuEntryUrl)
1487                         
1488                 self["config"].list = self.menulist
1489                 self["config"].l.setList(self.menulist)
1490
1491 class OperaBrowserBookmarkWindow(Screen):
1492         skin =  """
1493                 <screen name="HbbTVBrowserBookmarkWindow" position="center,120" size="600,400" title="Bookmark" >
1494                         <widget name="bookmarklist" position="0,0" size="600,200" zPosition="10" scrollbarMode="showOnDemand" />
1495
1496                         <ePixmap pixmap="skin_default/buttons/key_0.png" position="556,330" size="35,30" alphatest="on" />
1497                         <widget source="key_0" render="Label" position="258,330" zPosition="1" size="300,30" font="Regular;20" halign="right" valign="center"/>
1498
1499                         <ePixmap pixmap="skin_default/buttons/red.png" position="5,360" size="140,40" alphatest="on" />
1500                         <ePixmap pixmap="skin_default/buttons/green.png" position="155,360" size="140,40" alphatest="on" />
1501                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="305,360" size="140,40" alphatest="on" />
1502                         <ePixmap pixmap="skin_default/buttons/blue.png" position="450,360" size="140,40" alphatest="on" />
1503
1504                         <widget source="key_red" render="Label" position="5,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
1505                         <widget source="key_green" render="Label" position="155,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
1506                         <widget source="key_yellow" render="Label" position="305,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" foregroundColor="#ffffff" transparent="1" />
1507                         <widget source="key_blue" render="Label" position="450,360" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" foregroundColor="#ffffff" transparent="1" />
1508                 </screen>
1509                 """
1510
1511         def __init__(self, _session, _url=None, _title=None):
1512                 self.mUrl   = _url
1513                 self.mTitle = _title
1514                 self.mBookmarkManager = BookmarkManager.getInstance()
1515                 self.mSession = _session
1516                 Screen.__init__(self, _session)
1517                 self["actions"] = ActionMap(["DirectionActions", "OkCancelActions","ColorActions", "NumberActions"], {
1518                                 "ok"    : self.keyOK,
1519                                 "cancel": self.keyCancel,
1520                                 "red"   : self.keyRed,
1521                                 "green" : self.keyGreen,
1522                                 "yellow": self.keyYellow,
1523                                 "blue"  : self.keyBlue,
1524                                 "0"     : self.keyNumber,
1525                         },-2)
1526
1527                 self["key_red"]    = StaticText(_("Exit"))
1528                 self["key_green"]  = StaticText(_("Add"))
1529                 self["key_yellow"] = StaticText(_("Edit"))
1530                 self["key_blue"]   = StaticText(_("Delete"))
1531                 self["key_0"]      = StaticText(_("Set as Startpage"))
1532
1533                 self.mBookmarkList = self.setBookmarkList()
1534                 self["bookmarklist"] = MenuList(self.mBookmarkList)
1535
1536                 self.onLayoutFinish.append(self.layoutFinished)
1537
1538         def layoutFinished(self):
1539                 self.setTitle(_('Bookmark'))
1540
1541         def setBookmarkList(self):
1542                 l = []
1543                 #self.mBookmarkManager.dump()
1544                 cd = self.mBookmarkManager.getBookmarkRoot()
1545                 for ck in cd.iterkeys():
1546                         l.append(('# ' + cd[ck].mName, cd[ck]))
1547                         bd = cd[ck].mBookmarks
1548                         for bk in bd.iterkeys():
1549                                 l.append(('    - ' + bd[bk].mTitle, bd[bk]))
1550                 return l
1551         def updateBookmarkList(self):
1552                 self.mBookmarkList = self.setBookmarkList()
1553                 self["bookmarklist"].setList(self.mBookmarkList)
1554         def cbEditWindow(self, ret=False):
1555                 if not ret: 
1556                         return
1557                 self.updateBookmarkList()
1558         def getParentCategory(self):
1559                 idx = self["bookmarklist"].getSelectedIndex()
1560                 try:
1561                         while idx >= 0:
1562                                 data = self.mBookmarkList[idx][0].strip()
1563                                 if data[0] == '#':
1564                                         return self.mBookmarkList[idx][1]
1565                                 idx -= 1
1566                 except: pass
1567                 return None
1568         def isCategoryItem(self):
1569                 try:
1570                         head = self["bookmarklist"].getCurrent()[0].strip()
1571                         if head[0] == '#':
1572                                 return True
1573                 except: pass
1574                 return False
1575         def keyNumber(self):
1576                 data = self["bookmarklist"].getCurrent()[1]
1577                 if strIsEmpty(data.mUrl):
1578                         msg = _("Invalid URL. Please check again!!")
1579                         self.mSession.open(MessageBox, msg, MessageBox.TYPE_INFO)
1580                         return
1581                 def cbSetStartpage(ret=None):
1582                         if ret is None: return
1583                         if ret:
1584                                 data = self["bookmarklist"].getCurrent()[1]
1585                                 OperaBrowserSetting().setData(data.mUrl, data.mType)
1586                 msg = _("Do you want to set selected url to the Startpage?")
1587                 self.mSession.openWithCallback(cbSetStartpage, MessageBox, msg, MessageBox.TYPE_YESNO, default=True)
1588
1589         def keyGreen(self):
1590                 def cbGreen(data):
1591                         if data is None:
1592                                 return
1593                         if data[1] == 1:
1594                                 parent = self.getParentCategory()
1595                                 if parent is None:
1596                                         return
1597                                 if strIsEmpty(self.mTitle):
1598                                         return
1599                                 retAdd = self.mBookmarkManager.addBookmark(self.mTitle, self.mUrl, parent.mId, 0)
1600                                 if not retAdd:
1601                                         msg = _("Current page is already exist.")
1602                                         self.mSession.open(MessageBox, msg, MessageBox.TYPE_INFO)
1603                                 self.cbEditWindow(True)
1604                         elif data[1] == 2:
1605                                 parent = self.getParentCategory()
1606                                 if parent is None:
1607                                         return
1608                                 b = BookmarkData(0, '', '', parent.mId, 0)
1609                                 self.mSession.openWithCallback(self.cbEditWindow, BookmarkEditWindow, _('Add'), BookmarkEditWindow.BOOKMARK, b, self.mBookmarkManager)
1610                         elif data[1] == 3:
1611                                 c = CategoryData(0, '')
1612                                 self.mSession.openWithCallback(self.cbEditWindow, BookmarkEditWindow, _('Add'), BookmarkEditWindow.CATEGORY, c, self.mBookmarkManager)
1613                 if strIsEmpty(self.mUrl):
1614                         l = [(_('Direct Input(Bookmark)'),2,), (_('Direct Input(Category)'),3,)]
1615                 else:   l = [(_('Currentpage(Bookmark)'),1,), (_('Direct Input(Bookmark)'),2,), (_('Direct Input(Category)'),3,)]
1616                 self.mSession.openWithCallback(cbGreen, ChoiceBox, title=_("Please choose."), list=l)
1617         def keyYellow(self):
1618                 data = self["bookmarklist"].getCurrent()[1]
1619                 if self.isCategoryItem():
1620                         self.mSession.openWithCallback(self.cbEditWindow, BookmarkEditWindow, _('Edit'), BookmarkEditWindow.CATEGORY, data, self.mBookmarkManager)
1621                 else:   self.mSession.openWithCallback(self.cbEditWindow, BookmarkEditWindow, _('Edit'), BookmarkEditWindow.BOOKMARK, data, self.mBookmarkManager)
1622         def keyBlue(self):
1623                 def cbBlue(ret=None):
1624                         if not ret: return
1625                         data = self["bookmarklist"].getCurrent()[1]
1626                         if self.isCategoryItem():
1627                                 self.mBookmarkManager.deleteCategory(data.mId)
1628                         else:   self.mBookmarkManager.deleteBookmark(data.mId)
1629                         self.updateBookmarkList()
1630                 if self.isCategoryItem():
1631                         msg = _("Do you want to delete the category and the bookmarks?")
1632                 else:   msg = _("Do you want to delete the bookmark?")
1633                 self.mSession.openWithCallback(cbBlue, MessageBox, msg, MessageBox.TYPE_YESNO, default=True)
1634         def keyOK(self):
1635                 if self.isCategoryItem(): return
1636
1637                 data = self["bookmarklist"].getCurrent()[1]
1638                 url = data.mUrl.strip()
1639                 if len(url) == 0:
1640                         self.session.open(MessageBox, _("Can't open selected bookmark.\n   - URL data is empty!!"), type = MessageBox.TYPE_INFO)
1641                         return
1642                 mode = data.mType
1643                 if mode:
1644                         lang = language.getLanguage()
1645                         if lang == 'ru_RU' and os.path.exists('/usr/local/manual/ru_RU'):
1646                                 url = '/usr/local/manual/ru_RU/main.html'
1647                         elif lang == 'de_DE' and os.path.exists('/usr/local/manual/de_DE'):
1648                                 url = '/usr/local/manual/de_DE/main.html'
1649                 self.close((url, mode))
1650         def keyRed(self):
1651                 self.keyCancel()
1652         def keyCancel(self):
1653                 self.close()
1654
1655 class BrowserHelpWindow(Screen, HelpableScreen):
1656         MODE_GLOBAL,MODE_KEYBOARD,MODE_MOUSE = 1,2,3
1657         skin =  """
1658                 <screen name="BrowserHelpWindow" position="center,center" size="600,40" title="Browser Help" >
1659                         <ePixmap pixmap="skin_default/buttons/red.png" position="5,0" size="140,40" alphatest="on" />
1660                         <ePixmap pixmap="skin_default/buttons/green.png" position="155,0" size="140,40" alphatest="on" />
1661                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="305,0" size="140,40" alphatest="on" />
1662                         <ePixmap pixmap="skin_default/buttons/blue.png" position="450,0" size="140,40" alphatest="on" />
1663
1664                         <widget source="key_red" render="Label" position="5,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
1665                         <widget source="key_green" render="Label" position="155,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
1666                         <widget source="key_yellow" render="Label" position="305,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" foregroundColor="#ffffff" transparent="1" />
1667                         <widget source="key_blue" render="Label" position="450,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" foregroundColor="#ffffff" transparent="1" />
1668                 </screen>
1669                 """
1670         def __init__(self, session):
1671                 Screen.__init__(self, session)
1672                 HelpableScreen.__init__(self)
1673
1674                 self["key_red"]    = StaticText(_("Exit"))
1675                 self["key_green"]  = StaticText(_("Global"))
1676                 self["key_yellow"] = StaticText(_("Mouse"))
1677                 self["key_blue"]   = StaticText(_("Keyboard"))
1678
1679                 self["actions"] = ActionMap(["DirectionActions", "OkCancelActions","ColorActions"], {
1680                                 "ok"    : self.keyRed,
1681                                 "cancel": self.keyRed,
1682                                 "red"   : self.keyRed,
1683                                 "green" : self.keyGreen,
1684                                 "yellow": self.keyYellow,
1685                                 "blue"  : self.keyBlue,
1686                         },-2)
1687
1688                 self.showHelpTimer = eTimer()
1689                 self.showHelpTimer.callback.append(self.cbShowHelpTimerClosed)
1690                 self.showHelpTimer.start(500)
1691
1692                 self.onLayoutFinish.append(self.layoutFinished)
1693
1694         def layoutFinished(self):
1695                 self.setTitle(_('Browser Help'))
1696
1697         def cbShowHelpTimerClosed(self):
1698                 self.showHelpTimer.stop()
1699                 self.setHelpModeActions(self.MODE_GLOBAL)
1700
1701         def setHelpModeActions(self, _mode=0):
1702                 self.helpList = []
1703                 if _mode == self.MODE_GLOBAL:
1704                         self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", {
1705                                 "cancel" : (self.keyPass, _("Exit the Opera browser.")),
1706                         })
1707                         self["MenuActions"] = HelpableActionMap(self, "MenuActions", {
1708                                 "menu" : (self.keyPass, _("Show the Menu window.")),
1709                         })
1710                         self["ColorActions"] = HelpableActionMap(self, "ColorActions", {
1711                                 "green"  : (self.keyPass, _("Enter Key")),
1712                                 "yellow" : (self.keyPass, _("Show the Virtual keyboard window.")),
1713                                 "blue"   : (self.keyPass, _("Backspace Key")),
1714                         })
1715                         self["EPGSelectActions"] = HelpableActionMap(self, "EPGSelectActions", {
1716                                 "info" : (self.keyPass, _("Switch to keyboard/mouse mode.")),
1717                         })
1718
1719                 elif _mode == self.MODE_MOUSE:
1720                         self["DirectionActions"] = HelpableActionMap(self, "DirectionActions", {
1721                                 "up"    : (self.keyPass, _("It will move the mouse pointer up.")),
1722                                 "down"  : (self.keyPass, _("It will move the mouse pointer down.")),
1723                                 "left"  : (self.keyPass, _("It will move the mouse pointer left.")),
1724                                 "right" : (self.keyPass, _("It will move the mouse pointer right.")),
1725                         })
1726                         self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", {
1727                                 "ok" : (self.keyPass, _("Left Mouse Button")),
1728                         })
1729                         self["EPGSelectActions"] = HelpableActionMap(self, "EPGSelectActions", {
1730                                 "nextBouquet" : (self.keyPass, _("Right Mouse Button")),
1731                                 "nextService" : (self.keyPass, _("Left Key")),
1732                                 "prevService" : (self.keyPass, _("Right Key")),
1733                         })
1734                 elif _mode == self.MODE_KEYBOARD:
1735                         self["DirectionActions"] = HelpableActionMap(self, "DirectionActions", {
1736                                 "up"    : (self.keyPass, _("Up Key")),
1737                                 "down"  : (self.keyPass, _("Down Key")),
1738                                 "left"  : (self.keyPass, _("Left Key")),
1739                                 "right" : (self.keyPass, _("Right Key")),
1740                         })
1741                         self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", {
1742                                 "ok" : (self.keyPass, _("Enter Key")),
1743                         })
1744                         self["EPGSelectActions"] = HelpableActionMap(self, "EPGSelectActions", {
1745                                 "nextBouquet" : (self.keyPass, _("PageUp Key")),
1746                                 "prevBouquet" : (self.keyPass, _("PageDown Key")),
1747                                 "nextService" : (self.keyPass, _("Go to previous page.")),
1748                                 "prevService" : (self.keyPass, _("Go to next page.")),
1749                         })
1750
1751                 if _mode > 0:
1752                         self.showHelp()
1753
1754         def keyPass(self):
1755                 pass
1756
1757         def keyRed(self):
1758                 self.close()
1759         def keyGreen(self):
1760                 self.setHelpModeActions(self.MODE_GLOBAL)
1761         def keyYellow(self):
1762                 self.setHelpModeActions(self.MODE_MOUSE)
1763         def keyBlue(self):
1764                 self.setHelpModeActions(self.MODE_KEYBOARD)
1765
1766 class OperaBrowser(Screen):
1767         MENUBAR_ITEM_WIDTH  = 150
1768         MENUBAR_ITEM_HEIGHT = 30
1769         SUBMENULIST_WIDTH   = 200
1770         SUBMENULIST_HEIGHT  = 25
1771         SUBMENULIST_NEXT    = 2
1772
1773         # menulist->position->y : MENUBAR_ITEM_HEIGHT+30
1774         # menulist->size->x     : SUBMENULIST_WIDTH
1775         # submenulist->position->x : SUBMENULIST_WIDTH+50+SUBMENULIST_NEXT
1776         # submenulist->position->y : MENUBAR_ITEM_HEIGHT+30
1777         # submenulist->size->x  : SUBMENULIST_WIDTH
1778
1779         size = getDesktop(0).size()
1780         WIDTH  = int(size.width())
1781         HEIGHT = int(size.height())
1782         skin =  """
1783                 <screen name="OperaBrowser" position="0,0" size="%(width)d,%(height)d" backgroundColor="transparent" flags="wfNoBorder" title="Opera Browser">
1784                         <widget name="topArea" zPosition="-1" position="0,0" size="1280,60" font="Regular;20" valign="center" halign="center" backgroundColor="#000000" />
1785                         <widget name="menuitemFile" position="30,20" size="150,30" font="Regular;20" valign="center" halign="center" backgroundColor="#000000" foregroundColors="#9f1313,#a08500" />
1786                         <widget name="menuitemTool" position="180,20" size="150,30" font="Regular;20" valign="center" halign="center" backgroundColor="#000000" foregroundColors="#9f1313,#a08500" />
1787                         <widget name="menuitemHelp" position="330,20" size="150,30" font="Regular;20" valign="center" halign="center" backgroundColor="#000000" foregroundColors="#9f1313,#a08500" />
1788                         <widget name="menulist" position="50,60" size="200,150" backgroundColor="#000000" zPosition="10" scrollbarMode="showOnDemand" />
1789                         <widget name="submenulist" position="252,60" size="200,150" backgroundColor="#000000" zPosition="10" scrollbarMode="showOnDemand" />
1790                         <widget name="bottomArea" position="0,%(bottom_pos_y)d" size="%(bottom_size_x)d,80" font="Regular;20" valign="center" halign="center" backgroundColor="#000000" />
1791                 </screen>
1792                 """ % { 'width'  :WIDTH,
1793                         'height' :HEIGHT,
1794                         'bottom_pos_y'  :HEIGHT-80,
1795                         'bottom_size_x' :WIDTH }
1796
1797         COMMAND_MAP = {}
1798         MENUITEMS_LIST =[]
1799         def __init__(self, session, url=None, isWebAppMode=False):
1800                 Screen.__init__(self, session)
1801                 self["actions"] = ActionMap(["DirectionActions", "MenuActions", "OkCancelActions"], {
1802                          "cancel"      : self.keyCancel
1803                         ,"ok"          : self.keyOK
1804                         ,"left"        : self.keyLeft
1805                         ,"right"       : self.keyRight
1806                         ,"up"          : self.keyUp
1807                         ,"down"        : self.keyDown
1808                         ,"menu"        : self.keyMenu
1809                 }, -2)
1810
1811                 self.UpdateLanguageCB()
1812
1813                 self._terminatedBrowser = True
1814                 self._enableKeyEvent = True
1815                 self._currentPageUrl = None
1816                 self._currentPageTitle = None
1817                 self.menubarCurrentIndex = 0
1818                 self.lvMenuItems = []
1819                 self.lvSubMenuItems = []
1820
1821                 self["topArea"]    = Label()
1822                 self["bottomArea"] = Label()
1823
1824                 self["menuitemFile"] = MultiColorLabel()# modify menu
1825                 self["menuitemTool"] = MultiColorLabel()
1826                 self["menuitemHelp"] = MultiColorLabel()
1827
1828                 self["menulist"] = MenuList(self.setListOnView())
1829                 self["submenulist"] = MenuList(self.setSubListOnView())
1830
1831                 self.toggleMainScreenFlag = True
1832                 self.toggleListViewFlag = False
1833                 self.toggleSubListViewFlag = False
1834                 self.currentListView = self["menulist"]
1835
1836                 self.onLayoutFinish.append(self.layoutFinished)
1837
1838                 self._onCloseTimer = eTimer()
1839                 self._onCloseTimer.callback.append(self._cb_onClose)
1840
1841                 self.paramUrl = url
1842                 self.paramIsWebAppMode = isWebAppMode
1843                 language.addCallback(self.UpdateLanguageCB)
1844
1845         def UpdateLanguageCB(self):
1846                 # modify menu
1847                 self.MENUITEMS_LIST = [
1848                         [(_('Open Startpage'), None), (_('Open URL'), None), (_('Start/Stop'),None), (_('Exit'), None)],
1849                         [(_('Bookmark'), None), (_('Preference'), None)],
1850                         [(_('About'), None), (_('Help'), None)]]
1851                 self.COMMAND_MAP = {}
1852                 self.COMMAND_MAP[_('Exit')] = self._cmd_on_Exit
1853                 self.COMMAND_MAP[_('Help')] = self._cmd_on_Help
1854                 self.COMMAND_MAP[_('About')] = self._cmd_on_About
1855                 self.COMMAND_MAP[_('Open URL')] = self._cmd_on_OpenUrl
1856                 self.COMMAND_MAP[_('Start/Stop')] = self._cmd_on_StartStop
1857                 self.COMMAND_MAP[_('Bookmark')] = self._cmd_on_Bookmark
1858                 self.COMMAND_MAP[_('Preference')] = self._cmd_on_Preference
1859                 self.COMMAND_MAP[_('Return')] = self._cmd_on_ReturnToBrowser
1860                 self.COMMAND_MAP[_('Open Startpage')] = self._cmd_on_OpenStartpage
1861
1862         def enableRCMouse(self, mode): #mode=[0|1]|[False|True]
1863                 rcmouse_path = "/proc/stb/fp/mouse"
1864                 if os.path.exists(rcmouse_path):
1865                         os.system("echo %d > %s" % (mode, rcmouse_path))
1866
1867         def layoutFinished(self):
1868                 self["menuitemFile"].setText(_("File"))# modify menu
1869                 self["menuitemTool"].setText(_("Tools"))
1870                 self["menuitemHelp"].setText(_("Help"))
1871
1872                 self["menulist"].hide()
1873                 self["submenulist"].hide()
1874
1875                 self["bottomArea"].setText(_("Opera Web Browser Plugin v1.0"))
1876                 self.setTitle(_("BrowserMain"))
1877                 self.selectMenuitem()
1878
1879                 if self.paramUrl is not None:
1880                         self.keyMenu()
1881                         if self.paramIsWebAppMode:
1882                                 self.cbUrlText(data=self.paramUrl, mode=1, opcode='OP_BROWSER_OPEN_YOUTUBETV')
1883                         else:   self.cbUrlText(data=self.paramUrl, mode=1)
1884
1885         def selectMenuitem(self):
1886                 tmp = [self["menuitemFile"], self["menuitemTool"], self["menuitemHelp"]]# modify menu
1887                 self["menuitemFile"].setForegroundColorNum(0)
1888                 self["menuitemTool"].setForegroundColorNum(0)
1889                 self["menuitemHelp"].setForegroundColorNum(0)
1890                 tmp[self.menubarCurrentIndex].setForegroundColorNum(1)
1891
1892         def popupCloseAll(self):
1893                 self.keyLeft()
1894                 self.keyLeft()
1895                 self.keyUp()
1896                 self.keyCancel()
1897
1898         def setListOnView(self):
1899                 l = self.MENUITEMS_LIST[self.menubarCurrentIndex]
1900                 if not self._terminatedBrowser and self.menubarCurrentIndex == 0: # running
1901                         l = [(_('Return'), None)]
1902                 self.lvMenuItems = l #self.MENUITEMS_LIST[self.menubarCurrentIndex]     
1903                 return self.lvMenuItems
1904
1905         def setSubListOnView(self):
1906                 self.lvSubMenuItems = []
1907                 xl = self["menulist"].getCurrent()[1]
1908                 if xl is None: return []
1909                 for x in xl:
1910                         self.lvSubMenuItems.append((x,None))
1911                 return self.lvSubMenuItems
1912
1913         def toggleMainScreen(self):
1914                 if not self.toggleMainScreenFlag:
1915                         self.show()
1916                 else:   self.hide()
1917                 self.toggleMainScreenFlag = not self.toggleMainScreenFlag
1918
1919         def toggleListView(self):
1920                 if not self.toggleListViewFlag:
1921                         self["menulist"].show()
1922                 else:   self["menulist"].hide()
1923                 self.toggleListViewFlag = not self.toggleListViewFlag
1924
1925         def toggleSubListView(self):
1926                 if not self.toggleSubListViewFlag:
1927                         self["submenulist"].show()
1928                 else:   self["submenulist"].hide()
1929                 self.toggleSubListViewFlag = not self.toggleSubListViewFlag
1930
1931         def setCurrentListView(self, listViewIdx):
1932                 if listViewIdx == 0:
1933                         self.currentListView = None
1934                 elif listViewIdx == 1:
1935                         self.currentListView = self["menulist"]
1936                 elif listViewIdx == 2:
1937                         self.currentListView = self["submenulist"]
1938
1939         def _cb_onClose(self):
1940                 self._onCloseTimer.stop()
1941                 command_server = getCommandServer()
1942                 try:
1943                         if self._on_close_window in command_server.onHbbTVCloseCB:
1944                                         command_server.onHbbTVCloseCB.remove(self._on_close_window)
1945                 except Exception, ErrMsg: pass
1946                 try:
1947                         if self._on_setPageTitle in command_server.onSetPageTitleCB:
1948                                 command_server.onSetPageTitleCB.remove(self._on_setPageTitle)
1949                 except Exception, ErrMsg: pass
1950                 self._on_setPageTitle(_('Opera Browser'))
1951                 self.enableRCMouse(False)
1952                 self.toggleMainScreen()
1953                 restoreResolution()
1954                 fbClass.getInstance().unlock()
1955                 eRCInput.getInstance().unlock()
1956                 self._terminatedBrowser = True
1957                 self._enableKeyEvent = True
1958                 #if not self.toggleListViewFlag:
1959                 #       self.keyDown()
1960
1961                 self._currentPageUrl = ''
1962                 if self.paramUrl is not None:
1963                         self.keyCancel()
1964                 else:
1965                         self.keyRight()
1966                         self.keyLeft()
1967
1968         def _on_setPageTitle(self, title=None):
1969                 print "Title :",title
1970                 if title is None:
1971                         return
1972                 self.setTitle(title)
1973
1974         def cbUrlText(self, data=None, mode=0, opcode='OP_BROWSER_OPEN_URL'):
1975                 global _g_helper
1976                 if not _g_helper._is_browser_running():
1977                         return
1978                 print "Inputed Url :", data, mode
1979                 if strIsEmpty(data):
1980                         return
1981                 #self.hideSubmenu()
1982                 command_server = getCommandServer()
1983                 if self._on_setPageTitle not in command_server.onSetPageTitleCB:
1984                                 command_server.onSetPageTitleCB.append(self._on_setPageTitle)
1985                 if self._on_close_window not in command_server.onHbbTVCloseCB:
1986                         command_server.onHbbTVCloseCB.append(self._on_close_window)
1987                 self.toggleMainScreen()
1988                 self.enableRCMouse(True)
1989
1990                 fbClass.getInstance().lock()
1991                 eRCInput.getInstance().lock()
1992
1993                 #setResolution(1280, 720)
1994
1995                 command_util = getCommandUtil()
1996                 command_util.sendCommand(opcode, data, mode)
1997                 self._terminatedBrowser = False
1998                 self._enableKeyEvent = False
1999
2000         def _on_close_window(self):
2001                 self._onCloseTimer.start(1000)
2002
2003         def _cb_bookmarkWindowClosed(self, data=None):
2004                 if data is None:
2005                         return
2006                 (url, mode) = data
2007                 global _g_helper
2008                 if not _g_helper._is_browser_running():
2009                         message = _("Opera Browser was not running.\nPlease running browser using [File]>[Start/Stop] menu.")
2010                         self.session.open(MessageBox, message, MessageBox.TYPE_INFO)
2011                         return
2012                 self.cbUrlText(url, mode)
2013
2014         def _cmd_on_OpenUrl(self):
2015                 global _g_helper
2016                 if not _g_helper._is_browser_running():
2017                         message = _("Opera Browser was not running.\nPlease running browser using [File]>[Start/Stop] menu.")
2018                         self.session.open(MessageBox, message, MessageBox.TYPE_INFO)
2019                         return
2020                 self.session.openWithCallback(self.cbUrlText, VirtualKeyBoard, title=(_("Please enter URL here")), text='http://')
2021         def _cmd_on_About(self):
2022                 self.session.open(MessageBox, _('Opera Web Browser Plugin v1.0'), type = MessageBox.TYPE_INFO)
2023         def _cmd_on_Exit(self):
2024                 self.close()
2025         def _cb_cmdOnStartSTop(self):
2026                 self.keyMenu()
2027         def _cmd_on_StartStop(self):
2028                 global _g_helper
2029                 if _g_helper is None: 
2030                         return
2031                 _g_helper.showBrowserConfigBox(self._cb_cmdOnStartSTop)
2032
2033         def _cmd_on_Bookmark(self):
2034                 url = self._currentPageUrl
2035                 if url is None:
2036                         url = ''
2037                 title = self._currentPageTitle
2038                 if title is None:
2039                         title = ''
2040                 self.session.openWithCallback(self._cb_bookmarkWindowClosed, OperaBrowserBookmarkWindow, url, title)
2041         def _cmd_on_Preference(self):
2042                 url = self._currentPageUrl
2043                 if url is None:
2044                         url = ''
2045                 self.session.open(OperaBrowserPreferenceWindow, url)
2046         def _cmd_on_OpenStartpage(self):
2047                 global _g_helper
2048                 if not _g_helper._is_browser_running():
2049                         message = _("Opera Browser was not running.\nPlease running browser using [File]>[Start/Stop] menu.")
2050                         self.session.open(MessageBox, message, MessageBox.TYPE_INFO)
2051                         return
2052                 mode = 0
2053                 start = 'http://vuplus.com'
2054                 try:
2055                         d = OperaBrowserSetting().getData()
2056                         start = d['start']
2057                         mode = d['type']
2058                 except: pass
2059                 self.cbUrlText(start, mode)
2060         def _cmd_on_ReturnToBrowser(self):
2061                 self.keyCancel()
2062
2063         def _cmd_on_Help(self):
2064                 self.session.open(BrowserHelpWindow)
2065
2066         def doCommand(self, command):
2067                 try:
2068                         self.COMMAND_MAP[command]()
2069                 except Exception, ErrMsg: print ErrMsg
2070
2071         def keyOK(self):
2072                 if not self.toggleMainScreenFlag:
2073                         self.keyMenu()
2074                         return
2075                 if not self.toggleListViewFlag:
2076                         self.keyDown()
2077                         return
2078                 if self.currentListView.getCurrent()[1] is None:
2079                         self.doCommand(self.currentListView.getCurrent()[0])
2080                         #self.session.open(MessageBox, _(self.currentListView.getCurrent()[0]), type = MessageBox.TYPE_INFO)
2081                         return
2082                 self.keyRight()
2083
2084         def updateSelectedMenuitem(self, status):
2085                 if self.menubarCurrentIndex == 0 and status < 0:
2086                         self.menubarCurrentIndex = 2 # modify menu
2087                 elif self.menubarCurrentIndex == 2 and status > 0: # modify menu
2088                         self.menubarCurrentIndex = 0
2089                 else:   self.menubarCurrentIndex += status
2090                 self.selectMenuitem()
2091
2092         def keyLeft(self):
2093                 if not self.toggleMainScreenFlag:
2094                         return
2095                 if not self.toggleListViewFlag:
2096                         self.updateSelectedMenuitem(-1)
2097                         return
2098                 if self.toggleSubListViewFlag:
2099                         self.setCurrentListView(1)
2100                         self.toggleSubListView()
2101                         return
2102                 #if self.currentListView.getSelectedIndex():
2103                 self.currentListView.pageUp()
2104                 self.keyUp()
2105                 self.keyLeft()
2106                 self.keyDown()
2107
2108         def keyRight(self):
2109                 if not self.toggleMainScreenFlag:
2110                         return
2111                 if not self.toggleListViewFlag:
2112                         self.updateSelectedMenuitem(1)
2113                         return
2114                 if self.currentListView is None:
2115                         return
2116                 if self.currentListView.getCurrent()[1] is not None:
2117                         parentSelectedIndex = self.currentListView.getSelectedIndex()
2118                         self.setCurrentListView(2)
2119                         self.currentListView.setList(self.setSubListOnView())
2120                         self.currentListView.resize(self.SUBMENULIST_WIDTH, self.SUBMENULIST_HEIGHT*len(self.lvSubMenuItems)+5)
2121                         self.currentListView.move(self.MENUBAR_ITEM_WIDTH*self.menubarCurrentIndex + self.SUBMENULIST_WIDTH+self.SUBMENULIST_NEXT + 50,self.MENUBAR_ITEM_HEIGHT+30+(parentSelectedIndex*self.SUBMENULIST_HEIGHT))
2122                         self.toggleSubListView()
2123                         return
2124                 self.currentListView.pageUp()
2125                 self.keyUp()
2126                 self.keyRight()
2127                 self.keyDown()
2128
2129         def keyDown(self):
2130                 if not self.toggleMainScreenFlag:
2131                         return
2132                 if self.currentListView is None:
2133                         return
2134                 if not self.toggleListViewFlag:
2135                         self.currentListView.setList(self.setListOnView())
2136                         self.currentListView.resize(self.SUBMENULIST_WIDTH, self.SUBMENULIST_HEIGHT*len(self.lvMenuItems)+5)
2137                         self.currentListView.move(self.MENUBAR_ITEM_WIDTH*self.menubarCurrentIndex+1+ 50,self.MENUBAR_ITEM_HEIGHT+30)
2138                         self.toggleListView()
2139                         return
2140                 self.currentListView.down()
2141
2142         def keyUp(self):
2143                 if not self.toggleMainScreenFlag:
2144                         return
2145                 if self.currentListView is None:
2146                         return
2147                 if self.currentListView == self["menulist"]:
2148                         if self.currentListView.getSelectedIndex() == 0:
2149                                 self.toggleListView()
2150                                 return
2151                 self.currentListView.up()
2152
2153         def keyCancel(self):
2154                 if not self._terminatedBrowser:
2155                         #self._session.openWithCallback(self._cb_virtualKeyboardClosed, VirtualKeyBoard, title=("Please enter URL here"), text="")
2156                         fbClass.getInstance().lock()
2157                         eRCInput.getInstance().lock()
2158                         #setResolution(1280, 720)
2159                         if self.toggleListViewFlag:
2160                                 self.toggleMainScreen()
2161                         self._currentPageUrl   = None
2162                         self._currentPageTitle = None
2163                         command_util = getCommandUtil()
2164                         command_util.sendCommand('OP_BROWSER_MENU_RES')
2165                         return
2166                 self.close()
2167
2168         def keyMenu(self):
2169                 self.toggleMainScreen()
2170
2171         def setCurrentPageUrl(self, url, title=None):
2172                 self._currentPageUrl = url
2173                 if title is None:
2174                         idx = len(url)
2175                         if idx > 10: idx = 10
2176                         title = url[:idx]
2177                 self._currentPageTitle = title
2178                 print self._currentPageUrl
2179                 self.toggleMainScreen()
2180                 self.hideSubmenu()
2181                 self.keyDown()
2182
2183         def hideSubmenu(self):
2184                 self.currentListView.pageUp()
2185                 self.keyUp()
2186
2187 config.plugins.youtubetv = ConfigSubsection()
2188 config.plugins.youtubetv.showhelp = ConfigYesNo(default = False)
2189 config.plugins.youtubetv.uri = ConfigText(default = "http://www.youtube.com/tv", visible_width = 50, fixed_size = False)
2190 class YoutubeTVWindow(Screen, HelpableScreen):
2191         skin =  """
2192                 <screen name="YoutubeTVWindow" position="center,center" size="550,160" title="Start YouTube TV" >
2193                         <widget name="infomation" position="5,0" size="540,80" valign="center" halign="center" font="Regular;20" />
2194                         <widget name="startdesc" position="10,80" size="395,40" valign="center" font="Regular;20" />
2195                         <widget name="helpdesc" position="10,120" size="395,40" valign="center" font="Regular;20" />
2196                         <ePixmap pixmap="skin_default/buttons/green.png" position="400,80" size="140,40" alphatest="on" />
2197                         <ePixmap pixmap="skin_default/buttons/yellow.png" position="400,120" size="140,40" alphatest="on" />
2198                         <widget source="key_green" render="Label" position="400,80" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
2199                         <widget source="key_yellow" render="Label" position="400,120" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" foregroundColor="#ffffff" transparent="1" />
2200                 </screen>
2201                 """
2202         def __init__(self, session):
2203                 Screen.__init__(self, session)
2204                 HelpableScreen.__init__(self)
2205
2206                 self["actions"] = ActionMap(["WizardActions", "DirectionActions", "OkCancelActions","ColorActions", "EPGSelectActions",], {
2207                                 "cancel": self.keyCancel,
2208                                 "red"   : self.keyCancel,
2209                                 "green" : self.keyGreen,
2210                                 "yellow": self.keyYellow,
2211                         },-2)
2212
2213                 self["key_green"]  = StaticText(_("Start"))
2214                 self["key_yellow"] = StaticText(_("Help"))
2215
2216                 self["infomation"] = Label()
2217                 self["startdesc"]  = Label()
2218                 self["helpdesc"]   = Label()
2219
2220                 self.onLayoutFinish.append(self.layoutFinished)
2221
2222         def layoutFinished(self):
2223                 self.setTitle(_('Start YouTube TV'))
2224                 self["infomation"].setText(_("YouTube TV is a new way to watch YouTube videos on Vu+"))
2225                 self["startdesc" ].setText(_("* Start YouTube TV"))
2226                 self["helpdesc"  ].setText(_("* RC Help"))
2227
2228         def setHelpModeActions(self):
2229                 self.helpList = []
2230                 self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", {
2231                         "ok"    : (self.keyPass, _("Play ther selected the video")),
2232                         "cancel": (self.keyPass, _("Exit the YouTube TV")),
2233                 })
2234                 self["EventViewActions"] = HelpableActionMap(self, "EventViewActions", {
2235                         "pageUp"    : (self.keyPass, _("Move up")),
2236                         "pageDown"  : (self.keyPass, _("Move down")),
2237                         "prevEvent" : (self.keyPass, _("Move left")),
2238                         "nextEvent" : (self.keyPass, _("Move right")),
2239                 })
2240                 self["EPGSelectActions"] = HelpableActionMap(self, "EPGSelectActions", {
2241                         "info"        : (self.keyPass, _("Search a video")),
2242                         "nextService" : (self.keyPass, _("Skip forward 10 sec")),
2243                         "prevService" : (self.keyPass, _("Skip backward 10 sec")),
2244                 })
2245                 self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions", {
2246                         "play"  : (self.keyPass, _("Play current video")),
2247                         "pause" : (self.keyPass, _("Pause current video")),
2248                         "stop"  : (self.keyPass, _("Stop current video")),
2249                 })
2250                 self["ColorActions"] = HelpableActionMap(self, "ColorActions", {
2251                         "red"   : (self.keyPass, _("Back")),
2252                 })
2253                 self.showHelp()
2254
2255         def keyPass(self):
2256                 pass
2257         def keyCancel(self):
2258                 config.plugins.youtubetv.showhelp.cancel()
2259                 self.close(False)
2260         def keyGreen(self):
2261                 config.plugins.youtubetv.showhelp.save()
2262                 config.plugins.youtubetv.save()
2263                 config.plugins.save()
2264                 self.close(True)
2265         def keyYellow(self):
2266                 self.setHelpModeActions()
2267         def keyBlue(self):
2268                 if config.plugins.youtubetv.showhelp.value == True :
2269                         config.plugins.youtubetv.showhelp.setValue(False)
2270                 else:   config.plugins.youtubetv.showhelp.setValue(True)
2271
2272 class YoutubeTVSettings(ConfigListScreen, Screen):
2273     skin=   """
2274         <screen position="center,center" size="600,140" title="YouTube TV Settings">
2275             <widget name="config" position="0,0" size="600,100" scrollbarMode="showOnDemand" />
2276
2277             <ePixmap pixmap="skin_default/buttons/red.png" position="310,100" size="140,40" alphatest="on" />
2278             <ePixmap pixmap="skin_default/buttons/green.png" position="150,100" size="140,40" alphatest="on" />
2279
2280             <widget source="key_red" render="Label" position="310,100" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" />
2281             <widget source="key_green" render="Label" position="150,100" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" />
2282         </screen>
2283         """
2284     def __init__(self, session):
2285         self.session = session
2286         Screen.__init__(self, session)
2287
2288         self.menulist = []
2289         ConfigListScreen.__init__(self, self.menulist)
2290
2291         self["actions"] = ActionMap(["OkCancelActions", "ColorActions",], {
2292             "ok"     : self.keyGreen,
2293             "green"  : self.keyGreen,
2294             "red"    : self.keyRed,
2295             "cancel" : self.keyRed,
2296                 }, -2)
2297
2298         self["key_red"]   = StaticText(_("Cancel"))
2299         self["key_green"] = StaticText(_("Save"))
2300
2301         self.makeConfigList()
2302         self.onLayoutFinish.append(self.layoutFinished)
2303
2304     def layoutFinished(self):
2305         self.setTitle(_('YouTube TV Settings'))
2306
2307     def keyGreen(self):
2308         config.plugins.youtubetv.showhelp.save()
2309         config.plugins.youtubetv.uri.save()
2310         config.plugins.youtubetv.save()
2311         config.plugins.save()
2312         self.close()
2313     def keyRed(self):
2314         config.plugins.youtubetv.showhelp.cancel()
2315         config.plugins.youtubetv.uri.cancel()
2316         self.close()
2317
2318     def keyLeft(self):
2319         ConfigListScreen.keyLeft(self)
2320
2321     def keyRight(self):
2322         ConfigListScreen.keyRight(self)
2323
2324     def makeConfigList(self):
2325         self.menulist = []
2326         entryUri = getConfigListEntry(_("YouTube TV URL"), config.plugins.youtubetv.uri)
2327         entryShowHelp = getConfigListEntry(_("Do not show YouTube TV Stater again"), config.plugins.youtubetv.showhelp)
2328         self.menulist.append(entryUri)
2329         self.menulist.append(entryShowHelp)
2330
2331         self["config"].list = self.menulist
2332         self["config"].l.setList(self.menulist)
2333
2334 def auto_start_main(reason, **kwargs):
2335         if reason:
2336                 command_server = getCommandServer()
2337                 command_server.stop()
2338
2339 from  Screens.HelpMenu import HelpableScreen
2340 def session_start_main(session, reason, **kwargs):
2341         fbClass.getInstance().unlock()
2342         eRCInput.getInstance().unlock()
2343
2344         from enigma import getDesktop
2345         desktopSize = getDesktop(0).size()
2346         setDefaultResolution(desktopSize.width(), desktopSize.height())
2347
2348         global _g_helper
2349         _g_helper = session.open(HbbTVHelper)
2350
2351         HelpableScreen.__init__ = HelpableScreen__init__
2352         HelpableScreen.session = session
2353
2354 def HelpableScreen__init__(self):
2355         if isinstance(self, HelpableScreen):
2356                 HelpableScreen.showManual = showManual
2357
2358                 self["helpActions"] = ActionMap(["HelpbuttonActions"], {
2359                         "help_b" : self.showHelp,
2360                         "help_l" : self.showManual, 
2361                 }, -2)
2362
2363 _g_clearBrowserDataTimer = eTimer()
2364 def showManual(self):
2365         if not os.path.exists('/usr/local/manual'):
2366                 return
2367
2368         url = 'file:///usr/local/manual/main.html'
2369         lang = language.getLanguage()
2370         if lang == 'ru_RU' and os.path.exists('/usr/local/manual/ru_RU'):
2371                 url = 'file:///usr/local/manual/ru_RU/main.html'
2372         elif lang == 'de_DE' and os.path.exists('/usr/local/manual/de_DE'):
2373                 url = 'file:///usr/local/manual/de_DE/main.html'
2374
2375         def _do_clean():
2376                 _g_clearBrowserDataTimer.stop()
2377                 try:    _g_clearBrowserDataTimer.callback.remove(_do_clean)
2378                 except: pass
2379                 setPluginBrowser(None)
2380         def clearBrowserData():
2381                 _g_clearBrowserDataTimer.callback.append(_do_clean)
2382                 _g_clearBrowserDataTimer.start(50)
2383         setPluginBrowser(self.session.openWithCallback(clearBrowserData, OperaBrowser, url))
2384
2385 _g_backupSession = None
2386 def showYoutubeTV(session, **kwargs):
2387         def _do_clean():
2388                 _g_clearBrowserDataTimer.stop()
2389                 try:    _g_clearBrowserDataTimer.callback.remove(_do_clean)
2390                 except: pass
2391                 setPluginBrowser(None)
2392                 global _g_backupSession
2393                 
2394                 service = getBeforeService()
2395                 if service is not None:
2396                         _g_backupSession.nav.playService(eServiceReference(service))
2397                         _g_backupSession = None
2398         def clearBrowserData():
2399                 _g_clearBrowserDataTimer.callback.append(_do_clean)
2400                 _g_clearBrowserDataTimer.start(50)
2401         def cbYoutubeTVClose(ret):
2402                 if ret:
2403                         global _g_backupSession
2404                         _g_backupSession = session
2405                         service = session.nav.getCurrentlyPlayingServiceReference()
2406                         if service is not None:
2407                                 setBeforeService(service.toString())
2408                                 session.nav.stopService()
2409                         else:   setBeforeService(service)
2410                         setPluginBrowser(session.openWithCallback(clearBrowserData, OperaBrowser, config.plugins.youtubetv.uri.value, True))
2411         if config.plugins.youtubetv.showhelp.value == True:
2412                 cbYoutubeTVClose(True)
2413         else:   session.openWithCallback(cbYoutubeTVClose, YoutubeTVWindow)
2414
2415 def youtube_setting_main(session, **kwargs):
2416         session.open(YoutubeTVSettings)
2417
2418 def start_menu_main(menuid, **kwargs):
2419         if menuid == "mainmenu":
2420                 return [(_("YouTube TV"), showYoutubeTV, "youtube_tv", 46)]
2421         return []
2422
2423 def plugin_start_main(session, **kwargs):
2424         #session.open(OperaBrowser)
2425         def _do_clean():
2426                 _g_clearBrowserDataTimer.stop()
2427                 try:    _g_clearBrowserDataTimer.callback.remove(_do_clean)
2428                 except: pass
2429                 setPluginBrowser(None)
2430         def clearBrowserData():
2431                 _g_clearBrowserDataTimer.callback.append(_do_clean)
2432                 _g_clearBrowserDataTimer.start(50)
2433         setPluginBrowser(session.openWithCallback(clearBrowserData, OperaBrowser))
2434
2435 def plugin_extension_start_application(session, **kwargs):
2436         global _g_helper
2437         if _g_helper is None: 
2438                 return
2439         _g_helper.showApplicationSelectionBox()
2440
2441 def plugin_extension_browser_config(session, **kwargs):
2442         global _g_helper
2443         if _g_helper is None: 
2444                 return
2445         _g_helper.showBrowserConfigBox()
2446
2447 def Plugins(path, **kwargs):
2448         l = []
2449         l.append(PluginDescriptor(where=PluginDescriptor.WHERE_AUTOSTART, fnc=auto_start_main))
2450         l.append(PluginDescriptor(name=_("YouTube TV"), where=PluginDescriptor.WHERE_MENU, fnc=start_menu_main))
2451         l.append(PluginDescriptor(name=_("YouTube TV Settings"), where=PluginDescriptor.WHERE_PLUGINMENU, fnc=youtube_setting_main))
2452         l.append(PluginDescriptor(where=PluginDescriptor.WHERE_SESSIONSTART, needsRestart=True, fnc=session_start_main, weight=-10))
2453         l.append(PluginDescriptor(name=_("HbbTV Applications"), where=PluginDescriptor.WHERE_EXTENSIONSMENU, needsRestart=True, fnc=plugin_extension_start_application))
2454         l.append(PluginDescriptor(name=_("Browser Start/Stop"), where=PluginDescriptor.WHERE_EXTENSIONSMENU, needsRestart=True, fnc=plugin_extension_browser_config))
2455         l.append(PluginDescriptor(name=_("Opera Web Browser"), description=_("start opera web browser"), where=PluginDescriptor.WHERE_PLUGINMENU, needsRestart=True, fnc=plugin_start_main))
2456
2457         return l
2458