1
0
Fork 0
mirror of https://github.com/davatorium/rofi.git synced 2024-11-25 13:55:34 -05:00

Splitting over more files.

This commit is contained in:
Dave Davenport 2015-02-09 19:35:51 +01:00
parent f7eeaec60f
commit 682907d340
6 changed files with 816 additions and 699 deletions

View file

@ -33,6 +33,7 @@ rofi_SOURCES=\
source/history.c\
config/config.c\
source/helper.c\
source/x11-helper.c\
include/rofi.h\
include/rofi-i3.h\
include/run-dialog.h\
@ -42,7 +43,8 @@ rofi_SOURCES=\
include/xrmoptions.h\
include/history.h\
include/textbox.h\
include/helper.h
include/helper.h\
include/x11-helper.h
##
# Manpage

View file

@ -3,8 +3,6 @@
#include <X11/X.h>
#include <glib.h>
#define OVERLAP( a, b, c, d ) ( ( ( a ) == ( c ) && ( b ) == ( d ) ) || MIN ( ( a ) + ( b ), ( c ) + ( d ) ) - MAX ( ( a ), ( c ) ) > 0 )
#define INTERSECT( x, y, w, h, x1, y1, w1, h1 ) ( OVERLAP ( ( x ), ( w ), ( x1 ), ( w1 ) ) && OVERLAP ( ( y ), ( h ), ( y1 ), ( h1 ) ) )
/**
* Pointer to xdg cache directory.
@ -220,14 +218,4 @@ extern Settings config;
*/
void error_dialog ( const char *msg );
/**
* @param w The Window to read property from.
* @param atom The property identifier
*
* Get text property defined by atom from window.
* Support utf8.
*
* @returns a newly allocated string with the result or NULL
*/
char* window_get_text_prop ( Window w, Atom atom );
#endif

206
include/x11-helper.h Normal file
View file

@ -0,0 +1,206 @@
#ifndef __X11_HELPER_H__
#define __X11_HELPER_H__
// window lists
typedef struct
{
Window *array;
void **data;
int len;
} winlist;
/**
* Create a window list, pre-seeded with WINLIST entries.
*
* @returns A new window list.
*/
winlist* winlist_new ();
/**
* @param l The winlist.
* @param w The window to find.
*
* Find the window in the list, and return the array entry.
*
* @returns -1 if failed, index is successful.
*/
int winlist_find ( winlist *l, Window w );
/**
* @param l The winlist entry
*
* Free the winlist.
*/
void winlist_free ( winlist *l );
/**
* @param l The winlist entry
*
* Empty winlist without free-ing
*/
void winlist_empty ( winlist *l );
/**
* @param l The winlist.
* @param w The window to add.
* @param d Data pointer.
*
* Add one entry. If Full, extend with WINLIST entries.
*
* @returns 0 if failed, 1 is successful.
*/
int winlist_append ( winlist *l, Window w, void *d );
/**
* @param d Display connection to X server
* @param w window
*
* Get window attributes.
* This functions uses caching.
*
* @returns a XWindowAttributes
*/
XWindowAttributes* window_get_attributes ( Display *display, Window w );
int window_get_prop ( Display *display, Window w, Atom prop,
Atom *type, int *items,
void *buffer, unsigned int bytes ) __attribute__ ( ( nonnull ( 4, 5 ) ) );
/**
* @param display Connection to the X server.
* @param w The Window to read property from.
* @param atom The property identifier
*
* Get text property defined by atom from window.
* Support utf8.
*
* @returns a newly allocated string with the result or NULL
*/
char* window_get_text_prop ( Display *display, Window w, Atom atom );
int window_get_atom_prop ( Display *display, Window w, Atom atom, Atom *list, int count );
void window_set_atom_prop ( Display *display, Window w, Atom prop, Atom *atoms, int count );
int window_get_cardinal_prop ( Display *display, Window w, Atom atom, unsigned long *list, int count );
/**
* Create empty X11 cache for windows and windows attributes.
*/
void x11_cache_create ( void );
/**
* Empty the X11 cache.
* (does not free it.)
*/
void x11_cache_empty ( void );
/**
* Free the cache.
*/
void x11_cache_free ( void );
/**
* Window info.
*/
#define ATOM_ENUM( x ) x
#define ATOM_CHAR( x ) # x
// usable space on a monitor
#define EWMH_ATOMS( X ) \
X ( _NET_CLIENT_LIST_STACKING ), \
X ( _NET_NUMBER_OF_DESKTOPS ), \
X ( _NET_CURRENT_DESKTOP ), \
X ( _NET_ACTIVE_WINDOW ), \
X ( _NET_WM_NAME ), \
X ( _NET_WM_STATE ), \
X ( _NET_WM_STATE_SKIP_TASKBAR ), \
X ( _NET_WM_STATE_SKIP_PAGER ), \
X ( _NET_WM_STATE_ABOVE ), \
X ( _NET_WM_DESKTOP ), \
X ( CLIPBOARD ), \
X ( UTF8_STRING ), \
X ( _NET_WM_WINDOW_OPACITY )
enum { EWMH_ATOMS ( ATOM_ENUM ), NUM_NETATOMS };
extern const char *netatom_names[];
extern Atom netatoms[NUM_NETATOMS];
typedef struct
{
int x, y, w, h;
int l, r, t, b;
} workarea;
#define CLIENTTITLE 100
#define CLIENTCLASS 50
#define CLIENTNAME 50
#define CLIENTSTATE 10
#define CLIENTROLE 50
// a managable window
typedef struct
{
Window window, trans;
XWindowAttributes xattr;
char title[CLIENTTITLE];
char class[CLIENTCLASS];
char name[CLIENTNAME];
char role[CLIENTROLE];
int states;
Atom state[CLIENTSTATE];
workarea monitor;
int active;
} client;
// collect info on any window
// doesn't have to be a window we'll end up managing
client* window_client ( Display *display, Window win );
int client_has_state ( client *c, Atom state );
void monitor_active ( Display *display, workarea *mon );
int window_send_message ( Display *display, Window target, Window subject,
Atom atom, unsigned long protocol,
unsigned long mask, Time time );
/**
* @param display The display.
*
* Release keyboard.
*/
void release_keyboard ( Display *display );
/**
* @param display The display.
* @param w Window we want to grab keyboard on.
*
* Grab keyboard and mouse.
*
* @return 1 when keyboard is grabbed, 0 not.
*/
int take_keyboard ( Display *display, Window w );
void grab_key ( Display *display, unsigned int modmask, KeySym key );
void x11_parse_key ( char *combo, unsigned int *mod, KeySym *key );
/**
* @param display The connection to the X server.
* @param box The window to set the opacity on.
* @param opacity The opacity value. (0-100)
*
* Set the opacity of the window and sub-windows.
*/
void x11_set_window_opacity ( Display *display, Window box, unsigned int opacity );
/**
* Setup several items required.
* * Error handling,
* * Numlock detection
* * Cache
*/
void x11_setup ( Display *display );
#endif

View file

@ -39,6 +39,7 @@
#include <linux/un.h>
#include "rofi.h"
#include "x11-helper.h"
#include "rofi-i3.h"
#ifdef HAVE_I3_IPC_H
@ -122,7 +123,7 @@ int i3_support_initialize ( Display *display )
// Find the root window (each X has one.).
Window root = RootWindow ( display, XScreenNumberOfScreen ( screen ) );
// Get the i3 path property.
i3_socket_path = window_get_text_prop ( root, i3_sp_atom );
i3_socket_path = window_get_text_prop ( display, root, i3_sp_atom );
}
// If we find it, go into i3 mode.
return ( i3_socket_path != NULL ) ? TRUE : FALSE;

View file

@ -37,65 +37,49 @@
#include <X11/X.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xmd.h>
#include <X11/Xutil.h>
#include <X11/Xproto.h>
#include <X11/keysym.h>
#include <X11/XKBlib.h>
#include <X11/extensions/Xinerama.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "helper.h"
#include "x11-helper.h"
#include "rofi.h"
#include "rofi-i3.h"
#include "xrmoptions.h"
#include "textbox.h"
// Switchers.
#include "run-dialog.h"
#include "ssh-dialog.h"
#include "dmenu-dialog.h"
#include "script-dialog.h"
#include "xrmoptions.h"
#include "textbox.h"
#define LINE_MARGIN 3
typedef enum _MainLoopEvent
{
ML_XEVENT,
ML_TIMEOUT
} MainLoopEvent;
// This setting is no longer user configurable, but partial to this file:
int config_i3_mode = 0;
// Pidfile.
char *pidfile = NULL;
const char *cache_dir = NULL;
unsigned int NumlockMask = 0;
Display *display = NULL;
char *display_str = NULL;
static int ( *xerror )( Display *, XErrorEvent * );
#define ATOM_ENUM( x ) x
#define ATOM_CHAR( x ) # x
#define EWMH_ATOMS( X ) \
X ( _NET_CLIENT_LIST_STACKING ), \
X ( _NET_NUMBER_OF_DESKTOPS ), \
X ( _NET_CURRENT_DESKTOP ), \
X ( _NET_ACTIVE_WINDOW ), \
X ( _NET_WM_NAME ), \
X ( _NET_WM_STATE ), \
X ( _NET_WM_STATE_SKIP_TASKBAR ), \
X ( _NET_WM_STATE_SKIP_PAGER ), \
X ( _NET_WM_STATE_ABOVE ), \
X ( _NET_WM_DESKTOP ), \
X ( CLIPBOARD ), \
X ( UTF8_STRING ), \
X ( _NET_WM_WINDOW_OPACITY )
enum { EWMH_ATOMS ( ATOM_ENUM ), NUM_NETATOMS };
const char *netatom_names[] = { EWMH_ATOMS ( ATOM_CHAR ) };
Atom netatoms[NUM_NETATOMS];
unsigned int windows_modmask, rundialog_modmask, sshdialog_modmask;
KeySym rundialog_keysym, sshdialog_keysym, windows_keysym;
/**
* Structure defining a switcher.
* It consists of a name, callback and if enabled
@ -121,7 +105,6 @@ unsigned int num_switchers = 0;
// Current selected switcher.
unsigned int curr_switcher = 0;
/**
* @param name Name of the switcher to lookup.
*
@ -139,8 +122,6 @@ static int switcher_get ( const char *name )
return -1;
}
void catch_exit ( __attribute__( ( unused ) ) int sig )
{
while ( 0 < waitpid ( -1, NULL, WNOHANG ) ) {
@ -148,178 +129,14 @@ void catch_exit ( __attribute__( ( unused ) ) int sig )
}
}
/**
* @param d The display on witch the error occurred.
* @param ee The XErrorEvent
*
* X11 Error handler.
*/
static int display_oops ( Display *d, XErrorEvent *ee )
{
if ( ee->error_code == BadWindow
|| ( ee->request_code == X_GrabButton && ee->error_code == BadAccess )
|| ( ee->request_code == X_GrabKey && ee->error_code == BadAccess )
) {
return 0;
}
fprintf ( stderr, "error: request code=%d, error code=%d\n", ee->request_code, ee->error_code );
return xerror ( d, ee );
}
// usable space on a monitor
typedef struct
{
int x, y, w, h;
int l, r, t, b;
} workarea;
// window lists
typedef struct
{
Window *array;
void **data;
int len;
} winlist;
winlist *cache_client = NULL;
winlist *cache_xattr = NULL;
#define WINLIST 32
/**
* Create a window list, pre-seeded with WINLIST entries.
*
* @returns A new window list.
*/
winlist* winlist_new ()
{
winlist *l = g_malloc ( sizeof ( winlist ) );
l->len = 0;
l->array = g_malloc_n ( WINLIST + 1, sizeof ( Window ) );
l->data = g_malloc_n ( WINLIST + 1, sizeof ( void* ) );
return l;
}
/**
* @param l The winlist.
* @param w The window to add.
* @param d Data pointer.
*
* Add one entry. If Full, extend with WINLIST entries.
*
* @returns 0 if failed, 1 is successful.
*/
int winlist_append ( winlist *l, Window w, void *d )
{
if ( l->len > 0 && !( l->len % WINLIST ) ) {
l->array = g_realloc ( l->array, sizeof ( Window ) * ( l->len + WINLIST + 1 ) );
l->data = g_realloc ( l->data, sizeof ( void* ) * ( l->len + WINLIST + 1 ) );
}
// Make clang-check happy.
// TODO: make clang-check clear this should never be 0.
if ( l->data == NULL || l->array == NULL ) {
return 0;
}
l->data[l->len] = d;
l->array[l->len++] = w;
return l->len - 1;
}
/**
* @param l The winlist entry
*
* Empty winlist without free-ing
*/
void winlist_empty ( winlist *l )
{
while ( l->len > 0 ) {
g_free ( l->data[--( l->len )] );
}
}
/**
* @param l The winlist entry
*
* Free the winlist.
*/
void winlist_free ( winlist *l )
{
if ( l != NULL ) {
winlist_empty ( l );
g_free ( l->array );
g_free ( l->data );
g_free ( l );
}
}
/**
* @param l The winlist.
* @param w The window to find.
*
* Find the window in the list, and return the array entry.
*
* @returns -1 if failed, index is successful.
*/
int winlist_find ( winlist *l, Window w )
{
// iterate backwards. theory is: windows most often accessed will be
// nearer the end. testing with kcachegrind seems to support this...
int i;
for ( i = ( l->len - 1 ); i >= 0; i-- ) {
if ( l->array[i] == w ) {
return i;
}
}
return -1;
}
#define CLIENTTITLE 100
#define CLIENTCLASS 50
#define CLIENTNAME 50
#define CLIENTSTATE 10
#define CLIENTROLE 50
// a managable window
typedef struct
{
Window window, trans;
XWindowAttributes xattr;
char title[CLIENTTITLE];
char class[CLIENTCLASS];
char name[CLIENTNAME];
char role[CLIENTROLE];
int states;
Atom state[CLIENTSTATE];
workarea monitor;
int active;
} client;
unsigned int windows_modmask;
KeySym windows_keysym;
unsigned int rundialog_modmask;
KeySym rundialog_keysym;
unsigned int sshdialog_modmask;
KeySym sshdialog_keysym;
Window main_window = None;
GC gc = NULL;
Colormap map = None;
XVisualInfo vinfo;
int truecolor = FALSE;
static void create_visual_and_colormap ()
{
map = None;
// Try to create TrueColor map
if ( XMatchVisualInfo ( display, DefaultScreen ( display ), 32, TrueColor, &vinfo ) ) {
// Visual found, lets try to create map.
@ -360,36 +177,6 @@ static unsigned int color_get ( Display *display, const char *const name )
}
}
/**
* @param x The x position of the mouse [out]
* @param y The y position of the mouse [out]
*
* find mouse pointer location
*
* @returns 1 when found
*/
static int pointer_get ( Display *display, Window root, int *x, int *y )
{
*x = 0;
*y = 0;
Window rr, cr;
int rxr, ryr, wxr, wyr;
unsigned int mr;
if ( XQueryPointer ( display, root, &rr, &cr, &rxr, &ryr, &wxr, &wyr, &mr ) ) {
*x = rxr;
*y = ryr;
return 1;
}
return 0;
}
typedef enum _MainLoopEvent
{
ML_XEVENT,
ML_TIMEOUT
} MainLoopEvent;
static inline MainLoopEvent wait_for_xevent_or_timeout ( Display *display, int x11_fd )
{
// Check if events are pending.
@ -413,291 +200,6 @@ static inline MainLoopEvent wait_for_xevent_or_timeout ( Display *display, int x
return ML_XEVENT;
}
/**
* @param display The display.
* @param w Window we want to grab keyboard on.
*
* Grab keyboard and mouse.
*
* @return 1 when keyboard is grabbed, 0 not.
*/
static int take_keyboard ( Display *display, Window w )
{
if ( XGrabKeyboard ( display, w, True, GrabModeAsync, GrabModeAsync, CurrentTime ) == GrabSuccess ) {
return 1;
}
return 0;
}
/**
* @param display The display.
*
* Release keyboard.
*/
static void release_keyboard ( Display *display )
{
XUngrabKeyboard ( display, CurrentTime );
}
// XGetWindowAttributes with caching
static XWindowAttributes* window_get_attributes ( Window w )
{
int idx = winlist_find ( cache_xattr, w );
if ( idx < 0 ) {
XWindowAttributes *cattr = g_malloc ( sizeof ( XWindowAttributes ) );
if ( XGetWindowAttributes ( display, w, cattr ) ) {
winlist_append ( cache_xattr, w, cattr );
return cattr;
}
g_free ( cattr );
return NULL;
}
return cache_xattr->data[idx];
}
// retrieve a property of any type from a window
static int window_get_prop ( Window w, Atom prop, Atom *type, int *items, void *buffer, unsigned int bytes ) __attribute__ ( ( nonnull ( 3, 4 ) ) );
static int window_get_prop ( Window w, Atom prop, Atom *type, int *items, void *buffer, unsigned int bytes )
{
int format;
unsigned long nitems, nbytes;
unsigned char *ret = NULL;
memset ( buffer, 0, bytes );
if ( XGetWindowProperty ( display, w, prop, 0, bytes / 4, False, AnyPropertyType, type,
&format, &nitems, &nbytes, &ret ) == Success && ret && *type != None && format ) {
if ( format == 8 ) {
memmove ( buffer, ret, MIN ( bytes, nitems ) );
}
if ( format == 16 ) {
memmove ( buffer, ret, MIN ( bytes, nitems * sizeof ( short ) ) );
}
if ( format == 32 ) {
memmove ( buffer, ret, MIN ( bytes, nitems * sizeof ( long ) ) );
}
*items = ( int ) nitems;
XFree ( ret );
return 1;
}
return 0;
}
// retrieve a text property from a window
// technically we could use window_get_prop(), but this is better for character set support
char* window_get_text_prop ( Window w, Atom atom )
{
XTextProperty prop;
char *res = NULL;
char **list = NULL;
int count;
if ( XGetTextProperty ( display, w, &prop, atom ) && prop.value && prop.nitems ) {
if ( prop.encoding == XA_STRING ) {
res = g_malloc ( strlen ( ( char * ) prop.value ) + 1 );
// make clang-check happy.
if ( res ) {
strcpy ( res, ( char * ) prop.value );
}
}
else if ( Xutf8TextPropertyToTextList ( display, &prop, &list, &count ) >= Success && count > 0 && *list ) {
res = g_malloc ( strlen ( *list ) + 1 );
// make clang-check happy.
if ( res ) {
strcpy ( res, *list );
}
XFreeStringList ( list );
}
}
if ( prop.value ) {
XFree ( prop.value );
}
return res;
}
static int window_get_atom_prop ( Window w, Atom atom, Atom *list, int count )
{
Atom type;
int items;
return window_get_prop ( w, atom, &type, &items, list, count * sizeof ( Atom ) ) && type == XA_ATOM ? items : 0;
}
static void window_set_atom_prop ( Window w, Atom prop, Atom *atoms, int count )
{
XChangeProperty ( display, w, prop, XA_ATOM, 32, PropModeReplace, ( unsigned char * ) atoms, count );
}
static int window_get_cardinal_prop ( Window w, Atom atom, unsigned long *list, int count )
{
Atom type; int items;
return window_get_prop ( w, atom, &type, &items, list, count * sizeof ( unsigned long ) ) && type == XA_CARDINAL ? items : 0;
}
// a ClientMessage
static int window_send_message ( Window target, Window subject, Atom atom, unsigned long protocol, unsigned long mask, Time time )
{
XEvent e;
memset ( &e, 0, sizeof ( XEvent ) );
e.xclient.type = ClientMessage;
e.xclient.message_type = atom;
e.xclient.window = subject;
e.xclient.data.l[0] = protocol;
e.xclient.data.l[1] = time;
e.xclient.send_event = True;
e.xclient.format = 32;
int r = XSendEvent ( display, target, False, mask, &e ) ? 1 : 0;
XFlush ( display );
return r;
}
// find the dimensions of the monitor displaying point x,y
static void monitor_dimensions ( Screen *screen, int x, int y, workarea *mon )
{
memset ( mon, 0, sizeof ( workarea ) );
mon->w = WidthOfScreen ( screen );
mon->h = HeightOfScreen ( screen );
// locate the current monitor
if ( XineramaIsActive ( display ) ) {
int monitors;
XineramaScreenInfo *info = XineramaQueryScreens ( display, &monitors );
if ( info ) {
for ( int i = 0; i < monitors; i++ ) {
if ( INTERSECT ( x, y, 1, 1, info[i].x_org, info[i].y_org, info[i].width, info[i].height ) ) {
mon->x = info[i].x_org;
mon->y = info[i].y_org;
mon->w = info[i].width;
mon->h = info[i].height;
break;
}
}
}
XFree ( info );
}
}
// determine which monitor holds the active window, or failing that the mouse pointer
static void monitor_active ( workarea *mon )
{
Screen *screen = DefaultScreenOfDisplay ( display );
Window root = RootWindow ( display, XScreenNumberOfScreen ( screen ) );
int x, y;
Window id;
Atom type;
int count;
if ( window_get_prop ( root, netatoms[_NET_ACTIVE_WINDOW], &type, &count, &id, sizeof ( Window ) )
&& type == XA_WINDOW && count > 0 ) {
XWindowAttributes *attr = window_get_attributes ( id );
if ( attr != NULL ) {
Window junkwin;
if ( XTranslateCoordinates ( display, id, attr->root,
-attr->border_width,
-attr->border_width,
&x, &y, &junkwin ) == True ) {
monitor_dimensions ( screen, x, y, mon );
return;
}
}
}
if ( pointer_get ( display, root, &x, &y ) ) {
monitor_dimensions ( screen, x, y, mon );
return;
}
monitor_dimensions ( screen, 0, 0, mon );
}
// _NET_WM_STATE_*
static int client_has_state ( client *c, Atom state )
{
int i;
for ( i = 0; i < c->states; i++ ) {
if ( c->state[i] == state ) {
return 1;
}
}
return 0;
}
// collect info on any window
// doesn't have to be a window we'll end up managing
static client* window_client ( Window win )
{
if ( win == None ) {
return NULL;
}
int idx = winlist_find ( cache_client, win );
if ( idx >= 0 ) {
return cache_client->data[idx];
}
// if this fails, we're up that creek
XWindowAttributes *attr = window_get_attributes ( win );
if ( !attr ) {
return NULL;
}
client *c = g_malloc0 ( sizeof ( client ) );
c->window = win;
// copy xattr so we don't have to care when stuff is freed
memmove ( &c->xattr, attr, sizeof ( XWindowAttributes ) );
XGetTransientForHint ( display, win, &c->trans );
c->states = window_get_atom_prop ( win, netatoms[_NET_WM_STATE], c->state, CLIENTSTATE );
char *name;
if ( ( name = window_get_text_prop ( c->window, netatoms[_NET_WM_NAME] ) ) && name ) {
snprintf ( c->title, CLIENTTITLE, "%s", name );
g_free ( name );
}
else if ( XFetchName ( display, c->window, &name ) ) {
snprintf ( c->title, CLIENTTITLE, "%s", name );
XFree ( name );
}
name = window_get_text_prop ( c->window, XInternAtom ( display, "WM_WINDOW_ROLE", False ) );
if ( name != NULL ) {
snprintf ( c->role, CLIENTROLE, "%s", name );
XFree ( name );
}
XClassHint chint;
if ( XGetClassHint ( display, c->window, &chint ) ) {
snprintf ( c->class, CLIENTCLASS, "%s", chint.res_class );
snprintf ( c->name, CLIENTNAME, "%s", chint.res_name );
XFree ( chint.res_class );
XFree ( chint.res_name );
}
monitor_dimensions ( c->xattr.screen, c->xattr.x, c->xattr.y, &c->monitor );
winlist_append ( cache_client, c->window, c );
return c;
}
static void menu_hide_arrow_text ( int filtered_lines, int selected, int max_elements,
textbox *arrowbox_top, textbox *arrowbox_bottom )
{
@ -744,7 +246,7 @@ static int window_match ( char **tokens, __attribute__( ( unused ) ) const char
{
int match = 1;
winlist *ids = ( winlist * ) data;
client *c = window_client ( ids->array[index] );
client *c = window_client ( display, ids->array[index] );
if ( tokens ) {
for ( int j = 0; match && tokens[j]; j++ ) {
@ -840,15 +342,6 @@ static int levenshtein ( const char *s, const char *t )
return retv;
}
static void window_set_opacity ( Display *display, Window box, unsigned int opacity )
{
// Hack to set window opacity.
unsigned int opacity_set = ( unsigned int ) ( ( opacity / 100.0 ) * UINT32_MAX );
XChangeProperty ( display, box, netatoms[_NET_WM_WINDOW_OPACITY],
XA_CARDINAL, 32, PropModeReplace,
( unsigned char * ) &opacity_set, 1L );
}
Window create_window ( Display *display )
{
XSetWindowAttributes attr;
@ -865,7 +358,7 @@ Window create_window ( Display *display )
XSetLineAttributes ( display, gc, 2, LineOnOffDash, CapButt, JoinMiter );
XSetForeground ( display, gc, color_get ( display, config.menu_bc ) );
// make it an unmanaged window
window_set_atom_prop ( box, netatoms[_NET_WM_STATE], &netatoms[_NET_WM_STATE_ABOVE], 1 );
window_set_atom_prop ( display, box, netatoms[_NET_WM_STATE], &netatoms[_NET_WM_STATE_ABOVE], 1 );
XSetWindowAttributes sattr;
sattr.override_redirect = True;
XChangeWindowAttributes ( display, box, CWOverrideRedirect, &sattr );
@ -873,7 +366,7 @@ Window create_window ( Display *display )
// Set the WM_NAME
XStoreName ( display, box, "rofi" );
window_set_opacity ( display, box, config.window_opacity );
x11_set_window_opacity ( display, box, config.window_opacity );
return box;
}
@ -1462,11 +955,9 @@ static void menu_paste ( MenuState *state, XSelectionEvent *xse )
unsigned long dl, rm;
Atom da;
// TODO: use window_get_prop?
/* we have been given the current selection, now insert it into input */
XGetWindowProperty (
display,
main_window,
netatoms[UTF8_STRING],
XGetWindowProperty ( display, main_window, netatoms[UTF8_STRING],
0,
256 / 4, // max length in words.
False, // Do not delete clipboard.
@ -1527,7 +1018,7 @@ MenuReturn menu ( char **lines, unsigned int num_lines, char **input, char *prom
main_window = create_window ( display );
}
// Get active monitor size.
monitor_active ( &mon );
monitor_active ( display, &mon );
// we need this at this point so we can get height.
@ -1894,7 +1385,7 @@ void error_dialog ( const char *msg )
};
workarea mon;
// Get active monitor size.
monitor_active ( &mon );
monitor_active ( display, &mon );
// main window isn't explicitly destroyed in case we switch modes. Reusing it prevents flicker
XWindowAttributes attr;
if ( main_window == None || XGetWindowAttributes ( display, main_window, &attr ) == 0 ) {
@ -1978,13 +1469,13 @@ SwitcherMode run_switcher_window ( char **input, G_GNUC_UNUSED void *data )
Window curr_win_id = 0;
// Get the active window so we can highlight this.
if ( !( window_get_prop ( root, netatoms[_NET_ACTIVE_WINDOW], &type,
if ( !( window_get_prop ( display, root, netatoms[_NET_ACTIVE_WINDOW], &type,
&count, &curr_win_id, sizeof ( Window ) )
&& type == XA_WINDOW && count > 0 ) ) {
curr_win_id = 0;
}
if ( window_get_prop ( root, netatoms[_NET_CLIENT_LIST_STACKING],
if ( window_get_prop ( display, root, netatoms[_NET_CLIENT_LIST_STACKING],
&type, &nwins, wins, 100 * sizeof ( Window ) )
&& type == XA_WINDOW ) {
char pattern[50];
@ -2001,7 +1492,7 @@ SwitcherMode run_switcher_window ( char **input, G_GNUC_UNUSED void *data )
for ( i = nwins - 1; i > -1; i-- ) {
client *c;
if ( ( c = window_client ( wins[i] ) )
if ( ( c = window_client ( display, wins[i] ) )
&& !c->xattr.override_redirect
&& !client_has_state ( c, netatoms[_NET_WM_STATE_SKIP_PAGER] )
&& !client_has_state ( c, netatoms[_NET_WM_STATE_SKIP_TASKBAR] ) ) {
@ -2020,7 +1511,7 @@ SwitcherMode run_switcher_window ( char **input, G_GNUC_UNUSED void *data )
}
// Create pattern for printing the line.
if ( !window_get_cardinal_prop ( root, netatoms[_NET_NUMBER_OF_DESKTOPS], &desktops, 1 ) ) {
if ( !window_get_cardinal_prop ( display, root, netatoms[_NET_NUMBER_OF_DESKTOPS], &desktops, 1 ) ) {
desktops = 1;
}
if ( config_i3_mode ) {
@ -2037,7 +1528,7 @@ SwitcherMode run_switcher_window ( char **input, G_GNUC_UNUSED void *data )
Window w = ids->array[i];
client *c;
if ( ( c = window_client ( w ) ) ) {
if ( ( c = window_client ( display, w ) ) ) {
// final line format
unsigned long wmdesktop;
char desktop[5];
@ -2046,7 +1537,7 @@ SwitcherMode run_switcher_window ( char **input, G_GNUC_UNUSED void *data )
if ( !config_i3_mode ) {
// find client's desktop. this is zero-based, so we adjust by since most
// normal people don't think like this :-)
if ( !window_get_cardinal_prop ( c->window, netatoms[_NET_WM_DESKTOP], &wmdesktop, 1 ) ) {
if ( !window_get_cardinal_prop ( display, c->window, netatoms[_NET_WM_DESKTOP], &wmdesktop, 1 ) ) {
wmdesktop = 0xFFFFFFFF;
}
@ -2085,11 +1576,11 @@ SwitcherMode run_switcher_window ( char **input, G_GNUC_UNUSED void *data )
else{
// Change to the desktop of the selected window/client.
// TODO: get rid of strtol
window_send_message ( root, root, netatoms[_NET_CURRENT_DESKTOP], strtol ( list[selected_line], NULL, 10 ) - 1,
window_send_message ( display, root, root, netatoms[_NET_CURRENT_DESKTOP], strtol ( list[selected_line], NULL, 10 ) - 1,
SubstructureNotifyMask | SubstructureRedirectMask, time );
XSync ( display, False );
window_send_message ( root, ids->array[selected_line], netatoms[_NET_ACTIVE_WINDOW], 2, // 2 = pager
window_send_message ( display, root, ids->array[selected_line], netatoms[_NET_ACTIVE_WINDOW], 2, // 2 = pager
SubstructureNotifyMask | SubstructureRedirectMask, time );
}
}
@ -2128,6 +1619,7 @@ static int run_dmenu ()
if ( map != None ) {
XFreeColormap ( display, map );
map = None;
}
return ret_state;
}
@ -2195,6 +1687,7 @@ static void run_switcher ( int do_fork, SwitcherMode mode )
textbox_cleanup ( );
if ( map != None ) {
XFreeColormap ( display, map );
map = None;
}
if ( do_fork == TRUE ) {
@ -2229,87 +1722,6 @@ static void handle_keypress ( XEvent *ev )
}
}
// convert a Mod+key arg to mod mask and keysym
static void parse_key ( char *combo, unsigned int *mod, KeySym *key )
{
unsigned int modmask = 0;
if ( strcasestr ( combo, "shift" ) ) {
modmask |= ShiftMask;
}
if ( strcasestr ( combo, "control" ) ) {
modmask |= ControlMask;
}
if ( strcasestr ( combo, "mod1" ) ) {
modmask |= Mod1Mask;
}
if ( strcasestr ( combo, "alt" ) ) {
modmask |= Mod1Mask;
}
if ( strcasestr ( combo, "mod2" ) ) {
modmask |= Mod2Mask;
}
if ( strcasestr ( combo, "mod3" ) ) {
modmask |= Mod3Mask;
}
if ( strcasestr ( combo, "mod4" ) ) {
modmask |= Mod4Mask;
}
if ( strcasestr ( combo, "mod5" ) ) {
modmask |= Mod5Mask;
}
// If no modifier mask is set, allow any modifier.
*mod = modmask ? modmask : AnyModifier;
// Skip modifier (if exist) and parse key.
char i = strlen ( combo );
while ( i > 0 && !strchr ( "-+", combo[i - 1] ) ) {
i--;
}
KeySym sym = XStringToKeysym ( combo + i );
if ( sym == NoSymbol || ( !modmask && ( strchr ( combo, '-' ) || strchr ( combo, '+' ) ) ) ) {
fprintf ( stderr, "sorry, cannot understand key combination: %s\n", combo );
exit ( EXIT_FAILURE );
}
*key = sym;
}
// bind a key combination on a root window, compensating for Lock* states
static void grab_key ( Display *display, unsigned int modmask, KeySym key )
{
Screen *screen = DefaultScreenOfDisplay ( display );
Window root = RootWindow ( display, XScreenNumberOfScreen ( screen ) );
KeyCode keycode = XKeysymToKeycode ( display, key );
XUngrabKey ( display, keycode, AnyModifier, root );
if ( modmask != AnyModifier ) {
// bind to combinations of mod and lock masks, so caps and numlock don't confuse people
XGrabKey ( display, keycode, modmask, root, True, GrabModeAsync, GrabModeAsync );
XGrabKey ( display, keycode, modmask | LockMask, root, True, GrabModeAsync, GrabModeAsync );
if ( NumlockMask ) {
XGrabKey ( display, keycode, modmask | NumlockMask, root, True, GrabModeAsync, GrabModeAsync );
XGrabKey ( display, keycode, modmask | NumlockMask | LockMask, root, True, GrabModeAsync, GrabModeAsync );
}
}
else{
// nice simple single key bind
XGrabKey ( display, keycode, AnyModifier, root, True, GrabModeAsync, GrabModeAsync );
}
}
/**
* Help function. This calls man.
@ -2338,8 +1750,7 @@ static void cleanup ()
XCloseDisplay ( display );
}
}
winlist_free ( cache_xattr );
winlist_free ( cache_client );
x11_cache_free ();
i3_support_free_internals ();
@ -2377,34 +1788,27 @@ static void setup_switchers ( void )
for ( char *token = strtok_r ( switcher_str, ",", &savept );
token != NULL;
token = strtok_r ( NULL, ",", &savept ) ) {
// Window switcher.
if ( strcasecmp ( token, "window" ) == 0 ) {
// Resize and add entry.
switchers = (Switcher *) g_realloc ( switchers, sizeof ( Switcher ) * ( num_switchers + 1 ) );
g_strlcpy ( switchers[num_switchers].name, "window", 32 );
switchers[num_switchers].cb = run_switcher_window;
switchers[num_switchers].cb_data = NULL;
switchers[num_switchers].cb_data_free = NULL;
// Window switcher.
if ( strcasecmp ( token, "window" ) == 0 ) {
g_strlcpy ( switchers[num_switchers].name, "window", 32 );
switchers[num_switchers].cb = run_switcher_window;
num_switchers++;
}
// SSh dialog
else if ( strcasecmp ( token, "ssh" ) == 0 ) {
// Resize and add entry.
switchers = (Switcher *) g_realloc ( switchers, sizeof ( Switcher ) * ( num_switchers + 1 ) );
g_strlcpy ( switchers[num_switchers].name, "ssh", 32 );
switchers[num_switchers].cb = ssh_switcher_dialog;
switchers[num_switchers].cb_data = NULL;
switchers[num_switchers].cb_data_free = NULL;
num_switchers++;
}
// Run dialog
else if ( strcasecmp ( token, "run" ) == 0 ) {
// Resize and add entry.
switchers = (Switcher *) g_realloc ( switchers, sizeof ( Switcher ) * ( num_switchers + 1 ) );
g_strlcpy ( switchers[num_switchers].name, "run", 32 );
switchers[num_switchers].cb = run_switcher_dialog;
switchers[num_switchers].cb_data = NULL;
switchers[num_switchers].cb_data_free = NULL;
num_switchers++;
}
else {
@ -2412,7 +1816,6 @@ static void setup_switchers ( void )
ScriptOptions *sw = script_switcher_parse_setup ( token );
if ( sw != NULL ) {
// Resize and add entry.
switchers = (Switcher *) g_realloc ( switchers, sizeof ( Switcher ) * ( num_switchers + 1 ) );
g_strlcpy ( switchers[num_switchers].name, sw->name, 32 );
switchers[num_switchers].cb = script_switcher_dialog;
switchers[num_switchers].cb_data = sw;
@ -2487,6 +1890,7 @@ static void show_error_message ( const char *msg )
textbox_cleanup ( );
if ( map != None ) {
XFreeColormap ( display, map );
map = None;
}
}
@ -2496,19 +1900,16 @@ int main ( int argc, char *argv[] )
stored_argv = argv;
// catch help request
if ( find_arg ( argc, argv, "-h" ) >= 0 ||
find_arg ( argc, argv, "-help" ) >= 0 ) {
if ( find_arg ( argc, argv, "-h" ) >= 0 || find_arg ( argc, argv, "-help" ) >= 0 ) {
help ();
exit ( EXIT_SUCCESS );
}
// Version
if ( find_arg ( argc, argv, "-v" ) >= 0 ||
find_arg ( argc, argv, "-version" ) >= 0 ) {
if ( find_arg ( argc, argv, "-v" ) >= 0 || find_arg ( argc, argv, "-version" ) >= 0 ) {
fprintf ( stdout, "Version: "VERSION "\n" );
exit ( EXIT_SUCCESS );
}
// Get the path to the cache dir.
cache_dir = g_get_user_cache_dir ();
@ -2523,7 +1924,7 @@ int main ( int argc, char *argv[] )
// Register cleanup function.
atexit ( cleanup );
// Get DISPLAY
// Get DISPLAY, first env, then argument.
display_str = getenv ( "DISPLAY" );
find_arg_str ( argc, argv, "-display", &display_str );
@ -2541,37 +1942,13 @@ int main ( int argc, char *argv[] )
exit ( EXIT_SUCCESS );
}
// setup_switchers
setup_switchers ();
// Set up X interaction.
signal ( SIGCHLD, catch_exit );
// Set error handle
XSync ( display, False );
xerror = XSetErrorHandler ( display_oops );
XSync ( display, False );
// determine numlock mask so we can bind on keys with and without it
XModifierKeymap *modmap = XGetModifierMapping ( display );
KeyCode kc = XKeysymToKeycode ( display, XK_Num_Lock );
for ( int i = 0; i < 8; i++ ) {
for ( int j = 0; j < ( int ) modmap->max_keypermod; j++ ) {
if ( modmap->modifiermap[i * modmap->max_keypermod + j] == kc ) {
NumlockMask = ( 1 << i );
}
}
}
XFreeModifiermap ( modmap );
cache_client = winlist_new ();
cache_xattr = winlist_new ();
// X atom values
for ( int i = 0; i < NUM_NETATOMS; i++ ) {
netatoms[i] = XInternAtom ( display, netatom_names[i], False );
}
x11_setup ( display );
// Check for i3
config_i3_mode = i3_support_initialize ( display );
@ -2656,17 +2033,17 @@ int main ( int argc, char *argv[] )
else{
// Daemon mode, Listen to key presses..
if ( switcher_get ( "window" ) >= 0 ) {
parse_key ( config.window_key, &windows_modmask, &windows_keysym );
x11_parse_key ( config.window_key, &windows_modmask, &windows_keysym );
grab_key ( display, windows_modmask, windows_keysym );
}
if ( switcher_get ( "run" ) >= 0 ) {
parse_key ( config.run_key, &rundialog_modmask, &rundialog_keysym );
x11_parse_key ( config.run_key, &rundialog_modmask, &rundialog_keysym );
grab_key ( display, rundialog_modmask, rundialog_keysym );
}
if ( switcher_get ( "ssh" ) >= 0 ) {
parse_key ( config.ssh_key, &sshdialog_modmask, &sshdialog_keysym );
x11_parse_key ( config.ssh_key, &sshdialog_modmask, &sshdialog_keysym );
grab_key ( display, sshdialog_modmask, sshdialog_keysym );
}
@ -2683,8 +2060,7 @@ int main ( int argc, char *argv[] )
for (;; ) {
XEvent ev;
// caches only live for a single event
winlist_empty ( cache_xattr );
winlist_empty ( cache_client );
x11_cache_empty ();
// block and wait for something
XNextEvent ( display, &ev );

544
source/x11-helper.c Normal file
View file

@ -0,0 +1,544 @@
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <glib.h>
#include <X11/X.h>
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xmd.h>
#include <X11/Xutil.h>
#include <X11/Xproto.h>
#include <X11/keysym.h>
#include <X11/XKBlib.h>
#include <X11/extensions/Xinerama.h>
#define OVERLAP( a, b, c, d ) ( ( ( a ) == ( c ) && ( b ) == ( d ) ) || MIN ( ( a ) + ( b ), ( c ) + ( d ) ) - MAX ( ( a ), ( c ) ) > 0 )
#define INTERSECT( x, y, w, h, x1, y1, w1, h1 ) ( OVERLAP ( ( x ), ( w ), ( x1 ), ( w1 ) ) && OVERLAP ( ( y ), ( h ), ( y1 ), ( h1 ) ) )
#include "x11-helper.h"
#define WINLIST 32
// Mask indicating num-lock.
unsigned int NumlockMask = 0;
winlist *cache_client = NULL;
winlist *cache_xattr = NULL;
winlist* winlist_new ()
{
winlist *l = g_malloc ( sizeof ( winlist ) );
l->len = 0;
l->array = g_malloc_n ( WINLIST + 1, sizeof ( Window ) );
l->data = g_malloc_n ( WINLIST + 1, sizeof ( void* ) );
return l;
}
int winlist_append ( winlist *l, Window w, void *d )
{
if ( l->len > 0 && !( l->len % WINLIST ) ) {
l->array = g_realloc ( l->array, sizeof ( Window ) * ( l->len + WINLIST + 1 ) );
l->data = g_realloc ( l->data, sizeof ( void* ) * ( l->len + WINLIST + 1 ) );
}
// Make clang-check happy.
// TODO: make clang-check clear this should never be 0.
if ( l->data == NULL || l->array == NULL ) {
return 0;
}
l->data[l->len] = d;
l->array[l->len++] = w;
return l->len - 1;
}
void winlist_empty ( winlist *l )
{
while ( l->len > 0 ) {
g_free ( l->data[--( l->len )] );
}
}
void winlist_free ( winlist *l )
{
if ( l != NULL ) {
winlist_empty ( l );
g_free ( l->array );
g_free ( l->data );
g_free ( l );
}
}
int winlist_find ( winlist *l, Window w )
{
// iterate backwards. theory is: windows most often accessed will be
// nearer the end. testing with kcachegrind seems to support this...
int i;
for ( i = ( l->len - 1 ); i >= 0; i-- ) {
if ( l->array[i] == w ) {
return i;
}
}
return -1;
}
XWindowAttributes* window_get_attributes ( Display *display, Window w )
{
int idx = winlist_find ( cache_xattr, w );
if ( idx < 0 ) {
XWindowAttributes *cattr = g_malloc ( sizeof ( XWindowAttributes ) );
if ( XGetWindowAttributes ( display, w, cattr ) ) {
winlist_append ( cache_xattr, w, cattr );
return cattr;
}
g_free ( cattr );
return NULL;
}
return cache_xattr->data[idx];
}
// retrieve a property of any type from a window
int window_get_prop ( Display *display, Window w, Atom prop,
Atom *type, int *items,
void *buffer, unsigned int bytes )
{
int format;
unsigned long nitems, nbytes;
unsigned char *ret = NULL;
memset ( buffer, 0, bytes );
if ( XGetWindowProperty ( display, w, prop, 0, bytes / 4, False, AnyPropertyType, type,
&format, &nitems, &nbytes, &ret ) == Success && ret && *type != None && format ) {
if ( format == 8 ) {
memmove ( buffer, ret, MIN ( bytes, nitems ) );
}
if ( format == 16 ) {
memmove ( buffer, ret, MIN ( bytes, nitems * sizeof ( short ) ) );
}
if ( format == 32 ) {
memmove ( buffer, ret, MIN ( bytes, nitems * sizeof ( long ) ) );
}
*items = ( int ) nitems;
XFree ( ret );
return 1;
}
return 0;
}
// retrieve a text property from a window
// technically we could use window_get_prop(), but this is better for character set support
char* window_get_text_prop ( Display *display, Window w, Atom atom )
{
XTextProperty prop;
char *res = NULL;
char **list = NULL;
int count;
if ( XGetTextProperty ( display, w, &prop, atom ) && prop.value && prop.nitems ) {
if ( prop.encoding == XA_STRING ) {
res = g_malloc ( strlen ( ( char * ) prop.value ) + 1 );
// make clang-check happy.
if ( res ) {
strcpy ( res, ( char * ) prop.value );
}
}
else if ( Xutf8TextPropertyToTextList ( display, &prop, &list, &count ) >= Success && count > 0 && *list ) {
res = g_malloc ( strlen ( *list ) + 1 );
// make clang-check happy.
if ( res ) {
strcpy ( res, *list );
}
XFreeStringList ( list );
}
}
if ( prop.value ) {
XFree ( prop.value );
}
return res;
}
int window_get_atom_prop ( Display *display, Window w, Atom atom, Atom *list, int count )
{
Atom type;
int items;
return window_get_prop ( display, w, atom, &type, &items, list, count * sizeof ( Atom ) ) && type == XA_ATOM ? items : 0;
}
void window_set_atom_prop ( Display *display, Window w, Atom prop, Atom *atoms, int count )
{
XChangeProperty ( display, w, prop, XA_ATOM, 32, PropModeReplace, ( unsigned char * ) atoms, count );
}
int window_get_cardinal_prop ( Display *display, Window w, Atom atom, unsigned long *list, int count )
{
Atom type; int items;
return window_get_prop ( display, w, atom, &type, &items, list, count * sizeof ( unsigned long ) ) && type == XA_CARDINAL ? items : 0;
}
void x11_cache_create ( void )
{
cache_client = winlist_new ();
cache_xattr = winlist_new ();
}
void x11_cache_empty ( void )
{
winlist_empty ( cache_xattr );
winlist_empty ( cache_client );
}
void x11_cache_free ( void )
{
winlist_free ( cache_xattr );
winlist_free ( cache_client );
}
// find the dimensions of the monitor displaying point x,y
static void monitor_dimensions ( Display *display, Screen *screen, int x, int y, workarea *mon )
{
memset ( mon, 0, sizeof ( workarea ) );
mon->w = WidthOfScreen ( screen );
mon->h = HeightOfScreen ( screen );
// locate the current monitor
if ( XineramaIsActive ( display ) ) {
int monitors;
XineramaScreenInfo *info = XineramaQueryScreens ( display, &monitors );
if ( info ) {
for ( int i = 0; i < monitors; i++ ) {
if ( INTERSECT ( x, y, 1, 1, info[i].x_org, info[i].y_org, info[i].width, info[i].height ) ) {
mon->x = info[i].x_org;
mon->y = info[i].y_org;
mon->w = info[i].width;
mon->h = info[i].height;
break;
}
}
}
XFree ( info );
}
}
// _NET_WM_STATE_*
int client_has_state ( client *c, Atom state )
{
for ( int i = 0; i < c->states; i++ ) {
if ( c->state[i] == state ) {
return 1;
}
}
return 0;
}
client* window_client ( Display *display, Window win )
{
if ( win == None ) {
return NULL;
}
int idx = winlist_find ( cache_client, win );
if ( idx >= 0 ) {
return cache_client->data[idx];
}
// if this fails, we're up that creek
XWindowAttributes *attr = window_get_attributes ( display, win );
if ( !attr ) {
return NULL;
}
client *c = g_malloc0 ( sizeof ( client ) );
c->window = win;
// copy xattr so we don't have to care when stuff is freed
memmove ( &c->xattr, attr, sizeof ( XWindowAttributes ) );
XGetTransientForHint ( display, win, &c->trans );
c->states = window_get_atom_prop ( display, win, netatoms[_NET_WM_STATE], c->state, CLIENTSTATE );
char *name;
if ( ( name = window_get_text_prop ( display, c->window, netatoms[_NET_WM_NAME] ) ) && name ) {
snprintf ( c->title, CLIENTTITLE, "%s", name );
g_free ( name );
}
else if ( XFetchName ( display, c->window, &name ) ) {
snprintf ( c->title, CLIENTTITLE, "%s", name );
XFree ( name );
}
name = window_get_text_prop ( display, c->window, XInternAtom ( display, "WM_WINDOW_ROLE", False ) );
if ( name != NULL ) {
snprintf ( c->role, CLIENTROLE, "%s", name );
XFree ( name );
}
XClassHint chint;
if ( XGetClassHint ( display, c->window, &chint ) ) {
snprintf ( c->class, CLIENTCLASS, "%s", chint.res_class );
snprintf ( c->name, CLIENTNAME, "%s", chint.res_name );
XFree ( chint.res_class );
XFree ( chint.res_name );
}
monitor_dimensions ( display, c->xattr.screen, c->xattr.x, c->xattr.y, &c->monitor );
winlist_append ( cache_client, c->window, c );
return c;
}
/**
* @param x The x position of the mouse [out]
* @param y The y position of the mouse [out]
*
* find mouse pointer location
*
* @returns 1 when found
*/
static int pointer_get ( Display *display, Window root, int *x, int *y )
{
*x = 0;
*y = 0;
Window rr, cr;
int rxr, ryr, wxr, wyr;
unsigned int mr;
if ( XQueryPointer ( display, root, &rr, &cr, &rxr, &ryr, &wxr, &wyr, &mr ) ) {
*x = rxr;
*y = ryr;
return 1;
}
return 0;
}
// determine which monitor holds the active window, or failing that the mouse pointer
void monitor_active ( Display *display, workarea *mon )
{
Screen *screen = DefaultScreenOfDisplay ( display );
Window root = RootWindow ( display, XScreenNumberOfScreen ( screen ) );
int x, y;
Window id;
Atom type;
int count;
if ( window_get_prop ( display, root, netatoms[_NET_ACTIVE_WINDOW], &type, &count, &id, sizeof ( Window ) )
&& type == XA_WINDOW && count > 0 ) {
XWindowAttributes *attr = window_get_attributes ( display, id );
if ( attr != NULL ) {
Window junkwin;
if ( XTranslateCoordinates ( display, id, attr->root,
-attr->border_width,
-attr->border_width,
&x, &y, &junkwin ) == True ) {
monitor_dimensions ( display, screen, x, y, mon );
return;
}
}
}
if ( pointer_get ( display, root, &x, &y ) ) {
monitor_dimensions ( display, screen, x, y, mon );
return;
}
monitor_dimensions ( display, screen, 0, 0, mon );
}
int window_send_message ( Display *display, Window target,
Window subject, Atom atom,
unsigned long protocol, unsigned long mask, Time time )
{
XEvent e;
memset ( &e, 0, sizeof ( XEvent ) );
e.xclient.type = ClientMessage;
e.xclient.message_type = atom;
e.xclient.window = subject;
e.xclient.data.l[0] = protocol;
e.xclient.data.l[1] = time;
e.xclient.send_event = True;
e.xclient.format = 32;
int r = XSendEvent ( display, target, False, mask, &e ) ? 1 : 0;
XFlush ( display );
return r;
}
int take_keyboard ( Display *display, Window w )
{
if ( XGrabKeyboard ( display, w, True, GrabModeAsync, GrabModeAsync, CurrentTime ) == GrabSuccess ) {
return 1;
}
return 0;
}
void release_keyboard ( Display *display )
{
XUngrabKeyboard ( display, CurrentTime );
}
// bind a key combination on a root window, compensating for Lock* states
void grab_key ( Display *display, unsigned int modmask, KeySym key )
{
Screen *screen = DefaultScreenOfDisplay ( display );
Window root = RootWindow ( display, XScreenNumberOfScreen ( screen ) );
KeyCode keycode = XKeysymToKeycode ( display, key );
XUngrabKey ( display, keycode, AnyModifier, root );
if ( modmask != AnyModifier ) {
// bind to combinations of mod and lock masks, so caps and numlock don't confuse people
XGrabKey ( display, keycode, modmask, root, True, GrabModeAsync, GrabModeAsync );
XGrabKey ( display, keycode, modmask | LockMask, root, True, GrabModeAsync, GrabModeAsync );
if ( NumlockMask ) {
XGrabKey ( display, keycode, modmask | NumlockMask, root, True, GrabModeAsync, GrabModeAsync );
XGrabKey ( display, keycode, modmask | NumlockMask | LockMask, root, True, GrabModeAsync, GrabModeAsync );
}
}
else{
// nice simple single key bind
XGrabKey ( display, keycode, AnyModifier, root, True, GrabModeAsync, GrabModeAsync );
}
}
static void x11_figure_out_numlock_mask ( Display *display )
{
XModifierKeymap *modmap = XGetModifierMapping ( display );
KeyCode kc = XKeysymToKeycode ( display, XK_Num_Lock );
for ( int i = 0; i < 8; i++ ) {
for ( int j = 0; j < ( int ) modmap->max_keypermod; j++ ) {
if ( modmap->modifiermap[i * modmap->max_keypermod + j] == kc ) {
NumlockMask = ( 1 << i );
}
}
}
XFreeModifiermap ( modmap );
}
// convert a Mod+key arg to mod mask and keysym
void x11_parse_key ( char *combo, unsigned int *mod, KeySym *key )
{
unsigned int modmask = 0;
if ( strcasestr ( combo, "shift" ) ) {
modmask |= ShiftMask;
}
if ( strcasestr ( combo, "control" ) ) {
modmask |= ControlMask;
}
if ( strcasestr ( combo, "mod1" ) ) {
modmask |= Mod1Mask;
}
if ( strcasestr ( combo, "alt" ) ) {
modmask |= Mod1Mask;
}
if ( strcasestr ( combo, "mod2" ) ) {
modmask |= Mod2Mask;
}
if ( strcasestr ( combo, "mod3" ) ) {
modmask |= Mod3Mask;
}
if ( strcasestr ( combo, "mod4" ) ) {
modmask |= Mod4Mask;
}
if ( strcasestr ( combo, "mod5" ) ) {
modmask |= Mod5Mask;
}
// If no modifier mask is set, allow any modifier.
*mod = modmask ? modmask : AnyModifier;
// Skip modifier (if exist) and parse key.
char i = strlen ( combo );
while ( i > 0 && !strchr ( "-+", combo[i - 1] ) ) {
i--;
}
KeySym sym = XStringToKeysym ( combo + i );
if ( sym == NoSymbol || ( !modmask && ( strchr ( combo, '-' ) || strchr ( combo, '+' ) ) ) ) {
fprintf ( stderr, "sorry, cannot understand key combination: %s\n", combo );
exit ( EXIT_FAILURE );
}
*key = sym;
}
void x11_set_window_opacity ( Display *display, Window box, unsigned int opacity )
{
// Hack to set window opacity.
unsigned int opacity_set = ( unsigned int ) ( ( opacity / 100.0 ) * UINT32_MAX );
XChangeProperty ( display, box, netatoms[_NET_WM_WINDOW_OPACITY],
XA_CARDINAL, 32, PropModeReplace,
( unsigned char * ) &opacity_set, 1L );
}
static void x11_create_frequently_used_atoms ( Display *display )
{
// X atom values
for ( int i = 0; i < NUM_NETATOMS; i++ ) {
netatoms[i] = XInternAtom ( display, netatom_names[i], False );
}
}
static int ( *xerror )( Display *, XErrorEvent * );
/**
* @param d The display on witch the error occurred.
* @param ee The XErrorEvent
*
* X11 Error handler.
*/
static int display_oops ( Display *d, XErrorEvent *ee )
{
if ( ee->error_code == BadWindow
|| ( ee->request_code == X_GrabButton && ee->error_code == BadAccess )
|| ( ee->request_code == X_GrabKey && ee->error_code == BadAccess )
) {
return 0;
}
fprintf ( stderr, "error: request code=%d, error code=%d\n", ee->request_code, ee->error_code );
return xerror ( d, ee );
}
void x11_setup ( Display *display )
{
// Set error handle
XSync ( display, False );
xerror = XSetErrorHandler ( display_oops );
XSync ( display, False );
// determine numlock mask so we can bind on keys with and without it
x11_figure_out_numlock_mask ( display );
x11_cache_create ();
x11_create_frequently_used_atoms ( display );
}