Home | History | Annotate | Download | only in unix
      1 
      2 /*
      3  * Copyright 2011 Google Inc.
      4  *
      5  * Use of this source code is governed by a BSD-style license that can be
      6  * found in the LICENSE file.
      7  */
      8 #include <X11/Xlib.h>
      9 #include <X11/Xatom.h>
     10 #include <X11/XKBlib.h>
     11 #include <GL/glx.h>
     12 #include <GL/gl.h>
     13 #include <GL/glu.h>
     14 
     15 #include "SkWindow.h"
     16 
     17 #include "SkBitmap.h"
     18 #include "SkCanvas.h"
     19 #include "SkColor.h"
     20 #include "SkEvent.h"
     21 #include "SkKey.h"
     22 #include "SkWindow.h"
     23 #include "XkeysToSkKeys.h"
     24 extern "C" {
     25     #include "keysym2ucs.h"
     26 }
     27 
     28 const int WIDTH = 500;
     29 const int HEIGHT = 500;
     30 
     31 // Determine which events to listen for.
     32 const long EVENT_MASK = StructureNotifyMask|ButtonPressMask|ButtonReleaseMask
     33         |ExposureMask|PointerMotionMask|KeyPressMask|KeyReleaseMask;
     34 
     35 SkOSWindow::SkOSWindow(void*)
     36     : fVi(nullptr)
     37     , fMSAASampleCount(0) {
     38     fUnixWindow.fDisplay = nullptr;
     39     fUnixWindow.fGLContext = nullptr;
     40     this->initWindow(0, nullptr);
     41     this->resize(WIDTH, HEIGHT);
     42 }
     43 
     44 SkOSWindow::~SkOSWindow() {
     45     this->internalCloseWindow();
     46 }
     47 
     48 void SkOSWindow::internalCloseWindow() {
     49     if (fUnixWindow.fDisplay) {
     50         this->detach();
     51         SkASSERT(fUnixWindow.fGc);
     52         XFreeGC(fUnixWindow.fDisplay, fUnixWindow.fGc);
     53         fUnixWindow.fGc = nullptr;
     54         XDestroyWindow(fUnixWindow.fDisplay, fUnixWindow.fWin);
     55         fVi = nullptr;
     56         XCloseDisplay(fUnixWindow.fDisplay);
     57         fUnixWindow.fDisplay = nullptr;
     58         fMSAASampleCount = 0;
     59     }
     60 }
     61 
     62 void SkOSWindow::initWindow(int requestedMSAASampleCount, AttachmentInfo* info) {
     63     if (fMSAASampleCount != requestedMSAASampleCount) {
     64         this->internalCloseWindow();
     65     }
     66     // presence of fDisplay means we already have a window
     67     if (fUnixWindow.fDisplay) {
     68         if (info) {
     69             if (fVi) {
     70                 glXGetConfig(fUnixWindow.fDisplay, fVi, GLX_SAMPLES_ARB, &info->fSampleCount);
     71                 glXGetConfig(fUnixWindow.fDisplay, fVi, GLX_STENCIL_SIZE, &info->fStencilBits);
     72             } else {
     73                 info->fSampleCount = 0;
     74                 info->fStencilBits = 0;
     75             }
     76         }
     77         return;
     78     }
     79     fUnixWindow.fDisplay = XOpenDisplay(nullptr);
     80     Display* dsp = fUnixWindow.fDisplay;
     81     if (nullptr == dsp) {
     82         SkDebugf("Could not open an X Display");
     83         return;
     84     }
     85     // Attempt to create a window that supports GL
     86     GLint att[] = {
     87         GLX_RGBA,
     88         GLX_DEPTH_SIZE, 24,
     89         GLX_DOUBLEBUFFER,
     90         GLX_STENCIL_SIZE, 8,
     91         None
     92     };
     93     SkASSERT(nullptr == fVi);
     94     if (requestedMSAASampleCount > 0) {
     95         static const GLint kAttCount = SK_ARRAY_COUNT(att);
     96         GLint msaaAtt[kAttCount + 4];
     97         memcpy(msaaAtt, att, sizeof(att));
     98         SkASSERT(None == msaaAtt[kAttCount - 1]);
     99         msaaAtt[kAttCount - 1] = GLX_SAMPLE_BUFFERS_ARB;
    100         msaaAtt[kAttCount + 0] = 1;
    101         msaaAtt[kAttCount + 1] = GLX_SAMPLES_ARB;
    102         msaaAtt[kAttCount + 2] = requestedMSAASampleCount;
    103         msaaAtt[kAttCount + 3] = None;
    104         fVi = glXChooseVisual(dsp, DefaultScreen(dsp), msaaAtt);
    105         fMSAASampleCount = requestedMSAASampleCount;
    106     }
    107     if (nullptr == fVi) {
    108         fVi = glXChooseVisual(dsp, DefaultScreen(dsp), att);
    109         fMSAASampleCount = 0;
    110     }
    111 
    112     if (fVi) {
    113         if (info) {
    114             glXGetConfig(dsp, fVi, GLX_SAMPLES_ARB, &info->fSampleCount);
    115             glXGetConfig(dsp, fVi, GLX_STENCIL_SIZE, &info->fStencilBits);
    116         }
    117         Colormap colorMap = XCreateColormap(dsp,
    118                                             RootWindow(dsp, fVi->screen),
    119                                             fVi->visual,
    120                                              AllocNone);
    121         XSetWindowAttributes swa;
    122         swa.colormap = colorMap;
    123         swa.event_mask = EVENT_MASK;
    124         fUnixWindow.fWin = XCreateWindow(dsp,
    125                                          RootWindow(dsp, fVi->screen),
    126                                          0, 0, // x, y
    127                                          WIDTH, HEIGHT,
    128                                          0, // border width
    129                                          fVi->depth,
    130                                          InputOutput,
    131                                          fVi->visual,
    132                                          CWEventMask | CWColormap,
    133                                          &swa);
    134     } else {
    135         if (info) {
    136             info->fSampleCount = 0;
    137             info->fStencilBits = 0;
    138         }
    139         // Create a simple window instead.  We will not be able to show GL
    140         fUnixWindow.fWin = XCreateSimpleWindow(dsp,
    141                                                DefaultRootWindow(dsp),
    142                                                0, 0,  // x, y
    143                                                WIDTH, HEIGHT,
    144                                                0,     // border width
    145                                                0,     // border value
    146                                                0);    // background value
    147     }
    148     this->mapWindowAndWait();
    149     fUnixWindow.fGc = XCreateGC(dsp, fUnixWindow.fWin, 0, nullptr);
    150 }
    151 
    152 static unsigned getModi(const XEvent& evt) {
    153     static const struct {
    154         unsigned    fXMask;
    155         unsigned    fSkMask;
    156     } gModi[] = {
    157         // X values found by experiment. Is there a better way?
    158         { 1,    kShift_SkModifierKey },
    159         { 4,    kControl_SkModifierKey },
    160         { 8,    kOption_SkModifierKey },
    161     };
    162 
    163     unsigned modi = 0;
    164     for (size_t i = 0; i < SK_ARRAY_COUNT(gModi); ++i) {
    165         if (evt.xkey.state & gModi[i].fXMask) {
    166             modi |= gModi[i].fSkMask;
    167         }
    168     }
    169     return modi;
    170 }
    171 
    172 static SkMSec gTimerDelay;
    173 
    174 static bool MyXNextEventWithDelay(Display* dsp, XEvent* evt) {
    175     // Check for pending events before entering the select loop. There might
    176     // be events in the in-memory queue but not processed yet.
    177     if (XPending(dsp)) {
    178         XNextEvent(dsp, evt);
    179         return true;
    180     }
    181 
    182     SkMSec ms = gTimerDelay;
    183     if (ms > 0) {
    184         int x11_fd = ConnectionNumber(dsp);
    185         fd_set input_fds;
    186         FD_ZERO(&input_fds);
    187         FD_SET(x11_fd, &input_fds);
    188 
    189         timeval tv;
    190         tv.tv_sec = ms / 1000;              // seconds
    191         tv.tv_usec = (ms % 1000) * 1000;    // microseconds
    192 
    193         if (!select(x11_fd + 1, &input_fds, nullptr, nullptr, &tv)) {
    194             if (!XPending(dsp)) {
    195                 return false;
    196             }
    197         }
    198     }
    199     XNextEvent(dsp, evt);
    200     return true;
    201 }
    202 
    203 static Atom wm_delete_window_message;
    204 
    205 SkOSWindow::NextXEventResult SkOSWindow::nextXEvent() {
    206     XEvent evt;
    207     Display* dsp = fUnixWindow.fDisplay;
    208 
    209     if (!MyXNextEventWithDelay(dsp, &evt)) {
    210         return kContinue_NextXEventResult;
    211     }
    212 
    213     switch (evt.type) {
    214         case Expose:
    215             if (0 == evt.xexpose.count) {
    216                 return kPaintRequest_NextXEventResult;
    217             }
    218             break;
    219         case ConfigureNotify:
    220             this->resize(evt.xconfigure.width, evt.xconfigure.height);
    221             break;
    222         case ButtonPress:
    223             if (evt.xbutton.button == Button1)
    224                 this->handleClick(evt.xbutton.x, evt.xbutton.y,
    225                             SkView::Click::kDown_State, nullptr, getModi(evt));
    226             break;
    227         case ButtonRelease:
    228             if (evt.xbutton.button == Button1)
    229                 this->handleClick(evt.xbutton.x, evt.xbutton.y,
    230                               SkView::Click::kUp_State, nullptr, getModi(evt));
    231             break;
    232         case MotionNotify:
    233             this->handleClick(evt.xmotion.x, evt.xmotion.y,
    234                            SkView::Click::kMoved_State, nullptr, getModi(evt));
    235             break;
    236         case KeyPress: {
    237             int shiftLevel = (evt.xkey.state & ShiftMask) ? 1 : 0;
    238             KeySym keysym = XkbKeycodeToKeysym(dsp, evt.xkey.keycode,
    239                                                0, shiftLevel);
    240             if (keysym == XK_Escape) {
    241                 return kQuitRequest_NextXEventResult;
    242             }
    243             this->handleKey(XKeyToSkKey(keysym));
    244             long uni = keysym2ucs(keysym);
    245             if (uni != -1) {
    246                 this->handleChar((SkUnichar) uni);
    247             }
    248             break;
    249         }
    250         case KeyRelease:
    251             this->handleKeyUp(XKeyToSkKey(XkbKeycodeToKeysym(dsp, evt.xkey.keycode, 0, 0)));
    252             break;
    253         case ClientMessage:
    254             if ((Atom)evt.xclient.data.l[0] == wm_delete_window_message) {
    255                 return kQuitRequest_NextXEventResult;
    256             }
    257             // fallthrough
    258         default:
    259             // Do nothing for other events
    260             break;
    261     }
    262     return kContinue_NextXEventResult;
    263 }
    264 
    265 void SkOSWindow::loop() {
    266     Display* dsp = fUnixWindow.fDisplay;
    267     if (nullptr == dsp) {
    268         return;
    269     }
    270     Window win = fUnixWindow.fWin;
    271 
    272     wm_delete_window_message = XInternAtom(dsp, "WM_DELETE_WINDOW", False);
    273     XSetWMProtocols(dsp, win, &wm_delete_window_message, 1);
    274 
    275     XSelectInput(dsp, win, EVENT_MASK);
    276 
    277     bool sentExposeEvent = false;
    278 
    279     for (;;) {
    280         SkEvent::ServiceQueueTimer();
    281 
    282         bool moreToDo = SkEvent::ProcessEvent();
    283 
    284         if (this->isDirty() && !sentExposeEvent) {
    285             sentExposeEvent = true;
    286 
    287             XEvent evt;
    288             sk_bzero(&evt, sizeof(evt));
    289             evt.type = Expose;
    290             evt.xexpose.display = dsp;
    291             XSendEvent(dsp, win, false, ExposureMask, &evt);
    292         }
    293 
    294         if (XPending(dsp) || !moreToDo) {
    295             switch (this->nextXEvent()) {
    296                 case kContinue_NextXEventResult:
    297                     break;
    298                 case kPaintRequest_NextXEventResult:
    299                     sentExposeEvent = false;
    300                     if (this->isDirty()) {
    301                         this->update(nullptr);
    302                     }
    303                     this->doPaint();
    304                     break;
    305                 case kQuitRequest_NextXEventResult:
    306                     return;
    307             }
    308         }
    309     }
    310 }
    311 
    312 void SkOSWindow::mapWindowAndWait() {
    313     SkASSERT(fUnixWindow.fDisplay);
    314     Display* dsp = fUnixWindow.fDisplay;
    315     Window win = fUnixWindow.fWin;
    316     XMapWindow(dsp, win);
    317 
    318     long eventMask = StructureNotifyMask;
    319     XSelectInput(dsp, win, eventMask);
    320 
    321     // Wait until screen is ready.
    322     XEvent evt;
    323     do {
    324         XNextEvent(dsp, &evt);
    325     } while(evt.type != MapNotify);
    326 
    327 }
    328 
    329 ////////////////////////////////////////////////
    330 
    331 // Some helper code to load the correct version of glXSwapInterval
    332 #define GLX_GET_PROC_ADDR(name) glXGetProcAddress(reinterpret_cast<const GLubyte*>((name)))
    333 #define EXT_WRANGLE(name, type, ...) \
    334     if (GLX_GET_PROC_ADDR(#name)) { \
    335         static type k##name; \
    336         if (!k##name) { \
    337             k##name = (type) GLX_GET_PROC_ADDR(#name); \
    338         } \
    339         k##name(__VA_ARGS__); \
    340         /*SkDebugf("using %s\n", #name);*/ \
    341         return; \
    342     }
    343 
    344 static void glXSwapInterval(Display* dsp, GLXDrawable drawable, int interval) {
    345     EXT_WRANGLE(glXSwapIntervalEXT, PFNGLXSWAPINTERVALEXTPROC, dsp, drawable, interval);
    346     EXT_WRANGLE(glXSwapIntervalMESA, PFNGLXSWAPINTERVALMESAPROC, interval);
    347     EXT_WRANGLE(glXSwapIntervalSGI, PFNGLXSWAPINTERVALSGIPROC, interval);
    348 }
    349 
    350 /////////////////////////////////////////////////////////////////////////
    351 
    352 bool SkOSWindow::attach(SkBackEndTypes, int msaaSampleCount, 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 
    381 void SkOSWindow::detach() {
    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 
    390 void SkOSWindow::present() {
    391     if (fUnixWindow.fDisplay && fUnixWindow.fGLContext) {
    392         glXSwapBuffers(fUnixWindow.fDisplay, fUnixWindow.fWin);
    393     }
    394 }
    395 
    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 
    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 
    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 
    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 
    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 
    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 
    511 void SkEvent::SignalNonEmptyQueue() {
    512     // nothing to do, since we spin on our event-queue, polling for XPending
    513 }
    514 
    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