From: Jean-Philippe Bruyère Date: Thu, 4 Jun 2020 14:13:14 +0000 (+0200) Subject: remove loadTemplate with declaringType args, use normal iml load for templates, singl... X-Git-Tag: v0.9.5-beta~113^2~16 X-Git-Url: https://git.osiis.dedyn.io/?a=commitdiff_plain;h=89ef03b5bf7a317a290c5161d5e5cc1c6df8bc1d;p=jp%2Fcrow.git remove loadTemplate with declaringType args, use normal iml load for templates, single static GetStreamFromPath in all cases --- diff --git a/Crow/Templates/Window.template b/Crow/Templates/Window.template index 4c0c0f1f..a47a0e30 100644 --- a/Crow/Templates/Window.template +++ b/Crow/Templates/Window.template @@ -1,7 +1,6 @@  + Background="{./Background}"> @@ -26,6 +25,6 @@ - + diff --git a/Crow/src/Fill/BmpPicture.cs b/Crow/src/Fill/BmpPicture.cs index b707326e..c000628d 100644 --- a/Crow/src/Fill/BmpPicture.cs +++ b/Crow/src/Fill/BmpPicture.cs @@ -44,7 +44,7 @@ namespace Crow Dimensions = sp.Dims; return; } - using (Stream stream = Interface.StaticGetStreamFromPath (Path)) { + using (Stream stream = Interface.GetStreamFromPath (Path)) { #if STB_SHARP StbImageSharp.ImageResult stbi = StbImageSharp.ImageResult.FromStream (stream, StbImageSharp.ColorComponents.RedGreenBlueAlpha); image = new byte [stbi.Data.Length]; diff --git a/Crow/src/Fill/SvgPicture.cs b/Crow/src/Fill/SvgPicture.cs index 33f68955..850400cd 100644 --- a/Crow/src/Fill/SvgPicture.cs +++ b/Crow/src/Fill/SvgPicture.cs @@ -61,7 +61,7 @@ namespace Crow Dimensions = sp.Dims; return; } - using (Stream stream = Interface.StaticGetStreamFromPath (Path)) { + using (Stream stream = Interface.GetStreamFromPath (Path)) { using (MemoryStream ms = new MemoryStream ()) { stream.CopyTo (ms); diff --git a/Crow/src/IML/CompilerServices.cs b/Crow/src/IML/CompilerServices.cs index 4d0dd567..cf3ee73f 100644 --- a/Crow/src/IML/CompilerServices.cs +++ b/Crow/src/IML/CompilerServices.cs @@ -76,8 +76,7 @@ namespace Crow.IML internal static MethodInfo miGetDataSource = typeof(Widget).GetProperty("DataSource").GetGetMethod (); internal static EventInfo eiLogicalParentChanged = typeof(Widget).GetEvent("LogicalParentChanged"); - internal static MethodInfo miIFaceLoad = typeof(Interface).GetMethod ("CreateInstance", BindingFlags.Instance | BindingFlags.Public); - internal static MethodInfo miIFaceCreateTemplateInst = typeof (Interface).GetMethod ("CreateTemplateInstance", BindingFlags.Instance | BindingFlags.Public); + internal static MethodInfo miIFaceCreateInstance = typeof(Interface).GetMethod ("CreateInstance", BindingFlags.Instance | BindingFlags.Public); internal static MethodInfo miGetITemp = typeof(Interface).GetMethod ("GetItemTemplate", BindingFlags.Instance | BindingFlags.Public); internal static MethodInfo miAddITemp = typeof(Dictionary).GetMethod ("set_Item", new Type[] { typeof(string), typeof(ItemTemplate) }); diff --git a/Crow/src/IML/Instantiator.cs b/Crow/src/IML/Instantiator.cs index 9451f6ed..9668a8c2 100644 --- a/Crow/src/IML/Instantiator.cs +++ b/Crow/src/IML/Instantiator.cs @@ -62,7 +62,7 @@ namespace Crow.IML { /// /// Initializes a new instance of the Instantiator class. /// - public Instantiator (Interface _iface, string path) : this (_iface, _iface.GetStreamFromPath(path), path) { + public Instantiator (Interface _iface, string path) : this (_iface, Interface.GetStreamFromPath(path), path) { } /// @@ -281,7 +281,7 @@ namespace Crow.IML { itemTmpID += path+dataType+datas; if (!iface.ItemTemplates.ContainsKey (itemTmpID)) iface.ItemTemplates [itemTmpID] = - new ItemTemplate (iface, path, ctx.CurrentNodeType, dataTest, dataType, datas); + new ItemTemplate (iface, path, dataTest, dataType, datas); } return new string [] { dataType, itemTmpID, datas, dataTest }; } @@ -322,14 +322,9 @@ namespace Crow.IML { if (!string.IsNullOrEmpty (templatePath)) { ctx.il.Emit (OpCodes.Ldloc_0);//Load current templatedControl ref - // ctx.il.Emit (OpCodes.Ldnull);//default template loading - //} else { ctx.il.Emit (OpCodes.Ldarg_1);//load currentInterface ctx.il.Emit (OpCodes.Ldstr, templatePath); //Load template path string - //get declaring type for search fallback assembly - ctx.il.Emit (OpCodes.Ldloc_0); - ctx.il.Emit (OpCodes.Call, CompilerServices.miGetType); - ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miIFaceCreateTemplateInst); + ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miIFaceCreateInstance); ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miLoadTmp);//load template } } @@ -340,7 +335,7 @@ namespace Crow.IML { if (iface.ItemTemplates.ContainsKey (itemTemplatePath)) { itemTemplateIds.Add (new string [] { "default", itemTemplatePath, "" }); } else { - using (Stream stream = iface.GetTemplateStreamFromPath (itemTemplatePath, ctx.CurrentNodeType)) { + using (Stream stream = Interface.GetStreamFromPath (itemTemplatePath)) { //itemtemplate files may have multiple root nodes XmlReaderSettings itrSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment }; using (XmlReader itr = XmlReader.Create (stream, itrSettings)) { @@ -378,9 +373,6 @@ namespace Crow.IML { //load itemTemplate ctx.il.Emit (OpCodes.Ldarg_1);//load currentInterface ctx.il.Emit (OpCodes.Ldstr, iTempId [1]);//load path - //second arg is Type, to find assembly where to search if not in entry - ctx.il.Emit (OpCodes.Ldloc_0);//load TempControl ref - ctx.il.Emit (OpCodes.Call, CompilerServices.miGetType); ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miGetITemp); ctx.il.Emit (OpCodes.Callvirt, CompilerServices.miAddITemp); diff --git a/Crow/src/Interface.cs b/Crow/src/Interface.cs index 76858729..5adf3172 100644 --- a/Crow/src/Interface.cs +++ b/Crow/src/Interface.cs @@ -454,19 +454,20 @@ namespace Crow /// Than in any IML expresion, in style or xml, constant may be used as a replacement string with ${CONSTANTID}. /// If a constant is not resolved in iml while creating the instantiator, an error is thrown. /// - public readonly Dictionary StylingConstants = new Dictionary (); + public Dictionary StylingConstants; /// parse all styling data's during application startup and build global Styling Dictionary protected virtual void loadStyling() { + StylingConstants = new Dictionary (); Styling = new Dictionary (); //fetch styling info in this order, if member styling is alreadey referenced in previous //assembly, it's ignored. - loadStylingFromAssembly (Assembly.GetEntryAssembly ()); - loadStylingFromAssembly (Assembly.GetExecutingAssembly ()); + loadStylingFromAssembly (Assembly.GetExecutingAssembly ()); foreach (Assembly a in crowAssemblies) { loadStylingFromAssembly (a); } + loadStylingFromAssembly (Assembly.GetEntryAssembly ()); } /// Search for .style resources in assembly protected void loadStylingFromAssembly (Assembly assembly) { @@ -476,93 +477,44 @@ namespace Crow .GetManifestResourceNames () .Where (r => r.EndsWith (".style", StringComparison.OrdinalIgnoreCase))) { using (StyleReader sr = new StyleReader (assembly.GetManifestResourceStream (s))) - sr.Parse (this, s); + sr.Parse (this.StylingConstants, this.Styling, s); } } #endregion #region Load/Save - /// get template stream from path providing the declaring type for which - /// this template is loaded. If not found in entry assembly, the assembly where the type is defined - /// will be searched - /// - /// The template stream - public virtual Stream GetTemplateStreamFromPath (string path, Type declaringType) - { - Stream s = null; - if (path.StartsWith ("#", StringComparison.Ordinal)) { - string resId = path.Substring (1); - s = Assembly.GetEntryAssembly ()?.GetManifestResourceStream (resId); - if (s != null) - return s; - string assemblyName = resId.Split ('.')[0]; - Assembly a = AppDomain.CurrentDomain.GetAssemblies ().FirstOrDefault (aa => aa.GetName ().Name == assemblyName); - s = a?.GetManifestResourceStream (resId); - if (s != null) - return s; - s = Assembly.GetAssembly (declaringType).GetManifestResourceStream (resId); - if (s == null) - throw new Exception ($"Template ressource not found '{path}'"); - } else { - if (!File.Exists (path)) - throw new FileNotFoundException ($"Template not found: {path}", path); - s = new FileStream (path, FileMode.Open, FileAccess.Read); - } - return s; + static bool tryGetResource (Assembly a, string resId, out Stream stream) { + stream = null; + if (a == null) + return false; + stream = a.GetManifestResourceStream (resId); + return stream != null; } - /// Open file or find a resource from path string - /// A file or resource stream - /// This could be a normal file path, or an embedded ressource ID - /// Resource ID's must be prefixed with '#' character - public virtual Stream GetStreamFromPath (string path) - { - Stream stream = null; - if (path.StartsWith ("#", StringComparison.Ordinal)) { - string resId = path.Substring (1); - stream = Assembly.GetEntryAssembly ()?.GetManifestResourceStream (resId); - if (stream != null) - return stream; - string assemblyName = resId.Split ('.') [0]; - Assembly a = AppDomain.CurrentDomain.GetAssemblies ().FirstOrDefault (aa => aa.GetName ().Name == assemblyName); - if (a == null) - throw new Exception ($"Assembly '{assemblyName}' not found for ressource '{path}'."); - stream = a.GetManifestResourceStream (resId); - if (stream == null) - throw new Exception ("Resource not found: " + path); - } else { - if (!File.Exists (path)) - throw new FileNotFoundException ($"File not found: {path}", path); - stream = new FileStream (path, FileMode.Open, FileAccess.Read); - } - return stream; - } - public static Stream StaticGetStreamFromPath (string path) + public static Stream GetStreamFromPath (string path) { - Stream stream = null; - if (path.StartsWith ("#", StringComparison.Ordinal)) { + Stream stream = null; string resId = path.Substring (1); - stream = Assembly.GetEntryAssembly ()?.GetManifestResourceStream (resId); - if (stream != null) + if (tryGetResource (Assembly.GetEntryAssembly (), resId, out stream)) return stream; - string assemblyName = resId.Split ('.') [0]; - Assembly a = AppDomain.CurrentDomain.GetAssemblies ().FirstOrDefault (aa => aa.GetName ().Name == assemblyName); - if (a == null) - throw new Exception ($"Assembly '{assemblyName}' not found for ressource '{path}'."); - stream = a.GetManifestResourceStream (resId); - /*foreach (var s in a.GetManifestResourceNames()) { - System.Diagnostics.Debug.WriteLine (s); - }*/ - if (stream == null) - throw new Exception ("Resource not found: " + path); - } else { - if (!File.Exists (path)) - throw new FileNotFoundException ($"File not found: {path}", path); - stream = new FileStream (path, FileMode.Open, FileAccess.Read); - } - return stream; + string[] assemblyNames = resId.Split ('.'); + if (tryGetResource (AppDomain.CurrentDomain.GetAssemblies () + .FirstOrDefault (aa => aa.GetName ().Name == assemblyNames[0]), resId, out stream)) + return stream; + if (assemblyNames.Length > 3) + if (tryGetResource (AppDomain.CurrentDomain.GetAssemblies () + .FirstOrDefault (aa => aa.GetName ().Name == $"{assemblyNames[0]}.{assemblyNames[1]}"), resId, out stream)) + return stream; + foreach (Assembly ca in crowAssemblies) + if (tryGetResource (ca, resId, out stream)) + return stream; + throw new Exception ("Resource not found: " + path); + } + if (!File.Exists (path)) + throw new FileNotFoundException ($"File not found: {path}", path); + return new FileStream (path, FileMode.Open, FileAccess.Read); } /// /// Add the content of the IML fragment to the graphic tree of this interface @@ -603,28 +555,7 @@ namespace Crow /// new instance of graphic object created /// path of the iml file to load public virtual Widget CreateInstance (string path) - { - //try { - return GetInstantiator (path).CreateInstance (); - //} catch (Exception ex) { - // throw new Exception ("Error loading <" + path + ">:", ex); - //} - } - /// - /// Create an instance of a GraphicObject linked to this interface but not added to the GraphicTree - /// - /// new instance of graphic object created - /// path of the iml file to load - public virtual Widget CreateTemplateInstance (string path, Type declaringType) - { -// try { - if (!Templates.ContainsKey (path)) - Templates [path] = new Instantiator (this, GetTemplateStreamFromPath(path, declaringType), path); - return Templates [path].CreateInstance (); - //} catch (Exception ex) { - // throw new Exception ("Error loading Template <" + path + ">:", ex); - //} - } + => GetInstantiator (path).CreateInstance (); /// /// Fetch instantiator from cache or create it. /// @@ -639,9 +570,9 @@ namespace Crow /// try to fetch the requested one in the cache or create it. /// They have additional properties for recursivity and /// custom display per item type - public virtual ItemTemplate GetItemTemplate(string path, Type declaringType){ + public virtual ItemTemplate GetItemTemplate(string path){ if (!ItemTemplates.ContainsKey(path)) - ItemTemplates [path] = new ItemTemplate(this, path, declaringType); + ItemTemplates [path] = new ItemTemplate(this, path); return ItemTemplates [path] as ItemTemplate; } #endregion diff --git a/Crow/src/ItemTemplate.cs b/Crow/src/ItemTemplate.cs index 1d779be7..01e76b59 100644 --- a/Crow/src/ItemTemplate.cs +++ b/Crow/src/ItemTemplate.cs @@ -81,8 +81,8 @@ namespace Crow /// IML file to parse /// type this item will be choosen for, or member of the data item /// for hierarchical data, method to call for children fetching - public ItemTemplate (Interface _iface, string path, Type declaringType, string _dataTest = "TypeOf", string _dataType = "default", string _fetchDataMethod = null) - : base(_iface, _iface.GetTemplateStreamFromPath (path, declaringType)) { + public ItemTemplate (Interface _iface, string path, string _dataTest = "TypeOf", string _dataType = "default", string _fetchDataMethod = null) + : base(_iface, Interface.GetStreamFromPath (path)) { strDataType = _dataType; fetchMethodName = _fetchDataMethod; dataTest = _dataTest; diff --git a/Crow/src/Widgets/TemplatedControl.cs b/Crow/src/Widgets/TemplatedControl.cs index 896ecdce..965676e7 100644 --- a/Crow/src/Widgets/TemplatedControl.cs +++ b/Crow/src/Widgets/TemplatedControl.cs @@ -54,7 +54,7 @@ namespace Crow if (string.IsNullOrEmpty(_template)) loadTemplate (); else - loadTemplate (IFace.CreateTemplateInstance (_template, this.GetType())); + loadTemplate (IFace.CreateInstance (_template)); } } /// diff --git a/Crow/src/XCursor.cs b/Crow/src/XCursor.cs index e6eb4636..cb596c70 100644 --- a/Crow/src/XCursor.cs +++ b/Crow/src/XCursor.cs @@ -88,7 +88,7 @@ namespace Crow public static XCursorFile Load(string path) { - return loadFromStream (Interface.StaticGetStreamFromPath (path)); + return loadFromStream (Interface.GetStreamFromPath (path)); } static XCursor imageLoad (BinaryReader sr) diff --git a/Crow/src/styling/StyleReader.cs b/Crow/src/styling/StyleReader.cs index d4e56de9..96b79b9e 100644 --- a/Crow/src/styling/StyleReader.cs +++ b/Crow/src/styling/StyleReader.cs @@ -60,8 +60,7 @@ namespace Crow /// Parse the full style stream and load the result in 'Styling' and 'StylingConstant' /// fields of the interface passed as argument. /// - /// the Interface to load the style for - public void Parse (Interface iFace, string resId) + public void Parse (Dictionary StylingConstants, Dictionary Styling, string resId) { column = 1; line = 1; @@ -133,9 +132,9 @@ namespace Crow break; constantId += c; } - if (string.IsNullOrEmpty (constantId) || !iFace.StylingConstants.ContainsKey (constantId)) + if (string.IsNullOrEmpty (constantId) || !StylingConstants.ContainsKey (constantId)) throw new ParserException (line, column, "Empty constant id in styling", resId); - token += iFace.StylingConstants [constantId]; + token += StylingConstants [constantId]; continue; } } else if (c == '\"') { @@ -151,15 +150,15 @@ namespace Crow ReadChar (); if (targetsClasses.Count == 0) { //style constants - iFace.StylingConstants[currentProperty] = token; + StylingConstants[currentProperty] = token; curState = States.classNames; } else { foreach (string tc in targetsClasses) { - if (!iFace.Styling.ContainsKey (tc)) - iFace.Styling [tc] = new Style (); - iFace.Styling [tc] [currentProperty] = token; + if (!Styling.ContainsKey (tc)) + Styling [tc] = new Style (); + Styling [tc] [currentProperty] = token; #if DESIGN_MODE - iFace.Styling [tc].Locations[currentProperty] = new FileLocation(resId, line, column - token.Length - 1, token.Length); + Styling [tc].Locations[currentProperty] = new FileLocation(resId, line, column - token.Length - 1, token.Length); #endif } curState = States.members; diff --git a/Samples/ShowCase/ShowCase.cs b/Samples/ShowCase/ShowCase.cs index 10da3683..8f3c70ec 100644 --- a/Samples/ShowCase/ShowCase.cs +++ b/Samples/ShowCase/ShowCase.cs @@ -10,9 +10,8 @@ using Crow.IML; namespace ShowCase { - class Showcase : Interface + class Showcase : SampleBase { - static void Main () { #if NETCOREAPP3_1 @@ -24,8 +23,20 @@ namespace ShowCase public Container crowContainer; + public string CurrentDir { + get { return Configuration.Global.Get ("CurrentDir"); } + set { + if (CurrentDir == value) + return; + Configuration.Global.Set ("CurrentDir", value); + NotifyValueChanged ("CurrentDir",CurrentDir); + } + } + protected override void OnInitialized () { + if (string.IsNullOrEmpty (CurrentDir)) + CurrentDir = Path.Combine (Directory.GetCurrentDirectory (), "Interfaces"); Widget g = Load ("#ShowCase.showcase.crow"); g.DataSource = this; crowContainer = g.FindByName ("CrowContainer") as Container; @@ -46,12 +57,6 @@ namespace ShowCase #endif } - public Showcase () - : base (1024, 800) - { - } - - void Dv_SelectedItemChanged (object sender, SelectionChangeEventArgs e) { FileSystemInfo fi = e.NewValue as FileSystemInfo; @@ -59,23 +64,11 @@ namespace ShowCase return; if (fi is DirectoryInfo) return; - hideError (); - lock (UpdateMutex) { - try { - Widget g = CreateInstance (fi.FullName); - crowContainer.SetChild (g); - g.DataSource = this; - } catch (Exception ex) { - Console.WriteLine (ex.ToString ()); - showError (ex); - } - } string source = ""; using (Stream s = new FileStream (fi.FullName, FileMode.Open)) { - using (StreamReader sr = new StreamReader (s)) { + using (StreamReader sr = new StreamReader (s)) source = sr.ReadToEnd (); - } } NotifyValueChanged ("source", source); } @@ -104,9 +97,12 @@ namespace ShowCase crowContainer.SetChild (g); g.DataSource = this; } + } catch (InstantiatorException itorex) { + Console.WriteLine (itorex.ToString ()); + showError (itorex.InnerException); } catch (Exception ex) { - Console.WriteLine (ex.ToString ()); - showError ((Exception)ex); + Console.WriteLine (ex); + showError (ex); } } diff --git a/Samples/common/ui/Interfaces/Divers/testFocus.crow b/Samples/common/ui/Interfaces/Divers/testFocus.crow index 1f262631..d8f914ee 100644 --- a/Samples/common/ui/Interfaces/Divers/testFocus.crow +++ b/Samples/common/ui/Interfaces/Divers/testFocus.crow @@ -29,15 +29,15 @@