summaryrefslogtreecommitdiff
path: root/lib/Wayland/Display.lean
blob: f07c5ffb5e04dc7250401c67f1a4cead2ef8971c (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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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, DecidableEq

/-- Handle to a client object, possibly dead. -/
structure Object (ι : InterfaceName) : Type where
  private proxy : 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
  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 ι))
  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 describing an interface. This is not associated with a type, but rather with the interface's name. -/
class Interface (ι : InterfaceName) where
  event : Type
  requests : Array MessageDesc
  events : Array MessageDesc
  demarshalEvent {m : Type → Type} [ArgumentDemarshaller m] : OpCode → m 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 listen : (proxy : Native.Proxy) → (handler : UInt32 → Native.ArgumentBuffer → Handler σ) → IO Unit
  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
      listen proxy handler := proxy.listen (fun x y ↦ ⟨loop, handler x y⟩)
      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

/-- Flush any pending requests. -/
def DisplayM.flush : DisplayM σ Unit := do
  (← read).disp.flush

/-- 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 x y := global₁.addTimer x (zoomState lens y)
      addSignal x y := global₁.addSignal x (zoomState lens y)
      listen proxy handler := global₁.listen proxy (fun x y ↦ zoomState lens (handler x y))
      remove := global₁.remove
      quit := global₁.quit }
  zoomState lens (ReaderT.run inner global₂)

end DisplayMonad

section ArgumentMarshalling

/-- Implementation of the `ArgumentReader` and `ArgumentWriter` monads using `Native.ArgumentBuffer`. -/
private def ArgumentBufferM : Type → Type :=
  ReaderT Native.ArgumentBuffer IO

deriving instance Monad for ArgumentBufferM

private instance : MonadLift (ReaderT Native.ArgumentBuffer IO) ArgumentBufferM where
  monadLift := id

private instance : ArgumentMarshaller ArgumentBufferM where
  marshalInt v := do (← read).writeInt v
  marshalUInt v := do (← read).writeUInt v
  marshalFixed v := do (← read).writeFixed v
  marshalString v := do (← read).writeString v
  marshalObject v := do (← read).writeObject (v.map Object.proxy)
  marshalArray v := do (← read).writeArray v
  marshalFD v := do (← read).writeFD v

private instance : ArgumentDemarshaller ArgumentBufferM where
  demarshalInt := do (← read).readInt
  demarshalUInt := do (← read).readUInt
  demarshalFixed := do (← read).readFixed
  demarshalString := do (← read).readString
  demarshalObject := do let proxy ← (← read).readObject; return proxy.map Object.mk
  demarshalArray := do (← read).readArray
  demarshalFD := do (← read).readFD

private def ArgumentBufferM.run {α : Type} : ArgumentBufferM α → Native.ArgumentBuffer → IO α :=
  ReaderT.run

end ArgumentMarshalling

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'.requests.map MessageDesc.toNative
          events := iface'.events.map MessageDesc.toNative }

/-- Get the `wl_display` instance within the display monad. -/
def DisplayM.getDisplay : DisplayM σ (Object "wl_display") := do
  let proxy ← Native.Proxy.fromDisplay (← read).disp
  return ⟨proxy⟩

/-- Send a request for an object to the server that doesn't construct any new object. -/
def Object.send {ι : InterfaceName} (obj : Object ι) (marshaller : ∀ {α} [ArgumentMarshaller α], α OpCode) : DisplayM σ Unit := do
  let argBuffer ← Native.ArgumentBuffer.new
  let opcode ← ArgumentBufferM.run marshaller argBuffer
  obj.proxy.send opcode argBuffer

/-- Send a request for an object to the server, allocating a new id for a constructed object in the process. -/
def Object.sendConstructor {ι ι' : InterfaceName} [iface : ResolvedInterface ι'] (obj : Object ι) (marshaller : ∀ {α} [ArgumentMarshaller α], α OpCode) : DisplayM σ (Object ι') := do
  DisplayM.ensureInterface ι'
  let typeMap := (← read).typeMap
  let argBuffer ← Native.ArgumentBuffer.new
  let opcode ← ArgumentBufferM.run marshaller argBuffer
  let proxy ← obj.proxy.sendConstructor opcode argBuffer typeMap ι'
  return ⟨proxy⟩

/-- Listen for events from the server for an object. -/
def Object.listen {ι : InterfaceName} [iface : Interface ι] (obj : Object ι) (handler : iface.event → DisplayM σ Unit) : DisplayM σ Unit := do
  let global ← read
  let actualHandler (opcode : UInt32) (argBuffer : Native.ArgumentBuffer) : StateT σ IO Unit := do
    let event ← ArgumentBufferM.run (iface.demarshalEvent opcode) argBuffer
    ReaderT.run (handler event) global
  global.listen obj.proxy actualHandler

end Proxies

end Wayland