1# Copyright 2013 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.
4import StringIO
5
6from telemetry.internal.backends.chrome_inspector import websocket
7
8
9class InspectorConsole(object):
10  def __init__(self, inspector_websocket):
11    self._inspector_websocket = inspector_websocket
12    self._inspector_websocket.RegisterDomain('Console', self._OnNotification)
13    self._message_output_stream = None
14    self._last_message = None
15    self._console_enabled = False
16
17  def _OnNotification(self, msg):
18    if msg['method'] == 'Console.messageAdded':
19      assert self._message_output_stream
20      if msg['params']['message']['url'] == 'chrome://newtab/':
21        return
22      self._last_message = '(%s) %s:%i: %s' % (
23        msg['params']['message']['level'],
24        msg['params']['message']['url'],
25        msg['params']['message']['line'],
26        msg['params']['message']['text'])
27      self._message_output_stream.write(
28        '%s\n' % self._last_message)
29
30    elif msg['method'] == 'Console.messageRepeatCountUpdated':
31      if self._message_output_stream:
32        self._message_output_stream.write(
33          '%s\n' % self._last_message)
34
35  def GetCurrentConsoleOutputBuffer(self, timeout=10):
36    self._message_output_stream = StringIO.StringIO()
37    self._EnableConsoleOutputStream()
38    try:
39      self._inspector_websocket.DispatchNotifications(timeout)
40      return self._message_output_stream.getvalue()
41    except websocket.WebSocketTimeoutException:
42      return self._message_output_stream.getvalue()
43    finally:
44      self._DisableConsoleOutputStream()
45      self._message_output_stream.close()
46      self._message_output_stream = None
47
48
49  def _EnableConsoleOutputStream(self):
50    self._inspector_websocket.SyncRequest({'method': 'Console.enable'})
51
52  def _DisableConsoleOutputStream(self):
53    self._inspector_websocket.SyncRequest({'method': 'Console.disable'})
54