aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Modules/Tango.PPC.Browser/Helpers/BoundObjectsHelper.cs
blob: fe68ee8483f10c4600d328689150e5ad50c6db67 (plain)
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Tango.PPC.Browser.Attributes;
using CefSharp;
using CefSharp.Wpf;
using Tango.Core.Helpers;
using System.Windows.Threading;

namespace Tango.PPC.Browser.Helpers
{
    public static class BoundObjectsHelper
    {
        private static DispatcherTimer _timer;
        private static Dispatcher _dispatcher;
        private static ChromiumWebBrowser _browser;

        private static List<String> _scripts = new List<string>();

        public static void RegisterAllBoundObjects(ChromiumWebBrowser browser, Dispatcher dispatcher)
        {
            _dispatcher = dispatcher;
            _browser = browser;

            _timer = new DispatcherTimer(DispatcherPriority.Background, dispatcher);
            _timer.Tick += _timer_Tick;
            _timer.Interval = TimeSpan.FromSeconds(2);
            _timer.Stop();

            foreach (var type in typeof(BoundObjectsHelper).Assembly.GetTypes().Where(x => x.GetCustomAttribute<BoundObjectAttribute>() != null))
            {
                var att = type.GetCustomAttribute<BoundObjectAttribute>();

                var script = EmbeddedResourceHelper.GetEmbeddedResourceText($"Tango.PPC.Browser.Scripts.{att.ScriptFile}");
                _scripts.Add(script);

                browser.JavascriptObjectRepository.Register(att.Name, Activator.CreateInstance(type), true);

                browser.FrameLoadEnd += Browser_FrameLoadEnd;
            }
        }

        private static void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            _timer.Stop();
            _timer.Start();
        }

        private static void _timer_Tick(object sender, EventArgs e)
        {
            try
            {
                _timer.Stop();

                _dispatcher.BeginInvoke(new Action(() =>
                {
                    foreach (var script in _scripts)
                    {
                        _browser.GetMainFrame().ExecuteJavaScriptAsync(script);
                    }
                }));
            }
            catch
            {
                _timer.Start();
            }
        }
    }
}