2dcairoawesome-wm

How to cache a drawn surface in cairo and make it use that instead of redrawing it?


I'm writing an alternative widget library for AwesomeWM. In this project, I would like to give the user some functions for manipulating nodes, but some operations are easier to optimize than others.

For example, if someone scales an element down, then maybe the element has to be redrawn, and I'll have to mark the dirty areas for redraw on the parent, so not much I can optimize.

But if translate an element in the layout, especially an element on which something very expensive was drawn, for example a trigonometric math function that I used to graph a bunch of points on the surface, then it would be much nicer to store the surface somewhere, tell cairo to use that when redrawing, and mark the dirty areas for redraw on the parent.

My question is: can I cache a surface and make cairo use it later instead of redrawing it every time?
(Example code would be much appreciated. I'm new to cairo.)


Solution

  • Yes, it can be done. Look at the lib/wibox/container/background.lua from the main codebase for how to do it with a recording surface. Look in my old github (github.com/elv13) modules for how to do it with set_source_surface. Keep in mind that a widget has to be very expensive to redraw for this to be worth it. Normally, it causes more problems than it solves. If you manually paint, also make sure your origin is aligned to a pixel, otherwise it looks blurry.