]> git.sur5r.net Git - i3/i3/blob - docs/hacking-howto
cking-howto: update links
[i3/i3] / docs / hacking-howto
1 Hacking i3: How To
2 ==================
3 Michael Stapelberg <michael@i3wm.org>
4 February 2013
5
6 This document is intended to be the first thing you read before looking and/or
7 touching i3’s source code. It should contain all important information to help
8 you understand why things are like they are. If it does not mention something
9 you find necessary, please do not hesitate to contact me.
10
11 == Window Managers
12
13 A window manager is not necessarily needed to run X, but it is usually used in
14 combination with X to facilitate some things. The window manager's job is to
15 take care of the placement of windows, to provide the user with some mechanisms
16 to change the position/size of windows and to communicate with clients to a
17 certain extent (for example handle fullscreen requests of clients such as
18 MPlayer).
19
20 There are no different contexts in which X11 clients run, so a window manager
21 is just another client, like all other X11 applications. However, it handles
22 some events which normal clients usually don’t handle.
23
24 In the case of i3, the tasks (and order of them) are the following:
25
26 . Grab the key bindings (events will be sent upon keypress/keyrelease)
27 . Iterate through all existing windows (if the window manager is not started as
28   the first client of X) and manage them (reparent them, create window
29   decorations, etc.)
30 . When new windows are created, manage them
31 . Handle the client’s `_WM_STATE` property, but only `_WM_STATE_FULLSCREEN` and
32   `_NET_WM_STATE_DEMANDS_ATTENTION`
33 . Handle the client’s `WM_NAME` property
34 . Handle the client’s size hints to display them proportionally
35 . Handle the client’s urgency hint
36 . Handle enter notifications (focus follows mouse)
37 . Handle button (as in mouse buttons) presses for focus/raise on click
38 . Handle expose events to re-draw own windows such as decorations
39 . React to the user’s commands: Change focus, Move windows, Switch workspaces,
40   Change the layout mode of a container (default/stacking/tabbed), start a new
41   application, restart the window manager
42
43 In the following chapters, each of these tasks and their implementation details
44 will be discussed.
45
46 === Tiling window managers
47
48 Traditionally, there are two approaches to managing windows: The most common
49 one nowadays is floating, which means the user can freely move/resize the
50 windows. The other approach is called tiling, which means that your window
51 manager distributes windows to use as much space as possible while not
52 overlapping each other.
53
54 The idea behind tiling is that you should not need to waste your time
55 moving/resizing windows while you usually want to get some work done. After
56 all, most users sooner or later tend to lay out their windows in a way which
57 corresponds to tiling or stacking mode in i3. Therefore, why not let i3 do this
58 for you? Certainly, it’s faster than you could ever do it.
59
60 The problem with most tiling window managers is that they are too inflexible.
61 In my opinion, a window manager is just another tool, and similar to vim which
62 can edit all kinds of text files (like source code, HTML, …) and is not limited
63 to a specific file type, a window manager should not limit itself to a certain
64 layout (like dwm, awesome, …) but provide mechanisms for you to easily create
65 the layout you need at the moment.
66
67 === The layout tree
68
69 The data structure which i3 uses to keep track of your windows is a tree. Every
70 node in the tree is a container (type +Con+). Some containers represent actual
71 windows (every container with a +window != NULL+), some represent split
72 containers and a few have special purposes: they represent workspaces, outputs
73 (like VGA1, LVDS1, …) or the X11 root window.
74
75 So, when you open a terminal and immediately open another one, they reside in
76 the same split container, which uses the default layout. In case of an empty
77 workspace, the split container we are talking about is the workspace.
78
79 To get an impression of how different layouts are represented, just play around
80 and look at the data structures -- they are exposed as a JSON hash. See
81 http://i3wm.org/docs/ipc.html#_tree_reply for documentation on that and an
82 example.
83
84 == Files
85
86 include/atoms.xmacro::
87 A file containing all X11 atoms which i3 uses. This file will be included
88 various times (for defining, requesting and receiving the atoms), each time
89 with a different definition of xmacro().
90
91 include/data.h::
92 Contains data definitions used by nearly all files. You really need to read
93 this first.
94
95 include/*.h::
96 Contains forward definitions for all public functions, as well as
97 doxygen-compatible comments (so if you want to get a bit more of the big
98 picture, either browse all header files or use doxygen if you prefer that).
99
100 src/config_parser.c::
101 Contains a custom configuration parser. See src/command_parser.c for rationale
102  on why we use a custom parser.
103
104 src/click.c::
105 Contains all functions which handle mouse button clicks (right mouse button
106 clicks initiate resizing and thus are relatively complex).
107
108 src/command_parser.c::
109 Contains a hand-written parser to parse commands (commands are what
110 you bind on keys and what you can send to i3 using the IPC interface, like
111 'move left' or 'workspace 4').
112
113 src/con.c::
114 Contains all functions which deal with containers directly (creating
115 containers, searching containers, getting specific properties from containers,
116 …).
117
118 src/config.c::
119 Contains all functions handling the configuration file (calling the parser
120 (src/cfgparse.y) with the correct path, switching key bindings mode).
121
122 src/debug.c::
123 Contains debugging functions to print unhandled X events.
124
125 src/ewmh.c::
126 Functions to get/set certain EWMH properties easily.
127
128 src/floating.c::
129 Contains functions for floating mode (mostly resizing/dragging).
130
131 src/handlers.c::
132 Contains all handlers for all kinds of X events (new window title, new hints,
133 unmapping, key presses, button presses, …).
134
135 src/ipc.c::
136 Contains code for the IPC interface.
137
138 src/load_layout.c::
139 Contains code for loading layouts from JSON files.
140
141 src/log.c::
142 Contains the logging functions.
143
144 src/main.c::
145 Initializes the window manager.
146
147 src/manage.c::
148 Looks at existing or new windows and decides whether to manage them. If so, it
149 reparents the window and inserts it into our data structures.
150
151 src/match.c::
152 A "match" is a data structure which acts like a mask or expression to match
153 certain windows or not. For example, when using commands, you can specify a
154 command like this: [title="*Firefox*"] kill. The title member of the match
155 data structure will then be filled and i3 will check each window using
156 match_matches_window() to find the windows affected by this command.
157
158 src/move.c::
159 Contains code to move a container in a specific direction.
160
161 src/output.c::
162 Functions to handle CT_OUTPUT cons.
163
164 src/randr.c::
165 The RandR API is used to get (and re-query) the configured outputs (monitors,
166 …).
167
168 src/render.c::
169 Renders the tree data structure by assigning coordinates to every node. These
170 values will later be pushed to X11 in +src/x.c+.
171
172 src/resize.c::
173 Contains the functions to resize containers.
174
175 src/restore_layout.c::
176 Everything for restored containers that is not pure state parsing (which can be
177 found in load_layout.c).
178
179 src/sighandler.c::
180 Handles +SIGSEGV+, +SIGABRT+ and +SIGFPE+ by showing a dialog that i3 crashed.
181 You can chose to let it dump core, to restart it in-place or to restart it
182 in-place but forget about the layout.
183
184 src/tree.c::
185 Contains functions which open or close containers in the tree, change focus or
186 cleanup ("flatten") the tree. See also +src/move.c+ for another similar
187 function, which was moved into its own file because it is so long.
188
189 src/util.c::
190 Contains useful functions which are not really dependant on anything.
191
192 src/window.c::
193 Handlers to update X11 window properties like +WM_CLASS+, +_NET_WM_NAME+,
194 +CLIENT_LEADER+, etc.
195
196 src/workspace.c::
197 Contains all functions related to workspaces (displaying, hiding, renaming…)
198
199 src/x.c::
200 Transfers our in-memory tree (see +src/render.c+) to X11.
201
202 src/xcb.c::
203 Contains wrappers to use xcb more easily.
204
205 src/xcursor.c::
206 XCursor functions (for cursor themes).
207
208 src/xinerama.c::
209 Legacy support for Xinerama. See +src/randr.c+ for the preferred API.
210
211 == Data structures
212
213
214 See include/data.h for documented data structures. The most important ones are
215 explained right here.
216
217 /////////////////////////////////////////////////////////////////////////////////
218 // TODO: update image
219
220 image:bigpicture.png[The Big Picture]
221
222 /////////////////////////////////////////////////////////////////////////////////
223
224 So, the hierarchy is:
225
226 . *X11 root window*, the root container
227 . *Output container* (LVDS1 in this example)
228 . *Content container* (there are also containers for dock windows)
229 . *Workspaces* (Workspace 1 in this example, with horizontal orientation)
230 . *Split container* (vertically split)
231 . *X11 window containers*
232
233 The data type is +Con+, in all cases.
234
235 === X11 root window
236
237 The X11 root window is a single window per X11 display (a display is identified
238 by +:0+ or +:1+ etc.). The root window is what you draw your background image
239 on. It spans all the available outputs, e.g. +VGA1+ is a specific part of the
240 root window and +LVDS1+ is a specific part of the root window.
241
242 === Output container
243
244 Every active output obtained through RandR is represented by one output
245 container. Outputs are considered active when a mode is configured (meaning
246 something is actually displayed on the output) and the output is not a clone.
247
248 For example, if your notebook has a screen resolution of 1280x800 px and you
249 connect a video projector with a resolution of 1024x768 px, set it up in clone
250 mode (+xrandr \--output VGA1 \--mode 1024x768 \--same-as LVDS1+), i3 will
251 reduce the resolution to the lowest common resolution and disable one of the
252 cloned outputs afterwards.
253
254 However, if you configure it using +xrandr \--output VGA1 \--mode 1024x768
255 \--right-of LVDS1+, i3 will set both outputs active. For each output, a new
256 workspace will be assigned. New workspaces are created on the output you are
257 currently on.
258
259 === Content container
260
261 Each output has multiple children. Two of them are dock containers which hold
262 dock clients. The other one is the content container, which holds the actual
263 content (workspaces) of this output.
264
265 === Workspace
266
267 A workspace is identified by its name. Basically, you could think of
268 workspaces as different desks in your office, if you like the desktop
269 metaphor. They just contain different sets of windows and are completely
270 separate of each other. Other window managers also call this ``Virtual
271 desktops''.
272
273 === Split container
274
275 A split container is a container which holds an arbitrary amount of split
276 containers or X11 window containers. It has an orientation (horizontal or
277 vertical) and a layout.
278
279 Split containers (and X11 window containers, which are a subtype of split
280 containers) can have different border styles.
281
282 === X11 window container
283
284 An X11 window container holds exactly one X11 window. These are the leaf nodes
285 of the layout tree, they cannot have any children.
286
287 == List/queue macros
288
289 i3 makes heavy use of the list macros defined in BSD operating systems. To
290 ensure that the operating system on which i3 is compiled has all the expected
291 features, i3 comes with `include/queue.h`. On BSD systems, you can use man
292 `queue(3)`. On Linux, you have to use google (or read the source).
293
294 The lists used are +SLIST+ (single linked lists), +CIRCLEQ+ (circular
295 queues) and +TAILQ+ (tail queues). Usually, only forward traversal is necessary,
296 so an `SLIST` works fine. If inserting elements at arbitrary positions or at
297 the end of a list is necessary, a +TAILQ+ is used instead. However, for the
298 windows inside a container, a +CIRCLEQ+ is necessary to go from the currently
299 selected window to the window above/below.
300
301 == Naming conventions
302
303 There is a row of standard variables used in many events. The following names
304 should be chosen for those:
305
306  * ``conn'' is the xcb_connection_t
307  * ``event'' is the event of the particular type
308  * ``con'' names a container
309  * ``current'' is a loop variable when using +TAILQ_FOREACH+ etc.
310
311 == Startup (src/mainx.c, main())
312
313  * Establish the xcb connection
314  * Check for XKB extension on the separate X connection, load Xcursor
315  * Check for RandR screens (with a fall-back to Xinerama)
316  * Grab the keycodes for which bindings exist
317  * Manage all existing windows
318  * Enter the event loop
319
320 == Keybindings
321
322 === Grabbing the bindings
323
324 Grabbing the bindings is quite straight-forward. You pass X your combination of
325 modifiers and the keycode you want to grab and whether you want to grab them
326 actively or passively. Most bindings (everything except for bindings using
327 Mode_switch) are grabbed passively, that is, just the window manager gets the
328 event and cannot replay it.
329
330 We need to grab bindings that use Mode_switch actively because of a bug in X.
331 When the window manager receives the keypress/keyrelease event for an actively
332 grabbed keycode, it has to decide what to do with this event: It can either
333 replay it so that other applications get it or it can prevent other
334 applications from receiving it.
335
336 So, why do we need to grab keycodes actively? Because X does not set the
337 state-property of keypress/keyrelease events properly. The Mode_switch bit is
338 not set and we need to get it using XkbGetState. This means we cannot pass X
339 our combination of modifiers containing Mode_switch when grabbing the key and
340 therefore need to grab the keycode itself without any modifiers. This means,
341 if you bind Mode_switch + keycode 38 ("a"), i3 will grab keycode 38 ("a") and
342 check on each press of "a" if the Mode_switch bit is set using XKB. If yes, it
343 will handle the event, if not, it will replay the event.
344
345 === Handling a keypress
346
347 As mentioned in "Grabbing the bindings", upon a keypress event, i3 first gets
348 the correct state.
349
350 Then, it looks through all bindings and gets the one which matches the received
351 event.
352
353 The bound command is parsed by the cmdparse lexer/parser, see +parse_cmd+ in
354 +src/cmdparse.y+.
355
356 == Manage windows (src/main.c, manage_window() and reparent_window())
357
358 `manage_window()` does some checks to decide whether the window should be
359 managed at all:
360
361  * Windows have to be mapped, that is, visible on screen
362  * The override_redirect must not be set. Windows with override_redirect shall
363    not be managed by a window manager
364
365 Afterwards, i3 gets the initial geometry and reparents the window (see
366 `reparent_window()`) if it wasn’t already managed.
367
368 Reparenting means that for each window which is reparented, a new window,
369 slightly larger than the original one, is created. The original window is then
370 reparented to the bigger one (called "frame").
371
372 After reparenting, the window type (`_NET_WM_WINDOW_TYPE`) is checked to see
373 whether this window is a dock (`_NET_WM_WINDOW_TYPE_DOCK`), like dzen2 for
374 example. Docks are handled differently, they don’t have decorations and are not
375 assigned to a specific container. Instead, they are positioned at the bottom
376 or top of the screen (in the appropriate dock area containers). To get the
377 height which needs to be reserved for the window, the `_NET_WM_STRUT_PARTIAL`
378 property is used.
379
380 Furthermore, the list of assignments (to other workspaces, which may be on
381 other screens) is checked. If the window matches one of the user’s criteria,
382 it may either be put in floating mode or moved to a different workspace. If the
383 target workspace is not visible, the window will not be mapped.
384
385 == What happens when an application is started?
386
387 i3 does not care about applications. All it notices is when new windows are
388 mapped (see `src/handlers.c`, `handle_map_request()`). The window is then
389 reparented (see section "Manage windows").
390
391 After reparenting the window, `render_tree()` is called which renders the
392 internal layout table. The new window has been placed in the currently focused
393 container and therefore the new window and the old windows (if any) need to be
394 moved/resized so that the currently active layout (default/stacking/tabbed mode)
395 is rendered correctly. To move/resize windows, a window is ``configured'' in
396 X11-speak.
397
398 Some applications, such as MPlayer obviously assume the window manager is
399 stupid and try to configure their windows by themselves. This generates an
400 event called configurerequest. i3 handles these events and tells the window the
401 size it had before the configurerequest (with the exception of not yet mapped
402 windows, which get configured like they want to, and floating windows, which
403 can reconfigure themselves).
404
405 == _NET_WM_STATE
406
407 Only the _NET_WM_STATE_FULLSCREEN atom is handled. It calls
408 ``toggle_fullscreen()'' for the specific client which just configures the
409 client to use the whole screen on which it currently is. Also, it is set as
410 fullscreen_client for the i3Screen.
411
412 == WM_NAME
413
414 When the WM_NAME property of a window changes, its decoration (containing the
415 title) is re-rendered. Note that WM_NAME is in COMPOUND_TEXT encoding which is
416 totally uncommon and cumbersome. Therefore, the _NET_WM_NAME atom will be used
417 if present.
418
419 == _NET_WM_NAME
420
421 Like WM_NAME, this atom contains the title of a window. However, _NET_WM_NAME
422 is encoded in UTF-8. i3 will recode it to UCS-2 in order to be able to pass it
423 to X. Using an appropriate font (ISO-10646), you can see most special
424 characters (every special character contained in your font).
425
426 == Size hints
427
428 Size hints specify the minimum/maximum size for a given window as well as its
429 aspect ratio.  This is important for clients like mplayer, who only set the
430 aspect ratio and resize their window to be as small as possible (but only with
431 some video outputs, for example in Xv, while when using x11, mplayer does the
432 necessary centering for itself).
433
434 So, when an aspect ratio was specified, i3 adjusts the height of the window
435 until the size maintains the correct aspect ratio. For the code to do this, see
436 src/layout.c, function resize_client().
437
438 == Rendering (src/layout.c, render_layout() and render_container())
439
440 Rendering in i3 version 4 is the step which assigns the correct sizes for
441 borders, decoration windows, child windows and the stacking order of all
442 windows. In a separate step (+x_push_changes()+), these changes are pushed to
443 X11.
444
445 Keep in mind that all these properties (+rect+, +window_rect+ and +deco_rect+)
446 are temporary, meaning they will be overwritten by calling +render_con+.
447 Persistent position/size information is kept in +geometry+.
448
449 The entry point for every rendering operation (except for the case of moving
450 floating windows around) currently is +tree_render()+ which will re-render
451 everything that’s necessary (for every output, only the currently displayed
452 workspace is rendered). This behavior is expected to change in the future,
453 since for a lot of updates, re-rendering everything is not actually necessary.
454 Focus was on getting it working correct, not getting it work very fast.
455
456 What +tree_render()+ actually does is calling +render_con()+ on the root
457 container and then pushing the changes to X11. The following sections talk
458 about the different rendering steps, in the order of "top of the tree" (root
459 container) to the bottom.
460
461 === Rendering the root container
462
463 The i3 root container (`con->type == CT_ROOT`) represents the X11 root window.
464 It contains one child container for every output (like LVDS1, VGA1, …), which
465 is available on your computer.
466
467 Rendering the root will first render all tiling windows and then all floating
468 windows. This is necessary because a floating window can be positioned in such
469 a way that it is visible on two different outputs. Therefore, by first
470 rendering all the tiling windows (of all outputs), we make sure that floating
471 windows can never be obscured by tiling windows.
472
473 Essentially, though, this code path will just call +render_con()+ for every
474 output and +x_raise_con(); render_con()+ for every floating window.
475
476 In the special case of having a "global fullscreen" window (fullscreen mode
477 spanning all outputs), a shortcut is taken and +x_raise_con(); render_con()+ is
478 only called for the global fullscreen window.
479
480 === Rendering an output
481
482 Output containers (`con->layout == L_OUTPUT`) represent a hardware output like
483 LVDS1, VGA1, etc. An output container has three children (at the moment): One
484 content container (having workspaces as children) and the top/bottom dock area
485 containers.
486
487 The rendering happens in the function +render_l_output()+ in the following
488 steps:
489
490 1. Find the content container (`con->type == CT_CON`)
491 2. Get the currently visible workspace (+con_get_fullscreen_con(content,
492    CF_OUTPUT)+).
493 3. If there is a fullscreened window on that workspace, directly render it and
494    return, thus ignoring the dock areas.
495 4. Sum up the space used by all the dock windows (they have a variable height
496    only).
497 5. Set the workspace rects (x/y/width/height) based on the position of the
498    output (stored in `con->rect`) and the usable space
499    (`con->rect.{width,height}` without the space used for dock windows).
500 6. Recursively raise and render the output’s child containers (meaning dock
501    area containers and the content container).
502
503 === Rendering a workspace or split container
504
505 From here on, there really is no difference anymore. All containers are of
506 `con->type == CT_CON` (whether workspace or split container) and some of them
507 have a `con->window`, meaning they represent an actual window instead of a
508 split container.
509
510 ==== Default layout
511
512 In default layout, containers are placed horizontally or vertically next to
513 each other (depending on the `con->orientation`). If a child is a leaf node (as
514 opposed to a split container) and has border style "normal", appropriate space
515 will be reserved for its window decoration.
516
517 ==== Stacked layout
518
519 In stacked layout, only the focused window is actually shown (this is achieved
520 by calling +x_raise_con()+ in reverse focus order at the end of +render_con()+).
521
522 The available space for the focused window is the size of the container minus
523 the height of the window decoration for all windows inside this stacked
524 container.
525
526 If border style is "1pixel" or "none", no window decoration height will be
527 reserved (or displayed later on), unless there is more than one window inside
528 the stacked container.
529
530 ==== Tabbed layout
531
532 Tabbed layout works precisely like stacked layout, but the window decoration
533 position/size is different: They are placed next to each other on a single line
534 (fixed height).
535
536 ==== Dock area layout
537
538 This is a special case. Users cannot choose the dock area layout, but it will be
539 set for the dock area containers. In the dockarea layout (at the moment!),
540 windows will be placed above each other.
541
542 === Rendering a window
543
544 A window’s size and position will be determined in the following way:
545
546 1. Subtract the border if border style is not "none" (but "normal" or "1pixel").
547 2. Subtract the X11 border, if the window has an X11 border > 0.
548 3. Obey the aspect ratio of the window (think MPlayer).
549 4. Obey the height- and width-increments of the window (think terminal emulator
550    which can only be resized in one-line or one-character steps).
551
552 == Pushing updates to X11 / Drawing
553
554 A big problem with i3 before version 4 was that we just sent requests to X11
555 anywhere in the source code. This was bad because nobody could understand the
556 entirety of our interaction with X11, it lead to subtle bugs and a lot of edge
557 cases which we had to consider all over again.
558
559 Therefore, since version 4, we have a single file, +src/x.c+, which is
560 responsible for repeatedly transferring parts of our tree datastructure to X11.
561
562 +src/x.c+ consists of multiple parts:
563
564 1. The state pushing: +x_push_changes()+, which calls +x_push_node()+.
565 2. State modification functions: +x_con_init+, +x_reinit+,
566    +x_reparent_child+, +x_move_win+, +x_con_kill+, +x_raise_con+, +x_set_name+
567    and +x_set_warp_to+.
568 3. Expose event handling (drawing decorations): +x_deco_recurse()+ and
569    +x_draw_decoration()+.
570
571 === Pushing state to X11
572
573 In general, the function +x_push_changes+ should be called to push state
574 changes. Only when the scope of the state change is clearly defined (for
575 example only the title of a window) and its impact is known beforehand, one can
576 optimize this and call +x_push_node+ on the appropriate con directly.
577
578 +x_push_changes+ works in the following steps:
579
580 1. Clear the eventmask for all mapped windows. This leads to not getting
581    useless ConfigureNotify or EnterNotify events which are caused by our
582    requests. In general, we only want to handle user input.
583 2. Stack windows above each other, in reverse stack order (starting with the
584    most obscured/bottom window). This is relevant for floating windows which
585    can overlap each other, but also for tiling windows in stacked or tabbed
586    containers. We also update the +_NET_CLIENT_LIST_STACKING+ hint which is
587    necessary for tab drag and drop in Chromium.
588 3. +x_push_node+ will be called for the root container, recursively calling
589    itself for the container’s children. This function actually pushes the
590    state, see the next paragraph.
591 4. If the pointer needs to be warped to a different position (for example when
592    changing focus to a differnt output), it will be warped now.
593 5. The eventmask is restored for all mapped windows.
594 6. Window decorations will be rendered by calling +x_deco_recurse+ on the root
595    container, which then recursively calls itself for the children.
596 7. If the input focus needs to be changed (because the user focused a different
597    window), it will be updated now.
598 8. +x_push_node_unmaps+ will be called for the root container. This function
599    only pushes UnmapWindow requests. Separating the state pushing is necessary
600    to handle fullscreen windows (and workspace switches) in a smooth fashion:
601    The newly visible windows should be visible before the old windows are
602    unmapped.
603
604 +x_push_node+ works in the following steps:
605
606 1. Update the window’s +WM_NAME+, if changed (the +WM_NAME+ is set on i3
607    containers mainly for debugging purposes).
608 2. Reparents a child window into the i3 container if the container was created
609    for a specific managed window.
610 3. If the size/position of the i3 container changed (due to opening a new
611    window or switching layouts for example), the window will be reconfigured.
612    Also, the pixmap which is used to draw the window decoration/border on is
613    reconfigured (pixmaps are size-dependent).
614 4. Size/position for the child window is adjusted.
615 5. The i3 container is mapped if it should be visible and was not yet mapped.
616    When mapping, +WM_STATE+ is set to +WM_STATE_NORMAL+. Also, the eventmask of
617    the child window is updated and the i3 container’s contents are copied from
618    the pixmap.
619 6. +x_push_node+ is called recursively for all children of the current
620    container.
621
622 +x_push_node_unmaps+ handles the remaining case of an i3 container being
623 unmapped if it should not be visible anymore. +WM_STATE+ will be set to
624 +WM_STATE_WITHDRAWN+.
625
626
627 === Drawing window decorations/borders/backgrounds
628
629 +x_draw_decoration+ draws window decorations. It is run for every leaf
630 container (representing an actual X11 window) and for every non-leaf container
631 which is in a stacked/tabbed container (because stacked/tabbed containers
632 display a window decoration for split containers, which at the moment just says
633 "another container").
634
635 Then, parameters are collected to be able to determine whether this decoration
636 drawing is actually necessary or was already done. This saves a substantial
637 number of redraws (depending on your workload, but far over 50%).
638
639 Assuming that we need to draw this decoration, we start by filling the empty
640 space around the child window (think of MPlayer with a specific aspect ratio)
641 in the user-configured client background color.
642
643 Afterwards, we draw the appropriate border (in case of border styles "normal"
644 and "1pixel") and the top bar (in case of border style "normal").
645
646 The last step is drawing the window title on the top bar.
647
648
649 /////////////////////////////////////////////////////////////////////////////////
650
651 == Resizing containers
652
653 By clicking and dragging the border of a container, you can resize the whole
654 column (respectively row) which this container is in. This is necessary to keep
655 the table layout working and consistent.
656
657 The resizing works similarly to the resizing of floating windows or movement of
658 floating windows:
659
660 * A new, invisible window with the size of the root window is created
661   (+grabwin+)
662 * Another window, 2px width and as high as your screen (or vice versa for
663   horizontal resizing) is created. Its background color is the border color and
664   it is only there to inform the user how big the container will be (it
665   creates the impression of dragging the border out of the container).
666 * The +drag_pointer+ function of +src/floating.c+ is called to grab the pointer
667   and enter its own event loop which will pass all events (expose events) but
668   motion notify events. This function then calls the specified callback
669   (+resize_callback+) which does some boundary checking and moves the helper
670   window. As soon as the mouse button is released, this loop will be
671   terminated.
672 * The new width_factor for each involved column (respectively row) will be
673   calculated.
674
675 /////////////////////////////////////////////////////////////////////////////////
676
677 == User commands (parser-specs/commands.spec)
678
679 In the configuration file and when using i3 interactively (with +i3-msg+, for
680 example), you use commands to make i3 do things, like focus a different window,
681 set a window to fullscreen, and so on. An example command is +floating enable+,
682 which enables floating mode for the currently focused window. See the
683 appropriate section in the link:userguide.html[User’s Guide] for a reference of
684 all commands.
685
686 In earlier versions of i3, interpreting these commands was done using lex and
687 yacc, but experience has shown that lex and yacc are not well suited for our
688 command language. Therefore, starting from version 4.2, we use a custom parser
689 for user commands (not yet for the configuration file).
690 The input specification for this parser can be found in the file
691 +parser-specs/commands.spec+. Should you happen to use Vim as an editor, use
692 :source parser-specs/highlighting.vim to get syntax highlighting for this file
693 (highlighting files for other editors are welcome).
694
695 .Excerpt from commands.spec
696 -----------------------------------------------------------------------
697 state INITIAL:
698   '[' -> call cmd_criteria_init(); CRITERIA
699   'move' -> MOVE
700   'exec' -> EXEC
701   'workspace' -> WORKSPACE
702   'exit' -> call cmd_exit()
703   'restart' -> call cmd_restart()
704   'reload' -> call cmd_reload()
705 -----------------------------------------------------------------------
706
707 The input specification is written in an extremely simple format. The
708 specification is then converted into C code by the Perl script
709 generate-commands-parser.pl (the output file names begin with GENERATED and the
710 files are stored in the +include+ directory). The parser implementation
711 +src/commands_parser.c+ includes the generated C code at compile-time.
712
713 The above excerpt from commands.spec illustrates nearly all features of our
714 specification format: You describe different states and what can happen within
715 each state. State names are all-caps; the state in the above excerpt is called
716 INITIAL. A list of tokens and their actions (separated by an ASCII arrow)
717 follows. In the excerpt, all tokens are literals, that is, simple text strings
718 which will be compared with the input. An action is either the name of a state
719 in which the parser will transition into, or the keyword 'call', followed by
720 the name of a function (and optionally a state).
721
722 === Example: The WORKSPACE state
723
724 Let’s have a look at the WORKSPACE state, which is a good example of all
725 features. This is its definition:
726
727 .WORKSPACE state (commands.spec)
728 ----------------------------------------------------------------
729 # workspace next|prev|next_on_output|prev_on_output
730 # workspace back_and_forth
731 # workspace <name>
732 state WORKSPACE:
733   direction = 'next_on_output', 'prev_on_output', 'next', 'prev'
734       -> call cmd_workspace($direction)
735   'back_and_forth'
736       -> call cmd_workspace_back_and_forth()
737   workspace = string
738       -> call cmd_workspace_name($workspace)
739 ----------------------------------------------------------------
740
741 As you can see from the commands, there are multiple different valid variants
742 of the workspace command:
743
744 workspace <direction>::
745         The word 'workspace' can be followed by any of the tokens 'next',
746         'prev', 'next_on_output' or 'prev_on_output'. This command will
747         switch to the next or previous workspace (optionally on the same
748         output). +
749         There is one function called +cmd_workspace+, which is defined
750         in +src/commands.c+. It will handle this kind of command. To know which
751         direction was specified, the direction token is stored on the stack
752         with the name "direction", which is what the "direction = " means in
753         the beginning. +
754
755 NOTE: Note that you can specify multiple literals in the same line. This has
756         exactly the same effect as if you specified `direction =
757         'next_on_output' -> call cmd_workspace($direction)` and so forth. +
758
759 NOTE: Also note that the order of literals is important here: If 'next' were
760         ordered before 'next_on_output', then 'next_on_output' would never
761         match.
762
763 workspace back_and_forth::
764         This is a very simple case: When the literal 'back_and_forth' is found
765         in the input, the function +cmd_workspace_back_and_forth+ will be
766         called without parameters and the parser will return to the INITIAL
767         state (since no other state was specified).
768 workspace <name>::
769         In this case, the workspace command is followed by an arbitrary string,
770         possibly in quotes, for example "workspace 3" or "workspace bleh". +
771         This is the first time that the token is actually not a literal (not in
772         single quotes), but just called string. Other possible tokens are word
773         (the same as string, but stops matching at a whitespace) and end
774         (matches the end of the input).
775
776 === Introducing a new command
777
778 The following steps have to be taken in order to properly introduce a new
779 command (or possibly extend an existing command):
780
781 1. Define a function beginning with +cmd_+ in the file +src/commands.c+. Copy
782    the prototype of an existing function.
783 2. After adding a comment on what the function does, copy the comment and
784    function definition to +include/commands.h+. Make the comment in the header
785    file use double asterisks to make doxygen pick it up.
786 3. Write a test case (or extend an existing test case) for your feature, see
787    link:testsuite.html[i3 testsuite]. For now, it is sufficient to simply call
788    your command in all the various possible ways.
789 4. Extend the parser specification in +parser-specs/commands.spec+. Run the
790    testsuite and see if your new function gets called with the appropriate
791    arguments for the appropriate input.
792 5. Actually implement the feature.
793 6. Document the feature in the link:userguide.html[User’s Guide].
794
795 == Moving containers
796
797 The movement code is pretty delicate. You need to consider all cases before
798 making any changes or before being able to fully understand how it works.
799
800 === Case 1: Moving inside the same container
801
802 The reference layout for this case is a single workspace in horizontal
803 orientation with two containers on it. Focus is on the left container (1).
804
805
806 [width="15%",cols="^,^"]
807 |========
808 | 1 | 2
809 |========
810
811 When moving the left window to the right (command +move right+), tree_move will
812 look for a container with horizontal orientation and finds the parent of the
813 left container, that is, the workspace. Afterwards, it runs the code branch
814 commented with "the easy case": it calls TAILQ_NEXT to get the container right
815 of the current one and swaps both containers.
816
817 === Case 2: Move a container into a split container
818
819 The reference layout for this case is a horizontal workspace with two
820 containers. The right container is a v-split with two containers. Focus is on
821 the left container (1).
822
823 [width="15%",cols="^,^"]
824 |========
825 1.2+^.^| 1 | 2
826 | 3
827 |========
828
829 When moving to the right (command +move right+), i3 will work like in case 1
830 ("the easy case"). However, as the right container is not a leaf container, but
831 a v-split, the left container (1) will be inserted at the right position (below
832 2, assuming that 2 is focused inside the v-split) by calling +insert_con_into+.
833
834 +insert_con_into+ detaches the container from its parent and inserts it
835 before/after the given target container. Afterwards, the on_remove_child
836 callback is called on the old parent container which will then be closed, if
837 empty.
838
839 Afterwards, +con_focus+ will be called to fix the focus stack and the tree will
840 be flattened.
841
842 === Case 3: Moving to non-existant top/bottom
843
844 Like in case 1, the reference layout for this case is a single workspace in
845 horizontal orientation with two containers on it. Focus is on the left
846 container:
847
848 [width="15%",cols="^,^"]
849 |========
850 | 1 | 2
851 |========
852
853 This time however, the command is +move up+ or +move down+. tree_move will look
854 for a container with vertical orientation. As it will not find any,
855 +same_orientation+ is NULL and therefore i3 will perform a forced orientation
856 change on the workspace by creating a new h-split container, moving the
857 workspace contents into it and then changing the workspace orientation to
858 vertical. Now it will again search for parent containers with vertical
859 orientation and it will find the workspace.
860
861 This time, the easy case code path will not be run as we are not moving inside
862 the same container. Instead, +insert_con_into+ will be called with the focused
863 container and the container above/below the current one (on the level of
864 +same_orientation+).
865
866 Now, +con_focus+ will be called to fix the focus stack and the tree will be
867 flattened.
868
869 === Case 4: Moving to existant top/bottom
870
871 The reference layout for this case is a vertical workspace with two containers.
872 The bottom one is a h-split containing two containers (1 and 2). Focus is on
873 the bottom left container (1).
874
875 [width="15%",cols="^,^"]
876 |========
877 2+| 3
878 | 1 | 2
879 |========
880
881 This case is very much like case 3, only this time the forced workspace
882 orientation change does not need to be performed because the workspace already
883 is in vertical orientation.
884
885 === Case 5: Moving in one-child h-split
886
887 The reference layout for this case is a horizontal workspace with two
888 containers having a v-split on the left side with a one-child h-split on the
889 bottom. Focus is on the bottom left container (2(h)):
890
891 [width="15%",cols="^,^"]
892 |========
893 | 1 1.2+^.^| 3
894 | 2(h)
895 |========
896
897 In this case, +same_orientation+ will be set to the h-split container around
898 the focused container. However, when trying the easy case, the next/previous
899 container +swap+ will be NULL. Therefore, i3 will search again for a
900 +same_orientation+ container, this time starting from the parent of the h-split
901 container.
902
903 After determining a new +same_orientation+ container (if it is NULL, the
904 orientation will be force-changed), this case is equivalent to case 2 or case
905 4.
906
907
908 === Case 6: Floating containers
909
910 The reference layout for this case is a horizontal workspace with two
911 containers plus one floating h-split container. Focus is on the floating
912 container.
913
914 TODO: nice illustration. table not possible?
915
916 When moving up/down, the container needs to leave the floating container and it
917 needs to be placed on the workspace (at workspace level). This is accomplished
918 by calling the function +attach_to_workspace+.
919
920 == Click handling
921
922 Without much ado, here is the list of cases which need to be considered:
923
924 * click to focus (tiling + floating) and raise (floating)
925 * click to focus/raise when in stacked/tabbed mode
926 * floating_modifier + left mouse button to drag a floating con
927 * floating_modifier + right mouse button to resize a floating con
928 * click on decoration in a floating con to either initiate a resize (if there
929   is more than one child in the floating con) or to drag the
930   floating con (if it’s the one at the top).
931 * click on border in a floating con to resize the floating con
932 * floating_modifier + right mouse button to resize a tiling con
933 * click on border/decoration to resize a tiling con
934
935 == Gotchas
936
937 * Forgetting to call `xcb_flush(conn);` after sending a request. This usually
938   leads to code which looks like it works fine but which does not work under
939   certain conditions.
940
941 * Forgetting to call `floating_fix_coordinates(con, old_rect, new_rect)` after
942   moving workspaces across outputs. Coordinates for floating containers are
943   not relative to workspace boundaries, so you must correct their coordinates
944   or those containers will show up in the wrong workspace or not at all.
945
946 == Using git / sending patches
947
948 === Introduction
949
950 For a short introduction into using git, see
951 http://web.archive.org/web/20121024222556/http://www.spheredev.org/wiki/Git_for_the_lazy
952 or, for more documentation, see http://git-scm.com/documentation
953
954 Please talk to us before working on new features to see whether they will be
955 accepted. There are a few things which we don’t want to see in i3, e.g. a
956 command which will focus windows in an alt+tab like way.
957
958 When working on bugfixes, please make sure you mention that you are working on
959 it in the corresponding bugreport at https://github.com/i3/i3/issues In case
960 there is no bugreport yet, please create one.
961
962 After you are done, please submit your work for review at https://github.com/i3/i3
963
964 Do not send emails to the mailing list or any author directly, and don’t submit
965 them in the bugtracker, since all reviews should be done in public at
966 http://cr.i3wm.org/. In order to make your review go as fast as possible, you
967 could have a look at previous reviews and see what the common mistakes are.
968
969 === Which branch to use?
970
971 Work on i3 generally happens in two branches: “master” and “next”. Since
972 “master” is what people get when they check out the git repository, its
973 contents are always stable. That is, it contains the source code of the latest
974 release, plus any bugfixes that were applied since that release.
975
976 New features are only found in the “next” branch. Therefore, if you are working
977 on a new feature, use the “next” branch. If you are working on a bugfix, use
978 the “next” branch, too, but make sure your code also works on “master”.
979
980 == Thought experiments
981
982 In this section, we collect thought experiments, so that we don’t forget our
983 thoughts about specific topics. They are not necessary to get into hacking i3,
984 but if you are interested in one of the topics they cover, you should read them
985 before asking us why things are the way they are or why we don’t implement
986 things.
987
988 === Using cgroups per workspace
989
990 cgroups (control groups) are a linux-only feature which provides the ability to
991 group multiple processes. For each group, you can individually set resource
992 limits, like allowed memory usage. Furthermore, and more importantly for our
993 purposes, they serve as a namespace, a label which you can attach to processes
994 and their children.
995
996 One interesting use for cgroups is having one cgroup per workspace (or
997 container, doesn’t really matter). That way, you could set different priorities
998 and have a workspace for important stuff (say, writing a LaTeX document or
999 programming) and a workspace for unimportant background stuff (say,
1000 JDownloader). Both tasks can obviously consume a lot of I/O resources, but in
1001 this example it doesn’t really matter if JDownloader unpacks the download a
1002 minute earlier or not. However, your compiler should work as fast as possible.
1003 Having one cgroup per workspace, you would assign more resources to the
1004 programming workspace.
1005
1006 Another interesting feature is that an inherent problem of the workspace
1007 concept could be solved by using cgroups: When starting an application on
1008 workspace 1, then switching to workspace 2, you will get the application’s
1009 window(s) on workspace 2 instead of the one you started it on. This is because
1010 the window manager does not have any mapping between the process it starts (or
1011 gets started in any way) and the window(s) which appear.
1012
1013 Imagine for example using dmenu: The user starts dmenu by pressing Mod+d, dmenu
1014 gets started with PID 3390. The user then decides to launch Firefox, which
1015 takes a long time. So he enters firefox into dmenu and presses enter. Firefox
1016 gets started with PID 4001. When it finally finishes loading, it creates an X11
1017 window and uses MapWindow to make it visible. This is the first time i3
1018 actually gets in touch with Firefox. It decides to map the window, but it has
1019 no way of knowing that this window (even though it has the _NET_WM_PID property
1020 set to 4001) belongs to the dmenu the user started before.
1021
1022 How do cgroups help with this? Well, when pressing Mod+d to launch dmenu, i3
1023 would create a new cgroup, let’s call it i3-3390-1. It launches dmenu in that
1024 cgroup, which gets PID 3390. As before, the user enters firefox and Firefox
1025 gets launched with PID 4001. This time, though, the Firefox process with PID
1026 4001 is *also* member of the cgroup i3-3390-1 (because fork()ing in a cgroup
1027 retains the cgroup property). Therefore, when mapping the window, i3 can look
1028 up in which cgroup the process is and can establish a mapping between the
1029 workspace and the window.
1030
1031 There are multiple problems with this approach:
1032
1033 . Every application has to properly set +_NET_WM_PID+. This is acceptable and
1034   patches can be written for the few applications which don’t set the hint yet.
1035 . It does only work on Linux, since cgroups are a Linux-only feature. Again,
1036   this is acceptable.
1037 . The main problem is that some applications create X11 windows completely
1038   independent of UNIX processes. An example for this is Chromium (or
1039   gnome-terminal), which, when being started a second time, communicates with
1040   the first process and lets the first process open a new window. Therefore, if
1041   you have a Chromium window on workspace 2 and you are currently working on
1042   workspace 3, starting +chromium+ does not lead to the desired result (the
1043   window will open on workspace 2).
1044
1045 Therefore, my conclusion is that the only proper way of fixing the "window gets
1046 opened on the wrong workspace" problem is in the application itself. Most
1047 modern applications support freedesktop startup-notifications  which can be
1048 used for this.