3 Module for utility methods.
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
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
33 entity
= re
.compile(r
'\&.\w*?\;')
34 def convert_entities(text
):
36 entities
= htmlentitydefs
.entitydefs
38 ent_code
= entities
.get(ents
[1:-1], None)
39 if ent_code
is not None:
41 ents
= unicode(ent_code
, get_locale_encoding())
42 except UnicodeDecodeError:
43 ents
= unicode(ent_code
, 'latin-1')
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:
57 return unichr(int(code
, base
))
61 in_entity
= entity
.search(text
)
65 ctext
= in_entity
.re
.sub(conv
, text
)
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
)
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():
82 encoding
= locale
.getpreferredencoding()
84 encoding
= sys
.getdefaultencoding()
87 def format_date(date
, format
=None, encoding
=None):
89 format
= get_date_format()
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')
112 if os
.environ
.has_key("STRAW_DATA"):
113 datad
= os
.environ
["STRAW_DATA"]
115 datad
= constants
.datadir
116 if not os
.path
.isdir(datad
):
117 raise "FileNotFoundError", "couldn't find Straw data directory"
120 def find_locale_dir():
122 if os
.environ
.has_key("STRAW_LOCALE"):
123 localed
= os
.environ
["STRAW_LOCALE"]
125 localed
= constants
.localedir
126 if not os
.path
.isdir(localed
):
127 raise "FileNotFoundError", "couldn't find locale data directory"
130 def find_glade_file(libdir
=None):
132 if os
.environ
.has_key("STRAW_GLADE"):
133 gladef
= os
.environ
["STRAW_GLADE"]
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"
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):
147 return _listdifftest(l1
, l2
, test
)
162 return (common
, inl1
, inl2
)
170 config
= Config
.get_instance()
171 if config
.browser_cmd
:
173 cmdbin
, args
= string
.splitfields(str(config
.browser_cmd
), maxsplit
=1)
175 pid
= subprocess
.Popen([cmdbin
, link
]).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
)))
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
195 raise TypeError("can't handle %s" % exc
.__name
__)
198 codecs
.register_error('html_replace', html_replace
)