summaryrefslogtreecommitdiffstats
path: root/test3.hs
blob: 16bbe61fa13e843bcd0b74eb3c7cb6fccb74b89c (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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}


import Data.Default
import Graphics.Vty

--import Data.List

import Control.Applicative
--import Language.Haskell.TH.Ppr (bytesToString)
--import Data.Aeson
--import Data.List.Split
--import Data.Attoparsec.ByteString hiding (string)
import Data.Maybe
import Data.Monoid
--import Data.String
--import Data.Traversable
import Data.Tree
import qualified Data.Tree.Zipper as Z
--import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
--import qualified Data.ByteString.Char8 as BS8
--import qualified Data.Text.Lazy as TL
import qualified Data.Text as T
--import qualified Data.Text.Encoding as T
--import qualified Data.Text.IO as T
--import Data.Version (Version(..), parseVersion)
--import System.Process
--import System.IO
--import qualified Data.Map as M

import System.Environment
import Notmuch
import Notmuch.Message
import Notmuch.SearchResult
--import Safe

import Control.Exception

import TreeView

import TreeSearch
--import Editor (edit)
import System.Process
import System.Environment
import qualified Data.ByteString.Lazy as LBS
import System.IO
import System.Directory
import Control.Exception (bracket)
import Control.Exception
import System.IO
import Control.DeepSeq (rnf)


data State = State
    { vty :: Vty
    , cursor :: Z.TreePos Z.Full TreeView
    , xoffset :: Int
    , yoffset :: Int
    , message :: String
    }


toggleTag :: T.Text -> Message -> IO ()
toggleTag tag m = do
    _ <- if tag `elem` messageTags m
        then
            unsetTag tagString (unMessageID $ messageId m)
        else
            setTag tagString (unMessageID $ messageId m)
    return ()
  where
    tagString = T.unpack tag


tagMessage :: T.Text -> Message -> IO LBS.ByteString
tagMessage tag m =
  setTag (T.unpack tag) (unMessageID $ messageId m)


untagMessage :: T.Text -> Message -> IO LBS.ByteString
untagMessage tag m =
  unsetTag (T.unpack tag) (unMessageID $ messageId m)


main :: IO ()
main =
    main' "tag:inbox AND NOT tag:killed"

main' :: String -> IO ()
main' query = do
    setEnv "HOME" "/home/tv"
    bracket (mkVty def) finit run
  where

    finit vty = do
        shutdown vty

    run vty0 = do
        --XXX show a single thread
        --t_ <- getThread "0000000000000862"
        --let v = fromMessageTree t_
        --let c = findMessage (MessageID "87egtmvj0n.fsf@write-only.cryp.to") v
        --rec vty 0 c v

        r_ <- either error id <$> search query
        rec State
            { vty = vty0
            , cursor = Z.fromTree $ fromSearchResults query r_
            , xoffset = 0
            , yoffset = 0
            , message = "Welcome to much; quit with ^C"
            }

    rec :: State -> IO ()
    rec q0@State{..} = do
        let
            img =
                --string def (show i) <->
                --string def (maybe "Nothing" describe (focusPrev v cursor)) <->
                --string def (maybe "Nothing" describe cursor) <->
                --string def (maybe "Nothing" describe (focusNext v cursor)) <->
                --string def (maybe "Nothing" describe (focusPrev v cursor)) <->
                --string def (describe $ Z.label cursor) <->
                --string def (maybe "Nothing" describe (focusNext v cursor)) <->
                treeImage (Just $ Z.label cursor) (Z.toTree cursor)
                --renderTree q
            pic = picForImage $
                    (string def message) <->
                    translate xoffset yoffset img
            --v = Z.root cursor
        update vty pic
        nextEvent vty >>= \e -> case e of
            EvKey KEsc [] ->
                rec q

            EvKey (KChar 'c') [MCtrl] ->
                error "^C"

            EvKey (KChar 'k') [] ->
                rec q { cursor = fromMaybe (Z.root cursor) $ findPrev cursor }
            EvKey (KChar 'j') [] ->
                rec q { cursor = fromMaybe (Z.root cursor) $ findNext cursor }
            EvKey KEnter [] ->
                onEnter cursor

            EvKey (KChar 'H') [] -> rec q { xoffset = xoffset - 3 }
            EvKey (KChar 'L') [] -> rec q { xoffset = xoffset + 3 }
            EvKey (KChar 'J') [] -> rec q { yoffset = yoffset - 3 }
            EvKey (KChar 'K') [] -> rec q { yoffset = yoffset + 3 }

            EvKey (KChar 'r') [] ->
                case getMessage (Z.label cursor) of
                    Just m -> do
                        replyToAll m q >>= rec
                    Nothing ->
                        rec q { message = "no message" }
                --reply ToAll q >>= \case
                --    Left s -> rec q { message = s }
                --    Right () -> rec q

            EvResize _w _h ->
                rec q

            _ -> do
                rec q { message = "unbound key: " ++ show e }
      where

        q = q0 { message = "" }

        onEnter c_ = case Z.label c_ of
            TVMessage m -> do
                toggleTag "open" m

                let loc = cursor
                    Just sr = findParent isTVSearchResult loc
                    --Just sr0 = Z.firstChild sr -- TODO can there be only one (thread per sr)?
                    TVSearchResult the_sr = Z.label sr
                    ThreadID tid = searchThread the_sr

                t_ <- return . fromMessageForest =<< getThread tid

                let loc' = Z.modifyTree (\(Node l _) -> Node l t_) sr
                rec q { cursor = select (==Z.label cursor) loc' }

            TVSearchResult sr -> do
                --let Just loc = findTree (==c_) $ Z.fromTree v
                let loc = cursor

                let open = not $ null $ subForest $ Z.tree loc
                let ThreadID tid = searchThread sr

                t_ <-
                    if open
                        then return []
                        else return . fromMessageForest =<< getThread tid

                let loc' = Z.modifyTree (\(Node l _) -> Node l t_) loc
                rec q { cursor = select (==Z.label cursor) loc' }

            _ ->
                -- TODO make some noise
                rec q


select :: (a -> Bool) -> Z.TreePos Z.Full a -> Z.TreePos Z.Full a
select p loc = fromMaybe (error "cannot select") $ findTree p $ Z.root loc


treeImage :: Maybe TreeView -> Tree TreeView -> Image
treeImage c (Node n ns) =
    treeViewImage (c == Just n) n <->
    translateX 2 (vertCat $ map (treeImage c) ns)


--reply :: ReplyTo -> State -> IO (Either String ())
--reply replyTo _q@State{..} =
--    case getMessage (Z.label cursor) of
--        Just Message{..} -> do
--            x <- notmuchReply replyTo ("id:" <> unMessageID messageId)
--            edit x
--            return $ Right ()
--        Nothing ->
--            return $ Left "no message"

--edit :: LBS.ByteString -> IO ()
--edit draft = do
--    editor <- getEnv "EDITOR"
--    logname <- getEnv "LOGNAME"
--    tmpdir <- getTemporaryDirectory
--
--    let template = logname ++ "_much_draft_XXX.email"
--
--    bracket (openTempFile tmpdir template) cleanup $ \(path, h) -> do
--        LBS.hPut h draft
--        hClose h
--        --hFlush h
--        system (editor ++ " " ++ path)
--        return ()
--  where
--    cleanup (path, h) = do
--        removeFile path
--        hClose h

replyToAll Message{..} q = do
    editor <- getEnv "EDITOR"
    logname <- getEnv "LOGNAME"
    tmpdir <- getTemporaryDirectory

    let template = logname ++ "_much_draft_XXX.email"

    bracket (openTempFile tmpdir template) cleanup $ \(path, draftH) -> do
        (_, _, _, procH) <-
            withFile "/dev/null" ReadMode $ \devnull ->
                createProcess
                    (proc "notmuch" [ "reply" , "id:" <> unMessageID messageId ])
                        { std_in = UseHandle devnull
                        , std_out = UseHandle draftH
                        }
        hClose draftH
        waitForProcess procH
        code <- system (editor ++ " " ++ path)
        return q { message = show code }
  where
    cleanup = removeFile . fst


replyToAll2 = do
    editor <- getEnv "EDITOR"
    logname <- getEnv "LOGNAME"
    tmpdir <- getTemporaryDirectory

    let template = logname ++ "_much_draft_XXX.email"

    let msgId = "20141227121335.701B43F@mx2.informatik.uni-stuttgart.de"

    bracket (openTempFile tmpdir template) cleanup $ \(path, draftH) -> do
        (_, _, _, procH) <-
            withFile "/dev/null" ReadMode $ \devnull ->
                createProcess
                    (proc "notmuch" [ "reply" , "id:" <> msgId ])
                        { std_in = UseHandle devnull
                        , std_out = UseHandle draftH
                        }
        hClose draftH
        waitForProcess procH
        code <- system (editor ++ " " ++ path)
        print code
        --return q { message = show code }
  where
    cleanup = removeFile . fst



--    (_, Just hout, _, ph) <- createProcess (proc "notmuch" args)
--                                          { std_out = CreatePipe }
--    output <- LBS.hGetContents hout
--
--
--    withForkWait (evaluate $ rnf output) $ \waitOut -> do
--
--      ---- now write any input
--      --unless (null input) $
--      --  ignoreSigPipe $ hPutStr inh input
--      -- hClose performs implicit hFlush, and thus may trigger a SIGPIPE
--      --ignoreSigPipe $ hClose inh
--
--      -- wait on the output
--      waitOut
--      hClose hout
--
--    -- wait on the process
--    _ex <- waitForProcess ph
--    --return (ex, output)
--
--    --case ex of
--    --    ExitSuccess   -> return output
--    --    ExitFailure r -> processFailedException "readProcess" cmd args r
--
--    return output