Xmonad Layout Follow up - haskell

This is a follow up to a question that I had before. I know about the DoRectFloat/RationalRect modules and such, but, I've tried to write proper Haskell and it either doesn't compile, or it compiles and doesn't do what I want.
(These are floating windows that I want) What I want is a layout like
How would I go about writing this?
My current Xmonad Config:
--my XMonad Config
--xterm, contrib, feh, and nitrogen are used here
import XMonad
import Data.Monoid
import XMonad.Util.Run
import XMonad.Layout.Gaps
import XMonad.Util.SpawnOnce
import XMonad.Layout.Spacing
import System.Exit
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.ManageHelpers
import XMonad.ManageHook
import qualified DBus as D
import qualified DBus.Client as D
import XMonad.Hooks.DynamicLog
import qualified Codec.Binary.UTF8.String as String
import XMonad.Util.EZConfig(additionalKeys)
import System.IO
import qualified XMonad.StackSet as W
import qualified Data.Map as M
import Graphics.X11.ExtraTypes.XF86
-- The preferred terminal program, which is used in a binding below and by
-- certain contrib modules.
--
myTerminal = "xterm"
-- Whether focus follows the mouse pointer.
myFocusFollowsMouse :: Bool
myFocusFollowsMouse = True
-- Whether clicking on a window to focus also passes the click to the window
myClickJustFocuses :: Bool
myClickJustFocuses = False
-- Width of the window border in pixels.
--
myBorderWidth = 2
-- modMask lets you specify which modkey you want to use. The default
-- is mod1Mask ("left alt"). You may also consider using mod3Mask
-- ("right alt"), which does not conflict with emacs keybindings. The
-- "windows key" is usually mod4Mask.
--
myModMask = mod1Mask
-- The default number of workspaces (virtual screens) and their names.
-- By default we use numeric strings, but any string may be used as a
-- workspace name. The number of workspaces is determined by the length
-- of this list.
--
-- A tagging example:
--
-- > workspaces = ["web", "irc", "code" ] ++ map show [4..9]
--
myWorkspaces = ["1","2","3","4","5","6","7","8","9"]
-- Border colors for unfocused and focused windows, respectively.
--
myNormalBorderColor = "#0a0b11"
myFocusedBorderColor = "#ace5e0"
--soda
------------------------------------------------------------------------
-- Key bindings. Add, modify or remove key bindings here.
--
myKeys conf#(XConfig {XMonad.modMask = modm}) = M.fromList $
-- launch a terminal
[ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf)
-- launch dmenu
, ((modm, xK_d ), spawn "dmenu_run")
--launch ff
, ((modm, xK_p ), spawn "brave")
--vol
, ((modm, xK_F8 ), spawn "pactl set-sink-mute #DEFAULT_SINK# toggle")
, ((modm, xK_i ), spawn "pactl set-sink-port 0 analog-output-speaker")
, ((modm, xK_o ), spawn "pactl set-sink-port 0 analog-output-headphones")
, ((modm, xK_F6 ), spawn "pactl set-sink-volume #DEFAULT_SINK# 50%")
, ((modm, xK_Up ), spawn "pactl set-sink-volume #DEFAULT_SINK# +3%")
, ((modm, xK_Down ), spawn "pactl set-sink-volume #DEFAULT_SINK# -3%")
--, ((0, xK_Right), spawn "xbacklight -dec 10")
--, ((0, xK_Left), spawn "xbacklight -inc 10")
--lol
, ((0, xF86XK_AudioRaiseVolume ), spawn "pactl set-sink-volume #DEFAULT_SINK# +5%")
, ((0, xF86XK_AudioLowerVolume ), spawn "pactl set-sink-volume #DEFAULT_SINK# -5%")
, ((0, xF86XK_AudioMute ), spawn "pactl set-sink-mute #DEFAULT_SINK# toggle")
-- launch gmrun
--, ((modm .|. shiftMask, xK_p ), spawn "gmrun")
, ((modm .|. shiftMask, xK_v ), spawn "virtualbox")
, ((modm .|. shiftMask, xK_b ), spawn "xrandr --output eDP-1 --brightness 0.5")
, ((modm .|. shiftMask, xK_z ), spawn "xrandr --output eDP-1 --brightness 1")
--master settings /gnome
, ((modm .|. shiftMask, xK_f ), spawn "gnome-control-center")
--eq
, ((modm .|. shiftMask, xK_u ), spawn "pulseeffects")
--lock (you need i3lock installed on your system)
, ((modm .|. shiftMask, xK_x ), spawn "i3lock -i ~/.config/i3/spart.png")
--fm
, ((modm .|. shiftMask, xK_g ), spawn "pcmanfm")
-- close focused window
, ((modm .|. shiftMask, xK_c ), kill)
-- Rotate through the available layout algorithms
, ((modm, xK_space ), sendMessage NextLayout)
-- Reset the layouts on the current workspace to default
, ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf)
-- Resize viewed windows to the correct size
, ((modm, xK_n ), refresh)
-- Move focus to the next window
, ((modm, xK_Tab ), windows W.focusDown)
-- Move focus to the next window
, ((modm, xK_j ), windows W.focusDown)
-- Move focus to the previous window
, ((modm, xK_k ), windows W.focusUp )
-- Move focus to the master window
, ((modm, xK_m ), windows W.focusMaster )
-- Swap the focused window and the master window
, ((modm, xK_Return), windows W.swapMaster)
-- Swap the focused window with the next window
, ((modm .|. shiftMask, xK_j ), windows W.swapDown )
-- Swap the focused window with the previous window
, ((modm .|. shiftMask, xK_k ), windows W.swapUp )
-- Shrink the master area
, ((modm, xK_h ), sendMessage Shrink)
-- Expand the master area
, ((modm, xK_l ), sendMessage Expand)
-- Push window back into tiling
, ((modm, xK_t ), withFocused $ windows . W.sink)
-- Increment the number of windows in the master area
, ((modm , xK_comma ), sendMessage (IncMasterN 1))
-- Deincrement the number of windows in the master area
, ((modm , xK_period), sendMessage (IncMasterN (-1)))
-- Toggle the status bar gap
-- Use this binding with avoidStruts from Hooks.ManageDocks.
-- See also the statusBar function from Hooks.DynamicLog.
--
-- , ((modm , xK_b ), sendMessage ToggleStruts)
-- Quit xmonad
, ((modm .|. shiftMask, xK_q ), io (exitWith ExitSuccess))
-- Restart xmonad
, ((modm , xK_q ), spawn "xmonad --recompile; xmonad --restart")
-- Run xmessage with a summary of the default keybindings (useful for beginners)
, ((modm .|. shiftMask, xK_slash ), spawn ("echo \"" ++ help ++ "\" | xmessage -file -"))
]
++
--
-- mod-[1..9], Switch to workspace N
-- mod-shift-[1..9], Move client to workspace N
--
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9]
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
--
-- mod-{w,e,r}, Switch to physical/Xinerama screens 1, 2, or 3
-- mod-shift-{w,e,r}, Move client to screen 1, 2, or 3
--
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
------------------------------------------------------------------------
-- Mouse bindings: default actions bound to mouse events
--
myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
-- mod-button1, Set the window to floating mode and move by dragging
[ ((modm, button1), (\w -> focus w >> mouseMoveWindow w
>> windows W.shiftMaster))
-- mod-button2, Raise the window to the top of the stack
, ((modm, button2), (\w -> focus w >> windows W.shiftMaster))
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modm, button3), (\w -> focus w >> mouseResizeWindow w
>> windows W.shiftMaster))
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
------------------------------------------------------------------------
-- Layouts:
-- You can specify and transform your layouts by modifying these values.
-- If you change layout bindings be sure to use 'mod-shift-space' after
-- restarting (with 'mod-q') to reset your layout state to the new
-- defaults, as xmonad preserves your old layout settings by default.
--
-- The available layouts. Note that each layout is separated by |||,
-- which denotes layout choice.
--
myLayout = tiled ||| Mirror tiled ||| theg ||| Full
where
tiled = spacing 35 $ Tall nmaster delta ratio
theg = gaps [(U,18), (R,23)] $ Tall 1 (3/100) (1/2)
nmaster = 1
ratio = 1/2
delta = 3/100
------------------------------------------------------------------------
-- Window rules:
-- Execute arbitrary actions and WindowSet manipulations when managing
-- a new window. You can use this to, for example, always float a
-- particular program, or have a client always appear on a particular
-- workspace.
--
-- To find the property name associated with a program, use
-- > xprop | grep WM_CLASS
-- and click on the client you're interested in.
--
-- To match on the WM_NAME, you can use 'title' in the same way that
-- 'className' and 'resource' are used below.
-- --> (doRectFloat $ W.RationalRect 0.5 0.5 0.9 0.9)
myManageHook = composeAll . concat $
[ [className =? "mpv" --> doFloat]
, [className =? "xterm" --> (doRectFloat $ W.RationalRect 0.5 0.5 0.4 0.4)]
--, [className =? c --> (doRectFloat $ W.RationalRect 0.5 0.5 0.9 0.9)| c <- mylol]
, [manageDocks]
]
where
myTop = ["xterm htop"]
myTerm = ["xterm"]
myVis = ["xterm vis"]
------------------------------------------------------------------------
-- Event handling
-- * EwmhDesktops users should change this to ewmhDesktopsEventHook
--
-- Defines a custom handler function for X Events. The function should
-- return (All True) if the default handler is to be run afterwards. To
-- combine event hooks use mappend or mconcat from Data.Monoid.
--
myEventHook = mempty
------------------------------------------------------------------------
-- Status bars and logging
-- Perform an arbitrary action on each internal state change or X event.
-- See the 'XMonad.Hooks.DynamicLog' extension for examples.
--
myLogHook = return ()
------------------------------------------------------------------------
-- Startup hook
-- Perform an arbitrary action each time xmonad starts or is restarted
-- with mod-q. Used by, e.g., XMonad.Layout.PerWorkspace to initialize
-- per-workspace layout choices.
--
-- By default, do nothing.
myStartupHook :: X ()
myStartupHook = do
spawn "nitrogen --restore &"
spawn "picom &"
spawn "xterm vis"
spawn "xsetroot -cursor_name left_ptr"
spawn "xset b off"
------------------------------------------------------------------------
-- Now run xmonad with all the defaults we set up.
-- Run xmonad with the settings you specify. No need to modify this.
--
main = do
xmproc <- spawnPipe "xmobar -x 0 ~/.xmonad/taskbarrc"
xmonad $ docks defaults
-- A structure containing your configuration settings, overriding
-- fields in the default config. Any you don't override, will
-- use the defaults defined in xmonad/XMonad/Config.hs
--
-- No need to modify this.
--
defaults = def {
-- simple stuff
terminal = myTerminal,
focusFollowsMouse = myFocusFollowsMouse,
clickJustFocuses = myClickJustFocuses,
borderWidth = myBorderWidth,
modMask = myModMask,
workspaces = myWorkspaces,
normalBorderColor = myNormalBorderColor,
focusedBorderColor = myFocusedBorderColor,
-- key bindings
keys = myKeys,
mouseBindings = myMouseBindings,
-- hooks, layouts
layoutHook = myLayout,
manageHook = myManageHook,
handleEventHook = myEventHook,
logHook = myLogHook,
startupHook = myStartupHook
}
-- | Finally, a copy of the default bindings in simple textual tabular format.
help :: String
help = unlines ["The default modifier key is 'alt'. Default keybindings:",
"",
"-- launching and killing programs",
"mod-Shift-Enter Launch xterminal",
"mod-p Launch dmenu",
"mod-Shift-p Launch gmrun",
"mod-Shift-c Close/kill the focused window",
"mod-Space Rotate through the available layout algorithms",
"mod-Shift-Space Reset the layouts on the current workSpace to default",
"mod-n Resize/refresh viewed windows to the correct size",
"",
"-- move focus up or down the window stack",
"mod-Tab Move focus to the next window",
"mod-Shift-Tab Move focus to the previous window",
"mod-j Move focus to the next window",
"mod-k Move focus to the previous window",
"mod-m Move focus to the master window",
"",
"-- modifying the window order",
"mod-Return Swap the focused window and the master window",
"mod-Shift-j Swap the focused window with the next window",
"mod-Shift-k Swap the focused window with the previous window",
"",
"-- resizing the master/slave ratio",
"mod-h Shrink the master area",
"mod-l Expand the master area",
"",
"-- floating layer support",
"mod-t Push window back into tiling; unfloat and re-tile it",
"",
"-- increase or decrease number of windows in the master area",
"mod-comma (mod-,) Increment the number of windows in the master area",
"mod-period (mod-.) Deincrement the number of windows in the master area",
"",
"-- quit, or restart",
"mod-Shift-q Quit xmonad",
"mod-q Restart xmonad",
"mod-[1..9] Switch to workSpace N",
"",
"-- Workspaces & screens",
"mod-Shift-[1..9] Move client to workspace N",
"mod-{w,e,r} Switch to physical/Xinerama screens 1, 2, or 3",
"mod-Shift-{w,e,r} Move client to screen 1, 2, or 3",
"",
"-- Mouse bindings: default actions bound to mouse events",
"mod-button1 Set the window to floating mode and move by dragging",
"mod-button2 Raise the window to the top of the stack",
"mod-button3 Set the window to floating mode and resize by dragging"]

When starting the three windows, use xterm's -class option to modify the WM_CLASS property it attaches to its window, choosing a different and unique class for each of the three. Then you can select for that class in your manage hook to only match the right window.

Related

Execute code beyond original screen view with Vim to R using GNU Screen

I'm using GNU Screen to send code from Vim to R with the following .vimrc configuration:
map <C-L> "kyy:echo system("screen -S $STY -p R -X stuff ".shellescape(#k))<CR>j
vmap <C-L> "xy:echo system("screen -S $STY -p R -X stuff ".shellescape(#x."\n"))<CR>j
(I use cntr-L to send code from Vim to my R window titled "R".)
I can run functions within the current screen,
exp_val <- function(roll){
vals <- numeric(length(roll))
vals[roll == "G"] <- 1/6
vals[roll == "Y"] <- 1/3
vals[roll == "R"] <- 1/2
sum(vals)
}
prob_choice <- function(roll, ng = 6, ny = 4, nr = 3){
tot <- ng + ny + nr
i <- c(ng,ny,nr)
col <- c("G","Y","R")
p1 <- i[col==roll[1]]/tot
i[col==roll[1]] <- i[col==roll[1]] - 1
p2 <- i[col==roll[2]]/(tot-1)
i[col==roll[2]] <- i[col==roll[2]] - 1
p3 <- i[col==roll[3]]/(tot-2)
p1*p2*p3
}
but when I try to scroll down and highlight another function that extends below the original screen view
single_round <- function(sampsp,probs=rep(1/nrow(sampsp),nrow(sampsp))){
r <- sample(1:nrow(sampsp),1,prob = probs)
dice <- sampsp[r,]
roll <- numeric(3)
i <- which(dice=="G"); roll[i] <- sample(c("B","S","F"),1,prob = c(1/2,1/6,1/3))
j <- which(dice=="Y"); roll[j] <- sample(c("B","S","F"),1,prob = c(1/3,1/3,1/3))
k <- which(dice=="R"); roll[k] <- sample(c("B","S","F"),1,prob = c(1/6,1/2,1/3))
num_dice <- c(length(i),length(j),length(k))
outcome <- c(sum(roll=="B"),sum(roll=="S"),sum(roll=="F"))
if (is.null(roll[i])){roll[i] <- 0}
if (is.null(roll[j])){roll[j] <- 0}
if (is.null(roll[k])){roll[k] <- 0}
feet <- c(sum(roll[i]=="F"),sum(roll[j]=="F"),sum(roll[k]=="F")) # to keep track of color of footprints
list(num_dice,outcome,feet)
}
I get the following error
X: stuff: one or two arguments required
Is there anything I can change in my .vimrc so I can highlight and execute a large part of the script that extends beyond the original screen view?

What would be a typical game skeleton in Haskell [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What would be the typical game skeleton for a Haskell game, let's say a simple shoot them up for instance?
I am particularly interested on the data structure, and how to manage the update of all the elements in the world, in regards of immutability issue.
Just saying that
new_world=update_world(world)
is a little bit simplistic. For instance, how to deal with multiple interaction that can occurs between element of the world (collisions, reaction to player, etc....) especially when you have a lot of 'independent' elements impacted.
The main concern is about immutability of the world, which makes very difficult to update a "small" part of the world based on another subset of the world.
I love gloss (gloss 2D library. it's very closed to your needs (I think)
A very simple example
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
-- Your app data
data App = App { mouseX :: Float
, mouseY :: Float
}
-- Draw world using your app data
-- Here thing about *draw* your world (e.g. if radius > MAX then red else blue)
drawWorld (App mousex mousey) = color white $ circle mousex
-- Handle input events and update your app data
-- Here thing about user interaction (e.g. when press button start jump!)
handleEvent
(EventMotion (x, y)) -- current viewport mouse coordinates
(App _ _) = App x y
handleEvent e w = w
-- Without input events you can update your world by time
-- Here thing about time (e.g. if jumping use `t` to compute new position)
handleTime t w = w
runApp =
play
( InWindow "Test" (300, 300) (0, 0) ) -- full screen or in window
black -- background color
20 -- frames per second
( App 0 0 ) -- your initial world
drawWorld -- how to draw the world?
handleEvent -- how app data is updated when IO events?
handleTime -- how app data is updated along the time?
-- enjoy!
main = runApp
One simple example modifying some data structure (a list of circle radius) along the three event handlers (draw, input and time)
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
import System.IO.Unsafe
data App = App { mouseX :: Float
, mouseY :: Float
, circleList :: [Float]
, lastTime :: Float
, currTime :: Float
}
drawWorld app =
color white $ pictures $ map circle $ circleList app
handleEvent
(EventMotion (x, y)) -- current viewport mouse coordinates
app = app { mouseX = x, mouseY = y,
-- drop circles with radius > mouse **MOVED** position
circleList = filter (<(abs x)) $ circleList app }
handleEvent e app = app
handleTime t app =
app { currTime = currTime', lastTime = lastTime', circleList = circleList' }
where currTime' = currTime app + t
-- create new circle each 1 second
createNew = currTime' - lastTime app > 1
lastTime' = if createNew then currTime' else lastTime app
-- each step, increase all circle radius
circleList' = (if createNew then [0] else []) ++ map (+0.5) (circleList app)
runApp =
play
( InWindow "Test" (300, 300) (0, 0) )
black
20
( App 0 0 [] 0 0 )
drawWorld
handleEvent
handleTime
main = runApp
with result

Icons for indicating layouts in XMobar (XMonad)

I know XMobar supports bitmap icons and I was able to configure those. However I also want to use icons for indicating current XMonad layout, but XMobar gets it on stdin from XMonad. And I couldn't figure out a way to pass bitmap icons instead of regular symbols.
So how one would pass icons instead of symbols for indicating XMonad layout in XMobar?
My current part of config relative to layouts:
defaultLayouts = smartBorders(avoidStruts(
renamed [Replace "R"] (ResizableTall 1 (3/100) (1/2) [])
||| renamed [Replace "R!"] (Mirror (ResizableTall 1 (3/100) (1/2) []))
||| renamed [Replace "F"] (noBorders Full)
||| renamed [Replace "#"] (Grid)
||| renamed [Replace "3C"] (ThreeColMid 1 (3/100) (3/4))
||| renamed [Replace "O"] (Circle)))
chatLayout = renamed [Replace "Chat"]
$ avoidStruts $ withIM (0.2) isPidgin
$ reflectHoriz $ withIM (0.2) isSkype (Grid)
where
isSkype = (Title "zoresvit - Skype™")
isPidgin = (Title "Buddy List")
fullLayout = renamed [Replace "F"] $ avoidStruts $ noBorders $ (Full)
myLayouts = onWorkspace "η" chatLayout $ defaultLayouts
main = do
xmproc <- spawnPipe "xmobar ~/.xmobarrc"
xmonad $ withUrgencyHook NoUrgencyHook $ defaultConfig {
borderWidth = myBorderWidth
, focusedBorderColor = myFocusedBorderColor
, handleEventHook = fullscreenEventHook
, layoutHook = myLayouts
, manageHook = manageHook defaultConfig
<+> composeAll myManagementHooks
<+> manageDocks
, modMask = myModMask
, normalBorderColor = myNormalBorderColor
, startupHook = do
spawn "~/.xmonad/startup_hook.sh"
, terminal = myTerminal
, workspaces = myWorkspaces
, logHook = dynamicLogWithPP $ xmobarPP {
ppOutput = hPutStrLn xmproc
, ppCurrent = xmobarColor solarizedGreen "" . wrap myCurrentWSLeft myCurrentWSRight
, ppHidden = xmobarColor solarizedBase0 ""
, ppHiddenNoWindows = xmobarColor solarizedBase02 ""
, ppLayout = xmobarColor solarizedCyan ""
, ppTitle = xmobarColor solarizedBase1 "" . shorten myTitleLength
, ppUrgent = xmobarColor solarizedRed "" . wrap myUrgentWSLeft myUrgentWSRight
, ppVisible = xmobarColor solarizedBase01 "" . wrap myVisibleWSLeft myVisibleWSRight
}
} `additionalKeys` myKeyBindings
As an alternate suggestion, you can change how XMonad displays the Layout titles. First, change the line
, ppLayout = xmobarColor solarizedCyan ""
to read
, ppLayout = xmobarColor solarizedCyan "" . myLayoutPrinter
Then, add the following function somewhere in your file:
myLayoutPrinter :: String -> String
myLayoutPrinter "Full" = "<icon=layout_full.xbm/>"
myLayoutPrinter "Tall" = "<icon=layout_tall.xbm/>"
myLayoutPrinter "Mirror Tall" = "<icon=layout_mirror_tall.xbm/>"
myLayoutPrinter x = x
Obviously, you'll need to customize the names of the layouts that you use, as well as the icon names.
In theory, you could even take it a step further, if you wanted to get really gaudy and give each layout its own colour. You'd actually simplify the ppLayout line down to
, ppLayout = myLayoutPrinter
The added the custom colours into myLayoutPrinter
myLayoutPrinter :: String -> String
myLayoutPrinter "Full" = xmobarColor "red" "" "<icon=layout_full.xbm/>"
myLayoutPrinter "Tall" = xmobarColor "green" "" "<icon=layout_tall.xbm/>"
myLayoutPrinter "Mirror Tall" = xmobarColor "blue" "" "<icon=layout_mirror_tall.xbm/>"
myLayoutPrinter x = xmobarColor "white" "" x
Just add this to your xmonad.hs:
import XMonad.Layout.Named
myLayout = named "<icon=/home/foo/bar/icon.xpm/>" $ ResizableTall 1 (3/100) (1/2) []

Why is X library reporting wrong string length values?

I was trying to get the width of the string, using XTextWidth() function, but for some reason the returned value is always bigger than the actual displayed length of string. In the following example, the value printed out is 196, while if I measure the width on-screen, it's somewhere around 168 pixels (the following is compilable and runnable example):
import Control.Concurrent
import qualified Graphics.X11.Xlib as X
import qualified Graphics.X11.Xlib.Types as Xt
import qualified Graphics.X11.Types as Xt
main = do
display <- X.openDisplay ""
let dflt = X.defaultScreen display
border = X.blackPixel display dflt
background = X.whitePixel display dflt
rootw <- X.rootWindow display dflt
win <- X.createSimpleWindow display rootw 0 0 500 300 1 border background
X.mapWindow display win
X.moveWindow display win 0 0
updateScreen display win
updateScreen display win = do
gc <- X.createGC display win
bgcolor <- initColor display "white"
fgcolor <- initColor display "black"
X.setBackground display gc bgcolor
X.setForeground display gc fgcolor
font <- X.loadQueryFont display "-misc-fixed-*-*-*-*-14-*-*-*-*-*-*"
let str = "Some reasonably long string."
len = X.textWidth font str
putStrLn $ show len
X.drawImageString display win gc 0 50 str
X.freeFont display font
X.freeGC display gc
threadDelay 100000
updateScreen display win
initColor :: X.Display -> String -> IO X.Pixel
initColor dpy color = do
let colormap = X.defaultColormap dpy (X.defaultScreen dpy)
(apros,_) <- X.allocNamedColor dpy colormap color
return $ X.color_pixel apros
How can I fix it?
You are not displaying with the selected font. Try this:
X.setFont display gc $ X.fontFromFontStruct font

gtk2hs: Request recalculation of windows size after removing a widget

I have a Window with three Entry widgets and one Button. I use the button to remove one of the widgets programmatically. The problem is that the main window doesn't change it's size to fit the new layout after it's been removed.
I can imagine that I need to send some Signal or Event to the main loop which would cause the recalculation but I've been unable to find such functionality.
Here is some example code:
import Graphics.UI.Gtk
import Data.IORef
import qualified Graphics.UI.Gtk as G hiding (Point)
import qualified Graphics.UI.Gtk.Gdk.EventM as E
import qualified Graphics.UI.Gtk.Abstract.Widget as W
import qualified Graphics.Rendering.Cairo as C
makeEntry :: String -> IO Entry
makeEntry str = do e <- entryNew
entrySetText e str
return e
main :: IO ()
main = do
initGUI
window <- windowNew
box <- vBoxNew False 0
G.on window G.keyPressEvent $ E.tryEvent $ do
"Escape" <- E.eventKeyName
C.liftIO $ G.widgetDestroy window
set window [ containerChild := box ]
e1 <- makeEntry "e1"
boxPackStart box e1 PackNatural 0
e2 <- makeEntry "e2"
boxPackStart box e2 PackNatural 0
e3 <- makeEntry "e3"
boxPackStart box e3 PackNatural 0
button <- buttonNew
set button [ buttonLabel := "Remove" ]
boxPackStart box button PackNatural 0
onClicked button (containerRemove box e2)
onDestroy window mainQuit
widgetShowAll window
mainGUI
You can ask your top-level window how big it wants to be, and make it be that big:
refresh window = do
Requisition w h <- widgetSizeRequest window
windowResize window w h
To use this, stick it in the button's click-handler:
onClicked button (containerRemove box e2 >> refresh window)

Resources