"""Interfaces for launching and remotely controlling Web browsers.""" import os import sys __all__ = ["Error", "open", "get", "register"] class Error(Exception): pass _browsers = {} # Dictionary of available browser controllers _tryorder = [] # Preference order of available browsers def register(name, klass, instance=None): """Register a browser connector and, optionally, connection.""" _browsers[name.lower()] = [klass, instance] def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if using is not None: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if '%s' in browser: # User gave us a command line, don't mess with it. return GenericBrowser(browser) else: # User gave us a browser name. try: command = _browsers[browser.lower()] except KeyError: command = _synthesize(browser) if command[1] is None: return command[0]() else: return command[1] raise Error("could not locate runnable browser") # Please note: the following definition hides a builtin function. def open(url, new=0, autoraise=1): get().open(url, new, autoraise) def open_new(url): get().open(url, 1) def _synthesize(browser): """Attempt to synthesize a controller base on existing controllers. This is useful to create a controller when a user specifies a path to an entry in the BROWSER environment variable -- we can copy a general controller to operate using a specific installation of the desired browser in this way. If we can't create a controller in this way, or if there is no executable for the requested browser, return [None, None]. """ if not os.path.exists(browser): return [None, None] name = os.path.basename(browser) try: command = _browsers[name.lower()] except KeyError: return [None, None] # now attempt to clone to fit the new name: controller = command[1] if controller and name.lower() == controller.basename: import copy controller = copy.copy(controller) controller.name = browser controller.basename = os.path.basename(browser) register(browser, None, controller) return [None, controller] return [None, None] def _iscommand(cmd): """Return True if cmd can be found on the executable search path.""" path = os.environ.get("PATH") if not path: return False for d in path.split(os.pathsep): exe = os.path.join(d, cmd) if os.path.isfile(exe): return True return False PROCESS_CREATION_DELAY = 4 class GenericBrowser: def __init__(self, cmd): self.name, self.args = cmd.split(None, 1) self.basename = os.path.basename(self.name) def open(self, url, new=0, autoraise=1): assert "'" not in url command = "%s %s" % (self.name, self.args) os.system(command % url) def open_new(self, url): self.open(url) class Netscape: "Launcher class for Netscape browsers." def __init__(self, name): self.name = name self.basename = os.path.basename(name) def _remote(self, action, autoraise): raise_opt = ("-noraise", "-raise")[autoraise] cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name, raise_opt, action) rc = os.system(cmd) if rc: import time os.system("%s &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc def open(self, url, new=0, autoraise=1): if new: self._remote("openURL(%s, new-window)"%url, autoraise) else: self._remote("openURL(%s)" % url, autoraise) def open_new(self, url): self.open(url, 1) class Galeon: """Launcher class for Galeon browsers.""" def __init__(self, name): self.name = name self.basename = os.path.basename(name) def _remote(self, action, autoraise): raise_opt = ("--noraise", "")[autoraise] cmd = "%s %s %s >/dev/null 2>&1" % (self.name, raise_opt, action) rc = os.system(cmd) if rc: import time os.system("%s >/dev/null 2>&1 &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc def open(self, url, new=0, autoraise=1): if new: self._remote("-w '%s'" % url, autoraise) else: self._remote("-n '%s'" % url, autoraise) def open_new(self, url): self.open(url, 1) class Konqueror: """Controller for the KDE File Manager (kfm, or Konqueror). See http://developer.kde.org/documentation/other/kfmclient.html for more information on the Konqueror remote-control interface. """ def __init__(self): if _iscommand("konqueror"): self.name = self.basename = "konqueror" else: self.name = self.basename = "kfm" def _remote(self, action): cmd = "kfmclient %s >/dev/null 2>&1" % action rc = os.system(cmd) if rc: import time if self.basename == "konqueror": os.system(self.name + " --silent &") else: os.system(self.name + " -d &") time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc def open(self, url, new=1, autoraise=1): # XXX Currently I know no way to prevent KFM from # opening a new win. assert "'" not in url self._remote("openURL '%s'" % url) open_new = open class Grail: # There should be a way to maintain a connection to Grail, but the # Grail remote control protocol doesn't really allow that at this # point. It probably neverwill! def _find_grail_rc(self): import glob import pwd import socket import tempfile tempdir = os.path.join(tempfile.gettempdir(), ".grail-unix") user = pwd.getpwuid(os.getuid())[0] filename = os.path.join(tempdir, user + "-*") maybes = glob.glob(filename) if not maybes: return None s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) for fn in maybes: # need to PING each one until we find one that's live try: s.connect(fn) except socket.error: # no good; attempt to clean it out, but don't fail: try: os.unlink(fn) except IOError: pass else: return s def _remote(self, action): s = self._find_grail_rc() if not s: return 0 s.send(action) s.close() return 1 def open(self, url, new=0, autoraise=1): if new: self._remote("LOADNEW " + url) else: self._remote("LOAD " + url) def open_new(self, url): self.open(url, 1) class WindowsDefault: def open(self, url, new=0, autoraise=1): os.startfile(url) def open_new(self, url): self.open(url) # # Platform support for Unix # # This is the right test because all these Unix browsers require either # a console terminal of an X display to run. Note that we cannot split # the TERM and DISPLAY cases, because we might be running Python from inside # an xterm. if os.environ.get("TERM") or os.environ.get("DISPLAY"): _tryorder = ["links", "lynx", "w3m"] # Easy cases first -- register console browsers if we have them. if os.environ.get("TERM"): # The Links browser if _iscommand("links"): register("links", None, GenericBrowser("links '%s'")) # The Lynx browser if _iscommand("lynx"): register("lynx", None, GenericBrowser("lynx '%s'")) # The w3m browser if _iscommand("w3m"): register("w3m", None, GenericBrowser("w3m '%s'")) # X browsers have more in the way of options if os.environ.get("DISPLAY"): _tryorder = ["galeon", "skipstone", "mozilla-firefox", "mozilla-firebird", "mozilla", "netscape", "kfm", "grail"] + _tryorder # First, the Netscape series for browser in ("mozilla-firefox", "mozilla-firebird", "mozilla", "netscape"): if _iscommand(browser): register(browser, None, Netscape(browser)) # Next, Mosaic -- old but still in use. if _iscommand("mosaic"): register("mosaic", None, GenericBrowser( "mosaic '%s' >/dev/null &")) # Gnome's Galeon if _iscommand("galeon"): register("galeon", None, Galeon("galeon")) # Skipstone, another Gtk/Mozilla based browser if _iscommand("skipstone"): register("skipstone", None, GenericBrowser( "skipstone '%s' >/dev/null &")) # Konqueror/kfm, the KDE browser. if _iscommand("kfm") or _iscommand("konqueror"): register("kfm", Konqueror, Konqueror()) # Grail, the Python browser. if _iscommand("grail"): register("grail", Grail, None) class InternetConfig: def open(self, url, new=0, autoraise=1): ic.launchurl(url) def open_new(self, url): self.open(url) # # Platform support for Windows # if sys.platform[:3] == "win": _tryorder = ["netscape", "windows-default"] register("windows-default", WindowsDefault) # # Platform support for MacOS # try: import ic except ImportError: pass else: # internet-config is the only supported controller on MacOS, # so don't mess with the default! _tryorder = ["internet-config"] register("internet-config", InternetConfig) # # Platform support for OS/2 # if sys.platform[:3] == "os2" and _iscommand("netscape.exe"): _tryorder = ["os2netscape"] register("os2netscape", None, GenericBrowser("start netscape.exe %s")) # OK, now that we know what the default preference orders for each # platform are, allow user to override them with the BROWSER variable. # if "BROWSER" in os.environ: # It's the user's responsibility to register handlers for any unknown # browser referenced by this value, before calling open(). _tryorder = os.environ["BROWSER"].split(os.pathsep) for cmd in _tryorder: if not cmd.lower() in _browsers: if _iscommand(cmd.lower()): register(cmd.lower(), None, GenericBrowser( "%s '%%s'" % cmd.lower())) cmd = None # to make del work if _tryorder was empty del cmd _tryorder = filter(lambda x: x.lower() in _browsers or x.find("%s") > -1, _tryorder) # what to do if _tryorder is now empty? 239' href='#n239'>239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
#!/bin/env python
#------------------------------------------------------------------------
#           Copyright (c) 1997-2001 by Total Control Software
#                         All Rights Reserved
#------------------------------------------------------------------------
#
# Module Name:  dbShelve.py
#
# Description:  A reimplementation of the standard shelve.py that
#               forces the use of cPickle, and DB.
#
# Creation Date:    11/3/97 3:39:04PM
#
# License:      This is free software.  You may use this software for any
#               purpose including modification/redistribution, so long as
#               this header remains intact and that you do not claim any
#               rights of ownership or authorship of this software.  This
#               software has been tested, but no warranty is expressed or
#               implied.
#
# 13-Dec-2000:  Updated to be used with the new bsddb3 package.
#               Added DBShelfCursor class.
#
#------------------------------------------------------------------------

"""Manage shelves of pickled objects using bsddb database files for the
storage.
"""

#------------------------------------------------------------------------

import cPickle
import db
import sys

#At version 2.3 cPickle switched to using protocol instead of bin and
#DictMixin was added
if sys.version_info[:3] >= (2, 3, 0):
    HIGHEST_PROTOCOL = cPickle.HIGHEST_PROTOCOL
    def _dumps(object, protocol):
        return cPickle.dumps(object, protocol=protocol)
    from UserDict import DictMixin
else:
    HIGHEST_PROTOCOL = None
    def _dumps(object, protocol):
        return cPickle.dumps(object, bin=protocol)
    class DictMixin: pass

#------------------------------------------------------------------------


def open(filename, flags=db.DB_CREATE, mode=0660, filetype=db.DB_HASH,
         dbenv=None, dbname=None):
    """
    A simple factory function for compatibility with the standard
    shleve.py module.  It can be used like this, where key is a string
    and data is a pickleable object:

        from bsddb import dbshelve
        db = dbshelve.open(filename)

        db[key] = data

        db.close()
    """
    if type(flags) == type(''):
        sflag = flags
        if sflag == 'r':
            flags = db.DB_RDONLY
        elif sflag == 'rw':
            flags = 0
        elif sflag == 'w':
            flags =  db.DB_CREATE
        elif sflag == 'c':
            flags =  db.DB_CREATE
        elif sflag == 'n':
            flags = db.DB_TRUNCATE | db.DB_CREATE
        else:
            raise db.DBError, "flags should be one of 'r', 'w', 'c' or 'n' or use the bsddb.db.DB_* flags"

    d = DBShelf(dbenv)
    d.open(filename, dbname, filetype, flags, mode)
    return d

#---------------------------------------------------------------------------

class DBShelveError(db.DBError): pass


class DBShelf(DictMixin):
    """A shelf to hold pickled objects, built upon a bsddb DB object.  It
    automatically pickles/unpickles data objects going to/from the DB.
    """
    def __init__(self, dbenv=None):
        self.db = db.DB(dbenv)
        self._closed = True
        if HIGHEST_PROTOCOL:
            self.protocol = HIGHEST_PROTOCOL
        else:
            self.protocol = 1


    def __del__(self):
        self.close()


    def __getattr__(self, name):
        """Many methods we can just pass through to the DB object.
        (See below)
        """
        return getattr(self.db, name)


    #-----------------------------------
    # Dictionary access methods

    def __len__(self):
        return len(self.db)


    def __getitem__(self, key):
        data = self.db[key]
        return cPickle.loads(data)


    def __setitem__(self, key, value):
        data = _dumps(value, self.protocol)
        self.db[key] = data


    def __delitem__(self, key):
        del self.db[key]


    def keys(self, txn=None):
        if txn != None:
            return self.db.keys(txn)
        else:
            return self.db.keys()


    def open(self, *args, **kwargs):
        self.db.open(*args, **kwargs)
        self._closed = False


    def close(self, *args, **kwargs):
        self.db.close(*args, **kwargs)
        self._closed = True


    def __repr__(self):
        if self._closed:
            return '<DBShelf @ 0x%x - closed>' % (id(self))
        else:
            return repr(dict(self.iteritems()))


    def items(self, txn=None):
        if txn != None:
            items = self.db.items(txn)
        else:
            items = self.db.items()
        newitems = []

        for k, v in items:
            newitems.append( (k, cPickle.loads(v)) )
        return newitems

    def values(self, txn=None):
        if txn != None:
            values = self.db.values(txn)
        else:
            values = self.db.values()

        return map(cPickle.loads, values)

    #-----------------------------------
    # Other methods

    def __append(self, value, txn=None):
        data = _dumps(value, self.protocol)
        return self.db.append(data, txn)

    def append(self, value, txn=None):
        if self.get_type() == db.DB_RECNO:
            return self.__append(value, txn=txn)
        raise DBShelveError, "append() only supported when dbshelve opened with filetype=dbshelve.db.DB_RECNO"


    def associate(self, secondaryDB, callback, flags=0):
        def _shelf_callback(priKey, priData, realCallback=callback):
            data = cPickle.loads(priData)
            return realCallback(priKey, data)
        return self.db.associate(secondaryDB, _shelf_callback, flags)


    #def get(self, key, default=None, txn=None, flags=0):
    def get(self, *args, **kw):
        # We do it with *args and **kw so if the default value wasn't
        # given nothing is passed to the extension module.  That way
        # an exception can be raised if set_get_returns_none is turned
        # off.
        data = apply(self.db.get, args, kw)
        try:
            return cPickle.loads(data)
        except (TypeError, cPickle.UnpicklingError):
            return data  # we may be getting the default value, or None,
                         # so it doesn't need unpickled.

    def get_both(self, key, value, txn=None, flags=0):
        data = _dumps(value, self.protocol)
        data = self.db.get(key, data, txn, flags)
        return cPickle.loads(data)


    def cursor(self, txn=None, flags=0):
        c = DBShelfCursor(self.db.cursor(txn, flags))
        c.protocol = self.protocol
        return c


    def put(self, key, value, txn=None, flags=0):
        data = _dumps(value, self.protocol)
        return self.db.put(key, data, txn, flags)


    def join(self, cursorList, flags=0):
        raise NotImplementedError


    #----------------------------------------------
    # Methods allowed to pass-through to self.db
    #
    #    close,  delete, fd, get_byteswapped, get_type, has_key,
    #    key_range, open, remove, rename, stat, sync,
    #    upgrade, verify, and all set_* methods.


#---------------------------------------------------------------------------

class DBShelfCursor:
    """
    """
    def __init__(self, cursor):
        self.dbc = cursor

    def __del__(self):
        self.close()


    def __getattr__(self, name):
        """Some methods we can just pass through to the cursor object.  (See below)"""
        return getattr(self.dbc, name)


    #----------------------------------------------

    def dup(self, flags=0):
        c = DBShelfCursor(self.dbc.dup(flags))
        c.protocol = self.protocol
        return c


    def put(self, key, value, flags=0):
        data = _dumps(value, self.protocol)
        return self.dbc.put(key, data, flags)


    def get(self, *args):
        count = len(args)  # a method overloading hack
        method = getattr(self, 'get_%d' % count)
        apply(method, args)

    def get_1(self, flags):
        rec = self.dbc.get(flags)
        return self._extract(rec)

    def get_2(self, key, flags):
        rec = self.dbc.get(key, flags)
        return self._extract(rec)

    def get_3(self, key, value, flags):
        data = _dumps(value, self.protocol)
        rec = self.dbc.get(key, flags)
        return self._extract(rec)


    def current(self, flags=0): return self.get_1(flags|db.DB_CURRENT)
    def first(self, flags=0): return self.get_1(flags|db.DB_FIRST)
    def last(self, flags=0): return self.get_1(flags|db.DB_LAST)
    def next(self, flags=0): return self.get_1(flags|db.DB_NEXT)
    def prev(self, flags=0): return self.get_1(flags|db.DB_PREV)
    def consume(self, flags=0): return self.get_1(flags|db.DB_CONSUME)
    def next_dup(self, flags=0): return self.get_1(flags|db.DB_NEXT_DUP)
    def next_nodup(self, flags=0): return self.get_1(flags|db.DB_NEXT_NODUP)
    def prev_nodup(self, flags=0): return self.get_1(flags|db.DB_PREV_NODUP)


    def get_both(self, key, value, flags=0):
        data = _dumps(value, self.protocol)
        rec = self.dbc.get_both(key, flags)
        return self._extract(rec)


    def set(self, key, flags=0):
        rec = self.dbc.set(key, flags)
        return self._extract(rec)

    def set_range(self, key, flags=0):
        rec = self.dbc.set_range(key, flags)
        return self._extract(rec)

    def set_recno(self, recno, flags=0):
        rec = self.dbc.set_recno(recno, flags)
        return self._extract(rec)

    set_both = get_both

    def _extract(self, rec):
        if rec is None:
            return None
        else:
            key, data = rec
            return key, cPickle.loads(data)

    #----------------------------------------------
    # Methods allowed to pass-through to self.dbc
    #
    # close, count, delete, get_recno, join_item


#---------------------------------------------------------------------------