~m-buck/+junk/gtk-desktop-info

« back to all changes in this revision

Viewing changes to plugin_null.py

  • Committer: Mark Buck (Kaivalagi)
  • Date: 2009-06-19 17:13:00 UTC
  • Revision ID: m_buck@hotmail.com-20090619171300-5cbhr90xwg62z27y
Added --backgroundblend and --backgroundcolour options for visual seperation of output from wallpaper if required, Fixed song length output in the rhythmbox plugin when songs are an hour long or more, Added copy option to right click, enabling the copying of html content to the clipboard for testing, Moved common functions into a plugin_common module

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
#
7
7
#  Author: Kaivalagi
8
8
# Created: 23/11/2008
9
 
from htmlentitydefs import name2codepoint, codepoint2name
10
9
from optparse import OptionParser
11
 
import traceback
 
10
from plugin_common import getTypedValue
12
11
import codecs
 
12
import fileinput
 
13
import logging
13
14
import os
 
15
import re
14
16
import shutil
15
 
import re
16
 
import logging
17
 
import fileinput
 
17
import traceback
18
18
 
19
19
app_name = "gtk-desktop-info"
20
20
app_path = os.path.dirname(os.path.abspath(__file__))
23
23
class NullConfig:
24
24
    HEADERTEMPLATE = None
25
25
    TEMPLATE = None
26
 
    
 
26
 
27
27
class Output:
28
 
    
 
28
 
29
29
    options = None
30
30
    output = u""
31
31
    error = u""
34
34
        self.options = options
35
35
        self.logger = logging.getLogger(app_name+"."+module_name)
36
36
        self.loadConfigData()
37
 
            
 
37
 
38
38
    def loadConfigData(self):
39
 
        try:         
 
39
        try:
40
40
 
41
41
            self.config = NullConfig()
42
 
            
 
42
 
43
43
            if self.options.config != None:
44
44
                # load the config based on options passed in from the main app
45
45
                configfilepath = self.options.config
46
46
            else:
47
47
                # load plugin config from home directory of the user
48
48
                configfilepath = os.path.join(os.path.expanduser('~'), ".config/"+app_name+"/"+module_name+".config")
49
 
                            
 
49
 
50
50
            if os.path.exists(configfilepath):
51
 
                
 
51
 
52
52
                self.logger.info("Loading config settings from \"%s\""%configfilepath)
53
 
                
 
53
 
54
54
                for line in fileinput.input(os.path.expanduser(configfilepath)):
55
55
                    line = line.strip()
56
56
                    if len(line) > 0 and line[0:1] != "#": # ignore commented lines or empty ones
57
 
    
 
57
 
58
58
                        name = line.split("=")[0].strip().upper() # config setting name on the left of =
59
59
                        value = line.split("=")[1].split("#")[0].strip() # config value on the right of = (minus any trailing comments)
60
 
    
 
60
 
61
61
                        if len(value) > 0:
62
62
                            if name == "HEADERTEMPLATE":
63
 
                                self.config.HEADERTEMPLATE = self.getTypedValue(value, "string")                            
 
63
                                self.config.HEADERTEMPLATE = getTypedValue(value, "string")
64
64
                            elif name == "TEMPLATE":
65
 
                                self.config.TEMPLATE = self.getTypedValue(value, "string")                                                                                      
 
65
                                self.config.TEMPLATE = getTypedValue(value, "string")
66
66
                            else:
67
67
                                self.logger.error("Unknown option in config file: " + name)
68
68
            else:
69
69
                self.logger.info("Config data file %s not found, using defaults and setting up config file for next time" % configfilepath)
70
 
                
 
70
 
71
71
                userconfigpath = os.path.join(os.path.expanduser('~'), ".config/"+app_name+"/")
72
72
                configsource = os.path.join(app_path, "config/"+module_name+".config")
73
 
                
 
73
 
74
74
                if os.path.exists(userconfigpath) == False:
75
75
                    os.makedirs(userconfigpath)
76
76
 
77
77
                shutil.copy(configsource, configfilepath)
78
 
                
 
78
 
79
79
        except Exception, e:
80
80
            self.logger.error(e.__str__()+"\n"+traceback.format_exc())
81
81
 
82
 
    def getTypedValue(self, value, expectedtype):
83
 
        
84
 
        try:
85
 
            if len(value.strip(" ")) == 0:
86
 
                return None
87
 
            
88
 
            elif value.lower() == "true":
89
 
                if expectedtype == "boolean":
90
 
                    return True
91
 
                else:
92
 
                    self.logger.error("Expected type was '%s', but the value '%s' was given"%(expectedtype, value))
93
 
                    
94
 
            elif value.lower() == "false":
95
 
                if expectedtype == "boolean":
96
 
                    return False
97
 
                else:
98
 
                    self.logger.error("Expected type was '%s', but the value '%s' was given"%(expectedtype, value))
99
 
                    
100
 
            elif self.isNumeric(value) == True:
101
 
                if expectedtype == "integer":
102
 
                    return int(value)
103
 
                else:
104
 
                    self.logger.error("Expected type was '%s', but the value '%s' was given"%(expectedtype, value))
105
 
                    
106
 
            else:
107
 
                return value
108
 
 
109
 
        except (TypeError, ValueError):
110
 
            self.logger.error("Cannot convert '%s' to expected type of '%s'"%(value,expectedtype))
111
 
            return value
112
 
 
113
82
    def getOutput(self):
114
83
 
115
84
        if self.options.noheader == True:
134
103
            headertemplate = inputfile.read()
135
104
        finally:
136
105
            inputfile.close()
137
 
                        
 
106
 
138
107
        if self.options.template != None:
139
108
            templatefilepath = self.options.template
140
109
            self.logger.info("Using custom template file '%s'"%templatefilepath)
144
113
        else:
145
114
            templatefilepath = app_path+"/templates/null.template"
146
115
            self.logger.info("Using default template")
147
 
             
 
116
 
148
117
        # load the file
149
118
        try:
150
119
            inputfile = codecs.open(os.path.expanduser(templatefilepath), encoding='utf-8')
154
123
            template = inputfile.read()
155
124
        finally:
156
125
            inputfile.close()
157
 
            
 
126
 
158
127
        output = headertemplate + "\n" + template
159
128
 
160
129
        return output.encode("utf-8")
161
130
 
162
 
    def getHTMLText(self,text):
163
 
        try:
164
 
            htmlentities = []               
165
 
            for char in text: #html:
166
 
                if ord(char) < 128:
167
 
                    htmlentities.append(char)
168
 
                else:
169
 
                    htmlentities.append('&%s;' % codepoint2name[ord(char)])
170
 
            html = "".join(htmlentities)
171
 
            
172
 
            html = html.replace("\n","<br>\n") # switch out new line for html breaks
173
 
            return html            
174
 
        except:
175
 
            return text
176
 
 
177
 
    def getCleanText(self,html):
178
 
        try:
179
 
            text = str(html)
180
 
            text = text.replace("\n","") # remove new lines from html
181
 
            text = text.replace("&apos;","'") # workaround for shitty xml codes not compliant with html
182
 
            text = text.replace("<br>","\n") # switch out html breaks for new line
183
 
            text = re.sub('<(.|\n)+?>','',text) # remove any html tags
184
 
            text =  re.sub('&(%s);' % '|'.join(name2codepoint), lambda m: chr(name2codepoint[m.group(1)]), text)
185
 
            return text            
186
 
        except:
187
 
            return html
188
 
    
189
 
    def isNumeric(self,value):
190
 
        try:
191
 
            temp = int(value)
192
 
            return True
193
 
        except:
194
 
            return False
195
 
  
196
131
def getHTML(options):
197
132
    output = Output(options)
198
133
    html = output.getOutput()
201
136
 
202
137
# to enable testing in isolation
203
138
if __name__ == "__main__":
204
 
    
 
139
 
205
140
    parser = OptionParser()
206
 
    parser.add_option("--noheader", dest="noheader", default=False, action="store_true", help=u"Turn off header output. This will override any header template setting to be nothing")        
 
141
    parser.add_option("--noheader", dest="noheader", default=False, action="store_true", help=u"Turn off header output. This will override any header template setting to be nothing")
207
142
    parser.add_option("--headertemplate", dest="headertemplate", type="string", metavar="FILE", help=u"Override the header template for the plugin, default or config based template ignored.")
208
143
    parser.add_option("--template", dest="template", type="string", metavar="FILE", help=u"Override the template for the plugin, default or config based template ignored.")
209
144
    parser.add_option("--verbose", dest="verbose", default=False, action="store_true", help=u"Outputs verbose info to the terminal")
210
145
    parser.add_option("--version", dest="version", default=False, action="store_true", help=u"Displays the version of the script.")
211
 
    parser.add_option("--logfile", dest="logfile", type="string", metavar="FILE", help=u"If a filepath is set, the script logs to the filepath.")                
212
 
    
 
146
    parser.add_option("--logfile", dest="logfile", type="string", metavar="FILE", help=u"If a filepath is set, the script logs to the filepath.")
 
147
 
213
148
    (options, args) = parser.parse_args()
214
 
        
 
149
 
215
150
    output = Output(options)
216
151
    html = output.getOutput()
217
152
    del output
218
153
    print html
219
 
    
 
 
b'\\ No newline at end of file'