{-# Language OverloadedStrings #-}
{-|
Module      : Client.View.KeyMap
Description : List of the current key map
Copyright   : (c) Eric Mertens, 2017
License     : ISC
Maintainer  : emertens@gmail.com

This module provides a view of the key bindings map

-}
module Client.View.KeyMap (keyMapLines) where

import           Client.Configuration
import           Client.EventLoop.Actions
import           Client.Image.PackedImage
import           Client.State
import           Control.Lens
import           Data.List
import           Data.Ord
import           Graphics.Vty.Attributes
import           Graphics.Vty.Input

-- | Show the client keybindings
keyMapLines ::
  ClientState {- ^ client state -} ->
  [Image']    {- ^ output lines -}
keyMapLines :: ClientState -> [Image']
keyMapLines ClientState
st
  = forall a. ClientState -> (a -> Text) -> [a] -> [a]
clientFilter ClientState
st Image' -> Text
imageText
  forall a b. (a -> b) -> a -> b
$ [([Modifier], Key, Action)] -> [Image']
renderEntries
  forall a b. (a -> b) -> a -> b
$ KeyMap -> [([Modifier], Key, Action)]
keyMapEntries
  forall a b. (a -> b) -> a -> b
$ forall s (m :: * -> *) a. MonadReader s m => Getting a s a -> m a
view (Lens' ClientState Configuration
clientConfig forall b c a. (b -> c) -> (a -> b) -> a -> c
. Lens' Configuration KeyMap
configKeyMap) ClientState
st

renderEntries :: [([Modifier], Key, Action)] -> [Image']
renderEntries :: [([Modifier], Key, Action)] -> [Image']
renderEntries [([Modifier], Key, Action)]
entries =
  [ Int -> Image' -> Image'
resizeImage Int
keyColWidth Image'
key forall a. Semigroup a => a -> a -> a
<> Image'
act | (Image'
key,Image'
act) <- [(Image', Image')]
images ]

  where
    third :: (a, b, c) -> c
third (a
_,b
_,c
x) = c
x

    images :: [(Image', Image')]
images =
      [ ( Attr -> String -> Image'
string Attr
defAttr ([Modifier] -> Key -> String
prettyModifierKey [Modifier]
mods Key
key)
        , Attr -> Text -> Image'
text'  Attr
defAttr (Action -> Text
actionName Action
act            )
        )
      | ([Modifier]
mods,Key
key,Action
act) <- forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (forall a b. Ord a => (b -> a) -> b -> b -> Ordering
comparing forall {a} {b} {c}. (a, b, c) -> c
third) [([Modifier], Key, Action)]
entries
      ]

    keyColWidth :: Int
keyColWidth = Int
1 forall a. Num a => a -> a -> a
+ forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum (Int
0 forall a. a -> [a] -> [a]
: forall a b. (a -> b) -> [a] -> [b]
map (Image' -> Int
imageWidth forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall a b. (a, b) -> a
fst) [(Image', Image')]
images)