X11::Xlib - Low-level access to the X11 library
# C-style use X11::Xlib ':all'; my $display = XOpenDisplay($conn_string); XTestFakeMotionEvent($display, undef, 50, 50); XFlush($display); # or, Object-Oriented perl style: use X11::Xlib; my $display= X11::Xlib->new($conn_string); # shortcut for X11::Xlib::Display->new my $window= $display->new_window({ x => 0, y => 0, width => 50, height => 50); $window->show();
This module provides low-level access to Xlib functions.
This includes access to some X11 extensions like the X11 test library (Xtst).
If you import the Xlib functions directly, or call them as methods on an instance of X11::Xlib, you get a near-C experience where you are required to manage the lifespan of resources, XIDs are integers instead of objects, and the library doesn't make any attempt to keep you from passing bad data to Xlib.
If you instead create a X11::Xlib::Display object and call all your methods on that, you get a more friendly wrapper around Xlib that helps you manage resource lifespan, wraps XIDs with perl objects, and does some sanity checking on the state of the library when you call methods.
The X11::Xlib connection is a hashref with a few attributes and methods independent of Xlib.
Boolean flag that determines whether the destructor will call XCloseDisplay. Defaults to true for connections returned by "XOpenDisplay".
This is an alias for X11::Xlib::Display->new, to help encourage using the object oriented interface.
X11::Xlib::Display->new
X11::Xlib::install_error_handlers( $bool_nonfatal, $bool_fatal );
Error handling in Xlib is pretty bad. The first problem is that non-fatal errors are reported asynchronously in an API masquerading as if they were synchronous function calls. This is mildly annoying. This library eases the pain by giving you a nice XEvent object to work with, and the ability to deliver the errors to a callback on your display or window object.
The second much larger problem is that fatal errors (like losing the connection to the server) cause a mandatory termination of the host program. Seriously. The default behavior of Xlib is to print a message and abort, but even if you install the C error handler to try to gracefully recover, when the error handler returns Xlib still kills your program. Under normal circumstances you would have to perform all cleanup with your stack tied up through Xlib, but this library cheats by using croak (longjmp) to escape the callback and let you wrap up your script in a normal manner. However, after a fatal error Xlib's internal state could be damaged, so it is unsafe to make any more Xlib calls. The library tries to help assert this by invalidating all the connection objects.
longjmp
If you really need your program to keep running your best bet is to state-dump to shared memory and then exec() a fresh copy of your script and reload the dumped state. Or use XCB instead of Xlib.
exec()
Most functions can be called as methods on the Xlib connection object, since this is usually the first argument. Every Xlib function listed below can be exported, and you can grab them all with
use X11::Xlib ':functions';
my $display= X11::Xlib::XOpenDisplay($connection_string);
Instantiate a new (C-level) "Display" instance. This object contains the connection to the X11 display. This will be an instance of X11::Xlib. The X11::Xlib::Display object constructor is recommended instead.
X11::Xlib
The $connection_string variable specifies the display string to open. ("host:display.screen", or often ":0" to connect to the only screen of the only display on localhost) If unset, Xlib uses the $DISPLAY environement variable.
$connection_string
"host:display.screen"
":0"
localhost
$DISPLAY
If the handle goes out of scope, its destructor calls XCloseDisplay, unless you already called XCloseDisplay or the X connection was lost. (Be sure to read the notes under "install_error_handlers"
XCloseDisplay
XCloseDisplay($display); # or, just: undef $display
Close a handle returned by XOpenDisplay. You do not need to call this method since the handle's destructor does it for you, unless you want to forcibly stop communicating with X and can't track down your references. Once closed, all further Xlib calls on the handle will die with an exception.
XOpenDisplay
my $fh= IO::Handle->new_from_fd( $display->ConnectionNumber, 'w+' );
Return the file descriptor (integer) of the socket connected to the server. This is useful for select/poll designs. (See also: "wait_event" in X11::Xlib::Display)
XSetCloseDownMode($display, $close_mode)
Determines what resources are freed upon disconnect. See X11 documentation.
Most of these functions return an "XEvent" by way of an "out" parameter that gets overwritten during the call, in the style of C. The variable receiving the event does not need to be initialized.
XNextEvent($display, my $event_return) ... # event scalar is populated with event
You probably don't want this. It blocks forever until an event arrives, even ignoring signals. I added it for completeness. See "wait_event" in X11::Xlib::Display for a more perl-ish interface.
if ( XCheckMaskEvent($display, $event_mask, my $event_return) ) ... if ( XCheckTypedEvent($display, $event_type, my $event_return) ) ... if ( XCheckWindowEvent($display, $event_mask, $window, my $event_return) ) ... if ( XCheckTypedWindowEvent($display, $event_type, $window, my $event_return) ) ...
Each of these variations checks whether there is a matching event received from the server and not yet extracted form the message queue. If so, it stores the event into $event_return and returns true. Else it returns false without blocking.
$event_return
(Xlib also has another variant that uses a callback to choose which message to extract, but I didn't implement that because it seemed like a pain and probably nobody would use it.)
XSendEvent($display, $window, $propagate, $event_mask, $xevent) or die "Xlib hates us";
Send an XEvent to the server, to be redispatched however appropriate.
XPutBackEvent($display, $xevent)
Push an XEvent back onto your own incoming queue. This can presumably put arbitrarily bogus events onto your own queue since it returns void.
XFlush($display)
Push any queued messages to the X11 server. Some Xlib calls perform an implied flush of the queue, while others don't. If you're wondering why nothing happened when you called an XTest function, this is why.
XSync($display); XSync($display, $discard);
Force a round trip to the server to process all pending messages and receive the responses (or errors). A true value for the second argument will wipe your incoming event queue.
XSelectInput($display, $window, $event_mask)
Change the event mask for a window.
Xlib provides opaque "Display" and "Screen" structs which have locally- stored attributes, but which you must use method calls to access. For each attribute of a screen, there are four separate ways to access it:
DisplayFoo($display, $screen_num); # C Macro like ->{screens}[$screen_num]{foo} XDisplayFoo($display, $screen_num); # External linked function from Xlib FooOfScreen($screen_pointer); # C Macro like ->{foo} XFooOfScreen($screen_pointer); # External linked function from Xlib
Since screen pointers become invalid when the Display is closed, I decided not to expose them, and since DisplayFoo and XDisplayFoo are identical I decided to only implement the first since it makes one less symbol to link from Xlib.
So, if you grab some sample code from somewhere and wonder where those functions went, drop the leading X and do a quick search on this page.
my $n= ScreenCount($display);
Return number of configured "Screen"s of this display.
my $w= DisplayWidth($display, $screen); my $h= DisplayHeight($display, $screen); # use instead of WidthOfScreen, HeightOfScreen
Return the width or height of screen number $screen. You can omit the $screen paramter to use the default screen of your Display connection.
$screen
my $w= DisplayWidthMM($display, $screen); my $h= DisplayHeightMM($display, $screen); # use instead of WidthMMOfScreen, HeightMMOfScreen
Return the physical width or height (in millimeters) of screen number $screen. You can omit the screen number to use the default screen of the display.
my $xid= RootWindow($display, $screen)
Return the XID of the X11 root window. $screen is optional, and defaults to the default screen of your connection. If you want a Window object, call this method on X11::Xlib::Display.
my $visual= DefaultVisual($display, $screen); # use instead of DefaultVisualOfScreen
Screen is optional and defaults to the default screen of your connection. This returns a "Visual", not a "XVisualInfo".
my $bits_per_pixel= DefaultDepth($display, $screen); # use instead of DefaultDepthOfScreen, DisplayPlanes, PlanesOfScreen
Return bits-per-pixel of the root window of a screen. If you omit $screen it uses the default screen.
XMatchVisualInfo($display, $screen, $depth, $class, my $xvisualinfo_return) or die "Don't have one of those";
Loads the details of a "Visual" into the final argument, which must be an "XVisualInfo" (or undefined, to create one)
Returns true if it found a matching visual.
my @info_structs= XGetVisualInfo($display, $mask, $xvis_template);
Returns a list of "XVisualInfo" each describing an available "Visual" which matches the template you provided. (which is also an XVisualInfo)
XVisualInfo
$mask can be any combination of:
$mask
VisualIDMask VisualScreenMask VisualDepthMask VisualClassMask VisualRedMaskMask VisualGreenMaskMask VisualBlueMaskMask VisualColormapSizeMask VisualBitsPerRGBMask VisualAllMask
each describing a field of X11::Xlib::XVisualInfo which is relevant to your search.
my $vis_id= XVisualIDFromVisual($visual); # or, assuming $visual is blessed, my $vis_id= $visual->id;
Pull the visual ID out of the opaque object $visual.
If what you wanted was actually the "XVisualInfo" for a $visual, then try:
$visual
my ($vis_info)= GetVisualInfo($display, VisualIDMask, { visualid => $vis_id }); # or with Display object: $display->visual_by_id($vis_id);
my $xid= XCreateColormap($display, $rootwindow, $visual, $alloc_flag); # or 99% of the time my $xid= XCreateColormap($display, RootWindow($display), DefaultVisual($display), AllocNone); # and thus these are the defaults my $xid= XCreateColormap($display);
Create a "Colormap". The $visual is a "Visual" object, and the $alloc_flag is either AllocNone or AllocAll.
$alloc_flag
AllocNone
AllocAll
XFreeColormap($display, $colormap);
Delete a "Colormap", and set the colormap to None for any window that was using it.
None
XInstallColormap XUninstallColormap, XListInstalledColormaps XGetWMColormapWindows XSetWMColormapWindows, XSetWindowColormap XAllocColor XStoreColors XFreeColors XAllocColorPlanes XAllocNamedColor XQueryColors XCopyColormapAndFree
If anyone actually needs palette graphics anymore, send me a patch :-)
my $xid= XCreatePixmap($display, $drawable, $width, $height, $depth);
The $drawable parameter is just used to determine the screen. You probably want to pass either DefaultRootWindow($display) or the window you're creating the pixmap for.
$drawable
DefaultRootWindow($display)
XFreePixmap($display, $pixmap);
my $pixmap_xid= XCreateBitmapFromData($display, $drawable, $data, $width, $height);
First, be aware that in X11, a "bitmap" is literally a "Bit" "Map" (1 bit per pixel).
The $drawable determines which screen the pixmap is created for. The $data is a string of bytes.
$data
The $data should technically be opaque, written by another X11 function after having rendering graphics to a pixmap or something, but since those aren't implemented here yet, you'll just have to know the format.
my $pixmap_xid= XCreatePixmapFromBitmapData($display, $drawable, $data, $width, $height, $fg, $bg, $depth);
This function uses a bitmap (1 bit per pixel) and a foreground and background color to build a pixmap of those two colors. It's basically upscaling color from monochrome to $depth.
$depth
my $wnd_xid= XCreateWindow( $display, $parent_window, # such as DefaultRootWindow() $x, $y, $width, $height, $border_width, $color_depth, # such as $visual_info->depth or DefaultDepth($display) $class, # InputOutput, InputOnly, or CopyFromParent $visual, # such as $visual_info->visual or DefaultVisual($display) $attr_mask, # indicates which fields of \%attrs are initialized \%attrs # struct XSetWindowAttributes or hashref of its fields );
The parameters the probably need more explanation are $visual and %attrs.
%attrs
$visual is a "Visual". You probably either want to use the default visual of the screen ("DefaultVisual") or look up your own visual using "XGetVisualInfo" or "XMatchVisualInfo" (which is a "VisualInfo", and has an attribute ->visual). In the second case, you should also pass $visual_info->depth as the $depth parameter, and create a matching "Colormap" which you pass via the \%attrs parameter.
->visual
$visual_info->depth
\%attrs
Since this function didn't have nearly enough parameters for the imaginations of the Xlib creators, they added the full "XSetWindowAttributes" structure as a final argument. But to save you the trouble of setting all those fields, they added an $attr_mask to indicate which fields you are using.
$attr_mask
The window is initially un-mapped (i.e. hidden). See "XMapWindow"
my $wnd_xid= XCreateSimpleWindow( $display, $parent_window, $x, $y, $width, $height, $border_width, $border_color, $background_color );
This function basically creates a "child window", clipped to its parent, with all the same visual configuration.
It is initially unmapped. See "XMapWindow".
XMapWindow($display, $window);
Ask the X server to show a window. This call is asynchronous and you should call "XFlush" if you want it to appear immediately. The window will only appear if the parent window is also mapped. The server sends back a MapNotify event if the Window event mask allows it, and if a variety of other conditions are met. It's really pretty complicated and you should read the offical docs.
my ($root, $x, $y, $width, $height, $border_width, $color_depth); XGetGeometry($display, $drawable, $root, $x, $y, $width, $height, $border_width, $color_depth) or die "XGetGeometry failed"; # All vars declared above should now be defined
This function loads the geometry of the window into the variables you supply. You may omit the ones you don't care about.
my ($hints_out, $supplied_fields_out); XGetWMNormalHints($display, $window, $hints_out, $supplied_fields_out) or warn "Doesn't have WM hints";
If a window has Window Manager Normal Hints defined on it, this function will store them into the $hints_out variable (which will become a X11::Xlib::XSizeHints if it wasn't already). It will also set the bits of $supplied_fields_out to indicate which fields the X11 server knows about. This is different from the bits in $hints_out->flags that indicate which individual fields are defined for this window.
$hints_out
$supplied_fields_out
$hints_out->flags
XSetWMNormalHints($display, $window, $hints);
Set window manager hints for the specified window. $hints is an instance of X11::Xlib::XSizeHints, or a hashref of its fields. Note that the ->flags member of this struct will be initialized for you if you pass a hashref, according to what fields exist in the hashref.
$hints
->flags
XUnmapWindow($display, $window);
Hide a window.
XDestroyWindow($display, $window);
Unmap and destroy a window.
These methods create fake server-wide input events, useful for automated testing. They are available through the XTEST extension.
Don't forget to call "XFlush" after these methods, if you want the events to happen immediately.
XTestFakeMotionEvent($display, $screen, $x, $y, $EventSendDelay)
Fake a mouse movement to position $x,$y on screen number $screen.
$x
$y
The optional $EventSendDelay parameter specifies the number of milliseconds to wait before sending the event. The default is 10 milliseconds.
$EventSendDelay
XTestFakeButtonEvent($display, $button, $pressed, $EventSendDelay)
Simulate an action on mouse button number $button. $pressed indicates whether the button should be pressed (true) or released (false).
$button
$pressed
The optional $EventSendDelay parameter specifies the number of milliseconds ro wait before sending the event. The default is 10 milliseconds.
XTestFakeKeyEvent($display, $kc, $pressed, $EventSendDelay)
Simulate a event on any key on the keyboard. $kc is the key code (8 to 255), and $pressed indicates if the key was pressed or released.
$kc
XQueryKeymap($display)
Return a list of the key codes currently pressed on the keyboard.
XGetKeyboardMapping($display, $keycode, $count)
Return an array of KeySym numbers corresponding to $count keys, starting at $keycode.
$count
$keycode
Each value in the array corresponds to a combination of key modifiers (Shift, Lock, Mode). The X11 server may return a variable number of codes per key, which you can determine by dividing the total number of values returned by this function by the $count.
For an easier interface, see X11::Xlib::Keymap.
my $mapping= XGetModifierMapping($display);
Return an arrayref of 8 arrayrefs, one for each of the possible modifiers. The inner arrayrefs can contain a variable number of key codes which belong to the modifier group. See X11::Xlib::Keymap for an explanation.
XSetModifierMapping($display, \@modifiers);
@modifiers is an array of 8 arrayrefs, each holding the set of key codes that are part of the modifier. This is the same format as returned by XGetModifierMapping.
@modifiers
XGetModifierMapping
XRefreshKeyboardMapping($mapping_event);
Given a XMappingEvent, reload the internal Xlib cache for the parts of the keymap or modmap which have changed.
The functions below (using the internal Xlib cache) are an alternative to processing the keymap directly.
XLookupString($key_event, $text_out, $keycode_out);
Given a XKeyEvent, translate the key code and modifiers vs. the internal Xlib cached keymap/modmap and write the text name of the key into $text_out. This will either be a name of a key, or the character the key normally generates in a Latin-1 environment. If $keycode_out is given, it will be overwritten with the numeric value of the KeySym.
$text_out
$keycode_out
(If you want to do more than Latin-1, see X11::Xlib::Keymap for utilities to manipulate the keymap directly.)
XKeysymToKeycode($display, $keysym)
Return the key code corresponding to the character number $keysym.
$keysym
XKeysymToString($keysym)
Return the human-readable string for character number $keysym.
XKeysymToString is the exact reverse of XStringToKeysym.
XKeysymToString
XStringToKeysym
XStringToKeysym($string)
Return the keysym number for the human-readable character $string.
$string
XStringToKeysym is the exact reverse of XKeysymToString.
XConvertCase($keysym, $lowercase_out, $uppercase_out);
Return the lowercase and uppercase KeySyms values for $keysym.
IsFunctionKey($keysym)
Return true if $keysym is a function key (F1 .. F35)
IsKeypadKey($keysym)
Return true if $keysym is on numeric keypad.
IsMiscFunctionKey($keysym)
Return true is key if... honestly don't know :\
IsModifierKey($keysym)
Return true if $keysym is a modifier key (Shift, Alt).
IsPFKey($keysym)
Xlib docs are fun. No mention of what "PF" might be.
IsPrivateKeypadKey($keysym)
True for vendor-private key codes.
XBell($display, $percent)
Make the X server emit a sound.
Xlib has a lot of C structs. Most of them do not have much "depth" (i.e. pointers to further nested structs) and so I chose to represent them as simple blessed scalar refs to a byte string. This gives you the ability to pack new values into the struct which might not be known by this module, and keeps the object relatively lightweight. Most also have a pack and unpack method which convert from/to a hashref. Sometimes however these structs do contain a raw pointer value, and so you should take extreme care if you do modify the bytes.
pack
unpack
Xlib also has a lot of opaque pointers where they just give you a pointer and some methods to access it without any explanation of its inner fields. I represent these with the matching Perl feature for blessed opaque references, so the only way to interact with the pointer value is through XS code. In each case, when the object goes out of scope, this library calls any appropriate "Free" function.
Finally, there are lots of objects which exist on the server, and Xlib just gives you a number ("XID") to refer to them when making future requests. Windows are the most common example. Since these are simple integers, and can be shared among any program connected to the same display, this module allows a mix of simple scalar values or blessed objects when calling any function that expects an XID. The blessed objects derive from X11::Xlib::XID.
XID
Most supported structures have their own package with further documentation, but here is a quick list:
Represents a connection to an X11 server. Xlib provides an opaque pointer Display* on which you can call methods. These are represented by this package, X11::Xlib. The X11::Xlib::Display package provides a more perl-ish interface and some helper methods to "DWIM".
Display*
The Xlib Screen* is not exported by this module, since most methods that use a Screen* have a matching method that uses a Display*. If you are using the object-oriented Display you then get Screen objects for convenience, but they are just a wrapper around the Display and screen number instead of screen pointer.
Screen*
An opaque pointer describing binary representation of pixels for some mode of the display. There's probably only one in use on the entire display (i.e. RGBA) but Xlib makes you look it up and pass it around to various functions.
A more useful struct describing a Visual. See X11::Xlib::XVisualInfo.
A struct that can hold any sort of message sent to/from the server. The struct is a union of many other structs, which you can read about in X11::Xlib::XEvent.
An XID referencing what used to be a palette for 8-bit graphics but which is now mostly a useless appendage to be passed to "XCreateWindow". When using the object-oriented Display, these are wrapped by X11::Xlib::Colormap.
Display
An XID referencing a rectangular pixel buffer. Has dimensions and color depth and is bound to a "Screen". Can be used for copying images, or tiling. When using the object-oriented Display, these are wrapped by X11::Xlib::Pixmap.
An XID referencing a Window. Used for painting, event/input delivery, and having data tagged to them. Not abused nearly as much as the Win32 API abuses its Window structures. See X11::Xlib::Window for details.
Xlib libraries are found on most graphical Unixes, but you might lack the header files needed for this module. Try the following:
sudo apt-get install libxtst-dev
sudo yum install libXtst-devel
This module provides a higher-level API for X input simulation and testing.
Functions provided by X11/Xlib are mostly included in the Gtk2 binding, but through the GTK API and perl objects.
Pure-perl implementation of the X11 protocol.
This module still only covers a small fraction of the Xlib API. Patches are welcome :)
Olivier Thauvin, <nanardon@nanardon.zarb.org>
Michael Conrad, <mike@nrdvana.net>
Copyright (C) 2009-2010 by Olivier Thauvin
Copyright (C) 2017 by Michael Conrad
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available.
To install X11::Xlib, copy and paste the appropriate command in to your terminal.
cpanm
cpanm X11::Xlib
CPAN shell
perl -MCPAN -e shell install X11::Xlib
For more information on module installation, please visit the detailed CPAN module installation guide.