+
+updateStateC :: ConduitM FromServerMessage FromServerMessage (StateT SessionState (ReaderT SessionContext IO)) ()
+updateStateC = awaitForever $ \msg -> do
+ updateState msg
+ yield msg
+
+updateState :: (MonadIO m, HasReader SessionContext m, HasState SessionState m)
+ => FromServerMessage -> m ()
+updateState (NotPublishDiagnostics n) = do
+ let List diags = n ^. params . diagnostics
+ doc = n ^. params . uri
+ modify (\s ->
+ let newDiags = Map.insert (toNormalizedUri doc) diags (curDiagnostics s)
+ in s { curDiagnostics = newDiags })
+
+updateState (ReqApplyWorkspaceEdit r) = do
+
+ allChangeParams <- case r ^. params . edit . documentChanges of
+ Just (List cs) -> do
+ mapM_ (checkIfNeedsOpened . (^. textDocument . uri)) cs
+ return $ map getParams cs
+ Nothing -> case r ^. params . edit . changes of
+ Just cs -> do
+ mapM_ checkIfNeedsOpened (HashMap.keys cs)
+ return $ concatMap (uncurry getChangeParams) (HashMap.toList cs)
+ Nothing -> error "No changes!"
+
+ modifyM $ \s -> do
+ newVFS <- liftIO $ changeFromServerVFS (vfs s) r
+ return $ s { vfs = newVFS }
+
+ let groupedParams = groupBy (\a b -> a ^. textDocument == b ^. textDocument) allChangeParams
+ mergedParams = map mergeParams groupedParams
+
+ -- TODO: Don't do this when replaying a session
+ forM_ mergedParams (sendMessage . NotificationMessage "2.0" TextDocumentDidChange)
+
+ -- Update VFS to new document versions
+ let sortedVersions = map (sortBy (compare `on` (^. textDocument . version))) groupedParams
+ latestVersions = map ((^. textDocument) . last) sortedVersions
+ bumpedVersions = map (version . _Just +~ 1) latestVersions
+
+ forM_ bumpedVersions $ \(VersionedTextDocumentIdentifier uri v) ->
+ modify $ \s ->
+ let oldVFS = vfs s
+ update (VirtualFile oldV file_ver t) = VirtualFile (fromMaybe oldV v) (file_ver + 1) t
+ newVFS = updateVFS (Map.adjust update (toNormalizedUri uri)) oldVFS
+ in s { vfs = newVFS }
+
+ where checkIfNeedsOpened uri = do
+ oldVFS <- vfs <$> get
+ ctx <- ask
+
+ -- if its not open, open it
+ unless (toNormalizedUri uri `Map.member` vfsMap oldVFS) $ do
+ let fp = fromJust $ uriToFilePath uri
+ contents <- liftIO $ T.readFile fp
+ let item = TextDocumentItem (filePathToUri fp) "" 0 contents
+ msg = NotificationMessage "2.0" TextDocumentDidOpen (DidOpenTextDocumentParams item)
+ liftIO $ B.hPut (serverIn ctx) $ addHeader (encode msg)
+
+ modifyM $ \s -> do
+ let (newVFS,_) = openVFS (vfs s) msg
+ return $ s { vfs = newVFS }
+
+ getParams (TextDocumentEdit docId (List edits)) =
+ let changeEvents = map (\e -> TextDocumentContentChangeEvent (Just (e ^. range)) Nothing (e ^. newText)) edits
+ in DidChangeTextDocumentParams docId (List changeEvents)
+
+ textDocumentVersions uri = map (VersionedTextDocumentIdentifier uri . Just) [0..]
+
+ textDocumentEdits uri edits = map (\(v, e) -> TextDocumentEdit v (List [e])) $ zip (textDocumentVersions uri) edits
+
+ getChangeParams uri (List edits) = map getParams (textDocumentEdits uri (reverse edits))
+
+ mergeParams :: [DidChangeTextDocumentParams] -> DidChangeTextDocumentParams
+ mergeParams params = let events = concat (toList (map (toList . (^. contentChanges)) params))
+ in DidChangeTextDocumentParams (head params ^. textDocument) (List events)
+updateState _ = return ()
+
+sendMessage :: (MonadIO m, HasReader SessionContext m, ToJSON a) => a -> m ()
+sendMessage msg = do
+ h <- serverIn <$> ask
+ logMsg LogClient msg
+ liftIO $ B.hPut h (addHeader $ encode msg)
+
+-- | Execute a block f that will throw a 'Timeout' exception
+-- after duration seconds. This will override the global timeout
+-- for waiting for messages to arrive defined in 'SessionConfig'.
+withTimeout :: Int -> Session a -> Session a
+withTimeout duration f = do
+ chan <- asks messageChan
+ timeoutId <- curTimeoutId <$> get
+ modify $ \s -> s { overridingTimeout = True }
+ liftIO $ forkIO $ do
+ threadDelay (duration * 1000000)
+ writeChan chan (TimeoutMessage timeoutId)
+ res <- f
+ modify $ \s -> s { curTimeoutId = timeoutId + 1,
+ overridingTimeout = False
+ }
+ return res
+
+data LogMsgType = LogServer | LogClient
+ deriving Eq
+
+-- | Logs the message if the config specified it
+logMsg :: (ToJSON a, MonadIO m, HasReader SessionContext m)
+ => LogMsgType -> a -> m ()
+logMsg t msg = do
+ shouldLog <- asks $ logMessages . config
+ shouldColor <- asks $ logColor . config
+ liftIO $ when shouldLog $ do
+ when shouldColor $ setSGR [SetColor Foreground Dull color]
+ putStrLn $ arrow ++ showPretty msg
+ when shouldColor $ setSGR [Reset]
+
+ where arrow
+ | t == LogServer = "<-- "
+ | otherwise = "--> "
+ color
+ | t == LogServer = Magenta
+ | otherwise = Cyan
+
+ showPretty = B.unpack . encodePretty
+
+