Introduce a Spinner when no progress bar is displayed

Why?
====

With a spinner in place, there's visual indication that something's
happening.
This commit is contained in:
Joshua Clayton 2016-05-06 16:11:09 -04:00
parent 3a63276834
commit 0f4e056641
3 changed files with 51 additions and 2 deletions

View File

@ -3,7 +3,10 @@ module Unused.CLI.SearchWithoutProgress
) where
import Unused.TermSearch (search)
import Unused.CLI.Spinner (startSpinner, stopSpinner)
searchWithoutProgressBar :: [String] -> IO [String]
searchWithoutProgressBar terms =
concat <$> mapM search terms
searchWithoutProgressBar terms = do
putStr " "
sp <- startSpinner
concat <$> mapM search terms <* stopSpinner sp

45
src/Unused/CLI/Spinner.hs Normal file
View File

@ -0,0 +1,45 @@
module Unused.CLI.Spinner
( startSpinner
, stopSpinner
) where
import Control.Monad (forever)
import Control.Concurrent (ThreadId, killThread, threadDelay, forkIO)
import Unused.CLI.Util
data Spinner = Spinner
{ sSnapshots :: [String]
, sLength :: Int
, sDelay :: Int
, sColors :: [Color]
, sThreadId :: Maybe ThreadId
}
startSpinner :: IO Spinner
startSpinner = do
let s = buildSpinner
tid <- forkIO $ runSpinner 0 s
return $ s { sThreadId = Just tid }
stopSpinner :: Spinner -> IO ()
stopSpinner Spinner{ sThreadId = Nothing } = return ()
stopSpinner Spinner{ sThreadId = Just tid } = killThread tid
buildSpinner :: Spinner
buildSpinner =
Spinner snapshots (length snapshots) 100000 colors Nothing
where
snapshots = ["", "", "", "", "", "", "", ""]
colors = cycle [Black, Red, Yellow, Green, Blue, Cyan, Magenta]
runSpinner :: Int -> Spinner -> IO ()
runSpinner i s = forever $ do
setSGR [SetColor Foreground Dull currentColor]
putStr currentSnapshot
cursorBackward 1
threadDelay $ sDelay s
runSpinner (i + 1) s
where
currentSnapshot = sSnapshots s !! (i `mod` snapshotLength)
currentColor = sColors s !! (i `div` snapshotLength)
snapshotLength = sLength s

View File

@ -27,6 +27,7 @@ library
, Unused.CLI.SearchWithProgress
, Unused.CLI.SearchWithoutProgress
, Unused.CLI.Util
, Unused.CLI.Spinner
build-depends: base >= 4.7 && < 5
, process
, parsec