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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
|
import Wayland.Native
import Wayland.Basic.PosixSignal
import Wayland.Basic.Duration
import Wayland.Basic.Lens
/-!
# The Display Monad
All event handlers and effectful code is run within the `DisplayM` monad, which encapsulates the connection to a
Wayland server. Its main purpose is managing its event loop -- processing timers, signal handlers, and Wayland events.
Furthermore, it manages a global state `σ` and allows focussing on a relevant part of that state using
lenses.
-/
variable {σ α : Type}
namespace Wayland
section Interfaces
/-- The name of an interface (e.g., `"wl_display"`), commonly used to resolve the corresponding interface description
using the `Interface` class. -/
def InterfaceName : Type := String
deriving Repr, Nonempty, BEq, ToString
/-- The numeric identifier of a request/event in an interface. -/
def OpCode : Type := UInt32
deriving Repr, Nonempty, BEq, OfNat
/-- Handle to a client object, possibly dead. -/
def Object (ι : InterfaceName) : Type := Native.Proxy
deriving Nonempty
/-- Monad in which arguments can be marshalled one after another. -/
class ArgumentMarshaller (m : Type → Type) extends Monad m where
marshalInt : Int32 → m Unit
marshalUInt : UInt32 → m Unit
marshalFixed : Float32 → m Unit
marshalString : Option String → m Unit
marshalObject {ι : InterfaceName} : Option (Object ι) → m Unit
marshalNewID {ι : InterfaceName} : Object ι → m Unit
marshalArray : ByteArray → m Unit
marshalFD : Int32 → m Unit
/-- Monad in which arguments can be demarshalled one after another. -/
class ArgumentDemarshaller (m : Type → Type) extends Monad m where
demarshalInt : m Int32
demarshalUInt : m UInt32
demarshalFixed : m Float32
demarshalString : m (Option String)
demarshalObject {ι : InterfaceName} : m (Option (Object ι))
demarshalNewID {ι : InterfaceName} : m (Object ι)
demarshalArray : m ByteArray
demarshalFD : m Int32
/-- Nullability annotation in an interface's message. -/
inductive Nullability where
| nullable
| notNull
/-- Argument description in an interface's message. -/
inductive ArgumentDesc where
| int : ArgumentDesc
| uint : ArgumentDesc
| fixed : ArgumentDesc
| string : Nullability → ArgumentDesc
| object : Nullability → InterfaceName → ArgumentDesc
| newID : InterfaceName → ArgumentDesc
| array : ArgumentDesc
| fd : ArgumentDesc
/-- Message description for an interface. -/
structure MessageDesc where
name : String
args : Array ArgumentDesc
since : UInt32
isDestructor : Bool
/-- Class for types describing the request messages of an interface. -/
class Request (α : Type) where
messages : Array MessageDesc
signature : α → MessageDesc
marshal {m : Type → Type} [ArgumentMarshaller m] : α → m OpCode
/-- Class for types describing the event messages of an interface. -/
class Event (α : Type) where
messages : Array MessageDesc
signature : α → MessageDesc
demarshal {m : Type → Type} [ArgumentDemarshaller m] : OpCode → m α
/-- Class describing an interface. This is not associated with a type, but rather with the interface's name. -/
class Interface (ι : InterfaceName) where
request : Type
[requestClass : Request request]
event : Type
[eventClass : Event event]
version : UInt32
/-- Interface where all dependency interfaces can be resolvew. -/
class ResolvedInterface (ι : InterfaceName) where
referencedInterfaces : Array ((ι' : InterfaceName) × Interface ι')
contains_self : ∃ α, ⟨ι, α⟩ ∈ referencedInterfaces := by exists inferInstance; simp
-- TODO: Verify that dependencies of interfaces are in referencedInterfaces
end Interfaces
section DisplayMonad
/-- A token managing a single source of events such as a timer or a signal handler. This can be used to unregister the
event. -/
def EventSource : Type := Native.EventSource
deriving Nonempty
/-- Internal handler interface passed as a message to the event loop. -/
private abbrev Handler (σ : Type) := StateT σ IO Unit
/-- Access to the display and event loop, providing the main functionality. -/
structure Display (σ : Type) where
private disp : Native.Display
private typeMap : Native.TypeMap
private addTimer : (delayMs : UInt32) → (msg : Handler σ) → IO EventSource
private addSignal : (signum : UInt32) → (msg : Handler σ) → IO EventSource
private remove : (source : EventSource) → IO Unit
private quit : IO Unit
/-- The display monad: A monad extending the `IO` monad with Wayland display related operations as well as state
management for a state type σ. -/
def DisplayM (σ : Type) : Type → Type :=
ReaderT (Display σ) (StateT σ IO)
deriving instance Monad for DisplayM σ
deriving instance MonadState σ for DisplayM σ
private instance : MonadLift (ReaderT (Display σ) (StateT σ IO)) (DisplayM σ) where
monadLift := id
/-- Connect to a Wayland server and start the application's main loop.
Parameters:
· `setUp`: Executed on startup before launching the event loop.
· `initialState`: The initial state value within the monad.
· `name`: Socket name for connecting to the Wayland server (by default, `wayland-0` is used). -/
partial def DisplayM.run' (setUp : DisplayM σ Unit) (initialState : σ) (name : Option String := .none) : IO σ := do
let disp ← Native.Display.new name
let typeMap ← Native.TypeMap.new
let loop ← Native.EventLoop.new
_ ← loop.addDisplay disp
let global : Display σ :=
{ disp := disp
typeMap := typeMap
addTimer := loop.addTimer
addSignal := loop.addSignal
remove := loop.remove
quit := loop.quit }
let rec inner : StateT σ IO Unit := do
match (← loop.poll) with
| .none => return
| .some msg => msg; inner
let main : StateT σ IO Unit := do
setUp.run global
inner
main.run initialState |>.map Prod.snd
/-- Connect to a Wayland server and start the application's main loop.
Parameters:
· `setUp`: Executed on startup before launching the event loop.
· `initialState`: The initial state value within the monad.
· `name`: Socket name for connecting to the Wayland server (by default, `wayland-0` is used). -/
def DisplayM.run (setUp : DisplayM σ Unit) (initialState : σ) (name : Option String := .none) : IO Unit :=
DisplayM.run' setUp initialState (name := name) |> discard
/-- Lift an `IO` operation into the Display monad.
Note that `DisplayM` does not provide an instance for `MonadLift IO` to make access to `IO` more explicit. This should
not be used often. -/
def DisplayM.liftIO (io : IO α) : DisplayM σ α :=
io
/-- Request the application to stop processing events and exit the event loop.
This can be sent at any time and stops the event loop before any further events can be processed. -/
def DisplayM.requestQuit : DisplayM σ Unit := do
(← read).quit
/-- Register a (POSIX) signal handler.
When the given `signal` is caught, the `handler` is executed as a part of the event loop. The returned event source can
be used to unregister the handler. -/
def DisplayM.registerSignal (signal : PosixSignal) (handler : DisplayM σ Unit) : DisplayM σ EventSource := do
let global ← read
global.addSignal signal.signum (ReaderT.run handler global)
/-- Register a (one-shot) timer.
After the given `timeout`, the `handler` is executed as a part of the event loop. The returned event source can be used
to cancel the timer. -/
def DisplayM.registerTimer (timeout : Duration) (handler : DisplayM σ Unit) : DisplayM σ EventSource := do
let global ← read
global.addTimer timeout.toMilliseconds (ReaderT.run handler global)
/-- Unregister a previously registered event source.
If the handler is currently active, it will run to completion, but the event is no longer processed as a part of the
event loop. -/
def DisplayM.unregister (source : EventSource) : DisplayM σ Unit := do
(← read).remove source
private def zoomState {σ₁ σ₂ : Type} {m : Type → Type} [Monad m] (lens : Lens σ₁ σ₂) (inner : StateT σ₂ m α) : StateT σ₁ m α := do
let oldOuter ← get
let (res, newInner) ← inner.run (lens.get oldOuter)
set (lens.set newInner oldOuter)
return res
/-- Zoom into a specific part of the state using a lens.
This is possible because handlers can only ever be submitted in the `DisplayM` monad, but never retrieved. -/
def DisplayM.zoom {σ₁ σ₂ : Type} (lens : Lens σ₁ σ₂) (inner : DisplayM σ₂ α) : DisplayM σ₁ α := do
let global₁ : Display σ₁ ← read
let global₂ : Display σ₂ :=
{ disp := global₁.disp
typeMap := global₁.typeMap
addTimer := fun x y ↦ global₁.addTimer x (zoomState lens y)
addSignal := fun x y ↦ global₁.addSignal x (zoomState lens y)
remove := global₁.remove
quit := global₁.quit }
zoomState lens (ReaderT.run inner global₂)
end DisplayMonad
section Proxies
private def MessageDesc.toNative (msg : MessageDesc) : Native.Message :=
let argString : ArgumentDesc → String
| .int => "i"
| .uint => "u"
| .fixed => "f"
| .string .nullable => "?s"
| .string .notNull => "s"
| .object .nullable _ => "?o"
| .object .notNull _ => "o"
| .newID _ => "n"
| .array => "a"
| .fd => "h"
let argType : ArgumentDesc → Option String
| .object _ iface => .some iface
| .newID iface => .some iface
| _ => .none
{ name := msg.name
signature := s!"{msg.since}{String.join (msg.args.toList.map argString)}"
types := msg.args.map argType }
/-- Ensure the given interface (and all of its dependencies) are registered in the display's `TypeMap`. -/
private def DisplayM.ensureInterface (ι : InterfaceName) [iface : ResolvedInterface ι] : DisplayM σ Unit := do
let typeMap := (← read).typeMap
for ⟨ι', iface'⟩ in iface.referencedInterfaces do
if !(← typeMap.contains ι') then
typeMap.register
{ name := ι'
version := iface'.version
requests := iface'.requestClass.messages.map MessageDesc.toNative
events := iface'.eventClass.messages.map MessageDesc.toNative }
-- def Object.send [iface : Interface ι] (obj : Object ι) (req : iface.request) : DisplayM σ Unit := sorry
-- def Object.listen [iface : Interface ι] (obj : Object ι) (handler : iface.event → DisplayM σ Unit) : DisplayM σ Unit := sorry
end Proxies
end Wayland
|