22from socketserver import TCPServer
33from webbrowser import open_new_tab
44import pathlib
5+ import json
6+ import urllib .parse
57
68
7- def open_in_perfetto (tracefile : pathlib .Path ):
9+ def open_in_perfetto (tracefile : pathlib .Path , startupCommands = [] ):
810 print (f"Opening { str (tracefile )} on ui.perfetto.dev" )
9- content = tracefile .read_text ()
11+
12+ content = tracefile .read_bytes ()
13+ contentType = (
14+ "text/json" if tracefile .suffix == ".json" else "application/x-protobuf"
15+ )
1016
1117 PORT = 9001
1218 ORIGIN = "https://ui.perfetto.dev"
1319
1420 class TraceHandler (BaseHTTPRequestHandler ):
1521 def do_GET (self ):
16- if self .path != "/trace.json " :
22+ if self .path != "/trace/ " :
1723 self .send_error (405 )
1824
1925 self .server .trace_served = True
2026 self .send_response (200 )
2127 self .send_header ("Access-Control-Allow-Origin" , ORIGIN )
2228 self .send_header ("Cache-Control" , "no-cache" )
23- self .send_header ("Content-type" , "text/json" )
29+ self .send_header ("Content-type" , contentType )
2430 self .send_header ("Content-length" , str (len (content )))
2531 self .end_headers ()
26- self .wfile .write (content . encode () )
32+ self .wfile .write (content )
2733
2834 def do_POST (self ):
2935 self .send_error (405 )
@@ -35,7 +41,13 @@ def log_message(self, format, *args):
3541
3642 TCPServer .allow_reuse_address = True
3743 with TCPServer (("127.0.0.1" , PORT ), TraceHandler ) as httpd :
38- address = f"{ ORIGIN } /#!/?url=http://127.0.0.1:{ PORT } /trace.json"
44+ address = f"{ ORIGIN } /#!/?url=http://127.0.0.1:{ PORT } /trace/"
45+
46+ if startupCommands :
47+ print (json .dumps (startupCommands ))
48+ encoded = urllib .parse .quote (json .dumps (startupCommands ))
49+ address += f"&startupCommands={ encoded } "
50+
3951 open_new_tab (address )
4052
4153 httpd .trace_served = False
0 commit comments