Search code examples
haskellgtkbase64gladegtk2hs

GUI for BASE64 Encoder in Haskell using Gtk2hs and Glade


I have got following problem. I try to create a simple GUI for BASE64 Encoder in Haskell using Gtk2Hs and Glade. This is example of BASE64 Encoder in Haskell.

{-# LANGUAGE OverloadedStrings #-}

import Data.ByteString.Base64
import Data.ByteString.Char8

main = do
    print $ unpack $ encode "Hello, world!"
    print $ decode "SGVsbG8sIHdvcmxkIQ=="

Now I want to create GUI for this example, but I would like to be able to enter any value to encode. I already created template with following components: - entry1 (to enter value to encode) - button (to start generating) - entry2 (to view generated value)

My haskell code:

entry1 <- builderGetObject hello castToEntry "entry1"
entry2 <- builderGetObject hello castToEntry "entry2"
button <- builderGetObject hello castToButton "button"
onClicked button $ do
    name2 <- get entry1 entryText
    set entry2 [ entryText := unpack $ encode name2]

I receive the following error when compiling

Couldn't match expected type `ByteString' with actual type `String'
In the first argument of `encode', namely `name2'
In the second argument of `($)', namely `encode name2'
In the second argument of `(:=)', namely `unpack $ encode name2'

Solution

  • name2 is of type String, whereas encode requires a ByteString. The simplest thing to do is just use the pack function from Data.ByteString.Char8 to make the conversion. However, there's a problem with this: it will only work properly for ASCII codepoints. What happens if the user enters non-ASCII characters (לדוגמה, כזה)?

    Instead, I'd recommend UTF8-encoding your text. To do that, I'd use the text package, which would look something like:

    import qualified Data.Text as T
    import qualified Data.Text.Encoding as TE
    
    encode $ TE.encodeUtf8 $ T.pack name2