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 /-- 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 deriving Nonempty /-- Opaque handle to an object whose type is not statically known. -/ structure AnyObject : Type where private proxy : Native.Proxy private type : String 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 σ 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 return proxy.map Object.mk demarshalAnyObject := do let proxy ← (← read).readObject proxy.mapM fun proxy ↦ do return ⟨proxy, ← proxy.getType⟩ 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⟩ variable {ι ι' : InterfaceName} 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⟩ /-- 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, ι⟩ /-- 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⟩ else .none end Proxies end Wayland