The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

X11::Xlib - Low-level access to the X11 library

SYNOPSIS

  # 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
  $display->fake_motion(undef, 50, 50)
  $display->flush;

DESCRIPTION

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.

ATTRIBUTES

The X11::Xlib connection is a hashref with a few attributes and methods independent of Xlib.

autoclose

Boolean flag that determines whether the destructor will call "XCloseDisplay". Defaults to true for connections returned by "XOpenDisplay".

FUNCTIONS

new

This is an alias for X11::Xlib::Display->new, to help encourage using the object oriented interface.

install_error_handlers

  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 dammaged, so it is unsafe to make any more Xlib calls. This library tries to help enforce that by invalidating all the connection objects.

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.

XLIB API

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';

CONNECTION FUNCTIONS

XOpenDisplay

  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.

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.

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.

ConnectionNumber

  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

  XSetCloseDownMode($display, $close_mode)

Determines what resources are freed upon disconnect. See X11 documentation.

COMMUNICATION FUNCTIONS

Most of these functions return an "XEvent" by way of an "out" parameter that gets overwritten during the call, in the style of C. You may pass in an undefined scalar to be automatically allocated for you.

XNextEvent

  XNextEvent($display, my $event_return)
  ... # event scalar is populated with event

You probably don't want this. It blocks forever until an event arrives. I added it for completeness. See "wait_event" in X11::Xlib::Display for a more Perl-ish interface.

XCheckMaskEvent

XCheckWindowEvent

XCheckTypedEvent

XCheckTypedWindowEvent

  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.

(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

  XSendEvent($display, $window, $propagate, $event_mask, $xevent)
    or die "Xlib hates us";

Send an XEvent.

XPutBackEvent

  XPutBackEvent($display, $xevent)

Push an XEvent back onto the queue. This can also presumably put an arbitrarily bogus event onto your own queue since it returns void.

XFlush

  XFlush($display)

Push any queued messages to the X11 server. If you're wondering why nothing happened when you called an XTest function, this is why.

XSync

  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

  XSelectInput($display, $window, $event_mask)

Change the event mask for a window.

SCREEN ATTRIBUTES

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.

ScreenCount

  my $n= ScreenCount($display);

Return number of configured "Screen"s of this display.

DisplayWidth

DisplayHeight

  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.

DisplayWidthMM

DisplayHeightMM

  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.

RootWindow

  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.

DefaultVisual

  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".

DefaultDepth

  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.

VISUAL/COLORMAP FUNCTIONS

XMatchVisualInfo

  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.

XGetVisualInfo

  my @info_structs= XGetVisualInfo($display, $mask, $xvis_template);

Returns a list of "XVisualInfo" each describing an available "Visual" which matches the template you provided. (also an XVisualInfo)

$mask can be one of:

  VisualIDMask
  VisualScreenMask
  VisualDepthMask
  VisualClassMask
  VisualRedMaskMask
  VisualGreenMaskMask
  VisualBlueMaskMask
  VisualColormapSizeMask
  VisualBitsPerRGBMask
  VisualAllMask

each describing a field of X11::Xlib::XVisualInfo which is relevant to your search.

XVisualIDFromVisual

  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:

  my ($vis_info)= GetVisualInfo($display, VisualIDMask, { visualid => $vis_id });
  # or with Display object:
  $display->visual_by_id($vis_id);

XCreateColormap

  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.

XFreeColormap

  XFreeColormap($display, $colormap);

Delete a "Colormap", and set the colormap to None for any window that was using it.

Colormap TODO

  XInstallColormap XUninstallColormap, XListInstalledColormaps
  XGetWMColormapWindows XSetWMColormapWindows, XSetWindowColormap
  XAllocColor XStoreColors XFreeColors XAllocColorPlanes XAllocNamedColor
  XQueryColors XCopyColormapAndFree

If anyone actually needs palette graphics anymore, send me a patch :-)

PIXMAP FUNCTIONS

XCreatePixmap

  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.

XFreePixmap

  XFreePixmap($display, $pixmap);

XCreateBitmapFromData

  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.

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.

XCreatePixmapFromBitmapData

  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.

WINDOW FUNCTIONS

XCreateWindow

  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.

$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.

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.

The window is initially un-mapped (i.e. hidden). See "XMapWindow"

XCreateSimpleWindow

  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

  XMapWindow($display, $window);

Ask the X server to show a window. This call 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.

XGetGeometry

  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.

XGetWMNormalHints

  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.

XSetWMNormalHints

  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.

XUnmapWindow

  XUnmapWindow($display, $window);

Hide a window.

XDestroyWindow

  XDestroyWindow($display, $window);

Unmap and destroy a window.

XTEST INPUT SIMULATION

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

  XTestFakeMotionEvent($display, $screen, $x, $y, $EventSendDelay)

Fake a mouse movement on screen number $screen to position $x,$y.

The optional $EventSendDelay parameter specifies the number of milliseconds to wait before sending the event. The default is 10 milliseconds.

XTestFakeButtonEvent

  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).

The optional $EventSendDelay parameter specifies the number of milliseconds ro wait before sending the event. The default is 10 milliseconds.

XTestFakeKeyEvent

  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.

The optional $EventSendDelay parameter specifies the number of milliseconds to wait before sending the event. The default is 10 milliseconds.

XBell

  XBell($display, $percent)

Make the X server emit a sound.

XQueryKeymap

  XQueryKeymap($display)

Return a list of the key codes currently pressed on the keyboard.

KEYCODE FUNCTIONS

XKeysymToKeycode

  XKeysymToKeycode($display, $keysym)

Return the key code corresponding to the character number $keysym.

XGetKeyboardMapping

  XGetKeyboardMapping($display, $keycode, $count)

Return an array of character numbers corresponding to the key $keycode.

Each value in the array corresponds to the action of a key modifier (Shift, Alt).

$count is the number of the keycode to return. The default value is 1, e.g. it returns the character corresponding to the given $keycode.

XKeysymToString

  XKeysymToString($keysym)

Return the human-readable string for character number $keysym.

XKeysymToString is the exact reverse of XStringToKeysym.

XStringToKeysym

  XStringToKeysym($string)

Return the keysym number for the human-readable character $string.

XStringToKeysym is the exact reverse of XKeysymToString.

IsFunctionKey

  IsFunctionKey($keysym)

Return true if $keysym is a function key (F1 .. F35)

IsKeypadKey

  IsKeypadKey($keysym)

Return true if $keysym is on numeric keypad.

IsMiscFunctionKey

  IsMiscFunctionKey($keysym)

Return true is key if... honestly don't know :\

IsModifierKey

  IsModifierKey($keysym)

Return true if $keysym is a modifier key (Shift, Alt).

IsPFKey

  IsPFKey($keysym)

Xlib docs are fun. No mention of what "PF" might be.

IsPrivateKeypadKey

  IsPrivateKeypadKey($keysym)

True for vendor-private key codes.

STRUCTURES

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.

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.

Most supported structures have their own package with further documentation, but here is a quick list:

Display

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".

Screen

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.

Visual

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.

XVisualInfo

A more useful struct describing a Visual. See X11::Xlib::XVisualInfo.

XEvent

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.

Colormap

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.

Pixmap

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.

Window

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.

SYSTEM DEPENDENCIES

Xlib libraries are found on most graphical Unixes, but you might lack the header files needed for this module. Try the following:

Debian (Ubuntu, Mint)

sudo apt-get install libxtst-dev

Fedora

sudo yum install libXtst-devel

SEE ALSO

X11::GUITest

This module provides a higher-level API for X input simulation and testing.

Gtk2

Functions provided by X11/Xlib are mostly included in the Gtk2 binding, but through the GTK API and perl objects.

TODO

This module still only covers a fraction of the Xlib API. Patches are welcome :)

AUTHOR

Olivier Thauvin, <nanardon@nanardon.zarb.org>

Michael Conrad, <mike@nrdvana.net>

COPYRIGHT AND LICENSE

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.