mischief-live-0.1.0.0: src/Mischief/Live.hs
{-# LANGUAGE AllowAmbiguousTypes #-}
module Mischief.Live
( -- * Mischief Live
-- $intro
-- * Project Structure
-- $structure
-- * How to Run
-- $run
-- * How to Use
-- $how
-- * Extensions
-- $extensions
-- * Preparing for Release
-- $release
attachLive,
live,
LiveExtensions (..),
Extension,
OnLiveLoad,
liveIfChanged,
ghc2024Extensions,
)
where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Data.Data (Proxy (Proxy), TypeRep, Typeable, typeRep)
import Data.Foldable (for_)
import Data.Map (Map)
import Data.Map qualified as Map
import Language.Haskell.Interpreter
import Mischief.ECS
import Mischief.ECS.App (App (..))
import Mischief.ECS.Resources (modifyRes')
import Mischief.ECS.World (SystemAny (systemAny), World (..), runSystem)
import Mischief.Live.Interpreter
import System.Directory
import System.FSNotify
import Unsafe.Coerce
newtype LiveExtensions = LiveExtensions [Extension] deriving newtype (Semigroup)
instance Default LiveExtensions where
def =
ghc2024Extensions
<> LiveExtensions
[ DeriveAnyClass,
UnknownExtension "DerivingStrategies",
DuplicateRecordFields,
UnknownExtension "ImportQualifiedPost",
MultiWayIf,
UnknownExtension "NoFieldSelectors",
UnknownExtension "OverloadedRecordDot",
OverloadedStrings,
QuasiQuotes,
TypeFamilyDependencies
]
ghc2024Extensions :: LiveExtensions
ghc2024Extensions =
LiveExtensions
[ BangPatterns,
BinaryLiterals,
ConstrainedClassMethods,
ConstraintKinds,
DataKinds,
DeriveDataTypeable,
DeriveFoldable,
DeriveFunctor,
DeriveGeneric,
DeriveLift,
DeriveTraversable,
UnknownExtension "DerivingStrategies",
DisambiguateRecordFields,
DoAndIfThenElse,
EmptyCase,
EmptyDataDecls,
UnknownExtension "EmptyDataDeriving",
ExistentialQuantification,
ExplicitForAll,
ExplicitNamespaces,
UnknownExtension "FieldSelectors",
FlexibleContexts,
FlexibleInstances,
ForeignFunctionInterface,
GADTs,
GADTSyntax,
UnknownExtension "GeneralisedNewtypeDeriving",
UnknownExtension "HexFloatLiterals",
ImplicitPrelude,
UnknownExtension "ImportQualifiedPost",
InstanceSigs,
KindSignatures,
LambdaCase,
MonoLocalBinds,
MonomorphismRestriction,
MultiParamTypeClasses,
NamedFieldPuns,
NamedWildCards,
UnknownExtension "NumericUnderscores",
PatternGuards,
PolyKinds,
PostfixOperators,
RankNTypes,
RelaxedPolyRec,
RoleAnnotations,
ScopedTypeVariables,
StandaloneDeriving,
UnknownExtension "StandaloneKindSignatures",
UnknownExtension "StarIsType",
TraditionalRecordSyntax,
TupleSections,
TypeApplications,
TypeOperators,
TypeSynonymInstances
]
attachLive :: FilePath -> [FilePath] -> LiveExtensions -> App -> IO ()
attachLive path files (LiveExtensions ext) app = do
path <- makeAbsolute path
-- paths <- getFilesRecursively path
chanReq <- newBroadcastTChanIO
chanReqRead <- atomically $ dupTChan chanReq
runSystem (insertRes $ InterpreterChan chanReq) app.world
-- runSystem (insertRes $ LivePaths $ path :| paths) app.world
runSystem (insertRes $ LiveRegistry Map.empty) app.world
void $ forkIO $ withCurrentDirectory path $ interpreterInit files ext chanReqRead
void $ forkIO $ withManager $ watcher app.world path
watcher :: World -> FilePath -> WatchManager -> IO ()
watcher World {deferredAsync} dir mgr = do
void $ watchTree mgr dir (const True) $ const $ atomically $ do
modifyTVar' deferredAsync (++ [resetLiveCode])
forever $ threadDelay 10000000000000000
resetLiveCode :: System ()
resetLiveCode = do
Just (InterpreterChan chanReq) <- res
-- reset <- liftIO $ atomically $ do
-- p <- peekTChan chanReq
-- case p of
-- Reset -> pure False
-- _ -> True <$ writeTChan chanReq Reset
-- when reset $ do
liftIO $ atomically $ writeTChan chanReq Reset
insertRes $ LiveRegistry Map.empty
trigger OnLiveLoad
data LiveKey = LiveKey
{ moduleName :: String,
valName :: String,
valType :: TypeRep
}
deriving (Eq, Ord)
data LiveValue where
LiveValue :: (Typeable a) => a -> LiveValue
newtype LiveRegistry = LiveRegistry (Map LiveKey LiveValue) deriving anyclass (Component)
live :: forall a m w. (Typeable a, MonadSystem w m) => ModuleName -> String -> m (Maybe a)
live m f = do
Just (InterpreterChan chanReq) <- res
Just (LiveRegistry reg) <- res
let key = LiveKey {moduleName = m, valName = f, valType = typeRep $ Proxy @a}
case Map.lookup key reg of
Just (LiveValue val) -> pure $ Just $ unsafeCoerce val
Nothing -> do
a <- liftIO $ do
t <- newTMVarIO AwaitingResult
atomically $ writeTChan chanReq (Request m f t)
waitForResult t
for_ a $ \a -> do
let s = modifyRes' $ \(LiveRegistry m) -> LiveRegistry $ Map.insert key (LiveValue a) m
systemAny s (defer s)
pure a
liveIfChanged :: forall a m w. (Typeable a, MonadSystem w m) => ModuleName -> String -> m (Maybe a)
liveIfChanged m f = do
Just (InterpreterChan chanReq) <- res
Just (LiveRegistry reg) <- res
let key = LiveKey {moduleName = m, valName = f, valType = typeRep $ Proxy @a}
case Map.lookup key reg of
Just _ -> pure Nothing
Nothing -> do
a <- liftIO $ do
t <- newTMVarIO AwaitingResult
atomically $ writeTChan chanReq (Request m f t)
waitForResult t
for_ a $ \a -> do
let s = modifyRes' $ \(LiveRegistry m) -> LiveRegistry $ Map.insert key (LiveValue a) m
systemAny s (defer s)
pure a
waitForResult :: TMVar (Result a) -> IO (Maybe a)
waitForResult t = do
x <- atomically $ readTMVar t
case x of
Result a -> pure $ Just $ unsafeCoerce a
NoResult -> pure Nothing
AwaitingResult -> waitForResult t
data OnLiveLoad = OnLiveLoad deriving (Mischief.ECS.Event)
-- $intro
-- This library is a lightweight, yet powerful, addition to the core ECS library. It enables a form of live coding
-- by running a background interpreter over the code from a chosen target, letting you modify the functions from it
-- during the runtime of your main compiled library.
-- $structure
-- I will be describing the general recommended structure of a mischief app that uses this library. It is also recommended to
-- look at or clone one of the @-live@ branches in the [template repository](https://codeberg.org/mischief/template) for a more concrete example
-- or starting point.
--
-- In order to properly use this library, you will need at least one library besides your executable (the main \"library\" that you're running). You can define
-- it in your @.cabal@ file. In the template, this library is generally named @live@, with it's starting point in a @Live.hs@ module.
--
-- In this live library you can write any code that you wish to be able to freely change at runtime. Systems, shaders, and so on.
--
-- Your executable cannot depend on the live library, and the live library cannot depend on your executable. Because of this restriction, it is
-- recommended to create a third library, containing the /common/ logic and definitions that you wish both the executable and the live library to see.
-- You'll generally define types, such as components and materials in this common library.
-- $run
-- In order to run your executable, you should use the following command:
--
-- @
-- cabal run --write-ghc-environment-files=always --enable-shared --enable-executable-dynamic
-- @
--
-- The first flag will write an environment file which the interpreter can read to see all dependencies. The other two
-- ensure your local libraries are compiled dynamically so that the interpreter can access them. These are very important! GHC
-- is likely to be stuck in the linking phase if you depend on @mischief-live@ and don't compile your code dynamically!
--
-- On windows you may also need to add the @-fthreaded@ flag, as this library uses [fsnotify](https://hackage.haskell.org/package/fsnotify) for reacting to file changes.
-- $how
-- This library's API is really simple! It only has two functions you need to be aware of.
--
-- First, you need to use @attachLive@ to attach the interpreter to your app before running it:
--
-- @
-- app <- 'newApp'
-- 'attachLive' \".\/live\/" [\"Live.hs\"] 'def' app
-- @
--
-- The first parameter is the directory where your live library is located. The second is a list of
-- files to load when initializing the interpreter, relative to the previous path. There is also
-- a list of extensions you need to pass, but more on that later, @def@ is usually enough.
--
-- Second, there is the main primitive introduces by this library, @live@:
--
-- @
-- x <- 'live' \@'Int' \"Live\" \"myInt\"
-- @
--
-- The @live@ function takes a module name and a top-level function from that module, and produces its latest value. In this case,
-- the @Live@ module is expected to look something like this:
--
-- @
-- module Live where
--
-- myInt :: 'Int'
-- myInt = 3
-- @
--
-- The @\@Int@ type hint is optional, @live@ usually infers the value.
--
-- This function is smart. It caches the functions you've already requested, so it only interprets them the first time you ask for them, at the
-- start of the app or after you made a change to the live library.
--
-- There is also the @'liveIfChanged'@ function which will return a value only if this is the first time you're asking for it since the last change in the live library.
--
-- The @'OnLiveLoad'@ event is triggered each time a change in the live library is detected and the interpreter is reset.
-- $extenions
-- A list of language extensions that are applied when interpreting the live library need to be provided. The Default instance
-- adds all the extensions enabled by default by @ghc2024@, as well as the set of extensions recommended by Mischief. You can see
-- the exact list in the source of this file!
--
-- In order to customize the list of extensions, you can use the 'ghc2024Extensions' and the 'def' as a starting point, adding more extensions on top. For instance:
--
-- @
-- myExtensions :: 'LiveExtensions'
-- myExtensions = 'ghc2024Extensions' <> LiveExtensions ['UndecidableInstances']
-- @
--
-- You should set these to match the extensions listed under your live library in the @.cabal@ file.
-- $release
-- When releasing your app, you'll want to comment out the @mischief-live@ dependencies in your @.cabal@ file, and compile your
-- app normally, without the dynamic flags.
--
-- The simplest approach to ensure your app still works as expected with minimal refactoring is to have your executable depend on the
-- live library and import it, replacing all the @live@ calls with actual calls to the relevant functions.
--
-- Options are being considered for streamlining this process, such as a macro that can smartly switch between @live@ and the
-- direct calls. Your feedback and ideas are appreciated!