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 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) /-- 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 /-- Shorthand to ensure the reference count of an `Object` does not drop to `0`. -/ def Object.keep {ι : InterfaceName} (obj : Object ι) : DisplayM σ Unit := obj.proxy.keep end Proxies end Wayland