Fixed item navigation and cleaned up feed and item changes
[straw.git] / src / lib / utils.py
blob111e556ea6f93569a7951d09d86af9003ff02065
1 """ utils.py
3 Module for utility methods.
4 """
5 __copyright__ = "Copyright (c) 2002-2005 Free Software Foundation, Inc."
6 __license__ = """GNU General Public License
8 This program is free software; you can redistribute it and/or modify it under the
9 terms of the GNU General Public License as published by the Free Software
10 Foundation; either version 2 of the License, or (at your option) any later
11 version.
13 This program is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License along with
18 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19 Place - Suite 330, Boston, MA 02111-1307, USA. """
21 import re, string, htmlentitydefs
22 from htmlentitydefs import codepoint2name
23 import urllib, urlparse, locale
24 import time, calendar
25 import os
26 import os.path
27 import subprocess
28 import sys
29 import error
30 import constants
31 import gtk
33 entity = re.compile(r'\&.\w*?\;')
34 def convert_entities(text):
35 def conv(ents):
36 entities = htmlentitydefs.entitydefs
37 ents = ents.group(0)
38 ent_code = entities.get(ents[1:-1], None)
39 if ent_code is not None:
40 try:
41 ents = unicode(ent_code, get_locale_encoding())
42 except UnicodeDecodeError:
43 ents = unicode(ent_code, 'latin-1')
44 except Exception, ex:
45 error.log("error occurred while converting entity %s: %s" % (ents, ex))
47 # check if it still needs conversion
48 if entity.search(ents) is None:
49 return ents
51 if ents[1] == '#':
52 code = ents[2:-1]
53 base = 10
54 if code[0] == 'x':
55 code = code[1:]
56 base = 16
57 return unichr(int(code, base))
58 else:
59 return
61 in_entity = entity.search(text)
62 if in_entity is None:
63 return text
64 else:
65 ctext = in_entity.re.sub(conv, text)
66 return ctext
68 def complete_url(url, feed_location):
69 url = urllib.quote(url, safe=string.punctuation)
70 if urlparse.urlparse(url)[0] == '':
71 return urlparse.urljoin(feed_location, url)
72 else:
73 return url
75 def get_url_location(url):
76 url = urllib.quote(url, safe=string.punctuation)
77 parsed_url = urlparse.urlsplit(url)
78 return urlparse.urlunsplit((parsed_url[0], parsed_url[1], '','',''))
80 def get_locale_encoding():
81 try:
82 encoding = locale.getpreferredencoding()
83 except locale.Error:
84 encoding = sys.getdefaultencoding()
85 return encoding
87 def format_date(date, format=None, encoding=None):
88 if format is None:
89 format = get_date_format()
90 if encoding is None:
91 encoding = get_locale_encoding()
92 timestr = time.strftime(format, time.localtime(calendar.timegm(date)))
93 return unicode(timestr, encoding)
95 def get_date_format():
96 # this is here just to make xgettext happy: it should be defined in
97 # only one place, and a good one would be MainWindow.py module level.
98 # however, we can't access _ there.
99 # The format: %A is the full weekday name
100 # %B is the full month name
101 # %e is the day of the month as a decimal number,
102 # without leading zero
103 # This should be translated to be suitable for the locale in
104 # question, feel free to alter the order and the parameters (they
105 # are strftime(3) parameters, the whole string is passed to the
106 # function, Straw does no additional interpretation) if you feel
107 # it's necessary in the translation file.
108 return _('%A %B %e %H:%M')
110 def find_data_dir():
111 datad = ''
112 if os.environ.has_key("STRAW_DATA"):
113 datad = os.environ["STRAW_DATA"]
114 else:
115 datad = constants.datadir
116 if not os.path.isdir(datad):
117 raise "FileNotFoundError", "couldn't find Straw data directory"
118 return datad
120 def find_locale_dir():
121 localed = ''
122 if os.environ.has_key("STRAW_LOCALE"):
123 localed = os.environ["STRAW_LOCALE"]
124 else:
125 localed = constants.localedir
126 if not os.path.isdir(localed):
127 raise "FileNotFoundError", "couldn't find locale data directory"
128 return localed
130 def find_glade_file(libdir=None):
131 gladef = ''
132 if os.environ.has_key("STRAW_GLADE"):
133 gladef = os.environ["STRAW_GLADE"]
134 else:
135 gladef = os.path.normpath(os.path.join(constants.gladedir, "straw.glade"))
136 if not os.path.isfile(gladef):
137 raise "FileNotFoundError", "couldn't find straw.glade"
138 return gladef
140 def find_image_dir():
141 if not os.path.isdir(constants.imagedir):
142 raise "FileNotFoundError", "could not find image (pixmaps) directory"
143 return constants.imagedir
145 def listdiff(l1, l2, test=None):
146 if test is not None:
147 return _listdifftest(l1, l2, test)
148 common = []
149 inl1 = []
150 inl2 = []
151 for e in l1:
152 if e in l2:
153 common.append(e)
154 else:
155 inl1.append(e)
156 for e in l2:
157 if e in l1:
158 if e not in common:
159 common.append(e)
160 else:
161 inl2.append(e)
162 return (common, inl1, inl2)
164 import string
165 import gnomevfs
166 import Config
167 import dialogs
169 def url_show(url):
170 config = Config.get_instance()
171 if config.browser_cmd:
172 try:
173 cmdbin, args = string.splitfields(str(config.browser_cmd), maxsplit=1)
174 link = args % url
175 pid = subprocess.Popen([cmdbin, link]).pid
176 return pid
177 except ValueError, ve:
178 dialogs.report_error(_("An error occurred while trying to open link"),
179 _("There was a problem opening '%s'\n\nError thrown is '%s'") % (url,str(ve)))
180 else:
181 return gnomevfs.url_show(url)
184 def set_clipboard_text(text):
185 clipboard = gtk.clipboard_get(selection="CLIPBOARD")
186 clipboard.set_text(text)
188 def html_replace(exc):
189 """ Python Cookbook 2ed, Section 1.23
191 if isinstance(exc, (UnicodeDecodeError, UnicodeTranslateError)):
192 s = [ u'&%s;' % codepoint2name[ord(c)] for c in exc.object[exc.start:exc.end]]
193 return ''.join(s), exc.end
194 else:
195 raise TypeError("can't handle %s" % exc.__name__)
197 import codecs
198 codecs.register_error('html_replace', html_replace)