DevTools: cut host and port from webSocketDebuggerUrl in addition to ws:// prefix
[chromium-blink-merge.git] / content / browser / devtools / protocol / devtools_protocol_handler_generator.py
blob0ba741503f998fadc2e1893eaaac382fcca70eb2
1 #!/usr/bin/env python
2 # Copyright 2014 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 import sys
7 import string
8 import json
10 blink_protocol_path = sys.argv[1]
11 browser_protocol_path = sys.argv[2]
12 output_cc_path = sys.argv[3]
13 output_h_path = sys.argv[4]
15 header = """\
16 // Copyright 2014 The Chromium Authors. All rights reserved.
17 // Use of this source code is governed by a BSD-style license that can be
18 // found in the LICENSE file.
20 // THIS FILE IS AUTOGENERATED. DO NOT EDIT.
21 // Generated by
22 // content/public/browser/devtools_protocol_handler_generator.py from
23 // third_party/WebKit/Source/devtools/protocol.json and
24 // content/browser/devtools/browser_protocol.json
25 """
27 template_h = string.Template(header + """\
29 #ifndef CONTENT_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_PROTOCOL_DISPATCHER_H_
30 #define CONTENT_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_PROTOCOL_DISPATCHER_H_
32 #include "content/browser/devtools/protocol/devtools_protocol_client.h"
34 namespace content {
36 class DevToolsProtocolDispatcher;
38 namespace devtools {
40 extern const char kProtocolVersion[];
42 bool IsSupportedProtocolVersion(const std::string& version);
44 template<typename T>
45 base::Value* CreateValue(const T& param) {
46 return new base::FundamentalValue(param);
49 template<class T>
50 base::Value* CreateValue(scoped_ptr<T>& param) {
51 return param.release();
54 template<class T>
55 base::Value* CreateValue(scoped_refptr<T> param) {
56 return param->ToValue().release();
59 template<typename T>
60 base::Value* CreateValue(const std::vector<T> param) {
61 base::ListValue* result = new base::ListValue();
62 for (auto& item : param) {
63 result->Append(CreateValue(item));
65 return result;
68 template<>
69 base::Value* CreateValue(const std::string& param);
71 ${types}\
73 } // namespace devtools
75 class DevToolsProtocolDispatcher {
76 public:
77 using Notifier = DevToolsProtocolClient::RawMessageCallback;
78 using CommandHandler =
79 base::Callback<bool(int, scoped_ptr<base::DictionaryValue>)>;
81 explicit DevToolsProtocolDispatcher(const Notifier& notifier);
82 ~DevToolsProtocolDispatcher();
84 CommandHandler FindCommandHandler(const std::string& method);
86 ${setters}\
88 private:
89 using Response = DevToolsProtocolClient::Response;
90 using CommandHandlers = std::map<std::string, CommandHandler>;
92 ${methods}\
94 Notifier notifier_;
95 DevToolsProtocolClient client_;
96 CommandHandlers command_handlers_;
97 ${fields}\
100 } // namespace content
102 #endif // CONTENT_BROWSER_DEVTOOLS_PROTOCOL_DEVTOOLS_PROTOCOL_DISPATCHER_H_
103 """)
105 tmpl_typedef = string.Template("""\
106 namespace ${domain} {
107 typedef ${param_type} ${declared_name};
108 } // namespace ${domain}
109 """)
111 tmpl_struct = string.Template("""\
112 namespace ${domain} {
113 template<int MASK>
114 struct ${declared_name}Builder
115 : base::RefCounted<${declared_name}Builder<MASK>> {
116 public:
117 enum {
118 kAllSet = 0,
119 ${fields_enum}\
122 ${methods}\
124 static scoped_refptr<${declared_name}Builder<kNoneSet>> Create() {
125 return new ${declared_name}Builder<kNoneSet>();
128 scoped_ptr<base::DictionaryValue> ToValue() {
129 static_assert(MASK == kAllSet, "required properties missing");
130 return make_scoped_ptr(dict_->DeepCopy());
133 private:
134 friend struct ${declared_name}Builder<0>;
136 ${declared_name}Builder() : dict_(new base::DictionaryValue()) {
139 template<class T> T* ThisAs() {
140 static_assert(sizeof(*this) == sizeof(T), "cannot cast");
141 return reinterpret_cast<T*>(this);
144 scoped_ptr<base::DictionaryValue> dict_;
147 typedef ${declared_name}Builder<0> ${declared_name};
149 } // namespace ${domain}
150 """)
152 tmpl_builder_setter_req = string.Template("""\
153 scoped_refptr<${declared_name}Builder<MASK & ~k${Param}>>
154 set_${param}(${pass_type} ${param}) {
155 static_assert(MASK & k${Param}, "already set");
156 dict_->Set("${proto_param}", CreateValue(${param}));
157 return ThisAs<${declared_name}Builder<MASK & ~k${Param}>>();
159 """)
161 tmpl_builder_setter_opt = string.Template("""\
162 scoped_refptr<${declared_name}Builder<MASK>>
163 set_${param}(${pass_type} ${param}) {
164 dict_->Set("${proto_param}", CreateValue(${param}));
165 return this;
167 """)
169 tmpl_builder_enum = string.Template("""\
170 k${Param} = 1 << ${ordinal},
171 """)
173 tmpl_builder_none_set = string.Template("""\
174 kNoneSet = ${all_fields}
175 """)
177 tmpl_named_enum = string.Template("""\
178 namespace ${domain} {
179 ${values}\
180 } // namespace ${domain}
181 """)
183 tmpl_inline_enum = string.Template("""\
184 namespace ${domain} {
185 namespace ${subdomain} {
186 ${values}\
187 } // namespace ${subdomain}
188 } // namespace ${domain}
189 """)
191 tmpl_enum_value = string.Template("""\
192 extern const char k${Enum}${Value}[];
193 """)
195 tmpl_enum_value_def = string.Template("""\
196 const char k${Enum}${Value}[] = "${value}";
197 """)
199 tmpl_handler = string.Template("""\
200 namespace ${domain} {
201 class ${Domain}Handler;
202 } // namespace domain
203 """)
205 tmpl_client = string.Template("""\
206 namespace ${domain} {
207 class Client : public DevToolsProtocolClient {
208 public:
209 explicit Client(const RawMessageCallback& raw_message_callback);
210 ~Client() override;
212 ${methods}\
214 } // namespace ${domain}
215 """)
217 tmpl_event = string.Template("""\
218 void ${Command}(
219 scoped_refptr<${Command}Params> params);
220 """)
222 tmpl_response = string.Template("""\
223 void Send${Command}Response(
224 DevToolsCommandId command_id,
225 scoped_refptr<${Command}Response> params);
226 """)
228 tmpl_setter = string.Template("""\
229 void Set${Domain}Handler(
230 devtools::${domain}::${Domain}Handler* ${domain}_handler);
231 """)
233 tmpl_callback = string.Template("""\
234 bool On${Domain}${Command}(
235 DevToolsCommandId command_id,
236 scoped_ptr<base::DictionaryValue> params);
237 """)
239 tmpl_field = string.Template("""\
240 devtools::${domain}::${Domain}Handler* ${domain}_handler_;
241 """)
243 template_cc = string.Template(header + """\
245 #include "base/bind.h"
246 #include "base/strings/string_number_conversions.h"
247 ${includes}\
249 namespace content {
251 DevToolsProtocolDispatcher::DevToolsProtocolDispatcher(
252 const Notifier& notifier)
253 : notifier_(notifier),
254 client_(notifier),
255 ${fields_init} {
258 DevToolsProtocolDispatcher::~DevToolsProtocolDispatcher() {
261 DevToolsProtocolDispatcher::CommandHandler
262 DevToolsProtocolDispatcher::FindCommandHandler(const std::string& method) {
263 CommandHandlers::iterator it = command_handlers_.find(method);
264 return it == command_handlers_.end() ? CommandHandler() : it->second;
267 ${methods}\
269 namespace devtools {
271 const char kProtocolVersion[] = "${major}.${minor}";
273 bool IsSupportedProtocolVersion(const std::string& version) {
274 std::vector<std::string> tokens;
275 Tokenize(version, ".", &tokens);
276 int major, minor;
277 return tokens.size() == 2 &&
278 base::StringToInt(tokens[0], &major) && major == ${major} &&
279 base::StringToInt(tokens[1], &minor) && minor <= ${minor};
282 template<>
283 base::Value* CreateValue(const std::string& param) {
284 return new base::StringValue(param);
287 ${types}\
289 } // namespace devtools
291 } // namespace content
292 """)
294 tmpl_include = string.Template("""\
295 #include "content/browser/devtools/protocol/${domain}_handler.h"
296 """)
298 tmpl_field_init = string.Template("${domain}_handler_(nullptr)")
300 tmpl_setter_impl = string.Template("""\
301 void DevToolsProtocolDispatcher::Set${Domain}Handler(
302 devtools::${domain}::${Domain}Handler* ${domain}_handler) {
303 DCHECK(!${domain}_handler_);
304 ${domain}_handler_ = ${domain}_handler;
305 ${initializations}\
307 """)
309 tmpl_register = string.Template("""\
310 command_handlers_["${Domain}.${command}"] =
311 base::Bind(
312 &DevToolsProtocolDispatcher::On${TargetDomain}${Command},
313 base::Unretained(this));
314 """)
316 tmpl_init_client = string.Template("""\
317 ${domain}_handler_->SetClient(make_scoped_ptr(
318 new devtools::${domain}::Client(notifier_)));
319 """)
321 tmpl_callback_impl = string.Template("""\
322 bool DevToolsProtocolDispatcher::On${Domain}${Command}(
323 DevToolsCommandId command_id,
324 scoped_ptr<base::DictionaryValue> params) {
325 ${prep}\
326 Response response = ${domain}_handler_->${Command}(${args});
327 scoped_ptr<base::DictionaryValue> protocol_response;
328 if (client_.SendError(command_id, response))
329 return true;
330 if (response.IsFallThrough())
331 return false;
332 scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue());
333 ${wrap}\
334 client_.SendSuccess(command_id, result.Pass());
335 return true;
337 """)
339 tmpl_wrap = string.Template("""\
340 result->Set("${proto_param}", devtools::CreateValue(out_${param}));
341 """)
343 tmpl_callback_async_impl = string.Template("""\
344 bool DevToolsProtocolDispatcher::On${Domain}${Command}(
345 DevToolsCommandId command_id,
346 scoped_ptr<base::DictionaryValue> params) {
347 ${prep}\
348 Response response = ${domain}_handler_->${Command}(${args});
349 if (client_.SendError(command_id, response))
350 return true;
351 return !response.IsFallThrough();
353 """)
355 tmpl_prep_req = string.Template("""\
356 ${raw_type} in_${param}${init};
357 if (!params || !params->Get${Type}("${proto_param}", &in_${param})) {
358 client_.SendError(command_id, Response::InvalidParams("${proto_param}"));
359 return true;
361 """)
363 tmpl_prep_req_list = string.Template("""\
364 base::ListValue* list_${param} = nullptr;
365 if (!params || !params->GetList("${proto_param}", &list_${param})) {
366 client_.SendError(command_id, Response::InvalidParams("${proto_param}"));
367 return true;
369 std::vector<${item_type}> in_${param};
370 for (base::ListValue::const_iterator it =
371 list_${param}->begin(); it != list_${param}->end(); ++it) {
372 ${item_raw_type} item;
373 if (!(*it)->GetAs${ItemType}(&item)) {
374 client_.SendError(command_id, Response::InvalidParams("${proto_param}"));
375 return true;
377 in_${param}.push_back(${item_pass});
379 """)
381 tmpl_prep_opt = string.Template("""\
382 ${raw_type} in_${param}${init};
383 bool ${param}_found = params && params->Get${Type}(
384 "${proto_param}",
385 &in_${param});
386 """)
388 tmpl_prep_output = string.Template("""\
389 ${param_type} out_${param}${init};
390 """)
392 tmpl_arg_name = string.Template("in_${param}")
394 tmpl_arg_req = string.Template("${param_pass}")
396 tmpl_arg_opt = string.Template(
397 "${param}_found ? ${param_pass} : nullptr")
399 tmpl_object_pass = string.Template(
400 "make_scoped_ptr<base::DictionaryValue>(${name}->DeepCopy())")
402 tmpl_client_impl = string.Template("""\
403 namespace ${domain} {
405 Client::Client(const RawMessageCallback& raw_message_callback)
406 : DevToolsProtocolClient(raw_message_callback) {
409 Client::~Client() {
412 ${methods}\
414 } // namespace ${domain}
415 """)
417 tmpl_event_impl = string.Template("""\
418 void Client::${Command}(
419 scoped_refptr<${Command}Params> params) {
420 SendNotification("${Domain}.${command}",
421 params->ToValue().Pass());
423 """)
425 tmpl_response_impl = string.Template("""\
426 void Client::Send${Command}Response(
427 DevToolsCommandId command_id,
428 scoped_refptr<${Command}Response> params) {
429 SendSuccess(command_id, params->ToValue().Pass());
431 """)
433 tmpl_typename = string.Template("devtools::${domain}::${declared_name}")
435 def Capitalize(s):
436 return s[:1].upper() + s[1:]
438 def Uncamelcase(s):
439 result = ""
440 for i, c in enumerate(s):
441 if c.isupper():
442 if (i > 0) and ((i < len(s)-1) and s[i+1].islower() or s[i-1].islower()):
443 result += "_"
444 result += c.lower()
445 else:
446 result += c
447 return result
449 types = {}
450 blink_protocol = json.loads(open(blink_protocol_path, "r").read())
451 browser_protocol = json.loads(open(browser_protocol_path, "r").read())
452 type_decls = []
453 type_impls = []
454 handler_methods = []
455 handler_method_impls = []
456 domain_maps = []
457 redirects = {}
459 all_domains = blink_protocol["domains"] + browser_protocol["domains"]
461 for json_domain in all_domains:
462 if "types" in json_domain:
463 for json_type in json_domain["types"]:
464 types["%s.%s" % (json_domain["domain"], json_type["id"])] = json_type
466 def DeclareStruct(json_properties, mapping):
467 methods = []
468 fields_enum = []
469 enum_items = []
470 req_fields_num = 0
471 for json_prop in json_properties:
472 prop_map = mapping.copy()
473 prop_map["proto_param"] = json_prop["name"]
474 prop_map["param"] = Uncamelcase(json_prop["name"])
475 prop_map["Param"] = Capitalize(json_prop["name"])
476 prop_map["subdomain"] = Uncamelcase(prop_map["declared_name"])
477 del prop_map["declared_name"]
478 ResolveType(json_prop, prop_map)
479 prop_map["declared_name"] = mapping["declared_name"]
480 if json_prop.get("optional"):
481 methods.append(tmpl_builder_setter_opt.substitute(prop_map))
482 else:
483 methods.append(tmpl_builder_setter_req.substitute(prop_map))
484 enum_items.append("k%s" % prop_map["Param"]);
485 fields_enum.append(tmpl_builder_enum.substitute(prop_map,
486 ordinal = req_fields_num))
487 req_fields_num += 1
489 all_fields = "kAllSet"
490 if len(enum_items) > 0:
491 all_fields = " | ".join(enum_items)
492 fields_enum.append(tmpl_builder_none_set.substitute(mapping,
493 all_fields = all_fields))
494 type_decls.append(tmpl_struct.substitute(mapping,
495 methods = "\n".join(methods),
496 fields_enum = "".join(fields_enum)))
498 def DeclareEnum(json, mapping):
499 values = []
500 value_defs = []
501 tmpl_enum = tmpl_inline_enum
502 if "declared_name" in mapping:
503 mapping["Enum"] = mapping["declared_name"]
504 tmpl_enum = tmpl_named_enum
505 else:
506 mapping["Enum"] = Capitalize(mapping["proto_param"])
508 for enum_value in json["enum"]:
509 values.append(tmpl_enum_value.substitute(mapping,
510 Value = Capitalize(enum_value)))
511 value_defs.append(tmpl_enum_value_def.substitute(mapping,
512 value = enum_value,
513 Value = Capitalize(enum_value)))
514 type_decls.append(tmpl_enum.substitute(mapping,
515 values = "".join(values)))
516 type_impls.append(tmpl_enum.substitute(mapping,
517 values = "".join(value_defs)))
519 def ResolveRef(json, mapping):
520 dot_pos = json["$ref"].find(".")
521 if dot_pos == -1:
522 domain_name = mapping["Domain"]
523 type_name = json["$ref"]
524 else:
525 domain_name = json["$ref"][:dot_pos]
526 type_name = json["$ref"][dot_pos + 1:]
527 json_type = types["%s.%s" % (domain_name, type_name)]
528 mapping["declared_name"] = Capitalize(type_name)
529 mapping["Domain"] = domain_name
530 mapping["domain"] = Uncamelcase(domain_name)
531 mapping["param_type"] = tmpl_typename.substitute(mapping)
532 ResolveType(json_type, mapping)
533 if not "___type_declared" in json_type:
534 json_type["___type_declared"] = True;
535 if (json_type.get("type") == "object") and ("properties" in json_type):
536 DeclareStruct(json_type["properties"], mapping)
537 else:
538 if ("enum" in json_type):
539 DeclareEnum(json_type, mapping)
540 type_decls.append(tmpl_typedef.substitute(mapping))
542 def ResolveArray(json, mapping):
543 items_map = mapping.copy()
544 ResolveType(json["items"], items_map)
545 if items_map["Type"] == "List":
546 # TODO(dgozman) Implement this.
547 raise Exception("Nested arrays are not implemented")
548 mapping["param_type"] = "std::vector<%s>" % items_map["param_type"]
549 mapping["Type"] = "List"
550 mapping["pass_type"] = "const %s&" % mapping["param_type"]
551 mapping["storage_type"] = "std::vector<%s>" % items_map["storage_type"]
552 mapping["raw_type"] = mapping["storage_type"]
553 mapping["prep_req"] = tmpl_prep_req_list.substitute(mapping,
554 item_type = items_map["storage_type"],
555 item_init = items_map["init"],
556 item_raw_type = items_map["raw_type"],
557 item_pass = items_map["pass_template"].substitute(name="item", opt=""),
558 ItemType = items_map["Type"])
559 mapping["arg_out"] = "&out_%s" % mapping["param"]
561 def ResolveObject(json, mapping):
562 mapping["Type"] = "Dictionary"
563 mapping["storage_type"] = "scoped_ptr<base::DictionaryValue>"
564 mapping["raw_type"] = "base::DictionaryValue*"
565 mapping["pass_template"] = tmpl_object_pass
566 if "properties" in json:
567 if not "declared_name" in mapping:
568 mapping["declared_name"] = ("%s%s" %
569 (mapping["Command"], Capitalize(mapping["proto_param"])))
570 mapping["param_type"] = ("scoped_refptr<%s>" %
571 tmpl_typename.substitute(mapping))
572 DeclareStruct(json["properties"], mapping)
573 else:
574 mapping["param_type"] = ("scoped_refptr<%s>" %
575 tmpl_typename.substitute(mapping))
576 mapping["pass_type"] = mapping["param_type"]
577 mapping["arg_out"] = "&out_%s" % mapping["param"]
578 else:
579 mapping["param_type"] = "base::DictionaryValue"
580 mapping["pass_type"] = "scoped_ptr<base::DictionaryValue>"
581 mapping["arg_out"] = "out_%s.get()" % mapping["param"]
582 mapping["prep_req"] = tmpl_prep_req.substitute(mapping)
584 def ResolvePrimitive(json, mapping):
585 jsonrpc_type = json["type"]
586 if jsonrpc_type == "boolean":
587 mapping["param_type"] = "bool"
588 mapping["Type"] = "Boolean"
589 mapping["init"] = " = false"
590 elif jsonrpc_type == "integer":
591 mapping["param_type"] = "int"
592 mapping["Type"] = "Integer"
593 mapping["init"] = " = 0"
594 elif jsonrpc_type == "number":
595 mapping["param_type"] = "double"
596 mapping["Type"] = "Double"
597 mapping["init"] = " = 0.0"
598 elif jsonrpc_type == "string":
599 mapping["param_type"] = "std::string"
600 mapping["pass_type"] = "const std::string&"
601 mapping["Type"] = "String"
602 if "enum" in json and not "declared_name" in mapping:
603 if not "subdomain" in mapping:
604 mapping["subdomain"] = Uncamelcase(mapping["command"])
605 DeclareEnum(json, mapping)
606 else:
607 raise Exception("Unknown type: %s" % json_type)
608 mapping["storage_type"] = mapping["param_type"]
609 mapping["raw_type"] = mapping["param_type"]
610 mapping["prep_req"] = tmpl_prep_req.substitute(mapping)
611 if jsonrpc_type != "string":
612 mapping["pass_type"] = mapping["param_type"]
613 mapping["arg_out"] = "&out_%s" % mapping["param"]
615 def ResolveType(json, mapping):
616 mapping["init"] = ""
617 mapping["pass_template"] = string.Template("${opt}${name}")
618 if "$ref" in json:
619 ResolveRef(json, mapping)
620 elif "type" in json:
621 jsonrpc_type = json["type"]
622 if jsonrpc_type == "array":
623 ResolveArray(json, mapping)
624 elif jsonrpc_type == "object":
625 ResolveObject(json, mapping)
626 else:
627 ResolvePrimitive(json, mapping)
628 else:
629 raise Exception("Unknown type at %s.%s %s" %
630 (mapping["Domain"], mapping["command"], mapping["proto_param"]))
632 setters = []
633 fields = []
635 includes = []
636 fields_init = []
638 for json_domain in all_domains:
639 domain_map = {}
640 domain_map["Domain"] = json_domain["domain"]
641 domain_map["domain"] = Uncamelcase(json_domain["domain"])
643 initializations = []
644 client_methods = []
645 client_method_impls = []
646 domain_empty = True
647 domain_needs_client = False
649 if "commands" in json_domain:
650 for json_command in json_domain["commands"]:
651 if (not ("handlers" in json_command) or
652 not ("browser" in json_command["handlers"])):
653 continue
654 domain_empty = False
656 command_map = domain_map.copy()
657 command_map["command"] = json_command["name"]
658 command_map["Command"] = Capitalize(json_command["name"])
660 if "redirect" in json_command:
661 redirect_domain = json_command["redirect"]
662 if not (redirect_domain in redirects):
663 redirects[redirect_domain] = []
664 command_map["TargetDomain"] = redirect_domain
665 redirects[redirect_domain].append(tmpl_register.substitute(command_map))
666 continue
668 command_map["TargetDomain"] = command_map["Domain"]
669 prep = []
670 args = []
672 if "parameters" in json_command:
673 for json_param in json_command["parameters"]:
674 param_map = command_map.copy()
675 param_map["proto_param"] = json_param["name"]
676 param_map["param"] = Uncamelcase(json_param["name"])
677 ResolveType(json_param, param_map)
678 if json_param.get("optional"):
679 if param_map["Type"] in ["List"]:
680 # TODO(vkuzkokov) Implement transformation of base::ListValue
681 # to std::vector and base::DictonaryValue to struct.
682 raise Exception(
683 "Optional array parameters are not implemented")
684 prep.append(tmpl_prep_opt.substitute(param_map))
685 param_pass = param_map["pass_template"].substitute(
686 name=tmpl_arg_name.substitute(param_map),
687 opt="&")
688 args.append(
689 tmpl_arg_opt.substitute(param_map, param_pass=param_pass))
690 else:
691 prep.append(param_map["prep_req"])
692 param_pass = param_map["pass_template"].substitute(
693 name=tmpl_arg_name.substitute(param_map),
694 opt="")
695 args.append(
696 tmpl_arg_req.substitute(param_map, param_pass=param_pass))
698 if json_command.get("async"):
699 domain_needs_client = True
700 json_returns = []
701 if "returns" in json_command:
702 json_returns = json_command["returns"]
703 command_map["declared_name"] = "%sResponse" % command_map["Command"]
704 DeclareStruct(json_returns, command_map)
705 # TODO(vkuzkokov) Pass async callback instance similar to how
706 # InspectorBackendDispatcher does it. This, however, can work
707 # only if Blink and Chrome are in the same repo.
708 args.insert(0, "command_id")
709 handler_method_impls.append(
710 tmpl_callback_async_impl.substitute(command_map,
711 prep = "".join(prep),
712 args = "\n " + ",\n ".join(args)))
713 client_methods.append(tmpl_response.substitute(command_map))
714 client_method_impls.append(tmpl_response_impl.substitute(command_map))
715 else:
716 wrap = []
717 if "returns" in json_command:
718 for json_param in json_command["returns"]:
719 param_map = command_map.copy()
720 param_map["proto_param"] = json_param["name"]
721 param_map["param"] = Uncamelcase(json_param["name"])
722 if json_param.get("optional"):
723 # TODO(vkuzkokov) Implement Optional<T> for value types.
724 raise Exception("Optional return values are not implemented")
725 ResolveType(json_param, param_map)
726 prep.append(tmpl_prep_output.substitute(param_map))
727 args.append(param_map["arg_out"])
728 wrap.append(tmpl_wrap.substitute(param_map))
729 args_str = ""
730 if len(args) > 0:
731 args_str = "\n " + ",\n ".join(args)
732 handler_method_impls.append(tmpl_callback_impl.substitute(command_map,
733 prep = "".join(prep),
734 args = args_str,
735 wrap = "".join(wrap)))
737 initializations.append(tmpl_register.substitute(command_map))
738 handler_methods.append(tmpl_callback.substitute(command_map))
740 if "events" in json_domain:
741 for json_event in json_domain["events"]:
742 if (not ("handlers" in json_event) or
743 not ("browser" in json_event["handlers"])):
744 continue
745 domain_empty = False
746 domain_needs_client = True
748 event_map = domain_map.copy()
749 event_map["command"] = json_event["name"]
750 event_map["Command"] = Capitalize(json_event["name"])
752 json_parameters = []
753 if "parameters" in json_event:
754 json_parameters = json_event["parameters"]
755 event_map["declared_name"] = "%sParams" % event_map["Command"]
756 DeclareStruct(json_parameters, event_map);
758 client_methods.append(tmpl_event.substitute(event_map))
759 client_method_impls.append(tmpl_event_impl.substitute(event_map))
761 if domain_empty:
762 continue
763 type_decls.append(tmpl_handler.substitute(domain_map))
764 setters.append(tmpl_setter.substitute(domain_map))
765 fields.append(tmpl_field.substitute(domain_map))
766 includes.append(tmpl_include.substitute(domain_map))
767 fields_init.append(tmpl_field_init.substitute(domain_map))
768 if domain_needs_client:
769 type_decls.append(tmpl_client.substitute(domain_map,
770 methods = "".join(client_methods)))
771 initializations.append(tmpl_init_client.substitute(domain_map))
772 type_impls.append(tmpl_client_impl.substitute(domain_map,
773 methods = "\n".join(client_method_impls)))
774 domain_map["initializations"] = "".join(initializations)
775 domain_maps.append(domain_map)
777 for domain_map in domain_maps:
778 domain = domain_map["Domain"]
779 if domain in redirects:
780 domain_map["initializations"] += "".join(redirects[domain])
781 handler_method_impls.append(tmpl_setter_impl.substitute(domain_map))
783 output_h_file = open(output_h_path, "w")
784 output_cc_file = open(output_cc_path, "w")
786 output_h_file.write(template_h.substitute({},
787 types = "\n".join(type_decls),
788 setters = "".join(setters),
789 methods = "".join(handler_methods),
790 fields = "".join(fields)))
791 output_h_file.close()
793 output_cc_file.write(template_cc.substitute({},
794 major = blink_protocol["version"]["major"],
795 minor = blink_protocol["version"]["minor"],
796 includes = "".join(sorted(includes)),
797 fields_init = ",\n ".join(fields_init),
798 methods = "\n".join(handler_method_impls),
799 types = "\n".join(type_impls)))
800 output_cc_file.close()