Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(375)

Side by Side Diff: components/wug/generator/view_model.py

Issue 928163002: Initial implementation of WebUI generator (WUG) toolkit. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Owners updated. Created 5 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright 2015 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.
4
5 import os
6 import datetime
7 import util
8
9 H_FILE_TEMPLATE = \
10 """// Copyright %(year)d The Chromium Authors. All rights reserved.
11 // Use of this source code is governed by a BSD-style license that can be
12 // found in the LICENSE file.
13
14 // NOTE: this file is generated from "%(source)s". Do not modify directly.
15
16 #ifndef %(include_guard)s
17 #define %(include_guard)s
18
19 #include "base/macros.h"
20 #include "components/wug/view_model.h"
21
22 namespace content {
23 class BrowserContext;
24 }
25
26 %(children_forward_declarations)s
27
28 namespace %(namespace)s {
29
30 class %(class_name)s : public ::wug::ViewModel {
31 public:
32 using FactoryFunction = %(class_name)s* (*)(content::BrowserContext*);
33
34 %(context_keys)s
35
36 static %(class_name)s* Create(content::BrowserContext* context);
37 static void SetFactory(FactoryFunction factory);
38
39 %(class_name)s();
40
41 %(children_getters)s
42
43 %(context_getters)s
44
45 %(event_handlers)s
46
47 void Initialize() override {}
48 void OnAfterChildrenReady() override {}
49 void OnViewBound() override {}
50
51 private:
52 void OnEvent(const std::string& event) final;
53
54 static FactoryFunction factory_function_;
55 };
56
57 } // namespace %(namespace)s
58
59 #endif // %(include_guard)s
60 """
61
62 CHILD_FORWARD_DECLARATION_TEMPLATE = \
63 """namespace %(ns)s {
64 class %(child_type)s;
65 }
66 """
67 CONTEXT_KEY_DECLARATION_TEMPLATE = \
68 """ static const char %s[];"""
69
70 CHILD_GETTER_DECLARATION_TEMPLATE = \
71 """ virtual %(ns)s::%(child_type)s* %(method_name)s() const;""";
72
73 CONTEXT_VALUE_GETTER_DECLARATION_TEMPLATE = \
74 """ %(type)s %(method_name)s() const;"""
75
76 EVENT_HANDLER_DECLARATION_TEMPLATE = \
77 """ virtual void %s() = 0;"""
78
79 CC_FILE_TEMPLATE = \
80 """// Copyright %(year)d The Chromium Authors. All rights reserved.
81 // Use of this source code is governed by a BSD-style license that can be
82 // found in the LICENSE file.
83
84 // NOTE: this file is generated from "%(source)s". Do not modify directly.
85
86 #include "%(header_path)s"
87
88 #include "base/logging.h"
89 #include "components/wug/view.h"
90 %(children_includes)s
91
92 namespace %(namespace)s {
93
94 %(context_keys)s
95
96 %(class_name)s::FactoryFunction %(class_name)s::factory_function_;
97
98 %(class_name)s* %(class_name)s::Create(content::BrowserContext* context) {
99 CHECK(factory_function_) << "Factory function for %(class_name)s was not "
100 "set.";
101 return factory_function_(context);
102 }
103
104 void %(class_name)s::SetFactory(FactoryFunction factory) {
105 factory_function_ = factory;
106 }
107
108 %(class_name)s::%(class_name)s() {
109 %(constructor_body)s
110 }
111
112 %(children_getters)s
113
114 %(context_getters)s
115
116 void %(class_name)s::OnEvent(const std::string& event) {
117 %(event_dispatcher_body)s
118 LOG(ERROR) << "Unknown event '" << event << "'";
119 }
120
121 } // namespace %(namespace)s
122 """
123
124 CONTEXT_KEY_DEFINITION_TEMPLATE = \
125 """const char %(class_name)s::%(name)s[] = "%(value)s";"""
126
127 CHILD_GETTER_DEFINITION_TEMPLATE = \
128 """%(ns)s::%(child_type)s* %(class_name)s::%(method_name)s() const {
129 return static_cast<%(ns)s::%(child_type)s*>(
130 view()->GetChild("%(child_id)s")->GetViewModel());
131 }
132 """
133
134 CONTEXT_VALUE_GETTER_DEFINITION_TEMPLATE = \
135 """%(type)s %(class_name)s::%(method_name)s() const {
136 return context().%(context_getter)s(%(key_constant)s);
137 }
138 """
139
140 FIELD_TYPE_TO_GETTER_TYPE = {
141 'boolean': 'bool',
142 'integer': 'int',
143 'double': 'double',
144 'string': 'std::string',
145 'string_list': 'login::StringList'
146 }
147
148 DISPATCH_EVENT_TEMPLATE = \
149 """ if (event == "%(event_id)s") {
150 %(method_name)s();
151 return;
152 }"""
153
154 def GetCommonSubistitutions(declaration):
155 subs = {}
156 subs['year'] = datetime.date.today().year
157 subs['namespace'] = declaration.namespace
158 subs['class_name'] = declaration.view_model_class
159 subs['source'] = declaration.path
160 return subs
161
162 def FieldNameToConstantName(field_name):
163 return 'kContextKey' + util.ToUpperCamelCase(field_name)
164
165 def GenContextKeysDeclarations(fields):
166 return '\n'.join(
167 (CONTEXT_KEY_DECLARATION_TEMPLATE % \
168 FieldNameToConstantName(f.name) for f in fields))
169
170 def GenChildrenForwardDeclarations(children):
171 lines = []
172 for declaration in set(children.itervalues()):
173 lines.append(CHILD_FORWARD_DECLARATION_TEMPLATE % {
174 'ns': declaration.namespace,
175 'child_type': declaration.view_model_class
176 })
177 return '\n'.join(lines)
178
179 def ChildIdToChildGetterName(id):
180 return 'Get%s' % util.ToUpperCamelCase(id)
181
182 def GenChildrenGettersDeclarations(children):
183 lines = []
184 for id, declaration in children.iteritems():
185 lines.append(CHILD_GETTER_DECLARATION_TEMPLATE % {
186 'ns': declaration.namespace,
187 'child_type': declaration.view_model_class,
188 'method_name': ChildIdToChildGetterName(id)
189 })
190 return '\n'.join(lines)
191
192 def FieldNameToGetterName(field_name):
193 return 'Get%s' % util.ToUpperCamelCase(field_name)
194
195 def GenContextGettersDeclarations(context_fields):
196 lines = []
197 for field in context_fields:
198 lines.append(CONTEXT_VALUE_GETTER_DECLARATION_TEMPLATE % {
199 'type': FIELD_TYPE_TO_GETTER_TYPE[field.type],
200 'method_name': FieldNameToGetterName(field.name)
201 })
202 return '\n'.join(lines)
203
204 def EventIdToMethodName(event):
205 return 'On' + util.ToUpperCamelCase(event)
206
207 def GenEventHandlersDeclarations(events):
208 lines = []
209 for event in events:
210 lines.append(EVENT_HANDLER_DECLARATION_TEMPLATE %
211 EventIdToMethodName(event))
212 return '\n'.join(lines)
213
214 def GenHFile(declaration):
215 subs = GetCommonSubistitutions(declaration)
216 subs['include_guard'] = \
217 util.PathToIncludeGuard(declaration.view_model_include_path)
218 subs['context_keys'] = GenContextKeysDeclarations(declaration.fields)
219 subs['children_forward_declarations'] = \
220 GenChildrenForwardDeclarations(declaration.children)
221 subs['children_getters'] = \
222 GenChildrenGettersDeclarations(declaration.children);
223 subs['context_getters'] = \
224 GenContextGettersDeclarations(declaration.fields);
225 subs['event_handlers'] = GenEventHandlersDeclarations(declaration.events)
226 return H_FILE_TEMPLATE % subs
227
228 def GenContextKeysDefinitions(declaration):
229 lines = []
230 for field in declaration.fields:
231 definition = CONTEXT_KEY_DEFINITION_TEMPLATE % {
232 'class_name': declaration.view_model_class,
233 'name': FieldNameToConstantName(field.name),
234 'value': field.id
235 }
236 lines.append(definition)
237 return '\n'.join(lines)
238
239 def GenChildrenIncludes(children):
240 lines = []
241 for declaration in set(children.itervalues()):
242 lines.append('#include "%s"' % declaration.view_model_include_path)
243 return '\n'.join(lines)
244
245 def GenContextFieldInitialization(field):
246 lines = []
247 key_constant = FieldNameToConstantName(field.name)
248 setter_method = 'Set' + util.ToUpperCamelCase(field.type)
249 if field.type == 'string_list':
250 lines.append(' {')
251 lines.append(' std::vector<std::string> defaults;')
252 for s in field.default_value:
253 lines.append(' defaults.push_back("%s");' % s)
254 lines.append(' context().%s(%s, defaults);' %
255 (setter_method, key_constant))
256 lines.append(' }')
257 else:
258 setter = ' context().%s(%s, ' % (setter_method, key_constant)
259 if field.type in ['integer', 'double']:
260 setter += str(field.default_value)
261 elif field.type == 'boolean':
262 setter += 'true' if field.default_value else 'false'
263 else:
264 assert field.type == 'string'
265 setter += '"%s"' % field.default_value
266 setter += ");"
267 lines.append(setter)
268 return '\n'.join(lines)
269
270 def GenChildrenGettersDefenitions(declaration):
271 lines = []
272 for id, child in declaration.children.iteritems():
273 lines.append(CHILD_GETTER_DEFINITION_TEMPLATE % {
274 'ns': child.namespace,
275 'child_type': child.view_model_class,
276 'class_name': declaration.view_model_class,
277 'method_name': ChildIdToChildGetterName(id),
278 'child_id': id
279 });
280 return '\n'.join(lines)
281
282 def GenContextGettersDefinitions(declaration):
283 lines = []
284 for field in declaration.fields:
285 lines.append(CONTEXT_VALUE_GETTER_DEFINITION_TEMPLATE % {
286 'type': FIELD_TYPE_TO_GETTER_TYPE[field.type],
287 'class_name': declaration.view_model_class,
288 'method_name': FieldNameToGetterName(field.name),
289 'context_getter': 'Get' + util.ToUpperCamelCase(
290 field.type),
291 'key_constant': FieldNameToConstantName(field.name)
292 });
293 return '\n'.join(lines)
294
295 def GenEventDispatcherBody(events):
296 lines = []
297 for event in events:
298 lines.append(DISPATCH_EVENT_TEMPLATE % {
299 'event_id': util.ToLowerCamelCase(event),
300 'method_name': EventIdToMethodName(event)
301 });
302 return '\n'.join(lines)
303
304 def GenCCFile(declaration):
305 subs = GetCommonSubistitutions(declaration)
306 subs['header_path'] = declaration.view_model_include_path
307 subs['context_keys'] = GenContextKeysDefinitions(declaration)
308 subs['children_includes'] = GenChildrenIncludes(declaration.children)
309 initializations = [GenContextFieldInitialization(field) \
310 for field in declaration.fields]
311 initializations.append(' base::DictionaryValue diff;');
312 initializations.append(' context().GetChangesAndReset(&diff);');
313 subs['constructor_body'] = '\n'.join(initializations)
314 subs['children_getters'] = GenChildrenGettersDefenitions(declaration)
315 subs['context_getters'] = GenContextGettersDefinitions(declaration)
316 subs['event_dispatcher_body'] = GenEventDispatcherBody(declaration.events)
317 return CC_FILE_TEMPLATE % subs
318
319 def ListOutputs(declaration, destination):
320 dirname = os.path.join(destination, os.path.dirname(declaration.path))
321 h_file_path = os.path.join(dirname, declaration.view_model_h_name)
322 cc_file_path = os.path.join(dirname, declaration.view_model_cc_name)
323 return [h_file_path, cc_file_path]
324
325 def Gen(declaration, destination):
326 h_file_path, cc_file_path = ListOutputs(declaration, destination)
327 util.CreateDirIfNotExists(os.path.dirname(h_file_path))
328 open(h_file_path, 'w').write(GenHFile(declaration))
329 open(cc_file_path, 'w').write(GenCCFile(declaration))
330
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698