4.3.1r21
[enigma2.git] / usr / lib / enigma2 / python / Plugins / Extensions / Browser / Browser.py
1 import _webview
2 from webview import eWebView
3 from enigma import getDesktop, getPrevAsciiCode, eTimer, eListboxPythonStringContent, eDict, eServiceReference, eRCInput, ePoint, eRect, cvar
4 import enigma
5 enigma.eWebView = eWebView
6
7 from Components.ActionMap import NumberActionMap, ActionMap, HelpableActionMap
8 from Components.config import config, ConfigSubsection, ConfigText, ConfigSelection, ConfigYesNo, ConfigDirectory
9 from Components.Input import Input
10 from Components.Label import Label
11 from Components.Language import language
12 from Components.MenuList import MenuList
13 from Components.Pixmap import Pixmap
14 from Components.Sources.Boolean import Boolean
15 from Components.Sources.CanvasSource import CanvasSource
16 from Components.Sources.StaticText import StaticText
17 from Components.Sources.WebNavigation import WebNavigation
18
19 from Screens.ChoiceBox import ChoiceBox
20 from Screens.HelpMenu import HelpableScreen
21 from Screens.MessageBox import MessageBox
22 from Screens.Screen import Screen
23 from Screens.VirtualKeyBoard import VirtualKeyBoard
24
25 from Tools.BoundFunction import boundFunction
26 from Tools.Directories import SCOPE_PLUGINS, resolveFilename
27 from Tools.Log import Log
28
29 from BrowserDB import BrowserDB, HistoryItem, Certificate, Cookie
30 from BrowserMenu import BrowserMenu
31 from BrowserVideoWindow import BrowserVideoWindow
32 from WebMediaPlayerProxy import WebMediaPlayerProxy
33 from Downloads import downloadManager, DownloadJob
34 from EnhancedInput import EnhancedInput
35 from MoviePlayer import MoviePlayer
36
37 from base64 import b64decode, b64encode
38 from urllib import unquote as url_unquote, quote_plus as url_quote_plus
39 from urlparse import urlparse
40
41 config.plugins.WebBrowser = ConfigSubsection()
42 config.plugins.WebBrowser.home = ConfigText(default = "http://box.dream-multimedia-tv.de")
43 config.plugins.WebBrowser.startPage = ConfigSelection([ ("home", _("Home Page")), ("lastvisted", _("Last visted")) ])
44 config.plugins.WebBrowser.lastvisited = ConfigText(default = "http://box.dream-multimedia-tv.de")
45 config.plugins.WebBrowser.searchProvider = ConfigSelection([ ("http://www.google.de/search?q=", _("Google")), ("http://www.bing.com/search?q=", _("Bing")) ])
46 config.plugins.WebBrowser.fullscreen = ConfigYesNo( default = False )
47 config.plugins.WebBrowser.scrollOffset = ConfigSelection([ ("75", "75"), ("150", "150"), ("200", "200") ])
48 config.plugins.WebBrowser.storage = ConfigSubsection()
49 config.plugins.WebBrowser.storage.enabled = ConfigYesNo( default = False )
50 config.plugins.WebBrowser.storage.path = ConfigDirectory(default = "/media/hdd/webkit-data")
51 config.plugins.WebBrowser.downloadpath = ConfigDirectory(default = "/media/hdd")
52
53 class Browser(Screen, HelpableScreen):
54
55         def __init__(self, session, fullscreen = False, url = None, isHbbtv = False, isTransparent = False, hbbtvMenu = None):
56                 size = getDesktop(0).size()
57                 width = int(size.width() * 0.9)
58                 fwidth = int(size.width())
59                 height = int(size.height() * 0.85)
60                 fheight = int(size.height())
61
62                 Browser.skin = """
63                         <screen name="Browser" position="center,center" size="%(w)d,%(h)d" title="Web Browser" backgroundColor="#FF000000">
64                                 <widget name="cursor" position="0,0" size="19,30" zPosition="1" alphatest="on"/>
65                                 <widget name="url" position="0,0" zPosition="2" size="%(w)d,25" font="Regular;20" halign="left" valign="bottom" backgroundColor="background"/>
66                                 <widget name="loading" position="%(loadingX)d,0" zPosition="3" size="150,25" font="Regular;20" halign="right" valign="bottom" backgroundColor="background"/>
67                                 <widget name="urlList" position="0,30" zPosition="2" size="%(w)d,150" backgroundColor="background"/>
68                                 <widget name="text" position="%(textX)d,100" size="350,40" font="Regular;20"  zPosition="2" halign="center" valign="center" backgroundColor="background"/>
69                                 <widget source="webnavigation" render="WebView" position="0,25" zPosition="0" size="%(w)d,%(mainH)d" transparent="1"/>
70                                 <widget source="canvas" render="Canvas" position="0,25" zPosition="1" size="%(w)d,%(mainH)d" backgroundColor="#FF000000" transparent="1" alphatest="on"/>
71
72                                 <group name="_buttonBar">
73                                         <widget name="buttonBar" position="0,%(btnBarY)d" size="%(w)d,30" zPosition="0" backgroundColor="background" transparent="0" />
74                                         <ePixmap pixmap="skin_default/buttons/button_red_off.png" position="5,%(btnY)d" size="15,16" alphatest="on" />
75                                         <widget source="button_red" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_red.png" position="5,%(btnY)d" size="15,16" alphatest="on">
76                                                 <convert type="ConditionalShowHide" />
77                                         </widget>
78                                         <widget name="red" position="25,%(btnTxtY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1" />
79
80                                         <ePixmap pixmap="skin_default/buttons/button_green_off.png" position="195,%(btnY)d" size="15,16" alphatest="on" />
81                                         <widget source="button_green" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_green.png" position="195,%(btnY)d" size="15,16" alphatest="on">
82                                                 <convert type="ConditionalShowHide" />
83                                         </widget>
84                                         <widget name="green" position="215,%(btnTxtY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
85
86                                         <ePixmap pixmap="skin_default/buttons/button_yellow_off.png" position="385,%(btnY)d" size="15,16" alphatest="on" />
87                                         <widget source="button_yellow" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_yellow.png" position="385,%(btnY)d" size="15,16" alphatest="on">
88                                                 <convert type="ConditionalShowHide" />
89                                         </widget>
90                                         <widget name="yellow" position="405,%(btnTxtY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
91
92                                         <ePixmap pixmap="skin_default/buttons/button_blue_off.png" position="585,%(btnY)d" size="15,16" alphatest="on" />
93                                         <widget source="button_blue" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_blue.png" position="585,%(btnY)d" size="15,16" alphatest="on">
94                                                 <convert type="ConditionalShowHide" />
95                                         </widget>
96                                         <widget name="blue" position="605,%(btnTxtY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
97                                 </group>
98                                 <widget name="statuslabel" position="%(notifX)d,%(btnTxtY)d" size="350,20" font="Regular;18"  zPosition="3" halign="right" valign="center" backgroundColor="background" />
99                         </screen>
100                         """ %{  "w" : width,
101                                         "h" : height,
102                                         "loadingX" : width-150,
103                                         "textX" : (width - 375) / 2,
104                                         "mainH" : height-55,
105                                         "btnY" : height-22,
106                                         "btnTxtY" : height-24,
107                                         "btnBarY" : height - 30,
108                                         "notifX" : width-350
109                                 }
110
111                 Browser.skinFullscreen = """
112                         <screen name="BrowserFullscreen" flags="wfNoBorder" position="center,center" size="%(w)d,%(h)d" title="Web Browser" backgroundColor="#FF000000">
113                                 <widget name="cursor" position="0,0" size="19,30" zPosition="1" alphatest="on"/>
114                                 <widget name="url" position="75,75" zPosition="2" size="%(urlW)d,25" font="Regular;20" halign="left" valign="bottom" backgroundColor="background"/>
115                                 <widget name="loading" position="%(loadingX)d,%(loadingY)d" zPosition="2" size="200,50" font="Regular;20" halign="center" valign="center" backgroundColor="background"/>
116                                 <widget name="urlList" position="75,100" zPosition="2" size="%(urlW)d,150" backgroundColor="background" transparent="0" />
117                                 <widget name="text" position="%(textX)d,100" size="350,40" font="Regular;20"  zPosition="2" halign="center" valign="center" backgroundColor="background" transparent="0" />
118                                 <widget source="webnavigation" render="WebView" position="0,0" zPosition="0" size="%(w)d,%(h)d" transparent="1"/>
119                                 <widget source="canvas" render="Canvas" position="0,0" zPosition="1" size="%(w)d,%(h)d" backgroundColor="#FF000000" transparent="1" alphatest="on"/>
120
121                                 <group name="_buttonBar">
122                                         <widget name="buttonBar" position="%(btnBarX)d,%(btnBarY)d" size="200,110" zPosition="0" backgroundColor="background" transparent="0" />
123                                         <widget source="button_red_off" render="Pixmap" pixmap="skin_default/buttons/button_red_off.png" position="%(btnX)d,%(btnRedY)d" size="15,16" zPosition="1" alphatest="on">
124                                                 <convert type="ConditionalShowHide" />
125                                         </widget>
126                                         <widget source="button_red" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_red.png" position="%(btnX)d,%(btnRedY)d" size="15,16" alphatest="on">
127                                                 <convert type="ConditionalShowHide" />
128                                         </widget>
129                                         <widget name="red" position="%(btnTxtX)d,%(btnRedY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
130
131                                         <widget source="button_green_off" render="Pixmap" pixmap="skin_default/buttons/button_green_off.png" position="%(btnX)d,%(btnGreenY)d" size="15,16" zPosition="1" alphatest="on">
132                                                 <convert type="ConditionalShowHide" />
133                                         </widget>
134                                         <widget source="button_green" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_green.png" position="%(btnX)d,%(btnGreenY)d" size="15,16" alphatest="on">
135                                                 <convert type="ConditionalShowHide" />
136                                         </widget>
137                                         <widget name="green" position="%(btnTxtX)d,%(btnGreenY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
138
139                                         <widget source="button_yellow_off" render="Pixmap" pixmap="skin_default/buttons/button_yellow_off.png" position="%(btnX)d,%(btnYellowY)d" size="15,16" zPosition="1" alphatest="on">
140                                                 <convert type="ConditionalShowHide" />
141                                         </widget>
142                                         <widget source="button_yellow" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_yellow.png" position="%(btnX)d,%(btnYellowY)d" size="15,16" alphatest="on">
143                                                 <convert type="ConditionalShowHide" />
144                                         </widget>
145                                         <widget name="yellow" position="%(btnTxtX)d,%(btnYellowY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
146
147                                         <widget source="button_blue_off" render="Pixmap" pixmap="skin_default/buttons/button_blue_off.png" position="%(btnX)d,%(btnBlueY)d" size="15,16" zPosition="1" alphatest="on">
148                                                 <convert type="ConditionalShowHide" />
149                                         </widget>
150                                         <widget source="button_blue" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_blue.png" position="%(btnX)d,%(btnBlueY)d" size="15,16" alphatest="on">
151                                                 <convert type="ConditionalShowHide" />
152                                         </widget>
153                                         <widget name="blue" position="%(btnTxtX)d,%(btnBlueY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
154                                 </group>
155
156                                 <widget name="statuslabel" position="%(notifX)d,%(loadingY)d" size="350,50" zPosition="1" font="Regular;18" halign="center" valign="center" backgroundColor="background" transparent="0" />
157                         </screen>
158                         """ %{  "w" : fwidth,
159                                         "h" : fheight,
160                                         "urlW": fwidth - 150,
161                                         "loadingY" : fheight - 125,
162                                         "loadingX" : ( fwidth / 2 ) - 75,
163                                         "textX" : (fwidth - 375) / 2,
164                                         "mainH" : fheight-55,
165                                         "btnBarX": fwidth - 75 - 200,
166                                         "btnBarY": fheight - 75 - 108,
167                                         "btnX" : fwidth - 75 - 190,
168                                         "btnTxtX" : fwidth - 75 - 165,
169                                         "btnRedY" : fheight - 75 - 100,
170                                         "btnGreenY" : fheight - 75 - 75,
171                                         "btnYellowY" : fheight - 75 - 50,
172                                         "btnBlueY" : fheight - 75 - 25,
173                                         "notifX" : ( fwidth / 2 ) - 175,
174                                 }
175
176                 self.__isHbbtv = isHbbtv
177                 if self.__isHbbtv:
178                         isTransparent = fullscreen = True
179
180                 self.__hbbtvMenu = hbbtvMenu
181                 self._videoWindow = None
182
183                 self.__isTransparent = isTransparent
184                 self.__fullscreen = fullscreen
185                 if self.__fullscreen:
186                         Browser.skin = Browser.skinFullscreen
187
188                 Screen.__init__(self, session)
189                 HelpableScreen.__init__(self)
190
191                 if self.__fullscreen:
192                         self.skinName = "BrowserFullscreen"
193
194                 self.__startUrl = url
195
196                 self["loading"] = Label("")
197
198                 self.urlInput = EnhancedInput()
199                 self["url"] = self.urlInput
200
201                 self.textInput = Input()
202                 self["text"] = self.textInput
203                 self.textInput.hide()
204
205                 self.statuslabel = Label("")
206                 self["statuslabel"] = self.statuslabel
207                 self.statuslabel.hide();
208
209                 self.urlInputEnabled = False
210
211                 self.webnavigation = WebNavigation()
212                 self.webnavigation.zoomFactor = 1.0
213                 self.__onStoragePathChanged()
214                 self["webnavigation"] = self.webnavigation
215
216                 self.__urlList = MenuList([], enableWrapAround = True, content = eListboxPythonStringContent)
217                 self["urlList"] = self.__urlList
218
219                 self.canvas =  CanvasSource()
220                 self["canvas"] = self.canvas
221
222                 self["buttonBar"] = Label("")
223                 self["button_red_off"] = Boolean(True)
224                 self["button_green_off"] = Boolean(True)
225                 self["button_yellow_off"] = Boolean(True)
226                 self["button_blue_off"] = Boolean(True)
227                 self["button_red"] = Boolean(True)
228                 self["button_green"] = Boolean(False)
229                 self["button_yellow"] = Boolean(True)
230                 self["button_blue"] = Boolean(True)
231                 self["red"] = Label(_("Mouse Off"))
232                 self["green"] = Label("")
233                 self["yellow"] = Label(_("Navigation"))
234                 self["blue"] = Label(_("Pagescroll"))
235
236                 self["cursor"] = Pixmap()
237                 self.__cursorPos = ePoint(50,50)
238                 self.__mouseMode = False
239
240                 self.__db = BrowserDB.getInstance()
241                 self.pageTitle = ""
242
243                 self.__urlSuggestionTimer = eTimer()
244                 self.__urlSuggestionTimer_conn = self.__urlSuggestionTimer.timeout.connect(self.__onSuggestionTimeout)
245                 self.__inputTimer = eTimer()
246                 self.__inputTimer_conn = self.__inputTimer.timeout.connect(self.onInputTimer)
247                 self.__statusTimer = eTimer()
248                 self.__statusTimer_conn = self.__statusTimer.timeout.connect(self.__hideStatus)
249
250                 self.__scrollMode = False
251                 self.__zoomMode = False
252                 self.__isInput = False
253                 self.__hasSslErrors = False
254                 self.__handledUnsupportedContent = False
255                 self.__currentPEM = None
256                 self.__currentUser = None
257                 self.__currentPass = None
258                 self.__currentRealm = None
259                 self.__keyboardMode = eRCInput.getInstance().getKeyboardMode()
260
261                 self.onFirstExecBegin.append(self.__onFirstExecBegin)
262                 self.onExecEnd = []
263                 self.onPageLoadFinished = []
264                 self.onActionTv = []
265                 self.onActionRecord = []
266                 self.onUrlChanged = []
267
268                 self["helpableactions"] = HelpableActionMap(self, "BrowserActions",
269                 {
270                         "exit": (self.__actionExit, _("Close the browser")),
271                         "url": (self.__actionEnterUrl, _("Enter web address or search term")),
272                         "back": self.__actionBack,
273                         "forward": self.__actionForward,
274                         "left": self.__actionLeft,
275                         "right": self.__actionRight,
276                         "up": self.__actionUp,
277                         "down": self.__actionDown,
278                         "pageUp": (self.__actionPageUp, _("Page Up / Zoom in")),
279                         "pageDown": (self.__actionPageDown, _("Page Down / Zoom out")),
280                         "seekBack": boundFunction(self.__actionNavigate, eWebView.navMediaRewind),
281                         "seekFwd": boundFunction(self.__actionNavigate, eWebView.navMediaFastForward),
282                         "tab": (boundFunction(self.__actionNavigate, eWebView.navTab), _("Tab")),
283                         "backspace": (self.__actionBackspace, _("Backspace / Navigate back")),
284                         "backtab": boundFunction(self.__actionNavigate, eWebView.navBacktab),
285                         "delete": (self.__actionDelete, _("Delete / Navigate forward")),
286                         "ascii": self.__actionAscii,
287                         "text" : (self.__actionVirtualAscii, _("Open Virtual Keyboard")),
288                         "ok" : self.__actionOk,
289                         "enter" : self.__actionEnter,
290                         "menu" : (self.__actionMenu, _("Menu")),
291                         "fullscreen" : self.__actionFullscreen,
292                         "play" : self.__actionPlay,
293                         "pause" : self.__actionPause,
294                         "playpause" : self.__actionPlayPause,
295                         "stop" : self.actionStop,
296                         "tv" : self.__actionTv,
297                         "record" : self.__actionRecord,
298                 }, -2)
299
300                 self["coloractions"] = ActionMap(["ColorActions"],
301                 {
302                         "red" : self.__actionRed,
303                         "green" : self.__actionGreen,
304                         "yellow" : self.__actionYellow,
305                         "blue" : self.__actionBlue,
306                 })
307
308                 self["numberactions"] = NumberActionMap(["NumberActions"],
309                 {
310                         "1": self.keyNumberGlobal,
311                         "2": self.keyNumberGlobal,
312                         "3": self.keyNumberGlobal,
313                         "4": self.keyNumberGlobal,
314                         "5": self.keyNumberGlobal,
315                         "6": self.keyNumberGlobal,
316                         "7": self.keyNumberGlobal,
317                         "8": self.keyNumberGlobal,
318                         "9": self.keyNumberGlobal,
319                         "0": self.keyNumberGlobal
320                 })
321
322                 self._mediaProxy = WebMediaPlayerProxy.register(self)
323                 Log.w(self._mediaProxy)
324                 self._startService = self.session.nav.getCurrentServiceReference()
325                 self._serviceRestoreTimer = eTimer()
326                 self._serviceRestoreTimer_conn = self._serviceRestoreTimer.timeout.connect(self._onRestoreService)
327                 self.onClose.append(self.__onClose)
328
329 #       WebMediaPlayerProxy APIs
330         def playStream(self, ref):
331                 self._serviceRestoreTimer.stop()
332                 ref.setUserAgent(cvar.hbbtvUserAgent)
333                 self.session.nav.playService(ref)
334
335         def stopStream(self):
336                 self.session.nav.stopService()
337                 self._serviceRestoreTimer.startLongTimer(1)
338
339         def _onRestoreService(self):
340                 if self._startService:
341                         self.session.nav.playService(self._startService)
342
343         def __onClose(self):
344                 self._onRestoreService()
345                 WebMediaPlayerProxy.unregister(self)
346                 self.resetVideoWindow()
347
348         def ignoreSource(self, source):
349                 # its not needed to create the canvas when this is a Hbbtv Browser
350                 # this saves a lot of accel memory...
351                 return source == "canvas" and self.__isHbbtv
352
353         def execEnd(self):
354                 Screen.execEnd(self)
355                 for fnc in self.onExecEnd:
356                         fnc()
357
358         def scaleRect(self, rect, callback):
359                 self.webnavigation.scale(rect, callback)
360
361         def setBackgroundTransparent(self, enabled):
362                 self.webnavigation.setBackgroundTransparent(enabled)
363
364         def setHbbtv(self, enabled):
365                 self.webnavigation.setHbbtv(enabled)
366
367         def __setKeyBoardModeAscii(self):
368                 eRCInput.getInstance().setKeyboardMode(eRCInput.kmAscii)
369
370         def __unsetKeyBoardModeAscii(self):
371                 eRCInput.getInstance().setKeyboardMode(self.__keyboardMode)
372
373         def __setStatus(self, text):
374                 print "[Browser].__setStatus"
375                 self.statuslabel.setText(text)
376                 self.statuslabel.show()
377                 self.__statusTimer.startLongTimer(3)
378
379         def __hideStatus(self):
380                 self["statuslabel"].hide()
381                 self.__statusTimer.stop()
382
383         def __setMouseMode(self, enabled):
384                 self.__mouseMode = enabled
385                 if enabled:
386                         self.__setCursor()
387                         self["cursor"].show()
388                         self["red"].setText("Mouse On")
389                         self.__clearCanvas()
390                 else:
391                         self["cursor"].hide()
392                         self["red"].setText("Mouse Off")
393
394         def __actionExit(self):
395                 if self.__isHbbtv:
396                         self.__actionExitCB(True)
397                         return
398                 self.session.openWithCallback(self.__actionExitCB, MessageBox, _("Do you really want to exit the browser?"), type = MessageBox.TYPE_YESNO)
399
400         def __actionExitCB(self, confirmed):
401                 if confirmed:
402                         self.__urlSuggestionTimer.stop()
403                         self.__inputTimer.stop()
404                         if not self.__isHbbtv:
405                                 config.plugins.WebBrowser.lastvisited.value = self.webnavigation.url
406                                 config.plugins.WebBrowser.lastvisited.save()
407                         self.__persistCookies()
408                         self.close()
409
410         def __onFirstExecBegin(self):
411                 self["cursor"].instance.setPixmapFromFile(resolveFilename(SCOPE_PLUGINS, "Extensions/Browser/cursor.png"))
412                 self.__setCursor()
413                 self.__setMouseMode(self.__mouseMode)
414
415                 #enable/disable transparent background
416                 self.setHbbtv(self.__isHbbtv)
417                 if not self.__isHbbtv and self.__isTransparent:
418                         self.setBackgroundTransparent(self.__isTransparent)
419                 #set Accept-Language header to current language
420                 lang = '-'.join(language.getLanguage().split('_'))
421                 self.webnavigation.setAcceptLanguage(lang)
422                 self.__registerCallbacks()
423                 self.__urlList.hide()
424                 self.__restoreCookies()
425                 if self.__fullscreen:
426                         self.__showHideBars(False)
427                         self.__showHideButtonBar(False)
428                 if self.__startUrl is None:
429                         if config.plugins.WebBrowser.startPage.value == "home":
430                                 self.__actionHome()
431                         else:
432                                 self.setUrl(config.plugins.WebBrowser.lastvisited.value)
433                 else:
434                         self.setUrl(self.__startUrl)
435
436         def __clearCanvas(self):
437                 size = getDesktop(0).size()
438                 self.canvas.fill(0, 0, size.width(), size.height(), 0xFF000000)
439                 self.canvas.flush()
440
441         def __onStoragePathChanged(self):
442                 if config.plugins.WebBrowser.storage.enabled.value:
443                         self.webnavigation.enablePersistentStorage(config.plugins.WebBrowser.storage.path.value)
444
445         def __onMicroFocusChanged(self, x, y, w, h, isInput):
446                 if not self.__isHbbtv and not self.__mouseMode:
447                         self.__cursorPos.setX(x)
448                         self.__cursorPos.setY(y)
449
450                         if self.__isInput and not isInput:
451                                 self.__unsetKeyBoardModeAscii()
452
453                         self.__isInput = isInput
454                         if self.__isInput:
455                                 self.setKeyboardModeAscii()
456
457                         self.__clearCanvas()
458                         lw = 4 #line width
459                         y = y
460                         x = x - lw
461                         w = w + lw
462                         blo = y + h #bottom line offset
463                         color =0xFF9900 #line color
464
465                         self.canvas.fill(x, y, lw, h, color)#left line
466                         self.canvas.fill(x, blo, w, lw, color)#bottom line
467                         self.canvas.flush()#Done -> Flush
468
469         def __onSuggestionTimeout(self):
470                 needle = self.urlInput.getText()
471                 if needle != "":
472                         list = self.__db.suggsetUrls(self.urlInput.getText())
473                         list.insert(0, needle)
474                         list.insert(1, _("Search for '%s'") %needle)
475                         self.__urlList.setList(list)
476                         self.__urlList.moveToIndex(0)
477                         self.__urlList.show()
478                 else:
479                         self.__urlList.hide()
480
481         def __onAuthRequired(self, token, user, password, realm):
482                 if self.__currentUser != None and self.__currentPassword != None and realm == self.__currentRealm:
483                         d = eDict()
484                         d.setString("user", self.__currentUser)
485                         d.setString("password", self.__currentPassword)
486                         self.webnavigation.setDict(token, d)
487                         self.__currentUser = None
488                         self.__currentPassword = None
489                         self.__currentRealm = None
490                 else:
491                         msgbox = self.session.openWithCallback(self.__onAuthRequiredCB, HttpAuthenticationDialog, user, password, realm)
492                         msgbox.setTitle(_("Authentication required"))
493
494         def __onAuthRequiredCB(self, dict):
495                 if dict != None:
496                         self.__currentUser = dict["user"]
497                         self.__currentPassword = dict["password"]
498                         self.__currentRealm = dict["realm"]
499                         self.setUrl(self.webnavigation.url)
500
501         def __onProxyAuthRequired(self, token, user, password, realm):
502                 self.onAuthRequired(token, user, password, realm)
503
504         def __onDownloadRequested(self, url):
505                 print "[Browser].__onDownloadRequested '%s'" %(url)
506                 filename = url_unquote(url).split("/")[-1]
507                 localfile = "%s/%s" %(config.plugins.WebBrowser.downloadpath.value, filename)
508                 downloadManager.AddJob(DownloadJob(url, localfile, filename))
509                 self.session.open(MessageBox, _("Download started..."), type = MessageBox.TYPE_INFO, timeout = 3)
510
511         def __onUnsupportedContent(self, url, contentType):
512                 print "[Browser].__onUnsupportedContent 'url=%s; contentType='%s'" %(url, contentType)
513                 self.__handledUnsupportedContent = True
514                 if contentType.startswith("video") or contentType.startswith("audio"):
515                         list = [( _("Download"), ("download", url) ),
516                                         ( _("Play"), ("play", url) )]
517                         self.session.openWithCallback(self.__onUnsupportedContentCB, ChoiceBox, title=_("You've selected a media file what do you want to do?"), list = list)
518                 else:
519                         self.__onDownloadRequested(url)
520
521         def __onUnsupportedContentCB(self, answer):
522                 if answer != None:
523                         answer = answer and answer[1]
524                         if answer[0] == "download":
525                                 self.__onDownloadRequested(answer[1])
526                         else:
527                                 service = eServiceReference(eServiceReference.idGST,0,answer[1])
528                                 self.session.open(MoviePlayer, service)
529
530         def __actionMenu(self):
531                 if self.__isHbbtv:
532                         if self.__hbbtvMenu is not None:
533                                 self.__hbbtvMenu()
534                         return
535
536                 self.__urlSuggestionTimer.stop()
537                 self.__inputTimer.stop()
538                 self.__urlList.hide()
539                 self.__persistCookies()
540                 self.session.openWithCallback(self.__menuCB, BrowserMenu, self.pageTitle, self.webnavigation.url)
541
542         def __menuCB(self, actions = None):
543                 if actions != None:
544                         for action in actions:
545                                 if action[0] == BrowserMenu.ACTION_BOOKMARK:
546                                         self.setUrl(action[1])
547                                 elif action[0] == BrowserMenu.ACTION_COOKIES:
548                                         self.__restoreCookies()
549                                 elif action[0] == BrowserMenu.ACTION_STORAGE_PATH:
550                                         self.__onStoragePathChanged()
551
552                 if self.skinName == "BrowserFullscreen" and not config.plugins.WebBrowser.fullscreen.value:
553                         self.__requireRestart()
554                 if self.skinName != "BrowserFullscreen" and config.plugins.WebBrowser.fullscreen.value:
555                         self.__requireRestart()
556
557         def __requireRestart(self):
558                 text = _("Some of the configuration changes require a restart of the Browser.\nDo you want to restart the Browser now?")
559                 msgbox = self.session.openWithCallback(self.__requireRestartCB, MessageBox, text, type = MessageBox.TYPE_YESNO)
560                 msgbox.setTitle(_("Restart required"))
561
562         def __requireRestartCB(self, confirmed):
563                 if confirmed:
564                         self.close(self.session, True, self.webnavigation.url)
565
566         def __enableUrlInput(self):
567                 self.urlInputEnabled = True
568                 self.urlInput.markAll()
569                 self.__setKeyBoardModeAscii()
570                 if self.__fullscreen:
571                         self.__showHideBars()
572
573         def __disableUrlInput(self, hide = True):
574                 self.urlInputEnabled = False
575                 self.__urlSuggestionTimer.stop()
576                 self.__urlList.hide()
577                 self.urlInput.markNone()
578                 if not self.__isInput:
579                         self.__unsetKeyBoardModeAscii()
580                 if self.__fullscreen and hide:
581                         self.__showHideBars(False)
582
583         def __showHideButtonBar(self, visible = True):
584                 if visible:
585                         self["_buttonBar"].show()
586                 else:
587                         self["_buttonBar"].hide()
588                         
589                 used_buttons = ("button_red_off", "button_green_off", "button_yellow_off",
590                         "button_blue_off", "button_red", "button_yellow", "button_blue")
591                 for button in used_buttons:
592                         self[button].setBoolean(visible)
593                 #disable green
594                 self["button_green"].setBoolean(False)
595
596         def __showHideBars(self, visible = True):
597                 if self.__fullscreen:
598                         if visible:
599                                 self.urlInput.show()
600                         else:
601                                 self.urlInput.hide()
602
603                         if not self.__isHbbtv:
604                                 self.__showHideButtonBar(visible)
605
606         def __registerCallbacks(self):
607                 print "[Browser].__registerCallbacks"
608                 self.webnavigation.onUrlChanged.append(self.__onUrlChanged)
609                 self.webnavigation.onTitleChanged.append(self.__onTitleChanged)
610                 self.webnavigation.onLoadProgress.append(self.__onLoadProgress)
611                 self.webnavigation.onLoadFinished.append(self.__onLoadFinished)
612                 self.webnavigation.onDownloadRequested.append(self.__onDownloadRequested)
613                 self.webnavigation.onUnsupportedContent.append(self.__onUnsupportedContent)
614                 self.webnavigation.onMicroFocusChanged.append(self.__onMicroFocusChanged)
615                 self.webnavigation.onWindowRequested.append(self.__onWindowRequested)
616                 self.webnavigation.onSslErrors.append(self.__onSslErrors)
617                 self.webnavigation.onAuthRequired.append(self.__onAuthRequired)
618                 self.webnavigation.onProxyAuthRequired.append(self.__onProxyAuthRequired)
619
620         def __actionOk(self):
621                 if self.textInput.visible:
622                         self.onInputTimer()
623                 elif self.urlInputEnabled:
624                         if self.__urlList.visible and self.__urlList.getSelectedIndex() > 0:
625                                 if self.__urlList.getSelectedIndex() == 1:
626                                         self.__searchUsingCurrentUrlValue()
627                                         self.__disableUrlInput(False)
628                                 else:
629                                         self.urlInput.setText(self.__urlList.getCurrent())
630                                         self.urlInput.end()
631                                         self.__urlList.hide()
632                         else:
633                                 self.setUrl(self.urlInput.getText())
634                                 self.__isInput = False
635                                 self.__disableUrlInput(False)
636
637                 else:
638                         if self.__mouseMode:
639                                 self.webnavigation.leftClick(self.__cursorPos)
640                         else:
641                                 self.__actionNavigate(eWebView.navOpenLink)
642
643         def __actionEnter(self):
644                 if self.textInput.visible or self.urlInputEnabled:
645                         self.__actionOk()
646                 else:
647                         if self.__mouseMode:
648                                 self.webnavigation.leftClick(self.__cursorPos)
649                         else:
650                                 self.__actionNavigate(eWebView.navOpenLink)
651
652         def __actionPlay(self):
653                 self.__actionNavigate(eWebView.navMediaPlay)
654
655         def __actionPause(self):
656                 self.__actionNavigate(eWebView.navMediaPause)
657
658         def __actionPlayPause(self):
659                 self.__actionNavigate(eWebView.navMediaPlay) #playpause doesn't work anywhere, but play does (HBBTV)
660
661         def actionStop(self):
662                 self.__actionNavigate(eWebView.navMediaStop)
663
664         def __actionBack(self):
665                 if self.__isHbbtv:
666                         self.__actionNavigate(eWebView.navBack)
667                 else:
668                         self.__actionNavigate(eWebView.navBackExplicit)
669
670         def __actionForward(self):
671                 if self.__isHbbtv:
672                         self.__actionNavigate(eWebView.navForward)
673                 else:
674                         self.__actionNavigate(eWebView.navForwardExplicit)
675
676         def __actionBackspace(self):
677                 if self.textInput.visible:
678                         self.restartTimer()
679                         self.textInput.deleteBackward()
680                 elif self.urlInputEnabled:
681                         self.urlInput.deleteBackward()
682                         self.__onUrlInputChanged()
683                 else:
684                         if self.__isInput:
685                                 self.__actionNavigate(eWebView.navBackspace)
686                         else:
687                                 self.__actionBack()
688
689         def __actionDelete(self):
690                 if self.textInput.visible:
691                         self.restartTimer()
692                         self.textInput.delete()
693                 elif self.urlInputEnabled:
694                         self.urlInput.delete()
695                         self.__onUrlInputChanged()
696                 else:
697                         if self.__isInput:
698                                 self.__actionNavigate(eWebView.navDelete)
699                         else:
700                                 self.__actionForward()
701
702         def __moveCursor(self, x=0, y=0):
703                 if x != 0 or y != 0:
704                         wSize = self.webnavigation.size
705                         #horizontal
706                         if x != 0:
707                                 x = self.__cursorPos.x() + x
708                                 w = wSize.width()
709                                 if x <= 2:
710                                         x = 2
711                                         self.__scroll(0-int(config.plugins.WebBrowser.scrollOffset.value), 0)
712                                 elif x >= w-2:
713                                         x = w-2
714                                         self.__scroll(int(config.plugins.WebBrowser.scrollOffset.value), 0)
715                                 self.__cursorPos.setX(x)
716                         #vertical
717                         if y != 0:
718                                 y = self.__cursorPos.y() + y
719                                 h = wSize.height()
720                                 if y < 2:
721                                         y = 2
722                                         self.__scroll(0, 0-int(config.plugins.WebBrowser.scrollOffset.value))
723                                 elif y > h-2:
724                                         y = h-2
725                                         self.__scroll(0, int(config.plugins.WebBrowser.scrollOffset.value))
726                                 self.__cursorPos.setY(y)
727                 self.__setCursor()
728
729         def __setCursor(self):
730                 wPos = self.webnavigation.position
731                 relPos = None
732                 if wPos.x() > 0 or wPos.y() > 0:
733                         relPos = ePoint(self.__cursorPos.x() + wPos.x(), self.__cursorPos.y() + wPos.y())
734                 else:
735                         relPos = self.__cursorPos
736                 self["cursor"].move(relPos)
737
738         def __actionLeft(self):
739                 if self.urlInputEnabled:
740                         self.urlInput.left()
741                 elif self.__scrollMode:
742                         self.__scroll(0-int(config.plugins.WebBrowser.scrollOffset.value), 0)
743                 elif self.textInput.visible:
744                         self.restartTimer()
745                         self.textInput.left()
746                 else:
747                         if self.__mouseMode:
748                                 self.__moveCursor(x=-10)
749                         else:
750                                 self.__actionNavigate(eWebView.navLeft)
751
752         def __actionRight(self):
753                 if self.urlInputEnabled:
754                         self.urlInput.right()
755                 elif self.__scrollMode:
756                         self.__scroll(int(config.plugins.WebBrowser.scrollOffset.value), 0)
757                 elif self.textInput.visible:
758                         self.restartTimer()
759                         self.textInput.right()
760                 else:
761                         if self.__mouseMode:
762                                 self.__moveCursor(x=10)
763                         else:
764                                 self.__actionNavigate(eWebView.navRight)
765
766         def __actionUp(self):
767                 if self.urlInputEnabled:
768                         if self.__urlList.visible:
769                                 self.__urlList.up()
770                 elif self.__scrollMode:
771                         self.__scroll(0, 0-int(config.plugins.WebBrowser.scrollOffset.value))
772                 elif self.textInput.visible:
773                         self.restartTimer()
774                         self.textInput.up()
775                 else:
776                         if self.__mouseMode:
777                                 self.__moveCursor(y=-10)
778                         else:
779                                 self.__actionNavigate(eWebView.navUp)
780
781         def __actionDown(self):
782                 if self.urlInputEnabled:
783                         if self.__urlList.visible:
784                                 self.__urlList.down()
785                         #else:
786                         #       self.urlInput.down()
787                 elif self.__scrollMode:
788                         self.__scroll(0, int(config.plugins.WebBrowser.scrollOffset.value))
789                 elif self.textInput.visible:
790                         self.restartTimer()
791                         self.textInput.down()
792                 else:
793                         if self.__mouseMode:
794                                 self.__moveCursor(y=10)
795                         else:
796                                 self.__actionNavigate(eWebView.navDown)
797
798         def __actionTv(self):
799                 for fnc in self.onActionTv:
800                         if fnc() is True: #Function told us to stop handling
801                                 return
802
803         def __actionRecord(self):
804                 for fnc in self.onActionRecord:
805                         if fnc() is True: #Function told us to stop handling
806                                 return
807
808         def __scroll(self, dx, dy):
809                 self.webnavigation.scroll(dx, dy)
810
811         def __actionRed(self):
812                 if self.__isHbbtv:
813                         self.__actionNavigate(eWebView.navRed)
814                 else:
815                         self.__setMouseMode(not self.__mouseMode)
816
817         def __actionGreen(self):
818                 self.__actionNavigate(eWebView.navGreen)
819
820         def __actionYellow(self):
821                 if self.__isHbbtv:
822                         self.__actionNavigate(eWebView.navYellow)
823                 else:
824                         self.__scrollMode = not self.__scrollMode
825                         enDis = _("disabled")
826                         mode = _("Navigation")
827                         if self.__scrollMode:
828                                 enDis = _("enabled")
829                                 mode = _("Scrolling")
830                         text = _("Scroll mode is now %s") %enDis
831                         self["yellow"].setText(mode)
832                         self.__setStatus(text)
833
834         def __actionBlue(self):
835                 if self.__isHbbtv:
836                         self.__actionNavigate(eWebView.navBlue)
837                 else:
838                         self.__zoomMode = not self.__zoomMode
839                         enDis = _("disabled")
840                         mode = _("Pagescroll")
841                         if self.__zoomMode:
842                                 enDis = _("enabled")
843                                 mode = _("Zoom")
844                         text = _("Zoom mode is now %s") %enDis
845                         self["blue"].setText(mode)
846                         self.__setStatus(text)
847
848         def restartTimer(self):
849                 self.__inputTimer.stop()
850                 self.__inputTimer.startLongTimer(5)
851
852         def __onUrlChanged(self, url):
853                 if url != None:
854                         self.__clearCanvas()
855                         self.urlInput.setText(url)
856                         self.urlInput.markNone()
857                         if self.__fullscreen and not self.__isHbbtv:
858                                 self.__showHideBars()
859
860                         for fnc in self.onUrlChanged:
861                                 fnc(url)
862
863         def __onTitleChanged(self, title):
864                 if title != None:
865                         self.pageTitle = title
866                         self.setTitle("Web Browser - %s" %self.pageTitle)
867
868         def __onLoadProgress(self, progress):
869                 print "[Browser].__onLoadProgress %s" %progress
870                 if(progress < 100):
871                         self["loading"].show()
872                         self["loading"].setText(_("Loading... %s%%" %progress))
873                 else:
874                         self["loading"].hide()
875                         self["loading"].setText("")
876
877         def __onLoadFinished(self, val):
878                 print "[Browser].__onLoadFinished %s" %val
879                 if val == 1:
880                         if not self.__isHbbtv:
881                                 self.__db.addToHistory(HistoryItem(title = self.pageTitle, url = self.webnavigation.url));
882                         if self.__fullscreen:
883                                 self.__showHideBars(False)
884                 else:
885                         if not self.__hasSslErrors and not self.__handledUnsupportedContent:
886                                 self.__handledUnsupportedContent = False
887                 for fnc in self.onPageLoadFinished:
888                         fnc()
889
890         def __searchUsingCurrentUrlValue(self):
891                 needle = self.urlInput.getText()
892                 if needle != "":
893                         needle = needle.replace("http://", "").replace("https://", "").replace("ftp://", "")
894                         self.__onSearchRequested(needle)
895
896         def __onSearchRequested(self, needle):
897                 if needle != "" and needle != None:
898                         needle = url_quote_plus(needle)
899                         url = "%s%s" %(config.plugins.WebBrowser.searchProvider.value, needle)
900                         self.setUrl(url)
901
902         def __onWindowRequested(self, url):
903                 print "[Browser].__onWindowRequested :: '%s'" %url
904                 self.setUrl(url)
905
906         def __onSslErrors(self, token, errors, pems):
907                 print "[Browser].__onSslErrors :: 'token='%s', errors='%s'" %(token, errors)
908                 self.__hasSslErrors = True
909                 cnt = 0
910                 perrors = {}
911                 pems = list(pems)
912                 pems.sort()
913                 for bytes in pems:
914                         pem = "".join(map(chr, bytes))
915                         if pem.strip() != "":
916                                 messages = perrors.get(pem, [])
917                                 messages.append(errors[cnt])
918                                 perrors[pem] = messages
919                                 cnt += 1
920
921                 for pem, messages in perrors.iteritems():
922                         cert = Certificate(-1, self.__getCurrentNetloc(), pem)
923                         checkVal = self.__db.checkCert( cert ) == BrowserDB.CERT_UNKOWN
924                         if checkVal == BrowserDB.CERT_OK:
925                                 print "[Browser].__onSslErrors :: netloc/pem combination known and trusted!"
926                                 dict = eDict()
927                                 dict.setFlag("ignore")
928                                 self.webnavigation.setDict(token, dict)
929                         else:
930                                 print "[Browser].__onSslErrors :: netloc/pem combination NOT known and/or trusted!"
931                                 self.__currentPEM = pem
932
933                                 errorstr = ""
934                                 for m in messages:
935                                         errorstr = "%s\n%s" %(m, errorstr)
936
937                                 text = ""
938                                 if checkVal == BrowserDB.CERT_UNKOWN:
939                                         text = _("A certificate for the desired secure connection has the following errors:\n%s\nDo you want to add an exception for this certificate and accept connections to this host anyways?") %errorstr
940                                 elif checkVal == BrowserDB.CERT_CHANGED:
941                                         text = _("ATTENTION!\nPotential security breach detected!\nA certificate for the desired secure connection has CHANGED!\nIn addition it has the following errors:\n%s\nDo you want to add an exception for this certificate and accept connections to this host anyways?") %errorstr
942                                 msgbox = self.session.openWithCallback( self.__onSslErrorCB, MessageBox, text, type = MessageBox.TYPE_YESNO)
943                                 msgbox.setTitle(_("Certificate errors!"))
944
945         def __onSslErrorCB(self, confirmed):
946                 self.__hasSslErrors = False
947                 if confirmed:
948                         print "[Browser].__onSslErrorCB :: loc='%s', PEM='%s'" %(self.__getCurrentNetloc(), self.__currentPEM)
949                         self.__db.addCert( Certificate(-1, self.__getCurrentNetloc(), self.__currentPEM) )
950                         self.setUrl(self.webnavigation.url)
951
952         def __getCurrentNetloc(self):
953                 return self.__getNetloc(self.webnavigation.url)
954
955         def __getNetloc(self, url):
956                 return urlparse(url).netloc
957
958         def __actionHome(self):
959                 self.setUrl(config.plugins.WebBrowser.home.value)
960
961         def __actionEnterUrl(self):
962                 if self.urlInputEnabled:
963                         self.__disableUrlInput()
964                 else:
965                         self.__enableUrlInput()
966
967         def setUrl(self, url):
968                 if url != None:
969                         if url.find("://") == -1:
970                                 url = "http://%s" %url
971                         if url:
972                                 self.webnavigation.url = url
973
974         def getUserAgent(self):
975                 return self.webnavigation.useragent
976
977         def setUserAgent(self, useragent):
978                 self.webnavigation.useragent = useragent
979
980         def __actionAscii(self):
981                 if self.urlInputEnabled:
982                         self.urlInput.handleAscii(getPrevAsciiCode())
983                         self.__onUrlInputChanged()
984                 elif self.__isInput:
985                         self.webnavigation.changed(WebNavigation.COMMAND_ASCII_INPUT, getPrevAsciiCode())
986                 else:
987                         self.__actionNavigateNumber(chr(getPrevAsciiCode()))
988
989         def __actionNavigateNumber(self, char):
990                 print "[Browser].__actionNavigateNumber %s" %char
991                 nav = { '0' : eWebView.nav0,
992                                 '1' : eWebView.nav1,
993                                 '2' : eWebView.nav2,
994                                 '3' : eWebView.nav3,
995                                 '4' : eWebView.nav4,
996                                 '5' : eWebView.nav5,
997                                 '6' : eWebView.nav6,
998                                 '7' : eWebView.nav7,
999                                 '8' : eWebView.nav8,
1000                                 '9' : eWebView.nav9,
1001                                 }
1002
1003                 action = nav.get(str(char), None)
1004                 if action != None:
1005                         if self.__mouseMode:
1006                                 self.__actionMouseJump(char)
1007                         else:
1008                                 self.__actionNavigate(action)
1009
1010         def __actionMouseJump(self, char):
1011                 size = self.webnavigation.size
1012                 off = 100 #offset
1013
1014                 hcenter = size.width() / 2
1015                 vcenter = size.height() / 2
1016
1017                 roff = size.width() - off #right offset
1018                 boff = size.height() - off # bottom offset
1019
1020                 offsets = {
1021                         '1' : [off,off],
1022                         '2' : [hcenter, off],
1023                         '3' : [roff, off],
1024                         '4' : [off, vcenter],
1025                         '5' : [hcenter, vcenter],
1026                         '6' : [roff, vcenter],
1027                         '7' : [off, boff],
1028                         '8' : [hcenter, boff],
1029                         '9' : [roff, boff],
1030                         }
1031                 offset = offsets.get(str(char), None)
1032                 if offset:
1033                         self.__cursorPos.setX(offset[0])
1034                         self.__cursorPos.setY(offset[1])
1035                         self.__setCursor()
1036
1037         def __actionVirtualAscii(self):
1038                 self.session.openWithCallback(self.sendTextAsAscii, VirtualKeyBoard, title="Browser Input")
1039
1040         def __actionPageUp(self):
1041                 if self.__zoomMode:
1042                         self.webnavigation.zoomFactor += 0.1
1043                 else:
1044                         self.__actionNavigate(eWebView.navPageUp)
1045
1046         def __actionPageDown(self):
1047                 if self.__zoomMode:
1048                         self.webnavigation.zoomFactor -= 0.1
1049                 else:
1050                         self.__actionNavigate(eWebView.navPageDown)
1051
1052         def sendTextAsAscii(self, text):
1053                 if text != None:
1054                         for c in text:
1055                                 self.webnavigation.changed(WebNavigation.COMMAND_ASCII_INPUT, ord(c))
1056
1057         def __actionNavigate(self, param):
1058                 if not self.urlInputEnabled and not self.textInput.visible:
1059                         self.webnavigation.changed(WebNavigation.COMMAND_NAVIGATE, param)
1060
1061         def keyNumberGlobal(self, number):
1062                 if self.urlInputEnabled:
1063                         self.urlInput.number(number)
1064                         self.__onUrlInputChanged()
1065                 elif self.__isInput:
1066                         self.textInput.show()
1067                         self.restartTimer()
1068                         self.textInput.number(number)
1069                 else:
1070                         self.__actionNavigateNumber(number)
1071
1072         def __onUrlInputChanged(self):
1073                 if not self.__urlSuggestionTimer.isActive():
1074                         self.__urlSuggestionTimer.startLongTimer(1)
1075
1076         def onInputTimer(self):
1077                 self.__inputTimer.stop()
1078                 self.textInput.hide()
1079                 text = self.textInput.getText()
1080                 self.textInput.setText("")
1081                 if text != "" and text != None:
1082                         self.sendTextAsAscii(text)
1083
1084         def __actionFullscreen(self):
1085                 self.webnavigation.size = (self.width, self.height)
1086                 self.webnavigation.position = (0, 0)
1087
1088         def __restoreCookies(self):
1089                 cookies = self.__db.getCookies()
1090                 print "[Browser].__restoreCookies ::: restoring %s cookies" %len(cookies)
1091                 rawCookies = []
1092                 for cookie in cookies:
1093                         rawCookies.append( b64encode(cookie.raw) )
1094                 self.webnavigation.cookies = ','.join(rawCookies)
1095
1096         def __persistCookies(self):
1097                 rawCookies = self.webnavigation.cookies
1098                 if rawCookies.strip() != "":
1099                         rawCookies = rawCookies.split(",")
1100                         cookies = []
1101                         cookie = None
1102                         for rawCookie in rawCookies:
1103                                 cookie = Cookie.fromRawString(b64decode(rawCookie))
1104                                 if cookie != None:
1105                                         cookies.append( cookie )
1106                         print "[Browser].__persistCookies ::: persisting %s cookies" %len(cookies)
1107                         self.__db.persistCookies(cookies)
1108                 else:
1109                         print "[Browser].__persistCookies ::: NO cookies to be persisted"
1110
1111 #VIDEO 
1112         def showVideo(self):
1113                 if self._videoWindow != None:
1114                         self._videoWindow.show()
1115
1116         def hideVideo(self):
1117                 if self._videoWindow != None:
1118                         self._videoWindow.hide()
1119
1120         def _adjustVideoLimits(self, var, lower, upper):
1121                 var = int(var)
1122                 var = max(var, lower)
1123                 var = min(var, upper)
1124                 return var
1125
1126         def setVideoWindow(self, x, y, w, h):
1127                 w = self._adjustVideoLimits(w, 128, 1280)
1128                 h = self._adjustVideoLimits(h, 72, 720)
1129                 x = self._adjustVideoLimits(x, 0, 1280)
1130                 y = self._adjustVideoLimits(y, 0, 720)
1131
1132                 Log.i("x=%s, y=%s, w=%s, h=%s" % (x, y, w, h))
1133                 self.scaleRect(eRect(x, y, w, h), self._doSetVideoWindow)
1134
1135         def _doSetVideoWindow(self, rect):
1136                 Log.w("x=%s, y=%s, w=%s, h=%s" % (rect.x(), rect.y(), rect.width(), rect.height()))
1137                 if self._videoWindow == None:
1138                         self._videoWindow = self.session.instantiateDialog(BrowserVideoWindow, point=rect.topLeft(), size=rect.size(), zPosition=-1)
1139                 self._videoWindow.setRect(rect.topLeft(), rect.size())
1140                 self._videoWindow.show()
1141
1142         def resetVideoWindow(self):
1143                 if self._videoWindow:
1144                         self.session.deleteDialog(self._videoWindow)
1145                         self._videoWindow = None
1146
1147         def toggleVideoFullscreen(self):
1148                 if self._videoWindow:
1149                         if self._videoWindow.toggleFullscreen():
1150                                 self.hide()
1151                         else:
1152                                 self.show()
1153                         return True
1154
1155 class HttpAuthenticationDialog(Screen):
1156         skin = """
1157                 <screen position="center,center" size="600,120"  title="Authentication required">
1158                         <widget source="realm" render="Label" position="5,0" zPosition="1" size="590,25" font="Regular;22" halign="left" valign="bottom" backgroundColor="background" transparent="1" />
1159                         <widget source="userTitle" render="Label" position="5,30" zPosition="1" size="120,25" font="Regular;22" halign="right" valign="bottom" backgroundColor="background" transparent="1" />
1160                         <widget source="passwordTitle" render="Label" position="5,70" zPosition="1" size="120,25" font="Regular;22" halign="right" valign="bottom" backgroundColor="background" transparent="1" />
1161                         <widget name="user" position="130,30" size="420,25" font="Regular;22" halign="left" valign="bottom" backgroundColor="background" transparent="1"/>
1162                         <widget name="password" position="130,70" size="420,25" font="Regular;22" halign="left" valign="bottom" backgroundColor="background" transparent="1"/>
1163                         <widget name="userActive" position="560,30" zPosition="1" size="40,25" font="Regular;22" halign="right" valign="bottom" backgroundColor="background" transparent="1" />
1164                         <widget name="passwordActive" position="560,70" zPosition="1" size="40,25" font="Regular;22" halign="right" valign="bottom" backgroundColor="background" transparent="1" />
1165                 </screen>"""
1166
1167         def __init__(self, session, user = "", password = "", realm = ""):
1168                 Screen.__init__(self, session)
1169
1170                 self.user = user
1171                 self.password = password
1172                 self.realm = realm
1173
1174                 self["realm"] = StaticText(self.realm)
1175                 self["userTitle"] = StaticText(_("User:"))
1176                 self["passwordTitle"] = StaticText(_("Password:"))
1177
1178                 self["userActive"] = Label("<")
1179                 self["passwordActive"] = Label("<")
1180
1181                 self._inputFirst = EnhancedInput( self.user )
1182                 self["user"] = self._inputFirst
1183                 self._inputSecond = EnhancedInput( self.password, type = Input.PIN )
1184                 self["password"] = self._inputSecond
1185
1186                 self["actions"] = ActionMap(["SimpleEditorActions"],
1187                 {
1188                         "ok" : self.__ok,
1189                         "exit" : self.__cancel,
1190                         "up" : self.__up,
1191                         "down" : self.__down,
1192                         "left" : self.__left,
1193                         "right" : self.__right,
1194                         "ascii" : self.__ascii,
1195                         "delete" : self.__delete,
1196                         "backspace" : self.__backspace
1197                 })
1198                 self["numberactions"] = NumberActionMap(["NumberActions"],
1199                 {
1200                         "1": self.__keyNumberGlobal,
1201                         "2": self.__keyNumberGlobal,
1202                         "3": self.__keyNumberGlobal,
1203                         "4": self.__keyNumberGlobal,
1204                         "5": self.__keyNumberGlobal,
1205                         "6": self.__keyNumberGlobal,
1206                         "7": self.__keyNumberGlobal,
1207                         "8": self.__keyNumberGlobal,
1208                         "9": self.__keyNumberGlobal,
1209                         "0": self.__keyNumberGlobal
1210                 })
1211
1212                 self.userFocus = False
1213                 self.onShow.append(self.__toggleInput)
1214
1215         def __ok(self):
1216                 user = self._inputFirst.getText()
1217                 password = self._inputSecond.getText()
1218                 if user != None and password != None and user != "":
1219                         self.close( { "user" : user, "password" : password, "realm" : self.realm} )
1220                 else:
1221                         self.close(None)
1222
1223         def __cancel(self):
1224                 self.close(None)
1225
1226         def __up(self):
1227                 self.__toggleInput()
1228
1229         def __down(self):
1230                 self.__toggleInput()
1231
1232         def __toggleInput(self):
1233                 self.userFocus = not self.userFocus
1234                 if self.userFocus:
1235                         self["userActive"].show()
1236                         self._inputFirst.end()
1237                         self["passwordActive"].hide()
1238                         self._inputSecond.markNone()
1239                 else:
1240                         self["userActive"].hide()
1241                         self._inputFirst.markNone()
1242                         self["passwordActive"].show()
1243                         self._inputSecond.end()
1244
1245         def __left(self):
1246                 if self.userFocus:
1247                         self._inputFirst.left()
1248                 else:
1249                         self._inputSecond.left()
1250
1251         def __right(self):
1252                 if self.userFocus:
1253                         self._inputFirst.right()
1254                 else:
1255                         self._inputSecond.right()
1256
1257         def __delete(self):
1258                 if self.userFocus:
1259                         self._inputFirst.delete()
1260                 else:
1261                         self._inputSecond.delete()
1262
1263         def __backspace(self):
1264                 if self.userFocus:
1265                         self._inputFirst.deleteBackward()
1266                 else:
1267                         self._inputSecond.deleteBackward()
1268
1269         def __keyNumberGlobal(self, number):
1270                 if self.userFocus:
1271                         self._inputFirst.number(number)
1272                 else:
1273                         self._inputSecond.number(number)
1274
1275         def __ascii(self):
1276                 if self.userFocus:
1277                         self._inputFirst.handleAscii(getPrevAsciiCode())
1278                 else:
1279                         self._inputSecond.handleAscii(getPrevAsciiCode())