]> git.sur5r.net Git - i3/i3/blob - docs/hacking-howto
document the different cases for click handling
[i3/i3] / docs / hacking-howto
1 Hacking i3: How To
2 ==================
3 Michael Stapelberg <michael+i3@stapelberg.de>
4 February 2010
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 PLEASE BEWARE THAT THIS DOCUMENT IS ONLY PARTIALLY UPDATED FOR -tree YET!
12
13 == Window Managers
14
15 A window manager is not necessarily needed to run X, but it is usually used in
16 combination with X to facilitate some things. The window manager's job is to
17 take care of the placement of windows, to provide the user with some mechanisms
18 to change the position/size of windows and to communicate with clients to a
19 certain extent (for example handle fullscreen requests of clients such as
20 MPlayer).
21
22 There are no different contexts in which X11 clients run, so a window manager
23 is just another client, like all other X11 applications. However, it handles
24 some events which normal clients usually don’t handle.
25
26 In the case of i3, the tasks (and order of them) are the following:
27
28 . Grab the key bindings (events will be sent upon keypress/keyrelease)
29 . Iterate through all existing windows (if the window manager is not started as
30   the first client of X) and manage them (reparent them, create window
31   decorations, etc.)
32 . When new windows are created, manage them
33 . Handle the client’s `_WM_STATE` property, but only the `_WM_STATE_FULLSCREEN`
34 . Handle the client’s `WM_NAME` property
35 . Handle the client’s size hints to display them proportionally
36 . Handle the client’s urgency hint
37 . Handle enter notifications (focus follows mouse)
38 . Handle button (as in mouse buttons) presses for focus/raise on click
39 . Handle expose events to re-draw own windows such as decorations
40 . React to the user’s commands: Change focus, Move windows, Switch workspaces,
41   Change the layout mode of a container (default/stacking/tabbed), start a new
42   application, restart the window manager
43
44 In the following chapters, each of these tasks and their implementation details
45 will be discussed.
46
47 === Tiling window managers
48
49 Traditionally, there are two approaches to managing windows: The most common
50 one nowadays is floating, which means the user can freely move/resize the
51 windows. The other approach is called tiling, which means that your window
52 manager distributes windows to use as much space as possible while not
53 overlapping each other.
54
55 The idea behind tiling is that you should not need to waste your time
56 moving/resizing windows while you usually want to get some work done. After
57 all, most users sooner or later tend to lay out their windows in a way which
58 corresponds to tiling or stacking mode in i3. Therefore, why not let i3 do this
59 for you? Certainly, it’s faster than you could ever do it.
60
61 The problem with most tiling window managers is that they are too unflexible.
62 In my opinion, a window manager is just another tool, and similar to vim which
63 can edit all kinds of text files (like source code, HTML, …) and is not limited
64 to a specific file type, a window manager should not limit itself to a certain
65 layout (like dwm, awesome, …) but provide mechanisms for you to easily create
66 the layout you need at the moment.
67
68 === The layout table
69
70 To accomplish flexible layouts, we decided to simply use a table. The table
71 grows and shrinks as you need it. Each cell holds a container which then holds
72 windows (see picture below). You can use different layouts for each container
73 (default layout and stacking layout).
74
75 So, when you open a terminal and immediately open another one, they reside in
76 the same container, in default layout. The layout table has exactly one column,
77 one row and therefore one cell. When you move one of the terminals to the
78 right, the table needs to grow. It will be expanded to two columns and one row.
79 This enables you to have different layouts for each container. The table then
80 looks like this:
81
82 [width="15%",cols="^,^"]
83 |========
84 | T1 | T2
85 |========
86
87 When moving terminal 2 to the bottom, the table will be expanded again.
88
89 [width="15%",cols="^,^"]
90 |========
91 | T1 |
92 |    | T2
93 |========
94
95 You can really think of the layout table like a traditional HTML table, if
96 you’ve ever designed one. Especially col- and rowspan work similarly. Below,
97 you see an example of colspan=2 for the first container (which has T1 as
98 window).
99
100 [width="15%",cols="^asciidoc"]
101 |========
102 | T1
103 |
104 [cols="^,^",frame="none"]
105 !========
106 ! T2 ! T3
107 !========
108 |========
109
110 Furthermore, you can freely resize table cells.
111
112 == Files
113
114 include/data.h::
115 Contains data definitions used by nearly all files. You really need to read
116 this first.
117
118 include/*.h::
119 Contains forward definitions for all public functions, as well as
120 doxygen-compatible comments (so if you want to get a bit more of the big
121 picture, either browse all header files or use doxygen if you prefer that).
122
123 src/cfgparse.l::
124 Contains the lexer for i3’s configuration file, written for +flex(1)+.
125
126 src/cfgparse.y::
127 Contains the parser for i3’s configuration file, written for +bison(1)+.
128
129 src/click.c::
130 Contains all functions which handle mouse button clicks (right mouse button
131 clicks initiate resizing and thus are relatively complex).
132
133 src/client.c::
134 Contains all functions which are specific to a certain client (make it
135 fullscreen, see if its class/name matches a pattern, kill it, …).
136
137 src/commands.c::
138 Parsing commands and actually executing them (focusing, moving, …).
139
140 src/config.c::
141 Parses the configuration file.
142
143 src/debug.c::
144 Contains debugging functions to print unhandled X events.
145
146 src/floating.c::
147 Contains functions for floating mode (mostly resizing/dragging).
148
149 src/handlers.c::
150 Contains all handlers for all kinds of X events (new window title, new hints,
151 unmapping, key presses, button presses, …).
152
153 src/ipc.c::
154 Contains code for the IPC interface.
155
156 src/layout.c::
157 Renders your layout (screens, workspaces, containers).
158
159 src/mainx.c::
160 Initializes the window manager.
161
162 src/manage.c::
163 Looks at existing or new windows and decides whether to manage them. If so, it
164 reparents the window and inserts it into our data structures.
165
166 src/resize.c::
167 Contains the functions to resize columns/rows in the table.
168
169 src/table.c::
170 Manages the most important internal data structure, the design table.
171
172 src/util.c::
173 Contains useful functions which are not really dependant on anything.
174
175 src/workspace.c::
176 Contains all functions related to workspaces (displaying, hiding, renaming…)
177
178 src/xcb.c::
179 Contains wrappers to use xcb more easily.
180
181 src/xinerama.c::
182 (Re-)initializes the available screens and converts them to virtual screens
183 (see below).
184
185 == Data structures
186
187 See include/data.h for documented data structures. The most important ones are
188 explained right here.
189
190 image:bigpicture.png[The Big Picture]
191
192 So, the hierarchy is:
193
194 . *Virtual screens* (Screen 0 in this example)
195 . *Workspaces* (Workspace 1 in this example)
196 . *Table* (There can only be one table per Workspace)
197 . *Container* (left and right in this example)
198 . *Client* (The two clients in the left container)
199
200 === Virtual screens
201
202 A virtual screen (type `i3Screen`) is generated from the connected screens
203 obtained through Xinerama. The difference to the raw Xinerama monitors as seen
204 when using +xrandr(1)+ is that it falls back to the lowest common resolution of
205 the logical screens.
206
207 For example, if your notebook has 1280x800 and you connect a video projector
208 with 1024x768, set up in clone mode (+xrandr \--output VGA \--mode 1024x768
209 \--same-as LVDS+), i3 will have one virtual screen.
210
211 However, if you configure it using +xrandr \--output VGA \--mode 1024x768
212 \--right-of LVDS+, i3 will generate two virtual screens. For each virtual
213 screen, a new workspace will be assigned. New workspaces are created on the
214 screen you are currently on.
215
216 === Workspace
217
218 A workspace is identified by its number. Basically, you could think of
219 workspaces as different desks in your office, if you like the desktop
220 methaphor. They just contain different sets of windows and are completely
221 separate of each other. Other window managers also call this ``Virtual
222 desktops''.
223
224 === The layout table
225
226 Each workspace has a table, which is just a two-dimensional dynamic array
227 containing Containers (see below). This table grows and shrinks as you need it
228 (by moving windows to the right you can create a new column in the table, by
229 moving them to the bottom you create a new row).
230
231 === Container
232
233 A container is the content of a table’s cell. It holds an arbitrary amount of
234 windows and has a specific layout (default layout, stack layout or tabbed
235 layout). Containers can consume multiple table cells by modifying their
236 colspan/rowspan attribute.
237
238 === Client
239
240 A client is x11-speak for a window.
241
242 == List/queue macros
243
244 i3 makes heavy use of the list macros defined in BSD operating systems. To
245 ensure that the operating system on which i3 is compiled has all the expected
246 features, i3 comes with `include/queue.h`. On BSD systems, you can use man
247 `queue(3)`. On Linux, you have to use google (or read the source).
248
249 The lists used are `SLIST` (single linked lists), `CIRCLEQ` (circular
250 queues) and TAILQ (tail queues). Usually, only forward traversal is necessary,
251 so an `SLIST` works fine. If inserting elements at arbitrary positions or at
252 the end of a list is necessary, a `TAILQ` is used instead. However, for the
253 windows inside a container, a `CIRCLEQ` is necessary to go from the currently
254 selected window to the window above/below.
255
256 == Naming conventions
257
258 There is a row of standard variables used in many events. The following names
259 should be chosen for those:
260
261  * ``conn'' is the xcb_connection_t
262  * ``event'' is the event of the particular type
263  * ``container'' names a container
264  * ``client'' names a client, for example when using a +CIRCLEQ_FOREACH+
265
266 == Startup (src/mainx.c, main())
267
268  * Establish the xcb connection
269  * Check for XKB extension on the separate X connection
270  * Check for Xinerama screens
271  * Grab the keycodes for which bindings exist
272  * Manage all existing windows
273  * Enter the event loop
274
275 == Keybindings
276
277 === Grabbing the bindings
278
279 Grabbing the bindings is quite straight-forward. You pass X your combination of
280 modifiers and the keycode you want to grab and whether you want to grab them
281 actively or passively. Most bindings (everything except for bindings using
282 Mode_switch) are grabbed passively, that is, just the window manager gets the
283 event and cannot replay it.
284
285 We need to grab bindings that use Mode_switch actively because of a bug in X.
286 When the window manager receives the keypress/keyrelease event for an actively
287 grabbed keycode, it has to decide what to do with this event: It can either
288 replay it so that other applications get it or it can prevent other
289 applications from receiving it.
290
291 So, why do we need to grab keycodes actively? Because X does not set the
292 state-property of keypress/keyrelease events properly. The Mode_switch bit is
293 not set and we need to get it using XkbGetState. This means we cannot pass X
294 our combination of modifiers containing Mode_switch when grabbing the key and
295 therefore need to grab the keycode itself without any modifiers. This means,
296 if you bind Mode_switch + keycode 38 ("a"), i3 will grab keycode 38 ("a") and
297 check on each press of "a" if the Mode_switch bit is set using XKB. If yes, it
298 will handle the event, if not, it will replay the event.
299
300 === Handling a keypress
301
302 As mentioned in "Grabbing the bindings", upon a keypress event, i3 first gets
303 the correct state.
304
305 Then, it looks through all bindings and gets the one which matches the received
306 event.
307
308 The bound command is parsed directly in command mode.
309
310 == Manage windows (src/mainx.c, manage_window() and reparent_window())
311
312 `manage_window()` does some checks to decide whether the window should be
313 managed at all:
314
315  * Windows have to be mapped, that is, visible on screen
316  * The override_redirect must not be set. Windows with override_redirect shall
317    not be managed by a window manager
318
319 Afterwards, i3 gets the intial geometry and reparents the window (see
320 `reparent_window()`) if it wasn’t already managed.
321
322 Reparenting means that for each window which is reparented, a new window,
323 slightly larger than the original one, is created. The original window is then
324 reparented to the bigger one (called "frame").
325
326 After reparenting, the window type (`_NET_WM_WINDOW_TYPE`) is checked to see
327 whether this window is a dock (`_NET_WM_WINDOW_TYPE_DOCK`), like dzen2 for
328 example. Docks are handled differently, they don’t have decorations and are not
329 assigned to a specific container. Instead, they are positioned at the bottom
330 of the screen. To get the height which needsd to be reserved for the window,
331 the `_NET_WM_STRUT_PARTIAL` property is used.
332
333 Furthermore, the list of assignments (to other workspaces, which may be on
334 other screens) is checked. If the window matches one of the user’s criteria,
335 it may either be put in floating mode or moved to a different workspace. If the
336 target workspace is not visible, the window will not be mapped.
337
338 == What happens when an application is started?
339
340 i3 does not care for applications. All it notices is when new windows are
341 mapped (see `src/handlers.c`, `handle_map_request()`). The window is then
342 reparented (see section "Manage windows").
343
344 After reparenting the window, `render_layout()` is called which renders the
345 internal layout table. The new window has been placed in the currently focused
346 container and therefore the new window and the old windows (if any) need to be
347 moved/resized so that the currently active layout (default/stacking/tabbed mode)
348 is rendered correctly. To move/resize windows, a window is ``configured'' in
349 X11-speak.
350
351 Some applications, such as MPlayer obviously assume the window manager is
352 stupid and try to configure their windows by themselves. This generates an
353 event called configurerequest. i3 handles these events and tells the window the
354 size it had before the configurerequest (with the exception of not yet mapped
355 windows, which get configured like they want to, and floating windows, which
356 can reconfigure themselves).
357
358 == _NET_WM_STATE
359
360 Only the _NET_WM_STATE_FULLSCREEN atom is handled. It calls
361 ``toggle_fullscreen()'' for the specific client which just configures the
362 client to use the whole screen on which it currently is. Also, it is set as
363 fullscreen_client for the i3Screen.
364
365 == WM_NAME
366
367 When the WM_NAME property of a window changes, its decoration (containing the
368 title) is re-rendered. Note that WM_NAME is in COMPOUND_TEXT encoding which is
369 totally uncommon and cumbersome. Therefore, the _NET_WM_NAME atom will be used
370 if present.
371
372 == _NET_WM_NAME
373
374 Like WM_NAME, this atom contains the title of a window. However, _NET_WM_NAME
375 is encoded in UTF-8. i3 will recode it to UCS-2 in order to be able to pass it
376 to X. Using an appropriate font (ISO-10646), you can see most special
377 characters (every special character contained in your font).
378
379 == Size hints
380
381 Size hints specify the minimum/maximum size for a given window as well as its
382 aspect ratio.  This is important for clients like mplayer, who only set the
383 aspect ratio and resize their window to be as small as possible (but only with
384 some video outputs, for example in Xv, while when using x11, mplayer does the
385 necessary centering for itself).
386
387 So, when an aspect ratio was specified, i3 adjusts the height of the window
388 until the size maintains the correct aspect ratio. For the code to do this, see
389 src/layout.c, function resize_client().
390
391 == Rendering (src/layout.c, render_layout() and render_container())
392
393 There are several entry points to rendering: `render_layout()`,
394 `render_workspace()` and `render_container()`. The former one calls
395 `render_workspace()` for every screen, which in turn will call
396 `render_container()` for every container inside its layout table. Therefore, if
397 you need to render only a single container, for example because a window was
398 removed, added or changed its title, you should directly call
399 render_container().
400
401 Rendering consists of two steps: In the first one, in `render_workspace()`, each
402 container gets its position (screen offset + offset in the table) and size
403 (container's width times colspan/rowspan). Then, `render_container()` is called,
404 which takes different approaches, depending on the mode the container is in:
405
406 === Common parts
407
408 On the frame (the window which was created around the client’s window for the
409 decorations), a black rectangle is drawn as a background for windows like
410 MPlayer, which do not completely fit into the frame.
411
412 === Default mode
413
414 Each clients gets the container’s width and an equal amount of height.
415
416 === Stack mode
417
418 In stack mode, a window containing the decorations of all windows inside the
419 container is placed at the top. The currently focused window is then given the
420 whole remaining space.
421
422 === Tabbed mode
423
424 Tabbed mode is like stack mode, except that the window decorations are drawn
425 in one single line at the top of the container.
426
427 === Window decorations
428
429 The window decorations consist of a rectangle in the appropriate color (depends
430 on whether this window is the currently focused one, the last focused one in a
431 not focused container or not focused at all) forming the background.
432 Afterwards, two lighter lines are drawn and the last step is drawing the
433 window’s title (see WM_NAME) onto it.
434
435 === Fullscreen windows
436
437 For fullscreen windows, the `rect` (x, y, width, height) is not changed to
438 allow the client to easily go back to its previous position. Instead,
439 fullscreen windows are skipped when rendering.
440
441 === Resizing containers
442
443 By clicking and dragging the border of a container, you can resize the whole
444 column (respectively row) which this container is in. This is necessary to keep
445 the table layout working and consistent.
446
447 The resizing works similarly to the resizing of floating windows or movement of
448 floating windows:
449
450 * A new, invisible window with the size of the root window is created
451   (+grabwin+)
452 * Another window, 2px width and as high as your screen (or vice versa for
453   horizontal resizing) is created. Its background color is the border color and
454   it is only there to inform the user how big the container will be (it
455   creates the impression of dragging the border out of the container).
456 * The +drag_pointer+ function of +src/floating.c+ is called to grab the pointer
457   and enter its own event loop which will pass all events (expose events) but
458   motion notify events. This function then calls the specified callback
459   (+resize_callback+) which does some boundary checking and moves the helper
460   window. As soon as the mouse button is released, this loop will be
461   terminated.
462 * The new width_factor for each involved column (respectively row) will be
463   calculated.
464
465 == User commands / commandmode (src/commands.c)
466
467 Like in vim, you can control i3 using commands. They are intended to be a
468 powerful alternative to lots of shortcuts, because they can be combined. There
469 are a few special commands, which are the following:
470
471 exec <command>::
472 Starts the given command by passing it to `/bin/sh`.
473
474 restart::
475 Restarts i3 by executing `argv[0]` (the path with which you started i3) without
476 forking.
477
478 w::
479 "With". This is used to select a bunch of windows. Currently, only selecting
480 the whole container in which the window is in, is supported by specifying "w".
481
482 f, s, d::
483 Toggle fullscreen, stacking, default mode for the current window/container.
484
485 The other commands are to be combined with a direction. The directions are h,
486 j, k and l, like in vim (h = left, j = down, k = up, l = right). When you just
487 specify the direction keys, i3 will move the focus in that direction. You can
488 provide "m" or "s" before the direction to move a window respectively or snap.
489
490 == Moving containers
491
492 The movement code is pretty delicate. You need to consider all cases before
493 making any changes or before being able to fully understand how it works.
494
495 === Case 1: Moving inside the same container
496
497 The reference layout for this case is a single workspace in horizontal
498 orientation with two containers on it. Focus is on the left container (1).
499
500
501 [width="15%",cols="^,^"]
502 |========
503 | 1 | 2
504 |========
505
506 When moving the left window to the right (command +move right+), tree_move will
507 look for a container with horizontal orientation and finds the parent of the
508 left container, that is, the workspace. Afterwards, it runs the code branch
509 commented with "the easy case": it calls TAILQ_NEXT to get the container right
510 of the current one and swaps both containers.
511
512 === Case 2: Move a container into a split container
513
514 The reference layout for this case is a horizontal workspace with two
515 containers. The right container is a v-split with two containers. Focus is on
516 the left container (1).
517
518 [width="15%",cols="^,^"]
519 |========
520 1.2+^.^| 1 | 2
521 | 3
522 |========
523
524 When moving to the right (command +move right+), i3 will work like in case 1
525 ("the easy case"). However, as the right container is not a leaf container, but
526 a v-split, the left container (1) will be inserted at the right position (below
527 2, assuming that 2 is focused inside the v-split) by calling +insert_con_into+.
528
529 +insert_con_into+ detaches the container from its parent and inserts it
530 before/after the given target container. Afterwards, the on_remove_child
531 callback is called on the old parent container which will then be closed, if
532 empty.
533
534 Afterwards, +con_focus+ will be called to fix the focus stack and the tree will
535 be flattened.
536
537 === Case 3: Moving to non-existant top/bottom
538
539 Like in case 1, the reference layout for this case is a single workspace in
540 horizontal orientation with two containers on it. Focus is on the left
541 container:
542
543 [width="15%",cols="^,^"]
544 |========
545 | 1 | 2
546 |========
547
548 This time however, the command is +move up+ or +move down+. tree_move will look
549 for a container with vertical orientation. As it will not find any,
550 +same_orientation+ is NULL and therefore i3 will perform a forced orientation
551 change on the workspace by creating a new h-split container, moving the
552 workspace contents into it and then changing the workspace orientation to
553 vertical. Now it will again search for parent containers with vertical
554 orientation and it will find the workspace.
555
556 This time, the easy case code path will not be run as we are not moving inside
557 the same container. Instead, +insert_con_into+ will be called with the focused
558 container and the container above/below the current one (on the level of
559 +same_orientation+).
560
561 Now, +con_focus+ will be called to fix the focus stack and the tree will be
562 flattened.
563
564 === Case 4: Moving to existant top/bottom
565
566 The reference layout for this case is a vertical workspace with two containers.
567 The bottom one is a h-split containing two containers (1 and 2). Focus is on
568 the bottom left container (1).
569
570 [width="15%",cols="^,^"]
571 |========
572 2+| 3
573 | 1 | 2
574 |========
575
576 This case is very much like case 3, only this time the forced workspace
577 orientation change does not need to be performed because the workspace already
578 is in vertical orientation.
579
580 === Case 5: Moving in one-child h-split
581
582 The reference layout for this case is a horizontal workspace with two
583 containers having a v-split on the left side with a one-child h-split on the
584 bottom. Focus is on the bottom left container (2(h)):
585
586 [width="15%",cols="^,^"]
587 |========
588 | 1 1.2+^.^| 3
589 | 2(h)
590 |========
591
592 In this case, +same_orientation+ will be set to the h-split container around
593 the focused container. However, when trying the easy case, the next/previous
594 container +swap+ will be NULL. Therefore, i3 will search again for a
595 +same_orientation+ container, this time starting from the parent of the h-split
596 container.
597
598 After determining a new +same_orientation+ container (if it is NULL, the
599 orientation will be force-changed), this case is equivalent to case 2 or case
600 4.
601
602
603 === Case 6: Floating containers
604
605 The reference layout for this case is a horizontal workspace with two
606 containers plus one floating h-split container. Focus is on the floating
607 container.
608
609 TODO: nice illustration. table not possible?
610
611 When moving up/down, the container needs to leave the floating container and it
612 needs to be placed on the workspace (at workspace level). This is accomplished
613 by calling the function +attach_to_workspace+.
614
615 == Click handling
616
617 Without much ado, here is the list of cases which need to be considered:
618
619 * click to focus (tiling + floating) and raise (floating)
620 * click to focus/raise when in stacked/tabbed mode
621 * floating_modifier + left mouse button to drag a floating con
622 * floating_modifier + right mouse button to resize a floating con
623 * click on decoration in a floating con to either initiate a resize (if there
624   is more than one child in the floating con) or to drag the
625   floating con (if it’s the one at the top).
626 * click on border in a floating con to resize the floating con
627 * floating_modifier + right mouse button to resize a tiling con
628 * click on border/decoration to resize a tiling con
629
630 == Gotchas
631
632 * Forgetting to call `xcb_flush(conn);` after sending a request. This usually
633   leads to code which looks like it works fine but which does not work under
634   certain conditions.
635
636 == Using git / sending patches
637
638 For a short introduction into using git, see
639 http://www.spheredev.org/wiki/Git_for_the_lazy or, for more documentation, see
640 http://git-scm.com/documentation
641
642 When you want to send a patch because you fixed a bug or implemented a cool
643 feature (please talk to us before working on features to see whether they are
644 maybe already implemented, not possible for some some reason, or don’t fit
645 into the concept), please use git to create a patchfile.
646
647 First of all, update your working copy to the latest version of the master
648 branch:
649
650 --------
651 git pull
652 --------
653
654 Afterwards, make the necessary changes for your bugfix/feature. Then, review
655 the changes using +git diff+ (you might want to enable colors in the diff using
656 +git config diff.color auto+).  When you are definitely done, use +git commit
657 -a+ to commit all changes you’ve made.
658
659 Then, use the following command to generate a patchfile which we can directly
660 apply to the branch, preserving your commit message and name:
661
662 -----------------------
663 git format-patch origin
664 -----------------------
665
666 Just send us the generated file via email.