2 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
6 # A simple native client in python.
7 # All this client does is echo the text it receives back at the extension.
14 def WriteMessage(message
):
16 sys
.stdout
.write(struct
.pack("I", len(message
)))
17 sys
.stdout
.write(message
)
30 sys
.stderr
.write("URL of the calling application is not specified.\n")
32 # TODO(sergeyu): Use argparse module to parse the arguments (not available in
34 for arg
in sys
.argv
[1:]:
35 if arg
.startswith('--'):
36 if arg
.startswith('--parent-window='):
37 parent_window
= long(arg
[len('--parent-window='):])
38 elif caller_url
== None:
41 if platform
.system() == 'Windows':
43 if parent_window
and not win32gui
.IsWindow(parent_window
):
44 sys
.stderr
.write('Invalid --parent-window.\n')
48 # Read the message type (first 4 bytes).
49 text_length_bytes
= sys
.stdin
.read(4)
51 if len(text_length_bytes
) == 0:
54 # Read the message length (4 bytes).
55 text_length
= struct
.unpack('i', text_length_bytes
)[0]
57 # Read the text (JSON object) of the message.
58 text
= sys
.stdin
.read(text_length
).decode('utf-8')
60 # bigMessage() test sends a special message that is sent to verify that
61 # chrome rejects messages that are too big. Try sending a message bigger
62 # than 1MB after receiving a message that contains 'bigMessageTest'.
63 if 'bigMessageTest' in text
:
64 text
= '{"key": "' + ("x" * 1024 * 1024) + '"}'
66 # "stopHostTest" verifies that Chrome properly handles the case when the
67 # host quits before port is closed. When the test receives response it
68 # will try sending second message and it should fail becasue the stdin
69 # pipe will be closed at that point.
70 if 'stopHostTest' in text
:
71 # Using os.close() here because sys.stdin.close() doesn't really close
72 # the pipe (it just marks it as closed, but doesn't close the file
74 os
.close(sys
.stdin
.fileno())
75 WriteMessage('{"stopped": true }')
80 message
= '{{"id": {0}, "echo": {1}, "caller_url": "{2}"}}'.format(
81 message_number
, text
, caller_url
).encode('utf-8')
82 if not WriteMessage(message
):
85 if __name__
== '__main__':