https://wiki.haskell.org/index.php?title=Xmonad/Guided_tour_of_the_xmonad_source/Core.hs&feed=atom&action=historyXmonad/Guided tour of the xmonad source/Core.hs - Revision history2016-07-24T13:45:20ZRevision history for this page on the wikiMediaWiki 1.19.14+dfsg-1https://wiki.haskell.org/index.php?title=Xmonad/Guided_tour_of_the_xmonad_source/Core.hs&diff=45548&oldid=prevFlow: /* The X monad */2012-05-02T10:58:46Z<p><span dir="auto"><span class="autocomment">The X monad</span></span></p>
<table class='diff diff-contentalign-left'>
<tr valign='top'>
<td colspan='1' style="background-color: white; color:black;">← Older revision</td>
<td colspan='1' style="background-color: white; color:black;">Revision as of 10:58, 2 May 2012</td>
</tr></table>Flowhttps://wiki.haskell.org/index.php?title=Xmonad/Guided_tour_of_the_xmonad_source/Core.hs&diff=19667&oldid=prevByorgey: additional content2008-03-04T20:30:52Z<p>additional content</p>
<table class='diff diff-contentalign-left'>
<tr valign='top'>
<td colspan='1' style="background-color: white; color:black;">← Older revision</td>
<td colspan='1' style="background-color: white; color:black;">Revision as of 20:30, 4 March 2008</td>
</tr></table>Byorgeyhttps://wiki.haskell.org/index.php?title=Xmonad/Guided_tour_of_the_xmonad_source/Core.hs&diff=19664&oldid=prevByorgey: break up guided tour into subpages2008-03-04T20:14:50Z<p>break up guided tour into subpages</p>
<p><b>New page</b></p><div><br />
The next source file to examine is Core.hs. It defines several core data types and some of the core functionality of xmonad. If StackSet.hs is the heart of xmonad, Core.hs is its guts.<br />
<br />
=== <hask>XState</hask>, <hask>XConf</hask>, and <hask>XConfig</hask> ===<br />
<br />
These three record types make up the core of xmonad's state and configuration:<br />
<br />
* A value of type <hask>XState</hask> stores xmonad's mutable runtime state, consisting of the list of workspaces, a set of mapped windows, something to do with keeping track of pending UnmapEvents, and something to do with dragging. <br />
<haskell><br />
data XState = XState<br />
{ windowset :: !WindowSet -- ^ workspace list<br />
, mapped :: !(S.Set Window) -- ^ the Set of mapped windows<br />
, waitingUnmap :: !(M.Map Window Int) -- ^ the number of expected UnmapEvents<br />
, dragging :: !(Maybe (Position -> Position -> X (), X ())) }<br />
</haskell><br />
<br />
Note that the <hask>WindowSet</hask> type is just a <hask>StackSet</hask> with various concrete types substituted for its type parameters:<br />
<br />
<haskell><br />
type WindowSet = StackSet WorkspaceId (Layout Window) Window ScreenId ScreenDetail<br />
type WindowSpace = Workspace WorkspaceId (Layout Window) Window<br />
<br />
-- | Virtual workspace indicies<br />
type WorkspaceId = String<br />
<br />
-- | Physical screen indicies<br />
newtype ScreenId = S Int deriving (Eq,Ord,Show,Read,Enum,Num,Integral,Real)<br />
<br />
-- | The 'Rectangle' with screen dimensions and the list of gaps<br />
data ScreenDetail = SD { screenRect :: !Rectangle<br />
, statusGap :: !(Int,Int,Int,Int) -- ^ width of status bar on the screen<br />
} deriving (Eq,Show, Read)<br />
</haskell><br />
<br />
The type of workspace tags, <hask>WorkspaceId</hask>, is just <hask>String</hask>; a <hask>ScreenDetail</hask> stores information about the screen dimension as well as any gaps which should be left at the edges of the screen for status bars and other such things. Now, you may wonder why we have<br />
<br />
<haskell><br />
newtype ScreenId = S Int deriving (...)<br />
</haskell><br />
<br />
rather than just <hask>type ScreenId = Int</hask>? The reason is that if <hask>type ScreenId = Int</hask>, it would be possible to accidentally do arithmetic with <hask>ScreenId</hask>s mixed with other <hask>Int</hask> values, which clearly doesn't make sense. Making <hask>ScreenId</hask> a separate type means that the type system will enforce non-mixing of <hask>ScreenId</hask>s with other types, while using <hask>newtype</hask> with automatic instance deriving means none of the convenience is lost -- we can write code ''just as if'' <hask>ScreenId</hask>s are normal <hask>Int</hask> values, but be sure that we can't accidentally get mixed up and do something silly like add a <hask>ScreenId</hask> to the width of a window. This is the power of a rich static type system like Haskell's -- we can encode certain invariants and constraints in the type system, and have them automatically checked at compile time.<br />
<br />
* An <hask>XConf</hask> record stores xmonad's (immutable) configuration data, such as window border colors, the keymap, information about the X11 display and root window, and other user-specified configuration information. The reason this record is separated from <hask>XState</hask> is that, as we'll see later, xmonad's code provides a static guarantee that the data stored in this record is truly read-only, and cannot be changed while xmonad is running.<br />
<br />
* <hask>XConfig</hask> provides a way for the user to customize xmonad's configuration, by defining an <hask>XConfig</hask> record in their <hask>xmonad.hs</hask> file. You're probably already familiar with this record type.<br />
<br />
=== The <hask>X</hask> monad ===<br />
<br />
And now, what you've all been waiting for: the X monad!<br />
<br />
<haskell><br />
newtype X a = X (ReaderT XConf (StateT XState IO) a)<br />
deriving (Functor, Monad, MonadIO, MonadState XState, MonadReader XConf)<br />
</haskell><br />
<br />
The X monad represents a common pattern for building custom monad instances: using ''monad transformers'', one can simply 'layer' the capabilities and effects of several monads into one, and then use GHC's newtype deriving capabilities to automatically derive instances of the relevant type classes. In this case, the base monad out of which the X monad is built is IO; this is necessary since communicating with the X server involves IO operations. On top of that is <hask>StateT XState</hask>, which automatically threads a mutable <hask>XState</hask> record through computations in the X monad; finally there is a <hask>ReaderT XConf</hask> which also threads a read-only <hask>XConf</hask> record through. As noted in the comments in the source, the <hask>XState</hask> record can be accessed with any functions in the [http://haskell.org/ghc/docs/latest/html/libraries/mtl/Control-Monad-State-Class.html#t%3AMonadState <hask>MonadState</hask>] type class, such as <hask>get</hask>, <hask>put</hask>, <hask>gets</hask>, and <hask>modify</hask>; the <hask>XConf</hask> record can be accessed with [http://haskell.org/ghc/docs/latest/html/libraries/mtl/Control-Monad-Reader-Class.html#t%3AMonadReader <hask>MonadReader</hask>] functions, such as <hask>ask</hask>.<br />
<br />
For more information on monad transformers in general, I recommend reading Martin Grabmüller's excellent tutorial paper, [http://uebb.cs.tu-berlin.de/~magr/pub/Transformers.en.html Monad Transformers Step-by-Step]; for more information on this particular style of composing monad transformers and using automatic newtype deriving, read Cale Gibbard's tutorial, [http://cale.yi.org/index.php/How_To_Use_Monad_Transformers How To Use Monad Transformers].<br />
<br />
Along with the X monad, several utility functions are provided, such as <hask>runX</hask>, which turns an action in the X monad into an IO action, and <hask>catchX</hask>, which provides error handling for X actions. There are also several higher-order functions provided for convenience, including <hask>withDisplay</hask> (apply a function producing an X action to the current display) and <hask>withWindowSet</hask> (apply a function to the current window set).<br />
<br />
=== <hask>ManageHook</hask> ===<br />
<br />
This is a bit more advanced, and not really a central part of the system, so I'm skipping it for now, hopefully coming back to add more later. <br />
<br />
=== <hask>LayoutClass</hask> ===<br />
<br />
Next, let's take a look at the <hask>LayoutClass</hask>. This is one of the places that Haskell's type classes really shine. <hask>LayoutClass</hask> is a type class of which every layout must be an instance. It defines the basic functions which define what a layout is and how it behaves. The comments in the source code explain very clearly what each of these functions is supposed to do, but here are some highlights:<br />
<br />
* Note that all the <hask>LayoutClass</hask> functions provide default implementations, so that <hask>LayoutClass</hask> instances do not have to provide implementations of those functions where the default behavior is desired. For example, by default, <hask>doLayout</hask> simply calls <hask>pureLayout</hask>, so a layout that does not require access to the X monad need only implement the <hask>pureLayout</hask> function. (For example, the Accordion, Square, and Grid layouts from the contrib library all use this approach.)<br />
<br />
* Layouts can have their own private state, by storing this state in the <hask>LayoutClass</hask> instance and returning a modified structue (via <hask>doLayout</hask>) when the state changes.<br />
<br />
* Both <hask>doLayout</hask> and <hask>handleMessage</hask> have corresponding "pure" versions, which do not give results in the X monad. These functions are never called directly by the xmonad core, which only calls <hask>doLayout</hask> and <hask>handleMessage</hask>, but a layout may choose to implement one (or both) of these "pure" functions, which will be called by the default implementation of the "impure" versions. Layouts which implement <hask>pureLayout</hask> or <hask>pureMessage</hask> are guaranteed to only make decisions about layout or messages (respectively) based on the internal layout state, and not on the state of the system or the window manager in general. <br />
<br />
Now, every distinct layout will have a distinct type, although of course they all must be instances of <hask>LayoutClass</hask>. Given Haskell's strong typing, how can we store different layouts with different workspaces, or even change layouts on the fly? The solution is to wrap layouts using an <i>existential type</i> which hides the particular layout type and only exposes the fact that it is an instance of <hask>LayoutClass</hask>. Not only does this solve the problems caused by separate types for each layout, but it also guarantees that the xmonad core can only ever interact with a layout by calling functions from its <hask>LayoutClass</hask> instance. (Actually, this is a lie, since <hask>doLayout</hask> and <hask>handleMessage</hask> give results in the <hask>X</hask> monad, meaning they have access to the window manager state...)<br />
<br />
<haskell><br />
-- | An existential type that can hold any object that is in Read and LayoutClass.<br />
data Layout a = forall l. (LayoutClass l a, Read (l a)) => Layout (l a)<br />
</haskell><br />
<br />
The <hask>forall l.</hask> abstracts over all layout types (types which are an instance of <hask>LayoutClass</hask>); this is what makes it an existential type. Note that <hask>l</hask> does not appear on the left-hand side of the type declaration. A variable <hask>lay</hask> may have the highly specific type of some particular layout (for example, the types of layouts formed by stacking various layout combinators and transformers can get rather long and hairy!), but no matter what the type of <hask>lay</hask>, <hask>Layout lay</hask> will simply have the type <hask>Layout a</hask> for some window type <hask>a</hask> (usually <hask>Window</hask>).<br />
<br />
Note that <hask>(l a)</hask> is also required to be an instance of the <hask>Read</hask> type class -- this is so the state of all the layouts can be serialized and then read back in during dynamic restarts.<br />
<br />
=== Messages ===<br />
<br />
The xmonad core uses <i>messages</i> to communicate with layouts. The obvious, simple way to define messages would be by defining a new data type, something like<br />
<br />
<haskell><br />
-- WARNING: not real xmonad code!<br />
<br />
data Message = Hide | ReleaseResources | ShowMonkey<br />
</haskell><br />
<br />
thus defining three messages types, which tell a layout to hide itself, release any resources, and display a monkey, respectively.<br />
<br />
The problem with such an approach should be obvious: it is completely inflexible and inextensible; adding new message types later would be a pain, and it would be practically impossible for extension layouts to define their own message types without modifying the core. So, xmonad uses a more sophisticated system (at the cost of making things slightly harder to read and understand).<br />
<br />
Instead of defining a <hask>Message</hask> data type, xmonad defines a <hask>Message</hask> <i>type class</i>:<br />
<br />
<haskell><br />
class Typeable a => Message a<br />
<br />
data SomeMessage = forall a. Message a => SomeMessage a<br />
</haskell><br />
<br />
The <hask>Message</hask> class comes along with an existential wrapper <hask>SomeMessage</hask>, just like <hask>LayoutClass</hask> comes along with the <hask>Layout</hask> wrapper.<br />
<br />
Note also that the <hask>Message</hask> type class doesn't declare any methods; it simply serves as a marker for types whose values we wish to use as messages. The <hask>Typeable</hask> constraint ensures that the types of values used as messages can be carried around as values at runtime, so dynamic type checks can be performed on messages extracted from a <hask>SomeMessage</hask> wrapper:<br />
<br />
<haskell><br />
-- | And now, unwrap a given, unknown Message type, performing a (dynamic)<br />
-- type check on the result.<br />
--<br />
fromMessage :: Message m => SomeMessage -> Maybe m<br />
fromMessage (SomeMessage m) = cast m<br />
</haskell><br />
<br />
Complicated? A bit, perhaps, but the good news is that you probably don't have to worry too much about it. =)<br />
<br />
Finally, raw X events (like key presses, mouse movements, and so on) count as <hask>Message</hask>s, and two core message values are also defined as members of the <hask>LayoutMessages</hask> type.<br />
<br />
<haskell><br />
-- | X Events are valid Messages<br />
instance Message Event<br />
<br />
-- | LayoutMessages are core messages that all layouts (especially stateful<br />
-- layouts) should consider handling.<br />
data LayoutMessages = Hide -- ^ sent when a layout becomes non-visible<br />
| ReleaseResources -- ^ sent when xmonad is exiting or restarting<br />
deriving (Typeable, Eq)<br />
<br />
instance Message LayoutMessages<br />
</haskell><br />
<br />
=== Utility functions ===<br />
<br />
=== On-the-fly recompilation ===</div>Byorgey