x11xlib

Sharing colormap between windows


I create a x11 window using XCreateWindow function. I create colormap this way:

XSetWindowAttributes attribs = { 0 };
Colormap cmap = XCreateColormap(dpy, rootWindow, visualInfo->visual, AllocNone);
attribs.colormap = cmap;

attribs variable is passed to the XCreateWindow. In my application I want to create a few windows. Should I call XCreateColormap when creating a window or I can create colormap object once and share it between windows ?


Solution

  • You can and should create a colormap shared between windows.

    Colormaps are resources (sometimes even hardware resources) and it doesn't make sense to waste them.

    One doesn't create colormaps these days very often because true color displays are taken for granted, but back in the day with 256 or maybe even 16 indexed colours they were a thing. There was usually just one hardware colormap with 256/16 entries. Activating a window via a window manager would load that window's colormap into the hardware colormap. As a result, if a window had some non-standard colormap, inactive windows with different colormaps would display weird colours.

    So if your application windows all need to display the same colours, they should just use one colormap. Otherwise on such an old indexed colour system they could show inconsistent colours. Example (in pseudocode):

    colormap1 = XCreateColormap(...);
    window1 = XCreateWindow (... using colormap1 ... );
    
    colormap2 = XCreateColormap(...);
    window2 = XCreateWindow (... using colormap2 ... );
    
    XAllocColor (..., colormap1, pink); // allocates at index 13
    XAllocColor (..., colormap1, beige); // allocates at index 14
    
    XAllocColor (..., colormap2, pink); // allocates at index 14
    XAllocColor (..., colormap2, beige); // allocates at index 13
    

    Now when you select window 1, in window 2 pink and beige would swap places, and when you select window 2, the same happens in window 1. You would not be able to view both windows simultaneously in their intended colours.