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

Side by Side Diff: pkg/polymer/lib/src/mirror_loader.dart

Issue 293023008: Bring back initPolymer, allow boot.js only if using "polymer_experimental.html". (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Created 6 years, 7 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 | Annotate | Revision Log
« no previous file with comments | « pkg/polymer/lib/src/loader.dart ('k') | pkg/polymer/lib/src/static_loader.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a 2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 /// Contains logic to initialize polymer apps during development. This 5 /// Contains logic to initialize polymer apps during development. This
6 /// implementation uses dart:mirrors to load each library as they are discovered 6 /// implementation uses dart:mirrors to load each library as they are discovered
7 /// through HTML imports. This is only meant to be during development in 7 /// through HTML imports. This is only meant to be during development in
8 /// dartium, and the polymer transformers replace this implementation with 8 /// dartium, and the polymer transformers replace this implementation with
9 /// codege generation in the polymer-build steps. 9 /// codege generation in the polymer-build steps.
10 library polymer.src.mirror_loader; 10 library polymer.src.mirror_loader;
11 11
12 import 'dart:async'; 12 import 'dart:async';
13 import 'dart:html'; 13 import 'dart:html';
14 import 'dart:collection' show LinkedHashMap; 14 import 'dart:collection' show LinkedHashMap;
15 15
16 // Technically, we shouldn't need any @MirrorsUsed, since this is for 16 // Technically, we shouldn't need any @MirrorsUsed, since this is for
17 // development only, but our test bots don't yet run pub-build. See more details 17 // development only, but our test bots don't yet run pub-build. See more details
18 // on the comments of the mirrors import in `lib/polymer.dart`. 18 // on the comments of the mirrors import in `lib/polymer.dart`.
19 @MirrorsUsed(metaTargets: 19 @MirrorsUsed(metaTargets:
20 const [CustomTag, InitMethodAnnotation], 20 const [CustomTag, InitMethodAnnotation],
21 override: const ['smoke.mirrors', 'polymer.src.mirror_loader']) 21 override: const ['smoke.mirrors', 'polymer.src.mirror_loader'])
22 import 'dart:mirrors'; 22 import 'dart:mirrors';
23 23
24 import 'package:logging/logging.dart' show Logger; 24 import 'package:logging/logging.dart' show Logger;
25 import 'package:observe/src/dirty_check.dart';
25 import 'package:polymer/polymer.dart'; 26 import 'package:polymer/polymer.dart';
26 import 'package:observe/src/dirty_check.dart';
27 27
28 28
29 /// Used by code generated from the experimental polymer bootstrap in boot.js.
29 void startPolymerInDevelopment(List<String> librariesToLoad) { 30 void startPolymerInDevelopment(List<String> librariesToLoad) {
30 dirtyCheckZone()..run(() { 31 dirtyCheckZone()..run(() {
31 startPolymer(discoverInitializers(librariesToLoad), false); 32 startPolymer(discoverInitializers(librariesToLoad), false);
32 }); 33 });
33 } 34 }
34 35
35 /// Set of initializers that are invoked by `initPolymer`. This is computed the 36 /// Set of initializers that are invoked by `initPolymer`. This is computed the
36 /// list by crawling HTML imports, searching for script tags, and including an 37 /// list by crawling HTML imports, searching for script tags, and including an
37 /// initializer for each type tagged with a [CustomTag] annotation and for each 38 /// initializer for each type tagged with a [CustomTag] annotation and for each
38 /// top-level method annotated with [initMethod]. 39 /// top-level method annotated with [initMethod].
40 List<Function> initializers = discoverInitializers(
41 discoverLibrariesToLoad(document, window.location.href));
42
43 /// True if we're in deployment mode.
44 bool deployMode = false;
39 45
40 /// Discovers what script tags are loaded from HTML pages and collects the 46 /// Discovers what script tags are loaded from HTML pages and collects the
41 /// initializers of their corresponding libraries. 47 /// initializers of their corresponding libraries.
42 // Visible for testing only. 48 // Visible for testing only.
43 List<Function> discoverInitializers(List<String> librariesToLoad) { 49 List<Function> discoverInitializers(Iterable<String> librariesToLoad) {
44 var initializers = []; 50 var initializers = [];
45 for (var lib in librariesToLoad) { 51 for (var lib in librariesToLoad) {
46 try { 52 try {
47 _loadLibrary(lib, initializers); 53 _loadLibrary(lib, initializers);
48 } catch (e, s) { 54 } catch (e, s) {
49 // Deliver errors async, so if a single library fails it doesn't prevent 55 // Deliver errors async, so if a single library fails it doesn't prevent
50 // other things from loading. 56 // other things from loading.
51 new Completer().completeError(e, s); 57 new Completer().completeError(e, s);
52 } 58 }
53 } 59 }
54 return initializers; 60 return initializers;
55 } 61 }
56 62
63 /// Walks the HTML import structure to discover all script tags that are
64 /// implicitly loaded. This code is only used in Dartium and should only be
65 /// called after all HTML imports are resolved. Polymer ensures this by asking
66 /// users to put their Dart script tags after all HTML imports (this is checked
67 /// by the linter, and Dartium will otherwise show an error message).
68 List<_ScriptInfo> _discoverScripts(Document doc, String baseUri, [_State state]) {
69 if (state == null) state = new _State();
70 if (doc == null) {
71 print('warning: $baseUri not found.');
72 return state.scripts;
73 }
74 if (!state.seen.add(doc)) return state.scripts;
75
76 for (var node in doc.querySelectorAll('script,link[rel="import"]')) {
77 if (node is LinkElement) {
78 _discoverScripts(node.import, node.href, state);
79 } else if (node is ScriptElement && node.type == 'application/dart') {
80 state.scripts.add(_scriptInfoFor(node, baseUri));
81 }
82 }
83 return state.scripts;
84 }
85
86 /// Internal state used in [_discoverScripts].
87 class _State {
88 /// Documents that we have visited thus far.
89 final Set<Document> seen = new Set();
90
91 /// Scripts that have been discovered, in tree order.
92 final List<_ScriptInfo> scripts = [];
93 }
94
95 /// Holds information about a Dart script tag.
96 class _ScriptInfo {
97 /// The original URL seen in the tag fully resolved.
98 final String resolvedUrl;
99
100 /// Whether there was no URL, but code inlined instead.
101 bool get isInline => text != null;
102
103 /// Whether it seems to be a 'package:' URL (starts with the package-root).
104 bool get isPackage => packageUrl != null;
105
106 /// The equivalent 'package:' URL, if any.
107 final String packageUrl;
108
109 /// The inlined text, if any.
110 final String text;
111
112 /// Returns a base64 `data:` uri with the contents of [text].
113 // TODO(sigmund): change back to application/dart: using text/javascript seems
114 // wrong but it hides a warning in Dartium (dartbug.com/18000).
115 String get dataUrl => 'data:text/javascript;base64,${window.btoa(text)}';
116
117 /// URL to import the contents of the original script from Dart. This is
118 /// either the source URL if the script tag had a `src` attribute, or a base64
119 /// encoded `data:` URL if the script contents are inlined, or a `package:`
120 /// URL if the script can be resolved via a package URL.
121 String get importUrl =>
122 isInline ? dataUrl : (isPackage ? packageUrl : resolvedUrl);
123
124 _ScriptInfo(this.resolvedUrl, {this.packageUrl, this.text});
125 }
126
127
128 // TODO(sigmund): explore other (cheaper) ways to resolve URIs relative to the
129 // root library (see dartbug.com/12612)
130 final _rootUri = currentMirrorSystem().isolate.rootLibrary.uri;
131
132 /// Returns [_ScriptInfo] for [script] which was seen in [baseUri].
133 _ScriptInfo _scriptInfoFor(script, baseUri) {
134 var uriString = script.src;
135 if (uriString != '') {
136 var uri = _rootUri.resolve(uriString);
137 if (!_isHttpStylePackageUrl(uri)) return new _ScriptInfo('$uri');
138 // Use package: urls if available. This rule here is more permissive than
139 // how we translate urls in polymer-build, but we expect Dartium to limit
140 // the cases where there are differences. The polymer-build issues an error
141 // when using packages/ inside lib without properly stepping out all the way
142 // to the packages folder. If users don't create symlinks in the source
143 // tree, then Dartium will also complain because it won't find the file seen
144 // in an HTML import.
145 var packagePath = uri.path.substring(
146 uri.path.lastIndexOf('packages/') + 'packages/'.length);
147 return new _ScriptInfo('$uri', packageUrl: 'package:$packagePath');
148 }
149
150 return new _ScriptInfo(baseUri, text: script.text);
151 }
152
153 /// Whether [uri] is an http URI that contains a 'packages' segment, and
154 /// therefore could be converted into a 'package:' URI.
155 bool _isHttpStylePackageUrl(Uri uri) {
156 var uriPath = uri.path;
157 return uri.scheme == _rootUri.scheme &&
158 // Don't process cross-domain uris.
159 uri.authority == _rootUri.authority &&
160 uriPath.endsWith('.dart') &&
161 (uriPath.contains('/packages/') || uriPath.startsWith('packages/'));
162 }
163
164 Iterable<String> discoverLibrariesToLoad(Document doc, String baseUri) =>
165 _discoverScripts(doc, baseUri).map(
166 (info) => _packageUrlExists(info) ? info.packageUrl : info.resolvedUrl);
167
168 bool _packageUrlExists(_ScriptInfo info) =>
169 info.isPackage && _libs[Uri.parse(info.packageUrl)] != null;
170
57 /// All libraries in the current isolate. 171 /// All libraries in the current isolate.
58 final _libs = currentMirrorSystem().libraries; 172 final _libs = currentMirrorSystem().libraries;
59 173
60 final Logger _loaderLog = new Logger('polymer.src.mirror_loader'); 174 final Logger _loaderLog = new Logger('polymer.src.mirror_loader');
61 175
62 /// Reads the library at [uriString] (which can be an absolute URI or a relative 176 /// Reads the library at [uriString] (which can be an absolute URI or a relative
63 /// URI from the root library), and: 177 /// URI from the root library), and:
64 /// 178 ///
65 /// * If present, invokes any top-level and static functions marked 179 /// * If present, invokes any top-level and static functions marked
66 /// with the [initMethod] annotation (in the order they appear). 180 /// with the [initMethod] annotation (in the order they appear).
(...skipping 86 matching lines...) Expand 10 before | Expand all | Expand 10 after
153 " ${method.simpleName} is not."); 267 " ${method.simpleName} is not.");
154 return; 268 return;
155 } 269 }
156 if (!method.parameters.where((p) => !p.isOptional).isEmpty) { 270 if (!method.parameters.where((p) => !p.isOptional).isEmpty) {
157 print("warning: methods marked with @initMethod should take no " 271 print("warning: methods marked with @initMethod should take no "
158 "arguments, ${method.simpleName} expects some."); 272 "arguments, ${method.simpleName} expects some.");
159 return; 273 return;
160 } 274 }
161 initializers.add(() => obj.invoke(method.simpleName, const [])); 275 initializers.add(() => obj.invoke(method.simpleName, const []));
162 } 276 }
OLDNEW
« no previous file with comments | « pkg/polymer/lib/src/loader.dart ('k') | pkg/polymer/lib/src/static_loader.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698