OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 import os as real_os |
| 6 import sys as real_sys |
| 7 import subprocess as real_subprocess |
| 8 import urllib2 |
| 9 import json |
| 10 import tab |
| 11 |
| 12 import browser_finder |
| 13 |
| 14 class Browser(object): |
| 15 def __init__(self, options): |
| 16 self._executable = browser_finder.Find(options) |
| 17 if not self._executable: |
| 18 raise Exception("Cannot create browser, no executable found!") |
| 19 |
| 20 # TODO(nduca): Delete the user data dir or create one that is unique. |
| 21 tmpdir = "/tmp/simple-browser-controller-profile" |
| 22 if real_os.path.exists(tmpdir): |
| 23 ret = real_os.system("rm -rf -- %s" % tmpdir) |
| 24 assert ret == 0 |
| 25 self._port = options.remote_debugging_port |
| 26 args = [self._executable, |
| 27 "--no-first-run", |
| 28 "--remote-debugging-port=%i" % self._port] |
| 29 if not options.dont_override_profile: |
| 30 args.append("--user-data-dir=%s" % tmpdir) |
| 31 args.extend(options.args) |
| 32 if options.hide_stdout: |
| 33 self._devnull = open(real_os.devnull, 'w') |
| 34 self._proc = real_subprocess.Popen( |
| 35 args,stdout=self._devnull, stderr=self._devnull) |
| 36 else: |
| 37 self._devnull = None |
| 38 self._proc = real_subprocess.Popen(args) |
| 39 |
| 40 try: |
| 41 self._WaitForBrowserToComeUp() |
| 42 except: |
| 43 self.Close() |
| 44 raise |
| 45 |
| 46 def _WaitForBrowserToComeUp(self): |
| 47 while True: |
| 48 try: |
| 49 self._ListTabs() |
| 50 break |
| 51 except urllib2.URLError, ex: |
| 52 pass |
| 53 |
| 54 def _ListTabs(self): |
| 55 req = urllib2.urlopen("http://localhost:%i/json" % self._port) |
| 56 data = req.read() |
| 57 return json.loads(data) |
| 58 |
| 59 @property |
| 60 def num_tabs(self): |
| 61 return len(self._ListTabs()) |
| 62 |
| 63 def GetNthTabURL(self, index): |
| 64 return self._ListTabs()[index]["url"] |
| 65 |
| 66 def ConnectToNthTab(self, index): |
| 67 return tab.Tab(self, self._ListTabs()[index]) |
| 68 |
| 69 def __enter__(self): |
| 70 return self |
| 71 |
| 72 def __exit__(self, *args): |
| 73 if self._proc: |
| 74 self.Close() |
| 75 |
| 76 def Close(self): |
| 77 self._proc.terminate() |
| 78 self._proc.wait() |
| 79 self._proc = None |
| 80 |
| 81 if self._devnull: |
| 82 self._devnull.close() |
OLD | NEW |