blob: ce5b48e00dbfa141cfad09d557e816f1a835e04a [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Ka-Ping Yee0a8c29b2001-03-02 02:01:40 +00002"""Interfaces for launching and remotely controlling Web browsers."""
Guido van Rossum992d4a32007-07-11 13:09:30 +00003# Maintained by Georg Brandl.
Fred Drakec70b4482000-07-09 16:45:56 +00004
Fred Drakeee763952008-12-10 06:02:39 +00005import io
Fred Drakec70b4482000-07-09 16:45:56 +00006import os
Guido van Rossumd8faa362007-04-27 19:54:29 +00007import shlex
Fred Drakec70b4482000-07-09 16:45:56 +00008import sys
Georg Brandle8f24432005-10-03 14:16:44 +00009import stat
Georg Brandl23929f22006-01-20 21:03:35 +000010import subprocess
11import time
Fred Drakec70b4482000-07-09 16:45:56 +000012
Georg Brandle8f24432005-10-03 14:16:44 +000013__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
Skip Montanaro40fc1602001-03-01 04:27:19 +000014
Fred Drakec70b4482000-07-09 16:45:56 +000015class Error(Exception):
16 pass
17
Tim Peters658cba62001-02-09 20:06:00 +000018_browsers = {} # Dictionary of available browser controllers
19_tryorder = [] # Preference order of available browsers
Fred Drakec70b4482000-07-09 16:45:56 +000020
Georg Brandle8f24432005-10-03 14:16:44 +000021def register(name, klass, instance=None, update_tryorder=1):
Fred Drakec70b4482000-07-09 16:45:56 +000022 """Register a browser connector and, optionally, connection."""
23 _browsers[name.lower()] = [klass, instance]
Georg Brandle8f24432005-10-03 14:16:44 +000024 if update_tryorder > 0:
25 _tryorder.append(name)
26 elif update_tryorder < 0:
27 _tryorder.insert(0, name)
Fred Drakec70b4482000-07-09 16:45:56 +000028
Eric S. Raymondf7f18512001-01-23 13:16:32 +000029def get(using=None):
30 """Return a browser launcher instance appropriate for the environment."""
Raymond Hettinger10ff7062002-06-02 03:04:52 +000031 if using is not None:
Eric S. Raymondf7f18512001-01-23 13:16:32 +000032 alternatives = [using]
33 else:
34 alternatives = _tryorder
35 for browser in alternatives:
Raymond Hettingerbac788a2004-05-04 09:21:43 +000036 if '%s' in browser:
Georg Brandl23929f22006-01-20 21:03:35 +000037 # User gave us a command line, split it into name and args
Guido van Rossumd8faa362007-04-27 19:54:29 +000038 browser = shlex.split(browser)
39 if browser[-1] == '&':
40 return BackgroundBrowser(browser[:-1])
41 else:
42 return GenericBrowser(browser)
Eric S. Raymondf7f18512001-01-23 13:16:32 +000043 else:
Georg Brandle8f24432005-10-03 14:16:44 +000044 # User gave us a browser name or path.
Fred Drakef4e5bd92001-04-12 22:07:27 +000045 try:
46 command = _browsers[browser.lower()]
47 except KeyError:
48 command = _synthesize(browser)
Georg Brandle8f24432005-10-03 14:16:44 +000049 if command[1] is not None:
Eric S. Raymondf7f18512001-01-23 13:16:32 +000050 return command[1]
Georg Brandle8f24432005-10-03 14:16:44 +000051 elif command[0] is not None:
52 return command[0]()
Eric S. Raymondf7f18512001-01-23 13:16:32 +000053 raise Error("could not locate runnable browser")
Fred Drakec70b4482000-07-09 16:45:56 +000054
55# Please note: the following definition hides a builtin function.
Georg Brandle8f24432005-10-03 14:16:44 +000056# It is recommended one does "import webbrowser" and uses webbrowser.open(url)
57# instead of "from webbrowser import *".
Fred Drakec70b4482000-07-09 16:45:56 +000058
Alexandre Vassalottie223eb82009-07-29 20:12:15 +000059def open(url, new=0, autoraise=True):
Georg Brandle8f24432005-10-03 14:16:44 +000060 for name in _tryorder:
61 browser = get(name)
62 if browser.open(url, new, autoraise):
63 return True
64 return False
Fred Drakec70b4482000-07-09 16:45:56 +000065
Fred Drake3f8f1642001-07-19 03:46:26 +000066def open_new(url):
Georg Brandle8f24432005-10-03 14:16:44 +000067 return open(url, 1)
68
69def open_new_tab(url):
70 return open(url, 2)
Fred Drakec70b4482000-07-09 16:45:56 +000071
Fred Drakef4e5bd92001-04-12 22:07:27 +000072
Georg Brandle8f24432005-10-03 14:16:44 +000073def _synthesize(browser, update_tryorder=1):
Fred Drakef4e5bd92001-04-12 22:07:27 +000074 """Attempt to synthesize a controller base on existing controllers.
75
76 This is useful to create a controller when a user specifies a path to
77 an entry in the BROWSER environment variable -- we can copy a general
78 controller to operate using a specific installation of the desired
79 browser in this way.
80
81 If we can't create a controller in this way, or if there is no
82 executable for the requested browser, return [None, None].
83
84 """
Georg Brandle8f24432005-10-03 14:16:44 +000085 cmd = browser.split()[0]
86 if not _iscommand(cmd):
Fred Drakef4e5bd92001-04-12 22:07:27 +000087 return [None, None]
Georg Brandle8f24432005-10-03 14:16:44 +000088 name = os.path.basename(cmd)
Fred Drakef4e5bd92001-04-12 22:07:27 +000089 try:
90 command = _browsers[name.lower()]
91 except KeyError:
92 return [None, None]
93 # now attempt to clone to fit the new name:
94 controller = command[1]
95 if controller and name.lower() == controller.basename:
96 import copy
97 controller = copy.copy(controller)
98 controller.name = browser
99 controller.basename = os.path.basename(browser)
Georg Brandle8f24432005-10-03 14:16:44 +0000100 register(browser, None, controller, update_tryorder)
Fred Drakef4e5bd92001-04-12 22:07:27 +0000101 return [None, controller]
Andrew M. Kuchling118aa532001-08-13 14:37:23 +0000102 return [None, None]
Fred Drakef4e5bd92001-04-12 22:07:27 +0000103
Fred Drake3f8f1642001-07-19 03:46:26 +0000104
Georg Brandle8f24432005-10-03 14:16:44 +0000105if sys.platform[:3] == "win":
106 def _isexecutable(cmd):
107 cmd = cmd.lower()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000108 if os.path.isfile(cmd) and cmd.endswith((".exe", ".bat")):
Georg Brandle8f24432005-10-03 14:16:44 +0000109 return True
110 for ext in ".exe", ".bat":
111 if os.path.isfile(cmd + ext):
112 return True
113 return False
114else:
115 def _isexecutable(cmd):
116 if os.path.isfile(cmd):
117 mode = os.stat(cmd)[stat.ST_MODE]
118 if mode & stat.S_IXUSR or mode & stat.S_IXGRP or mode & stat.S_IXOTH:
119 return True
120 return False
121
Fred Drake3f8f1642001-07-19 03:46:26 +0000122def _iscommand(cmd):
Georg Brandle8f24432005-10-03 14:16:44 +0000123 """Return True if cmd is executable or can be found on the executable
124 search path."""
125 if _isexecutable(cmd):
126 return True
Fred Drake3f8f1642001-07-19 03:46:26 +0000127 path = os.environ.get("PATH")
128 if not path:
Tim Petersbc0e9102002-04-04 22:55:58 +0000129 return False
Fred Drake3f8f1642001-07-19 03:46:26 +0000130 for d in path.split(os.pathsep):
131 exe = os.path.join(d, cmd)
Georg Brandle8f24432005-10-03 14:16:44 +0000132 if _isexecutable(exe):
Tim Petersbc0e9102002-04-04 22:55:58 +0000133 return True
134 return False
Fred Drake3f8f1642001-07-19 03:46:26 +0000135
136
Georg Brandle8f24432005-10-03 14:16:44 +0000137# General parent classes
138
139class BaseBrowser(object):
Georg Brandl23929f22006-01-20 21:03:35 +0000140 """Parent class for all browsers. Do not use directly."""
Tim Peters887c0802006-01-20 23:40:56 +0000141
Georg Brandl23929f22006-01-20 21:03:35 +0000142 args = ['%s']
Tim Peters887c0802006-01-20 23:40:56 +0000143
Georg Brandle8f24432005-10-03 14:16:44 +0000144 def __init__(self, name=""):
145 self.name = name
Georg Brandlb9801132005-10-08 20:47:38 +0000146 self.basename = name
Tim Peters536cf992005-12-25 23:18:31 +0000147
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000148 def open(self, url, new=0, autoraise=True):
Neal Norwitz196f7332005-10-04 03:17:49 +0000149 raise NotImplementedError
150
Georg Brandle8f24432005-10-03 14:16:44 +0000151 def open_new(self, url):
152 return self.open(url, 1)
153
154 def open_new_tab(self, url):
155 return self.open(url, 2)
Fred Drake3f8f1642001-07-19 03:46:26 +0000156
157
Georg Brandle8f24432005-10-03 14:16:44 +0000158class GenericBrowser(BaseBrowser):
159 """Class for all browsers started with a command
160 and without remote functionality."""
161
Georg Brandl23929f22006-01-20 21:03:35 +0000162 def __init__(self, name):
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000163 if isinstance(name, str):
Georg Brandl23929f22006-01-20 21:03:35 +0000164 self.name = name
Guido van Rossum992d4a32007-07-11 13:09:30 +0000165 self.args = ["%s"]
Georg Brandl23929f22006-01-20 21:03:35 +0000166 else:
167 # name should be a list with arguments
168 self.name = name[0]
169 self.args = name[1:]
Georg Brandlb9801132005-10-08 20:47:38 +0000170 self.basename = os.path.basename(self.name)
Fred Drake3f8f1642001-07-19 03:46:26 +0000171
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000172 def open(self, url, new=0, autoraise=True):
Tim Peters887c0802006-01-20 23:40:56 +0000173 cmdline = [self.name] + [arg.replace("%s", url)
Georg Brandl23929f22006-01-20 21:03:35 +0000174 for arg in self.args]
175 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000176 if sys.platform[:3] == 'win':
177 p = subprocess.Popen(cmdline)
178 else:
179 p = subprocess.Popen(cmdline, close_fds=True)
Georg Brandl23929f22006-01-20 21:03:35 +0000180 return not p.wait()
181 except OSError:
182 return False
183
184
185class BackgroundBrowser(GenericBrowser):
186 """Class for all browsers which are to be started in the
187 background."""
188
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000189 def open(self, url, new=0, autoraise=True):
Georg Brandl23929f22006-01-20 21:03:35 +0000190 cmdline = [self.name] + [arg.replace("%s", url)
191 for arg in self.args]
Georg Brandl23929f22006-01-20 21:03:35 +0000192 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000193 if sys.platform[:3] == 'win':
194 p = subprocess.Popen(cmdline)
195 else:
196 setsid = getattr(os, 'setsid', None)
197 if not setsid:
198 setsid = getattr(os, 'setpgrp', None)
199 p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid)
Georg Brandl23929f22006-01-20 21:03:35 +0000200 return (p.poll() is None)
201 except OSError:
202 return False
Fred Drake3f8f1642001-07-19 03:46:26 +0000203
204
Georg Brandle8f24432005-10-03 14:16:44 +0000205class UnixBrowser(BaseBrowser):
206 """Parent class for all Unix browsers with remote functionality."""
Fred Drake3f8f1642001-07-19 03:46:26 +0000207
Georg Brandle8f24432005-10-03 14:16:44 +0000208 raise_opts = None
Georg Brandl23929f22006-01-20 21:03:35 +0000209 remote_args = ['%action', '%s']
Georg Brandle8f24432005-10-03 14:16:44 +0000210 remote_action = None
211 remote_action_newwin = None
212 remote_action_newtab = None
Georg Brandl23929f22006-01-20 21:03:35 +0000213 background = False
214 redirect_stdout = True
Georg Brandle8f24432005-10-03 14:16:44 +0000215
Georg Brandl23929f22006-01-20 21:03:35 +0000216 def _invoke(self, args, remote, autoraise):
217 raise_opt = []
218 if remote and self.raise_opts:
219 # use autoraise argument only for remote invocation
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000220 autoraise = int(autoraise)
Georg Brandl23929f22006-01-20 21:03:35 +0000221 opt = self.raise_opts[autoraise]
222 if opt: raise_opt = [opt]
223
224 cmdline = [self.name] + raise_opt + args
Tim Peters887c0802006-01-20 23:40:56 +0000225
Georg Brandl23929f22006-01-20 21:03:35 +0000226 if remote or self.background:
Amaury Forgeot d'Arcbc2ce572008-12-05 01:02:21 +0000227 inout = io.open(os.devnull, "r+")
Georg Brandl23929f22006-01-20 21:03:35 +0000228 else:
229 # for TTY browsers, we need stdin/out
230 inout = None
Georg Brandl23929f22006-01-20 21:03:35 +0000231 p = subprocess.Popen(cmdline, close_fds=True, stdin=inout,
232 stdout=(self.redirect_stdout and inout or None),
Gregory P. Smith8f7724f2011-03-15 15:24:43 -0400233 stderr=inout, start_new_session=True)
Georg Brandl23929f22006-01-20 21:03:35 +0000234 if remote:
Jesus Ceac9aa3212012-08-01 03:57:52 +0200235 # wait at most five seconds. If the subprocess is not finished, the
Georg Brandl23929f22006-01-20 21:03:35 +0000236 # remote invocation has (hopefully) started a new instance.
Jesus Ceac9aa3212012-08-01 03:57:52 +0200237 try:
238 rc = p.wait(5)
239 # if remote call failed, open() will try direct invocation
240 return not rc
241 except subprocess.TimeoutExpired:
242 return True
Georg Brandl23929f22006-01-20 21:03:35 +0000243 elif self.background:
244 if p.poll() is None:
245 return True
246 else:
247 return False
248 else:
249 return not p.wait()
Fred Drake3f8f1642001-07-19 03:46:26 +0000250
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000251 def open(self, url, new=0, autoraise=True):
Georg Brandle8f24432005-10-03 14:16:44 +0000252 if new == 0:
253 action = self.remote_action
254 elif new == 1:
255 action = self.remote_action_newwin
256 elif new == 2:
257 if self.remote_action_newtab is None:
258 action = self.remote_action_newwin
259 else:
260 action = self.remote_action_newtab
Fred Drake3f8f1642001-07-19 03:46:26 +0000261 else:
Georg Brandl23929f22006-01-20 21:03:35 +0000262 raise Error("Bad 'new' parameter to open(); " +
263 "expected 0, 1, or 2, got %s" % new)
Tim Peters887c0802006-01-20 23:40:56 +0000264
Georg Brandl23929f22006-01-20 21:03:35 +0000265 args = [arg.replace("%s", url).replace("%action", action)
266 for arg in self.remote_args]
267 success = self._invoke(args, True, autoraise)
268 if not success:
269 # remote invocation failed, try straight way
270 args = [arg.replace("%s", url) for arg in self.args]
271 return self._invoke(args, False, False)
272 else:
273 return True
Fred Drake3f8f1642001-07-19 03:46:26 +0000274
275
Georg Brandle8f24432005-10-03 14:16:44 +0000276class Mozilla(UnixBrowser):
277 """Launcher class for Mozilla/Netscape browsers."""
Neal Norwitz8dd28eb2002-10-10 22:49:29 +0000278
Georg Brandl23929f22006-01-20 21:03:35 +0000279 raise_opts = ["-noraise", "-raise"]
Georg Brandl23929f22006-01-20 21:03:35 +0000280 remote_args = ['-remote', 'openURL(%s%action)']
281 remote_action = ""
282 remote_action_newwin = ",new-window"
283 remote_action_newtab = ",new-tab"
Georg Brandl23929f22006-01-20 21:03:35 +0000284 background = True
Neal Norwitz8dd28eb2002-10-10 22:49:29 +0000285
Georg Brandle8f24432005-10-03 14:16:44 +0000286Netscape = Mozilla
Neal Norwitz8dd28eb2002-10-10 22:49:29 +0000287
288
Georg Brandle8f24432005-10-03 14:16:44 +0000289class Galeon(UnixBrowser):
290 """Launcher class for Galeon/Epiphany browsers."""
291
Georg Brandl23929f22006-01-20 21:03:35 +0000292 raise_opts = ["-noraise", ""]
293 remote_args = ['%action', '%s']
294 remote_action = "-n"
295 remote_action_newwin = "-w"
Georg Brandl23929f22006-01-20 21:03:35 +0000296 background = True
Fred Drake3f8f1642001-07-19 03:46:26 +0000297
298
Senthil Kumaranea6b4182011-12-21 22:20:32 +0800299class Chrome(UnixBrowser):
300 "Launcher class for Google Chrome browser."
301
302 remote_args = ['%action', '%s']
303 remote_action = ""
304 remote_action_newwin = "--new-window"
305 remote_action_newtab = ""
306 background = True
307
308Chromium = Chrome
309
310
Georg Brandle8f24432005-10-03 14:16:44 +0000311class Opera(UnixBrowser):
312 "Launcher class for Opera browser."
313
Terry Reedydad532f2010-12-28 19:30:19 +0000314 raise_opts = ["-noraise", ""]
Georg Brandl23929f22006-01-20 21:03:35 +0000315 remote_args = ['-remote', 'openURL(%s%action)']
316 remote_action = ""
317 remote_action_newwin = ",new-window"
318 remote_action_newtab = ",new-page"
319 background = True
Georg Brandle8f24432005-10-03 14:16:44 +0000320
321
322class Elinks(UnixBrowser):
323 "Launcher class for Elinks browsers."
324
Georg Brandl23929f22006-01-20 21:03:35 +0000325 remote_args = ['-remote', 'openURL(%s%action)']
326 remote_action = ""
327 remote_action_newwin = ",new-window"
328 remote_action_newtab = ",new-tab"
329 background = False
Georg Brandle8f24432005-10-03 14:16:44 +0000330
Georg Brandl23929f22006-01-20 21:03:35 +0000331 # elinks doesn't like its stdout to be redirected -
332 # it uses redirected stdout as a signal to do -dump
333 redirect_stdout = False
334
335
336class Konqueror(BaseBrowser):
337 """Controller for the KDE File Manager (kfm, or Konqueror).
338
339 See the output of ``kfmclient --commands``
340 for more information on the Konqueror remote-control interface.
341 """
342
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000343 def open(self, url, new=0, autoraise=True):
Georg Brandl23929f22006-01-20 21:03:35 +0000344 # XXX Currently I know no way to prevent KFM from opening a new win.
345 if new == 2:
346 action = "newTab"
347 else:
348 action = "openURL"
Tim Peters887c0802006-01-20 23:40:56 +0000349
Amaury Forgeot d'Arc2b2b44d2008-05-12 14:41:00 +0000350 devnull = io.open(os.devnull, "r+")
Georg Brandl23929f22006-01-20 21:03:35 +0000351 # if possible, put browser in separate process group, so
352 # keyboard interrupts don't affect browser as well as Python
353 setsid = getattr(os, 'setsid', None)
354 if not setsid:
355 setsid = getattr(os, 'setpgrp', None)
Tim Peters887c0802006-01-20 23:40:56 +0000356
Georg Brandl23929f22006-01-20 21:03:35 +0000357 try:
358 p = subprocess.Popen(["kfmclient", action, url],
359 close_fds=True, stdin=devnull,
360 stdout=devnull, stderr=devnull)
361 except OSError:
362 # fall through to next variant
363 pass
364 else:
365 p.wait()
366 # kfmclient's return code unfortunately has no meaning as it seems
367 return True
368
369 try:
370 p = subprocess.Popen(["konqueror", "--silent", url],
371 close_fds=True, stdin=devnull,
372 stdout=devnull, stderr=devnull,
373 preexec_fn=setsid)
374 except OSError:
375 # fall through to next variant
376 pass
377 else:
378 if p.poll() is None:
379 # Should be running now.
380 return True
Tim Peters887c0802006-01-20 23:40:56 +0000381
Georg Brandl23929f22006-01-20 21:03:35 +0000382 try:
383 p = subprocess.Popen(["kfm", "-d", url],
384 close_fds=True, stdin=devnull,
385 stdout=devnull, stderr=devnull,
386 preexec_fn=setsid)
387 except OSError:
388 return False
389 else:
390 return (p.poll() is None)
Georg Brandle8f24432005-10-03 14:16:44 +0000391
392
393class Grail(BaseBrowser):
Fred Drake3f8f1642001-07-19 03:46:26 +0000394 # There should be a way to maintain a connection to Grail, but the
395 # Grail remote control protocol doesn't really allow that at this
Georg Brandl23929f22006-01-20 21:03:35 +0000396 # point. It probably never will!
Fred Drake3f8f1642001-07-19 03:46:26 +0000397 def _find_grail_rc(self):
398 import glob
399 import pwd
400 import socket
401 import tempfile
402 tempdir = os.path.join(tempfile.gettempdir(),
403 ".grail-unix")
Fred Drake16623fe2001-10-13 16:00:52 +0000404 user = pwd.getpwuid(os.getuid())[0]
Fred Drake3f8f1642001-07-19 03:46:26 +0000405 filename = os.path.join(tempdir, user + "-*")
406 maybes = glob.glob(filename)
407 if not maybes:
408 return None
409 s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
410 for fn in maybes:
411 # need to PING each one until we find one that's live
412 try:
413 s.connect(fn)
414 except socket.error:
415 # no good; attempt to clean it out, but don't fail:
416 try:
417 os.unlink(fn)
418 except IOError:
419 pass
420 else:
421 return s
422
423 def _remote(self, action):
424 s = self._find_grail_rc()
425 if not s:
426 return 0
427 s.send(action)
428 s.close()
429 return 1
430
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000431 def open(self, url, new=0, autoraise=True):
Fred Drake3f8f1642001-07-19 03:46:26 +0000432 if new:
Georg Brandle8f24432005-10-03 14:16:44 +0000433 ok = self._remote("LOADNEW " + url)
Fred Drake3f8f1642001-07-19 03:46:26 +0000434 else:
Georg Brandle8f24432005-10-03 14:16:44 +0000435 ok = self._remote("LOAD " + url)
436 return ok
Fred Drake3f8f1642001-07-19 03:46:26 +0000437
Fred Drakec70b4482000-07-09 16:45:56 +0000438
Tim Peters658cba62001-02-09 20:06:00 +0000439#
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000440# Platform support for Unix
441#
Fred Drakec70b4482000-07-09 16:45:56 +0000442
Georg Brandle8f24432005-10-03 14:16:44 +0000443# These are the right tests because all these Unix browsers require either
444# a console terminal or an X display to run.
Fred Drakec70b4482000-07-09 16:45:56 +0000445
Neal Norwitz196f7332005-10-04 03:17:49 +0000446def register_X_browsers():
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000447
Matthias Kloseda80b1e2012-04-04 14:19:04 +0200448 # use xdg-open if around
449 if _iscommand("xdg-open"):
450 register("xdg-open", None, BackgroundBrowser("xdg-open"))
451
452 # The default GNOME3 browser
453 if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gvfs-open"):
454 register("gvfs-open", None, BackgroundBrowser("gvfs-open"))
455
Guido van Rossumd8faa362007-04-27 19:54:29 +0000456 # The default GNOME browser
457 if "GNOME_DESKTOP_SESSION_ID" in os.environ and _iscommand("gnome-open"):
458 register("gnome-open", None, BackgroundBrowser("gnome-open"))
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000459
Guido van Rossumd8faa362007-04-27 19:54:29 +0000460 # The default KDE browser
461 if "KDE_FULL_SESSION" in os.environ and _iscommand("kfmclient"):
462 register("kfmclient", Konqueror, Konqueror("kfmclient"))
463
464 # The Mozilla/Netscape browsers
Georg Brandl4a5a9182005-11-22 19:18:01 +0000465 for browser in ("mozilla-firefox", "firefox",
466 "mozilla-firebird", "firebird",
Thomas Wouters477c8d52006-05-27 19:21:47 +0000467 "seamonkey", "mozilla", "netscape"):
Georg Brandl4a5a9182005-11-22 19:18:01 +0000468 if _iscommand(browser):
469 register(browser, None, Mozilla(browser))
470
Georg Brandle8f24432005-10-03 14:16:44 +0000471 # Konqueror/kfm, the KDE browser.
Georg Brandlb9801132005-10-08 20:47:38 +0000472 if _iscommand("kfm"):
473 register("kfm", Konqueror, Konqueror("kfm"))
474 elif _iscommand("konqueror"):
475 register("konqueror", Konqueror, Konqueror("konqueror"))
Neal Norwitz8dd28eb2002-10-10 22:49:29 +0000476
Georg Brandle8f24432005-10-03 14:16:44 +0000477 # Gnome's Galeon and Epiphany
478 for browser in ("galeon", "epiphany"):
479 if _iscommand(browser):
480 register(browser, None, Galeon(browser))
Gustavo Niemeyer1456fde2002-11-25 17:25:04 +0000481
Georg Brandle8f24432005-10-03 14:16:44 +0000482 # Skipstone, another Gtk/Mozilla based browser
483 if _iscommand("skipstone"):
Georg Brandl23929f22006-01-20 21:03:35 +0000484 register("skipstone", None, BackgroundBrowser("skipstone"))
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000485
Senthil Kumaranea6b4182011-12-21 22:20:32 +0800486 # Google Chrome/Chromium browsers
487 for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"):
488 if _iscommand(browser):
489 register(browser, None, Chrome(browser))
490
Georg Brandle8f24432005-10-03 14:16:44 +0000491 # Opera, quite popular
492 if _iscommand("opera"):
493 register("opera", None, Opera("opera"))
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000494
Georg Brandle8f24432005-10-03 14:16:44 +0000495 # Next, Mosaic -- old but still in use.
496 if _iscommand("mosaic"):
Georg Brandl23929f22006-01-20 21:03:35 +0000497 register("mosaic", None, BackgroundBrowser("mosaic"))
Fred Drake3f8f1642001-07-19 03:46:26 +0000498
Georg Brandle8f24432005-10-03 14:16:44 +0000499 # Grail, the Python browser. Does anybody still use it?
500 if _iscommand("grail"):
501 register("grail", Grail, None)
Fred Drake3f8f1642001-07-19 03:46:26 +0000502
Neal Norwitz196f7332005-10-04 03:17:49 +0000503# Prefer X browsers if present
504if os.environ.get("DISPLAY"):
505 register_X_browsers()
506
Georg Brandle8f24432005-10-03 14:16:44 +0000507# Also try console browsers
508if os.environ.get("TERM"):
509 # The Links/elinks browsers <http://artax.karlin.mff.cuni.cz/~mikulas/links/>
510 if _iscommand("links"):
Georg Brandl23929f22006-01-20 21:03:35 +0000511 register("links", None, GenericBrowser("links"))
Georg Brandle8f24432005-10-03 14:16:44 +0000512 if _iscommand("elinks"):
513 register("elinks", None, Elinks("elinks"))
514 # The Lynx browser <http://lynx.isc.org/>, <http://lynx.browser.org/>
515 if _iscommand("lynx"):
Georg Brandl23929f22006-01-20 21:03:35 +0000516 register("lynx", None, GenericBrowser("lynx"))
Georg Brandle8f24432005-10-03 14:16:44 +0000517 # The w3m browser <http://w3m.sourceforge.net/>
518 if _iscommand("w3m"):
Georg Brandl23929f22006-01-20 21:03:35 +0000519 register("w3m", None, GenericBrowser("w3m"))
Fred Drake3f8f1642001-07-19 03:46:26 +0000520
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000521#
522# Platform support for Windows
523#
Fred Drakec70b4482000-07-09 16:45:56 +0000524
525if sys.platform[:3] == "win":
Georg Brandle8f24432005-10-03 14:16:44 +0000526 class WindowsDefault(BaseBrowser):
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000527 def open(self, url, new=0, autoraise=True):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000528 try:
529 os.startfile(url)
530 except WindowsError:
531 # [Error 22] No application is associated with the specified
532 # file for this operation: '<URL>'
533 return False
534 else:
535 return True
Georg Brandle8f24432005-10-03 14:16:44 +0000536
537 _tryorder = []
538 _browsers = {}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000539
540 # First try to use the default Windows browser
541 register("windows-default", WindowsDefault)
542
543 # Detect some common Windows browsers, fallback to IE
544 iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
545 "Internet Explorer\\IEXPLORE.EXE")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000546 for browser in ("firefox", "firebird", "seamonkey", "mozilla",
Guido van Rossumd8faa362007-04-27 19:54:29 +0000547 "netscape", "opera", iexplore):
Georg Brandle8f24432005-10-03 14:16:44 +0000548 if _iscommand(browser):
Georg Brandl23929f22006-01-20 21:03:35 +0000549 register(browser, None, BackgroundBrowser(browser))
Fred Drakec70b4482000-07-09 16:45:56 +0000550
Fred Drakec70b4482000-07-09 16:45:56 +0000551#
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000552# Platform support for MacOS
553#
Fred Drakec70b4482000-07-09 16:45:56 +0000554
Georg Brandle8f24432005-10-03 14:16:44 +0000555if sys.platform == 'darwin':
556 # Adapted from patch submitted to SourceForge by Steven J. Burr
557 class MacOSX(BaseBrowser):
558 """Launcher class for Aqua browsers on Mac OS X
559
560 Optionally specify a browser name on instantiation. Note that this
561 will not work for Aqua browsers if the user has moved the application
562 package after installation.
563
564 If no browser is specified, the default browser, as specified in the
565 Internet System Preferences panel, will be used.
566 """
567 def __init__(self, name):
568 self.name = name
569
Alexandre Vassalottie223eb82009-07-29 20:12:15 +0000570 def open(self, url, new=0, autoraise=True):
Georg Brandle8f24432005-10-03 14:16:44 +0000571 assert "'" not in url
Georg Brandl23929f22006-01-20 21:03:35 +0000572 # hack for local urls
573 if not ':' in url:
574 url = 'file:'+url
Tim Peters887c0802006-01-20 23:40:56 +0000575
Georg Brandle8f24432005-10-03 14:16:44 +0000576 # new must be 0 or 1
577 new = int(bool(new))
578 if self.name == "default":
579 # User called open, open_new or get without a browser parameter
Georg Brandl1cb179e2005-11-09 21:42:48 +0000580 script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
Georg Brandle8f24432005-10-03 14:16:44 +0000581 else:
582 # User called get and chose a browser
583 if self.name == "OmniWeb":
584 toWindow = ""
585 else:
586 # Include toWindow parameter of OpenURL command for browsers
587 # that support it. 0 == new window; -1 == existing
588 toWindow = "toWindow %d" % (new - 1)
Georg Brandl1cb179e2005-11-09 21:42:48 +0000589 cmd = 'OpenURL "%s"' % url.replace('"', '%22')
Georg Brandle8f24432005-10-03 14:16:44 +0000590 script = '''tell application "%s"
591 activate
592 %s %s
593 end tell''' % (self.name, cmd, toWindow)
594 # Open pipe to AppleScript through osascript command
595 osapipe = os.popen("osascript", "w")
596 if osapipe is None:
597 return False
598 # Write script to osascript's stdin
599 osapipe.write(script)
600 rc = osapipe.close()
601 return not rc
602
Ronald Oussoren4d39f6e2010-05-02 09:54:35 +0000603 class MacOSXOSAScript(BaseBrowser):
604 def __init__(self, name):
605 self._name = name
606
607 def open(self, url, new=0, autoraise=True):
608 if self._name == 'default':
609 script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
610 else:
611 script = '''
612 tell application "%s"
613 activate
614 open location "%s"
615 end
616 '''%(self._name, url.replace('"', '%22'))
617
618 osapipe = os.popen("osascript", "w")
619 if osapipe is None:
620 return False
621
622 osapipe.write(script)
623 rc = osapipe.close()
624 return not rc
625
626
Georg Brandle8f24432005-10-03 14:16:44 +0000627 # Don't clear _tryorder or _browsers since OS X can use above Unix support
628 # (but we prefer using the OS X specific stuff)
Ronald Oussoren4d39f6e2010-05-02 09:54:35 +0000629 register("safari", None, MacOSXOSAScript('safari'), -1)
630 register("firefox", None, MacOSXOSAScript('firefox'), -1)
631 register("MacOSX", None, MacOSXOSAScript('default'), -1)
Georg Brandle8f24432005-10-03 14:16:44 +0000632
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000633
Martin v. Löwis3a89b2b2001-11-25 14:35:58 +0000634#
635# Platform support for OS/2
636#
637
Georg Brandle8f24432005-10-03 14:16:44 +0000638if sys.platform[:3] == "os2" and _iscommand("netscape"):
639 _tryorder = []
640 _browsers = {}
Martin v. Löwis3a89b2b2001-11-25 14:35:58 +0000641 register("os2netscape", None,
Georg Brandl23929f22006-01-20 21:03:35 +0000642 GenericBrowser(["start", "netscape", "%s"]), -1)
Georg Brandle8f24432005-10-03 14:16:44 +0000643
Martin v. Löwis3a89b2b2001-11-25 14:35:58 +0000644
Eric S. Raymondf7f18512001-01-23 13:16:32 +0000645# OK, now that we know what the default preference orders for each
646# platform are, allow user to override them with the BROWSER variable.
Raymond Hettinger54f02222002-06-01 14:18:47 +0000647if "BROWSER" in os.environ:
Georg Brandle8f24432005-10-03 14:16:44 +0000648 _userchoices = os.environ["BROWSER"].split(os.pathsep)
649 _userchoices.reverse()
Skip Montanarocdab3bf2001-07-18 20:03:32 +0000650
Georg Brandle8f24432005-10-03 14:16:44 +0000651 # Treat choices in same way as if passed into get() but do register
652 # and prepend to _tryorder
653 for cmdline in _userchoices:
654 if cmdline != '':
Benjamin Peterson8719ad52009-09-11 22:24:02 +0000655 cmd = _synthesize(cmdline, -1)
656 if cmd[1] is None:
657 register(cmdline, None, GenericBrowser(cmdline), -1)
Georg Brandle8f24432005-10-03 14:16:44 +0000658 cmdline = None # to make del work if _userchoices was empty
659 del cmdline
660 del _userchoices
Skip Montanarocdab3bf2001-07-18 20:03:32 +0000661
Skip Montanarocdab3bf2001-07-18 20:03:32 +0000662# what to do if _tryorder is now empty?
Georg Brandle8f24432005-10-03 14:16:44 +0000663
664
665def main():
666 import getopt
667 usage = """Usage: %s [-n | -t] url
668 -n: open new window
669 -t: open new tab""" % sys.argv[0]
670 try:
671 opts, args = getopt.getopt(sys.argv[1:], 'ntd')
Guido van Rossumb940e112007-01-10 16:19:56 +0000672 except getopt.error as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000673 print(msg, file=sys.stderr)
674 print(usage, file=sys.stderr)
Georg Brandle8f24432005-10-03 14:16:44 +0000675 sys.exit(1)
676 new_win = 0
677 for o, a in opts:
678 if o == '-n': new_win = 1
679 elif o == '-t': new_win = 2
Guido van Rossumb053cd82006-08-24 03:53:23 +0000680 if len(args) != 1:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000681 print(usage, file=sys.stderr)
Georg Brandle8f24432005-10-03 14:16:44 +0000682 sys.exit(1)
683
684 url = args[0]
685 open(url, new_win)
686
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000687 print("\a")
Georg Brandl23929f22006-01-20 21:03:35 +0000688
Georg Brandle8f24432005-10-03 14:16:44 +0000689if __name__ == "__main__":
690 main()