From 0a61ad36cbf57920d4027d510ef4e0b7d48d1dfd Mon Sep 17 00:00:00 2001 From: Elias Almqvist Date: Tue, 26 Mar 2024 22:03:00 +0100 Subject: [PATCH] Formatting (fixed retarded style from prev devs) --- src/.clang-format | 24 + src/.editorconfig | 12 + src/IPCClient.c | 89 ++- src/IPCClient.h | 16 +- src/config.def.h | 267 +++---- src/config.h | 69 +- src/drw.c | 187 +++-- src/drw.h | 19 +- src/dwm-msg.c | 799 ++++++++++---------- src/dwm.c | 1393 ++++++++++++++++------------------ src/ipc.c | 1809 ++++++++++++++++++++++----------------------- src/ipc.h | 111 +-- src/transient.c | 6 +- src/util.c | 229 +++--- src/util.h | 6 +- src/yajl_dumps.c | 173 ++--- src/yajl_dumps.h | 40 +- 17 files changed, 2555 insertions(+), 2694 deletions(-) create mode 100644 src/.clang-format create mode 100644 src/.editorconfig diff --git a/src/.clang-format b/src/.clang-format new file mode 100644 index 0000000..0902e6d --- /dev/null +++ b/src/.clang-format @@ -0,0 +1,24 @@ +--- +BasedOnStyle: LLVM +IndentWidth: 4 +AllowShortFunctionsOnASingleLine: 'None' +AllowShortIfStatementsOnASingleLine: 'Never' +AlignAfterOpenBracket: 'Align' +AlignConsecutiveAssignments: 'Consecutive' +AlignConsecutiveBitFields: 'Consecutive' +AlignConsecutiveMacros: 'Consecutive' +AlignOperands: 'AlignAfterOperator' +AlignTrailingComments: true +AllowAllArgumentsOnNextLine: false +AllowShortBlocksOnASingleLine: 'Empty' +AllowShortLoopsOnASingleLine: false +BreakBeforeBraces: 'Attach' +BreakBeforeBinaryOperators: 'NonAssignment' +SpaceAfterCStyleCast: true +SpaceAfterLogicalNot: false +SpaceBeforeParens: 'ControlStatements' +TabWidth: 4 +UseTab: 'ForIndentation' +ColumnLimit: 78 +UseCRLF: false +DeriveLineEnding: false diff --git a/src/.editorconfig b/src/.editorconfig new file mode 100644 index 0000000..88812da --- /dev/null +++ b/src/.editorconfig @@ -0,0 +1,12 @@ +# This file is for unifying the coding style for different editors and IDEs +# See editorconfig.org + +root = true + +[*.{c,h,cpp,hpp}] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/src/IPCClient.c b/src/IPCClient.c index 0d3eefb..cf012bd 100644 --- a/src/IPCClient.c +++ b/src/IPCClient.c @@ -5,62 +5,59 @@ #include "util.h" -IPCClient * -ipc_client_new(int fd) -{ - IPCClient *c = (IPCClient *)malloc(sizeof(IPCClient)); +IPCClient *ipc_client_new(int fd) { + IPCClient *c = (IPCClient *) malloc(sizeof(IPCClient)); - if (c == NULL) return NULL; + if (c == NULL) + return NULL; - // Initialize struct - memset(&c->event, 0, sizeof(struct epoll_event)); + // Initialize struct + memset(&c->event, 0, sizeof(struct epoll_event)); - c->buffer_size = 0; - c->buffer = NULL; - c->fd = fd; - c->event.data.fd = fd; - c->next = NULL; - c->prev = NULL; - c->subscriptions = 0; + c->buffer_size = 0; + c->buffer = NULL; + c->fd = fd; + c->event.data.fd = fd; + c->next = NULL; + c->prev = NULL; + c->subscriptions = 0; - return c; + return c; } -void -ipc_list_add_client(IPCClientList *list, IPCClient *nc) -{ - DEBUG("Adding client with fd %d to list\n", nc->fd); - - if (*list == NULL) { - // List is empty, point list at first client - *list = nc; - } else { - IPCClient *c; - // Go to last client in list - for (c = *list; c && c->next; c = c->next) - ; - c->next = nc; - nc->prev = c; - } +void ipc_list_add_client(IPCClientList *list, IPCClient *nc) { + DEBUG("Adding client with fd %d to list\n", nc->fd); + + if (*list == NULL) { + // List is empty, point list at first client + *list = nc; + } else { + IPCClient *c; + // Go to last client in list + for (c = *list; c && c->next; c = c->next) + ; + c->next = nc; + nc->prev = c; + } } -void -ipc_list_remove_client(IPCClientList *list, IPCClient *c) -{ - IPCClient *cprev = c->prev; - IPCClient *cnext = c->next; +void ipc_list_remove_client(IPCClientList *list, IPCClient *c) { + IPCClient *cprev = c->prev; + IPCClient *cnext = c->next; - if (cprev != NULL) cprev->next = c->next; - if (cnext != NULL) cnext->prev = c->prev; - if (c == *list) *list = c->next; + if (cprev != NULL) + cprev->next = c->next; + if (cnext != NULL) + cnext->prev = c->prev; + if (c == *list) + *list = c->next; } -IPCClient * -ipc_list_get_client(IPCClientList list, int fd) -{ - for (IPCClient *c = list; c; c = c->next) { - if (c->fd == fd) return c; - } +IPCClient *ipc_list_get_client(IPCClientList list, int fd) { + for (IPCClient *c = list; c; c = c->next) { + if (c->fd == fd) + return c; + } - return NULL; + return NULL; } diff --git a/src/IPCClient.h b/src/IPCClient.h index 307dfba..e84b289 100644 --- a/src/IPCClient.h +++ b/src/IPCClient.h @@ -11,15 +11,15 @@ typedef struct IPCClient IPCClient; * linked list */ struct IPCClient { - int fd; - int subscriptions; + int fd; + int subscriptions; - char *buffer; - uint32_t buffer_size; + char *buffer; + uint32_t buffer_size; - struct epoll_event event; - IPCClient *next; - IPCClient *prev; + struct epoll_event event; + IPCClient *next; + IPCClient *prev; }; typedef IPCClient *IPCClientList; @@ -58,4 +58,4 @@ void ipc_list_remove_client(IPCClientList *list, IPCClient *c); */ IPCClient *ipc_list_get_client(IPCClientList list, int fd); -#endif // IPC_CLIENT_H_ +#endif // IPC_CLIENT_H_ diff --git a/src/config.def.h b/src/config.def.h index b567930..fd76252 100644 --- a/src/config.def.h +++ b/src/config.def.h @@ -1,162 +1,169 @@ /* See LICENSE file for copyright and license details. */ /* appearance */ -static const unsigned int borderpx = 1; /* border pixel of windows */ -static const unsigned int gappx = 5; /* gaps between windows */ -static const unsigned int snap = 32; /* snap pixel */ -static const int showbar = 1; /* 0 means no bar */ -static const int topbar = 1; /* 0 means bottom bar */ -static const int usealtbar = 1; /* 1 means use non-dwm status bar */ -static const char *altbarclass = "Polybar"; /* Alternate bar class name */ -static const char *alttrayname = "tray"; /* Polybar tray instance name */ -static const char *altbarcmd = "$HOME/bar.sh"; /* Alternate bar launch command */ -static const char *fonts[] = { "monospace:size=10" }; -static const char dmenufont[] = "monospace:size=10"; -static const char col_gray1[] = "#222222"; -static const char col_gray2[] = "#444444"; -static const char col_gray3[] = "#bbbbbb"; -static const char col_gray4[] = "#eeeeee"; -static const char col_cyan[] = "#005577"; -static const char *colors[][3] = { - /* fg bg border */ - [SchemeNorm] = { col_gray3, col_gray1, col_gray2 }, - [SchemeSel] = { col_gray4, col_cyan, col_cyan }, +static const unsigned int borderpx = 1; /* border pixel of windows */ +static const unsigned int gappx = 5; /* gaps between windows */ +static const unsigned int snap = 32; /* snap pixel */ +static const int showbar = 1; /* 0 means no bar */ +static const int topbar = 1; /* 0 means bottom bar */ +static const int usealtbar = 1; /* 1 means use non-dwm status bar */ +static const char *altbarclass = "Polybar"; /* Alternate bar class name */ +static const char *alttrayname = "tray"; /* Polybar tray instance name */ +static const char *altbarcmd = + "$HOME/bar.sh"; /* Alternate bar launch command */ +static const char *fonts[] = {"monospace:size=10"}; +static const char dmenufont[] = "monospace:size=10"; +static const char col_gray1[] = "#222222"; +static const char col_gray2[] = "#444444"; +static const char col_gray3[] = "#bbbbbb"; +static const char col_gray4[] = "#eeeeee"; +static const char col_cyan[] = "#005577"; +static const char *colors[][3] = { + /* fg bg border */ + [SchemeNorm] = {col_gray3, col_gray1, col_gray2}, + [SchemeSel] = {col_gray4, col_cyan, col_cyan}, }; /* tagging */ -static const char *tags[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9" }; +static const char *tags[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9"}; static const Rule rules[] = { - /* xprop(1): - * WM_CLASS(STRING) = instance, class - * WM_NAME(STRING) = title - */ - /* class instance title tags mask isfloating monitor */ - { "Gimp", NULL, NULL, 0, 1, -1 }, - { "Firefox", NULL, NULL, 1 << 8, 0, -1 }, + /* xprop(1): + * WM_CLASS(STRING) = instance, class + * WM_NAME(STRING) = title + */ + /* class instance title tags mask isfloating monitor + */ + {"Gimp", NULL, NULL, 0, 1, -1}, + {"Firefox", NULL, NULL, 1 << 8, 0, -1}, }; /* layout(s) */ -static const float mfact = 0.55; /* factor of master area size [0.05..0.95] */ -static const int nmaster = 1; /* number of clients in master area */ -static const int resizehints = 1; /* 1 means respect size hints in tiled resizals */ +static const float mfact = 0.55; /* factor of master area size [0.05..0.95] */ +static const int nmaster = 1; /* number of clients in master area */ +static const int resizehints = + 1; /* 1 means respect size hints in tiled resizals */ static const Layout layouts[] = { - /* symbol arrange function */ - { "[]=", tile }, /* first entry is default */ - { "><>", NULL }, /* no layout function means floating behavior */ - { "[M]", monocle }, + /* symbol arrange function */ + {"[]=", tile}, /* first entry is default */ + {"><>", NULL}, /* no layout function means floating behavior */ + {"[M]", monocle}, }; /* key definitions */ #define MODKEY Mod1Mask -#define TAGKEYS(KEY,TAG) \ - { MODKEY, KEY, view, {.ui = 1 << TAG} }, \ - { MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \ - { MODKEY|ShiftMask, KEY, tag, {.ui = 1 << TAG} }, \ - { MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} }, +#define TAGKEYS(KEY, TAG) \ + {MODKEY, KEY, view, {.ui = 1 << TAG}}, \ + {MODKEY | ControlMask, KEY, toggleview, {.ui = 1 << TAG}}, \ + {MODKEY | ShiftMask, KEY, tag, {.ui = 1 << TAG}}, \ + {MODKEY | ControlMask | ShiftMask, \ + KEY, \ + toggletag, \ + {.ui = 1 << TAG}}, /* helper for spawning shell commands in the pre dwm-5.0 fashion */ -#define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } } +#define SHCMD(cmd) \ + { \ + .v = (const char *[]) { \ + "/bin/sh", "-c", cmd, NULL \ + } \ + } #define STATUSBAR "dwmblocks" /* commands */ -static char dmenumon[2] = "0"; /* component of dmenucmd, manipulated in spawn() */ -static const char *dmenucmd[] = { "dmenu_run", "-m", dmenumon, "-fn", dmenufont, "-nb", col_gray1, "-nf", col_gray3, "-sb", col_cyan, "-sf", col_gray4, NULL }; -static const char *termcmd[] = { "st", NULL }; +static char dmenumon[2] = + "0"; /* component of dmenucmd, manipulated in spawn() */ +static const char *dmenucmd[] = { + "dmenu_run", "-m", dmenumon, "-fn", dmenufont, "-nb", col_gray1, "-nf", + col_gray3, "-sb", col_cyan, "-sf", col_gray4, NULL}; +static const char *termcmd[] = {"st", NULL}; static Key keys[] = { - /* modifier key function argument */ - { MODKEY, XK_p, spawn, {.v = dmenucmd } }, - { MODKEY|ShiftMask, XK_Return, spawn, {.v = termcmd } }, - { MODKEY, XK_b, togglebar, {0} }, - { MODKEY, XK_j, focusstack, {.i = +1 } }, - { MODKEY, XK_k, focusstack, {.i = -1 } }, - { MODKEY, XK_i, incnmaster, {.i = +1 } }, - { MODKEY, XK_d, incnmaster, {.i = -1 } }, - { MODKEY, XK_h, setmfact, {.f = -0.05} }, - { MODKEY, XK_l, setmfact, {.f = +0.05} }, - { MODKEY, XK_Return, zoom, {0} }, - { MODKEY, XK_Down, moveresize, {.v = "0x 25y 0w 0h" } }, - { MODKEY, XK_Up, moveresize, {.v = "0x -25y 0w 0h" } }, - { MODKEY, XK_Right, moveresize, {.v = "25x 0y 0w 0h" } }, - { MODKEY, XK_Left, moveresize, {.v = "-25x 0y 0w 0h" } }, - { MODKEY|ShiftMask, XK_Down, moveresize, {.v = "0x 0y 0w 25h" } }, - { MODKEY|ShiftMask, XK_Up, moveresize, {.v = "0x 0y 0w -25h" } }, - { MODKEY|ShiftMask, XK_Right, moveresize, {.v = "0x 0y 25w 0h" } }, - { MODKEY|ShiftMask, XK_Left, moveresize, {.v = "0x 0y -25w 0h" } }, - { MODKEY|ControlMask, XK_Up, moveresizeedge, {.v = "t"} }, - { MODKEY|ControlMask, XK_Down, moveresizeedge, {.v = "b"} }, - { MODKEY|ControlMask, XK_Left, moveresizeedge, {.v = "l"} }, - { MODKEY|ControlMask, XK_Right, moveresizeedge, {.v = "r"} }, - { MODKEY|ControlMask|ShiftMask, XK_Up, moveresizeedge, {.v = "T"} }, - { MODKEY|ControlMask|ShiftMask, XK_Down, moveresizeedge, {.v = "B"} }, - { MODKEY|ControlMask|ShiftMask, XK_Left, moveresizeedge, {.v = "L"} }, - { MODKEY|ControlMask|ShiftMask, XK_Right, moveresizeedge, {.v = "R"} }, - { MODKEY, XK_Tab, view, {0} }, - { MODKEY|ShiftMask, XK_c, killclient, {0} }, - { MODKEY, XK_t, setlayout, {.v = &layouts[0]} }, - { MODKEY, XK_f, setlayout, {.v = &layouts[1]} }, - { MODKEY, XK_m, setlayout, {.v = &layouts[2]} }, - { MODKEY, XK_space, setlayout, {0} }, - { MODKEY|ShiftMask, XK_space, togglefloating, {0} }, - { MODKEY|ShiftMask, XK_f, togglefullscr, {0} }, - { MODKEY, XK_0, view, {.ui = ~0 } }, - { MODKEY|ShiftMask, XK_0, tag, {.ui = ~0 } }, - { MODKEY, XK_comma, focusmon, {.i = -1 } }, - { MODKEY, XK_period, focusmon, {.i = +1 } }, - { MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1 } }, - { MODKEY|ShiftMask, XK_period, tagmon, {.i = +1 } }, - { MODKEY, XK_minus, setgaps, {.i = -1 } }, - { MODKEY, XK_equal, setgaps, {.i = +1 } }, - { MODKEY|ShiftMask, XK_equal, setgaps, {.i = 0 } }, - TAGKEYS( XK_1, 0) - TAGKEYS( XK_2, 1) - TAGKEYS( XK_3, 2) - TAGKEYS( XK_4, 3) - TAGKEYS( XK_5, 4) - TAGKEYS( XK_6, 5) - TAGKEYS( XK_7, 6) - TAGKEYS( XK_8, 7) - TAGKEYS( XK_9, 8) - { MODKEY|ShiftMask, XK_q, quit, {0} }, + /* modifier key function argument */ + {MODKEY, XK_p, spawn, {.v = dmenucmd}}, + {MODKEY | ShiftMask, XK_Return, spawn, {.v = termcmd}}, + {MODKEY, XK_b, togglebar, {0}}, + {MODKEY, XK_j, focusstack, {.i = +1}}, + {MODKEY, XK_k, focusstack, {.i = -1}}, + {MODKEY, XK_i, incnmaster, {.i = +1}}, + {MODKEY, XK_d, incnmaster, {.i = -1}}, + {MODKEY, XK_h, setmfact, {.f = -0.05}}, + {MODKEY, XK_l, setmfact, {.f = +0.05}}, + {MODKEY, XK_Return, zoom, {0}}, + {MODKEY, XK_Down, moveresize, {.v = "0x 25y 0w 0h"}}, + {MODKEY, XK_Up, moveresize, {.v = "0x -25y 0w 0h"}}, + {MODKEY, XK_Right, moveresize, {.v = "25x 0y 0w 0h"}}, + {MODKEY, XK_Left, moveresize, {.v = "-25x 0y 0w 0h"}}, + {MODKEY | ShiftMask, XK_Down, moveresize, {.v = "0x 0y 0w 25h"}}, + {MODKEY | ShiftMask, XK_Up, moveresize, {.v = "0x 0y 0w -25h"}}, + {MODKEY | ShiftMask, XK_Right, moveresize, {.v = "0x 0y 25w 0h"}}, + {MODKEY | ShiftMask, XK_Left, moveresize, {.v = "0x 0y -25w 0h"}}, + {MODKEY | ControlMask, XK_Up, moveresizeedge, {.v = "t"}}, + {MODKEY | ControlMask, XK_Down, moveresizeedge, {.v = "b"}}, + {MODKEY | ControlMask, XK_Left, moveresizeedge, {.v = "l"}}, + {MODKEY | ControlMask, XK_Right, moveresizeedge, {.v = "r"}}, + {MODKEY | ControlMask | ShiftMask, XK_Up, moveresizeedge, {.v = "T"}}, + {MODKEY | ControlMask | ShiftMask, XK_Down, moveresizeedge, {.v = "B"}}, + {MODKEY | ControlMask | ShiftMask, XK_Left, moveresizeedge, {.v = "L"}}, + {MODKEY | ControlMask | ShiftMask, XK_Right, moveresizeedge, {.v = "R"}}, + {MODKEY, XK_Tab, view, {0}}, + {MODKEY | ShiftMask, XK_c, killclient, {0}}, + {MODKEY, XK_t, setlayout, {.v = &layouts[0]}}, + {MODKEY, XK_f, setlayout, {.v = &layouts[1]}}, + {MODKEY, XK_m, setlayout, {.v = &layouts[2]}}, + {MODKEY, XK_space, setlayout, {0}}, + {MODKEY | ShiftMask, XK_space, togglefloating, {0}}, + {MODKEY | ShiftMask, XK_f, togglefullscr, {0}}, + {MODKEY, XK_0, view, {.ui = ~0}}, + {MODKEY | ShiftMask, XK_0, tag, {.ui = ~0}}, + {MODKEY, XK_comma, focusmon, {.i = -1}}, + {MODKEY, XK_period, focusmon, {.i = +1}}, + {MODKEY | ShiftMask, XK_comma, tagmon, {.i = -1}}, + {MODKEY | ShiftMask, XK_period, tagmon, {.i = +1}}, + {MODKEY, XK_minus, setgaps, {.i = -1}}, + {MODKEY, XK_equal, setgaps, {.i = +1}}, + {MODKEY | ShiftMask, XK_equal, setgaps, {.i = 0}}, + TAGKEYS(XK_1, 0) TAGKEYS(XK_2, 1) TAGKEYS(XK_3, 2) TAGKEYS(XK_4, 3) + TAGKEYS(XK_5, 4) TAGKEYS(XK_6, 5) TAGKEYS(XK_7, 6) TAGKEYS(XK_8, 7) + TAGKEYS(XK_9, 8){MODKEY | ShiftMask, XK_q, quit, {0}}, }; /* button definitions */ -/* click can be ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */ +/* click can be ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, + * ClkClientWin, or ClkRootWin */ static Button buttons[] = { - /* click event mask button function argument */ - { ClkLtSymbol, 0, Button1, setlayout, {0} }, - { ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]} }, - { ClkWinTitle, 0, Button2, zoom, {0} }, - { ClkStatusText, 0, Button1, sigstatusbar, {.i = 1} }, - { ClkStatusText, 0, Button2, sigstatusbar, {.i = 2} }, - { ClkStatusText, 0, Button3, sigstatusbar, {.i = 3} }, - { ClkClientWin, MODKEY, Button1, movemouse, {0} }, - { ClkClientWin, MODKEY, Button2, togglefloating, {0} }, - { ClkClientWin, MODKEY, Button3, resizemouse, {0} }, - { ClkTagBar, 0, Button1, view, {0} }, - { ClkTagBar, 0, Button3, toggleview, {0} }, - { ClkTagBar, MODKEY, Button1, tag, {0} }, - { ClkTagBar, MODKEY, Button3, toggletag, {0} }, + /* click event mask button function argument + */ + {ClkLtSymbol, 0, Button1, setlayout, {0}}, + {ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]}}, + {ClkWinTitle, 0, Button2, zoom, {0}}, + {ClkStatusText, 0, Button1, sigstatusbar, {.i = 1}}, + {ClkStatusText, 0, Button2, sigstatusbar, {.i = 2}}, + {ClkStatusText, 0, Button3, sigstatusbar, {.i = 3}}, + {ClkClientWin, MODKEY, Button1, movemouse, {0}}, + {ClkClientWin, MODKEY, Button2, togglefloating, {0}}, + {ClkClientWin, MODKEY, Button3, resizemouse, {0}}, + {ClkTagBar, 0, Button1, view, {0}}, + {ClkTagBar, 0, Button3, toggleview, {0}}, + {ClkTagBar, MODKEY, Button1, tag, {0}}, + {ClkTagBar, MODKEY, Button3, toggletag, {0}}, }; -static const char *ipcsockpath = "/tmp/dwm.sock"; +static const char *ipcsockpath = "/tmp/dwm.sock"; static IPCCommand ipccommands[] = { - IPCCOMMAND( view, 1, {ARG_TYPE_UINT} ), - IPCCOMMAND( toggleview, 1, {ARG_TYPE_UINT} ), - IPCCOMMAND( tag, 1, {ARG_TYPE_UINT} ), - IPCCOMMAND( toggletag, 1, {ARG_TYPE_UINT} ), - IPCCOMMAND( tagmon, 1, {ARG_TYPE_UINT} ), - IPCCOMMAND( focusmon, 1, {ARG_TYPE_SINT} ), - IPCCOMMAND( focusstack, 1, {ARG_TYPE_SINT} ), - IPCCOMMAND( zoom, 1, {ARG_TYPE_NONE} ), - IPCCOMMAND( incnmaster, 1, {ARG_TYPE_SINT} ), - IPCCOMMAND( killclient, 1, {ARG_TYPE_SINT} ), - IPCCOMMAND( togglefloating, 1, {ARG_TYPE_NONE} ), - IPCCOMMAND( setmfact, 1, {ARG_TYPE_FLOAT} ), - IPCCOMMAND( setlayoutsafe, 1, {ARG_TYPE_PTR} ), - IPCCOMMAND( quit, 1, {ARG_TYPE_NONE} ) -}; - + IPCCOMMAND(view, 1, {ARG_TYPE_UINT}), + IPCCOMMAND(toggleview, 1, {ARG_TYPE_UINT}), + IPCCOMMAND(tag, 1, {ARG_TYPE_UINT}), + IPCCOMMAND(toggletag, 1, {ARG_TYPE_UINT}), + IPCCOMMAND(tagmon, 1, {ARG_TYPE_UINT}), + IPCCOMMAND(focusmon, 1, {ARG_TYPE_SINT}), + IPCCOMMAND(focusstack, 1, {ARG_TYPE_SINT}), + IPCCOMMAND(zoom, 1, {ARG_TYPE_NONE}), + IPCCOMMAND(incnmaster, 1, {ARG_TYPE_SINT}), + IPCCOMMAND(killclient, 1, {ARG_TYPE_SINT}), + IPCCOMMAND(togglefloating, 1, {ARG_TYPE_NONE}), + IPCCOMMAND(setmfact, 1, {ARG_TYPE_FLOAT}), + IPCCOMMAND(setlayoutsafe, 1, {ARG_TYPE_PTR}), + IPCCOMMAND(quit, 1, {ARG_TYPE_NONE})}; diff --git a/src/config.h b/src/config.h index 96cb827..a3b83af 100644 --- a/src/config.h +++ b/src/config.h @@ -4,40 +4,40 @@ #define STATUSBAR "dwmblocks" /* appearance */ -static const unsigned int borderpx = 0; /* border pixel of windows */ -static const unsigned int snap = 0; /* snap pixel (32)*/ -static const unsigned int gappx = 0; +static const unsigned int borderpx = 0; /* border pixel of windows */ +static const unsigned int snap = 0; /* snap pixel (32)*/ +static const unsigned int gappx = 0; static const unsigned int gapmodes[] = {20, 0}; -static const int showbar = 1; /* 0 means no bar */ -static const int topbar = 1; /* 0 means bottom bar */ -static const int barverticalpadding = 6; /* Vertical bar padding */ -static const int usealtbar = 0; /* 1 means use non-dwm status bar */ +static const int showbar = 1; /* 0 means no bar */ +static const int topbar = 1; /* 0 means bottom bar */ +static const int barverticalpadding = 6; /* Vertical bar padding */ +static const int usealtbar = 0; /* 1 means use non-dwm status bar */ static const char *altbarclass = "Polybar"; /* Alternate bar class name */ static const char *alttrayname = "tray"; /* Polybar tray instance name */ // static const char *altbarcmd = "$HOME/.config/polybar/launch"; /* // Alternate bar launch command */ -static const char *altbarcmd = ""; -static const char *fonts[] = {"Fira Code:size=11"}; +static const char *altbarcmd = ""; +static const char *fonts[] = {"Fira Code:size=11"}; static const char dmenufont[] = "Fira Code:size=15"; -static const char bg_color[] = "#181818"; -static const char bg_alt_color[] = "#111111"; -static const char text_color[] = "#bbc2cf"; -static const char selected_color[] = "#81a2be"; -static const char border_color_sel[] = "#444953"; +static const char bg_color[] = "#181818"; +static const char bg_alt_color[] = "#111111"; +static const char text_color[] = "#bbc2cf"; +static const char selected_color[] = "#81a2be"; +static const char border_color_sel[] = "#444953"; static const char border_color_norm[] = "#32373f"; static const char col_gray1[] = "#222222"; static const char col_gray2[] = "#444444"; static const char col_gray3[] = "#bbbbbb"; static const char col_gray4[] = "#eeeeee"; -static const char col_cyan[] = "#5f819d"; +static const char col_cyan[] = "#5f819d"; // static const char col_cyan[] = "#51afef"; static const char *colors[][3] = { /* fg bg border */ [SchemeNorm] = {text_color, bg_color, border_color_norm}, - [SchemeSel] = {col_cyan, bg_alt_color, border_color_sel}, + [SchemeSel] = {col_cyan, bg_alt_color, border_color_sel}, }; /* tagging */ @@ -73,29 +73,34 @@ static const Layout layouts[] = { /* key definitions */ #define MODKEY Mod4Mask -#define TAGKEYS(KEY, TAG) \ - {MODKEY, KEY, view, {.ui = 1 << TAG}}, \ - {MODKEY | ControlMask, KEY, toggleview, {.ui = 1 << TAG}}, \ - {MODKEY | ShiftMask, KEY, tag, {.ui = 1 << TAG}}, \ - {MODKEY | ControlMask | ShiftMask, KEY, toggletag, {.ui = 1 << TAG}}, +#define TAGKEYS(KEY, TAG) \ + {MODKEY, KEY, view, {.ui = 1 << TAG}}, \ + {MODKEY | ControlMask, KEY, toggleview, {.ui = 1 << TAG}}, \ + {MODKEY | ShiftMask, KEY, tag, {.ui = 1 << TAG}}, \ + {MODKEY | ControlMask | ShiftMask, \ + KEY, \ + toggletag, \ + {.ui = 1 << TAG}}, /* helper for spawning shell commands in the pre dwm-5.0 fashion */ -#define SHCMD(cmd) \ - { \ - .v = (const char *[]) { "/bin/sh", "-c", cmd, NULL } \ - } +#define SHCMD(cmd) \ + { \ + .v = (const char *[]) { \ + "/bin/sh", "-c", cmd, NULL \ + } \ + } /* commands */ static char dmenumon[2] = "0"; /* component of dmenucmd, manipulated in spawn() */ -static const char *dmenucmd[] = {"dmenu_run", "-m", dmenumon, "-p", - "Run $", "-z", "512", NULL}; -static const char *termcmd[] = {"alacritty", NULL}; -static const char *browsercmd[] = {"firefox", NULL}; +static const char *dmenucmd[] = {"dmenu_run", "-m", dmenumon, "-p", + "Run $", "-z", "512", NULL}; +static const char *termcmd[] = {"alacritty", NULL}; +static const char *browsercmd[] = {"firefox", NULL}; static const char *betterlockscreencmd[] = {"betterlockscreen", "--lock", "blur", NULL}; -static const char *screenshotcmd[] = {"flameshot", "gui", NULL}; -static const char *cmuspausecmd[] = {"cmus-remote", "--pause", NULL}; +static const char *screenshotcmd[] = {"flameshot", "gui", NULL}; +static const char *cmuspausecmd[] = {"cmus-remote", "--pause", NULL}; static Key keys[] = { /* modifier key @@ -197,7 +202,7 @@ static Button buttons[] = { {ClkTagBar, MODKEY, Button3, toggletag, {0}}, }; -static const char *ipcsockpath = "/tmp/dwm.sock"; +static const char *ipcsockpath = "/tmp/dwm.sock"; static IPCCommand ipccommands[] = { IPCCOMMAND(view, 1, {ARG_TYPE_UINT}), IPCCOMMAND(toggleview, 1, {ARG_TYPE_UINT}), diff --git a/src/drw.c b/src/drw.c index cd899f8..3d037d1 100644 --- a/src/drw.c +++ b/src/drw.c @@ -1,9 +1,9 @@ /* See LICENSE file for copyright and license details. */ +#include +#include #include #include #include -#include -#include #include "drw.h" #include "util.h" @@ -11,23 +11,21 @@ #define UTF_INVALID 0xFFFD #define UTF_SIZ 4 -static const unsigned char utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0}; -static const unsigned char utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8}; -static const long utfmin[UTF_SIZ + 1] = { 0, 0, 0x80, 0x800, 0x10000}; -static const long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF}; +static const unsigned char utfbyte[UTF_SIZ + 1] = {0x80, 0, 0xC0, 0xE0, 0xF0}; +static const unsigned char utfmask[UTF_SIZ + 1] = {0xC0, 0x80, 0xE0, 0xF0, + 0xF8}; +static const long utfmin[UTF_SIZ + 1] = {0, 0, 0x80, 0x800, 0x10000}; +static const long utfmax[UTF_SIZ + 1] = {0x10FFFF, 0x7F, 0x7FF, 0xFFFF, + 0x10FFFF}; -static long -utf8decodebyte(const char c, size_t *i) -{ +static long utf8decodebyte(const char c, size_t *i) { for (*i = 0; *i < (UTF_SIZ + 1); ++(*i)) - if (((unsigned char)c & utfmask[*i]) == utfbyte[*i]) - return (unsigned char)c & ~utfmask[*i]; + if (((unsigned char) c & utfmask[*i]) == utfbyte[*i]) + return (unsigned char) c & ~utfmask[*i]; return 0; } -static size_t -utf8validate(long *u, size_t i) -{ +static size_t utf8validate(long *u, size_t i) { if (!BETWEEN(*u, utfmin[i], utfmax[i]) || BETWEEN(*u, 0xD800, 0xDFFF)) *u = UTF_INVALID; for (i = 1; *u > utfmax[i]; ++i) @@ -35,9 +33,7 @@ utf8validate(long *u, size_t i) return i; } -static size_t -utf8decode(const char *c, long *u, size_t clen) -{ +static size_t utf8decode(const char *c, long *u, size_t clen) { size_t i, j, len, type; long udecoded; @@ -60,26 +56,23 @@ utf8decode(const char *c, long *u, size_t clen) return len; } -Drw * -drw_create(Display *dpy, int screen, Window root, unsigned int w, unsigned int h) -{ +Drw *drw_create(Display *dpy, int screen, Window root, unsigned int w, + unsigned int h) { Drw *drw = ecalloc(1, sizeof(Drw)); - drw->dpy = dpy; - drw->screen = screen; - drw->root = root; - drw->w = w; - drw->h = h; + drw->dpy = dpy; + drw->screen = screen; + drw->root = root; + drw->w = w; + drw->h = h; drw->drawable = XCreatePixmap(dpy, root, w, h, DefaultDepth(dpy, screen)); - drw->gc = XCreateGC(dpy, root, 0, NULL); + drw->gc = XCreateGC(dpy, root, 0, NULL); XSetLineAttributes(dpy, drw->gc, 1, LineSolid, CapButt, JoinMiter); return drw; } -void -drw_resize(Drw *drw, unsigned int w, unsigned int h) -{ +void drw_resize(Drw *drw, unsigned int w, unsigned int h) { if (!drw) return; @@ -87,12 +80,11 @@ drw_resize(Drw *drw, unsigned int w, unsigned int h) drw->h = h; if (drw->drawable) XFreePixmap(drw->dpy, drw->drawable); - drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, DefaultDepth(drw->dpy, drw->screen)); + drw->drawable = XCreatePixmap(drw->dpy, drw->root, w, h, + DefaultDepth(drw->dpy, drw->screen)); } -void -drw_free(Drw *drw) -{ +void drw_free(Drw *drw) { XFreePixmap(drw->dpy, drw->drawable); XFreeGC(drw->dpy, drw->gc); drw_fontset_free(drw->fonts); @@ -102,11 +94,10 @@ drw_free(Drw *drw) /* This function is an implementation detail. Library users should use * drw_fontset_create instead. */ -static Fnt * -xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern) -{ +static Fnt *xfont_create(Drw *drw, const char *fontname, + FcPattern *fontpattern) { Fnt *font; - XftFont *xfont = NULL; + XftFont *xfont = NULL; FcPattern *pattern = NULL; if (fontname) { @@ -116,11 +107,14 @@ xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern) * behaviour whereas the former just results in missing-character * rectangles being drawn, at least with some fonts. */ if (!(xfont = XftFontOpenName(drw->dpy, drw->screen, fontname))) { - fprintf(stderr, "error, cannot load font from name: '%s'\n", fontname); + fprintf(stderr, "error, cannot load font from name: '%s'\n", + fontname); return NULL; } if (!(pattern = FcNameParse((FcChar8 *) fontname))) { - fprintf(stderr, "error, cannot parse font name to pattern: '%s'\n", fontname); + fprintf(stderr, + "error, cannot parse font name to pattern: '%s'\n", + fontname); XftFontClose(drw->dpy, xfont); return NULL; } @@ -141,23 +135,22 @@ xfont_create(Drw *drw, const char *fontname, FcPattern *fontpattern) * and lots more all over the internet. */ FcBool iscol; - if(FcPatternGetBool(xfont->pattern, FC_COLOR, 0, &iscol) == FcResultMatch && iscol) { + if (FcPatternGetBool(xfont->pattern, FC_COLOR, 0, &iscol) == FcResultMatch + && iscol) { XftFontClose(drw->dpy, xfont); return NULL; } - font = ecalloc(1, sizeof(Fnt)); - font->xfont = xfont; + font = ecalloc(1, sizeof(Fnt)); + font->xfont = xfont; font->pattern = pattern; - font->h = xfont->ascent + xfont->descent; - font->dpy = drw->dpy; + font->h = xfont->ascent + xfont->descent; + font->dpy = drw->dpy; return font; } -static void -xfont_free(Fnt *font) -{ +static void xfont_free(Fnt *font) { if (!font) return; if (font->pattern) @@ -166,9 +159,7 @@ xfont_free(Fnt *font) free(font); } -Fnt* -drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount) -{ +Fnt *drw_fontset_create(Drw *drw, const char *fonts[], size_t fontcount) { Fnt *cur, *ret = NULL; size_t i; @@ -178,30 +169,26 @@ drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount) for (i = 1; i <= fontcount; i++) { if ((cur = xfont_create(drw, fonts[fontcount - i], NULL))) { cur->next = ret; - ret = cur; + ret = cur; } } return (drw->fonts = ret); } -void -drw_fontset_free(Fnt *font) -{ +void drw_fontset_free(Fnt *font) { if (font) { drw_fontset_free(font->next); xfont_free(font); } } -void -drw_clr_create(Drw *drw, Clr *dest, const char *clrname) -{ +void drw_clr_create(Drw *drw, Clr *dest, const char *clrname) { if (!drw || !dest || !clrname) return; if (!XftColorAllocName(drw->dpy, DefaultVisual(drw->dpy, drw->screen), - DefaultColormap(drw->dpy, drw->screen), - clrname, dest)) + DefaultColormap(drw->dpy, drw->screen), clrname, + dest)) die("error, cannot allocate color '%s'", clrname); dest->pixel |= 0xff << 24; @@ -209,14 +196,13 @@ drw_clr_create(Drw *drw, Clr *dest, const char *clrname) /* Wrapper to create color schemes. The caller has to call free(3) on the * returned color scheme when done using it. */ -Clr * -drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount) -{ +Clr *drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount) { size_t i; Clr *ret; /* need at least two colors for a scheme */ - if (!drw || !clrnames || clrcount < 2 || !(ret = ecalloc(clrcount, sizeof(XftColor)))) + if (!drw || !clrnames || clrcount < 2 + || !(ret = ecalloc(clrcount, sizeof(XftColor)))) return NULL; for (i = 0; i < clrcount; i++) @@ -224,35 +210,31 @@ drw_scm_create(Drw *drw, const char *clrnames[], size_t clrcount) return ret; } -void -drw_setfontset(Drw *drw, Fnt *set) -{ +void drw_setfontset(Drw *drw, Fnt *set) { if (drw) drw->fonts = set; } -void -drw_setscheme(Drw *drw, Clr *scm) -{ +void drw_setscheme(Drw *drw, Clr *scm) { if (drw) drw->scheme = scm; } -void -drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert) -{ +void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, + int filled, int invert) { if (!drw || !drw->scheme) return; - XSetForeground(drw->dpy, drw->gc, invert ? drw->scheme[ColBg].pixel : drw->scheme[ColFg].pixel); + XSetForeground(drw->dpy, drw->gc, + invert ? drw->scheme[ColBg].pixel + : drw->scheme[ColFg].pixel); if (filled) XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h); else XDrawRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w - 1, h - 1); } -int -drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert) -{ +int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, + unsigned int lpad, const char *text, int invert) { char buf[1024]; int ty; unsigned int ew; @@ -274,7 +256,8 @@ drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lp if (!render) { w = ~w; } else { - XSetForeground(drw->dpy, drw->gc, drw->scheme[invert ? ColFg : ColBg].pixel); + XSetForeground(drw->dpy, drw->gc, + drw->scheme[invert ? ColFg : ColBg].pixel); XFillRectangle(drw->dpy, drw->drawable, drw->gc, x, y, w, h); d = XftDrawCreate(drw->dpy, drw->drawable, DefaultVisual(drw->dpy, drw->screen), @@ -286,12 +269,14 @@ drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lp usedfont = drw->fonts; while (1) { utf8strlen = 0; - utf8str = text; - nextfont = NULL; + utf8str = text; + nextfont = NULL; while (*text) { utf8charlen = utf8decode(text, &utf8codepoint, UTF_SIZ); for (curfont = drw->fonts; curfont; curfont = curfont->next) { - charexists = charexists || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint); + charexists = + charexists + || XftCharExists(drw->dpy, curfont->xfont, utf8codepoint); if (charexists) { if (curfont == usedfont) { utf8strlen += utf8charlen; @@ -325,7 +310,8 @@ drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lp if (render) { ty = y + (h - usedfont->h) / 2 + usedfont->xfont->ascent; XftDrawStringUtf8(d, &drw->scheme[invert ? ColBg : ColFg], - usedfont->xfont, x, ty, (XftChar8 *)buf, len); + usedfont->xfont, x, ty, + (XftChar8 *) buf, len); } x += ew; w -= ew; @@ -336,7 +322,7 @@ drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lp break; } else if (nextfont) { charexists = 0; - usedfont = nextfont; + usedfont = nextfont; } else { /* Regardless of whether or not a fallback font is found, the * character must be drawn. */ @@ -346,8 +332,10 @@ drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lp FcCharSetAddChar(fccharset, utf8codepoint); if (!drw->fonts->pattern) { - /* Refer to the comment in xfont_create for more information. */ - die("the first font in the cache must be loaded from a font string."); + /* Refer to the comment in xfont_create for more information. + */ + die("the first font in the cache must be loaded from a font " + "string."); } fcpattern = FcPatternDuplicate(drw->fonts->pattern); @@ -364,8 +352,11 @@ drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lp if (match) { usedfont = xfont_create(drw, NULL, match); - if (usedfont && XftCharExists(drw->dpy, usedfont->xfont, utf8codepoint)) { - for (curfont = drw->fonts; curfont->next; curfont = curfont->next) + if (usedfont + && XftCharExists(drw->dpy, usedfont->xfont, + utf8codepoint)) { + for (curfont = drw->fonts; curfont->next; + curfont = curfont->next) ; /* NOP */ curfont->next = usedfont; } else { @@ -381,9 +372,8 @@ drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lp return x + (render ? w : 0); } -void -drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h) -{ +void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, + unsigned int h) { if (!drw) return; @@ -391,32 +381,27 @@ drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h) XSync(drw->dpy, False); } -unsigned int -drw_fontset_getwidth(Drw *drw, const char *text) -{ +unsigned int drw_fontset_getwidth(Drw *drw, const char *text) { if (!drw || !drw->fonts || !text) return 0; return drw_text(drw, 0, 0, 0, 0, 0, text, 0); } -void -drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h) -{ +void drw_font_getexts(Fnt *font, const char *text, unsigned int len, + unsigned int *w, unsigned int *h) { XGlyphInfo ext; if (!font || !text) return; - XftTextExtentsUtf8(font->dpy, font->xfont, (XftChar8 *)text, len, &ext); + XftTextExtentsUtf8(font->dpy, font->xfont, (XftChar8 *) text, len, &ext); if (w) *w = ext.xOff; if (h) *h = font->h; } -Cur * -drw_cur_create(Drw *drw, int shape) -{ +Cur *drw_cur_create(Drw *drw, int shape) { Cur *cur; if (!drw || !(cur = ecalloc(1, sizeof(Cur)))) @@ -427,9 +412,7 @@ drw_cur_create(Drw *drw, int shape) return cur; } -void -drw_cur_free(Drw *drw, Cur *cursor) -{ +void drw_cur_free(Drw *drw, Cur *cursor) { if (!cursor) return; diff --git a/src/drw.h b/src/drw.h index 4bcd5ad..dd79e53 100644 --- a/src/drw.h +++ b/src/drw.h @@ -27,15 +27,17 @@ typedef struct { } Drw; /* Drawable abstraction */ -Drw *drw_create(Display *dpy, int screen, Window win, unsigned int w, unsigned int h); +Drw *drw_create(Display *dpy, int screen, Window win, unsigned int w, + unsigned int h); void drw_resize(Drw *drw, unsigned int w, unsigned int h); void drw_free(Drw *drw); /* Fnt abstraction */ -Fnt *drw_fontset_create(Drw* drw, const char *fonts[], size_t fontcount); -void drw_fontset_free(Fnt* set); +Fnt *drw_fontset_create(Drw *drw, const char *fonts[], size_t fontcount); +void drw_fontset_free(Fnt *set); unsigned int drw_fontset_getwidth(Drw *drw, const char *text); -void drw_font_getexts(Fnt *font, const char *text, unsigned int len, unsigned int *w, unsigned int *h); +void drw_font_getexts(Fnt *font, const char *text, unsigned int len, + unsigned int *w, unsigned int *h); /* Colorscheme abstraction */ void drw_clr_create(Drw *drw, Clr *dest, const char *clrname); @@ -50,8 +52,11 @@ void drw_setfontset(Drw *drw, Fnt *set); void drw_setscheme(Drw *drw, Clr *scm); /* Drawing functions */ -void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, int filled, int invert); -int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, unsigned int lpad, const char *text, int invert); +void drw_rect(Drw *drw, int x, int y, unsigned int w, unsigned int h, + int filled, int invert); +int drw_text(Drw *drw, int x, int y, unsigned int w, unsigned int h, + unsigned int lpad, const char *text, int invert); /* Map functions */ -void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, unsigned int h); +void drw_map(Drw *drw, Window win, int x, int y, unsigned int w, + unsigned int h); diff --git a/src/dwm-msg.c b/src/dwm-msg.c index 1971d32..9e19a40 100644 --- a/src/dwm-msg.c +++ b/src/dwm-msg.c @@ -15,310 +15,302 @@ // clang-format off #define IPC_MAGIC_ARR { 'D', 'W', 'M', '-', 'I', 'P', 'C' } // clang-format on -#define IPC_MAGIC_LEN 7 // Not including null char +#define IPC_MAGIC_LEN 7 // Not including null char -#define IPC_EVENT_TAG_CHANGE "tag_change_event" -#define IPC_EVENT_CLIENT_FOCUS_CHANGE "client_focus_change_event" -#define IPC_EVENT_LAYOUT_CHANGE "layout_change_event" +#define IPC_EVENT_TAG_CHANGE "tag_change_event" +#define IPC_EVENT_CLIENT_FOCUS_CHANGE "client_focus_change_event" +#define IPC_EVENT_LAYOUT_CHANGE "layout_change_event" #define IPC_EVENT_MONITOR_FOCUS_CHANGE "monitor_focus_change_event" #define IPC_EVENT_FOCUSED_TITLE_CHANGE "focused_title_change_event" #define IPC_EVENT_FOCUSED_STATE_CHANGE "focused_state_change_event" -#define YSTR(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str)) -#define YINT(num) yajl_gen_integer(gen, num) +#define YSTR(str) yajl_gen_string(gen, (unsigned char *) str, strlen(str)) +#define YINT(num) yajl_gen_integer(gen, num) #define YDOUBLE(num) yajl_gen_double(gen, num) -#define YBOOL(v) yajl_gen_bool(gen, v) -#define YNULL() yajl_gen_null(gen) -#define YARR(body) \ - { \ - yajl_gen_array_open(gen); \ - body; \ - yajl_gen_array_close(gen); \ - } -#define YMAP(body) \ - { \ - yajl_gen_map_open(gen); \ - body; \ - yajl_gen_map_close(gen); \ - } +#define YBOOL(v) yajl_gen_bool(gen, v) +#define YNULL() yajl_gen_null(gen) +#define YARR(body) \ + { \ + yajl_gen_array_open(gen); \ + body; \ + yajl_gen_array_close(gen); \ + } +#define YMAP(body) \ + { \ + yajl_gen_map_open(gen); \ + body; \ + yajl_gen_map_close(gen); \ + } typedef unsigned long Window; -const char *DEFAULT_SOCKET_PATH = "/tmp/dwm.sock"; -static int sock_fd = -1; +const char *DEFAULT_SOCKET_PATH = "/tmp/dwm.sock"; +static int sock_fd = -1; static unsigned int ignore_reply = 0; typedef enum IPCMessageType { - IPC_TYPE_RUN_COMMAND = 0, - IPC_TYPE_GET_MONITORS = 1, - IPC_TYPE_GET_TAGS = 2, - IPC_TYPE_GET_LAYOUTS = 3, - IPC_TYPE_GET_DWM_CLIENT = 4, - IPC_TYPE_SUBSCRIBE = 5, - IPC_TYPE_EVENT = 6 + IPC_TYPE_RUN_COMMAND = 0, + IPC_TYPE_GET_MONITORS = 1, + IPC_TYPE_GET_TAGS = 2, + IPC_TYPE_GET_LAYOUTS = 3, + IPC_TYPE_GET_DWM_CLIENT = 4, + IPC_TYPE_SUBSCRIBE = 5, + IPC_TYPE_EVENT = 6 } IPCMessageType; // Every IPC message must begin with this typedef struct dwm_ipc_header { - uint8_t magic[IPC_MAGIC_LEN]; - uint32_t size; - uint8_t type; + uint8_t magic[IPC_MAGIC_LEN]; + uint32_t size; + uint8_t type; } __attribute((packed)) dwm_ipc_header_t; -static int -recv_message(uint8_t *msg_type, uint32_t *reply_size, uint8_t **reply) -{ - uint32_t read_bytes = 0; - const int32_t to_read = sizeof(dwm_ipc_header_t); - char header[to_read]; - char *walk = header; - - // Try to read header - while (read_bytes < to_read) { - ssize_t n = read(sock_fd, header + read_bytes, to_read - read_bytes); - - if (n == 0) { - if (read_bytes == 0) { - fprintf(stderr, "Unexpectedly reached EOF while reading header."); - fprintf(stderr, - "Read %" PRIu32 " bytes, expected %" PRIu32 " total bytes.\n", - read_bytes, to_read); - return -2; - } else { - fprintf(stderr, "Unexpectedly reached EOF while reading header."); - fprintf(stderr, - "Read %" PRIu32 " bytes, expected %" PRIu32 " total bytes.\n", - read_bytes, to_read); - return -3; - } - } else if (n == -1) { - return -1; - } - - read_bytes += n; - } - - // Check if magic string in header matches - if (memcmp(walk, IPC_MAGIC, IPC_MAGIC_LEN) != 0) { - fprintf(stderr, "Invalid magic string. Got '%.*s', expected '%s'\n", - IPC_MAGIC_LEN, walk, IPC_MAGIC); - return -3; - } - - walk += IPC_MAGIC_LEN; - - // Extract reply size - memcpy(reply_size, walk, sizeof(uint32_t)); - walk += sizeof(uint32_t); - - // Extract message type - memcpy(msg_type, walk, sizeof(uint8_t)); - walk += sizeof(uint8_t); - - (*reply) = malloc(*reply_size); - - // Extract payload - read_bytes = 0; - while (read_bytes < *reply_size) { - ssize_t n = read(sock_fd, *reply + read_bytes, *reply_size - read_bytes); - - if (n == 0) { - fprintf(stderr, "Unexpectedly reached EOF while reading payload."); - fprintf(stderr, "Read %" PRIu32 " bytes, expected %" PRIu32 " bytes.\n", - read_bytes, *reply_size); - free(*reply); - return -2; - } else if (n == -1) { - if (errno == EINTR || errno == EAGAIN) continue; - free(*reply); - return -1; - } - - read_bytes += n; - } - - return 0; +static int recv_message(uint8_t *msg_type, uint32_t *reply_size, + uint8_t **reply) { + uint32_t read_bytes = 0; + const int32_t to_read = sizeof(dwm_ipc_header_t); + char header[to_read]; + char *walk = header; + + // Try to read header + while (read_bytes < to_read) { + ssize_t n = read(sock_fd, header + read_bytes, to_read - read_bytes); + + if (n == 0) { + if (read_bytes == 0) { + fprintf(stderr, + "Unexpectedly reached EOF while reading header."); + fprintf(stderr, + "Read %" PRIu32 " bytes, expected %" PRIu32 + " total bytes.\n", + read_bytes, to_read); + return -2; + } else { + fprintf(stderr, + "Unexpectedly reached EOF while reading header."); + fprintf(stderr, + "Read %" PRIu32 " bytes, expected %" PRIu32 + " total bytes.\n", + read_bytes, to_read); + return -3; + } + } else if (n == -1) { + return -1; + } + + read_bytes += n; + } + + // Check if magic string in header matches + if (memcmp(walk, IPC_MAGIC, IPC_MAGIC_LEN) != 0) { + fprintf(stderr, "Invalid magic string. Got '%.*s', expected '%s'\n", + IPC_MAGIC_LEN, walk, IPC_MAGIC); + return -3; + } + + walk += IPC_MAGIC_LEN; + + // Extract reply size + memcpy(reply_size, walk, sizeof(uint32_t)); + walk += sizeof(uint32_t); + + // Extract message type + memcpy(msg_type, walk, sizeof(uint8_t)); + walk += sizeof(uint8_t); + + (*reply) = malloc(*reply_size); + + // Extract payload + read_bytes = 0; + while (read_bytes < *reply_size) { + ssize_t n = + read(sock_fd, *reply + read_bytes, *reply_size - read_bytes); + + if (n == 0) { + fprintf(stderr, + "Unexpectedly reached EOF while reading payload."); + fprintf(stderr, + "Read %" PRIu32 " bytes, expected %" PRIu32 " bytes.\n", + read_bytes, *reply_size); + free(*reply); + return -2; + } else if (n == -1) { + if (errno == EINTR || errno == EAGAIN) + continue; + free(*reply); + return -1; + } + + read_bytes += n; + } + + return 0; } -static int -read_socket(IPCMessageType *msg_type, uint32_t *msg_size, char **msg) -{ - int ret = -1; +static int read_socket(IPCMessageType *msg_type, uint32_t *msg_size, + char **msg) { + int ret = -1; - while (ret != 0) { - ret = recv_message((uint8_t *)msg_type, msg_size, (uint8_t **)msg); + while (ret != 0) { + ret = recv_message((uint8_t *) msg_type, msg_size, (uint8_t **) msg); - if (ret < 0) { - // Try again (non-fatal error) - if (ret == -1 && (errno == EINTR || errno == EAGAIN)) continue; + if (ret < 0) { + // Try again (non-fatal error) + if (ret == -1 && (errno == EINTR || errno == EAGAIN)) + continue; - fprintf(stderr, "Error receiving response from socket. "); - fprintf(stderr, "The connection might have been lost.\n"); - exit(2); - } - } + fprintf(stderr, "Error receiving response from socket. "); + fprintf(stderr, "The connection might have been lost.\n"); + exit(2); + } + } - return 0; + return 0; } -static ssize_t -write_socket(const void *buf, size_t count) -{ - size_t written = 0; - - while (written < count) { - const ssize_t n = - write(sock_fd, ((uint8_t *)buf) + written, count - written); - - if (n == -1) { - if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) - continue; - else - return n; - } - written += n; - } - return written; +static ssize_t write_socket(const void *buf, size_t count) { + size_t written = 0; + + while (written < count) { + const ssize_t n = + write(sock_fd, ((uint8_t *) buf) + written, count - written); + + if (n == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) + continue; + else + return n; + } + written += n; + } + return written; } -static void -connect_to_socket() -{ - struct sockaddr_un addr; +static void connect_to_socket() { + struct sockaddr_un addr; - int sock = socket(AF_UNIX, SOCK_STREAM, 0); + int sock = socket(AF_UNIX, SOCK_STREAM, 0); - // Initialize struct to 0 - memset(&addr, 0, sizeof(struct sockaddr_un)); + // Initialize struct to 0 + memset(&addr, 0, sizeof(struct sockaddr_un)); - addr.sun_family = AF_UNIX; - strcpy(addr.sun_path, DEFAULT_SOCKET_PATH); + addr.sun_family = AF_UNIX; + strcpy(addr.sun_path, DEFAULT_SOCKET_PATH); - connect(sock, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)); + connect(sock, (const struct sockaddr *) &addr, + sizeof(struct sockaddr_un)); - sock_fd = sock; + sock_fd = sock; } -static int -send_message(IPCMessageType msg_type, uint32_t msg_size, uint8_t *msg) -{ - dwm_ipc_header_t header = { - .magic = IPC_MAGIC_ARR, .size = msg_size, .type = msg_type}; +static int send_message(IPCMessageType msg_type, uint32_t msg_size, + uint8_t *msg) { + dwm_ipc_header_t header = {.magic = IPC_MAGIC_ARR, + .size = msg_size, + .type = msg_type}; - size_t header_size = sizeof(dwm_ipc_header_t); - size_t total_size = header_size + msg_size; + size_t header_size = sizeof(dwm_ipc_header_t); + size_t total_size = header_size + msg_size; - uint8_t buffer[total_size]; + uint8_t buffer[total_size]; - // Copy header to buffer - memcpy(buffer, &header, header_size); - // Copy message to buffer - memcpy(buffer + header_size, msg, header.size); + // Copy header to buffer + memcpy(buffer, &header, header_size); + // Copy message to buffer + memcpy(buffer + header_size, msg, header.size); - write_socket(buffer, total_size); + write_socket(buffer, total_size); - return 0; + return 0; } -static int -is_float(const char *s) -{ - size_t len = strlen(s); - int is_dot_used = 0; - int is_minus_used = 0; - - // Floats can only have one decimal point in between or digits - // Optionally, floats can also be below zero (negative) - for (int i = 0; i < len; i++) { - if (isdigit(s[i])) - continue; - else if (!is_dot_used && s[i] == '.' && i != 0 && i != len - 1) { - is_dot_used = 1; - continue; - } else if (!is_minus_used && s[i] == '-' && i == 0) { - is_minus_used = 1; - continue; - } else - return 0; - } - - return 1; +static int is_float(const char *s) { + size_t len = strlen(s); + int is_dot_used = 0; + int is_minus_used = 0; + + // Floats can only have one decimal point in between or digits + // Optionally, floats can also be below zero (negative) + for (int i = 0; i < len; i++) { + if (isdigit(s[i])) + continue; + else if (!is_dot_used && s[i] == '.' && i != 0 && i != len - 1) { + is_dot_used = 1; + continue; + } else if (!is_minus_used && s[i] == '-' && i == 0) { + is_minus_used = 1; + continue; + } else + return 0; + } + + return 1; } -static int -is_unsigned_int(const char *s) -{ - size_t len = strlen(s); +static int is_unsigned_int(const char *s) { + size_t len = strlen(s); - // Unsigned int can only have digits - for (int i = 0; i < len; i++) { - if (isdigit(s[i])) - continue; - else - return 0; - } + // Unsigned int can only have digits + for (int i = 0; i < len; i++) { + if (isdigit(s[i])) + continue; + else + return 0; + } - return 1; + return 1; } -static int -is_signed_int(const char *s) -{ - size_t len = strlen(s); - - // Signed int can only have digits and a negative sign at the start - for (int i = 0; i < len; i++) { - if (isdigit(s[i])) - continue; - else if (i == 0 && s[i] == '-') { - continue; - } else - return 0; - } - - return 1; +static int is_signed_int(const char *s) { + size_t len = strlen(s); + + // Signed int can only have digits and a negative sign at the start + for (int i = 0; i < len; i++) { + if (isdigit(s[i])) + continue; + else if (i == 0 && s[i] == '-') { + continue; + } else + return 0; + } + + return 1; } -static void -flush_socket_reply() -{ - IPCMessageType reply_type; - uint32_t reply_size; - char *reply; +static void flush_socket_reply() { + IPCMessageType reply_type; + uint32_t reply_size; + char *reply; - read_socket(&reply_type, &reply_size, &reply); + read_socket(&reply_type, &reply_size, &reply); - free(reply); + free(reply); } -static void -print_socket_reply() -{ - IPCMessageType reply_type; - uint32_t reply_size; - char *reply; +static void print_socket_reply() { + IPCMessageType reply_type; + uint32_t reply_size; + char *reply; - read_socket(&reply_type, &reply_size, &reply); + read_socket(&reply_type, &reply_size, &reply); - printf("%.*s\n", reply_size, reply); - fflush(stdout); - free(reply); + printf("%.*s\n", reply_size, reply); + fflush(stdout); + free(reply); } -static int -run_command(const char *name, char *args[], int argc) -{ - const unsigned char *msg; - size_t msg_size; +static int run_command(const char *name, char *args[], int argc) { + const unsigned char *msg; + size_t msg_size; - yajl_gen gen = yajl_gen_alloc(NULL); + yajl_gen gen = yajl_gen_alloc(NULL); - // Message format: - // { - // "command": "", - // "args": [ ... ] - // } - // clang-format off + // Message format: + // { + // "command": "", + // "args": [ ... ] + // } + // clang-format off YMAP( YSTR("command"); YSTR(name); YSTR("args"); YARR( @@ -335,214 +327,205 @@ run_command(const char *name, char *args[], int argc) } ) ) - // clang-format on + // clang-format on - yajl_gen_get_buf(gen, &msg, &msg_size); + yajl_gen_get_buf(gen, &msg, &msg_size); - send_message(IPC_TYPE_RUN_COMMAND, msg_size, (uint8_t *)msg); + send_message(IPC_TYPE_RUN_COMMAND, msg_size, (uint8_t *) msg); - if (!ignore_reply) - print_socket_reply(); - else - flush_socket_reply(); + if (!ignore_reply) + print_socket_reply(); + else + flush_socket_reply(); - yajl_gen_free(gen); + yajl_gen_free(gen); - return 0; + return 0; } -static int -get_monitors() -{ - send_message(IPC_TYPE_GET_MONITORS, 1, (uint8_t *)""); - print_socket_reply(); - return 0; +static int get_monitors() { + send_message(IPC_TYPE_GET_MONITORS, 1, (uint8_t *) ""); + print_socket_reply(); + return 0; } -static int -get_tags() -{ - send_message(IPC_TYPE_GET_TAGS, 1, (uint8_t *)""); - print_socket_reply(); +static int get_tags() { + send_message(IPC_TYPE_GET_TAGS, 1, (uint8_t *) ""); + print_socket_reply(); - return 0; + return 0; } -static int -get_layouts() -{ - send_message(IPC_TYPE_GET_LAYOUTS, 1, (uint8_t *)""); - print_socket_reply(); +static int get_layouts() { + send_message(IPC_TYPE_GET_LAYOUTS, 1, (uint8_t *) ""); + print_socket_reply(); - return 0; + return 0; } -static int -get_dwm_client(Window win) -{ - const unsigned char *msg; - size_t msg_size; +static int get_dwm_client(Window win) { + const unsigned char *msg; + size_t msg_size; - yajl_gen gen = yajl_gen_alloc(NULL); + yajl_gen gen = yajl_gen_alloc(NULL); - // Message format: - // { - // "client_window_id": "" - // } - // clang-format off + // Message format: + // { + // "client_window_id": "" + // } + // clang-format off YMAP( YSTR("client_window_id"); YINT(win); ) - // clang-format on + // clang-format on - yajl_gen_get_buf(gen, &msg, &msg_size); + yajl_gen_get_buf(gen, &msg, &msg_size); - send_message(IPC_TYPE_GET_DWM_CLIENT, msg_size, (uint8_t *)msg); + send_message(IPC_TYPE_GET_DWM_CLIENT, msg_size, (uint8_t *) msg); - print_socket_reply(); + print_socket_reply(); - yajl_gen_free(gen); + yajl_gen_free(gen); - return 0; + return 0; } -static int -subscribe(const char *event) -{ - const unsigned char *msg; - size_t msg_size; +static int subscribe(const char *event) { + const unsigned char *msg; + size_t msg_size; - yajl_gen gen = yajl_gen_alloc(NULL); + yajl_gen gen = yajl_gen_alloc(NULL); - // Message format: - // { - // "event": "", - // "action": "subscribe" - // } - // clang-format off + // Message format: + // { + // "event": "", + // "action": "subscribe" + // } + // clang-format off YMAP( YSTR("event"); YSTR(event); YSTR("action"); YSTR("subscribe"); ) - // clang-format on + // clang-format on - yajl_gen_get_buf(gen, &msg, &msg_size); + yajl_gen_get_buf(gen, &msg, &msg_size); - send_message(IPC_TYPE_SUBSCRIBE, msg_size, (uint8_t *)msg); + send_message(IPC_TYPE_SUBSCRIBE, msg_size, (uint8_t *) msg); - if (!ignore_reply) - print_socket_reply(); - else - flush_socket_reply(); + if (!ignore_reply) + print_socket_reply(); + else + flush_socket_reply(); - yajl_gen_free(gen); + yajl_gen_free(gen); - return 0; + return 0; } -static void -usage_error(const char *prog_name, const char *format, ...) -{ - va_list args; - va_start(args, format); +static void usage_error(const char *prog_name, const char *format, ...) { + va_list args; + va_start(args, format); - fprintf(stderr, "Error: "); - vfprintf(stderr, format, args); - fprintf(stderr, "\nusage: %s [...]\n", prog_name); - fprintf(stderr, "Try '%s help'\n", prog_name); + fprintf(stderr, "Error: "); + vfprintf(stderr, format, args); + fprintf(stderr, "\nusage: %s [...]\n", prog_name); + fprintf(stderr, "Try '%s help'\n", prog_name); - va_end(args); - exit(1); + va_end(args); + exit(1); } -static void -print_usage(const char *name) -{ - printf("usage: %s [options] [...]\n", name); - puts(""); - puts("Commands:"); - puts(" run_command [args...] Run an IPC command"); - puts(""); - puts(" get_monitors Get monitor properties"); - puts(""); - puts(" get_tags Get list of tags"); - puts(""); - puts(" get_layouts Get list of layouts"); - puts(""); - puts(" get_dwm_client Get dwm client proprties"); - puts(""); - puts(" subscribe [events...] Subscribe to specified events"); - puts(" Options: " IPC_EVENT_TAG_CHANGE ","); - puts(" " IPC_EVENT_LAYOUT_CHANGE ","); - puts(" " IPC_EVENT_CLIENT_FOCUS_CHANGE ","); - puts(" " IPC_EVENT_MONITOR_FOCUS_CHANGE ","); - puts(" " IPC_EVENT_FOCUSED_TITLE_CHANGE ","); - puts(" " IPC_EVENT_FOCUSED_STATE_CHANGE); - puts(""); - puts(" help Display this message"); - puts(""); - puts("Options:"); - puts(" --ignore-reply Don't print reply messages from"); - puts(" run_command and subscribe."); - puts(""); +static void print_usage(const char *name) { + printf("usage: %s [options] [...]\n", name); + puts(""); + puts("Commands:"); + puts(" run_command [args...] Run an IPC command"); + puts(""); + puts(" get_monitors Get monitor properties"); + puts(""); + puts(" get_tags Get list of tags"); + puts(""); + puts(" get_layouts Get list of layouts"); + puts(""); + puts(" get_dwm_client Get dwm client proprties"); + puts(""); + puts(" subscribe [events...] Subscribe to specified events"); + puts(" Options: " IPC_EVENT_TAG_CHANGE + ","); + puts(" " IPC_EVENT_LAYOUT_CHANGE ","); + puts(" " IPC_EVENT_CLIENT_FOCUS_CHANGE + ","); + puts(" " IPC_EVENT_MONITOR_FOCUS_CHANGE + ","); + puts(" " IPC_EVENT_FOCUSED_TITLE_CHANGE + ","); + puts(" " IPC_EVENT_FOCUSED_STATE_CHANGE); + puts(""); + puts(" help Display this message"); + puts(""); + puts("Options:"); + puts(" --ignore-reply Don't print reply messages from"); + puts(" run_command and subscribe."); + puts(""); } -int -main(int argc, char *argv[]) -{ - const char *prog_name = argv[0]; - - connect_to_socket(); - if (sock_fd == -1) { - fprintf(stderr, "Failed to connect to socket\n"); - return 1; - } - - int i = 1; - if (i < argc && strcmp(argv[i], "--ignore-reply") == 0) { - ignore_reply = 1; - i++; - } - - if (i >= argc) usage_error(prog_name, "Expected an argument, got none"); - - if (strcmp(argv[i], "help") == 0) - print_usage(prog_name); - else if (strcmp(argv[i], "run_command") == 0) { - if (++i >= argc) usage_error(prog_name, "No command specified"); - // Command name - char *command = argv[i]; - // Command arguments are everything after command name - char **command_args = argv + ++i; - // Number of command arguments - int command_argc = argc - i; - run_command(command, command_args, command_argc); - } else if (strcmp(argv[i], "get_monitors") == 0) { - get_monitors(); - } else if (strcmp(argv[i], "get_tags") == 0) { - get_tags(); - } else if (strcmp(argv[i], "get_layouts") == 0) { - get_layouts(); - } else if (strcmp(argv[i], "get_dwm_client") == 0) { - if (++i < argc) { - if (is_unsigned_int(argv[i])) { - Window win = atol(argv[i]); - get_dwm_client(win); - } else - usage_error(prog_name, "Expected unsigned integer argument"); - } else - usage_error(prog_name, "Expected the window id"); - } else if (strcmp(argv[i], "subscribe") == 0) { - if (++i < argc) { - for (int j = i; j < argc; j++) subscribe(argv[j]); - } else - usage_error(prog_name, "Expected event name"); - // Keep listening for events forever - while (1) { - print_socket_reply(); - } - } else - usage_error(prog_name, "Invalid argument '%s'", argv[i]); - - return 0; +int main(int argc, char *argv[]) { + const char *prog_name = argv[0]; + + connect_to_socket(); + if (sock_fd == -1) { + fprintf(stderr, "Failed to connect to socket\n"); + return 1; + } + + int i = 1; + if (i < argc && strcmp(argv[i], "--ignore-reply") == 0) { + ignore_reply = 1; + i++; + } + + if (i >= argc) + usage_error(prog_name, "Expected an argument, got none"); + + if (strcmp(argv[i], "help") == 0) + print_usage(prog_name); + else if (strcmp(argv[i], "run_command") == 0) { + if (++i >= argc) + usage_error(prog_name, "No command specified"); + // Command name + char *command = argv[i]; + // Command arguments are everything after command name + char **command_args = argv + ++i; + // Number of command arguments + int command_argc = argc - i; + run_command(command, command_args, command_argc); + } else if (strcmp(argv[i], "get_monitors") == 0) { + get_monitors(); + } else if (strcmp(argv[i], "get_tags") == 0) { + get_tags(); + } else if (strcmp(argv[i], "get_layouts") == 0) { + get_layouts(); + } else if (strcmp(argv[i], "get_dwm_client") == 0) { + if (++i < argc) { + if (is_unsigned_int(argv[i])) { + Window win = atol(argv[i]); + get_dwm_client(win); + } else + usage_error(prog_name, "Expected unsigned integer argument"); + } else + usage_error(prog_name, "Expected the window id"); + } else if (strcmp(argv[i], "subscribe") == 0) { + if (++i < argc) { + for (int j = i; j < argc; j++) + subscribe(argv[j]); + } else + usage_error(prog_name, "Expected event name"); + // Keep listening for events forever + while (1) { + print_socket_reply(); + } + } else + usage_error(prog_name, "Invalid argument '%s'", argv[i]); + + return 0; } diff --git a/src/dwm.c b/src/dwm.c index 740a57c..8a54c5f 100644 --- a/src/dwm.c +++ b/src/dwm.c @@ -20,6 +20,12 @@ * * To understand everything else, start reading main(). */ +#include +#include +#include +#include +#include +#include #include #include #include @@ -27,17 +33,11 @@ #include #include #include -#include -#include +#include #include +#include #include -#include -#include -#include -#include -#include -#include -#include +#include #ifdef XINERAMA #include #endif /* XINERAMA */ @@ -47,28 +47,54 @@ #include "util.h" /* macros */ -#define BUTTONMASK (ButtonPressMask|ButtonReleaseMask) -#define CLEANMASK(mask) (mask & ~(numlockmask|LockMask) & (ShiftMask|ControlMask|Mod1Mask|Mod2Mask|Mod3Mask|Mod4Mask|Mod5Mask)) -#define INTERSECT(x,y,w,h,m) (MAX(0, MIN((x)+(w),(m)->mx+(m)->mw) - MAX((x),(m)->mx)) \ - * MAX(0, MIN((y)+(h),(m)->my+(m)->mh) - MAX((y),(m)->my))) -#define ISVISIBLEONTAG(C, T) ((C->tags & T)) -#define ISVISIBLE(C) ISVISIBLEONTAG(C, C->mon->tagset[C->mon->seltags]) -#define LENGTH(X) (sizeof X / sizeof X[0]) -#define MOUSEMASK (BUTTONMASK|PointerMotionMask) -#define WIDTH(X) ((X)->w + 2 * (X)->bw) -#define HEIGHT(X) ((X)->h + 2 * (X)->bw) -#define TAGMASK ((1 << LENGTH(tags)) - 1) -#define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad) +#define BUTTONMASK (ButtonPressMask | ButtonReleaseMask) +#define CLEANMASK(mask) \ + (mask & ~(numlockmask | LockMask) \ + & (ShiftMask | ControlMask | Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask \ + | Mod5Mask)) +#define INTERSECT(x, y, w, h, m) \ + (MAX(0, MIN((x) + (w), (m)->mx + (m)->mw) - MAX((x), (m)->mx)) \ + * MAX(0, MIN((y) + (h), (m)->my + (m)->mh) - MAX((y), (m)->my))) +#define ISVISIBLEONTAG(C, T) ((C->tags & T)) +#define ISVISIBLE(C) ISVISIBLEONTAG(C, C->mon->tagset[C->mon->seltags]) +#define LENGTH(X) (sizeof X / sizeof X[0]) +#define MOUSEMASK (BUTTONMASK | PointerMotionMask) +#define WIDTH(X) ((X)->w + 2 * (X)->bw) +#define HEIGHT(X) ((X)->h + 2 * (X)->bw) +#define TAGMASK ((1 << LENGTH(tags)) - 1) +#define TEXTW(X) (drw_fontset_getwidth(drw, (X)) + lrpad) /* enums */ enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */ -enum { SchemeNorm, SchemeSel }; /* color schemes */ -enum { NetSupported, NetWMName, NetWMState, NetWMCheck, - NetWMFullscreen, NetActiveWindow, NetWMWindowType, - NetWMWindowTypeDialog, NetClientList, NetLast }; /* EWMH atoms */ -enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */ -enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, - ClkClientWin, ClkRootWin, ClkLast }; /* clicks */ +enum { SchemeNorm, SchemeSel }; /* color schemes */ +enum { + NetSupported, + NetWMName, + NetWMState, + NetWMCheck, + NetWMFullscreen, + NetActiveWindow, + NetWMWindowType, + NetWMWindowTypeDialog, + NetClientList, + NetLast +}; /* EWMH atoms */ +enum { + WMProtocols, + WMDelete, + WMState, + WMTakeFocus, + WMLast +}; /* default atoms */ +enum { + ClkTagBar, + ClkLtSymbol, + ClkStatusText, + ClkWinTitle, + ClkClientWin, + ClkRootWin, + ClkLast +}; /* clicks */ typedef struct TagState TagState; struct TagState { @@ -127,19 +153,18 @@ typedef struct { void (*arrange)(Monitor *); } Layout; - struct Monitor { char ltsymbol[16]; char lastltsymbol[16]; float mfact; int nmaster; int num; - int by, bh; /* bar geometry */ - int tx, tw; /* bar tray geometry */ - int mx, my, mw, mh; /* screen size */ - int wx, wy, ww, wh; /* window area */ - int gappx; /* gaps between windows */ - int gapidx; /* gap mode index */ + int by, bh; /* bar geometry */ + int tx, tw; /* bar tray geometry */ + int mx, my, mw, mh; /* screen size */ + int wx, wy, ww, wh; /* window area */ + int gappx; /* gaps between windows */ + int gapidx; /* gap mode index */ unsigned int seltags; unsigned int sellt; unsigned int tagset[2]; @@ -168,7 +193,8 @@ typedef struct { /* function declarations */ static void applyrules(Client *c); -static int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact); +static int applysizehints(Client *c, int *x, int *y, int *w, int *h, + int interact); static void arrange(Monitor *m); static void arrangemon(Monitor *m); static void attach(Client *c); @@ -281,36 +307,35 @@ static void zoom(const Arg *arg); /* variables */ static const char autostartblocksh[] = "autostart_blocking.sh"; -static const char autostartsh[] = "autostart.sh"; -static const char broken[] = "broken"; -static const char dwmdir[] = "dwm"; -static const char localshare[] = ".local/share"; +static const char autostartsh[] = "autostart.sh"; +static const char broken[] = "broken"; +static const char dwmdir[] = "dwm"; +static const char localshare[] = ".local/share"; static char stext[256]; static int statusw; static int statussig; static pid_t statuspid = -1; static int screen; -static int sw, sh; /* X display screen geometry width, height */ -static int bh, blw = 0; /* bar geometry */ -static int lrpad; /* sum of left and right padding for text */ +static int sw, sh; /* X display screen geometry width, height */ +static int bh, blw = 0; /* bar geometry */ +static int lrpad; /* sum of left and right padding for text */ static int (*xerrorxlib)(Display *, XErrorEvent *); -static unsigned int numlockmask = 0; -static void (*handler[LASTEvent]) (XEvent *) = { - [ButtonPress] = buttonpress, - [ClientMessage] = clientmessage, - [ConfigureRequest] = configurerequest, - [ConfigureNotify] = configurenotify, - [DestroyNotify] = destroynotify, - [EnterNotify] = enternotify, - [Expose] = expose, - [FocusIn] = focusin, - [KeyPress] = keypress, - [MappingNotify] = mappingnotify, - [MapRequest] = maprequest, - [MotionNotify] = motionnotify, - [PropertyNotify] = propertynotify, - [UnmapNotify] = unmapnotify -}; +static unsigned int numlockmask = 0; +static void (*handler[LASTEvent])(XEvent *) = { + [ButtonPress] = buttonpress, + [ClientMessage] = clientmessage, + [ConfigureRequest] = configurerequest, + [ConfigureNotify] = configurenotify, + [DestroyNotify] = destroynotify, + [EnterNotify] = enternotify, + [Expose] = expose, + [FocusIn] = focusin, + [KeyPress] = keypress, + [MappingNotify] = mappingnotify, + [MapRequest] = maprequest, + [MotionNotify] = motionnotify, + [PropertyNotify] = propertynotify, + [UnmapNotify] = unmapnotify}; static Atom wmatom[WMLast], netatom[NetLast]; static int epoll_fd; static int dpy_fd; @@ -329,39 +354,39 @@ static Window root, wmcheckwin; #ifdef VERSION #include "IPCClient.c" -#include "yajl_dumps.c" #include "ipc.c" +#include "yajl_dumps.c" #endif /* compile-time check if all tags fit into an unsigned int bit array. */ -struct NumTags { char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; }; +struct NumTags { + char limitexceeded[LENGTH(tags) > 31 ? -1 : 1]; +}; /* function implementations */ -void -applyrules(Client *c) -{ +void applyrules(Client *c) { const char *class, *instance; unsigned int i; const Rule *r; Monitor *m; - XClassHint ch = { NULL, NULL }; + XClassHint ch = {NULL, NULL}; /* rule matching */ c->isfloating = 0; - c->tags = 0; + c->tags = 0; XGetClassHint(dpy, c->win, &ch); class = ch.res_class ? ch.res_class : broken; - instance = ch.res_name ? ch.res_name : broken; + instance = ch.res_name ? ch.res_name : broken; for (i = 0; i < LENGTH(rules); i++) { r = &rules[i]; if ((!r->title || strstr(c->name, r->title)) - && (!r->class || strstr(class, r->class)) - && (!r->instance || strstr(instance, r->instance))) - { + && (!r->class || strstr(class, r->class)) + && (!r->instance || strstr(instance, r->instance))) { c->isfloating = r->isfloating; c->tags |= r->tags; - for (m = mons; m && m->num != r->monitor; m = m->next); + for (m = mons; m && m->num != r->monitor; m = m->next) + ; if (m) c->mon = m; } @@ -370,12 +395,11 @@ applyrules(Client *c) XFree(ch.res_class); if (ch.res_name) XFree(ch.res_name); - c->tags = c->tags & TAGMASK ? c->tags & TAGMASK : c->mon->tagset[c->mon->seltags]; + c->tags = c->tags & TAGMASK ? c->tags & TAGMASK + : c->mon->tagset[c->mon->seltags]; } -int -applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact) -{ +int applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact) { int baseismin; Monitor *m = c->mon; @@ -414,9 +438,9 @@ applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact) } /* adjust for aspect limits */ if (c->mina > 0 && c->maxa > 0) { - if (c->maxa < (float)*w / *h) + if (c->maxa < (float) *w / *h) *w = *h * c->maxa + 0.5; - else if (c->mina < (float)*h / *w) + else if (c->mina < (float) *h / *w) *h = *w * c->mina + 0.5; } if (baseismin) { /* increment calculation requires this */ @@ -439,64 +463,58 @@ applysizehints(Client *c, int *x, int *y, int *w, int *h, int interact) return *x != c->x || *y != c->y || *w != c->w || *h != c->h; } -void -arrange(Monitor *m) -{ +void arrange(Monitor *m) { if (m) showhide(m->stack); - else for (m = mons; m; m = m->next) - showhide(m->stack); + else + for (m = mons; m; m = m->next) + showhide(m->stack); if (m) { arrangemon(m); restack(m); - } else for (m = mons; m; m = m->next) - arrangemon(m); + } else + for (m = mons; m; m = m->next) + arrangemon(m); } -void -arrangemon(Monitor *m) -{ +void arrangemon(Monitor *m) { strncpy(m->ltsymbol, m->lt[m->sellt]->symbol, sizeof m->ltsymbol); if (m->lt[m->sellt]->arrange) m->lt[m->sellt]->arrange(m); } -void -attach(Client *c) -{ - c->next = c->mon->clients; +void attach(Client *c) { + c->next = c->mon->clients; c->mon->clients = c; } -void -attachtop(Client *c) -{ +void attachtop(Client *c) { int n; Monitor *m = selmon; Client *below; for (n = 1, below = c->mon->clients; - below && below->next && (below->isfloating || !ISVISIBLEONTAG(below, c->tags) || n != m->nmaster); - n = below->isfloating || !ISVISIBLEONTAG(below, c->tags) ? n + 0 : n + 1, below = below->next); + below && below->next + && (below->isfloating || !ISVISIBLEONTAG(below, c->tags) + || n != m->nmaster); + n = below->isfloating || !ISVISIBLEONTAG(below, c->tags) ? n + 0 + : n + 1, + below = below->next) + ; c->next = NULL; if (below) { - c->next = below->next; + c->next = below->next; below->next = c; - } - else + } else c->mon->clients = c; } -void -attachstack(Client *c) -{ - c->snext = c->mon->stack; +void attachstack(Client *c) { + c->snext = c->mon->stack; c->mon->stack = c; } -void -buttonpress(XEvent *e) -{ +void buttonpress(XEvent *e) { unsigned int i, x, click; Arg arg = {0}; Client *c; @@ -517,20 +535,20 @@ buttonpress(XEvent *e) x += TEXTW(tags[i]); while (ev->x >= x && ++i < LENGTH(tags)); if (i < LENGTH(tags)) { - click = ClkTagBar; + click = ClkTagBar; arg.ui = 1 << i; } else if (ev->x < x + blw) click = ClkLtSymbol; else if (ev->x > selmon->ww - statusw) { - x = selmon->ww - statusw; - click = ClkStatusText; + x = selmon->ww - statusw; + click = ClkStatusText; statussig = 0; for (text = s = stext; *s && x <= ev->x; s++) { - if ((unsigned char)(*s) < ' ') { + if ((unsigned char) (*s) < ' ') { ch = *s; *s = '\0'; x += TEXTW(text) - lrpad; - *s = ch; + *s = ch; text = s + 1; if (x >= ev->x) break; @@ -546,14 +564,15 @@ buttonpress(XEvent *e) click = ClkClientWin; } for (i = 0; i < LENGTH(buttons); i++) - if (click == buttons[i].click && buttons[i].func && buttons[i].button == ev->button - && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state)) - buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 ? &arg : &buttons[i].arg); + if (click == buttons[i].click && buttons[i].func + && buttons[i].button == ev->button + && CLEANMASK(buttons[i].mask) == CLEANMASK(ev->state)) + buttons[i].func(click == ClkTagBar && buttons[i].arg.i == 0 + ? &arg + : &buttons[i].arg); } -void -checkotherwm(void) -{ +void checkotherwm(void) { xerrorxlib = XSetErrorHandler(xerrorstart); /* this causes an error if some other window manager is running */ XSelectInput(dpy, DefaultRootWindow(dpy), SubstructureRedirectMask); @@ -562,11 +581,9 @@ checkotherwm(void) XSync(dpy, False); } -void -cleanup(void) -{ - Arg a = {.ui = ~0}; - Layout foo = { "", NULL }; +void cleanup(void) { + Arg a = {.ui = ~0}; + Layout foo = {"", NULL}; Monitor *m; size_t i; @@ -591,19 +608,18 @@ cleanup(void) ipc_cleanup(); if (close(epoll_fd) < 0) { - fprintf(stderr, "Failed to close epoll file descriptor\n"); + fprintf(stderr, "Failed to close epoll file descriptor\n"); } } -void -cleanupmon(Monitor *mon) -{ +void cleanupmon(Monitor *mon) { Monitor *m; if (mon == mons) mons = mons->next; else { - for (m = mons; m && m->next != mon; m = m->next); + for (m = mons; m && m->next != mon; m = m->next) + ; m->next = mon->next; } if (!usealtbar) { @@ -613,47 +629,43 @@ cleanupmon(Monitor *mon) free(mon); } -void -clientmessage(XEvent *e) -{ +void clientmessage(XEvent *e) { XClientMessageEvent *cme = &e->xclient; - Client *c = wintoclient(cme->window); + Client *c = wintoclient(cme->window); if (!c) return; if (cme->message_type == netatom[NetWMState]) { if (cme->data.l[1] == netatom[NetWMFullscreen] - || cme->data.l[2] == netatom[NetWMFullscreen]) - setfullscreen(c, (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD */ - || (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ && !c->isfullscreen))); + || cme->data.l[2] == netatom[NetWMFullscreen]) + setfullscreen(c, + (cme->data.l[0] == 1 /* _NET_WM_STATE_ADD */ + || (cme->data.l[0] == 2 /* _NET_WM_STATE_TOGGLE */ + && !c->isfullscreen))); } else if (cme->message_type == netatom[NetActiveWindow]) { if (c != selmon->sel && !c->isurgent) seturgent(c, 1); } } -void -configure(Client *c) -{ +void configure(Client *c) { XConfigureEvent ce; - ce.type = ConfigureNotify; - ce.display = dpy; - ce.event = c->win; - ce.window = c->win; - ce.x = c->x; - ce.y = c->y; - ce.width = c->w; - ce.height = c->h; - ce.border_width = c->bw; - ce.above = None; + ce.type = ConfigureNotify; + ce.display = dpy; + ce.event = c->win; + ce.window = c->win; + ce.x = c->x; + ce.y = c->y; + ce.width = c->w; + ce.height = c->h; + ce.border_width = c->bw; + ce.above = None; ce.override_redirect = False; - XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *)&ce); + XSendEvent(dpy, c->win, False, StructureNotifyMask, (XEvent *) &ce); } -void -configurenotify(XEvent *e) -{ +void configurenotify(XEvent *e) { Monitor *m; Client *c; XConfigureEvent *ev = &e->xconfigure; @@ -662,8 +674,8 @@ configurenotify(XEvent *e) /* TODO: updategeom handling sucks, needs to be simplified */ if (ev->window == root) { dirty = (sw != ev->width || sh != ev->height); - sw = ev->width; - sh = ev->height; + sw = ev->width; + sh = ev->height; if (updategeom() || dirty) { drw_resize(drw, sw, bh); updatebars(); @@ -679,9 +691,7 @@ configurenotify(XEvent *e) } } -void -configurerequest(XEvent *e) -{ +void configurerequest(XEvent *e) { Client *c; Monitor *m; XConfigureRequestEvent *ev = &e->xconfigurerequest; @@ -694,66 +704,66 @@ configurerequest(XEvent *e) m = c->mon; if (ev->value_mask & CWX) { c->oldx = c->x; - c->x = m->mx + ev->x; + c->x = m->mx + ev->x; } if (ev->value_mask & CWY) { c->oldy = c->y; - c->y = m->my + ev->y; + c->y = m->my + ev->y; } if (ev->value_mask & CWWidth) { c->oldw = c->w; - c->w = ev->width; + c->w = ev->width; } if (ev->value_mask & CWHeight) { c->oldh = c->h; - c->h = ev->height; + c->h = ev->height; } if ((c->x + c->w) > m->mx + m->mw && c->isfloating) - c->x = m->mx + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */ + c->x = m->mx + + (m->mw / 2 - WIDTH(c) / 2); /* center in x direction */ if ((c->y + c->h) > m->my + m->mh && c->isfloating) - c->y = m->my + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */ - if ((ev->value_mask & (CWX|CWY)) && !(ev->value_mask & (CWWidth|CWHeight))) + c->y = + m->my + + (m->mh / 2 - HEIGHT(c) / 2); /* center in y direction */ + if ((ev->value_mask & (CWX | CWY)) + && !(ev->value_mask & (CWWidth | CWHeight))) configure(c); if (ISVISIBLE(c)) XMoveResizeWindow(dpy, c->win, c->x, c->y, c->w, c->h); } else configure(c); } else { - wc.x = ev->x; - wc.y = ev->y; - wc.width = ev->width; - wc.height = ev->height; + wc.x = ev->x; + wc.y = ev->y; + wc.width = ev->width; + wc.height = ev->height; wc.border_width = ev->border_width; - wc.sibling = ev->above; - wc.stack_mode = ev->detail; + wc.sibling = ev->above; + wc.stack_mode = ev->detail; XConfigureWindow(dpy, ev->window, ev->value_mask, &wc); } XSync(dpy, False); } -Monitor * -createmon(void) -{ +Monitor *createmon(void) { Monitor *m; - m = ecalloc(1, sizeof(Monitor)); + m = ecalloc(1, sizeof(Monitor)); m->tagset[0] = m->tagset[1] = 1; - m->bh = bh; - m->mfact = mfact; - m->nmaster = nmaster; - m->showbar = showbar; - m->topbar = topbar; - m->gappx = gappx; - m->gapidx = 0; - m->lt[0] = &layouts[0]; - m->lt[1] = &layouts[1 % LENGTH(layouts)]; + m->bh = bh; + m->mfact = mfact; + m->nmaster = nmaster; + m->showbar = showbar; + m->topbar = topbar; + m->gappx = gappx; + m->gapidx = 0; + m->lt[0] = &layouts[0]; + m->lt[1] = &layouts[1 % LENGTH(layouts)]; strncpy(m->ltsymbol, layouts[0].symbol, sizeof m->ltsymbol); return m; } -void -destroynotify(XEvent *e) -{ +void destroynotify(XEvent *e) { Client *c; Monitor *m; XDestroyWindowEvent *ev = &e->xdestroywindow; @@ -766,47 +776,44 @@ destroynotify(XEvent *e) unmanagetray(ev->window); } -void -detach(Client *c) -{ +void detach(Client *c) { Client **tc; - for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next); + for (tc = &c->mon->clients; *tc && *tc != c; tc = &(*tc)->next) + ; *tc = c->next; } -void -detachstack(Client *c) -{ +void detachstack(Client *c) { Client **tc, *t; - for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext); + for (tc = &c->mon->stack; *tc && *tc != c; tc = &(*tc)->snext) + ; *tc = c->snext; if (c == c->mon->sel) { - for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext); + for (t = c->mon->stack; t && !ISVISIBLE(t); t = t->snext) + ; c->mon->sel = t; } } -Monitor * -dirtomon(int dir) -{ +Monitor *dirtomon(int dir) { Monitor *m = NULL; if (dir > 0) { if (!(m = selmon->next)) m = mons; } else if (selmon == mons) - for (m = mons; m->next; m = m->next); + for (m = mons; m->next; m = m->next) + ; else - for (m = mons; m->next != selmon; m = m->next); + for (m = mons; m->next != selmon; m = m->next) + ; return m; } -void -drawbar(Monitor *m) -{ +void drawbar(Monitor *m) { if (usealtbar) return; @@ -823,13 +830,13 @@ drawbar(Monitor *m) x = 0; for (text = s = stext; *s; s++) { - if ((unsigned char)(*s) < ' ') { + if ((unsigned char) (*s) < ' ') { ch = *s; *s = '\0'; tw = TEXTW(text) - lrpad; drw_text(drw, m->ww - statusw + x, 0, tw, bh, 0, text, 0); x += tw; - *s = ch; + *s = ch; text = s + 1; } } @@ -846,12 +853,14 @@ drawbar(Monitor *m) x = 0; for (i = 0; i < LENGTH(tags); i++) { w = TEXTW(tags[i]); - drw_setscheme(drw, scheme[m->tagset[m->seltags] & 1 << i ? SchemeSel : SchemeNorm]); + drw_setscheme( + drw, + scheme[m->tagset[m->seltags] & 1 << i ? SchemeSel : SchemeNorm]); drw_text(drw, x, 0, w, bh, lrpad / 2, tags[i], urg & 1 << i); if (occ & 1 << i) drw_rect(drw, x + boxs, boxs, boxw, boxw, - m == selmon && selmon->sel && selmon->sel->tags & 1 << i, - urg & 1 << i); + m == selmon && selmon->sel && selmon->sel->tags & 1 << i, + urg & 1 << i); x += w; } w = blw = TEXTW(m->ltsymbol); @@ -872,23 +881,20 @@ drawbar(Monitor *m) drw_map(drw, m->barwin, 0, 0, m->ww, bh); } -void -drawbars(void) -{ +void drawbars(void) { Monitor *m; for (m = mons; m; m = m->next) drawbar(m); } -void -enternotify(XEvent *e) -{ +void enternotify(XEvent *e) { Client *c; Monitor *m; XCrossingEvent *ev = &e->xcrossing; - if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) && ev->window != root) + if ((ev->mode != NotifyNormal || ev->detail == NotifyInferior) + && ev->window != root) return; c = wintoclient(ev->window); m = c ? c->mon : wintomon(ev->window); @@ -900,9 +906,7 @@ enternotify(XEvent *e) focus(c); } -void -expose(XEvent *e) -{ +void expose(XEvent *e) { Monitor *m; XExposeEvent *ev = &e->xexpose; @@ -910,11 +914,10 @@ expose(XEvent *e) drawbar(m); } -void -focus(Client *c) -{ +void focus(Client *c) { if (!c || !ISVISIBLE(c)) - for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext); + for (c = selmon->stack; c && !ISVISIBLE(c); c = c->snext) + ; if (selmon->sel && selmon->sel != c) unfocus(selmon->sel, 0); if (c) { @@ -936,18 +939,14 @@ focus(Client *c) } /* there are some broken focus acquiring clients needing extra handling */ -void -focusin(XEvent *e) -{ +void focusin(XEvent *e) { XFocusChangeEvent *ev = &e->xfocus; if (selmon->sel && ev->window != selmon->sel->win) setfocus(selmon->sel); } -void -focusmon(const Arg *arg) -{ +void focusmon(const Arg *arg) { Monitor *m; if (!mons->next) @@ -959,17 +958,17 @@ focusmon(const Arg *arg) focus(NULL); } -void -focusstack(const Arg *arg) -{ +void focusstack(const Arg *arg) { Client *c = NULL, *i; if (!selmon->sel) return; if (arg->i > 0) { - for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next); + for (c = selmon->sel->next; c && !ISVISIBLE(c); c = c->next) + ; if (!c) - for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next); + for (c = selmon->clients; c && !ISVISIBLE(c); c = c->next) + ; } else { for (i = selmon->clients; i != selmon->sel; i = i->next) if (ISVISIBLE(i)) @@ -985,25 +984,23 @@ focusstack(const Arg *arg) } } -Atom -getatomprop(Client *c, Atom prop) -{ +Atom getatomprop(Client *c, Atom prop) { int di; unsigned long dl; unsigned char *p = NULL; Atom da, atom = None; if (XGetWindowProperty(dpy, c->win, prop, 0L, sizeof atom, False, XA_ATOM, - &da, &di, &dl, &dl, &p) == Success && p) { - atom = *(Atom *)p; + &da, &di, &dl, &dl, &p) + == Success + && p) { + atom = *(Atom *) p; XFree(p); } return atom; } -pid_t -getstatusbarpid() -{ +pid_t getstatusbarpid() { char buf[32], *str = buf, *c; FILE *fp; @@ -1018,16 +1015,14 @@ getstatusbarpid() return statuspid; } } - if (!(fp = popen("pidof -s "STATUSBAR, "r"))) + if (!(fp = popen("pidof -s " STATUSBAR, "r"))) return -1; fgets(buf, sizeof(buf), fp); pclose(fp); return strtol(buf, NULL, 10); } -int -getrootptr(int *x, int *y) -{ +int getrootptr(int *x, int *y) { int di; unsigned int dui; Window dummy; @@ -1035,17 +1030,17 @@ getrootptr(int *x, int *y) return XQueryPointer(dpy, root, &dummy, &dummy, x, y, &di, &di, &dui); } -long -getstate(Window w) -{ +long getstate(Window w) { int format; - long result = -1; + long result = -1; unsigned char *p = NULL; unsigned long n, extra; Atom real; - if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, wmatom[WMState], - &real, &format, &n, &extra, (unsigned char **)&p) != Success) + if (XGetWindowProperty(dpy, w, wmatom[WMState], 0L, 2L, False, + wmatom[WMState], &real, &format, &n, &extra, + (unsigned char **) &p) + != Success) return -1; if (n != 0) result = *p; @@ -1053,9 +1048,7 @@ getstate(Window w) return result; } -int -gettextprop(Window w, Atom atom, char *text, unsigned int size) -{ +int gettextprop(Window w, Atom atom, char *text, unsigned int size) { char **list = NULL; int n; XTextProperty name; @@ -1066,9 +1059,10 @@ gettextprop(Window w, Atom atom, char *text, unsigned int size) if (!XGetTextProperty(dpy, w, &name, atom) || !name.nitems) return 0; if (name.encoding == XA_STRING) - strncpy(text, (char *)name.value, size - 1); + strncpy(text, (char *) name.value, size - 1); else { - if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success && n > 0 && *list) { + if (XmbTextPropertyToTextList(dpy, &name, &list, &n) >= Success + && n > 0 && *list) { strncpy(text, *list, size - 1); XFreeStringList(list); } @@ -1078,34 +1072,32 @@ gettextprop(Window w, Atom atom, char *text, unsigned int size) return 1; } -void -grabbuttons(Client *c, int focused) -{ +void grabbuttons(Client *c, int focused) { updatenumlockmask(); { unsigned int i, j; - unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask }; + unsigned int modifiers[] = {0, LockMask, numlockmask, + numlockmask | LockMask}; XUngrabButton(dpy, AnyButton, AnyModifier, c->win); if (!focused) XGrabButton(dpy, AnyButton, AnyModifier, c->win, False, - BUTTONMASK, GrabModeSync, GrabModeSync, None, None); + BUTTONMASK, GrabModeSync, GrabModeSync, None, None); for (i = 0; i < LENGTH(buttons); i++) if (buttons[i].click == ClkClientWin) for (j = 0; j < LENGTH(modifiers); j++) XGrabButton(dpy, buttons[i].button, - buttons[i].mask | modifiers[j], - c->win, False, BUTTONMASK, - GrabModeAsync, GrabModeSync, None, None); + buttons[i].mask | modifiers[j], c->win, False, + BUTTONMASK, GrabModeAsync, GrabModeSync, None, + None); } } -void -grabkeys(void) -{ +void grabkeys(void) { updatenumlockmask(); { unsigned int i, j; - unsigned int modifiers[] = { 0, LockMask, numlockmask, numlockmask|LockMask }; + unsigned int modifiers[] = {0, LockMask, numlockmask, + numlockmask | LockMask}; KeyCode code; XUngrabKey(dpy, AnyKey, AnyModifier, root); @@ -1113,13 +1105,11 @@ grabkeys(void) if ((code = XKeysymToKeycode(dpy, keys[i].keysym))) for (j = 0; j < LENGTH(modifiers); j++) XGrabKey(dpy, code, keys[i].mod | modifiers[j], root, - True, GrabModeAsync, GrabModeAsync); + True, GrabModeAsync, GrabModeAsync); } } -int -handlexevent(struct epoll_event *ev) -{ +int handlexevent(struct epoll_event *ev) { if (ev->events & EPOLLIN) { XEvent ev; while (running && XPending(dpy)) { @@ -1129,51 +1119,44 @@ handlexevent(struct epoll_event *ev) ipc_send_events(mons, &lastselmon, selmon); } } - } else if (ev-> events & EPOLLHUP) { + } else if (ev->events & EPOLLHUP) { return -1; } return 0; } -void -incnmaster(const Arg *arg) -{ +void incnmaster(const Arg *arg) { selmon->nmaster = MAX(selmon->nmaster + arg->i, 0); arrange(selmon); } #ifdef XINERAMA -static int -isuniquegeom(XineramaScreenInfo *unique, size_t n, XineramaScreenInfo *info) -{ +static int isuniquegeom(XineramaScreenInfo *unique, size_t n, + XineramaScreenInfo *info) { while (n--) if (unique[n].x_org == info->x_org && unique[n].y_org == info->y_org - && unique[n].width == info->width && unique[n].height == info->height) + && unique[n].width == info->width + && unique[n].height == info->height) return 0; return 1; } #endif /* XINERAMA */ -void -keypress(XEvent *e) -{ +void keypress(XEvent *e) { unsigned int i; KeySym keysym; XKeyEvent *ev; - ev = &e->xkey; - keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0); + ev = &e->xkey; + keysym = XKeycodeToKeysym(dpy, (KeyCode) ev->keycode, 0); for (i = 0; i < LENGTH(keys); i++) if (keysym == keys[i].keysym - && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state) - && keys[i].func) + && CLEANMASK(keys[i].mod) == CLEANMASK(ev->state) && keys[i].func) keys[i].func(&(keys[i].arg)); } -void -killclient(const Arg *arg) -{ +void killclient(const Arg *arg) { if (!selmon->sel) return; if (!sendevent(selmon->sel, wmatom[WMDelete])) { @@ -1187,25 +1170,23 @@ killclient(const Arg *arg) } } -void -manage(Window w, XWindowAttributes *wa) -{ +void manage(Window w, XWindowAttributes *wa) { Client *c, *t = NULL; Window trans = None; XWindowChanges wc; - c = ecalloc(1, sizeof(Client)); + c = ecalloc(1, sizeof(Client)); c->win = w; /* geometry */ c->x = c->oldx = wa->x; c->y = c->oldy = wa->y; c->w = c->oldw = wa->width; c->h = c->oldh = wa->height; - c->oldbw = wa->border_width; + c->oldbw = wa->border_width; updatetitle(c); if (XGetTransientForHint(dpy, w, &trans) && (t = wintoclient(trans))) { - c->mon = t->mon; + c->mon = t->mon; c->tags = t->tags; } else { c->mon = selmon; @@ -1218,14 +1199,19 @@ manage(Window w, XWindowAttributes *wa) c->y = c->mon->my + c->mon->mh - HEIGHT(c); c->x = MAX(c->x, c->mon->mx); /* only fix client y-offset, if the client center might cover the bar */ - c->y = MAX(c->y, ((c->mon->by == c->mon->my) && (c->x + (c->w / 2) >= c->mon->wx) - && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) ? bh : c->mon->my); + c->y = MAX(c->y, ((c->mon->by == c->mon->my) + && (c->x + (c->w / 2) >= c->mon->wx) + && (c->x + (c->w / 2) < c->mon->wx + c->mon->ww)) + ? bh + : c->mon->my); c->bw = borderpx; wc.border_width = c->bw; - if(c->x == selmon->wx) c->x += (c->mon->ww - WIDTH(c)) / 2 - c->bw; - if(c->y == selmon->wy) c->y += (c->mon->wh - HEIGHT(c)) / 2 - c->bw; + if (c->x == selmon->wx) + c->x += (c->mon->ww - WIDTH(c)) / 2 - c->bw; + if (c->y == selmon->wy) + c->y += (c->mon->wh - HEIGHT(c)) / 2 - c->bw; XConfigureWindow(dpy, w, CWBorderWidth, &wc); XSetWindowBorder(dpy, w, scheme[SchemeNorm][ColBorder].pixel); @@ -1233,7 +1219,9 @@ manage(Window w, XWindowAttributes *wa) updatewindowtype(c); updatesizehints(c); updatewmhints(c); - XSelectInput(dpy, w, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask); + XSelectInput(dpy, w, + EnterWindowMask | FocusChangeMask | PropertyChangeMask + | StructureNotifyMask); grabbuttons(c, 0); if (!c->isfloating) c->isfloating = c->oldstate = trans != None || c->isfixed; @@ -1241,9 +1229,10 @@ manage(Window w, XWindowAttributes *wa) XRaiseWindow(dpy, c->win); attachtop(c); attachstack(c); - XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend, - (unsigned char *) &(c->win), 1); - XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, c->h); /* some windows require this */ + XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, + PropModeAppend, (unsigned char *) &(c->win), 1); + XMoveResizeWindow(dpy, c->win, c->x + 2 * sw, c->y, c->w, + c->h); /* some windows require this */ setclientstate(c, NormalState); if (c->mon == selmon) unfocus(selmon->sel, 0); @@ -1253,48 +1242,45 @@ manage(Window w, XWindowAttributes *wa) focus(NULL); } -void -managealtbar(Window win, XWindowAttributes *wa) -{ +void managealtbar(Window win, XWindowAttributes *wa) { Monitor *m; if (!(m = recttomon(wa->x, wa->y, wa->width, wa->height))) return; m->barwin = win; - m->by = wa->y; + m->by = wa->y; bh = m->bh = wa->height; updatebarpos(m); arrange(m); - XSelectInput(dpy, win, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask); + XSelectInput(dpy, win, + EnterWindowMask | FocusChangeMask | PropertyChangeMask + | StructureNotifyMask); XMoveResizeWindow(dpy, win, wa->x, wa->y, wa->width, wa->height); XMapWindow(dpy, win); - XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend, - (unsigned char *) &win, 1); + XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, + PropModeAppend, (unsigned char *) &win, 1); } -void -managetray(Window win, XWindowAttributes *wa) -{ +void managetray(Window win, XWindowAttributes *wa) { Monitor *m; if (!(m = recttomon(wa->x, wa->y, wa->width, wa->height))) return; m->traywin = win; - m->tx = wa->x; - m->tw = wa->width; + m->tx = wa->x; + m->tw = wa->width; updatebarpos(m); arrange(m); - XSelectInput(dpy, win, EnterWindowMask|FocusChangeMask|PropertyChangeMask|StructureNotifyMask); + XSelectInput(dpy, win, + EnterWindowMask | FocusChangeMask | PropertyChangeMask + | StructureNotifyMask); XMoveResizeWindow(dpy, win, wa->x, wa->y, wa->width, wa->height); XMapWindow(dpy, win); - XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, PropModeAppend, - (unsigned char *) &win, 1); + XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, + PropModeAppend, (unsigned char *) &win, 1); } - -void -mappingnotify(XEvent *e) -{ +void mappingnotify(XEvent *e) { XMappingEvent *ev = &e->xmapping; XRefreshKeyboardMapping(ev); @@ -1302,9 +1288,7 @@ mappingnotify(XEvent *e) grabkeys(); } -void -maprequest(XEvent *e) -{ +void maprequest(XEvent *e) { static XWindowAttributes wa; XMapRequestEvent *ev = &e->xmaprequest; @@ -1318,9 +1302,7 @@ maprequest(XEvent *e) manage(ev->window, &wa); } -void -monocle(Monitor *m) -{ +void monocle(Monitor *m) { unsigned int n = 0; Client *c; @@ -1333,9 +1315,7 @@ monocle(Monitor *m) resize(c, m->wx, m->wy, m->ww - 2 * c->bw, m->wh - 2 * c->bw, 0); } -void -motionnotify(XEvent *e) -{ +void motionnotify(XEvent *e) { static Monitor *mon = NULL; Monitor *m; XMotionEvent *ev = &e->xmotion; @@ -1350,9 +1330,7 @@ motionnotify(XEvent *e) mon = m; } -void -movemouse(const Arg *arg) -{ +void movemouse(const Arg *arg) { int x, y, ocx, ocy, nx, ny; Client *c; Monitor *m; @@ -1366,14 +1344,17 @@ movemouse(const Arg *arg) restack(selmon); ocx = c->x; ocy = c->y; - if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync, - None, cursor[CurMove]->cursor, CurrentTime) != GrabSuccess) + if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, + GrabModeAsync, None, cursor[CurMove]->cursor, + CurrentTime) + != GrabSuccess) return; if (!getrootptr(&x, &y)) return; do { - XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev); - switch(ev.type) { + XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, + &ev); + switch (ev.type) { case ConfigureRequest: case Expose: case MapRequest: @@ -1395,7 +1376,7 @@ movemouse(const Arg *arg) else if (abs((selmon->wy + selmon->wh) - (ny + HEIGHT(c))) < snap) ny = selmon->wy + selmon->wh - HEIGHT(c); if (!c->isfloating && selmon->lt[selmon->sellt]->arrange - && (abs(nx - c->x) > snap || abs(ny - c->y) > snap)) + && (abs(nx - c->x) > snap || abs(ny - c->y) > snap)) togglefloating(NULL); if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) resize(c, nx, ny, c->w, c->h, 1); @@ -1410,8 +1391,7 @@ movemouse(const Arg *arg) } } -void -moveresize(const Arg *arg) { +void moveresize(const Arg *arg) { /* only floating windows can be moved */ Client *c; c = selmon->sel; @@ -1425,10 +1405,13 @@ moveresize(const Arg *arg) { return; if (selmon->lt[selmon->sellt]->arrange && !c->isfloating) return; - if (sscanf((char *)arg->v, "%d%c %d%c %d%c %d%c", &x, &xAbs, &y, &yAbs, &w, &wAbs, &h, &hAbs) != 8) + if (sscanf((char *) arg->v, "%d%c %d%c %d%c %d%c", &x, &xAbs, &y, &yAbs, + &w, &wAbs, &h, &hAbs) + != 8) return; - /* compute new window position; prevent window from be positioned outside the current monitor */ + /* compute new window position; prevent window from be positioned outside + * the current monitor */ nw = c->w + w; if (wAbs == 'W') nw = w < selmon->mw - 2 * c->bw ? w : selmon->mw - 2 * c->bw; @@ -1463,20 +1446,21 @@ moveresize(const Arg *arg) { oh = c->h; XRaiseWindow(dpy, c->win); - Bool xqp = XQueryPointer(dpy, root, &dummy, &dummy, &msx, &msy, &dx, &dy, &dui); + Bool xqp = + XQueryPointer(dpy, root, &dummy, &dummy, &msx, &msy, &dx, &dy, &dui); resize(c, nx, ny, nw, nh, True); - /* move cursor along with the window to avoid problems caused by the sloppy focus */ - if (xqp && ox <= msx && (ox + ow) >= msx && oy <= msy && (oy + oh) >= msy) - { + /* move cursor along with the window to avoid problems caused by the + * sloppy focus */ + if (xqp && ox <= msx && (ox + ow) >= msx && oy <= msy + && (oy + oh) >= msy) { nmx = c->x - ox + c->w - ow; nmy = c->y - oy + c->h - oh; XWarpPointer(dpy, None, None, 0, 0, 0, 0, nmx, nmy); } } -void -moveresizeedge(const Arg *arg) { +void moveresizeedge(const Arg *arg) { /* move or resize floating window to edge of screen */ Client *c; c = selmon->sel; @@ -1493,30 +1477,35 @@ moveresizeedge(const Arg *arg) { nh = c->h; starty = selmon->showbar && topbar ? bh : 0; - bp = selmon->showbar && !topbar ? bh : 0; + bp = selmon->showbar && !topbar ? bh : 0; if (!c || !arg) return; if (selmon->lt[selmon->sellt]->arrange && !c->isfloating) return; - if(sscanf((char *)arg->v, "%c", &e) != 1) + if (sscanf((char *) arg->v, "%c", &e) != 1) return; - if(e == 't') + if (e == 't') ny = starty; - if(e == 'b') - ny = c->h > selmon->mh - 2 * c->bw ? c->h - bp : selmon->mh - c->h - 2 * c->bw - bp; + if (e == 'b') + ny = c->h > selmon->mh - 2 * c->bw + ? c->h - bp + : selmon->mh - c->h - 2 * c->bw - bp; - if(e == 'l') + if (e == 'l') nx = selmon->mx; - if(e == 'r') - nx = c->w > selmon->mw - 2 * c->bw ? selmon->mx + c->w : selmon->mx + selmon->mw - c->w - 2 * c->bw; + if (e == 'r') + nx = c->w > selmon->mw - 2 * c->bw + ? selmon->mx + c->w + : selmon->mx + selmon->mw - c->w - 2 * c->bw; - if(e == 'T') { - /* if you click to resize again, it will return to old size/position */ - if(c->h + starty == c->oldh + c->oldy) { + if (e == 'T') { + /* if you click to resize again, it will return to old size/position + */ + if (c->h + starty == c->oldh + c->oldy) { nh = c->oldh; ny = c->oldy; } else { @@ -1525,11 +1514,13 @@ moveresizeedge(const Arg *arg) { } } - if(e == 'B') - nh = c->h + c->y + 2 * c->bw + bp == selmon->mh ? c->oldh : selmon->mh - c->y - 2 * c->bw - bp; + if (e == 'B') + nh = c->h + c->y + 2 * c->bw + bp == selmon->mh + ? c->oldh + : selmon->mh - c->y - 2 * c->bw - bp; - if(e == 'L') { - if(selmon->mx + c->w == c->oldw + c->oldx) { + if (e == 'L') { + if (selmon->mx + c->w == c->oldw + c->oldx) { nw = c->oldw; nx = c->oldx; } else { @@ -1538,8 +1529,10 @@ moveresizeedge(const Arg *arg) { } } - if(e == 'R') - nw = c->w + c->x + 2 * c->bw == selmon->mx + selmon->mw ? c->oldw : selmon->mx + selmon->mw - c->x - 2 * c->bw; + if (e == 'R') + nw = c->w + c->x + 2 * c->bw == selmon->mx + selmon->mw + ? c->oldw + : selmon->mx + selmon->mw - c->x - 2 * c->bw; ox = c->x; oy = c->y; @@ -1547,36 +1540,34 @@ moveresizeedge(const Arg *arg) { oh = c->h; XRaiseWindow(dpy, c->win); - Bool xqp = XQueryPointer(dpy, root, &dummy, &dummy, &msx, &msy, &dx, &dy, &dui); + Bool xqp = + XQueryPointer(dpy, root, &dummy, &dummy, &msx, &msy, &dx, &dy, &dui); resize(c, nx, ny, nw, nh, True); - /* move cursor along with the window to avoid problems caused by the sloppy focus */ - if (xqp && ox <= msx && (ox + ow) >= msx && oy <= msy && (oy + oh) >= msy) { + /* move cursor along with the window to avoid problems caused by the + * sloppy focus */ + if (xqp && ox <= msx && (ox + ow) >= msx && oy <= msy + && (oy + oh) >= msy) { nmx = c->x - ox + c->w - ow; nmy = c->y - oy + c->h - oh; XWarpPointer(dpy, None, None, 0, 0, 0, 0, nmx, nmy); } } -Client * -nexttiled(Client *c) -{ - for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next); +Client *nexttiled(Client *c) { + for (; c && (c->isfloating || !ISVISIBLE(c)); c = c->next) + ; return c; } -void -pop(Client *c) -{ +void pop(Client *c) { detach(c); attach(c); focus(c); arrange(c->mon); } -void -propertynotify(XEvent *e) -{ +void propertynotify(XEvent *e) { Client *c; Window trans; XPropertyEvent *ev = &e->xproperty; @@ -1586,11 +1577,12 @@ propertynotify(XEvent *e) else if (ev->state == PropertyDelete) return; /* ignore */ else if ((c = wintoclient(ev->window))) { - switch(ev->atom) { - default: break; + switch (ev->atom) { + default: + break; case XA_WM_TRANSIENT_FOR: - if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) && - (c->isfloating = (wintoclient(trans)) != NULL)) + if (!c->isfloating && (XGetTransientForHint(dpy, c->win, &trans)) + && (c->isfloating = (wintoclient(trans)) != NULL)) arrange(c->mon); break; case XA_WM_NORMAL_HINTS: @@ -1611,51 +1603,46 @@ propertynotify(XEvent *e) } } -void -quit(const Arg *arg) -{ +void quit(const Arg *arg) { running = 0; } -Monitor * -recttomon(int x, int y, int w, int h) -{ +Monitor *recttomon(int x, int y, int w, int h) { Monitor *m, *r = selmon; - int a, area = 0; + int a, area = 0; for (m = mons; m; m = m->next) if ((a = INTERSECT(x, y, w, h, m)) > area) { area = a; - r = m; + r = m; } return r; } -void -resize(Client *c, int x, int y, int w, int h, int interact) -{ +void resize(Client *c, int x, int y, int w, int h, int interact) { if (applysizehints(c, &x, &y, &w, &h, interact)) resizeclient(c, x, y, w, h); } -void -resizeclient(Client *c, int x, int y, int w, int h) -{ +void resizeclient(Client *c, int x, int y, int w, int h) { XWindowChanges wc; - c->oldx = c->x; c->x = wc.x = x; - c->oldy = c->y; c->y = wc.y = y; - c->oldw = c->w; c->w = wc.width = w; - c->oldh = c->h; c->h = wc.height = h; - wc.border_width = c->bw; - XConfigureWindow(dpy, c->win, CWX|CWY|CWWidth|CWHeight|CWBorderWidth, &wc); + c->oldx = c->x; + c->x = wc.x = x; + c->oldy = c->y; + c->y = wc.y = y; + c->oldw = c->w; + c->w = wc.width = w; + c->oldh = c->h; + c->h = wc.height = h; + wc.border_width = c->bw; + XConfigureWindow(dpy, c->win, + CWX | CWY | CWWidth | CWHeight | CWBorderWidth, &wc); configure(c); XSync(dpy, False); } -void -resizemouse(const Arg *arg) -{ +void resizemouse(const Arg *arg) { int ocx, ocy, nw, nh; Client *c; Monitor *m; @@ -1669,13 +1656,17 @@ resizemouse(const Arg *arg) restack(selmon); ocx = c->x; ocy = c->y; - if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, GrabModeAsync, - None, cursor[CurResize]->cursor, CurrentTime) != GrabSuccess) + if (XGrabPointer(dpy, root, False, MOUSEMASK, GrabModeAsync, + GrabModeAsync, None, cursor[CurResize]->cursor, + CurrentTime) + != GrabSuccess) return; - XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1); + XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, + c->h + c->bw - 1); do { - XMaskEvent(dpy, MOUSEMASK|ExposureMask|SubstructureRedirectMask, &ev); - switch(ev.type) { + XMaskEvent(dpy, MOUSEMASK | ExposureMask | SubstructureRedirectMask, + &ev); + switch (ev.type) { case ConfigureRequest: case Expose: case MapRequest: @@ -1688,11 +1679,12 @@ resizemouse(const Arg *arg) nw = MAX(ev.xmotion.x - ocx - 2 * c->bw + 1, 1); nh = MAX(ev.xmotion.y - ocy - 2 * c->bw + 1, 1); - if (c->mon->wx + nw >= selmon->wx && c->mon->wx + nw <= selmon->wx + selmon->ww - && c->mon->wy + nh >= selmon->wy && c->mon->wy + nh <= selmon->wy + selmon->wh) - { + if (c->mon->wx + nw >= selmon->wx + && c->mon->wx + nw <= selmon->wx + selmon->ww + && c->mon->wy + nh >= selmon->wy + && c->mon->wy + nh <= selmon->wy + selmon->wh) { if (!c->isfloating && selmon->lt[selmon->sellt]->arrange - && (abs(nw - c->w) > snap || abs(nh - c->h) > snap)) + && (abs(nw - c->w) > snap || abs(nh - c->h) > snap)) togglefloating(NULL); } if (!selmon->lt[selmon->sellt]->arrange || c->isfloating) @@ -1700,9 +1692,11 @@ resizemouse(const Arg *arg) break; } } while (ev.type != ButtonRelease); - XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, c->h + c->bw - 1); + XWarpPointer(dpy, None, c->win, 0, 0, 0, 0, c->w + c->bw - 1, + c->h + c->bw - 1); XUngrabPointer(dpy, CurrentTime); - while (XCheckMaskEvent(dpy, EnterWindowMask, &ev)); + while (XCheckMaskEvent(dpy, EnterWindowMask, &ev)) + ; if ((m = recttomon(c->x, c->y, c->w, c->h)) != selmon) { sendmon(c, m); selmon = m; @@ -1710,9 +1704,7 @@ resizemouse(const Arg *arg) } } -void -restack(Monitor *m) -{ +void restack(Monitor *m) { Client *c; XEvent ev; XWindowChanges wc; @@ -1724,21 +1716,20 @@ restack(Monitor *m) XRaiseWindow(dpy, m->sel->win); if (m->lt[m->sellt]->arrange) { wc.stack_mode = Below; - wc.sibling = m->barwin; + wc.sibling = m->barwin; for (c = m->stack; c; c = c->snext) if (!c->isfloating && ISVISIBLE(c)) { - XConfigureWindow(dpy, c->win, CWSibling|CWStackMode, &wc); + XConfigureWindow(dpy, c->win, CWSibling | CWStackMode, &wc); wc.sibling = c->win; } } XSync(dpy, False); - while (XCheckMaskEvent(dpy, EnterWindowMask, &ev)); + while (XCheckMaskEvent(dpy, EnterWindowMask, &ev)) + ; } -void -run(void) -{ - int event_count = 0; +void run(void) { + int event_count = 0; const int MAX_EVENTS = 10; struct epoll_event events[MAX_EVENTS]; @@ -1758,15 +1749,20 @@ run(void) return; } else if (event_fd == ipc_get_sock_fd()) { ipc_handle_socket_epoll_event(events + i); - } else if (ipc_is_client_registered(event_fd)){ - if (ipc_handle_client_epoll_event(events + i, mons, &lastselmon, selmon, - tags, LENGTH(tags), layouts, LENGTH(layouts)) < 0) { - fprintf(stderr, "Error handling IPC event on fd %d\n", event_fd); + } else if (ipc_is_client_registered(event_fd)) { + if (ipc_handle_client_epoll_event( + events + i, mons, &lastselmon, selmon, tags, + LENGTH(tags), layouts, LENGTH(layouts)) + < 0) { + fprintf(stderr, "Error handling IPC event on fd %d\n", + event_fd); } } else { - fprintf(stderr, "Got event from unknown fd %d, ptr %p, u32 %d, u64 %lu", - event_fd, events[i].data.ptr, events[i].data.u32, - events[i].data.u64); + fprintf( + stderr, + "Got event from unknown fd %d, ptr %p, u32 %d, u64 %lu", + event_fd, events[i].data.ptr, events[i].data.u32, + events[i].data.u64); fprintf(stderr, " with events %d\n", events[i].events); return; } @@ -1774,9 +1770,7 @@ run(void) } } -void -runautostart(void) -{ +void runautostart(void) { char *pathpfx; char *path; char *xdgdatahome; @@ -1802,7 +1796,7 @@ runautostart(void) } else { /* space for path segments, separators and nul */ pathpfx = ecalloc(1, strlen(home) + strlen(localshare) - + strlen(dwmdir) + 3); + + strlen(dwmdir) + 3); if (sprintf(pathpfx, "%s/%s/%s", home, localshare, dwmdir) < 0) { free(pathpfx); @@ -1811,12 +1805,13 @@ runautostart(void) } /* check if the autostart script directory exists */ - if (! (stat(pathpfx, &sb) == 0 && S_ISDIR(sb.st_mode))) { + if (!(stat(pathpfx, &sb) == 0 && S_ISDIR(sb.st_mode))) { /* the XDG conformant path does not exist or is no directory * so we try ~/.dwm instead */ - char *pathpfx_new = realloc(pathpfx, strlen(home) + strlen(dwmdir) + 3); - if(pathpfx_new == NULL) { + char *pathpfx_new = + realloc(pathpfx, strlen(home) + strlen(dwmdir) + 3); + if (pathpfx_new == NULL) { free(pathpfx); return; } @@ -1851,9 +1846,7 @@ runautostart(void) free(path); } -void -scan(void) -{ +void scan(void) { unsigned int i, num; Window d1, d2, *wins = NULL; XWindowAttributes wa; @@ -1861,18 +1854,21 @@ scan(void) if (XQueryTree(dpy, root, &d1, &d2, &wins, &num)) { for (i = 0; i < num; i++) { if (!XGetWindowAttributes(dpy, wins[i], &wa) - || wa.override_redirect || XGetTransientForHint(dpy, wins[i], &d1)) + || wa.override_redirect + || XGetTransientForHint(dpy, wins[i], &d1)) continue; if (wmclasscontains(wins[i], altbarclass, "")) managealtbar(wins[i], &wa); - else if (wa.map_state == IsViewable || getstate(wins[i]) == IconicState) + else if (wa.map_state == IsViewable + || getstate(wins[i]) == IconicState) manage(wins[i], &wa); } for (i = 0; i < num; i++) { /* now the transients */ if (!XGetWindowAttributes(dpy, wins[i], &wa)) continue; if (XGetTransientForHint(dpy, wins[i], &d1) - && (wa.map_state == IsViewable || getstate(wins[i]) == IconicState)) + && (wa.map_state == IsViewable + || getstate(wins[i]) == IconicState)) manage(wins[i], &wa); } if (wins) @@ -1880,9 +1876,7 @@ scan(void) } } -void -scantray(void) -{ +void scantray(void) { unsigned int num; Window d1, d2, *wins = NULL; XWindowAttributes wa; @@ -1901,17 +1895,13 @@ scantray(void) XFree(wins); } - - -void -sendmon(Client *c, Monitor *m) -{ +void sendmon(Client *c, Monitor *m) { if (c->mon == m) return; unfocus(c, 1); detach(c); detachstack(c); - c->mon = m; + c->mon = m; c->tags = m->tagset[m->seltags]; /* assign tags of target monitor */ attachtop(c); attachstack(c); @@ -1919,18 +1909,14 @@ sendmon(Client *c, Monitor *m) arrange(NULL); } -void -setclientstate(Client *c, long state) -{ - long data[] = { state, None }; +void setclientstate(Client *c, long state) { + long data[] = {state, None}; XChangeProperty(dpy, c->win, wmatom[WMState], wmatom[WMState], 32, - PropModeReplace, (unsigned char *)data, 2); + PropModeReplace, (unsigned char *) data, 2); } -int -sendevent(Client *c, Atom proto) -{ +int sendevent(Client *c, Atom proto) { int n; Atom *protocols; int exists = 0; @@ -1942,60 +1928,54 @@ sendevent(Client *c, Atom proto) XFree(protocols); } if (exists) { - ev.type = ClientMessage; - ev.xclient.window = c->win; + ev.type = ClientMessage; + ev.xclient.window = c->win; ev.xclient.message_type = wmatom[WMProtocols]; - ev.xclient.format = 32; - ev.xclient.data.l[0] = proto; - ev.xclient.data.l[1] = CurrentTime; + ev.xclient.format = 32; + ev.xclient.data.l[0] = proto; + ev.xclient.data.l[1] = CurrentTime; XSendEvent(dpy, c->win, False, NoEventMask, &ev); } return exists; } -void -setfocus(Client *c) -{ +void setfocus(Client *c) { if (!c->neverfocus) { XSetInputFocus(dpy, c->win, RevertToPointerRoot, CurrentTime); - XChangeProperty(dpy, root, netatom[NetActiveWindow], - XA_WINDOW, 32, PropModeReplace, - (unsigned char *) &(c->win), 1); + XChangeProperty(dpy, root, netatom[NetActiveWindow], XA_WINDOW, 32, + PropModeReplace, (unsigned char *) &(c->win), 1); } sendevent(c, wmatom[WMTakeFocus]); } -void -setfullscreen(Client *c, int fullscreen) -{ +void setfullscreen(Client *c, int fullscreen) { if (fullscreen && !c->isfullscreen) { XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, - PropModeReplace, (unsigned char*)&netatom[NetWMFullscreen], 1); + PropModeReplace, + (unsigned char *) &netatom[NetWMFullscreen], 1); c->isfullscreen = 1; - c->oldstate = c->isfloating; - c->oldbw = c->bw; - c->bw = 0; - c->isfloating = 1; + c->oldstate = c->isfloating; + c->oldbw = c->bw; + c->bw = 0; + c->isfloating = 1; resizeclient(c, c->mon->mx, c->mon->my, c->mon->mw, c->mon->mh); XRaiseWindow(dpy, c->win); - } else if (!fullscreen && c->isfullscreen){ + } else if (!fullscreen && c->isfullscreen) { XChangeProperty(dpy, c->win, netatom[NetWMState], XA_ATOM, 32, - PropModeReplace, (unsigned char*)0, 0); + PropModeReplace, (unsigned char *) 0, 0); c->isfullscreen = 0; - c->isfloating = c->oldstate; - c->bw = c->oldbw; - c->x = c->oldx; - c->y = c->oldy; - c->w = c->oldw; - c->h = c->oldh; + c->isfloating = c->oldstate; + c->bw = c->oldbw; + c->x = c->oldx; + c->y = c->oldy; + c->w = c->oldw; + c->h = c->oldh; resizeclient(c, c->x, c->y, c->w, c->h); arrange(c->mon); } } -void -setgaps(const Arg *arg) -{ +void setgaps(const Arg *arg) { if ((arg->i == 0) || (selmon->gappx + arg->i < 0)) selmon->gappx = 0; else @@ -2003,35 +1983,30 @@ setgaps(const Arg *arg) arrange(selmon); } -void -switchgaps(const Arg *arg) -{ - selmon->gapidx = (selmon->gapidx + arg->i) % LENGTH(gapmodes); - selmon->gappx = gapmodes[selmon->gapidx]; +void switchgaps(const Arg *arg) { + selmon->gapidx = (selmon->gapidx + arg->i) % LENGTH(gapmodes); + selmon->gappx = gapmodes[selmon->gapidx]; arrange(selmon); } -void -setlayout(const Arg *arg) -{ +void setlayout(const Arg *arg) { if (!arg || !arg->v || arg->v != selmon->lt[selmon->sellt]) selmon->sellt ^= 1; if (arg && arg->v) - selmon->lt[selmon->sellt] = (Layout *)arg->v; - strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, sizeof selmon->ltsymbol); + selmon->lt[selmon->sellt] = (Layout *) arg->v; + strncpy(selmon->ltsymbol, selmon->lt[selmon->sellt]->symbol, + sizeof selmon->ltsymbol); if (selmon->sel) arrange(selmon); else drawbar(selmon); } -void -setlayoutsafe(const Arg *arg) -{ - const Layout *ltptr = (Layout *)arg->v; +void setlayoutsafe(const Arg *arg) { + const Layout *ltptr = (Layout *) arg->v; if (ltptr == 0) - setlayout(arg); + setlayout(arg); for (int i = 0; i < LENGTH(layouts); i++) { if (ltptr == &layouts[i]) setlayout(arg); @@ -2039,9 +2014,7 @@ setlayoutsafe(const Arg *arg) } /* arg > 1.0 will set mfact absolutely */ -void -setmfact(const Arg *arg) -{ +void setmfact(const Arg *arg) { float f; if (!arg || !selmon->lt[selmon->sellt]->arrange) @@ -2053,9 +2026,7 @@ setmfact(const Arg *arg) arrange(selmon); } -void -setup(void) -{ +void setup(void) { int i; XSetWindowAttributes wa; Atom utf8string; @@ -2065,34 +2036,36 @@ setup(void) /* init screen */ screen = DefaultScreen(dpy); - sw = DisplayWidth(dpy, screen); - sh = DisplayHeight(dpy, screen); - root = RootWindow(dpy, screen); - drw = drw_create(dpy, screen, root, sw, sh); + sw = DisplayWidth(dpy, screen); + sh = DisplayHeight(dpy, screen); + root = RootWindow(dpy, screen); + drw = drw_create(dpy, screen, root, sw, sh); if (!drw_fontset_create(drw, fonts, LENGTH(fonts))) die("no fonts could be loaded."); lrpad = drw->fonts->h; - bh = usealtbar ? 0 : drw->fonts->h + barverticalpadding; + bh = usealtbar ? 0 : drw->fonts->h + barverticalpadding; updategeom(); /* init atoms */ - utf8string = XInternAtom(dpy, "UTF8_STRING", False); - wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False); - wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False); - wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False); - wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False); + utf8string = XInternAtom(dpy, "UTF8_STRING", False); + wmatom[WMProtocols] = XInternAtom(dpy, "WM_PROTOCOLS", False); + wmatom[WMDelete] = XInternAtom(dpy, "WM_DELETE_WINDOW", False); + wmatom[WMState] = XInternAtom(dpy, "WM_STATE", False); + wmatom[WMTakeFocus] = XInternAtom(dpy, "WM_TAKE_FOCUS", False); netatom[NetActiveWindow] = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False); - netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False); - netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False); - netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False); + netatom[NetSupported] = XInternAtom(dpy, "_NET_SUPPORTED", False); + netatom[NetWMName] = XInternAtom(dpy, "_NET_WM_NAME", False); + netatom[NetWMState] = XInternAtom(dpy, "_NET_WM_STATE", False); netatom[NetWMCheck] = XInternAtom(dpy, "_NET_SUPPORTING_WM_CHECK", False); - netatom[NetWMFullscreen] = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); + netatom[NetWMFullscreen] = + XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False); - netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False); + netatom[NetWMWindowTypeDialog] = + XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False); netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False); /* init cursors */ cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr); cursor[CurResize] = drw_cur_create(drw, XC_sizing); - cursor[CurMove] = drw_cur_create(drw, XC_fleur); + cursor[CurMove] = drw_cur_create(drw, XC_fleur); /* init appearance */ scheme = ecalloc(LENGTH(colors), sizeof(Clr *)); for (i = 0; i < LENGTH(colors); i++) @@ -2103,21 +2076,22 @@ setup(void) /* supporting window for NetWMCheck */ wmcheckwin = XCreateSimpleWindow(dpy, root, 0, 0, 1, 1, 0, 0, 0); XChangeProperty(dpy, wmcheckwin, netatom[NetWMCheck], XA_WINDOW, 32, - PropModeReplace, (unsigned char *) &wmcheckwin, 1); + PropModeReplace, (unsigned char *) &wmcheckwin, 1); XChangeProperty(dpy, wmcheckwin, netatom[NetWMName], utf8string, 8, - PropModeReplace, (unsigned char *) "dwm", 3); + PropModeReplace, (unsigned char *) "dwm", 3); XChangeProperty(dpy, root, netatom[NetWMCheck], XA_WINDOW, 32, - PropModeReplace, (unsigned char *) &wmcheckwin, 1); + PropModeReplace, (unsigned char *) &wmcheckwin, 1); /* EWMH support per view */ XChangeProperty(dpy, root, netatom[NetSupported], XA_ATOM, 32, - PropModeReplace, (unsigned char *) netatom, NetLast); + PropModeReplace, (unsigned char *) netatom, NetLast); XDeleteProperty(dpy, root, netatom[NetClientList]); /* select events */ - wa.cursor = cursor[CurNormal]->cursor; - wa.event_mask = SubstructureRedirectMask|SubstructureNotifyMask - |ButtonPressMask|PointerMotionMask|EnterWindowMask - |LeaveWindowMask|StructureNotifyMask|PropertyChangeMask; - XChangeWindowAttributes(dpy, root, CWEventMask|CWCursor, &wa); + wa.cursor = cursor[CurNormal]->cursor; + wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask + | ButtonPressMask | PointerMotionMask | EnterWindowMask + | LeaveWindowMask | StructureNotifyMask + | PropertyChangeMask; + XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa); XSelectInput(dpy, root, wa.event_mask); grabkeys(); focus(NULL); @@ -2125,11 +2099,9 @@ setup(void) spawnbar(); } -void -setupepoll(void) -{ +void setupepoll(void) { epoll_fd = epoll_create1(0); - dpy_fd = ConnectionNumber(dpy); + dpy_fd = ConnectionNumber(dpy); struct epoll_event dpy_event; // Initialize struct to 0 @@ -2141,7 +2113,7 @@ setupepoll(void) fputs("Failed to create epoll file descriptor", stderr); } - dpy_event.events = EPOLLIN; + dpy_event.events = EPOLLIN; dpy_event.data.fd = dpy_fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, dpy_fd, &dpy_event)) { fputs("Failed to add display file descriptor to epoll", stderr); @@ -2149,33 +2121,32 @@ setupepoll(void) exit(1); } - if (ipc_init(ipcsockpath, epoll_fd, ipccommands, LENGTH(ipccommands)) < 0) { + if (ipc_init(ipcsockpath, epoll_fd, ipccommands, LENGTH(ipccommands)) + < 0) { fputs("Failed to initialize IPC\n", stderr); } } -void -seturgent(Client *c, int urg) -{ +void seturgent(Client *c, int urg) { XWMHints *wmh; c->isurgent = urg; if (!(wmh = XGetWMHints(dpy, c->win))) return; - wmh->flags = urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint); + wmh->flags = + urg ? (wmh->flags | XUrgencyHint) : (wmh->flags & ~XUrgencyHint); XSetWMHints(dpy, c->win, wmh); XFree(wmh); } -void -showhide(Client *c) -{ +void showhide(Client *c) { if (!c) return; if (ISVISIBLE(c)) { /* show clients top down */ XMoveWindow(dpy, c->win, c->x, c->y); - if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) && !c->isfullscreen) + if ((!c->mon->lt[c->mon->sellt]->arrange || c->isfloating) + && !c->isfullscreen) resize(c, c->x, c->y, c->w, c->h, 0); showhide(c->snext); } else { @@ -2185,17 +2156,14 @@ showhide(Client *c) } } -void -sigchld(int unused) -{ +void sigchld(int unused) { if (signal(SIGCHLD, sigchld) == SIG_ERR) die("can't install SIGCHLD handler:"); - while (0 < waitpid(-1, NULL, WNOHANG)); + while (0 < waitpid(-1, NULL, WNOHANG)) + ; } -void -sigstatusbar(const Arg *arg) -{ +void sigstatusbar(const Arg *arg) { union sigval sv; if (!statussig) @@ -2204,35 +2172,29 @@ sigstatusbar(const Arg *arg) if ((statuspid = getstatusbarpid()) <= 0) return; - sigqueue(statuspid, SIGRTMIN+statussig, sv); + sigqueue(statuspid, SIGRTMIN + statussig, sv); } -void -spawn(const Arg *arg) -{ +void spawn(const Arg *arg) { if (arg->v == dmenucmd) dmenumon[0] = '0' + selmon->num; if (fork() == 0) { if (dpy) close(ConnectionNumber(dpy)); setsid(); - execvp(((char **)arg->v)[0], (char **)arg->v); - fprintf(stderr, "dwm: execvp %s", ((char **)arg->v)[0]); + execvp(((char **) arg->v)[0], (char **) arg->v); + fprintf(stderr, "dwm: execvp %s", ((char **) arg->v)[0]); perror(" failed"); exit(EXIT_SUCCESS); } } -void -spawnbar() -{ +void spawnbar() { if (*altbarcmd) system(altbarcmd); } -void -tag(const Arg *arg) -{ +void tag(const Arg *arg) { if (selmon->sel && arg->ui & TAGMASK) { selmon->sel->tags = arg->ui & TAGMASK; focus(NULL); @@ -2240,21 +2202,18 @@ tag(const Arg *arg) } } -void -tagmon(const Arg *arg) -{ +void tagmon(const Arg *arg) { if (!selmon->sel || !mons->next) return; sendmon(selmon->sel, dirtomon(arg->i)); } -void -tile(Monitor *m) -{ +void tile(Monitor *m) { unsigned int i, n, h, mw, my, ty; Client *c; - for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++); + for (n = 0, c = nexttiled(m->clients); c; c = nexttiled(c->next), n++) + ; if (n == 0) return; @@ -2262,62 +2221,61 @@ tile(Monitor *m) mw = m->nmaster ? m->ww * m->mfact : 0; else mw = m->ww - m->gappx; - for (i = 0, my = ty = m->gappx, c = nexttiled(m->clients); c; c = nexttiled(c->next), i++) + for (i = 0, my = ty = m->gappx, c = nexttiled(m->clients); c; + c = nexttiled(c->next), i++) if (i < m->nmaster) { h = (m->wh - my) / (MIN(n, m->nmaster) - i) - m->gappx; - resize(c, m->wx + m->gappx, m->wy + my, mw - (2*c->bw) - m->gappx, h - (2*c->bw), 0); + resize(c, m->wx + m->gappx, m->wy + my, + mw - (2 * c->bw) - m->gappx, h - (2 * c->bw), 0); if (my + HEIGHT(c) + m->gappx < m->wh) my += HEIGHT(c) + m->gappx; } else { h = (m->wh - ty) / (n - i) - m->gappx; - resize(c, m->wx + mw + m->gappx, m->wy + ty, m->ww - mw - (2*c->bw) - 2*m->gappx, h - (2*c->bw), 0); + resize(c, m->wx + mw + m->gappx, m->wy + ty, + m->ww - mw - (2 * c->bw) - 2 * m->gappx, h - (2 * c->bw), + 0); if (ty + HEIGHT(c) + m->gappx < m->wh) ty += HEIGHT(c) + m->gappx; } } -void -togglebar(const Arg *arg) -{ +void togglebar(const Arg *arg) { /** - * Polybar tray does not raise maprequest event. It must be manually scanned - * for. Scanning it too early while the tray is being populated would give - * wrong dimensions. - */ + * Polybar tray does not raise maprequest event. It must be manually + * scanned for. Scanning it too early while the tray is being populated + * would give wrong dimensions. + */ if (!selmon->traywin) scantray(); selmon->showbar = !selmon->showbar; updatebarpos(selmon); - XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, selmon->bh); - XMoveResizeWindow(dpy, selmon->traywin, selmon->tx, selmon->by, selmon->tw, selmon->bh); + XMoveResizeWindow(dpy, selmon->barwin, selmon->wx, selmon->by, selmon->ww, + selmon->bh); + XMoveResizeWindow(dpy, selmon->traywin, selmon->tx, selmon->by, + selmon->tw, selmon->bh); arrange(selmon); } -void -togglefloating(const Arg *arg) -{ +void togglefloating(const Arg *arg) { if (!selmon->sel) return; if (selmon->sel->isfullscreen) /* no support for fullscreen windows */ return; - selmon->sel->isfloating = !selmon->sel->isfloating || selmon->sel->isfixed; + selmon->sel->isfloating = + !selmon->sel->isfloating || selmon->sel->isfixed; if (selmon->sel->isfloating) - resize(selmon->sel, selmon->sel->x, selmon->sel->y, - selmon->sel->w, selmon->sel->h, 0); + resize(selmon->sel, selmon->sel->x, selmon->sel->y, selmon->sel->w, + selmon->sel->h, 0); arrange(selmon); } -void -togglefullscr(const Arg *arg) -{ - if(selmon->sel) - setfullscreen(selmon->sel, !selmon->sel->isfullscreen); +void togglefullscr(const Arg *arg) { + if (selmon->sel) + setfullscreen(selmon->sel, !selmon->sel->isfullscreen); } -void -toggletag(const Arg *arg) -{ +void toggletag(const Arg *arg) { unsigned int newtags; if (!selmon->sel) @@ -2330,10 +2288,9 @@ toggletag(const Arg *arg) } } -void -toggleview(const Arg *arg) -{ - unsigned int newtagset = selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK); +void toggleview(const Arg *arg) { + unsigned int newtagset = + selmon->tagset[selmon->seltags] ^ (arg->ui & TAGMASK); if (newtagset) { selmon->tagset[selmon->seltags] = newtagset; @@ -2342,9 +2299,7 @@ toggleview(const Arg *arg) } } -void -unfocus(Client *c, int setfocus) -{ +void unfocus(Client *c, int setfocus) { if (!c) return; grabbuttons(c, 0); @@ -2355,9 +2310,7 @@ unfocus(Client *c, int setfocus) } } -void -unmanage(Client *c, int destroyed) -{ +void unmanage(Client *c, int destroyed) { Monitor *m = c->mon; XWindowChanges wc; @@ -2367,7 +2320,8 @@ unmanage(Client *c, int destroyed) wc.border_width = c->oldbw; XGrabServer(dpy); /* avoid race conditions */ XSetErrorHandler(xerrordummy); - XConfigureWindow(dpy, c->win, CWBorderWidth, &wc); /* restore border */ + XConfigureWindow(dpy, c->win, CWBorderWidth, + &wc); /* restore border */ XUngrabButton(dpy, AnyButton, AnyModifier, c->win); setclientstate(c, WithdrawnState); XSync(dpy, False); @@ -2380,39 +2334,33 @@ unmanage(Client *c, int destroyed) arrange(m); } -void -unmanagealtbar(Window w) -{ - Monitor *m = wintomon(w); +void unmanagealtbar(Window w) { + Monitor *m = wintomon(w); - if (!m) - return; + if (!m) + return; - m->barwin = 0; - m->by = 0; - m->bh = 0; - updatebarpos(m); - arrange(m); + m->barwin = 0; + m->by = 0; + m->bh = 0; + updatebarpos(m); + arrange(m); } -void -unmanagetray(Window w) -{ +void unmanagetray(Window w) { Monitor *m = wintomon(w); if (!m) return; m->traywin = 0; - m->tx = 0; - m->tw = 0; + m->tx = 0; + m->tw = 0; updatebarpos(m); arrange(m); } -void -unmapnotify(XEvent *e) -{ +void unmapnotify(XEvent *e) { Client *c; Monitor *m; XUnmapEvent *ev = &e->xunmap; @@ -2428,35 +2376,30 @@ unmapnotify(XEvent *e) unmanagetray(ev->window); } -void -updatebars(void) -{ +void updatebars(void) { if (usealtbar) return; Monitor *m; - XSetWindowAttributes wa = { - .override_redirect = True, - .background_pixmap = ParentRelative, - .event_mask = ButtonPressMask|ExposureMask - }; + XSetWindowAttributes wa = {.override_redirect = True, + .background_pixmap = ParentRelative, + .event_mask = ButtonPressMask | ExposureMask}; XClassHint ch = {"dwm", "dwm"}; for (m = mons; m; m = m->next) { if (m->barwin) continue; - m->barwin = XCreateWindow(dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen), - CopyFromParent, DefaultVisual(dpy, screen), - CWOverrideRedirect|CWBackPixmap|CWEventMask, &wa); + m->barwin = XCreateWindow( + dpy, root, m->wx, m->by, m->ww, bh, 0, DefaultDepth(dpy, screen), + CopyFromParent, DefaultVisual(dpy, screen), + CWOverrideRedirect | CWBackPixmap | CWEventMask, &wa); XDefineCursor(dpy, m->barwin, cursor[CurNormal]->cursor); XMapRaised(dpy, m->barwin); XSetClassHint(dpy, m->barwin, &ch); } } -void -updatebarpos(Monitor *m) -{ +void updatebarpos(Monitor *m) { m->wy = m->my; m->wh = m->mh; if (m->showbar) { @@ -2467,23 +2410,18 @@ updatebarpos(Monitor *m) m->by = -m->bh; } -void -updateclientlist() -{ +void updateclientlist() { Client *c; Monitor *m; XDeleteProperty(dpy, root, netatom[NetClientList]); for (m = mons; m; m = m->next) for (c = m->clients; c; c = c->next) - XChangeProperty(dpy, root, netatom[NetClientList], - XA_WINDOW, 32, PropModeAppend, - (unsigned char *) &(c->win), 1); + XChangeProperty(dpy, root, netatom[NetClientList], XA_WINDOW, 32, + PropModeAppend, (unsigned char *) &(c->win), 1); } -int -updategeom(void) -{ +int updategeom(void) { int dirty = 0; #ifdef XINERAMA @@ -2491,10 +2429,11 @@ updategeom(void) int i, j, n, nn; Client *c; Monitor *m; - XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn); + XineramaScreenInfo *info = XineramaQueryScreens(dpy, &nn); XineramaScreenInfo *unique = NULL; - for (n = 0, m = mons; m; m = m->next, n++); + for (n = 0, m = mons; m; m = m->next, n++) + ; /* only consider unique geometries as separate screens */ unique = ecalloc(nn, sizeof(XineramaScreenInfo)); for (i = 0, j = 0; i < nn; i++) @@ -2504,18 +2443,18 @@ updategeom(void) nn = j; if (n <= nn) { /* new monitors available */ for (i = 0; i < (nn - n); i++) { - for (m = mons; m && m->next; m = m->next); + for (m = mons; m && m->next; m = m->next) + ; if (m) m->next = createmon(); else mons = createmon(); } for (i = 0, m = mons; i < nn && m; m = m->next, i++) - if (i >= n - || unique[i].x_org != m->mx || unique[i].y_org != m->my - || unique[i].width != m->mw || unique[i].height != m->mh) - { - dirty = 1; + if (i >= n || unique[i].x_org != m->mx + || unique[i].y_org != m->my || unique[i].width != m->mw + || unique[i].height != m->mh) { + dirty = 1; m->num = i; m->mx = m->wx = unique[i].x_org; m->my = m->wy = unique[i].y_org; @@ -2525,9 +2464,10 @@ updategeom(void) } } else { /* less monitors available nn < n */ for (i = nn; i < n; i++) { - for (m = mons; m && m->next; m = m->next); + for (m = mons; m && m->next; m = m->next) + ; while ((c = m->clients)) { - dirty = 1; + dirty = 1; m->clients = c->next; detachstack(c); c->mon = mons; @@ -2542,11 +2482,11 @@ updategeom(void) free(unique); } else #endif /* XINERAMA */ - { /* default monitor setup */ + { /* default monitor setup */ if (!mons) mons = createmon(); if (mons->mw != sw || mons->mh != sh) { - dirty = 1; + dirty = 1; mons->mw = mons->ww = sw; mons->mh = mons->wh = sh; updatebarpos(mons); @@ -2559,25 +2499,21 @@ updategeom(void) return dirty; } -void -updatenumlockmask(void) -{ +void updatenumlockmask(void) { unsigned int i, j; XModifierKeymap *modmap; numlockmask = 0; - modmap = XGetModifierMapping(dpy); + modmap = XGetModifierMapping(dpy); for (i = 0; i < 8; i++) for (j = 0; j < modmap->max_keypermod; j++) if (modmap->modifiermap[i * modmap->max_keypermod + j] - == XKeysymToKeycode(dpy, XK_Num_Lock)) + == XKeysymToKeycode(dpy, XK_Num_Lock)) numlockmask = (1 << i); XFreeModifiermap(modmap); } -void -updatesizehints(Client *c) -{ +void updatesizehints(Client *c) { long msize; XSizeHints size; @@ -2611,41 +2547,37 @@ updatesizehints(Client *c) } else c->minw = c->minh = 0; if (size.flags & PAspect) { - c->mina = (float)size.min_aspect.y / size.min_aspect.x; - c->maxa = (float)size.max_aspect.x / size.max_aspect.y; + c->mina = (float) size.min_aspect.y / size.min_aspect.x; + c->maxa = (float) size.max_aspect.x / size.max_aspect.y; } else c->maxa = c->mina = 0.0; - c->isfixed = (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh); + c->isfixed = + (c->maxw && c->maxh && c->maxw == c->minw && c->maxh == c->minh); } -void -updatestatus(void) -{ +void updatestatus(void) { if (!gettextprop(root, XA_WM_NAME, stext, sizeof(stext))) { - strcpy(stext, "dwm-"VERSION); + strcpy(stext, "dwm-" VERSION); statusw = TEXTW(stext) - lrpad + 2; } else { char *text, *s, ch; - statusw = 0; + statusw = 0; for (text = s = stext; *s; s++) { - if ((unsigned char)(*s) < ' ') { + if ((unsigned char) (*s) < ' ') { ch = *s; *s = '\0'; statusw += TEXTW(text) - lrpad; - *s = ch; + *s = ch; text = s + 1; } } statusw += TEXTW(text) - lrpad + 2; - } drawbar(selmon); } -void -updatetitle(Client *c) -{ +void updatetitle(Client *c) { char oldname[sizeof(c->name)]; strcpy(oldname, c->name); @@ -2660,9 +2592,7 @@ updatetitle(Client *c) } } -void -updatewindowtype(Client *c) -{ +void updatewindowtype(Client *c) { Atom state = getatomprop(c, netatom[NetWMState]); Atom wtype = getatomprop(c, netatom[NetWMWindowType]); @@ -2672,9 +2602,7 @@ updatewindowtype(Client *c) c->isfloating = 1; } -void -updatewmhints(Client *c) -{ +void updatewmhints(Client *c) { XWMHints *wmh; if ((wmh = XGetWMHints(dpy, c->win))) { @@ -2691,9 +2619,7 @@ updatewmhints(Client *c) } } -void -view(const Arg *arg) -{ +void view(const Arg *arg) { if ((arg->ui & TAGMASK) == selmon->tagset[selmon->seltags]) return; selmon->seltags ^= 1; /* toggle sel tagset */ @@ -2703,9 +2629,7 @@ view(const Arg *arg) arrange(selmon); } -Client * -wintoclient(Window w) -{ +Client *wintoclient(Window w) { Client *c; Monitor *m; @@ -2716,9 +2640,7 @@ wintoclient(Window w) return NULL; } -Monitor * -wintomon(Window w) -{ +Monitor *wintomon(Window w) { int x, y; Client *c; Monitor *m; @@ -2733,11 +2655,9 @@ wintomon(Window w) return selmon; } -int -wmclasscontains(Window win, const char *class, const char *name) -{ - XClassHint ch = { NULL, NULL }; - int res = 1; +int wmclasscontains(Window win, const char *class, const char *name) { + XClassHint ch = {NULL, NULL}; + int res = 1; if (XGetClassHint(dpy, win, &ch)) { if (ch.res_name && strstr(ch.res_name, name) == NULL) @@ -2758,46 +2678,41 @@ wmclasscontains(Window win, const char *class, const char *name) /* There's no way to check accesses to destroyed windows, thus those cases are * ignored (especially on UnmapNotify's). Other types of errors call Xlibs * default error handler, which may call exit. */ -int -xerror(Display *dpy, XErrorEvent *ee) -{ +int xerror(Display *dpy, XErrorEvent *ee) { if (ee->error_code == BadWindow - || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch) - || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable) - || (ee->request_code == X_PolyFillRectangle && ee->error_code == BadDrawable) - || (ee->request_code == X_PolySegment && ee->error_code == BadDrawable) - || (ee->request_code == X_ConfigureWindow && ee->error_code == BadMatch) - || (ee->request_code == X_GrabButton && ee->error_code == BadAccess) - || (ee->request_code == X_GrabKey && ee->error_code == BadAccess) - || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable)) + || (ee->request_code == X_SetInputFocus && ee->error_code == BadMatch) + || (ee->request_code == X_PolyText8 && ee->error_code == BadDrawable) + || (ee->request_code == X_PolyFillRectangle + && ee->error_code == BadDrawable) + || (ee->request_code == X_PolySegment + && ee->error_code == BadDrawable) + || (ee->request_code == X_ConfigureWindow + && ee->error_code == BadMatch) + || (ee->request_code == X_GrabButton && ee->error_code == BadAccess) + || (ee->request_code == X_GrabKey && ee->error_code == BadAccess) + || (ee->request_code == X_CopyArea && ee->error_code == BadDrawable)) return 0; fprintf(stderr, "dwm: fatal error: request code=%d, error code=%d\n", - ee->request_code, ee->error_code); + ee->request_code, ee->error_code); return xerrorxlib(dpy, ee); /* may call exit */ } -int -xerrordummy(Display *dpy, XErrorEvent *ee) -{ +int xerrordummy(Display *dpy, XErrorEvent *ee) { return 0; } /* Startup Error handler to check if another window manager * is already running. */ -int -xerrorstart(Display *dpy, XErrorEvent *ee) -{ +int xerrorstart(Display *dpy, XErrorEvent *ee) { die("dwm: another window manager is already running"); return -1; } -void -zoom(const Arg *arg) -{ +void zoom(const Arg *arg) { Client *c = selmon->sel; if (!selmon->lt[selmon->sellt]->arrange - || (selmon->sel && selmon->sel->isfloating)) + || (selmon->sel && selmon->sel->isfloating)) return; if (c == nexttiled(selmon->clients)) if (!c || !(c = nexttiled(c->next))) @@ -2805,11 +2720,9 @@ zoom(const Arg *arg) pop(c); } -int -main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { if (argc == 2 && !strcmp("-v", argv[1])) - die("dwm-"VERSION); + die("dwm-" VERSION); else if (argc != 1) die("usage: dwm [-v]"); if (!setlocale(LC_CTYPE, "") || !XSupportsLocale()) diff --git a/src/ipc.c b/src/ipc.c index c404791..a0ebc36 100644 --- a/src/ipc.c +++ b/src/ipc.c @@ -19,163 +19,168 @@ static struct sockaddr_un sockaddr; static struct epoll_event sock_epoll_event; static IPCClientList ipc_clients = NULL; -static int epoll_fd = -1; -static int sock_fd = -1; +static int epoll_fd = -1; +static int sock_fd = -1; static IPCCommand *ipc_commands; static unsigned int ipc_commands_len; // Max size is 1 MB static const uint32_t MAX_MESSAGE_SIZE = 1000000; -static const int IPC_SOCKET_BACKLOG = 5; +static const int IPC_SOCKET_BACKLOG = 5; /** * Create IPC socket at specified path and return file descriptor to socket. * This initializes the static variable sockaddr. */ -static int -ipc_create_socket(const char *filename) -{ - char *normal_filename; - char *parent; - const size_t addr_size = sizeof(struct sockaddr_un); - const int sock_type = SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC; +static int ipc_create_socket(const char *filename) { + char *normal_filename; + char *parent; + const size_t addr_size = sizeof(struct sockaddr_un); + const int sock_type = SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC; - normalizepath(filename, &normal_filename); + normalizepath(filename, &normal_filename); - // In case socket file exists - unlink(normal_filename); + // In case socket file exists + unlink(normal_filename); - // For portability clear the addr structure, since some implementations have - // nonstandard fields in the structure - memset(&sockaddr, 0, addr_size); + // For portability clear the addr structure, since some implementations + // have nonstandard fields in the structure + memset(&sockaddr, 0, addr_size); - parentdir(normal_filename, &parent); - // Create parent directories - mkdirp(parent); - free(parent); + parentdir(normal_filename, &parent); + // Create parent directories + mkdirp(parent); + free(parent); - sockaddr.sun_family = AF_LOCAL; - strcpy(sockaddr.sun_path, normal_filename); - free(normal_filename); + sockaddr.sun_family = AF_LOCAL; + strcpy(sockaddr.sun_path, normal_filename); + free(normal_filename); - sock_fd = socket(AF_LOCAL, sock_type, 0); - if (sock_fd == -1) { - fputs("Failed to create socket\n", stderr); - return -1; - } + sock_fd = socket(AF_LOCAL, sock_type, 0); + if (sock_fd == -1) { + fputs("Failed to create socket\n", stderr); + return -1; + } - DEBUG("Created socket at %s\n", sockaddr.sun_path); + DEBUG("Created socket at %s\n", sockaddr.sun_path); - if (bind(sock_fd, (const struct sockaddr *)&sockaddr, addr_size) == -1) { - fputs("Failed to bind socket\n", stderr); - return -1; - } + if (bind(sock_fd, (const struct sockaddr *) &sockaddr, addr_size) == -1) { + fputs("Failed to bind socket\n", stderr); + return -1; + } - DEBUG("Socket binded\n"); + DEBUG("Socket binded\n"); - if (listen(sock_fd, IPC_SOCKET_BACKLOG) < 0) { - fputs("Failed to listen for connections on socket\n", stderr); - return -1; - } + if (listen(sock_fd, IPC_SOCKET_BACKLOG) < 0) { + fputs("Failed to listen for connections on socket\n", stderr); + return -1; + } - DEBUG("Now listening for connections on socket\n"); + DEBUG("Now listening for connections on socket\n"); - return sock_fd; + return sock_fd; } /** - * Internal function used to receive IPC messages from a given file descriptor. + * Internal function used to receive IPC messages from a given file + * descriptor. * * Returns -1 on error reading (could be EAGAIN or EINTR) * Returns -2 if EOF before header could be read * Returns -3 if invalid IPC header * Returns -4 if message length exceeds MAX_MESSAGE_SIZE */ -static int -ipc_recv_message(int fd, uint8_t *msg_type, uint32_t *reply_size, - uint8_t **reply) -{ - uint32_t read_bytes = 0; - const int32_t to_read = sizeof(dwm_ipc_header_t); - char header[to_read]; - char *walk = header; - - // Try to read header - while (read_bytes < to_read) { - const ssize_t n = read(fd, header + read_bytes, to_read - read_bytes); - - if (n == 0) { - if (read_bytes == 0) { - fprintf(stderr, "Unexpectedly reached EOF while reading header."); - fprintf(stderr, - "Read %" PRIu32 " bytes, expected %" PRIu32 " total bytes.\n", - read_bytes, to_read); - return -2; - } else { - fprintf(stderr, "Unexpectedly reached EOF while reading header."); - fprintf(stderr, - "Read %" PRIu32 " bytes, expected %" PRIu32 " total bytes.\n", - read_bytes, to_read); - return -3; - } - } else if (n == -1) { - // errno will still be set - return -1; - } - - read_bytes += n; - } - - // Check if magic string in header matches - if (memcmp(walk, IPC_MAGIC, IPC_MAGIC_LEN) != 0) { - fprintf(stderr, "Invalid magic string. Got '%.*s', expected '%s'\n", - IPC_MAGIC_LEN, walk, IPC_MAGIC); - return -3; - } - - walk += IPC_MAGIC_LEN; - - // Extract reply size - memcpy(reply_size, walk, sizeof(uint32_t)); - walk += sizeof(uint32_t); - - if (*reply_size > MAX_MESSAGE_SIZE) { - fprintf(stderr, "Message too long: %" PRIu32 " bytes. ", *reply_size); - fprintf(stderr, "Maximum message size is: %d\n", MAX_MESSAGE_SIZE); - return -4; - } - - // Extract message type - memcpy(msg_type, walk, sizeof(uint8_t)); - walk += sizeof(uint8_t); - - if (*reply_size > 0) - (*reply) = malloc(*reply_size); - else - return 0; - - read_bytes = 0; - while (read_bytes < *reply_size) { - const ssize_t n = read(fd, *reply + read_bytes, *reply_size - read_bytes); - - if (n == 0) { - fprintf(stderr, "Unexpectedly reached EOF while reading payload."); - fprintf(stderr, "Read %" PRIu32 " bytes, expected %" PRIu32 " bytes.\n", - read_bytes, *reply_size); - free(*reply); - return -2; - } else if (n == -1) { - // TODO: Should we return and wait for another epoll event? - // This would require saving the partial read in some way. - if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) continue; - - free(*reply); - return -1; - } - - read_bytes += n; - } - - return 0; +static int ipc_recv_message(int fd, uint8_t *msg_type, uint32_t *reply_size, + uint8_t **reply) { + uint32_t read_bytes = 0; + const int32_t to_read = sizeof(dwm_ipc_header_t); + char header[to_read]; + char *walk = header; + + // Try to read header + while (read_bytes < to_read) { + const ssize_t n = read(fd, header + read_bytes, to_read - read_bytes); + + if (n == 0) { + if (read_bytes == 0) { + fprintf(stderr, + "Unexpectedly reached EOF while reading header."); + fprintf(stderr, + "Read %" PRIu32 " bytes, expected %" PRIu32 + " total bytes.\n", + read_bytes, to_read); + return -2; + } else { + fprintf(stderr, + "Unexpectedly reached EOF while reading header."); + fprintf(stderr, + "Read %" PRIu32 " bytes, expected %" PRIu32 + " total bytes.\n", + read_bytes, to_read); + return -3; + } + } else if (n == -1) { + // errno will still be set + return -1; + } + + read_bytes += n; + } + + // Check if magic string in header matches + if (memcmp(walk, IPC_MAGIC, IPC_MAGIC_LEN) != 0) { + fprintf(stderr, "Invalid magic string. Got '%.*s', expected '%s'\n", + IPC_MAGIC_LEN, walk, IPC_MAGIC); + return -3; + } + + walk += IPC_MAGIC_LEN; + + // Extract reply size + memcpy(reply_size, walk, sizeof(uint32_t)); + walk += sizeof(uint32_t); + + if (*reply_size > MAX_MESSAGE_SIZE) { + fprintf(stderr, "Message too long: %" PRIu32 " bytes. ", *reply_size); + fprintf(stderr, "Maximum message size is: %d\n", MAX_MESSAGE_SIZE); + return -4; + } + + // Extract message type + memcpy(msg_type, walk, sizeof(uint8_t)); + walk += sizeof(uint8_t); + + if (*reply_size > 0) + (*reply) = malloc(*reply_size); + else + return 0; + + read_bytes = 0; + while (read_bytes < *reply_size) { + const ssize_t n = + read(fd, *reply + read_bytes, *reply_size - read_bytes); + + if (n == 0) { + fprintf(stderr, + "Unexpectedly reached EOF while reading payload."); + fprintf(stderr, + "Read %" PRIu32 " bytes, expected %" PRIu32 " bytes.\n", + read_bytes, *reply_size); + free(*reply); + return -2; + } else if (n == -1) { + // TODO: Should we return and wait for another epoll event? + // This would require saving the partial read in some way. + if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) + continue; + + free(*reply); + return -1; + } + + read_bytes += n; + } + + return 0; } /** @@ -186,28 +191,27 @@ ipc_recv_message(int fd, uint8_t *msg_type, uint32_t *reply_size, * Returns -1 on unknown error trying to write, errno will carry over from * write() call */ -static ssize_t -ipc_write_message(int fd, const void *buf, size_t count) -{ - size_t written = 0; - - while (written < count) { - const ssize_t n = write(fd, (uint8_t *)buf + written, count - written); - - if (n == -1) { - if (errno == EAGAIN || errno == EWOULDBLOCK) - return written; - else if (errno == EINTR) - continue; - else - return n; - } - - written += n; - DEBUG("Wrote %zu/%zu to client at fd %d\n", written, count, fd); - } - - return written; +static ssize_t ipc_write_message(int fd, const void *buf, size_t count) { + size_t written = 0; + + while (written < count) { + const ssize_t n = + write(fd, (uint8_t *) buf + written, count - written); + + if (n == -1) { + if (errno == EAGAIN || errno == EWOULDBLOCK) + return written; + else if (errno == EINTR) + continue; + else + return n; + } + + written += n; + DEBUG("Wrote %zu/%zu to client at fd %d\n", written, count, fd); + } + + return written; } /** @@ -215,35 +219,31 @@ ipc_write_message(int fd, const void *buf, size_t count) * handle, set yajl options, and in the future any other initialization that * should occur for event messages. */ -static void -ipc_event_init_message(yajl_gen *gen) -{ - *gen = yajl_gen_alloc(NULL); - yajl_gen_config(*gen, yajl_gen_beautify, 1); +static void ipc_event_init_message(yajl_gen *gen) { + *gen = yajl_gen_alloc(NULL); + yajl_gen_config(*gen, yajl_gen_beautify, 1); } /** - * Prepares buffers of IPC subscribers of specified event using buffer from yajl - * handle. + * Prepares buffers of IPC subscribers of specified event using buffer from + * yajl handle. */ -static void -ipc_event_prepare_send_message(yajl_gen gen, IPCEvent event) -{ - const unsigned char *buffer; - size_t len = 0; - - yajl_gen_get_buf(gen, &buffer, &len); - len++; // For null char - - for (IPCClient *c = ipc_clients; c; c = c->next) { - if (c->subscriptions & event) { - DEBUG("Sending selected client change event to fd %d\n", c->fd); - ipc_prepare_send_message(c, IPC_TYPE_EVENT, len, (char *)buffer); - } - } - - // Not documented, but this frees temp_buffer - yajl_gen_free(gen); +static void ipc_event_prepare_send_message(yajl_gen gen, IPCEvent event) { + const unsigned char *buffer; + size_t len = 0; + + yajl_gen_get_buf(gen, &buffer, &len); + len++; // For null char + + for (IPCClient *c = ipc_clients; c; c = c->next) { + if (c->subscriptions & event) { + DEBUG("Sending selected client change event to fd %d\n", c->fd); + ipc_prepare_send_message(c, IPC_TYPE_EVENT, len, (char *) buffer); + } + } + + // Not documented, but this frees temp_buffer + yajl_gen_free(gen); } /** @@ -251,31 +251,27 @@ ipc_event_prepare_send_message(yajl_gen gen, IPCEvent event) * handle, set yajl options, and in the future any other initialization that * should occur for reply messages. */ -static void -ipc_reply_init_message(yajl_gen *gen) -{ - *gen = yajl_gen_alloc(NULL); - yajl_gen_config(*gen, yajl_gen_beautify, 1); +static void ipc_reply_init_message(yajl_gen *gen) { + *gen = yajl_gen_alloc(NULL); + yajl_gen_config(*gen, yajl_gen_beautify, 1); } /** - * Prepares the IPC client's buffer with a message using the buffer of the yajl - * handle. + * Prepares the IPC client's buffer with a message using the buffer of the + * yajl handle. */ -static void -ipc_reply_prepare_send_message(yajl_gen gen, IPCClient *c, - IPCMessageType msg_type) -{ - const unsigned char *buffer; - size_t len = 0; +static void ipc_reply_prepare_send_message(yajl_gen gen, IPCClient *c, + IPCMessageType msg_type) { + const unsigned char *buffer; + size_t len = 0; - yajl_gen_get_buf(gen, &buffer, &len); - len++; // For null char + yajl_gen_get_buf(gen, &buffer, &len); + len++; // For null char - ipc_prepare_send_message(c, msg_type, len, (const char *)buffer); + ipc_prepare_send_message(c, msg_type, len, (const char *) buffer); - // Not documented, but this frees temp_buffer - yajl_gen_free(gen); + // Not documented, but this frees temp_buffer + yajl_gen_free(gen); } /** @@ -284,17 +280,15 @@ ipc_reply_prepare_send_message(yajl_gen gen, IPCClient *c, * Returns 0 if a command with the specified name was found * Returns -1 if a command with the specified name could not be found */ -static int -ipc_get_ipc_command(const char *name, IPCCommand *ipc_command) -{ - for (int i = 0; i < ipc_commands_len; i++) { - if (strcmp(ipc_commands[i].name, name) == 0) { - *ipc_command = ipc_commands[i]; - return 0; - } - } - - return -1; +static int ipc_get_ipc_command(const char *name, IPCCommand *ipc_command) { + for (int i = 0; i < ipc_commands_len; i++) { + if (strcmp(ipc_commands[i].name, name) == 0) { + *ipc_command = ipc_commands[i]; + return 0; + } + } + + return -1; } /** @@ -307,117 +301,116 @@ ipc_get_ipc_command(const char *name, IPCCommand *ipc_command) * Returns 0 if the message was successfully parsed * Returns -1 otherwise */ -static int -ipc_parse_run_command(char *msg, IPCParsedCommand *parsed_command) -{ - char error_buffer[1000]; - yajl_val parent = yajl_tree_parse(msg, error_buffer, 1000); - - if (parent == NULL) { - fputs("Failed to parse command from client\n", stderr); - fprintf(stderr, "%s\n", error_buffer); - fprintf(stderr, "Tried to parse: %s\n", msg); - return -1; - } - - // Format: - // { - // "command": "" - // "args": [ "arg1", "arg2", ... ] - // } - const char *command_path[] = {"command", 0}; - yajl_val command_val = yajl_tree_get(parent, command_path, yajl_t_string); - - if (command_val == NULL) { - fputs("No command key found in client message\n", stderr); - yajl_tree_free(parent); - return -1; - } - - const char *command_name = YAJL_GET_STRING(command_val); - size_t command_name_len = strlen(command_name); - parsed_command->name = (char *)malloc((command_name_len + 1) * sizeof(char)); - strcpy(parsed_command->name, command_name); - - DEBUG("Received command: %s\n", parsed_command->name); - - const char *args_path[] = {"args", 0}; - yajl_val args_val = yajl_tree_get(parent, args_path, yajl_t_array); - - if (args_val == NULL) { - fputs("No args key found in client message\n", stderr); - yajl_tree_free(parent); - return -1; - } - - unsigned int *argc = &parsed_command->argc; - Arg **args = &parsed_command->args; - ArgType **arg_types = &parsed_command->arg_types; - - *argc = args_val->u.array.len; - - // If no arguments are specified, make a dummy argument to pass to the - // function. This is just the way dwm's void(Arg*) functions are setup. - if (*argc == 0) { - *args = (Arg *)malloc(sizeof(Arg)); - *arg_types = (ArgType *)malloc(sizeof(ArgType)); - (*arg_types)[0] = ARG_TYPE_NONE; - (*args)[0].i = 0; - (*argc)++; - } else if (*argc > 0) { - *args = (Arg *)calloc(*argc, sizeof(Arg)); - *arg_types = (ArgType *)malloc(*argc * sizeof(ArgType)); - - for (int i = 0; i < *argc; i++) { - yajl_val arg_val = args_val->u.array.values[i]; - - if (YAJL_IS_NUMBER(arg_val)) { - if (YAJL_IS_INTEGER(arg_val)) { - // Any values below 0 must be a signed int - if (YAJL_GET_INTEGER(arg_val) < 0) { - (*args)[i].i = YAJL_GET_INTEGER(arg_val); - (*arg_types)[i] = ARG_TYPE_SINT; - DEBUG("i=%ld\n", (*args)[i].i); - // Any values above 0 should be an unsigned int - } else if (YAJL_GET_INTEGER(arg_val) >= 0) { - (*args)[i].ui = YAJL_GET_INTEGER(arg_val); - (*arg_types)[i] = ARG_TYPE_UINT; - DEBUG("ui=%ld\n", (*args)[i].i); - } - // If the number is not an integer, it must be a float - } else { - (*args)[i].f = (float)YAJL_GET_DOUBLE(arg_val); - (*arg_types)[i] = ARG_TYPE_FLOAT; - DEBUG("f=%f\n", (*args)[i].f); - // If argument is not a number, it must be a string - } - } else if (YAJL_IS_STRING(arg_val)) { - char *arg_s = YAJL_GET_STRING(arg_val); - size_t arg_s_size = (strlen(arg_s) + 1) * sizeof(char); - (*args)[i].v = (char *)malloc(arg_s_size); - (*arg_types)[i] = ARG_TYPE_STR; - strcpy((char *)(*args)[i].v, arg_s); - } - } - } - - yajl_tree_free(parent); - - return 0; +static int ipc_parse_run_command(char *msg, + IPCParsedCommand *parsed_command) { + char error_buffer[1000]; + yajl_val parent = yajl_tree_parse(msg, error_buffer, 1000); + + if (parent == NULL) { + fputs("Failed to parse command from client\n", stderr); + fprintf(stderr, "%s\n", error_buffer); + fprintf(stderr, "Tried to parse: %s\n", msg); + return -1; + } + + // Format: + // { + // "command": "" + // "args": [ "arg1", "arg2", ... ] + // } + const char *command_path[] = {"command", 0}; + yajl_val command_val = yajl_tree_get(parent, command_path, yajl_t_string); + + if (command_val == NULL) { + fputs("No command key found in client message\n", stderr); + yajl_tree_free(parent); + return -1; + } + + const char *command_name = YAJL_GET_STRING(command_val); + size_t command_name_len = strlen(command_name); + parsed_command->name = + (char *) malloc((command_name_len + 1) * sizeof(char)); + strcpy(parsed_command->name, command_name); + + DEBUG("Received command: %s\n", parsed_command->name); + + const char *args_path[] = {"args", 0}; + yajl_val args_val = yajl_tree_get(parent, args_path, yajl_t_array); + + if (args_val == NULL) { + fputs("No args key found in client message\n", stderr); + yajl_tree_free(parent); + return -1; + } + + unsigned int *argc = &parsed_command->argc; + Arg **args = &parsed_command->args; + ArgType **arg_types = &parsed_command->arg_types; + + *argc = args_val->u.array.len; + + // If no arguments are specified, make a dummy argument to pass to the + // function. This is just the way dwm's void(Arg*) functions are setup. + if (*argc == 0) { + *args = (Arg *) malloc(sizeof(Arg)); + *arg_types = (ArgType *) malloc(sizeof(ArgType)); + (*arg_types)[0] = ARG_TYPE_NONE; + (*args)[0].i = 0; + (*argc)++; + } else if (*argc > 0) { + *args = (Arg *) calloc(*argc, sizeof(Arg)); + *arg_types = (ArgType *) malloc(*argc * sizeof(ArgType)); + + for (int i = 0; i < *argc; i++) { + yajl_val arg_val = args_val->u.array.values[i]; + + if (YAJL_IS_NUMBER(arg_val)) { + if (YAJL_IS_INTEGER(arg_val)) { + // Any values below 0 must be a signed int + if (YAJL_GET_INTEGER(arg_val) < 0) { + (*args)[i].i = YAJL_GET_INTEGER(arg_val); + (*arg_types)[i] = ARG_TYPE_SINT; + DEBUG("i=%ld\n", (*args)[i].i); + // Any values above 0 should be an unsigned int + } else if (YAJL_GET_INTEGER(arg_val) >= 0) { + (*args)[i].ui = YAJL_GET_INTEGER(arg_val); + (*arg_types)[i] = ARG_TYPE_UINT; + DEBUG("ui=%ld\n", (*args)[i].i); + } + // If the number is not an integer, it must be a float + } else { + (*args)[i].f = (float) YAJL_GET_DOUBLE(arg_val); + (*arg_types)[i] = ARG_TYPE_FLOAT; + DEBUG("f=%f\n", (*args)[i].f); + // If argument is not a number, it must be a string + } + } else if (YAJL_IS_STRING(arg_val)) { + char *arg_s = YAJL_GET_STRING(arg_val); + size_t arg_s_size = (strlen(arg_s) + 1) * sizeof(char); + (*args)[i].v = (char *) malloc(arg_s_size); + (*arg_types)[i] = ARG_TYPE_STR; + strcpy((char *) (*args)[i].v, arg_s); + } + } + } + + yajl_tree_free(parent); + + return 0; } /** * Free the members of a IPCParsedCommand struct */ -static void -ipc_free_parsed_command_members(IPCParsedCommand *command) -{ - for (int i = 0; i < command->argc; i++) { - if (command->arg_types[i] == ARG_TYPE_STR) free((void *)command->args[i].v); - } - free(command->args); - free(command->arg_types); - free(command->name); +static void ipc_free_parsed_command_members(IPCParsedCommand *command) { + for (int i = 0; i < command->argc; i++) { + if (command->arg_types[i] == ARG_TYPE_STR) + free((void *) command->args[i].v); + } + free(command->args); + free(command->arg_types); + free(command->name); } /** @@ -428,28 +421,28 @@ ipc_free_parsed_command_members(IPCParsedCommand *command) * Returns -1 if the argument count doesn't match * Returns -2 if the argument types don't match */ -static int -ipc_validate_run_command(IPCParsedCommand *parsed, const IPCCommand actual) -{ - if (actual.argc != parsed->argc) return -1; - - for (int i = 0; i < parsed->argc; i++) { - ArgType ptype = parsed->arg_types[i]; - ArgType atype = actual.arg_types[i]; - - if (ptype != atype) { - if (ptype == ARG_TYPE_UINT && atype == ARG_TYPE_PTR) - // If this argument is supposed to be a void pointer, cast it - parsed->args[i].v = (void *)parsed->args[i].ui; - else if (ptype == ARG_TYPE_UINT && atype == ARG_TYPE_SINT) - // If this argument is supposed to be a signed int, cast it - parsed->args[i].i = parsed->args[i].ui; - else - return -2; - } - } - - return 0; +static int ipc_validate_run_command(IPCParsedCommand *parsed, + const IPCCommand actual) { + if (actual.argc != parsed->argc) + return -1; + + for (int i = 0; i < parsed->argc; i++) { + ArgType ptype = parsed->arg_types[i]; + ArgType atype = actual.arg_types[i]; + + if (ptype != atype) { + if (ptype == ARG_TYPE_UINT && atype == ARG_TYPE_PTR) + // If this argument is supposed to be a void pointer, cast it + parsed->args[i].v = (void *) parsed->args[i].ui; + else if (ptype == ARG_TYPE_UINT && atype == ARG_TYPE_SINT) + // If this argument is supposed to be a signed int, cast it + parsed->args[i].i = parsed->args[i].ui; + else + return -2; + } + } + + return 0; } /** @@ -458,86 +451,84 @@ ipc_validate_run_command(IPCParsedCommand *parsed, const IPCCommand actual) * Returns 0 if a valid event name was given * Returns -1 otherwise */ -static int -ipc_event_stoi(const char *subscription, IPCEvent *event) -{ - if (strcmp(subscription, "tag_change_event") == 0) - *event = IPC_EVENT_TAG_CHANGE; - else if (strcmp(subscription, "client_focus_change_event") == 0) - *event = IPC_EVENT_CLIENT_FOCUS_CHANGE; - else if (strcmp(subscription, "layout_change_event") == 0) - *event = IPC_EVENT_LAYOUT_CHANGE; - else if (strcmp(subscription, "monitor_focus_change_event") == 0) - *event = IPC_EVENT_MONITOR_FOCUS_CHANGE; - else if (strcmp(subscription, "focused_title_change_event") == 0) - *event = IPC_EVENT_FOCUSED_TITLE_CHANGE; - else if (strcmp(subscription, "focused_state_change_event") == 0) - *event = IPC_EVENT_FOCUSED_STATE_CHANGE; - else - return -1; - return 0; +static int ipc_event_stoi(const char *subscription, IPCEvent *event) { + if (strcmp(subscription, "tag_change_event") == 0) + *event = IPC_EVENT_TAG_CHANGE; + else if (strcmp(subscription, "client_focus_change_event") == 0) + *event = IPC_EVENT_CLIENT_FOCUS_CHANGE; + else if (strcmp(subscription, "layout_change_event") == 0) + *event = IPC_EVENT_LAYOUT_CHANGE; + else if (strcmp(subscription, "monitor_focus_change_event") == 0) + *event = IPC_EVENT_MONITOR_FOCUS_CHANGE; + else if (strcmp(subscription, "focused_title_change_event") == 0) + *event = IPC_EVENT_FOCUSED_TITLE_CHANGE; + else if (strcmp(subscription, "focused_state_change_event") == 0) + *event = IPC_EVENT_FOCUSED_STATE_CHANGE; + else + return -1; + return 0; } /** - * Parse a IPC_TYPE_SUBSCRIBE message from a client. This function extracts the - * event name and the subscription action from the message. + * Parse a IPC_TYPE_SUBSCRIBE message from a client. This function extracts + * the event name and the subscription action from the message. * * Returns 0 if message was successfully parsed * Returns -1 otherwise */ -static int -ipc_parse_subscribe(const char *msg, IPCSubscriptionAction *subscribe, - IPCEvent *event) -{ - char error_buffer[100]; - yajl_val parent = yajl_tree_parse((char *)msg, error_buffer, 100); - - if (parent == NULL) { - fputs("Failed to parse command from client\n", stderr); - fprintf(stderr, "%s\n", error_buffer); - return -1; - } - - // Format: - // { - // "event": "" - // "action": "" - // } - const char *event_path[] = {"event", 0}; - yajl_val event_val = yajl_tree_get(parent, event_path, yajl_t_string); - - if (event_val == NULL) { - fputs("No 'event' key found in client message\n", stderr); - return -1; - } - - const char *event_str = YAJL_GET_STRING(event_val); - DEBUG("Received event: %s\n", event_str); - - if (ipc_event_stoi(event_str, event) < 0) return -1; - - const char *action_path[] = {"action", 0}; - yajl_val action_val = yajl_tree_get(parent, action_path, yajl_t_string); - - if (action_val == NULL) { - fputs("No 'action' key found in client message\n", stderr); - return -1; - } - - const char *action = YAJL_GET_STRING(action_val); - - if (strcmp(action, "subscribe") == 0) - *subscribe = IPC_ACTION_SUBSCRIBE; - else if (strcmp(action, "unsubscribe") == 0) - *subscribe = IPC_ACTION_UNSUBSCRIBE; - else { - fputs("Invalid action specified for subscription\n", stderr); - return -1; - } - - yajl_tree_free(parent); - - return 0; +static int ipc_parse_subscribe(const char *msg, + IPCSubscriptionAction *subscribe, + IPCEvent *event) { + char error_buffer[100]; + yajl_val parent = yajl_tree_parse((char *) msg, error_buffer, 100); + + if (parent == NULL) { + fputs("Failed to parse command from client\n", stderr); + fprintf(stderr, "%s\n", error_buffer); + return -1; + } + + // Format: + // { + // "event": "" + // "action": "" + // } + const char *event_path[] = {"event", 0}; + yajl_val event_val = yajl_tree_get(parent, event_path, yajl_t_string); + + if (event_val == NULL) { + fputs("No 'event' key found in client message\n", stderr); + return -1; + } + + const char *event_str = YAJL_GET_STRING(event_val); + DEBUG("Received event: %s\n", event_str); + + if (ipc_event_stoi(event_str, event) < 0) + return -1; + + const char *action_path[] = {"action", 0}; + yajl_val action_val = yajl_tree_get(parent, action_path, yajl_t_string); + + if (action_val == NULL) { + fputs("No 'action' key found in client message\n", stderr); + return -1; + } + + const char *action = YAJL_GET_STRING(action_val); + + if (strcmp(action, "subscribe") == 0) + *subscribe = IPC_ACTION_SUBSCRIBE; + else if (strcmp(action, "unsubscribe") == 0) + *subscribe = IPC_ACTION_UNSUBSCRIBE; + else { + fputs("Invalid action specified for subscription\n", stderr); + return -1; + } + + yajl_tree_free(parent); + + return 0; } /** @@ -547,656 +538,630 @@ ipc_parse_subscribe(const char *msg, IPCSubscriptionAction *subscribe, * Returns 0 if message was successfully parsed * Returns -1 otherwise */ -static int -ipc_parse_get_dwm_client(const char *msg, Window *win) -{ - char error_buffer[100]; +static int ipc_parse_get_dwm_client(const char *msg, Window *win) { + char error_buffer[100]; - yajl_val parent = yajl_tree_parse(msg, error_buffer, 100); + yajl_val parent = yajl_tree_parse(msg, error_buffer, 100); - if (parent == NULL) { - fputs("Failed to parse message from client\n", stderr); - fprintf(stderr, "%s\n", error_buffer); - return -1; - } + if (parent == NULL) { + fputs("Failed to parse message from client\n", stderr); + fprintf(stderr, "%s\n", error_buffer); + return -1; + } - // Format: - // { - // "client_window_id": - // } - const char *win_path[] = {"client_window_id", 0}; - yajl_val win_val = yajl_tree_get(parent, win_path, yajl_t_number); + // Format: + // { + // "client_window_id": + // } + const char *win_path[] = {"client_window_id", 0}; + yajl_val win_val = yajl_tree_get(parent, win_path, yajl_t_number); - if (win_val == NULL) { - fputs("No client window id found in client message\n", stderr); - return -1; - } + if (win_val == NULL) { + fputs("No client window id found in client message\n", stderr); + return -1; + } - *win = YAJL_GET_INTEGER(win_val); + *win = YAJL_GET_INTEGER(win_val); - yajl_tree_free(parent); + yajl_tree_free(parent); - return 0; + return 0; } /** * Called when an IPC_TYPE_RUN_COMMAND message is received from a client. This - * function parses, executes the given command, and prepares a reply message to - * the client indicating success/failure. + * function parses, executes the given command, and prepares a reply message + * to the client indicating success/failure. * - * NOTE: There is currently no check for argument validity beyond the number of - * arguments given and types of arguments. There is also no way to check if the - * function succeeded based on dwm's void(const Arg*) function types. Pointer - * arguments can cause crashes if they are not validated in the function itself. + * NOTE: There is currently no check for argument validity beyond the number + * of arguments given and types of arguments. There is also no way to check if + * the function succeeded based on dwm's void(const Arg*) function types. + * Pointer arguments can cause crashes if they are not validated in the + * function itself. * * Returns 0 if message was successfully parsed * Returns -1 on failure parsing message */ -static int -ipc_run_command(IPCClient *ipc_client, char *msg) -{ - IPCParsedCommand parsed_command; - IPCCommand ipc_command; - - // Initialize struct - memset(&parsed_command, 0, sizeof(IPCParsedCommand)); - - if (ipc_parse_run_command(msg, &parsed_command) < 0) { - ipc_prepare_reply_failure(ipc_client, IPC_TYPE_RUN_COMMAND, - "Failed to parse run command"); - return -1; - } - - if (ipc_get_ipc_command(parsed_command.name, &ipc_command) < 0) { - ipc_prepare_reply_failure(ipc_client, IPC_TYPE_RUN_COMMAND, - "Command %s not found", parsed_command.name); - ipc_free_parsed_command_members(&parsed_command); - return -1; - } - - int res = ipc_validate_run_command(&parsed_command, ipc_command); - if (res < 0) { - if (res == -1) - ipc_prepare_reply_failure(ipc_client, IPC_TYPE_RUN_COMMAND, - "%u arguments provided, %u expected", - parsed_command.argc, ipc_command.argc); - else if (res == -2) - ipc_prepare_reply_failure(ipc_client, IPC_TYPE_RUN_COMMAND, - "Type mismatch"); - ipc_free_parsed_command_members(&parsed_command); - return -1; - } - - if (parsed_command.argc == 1) - ipc_command.func.single_param(parsed_command.args); - else if (parsed_command.argc > 1) - ipc_command.func.array_param(parsed_command.args, parsed_command.argc); - - DEBUG("Called function for command %s\n", parsed_command.name); - - ipc_free_parsed_command_members(&parsed_command); - - ipc_prepare_reply_success(ipc_client, IPC_TYPE_RUN_COMMAND); - return 0; +static int ipc_run_command(IPCClient *ipc_client, char *msg) { + IPCParsedCommand parsed_command; + IPCCommand ipc_command; + + // Initialize struct + memset(&parsed_command, 0, sizeof(IPCParsedCommand)); + + if (ipc_parse_run_command(msg, &parsed_command) < 0) { + ipc_prepare_reply_failure(ipc_client, IPC_TYPE_RUN_COMMAND, + "Failed to parse run command"); + return -1; + } + + if (ipc_get_ipc_command(parsed_command.name, &ipc_command) < 0) { + ipc_prepare_reply_failure(ipc_client, IPC_TYPE_RUN_COMMAND, + "Command %s not found", + parsed_command.name); + ipc_free_parsed_command_members(&parsed_command); + return -1; + } + + int res = ipc_validate_run_command(&parsed_command, ipc_command); + if (res < 0) { + if (res == -1) + ipc_prepare_reply_failure(ipc_client, IPC_TYPE_RUN_COMMAND, + "%u arguments provided, %u expected", + parsed_command.argc, ipc_command.argc); + else if (res == -2) + ipc_prepare_reply_failure(ipc_client, IPC_TYPE_RUN_COMMAND, + "Type mismatch"); + ipc_free_parsed_command_members(&parsed_command); + return -1; + } + + if (parsed_command.argc == 1) + ipc_command.func.single_param(parsed_command.args); + else if (parsed_command.argc > 1) + ipc_command.func.array_param(parsed_command.args, + parsed_command.argc); + + DEBUG("Called function for command %s\n", parsed_command.name); + + ipc_free_parsed_command_members(&parsed_command); + + ipc_prepare_reply_success(ipc_client, IPC_TYPE_RUN_COMMAND); + return 0; } /** * Called when an IPC_TYPE_GET_MONITORS message is received from a client. It * prepares a reply with the properties of all of the monitors in JSON. */ -static void -ipc_get_monitors(IPCClient *c, Monitor *mons, Monitor *selmon) -{ - yajl_gen gen; - ipc_reply_init_message(&gen); - dump_monitors(gen, mons, selmon); - - ipc_reply_prepare_send_message(gen, c, IPC_TYPE_GET_MONITORS); +static void ipc_get_monitors(IPCClient *c, Monitor *mons, Monitor *selmon) { + yajl_gen gen; + ipc_reply_init_message(&gen); + dump_monitors(gen, mons, selmon); + + ipc_reply_prepare_send_message(gen, c, IPC_TYPE_GET_MONITORS); } /** * Called when an IPC_TYPE_GET_TAGS message is received from a client. It * prepares a reply with info about all the tags in JSON. */ -static void -ipc_get_tags(IPCClient *c, const char *tags[], const int tags_len) -{ - yajl_gen gen; - ipc_reply_init_message(&gen); +static void ipc_get_tags(IPCClient *c, const char *tags[], + const int tags_len) { + yajl_gen gen; + ipc_reply_init_message(&gen); - dump_tags(gen, tags, tags_len); + dump_tags(gen, tags, tags_len); - ipc_reply_prepare_send_message(gen, c, IPC_TYPE_GET_TAGS); + ipc_reply_prepare_send_message(gen, c, IPC_TYPE_GET_TAGS); } /** * Called when an IPC_TYPE_GET_LAYOUTS message is received from a client. It * prepares a reply with a JSON array of available layouts */ -static void -ipc_get_layouts(IPCClient *c, const Layout layouts[], const int layouts_len) -{ - yajl_gen gen; - ipc_reply_init_message(&gen); +static void ipc_get_layouts(IPCClient *c, const Layout layouts[], + const int layouts_len) { + yajl_gen gen; + ipc_reply_init_message(&gen); - dump_layouts(gen, layouts, layouts_len); + dump_layouts(gen, layouts, layouts_len); - ipc_reply_prepare_send_message(gen, c, IPC_TYPE_GET_LAYOUTS); + ipc_reply_prepare_send_message(gen, c, IPC_TYPE_GET_LAYOUTS); } /** - * Called when an IPC_TYPE_GET_DWM_CLIENT message is received from a client. It - * prepares a JSON reply with the properties of the client with the specified - * window XID. + * Called when an IPC_TYPE_GET_DWM_CLIENT message is received from a client. + * It prepares a JSON reply with the properties of the client with the + * specified window XID. * * Returns 0 if the message was successfully parsed and if the client with the * specified window XID was found * Returns -1 if the message could not be parsed */ -static int -ipc_get_dwm_client(IPCClient *ipc_client, const char *msg, const Monitor *mons) -{ - Window win; +static int ipc_get_dwm_client(IPCClient *ipc_client, const char *msg, + const Monitor *mons) { + Window win; - if (ipc_parse_get_dwm_client(msg, &win) < 0) return -1; + if (ipc_parse_get_dwm_client(msg, &win) < 0) + return -1; - // Find client with specified window XID - for (const Monitor *m = mons; m; m = m->next) - for (Client *c = m->clients; c; c = c->next) - if (c->win == win) { - yajl_gen gen; - ipc_reply_init_message(&gen); + // Find client with specified window XID + for (const Monitor *m = mons; m; m = m->next) + for (Client *c = m->clients; c; c = c->next) + if (c->win == win) { + yajl_gen gen; + ipc_reply_init_message(&gen); - dump_client(gen, c); + dump_client(gen, c); - ipc_reply_prepare_send_message(gen, ipc_client, - IPC_TYPE_GET_DWM_CLIENT); + ipc_reply_prepare_send_message(gen, ipc_client, + IPC_TYPE_GET_DWM_CLIENT); - return 0; - } + return 0; + } - ipc_prepare_reply_failure(ipc_client, IPC_TYPE_GET_DWM_CLIENT, - "Client with window id %d not found", win); - return -1; + ipc_prepare_reply_failure(ipc_client, IPC_TYPE_GET_DWM_CLIENT, + "Client with window id %d not found", win); + return -1; } /** * Called when an IPC_TYPE_SUBSCRIBE message is received from a client. It - * subscribes/unsubscribes the client from the specified event and replies with - * the result. + * subscribes/unsubscribes the client from the specified event and replies + * with the result. * * Returns 0 if the message was successfully parsed. * Returns -1 if the message could not be parsed */ -static int -ipc_subscribe(IPCClient *c, const char *msg) -{ - IPCSubscriptionAction action = IPC_ACTION_SUBSCRIBE; - IPCEvent event = 0; - - if (ipc_parse_subscribe(msg, &action, &event)) { - ipc_prepare_reply_failure(c, IPC_TYPE_SUBSCRIBE, "Event does not exist"); - return -1; - } - - if (action == IPC_ACTION_SUBSCRIBE) { - DEBUG("Subscribing client on fd %d to %d\n", c->fd, event); - c->subscriptions |= event; - } else if (action == IPC_ACTION_UNSUBSCRIBE) { - DEBUG("Unsubscribing client on fd %d to %d\n", c->fd, event); - c->subscriptions ^= event; - } else { - ipc_prepare_reply_failure(c, IPC_TYPE_SUBSCRIBE, - "Invalid subscription action"); - return -1; - } - - ipc_prepare_reply_success(c, IPC_TYPE_SUBSCRIBE); - return 0; +static int ipc_subscribe(IPCClient *c, const char *msg) { + IPCSubscriptionAction action = IPC_ACTION_SUBSCRIBE; + IPCEvent event = 0; + + if (ipc_parse_subscribe(msg, &action, &event)) { + ipc_prepare_reply_failure(c, IPC_TYPE_SUBSCRIBE, + "Event does not exist"); + return -1; + } + + if (action == IPC_ACTION_SUBSCRIBE) { + DEBUG("Subscribing client on fd %d to %d\n", c->fd, event); + c->subscriptions |= event; + } else if (action == IPC_ACTION_UNSUBSCRIBE) { + DEBUG("Unsubscribing client on fd %d to %d\n", c->fd, event); + c->subscriptions ^= event; + } else { + ipc_prepare_reply_failure(c, IPC_TYPE_SUBSCRIBE, + "Invalid subscription action"); + return -1; + } + + ipc_prepare_reply_success(c, IPC_TYPE_SUBSCRIBE); + return 0; } -int -ipc_init(const char *socket_path, const int p_epoll_fd, IPCCommand commands[], - const int commands_len) -{ - // Initialize struct to 0 - memset(&sock_epoll_event, 0, sizeof(sock_epoll_event)); +int ipc_init(const char *socket_path, const int p_epoll_fd, + IPCCommand commands[], const int commands_len) { + // Initialize struct to 0 + memset(&sock_epoll_event, 0, sizeof(sock_epoll_event)); - int socket_fd = ipc_create_socket(socket_path); - if (socket_fd < 0) return -1; + int socket_fd = ipc_create_socket(socket_path); + if (socket_fd < 0) + return -1; - ipc_commands = commands; - ipc_commands_len = commands_len; + ipc_commands = commands; + ipc_commands_len = commands_len; - epoll_fd = p_epoll_fd; + epoll_fd = p_epoll_fd; - // Wake up to incoming connection requests - sock_epoll_event.data.fd = socket_fd; - sock_epoll_event.events = EPOLLIN; - if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd, &sock_epoll_event)) { - fputs("Failed to add sock file descriptor to epoll", stderr); - return -1; - } + // Wake up to incoming connection requests + sock_epoll_event.data.fd = socket_fd; + sock_epoll_event.events = EPOLLIN; + if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd, &sock_epoll_event)) { + fputs("Failed to add sock file descriptor to epoll", stderr); + return -1; + } - return socket_fd; + return socket_fd; } -void -ipc_cleanup() -{ - IPCClient *c = ipc_clients; - // Free clients and their buffers - while (c) { - ipc_drop_client(c); - c = ipc_clients; - } - - // Stop waking up for socket events - epoll_ctl(epoll_fd, EPOLL_CTL_DEL, sock_fd, &sock_epoll_event); - - // Uninitialize all static variables - epoll_fd = -1; - sock_fd = -1; - ipc_commands = NULL; - ipc_commands_len = 0; - memset(&sock_epoll_event, 0, sizeof(struct epoll_event)); - memset(&sockaddr, 0, sizeof(struct sockaddr_un)); - - // Delete socket - unlink(sockaddr.sun_path); - - shutdown(sock_fd, SHUT_RDWR); - close(sock_fd); +void ipc_cleanup() { + IPCClient *c = ipc_clients; + // Free clients and their buffers + while (c) { + ipc_drop_client(c); + c = ipc_clients; + } + + // Stop waking up for socket events + epoll_ctl(epoll_fd, EPOLL_CTL_DEL, sock_fd, &sock_epoll_event); + + // Uninitialize all static variables + epoll_fd = -1; + sock_fd = -1; + ipc_commands = NULL; + ipc_commands_len = 0; + memset(&sock_epoll_event, 0, sizeof(struct epoll_event)); + memset(&sockaddr, 0, sizeof(struct sockaddr_un)); + + // Delete socket + unlink(sockaddr.sun_path); + + shutdown(sock_fd, SHUT_RDWR); + close(sock_fd); } -int -ipc_get_sock_fd() -{ - return sock_fd; +int ipc_get_sock_fd() { + return sock_fd; } -IPCClient * -ipc_get_client(int fd) -{ - return ipc_list_get_client(ipc_clients, fd); +IPCClient *ipc_get_client(int fd) { + return ipc_list_get_client(ipc_clients, fd); } -int -ipc_is_client_registered(int fd) -{ - return (ipc_get_client(fd) != NULL); +int ipc_is_client_registered(int fd) { + return (ipc_get_client(fd) != NULL); } -int -ipc_accept_client() -{ - int fd = -1; +int ipc_accept_client() { + int fd = -1; - struct sockaddr_un client_addr; - socklen_t len = 0; + struct sockaddr_un client_addr; + socklen_t len = 0; - // For portability clear the addr structure, since some implementations - // have nonstandard fields in the structure - memset(&client_addr, 0, sizeof(struct sockaddr_un)); + // For portability clear the addr structure, since some implementations + // have nonstandard fields in the structure + memset(&client_addr, 0, sizeof(struct sockaddr_un)); - fd = accept(sock_fd, (struct sockaddr *)&client_addr, &len); - if (fd < 0 && errno != EINTR) { - fputs("Failed to accept IPC connection from client", stderr); - return -1; - } + fd = accept(sock_fd, (struct sockaddr *) &client_addr, &len); + if (fd < 0 && errno != EINTR) { + fputs("Failed to accept IPC connection from client", stderr); + return -1; + } - if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { - shutdown(fd, SHUT_RDWR); - close(fd); - fputs("Failed to set flags on new client fd", stderr); - } + if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { + shutdown(fd, SHUT_RDWR); + close(fd); + fputs("Failed to set flags on new client fd", stderr); + } - IPCClient *nc = ipc_client_new(fd); - if (nc == NULL) return -1; + IPCClient *nc = ipc_client_new(fd); + if (nc == NULL) + return -1; - // Wake up to messages from this client - nc->event.data.fd = fd; - nc->event.events = EPOLLIN | EPOLLHUP; - epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &nc->event); + // Wake up to messages from this client + nc->event.data.fd = fd; + nc->event.events = EPOLLIN | EPOLLHUP; + epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &nc->event); - ipc_list_add_client(&ipc_clients, nc); + ipc_list_add_client(&ipc_clients, nc); - DEBUG("%s%d\n", "New client at fd: ", fd); + DEBUG("%s%d\n", "New client at fd: ", fd); - return fd; + return fd; } -int -ipc_drop_client(IPCClient *c) -{ - int fd = c->fd; - shutdown(fd, SHUT_RDWR); - int res = close(fd); +int ipc_drop_client(IPCClient *c) { + int fd = c->fd; + shutdown(fd, SHUT_RDWR); + int res = close(fd); - if (res == 0) { - struct epoll_event ev; + if (res == 0) { + struct epoll_event ev; - // Stop waking up to messages from this client - epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &ev); - ipc_list_remove_client(&ipc_clients, c); + // Stop waking up to messages from this client + epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, &ev); + ipc_list_remove_client(&ipc_clients, c); - free(c->buffer); - free(c); + free(c->buffer); + free(c); - DEBUG("Successfully removed client on fd %d\n", fd); - } else if (res < 0 && res != EINTR) { - fprintf(stderr, "Failed to close fd %d\n", fd); - } + DEBUG("Successfully removed client on fd %d\n", fd); + } else if (res < 0 && res != EINTR) { + fprintf(stderr, "Failed to close fd %d\n", fd); + } - return res; + return res; } -int -ipc_read_client(IPCClient *c, IPCMessageType *msg_type, uint32_t *msg_size, - char **msg) -{ - int fd = c->fd; - int ret = - ipc_recv_message(fd, (uint8_t *)msg_type, msg_size, (uint8_t **)msg); - - if (ret < 0) { - // This will happen if these errors occur while reading header - if (ret == -1 && - (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) - return -2; - - fprintf(stderr, "Error reading message: dropping client at fd %d\n", fd); - ipc_drop_client(c); - - return -1; - } - - // Make sure receive message is null terminated to avoid parsing issues - if (*msg_size > 0) { - size_t len = *msg_size; - nullterminate(msg, &len); - *msg_size = len; - } - - DEBUG("[fd %d] ", fd); - if (*msg_size > 0) - DEBUG("Received message: '%.*s' ", *msg_size, *msg); - else - DEBUG("Received empty message "); - DEBUG("Message type: %" PRIu8 " ", (uint8_t)*msg_type); - DEBUG("Message size: %" PRIu32 "\n", *msg_size); - - return 0; +int ipc_read_client(IPCClient *c, IPCMessageType *msg_type, + uint32_t *msg_size, char **msg) { + int fd = c->fd; + int ret = ipc_recv_message(fd, (uint8_t *) msg_type, msg_size, + (uint8_t **) msg); + + if (ret < 0) { + // This will happen if these errors occur while reading header + if (ret == -1 + && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) + return -2; + + fprintf(stderr, "Error reading message: dropping client at fd %d\n", + fd); + ipc_drop_client(c); + + return -1; + } + + // Make sure receive message is null terminated to avoid parsing issues + if (*msg_size > 0) { + size_t len = *msg_size; + nullterminate(msg, &len); + *msg_size = len; + } + + DEBUG("[fd %d] ", fd); + if (*msg_size > 0) + DEBUG("Received message: '%.*s' ", *msg_size, *msg); + else + DEBUG("Received empty message "); + DEBUG("Message type: %" PRIu8 " ", (uint8_t) *msg_type); + DEBUG("Message size: %" PRIu32 "\n", *msg_size); + + return 0; } -ssize_t -ipc_write_client(IPCClient *c) -{ - const ssize_t n = ipc_write_message(c->fd, c->buffer, c->buffer_size); - - if (n < 0) return n; - - // TODO: Deal with client timeouts - - if (n == c->buffer_size) { - c->buffer_size = 0; - free(c->buffer); - // No dangling pointers! - c->buffer = NULL; - // Stop waking up when client is ready to receive messages - if (c->event.events & EPOLLOUT) { - c->event.events -= EPOLLOUT; - epoll_ctl(epoll_fd, EPOLL_CTL_MOD, c->fd, &c->event); - } - return n; - } - - // Shift unwritten buffer to beginning of buffer and reallocate - c->buffer_size -= n; - memmove(c->buffer, c->buffer + n, c->buffer_size); - c->buffer = (char *)realloc(c->buffer, c->buffer_size); - - return n; +ssize_t ipc_write_client(IPCClient *c) { + const ssize_t n = ipc_write_message(c->fd, c->buffer, c->buffer_size); + + if (n < 0) + return n; + + // TODO: Deal with client timeouts + + if (n == c->buffer_size) { + c->buffer_size = 0; + free(c->buffer); + // No dangling pointers! + c->buffer = NULL; + // Stop waking up when client is ready to receive messages + if (c->event.events & EPOLLOUT) { + c->event.events -= EPOLLOUT; + epoll_ctl(epoll_fd, EPOLL_CTL_MOD, c->fd, &c->event); + } + return n; + } + + // Shift unwritten buffer to beginning of buffer and reallocate + c->buffer_size -= n; + memmove(c->buffer, c->buffer + n, c->buffer_size); + c->buffer = (char *) realloc(c->buffer, c->buffer_size); + + return n; } -void -ipc_prepare_send_message(IPCClient *c, const IPCMessageType msg_type, - const uint32_t msg_size, const char *msg) -{ - dwm_ipc_header_t header = { - .magic = IPC_MAGIC_ARR, .type = msg_type, .size = msg_size}; +void ipc_prepare_send_message(IPCClient *c, const IPCMessageType msg_type, + const uint32_t msg_size, const char *msg) { + dwm_ipc_header_t header = {.magic = IPC_MAGIC_ARR, + .type = msg_type, + .size = msg_size}; - uint32_t header_size = sizeof(dwm_ipc_header_t); - uint32_t packet_size = header_size + msg_size; + uint32_t header_size = sizeof(dwm_ipc_header_t); + uint32_t packet_size = header_size + msg_size; - if (c->buffer == NULL) - c->buffer = (char *)malloc(c->buffer_size + packet_size); - else - c->buffer = (char *)realloc(c->buffer, c->buffer_size + packet_size); + if (c->buffer == NULL) + c->buffer = (char *) malloc(c->buffer_size + packet_size); + else + c->buffer = (char *) realloc(c->buffer, c->buffer_size + packet_size); - // Copy header to end of client buffer - memcpy(c->buffer + c->buffer_size, &header, header_size); - c->buffer_size += header_size; + // Copy header to end of client buffer + memcpy(c->buffer + c->buffer_size, &header, header_size); + c->buffer_size += header_size; - // Copy message to end of client buffer - memcpy(c->buffer + c->buffer_size, msg, msg_size); - c->buffer_size += msg_size; + // Copy message to end of client buffer + memcpy(c->buffer + c->buffer_size, msg, msg_size); + c->buffer_size += msg_size; - // Wake up when client is ready to receive messages - c->event.events |= EPOLLOUT; - epoll_ctl(epoll_fd, EPOLL_CTL_MOD, c->fd, &c->event); + // Wake up when client is ready to receive messages + c->event.events |= EPOLLOUT; + epoll_ctl(epoll_fd, EPOLL_CTL_MOD, c->fd, &c->event); } -void -ipc_prepare_reply_failure(IPCClient *c, IPCMessageType msg_type, - const char *format, ...) -{ - yajl_gen gen; - va_list args; +void ipc_prepare_reply_failure(IPCClient *c, IPCMessageType msg_type, + const char *format, ...) { + yajl_gen gen; + va_list args; - // Get output size - va_start(args, format); - size_t len = vsnprintf(NULL, 0, format, args); - va_end(args); - char *buffer = (char *)malloc((len + 1) * sizeof(char)); + // Get output size + va_start(args, format); + size_t len = vsnprintf(NULL, 0, format, args); + va_end(args); + char *buffer = (char *) malloc((len + 1) * sizeof(char)); - ipc_reply_init_message(&gen); + ipc_reply_init_message(&gen); - va_start(args, format); - vsnprintf(buffer, len + 1, format, args); - va_end(args); - dump_error_message(gen, buffer); + va_start(args, format); + vsnprintf(buffer, len + 1, format, args); + va_end(args); + dump_error_message(gen, buffer); - ipc_reply_prepare_send_message(gen, c, msg_type); - fprintf(stderr, "[fd %d] Error: %s\n", c->fd, buffer); + ipc_reply_prepare_send_message(gen, c, msg_type); + fprintf(stderr, "[fd %d] Error: %s\n", c->fd, buffer); - free(buffer); + free(buffer); } -void -ipc_prepare_reply_success(IPCClient *c, IPCMessageType msg_type) -{ - const char *success_msg = "{\"result\":\"success\"}"; - const size_t msg_len = strlen(success_msg) + 1; // +1 for null char +void ipc_prepare_reply_success(IPCClient *c, IPCMessageType msg_type) { + const char *success_msg = "{\"result\":\"success\"}"; + const size_t msg_len = strlen(success_msg) + 1; // +1 for null char - ipc_prepare_send_message(c, msg_type, msg_len, success_msg); + ipc_prepare_send_message(c, msg_type, msg_len, success_msg); } -void -ipc_tag_change_event(int mon_num, TagState old_state, TagState new_state) -{ - yajl_gen gen; - ipc_event_init_message(&gen); - dump_tag_event(gen, mon_num, old_state, new_state); - ipc_event_prepare_send_message(gen, IPC_EVENT_TAG_CHANGE); +void ipc_tag_change_event(int mon_num, TagState old_state, + TagState new_state) { + yajl_gen gen; + ipc_event_init_message(&gen); + dump_tag_event(gen, mon_num, old_state, new_state); + ipc_event_prepare_send_message(gen, IPC_EVENT_TAG_CHANGE); } -void -ipc_client_focus_change_event(int mon_num, Client *old_client, - Client *new_client) -{ - yajl_gen gen; - ipc_event_init_message(&gen); - dump_client_focus_change_event(gen, old_client, new_client, mon_num); - ipc_event_prepare_send_message(gen, IPC_EVENT_CLIENT_FOCUS_CHANGE); +void ipc_client_focus_change_event(int mon_num, Client *old_client, + Client *new_client) { + yajl_gen gen; + ipc_event_init_message(&gen); + dump_client_focus_change_event(gen, old_client, new_client, mon_num); + ipc_event_prepare_send_message(gen, IPC_EVENT_CLIENT_FOCUS_CHANGE); } -void -ipc_layout_change_event(const int mon_num, const char *old_symbol, - const Layout *old_layout, const char *new_symbol, - const Layout *new_layout) -{ - yajl_gen gen; - ipc_event_init_message(&gen); - dump_layout_change_event(gen, mon_num, old_symbol, old_layout, new_symbol, - new_layout); - ipc_event_prepare_send_message(gen, IPC_EVENT_LAYOUT_CHANGE); +void ipc_layout_change_event(const int mon_num, const char *old_symbol, + const Layout *old_layout, const char *new_symbol, + const Layout *new_layout) { + yajl_gen gen; + ipc_event_init_message(&gen); + dump_layout_change_event(gen, mon_num, old_symbol, old_layout, new_symbol, + new_layout); + ipc_event_prepare_send_message(gen, IPC_EVENT_LAYOUT_CHANGE); } -void -ipc_monitor_focus_change_event(const int last_mon_num, const int new_mon_num) -{ - yajl_gen gen; - ipc_event_init_message(&gen); - dump_monitor_focus_change_event(gen, last_mon_num, new_mon_num); - ipc_event_prepare_send_message(gen, IPC_EVENT_MONITOR_FOCUS_CHANGE); +void ipc_monitor_focus_change_event(const int last_mon_num, + const int new_mon_num) { + yajl_gen gen; + ipc_event_init_message(&gen); + dump_monitor_focus_change_event(gen, last_mon_num, new_mon_num); + ipc_event_prepare_send_message(gen, IPC_EVENT_MONITOR_FOCUS_CHANGE); } -void -ipc_focused_title_change_event(const int mon_num, const Window client_id, - const char *old_name, const char *new_name) -{ - yajl_gen gen; - ipc_event_init_message(&gen); - dump_focused_title_change_event(gen, mon_num, client_id, old_name, new_name); - ipc_event_prepare_send_message(gen, IPC_EVENT_FOCUSED_TITLE_CHANGE); +void ipc_focused_title_change_event(const int mon_num, const Window client_id, + const char *old_name, + const char *new_name) { + yajl_gen gen; + ipc_event_init_message(&gen); + dump_focused_title_change_event(gen, mon_num, client_id, old_name, + new_name); + ipc_event_prepare_send_message(gen, IPC_EVENT_FOCUSED_TITLE_CHANGE); } -void -ipc_focused_state_change_event(const int mon_num, const Window client_id, - const ClientState *old_state, - const ClientState *new_state) -{ - yajl_gen gen; - ipc_event_init_message(&gen); - dump_focused_state_change_event(gen, mon_num, client_id, old_state, - new_state); - ipc_event_prepare_send_message(gen, IPC_EVENT_FOCUSED_STATE_CHANGE); +void ipc_focused_state_change_event(const int mon_num, const Window client_id, + const ClientState *old_state, + const ClientState *new_state) { + yajl_gen gen; + ipc_event_init_message(&gen); + dump_focused_state_change_event(gen, mon_num, client_id, old_state, + new_state); + ipc_event_prepare_send_message(gen, IPC_EVENT_FOCUSED_STATE_CHANGE); } -void -ipc_send_events(Monitor *mons, Monitor **lastselmon, Monitor *selmon) -{ - for (Monitor *m = mons; m; m = m->next) { - unsigned int urg = 0, occ = 0, tagset = 0; - - for (Client *c = m->clients; c; c = c->next) { - occ |= c->tags; - - if (c->isurgent) urg |= c->tags; - } - tagset = m->tagset[m->seltags]; - - TagState new_state = {.selected = tagset, .occupied = occ, .urgent = urg}; - - if (memcmp(&m->tagstate, &new_state, sizeof(TagState)) != 0) { - ipc_tag_change_event(m->num, m->tagstate, new_state); - m->tagstate = new_state; - } - - if (m->lastsel != m->sel) { - ipc_client_focus_change_event(m->num, m->lastsel, m->sel); - m->lastsel = m->sel; - } - - if (strcmp(m->ltsymbol, m->lastltsymbol) != 0 || - m->lastlt != m->lt[m->sellt]) { - ipc_layout_change_event(m->num, m->lastltsymbol, m->lastlt, m->ltsymbol, - m->lt[m->sellt]); - strcpy(m->lastltsymbol, m->ltsymbol); - m->lastlt = m->lt[m->sellt]; - } - - if (*lastselmon != selmon) { - if (*lastselmon != NULL) - ipc_monitor_focus_change_event((*lastselmon)->num, selmon->num); - *lastselmon = selmon; - } - - Client *sel = m->sel; - if (!sel) continue; - ClientState *o = &m->sel->prevstate; - ClientState n = {.oldstate = sel->oldstate, - .isfixed = sel->isfixed, - .isfloating = sel->isfloating, - .isfullscreen = sel->isfullscreen, - .isurgent = sel->isurgent, - .neverfocus = sel->neverfocus}; - if (memcmp(o, &n, sizeof(ClientState)) != 0) { - ipc_focused_state_change_event(m->num, m->sel->win, o, &n); - *o = n; - } - } +void ipc_send_events(Monitor *mons, Monitor **lastselmon, Monitor *selmon) { + for (Monitor *m = mons; m; m = m->next) { + unsigned int urg = 0, occ = 0, tagset = 0; + + for (Client *c = m->clients; c; c = c->next) { + occ |= c->tags; + + if (c->isurgent) + urg |= c->tags; + } + tagset = m->tagset[m->seltags]; + + TagState new_state = {.selected = tagset, + .occupied = occ, + .urgent = urg}; + + if (memcmp(&m->tagstate, &new_state, sizeof(TagState)) != 0) { + ipc_tag_change_event(m->num, m->tagstate, new_state); + m->tagstate = new_state; + } + + if (m->lastsel != m->sel) { + ipc_client_focus_change_event(m->num, m->lastsel, m->sel); + m->lastsel = m->sel; + } + + if (strcmp(m->ltsymbol, m->lastltsymbol) != 0 + || m->lastlt != m->lt[m->sellt]) { + ipc_layout_change_event(m->num, m->lastltsymbol, m->lastlt, + m->ltsymbol, m->lt[m->sellt]); + strcpy(m->lastltsymbol, m->ltsymbol); + m->lastlt = m->lt[m->sellt]; + } + + if (*lastselmon != selmon) { + if (*lastselmon != NULL) + ipc_monitor_focus_change_event((*lastselmon)->num, + selmon->num); + *lastselmon = selmon; + } + + Client *sel = m->sel; + if (!sel) + continue; + ClientState *o = &m->sel->prevstate; + ClientState n = {.oldstate = sel->oldstate, + .isfixed = sel->isfixed, + .isfloating = sel->isfloating, + .isfullscreen = sel->isfullscreen, + .isurgent = sel->isurgent, + .neverfocus = sel->neverfocus}; + if (memcmp(o, &n, sizeof(ClientState)) != 0) { + ipc_focused_state_change_event(m->num, m->sel->win, o, &n); + *o = n; + } + } } -int -ipc_handle_client_epoll_event(struct epoll_event *ev, Monitor *mons, - Monitor **lastselmon, Monitor *selmon, - const char *tags[], const int tags_len, - const Layout *layouts, const int layouts_len) -{ - int fd = ev->data.fd; - IPCClient *c = ipc_get_client(fd); - - if (ev->events & EPOLLHUP) { - DEBUG("EPOLLHUP received from client at fd %d\n", fd); - ipc_drop_client(c); - } else if (ev->events & EPOLLOUT) { - DEBUG("Sending message to client at fd %d...\n", fd); - if (c->buffer_size) ipc_write_client(c); - } else if (ev->events & EPOLLIN) { - IPCMessageType msg_type = 0; - uint32_t msg_size = 0; - char *msg = NULL; - - DEBUG("Received message from fd %d\n", fd); - if (ipc_read_client(c, &msg_type, &msg_size, &msg) < 0) return -1; - - if (msg_type == IPC_TYPE_GET_MONITORS) - ipc_get_monitors(c, mons, selmon); - else if (msg_type == IPC_TYPE_GET_TAGS) - ipc_get_tags(c, tags, tags_len); - else if (msg_type == IPC_TYPE_GET_LAYOUTS) - ipc_get_layouts(c, layouts, layouts_len); - else if (msg_type == IPC_TYPE_RUN_COMMAND) { - if (ipc_run_command(c, msg) < 0) return -1; - ipc_send_events(mons, lastselmon, selmon); - } else if (msg_type == IPC_TYPE_GET_DWM_CLIENT) { - if (ipc_get_dwm_client(c, msg, mons) < 0) return -1; - } else if (msg_type == IPC_TYPE_SUBSCRIBE) { - if (ipc_subscribe(c, msg) < 0) return -1; - } else { - fprintf(stderr, "Invalid message type received from fd %d", fd); - ipc_prepare_reply_failure(c, msg_type, "Invalid message type: %d", - msg_type); - } - free(msg); - } else { - fprintf(stderr, "Epoll event returned %d from fd %d\n", ev->events, fd); - return -1; - } - - return 0; +int ipc_handle_client_epoll_event(struct epoll_event *ev, Monitor *mons, + Monitor **lastselmon, Monitor *selmon, + const char *tags[], const int tags_len, + const Layout *layouts, + const int layouts_len) { + int fd = ev->data.fd; + IPCClient *c = ipc_get_client(fd); + + if (ev->events & EPOLLHUP) { + DEBUG("EPOLLHUP received from client at fd %d\n", fd); + ipc_drop_client(c); + } else if (ev->events & EPOLLOUT) { + DEBUG("Sending message to client at fd %d...\n", fd); + if (c->buffer_size) + ipc_write_client(c); + } else if (ev->events & EPOLLIN) { + IPCMessageType msg_type = 0; + uint32_t msg_size = 0; + char *msg = NULL; + + DEBUG("Received message from fd %d\n", fd); + if (ipc_read_client(c, &msg_type, &msg_size, &msg) < 0) + return -1; + + if (msg_type == IPC_TYPE_GET_MONITORS) + ipc_get_monitors(c, mons, selmon); + else if (msg_type == IPC_TYPE_GET_TAGS) + ipc_get_tags(c, tags, tags_len); + else if (msg_type == IPC_TYPE_GET_LAYOUTS) + ipc_get_layouts(c, layouts, layouts_len); + else if (msg_type == IPC_TYPE_RUN_COMMAND) { + if (ipc_run_command(c, msg) < 0) + return -1; + ipc_send_events(mons, lastselmon, selmon); + } else if (msg_type == IPC_TYPE_GET_DWM_CLIENT) { + if (ipc_get_dwm_client(c, msg, mons) < 0) + return -1; + } else if (msg_type == IPC_TYPE_SUBSCRIBE) { + if (ipc_subscribe(c, msg) < 0) + return -1; + } else { + fprintf(stderr, "Invalid message type received from fd %d", fd); + ipc_prepare_reply_failure(c, msg_type, "Invalid message type: %d", + msg_type); + } + free(msg); + } else { + fprintf(stderr, "Epoll event returned %d from fd %d\n", ev->events, + fd); + return -1; + } + + return 0; } -int -ipc_handle_socket_epoll_event(struct epoll_event *ev) -{ - if (!(ev->events & EPOLLIN)) return -1; +int ipc_handle_socket_epoll_event(struct epoll_event *ev) { + if (!(ev->events & EPOLLIN)) + return -1; - // EPOLLIN means incoming client connection request - fputs("Received EPOLLIN event on socket\n", stderr); - int new_fd = ipc_accept_client(); + // EPOLLIN means incoming client connection request + fputs("Received EPOLLIN event on socket\n", stderr); + int new_fd = ipc_accept_client(); - return new_fd; + return new_fd; } diff --git a/src/ipc.h b/src/ipc.h index e3b5bba..86f4e09 100644 --- a/src/ipc.h +++ b/src/ipc.h @@ -17,67 +17,67 @@ // clang-format on typedef enum IPCMessageType { - IPC_TYPE_RUN_COMMAND = 0, - IPC_TYPE_GET_MONITORS = 1, - IPC_TYPE_GET_TAGS = 2, - IPC_TYPE_GET_LAYOUTS = 3, - IPC_TYPE_GET_DWM_CLIENT = 4, - IPC_TYPE_SUBSCRIBE = 5, - IPC_TYPE_EVENT = 6 + IPC_TYPE_RUN_COMMAND = 0, + IPC_TYPE_GET_MONITORS = 1, + IPC_TYPE_GET_TAGS = 2, + IPC_TYPE_GET_LAYOUTS = 3, + IPC_TYPE_GET_DWM_CLIENT = 4, + IPC_TYPE_SUBSCRIBE = 5, + IPC_TYPE_EVENT = 6 } IPCMessageType; typedef enum IPCEvent { - IPC_EVENT_TAG_CHANGE = 1 << 0, - IPC_EVENT_CLIENT_FOCUS_CHANGE = 1 << 1, - IPC_EVENT_LAYOUT_CHANGE = 1 << 2, - IPC_EVENT_MONITOR_FOCUS_CHANGE = 1 << 3, - IPC_EVENT_FOCUSED_TITLE_CHANGE = 1 << 4, - IPC_EVENT_FOCUSED_STATE_CHANGE = 1 << 5 + IPC_EVENT_TAG_CHANGE = 1 << 0, + IPC_EVENT_CLIENT_FOCUS_CHANGE = 1 << 1, + IPC_EVENT_LAYOUT_CHANGE = 1 << 2, + IPC_EVENT_MONITOR_FOCUS_CHANGE = 1 << 3, + IPC_EVENT_FOCUSED_TITLE_CHANGE = 1 << 4, + IPC_EVENT_FOCUSED_STATE_CHANGE = 1 << 5 } IPCEvent; typedef enum IPCSubscriptionAction { - IPC_ACTION_UNSUBSCRIBE = 0, - IPC_ACTION_SUBSCRIBE = 1 + IPC_ACTION_UNSUBSCRIBE = 0, + IPC_ACTION_SUBSCRIBE = 1 } IPCSubscriptionAction; /** * Every IPC packet starts with this structure */ typedef struct dwm_ipc_header { - uint8_t magic[IPC_MAGIC_LEN]; - uint32_t size; - uint8_t type; + uint8_t magic[IPC_MAGIC_LEN]; + uint32_t size; + uint8_t type; } __attribute((packed)) dwm_ipc_header_t; typedef enum ArgType { - ARG_TYPE_NONE = 0, - ARG_TYPE_UINT = 1, - ARG_TYPE_SINT = 2, - ARG_TYPE_FLOAT = 3, - ARG_TYPE_PTR = 4, - ARG_TYPE_STR = 5 + ARG_TYPE_NONE = 0, + ARG_TYPE_UINT = 1, + ARG_TYPE_SINT = 2, + ARG_TYPE_FLOAT = 3, + ARG_TYPE_PTR = 4, + ARG_TYPE_STR = 5 } ArgType; /** * An IPCCommand function can have either of these function signatures */ typedef union ArgFunction { - void (*single_param)(const Arg *); - void (*array_param)(const Arg *, int); + void (*single_param)(const Arg *); + void (*array_param)(const Arg *, int); } ArgFunction; typedef struct IPCCommand { - char *name; - ArgFunction func; - unsigned int argc; - ArgType *arg_types; + char *name; + ArgFunction func; + unsigned int argc; + ArgType *arg_types; } IPCCommand; typedef struct IPCParsedCommand { - char *name; - Arg *args; - ArgType *arg_types; - unsigned int argc; + char *name; + Arg *args; + ArgType *arg_types; + unsigned int argc; } IPCParsedCommand; /** @@ -88,15 +88,15 @@ typedef struct IPCParsedCommand { * @param commands Address of IPCCommands array defined in config.h * @param commands_len Length of commands[] array * - * @return int The file descriptor of the socket if it was successfully created, - * -1 otherwise + * @return int The file descriptor of the socket if it was successfully + * created, -1 otherwise */ int ipc_init(const char *socket_path, const int p_epoll_fd, IPCCommand commands[], const int commands_len); /** - * Uninitialize the socket and module. Free allocated memory and restore static - * variables to their state before ipc_init + * Uninitialize the socket and module. Free allocated memory and restore + * static variables to their state before ipc_init */ void ipc_cleanup(); @@ -150,16 +150,16 @@ int ipc_accept_client(); * @param c Address of IPCClient * @param msg_type Address to IPCMessageType variable which will be assigned * the message type of the received message - * @param msg_size Address to uint32_t variable which will be assigned the size - * of the received message + * @param msg_size Address to uint32_t variable which will be assigned the + * size of the received message * @param msg Address to char* variable which will be assigned the address of * the received message. This must be freed using free(). * - * @return 0 on success, -1 on error reading message, -2 if reading the message - * resulted in EAGAIN, EINTR, or EWOULDBLOCK. + * @return 0 on success, -1 on error reading message, -2 if reading the + * message resulted in EAGAIN, EINTR, or EWOULDBLOCK. */ -int ipc_read_client(IPCClient *c, IPCMessageType *msg_type, uint32_t *msg_size, - char **msg); +int ipc_read_client(IPCClient *c, IPCMessageType *msg_type, + uint32_t *msg_size, char **msg); /** * Write any pending buffer of the client to the client's socket @@ -204,8 +204,8 @@ void ipc_prepare_reply_failure(IPCClient *c, IPCMessageType msg_type, void ipc_prepare_reply_success(IPCClient *c, IPCMessageType msg_type); /** - * Send a tag_change_event to all subscribers. Should be called only when there - * has been a tag state change. + * Send a tag_change_event to all subscribers. Should be called only when + * there has been a tag state change. * * @param mon_num The index of the monitor (Monitor.num property) * @param old_state The old tag state @@ -259,7 +259,8 @@ void ipc_monitor_focus_change_event(const int last_mon_num, * @param new_name New name of the client window */ void ipc_focused_title_change_event(const int mon_num, const Window client_id, - const char *old_name, const char *new_name); + const char *old_name, + const char *new_name); /** * Send a focused_state_change_event to all subscribers. Should only be called @@ -285,8 +286,8 @@ void ipc_send_events(Monitor *mons, Monitor **lastselmon, Monitor *selmon); /** * Handle an epoll event caused by a registered IPC client. Read, process, and - * handle any received messages from clients. Write pending buffer to client if - * the client is ready to receive messages. Drop clients that have sent an + * handle any received messages from clients. Write pending buffer to client + * if the client is ready to receive messages. Drop clients that have sent an * EPOLLHUP. * * @param ev Associated epoll event returned by epoll_wait @@ -304,16 +305,18 @@ void ipc_send_events(Monitor *mons, Monitor **lastselmon, Monitor *selmon); int ipc_handle_client_epoll_event(struct epoll_event *ev, Monitor *mons, Monitor **lastselmon, Monitor *selmon, const char *tags[], const int tags_len, - const Layout *layouts, const int layouts_len); + const Layout *layouts, + const int layouts_len); /** - * Handle an epoll event caused by the IPC socket. This function only handles an - * EPOLLIN event indicating a new client requesting to connect to the socket. + * Handle an epoll event caused by the IPC socket. This function only handles + * an EPOLLIN event indicating a new client requesting to connect to the + * socket. * * @param ev Associated epoll event returned by epoll_wait * - * @return 0, if the event was successfully handled, -1 if not an EPOLLIN event - * or if a new IPC client connection request could not be accepted. + * @return 0, if the event was successfully handled, -1 if not an EPOLLIN + * event or if a new IPC client connection request could not be accepted. */ int ipc_handle_socket_epoll_event(struct epoll_event *ev); diff --git a/src/transient.c b/src/transient.c index 040adb5..5d689b6 100644 --- a/src/transient.c +++ b/src/transient.c @@ -1,9 +1,9 @@ /* cc transient.c -o transient -lX11 */ -#include -#include #include #include +#include +#include int main(void) { Display *d; @@ -16,7 +16,7 @@ int main(void) { exit(1); r = DefaultRootWindow(d); - f = XCreateSimpleWindow(d, r, 100, 100, 400, 400, 0, 0, 0); + f = XCreateSimpleWindow(d, r, 100, 100, 400, 400, 0, 0, 0); h.min_width = h.max_width = h.min_height = h.max_height = 400; h.flags = PMinSize | PMaxSize; XSetWMNormalHints(d, f, &h); diff --git a/src/util.c b/src/util.c index dca4794..e7bbba0 100644 --- a/src/util.c +++ b/src/util.c @@ -1,16 +1,14 @@ /* See LICENSE file for copyright and license details. */ +#include #include #include #include #include -#include #include #include "util.h" -void * -ecalloc(size_t nmemb, size_t size) -{ +void *ecalloc(size_t nmemb, size_t size) { void *p; if (!(p = calloc(nmemb, size))) @@ -18,15 +16,14 @@ ecalloc(size_t nmemb, size_t size) return p; } -void -die(const char *fmt, ...) { +void die(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); - if (fmt[0] && fmt[strlen(fmt)-1] == ':') { + if (fmt[0] && fmt[strlen(fmt) - 1] == ':') { fputc(' ', stderr); perror(NULL); } else { @@ -36,135 +33,127 @@ die(const char *fmt, ...) { exit(1); } -int -normalizepath(const char *path, char **normal) -{ - size_t len = strlen(path); - *normal = (char *)malloc((len + 1) * sizeof(char)); - const char *walk = path; - const char *match; - size_t newlen = 0; - - while ((match = strchr(walk, '/'))) { - // Copy everything between match and walk - strncpy(*normal + newlen, walk, match - walk); - newlen += match - walk; - walk += match - walk; - - // Skip all repeating slashes - while (*walk == '/') - walk++; - - // If not last character in path - if (walk != path + len) - (*normal)[newlen++] = '/'; - } +int normalizepath(const char *path, char **normal) { + size_t len = strlen(path); + *normal = (char *) malloc((len + 1) * sizeof(char)); + const char *walk = path; + const char *match; + size_t newlen = 0; + + while ((match = strchr(walk, '/'))) { + // Copy everything between match and walk + strncpy(*normal + newlen, walk, match - walk); + newlen += match - walk; + walk += match - walk; + + // Skip all repeating slashes + while (*walk == '/') + walk++; + + // If not last character in path + if (walk != path + len) + (*normal)[newlen++] = '/'; + } - (*normal)[newlen++] = '\0'; + (*normal)[newlen++] = '\0'; - // Copy remaining path - strcat(*normal, walk); - newlen += strlen(walk); + // Copy remaining path + strcat(*normal, walk); + newlen += strlen(walk); - *normal = (char *)realloc(*normal, newlen * sizeof(char)); + *normal = (char *) realloc(*normal, newlen * sizeof(char)); - return 0; + return 0; } -int -parentdir(const char *path, char **parent) -{ - char *normal; - char *walk; +int parentdir(const char *path, char **parent) { + char *normal; + char *walk; - normalizepath(path, &normal); + normalizepath(path, &normal); - // Pointer to last '/' - if (!(walk = strrchr(normal, '/'))) { - free(normal); - return -1; - } + // Pointer to last '/' + if (!(walk = strrchr(normal, '/'))) { + free(normal); + return -1; + } - // Get path up to last '/' - size_t len = walk - normal; - *parent = (char *)malloc((len + 1) * sizeof(char)); + // Get path up to last '/' + size_t len = walk - normal; + *parent = (char *) malloc((len + 1) * sizeof(char)); - // Copy path up to last '/' - strncpy(*parent, normal, len); - // Add null char - (*parent)[len] = '\0'; + // Copy path up to last '/' + strncpy(*parent, normal, len); + // Add null char + (*parent)[len] = '\0'; - free(normal); + free(normal); - return 0; + return 0; } -int -mkdirp(const char *path) -{ - char *normal; - char *walk; - size_t normallen; - - normalizepath(path, &normal); - normallen = strlen(normal); - walk = normal; - - while (walk < normal + normallen + 1) { - // Get length from walk to next / - size_t n = strcspn(walk, "/"); - - // Skip path / - if (n == 0) { - walk++; - continue; - } - - // Length of current path segment - size_t curpathlen = walk - normal + n; - char curpath[curpathlen + 1]; - struct stat s; - - // Copy path segment to stat - strncpy(curpath, normal, curpathlen); - strcpy(curpath + curpathlen, ""); - int res = stat(curpath, &s); - - if (res < 0) { - if (errno == ENOENT) { - DEBUG("Making directory %s\n", curpath); - if (mkdir(curpath, 0700) < 0) { - fprintf(stderr, "Failed to make directory %s\n", curpath); - perror(""); - free(normal); - return -1; - } - } else { - fprintf(stderr, "Error statting directory %s\n", curpath); - perror(""); - free(normal); - return -1; - } - } - - // Continue to next path segment - walk += n; - } - - free(normal); - - return 0; +int mkdirp(const char *path) { + char *normal; + char *walk; + size_t normallen; + + normalizepath(path, &normal); + normallen = strlen(normal); + walk = normal; + + while (walk < normal + normallen + 1) { + // Get length from walk to next / + size_t n = strcspn(walk, "/"); + + // Skip path / + if (n == 0) { + walk++; + continue; + } + + // Length of current path segment + size_t curpathlen = walk - normal + n; + char curpath[curpathlen + 1]; + struct stat s; + + // Copy path segment to stat + strncpy(curpath, normal, curpathlen); + strcpy(curpath + curpathlen, ""); + int res = stat(curpath, &s); + + if (res < 0) { + if (errno == ENOENT) { + DEBUG("Making directory %s\n", curpath); + if (mkdir(curpath, 0700) < 0) { + fprintf(stderr, "Failed to make directory %s\n", curpath); + perror(""); + free(normal); + return -1; + } + } else { + fprintf(stderr, "Error statting directory %s\n", curpath); + perror(""); + free(normal); + return -1; + } + } + + // Continue to next path segment + walk += n; + } + + free(normal); + + return 0; } -int -nullterminate(char **str, size_t *len) -{ - if ((*str)[*len - 1] == '\0') - return 0; +int nullterminate(char **str, size_t *len) { + if ((*str)[*len - 1] == '\0') + return 0; - (*len)++; - *str = (char*)realloc(*str, *len * sizeof(char)); - (*str)[*len - 1] = '\0'; + (*len)++; + *str = (char *) realloc(*str, *len * sizeof(char)); + (*str)[*len - 1] = '\0'; - return 0; + return 0; } diff --git a/src/util.h b/src/util.h index 73a238e..84a2655 100644 --- a/src/util.h +++ b/src/util.h @@ -1,8 +1,8 @@ /* See LICENSE file for copyright and license details. */ -#define MAX(A, B) ((A) > (B) ? (A) : (B)) -#define MIN(A, B) ((A) < (B) ? (A) : (B)) -#define BETWEEN(X, A, B) ((A) <= (X) && (X) <= (B)) +#define MAX(A, B) ((A) > (B) ? (A) : (B)) +#define MIN(A, B) ((A) < (B) ? (A) : (B)) +#define BETWEEN(X, A, B) ((A) <= (X) && (X) <= (B)) #ifdef _DEBUG #define DEBUG(...) fprintf(stderr, __VA_ARGS__) diff --git a/src/yajl_dumps.c b/src/yajl_dumps.c index 8bf9688..52094c6 100644 --- a/src/yajl_dumps.c +++ b/src/yajl_dumps.c @@ -2,36 +2,30 @@ #include -int -dump_tag(yajl_gen gen, const char *name, const int tag_mask) -{ - // clang-format off +int dump_tag(yajl_gen gen, const char *name, const int tag_mask) { + // clang-format off YMAP( YSTR("bit_mask"); YINT(tag_mask); YSTR("name"); YSTR(name); ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_tags(yajl_gen gen, const char *tags[], int tags_len) -{ - // clang-format off +int dump_tags(yajl_gen gen, const char *tags[], int tags_len) { + // clang-format off YARR( for (int i = 0; i < tags_len; i++) dump_tag(gen, tags[i], 1 << i); ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_client(yajl_gen gen, Client *c) -{ - // clang-format off +int dump_client(yajl_gen gen, Client *c) { + // clang-format off YMAP( YSTR("name"); YSTR(c->name); YSTR("tags"); YINT(c->tags); @@ -90,15 +84,13 @@ dump_client(yajl_gen gen, Client *c) YSTR("is_fullscreen"); YBOOL(c->isfullscreen); ) ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_monitor(yajl_gen gen, Monitor *mon, int is_selected) -{ - // clang-format off +int dump_monitor(yajl_gen gen, Monitor *mon, int is_selected) { + // clang-format off YMAP( YSTR("master_factor"); YDOUBLE(mon->mfact); YSTR("num_master"); YINT(mon->nmaster); @@ -156,15 +148,13 @@ dump_monitor(yajl_gen gen, Monitor *mon, int is_selected) YSTR("window_id"); YINT(mon->barwin); ) ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_monitors(yajl_gen gen, Monitor *mons, Monitor *selmon) -{ - // clang-format off +int dump_monitors(yajl_gen gen, Monitor *mons, Monitor *selmon) { + // clang-format off YARR( for (Monitor *mon = mons; mon; mon = mon->next) { if (mon == selmon) @@ -173,15 +163,14 @@ dump_monitors(yajl_gen gen, Monitor *mons, Monitor *selmon) dump_monitor(gen, mon, 0); } ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_layouts(yajl_gen gen, const Layout layouts[], const int layouts_len) -{ - // clang-format off +int dump_layouts(yajl_gen gen, const Layout layouts[], + const int layouts_len) { + // clang-format off YARR( for (int i = 0; i < layouts_len; i++) { YMAP( @@ -192,30 +181,26 @@ dump_layouts(yajl_gen gen, const Layout layouts[], const int layouts_len) ) } ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_tag_state(yajl_gen gen, TagState state) -{ - // clang-format off +int dump_tag_state(yajl_gen gen, TagState state) { + // clang-format off YMAP( YSTR("selected"); YINT(state.selected); YSTR("occupied"); YINT(state.occupied); YSTR("urgent"); YINT(state.urgent); ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_tag_event(yajl_gen gen, int mon_num, TagState old_state, - TagState new_state) -{ - // clang-format off +int dump_tag_event(yajl_gen gen, int mon_num, TagState old_state, + TagState new_state) { + // clang-format off YMAP( YSTR("tag_change_event"); YMAP( YSTR("monitor_number"); YINT(mon_num); @@ -223,16 +208,14 @@ dump_tag_event(yajl_gen gen, int mon_num, TagState old_state, YSTR("new_state"); dump_tag_state(gen, new_state); ) ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_client_focus_change_event(yajl_gen gen, Client *old_client, - Client *new_client, int mon_num) -{ - // clang-format off +int dump_client_focus_change_event(yajl_gen gen, Client *old_client, + Client *new_client, int mon_num) { + // clang-format off YMAP( YSTR("client_focus_change_event"); YMAP( YSTR("monitor_number"); YINT(mon_num); @@ -240,17 +223,16 @@ dump_client_focus_change_event(yajl_gen gen, Client *old_client, YSTR("new_win_id"); new_client == NULL ? YNULL() : YINT(new_client->win); ) ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_layout_change_event(yajl_gen gen, const int mon_num, - const char *old_symbol, const Layout *old_layout, - const char *new_symbol, const Layout *new_layout) -{ - // clang-format off +int dump_layout_change_event(yajl_gen gen, const int mon_num, + const char *old_symbol, const Layout *old_layout, + const char *new_symbol, + const Layout *new_layout) { + // clang-format off YMAP( YSTR("layout_change_event"); YMAP( YSTR("monitor_number"); YINT(mon_num); @@ -260,33 +242,30 @@ dump_layout_change_event(yajl_gen gen, const int mon_num, YSTR("new_address"); YINT((uintptr_t)new_layout); ) ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_monitor_focus_change_event(yajl_gen gen, const int last_mon_num, - const int new_mon_num) -{ - // clang-format off +int dump_monitor_focus_change_event(yajl_gen gen, const int last_mon_num, + const int new_mon_num) { + // clang-format off YMAP( YSTR("monitor_focus_change_event"); YMAP( YSTR("old_monitor_number"); YINT(last_mon_num); YSTR("new_monitor_number"); YINT(new_mon_num); ) ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_focused_title_change_event(yajl_gen gen, const int mon_num, - const Window client_id, const char *old_name, - const char *new_name) -{ - // clang-format off +int dump_focused_title_change_event(yajl_gen gen, const int mon_num, + const Window client_id, + const char *old_name, + const char *new_name) { + // clang-format off YMAP( YSTR("focused_title_change_event"); YMAP( YSTR("monitor_number"); YINT(mon_num); @@ -295,15 +274,13 @@ dump_focused_title_change_event(yajl_gen gen, const int mon_num, YSTR("new_name"); YSTR(new_name); ) ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_client_state(yajl_gen gen, const ClientState *state) -{ - // clang-format off +int dump_client_state(yajl_gen gen, const ClientState *state) { + // clang-format off YMAP( YSTR("old_state"); YBOOL(state->oldstate); YSTR("is_fixed"); YBOOL(state->isfixed); @@ -312,18 +289,16 @@ dump_client_state(yajl_gen gen, const ClientState *state) YSTR("is_urgent"); YBOOL(state->isurgent); YSTR("never_focus"); YBOOL(state->neverfocus); ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_focused_state_change_event(yajl_gen gen, const int mon_num, - const Window client_id, - const ClientState *old_state, - const ClientState *new_state) -{ - // clang-format off +int dump_focused_state_change_event(yajl_gen gen, const int mon_num, + const Window client_id, + const ClientState *old_state, + const ClientState *new_state) { + // clang-format off YMAP( YSTR("focused_state_change_event"); YMAP( YSTR("monitor_number"); YINT(mon_num); @@ -332,20 +307,18 @@ dump_focused_state_change_event(yajl_gen gen, const int mon_num, YSTR("new_state"); dump_client_state(gen, new_state); ) ) - // clang-format on + // clang-format on - return 0; + return 0; } -int -dump_error_message(yajl_gen gen, const char *reason) -{ - // clang-format off +int dump_error_message(yajl_gen gen, const char *reason) { + // clang-format off YMAP( YSTR("result"); YSTR("error"); YSTR("reason"); YSTR(reason); ) - // clang-format on + // clang-format on - return 0; + return 0; } diff --git a/src/yajl_dumps.h b/src/yajl_dumps.h index ee9948e..44738ac 100644 --- a/src/yajl_dumps.h +++ b/src/yajl_dumps.h @@ -4,23 +4,23 @@ #include #include -#define YSTR(str) yajl_gen_string(gen, (unsigned char *)str, strlen(str)) -#define YINT(num) yajl_gen_integer(gen, num) +#define YSTR(str) yajl_gen_string(gen, (unsigned char *) str, strlen(str)) +#define YINT(num) yajl_gen_integer(gen, num) #define YDOUBLE(num) yajl_gen_double(gen, num) -#define YBOOL(v) yajl_gen_bool(gen, v) -#define YNULL() yajl_gen_null(gen) -#define YARR(body) \ - { \ - yajl_gen_array_open(gen); \ - body; \ - yajl_gen_array_close(gen); \ - } -#define YMAP(body) \ - { \ - yajl_gen_map_open(gen); \ - body; \ - yajl_gen_map_close(gen); \ - } +#define YBOOL(v) yajl_gen_bool(gen, v) +#define YNULL() yajl_gen_null(gen) +#define YARR(body) \ + { \ + yajl_gen_array_open(gen); \ + body; \ + yajl_gen_array_close(gen); \ + } +#define YMAP(body) \ + { \ + yajl_gen_map_open(gen); \ + body; \ + yajl_gen_map_close(gen); \ + } int dump_tag(yajl_gen gen, const char *name, const int tag_mask); @@ -44,14 +44,16 @@ int dump_client_focus_change_event(yajl_gen gen, Client *old_client, int dump_layout_change_event(yajl_gen gen, const int mon_num, const char *old_symbol, const Layout *old_layout, - const char *new_symbol, const Layout *new_layout); + const char *new_symbol, + const Layout *new_layout); int dump_monitor_focus_change_event(yajl_gen gen, const int last_mon_num, const int new_mon_num); int dump_focused_title_change_event(yajl_gen gen, const int mon_num, const Window client_id, - const char *old_name, const char *new_name); + const char *old_name, + const char *new_name); int dump_client_state(yajl_gen gen, const ClientState *state); @@ -62,4 +64,4 @@ int dump_focused_state_change_event(yajl_gen gen, const int mon_num, int dump_error_message(yajl_gen gen, const char *reason); -#endif // YAJL_DUMPS_H_ +#endif // YAJL_DUMPS_H_