add license to python files
[enigma2-curlytx.git] / src / CurlyTx.py
1 # -*- coding: utf-8 -*-
2 # CurlyTx main window
3 # Copyright (C) 2011 Christian Weiske <cweiske@cweiske.de>
4 # License: GPLv3 or later
5
6 from . import _
7
8 from Screens.Screen import Screen
9 from Screens.HelpMenu import HelpableScreen
10 from Screens.MessageBox import MessageBox
11 from Components.Label import Label
12 from Components.ScrollLabel import ScrollLabel
13 from Components.ActionMap import ActionMap
14 from Components.Sources.StaticText import StaticText
15 from twisted.web import client
16 from twisted.web.client import _makeGetterFactory, HTTPClientFactory
17 from enigma import gFont
18
19 from . import config
20 from Components.config import config
21
22 class CurlyTx(Screen,HelpableScreen):
23     skin = """
24         <screen name="CurlyTx" position="center,center" size="560,400" title="CurlyTx" >
25           <ePixmap position="0,0" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />
26           <ePixmap position="140,0" size="140,40" pixmap="skin_default/buttons/green.png" transparent="1" alphatest="on" />
27           <ePixmap position="280,0" size="140,40" pixmap="skin_default/buttons/yellow.png" transparent="1" alphatest="on" />
28           <ePixmap position="420,0" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" />
29           <widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
30           <widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
31           <widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
32           <widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
33           <widget name="text" position="5,45" size="550,350" font="Console;20" />
34         </screen>"""
35
36     currentUrl = None
37     currentPage = None
38     currentFontSize = 20
39     httpGetterFactory = None
40     showingHeaders = False
41
42     def __init__(self, session, args = None):
43         #self.skin = CurlyTx.skin
44         Screen.__init__(self, session)
45         HelpableScreen.__init__(self)
46         #self.skinName = [ "CurlyTx", "Setup" ]
47
48         self["text"] = ScrollLabel("foo")
49
50         self["key_red"]    = StaticText(_("Settings"))
51         self["key_green"]  = StaticText(_("Reload"))
52         self["key_yellow"] = StaticText(_("Prev"))
53         self["key_blue"]   = StaticText(_("Next"))
54
55
56         self["actions"] = ActionMap(
57             ["WizardActions", "ColorActions", "InputActions", "InfobarEPGActions"], {
58                 "ok":   self.close,
59                 "back": self.close,
60                 "up":   self.pageUp,
61                 "down": self.pageDown,
62
63                 "red":    self.showSettings,
64                 "green":  self.reload,
65                 "yellow": self.prevPage,
66                 "blue":   self.nextPage,
67
68                 "showEventInfo": self.showHeader
69             }, -1)
70
71         self.loadHelp()
72         self.loadButtons()
73         self.loadUrl(config.plugins.CurlyTx.defaultPage.value)
74         self.onLayoutFinish.append(self.setTextFont)
75
76     def loadHelp(self):
77         self.helpList.append((
78                 self["actions"], "WizardActions",
79                 [("up", _("Scroll page contents up"))]))
80         self.helpList.append((
81                 self["actions"], "WizardActions",
82                 [("down", _("Scroll page contents down"))]))
83         self.helpList.append((
84                 self["actions"], "InfobarEPGActions",
85                 [("showEventInfo", _("Show HTTP response headers"))]))
86         self.helpList.append((
87                 self["actions"], "ColorActions",
88                 [("red", _("Show program settings"))]))
89         self.helpList.append((
90                 self["actions"], "ColorActions",
91                 [("green", _("Reload current page URL"))]))
92         self.helpList.append((
93                 self["actions"], "ColorActions",
94                 [("yellow", _("Switch to next configured page URL"))]))
95         self.helpList.append((
96                 self["actions"], "ColorActions",
97                 [("blue", _("Switch to previous configured page URL"))]))
98         self.helpList.append((
99                 self["actions"], "WizardActions",
100                 [("ok", _("Close window"))]))
101         self.helpList.append((
102                 self["actions"], "WizardActions",
103                 [("back", _("Close window"))]))
104         self.helpList.append((
105                 self["actions"], "HelpActions",
106                 [("displayHelp", _("Show this help screen"))]))
107
108     def loadButtons(self):
109         pageCount = len(config.plugins.CurlyTx.pages)
110         if pageCount == 0:
111             self["key_green"].setText("")
112             self["key_yellow"].setText("")
113             self["key_blue"].setText("")
114         elif pageCount == 1:
115             self["key_green"].setText(_("Reload"))
116             self["key_yellow"].setText("")
117             self["key_blue"].setText("")
118         else:
119             self["key_green"].setText(_("Reload"))
120             self["key_yellow"].setText(_("Prev"))
121             self["key_blue"].setText(_("Next"))
122
123     def pageUp(self):
124         self["text"].pageUp()
125
126     def pageDown(self):
127         self["text"].pageDown()
128
129     def prevPage(self):
130         if self.currentPage == None:
131             return
132
133         pageId = self.currentPage - 1
134         if pageId < 0:
135             pageId = len(config.plugins.CurlyTx.pages) - 1
136         self.loadUrl(pageId)
137
138     def nextPage(self):
139         if self.currentPage == None:
140             return
141
142         pageId = self.currentPage + 1
143         if pageId > len(config.plugins.CurlyTx.pages) - 1:
144             pageId = 0
145         self.loadUrl(pageId)
146
147     def reload(self):
148         if self.currentPage == None:
149             return
150
151         self.loadUrl(self.currentPage)
152
153     def loadUrl(self, pageId):
154         if pageId == None:
155             self.loadNoPage()
156             return
157
158         cfg = config.plugins.CurlyTx
159         pageCount = len(cfg.pages)
160         pageId = int(pageId)
161         if pageId > (pageCount - 1):
162             if len(cfg.pages) == 0:
163                 self.loadNoPage()
164             else:
165                 self["text"].setText(_("Invalid page") + " " + pageId);
166             return
167
168         url   = cfg.pages[pageId].uri.value
169         title = cfg.pages[pageId].title.value
170
171         if pageCount > 1:
172             title = "{0} [{1}/{2}]".format(title, pageId + 1, pageCount)
173
174         self.currentPage = pageId
175         self.currentUrl = url
176         self.currentFontSize = cfg.pages[pageId].fontSize.value
177
178         self.setTitle(title)
179         self.setTextFont()
180         self["text"].setText(_("Loading ...") + "\n" + url);
181
182         self.getPageWebClient(url).addCallback(self.urlLoaded).addErrback(self.urlFailed, url)
183
184     def setTextFont(self):
185         if self["text"].long_text is not None:
186             self["text"].long_text.setFont(gFont("Console", self.currentFontSize))
187
188     def urlLoaded(self, html):
189         self["text"].setText(html)
190
191     def urlFailed(self, error, url):
192         self["text"].setText(
193             _("Error fetching URL:") + "\n " + error.getErrorMessage()
194             + "\n\nURL: " + url
195             )
196
197     def loadNoPage(self):
198         self["text"].setText(_("Go and add a page in the settings"));
199
200     def showHeader(self):
201         if self.showingHeaders:
202             self["text"].setText(self.pageContent)
203             self.pageContent    = None
204             self.showingHeaders = False
205         else:
206             headers = _("HTTP response headers for") + "\n" + self.currentUrl + "\n\n"
207             for (k, v) in self.httpGetterFactory.response_headers.items():
208                 headers += k + ": " + ("\n" + k + ": ").join(v) + "\n"
209             self.pageContent = self["text"].getText()
210             self["text"].setText(headers)
211             self.showingHeaders = True
212
213     def showSettings(self):
214         from CurlyTxSettings import CurlyTxSettings
215         self.session.openWithCallback(self.onSettingsChanged, CurlyTxSettings)
216
217     def onSettingsChanged(self):
218         self.loadButtons()
219         if len(config.plugins.CurlyTx.pages) == 0:
220             self.currentPage = None
221             self.loadUrl(self.currentPage)
222         elif self.currentPage == None:
223             self.currentPage = 0
224             self.loadUrl(self.currentPage)
225
226
227     def getPageWebClient(self, url, contextFactory=None, *args, **kwargs):
228         """
229         Download a web page as a string.
230
231         COPY OF twisted.web.client.getPage to store the factory
232
233         Download a page. Return a deferred, which will callback with a
234         page (as a string) or errback with a description of the error.
235
236         See L{HTTPClientFactory} to see what extra arguments can be passed.
237         """
238         self.httpGetterFactory = _makeGetterFactory(
239             url,
240             HTTPClientFactory,
241             contextFactory=contextFactory,
242             *args, **kwargs)
243         return self.httpGetterFactory.deferred