aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Rivermonad/Client.hs
blob: 2d9e15f744b24ff4c5f03bf34bd88996ac0d88f9 (plain)
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
29
30
31
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
94
95
96
97
98
99
100
101
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
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}

-- | Client for rivermonad's IPC socket: newline-delimited JSON over a Unix
-- socket, one request per connection.
module Rivermonad.Client
    ( -- * Finding the window manager
      socketPath
    , available
    , selected
      -- * State
    , Snapshot(..)
    , Workspace(..)
    , Window(..)
    , Rect(..)
    , getSnapshot
      -- * Actions
    , viewWorkspace
    , focusWindow
    , shiftWindow
    , addWorkspace
    , removeWorkspace
    , renameWorkspace
    , setWorkspaces
    ) where

import Control.Exception (IOException, bracket, try)
import Data.Aeson ((.:), (.=))
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import System.Directory (doesPathExist)
import System.Environment (lookupEnv)
import System.FilePath ((</>))
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString.Lazy as LBS
import qualified Network.Socket as Socket
import qualified Network.Socket.ByteString as Socket


data Rect = Rect
    { rect_x :: Int
    , rect_y :: Int
    , rect_width :: Int
    , rect_height :: Int
    }
  deriving (Eq, Show)

data Window = Window
    { window_id :: Int
      -- ^ What 'focusWindow' and 'shiftWindow' take.  Only valid until the
      -- window manager restarts.
    , window_identifier :: Text
      -- ^ River's identifier of the window, stable across restarts.
    , window_title :: Text
    , window_app_id :: Text
    , window_rect :: Rect
    , window_focused :: Bool
      -- ^ The window its workspace focuses when shown.
    , window_floating :: Bool
    , window_fullscreen :: Bool
    }
  deriving (Eq, Show)

data Workspace = Workspace
    { workspace_name :: Text
    , workspace_focused :: Bool
    , workspace_visible :: Bool
    , workspace_layout :: Text
    , workspace_windows :: [Window]
    }
  deriving (Eq, Show)

data Snapshot = Snapshot
    { snapshot_screen :: Rect
      -- ^ The focused screen.
    , snapshot_workspaces :: [Workspace]
      -- ^ In the window manager's order.
    }
  deriving (Eq, Show)

parseRect :: Aeson.Object -> Aeson.Parser Rect
parseRect o =
    Rect <$> o .: "x" <*> o .: "y" <*> o .: "width" <*> o .: "height"

instance Aeson.FromJSON Rect where
    parseJSON = Aeson.withObject "Rect" parseRect

instance Aeson.FromJSON Window where
    parseJSON = Aeson.withObject "Window" $ \o ->
      Window
        <$> o .: "id"
        <*> o .: "identifier"
        <*> o .: "title"
        <*> o .: "app_id"
        <*> parseRect o
        <*> o .: "focused"
        <*> o .: "floating"
        <*> o .: "fullscreen"

instance Aeson.FromJSON Workspace where
    parseJSON = Aeson.withObject "Workspace" $ \o ->
      Workspace
        <$> o .: "name"
        <*> o .: "focused"
        <*> o .: "visible"
        <*> o .: "layout"
        <*> o .: "windows"

instance Aeson.FromJSON Snapshot where
    parseJSON = Aeson.withObject "Reply" $ \reply -> do
      o <- reply .: "Snapshot"
      Snapshot <$> o .: "screen" <*> o .: "workspaces"


-- | The socket of the rivermonad that manages this Wayland display.
-- @RIVERMONAD_SOCKET@ is only a fallback: in a session nested inside
-- another one it is inherited from the outer window manager.
socketPath :: IO FilePath
socketPath = do
    dir <- fromMaybe "/tmp" <$> lookupEnv "XDG_RUNTIME_DIR"
    display <- fromMaybe "wayland-0" <$> lookupEnv "WAYLAND_DISPLAY"
    let own = dir </> ("rivermonad-" <> map (\c -> if c == '/' then '_' else c) display <> ".sock")
    ownExists <- doesPathExist own
    lookupEnv "RIVERMONAD_SOCKET" >>= \case
      Just path | not ownExists, not (null path) -> return path
      _ -> return own

-- | Whether there is a rivermonad socket to talk to.
available :: IO Bool
available = socketPath >>= doesPathExist

-- | Whether to talk to rivermonad instead of an X11 window manager.
-- @DESKTOP_PAGER_BACKEND=x11@ or @=rivermonad@ decides.  Without it,
-- rivermonad is used when this is a Wayland session (@WAYLAND_DISPLAY@ is
-- set) and its socket exists.  A plain X11 session never picks rivermonad,
-- even if a river session of the same user runs next to it or has left a
-- socket file behind.
selected :: IO Bool
selected =
    lookupEnv "DESKTOP_PAGER_BACKEND" >>= \case
      Just "x11" -> return False
      Just "rivermonad" -> return True
      Just other -> fail $ "bad DESKTOP_PAGER_BACKEND: " <> show other
      Nothing ->
        lookupEnv "WAYLAND_DISPLAY" >>= \case
          Just display | not (null display) -> available
          _ -> return False


-- | Send one request and return the first line of the reply.
request :: Aeson.Value -> IO BS.ByteString
request value = do
    path <- socketPath
    r <- try $ bracket open Socket.close $ \s -> do
      Socket.connect s (Socket.SockAddrUnix path)
      Socket.sendAll s (LBS.toStrict (Aeson.encode value) <> "\n")
      readLine s mempty
    case r of
      Right line -> return line
      Left e -> fail $ "rivermonad: " <> path <> ": " <> show (e :: IOException)
  where
    open = Socket.socket Socket.AF_UNIX Socket.Stream Socket.defaultProtocol
    readLine s acc =
      case BS8.elemIndex '\n' acc of
        Just i -> return (BS.take i acc)
        Nothing -> do
          chunk <- Socket.recv s 65536
          if BS.null chunk then return acc else readLine s (acc <> chunk)

-- | Everything a pager shows.  Actions sent before are already applied.
getSnapshot :: IO Snapshot
getSnapshot = do
    line <- request (Aeson.String "Snapshot")
    case Aeson.eitherDecodeStrict' line of
      Right snapshot -> return snapshot
      Left e -> fail $ "rivermonad: bad snapshot: " <> e <> ": " <> BS8.unpack (BS.take 200 line)

action :: Aeson.Value -> IO ()
action a = do
    line <- request (Aeson.object [ "Action" .= a ])
    case Aeson.decodeStrict' line >>= Aeson.parseMaybe ok of
      Just _ ->
        return ()
      Nothing ->
        fail $ "rivermonad: request refused: " <> BS8.unpack line
  where
    ok :: Aeson.Value -> Aeson.Parser Aeson.Value
    ok = Aeson.withObject "Reply" (.: "Ok")

-- | Show a workspace on the focused screen.
viewWorkspace :: Text -> IO ()
viewWorkspace name = action $ Aeson.object [ "ViewWorkspace" .= name ]

-- | Focus a window, showing its workspace.
focusWindow :: Int -> IO ()
focusWindow window = action $ Aeson.object [ "FocusWindow" .= window ]

-- | Move a window to a workspace.
shiftWindow :: Int -> Text -> IO ()
shiftWindow window name =
    action $ Aeson.object [ "ShiftWindow" .= (Aeson.toJSON window, name) ]

addWorkspace :: Text -> IO ()
addWorkspace name = action $ Aeson.object [ "AddWorkspace" .= name ]

-- | Remove a workspace, if it has no windows.
removeWorkspace :: Text -> IO ()
removeWorkspace name = action $ Aeson.object [ "RemoveWorkspace" .= name ]

renameWorkspace :: Text -> Text -> IO ()
renameWorkspace old new = action $ Aeson.object [ "RenameWorkspace" .= (old, new) ]

-- | Make this the list of workspaces, in this order.  Names that are new
-- are created, names that are gone are removed if they have no windows, and
-- a name that is replaced by a new one in the same place is a rename.
setWorkspaces :: [Text] -> IO ()
setWorkspaces names = action $ Aeson.object [ "SetWorkspaces" .= names ]