Why is an XImage's data pointer null when capturing using XShmGetImage? - c++

I'm writing a program to rapidly capture images from one window, modify them, and output them to another window using Xlib with C++. I have this working via XGetImage:
#include <iostream>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
const int TEST_SIZE = 512;
int main()
{
// Open default display
Display *display = XOpenDisplay(nullptr);
int screen = DefaultScreen(display);
Window rootWin = RootWindow(display, screen);
GC graphicsContext = DefaultGC(display, screen);
// Create new window and subscribe to events
long blackPixel = BlackPixel(display, screen);
long whitePixel = WhitePixel(display, screen);
Window newWin = XCreateSimpleWindow(display, rootWin, 0, 0, TEST_SIZE, TEST_SIZE, 1, blackPixel, whitePixel);
XMapWindow(display, newWin);
XSelectInput(display, newWin, ExposureMask | KeyPressMask);
// Main event loop for new window
XImage *image;
XEvent event;
bool exposed = false;
bool killWindow = false;
while (!killWindow)
{
// Handle pending events
if (XPending(display) > 0)
{
XNextEvent(display, &event);
if (event.type == Expose)
{
exposed = true;
} else if (event.type == NoExpose)
{
exposed = false;
} else if (event.type == KeyPress)
{
killWindow = true;
}
}
// Capture the original image
image = XGetImage(display, rootWin, 0, 0, TEST_SIZE, TEST_SIZE, AllPlanes, ZPixmap);
// Modify the image
if (image->data != nullptr)
{
long pixel = 0;
for (int x = 0; x < image->width; x++)
{
for (int y = 0; y < image->height; y++)
{
// Invert the color of each pixel
pixel = XGetPixel(image, x, y);
XPutPixel(image, x, y, ~pixel);
}
}
}
// Output the modified image
if (exposed && killWindow == false)
{
XPutImage(display, newWin, graphicsContext, image, 0, 0, 0, 0, TEST_SIZE, TEST_SIZE);
}
XDestroyImage(image);
}
// Goodbye
XCloseDisplay(display);
}
It generates output like this: https://streamable.com/hovg9
I'm happy to have gotten this far, but from what I've read the performance isn't going to scale very well because it has to allocate space for a new image at every frame. In fact, without the call to XDestroyImage at the end of the loop this program fills up all 16GB of memory on my machine in a matter of seconds!
It seems the recommended approach here is to to set up a shared memory space where X can write the contents of each frame and my program can subsequently read and modify them without the need for any extra allocation. Since the call to XShmGetImage blocks and waits for IPC I believe this means I won't have to worry about any concurrency issues in the shared space.
I've attempted to implement the XShmGetImage approach with the following code:
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <X11/Xlib.h>
#include <X11/extensions/XShm.h>
#include <X11/Xutil.h>
const int TEST_SIZE = 512;
int main()
{
// Open default display
Display *display = XOpenDisplay(nullptr);
int screen = DefaultScreen(display);
Window rootWin = RootWindow(display, screen);
GC graphicsContext = DefaultGC(display, screen);
// Create new window and subscribe to events
long blackPixel = BlackPixel(display, screen);
long whitePixel = WhitePixel(display, screen);
Window newWin = XCreateSimpleWindow(display, rootWin, 0, 0, TEST_SIZE, TEST_SIZE, 1, blackPixel, whitePixel);
XMapWindow(display, newWin);
XSelectInput(display, newWin, ExposureMask | KeyPressMask);
// Allocate shared memory for image capturing
Visual *visual = DefaultVisual(display, 0);
XShmSegmentInfo shminfo;
int depth = DefaultDepth(display, screen);
XImage *image = XShmCreateImage(display, visual, depth, ZPixmap, nullptr, &shminfo, TEST_SIZE, TEST_SIZE);
shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height, IPC_CREAT | 0666);
shmat(shminfo.shmid, nullptr, 0);
shminfo.shmaddr = image->data;
shminfo.readOnly = False;
XShmAttach(display, &shminfo);
// Main event loop for new window
XEvent event;
bool exposed = false;
bool killWindow = false;
while (!killWindow)
{
// Handle pending events
if (XPending(display) > 0)
{
XNextEvent(display, &event);
if (event.type == Expose)
{
exposed = true;
} else if (event.type == NoExpose)
{
exposed = false;
} else if (event.type == KeyPress)
{
killWindow = true;
}
}
// Capture the original image
XShmGetImage(display, rootWin, image, 0, 0, AllPlanes);
// Modify the image
if (image->data != nullptr) // NEVER TRUE. DATA IS ALWAYS NULL!
{
long pixel = 0;
for (int x = 0; x < image->width; x++)
{
for (int y = 0; y < image->height; y++)
{
// Invert the color of each pixel
pixel = XGetPixel(image, x, y);
XPutPixel(image, x, y, ~pixel);
}
}
}
// Output the modified image
if (exposed && killWindow == false)
{
XShmPutImage(display, newWin, graphicsContext, image, 0, 0, 0, 0, 512, 512, false);
}
}
// Goodbye
XFree(image);
XCloseDisplay(display);
}
Somehow, the images are still being captured and sent to the new window, but the data pointer within the XImage is always null. I can't modify any of the contents and any usage of the XGetPixel and XPutPixel macros will fail. Notice in this video that none of the colors are being inverted like before: https://streamable.com/dckyv
This doesn't make any sense to me. Clearly the data is still being transferred between the windows, but where is it in the XImage structure? How can I access it via code?

It turns out I wasn't reading the signature for shmat correctly. It doesn't have a void return type, it returns a void pointer. This needs to be assigned directly to the XImage's data pointer in order for the data pointer to do anything.
In the call to XShmPutImage the shared memory location is referenced internally rather than the XImage's data pointer which is why this was still working even without utilizing the return value from shmat.
Here's the working code, along with a few other additions which I made for error handling and teardown:
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <X11/Xlib.h>
#include <X11/extensions/XShm.h>
#include <X11/Xutil.h>
const int TEST_SIZE = 512;
static int handleXError(Display *display, XErrorEvent *event)
{
printf("XErrorEvent triggered!\n");
printf("error_code: %d", event->error_code);
printf("minor_code: %d", event->minor_code);
printf("request_code: %d", event->request_code);
printf("resourceid: %lu", event->resourceid);
printf("serial: %d", event->error_code);
printf("type: %d", event->type);
return 0;
}
int main()
{
// Open default display
XSetErrorHandler(handleXError);
Display *display = XOpenDisplay(nullptr);
int screen = DefaultScreen(display);
Window rootWin = RootWindow(display, screen);
GC graphicsContext = DefaultGC(display, screen);
// Create new window and subscribe to events
long blackPixel = BlackPixel(display, screen);
long whitePixel = WhitePixel(display, screen);
Window newWin = XCreateSimpleWindow(display, rootWin, 0, 0, TEST_SIZE, TEST_SIZE, 1, blackPixel, whitePixel);
XMapWindow(display, newWin);
XSelectInput(display, newWin, ExposureMask | KeyPressMask);
// Allocate shared memory for image capturing
XShmSegmentInfo shminfo;
Visual *visual = DefaultVisual(display, screen);
int depth = DefaultDepth(display, screen);
XImage *image = XShmCreateImage(display, visual, depth, ZPixmap, nullptr, &shminfo, TEST_SIZE, TEST_SIZE);
shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height, IPC_CREAT | 0777);
image->data = (char*)shmat(shminfo.shmid, 0, 0);
shminfo.shmaddr = image->data;
shminfo.readOnly = False;
XShmAttach(display, &shminfo);
XSync(display, false);
shmctl(shminfo.shmid, IPC_RMID, 0);
// Main event loop for new window
XEvent event;
bool exposed = false;
bool killWindow = false;
while (!killWindow)
{
// Handle pending events
if (XPending(display) > 0)
{
XNextEvent(display, &event);
if (event.type == Expose)
{
exposed = true;
} else if (event.type == NoExpose)
{
exposed = false;
} else if (event.type == KeyPress)
{
killWindow = true;
}
}
// Capture the original image
XShmGetImage(display, rootWin, image, 0, 0, AllPlanes);
// Modify the image
if(image->data != nullptr) // NEVER TRUE. DATA IS ALWAYS NULL!
{
long pixel = 0;
for (int x = 0; x < image->width; x++)
{
for (int y = 0; y < image->height; y++)
{
// Invert the color of each pixel
pixel = XGetPixel(image, x, y);
XPutPixel(image, x, y, ~pixel);
}
}
}
// Output the modified image
if (exposed && killWindow == false)
{
XShmPutImage(display, newWin, graphicsContext, image, 0, 0, 0, 0, 512, 512, false);
}
}
// Goodbye
XShmDetach(display, &shminfo);
XDestroyImage(image);
shmdt(shminfo.shmaddr);
XCloseDisplay(display);
}

Related

WIN32 how to cache drawing results to a bitmap?

Because there are hover and leave events of the mouse in the interface, if re drawing in each leave event leads to a large amount of resource occupation, how to draw and cache it in memory only when the program is started or the interface is notified of changes, and send InvalidateRect() to directly use BitBlt mapping instead of re drawing in the rest of the time?
int dystat = 0;
int anistat = 0;
void CreatePanelDynamic(HWND h, HDC hdc, DRAWPANEL DrawFun, int Flag = 0)
{
//On hMemDC.
if (PanelID == PrevPanelID)
{
//
if (dystat == 0)
{
RECT rc;
GetClientRect(h, &rc);
BitBlt(hdc, 0, 0, rc.right - rc.left, rc.bottom - rc.top, in_ghdc, 0, 0, SRCCOPY); //by bitmap
}
else
{
_CreatePanel(h, hdc, DrawFun); //directly
dystat = 0;
}
anistat = 0;
}
if (PanelID != PrevPanelID) //animation
{
if (Flag == 0)
{
CreatePanelAnimation(h, hdc, DrawFun);
dystat = 1;
}
if (Flag == 1)
{
_CreatePanel(h, hdc, DrawFun);
dystat = 1;
}
PrevPanelID = PanelID;
anistat = 0;
}
}
My program is already using MemDC.

Create xlib window with a frame buffer i can draw directly and use XPutImage

I'm trying to create a xlib window, create a frame buffer that has a depth of 32 and draw that buffer to the window, However. Everything works until XPutImage gets called, the window never shows and the console outputs:
Process returned -1 (0xFFFFFFFF) execution time : ?.??? s
Press ENTER to continue;
If i comment out the XPutImage line in the Expose event then i get a window that has a transparent client area as desired. So I'm looking for an answer of how to fix this.
Note I'm new to Linux programming but have been doing windows programming for a long time. So I'm not familiar with Linux functions and protocols, yet ;)
I'm using Code::Blocks 20.03 on Fedora 32 (64-bit).
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
int main(int argc, char **argv)
{
Display *dpy;
XVisualInfo vinfo;
int depth;
XVisualInfo *visual_list;
XVisualInfo visual_template;
int nxvisuals;
int i;
XSetWindowAttributes attrs;
Window parent;
Visual *visual;
int width, height;
Window win;
int *framebuf;
XImage *ximage;
XEvent event;
dpy = XOpenDisplay(NULL);
nxvisuals = 0;
visual_template.screen = DefaultScreen(dpy);
visual_list = XGetVisualInfo (dpy, VisualScreenMask, &visual_template, &nxvisuals);
for (i = 0; i < nxvisuals; ++i)
{
printf(" %3d: visual 0x%lx class %d (%s) depth %d\n",
i,
visual_list[i].visualid,
visual_list[i].class,
visual_list[i].class == TrueColor ? "TrueColor" : "unknown",
visual_list[i].depth);
}
if (!XMatchVisualInfo(dpy, XDefaultScreen(dpy), 32, TrueColor, &vinfo))
{
fprintf(stderr, "no such visual\n");
return 1;
}
printf("Matched visual 0x%lx class %d (%s) depth %d\n",
vinfo.visualid,
vinfo.class,
vinfo.class == TrueColor ? "TrueColor" : "unknown",
vinfo.depth);
parent = XDefaultRootWindow(dpy);
XSync(dpy, True);
printf("creating RGBA child\n");
visual = vinfo.visual;
depth = vinfo.depth;
attrs.colormap = XCreateColormap(dpy, XDefaultRootWindow(dpy), visual, AllocNone);
attrs.background_pixel = 0;
attrs.border_pixel = 0;
width = 1000;
height = 700;
framebuf = malloc((width*height)*4);
for (i = 0; i < (width*height); i++)
{
framebuf[i] = 0xFFFFFFFF;
}
win = XCreateWindow(dpy, parent, 100, 100, width, height, 0, depth, InputOutput,
visual, CWBackPixel | CWColormap | CWBorderPixel, &attrs);
ximage = XCreateImage(dpy, vinfo.visual, 32, XYPixmap, 0, (char *)framebuf, width, height, 8, width*4);
if (ximage == 0)
{
printf("ximage is null!\n");
}
XSync(dpy, True);
XSelectInput(dpy, win, ExposureMask | KeyPressMask);
XGCValues gcv;
unsigned long gcm;
GC NormalGC;
//gcm = GCForeground | GCBackground | GCGraphicsExposures;
//gcv.foreground = BlackPixel(dpy, parent);
//gcv.background = WhitePixel(dpy, parent);
gcm = GCGraphicsExposures;
gcv.graphics_exposures = 0;
NormalGC = XCreateGC(dpy, parent, gcm, &gcv);
XMapWindow(dpy, win);
while(!XNextEvent(dpy, &event))
{
switch(event.type)
{
case Expose:
printf("I have been exposed!\n");
XPutImage(dpy, win, NormalGC, ximage, 0, 0, 0, 0, width, height);
break;
}
}
printf("No error\n");
return 0;
}
To get it to work, I had to change two lines in the code. You probably won't be happy because to get it to work I had to change it from RGBA to BGRX. Whenever I work with xlib I always had to use a 24 bit depth even though the data is stored in 32 bits. It is also stored BGRX not RGBX...
Here is the changed code.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
int main(int argc, char **argv)
{
Display *dpy;
XVisualInfo vinfo;
int depth;
XVisualInfo *visual_list;
XVisualInfo visual_template;
int nxvisuals;
int i;
XSetWindowAttributes attrs;
Window parent;
Visual *visual;
int width, height;
Window win;
int *framebuf;
XImage *ximage;
XEvent event;
dpy = XOpenDisplay(NULL);
nxvisuals = 0;
visual_template.screen = DefaultScreen(dpy);
visual_list = XGetVisualInfo (dpy, VisualScreenMask, &visual_template, &nxvisuals);
//Change to this line
//if (!XMatchVisualInfo(dpy, XDefaultScreen(dpy), 32, TrueColor, &vinfo))
if (!XMatchVisualInfo(dpy, XDefaultScreen(dpy), 24, TrueColor, &vinfo))
{
fprintf(stderr, "no such visual\n");
return 1;
}
parent = XDefaultRootWindow(dpy);
XSync(dpy, True);
printf("creating RGBA child\n");
visual = vinfo.visual;
depth = vinfo.depth;
attrs.colormap = XCreateColormap(dpy, XDefaultRootWindow(dpy), visual, AllocNone);
attrs.background_pixel = 0;
attrs.border_pixel = 0;
width = 1000;
height = 700;
framebuf = (int *) malloc((width*height)*4);
for (i = 0; i < (width*height); i++)
{
framebuf[i] = 0xFF00FFFF;
}
win = XCreateWindow(dpy, parent, 100, 100, width, height, 0, depth, InputOutput,
visual, CWBackPixel | CWColormap | CWBorderPixel, &attrs);
//Change to this line
//ximage = XCreateImage(dpy, vinfo.visual, 32, XYPixmap, 0, (char *)framebuf, width, height, 8, width*4);
ximage = XCreateImage(dpy, vinfo.visual, depth, ZPixmap, 0, (char *)framebuf, width, height, 8, width*4);
if (ximage == 0)
{
printf("ximage is null!\n");
}
XSync(dpy, True);
XSelectInput(dpy, win, ExposureMask | KeyPressMask);
XGCValues gcv;
unsigned long gcm;
GC NormalGC;
//gcm = GCForeground | GCBackground | GCGraphicsExposures;
//gcv.foreground = BlackPixel(dpy, parent);
//gcv.background = WhitePixel(dpy, parent);
gcm = GCGraphicsExposures;
gcv.graphics_exposures = 0;
NormalGC = XCreateGC(dpy, parent, gcm, &gcv);
XMapWindow(dpy, win);
while(!XNextEvent(dpy, &event))
{
switch(event.type)
{
case Expose:
printf("I have been exposed!\n");
XPutImage(dpy, win, NormalGC, ximage, 0, 0, 0, 0, width, height);
break;
}
}
printf("No error\n");
return 0;
}
You're using the parent's Drawable in XCreateGC(dpy, parent, gcm, &gcv); instead of the window's own.
To use 32bit color change it to XCreateGC(dpy, win, gcm, &gcv);

SDL text rendering access violation

I'm using SDL 2.0 with C++ for 2D graphics, compressed image format loading, sound playback and so on. Consider the following code:
int main(int argc, char *args[])
{
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO);
SDL_Window *pWindow = SDL_CreateWindow("Access Violation", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1920, 1080, SDL_WINDOW_FULLSCREEN);
SDL_Renderer *pRenderer = SDL_CreateRenderer(pWindow, -1, SDL_RENDERER_ACCELERATED);
Mix_Init(0);
Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);
Mix_Music *pMusic = Mix_LoadMUS("music.wav");
TTF_Init();
TTF_Font *pFont = TTF_OpenFont("font.ttf", 28);
bool quit = false;
SDL_Event ev;
while(!quit)
{
while(SDL_PollEvent(&ev) != 0)
{
switch(ev.type)
{
case SDL_QUIT:
quit = true;
break;
}
}
SDL_SetRenderDrawColor(pRenderer, 255, 255, 255, 255);
SDL_RenderClear(pRenderer);
for(int i = 0; i < 864; i++)
{
SDL_Color clr = { 0, 0, 0 };
SDL_Surface *pSurface = TTF_RenderText_Solid(pFont, "Hey!", clr);
SDL_Texture *pTexture = SDL_CreateTextureFromSurface(pRenderer, pSurface);
SDL_Rect dstrect = { (int)(i/27) * 60, (i%27)*40, pSurface->w, pSurface->h };
SDL_RenderCopy(pRenderer, pTexture, 0, &dstrect);
SDL_DestroyTexture(pTexture);
SDL_FreeSurface(pSurface);
}
SDL_RenderPresent(pRenderer);
}
TTF_CloseFont(pFont);
Mix_FreeMusic(pMusic);
SDL_DestroyRenderer(pRenderer);
SDL_DestroyWindow(pWindow);
Mix_CloseAudio();
Mix_Quit();
IMG_Quit();
TTF_Quit();
SDL_Quit();
return 0;
}
What this basically does is that it just initializes SDL, loads a music, loads a font, and fills continuously the whole screen with text. Fine.
But!
If I add this line
...
SDL_Event ev;
Mix_PlayMusic(pMusic, 0);
while(!quit)
...
right here, text redrawing in the cycle
for(int i = 0; i < 864; i++)
{
...
}
starts to behave unpredictably. One of the SDL's function will shoot an access violation, after some time - between 1 and 30 seconds after start. On the other hand, would I omit text redrawing, music is playing fine.
Any ideas? Of course, all return values are checked. I've omitted checks because of the clarity of the code.
EDIT: Typos.

XOpenDisplay failing

I'm writing a simple window class which is failing to return a display. Here's the short version:
#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
class WindowImpl
{
public:
WindowImpl()
{
open = true;
}
WindowImpl(float width, float height)
{
if(!create(width, height))
{
fprintf(stderr, "Could not open display\n");
exit(1);
}
open = true;
}
~WindowImpl()
{
XCloseDisplay(display);
};
bool create(float width, float height)
{
display = XOpenDisplay(NULL);
if(display == NULL)
return false;
int displayID = DefaultScreen(display);
window = XCreateSimpleWindow(display, RootWindow(display, displayID), 10, 10, width, height, 1, BlackPixel(display, displayID), WhitePixel(display, displayID));
XMapWindow(display, window);
return true;
}
bool isOpen()
{
return open;
}
void close()
{
open == false;
}
private:
Display* display;
Window window;
bool open;
};
int main()
{
WindowImpl myWindow(1920, 1080);
char* cmd;
while(myWindow.isOpen())
{
if(gets(cmd) == "close")
myWindow.close();
}
return 0;
}
WindowImpl::create fails, XOpenDisplay is returning NULL but I'm not sure why. Hopefully someone could shed some light on the problem here.
Edit: Changing WindowImpl::create to return true and false instead of 0 and 1 causes it to go through but the window still doesn't open;
For clarification:
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
Display* display;
Window window;
XEvent event;
char* message = "Hello";
int screenSize;
display = XOpenDisplay(NULL);
if(display == NULL)
{
fprintf(stderr, "Cannot open display\n");
exit(1);
}
screenSize = DefaultScreen(display);
window = XCreateSimpleWindow(display, RootWindow(display, screenSize), 10, 10, 1920, 1080, 1, BlackPixel(display, screenSize), WhitePixel(display, screenSize));
XSelectInput(display, window, ExposureMask | KeyPressMask);
XMapWindow(display, window);
KeySym keysym = XK_Escape;
KeyCode keycode = XKeysymToKeycode(display, keysym);
while(true)
{
XNextEvent(display, &event);
if(event.type == KeyPress && event.xkey.keycode == keycode)
break;
}
XCloseDisplay(display);
return 0;
}
Compiles and runs just fine.
When you create a windows, you need to let the X server to handle output buffer. Normally this is done when you enter into the window event loop, i.e. calling any function that has EVENT in its name.
Once you are not dealing with events in your code, another way to flush the output buffer is calling XFlush, as said in its manual:
The XFlush function flushes the output buffer. Most client applications need not use this function because the output buffer is automatically flushed as needed by calls to XPending, XNextEvent, and XWindowEvent. Events generated by the server may be enqueued into the library's event queue.
The XSync function flushes the output buffer and then waits until all requests have been received and processed by the X server.
So, to solve your issue, I suggest to put this line of code:
window = XCreateSimpleWindow(display, RootWindow(display, displayID), 10, 10, width, height, 1, BlackPixel(display, displayID), WhitePixel(display, displayID));
XMapWindow(display, window);
XFlush(display); // <------------
return true;

I want to make splash screen and now I have two problems?

1: I want to have a splash screen but I only have a window?so,how to do with sth like parm
2: I've used a while(!done) to draw the window so how to break out with a function or sth else
here is my code and much thx to you
g++ -o m_splash m_splash.cpp -lX11 -lImlib2
#include <stdio.h>
#include <X11/Xlib.h>
#include <Imlib2.h>
#include <unistd.h>
int main()
{
Imlib_Image m_img;
Display *m_dpy;
Pixmap m_pix;
Window m_root;
Screen *scn;
int m_width, m_height;
const char *filename = "/home/ang/so_zt/w.png";
m_img = imlib_load_image(filename);
if(!m_img)
{
printf("%s\n","init m_img faild");
}
imlib_context_set_image(m_img);
m_width = imlib_image_get_width();
m_height = imlib_image_get_height();
m_dpy = XOpenDisplay(NULL);
if(!m_dpy)
{
printf("%s\n","open display failed");
}
scn = DefaultScreenOfDisplay(m_dpy);
int s = DefaultScreen(m_dpy);
m_root = XCreateSimpleWindow(m_dpy, RootWindow(m_dpy,s),10,10,m_width,m_height,0,
BlackPixel(m_dpy, s), WhitePixel(m_dpy, s));
m_pix = XCreatePixmap(m_dpy, m_root, m_width, m_height, DefaultDepthOfScreen(scn));
imlib_context_set_display(m_dpy);
imlib_context_set_visual(DefaultVisualOfScreen(scn));
imlib_context_set_colormap(DefaultColormapOfScreen(scn));
imlib_context_set_drawable(m_pix);
imlib_render_image_on_drawable(0,0);
XSetWindowBackgroundPixmap(m_dpy, m_root, m_pix);
XClearWindow(m_dpy, m_root);
Atom wmDeleteMessage = XInternAtom(m_dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(m_dpy, m_root, &wmDeleteMessage, 1);
XSelectInput(m_dpy, m_root, ExposureMask | KeyPressMask | StructureNotifyMask);
XMapWindow(m_dpy, m_root);
bool done = false;
while (!done)
{
XEvent m_ev;
XNextEvent(m_dpy, &m_ev);
/* draw or redraw the window */
if (m_ev.type == Expose)
{
XFillRectangle(m_dpy, m_root, DefaultGC(m_dpy, DefaultScreen(m_dpy)), 20, 20, 10, 10);
}
/* exit on key press */
//usleep(1000000);
//done = true;
switch(m_ev.type)
{
case KeyPress:
XDestroyWindow(m_dpy, m_root);
break;
case DestroyNotify:
done = true;
break;
case ClientMessage:
if (m_ev.xclient.data.l[0] == wmDeleteMessage)
{
done = true;
}
break;
}
}
//XFreePixmap(m_dpy, m_pix);
//imlib_free_image();
//XCloseDisplay(m_dpy);
}
To make it a splash screen, use extended window manager hints.
#include <X11/Xatom.h>
Atom type = XInternAtom(m_dpy, "_NET_WM_WINDOW_TYPE", False);
Atom value = XInternAtom(m_dpy, "_NET_WM_WINDOW_TYPE_SPLASH", False);
XChangeProperty(m_dpy, m_root, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char*>(&value), 1);
The window then appears without decorations and stays until clicked.
When clicked you get an UnmapNotify event, so this what you should use to set done.
To avoid having to get events, add
XFlush(m_dpy);
after mapping the window to display it and
XUnmapWindow(m_dpy, m_root);
when you want to get rid of it.
In this example the program just sleeps for 5 seconds before continuing:
#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <Imlib2.h>
#include <unistd.h>
int main()
{
Imlib_Image m_img;
Display *m_dpy;
Pixmap m_pix;
Window m_root;
Screen *scn;
int m_width, m_height;
const char *filename = "w.png";
m_img = imlib_load_image(filename);
if(!m_img)
{
printf("%s\n","init m_img faild");
}
imlib_context_set_image(m_img);
m_width = imlib_image_get_width();
m_height = imlib_image_get_height();
m_dpy = XOpenDisplay(NULL);
if(!m_dpy)
{
printf("%s\n","open display failed");
}
scn = DefaultScreenOfDisplay(m_dpy);
int s = DefaultScreen(m_dpy);
m_root = XCreateSimpleWindow(m_dpy, RootWindow(m_dpy,s),10,10,m_width,m_height,0,
BlackPixel(m_dpy, s), WhitePixel(m_dpy, s));
m_pix = XCreatePixmap(m_dpy, m_root, m_width, m_height, DefaultDepthOfScreen(scn));
Atom type = XInternAtom(m_dpy, "_NET_WM_WINDOW_TYPE", False);
Atom value = XInternAtom(m_dpy, "_NET_WM_WINDOW_TYPE_SPLASH", False);
XChangeProperty(m_dpy, m_root, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char*>(&value), 1);
imlib_context_set_display(m_dpy);
imlib_context_set_visual(DefaultVisualOfScreen(scn));
imlib_context_set_colormap(DefaultColormapOfScreen(scn));
imlib_context_set_drawable(m_pix);
imlib_render_image_on_drawable(0,0);
XSetWindowBackgroundPixmap(m_dpy, m_root, m_pix);
XClearWindow(m_dpy, m_root);
Atom wmDeleteMessage = XInternAtom(m_dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(m_dpy, m_root, &wmDeleteMessage, 1);
XMapWindow(m_dpy, m_root);
XFlush(m_dpy);
sleep(5);
XUnmapWindow(m_dpy, m_root);
}
and this program can have a splash with hello world alse I do not know how to jump out of the while(!done) so much thx to U
g++ -o test_chr test_chr.cpp -lX11
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
Display *d;
Window w;
XEvent e;
const char *msg = "Hello, World!";
int s;
bool done = false;
/* open connection with the server */
d = XOpenDisplay(NULL);
if (d == NULL)
{
fprintf(stderr, "Cannot open display\n");
exit(1);
}
s = DefaultScreen(d);
/* create window */
w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 480, 320, 0,BlackPixel(d, s), WhitePixel(d, s));
Atom type = XInternAtom(d,"_NET_WM_WINDOW_TYPE", False);
Atom value = XInternAtom(d,"_NET_WM_WINDOW_TYPE_SPLASH", False);
XChangeProperty(d, w, type, XA_ATOM, 32, PropModeReplace, reinterpret_cast<unsigned char*>(&value), 1);
/* register interest in the delete window message */
Atom wmDeleteMessage = XInternAtom(d, "WM_DELETE_WINDOW", False);
XSetWMProtocols(d, w, &wmDeleteMessage, 1);
/* select kind of events we are interested in */
XSelectInput(d, w, ExposureMask | KeyPressMask | StructureNotifyMask);
/* map (show) the window */
XMapWindow(d, w);
/* event loop */
while (!done)
{
XNextEvent(d, &e);
/* draw or redraw the window */
if (e.type == Expose)
{
XDrawString(d, w, DefaultGC(d, s), 50, 50, msg, strlen(msg));
}
/* exit on key press */
switch(e.type)
{
case KeyPress:
XDestroyWindow(d, w);
break;
case DestroyNotify:
done = true;
break;
case ClientMessage:
if (e.xclient.data.l[0] == wmDeleteMessage)
{
done = true;
}
break;
}
}
/* close connection to server */
XCloseDisplay(d);
return 0;
}