public
Description: Dynamic languages in Silverlight
Homepage: http://sdlsdk.codeplex.com
Clone URL: git://github.com/jschementi/agdlr.git
agdlr / src / Microsoft.Scripting.Silverlight / DynamicApplication.cs
100644 365 lines (308 sloc) 13.818 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Microsoft Public License. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Microsoft Public License, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Microsoft Public License.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
 
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Resources;
using System.Xml;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using System.Net;
 
namespace Microsoft.Scripting.Silverlight {
 
    /// <summary>
    /// The entry point for dynamic language applications
    /// It is a static class that exists to bootstrap the DLR, and start running the application
    /// Also contains helper APIs. These can be accessed by using:
    ///
    /// System.Windows.Application.Current
    ///
    /// ... which returns the global instance of DynamicApplication
    /// </summary>
    public class DynamicApplication : Application {
 
        #region public properties
 
        /// <summary>
        /// Returns the entry point file
        /// </summary>
        public string EntryPoint {
            get { return _entryPoint; }
            set { _entryPoint = value; }
        }
 
        /// <summary>
        /// Determines if we emit optimized code, and whether turn on debugging features
        /// </summary>
        public bool Debug {
            get { return _debug; }
            set { _debug = value; }
        }
 
        /// <summary>
        /// Returns the "initParams" argument passed to the Silverlight control
        /// (otherwise would be inaccessible because the DLR host consumes them)
        /// </summary>
        public IDictionary<string, string> InitParams {
            get { return _initParams; }
        }
 
        /// <summary>
        /// Returns the instance of the DynamicApplication.
        /// Importantly, this method works if not on the UI thread, unlike
        /// Application.Current
        /// </summary>
        public static new DynamicApplication Current {
            get { return _Current; }
        }
        
        /// <summary>
        /// Indicates whether we report unhandled errors to the HTML page
        /// </summary>
        public bool ReportUnhandledErrors {
            get { return _reportErrors; }
            set {
                if (value != _reportErrors) {
                    _reportErrors = value;
                    if (_reportErrors) {
                        Application.Current.UnhandledException += OnUnhandledException;
                    } else {
                        Application.Current.UnhandledException -= OnUnhandledException;
                    }
                }
            }
        }
 
        /// <summary>
        /// Indicates what HTML element errors should be reported into.
        /// </summary>
        public string ErrorTargetID {
            get { return _errorTargetID; }
            set { _errorTargetID = value; }
        }
 
        /// <summary>
        /// Indicates whether or not CLR stack traces are shown in the error report
        /// </summary>
        public bool ExceptionDetail {
            get { return _exceptionDetail; }
        }
 
        /// <summary>
        /// The ScriptRuntime that application code runs in
        /// </summary>
        public ScriptRuntime Runtime {
            get { return _runtime; }
        }
 
        internal ScriptEngine Engine {
            get { return _engine; }
        }
 
        internal ScriptScope EntryPointScope {
            get { return _entryPointScope; }
        }
        #endregion
 
        #region instance variables
 
        private string _entryPoint;
        private bool _consoleEnabled;
        private bool _debug;
        private bool _exceptionDetail;
        private bool _reportErrors;
        private string _errorTargetID;
 
        private IDictionary<string, string> _initParams;
 
        private static int _UIThreadId;
 
        // we need to store this because we can't access Application.Current
        // if we're not on the UI thread
        private static volatile DynamicApplication _Current;
 
        private ScriptRuntime _runtime;
        private ScriptRuntimeSetup _runtimeSetup;
        private ScriptEngine _engine;
        private ScriptScope _entryPointScope;
 
        internal static bool InUIThread {
            get { return _UIThreadId == Thread.CurrentThread.ManagedThreadId; }
        }
        #endregion
 
        #region public API
 
        // these are instance methods so you can do Application.Current.TheMethod(...)
 
        /// <summary>
        /// Loads a XAML file, represented by a Uri, into a UIElement, and sets
        /// the UIElement as the RootVisual of the application.
        /// </summary>
        /// <param name="root">UIElement to load the XAML into</param>
        /// <param name="uri">Uri to a XAML file</param>
        /// <returns></returns>
        public DependencyObject LoadRootVisual(UIElement root, Uri uri) {
            Application.LoadComponent(root, uri);
            RootVisual = root;
            return root;
        }
 
        /// <summary>
        /// Loads a XAML file, represented by a string, into a UIElement, and sets
        /// the UIElement as the RootVisual of the application.
        /// </summary>
        /// <param name="root">UIElement to load the XAML into</param>
        /// <param name="uri">string representing the relative Uri of the XAML file</param>
        /// <returns></returns>
        public DependencyObject LoadRootVisual(UIElement root, string uri) {
            return LoadRootVisual(root, MakeUri(uri));
        }
 
        /// <summary>
        /// Loads a XAML file, represented by a string, into any object.
        /// </summary>
        /// <param name="component">The object to load the XAML into</param>
        /// <param name="uri">string representing the relative Uri of the XAML file</param>
        public void LoadComponent(object component, string uri) {
            LoadComponent(component, MakeUri(uri));
        }
 
        /// <summary>
        /// Makes a Uri object that is relative to the location of the "start" source file.
        /// </summary>
        /// <param name="relativeUri">Any Uri</param>
        /// <returns>A Uri relative to the "start" source file</returns>
        public Uri MakeUri(string relativeUri) {
            // Get the source file location so we can make the URI relative to the executing source file
            string baseUri = Path.GetDirectoryName(_entryPoint);
            if (baseUri != "") baseUri += "/";
            return new Uri(baseUri + relativeUri, UriKind.Relative);
        }
 
        public static ScriptRuntimeSetup CreateRuntimeSetup(IEnumerable<Assembly> assemblies) {
            ScriptRuntimeSetup setup = Configuration.TryParseFile();
            if (setup == null) {
                if (assemblies == null) {
                    if (!Package.ContainsDLRAssemblies(Deployment.Current.Parts)) {
                        assemblies = Package.GetExtensionAssemblies();
                    } else {
                        assemblies = Package.GetManifestAssemblies();
                    }
                }
                setup = Configuration.LoadFromAssemblies(assemblies);
            }
            setup.HostType = typeof(BrowserScriptHost);
            return setup;
        }
 
        public static ScriptRuntimeSetup CreateRuntimeSetup() {
            return CreateRuntimeSetup(null);
        }
 
        public static StreamResourceInfo XapFile {
            get {
                return BrowserPAL.PAL.XapFile;
            }
            set {
                BrowserPAL.PAL.XapFile = value;
            }
        }
        #endregion
 
        public static void LoadAssemblies(Action onComplete) {
            if (!Package.ContainsDLRAssemblies(Deployment.Current.Parts)) {
                // FIXME: for now, we manually redownload extensions.
                // A SL bug is stopping us from using Deployment.Current.ExternalParts
                // to figure out what extensions have been requested by the application.
                // FIXME: The extensions are downloaded one after the other ... should
                // be done in parallel.
                Extension.FetchDLR(delegate() {
                    onComplete.Invoke();
                });
            } else {
                onComplete.Invoke();
            }
        }
 
        #region implementation
 
        /// <summary>
        /// Called by Silverlight host when it instantiates our application
        /// </summary>
        public DynamicApplication() {
            if (_Current != null) {
                throw new Exception("Only one instance of DynamicApplication can be created");
            }
 
            _Current = this;
            _UIThreadId = Thread.CurrentThread.ManagedThreadId;
 
            Startup += new StartupEventHandler(DynamicApplication_Startup);
        }
 
        void DynamicApplication_Startup(object sender, StartupEventArgs e) {
            // Turn error reporting on while we parse initParams.
            // (Otherwise, we would silently fail if the initParams has an error)
            ReportUnhandledErrors = true;
 
            ParseArguments(e.InitParams);
 
            DynamicApplication.LoadAssemblies(delegate() {
                Start();
            });
        }
 
        void Start() {
            InitializeDLR();
            StartMainProgram();
        }
 
        private void InitializeDLR() {
            var setup = CreateRuntimeSetup();
            setup.DebugMode = _debug;
            setup.Options["SearchPaths"] = new string[] { String.Empty };
            
            _runtimeSetup = setup;
            _runtime = new ScriptRuntime(setup);
 
            _runtime.LoadAssembly(GetType().Assembly); // to expose our helper APIs
            LoadDefaultAssemblies(_runtime);
        }
 
        public static void LoadDefaultAssemblies(ScriptRuntime runtime) {
            // Add default references to Silverlight platform DLLs
            // (Currently we auto reference CoreCLR, UI controls, browser interop, and networking stack.)
            foreach (string name in new string[] { "mscorlib", "System", "System.Windows", "System.Windows.Browser", "System.Net" }) {
                runtime.LoadAssembly(GetAssemblyByName(name));
            }
        }
 
        public static Assembly GetAssemblyByName(string name) {
            return BrowserPAL.PAL.LoadAssembly(name);
        }
 
        private void StartMainProgram() {
            string code = Package.GetEntryPointContents();
            _engine = _runtime.GetEngineByFileExtension(Path.GetExtension(_entryPoint));
            _entryPointScope = _engine.CreateScope();
 
            if (_consoleEnabled)
                Repl.Show();
 
            ScriptSource sourceCode = _engine.CreateScriptSourceFromString(code, _entryPoint, SourceCodeKind.File);
            sourceCode.Compile(new ErrorFormatter.Sink()).Execute(_entryPointScope);
        }
 
 
        private void ParseArguments(IDictionary<string, string> args) {
            // save off the initParams (otherwise user code couldn't access it)
            // also, normalize initParams because otherwise it preserves whitespace, which is not very useful
            _initParams = new Dictionary<string, string>(args.Count);
            foreach (KeyValuePair<string, string> pair in args) {
                _initParams[pair.Key.Trim()] = pair.Value.Trim();
            }
 
            _initParams.TryGetValue("start", out _entryPoint);
 
            string consoleEnabled;
            if (_initParams.TryGetValue("console", out consoleEnabled)) {
                if (!bool.TryParse(consoleEnabled, out _consoleEnabled)) {
                    throw new ArgumentException("You must set 'console' to 'true' or 'false', for example: initParams: \"..., console=true\"");
                }
            }
            
            string debug;
            if (_initParams.TryGetValue("debug", out debug)) {
                if (!bool.TryParse(debug, out _debug)) {
                    throw new ArgumentException("You must set 'debug' to 'true' or 'false', for example: initParams: \"..., debug=true\"");
                }
            }
 
            string exceptionDetail;
            if (_initParams.TryGetValue("exceptionDetail", out exceptionDetail)) {
                if (!bool.TryParse(exceptionDetail, out _exceptionDetail)) {
                    throw new ArgumentException("You must set 'exceptionDetail' to 'true' or 'false', for example: initParams: \"..., exceptionDetail=true\"");
                }
            }
 
            string reportErrorsDiv;
            if (_initParams.TryGetValue("reportErrors", out reportErrorsDiv)) {
                _errorTargetID = reportErrorsDiv;
                ReportUnhandledErrors = true;
            } else {
                // if reportErrors is unspecified, set to false
                ReportUnhandledErrors = false;
            }
        }
 
        private void OnUnhandledException(object sender, ApplicationUnhandledExceptionEventArgs args) {
            args.Handled = true;
            ErrorFormatter.DisplayError(_errorTargetID, args.ExceptionObject);
        }
 
        #endregion
    }
}