Author: zoltan
Date: 2007-09-28 11:46:22 -0400 (Fri, 28 Sep 2007)
New Revision: 86583

Added:
   trunk/olive/class/agclr/Mono/DLRHost.cs
Modified:
   trunk/olive/class/agclr/Mono/ManagedXamlLoader.cs
Log:
2007-09-28  Zoltan Varga  <[EMAIL PROTECTED]>

        * DLRHost.cs: New class hosting the MS DLR inside Silverlight. Requires 
a 
        DLR which compiles cleanly under Silverlight, so it is not enabled yet.

        * ManagedXamlLoader: Add hooks for creating the DLR, loading script 
files,
        setting globals and hooking up events. Not enabled yet.


Added: trunk/olive/class/agclr/Mono/DLRHost.cs
===================================================================
--- trunk/olive/class/agclr/Mono/DLRHost.cs     2007-09-28 15:43:52 UTC (rev 
86582)
+++ trunk/olive/class/agclr/Mono/DLRHost.cs     2007-09-28 15:46:22 UTC (rev 
86583)
@@ -0,0 +1,279 @@
+//
+// DLRHost.cs
+//
+// Authors:
+//   Zoltan Varga ([EMAIL PROTECTED])
+//
+// Copyright 2007 Novell, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+// 
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+// 
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System;
+using System.IO;
+using System.Text;
+using System.Collections.Generic;
+using System.Reflection;
+
+using Microsoft.Scripting;
+using Microsoft.Scripting.Hosting;
+using IronPython.Hosting; 
+
+namespace Mono
+{
+       //
+       // This class hosts the MS Dynamic Language Runtime inside the 
Silverlight 
+       // environment
+       //
+       internal class DLRHost {
+
+               private SilverlightScriptHost host;
+               private PythonEngine engine;
+               private ScriptModule main_module;
+
+               public DLRHost () {
+                       // From a posting on the IronPython list
+                       ScriptEnvironmentSetup setup = new 
ScriptEnvironmentSetup(true);
+                       setup.PALType = typeof(SilverlightPAL);
+                       setup.HostType = typeof (SilverlightScriptHost);
+                       IScriptEnvironment environment = 
ScriptEnvironment.Create(setup); 
+                       host = (SilverlightScriptHost)environment.Host;
+
+                       engine = PythonEngine.CurrentEngine;
+            main_module = engine.CreateModule("__main__", 
ModuleOptions.PublishModule);
+
+                       string prefix = "";
+                       string executable = "";
+                       string version = engine.VersionString;
+
+            engine.InitializeModules(prefix, executable, version);
+
+                       // Add references to default assemblies
+                       ClrModule clr_module = ClrModule.GetInstance ();
+
+                       clr_module.AddReference (typeof (int).Assembly,    // 
mscorlib
+                                                                        typeof 
(DLRHost).Assembly, // agclr
+                                                                        typeof 
(Uri).Assembly // System
+                                                                        );
+                       // System.Silverlight
+            AssemblyName aname = new AssemblyName ();
+                       aname.Name = "System.SilverLight";
+                       clr_module.AddReference (Assembly.Load (aname));
+                       // System.Xml.Core
+                       aname.Name = "System.Xml.Core";
+                       clr_module.AddReference (Assembly.Load (aname));
+
+                       // The documentation doesn't say this, but 
Microsoft.Scripting is also loaded
+                       clr_module.AddReference (typeof 
(ScriptEnvironment).Assembly);
+               }                       
+
+               //
+               // Loads a source file from the given stream
+               // Throws MissingReferenceException if the file imports another 
file which is not
+               // yet loaded.
+               // fileMappings maps source file names to downloaded local file 
names
+               //
+               public void LoadSource (Stream stream, String type, 
Dictionary<string, string> fileMappings) {
+                       if (type != "text/python")
+                               throw new Exception ("Currently only mime type 
text/python is supported.");
+
+                       SourceUnit source_unit = SourceUnit.Create (engine, new 
ContentProvider (stream), "", SourceCodeKind.File);
+
+                       host.FileMappings = fileMappings;
+                       // FIXME: If the script references another file which 
needs to be downloaded
+                       // then part of the file is executed before a 
MissingReferenceException is 
+                       // thrown. When the missing file is downloaded, and we 
are called again, that
+                       // part is executed again.
+                       engine.ExecuteSourceUnit (source_unit, main_module);
+               }
+
+               //
+               // Set a global variable in the script environment
+               //
+               public void SetVariable (string name, object value) {
+                       main_module.SetVariable (name, value);
+               }
+
+               //
+               // Hook up the event EVENT_NAME on TARGET to the script 
function HANDLER_NAME
+               //
+               public void HookupEvent (object target, string event_name, 
string handler_name) {
+                       object o;
+                       main_module.TryLookupVariable (handler_name, out o);
+                       if (o == null)
+                               throw new Exception ("No function named '" + 
handler_name + "' was found.");
+                               
+                       // FIXME: Is there a way to do this from C# code ?
+                       try {
+                               main_module.SetVariable ("__HookupEvent", 
target);
+                               engine.Execute ("__HookupEvent." + event_name + 
" += " + handler_name, main_module);
+                       }
+                       finally {
+                               main_module.RemoveVariable ("__HookupEvent");
+                       }
+               }
+       }
+
+       class ContentProvider : SourceContentProvider {
+               TextReader reader;
+
+               public ContentProvider (Stream stream) {
+                       reader = new StreamReader (stream);
+               }
+
+               public ContentProvider (Stream stream, Encoding encoding) {
+                       reader = new StreamReader (stream, encoding, true);
+               }
+
+               public ContentProvider (TextReader reader) {
+                       this.reader = reader;
+               }
+
+               public override TextReader GetReader () {
+                       return reader;
+               }
+       }
+
+       class SilverlightScriptHost : ScriptHost
+       {
+               Dictionary<string, string> fileMappings;
+
+               public SilverlightScriptHost (ScriptEnvironment environment) : 
base (environment) {
+               }
+
+        public override SourceUnit TryGetSourceFileUnit(IScriptEngine engine, 
string path, Encoding encoding) {
+                       try {
+                               Stream s = Moonlight.LoadResource (path);
+                ContentProvider provider = new ContentProvider 
(LanguageContext.FromEngine (engine).GetSourceReader (s, encoding));
+                               return SourceUnit.Create (engine, provider, "", 
SourceCodeKind.File);
+                       }
+                       catch {
+                               return null;
+                       }
+               }
+
+        public override SourceUnit ResolveSourceFileUnit(string name) {
+                       // FIXME: Other languages ?
+                       string extension = ".py";
+                       name += extension;
+
+                       if (fileMappings.ContainsKey (name)) {
+                               string local = fileMappings [name];
+
+                               Stream s = new FileStream (local, 
FileMode.Open, FileAccess.Read);
+                               LanguageProvider lang_provider;
+                               
ScriptDomainManager.CurrentManager.TryGetLanguageProviderByFileExtension 
(extension, out lang_provider);
+                               return SourceUnit.Create 
(lang_provider.GetEngine (), new ContentProvider (s), "", SourceCodeKind.File);
+                       } else {
+                               throw new MissingReferenceException (name);
+                       }
+               }
+
+               public Dictionary<string, string> FileMappings {
+                       set {
+                               fileMappings = value;
+                       }
+               }
+       }
+       
+       class SilverlightPAL : PlatformAdaptationLayer
+    {
+        public override Assembly LoadAssembly(string name)
+        {
+            return Assembly.Load(LookupFullName(name));
+        }
+
+        private Dictionary<string, string> _assemblyFullNames = new 
Dictionary<string, string>();
+
+        public SilverlightPAL()
+        {
+            LoadSilverlightAssemblyNameMapping();
+        }
+
+        // TODO: This will not be necessary as it will eventually move down 
into the host
+        private void LoadSilverlightAssemblyNameMapping()
+        {
+            AssemblyName clrAssembly = new 
AssemblyName(typeof(object).Assembly.FullName);
+            foreach (string asm in new string[] { "mscorlib", "System", 
"System.Core", "System.Xml.Core" })
+            {
+                clrAssembly.Name = asm;
+                _assemblyFullNames.Add(asm.ToLower(), clrAssembly.FullName);
+            }
+
+            _assemblyFullNames.Add("system.silverlight", "System.SilverLight, 
Version=1.0.0.0, PublicKeyToken=b03f5f7f11d50a3a");
+            _assemblyFullNames.Add("agclr", "agclr, Version=0.0.0.0, 
PublicKeyToken=b03f5f7f11d50a3a");
+            _assemblyFullNames.Add("microsoft.visualbasic", 
"Microsoft.VisualBasic, Version=8.1.0.0, PublicKeyToken=b03f5f7f11d50a3a");
+
+            AssemblyName dlrAssembly = new 
AssemblyName(typeof(PlatformAdaptationLayer).Assembly.FullName);
+            foreach (string asm in new string[] {
+                "Microsoft.Scripting",
+                "Microsoft.Scripting.Silverlight",
+                "IronPython",
+                "IronPython.Modules",
+                "Microsoft.JScript.Compiler",
+                "Microsoft.JScript.Runtime",
+                "Microsoft.VisualBasic.Compiler",
+                "Microsoft.VisualBasic.Scripting",
+                "Ruby"})
+            {
+                dlrAssembly.Name = asm;
+                _assemblyFullNames.Add(asm.ToLower(), dlrAssembly.FullName);
+            }
+        }
+
+        protected new string LookupFullName(string name)
+        {
+            AssemblyName asm = new AssemblyName(name);
+            if (asm.Version != null || asm.GetPublicKeyToken() != null || 
asm.GetPublicKey() != null)
+            {
+                return name;
+            }
+            return _assemblyFullNames.ContainsKey(name.ToLower()) ? 
_assemblyFullNames[name.ToLower()] : name;
+        }
+
+    }
+
+       class MissingReferenceException : Exception {
+               string reference;
+
+               public MissingReferenceException (string reference) : base () {
+                       this.reference = reference;
+               }
+
+               public string Reference {
+                       get {
+                               return reference;
+                       }
+                       set {
+                               reference = value;
+                       }
+               }
+       }
+}
+
+
+//
+// FIXME:
+// - error handling: Silverlight usually displays a detailed error message in 
HTML
+// on top of the plugin frame
+// - in MS.NET, the x:Code directive should come before other elements
+// - changes to the x:Name property need to be propagated to the DLR
+// - exceptions in event handlers can bring down the whole process
+//

Modified: trunk/olive/class/agclr/Mono/ManagedXamlLoader.cs
===================================================================
--- trunk/olive/class/agclr/Mono/ManagedXamlLoader.cs   2007-09-28 15:43:52 UTC 
(rev 86582)
+++ trunk/olive/class/agclr/Mono/ManagedXamlLoader.cs   2007-09-28 15:46:22 UTC 
(rev 86583)
@@ -1,4 +1,4 @@
-//
+ //
 // ManagedXamlLoader.cs
 //
 // Authors:
@@ -30,6 +30,7 @@
 using System;
 using System.Reflection;
 using System.Collections;
+using System.Collections.Generic;
 using System.IO;
 using System.Windows;
 using System.Windows.Controls;
@@ -43,8 +44,12 @@
                IntPtr native_loader;
 //             string filename;
 //             string contents;
-               static Hashtable mappings = new Hashtable ();
+               static Dictionary<string, string> mappings = new Dictionary 
<string, string> ();
                XamlLoaderCallbacks callbacks;
+
+#if WITH_DLR
+               DLRHost dlr_host;
+#endif
                                
                public IntPtr PluginHandle {
                        get {
@@ -92,6 +97,7 @@
                        callbacks.insert_mapping = new InsertMappingCallback 
(insert_mapping);
                        callbacks.get_mapping = new GetMappingCallback 
(get_mapping);
                        callbacks.load_code = new LoadCodeCallback (load_code);
+                       callbacks.set_name_attribute = new 
SetNameAttributeCallback (set_name_attribute);
 
                        NativeMethods.xaml_loader_set_callbacks (native_loader, 
callbacks);
                        
@@ -114,7 +120,9 @@
                
                public string GetMapping (string key)
                {
-                       return mappings [key] as string;
+                       if (!mappings.ContainsKey (key))
+                               return null;
+                       return mappings [key];
                }
                
                private void insert_mapping (string key, string name)
@@ -129,7 +137,7 @@
                public void InsertMapping (string key, string name)
                {
                        //Console.WriteLine ("ManagedXamlLoader::InsertMapping 
({0}, {1}).", key, name);
-                       if (mappings.Contains (key)){
+                       if (mappings.ContainsKey (key)){
                                Console.Error.WriteLine 
("ManagedXamlLoader::InsertMapping ({0}, {1}): Inserting a duplicate key? 
(current value: {2}).", key, name, mappings [key]);
                                return;
                        }
@@ -137,9 +145,9 @@
                        mappings [key] = name;
                }
                
-               public void RequestAssembly (string asm_path)
+               public void RequestFile (string asm_path)
                {
-                       //Console.WriteLine 
("ManagedXamlLoader::RequestAssembly ({0}).", asm_path);
+                       //Console.WriteLine ("ManagedXamlLoader::RequestFile 
({0}).", asm_path);
                        NativeMethods.xaml_loader_add_missing (native_loader, 
asm_path);
                }
        
@@ -157,7 +165,7 @@
                                clientlib = Moonlight.LoadFile (asm_path);
                        } catch (System.IO.FileNotFoundException ex) {
                                //Console.WriteLine 
("ManagedXamlLoader::LoadAssembly (asm_path={0} asm_name={1}): client library 
not found.", asm_path, asm_name);
-                               RequestAssembly (asm_path);
+                               RequestFile (asm_path);
                                return AssemblyLoadResult.MissingAssembly;
                        }
 
@@ -211,7 +219,7 @@
                                        // not been downloaded, request it
                                        //
                                        Console.Error.WriteLine 
("ManagedXamlLoader::LoadAssembly ({0}, {1}): requesting download of '{2}' 
(exception: {3}).", asm_path, asm_name, req, ex.Message);
-                                       RequestAssembly (req);
+                                       RequestFile (req);
                                }
                        }
                        
@@ -327,6 +335,20 @@
                                return false;
                        }
 
+#if WITH_DLR
+                       if (dlr_host != null) {
+                               try {
+                                       dlr_host.HookupEvent (target, name, 
value);
+                               }
+                               catch (Exception ex) {
+                                       Console.WriteLine 
("ManagedXamlLoader::HookupEvent ({0}, {1}, {2}): unable to hookup event: {3}", 
target_ptr, name, value, ex);
+                                       return false;
+                               }
+                       } else {
+                               RememberEvent (target, name, value);
+                       }
+#endif
+
                        try {
                                Delegate d = Delegate.CreateDelegate 
(src.EventHandlerType, target, value);
                                if (d == null) {
@@ -342,28 +364,140 @@
                        }
                }
 
-               private void load_code (string source, string type)
+               private bool load_code (string source, string type)
                {
+                       try {
+                               return LoadCode (source, type);
+                       }
+                       catch (Exception ex) {
+                               Console.WriteLine ("ManagedXamlLoader::LoadCode 
({0}, {1}): {2}", source, type, ex);
+                               return false;
+                       }
+               }
+
+               private bool LoadCode (string source, string type)
+               {
                        Console.WriteLine ("ManagedXamlLoader.load_code: '" + 
source + "' '" + type + "'");
 
                        if (source == null) {
                                Console.WriteLine 
("ManagedXamlLoader.load_code: ERROR: Source can't be null.");
-                               return;
+                               return false;
                        }
 
-                       Stream s = null;
+                       if (type == null) {
+                               Console.WriteLine 
("ManagedXamlLoader.load_code: ERROR: Type can't be null.");
+                               return false;
+                       }
+
+                       //
+                       // First try the desktop case
+                       //
+                       Stream s = Moonlight.LoadResource (source);
+                       if (s != null) {
+#if WITH_DLR
+                               if (dlr_host == null)
+                                       dlr_host = new DLRHost ();
+                               dlr_host.LoadSource (s, type, mappings);
+                               SetGlobalsAndEvents ();
+#else
+                               Console.WriteLine 
("ManagedXamlLoader.load_code: Ignoring request to load code.");
+#endif
+                               return true;
+                       }
+
+                       //
+                       // Then the browser case
+                       //
+                       string local = GetMapping (source);
+                       if (local != null) {
+                               s = new FileStream (local, FileMode.Open, 
FileAccess.Read);
+#if WITH_DLR
+                               if (dlr_host == null)
+                                   dlr_host = new DLRHost ();
+                               try {
+                                       dlr_host.LoadSource (s, type, mappings);
+                               } catch (MissingReferenceException ex) {
+                                       RequestFile (ex.Reference);
+                                       return false;
+                               }
+                               SetGlobalsAndEvents ();
+#else
+                               Console.WriteLine 
("ManagedXamlLoader.load_code: Ignoring request to load code.");
+#endif
+                               return true;
+                       } else {
+                               RequestFile (source);
+
+                               return false;
+                       }
+               }
+
+               private void set_name_attribute (IntPtr target_ptr, string name)
+               {
                        try {
-                               s = Moonlight.LoadResource (source);
+                               SetNameAttribute (target_ptr, name);
                        }
                        catch (Exception ex) {
-                               Console.WriteLine 
("ManagedXamlLoader.load_code: ERROR: LoadResource failed: '" + ex + "'");
-                               return;
+                               Console.WriteLine 
("ManagedXamlLoader::SetNameAttribute () threw an exception: " + ex);
                        }
+               }
 
-                       if (s == null) {
-                               Console.WriteLine 
("ManagedXamlLoader.load_code: ERROR: Source file cannot be loaded.");
-                               return;
+               private void SetNameAttribute (IntPtr target_ptr, string name) {
+#if WITH_DLR
+                       Kind k = 
NativeMethods.dependency_object_get_object_type (target_ptr); 
+                       DependencyObject target = DependencyObject.Lookup (k, 
target_ptr);
+
+                       if (dlr_host != null) {
+                               dlr_host.SetVariable (name, target);
+                       } else {
+                               RememberName (target, name);
                        }
+#endif
                }
+
+#if WITH_DLR
+               private class RememberedEvent {
+                       public DependencyObject target;
+                       public string name;
+                       public string value;
+               }
+
+               private Dictionary<string, DependencyObject> named_objects;
+
+               private Dictionary<RememberedEvent, RememberedEvent> events;
+
+               //
+               // When SetNameAttribute and hookup_event are called, scripts 
are not yet loaded.
+               // So we store the info in hash tables and process them after a 
script has been
+               // loaded
+               private void RememberName (DependencyObject target, string 
name) {
+                       if (named_objects == null)
+                               named_objects = new Dictionary<string, 
DependencyObject> ();
+                       named_objects [name] = target;
+               }
+
+               private void RememberEvent (DependencyObject target, string 
name, string value) {
+                       if (events == null)
+                               events = new Dictionary<RememberedEvent, 
RememberedEvent> ();
+                       RememberedEvent ev = new RememberedEvent ();
+                       ev.target = target;
+                       ev.name = name;
+                       ev.value = value;
+                       events [ev] = ev;
+               }
+
+               private void SetGlobalsAndEvents () {
+                       if (named_objects != null) {
+                               foreach (KeyValuePair<string, DependencyObject> 
kvp in named_objects)
+                                       dlr_host.SetVariable (kvp.Key, 
kvp.Value);
+                               named_objects = null;
+                       }
+                       if (events != null) {
+                               foreach (RememberedEvent ev in events.Keys) {
+                                       dlr_host.HookupEvent (ev.target, 
ev.name, ev.value);
+                               }
+                       }
+               }
+#endif
        }
 }

_______________________________________________
Mono-patches maillist  -  [email protected]
http://lists.ximian.com/mailman/listinfo/mono-patches

Reply via email to