Search code examples
clipboardx11xlib

X11 - handling XSelectionRequestEvent after calling XSetSelectionOwner


I implement clipboard handling in my X11 application. The first step of a copy operation is calling XSetSelectionOwner:

Atom clipboardAtom = XInternAtom(display, "CLIPBOARD", False);
XSetSelectionOwner(display, clipboardAtom, clipboardWin, CurrentTime);

After that I get XSelectionRequestEvent. That event contains target atom. Does calling XSetSelectionOwner always set target atom to atom "TARGETS" ?

Atom targetsAtom = XInternAtom(display, "TARGETS", False);
//handling XSelectionRequestEvent after calling XSetSelectionOwner
if(event.xselectionrequest.target == targetsAtom)
{
}

Solution

  • XSelectionRequestEvent is the result of some other window (the .requestor field in the event) sending a ConvertSelection request. It is up to the requestor to set the value of the target field.

    The atom "TARGETS" is often (but not always) used by programs that support multiple types of selection. ICCCM says every selection owner must know how to answer this with the list of supported targets for this selection. The requestor will then decide what exact target to request if more than one is supported.

    Not all clients will send ConvertSelection with the target set to "TARGETS". For example, a text editor or a terminal will just send "UTF8_STRING" or similar and hope for the best. A client that can deal with multiple target types is likely to send "TARGETS". Notable examples are clients that implement the clipboard functionality (xclipboard or your desktop environment equivalent).

    Clipboard-like clients monitor selections and request info about it (and sometimes claim ownership) right after a selection changes. That's probably why you see XSelectionRequestEvent event(s) immediately after your window asserts a selection ownership. On a bare X server with no other clients, your window will never see any SelectionRequest events. If there are "regular" clients like text editors or terminal emulators, you will see SelectionRequest when one of those executes a paste command.