I want to write a GTK application that will show a thumbnail, or preview image of a window, or the root window (in x11 term, maybe can also be called the desktop). Could this be possible in GTK (2, or 3, or gtk+)? What API can i use to do this?
Hello, thanks for asking that, that’s a great question with a bit of a complicated answer. GTK alone cannot do this, because it only handles drawing the GUI for applications. Capturing images from the desktop or from other applications requires interaction with the window system. How you do it somewhat depends on your platform and what you’re trying to do.
If you use X11 and GTK3, the simplest way may be to use gdk_x11_get_default_root_xwindow combined with XGetImage. This is an older, slower method usually used for screenshots and it may work for simple cases. But it is not recommended if you want to show a live thumbnail, for example if you expect to see a video player working at full speed in the thumbnail. The XSHM API can be used to perform faster screen capture but it is harder to use. The DRI3 API can do it fastest out of all of the X11 APIs, but that is also the hardest one to use.
Note that these are not supported on Wayland for security reasons. If you want to support Wayland, you will maybe want to use the ScreenCast portal API which is a D-Bus API. This can work for capturing the desktop or a few windows that the user chooses, but it may be inadequate for trying to capture a large number of individual window thumbnails at the same time.
If you want to do something similar to how GNOME shows thumbnails in the activities overview and app switcher (Alt+Tab) then you will likely want to create a shell extension. A shell extension of this type will work in both X11 and Wayland, but is very different from writing a GTK app. It should also be even faster than trying to do this in an app, because a shell extension has direct access to the window manager’s compositing process, and does not need to wait for the compositor to transfer frames to it like an external app does. Hopefully that helps to at least clear a few things up? Let me know if you need clarification.
Well, you would probably load the XImage in with GdkPixbuf, but I just remembered something else. You can use gdk_get_default_root_window in combination with gdk_pixbuf_get_from_window to capture from the root window, I think that still works with GTK3 (but not GTK4). For other windows you will likely still have to use XQueryTree from Xlib to find them, and then you can use gdk_x11_window_foreign_new_for_display to gdk_pixbuf_get_from_window get a pixmap.