blob: ca4976a30f716385ccefbd03c0cde58d39dffcd3 [file] [log] [blame]
Ka-Ping Yee0a8c29b2001-03-02 02:01:40 +00001"""Interfaces for launching and remotely controlling Web browsers."""
Fred Drakec70b4482000-07-09 16:45:56 +00002
3import os
4import sys
5
Skip Montanaro40fc1602001-03-01 04:27:19 +00006__all__ = ["Error", "open", "get", "register"]
7
Fred Drakec70b4482000-07-09 16:45:56 +00008class Error(Exception):
9 pass
10
Tim Peters658cba62001-02-09 20:06:00 +000011_browsers = {} # Dictionary of available browser controllers
12_tryorder = [] # Preference order of available browsers
Fred Drakec70b4482000-07-09 16:45:56 +000013
14def register(name, klass, instance=None):
15 """Register a browser connector and, optionally, connection."""
16 _browsers[name.lower()] = [klass, instance]
17
Eric S. Raymondf7f18512001-01-23 13:16:32 +000018def get(using=None):
19 """Return a browser launcher instance appropriate for the environment."""
20 if using:
21 alternatives = [using]
22 else:
23 alternatives = _tryorder
24 for browser in alternatives:
25 if browser.find('%s') > -1:
26 # User gave us a command line, don't mess with it.
Eric S. Raymondf7eb4fa2001-03-31 01:50:52 +000027 return GenericBrowser(browser)
Eric S. Raymondf7f18512001-01-23 13:16:32 +000028 else:
Tim Peters658cba62001-02-09 20:06:00 +000029 # User gave us a browser name.
Fred Drakef4e5bd92001-04-12 22:07:27 +000030 try:
31 command = _browsers[browser.lower()]
32 except KeyError:
33 command = _synthesize(browser)
Eric S. Raymondf7f18512001-01-23 13:16:32 +000034 if command[1] is None:
35 return command[0]()
36 else:
37 return command[1]
38 raise Error("could not locate runnable browser")
Fred Drakec70b4482000-07-09 16:45:56 +000039
40# Please note: the following definition hides a builtin function.
41
Eric S. Raymondf79cb2d2001-01-23 13:49:44 +000042def open(url, new=0, autoraise=1):
43 get().open(url, new, autoraise)
Fred Drakec70b4482000-07-09 16:45:56 +000044
Fred Drake3f8f1642001-07-19 03:46:26 +000045def open_new(url):
Eric S. Raymondf7f18512001-01-23 13:16:32 +000046 get().open(url, 1)
Fred Drakec70b4482000-07-09 16:45:56 +000047
Fred Drakef4e5bd92001-04-12 22:07:27 +000048
49def _synthesize(browser):
50 """Attempt to synthesize a controller base on existing controllers.
51
52 This is useful to create a controller when a user specifies a path to
53 an entry in the BROWSER environment variable -- we can copy a general
54 controller to operate using a specific installation of the desired
55 browser in this way.
56
57 If we can't create a controller in this way, or if there is no
58 executable for the requested browser, return [None, None].
59
60 """
61 if not os.path.exists(browser):
62 return [None, None]
63 name = os.path.basename(browser)
64 try:
65 command = _browsers[name.lower()]
66 except KeyError:
67 return [None, None]
68 # now attempt to clone to fit the new name:
69 controller = command[1]
70 if controller and name.lower() == controller.basename:
71 import copy
72 controller = copy.copy(controller)
73 controller.name = browser
74 controller.basename = os.path.basename(browser)
75 register(browser, None, controller)
76 return [None, controller]
Andrew M. Kuchling118aa532001-08-13 14:37:23 +000077 return [None, None]
Fred Drakef4e5bd92001-04-12 22:07:27 +000078
Fred Drake3f8f1642001-07-19 03:46:26 +000079
80def _iscommand(cmd):
81 """Return true if cmd can be found on the executable search path."""
82 path = os.environ.get("PATH")
83 if not path:
84 return 0
85 for d in path.split(os.pathsep):
86 exe = os.path.join(d, cmd)
87 if os.path.isfile(exe):
88 return 1
89 return 0
90
91
92PROCESS_CREATION_DELAY = 4
93
94
95class GenericBrowser:
96 def __init__(self, cmd):
97 self.name, self.args = cmd.split(None, 1)
98 self.basename = os.path.basename(self.name)
99
100 def open(self, url, new=0, autoraise=1):
101 command = "%s %s" % (self.name, self.args)
102 os.system(command % url)
103
104 def open_new(self, url):
105 self.open(url)
106
107
108class Netscape:
109 "Launcher class for Netscape browsers."
110 def __init__(self, name):
111 self.name = name
112 self.basename = os.path.basename(name)
113
114 def _remote(self, action, autoraise):
115 raise_opt = ("-noraise", "-raise")[autoraise]
116 cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name,
117 raise_opt,
118 action)
Martin v. Löwis3a89b2b2001-11-25 14:35:58 +0000119 print cmd
Fred Drake3f8f1642001-07-19 03:46:26 +0000120 rc = os.system(cmd)
121 if rc:
122 import time
123 os.system("%s &" % self.name)
124 time.sleep(PROCESS_CREATION_DELAY)
125 rc = os.system(cmd)
126 return not rc
127
128 def open(self, url, new=0, autoraise=1):
129 if new:
130 self._remote("openURL(%s, new-window)"%url, autoraise)
131 else:
132 self._remote("openURL(%s)" % url, autoraise)
133
134 def open_new(self, url):
135 self.open(url, 1)
136
137
138class Konqueror:
139 """Controller for the KDE File Manager (kfm, or Konqueror).
140
141 See http://developer.kde.org/documentation/other/kfmclient.html
142 for more information on the Konqueror remote-control interface.
143
144 """
145 def __init__(self):
146 if _iscommand("konqueror"):
147 self.name = self.basename = "konqueror"
148 else:
149 self.name = self.basename = "kfm"
150
151 def _remote(self, action):
152 cmd = "kfmclient %s >/dev/null 2>&1" % action
153 rc = os.system(cmd)
154 if rc:
155 import time
156 if self.basename == "konqueror":
157 os.system(self.name + " --silent &")
158 else:
159 os.system(self.name + " -d &")
160 time.sleep(PROCESS_CREATION_DELAY)
161 rc = os.system(cmd)
162 return not rc
163
164 def open(self, url, new=1, autoraise=1):
165 # XXX Currently I know no way to prevent KFM from
166 # opening a new win.
167 self._remote("openURL %s" % url)
168
169 open_new = open
170
171
172class Grail:
173 # There should be a way to maintain a connection to Grail, but the
174 # Grail remote control protocol doesn't really allow that at this
175 # point. It probably neverwill!
176 def _find_grail_rc(self):
177 import glob
178 import pwd
179 import socket
180 import tempfile
181 tempdir = os.path.join(tempfile.gettempdir(),
182 ".grail-unix")
Fred Drake16623fe2001-10-13 16:00:52 +0000183 user = pwd.getpwuid(os.getuid())[0]
Fred Drake3f8f1642001-07-19 03:46:26 +0000184 filename = os.path.join(tempdir, user + "-*")
185 maybes = glob.glob(filename)
186 if not maybes:
187 return None
188 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
189 for fn in maybes:
190 # need to PING each one until we find one that's live
191 try:
192 s.connect(fn)
193 except socket.error:
194 # no good; attempt to clean it out, but don't fail:
195 try:
196 os.unlink(fn)
197 except IOError:
198 pass
199 else:
200 return s
201
202 def _remote(self, action):
203 s = self._find_grail_rc()
204 if not s:
205 return 0
206 s.send(action)
207 s.close()
208 return 1
209
210 def open(self, url, new=0, autoraise=1):
211 if new:
212 self._remote("LOADNEW " + url)
213 else:
214 self._remote("LOAD " + url)
215
216 def open_new(self, url):
217 self.open(url, 1)
218
219
220class WindowsDefault:
221 def open(self, url, new=0, autoraise=1):
222 os.startfile(url)
223
224 def open_new(self, url):
225 self.open(url)
Fred Drakec70b4482000-07-09 16:45:56 +0000226
Tim Peters658cba62001-02-09 20:06:00 +0000227#
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000228# Platform support for Unix
229#
Fred Drakec70b4482000-07-09 16:45:56 +0000230
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000231# This is the right test because all these Unix browsers require either
232# a console terminal of an X display to run. Note that we cannot split
233# the TERM and DISPLAY cases, because we might be running Python from inside
234# an xterm.
235if os.environ.get("TERM") or os.environ.get("DISPLAY"):
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000236 _tryorder = ("mozilla","netscape","kfm","grail","links","lynx","w3m")
Fred Drakec70b4482000-07-09 16:45:56 +0000237
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000238 # Easy cases first -- register console browsers if we have them.
239 if os.environ.get("TERM"):
240 # The Links browser <http://artax.karlin.mff.cuni.cz/~mikulas/links/>
241 if _iscommand("links"):
242 register("links", None, GenericBrowser("links %s"))
243 # The Lynx browser <http://lynx.browser.org/>
244 if _iscommand("lynx"):
245 register("lynx", None, GenericBrowser("lynx %s"))
246 # The w3m browser <http://ei5nazha.yz.yamagata-u.ac.jp/~aito/w3m/eng/>
247 if _iscommand("w3m"):
248 register("w3m", None, GenericBrowser("w3m %s"))
Fred Drakec70b4482000-07-09 16:45:56 +0000249
Ka-Ping Yee0a8c29b2001-03-02 02:01:40 +0000250 # X browsers have more in the way of options
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000251 if os.environ.get("DISPLAY"):
252 # First, the Netscape series
253 if _iscommand("netscape") or _iscommand("mozilla"):
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000254 if _iscommand("mozilla"):
255 register("mozilla", None, Netscape("mozilla"))
256 if _iscommand("netscape"):
257 register("netscape", None, Netscape("netscape"))
258
259 # Next, Mosaic -- old but still in use.
260 if _iscommand("mosaic"):
261 register("mosaic", None, GenericBrowser("mosaic %s >/dev/null &"))
262
263 # Konqueror/kfm, the KDE browser.
Fred Drakefc31f262001-03-26 15:06:15 +0000264 if _iscommand("kfm") or _iscommand("konqueror"):
Fred Drakef4e5bd92001-04-12 22:07:27 +0000265 register("kfm", Konqueror, Konqueror())
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000266
267 # Grail, the Python browser.
268 if _iscommand("grail"):
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000269 register("grail", Grail, None)
270
Fred Drake3f8f1642001-07-19 03:46:26 +0000271
272class InternetConfig:
273 def open(self, url, new=0, autoraise=1):
274 ic.launchurl(url)
275
276 def open_new(self, url):
277 self.open(url)
278
279
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000280#
281# Platform support for Windows
282#
Fred Drakec70b4482000-07-09 16:45:56 +0000283
284if sys.platform[:3] == "win":
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000285 _tryorder = ("netscape", "windows-default")
Fred Drakec70b4482000-07-09 16:45:56 +0000286 register("windows-default", WindowsDefault)
Fred Drakec70b4482000-07-09 16:45:56 +0000287
Fred Drakec70b4482000-07-09 16:45:56 +0000288#
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000289# Platform support for MacOS
290#
Fred Drakec70b4482000-07-09 16:45:56 +0000291
292try:
293 import ic
294except ImportError:
295 pass
296else:
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000297 # internet-config is the only supported controller on MacOS,
298 # so don't mess with the default!
299 _tryorder = ("internet-config")
Fred Drakec70b4482000-07-09 16:45:56 +0000300 register("internet-config", InternetConfig)
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000301
Martin v. Löwis3a89b2b2001-11-25 14:35:58 +0000302#
303# Platform support for OS/2
304#
305
306if sys.platform[:3] == "os2" and _iscommand("netscape.exe"):
307 _tryorder = ("os2netscape",)
308 register("os2netscape", None,
309 GenericBrowser("start netscape.exe %s"))
310
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000311# OK, now that we know what the default preference orders for each
312# platform are, allow user to override them with the BROWSER variable.
313#
314if os.environ.has_key("BROWSER"):
315 # It's the user's responsibility to register handlers for any unknown
316 # browser referenced by this value, before calling open().
317 _tryorder = os.environ["BROWSER"].split(":")
Skip Montanarocdab3bf2001-07-18 20:03:32 +0000318
319for cmd in _tryorder:
320 if not _browsers.has_key(cmd.lower()):
321 if _iscommand(cmd.lower()):
322 register(cmd.lower(), None, GenericBrowser("%s %%s" % cmd.lower()))
323
324_tryorder = filter(lambda x: _browsers.has_key(x.lower())
325 or x.find("%s") > -1, _tryorder)
326# what to do if _tryorder is now empty?