Debian Codegraph @

src/StatusNotifier/Tray.hs

raw
1 {-# LANGUAGE OverloadedStrings #-}
2 {-# LANGUAGE OverloadedLabels #-}
3 {-# LANGUAGE CPP #-}
4 module StatusNotifier.Tray where
5
6 import Control.Concurrent.MVar as MV
7 import Control.Exception.Base
8 import Control.Exception.Enclosed (catchAny)
9 import Control.Monad
10 import Control.Monad.Trans.Class
11 import Control.Monad.Trans.Maybe
12 import DBus.Client
13 import qualified DBus.Internal.Types as DBusTypes
14 import Data.Bool (bool)
15 import qualified Data.ByteString as BS
16 import Data.Coerce
17 import Data.Foldable (traverse_)
18 import Data.GI.Base.GError
19 import Data.Int
20 import Data.List
21 import qualified Data.Map.Strict as Map
22 import Data.Maybe
23 import Data.Ord
24 import Data.Ratio
25 import qualified Data.Text as T
26 import qualified GI.DbusmenuGtk3.Objects.Menu as DM
27 import qualified GI.GLib as GLib
28 import GI.GLib.Structs.Bytes
29 import qualified GI.Gdk as Gdk
30 import GI.Gdk.Enums
31 import GI.Gdk.Objects.Screen
32 import GI.Gdk.Structs.EventScroll
33 import GI.GdkPixbuf.Enums
34 import GI.GdkPixbuf.Objects.Pixbuf as Gdk
35 import qualified GI.Gtk as Gtk
36 import GI.Gtk.Flags
37 import GI.Gtk.Objects.IconTheme
38 import Graphics.UI.GIGtkStrut
39 import StatusNotifier.Host.Service
40 import qualified StatusNotifier.Item.Client as IC
41 import System.Directory
42 import System.FilePath
43 import System.Log.Logger
44 import Text.Printf
45
46 trayLogger :: Priority -> String -> IO ()
47 trayLogger = logM "StatusNotifier.Tray"
48
49 logItemInfo :: ItemInfo -> String -> IO ()
50 logItemInfo info message =
51 trayLogger INFO $ printf "%s - %s pixmap count: %s" message
52 (show $ info { iconPixmaps = []})
53 (show $ length $ iconPixmaps info)
54
55 getScaledWidthHeight :: Bool -> Int32 -> Int32 -> Int32 -> (Int32, Int32)
56 getScaledWidthHeight shouldTargetWidth targetSize width height =
57 let getRatio :: Int32 -> Rational
58 getRatio toScale =
59 fromIntegral targetSize / fromIntegral toScale
60 getOther :: Int32 -> Int32 -> Int32
61 getOther toScale other = floor $ getRatio toScale * fromIntegral other
62 in
63 if shouldTargetWidth
64 then (targetSize, getOther width height)
65 else (getOther height width, targetSize)
66
67 scalePixbufToSize :: Int32 -> Gtk.Orientation -> Pixbuf -> IO Pixbuf
68 scalePixbufToSize size orientation pixbuf = do
69 width <- pixbufGetWidth pixbuf
70 height <- pixbufGetHeight pixbuf
71 let warnAndReturnOrig =
72 trayLogger WARNING "Unable to scale pixbuf" >> return pixbuf
73 targetWidth = case orientation of
74 Gtk.OrientationHorizontal -> False
75 _ -> True
76 (scaledWidth, scaledHeight) =
77 getScaledWidthHeight targetWidth size width height
78 trayLogger DEBUG $
79 printf
80 "Scaling pb to %s, actualW: %s, actualH: %s, scaledW: %s, scaledH: %s"
81 (show size) (show width) (show height)
82 (show scaledWidth) (show scaledHeight)
83
84 trayLogger DEBUG $ printf "targetW: %s, targetH: %s"
85 (show scaledWidth) (show scaledHeight)
86 maybe warnAndReturnOrig return =<<
87 pixbufScaleSimple pixbuf scaledWidth scaledHeight InterpTypeBilinear
88
89 themeLoadFlags :: [IconLookupFlags]
90 themeLoadFlags = [IconLookupFlagsGenericFallback, IconLookupFlagsUseBuiltin]
91
92 getThemeWithDefaultFallbacks :: String -> IO IconTheme
93 getThemeWithDefaultFallbacks themePath = do
94 themeForIcon <- iconThemeNew
95 defaultTheme <- iconThemeGetDefault
96
97 _ <- runMaybeT $ do
98 screen <- MaybeT screenGetDefault
99 lift $ iconThemeSetScreen themeForIcon screen
100
101 filePaths <- iconThemeGetSearchPath defaultTheme
102 iconThemeAppendSearchPath themeForIcon themePath
103 mapM_ (iconThemeAppendSearchPath themeForIcon) filePaths
104
105 return themeForIcon
106
107 catchGErrorsAsLeft :: IO a -> IO (Either GError a)
108 catchGErrorsAsLeft action = catch (Right <$> action) (return . Left)
109
110 catchGErrorsAsNothing :: IO a -> IO (Maybe a)
111 catchGErrorsAsNothing action = catchGErrorsAsLeft action >>= rightToJustLogLeft
112 where rightToJustLogLeft (Right value) = return $ Just value
113 rightToJustLogLeft (Left error) = do
114 trayLogger WARNING $ printf "Encountered error: %s" $ show error
115 return Nothing
116
117 safePixbufNewFromFile :: FilePath -> IO (Maybe Gdk.Pixbuf)
118 safePixbufNewFromFile =
119 handleResult . catchGErrorsAsNothing . Gdk.pixbufNewFromFile
120 where
121 #if MIN_VERSION_gi_gdkpixbuf(2,0,26)
122 handleResult = fmap join
123 #else
124 handleResult = id
125 #endif
126
127 getIconPixbufByName :: Int32 -> T.Text -> Maybe String -> IO (Maybe Pixbuf)
128 getIconPixbufByName size name themePath = do
129 trayLogger DEBUG $ printf "Getting Pixbuf from name for %s" name
130 let nonEmptyThemePath = themePath >>= (\x -> if x == "" then Nothing else Just x)
131 themeForIcon <-
132 maybe iconThemeGetDefault getThemeWithDefaultFallbacks nonEmptyThemePath
133
134 let panelName = T.pack $ printf "%s-panel" name
135 hasPanelIcon <- iconThemeHasIcon themeForIcon panelName
136 hasIcon <- iconThemeHasIcon themeForIcon name
137
138 if hasIcon || hasPanelIcon
139
140 then do
141 let targetName = if hasPanelIcon then panelName else name
142 trayLogger DEBUG $ printf "Found icon %s in theme" name
143 catchAny (iconThemeLoadIcon themeForIcon targetName size themeLoadFlags)
144 (const $ pure Nothing)
145
146 else do
147 trayLogger DEBUG $ printf "Trying to load icon %s as filepath" name
148 -- Try to load the icon as a filepath
149 let nameString = T.unpack name
150 fileExists <- doesFileExist nameString
151 maybeFile <- if fileExists
152 then return $ Just nameString
153 else fmap join $ sequenceA $ getIconPathFromThemePath nameString <$> themePath
154 #if MIN_VERSION_gi_gdkpixbuf(2,0,26)
155 let handleResult = fmap join . sequenceA
156 #else
157 let handleResult = sequenceA
158 #endif
159 handleResult $ safePixbufNewFromFile <$> maybeFile
160
161 getIconPathFromThemePath :: String -> String -> IO (Maybe String)
162 getIconPathFromThemePath name themePath = if name == "" then return Nothing else do
163 trayLogger DEBUG $ printf
164 "Trying to load icon %s as filepath with theme path %s"
165 name themePath
166 pathExists <- doesDirectoryExist themePath
167 if pathExists
168 then do
169 fileNames <- catchAny (listDirectory themePath) (const $ return [])
170 trayLogger DEBUG $ printf
171 "Found files in theme path %s" (show fileNames)
172 return $ (themePath </>) <$> find (isPrefixOf name) fileNames
173 else return Nothing
174
175 getIconPixbufFromByteString :: Int32 -> Int32 -> BS.ByteString -> IO Pixbuf
176 getIconPixbufFromByteString width height byteString = do
177 trayLogger DEBUG "Getting Pixbuf from bytestring"
178 bytes <- bytesNew $ Just byteString
179 let bytesPerPixel = 4
180 rowStride = width * bytesPerPixel
181 sampleBits = 8
182 pixbufNewFromBytes bytes ColorspaceRgb True sampleBits width height rowStride
183
184 data ItemContext = ItemContext
185 { contextName :: DBusTypes.BusName
186 , contextMenu :: Maybe DM.Menu
187 , contextImage :: Gtk.Image
188 , contextButton :: Gtk.EventBox
189 }
190
191 data TrayImageSize = Expand | TrayImageSize Int32
192
193 data TrayClickAction = Activate | SecondaryActivate | PopupMenu
194
195 data TrayParams = TrayParams
196 { trayOrientation :: Gtk.Orientation
197 , trayImageSize :: TrayImageSize
198 , trayIconExpand :: Bool
199 , trayAlignment :: StrutAlignment
200 , trayOverlayScale :: Rational
201 , trayLeftClickAction :: TrayClickAction
202 , trayMiddleClickAction :: TrayClickAction
203 , trayRightClickAction :: TrayClickAction
204 }
205
206 defaultTrayParams = TrayParams
207 { trayOrientation = Gtk.OrientationHorizontal
208 , trayImageSize = Expand
209 , trayIconExpand = False
210 , trayAlignment = End
211 , trayOverlayScale = 3 % 5
212 , trayLeftClickAction = Activate
213 , trayMiddleClickAction = SecondaryActivate
214 , trayRightClickAction = PopupMenu
215 }
216
217 buildTray :: Host -> Client -> TrayParams -> IO Gtk.Box
218 buildTray Host
219 { itemInfoMap = getInfoMap
220 , addUpdateHandler = addUHandler
221 , removeUpdateHandler = removeUHandler
222 }
223 client
224 TrayParams { trayOrientation = orientation
225 , trayImageSize = imageSize
226 , trayIconExpand = shouldExpand
227 , trayAlignment = alignment
228 , trayOverlayScale = overlayScale
229 , trayLeftClickAction = leftClickAction
230 , trayMiddleClickAction = middleClickAction
231 , trayRightClickAction = rightClickAction
232 } = do
233 trayLogger INFO "Building tray"
234
235 trayBox <- Gtk.boxNew orientation 0
236 contextMap <- MV.newMVar Map.empty
237
238 let getContext name = Map.lookup name <$> MV.readMVar contextMap
239 showInfo info = show info { iconPixmaps = [] }
240
241 getSize rectangle =
242 case orientation of
243 Gtk.OrientationHorizontal ->
244 Gdk.getRectangleHeight rectangle
245 _ ->
246 Gdk.getRectangleWidth rectangle
247
248 getInfoAttr fn def name = maybe def fn . Map.lookup name <$> getInfoMap
249
250 getInfo :: ItemInfo -> DBusTypes.BusName -> IO ItemInfo
251 getInfo = getInfoAttr id
252
253 updateIconFromInfo info@ItemInfo { itemServiceName = name } =
254 getContext name >>= updateIcon
255 where updateIcon Nothing = updateHandler ItemAdded info
256 updateIcon (Just ItemContext { contextImage = image } ) = do
257 size <- case imageSize of
258 TrayImageSize size -> return size
259 Expand -> Gtk.widgetGetAllocation image >>= getSize
260 getScaledPixBufFromInfo size info >>=
261 let handlePixbuf mpbuf =
262 if isJust mpbuf
263 then Gtk.imageSetFromPixbuf image mpbuf
264 else trayLogger WARNING $
265 printf "Failed to get pixbuf for %s" $
266 showInfo info
267 in handlePixbuf
268
269 getTooltipText ItemInfo { itemToolTip = Just (_, _, titleText, fullText )}
270 | titleText == fullText = fullText
271 | titleText == "" = fullText
272 | fullText == "" = titleText
273 | otherwise = printf "%s: %s" titleText fullText
274 getTooltipText _ = ""
275
276 setTooltipText widget info =
277 Gtk.widgetSetTooltipText widget $ Just $ T.pack $ getTooltipText info
278
279 updateHandler ItemAdded
280 info@ItemInfo { menuPath = pathForMenu
281 , itemServiceName = serviceName
282 , itemServicePath = servicePath
283 } =
284 do
285 let serviceNameStr = coerce serviceName
286 servicePathStr = coerce servicePath :: String
287 serviceMenuPathStr = coerce <$> pathForMenu
288 logText = printf "Adding widget for %s - %s"
289 serviceNameStr servicePathStr
290
291 trayLogger INFO logText
292
293 button <- Gtk.eventBoxNew
294 Gtk.widgetAddEvents button [Gdk.EventMaskScrollMask]
295
296 image <-
297 case imageSize of
298 Expand -> do
299 image <- Gtk.imageNew
300 lastAllocation <- MV.newMVar Nothing
301
302 let setPixbuf allocation =
303 do
304 size <- getSize allocation
305
306 actualWidth <- Gdk.getRectangleWidth allocation
307 actualHeight <- Gdk.getRectangleHeight allocation
308
309 requestResize <- MV.modifyMVar lastAllocation $ \previous ->
310 let thisTime = Just (size, actualWidth, actualHeight)
311 in return (thisTime, thisTime /= previous)
312
313 trayLogger DEBUG $
314 printf
315 ("Allocating image size %s, width %s," <>
316 " height %s, resize %s")
317 (show size)
318 (show actualWidth)
319 (show actualHeight)
320 (show requestResize)
321
322 when requestResize $ do
323 trayLogger DEBUG "Requesting resize"
324 pixBuf <- getInfo info serviceName >>=
325 getScaledPixBufFromInfo size
326 when (isNothing pixBuf) $
327 trayLogger WARNING $
328 printf "Got null pixbuf for info %s" $
329 showInfo info
330 Gtk.imageSetFromPixbuf image pixBuf
331 void $ traverse
332 (\pb -> do
333 width <- pixbufGetWidth pb
334 height <- pixbufGetHeight pb
335 Gtk.widgetSetSizeRequest image width height)
336 pixBuf
337 void (Gdk.threadsAddIdle GLib.PRIORITY_DEFAULT $
338 Gtk.widgetQueueResize image >> return False)
339
340 _ <- Gtk.onWidgetSizeAllocate image setPixbuf
341 return image
342 TrayImageSize size -> do
343 pixBuf <- getScaledPixBufFromInfo size info
344 Gtk.imageNewFromPixbuf pixBuf
345
346 Gtk.widgetGetStyleContext image >>=
347 flip Gtk.styleContextAddClass "tray-icon-image"
348
349 Gtk.containerAdd button image
350 setTooltipText button info
351
352 maybeMenu <- sequenceA $ DM.menuNew (T.pack serviceNameStr) .
353 T.pack <$> serviceMenuPathStr
354
355 let context =
356 ItemContext { contextName = serviceName
357 , contextMenu = maybeMenu
358 , contextImage = image
359 , contextButton = button
360 }
361 popupItemForMenu menu =
362 Gtk.menuPopupAtWidget menu image
363 GravitySouthWest GravityNorthWest Nothing
364
365 _ <- Gtk.onWidgetButtonPressEvent button $ \event -> do
366 button <- Gdk.getEventButtonButton event
367 x <- round <$> Gdk.getEventButtonXRoot event
368 y <- round <$> Gdk.getEventButtonYRoot event
369 action <- case button of
370 1 -> bool leftClickAction PopupMenu <$> getInfoAttr
371 itemIsMenu True serviceName
372 2 -> return middleClickAction
373 _ -> return rightClickAction
374 case action of
375 Activate -> void $ IC.activate client serviceName servicePath x y
376 SecondaryActivate -> void $ IC.secondaryActivate client
377 serviceName servicePath x y
378 PopupMenu -> maybe (return ()) popupItemForMenu maybeMenu
379 return False
380 _ <- Gtk.onWidgetScrollEvent button $ \event -> do
381 direction <- getEventScrollDirection event
382 let direction' = case direction of
383 ScrollDirectionUp -> Just "vertical"
384 ScrollDirectionDown -> Just "vertical"
385 ScrollDirectionLeft -> Just "horizontal"
386 ScrollDirectionRight -> Just "horizontal"
387 _ -> Nothing
388 -- deltaX/deltaY are provided only in case of smooth scrolling which
389 -- is enabled via additional flag, we don't to enable/handle it
390 delta = case direction of
391 ScrollDirectionUp -> -1
392 ScrollDirectionDown -> 1
393 ScrollDirectionLeft -> -1
394 ScrollDirectionRight -> 1
395 _ -> 0
396 traverse_ (IC.scroll client serviceName servicePath delta) direction'
397 return False
398
399 MV.modifyMVar_ contextMap $ return . Map.insert serviceName context
400
401 Gtk.widgetShowAll button
402 let packFn =
403 case alignment of
404 End -> Gtk.boxPackEnd
405 _ -> Gtk.boxPackStart
406
407 packFn trayBox button shouldExpand True 0
408
409 updateHandler ItemRemoved ItemInfo { itemServiceName = name }
410 = getContext name >>= removeWidget
411 where removeWidget Nothing =
412 trayLogger WARNING "removeWidget: unrecognized service name."
413 removeWidget (Just ItemContext { contextButton = widgetToRemove }) =
414 do
415 Gtk.containerRemove trayBox widgetToRemove
416 MV.modifyMVar_ contextMap $ return . Map.delete name
417
418 updateHandler IconUpdated i = updateIconFromInfo i
419 updateHandler OverlayIconUpdated i = updateIconFromInfo i
420
421 updateHandler ToolTipUpdated info@ItemInfo { itemServiceName = name } =
422 void $ getContext name >>=
423 traverse (flip setTooltipText info . contextButton)
424
425 updateHandler _ _ = return ()
426
427 maybeAddOverlayToPixbuf size info pixbuf = do
428 runMaybeT $ do
429 let overlayHeight = floor (fromIntegral size * overlayScale)
430 overlayPixbuf <-
431 MaybeT $ getOverlayPixBufFromInfo overlayHeight info >>=
432 traverse (scalePixbufToSize overlayHeight Gtk.OrientationHorizontal)
433 lift $ do
434 actualOHeight <- getPixbufHeight overlayPixbuf
435 actualOWidth <- getPixbufWidth overlayPixbuf
436 mainHeight <- getPixbufHeight pixbuf
437 mainWidth <- getPixbufWidth pixbuf
438 pixbufComposite overlayPixbuf pixbuf
439 0 0 -- Top left corner
440 actualOWidth actualOHeight -- Overlay size
441 0 0 -- Offset
442 1.0 1.0 -- Scale
443 InterpTypeBilinear -- InterpType
444 255 -- Source image alpha
445 return pixbuf
446
447 getScaledPixBufFromInfo size info =
448 getPixBufFromInfo size info >>=
449 traverse (scalePixbufToSize size orientation >=>
450 maybeAddOverlayToPixbuf size info)
451
452 getPixBufFromInfo size
453 info@ItemInfo { iconName = name
454 , iconThemePath = mpath
455 , iconPixmaps = pixmaps
456 } = getPixBufFrom size name mpath pixmaps
457
458 getOverlayPixBufFromInfo size
459 info@ItemInfo
460 { overlayIconName = name
461 , iconThemePath = mpath
462 , overlayIconPixmaps = pixmaps
463 } = getPixBufFrom size (fromMaybe "" name)
464 mpath pixmaps
465
466 getPixBufFrom size name mpath pixmaps = do
467 let tooSmall (w, h, _) = w < size || h < size
468 largeEnough = filter (not . tooSmall) pixmaps
469 orderer (w1, h1, _) (w2, h2, _) =
470 case comparing id w1 w2 of
471 EQ -> comparing id h1 h2
472 a -> a
473 selectedPixmap =
474 if null largeEnough
475 then maximumBy orderer pixmaps
476 else minimumBy orderer largeEnough
477 getFromPixmaps (w, h, p) =
478 if BS.length p == 0
479 then Nothing
480 else Just $ getIconPixbufFromByteString w h p
481 if null pixmaps
482 then getIconPixbufByName size (T.pack name) mpath
483 else sequenceA $ getFromPixmaps selectedPixmap
484
485 uiUpdateHandler updateType info =
486 void $ Gdk.threadsAddIdle GLib.PRIORITY_DEFAULT $
487 updateHandler updateType info >> return False
488
489 handlerId <- addUHandler uiUpdateHandler
490 _ <- Gtk.onWidgetDestroy trayBox $ removeUHandler handlerId
491 return trayBox