Now it works with XCB, but code is a little ugly.