-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebview.ex
127 lines (97 loc) · 2.6 KB
/
webview.ex
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
defmodule WebView do
@moduledoc """
WebView API
"""
use GenServer
alias WebView.Native
alias WebView.Settings
@doc """
Returns a specification to start `WebView` under a supervisor.
See `Supervisor`.
"""
def child_spec(arg) do
spec = %{
id: __MODULE__,
start: {__MODULE__, :start, [arg]}
}
Supervisor.child_spec(spec, [])
end
@doc """
Starts the `WebView`. For a list of available options check the
`WebView.Settings` documentation.
"""
def start(opts \\ []) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@doc """
Sets the `WebView` title.
"""
def set_title(title, timeout \\ 1000) do
GenServer.call(__MODULE__, {:set_title, title}, timeout)
end
@doc """
Sets the `WebView` fullscreen on/off.
"""
def set_fullscreen(fullscreen \\ true, timeout \\ 1000) do
GenServer.call(__MODULE__, {:set_fullscreen, fullscreen}, timeout)
end
@doc """
Evaluates JavaScript code.
"""
def eval(js, timeout \\ 1000) do
GenServer.call(__MODULE__, {:eval, js}, timeout)
end
@doc """
Injects CSS.
"""
def inject_css(css, timeout \\ 1000) do
GenServer.call(__MODULE__, {:css, css}, timeout)
end
@doc """
Invoked when `WebView` is started. Initializes the actual `webview` and
then starts the loop.
"""
def init(opts \\ []) do
settings = struct!(Settings, opts)
send(self(), :create)
{:ok, %{settings: settings, created?: false, running?: false}}
end
@doc false
def handle_call({:set_title, title}, _, state) do
Native.set_title(title)
{:reply, :ok, state}
end
def handle_call({:set_fullscreen, fullscreen}, _, state) do
fullscreen = if fullscreen, do: 1, else: 0
Native.set_fullscreen(fullscreen)
{:reply, :ok, state}
end
def handle_call({:eval, js}, _, state) do
Native.eval(js)
{:reply, :ok, state}
end
def handle_call({:inject_css, css}, _, state) do
Native.inject_css(css)
{:reply, :ok, state}
end
@doc false
def handle_info(:loop, state) do
running? =
case Native.loop(0) do
:ok ->
send(self(), :loop)
true
:stop ->
false
end
{:noreply, %{state | running?: running?}}
end
def handle_info(:create, %{created?: true} = state), do: {:noreply, state}
def handle_info(:create, %{settings: %Settings{size: {w, h}} = s} = state) do
:ok = Native.create(s.title, s.url, w, h, bool_to_int(s.resizable), bool_to_int(s.debug))
Process.send_after(self(), :loop, 10)
{:noreply, state}
end
defp bool_to_int(true), do: 1
defp bool_to_int(false), do: 0
end