1 /*
2 * Copyright 2011 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7 #include <X11/Xlib.h>
8 #include <X11/Xatom.h>
9 #include <X11/XKBlib.h>
10 #include <GL/glx.h>
11 #include <GL/gl.h>
12 #include <GL/glu.h>
13
14 #include "SkWindow.h"
15
16 #include "SkBitmap.h"
17 #include "SkCanvas.h"
18 #include "SkColor.h"
19 #include "SkEvent.h"
20 #include "SkKey.h"
21 #include "SkWindow.h"
22 #include "XkeysToSkKeys.h"
23 extern "C" {
24 #include "keysym2ucs.h"
25 }
26
27 const int WIDTH = 500;
28 const int HEIGHT = 500;
29
30 // Determine which events to listen for.
31 const long EVENT_MASK = StructureNotifyMask|ButtonPressMask|ButtonReleaseMask
32 |ExposureMask|PointerMotionMask|KeyPressMask|KeyReleaseMask;
33
SkOSWindow(void *)34 SkOSWindow::SkOSWindow(void*)
35 : fVi(nullptr)
36 , fMSAASampleCount(0) {
37 fUnixWindow.fDisplay = nullptr;
38 fUnixWindow.fGLContext = nullptr;
39 this->initWindow(0, nullptr);
40 this->resize(WIDTH, HEIGHT);
41 }
42
~SkOSWindow()43 SkOSWindow::~SkOSWindow() {
44 this->internalCloseWindow();
45 }
46
internalCloseWindow()47 void SkOSWindow::internalCloseWindow() {
48 if (fUnixWindow.fDisplay) {
49 this->release();
50 SkASSERT(fUnixWindow.fGc);
51 XFreeGC(fUnixWindow.fDisplay, fUnixWindow.fGc);
52 fUnixWindow.fGc = nullptr;
53 XDestroyWindow(fUnixWindow.fDisplay, fUnixWindow.fWin);
54 fVi = nullptr;
55 XCloseDisplay(fUnixWindow.fDisplay);
56 fUnixWindow.fDisplay = nullptr;
57 fMSAASampleCount = 0;
58 }
59 }
60
initWindow(int requestedMSAASampleCount,AttachmentInfo * info)61 void SkOSWindow::initWindow(int requestedMSAASampleCount, AttachmentInfo* info) {
62 if (fMSAASampleCount != requestedMSAASampleCount) {
63 this->internalCloseWindow();
64 }
65 // presence of fDisplay means we already have a window
66 if (fUnixWindow.fDisplay) {
67 if (info) {
68 if (fVi) {
69 glXGetConfig(fUnixWindow.fDisplay, fVi, GLX_SAMPLES_ARB, &info->fSampleCount);
70 glXGetConfig(fUnixWindow.fDisplay, fVi, GLX_STENCIL_SIZE, &info->fStencilBits);
71 } else {
72 info->fSampleCount = 0;
73 info->fStencilBits = 0;
74 }
75 }
76 return;
77 }
78 fUnixWindow.fDisplay = XOpenDisplay(nullptr);
79 Display* dsp = fUnixWindow.fDisplay;
80 if (nullptr == dsp) {
81 SkDebugf("Could not open an X Display");
82 return;
83 }
84 // Attempt to create a window that supports GL
85 GLint att[] = {
86 GLX_RGBA,
87 GLX_DEPTH_SIZE, 24,
88 GLX_DOUBLEBUFFER,
89 GLX_STENCIL_SIZE, 8,
90 None
91 };
92 SkASSERT(nullptr == fVi);
93 if (requestedMSAASampleCount > 0) {
94 static const GLint kAttCount = SK_ARRAY_COUNT(att);
95 GLint msaaAtt[kAttCount + 4];
96 memcpy(msaaAtt, att, sizeof(att));
97 SkASSERT(None == msaaAtt[kAttCount - 1]);
98 msaaAtt[kAttCount - 1] = GLX_SAMPLE_BUFFERS_ARB;
99 msaaAtt[kAttCount + 0] = 1;
100 msaaAtt[kAttCount + 1] = GLX_SAMPLES_ARB;
101 msaaAtt[kAttCount + 2] = requestedMSAASampleCount;
102 msaaAtt[kAttCount + 3] = None;
103 fVi = glXChooseVisual(dsp, DefaultScreen(dsp), msaaAtt);
104 fMSAASampleCount = requestedMSAASampleCount;
105 }
106 if (nullptr == fVi) {
107 fVi = glXChooseVisual(dsp, DefaultScreen(dsp), att);
108 fMSAASampleCount = 0;
109 }
110
111 if (fVi) {
112 if (info) {
113 glXGetConfig(dsp, fVi, GLX_SAMPLES_ARB, &info->fSampleCount);
114 glXGetConfig(dsp, fVi, GLX_STENCIL_SIZE, &info->fStencilBits);
115 }
116 Colormap colorMap = XCreateColormap(dsp,
117 RootWindow(dsp, fVi->screen),
118 fVi->visual,
119 AllocNone);
120 XSetWindowAttributes swa;
121 swa.colormap = colorMap;
122 swa.event_mask = EVENT_MASK;
123 fUnixWindow.fWin = XCreateWindow(dsp,
124 RootWindow(dsp, fVi->screen),
125 0, 0, // x, y
126 WIDTH, HEIGHT,
127 0, // border width
128 fVi->depth,
129 InputOutput,
130 fVi->visual,
131 CWEventMask | CWColormap,
132 &swa);
133 } else {
134 if (info) {
135 info->fSampleCount = 0;
136 info->fStencilBits = 0;
137 }
138 // Create a simple window instead. We will not be able to show GL
139 fUnixWindow.fWin = XCreateSimpleWindow(dsp,
140 DefaultRootWindow(dsp),
141 0, 0, // x, y
142 WIDTH, HEIGHT,
143 0, // border width
144 0, // border value
145 0); // background value
146 }
147 this->mapWindowAndWait();
148 fUnixWindow.fGc = XCreateGC(dsp, fUnixWindow.fWin, 0, nullptr);
149 }
150
getModi(const XEvent & evt)151 static unsigned getModi(const XEvent& evt) {
152 static const struct {
153 unsigned fXMask;
154 unsigned fSkMask;
155 } gModi[] = {
156 // X values found by experiment. Is there a better way?
157 { 1, kShift_SkModifierKey },
158 { 4, kControl_SkModifierKey },
159 { 8, kOption_SkModifierKey },
160 };
161
162 unsigned modi = 0;
163 for (size_t i = 0; i < SK_ARRAY_COUNT(gModi); ++i) {
164 if (evt.xkey.state & gModi[i].fXMask) {
165 modi |= gModi[i].fSkMask;
166 }
167 }
168 return modi;
169 }
170
171 static SkMSec gTimerDelay;
172
MyXNextEventWithDelay(Display * dsp,XEvent * evt)173 static bool MyXNextEventWithDelay(Display* dsp, XEvent* evt) {
174 // Check for pending events before entering the select loop. There might
175 // be events in the in-memory queue but not processed yet.
176 if (XPending(dsp)) {
177 XNextEvent(dsp, evt);
178 return true;
179 }
180
181 SkMSec ms = gTimerDelay;
182 if (ms > 0) {
183 int x11_fd = ConnectionNumber(dsp);
184 fd_set input_fds;
185 FD_ZERO(&input_fds);
186 FD_SET(x11_fd, &input_fds);
187
188 timeval tv;
189 tv.tv_sec = ms / 1000; // seconds
190 tv.tv_usec = (ms % 1000) * 1000; // microseconds
191
192 if (!select(x11_fd + 1, &input_fds, nullptr, nullptr, &tv)) {
193 if (!XPending(dsp)) {
194 return false;
195 }
196 }
197 }
198 XNextEvent(dsp, evt);
199 return true;
200 }
201
202 static Atom wm_delete_window_message;
203
nextXEvent()204 SkOSWindow::NextXEventResult SkOSWindow::nextXEvent() {
205 XEvent evt;
206 Display* dsp = fUnixWindow.fDisplay;
207
208 if (!MyXNextEventWithDelay(dsp, &evt)) {
209 return kContinue_NextXEventResult;
210 }
211
212 switch (evt.type) {
213 case Expose:
214 if (0 == evt.xexpose.count) {
215 return kPaintRequest_NextXEventResult;
216 }
217 break;
218 case ConfigureNotify:
219 this->resize(evt.xconfigure.width, evt.xconfigure.height);
220 break;
221 case ButtonPress:
222 if (evt.xbutton.button == Button1)
223 this->handleClick(evt.xbutton.x, evt.xbutton.y,
224 SkView::Click::kDown_State, nullptr, getModi(evt));
225 break;
226 case ButtonRelease:
227 if (evt.xbutton.button == Button1)
228 this->handleClick(evt.xbutton.x, evt.xbutton.y,
229 SkView::Click::kUp_State, nullptr, getModi(evt));
230 break;
231 case MotionNotify:
232 this->handleClick(evt.xmotion.x, evt.xmotion.y,
233 SkView::Click::kMoved_State, nullptr, getModi(evt));
234 break;
235 case KeyPress: {
236 int shiftLevel = (evt.xkey.state & ShiftMask) ? 1 : 0;
237 KeySym keysym = XkbKeycodeToKeysym(dsp, evt.xkey.keycode,
238 0, shiftLevel);
239 if (keysym == XK_Escape) {
240 return kQuitRequest_NextXEventResult;
241 }
242 this->handleKey(XKeyToSkKey(keysym));
243 long uni = keysym2ucs(keysym);
244 if (uni != -1) {
245 this->handleChar((SkUnichar) uni);
246 }
247 break;
248 }
249 case KeyRelease:
250 this->handleKeyUp(XKeyToSkKey(XkbKeycodeToKeysym(dsp, evt.xkey.keycode, 0, 0)));
251 break;
252 case ClientMessage:
253 if ((Atom)evt.xclient.data.l[0] == wm_delete_window_message) {
254 return kQuitRequest_NextXEventResult;
255 }
256 // fallthrough
257 default:
258 // Do nothing for other events
259 break;
260 }
261 return kContinue_NextXEventResult;
262 }
263
loop()264 void SkOSWindow::loop() {
265 Display* dsp = fUnixWindow.fDisplay;
266 if (nullptr == dsp) {
267 return;
268 }
269 Window win = fUnixWindow.fWin;
270
271 wm_delete_window_message = XInternAtom(dsp, "WM_DELETE_WINDOW", False);
272 XSetWMProtocols(dsp, win, &wm_delete_window_message, 1);
273
274 XSelectInput(dsp, win, EVENT_MASK);
275
276 bool sentExposeEvent = false;
277
278 for (;;) {
279 SkEvent::ServiceQueueTimer();
280
281 bool moreToDo = SkEvent::ProcessEvent();
282
283 if (this->isDirty() && !sentExposeEvent) {
284 sentExposeEvent = true;
285
286 XEvent evt;
287 sk_bzero(&evt, sizeof(evt));
288 evt.type = Expose;
289 evt.xexpose.display = dsp;
290 XSendEvent(dsp, win, false, ExposureMask, &evt);
291 }
292
293 if (XPending(dsp) || !moreToDo) {
294 switch (this->nextXEvent()) {
295 case kContinue_NextXEventResult:
296 break;
297 case kPaintRequest_NextXEventResult:
298 sentExposeEvent = false;
299 if (this->isDirty()) {
300 this->update(nullptr);
301 }
302 this->doPaint();
303 break;
304 case kQuitRequest_NextXEventResult:
305 return;
306 }
307 }
308 }
309 }
310
mapWindowAndWait()311 void SkOSWindow::mapWindowAndWait() {
312 SkASSERT(fUnixWindow.fDisplay);
313 Display* dsp = fUnixWindow.fDisplay;
314 Window win = fUnixWindow.fWin;
315 XMapWindow(dsp, win);
316
317 long eventMask = StructureNotifyMask;
318 XSelectInput(dsp, win, eventMask);
319
320 // Wait until screen is ready.
321 XEvent evt;
322 do {
323 XNextEvent(dsp, &evt);
324 } while(evt.type != MapNotify);
325
326 }
327
328 ////////////////////////////////////////////////
329
330 // Some helper code to load the correct version of glXSwapInterval
331 #define GLX_GET_PROC_ADDR(name) glXGetProcAddress(reinterpret_cast<const GLubyte*>((name)))
332 #define EXT_WRANGLE(name, type, ...) \
333 if (GLX_GET_PROC_ADDR(#name)) { \
334 static type k##name; \
335 if (!k##name) { \
336 k##name = (type) GLX_GET_PROC_ADDR(#name); \
337 } \
338 k##name(__VA_ARGS__); \
339 /*SkDebugf("using %s\n", #name);*/ \
340 return; \
341 }
342
glXSwapInterval(Display * dsp,GLXDrawable drawable,int interval)343 static void glXSwapInterval(Display* dsp, GLXDrawable drawable, int interval) {
344 EXT_WRANGLE(glXSwapIntervalEXT, PFNGLXSWAPINTERVALEXTPROC, dsp, drawable, interval);
345 EXT_WRANGLE(glXSwapIntervalMESA, PFNGLXSWAPINTERVALMESAPROC, interval);
346 EXT_WRANGLE(glXSwapIntervalSGI, PFNGLXSWAPINTERVALSGIPROC, interval);
347 }
348
349 /////////////////////////////////////////////////////////////////////////
350
attach(SkBackEndTypes,int msaaSampleCount,bool deepColor,AttachmentInfo * info)351 bool SkOSWindow::attach(SkBackEndTypes, int msaaSampleCount, bool deepColor,
352 AttachmentInfo* info) {
353 this->initWindow(msaaSampleCount, info);
354
355 if (nullptr == fUnixWindow.fDisplay) {
356 return false;
357 }
358 if (nullptr == fUnixWindow.fGLContext) {
359 SkASSERT(fVi);
360
361 fUnixWindow.fGLContext = glXCreateContext(fUnixWindow.fDisplay,
362 fVi,
363 nullptr,
364 GL_TRUE);
365 if (nullptr == fUnixWindow.fGLContext) {
366 return false;
367 }
368 }
369 glXMakeCurrent(fUnixWindow.fDisplay,
370 fUnixWindow.fWin,
371 fUnixWindow.fGLContext);
372 glViewport(0, 0,
373 SkScalarRoundToInt(this->width()),
374 SkScalarRoundToInt(this->height()));
375 glClearColor(0, 0, 0, 0);
376 glClearStencil(0);
377 glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
378 return true;
379 }
380
release()381 void SkOSWindow::release() {
382 if (nullptr == fUnixWindow.fDisplay || nullptr == fUnixWindow.fGLContext) {
383 return;
384 }
385 glXMakeCurrent(fUnixWindow.fDisplay, None, nullptr);
386 glXDestroyContext(fUnixWindow.fDisplay, fUnixWindow.fGLContext);
387 fUnixWindow.fGLContext = nullptr;
388 }
389
present()390 void SkOSWindow::present() {
391 if (fUnixWindow.fDisplay && fUnixWindow.fGLContext) {
392 glXSwapBuffers(fUnixWindow.fDisplay, fUnixWindow.fWin);
393 }
394 }
395
onSetTitle(const char title[])396 void SkOSWindow::onSetTitle(const char title[]) {
397 if (nullptr == fUnixWindow.fDisplay) {
398 return;
399 }
400 XTextProperty textProp;
401 textProp.value = (unsigned char*)title;
402 textProp.format = 8;
403 textProp.nitems = strlen((char*)textProp.value);
404 textProp.encoding = XA_STRING;
405 XSetWMName(fUnixWindow.fDisplay, fUnixWindow.fWin, &textProp);
406 }
407
convertBitmapToXImage(XImage & image,const SkBitmap & bitmap)408 static bool convertBitmapToXImage(XImage& image, const SkBitmap& bitmap) {
409 sk_bzero(&image, sizeof(image));
410
411 int bitsPerPixel = bitmap.bytesPerPixel() * 8;
412 image.width = bitmap.width();
413 image.height = bitmap.height();
414 image.format = ZPixmap;
415 image.data = (char*) bitmap.getPixels();
416 image.byte_order = LSBFirst;
417 image.bitmap_unit = bitsPerPixel;
418 image.bitmap_bit_order = LSBFirst;
419 image.bitmap_pad = bitsPerPixel;
420 image.depth = 24;
421 image.bytes_per_line = bitmap.rowBytes() - bitmap.width() * 4;
422 image.bits_per_pixel = bitsPerPixel;
423 return XInitImage(&image);
424 }
425
doPaint()426 void SkOSWindow::doPaint() {
427 if (nullptr == fUnixWindow.fDisplay) {
428 return;
429 }
430 // If we are drawing with GL, we don't need XPutImage.
431 if (fUnixWindow.fGLContext) {
432 return;
433 }
434 // Draw the bitmap to the screen.
435 const SkBitmap& bitmap = getBitmap();
436 int width = bitmap.width();
437 int height = bitmap.height();
438
439 XImage image;
440 if (!convertBitmapToXImage(image, bitmap)) {
441 return;
442 }
443
444 XPutImage(fUnixWindow.fDisplay,
445 fUnixWindow.fWin,
446 fUnixWindow.fGc,
447 &image,
448 0, 0, // src x,y
449 0, 0, // dst x,y
450 width, height);
451 }
452
453 enum {
454 _NET_WM_STATE_REMOVE =0,
455 _NET_WM_STATE_ADD = 1,
456 _NET_WM_STATE_TOGGLE =2
457 };
458
makeFullscreen()459 bool SkOSWindow::makeFullscreen() {
460 Display* dsp = fUnixWindow.fDisplay;
461 if (nullptr == dsp) {
462 return false;
463 }
464
465 // Full screen
466 Atom wm_state = XInternAtom(dsp, "_NET_WM_STATE", False);
467 Atom fullscreen = XInternAtom(dsp, "_NET_WM_STATE_FULLSCREEN", False);
468
469 XEvent evt;
470 sk_bzero(&evt, sizeof(evt));
471 evt.type = ClientMessage;
472 evt.xclient.window = fUnixWindow.fWin;
473 evt.xclient.message_type = wm_state;
474 evt.xclient.format = 32;
475 evt.xclient.data.l[0] = _NET_WM_STATE_ADD;
476 evt.xclient.data.l[1] = fullscreen;
477 evt.xclient.data.l[2] = 0;
478
479 XSendEvent(dsp, DefaultRootWindow(dsp), False,
480 SubstructureRedirectMask | SubstructureNotifyMask, &evt);
481 return true;
482 }
483
setVsync(bool vsync)484 void SkOSWindow::setVsync(bool vsync) {
485 if (fUnixWindow.fDisplay && fUnixWindow.fGLContext && fUnixWindow.fWin) {
486 int swapInterval = vsync ? 1 : 0;
487 glXSwapInterval(fUnixWindow.fDisplay, fUnixWindow.fWin, swapInterval);
488 }
489 }
490
closeWindow()491 void SkOSWindow::closeWindow() {
492 Display* dsp = fUnixWindow.fDisplay;
493 if (nullptr == dsp) {
494 return;
495 }
496
497 XEvent evt;
498 sk_bzero(&evt, sizeof(evt));
499 evt.type = ClientMessage;
500 evt.xclient.message_type = XInternAtom(dsp, "WM_PROTOCOLS", true);
501 evt.xclient.window = fUnixWindow.fWin;
502 evt.xclient.format = 32;
503 evt.xclient.data.l[0] = XInternAtom(dsp, "WM_DELETE_WINDOW", false);
504 evt.xclient.data.l[1] = CurrentTime;
505
506 XSendEvent(dsp, fUnixWindow.fWin, false, NoEventMask, &evt);
507 }
508
509 ///////////////////////////////////////////////////////////////////////////////
510
SignalNonEmptyQueue()511 void SkEvent::SignalNonEmptyQueue() {
512 // nothing to do, since we spin on our event-queue, polling for XPending
513 }
514
SignalQueueTimer(SkMSec delay)515 void SkEvent::SignalQueueTimer(SkMSec delay) {
516 // just need to record the delay time. We handle waking up for it in
517 // MyXNextEventWithDelay()
518 gTimerDelay = delay;
519 }
520