home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2006 November (DVD) / PCWELT_11_2006.ISO / casper / filesystem.squashfs / usr / lib / deskbar-applet / handlers / mozilla.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2006-08-31  |  19.0 KB  |  632 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. import os
  5. import re
  6. import HTMLParser
  7. import base64
  8. import glob
  9. from os.path import join, expanduser, exists, basename
  10. from gettext import gettext as _
  11. from ConfigParser import RawConfigParser
  12. from deskbar.defs import VERSION
  13. import gtk
  14. from deskbar.Watcher import FileWatcher, DirWatcher
  15. import deskbar
  16. import deskbar.Indexer as deskbar
  17. import deskbar.Handler as deskbar
  18.  
  19. try:
  20.     set
  21. except NameError:
  22.     from sets import Set as set
  23.  
  24. from deskbar.BrowserMatch import is_preferred_browser
  25. from deskbar.BrowserMatch import BrowserSmartMatch, BrowserMatch
  26. USING_FIREFOX = False
  27. if is_preferred_browser('firefox'):
  28.     USING_FIREFOX = True
  29.  
  30.  
  31. def get_mozilla_home_file(needed_file):
  32.     default_profile_dir = expanduser('~/.mozilla/default')
  33.     if exists(default_profile_dir):
  34.         for d in os.listdir(default_profile_dir):
  35.             return join(default_profile_dir, d, needed_file)
  36.         
  37.     
  38.     return ''
  39.  
  40.  
  41. def get_firefox_home_file(needed_file):
  42.     firefox_dir = expanduser('~/.mozilla/firefox/')
  43.     config = RawConfigParser({
  44.         'Default': 0 })
  45.     config.read(expanduser(join(firefox_dir, 'profiles.ini')))
  46.     path = None
  47.     for section in config.sections():
  48.         if config.has_option(section, 'Default') and config.get(section, 'Default') == '1':
  49.             path = config.get(section, 'Path')
  50.             break
  51.             continue
  52.         if path == None and config.has_option(section, 'Path'):
  53.             path = config.get(section, 'Path')
  54.             continue
  55.     
  56.     if path == None:
  57.         return ''
  58.     
  59.     if path.startswith('/'):
  60.         return join(path, needed_file)
  61.     
  62.     return join(firefox_dir, path, needed_file)
  63.  
  64. GCONF_SHOW_ONLY_PRIMARY_KEY = deskbar.GCONF_DIR + '/mozilla/show_only_primary_search'
  65. SHOW_ONLY_PRIMARY = deskbar.GCONF_CLIENT.get_bool(GCONF_SHOW_ONLY_PRIMARY_KEY)
  66. if SHOW_ONLY_PRIMARY == None:
  67.     SHOW_ONLY_PRIMARY = False
  68.  
  69.  
  70. def _on_gconf_show_only_primary(value):
  71.     global SHOW_ONLY_PRIMARY
  72.     SHOW_ONLY_PRIMARY = value
  73.  
  74. deskbar.GCONF_CLIENT.notify_add(GCONF_SHOW_ONLY_PRIMARY_KEY, (lambda x, y, z, a: _on_gconf_show_only_primary(z.value.get_bool())))
  75. PRIMARY_SEARCH_ENGINE = None
  76.  
  77. try:
  78.     if USING_FIREFOX:
  79.         prefs_file = file(get_firefox_home_file('prefs.js'))
  80.     else:
  81.         prefs_file = None
  82.     for line in prefs_file:
  83.         if line.startswith('user_pref("browser.search.selectedEngine", "'):
  84.             line = line.strip()
  85.             PRIMARY_SEARCH_ENGINE = line[len('user_pref("browser.search.selectedEngine", "'):-len('");')]
  86.             break
  87.             continue
  88. except:
  89.     pass
  90.  
  91.  
  92. def _on_handler_preferences(dialog):
  93.     
  94.     def toggled_cb(sender, show_all_radio, show_primary_radio):
  95.         deskbar.GCONF_CLIENT.set_bool(GCONF_SHOW_ONLY_PRIMARY_KEY, show_primary_radio.get_active())
  96.  
  97.     
  98.     def sync_ui(new_show_only_primary, show_all_radio, show_primary_radio):
  99.         show_all_radio.set_active(not new_show_only_primary)
  100.         show_primary_radio.set_active(new_show_only_primary)
  101.  
  102.     glade = gtk.glade.XML(os.path.join(deskbar.SHARED_DATA_DIR, 'mozilla-search.glade'))
  103.     dialog = glade.get_widget('prefs-dialog')
  104.     show_all_radio = glade.get_widget('show_all_radio')
  105.     show_primary_radio = glade.get_widget('show_primary_radio')
  106.     show_primary_radio.set_active(SHOW_ONLY_PRIMARY)
  107.     show_all_radio.set_active(not SHOW_ONLY_PRIMARY)
  108.     show_all_radio.connect('toggled', toggled_cb, show_all_radio, show_primary_radio)
  109.     show_primary_radio.connect('toggled', toggled_cb, show_all_radio, show_primary_radio)
  110.     notify_id = deskbar.GCONF_CLIENT.notify_add(GCONF_SHOW_ONLY_PRIMARY_KEY, (lambda x, y, z, a: sync_ui(z.value.get_bool(), show_all_radio, show_primary_radio)))
  111.     dialog.set_icon_name('deskbar-applet')
  112.     dialog.show_all()
  113.     dialog.run()
  114.     dialog.destroy()
  115.     deskbar.GCONF_CLIENT.notify_remove(notify_id)
  116.  
  117.  
  118. def _check_requirements_bookmarks():
  119.     if is_preferred_browser('firefox') or is_preferred_browser('mozilla'):
  120.         return (deskbar.Handler.HANDLER_IS_HAPPY, None, None)
  121.     else:
  122.         return (deskbar.Handler.HANDLER_IS_NOT_APPLICABLE, 'Mozilla/Firefox is not your preferred browser, not using it.', None)
  123.  
  124.  
  125. def _check_requirements_search():
  126.     if is_preferred_browser('firefox'):
  127.         return (deskbar.Handler.HANDLER_IS_CONFIGURABLE, _('You can customize which search engines are offered.'), _on_handler_preferences)
  128.     elif is_preferred_browser('mozilla'):
  129.         return (deskbar.Handler.HANDLER_IS_HAPPY, None, None)
  130.     else:
  131.         return (deskbar.Handler.HANDLER_IS_NOT_APPLICABLE, 'Mozilla/Firefox is not your preferred browser, not using it.', None)
  132.  
  133. HANDLERS = {
  134.     'MozillaBookmarksHandler': {
  135.         'name': _('Web Bookmarks'),
  136.         'description': _('Open your web bookmarks by name'),
  137.         'requirements': _check_requirements_bookmarks,
  138.         'version': VERSION },
  139.     'MozillaSearchHandler': {
  140.         'name': _('Web Searches'),
  141.         'description': _("Search the web via your browser's search settings"),
  142.         'requirements': _check_requirements_search,
  143.         'version': VERSION },
  144.     'MozillaHistoryHandler': {
  145.         'name': _('Web History'),
  146.         'description': _('Open your web history by name'),
  147.         'requirements': _check_requirements_bookmarks,
  148.         'version': VERSION } }
  149.  
  150. class MozillaBookmarksHandler(deskbar.Handler.Handler):
  151.     
  152.     def __init__(self):
  153.         deskbar.Handler.Handler.__init__(self, 'stock_bookmark')
  154.         self._bookmarks = None
  155.  
  156.     
  157.     def initialize(self):
  158.         if not hasattr(self, 'watcher'):
  159.             self.watcher = FileWatcher()
  160.             self.watcher.connect('changed', (lambda watcher, f: self._parse_bookmarks()))
  161.         
  162.         parsed_file = self._parse_bookmarks()
  163.         if parsed_file != None:
  164.             self.watcher.add(parsed_file)
  165.         
  166.  
  167.     
  168.     def _parse_bookmarks(self):
  169.         (self._bookmarks, parsed_file, self._shortcuts_to_smart_bookmarks_map) = MozillaBookmarksParser(self).get_indexer()
  170.         return parsed_file
  171.  
  172.     
  173.     def stop(self):
  174.         self.watcher.remove_all()
  175.  
  176.     
  177.     def query(self, query):
  178.         x = self.query_smart_bookmarks(query, deskbar.DEFAULT_RESULTS_PER_HANDLER)
  179.         if x != None:
  180.             return x
  181.         else:
  182.             return self._bookmarks.look_up(query)[:deskbar.DEFAULT_RESULTS_PER_HANDLER]
  183.  
  184.     
  185.     def query_smart_bookmarks(self, query, max):
  186.         x = query.find(' ')
  187.         if x != -1:
  188.             prefix = query[:x]
  189.             
  190.             try:
  191.                 b = self._shortcuts_to_smart_bookmarks_map[prefix]
  192.                 text = query[x + 1:]
  193.                 return [
  194.                     BrowserSmartMatch(b.get_handler(), b.name, b.url, prefix, b, icon = b.icon)]
  195.             except KeyError:
  196.                 pass
  197.             except:
  198.                 None<EXCEPTION MATCH>KeyError
  199.             
  200.  
  201.         None<EXCEPTION MATCH>KeyError
  202.  
  203.  
  204.  
  205. class MozillaSearchHandler(deskbar.Handler.Handler):
  206.     
  207.     def __init__(self):
  208.         deskbar.Handler.Handler.__init__(self, 'stock_bookmark')
  209.         self._smart_bookmarks = None
  210.  
  211.     
  212.     def initialize(self):
  213.         smart_dirs = None
  214.         if USING_FIREFOX:
  215.             smart_dirs = [
  216.                 get_firefox_home_file('searchplugins'),
  217.                 get_firefox_home_file('search'),
  218.                 expanduser('~/.mozilla/searchplugins'),
  219.                 '/usr/lib/firefox/searchplugins',
  220.                 '/usr/local/lib/firefox/searchplugins',
  221.                 '/usr/lib/mozilla-firefox/searchplugins',
  222.                 '/usr/local/lib/mozilla-firefox/searchplugins']
  223.         else:
  224.             smart_dirs = [
  225.                 get_mozilla_home_file('search'),
  226.                 expanduser('~/.mozilla/searchplugins'),
  227.                 '/usr/lib/mozilla/searchplugins',
  228.                 '/usr/local/lib/mozilla/searchplugins']
  229.         if not hasattr(self, 'watcher'):
  230.             self.watcher = DirWatcher()
  231.             self.watcher.connect('changed', (lambda watcher, f: self._parse_search_engines(smart_dirs)))
  232.         
  233.         self.watcher.add(smart_dirs)
  234.         self._parse_search_engines(smart_dirs)
  235.  
  236.     
  237.     def _parse_search_engines(self, smart_dirs):
  238.         self._smart_bookmarks = MozillaSmartBookmarksDirParser(self, smart_dirs).get_smart_bookmarks()
  239.  
  240.     
  241.     def stop(self):
  242.         self.watcher.remove_all()
  243.  
  244.     
  245.     def query(self, query):
  246.         if SHOW_ONLY_PRIMARY and PRIMARY_SEARCH_ENGINE != None:
  247.             for s in self._smart_bookmarks:
  248.                 if s.name == PRIMARY_SEARCH_ENGINE:
  249.                     return [
  250.                         s]
  251.                     continue
  252.             
  253.             return self._smart_bookmarks
  254.         else:
  255.             return self._smart_bookmarks
  256.  
  257.  
  258.  
  259. class MozillaBookmarksParser(HTMLParser.HTMLParser):
  260.     
  261.     def __init__(self, handler):
  262.         HTMLParser.HTMLParser.__init__(self)
  263.         self.handler = handler
  264.         self.chars = ''
  265.         self.href = None
  266.         self.icon_data = None
  267.         self.bookmarks = set()
  268.         self._shortcuts_to_smart_bookmarks_map = { }
  269.         self._indexer = deskbar.Indexer.Indexer()
  270.         if USING_FIREFOX:
  271.             self.indexed_file = self._index_firefox()
  272.         else:
  273.             self.indexed_file = self._index_mozilla()
  274.         self.close()
  275.  
  276.     
  277.     def get_indexer(self):
  278.         '''
  279. \t\tReturns a completed indexer with the contents of bookmark file,
  280. \t\tthe name of the indexed file, and a map from shortcuts (or
  281. \t\tprefixes) to smart bookmarks - those bookmarks with %s in the
  282. \t\tURL.
  283. \t\t'''
  284.         return (self._indexer, self.indexed_file, self._shortcuts_to_smart_bookmarks_map)
  285.  
  286.     
  287.     def _index_mozilla(self):
  288.         
  289.         try:
  290.             bookmarks_file = get_mozilla_home_file('bookmarks.html')
  291.             if exists(bookmarks_file):
  292.                 self.feed(file(bookmarks_file).read())
  293.                 return bookmarks_file
  294.         except Exception:
  295.             msg = None
  296.             print 'Error retreiving Mozilla Bookmarks:', msg
  297.  
  298.  
  299.     
  300.     def _index_firefox(self):
  301.         
  302.         try:
  303.             bookmarks_file = get_firefox_home_file('bookmarks.html')
  304.             if exists(bookmarks_file):
  305.                 self.feed(file(bookmarks_file).read())
  306.                 return bookmarks_file
  307.         except Exception:
  308.             msg = None
  309.             print 'Error retreiving Mozilla Bookmarks:', msg
  310.  
  311.  
  312.     
  313.     def handle_starttag(self, tag, attrs):
  314.         tag = tag.lower()
  315.         if tag == 'a':
  316.             self.chars = ''
  317.             self.shortcuturl = None
  318.             for tag, value in attrs:
  319.                 if tag.lower() == 'href':
  320.                     self.href = value
  321.                 
  322.                 if tag.lower() == 'icon' and value != 'data:' and value.startswith('data:'):
  323.                     self.icon_data = value
  324.                 
  325.                 if tag.lower() == 'shortcuturl':
  326.                     self.shortcuturl = value
  327.                     continue
  328.             
  329.         
  330.  
  331.     
  332.     def handle_endtag(self, tag):
  333.         tag = tag.lower()
  334.         if tag == 'a':
  335.             if self.href == None or self.href.startswith('javascript:'):
  336.                 return None
  337.             
  338.             pixbuf = None
  339.             if self.icon_data != None:
  340.                 
  341.                 try:
  342.                     (header, content) = self.icon_data.split(',', 2)
  343.                     loader = gtk.gdk.PixbufLoader()
  344.                     loader.set_size(deskbar.ICON_HEIGHT, deskbar.ICON_HEIGHT)
  345.                     
  346.                     try:
  347.                         loader.write(base64.b64decode(content))
  348.                     except AttributeError:
  349.                         loader.write(base64.decodestring(content))
  350.  
  351.                     loader.close()
  352.                     pixbuf = loader.get_pixbuf()
  353.                 except Exception:
  354.                     msg = None
  355.                     print 'Error:mozilla.py:handle_endtag:', msg
  356.  
  357.                 self.icon_data = None
  358.             
  359.             bookmark = BrowserMatch(self.handler, self.chars, self.href, icon = pixbuf)
  360.             if self.shortcuturl != None:
  361.                 bookmark = BrowserSmartMatch(self.handler, self.chars, self.href, self.shortcuturl, bookmark, icon = pixbuf)
  362.                 self._shortcuts_to_smart_bookmarks_map[self.shortcuturl] = bookmark
  363.             else:
  364.                 self._indexer.add('%s %s' % (self.chars, self.href), bookmark)
  365.         
  366.  
  367.     
  368.     def handle_data(self, chars):
  369.         self.chars = self.chars + chars
  370.  
  371.  
  372.  
  373. class MozillaSmartBookmarksParser:
  374.     
  375.     def __init__(self, f):
  376.         '''
  377. \t\tInit the parse, no exception here
  378. \t\t'''
  379.         self.f = f
  380.         self.infos = {
  381.             'search': { },
  382.             'input': { } }
  383.  
  384.     
  385.     def get_infos(self):
  386.         infos = { }
  387.         args = '?'
  388.         for key, arg in self.infos['input'].items():
  389.             args += '%s=%s&' % (key, arg)
  390.         
  391.         if args.endswith('&'):
  392.             args = args[:-1]
  393.         
  394.         infos['name'] = self.infos['search']['name']
  395.         infos['description'] = self.infos['search']['description']
  396.         if 'url' not in self.infos['search']:
  397.             infos['url'] = self.infos['search']['action']
  398.         else:
  399.             infos['url'] = self.infos['search']['url']
  400.         infos['action'] = self.infos['search']['action'] + args
  401.         return infos
  402.  
  403.     
  404.     def parse(self):
  405.         '''
  406. \t\t'''
  407.         tokenizer = Tokenizer(self.f)
  408.         n = None
  409.         state = None
  410.         tokens = [
  411.             tokenizer.get_next_token(),
  412.             tokenizer.get_next_token()]
  413.         while tokens[0] != None:
  414.             (state, n, rest) = self._handle_token(state, tokens)
  415.             if n == None:
  416.                 break
  417.             
  418.             tokens = rest
  419.             for i in range(n - len(rest)):
  420.                 tokens.append(tokenizer.get_next_token())
  421.             
  422.  
  423.     
  424.     def _handle_token(self, state, tokens):
  425.         if state == None:
  426.             if tokens == [
  427.                 '<',
  428.                 'search'] or tokens == [
  429.                 '<',
  430.                 'SEARCH']:
  431.                 return ('search', 3, [])
  432.             elif state == None:
  433.                 raise ParseException('File %s does not begin with <search' % self.f)
  434.             
  435.         if state == 'search' and tokens[1] == '=':
  436.             self.infos['search'][tokens[0]] = tokens[2]
  437.             return ('search', 3, [])
  438.         
  439.         if (state == 'search' or state == 'anotherinput') and tokens == [
  440.             '>',
  441.             '<',
  442.             'input']:
  443.             return ('input', 6, [])
  444.         elif state == 'search':
  445.             raise ParseException('Expecting <input after <search section in file %s' % self.f)
  446.         
  447.         if state == 'input' and tokens[1] == '=':
  448.             if tokens[3] == 'user':
  449.                 self.infos['input'][tokens[2]] = '%s'
  450.                 if tokens[4] != '=':
  451.                     return ('anotherinput', 3, tokens[4:])
  452.                 
  453.             else:
  454.                 self.infos['input'][tokens[2]] = tokens[5]
  455.             return ('anotherinput', 3, [])
  456.         
  457.         return (None, None, None)
  458.  
  459.  
  460.  
  461. class TokenException(Exception):
  462.     pass
  463.  
  464.  
  465. class ParseException(Exception):
  466.     pass
  467.  
  468.  
  469. class Tokenizer:
  470.     
  471.     def __init__(self, f):
  472.         '''
  473. \t\tInit the tokenizer on the given file, may throw an exception.
  474. \t\t'''
  475.         self.i = 0
  476.         self.f = f
  477.         self.data = file(f).read()
  478.         self.state = 'linestart'
  479.  
  480.     
  481.     def get_next_token(self):
  482.         '''
  483. \t\tReturns the next token in the file.
  484. \t\tA token is one of:
  485. \t\t< = > name
  486. \t\t
  487. \t\tReturns None when the end of file is reached and beyond
  488. \t\t'''
  489.         while self.i < len(self.data):
  490.             char = self.data[self.i]
  491.             if char.isspace() and not (char == '\n'):
  492.                 self.i += 1
  493.                 continue
  494.             
  495.             if self.state == 'linestart' and char == '#':
  496.                 while self.i < len(self.data) and self.data[self.i] != '\n':
  497.                     self.i += 1
  498.                     continue
  499.                     self
  500.                 self.i += 1
  501.                 continue
  502.             
  503.             next_token = self.read_token()
  504.             if next_token == '\n':
  505.                 self.state = 'linestart'
  506.                 continue
  507.             
  508.             return next_token
  509.  
  510.     
  511.     def read_token(self):
  512.         '''
  513. \t\tReturn the token, self.i must point to the first char in this token.
  514. \t\tself.i is updated to point just after the returned token
  515. \t\tReturned token is one of:
  516. \t\t< = > 
  517.  name
  518. \t\t'''
  519.         char = self.data[self.i]
  520.         if char == '<' and char == '=' and char == '>' or char == '\n':
  521.             self.i += 1
  522.             return char
  523.         elif char == '"':
  524.             closing = self.data[self.i + 1:].find('"')
  525.             if closing == -1:
  526.                 raise TokenException("Couldn't find a proper closing quote in %s" % self.f)
  527.             
  528.             token = self.data[self.i + 1:self.i + 1 + closing]
  529.             self.i += closing + 2
  530.             return token
  531.         else:
  532.             token = ''
  533.             while self.i < len(self.data) and not self.data[self.i].isspace() and self.data[self.i] not in '=><':
  534.                 token += self.data[self.i]
  535.                 self.i += 1
  536.                 continue
  537.                 self
  538.             return token
  539.  
  540.  
  541.  
  542. class MozillaSmartBookmarksDirParser:
  543.     
  544.     def __init__(self, handler, dirs):
  545.         self._smart_bookmarks = []
  546.         foundbookmarks = []
  547.         for bookmarks_dir in dirs:
  548.             if not exists(bookmarks_dir):
  549.                 continue
  550.             
  551.             for f in glob.glob(join(bookmarks_dir, '*.src')):
  552.                 bmname = basename(f)
  553.                 if bmname in foundbookmarks:
  554.                     continue
  555.                 else:
  556.                     foundbookmarks.append(bmname)
  557.                 img = None
  558.                 
  559.                 try:
  560.                     img = _[1][0]
  561.                 except:
  562.                     pass
  563.  
  564.                 parser = MozillaSmartBookmarksParser(f)
  565.                 
  566.                 try:
  567.                     parser.parse()
  568.                     infos = parser.get_infos()
  569.                     bookmark = BrowserMatch(handler, infos['name'], infos['url'], icon = img)
  570.                     bookmark = BrowserSmartMatch(handler, infos['name'], infos['action'], icon = img, bookmark = bookmark)
  571.                     self._smart_bookmarks.append(bookmark)
  572.                 continue
  573.                 except Exception:
  574.                     msg = None
  575.                     print 'Error:MozillaSmartBookmarksDirParser:cannot parse smrt bookmark:%s:bookmark %s' % (msg, f)
  576.                     continue
  577.                 
  578.  
  579.             
  580.         
  581.  
  582.     
  583.     def get_smart_bookmarks(self):
  584.         '''
  585. \t\tReturn a list of MozillaSmartMatch instances representing smart bookmarks
  586. \t\t'''
  587.         return self._smart_bookmarks
  588.  
  589.  
  590. MOZILLA_HISTORY_REGEX = re.compile('\\=http[0-9a-zA-Z\\-\\&\\%\\=\\?\\:\\/\\.]*\\)')
  591.  
  592. class MozillaHistoryHandler(deskbar.Handler.Handler):
  593.     
  594.     def __init__(self):
  595.         deskbar.Handler.Handler.__init__(self, 'epiphany-history.png')
  596.         self._history = None
  597.  
  598.     
  599.     def initialize(self):
  600.         self._indexer = deskbar.Indexer.Indexer()
  601.         self._history = self._parse_history()
  602.         for history_url in self._history:
  603.             history_wo_http = history_url[history_url.find('//') + 2:]
  604.             if history_wo_http.find('www.') == -1:
  605.                 history_wo_www = history_wo_http
  606.             else:
  607.                 history_wo_www = history_wo_http[history_wo_http.find('www.') + 4:]
  608.             self._indexer.add('%s %s %s' % (history_wo_www, history_wo_http, history_url), BrowserMatch(self, history_wo_www, history_url, True))
  609.         
  610.  
  611.     
  612.     def _parse_history(self):
  613.         if USING_FIREFOX:
  614.             historydat = get_firefox_home_file('history.dat')
  615.         else:
  616.             historydat = get_mozilla_home_file('history.dat')
  617.         
  618.         try:
  619.             historycontents = file(historydat).read()
  620.             historycontents = re.findall(MOZILLA_HISTORY_REGEX, historycontents)
  621.             historycontents = [ x[1:-1] for x in historycontents ]
  622.             return historycontents
  623.         except:
  624.             return ''
  625.  
  626.  
  627.     
  628.     def query(self, query):
  629.         return self._indexer.look_up(query)[:deskbar.DEFAULT_RESULTS_PER_HANDLER]
  630.  
  631.  
  632.