Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / content / browser / devtools / protocol / devtools_protocol_handler_generator.py
blobcc2aa130b6840e6f2585bc825df34929bf91f3dc
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 "content/browser/devtools/protocol/devtools_protocol_handler.h"
247 #include "base/bind.h"
248 #include "base/strings/string_number_conversions.h"
249 ${includes}\
251 namespace content {
253 DevToolsProtocolDispatcher::DevToolsProtocolDispatcher(
254 const Notifier& notifier)
255 : notifier_(notifier),
256 client_(notifier),
257 ${fields_init} {
260 DevToolsProtocolDispatcher::~DevToolsProtocolDispatcher() {
263 DevToolsProtocolDispatcher::CommandHandler
264 DevToolsProtocolDispatcher::FindCommandHandler(const std::string& method) {
265 CommandHandlers::iterator it = command_handlers_.find(method);
266 return it == command_handlers_.end() ? CommandHandler() : it->second;
269 ${methods}\
271 namespace devtools {
273 const char kProtocolVersion[] = "${major}.${minor}";
275 bool IsSupportedProtocolVersion(const std::string& version) {
276 std::vector<std::string> tokens;
277 Tokenize(version, ".", &tokens);
278 int major, minor;
279 return tokens.size() == 2 &&
280 base::StringToInt(tokens[0], &major) && major == ${major} &&
281 base::StringToInt(tokens[1], &minor) && minor <= ${minor};
284 template<>
285 base::Value* CreateValue(const std::string& param) {
286 return new base::StringValue(param);
289 ${types}\
291 } // namespace devtools
293 } // namespace content
294 """)
296 tmpl_include = string.Template("""\
297 #include "content/browser/devtools/protocol/${domain}_handler.h"
298 """)
300 tmpl_field_init = string.Template("${domain}_handler_(nullptr)")
302 tmpl_setter_impl = string.Template("""\
303 void DevToolsProtocolDispatcher::Set${Domain}Handler(
304 devtools::${domain}::${Domain}Handler* ${domain}_handler) {
305 DCHECK(!${domain}_handler_);
306 ${domain}_handler_ = ${domain}_handler;
307 ${initializations}\
309 """)
311 tmpl_register = string.Template("""\
312 command_handlers_["${Domain}.${command}"] =
313 base::Bind(
314 &DevToolsProtocolDispatcher::On${TargetDomain}${Command},
315 base::Unretained(this));
316 """)
318 tmpl_init_client = string.Template("""\
319 ${domain}_handler_->SetClient(make_scoped_ptr(
320 new devtools::${domain}::Client(notifier_)));
321 """)
323 tmpl_callback_impl = string.Template("""\
324 bool DevToolsProtocolDispatcher::On${Domain}${Command}(
325 DevToolsCommandId command_id,
326 scoped_ptr<base::DictionaryValue> params) {
327 ${prep}\
328 Response response = ${domain}_handler_->${Command}(${args});
329 scoped_ptr<base::DictionaryValue> protocol_response;
330 if (client_.SendError(command_id, response))
331 return true;
332 if (response.IsFallThrough())
333 return false;
334 scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue());
335 ${wrap}\
336 client_.SendSuccess(command_id, result.Pass());
337 return true;
339 """)
341 tmpl_wrap = string.Template("""\
342 result->Set("${proto_param}", devtools::CreateValue(out_${param}));
343 """)
345 tmpl_callback_async_impl = string.Template("""\
346 bool DevToolsProtocolDispatcher::On${Domain}${Command}(
347 DevToolsCommandId command_id,
348 scoped_ptr<base::DictionaryValue> params) {
349 ${prep}\
350 Response response = ${domain}_handler_->${Command}(${args});
351 if (client_.SendError(command_id, response))
352 return true;
353 return !response.IsFallThrough();
355 """)
357 tmpl_prep_req = string.Template("""\
358 ${raw_type} in_${param}${init};
359 if (!params || !params->Get${Type}("${proto_param}", &in_${param})) {
360 client_.SendError(command_id, Response::InvalidParams("${proto_param}"));
361 return true;
363 """)
365 tmpl_prep_req_list = string.Template("""\
366 base::ListValue* list_${param} = nullptr;
367 if (!params || !params->GetList("${proto_param}", &list_${param})) {
368 client_.SendError(command_id, Response::InvalidParams("${proto_param}"));
369 return true;
371 std::vector<${item_type}> in_${param};
372 for (base::ListValue::const_iterator it =
373 list_${param}->begin(); it != list_${param}->end(); ++it) {
374 ${item_raw_type} item;
375 if (!(*it)->GetAs${ItemType}(&item)) {
376 client_.SendError(command_id, Response::InvalidParams("${proto_param}"));
377 return true;
379 in_${param}.push_back(${item_pass});
381 """)
383 tmpl_prep_opt = string.Template("""\
384 ${raw_type} in_${param}${init};
385 bool ${param}_found = params && params->Get${Type}(
386 "${proto_param}",
387 &in_${param});
388 """)
390 tmpl_prep_output = string.Template("""\
391 ${param_type} out_${param}${init};
392 """)
394 tmpl_arg_name = string.Template("in_${param}")
396 tmpl_arg_req = string.Template("${param_pass}")
398 tmpl_arg_opt = string.Template(
399 "${param}_found ? ${param_pass} : nullptr")
401 tmpl_object_pass = string.Template(
402 "make_scoped_ptr<base::DictionaryValue>(${name}->DeepCopy())")
404 tmpl_client_impl = string.Template("""\
405 namespace ${domain} {
407 Client::Client(const RawMessageCallback& raw_message_callback)
408 : DevToolsProtocolClient(raw_message_callback) {
411 Client::~Client() {
414 ${methods}\
416 } // namespace ${domain}
417 """)
419 tmpl_event_impl = string.Template("""\
420 void Client::${Command}(
421 scoped_refptr<${Command}Params> params) {
422 SendNotification("${Domain}.${command}",
423 params->ToValue().Pass());
425 """)
427 tmpl_response_impl = string.Template("""\
428 void Client::Send${Command}Response(
429 DevToolsCommandId command_id,
430 scoped_refptr<${Command}Response> params) {
431 SendSuccess(command_id, params->ToValue().Pass());
433 """)
435 tmpl_typename = string.Template("devtools::${domain}::${declared_name}")
437 def Capitalize(s):
438 return s[:1].upper() + s[1:]
440 def Uncamelcase(s):
441 result = ""
442 for i, c in enumerate(s):
443 if c.isupper():
444 if (i > 0) and ((i < len(s)-1) and s[i+1].islower() or s[i-1].islower()):
445 result += "_"
446 result += c.lower()
447 else:
448 result += c
449 return result
451 types = {}
452 blink_protocol = json.loads(open(blink_protocol_path, "r").read())
453 browser_protocol = json.loads(open(browser_protocol_path, "r").read())
454 type_decls = []
455 type_impls = []
456 handler_methods = []
457 handler_method_impls = []
458 domain_maps = []
459 redirects = {}
461 all_domains = blink_protocol["domains"] + browser_protocol["domains"]
463 for json_domain in all_domains:
464 if "types" in json_domain:
465 for json_type in json_domain["types"]:
466 types["%s.%s" % (json_domain["domain"], json_type["id"])] = json_type
468 def DeclareStruct(json_properties, mapping):
469 methods = []
470 fields_enum = []
471 enum_items = []
472 req_fields_num = 0
473 for json_prop in json_properties:
474 prop_map = mapping.copy()
475 prop_map["proto_param"] = json_prop["name"]
476 prop_map["param"] = Uncamelcase(json_prop["name"])
477 prop_map["Param"] = Capitalize(json_prop["name"])
478 prop_map["subdomain"] = Uncamelcase(prop_map["declared_name"])
479 del prop_map["declared_name"]
480 ResolveType(json_prop, prop_map)
481 prop_map["declared_name"] = mapping["declared_name"]
482 if json_prop.get("optional"):
483 methods.append(tmpl_builder_setter_opt.substitute(prop_map))
484 else:
485 methods.append(tmpl_builder_setter_req.substitute(prop_map))
486 enum_items.append("k%s" % prop_map["Param"]);
487 fields_enum.append(tmpl_builder_enum.substitute(prop_map,
488 ordinal = req_fields_num))
489 req_fields_num += 1
491 all_fields = "kAllSet"
492 if len(enum_items) > 0:
493 all_fields = " | ".join(enum_items)
494 fields_enum.append(tmpl_builder_none_set.substitute(mapping,
495 all_fields = all_fields))
496 type_decls.append(tmpl_struct.substitute(mapping,
497 methods = "\n".join(methods),
498 fields_enum = "".join(fields_enum)))
500 def DeclareEnum(json, mapping):
501 values = []
502 value_defs = []
503 tmpl_enum = tmpl_inline_enum
504 if "declared_name" in mapping:
505 mapping["Enum"] = mapping["declared_name"]
506 tmpl_enum = tmpl_named_enum
507 else:
508 mapping["Enum"] = Capitalize(mapping["proto_param"])
510 for enum_value in json["enum"]:
511 values.append(tmpl_enum_value.substitute(mapping,
512 Value = Capitalize(enum_value)))
513 value_defs.append(tmpl_enum_value_def.substitute(mapping,
514 value = enum_value,
515 Value = Capitalize(enum_value)))
516 type_decls.append(tmpl_enum.substitute(mapping,
517 values = "".join(values)))
518 type_impls.append(tmpl_enum.substitute(mapping,
519 values = "".join(value_defs)))
521 def ResolveRef(json, mapping):
522 dot_pos = json["$ref"].find(".")
523 if dot_pos == -1:
524 domain_name = mapping["Domain"]
525 type_name = json["$ref"]
526 else:
527 domain_name = json["$ref"][:dot_pos]
528 type_name = json["$ref"][dot_pos + 1:]
529 json_type = types["%s.%s" % (domain_name, type_name)]
530 mapping["declared_name"] = Capitalize(type_name)
531 mapping["Domain"] = domain_name
532 mapping["domain"] = Uncamelcase(domain_name)
533 mapping["param_type"] = tmpl_typename.substitute(mapping)
534 ResolveType(json_type, mapping)
535 if not "___type_declared" in json_type:
536 json_type["___type_declared"] = True;
537 if (json_type.get("type") == "object") and ("properties" in json_type):
538 DeclareStruct(json_type["properties"], mapping)
539 else:
540 if ("enum" in json_type):
541 DeclareEnum(json_type, mapping)
542 type_decls.append(tmpl_typedef.substitute(mapping))
544 def ResolveArray(json, mapping):
545 items_map = mapping.copy()
546 ResolveType(json["items"], items_map)
547 if items_map["Type"] == "List":
548 # TODO(dgozman) Implement this.
549 raise Exception("Nested arrays are not implemented")
550 mapping["param_type"] = "std::vector<%s>" % items_map["param_type"]
551 mapping["Type"] = "List"
552 mapping["pass_type"] = "const %s&" % mapping["param_type"]
553 mapping["storage_type"] = "std::vector<%s>" % items_map["storage_type"]
554 mapping["raw_type"] = mapping["storage_type"]
555 mapping["prep_req"] = tmpl_prep_req_list.substitute(mapping,
556 item_type = items_map["storage_type"],
557 item_init = items_map["init"],
558 item_raw_type = items_map["raw_type"],
559 item_pass = items_map["pass_template"].substitute(name="item", opt=""),
560 ItemType = items_map["Type"])
561 mapping["arg_out"] = "&out_%s" % mapping["param"]
563 def ResolveObject(json, mapping):
564 mapping["Type"] = "Dictionary"
565 mapping["storage_type"] = "scoped_ptr<base::DictionaryValue>"
566 mapping["raw_type"] = "base::DictionaryValue*"
567 mapping["pass_template"] = tmpl_object_pass
568 if "properties" in json:
569 if not "declared_name" in mapping:
570 mapping["declared_name"] = ("%s%s" %
571 (mapping["Command"], Capitalize(mapping["proto_param"])))
572 mapping["param_type"] = ("scoped_refptr<%s>" %
573 tmpl_typename.substitute(mapping))
574 DeclareStruct(json["properties"], mapping)
575 else:
576 mapping["param_type"] = ("scoped_refptr<%s>" %
577 tmpl_typename.substitute(mapping))
578 mapping["pass_type"] = mapping["param_type"]
579 mapping["arg_out"] = "&out_%s" % mapping["param"]
580 else:
581 mapping["param_type"] = "base::DictionaryValue"
582 mapping["pass_type"] = "scoped_ptr<base::DictionaryValue>"
583 mapping["arg_out"] = "out_%s.get()" % mapping["param"]
584 mapping["prep_req"] = tmpl_prep_req.substitute(mapping)
586 def ResolvePrimitive(json, mapping):
587 jsonrpc_type = json["type"]
588 if jsonrpc_type == "boolean":
589 mapping["param_type"] = "bool"
590 mapping["Type"] = "Boolean"
591 mapping["init"] = " = false"
592 elif jsonrpc_type == "integer":
593 mapping["param_type"] = "int"
594 mapping["Type"] = "Integer"
595 mapping["init"] = " = 0"
596 elif jsonrpc_type == "number":
597 mapping["param_type"] = "double"
598 mapping["Type"] = "Double"
599 mapping["init"] = " = 0.0"
600 elif jsonrpc_type == "string":
601 mapping["param_type"] = "std::string"
602 mapping["pass_type"] = "const std::string&"
603 mapping["Type"] = "String"
604 if "enum" in json and not "declared_name" in mapping:
605 if not "subdomain" in mapping:
606 mapping["subdomain"] = Uncamelcase(mapping["command"])
607 DeclareEnum(json, mapping)
608 else:
609 raise Exception("Unknown type: %s" % json_type)
610 mapping["storage_type"] = mapping["param_type"]
611 mapping["raw_type"] = mapping["param_type"]
612 mapping["prep_req"] = tmpl_prep_req.substitute(mapping)
613 if jsonrpc_type != "string":
614 mapping["pass_type"] = mapping["param_type"]
615 mapping["arg_out"] = "&out_%s" % mapping["param"]
617 def ResolveType(json, mapping):
618 mapping["init"] = ""
619 mapping["pass_template"] = string.Template("${opt}${name}")
620 if "$ref" in json:
621 ResolveRef(json, mapping)
622 elif "type" in json:
623 jsonrpc_type = json["type"]
624 if jsonrpc_type == "array":
625 ResolveArray(json, mapping)
626 elif jsonrpc_type == "object":
627 ResolveObject(json, mapping)
628 else:
629 ResolvePrimitive(json, mapping)
630 else:
631 raise Exception("Unknown type at %s.%s %s" %
632 (mapping["Domain"], mapping["command"], mapping["proto_param"]))
634 setters = []
635 fields = []
637 includes = []
638 fields_init = []
640 for json_domain in all_domains:
641 domain_map = {}
642 domain_map["Domain"] = json_domain["domain"]
643 domain_map["domain"] = Uncamelcase(json_domain["domain"])
645 initializations = []
646 client_methods = []
647 client_method_impls = []
648 domain_empty = True
649 domain_needs_client = False
651 if "commands" in json_domain:
652 for json_command in json_domain["commands"]:
653 if (not ("handlers" in json_command) or
654 not ("browser" in json_command["handlers"])):
655 continue
656 domain_empty = False
658 command_map = domain_map.copy()
659 command_map["command"] = json_command["name"]
660 command_map["Command"] = Capitalize(json_command["name"])
662 if "redirect" in json_command:
663 redirect_domain = json_command["redirect"]
664 if not (redirect_domain in redirects):
665 redirects[redirect_domain] = []
666 command_map["TargetDomain"] = redirect_domain
667 redirects[redirect_domain].append(tmpl_register.substitute(command_map))
668 continue
670 command_map["TargetDomain"] = command_map["Domain"]
671 prep = []
672 args = []
674 if "parameters" in json_command:
675 for json_param in json_command["parameters"]:
676 param_map = command_map.copy()
677 param_map["proto_param"] = json_param["name"]
678 param_map["param"] = Uncamelcase(json_param["name"])
679 ResolveType(json_param, param_map)
680 if json_param.get("optional"):
681 if param_map["Type"] in ["List"]:
682 # TODO(vkuzkokov) Implement transformation of base::ListValue
683 # to std::vector and base::DictonaryValue to struct.
684 raise Exception(
685 "Optional array parameters are not implemented")
686 prep.append(tmpl_prep_opt.substitute(param_map))
687 param_pass = param_map["pass_template"].substitute(
688 name=tmpl_arg_name.substitute(param_map),
689 opt="&")
690 args.append(
691 tmpl_arg_opt.substitute(param_map, param_pass=param_pass))
692 else:
693 prep.append(param_map["prep_req"])
694 param_pass = param_map["pass_template"].substitute(
695 name=tmpl_arg_name.substitute(param_map),
696 opt="")
697 args.append(
698 tmpl_arg_req.substitute(param_map, param_pass=param_pass))
700 if json_command.get("async"):
701 domain_needs_client = True
702 json_returns = []
703 if "returns" in json_command:
704 json_returns = json_command["returns"]
705 command_map["declared_name"] = "%sResponse" % command_map["Command"]
706 DeclareStruct(json_returns, command_map)
707 # TODO(vkuzkokov) Pass async callback instance similar to how
708 # InspectorBackendDispatcher does it. This, however, can work
709 # only if Blink and Chrome are in the same repo.
710 args.insert(0, "command_id")
711 handler_method_impls.append(
712 tmpl_callback_async_impl.substitute(command_map,
713 prep = "".join(prep),
714 args = "\n " + ",\n ".join(args)))
715 client_methods.append(tmpl_response.substitute(command_map))
716 client_method_impls.append(tmpl_response_impl.substitute(command_map))
717 else:
718 wrap = []
719 if "returns" in json_command:
720 for json_param in json_command["returns"]:
721 param_map = command_map.copy()
722 param_map["proto_param"] = json_param["name"]
723 param_map["param"] = Uncamelcase(json_param["name"])
724 if json_param.get("optional"):
725 # TODO(vkuzkokov) Implement Optional<T> for value types.
726 raise Exception("Optional return values are not implemented")
727 ResolveType(json_param, param_map)
728 prep.append(tmpl_prep_output.substitute(param_map))
729 args.append(param_map["arg_out"])
730 wrap.append(tmpl_wrap.substitute(param_map))
731 args_str = ""
732 if len(args) > 0:
733 args_str = "\n " + ",\n ".join(args)
734 handler_method_impls.append(tmpl_callback_impl.substitute(command_map,
735 prep = "".join(prep),
736 args = args_str,
737 wrap = "".join(wrap)))
739 initializations.append(tmpl_register.substitute(command_map))
740 handler_methods.append(tmpl_callback.substitute(command_map))
742 if "events" in json_domain:
743 for json_event in json_domain["events"]:
744 if (not ("handlers" in json_event) or
745 not ("browser" in json_event["handlers"])):
746 continue
747 domain_empty = False
748 domain_needs_client = True
750 event_map = domain_map.copy()
751 event_map["command"] = json_event["name"]
752 event_map["Command"] = Capitalize(json_event["name"])
754 json_parameters = []
755 if "parameters" in json_event:
756 json_parameters = json_event["parameters"]
757 event_map["declared_name"] = "%sParams" % event_map["Command"]
758 DeclareStruct(json_parameters, event_map);
760 client_methods.append(tmpl_event.substitute(event_map))
761 client_method_impls.append(tmpl_event_impl.substitute(event_map))
763 if domain_empty:
764 continue
765 type_decls.append(tmpl_handler.substitute(domain_map))
766 setters.append(tmpl_setter.substitute(domain_map))
767 fields.append(tmpl_field.substitute(domain_map))
768 includes.append(tmpl_include.substitute(domain_map))
769 fields_init.append(tmpl_field_init.substitute(domain_map))
770 if domain_needs_client:
771 type_decls.append(tmpl_client.substitute(domain_map,
772 methods = "".join(client_methods)))
773 initializations.append(tmpl_init_client.substitute(domain_map))
774 type_impls.append(tmpl_client_impl.substitute(domain_map,
775 methods = "\n".join(client_method_impls)))
776 domain_map["initializations"] = "".join(initializations)
777 domain_maps.append(domain_map)
779 for domain_map in domain_maps:
780 domain = domain_map["Domain"]
781 if domain in redirects:
782 domain_map["initializations"] += "".join(redirects[domain])
783 handler_method_impls.append(tmpl_setter_impl.substitute(domain_map))
785 output_h_file = open(output_h_path, "w")
786 output_cc_file = open(output_cc_path, "w")
788 output_h_file.write(template_h.substitute({},
789 types = "\n".join(type_decls),
790 setters = "".join(setters),
791 methods = "".join(handler_methods),
792 fields = "".join(fields)))
793 output_h_file.close()
795 output_cc_file.write(template_cc.substitute({},
796 major = blink_protocol["version"]["major"],
797 minor = blink_protocol["version"]["minor"],
798 includes = "".join(sorted(includes)),
799 fields_init = ",\n ".join(fields_init),
800 methods = "\n".join(handler_method_impls),
801 types = "\n".join(type_impls)))
802 output_cc_file.close()