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