We planned to upgrade GitLab and Mattermost to the latest version this Friday morning (early). You may experience some downtime!

App.icl 7.92 KB
Newer Older
Camil Staps's avatar
Camil Staps committed
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
implementation module Electron.App

import StdEnv
import StdMaybe

from Data.Func import hyperstrict, seqSt
import Data.Functor
import qualified Data.Map
from Data.Map import :: Map, instance Functor (Map k)
import Data.Map.GenJSON
import Data.Tuple
import System._Unsafe
import qualified Text
from Text import class Text, instance Text String

import graph_copy

import TCPIP

import ABC.Interpreter
import ABC.Interpreter.JavaScript

import iTasks
import iTasks.Internal.IWorld
import iTasks.Internal.Task

PORT :== 1234

29 30 31
derive JSONEncode TransportMethod
derive JSONDecode TransportMethod

Camil Staps's avatar
Camil Staps committed
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
derive JSONEncode Symbol, PrelinkedInterpretationEnvironment
JSONEncode{|{#Symbol}|} b xs = JSONEncode{|*|} b [x \\ x <-: xs]
JSONEncode{|{#Int}|}    b xs = JSONEncode{|*|} b [x \\ x <-: xs]

derive JSONDecode Symbol, PrelinkedInterpretationEnvironment
JSONDecode{|{#Symbol}|} b json = appFst (fmap toArray) (JSONDecode{|*|} b json)
JSONDecode{|{#Int}|}    b json = appFst (fmap toArray) (JSONDecode{|*|} b json)

toArray :: [a] -> {#a} | Array {#} a
toArray xs = {#x \\ x <- xs}

instance < ElectronProcess
where
	< a b = case a of
		MainProcess       -> b=:(RendererProcess _)
		RendererProcess a -> case b of
			MainProcess       -> False
			RendererProcess b -> a < b

JSONEncode{|Connection|} _ (Connection c) =
	[JSONArray [JSONString "_Connection", JSONString (copy_to_string c)]]
JSONDecode{|Connection|} _ json = case json of
	[JSONArray [JSONString "_Connection", JSONString s]:json] ->
		(Just (fst (copy_from_string {c \\ c <-: s})), json)
	_ ->
		(Nothing, json)

:: TCPLocal =
	{ processId :: !ElectronProcess
	, buffer    :: !String
	}

:: TCPMsg =
	{ type :: !String
	, val  :: !String
	}

:: TCPShare =
	{ rendererCounter :: !Int
	, tcpRx           :: !Map ElectronProcess [TCPMsg]
	, tcpTx           :: !Map ElectronProcess [TCPMsg]
	}

derive class iTask ElectronProcess, TCPLocal, TCPMsg, TCPShare

tcpShare :: SimpleSDSLens TCPShare
tcpShare = sharedStore "tcpShare"
	{ rendererCounter = 0
	, tcpRx           = 'Data.Map'.newMap
	, tcpTx           = 'Data.Map'.newMap
	}

tcpConnection :: !ElectronProcess -> SimpleSDSLens (Maybe Connection)
tcpConnection processId = mapReadWrite
	( 'Data.Map'.get processId
	, \mbConn map -> Just case mbConn of
		Nothing   -> 'Data.Map'.del processId map
		Just conn -> 'Data.Map'.put processId conn map
	)
	Nothing
	(sharedStore "tcpConnections" 'Data.Map'.newMap)

94 95 96 97 98 99 100 101
serveElectron ::
	!([String] EngineOptions -> EngineOptions)
	!(ElectronProcess UniversalConnectionDetails -> Task Connection)
	!*World -> *World
serveElectron modOpts startConnection w =
	doTasksWithOptions
		(\cli opts -> Ok (onStartup task,modOpts cli opts))
		w
Camil Staps's avatar
Camil Staps committed
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
where
	task :: Task ()
	task =
		getPIE >>- \pie ->
		(connect pie -&&- loop pie) @!
		()

	getPIE :: Task PrelinkedInterpretationEnvironment
	getPIE = mkInstantTask \_ iworld=:{IWorld | abcInterpreterEnv} -> (Ok abcInterpreterEnv,iworld)

	connect :: !PrelinkedInterpretationEnvironment -> Task ()
	connect pie = tcplisten PORT True tcpShare
		{ ConnectionHandlers
		| onConnect     = onConnect
		, onData        = onData
		, onShareChange = onShareChange
		, onDisconnect  = onDisconnect
		, onDestroy     = \local -> (Ok local, [])
		} @! ()
	where
		onConnect :: !ConnectionId !String !TCPShare -> (!MaybeErrorString TCPLocal, !Maybe TCPShare, ![String], !Bool)
		onConnect _ _ share=:{rendererCounter}
			# processId = if (rendererCounter==0) MainProcess (RendererProcess rendererCounter)
			# share & rendererCounter = rendererCounter+1
			= (Ok {processId=processId, buffer=""}, Just share, [], False)

		onData :: !String !TCPLocal !TCPShare -> (!MaybeErrorString TCPLocal, !Maybe TCPShare, ![String], !Bool)
		onData data local=:{processId,buffer} share=:{tcpRx}
			# buffer = buffer +++ data
			# lines = 'Text'.split "\n" buffer
			# local & buffer = last lines
			# lines = map (fromJSON o fromString) (init lines)
			| isEmpty lines
				= (Ok local, Nothing, [], False)
			| any isNothing lines
				# json = toString (toJSON {type="err", val="invalid json"}) +++ "\n"
				= (Ok local, Just share, [json], False)
			# share & tcpRx = foldr (\(Just msg) -> 'Data.Map'.alter (add msg) processId) tcpRx lines
			= (Ok local, Just share, [], False)
		where
			add :: !TCPMsg !(Maybe [TCPMsg]) -> Maybe [TCPMsg]
			add msg mbMsgs = case mbMsgs of
				Just msgs -> Just (msgs++[msg])
				Nothing   -> Just [msg]

		onShareChange :: !TCPLocal !TCPShare -> (!MaybeErrorString TCPLocal, !Maybe TCPShare, ![String], !Bool)
		onShareChange local=:{processId} share=:{tcpTx}
			# tx = fromMaybe [] ('Data.Map'.get processId tcpTx)
			| isEmpty tx
				= (Ok local, Nothing, [], False)
				# share & tcpTx = 'Data.Map'.put processId [] tcpTx
				= (Ok local, Just share, [toString (toJSON msg)+++"\n" \\ msg <- tx], False)

		onDisconnect :: !TCPLocal !TCPShare -> (!MaybeErrorString TCPLocal, !Maybe TCPShare)
		onDisconnect local=:{processId} share=:{tcpTx,tcpRx} =
			( Ok local
			, Just
				{ share
				& tcpRx = 'Data.Map'.del processId tcpRx
				, tcpTx = 'Data.Map'.del processId tcpTx
				}
			)

	loop :: !PrelinkedInterpretationEnvironment -> Task ()
	loop pie =
		watch tcpRx >>*
		[ OnValue (ifValue (any (not o isEmpty) o 'Data.Map'.elems) return)
		] >>- \rx ->
		set (const [] <$> rx) tcpRx >-| // TODO: atomic access; iTasks-SDK#370
		sequence [handle processId msg \\ (processId,msgs) <- 'Data.Map'.toList rx, msg <- msgs] >-|
		loop pie
	where
		tcpRx = mapReadWrite (\s -> s.tcpRx, \rx s -> Just {s & tcpRx=rx}) Nothing tcpShare

		handle :: !ElectronProcess !TCPMsg -> Task ()
		handle processId msg =
			get (tcpConnection processId) >>- \mbConnection ->
			catchAll
				(handle` mbConnection)
				(\s -> sendTCPMsg processId {type="err",val=s})
		where
			handle` mbConnection = case mbConnection of
				Nothing ->
					case msg.TCPMsg.type of
						"new" ->
							startConnection processId (connectionDetails processId) >>- \conn ->
							set (Just conn) (tcpConnection processId) @!
							()
						_ ->
							throw "invalid process id"
				Just (Connection c) ->
					case msg.TCPMsg.type of
						"msg"
							# (dyn,r) = jsDeserializeFromClient msg.val pie
							| r <> 0
								-> throw "failed to deserialize"
								-> case c.match dyn of
									Nothing -> throw "dynamic type mismatch"
									Just m  -> c.messageHandler m
						_ ->
							throw "invalid message type"

	connectionDetails :: !ElectronProcess -> UniversalConnectionDetails
	connectionDetails processId = ConnectionDetails
		{ serverWrite = \method val
			#! tuple = (0,dynamic val)
			#! (_,val) = if (method=:HyperstrictDynamic) (hyperstrict tuple) tuple
			-> sendSerializedTCPMsg processId "msg" val
		, clientWrite = \method val w
			#! tuple = (0,dynamic val)
			#! (_,val) = if (method=:HyperstrictDynamic) (hyperstrict tuple) tuple
			# (val,w) = jsSerializeOnClient val w
			# w = (jsGlobal "ABC" .# "component" .# "send" .$! ("msg", val)) w
			-> w
		, setClientMessageHandler = \handler w
			# (component,w) = jsGlobal "ABC" .# "component" .? w
			# fun = \{[1]=val} w -> case unsafeCoerce val of
				(val :: stoc^) -> handler val w
				_              -> jsTrace "dynamic type mismatch" w // TODO handle gracefully
			# (fun,w) = jsWrapFun fun component w
			# w = (component .# "message_handler" .= fun) w
			-> w
		}

runInElectron :: !ElectronProcess !(JSVal *JSWorld -> *JSWorld) -> Task ()
runInElectron processId f = sendSerializedTCPMsg processId "run" (wrapInitFunction f)

sendSerializedTCPMsg :: !ElectronProcess !String a -> Task ()
sendSerializedTCPMsg processId type val =
	serialize val >>= \serialized ->
	sendTCPMsg processId {type=type, val=serialized}

sendTCPMsg :: !ElectronProcess !TCPMsg -> Task ()
sendTCPMsg processId msg =
	upd (\share=:{tcpTx} -> {share & tcpTx='Data.Map'.alter (add msg) processId tcpTx}) tcpShare @!
	()
where
	add m Nothing  = Just [m]
	add m (Just q) = Just (q++[m])

serialize :: a -> Task String
serialize graph = mkInstantTask
	\id iworld=:{IWorld | abcInterpreterEnv}
		# serialized = jsSerializeGraph graph abcInterpreterEnv
		-> (Ok serialized, iworld)