summaryrefslogtreecommitdiffhomepage
path: root/src/Plugins/DateZone.hs
blob: 86114bb182eef20a71ea3d867b77bb9f797e7653 (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
{-# LANGUAGE DoAndIfThenElse #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Plugins.DateZone
-- Copyright   :  (c) Martin Perner
-- License     :  BSD-style (see LICENSE)
--
-- Maintainer  :  Martin Perner <martin@perner.cc>
-- Stability   :  unstable
-- Portability :  unportable
--
-- A date plugin with localization and location support for Xmobar
--
-- Based on Plugins.Date
--
-- Usage example: in template put
--
-- > Run DateZone "%a %H:%M:%S" "de_DE.UTF-8" "UTC" "utcDate" 10
--
-----------------------------------------------------------------------------

module Plugins.DateZone (DateZone(..)) where

import Plugins

import Localize

import Control.Concurrent.STM

import Data.Time.LocalTime
import Data.Time.Format
import Data.Time.LocalTime.TimeZone.Olson
import Data.Time.LocalTime.TimeZone.Series

import System.IO.Unsafe
import System.Locale (TimeLocale)
import System.Time



{-# NOINLINE localeLock #-}
-- ensures that only one plugin instance sets the locale
localeLock :: TMVar Bool
localeLock = unsafePerformIO (newTMVarIO False)

data DateZone = DateZone String String String String Int
    deriving (Read, Show)

instance Exec DateZone where
    alias (DateZone _ _ _ a _) = a
    start (DateZone f l z _ r) cb = do
      lock <- atomically $ takeTMVar localeLock
      setupTimeLocale l
      locale <- getTimeLocale
      atomically $ putTMVar localeLock lock
      if z /= "" then do
        timeZone <- getTimeZoneSeriesFromOlsonFile ("/usr/share/zoneinfo/" ++ z)
        go (dateZone f locale timeZone)
       else
        go (date f locale)

      where go func = func >>= cb >> tenthSeconds r >> go func

date :: String -> TimeLocale -> IO String
date format loc = do
  t <- toCalendarTime =<< getClockTime
  return $ formatCalendarTime loc format t

dateZone :: String -> TimeLocale -> TimeZoneSeries -> IO String
dateZone format loc timeZone = do
  zonedTime <- getZonedTime
  return $ formatTime loc format $ utcToLocalTime' timeZone $ zonedTimeToUTC zonedTime