Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/SharpVectorRenderingGdi/Forms/SvgPictureBox.cs @ 12762

Last change on this file since 12762 was 12762, checked in by aballeit, 9 years ago

#2283 GUI updates, Tree-chart, MCTS Version 2 (prune leaves)

File size: 23.6 KB
Line 
1using System;
2using System.IO;
3using System.Xml;
4using System.Text;
5using System.Drawing;
6using System.Windows.Forms;
7using System.ComponentModel;
8using System.Collections.Generic;
9
10using SharpVectors.Net;
11using SharpVectors.Xml;
12using SharpVectors.Dom;
13using SharpVectors.Dom.Css;
14using SharpVectors.Dom.Events;
15using SharpVectors.Dom.Svg;
16using SharpVectors.Renderers;
17using SharpVectors.Renderers.Gdi;
18
19namespace SharpVectors.Renderers.Forms
20{
21    public partial class SvgPictureBox : Control
22    {
23        #region Private Fields
24
25        private static readonly string UserAgentCssFileName = "useragent.css";
26        private static readonly string UserCssFileName = "user.css";
27
28        private GdiGraphicsRenderer renderer;
29
30        /// <summary>
31        /// Required designer variable.
32        /// </summary>
33        private System.ComponentModel.Container components = null;
34        private SvgPictureBoxWindow window;
35        private bool loaded = false;
36
37        //private Thread renderThread;
38        private Graphics surface;
39
40        #endregion
41
42        #region Constructors and Destructor
43
44        public SvgPictureBox()
45        {
46            InitializeComponent();
47
48            SetStyle(ControlStyles.UserPaint, true);
49            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
50            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
51
52            //scriptEngineByMimeType = new TypeDictionary();
53            //SetMimeTypeEngineType("application/ecmascript", typeof(JScriptEngine));
54
55            renderer = new GdiGraphicsRenderer();
56            renderer.OnRender = new RenderEvent(this.OnRender);
57            window = new SvgPictureBoxWindow(this, renderer);
58        }
59
60        /// <summary>
61        /// Clean up any resources being used.
62        /// </summary>
63        protected override void Dispose(bool disposing)
64        {
65            renderer.Dispose();
66
67            if (disposing)
68            {
69                if (components != null)
70                {
71                    components.Dispose();
72                    components = null;
73                }
74            }
75
76            base.Dispose(disposing);
77        }
78
79        #endregion
80
81        #region Public Events
82
83        public void OnRender(SvgRectF updatedRect)
84        {
85            if (surface != null)
86            {
87                if (updatedRect == SvgRectF.Empty)
88                    Draw(surface);
89                else
90                    Draw(surface, GdiConverter.ToRectangle(updatedRect));
91            }
92            else
93            {
94                surface = CreateGraphics();
95
96                UpdateGraphics(surface);
97
98                if (updatedRect == SvgRectF.Empty)
99                    Draw(surface);
100                else
101                    Draw(surface, GdiConverter.ToRectangle(updatedRect));
102                surface.Dispose();
103                surface = null;
104            }
105
106            // Collect the rendering regions for later updates
107            //SvgDocument doc = (window.Document as SvgDocument);
108            //SvgElement root = (doc.RootElement as SvgElement);
109            //root.CacheRenderingRegion(renderer);
110        }
111
112        private void UpdateGraphics(Graphics graphics)
113        {
114        }
115
116        private int lastX = -1;
117        private int lastY = -1;
118        protected override void OnMouseMove(MouseEventArgs e)
119        {
120            base.OnMouseMove(e);
121           
122            if (lastX == e.X && lastY == e.Y)
123                return;
124            lastX = e.X;
125            lastY = e.Y;
126
127            renderer.OnMouseEvent("mousemove", e);
128        }
129
130        protected override void OnMouseDown(MouseEventArgs e)
131        {
132            base.OnMouseDown(e);
133            renderer.OnMouseEvent("mousedown", e);
134        }
135
136        protected override void OnMouseUp(MouseEventArgs e)
137        {
138            base.OnMouseUp(e);
139            renderer.OnMouseEvent("mouseup", e);
140        }
141
142        #endregion
143
144        #region Public Properties
145
146        /// <summary>
147        /// Source URL for the Svg Content
148        /// </summary>
149        [Category("Data")]
150        [DefaultValue("")]
151        [Description("The URL of the document currently being display in this SvgPictureBox")]
152        public string SourceURL
153        {
154            get
155            {
156                return window.Source;
157            }
158            set
159            {
160                Load(value);
161            }
162        }
163
164        /// <summary>
165        /// Return current SvgWindow used by this control
166        /// </summary>
167        [Category("Data")]
168        [DefaultValue("")]
169        [Description("The Window Interface connected to the SvgPictureBox")]
170        public ISvgWindow Window
171        {
172            get
173            {
174                return window;
175            }
176        }
177
178        public Graphics Surface
179        {
180            get { return surface; }
181            set { surface = value; }
182        }
183
184        public RectangleF InvalidRect
185        {
186            get { return GdiConverter.ToRectangle(renderer.InvalidRect); }
187        }
188
189        #endregion
190
191        #region Public Methods
192
193        public void Load(string value)
194        {
195            try
196            {
197                // Worry about clearing the graphics nodes map...
198                renderer.ClearMap();
199                System.GC.Collect();
200                System.Threading.Thread.Sleep(1);
201
202                if (value != null && value.Length > 0)
203                {
204                    // Load the source
205                    window.Source = value;
206                    // Initialize the style sheets
207                    SetupStyleSheets();
208                    // Execute all script elements
209                    //UnloadEngines();
210                    //InitializeEvents();
211                    //ExecuteScripts();
212                    //JR
213                    if (this.AutoSize)
214                    {
215                        ISvgSvgElement svgEl = window.Document.RootElement;
216                        this.Width = (int)svgEl.Width.BaseVal.Value;
217                        this.Height = (int)svgEl.Height.BaseVal.Value;
218                    }
219                    renderer.InvalidRect = SvgRectF.Empty;
220                    Render();
221                    loaded = true;
222                }
223            }
224            catch (Exception e)
225            {   
226                StringBuilder builder = new StringBuilder();
227                builder.AppendLine("An error occurred while loading the document.\n");
228                builder.AppendLine();
229                builder.AppendLine(e.ToString());
230                MessageBox.Show(builder.ToString());
231            }
232        }
233
234        public void LoadXml(string xml)
235        {
236            try
237            {
238                // Worry about clearing the graphics nodes map...
239                renderer.ClearMap();
240                System.GC.Collect();
241                System.Threading.Thread.Sleep(1);
242
243                if (xml != null && xml.Length > 0)
244                {
245                    if (xml != null && xml.Length > 0)
246                    {
247                        SvgDocument doc = window.CreateEmptySvgDocument();
248                        doc.LoadXml(xml);
249                        window.Document = doc;
250                        SetupStyleSheets();
251                        //JR
252                        if (this.AutoSize)
253                        {
254                            ISvgRect r = window.Document.RootElement.GetBBox();
255                            this.Width = (int)r.Width;
256                            this.Height = (int)r.Height;
257                        }
258                        Render();
259                        loaded = true;
260                    }
261                }
262            }
263            catch (Exception e)
264            {
265                MessageBox.Show("An error occured while loading the document.\n" + e.Message);
266            }
267        }
268
269        public void Render()
270        {
271            if (this.window != null)
272            {
273                InvalidateAndRender();
274            }
275        }
276
277        public void Update(RectangleF rect)
278        {
279            if (this.window != null)
280            {
281                InvalidateAndUpdate(rect);
282            }
283        }
284
285        public void CacheRenderingRegions()
286        {
287            // Collect the rendering regions for later updates
288
289            //System.Threading.Thread.Sleep(1);
290            //SvgDocument doc = (window.Document as SvgDocument);
291            //SvgElement root = (doc.RootElement as SvgElement);
292            //root.CacheRenderingRegion(renderer);
293        }
294
295        /// <summary>
296        /// Create an empty SvgDocument and GdiRenderer for this control.  The empty SvgDocument is returned.  This method is needed only in situations where the library user needs to create an SVG DOM tree outside of the usual window Src setting mechanism.
297        /// </summary>
298        public SvgDocument CreateEmptySvgDocument()
299        {
300            SvgDocument svgDocument = window.CreateEmptySvgDocument();
301            SetupStyleSheets();
302
303            return svgDocument;
304        }
305
306        public void DrawTo(IntPtr hdc)
307        {
308            if (!this.DesignMode)
309            {
310                if (window != null)
311                {
312                    GdiGraphicsWrapper gw = GdiGraphicsWrapper.FromHdc(hdc, true);
313                    GdiGraphicsRenderer r = ((GdiGraphicsRenderer)window.Renderer);
314                    gw.Clear(r.BackColor);
315                    r.GraphicsWrapper = gw;
316                    window.Renderer.Render((SvgDocument)window.Document);
317                    r.GraphicsWrapper = null;
318                    gw.Dispose();
319                }
320            }
321        }
322
323        public void Draw(Graphics gr)
324        {
325            if (!this.DesignMode)
326            {
327                if (window != null)
328                {
329                    Bitmap rasterImage = ((GdiGraphicsRenderer)window.Renderer).RasterImage;
330
331                    if (rasterImage != null)
332                    {
333                        gr.DrawImage(rasterImage, 0, 0, rasterImage.Width, rasterImage.Height);
334                    }
335                }
336            }
337        }
338
339        public void Draw(Graphics gr, int offsetX, int offsetY)
340        {
341            if (!this.DesignMode)
342            {
343                if (window != null)
344                {
345                    Bitmap rasterImage = ((GdiGraphicsRenderer)window.Renderer).RasterImage;
346
347                    if (rasterImage != null)
348                    {
349                        gr.DrawImage(rasterImage, offsetX, offsetY, rasterImage.Width, rasterImage.Height);
350                    }
351                }
352            }
353        }
354
355        public void Draw(Graphics gr, RectangleF rect)
356        {
357            if (!this.DesignMode)
358            {
359                if (window != null)
360                {
361                    Bitmap rasterImage = ((GdiGraphicsRenderer)window.Renderer).RasterImage;
362
363                    if (rasterImage != null)
364                    {
365                        gr.DrawImage(rasterImage, rect, rect, GraphicsUnit.Pixel);
366                    }
367                }
368            }
369        }
370
371        #endregion
372
373        #region Protected Methods
374
375        protected override void OnPaint(PaintEventArgs e)
376        {
377            if (surface != null)
378            {
379                Draw(surface);
380            }
381            else
382            {
383                Graphics graphics = e.Graphics;
384
385                UpdateGraphics(graphics);
386
387                Draw(graphics);
388            }
389        }
390
391        protected override void OnResize(EventArgs e)
392        {
393            base.OnResize(e);
394            if (loaded)
395            {
396                // Worry about clearing the graphics nodes map...
397                //System.GC.Collect();
398                //System.Threading.Thread.Sleep(1);
399
400                (window as SvgWindow).Resize(this.Width, this.Height);
401                InvalidateAndRender();
402            }
403        }
404
405        /// <summary>
406        /// Loads the default user and agent stylesheets into the current SvgDocument
407        /// </summary>
408        protected virtual void SetupStyleSheets()
409        {
410            CssXmlDocument cssDocument = (CssXmlDocument)window.Document;
411            string appRootPath         = SvgApplicationContext.ExecutableDirectory.FullName;
412            FileInfo userAgentCssPath  = new FileInfo(appRootPath + "\\" + UserAgentCssFileName);
413            FileInfo userCssPath       = new FileInfo(appRootPath + "\\" + UserCssFileName);
414
415            if (userAgentCssPath.Exists)
416            {
417                cssDocument.SetUserAgentStyleSheet((new Uri("file:/" + userAgentCssPath.FullName)).AbsoluteUri);
418            }
419
420            if (userCssPath.Exists)
421            {
422                cssDocument.SetUserStyleSheet((new Uri("file:/" + userCssPath.FullName)).AbsoluteUri);
423            }
424        }
425
426        #endregion
427
428        #region Private Methods
429
430        private void InvalidateAndRender()
431        {
432            try
433            {
434                renderer.Render(window.Document as SvgDocument);
435            }
436            catch (Exception e)
437            {
438                MessageBox.Show("An exception occurred while rendering: " + e.Message);
439            }
440        }
441
442        private void InvalidateAndUpdate(RectangleF rect)
443        {
444            renderer.InvalidateRect(SvgConverter.ToRect(rect));
445            InvalidateAndRender();
446        }
447
448        #endregion
449
450        #region Scripting Methods and Properties
451
452//        private TypeDictionary scriptEngineByMimeType;
453//        private Dictionary<string, ScriptEngine> scriptEngines = new Dictionary<string, ScriptEngine>();
454
455//        public void SetMimeTypeEngineType(string mimeType, Type engineType)
456//        {
457//            scriptEngineByMimeType[mimeType] = engineType;
458//        }
459
460//        public ScriptEngine GetScriptEngineByMimeType(string mimeType)
461//        {
462//            ScriptEngine engine = null;
463
464//            if (mimeType == "")
465//                mimeType = ((ISvgWindow)window).Document.RootElement.GetAttribute("contentScriptType");
466
467//            if (mimeType == "" || mimeType == "text/ecmascript" || mimeType == "text/javascript" || mimeType == "application/javascript")
468//                mimeType = "application/ecmascript";
469
470//            if (!scriptEngines.ContainsKey(mimeType))
471//            {
472//                object[] args = new object[] { (window as ISvgWindow) };
473//                engine = (ScriptEngine)scriptEngineByMimeType.CreateInstance(mimeType, args);
474//                scriptEngines.Add(mimeType, engine);
475//                engine.Initialise();
476//            }
477
478//            if (engine == null)
479//                engine = scriptEngines[mimeType];
480
481//            return engine;
482//        }
483
484
485//        /// <summary>
486//        /// Clears the existing script engine list from any previously running instances
487//        /// </summary>
488//        private void UnloadEngines()
489//        {
490//            // Dispose of all running engines from previous document instances
491//            foreach (string mimeType in scriptEngines.Keys)
492//            {
493//                ScriptEngine engine = scriptEngines[mimeType];
494//                engine.Close();
495//                engine = null;
496//            }
497//            // Clear the list
498//            scriptEngines.Clear();
499//            ClosureEventMonitor.Clear();
500//            ScriptTimerMonitor.Reset();
501//        }
502
503//        /// <summary>
504//        /// Add event listeners for on* events within the document
505//        /// </summary>
506//        private void InitializeEvents()
507//        {
508//            SvgDocument document = (SvgDocument)window.Document;
509//            document.NamespaceManager.AddNamespace("svg", "http://www.w3.org/2000/svg");
510
511//            XmlNodeList nodes = document.SelectNodes(@"//*[namespace-uri()='http://www.w3.org/2000/svg']
512//                                                   [local-name()='svg' or
513//                                                    local-name()='g' or
514//                                                    local-name()='defs' or
515//                                                    local-name()='symbol' or
516//                                                    local-name()='use' or
517//                                                    local-name()='switch' or
518//                                                    local-name()='image' or
519//                                                    local-name()='path' or
520//                                                    local-name()='rect' or
521//                                                    local-name()='circle' or
522//                                                    local-name()='ellipse' or
523//                                                    local-name()='line' or
524//                                                    local-name()='polyline' or
525//                                                    local-name()='polygon' or
526//                                                    local-name()='text' or
527//                                                    local-name()='tref' or
528//                                                    local-name()='tspan' or
529//                                                    local-name()='textPath' or
530//                                                    local-name()='altGlyph' or
531//                                                    local-name()='a' or
532//                                                    local-name()='foreignObject']
533//                                                /@*[name()='onfocusin' or
534//                                                    name()='onfocusout' or
535//                                                    name()='onactivate' or
536//                                                    name()='onclick' or
537//                                                    name()='onmousedown' or
538//                                                    name()='onmouseup' or
539//                                                    name()='onmouseover' or
540//                                                    name()='onmousemove' or
541//                                                    name()='onmouseout' or
542//                                                    name()='onload']", document.NamespaceManager);
543
544//            foreach (XmlNode node in nodes)
545//            {
546//                IAttribute att = (IAttribute)node;
547//                IEventTarget targ = (IEventTarget)att.OwnerElement;
548//                ScriptEventMonitor mon = new ScriptEventMonitor((VsaScriptEngine)GetScriptEngineByMimeType(""), att, window);
549//                string eventName = null;
550//                switch (att.Name)
551//                {
552//                    case "onfocusin":
553//                        eventName = "focusin";
554//                        break;
555//                    case "onfocusout":
556//                        eventName = "focusout";
557//                        break;
558//                    case "onactivate":
559//                        eventName = "activate";
560//                        break;
561//                    case "onclick":
562//                        eventName = "click";
563//                        break;
564//                    case "onmousedown":
565//                        eventName = "mousedown";
566//                        break;
567//                    case "onmouseup":
568//                        eventName = "mouseup";
569//                        break;
570//                    case "onmouseover":
571//                        eventName = "mouseover";
572//                        break;
573//                    case "onmousemove":
574//                        eventName = "mousemove";
575//                        break;
576//                    case "onmouseout":
577//                        eventName = "mouseout";
578//                        break;
579//                    case "onload":
580//                        eventName = "SVGLoad";
581//                        break;
582//                }
583//                targ.AddEventListener(eventName, new EventListener(mon.EventHandler), false);
584//            }
585//        }
586
587//        /// <summary>
588//        /// Collect the text in all script elements, build engine and execute.
589//        /// </summary>
590//        private void ExecuteScripts()
591//        {
592//            Dictionary<string, StringBuilder> codeByMimeType = new Dictionary<string, StringBuilder>();
593//            StringBuilder codeBuilder;
594//            SvgDocument document = (SvgDocument)window.Document;
595
596//            XmlNodeList scripts = document.GetElementsByTagName("script", SvgDocument.SvgNamespace);
597//            StringBuilder code = new StringBuilder();
598
599//            foreach (XmlElement script in scripts)
600//            {
601//                string type = script.GetAttribute("type");
602
603//                if (GetScriptEngineByMimeType(type) != null)
604//                {
605//                    // make sure we have a StringBuilder for this MIME type
606//                    if (!codeByMimeType.ContainsKey(type))
607//                        codeByMimeType[type] = new StringBuilder();
608
609//                    // grab this MIME type's codeBuilder
610//                    codeBuilder = codeByMimeType[type];
611
612//                    if (script.HasChildNodes)
613//                    {
614//                        // process each child that is text node or a CDATA section
615//                        foreach (XmlNode node in script.ChildNodes)
616//                        {
617//                            if (node.NodeType == XmlNodeType.CDATA || node.NodeType == XmlNodeType.Text)
618//                            {
619//                                codeBuilder.Append(node.Value);
620//                            }
621//                        }
622//                    }
623
624//                    if (script.HasAttribute("href", "http://www.w3.org/1999/xlink"))
625//                    {
626//                        string href = script.GetAttribute("href", "http://www.w3.org/1999/xlink");
627//                        Uri baseUri = new Uri(((XmlDocument)((ISvgWindow)window).Document).BaseURI);
628//                        Uri hUri = new Uri(baseUri, href);
629//                        ExtendedHttpWebRequestCreator creator = new ExtendedHttpWebRequestCreator();
630//                        ExtendedHttpWebRequest request = (ExtendedHttpWebRequest)creator.Create(hUri);
631//                        ExtendedHttpWebResponse response = (ExtendedHttpWebResponse)request.GetResponse();
632//                        Stream rs = response.GetResponseStream();
633//                        StreamReader sr = new StreamReader(rs);
634//                        codeBuilder.Append(sr.ReadToEnd());
635//                        rs.Close();
636//                    }
637//                }
638//            }
639
640//            // execute code for all script engines
641//            //foreach (string mimeType in codeByMimeType.Keys)
642//            foreach (KeyValuePair<string, StringBuilder> pair in codeByMimeType)
643//            {
644//                string mimeType = pair.Key;
645//                //codeBuilder = codeByMimeType[mimeType];
646//                codeBuilder = pair.Value;
647
648//                if (codeBuilder.Length > 0)
649//                {
650//                    ScriptEngine engine = GetScriptEngineByMimeType(mimeType);
651//                    engine.Execute(codeBuilder.ToString());
652//                }
653//            }
654
655//            // load the root element
656//            ((ISvgWindow)window).Document.RootElement.DispatchEvent(new Event("SVGLoad", false, true));
657//        }
658
659        #endregion
660    }
661}
662
Note: See TracBrowser for help on using the repository browser.