Add offsetsGtk.hs
This commit is contained in:
parent
620dc5a47d
commit
4db33bda54
1 changed files with 61 additions and 0 deletions
61
offsetsGtk.hs
Normal file
61
offsetsGtk.hs
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
{-# LANGUAGE OverloadedLabels #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module Main where
|
||||
|
||||
import qualified GI.Gtk as Gtk
|
||||
import qualified GI.Gio as Gio
|
||||
import qualified Data.Text as T
|
||||
import Data.Text (Text)
|
||||
import Data.Maybe (fromMaybe)
|
||||
import Control.Monad (void)
|
||||
|
||||
-- | 'getWordAtOffset' takes a list of words and an offset (index)
|
||||
-- and returns the word at that offset if it exists.
|
||||
getWordAtOffset :: [Text] -> Int -> Maybe Text
|
||||
getWordAtOffset wordsList offset =
|
||||
if offset >= 0 && offset < length wordsList
|
||||
then Just (wordsList !! offset)
|
||||
else Nothing
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
-- Create a new GTK application with a unique application ID.
|
||||
app <- Gtk.applicationNew (Just "com.example.HaskellGiExample") []
|
||||
|
||||
-- Connect to the application's "activate" signal.
|
||||
void $ Gio.onApplicationActivate app $ do
|
||||
-- Create an application window (GTK 4 style).
|
||||
window <- Gtk.applicationWindowNew app
|
||||
|
||||
-- Create a text view widget.
|
||||
textView <- Gtk.textViewNew
|
||||
|
||||
-- Define some sample text.
|
||||
let sampleText = "Haskell GI makes GUI programming and text processing elegant"
|
||||
|
||||
-- Set the sample text in the text view's buffer.
|
||||
buffer <- Gtk.textViewGetBuffer textView
|
||||
Gtk.textBufferSetText buffer sampleText (-1)
|
||||
|
||||
-- Process the text: split into words and retrieve the word at a given offset.
|
||||
let wordsList = T.words sampleText
|
||||
offset = 3 -- For example, get the 4th word (zero-indexed)
|
||||
wordAtOffset = fromMaybe "No word found" (getWordAtOffset wordsList offset)
|
||||
|
||||
putStrLn $ "The word at offset " ++ show offset ++ " is: " ++ T.unpack wordAtOffset
|
||||
|
||||
-- Set the text view as the sole child of the window (wrap in Just).
|
||||
Gtk.windowSetChild window (Just textView)
|
||||
|
||||
-- Connect the window's close-request signal to quit the application.
|
||||
void $ Gtk.on window #closeRequest $ do
|
||||
Gio.applicationQuit app
|
||||
return False
|
||||
|
||||
-- Show the window.
|
||||
Gtk.widgetShow window
|
||||
|
||||
-- Run the application (which handles initialization and the main loop).
|
||||
_ <- Gio.applicationRun app Nothing
|
||||
return ()
|
||||
Loading…
Reference in a new issue