summaryrefslogtreecommitdiff
path: root/lib/Wayland/Display.lean
blob: d82a951c783e46768e86f7e4163a633c78b85365 (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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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, Hashable

/-- The numeric identifier of a request/event in an interface. -/
def OpCode : Type := UInt32
  deriving Repr, Nonempty, BEq, OfNat, DecidableEq

/-- A POSIX file descriptor. -/
def Fd : Type := Int32
  deriving Repr, Nonempty, BEq, DecidableEq

/-- Handle to a client object, possibly dead. -/
structure Object (ι : InterfaceName) : Type where
  private proxy : Native.Proxy
  private id : UInt64
  deriving Nonempty

/-- Opaque handle to an object whose type is not statically known. -/
structure AnyObject : Type where
  private proxy : Native.Proxy
  private type : String
  private id : UInt64
  deriving Nonempty

/-- Monad in which arguments can be marshalled one after another. -/
class ArgumentMarshaller (m : Type → Type) extends Monad m, MonadExcept String 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
  marshalAnyObject                  : Option AnyObject  → m Unit
  marshalArray                      : ByteArray         → m Unit
  marshalFd                         : Fd                → m Unit

/-- Monad in which arguments can be demarshalled one after another. -/
class ArgumentDemarshaller (m : Type → Type) extends Monad m, MonadExcept String m where
  demarshalInt                        : m Int32
  demarshalUInt                       : m UInt32
  demarshalFixed                      : m Float32
  demarshalString                     : m (Option String)
  demarshalObject {ι : InterfaceName} : m (Option (Object ι))
  demarshalAnyObject                  : m (Option AnyObject)
  demarshalArray                      : m ByteArray
  demarshalFd                         : m Fd

/-- Argument description in an interface's message. -/
inductive MarshalType where
  | int
  | uint
  | fixed
  | string
  | object
  | array
  | fd

/-- A type is `Marshallable` if it can be marshalled and demarshalled using a corresponding monad. -/
class Marshallable (α : Type) where
  marshal {m : Type → Type} [ArgumentMarshaller m] : MarshalType → α → m Unit
  demarshal {m : Type → Type} [ArgumentDemarshaller m] : MarshalType → m α

/-- 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 → (Option InterfaceName) → ArgumentDesc
  | newID : (Option 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) extends Interface ι 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 σ
deriving instance MonadExcept IO.Error 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 (ExceptT String 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)
  marshalAnyObject v := do (← read).writeObject (v.map AnyObject.proxy)
  marshalArray v := do (← read).writeArray v
  marshalFd v := do (← read).writeFd v

private instance : ArgumentDemarshaller (ExceptT String ArgumentBufferM) where
  demarshalInt := do (← read).readInt
  demarshalUInt := do (← read).readUInt
  demarshalFixed := do (← read).readFixed
  demarshalString := do (← read).readString
  demarshalObject := do
    let proxy ← (← read).readObject
    proxy.mapM fun proxy ↦ do
      return ⟨proxy, ← proxy.getID⟩
  demarshalAnyObject := do
    let proxy ← (← read).readObject
    proxy.mapM fun proxy ↦ do
      return ⟨proxy, ← proxy.getType, ← proxy.getID⟩
  demarshalArray := do (← read).readArray
  demarshalFd := do (← read).readFd

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

instance : Marshallable Int32 where
  marshal
  | .int => ArgumentMarshaller.marshalInt
  | _    => fun _ ↦ throw "Marshalling unexpected type, expected int."
  demarshal
  | .int => ArgumentDemarshaller.demarshalInt
  | _    => throw "Demarshalling unexpected type, expected int."

instance : Marshallable UInt32 where
  marshal
  | .uint => ArgumentMarshaller.marshalUInt
  | _     => fun _ ↦ throw "Marshalling unexpected type, expected uint."
  demarshal
  | .uint => ArgumentDemarshaller.demarshalUInt
  | _     => throw "Demarshalling unexpected type, expected uint."

instance : Marshallable Float32 where
  marshal
  | .fixed => ArgumentMarshaller.marshalFixed
  | _      => fun _ ↦ throw "Marshalling unexpected type, expected fixed."
  demarshal
  | .fixed => ArgumentDemarshaller.demarshalFixed
  | _      => throw "Demarshalling unexpected type, expected fixed."

instance : Marshallable (Option String) where
  marshal
  | .string => ArgumentMarshaller.marshalString
  | _       => fun _ ↦ throw "Marshalling unexpected type, expected string."
  demarshal
  | .string => ArgumentDemarshaller.demarshalString
  | _       => throw "Demarshalling unexpected type, expected string."

instance (ι : InterfaceName) : Marshallable (Option (Object ι)) where
  marshal
  | .object => ArgumentMarshaller.marshalObject
  | _       => fun _ ↦ throw "Marshalling unexpected type, expected object."
  demarshal
  | .object => ArgumentDemarshaller.demarshalObject
  | _       => throw "Demarshalling unexpected type, expected object."

instance : Marshallable (Option AnyObject) where
  marshal
  | .object => ArgumentMarshaller.marshalAnyObject
  | _       => fun _ ↦ throw "Marshalling unexpected type, expected object."
  demarshal
  | .object => ArgumentDemarshaller.demarshalAnyObject
  | _       => throw "Demarshalling unexpected type, expected object."

instance : Marshallable ByteArray where
  marshal
  | .array => ArgumentMarshaller.marshalArray
  | _      => fun _ ↦ throw "Marshalling unexpected type, expected array."
  demarshal
  | .array => ArgumentDemarshaller.demarshalArray
  | _      => throw "Demarshalling unexpected type, expected array."

instance : Marshallable Fd where
  marshal
  | .fd => ArgumentMarshaller.marshalFd
  | _   => fun _ ↦ throw "Marshalling unexpected type, expected fd."
  demarshal
  | .fd => ArgumentDemarshaller.demarshalFd
  | _   => throw "Demarshalling unexpected type, expected fd."

instance : Marshallable String where
  marshal a s := Marshallable.marshal a (Option.some s)
  demarshal a := do
    match ((← Marshallable.demarshal a) : Option String) with
    | .some s => pure s
    | .none   => throw "Received null for a non-nullable string."

instance (ι : InterfaceName) : Marshallable (Object ι) where
  marshal a o := Marshallable.marshal a (Option.some o)
  demarshal a := do
    match ((← Marshallable.demarshal a) : Option (Object ι)) with
    | .some o => pure o
    | .none   => throw "Received null for a non-nullable object."

instance : Marshallable AnyObject where
  marshal a o := Marshallable.marshal a (Option.some o)
  demarshal a := do
    match ((← Marshallable.demarshal a) : Option AnyObject) with
    | .some o => pure o
    | .none   => throw "Received null for a non-nullable object."

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 => iface
    | .newID iface => 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
  if not (← typeMap.isComplete ι) then
    for ⟨ι', iface'⟩ in iface.referencedInterfaces do
      typeMap.register
        { name := ι'
          version := iface'.version
          requests := iface'.requests.map MessageDesc.toNative
          events := iface'.events.map MessageDesc.toNative }
        (setComplete := if ι' == ι then 1 else 0)

def DisplayM.getDisplay' : DisplayM σ (Object "wl_display") := do
  let proxy ← Native.Proxy.fromDisplay (← read).disp
  return ⟨proxy, ← proxy.getID⟩

variable {ι ι' : InterfaceName}

instance : BEq (Object ι) where
  beq x y := x.id == y.id

instance : Hashable (Object ι) where
  hash x := x.id

instance : BEq AnyObject where
  beq x y := x.id == y.id

instance : Hashable AnyObject where
  hash x := x.id

private def marshalArguments (marshaller : ∀ {α} [ArgumentMarshaller α], α OpCode) : IO (Native.ArgumentBuffer × OpCode) := do
  let argBuffer ← Native.ArgumentBuffer.new
  let opcode : Except String OpCode ← ArgumentBufferM.run (ExceptT.run marshaller) argBuffer
  let opcode : OpCode ← IO.ofExcept opcode
  return (argBuffer, opcode)

/-- Send a request for an object to the server that doesn't construct any new object. -/
def Object.send (obj : Object ι) (marshaller : ∀ {α} [ArgumentMarshaller α], α OpCode) : DisplayM σ Unit := do
  let (argBuffer, opcode) ← marshalArguments marshaller
  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 [iface : ResolvedInterface ι'] (obj : Object ι) (marshaller : ∀ {α} [ArgumentMarshaller α], α OpCode) : DisplayM σ (Object ι') := do
  DisplayM.ensureInterface ι'
  let typeMap := (← read).typeMap
  let (argBuffer, opcode) ← marshalArguments marshaller
  let proxy ← obj.proxy.sendConstructor opcode argBuffer typeMap ι'
  return ⟨proxy, ← proxy.getID⟩

/-- Listen for events from the server for an object. -/
def Object.listen [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 : Except String iface.event ← ArgumentBufferM.run (ExceptT.run (iface.demarshalEvent opcode)) argBuffer
    let event : iface.event ← IO.ofExcept event
    ReaderT.run (handler event) global
  global.listen obj.proxy actualHandler

/-- Shorthand to ensure the reference count of an `Object` does not drop to `0`. -/
def Object.keep (obj : Object ι) : DisplayM σ Unit :=
  obj.proxy.keep

/-- Erase the type information from an object. -/
def Object.toAny (obj : Object ι) : AnyObject :=
  ⟨obj.proxy, ι, obj.id⟩

/-- Try to cast a type-erased object into a typed object. -/
def AnyObject.cast (obj : AnyObject) : Option (Object ι) :=
  if obj.type == ι then .some ⟨obj.proxy, obj.id⟩ else .none

end Proxies

end Wayland