aboutsummaryrefslogtreecommitdiff
path: root/xorg-server/hw/xwin/winclipboard/thread.c
blob: 20c473dd8a3147846c74dbf73a969d228f207868 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/*
 *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
 *Copyright (C) Colin Harrison 2005-2008
 *
 *Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 *"Software"), to deal in the Software without restriction, including
 *without limitation the rights to use, copy, modify, merge, publish,
 *distribute, sublicense, and/or sell copies of the Software, and to
 *permit persons to whom the Software is furnished to do so, subject to
 *the following conditions:
 *
 *The above copyright notice and this permission notice shall be
 *included in all copies or substantial portions of the Software.
 *
 *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
 *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *Except as contained in this notice, the name of the copyright holder(s)
 *and author(s) shall not be used in advertising or otherwise to promote
 *the sale, use or other dealings in this Software without prior written
 *authorization from the copyright holder(s) and author(s).
 *
 * Authors:	Harold L Hunt II
 *              Colin Harrison
 */

#ifdef HAVE_XWIN_CONFIG_H
#include <xwin-config.h>
#else
#define HAS_WINSOCK 1
#endif

/*
 * Including any server header might define the macro _XSERVER64 on 64 bit machines.
 * That macro must _NOT_ be defined for Xlib client code, otherwise bad things happen.
 * So let's undef that macro if necessary.
 */
#ifdef _XSERVER64
#undef _XSERVER64
#endif

#include <sys/types.h>
#include <signal.h>
#include <pthread.h>
#include "windisplay.h"
#ifdef __CYGWIN__
#include <errno.h>
#endif
#include "misc.h"
#include "winmsg.h"

#include <X11/Xatom.h>
#include <X11/extensions/Xfixes.h>
#include "winclipboard.h"
#include "internal.h"

/* Clipboard module constants */
#define WIN_CONNECT_RETRIES			40
#define WIN_CONNECT_DELAY			4
#define WIN_JMP_OKAY				0
#define WIN_JMP_ERROR_IO			2

#define WIN_CLIPBOARD_WINDOW_CLASS		"xwinclip"
#define WIN_CLIPBOARD_WINDOW_TITLE		"xwinclip"
#ifdef HAS_DEVWINDOWS
#define WIN_MSG_QUEUE_FNAME			"/dev/windows"
#endif

#ifdef _MSC_VER
#define snprintf _snprintf
#endif
/*
 * References to external symbols
 */

extern Bool g_fUnicodeClipboard;
extern Bool g_fClipboard;
extern Bool g_fClipboardStarted;
extern Bool g_fClipboardLaunched;
extern HWND g_hwndClipboard;
extern void *g_pClipboardDisplay;
extern Window g_iClipboardWindow;

/*
 * Global variables
 */

static jmp_buf g_jmpEntry;
static XIOErrorHandler g_winClipboardOldIOErrorHandler;
static pthread_t g_winClipboardProcThread;

int xfixes_event_base;
int xfixes_error_base;

Bool g_fUseUnicode = FALSE;

/*
 * Local function prototypes
 */

static HWND
winClipboardCreateMessagingWindow(Display *pDisplay, Window iWindow, ClipboardAtoms *atoms);

static int
 winClipboardErrorHandler(Display * pDisplay, XErrorEvent * pErr);

static int
 winClipboardIOErrorHandler(Display * pDisplay);

static void
winClipboardThreadExit(void *arg);

/*
 * Create X11 and Win32 messaging windows, and run message processing loop
 *
 * returns TRUE if shutdown was signalled to loop, FALSE if some error occurred
 */

Bool
winClipboardProc(Bool fUseUnicode, char *szDisplay)
{
    ClipboardAtoms atoms;
    int iReturn;
    HWND hwnd = NULL;
    int iConnectionNumber = 0;

#ifdef HAS_DEVWINDOWS
    int fdMessageQueue = 0;
#else
    struct timeval tvTimeout;
#endif
    fd_set fdsRead;
    int iMaxDescriptor;
    Display *pDisplay = NULL;
    Window iWindow = None;
    int iSelectError;
    Bool fShutDown = TRUE;
    static Bool fErrorHandlerSet = FALSE;

    pthread_cleanup_push(&winClipboardThreadExit, NULL);
    ClipboardConversionData data;

    winDebug("winClipboardProc - Hello\n");

    /* Save the Unicode support flag in a global */
    g_fUseUnicode = fUseUnicode;

    /* Allow multiple threads to access Xlib */
    if (XInitThreads() == 0) {
        ErrorF("winClipboardProc - XInitThreads failed.\n");
        goto thread_errorexit;
    }

    /* See if X supports the current locale */
    if (XSupportsLocale() == False) {
        ErrorF("winClipboardProc - Warning: Locale not supported by X.\n");
    }

    g_winClipboardProcThread = pthread_self();

    /* Set error handler */
    if (!fErrorHandlerSet) {
      XSetErrorHandler(winClipboardErrorHandler);
      g_winClipboardOldIOErrorHandler =
         XSetIOErrorHandler(winClipboardIOErrorHandler);
      fErrorHandlerSet = TRUE;
    }

    /* Set jump point for Error exits */
    iReturn = setjmp(g_jmpEntry);

    /* Check if we should continue operations */
    if (iReturn != WIN_JMP_ERROR_IO && iReturn != WIN_JMP_OKAY) {
        /* setjmp returned an unknown value, exit */
        ErrorF("winClipboardProc - setjmp returned: %d exiting\n", iReturn);
        goto thread_errorexit;
    }
    else if (iReturn == WIN_JMP_ERROR_IO) {
        /* TODO: Cleanup the Win32 window and free any allocated memory */
        ErrorF("winClipboardProc - setjmp returned for IO Error Handler.\n");
    }

    /* Make sure that the display opened */
    pDisplay = XOpenDisplay(szDisplay);
    if (pDisplay == NULL) {
        ErrorF("winClipboardProc - Failed opening the display, giving up\n");
        fShutDown = FALSE;
        goto thread_errorexit;
    }

    /* Save the display in the screen privates */
    g_pClipboardDisplay = pDisplay;

    winDebug ("winClipboardProc - XOpenDisplay () returned and "
           "successfully opened the display.\n");

    /* Get our connection number */
    iConnectionNumber = ConnectionNumber(pDisplay);

#ifdef HAS_DEVWINDOWS
    /* Open a file descriptor for the windows message queue */
    fdMessageQueue = open(WIN_MSG_QUEUE_FNAME, O_RDONLY);
    if (fdMessageQueue == -1) {
        ErrorF("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME);
        goto thread_errorexit;
    }

    /* Find max of our file descriptors */
    iMaxDescriptor = MAX(fdMessageQueue, iConnectionNumber) + 1;
#else
    iMaxDescriptor = iConnectionNumber + 1;
#endif

    if (!XFixesQueryExtension(pDisplay, &xfixes_event_base, &xfixes_error_base))
      ErrorF ("winClipboardProc - XFixes extension not present\n");

    /* Create atoms */
    atoms.atomClipboard = XInternAtom(pDisplay, "CLIPBOARD", False);
    atoms.atomLocalProperty = XInternAtom (pDisplay, "CYGX_CUT_BUFFER", False);
    atoms.atomUTF8String = XInternAtom (pDisplay, "UTF8_STRING", False);
    atoms.atomCompoundText = XInternAtom (pDisplay, "COMPOUND_TEXT", False);
    atoms.atomTargets = XInternAtom (pDisplay, "TARGETS", False);

    /* Create a messaging window */
    iWindow = XCreateSimpleWindow(pDisplay,
                                  DefaultRootWindow(pDisplay),
                                  1, 1,
                                  500, 500,
                                  0,
                                  BlackPixel(pDisplay, 0),
                                  BlackPixel(pDisplay, 0));
    if (iWindow == 0) {
        ErrorF("winClipboardProc - Could not create an X window.\n");
        goto thread_errorexit;
    }

    XStoreName(pDisplay, iWindow, "xwinclip");

    /* Select event types to watch */
    if (XSelectInput(pDisplay, iWindow, PropertyChangeMask) == BadWindow)
        ErrorF("winClipboardProc - XSelectInput generated BadWindow "
               "on messaging window\n");

    XFixesSelectSelectionInput (pDisplay,
                                iWindow,
                                XA_PRIMARY,
                                XFixesSetSelectionOwnerNotifyMask |
                                XFixesSelectionWindowDestroyNotifyMask |
                                XFixesSelectionClientCloseNotifyMask);

    XFixesSelectSelectionInput (pDisplay,
                                iWindow,
                                atoms.atomClipboard,
                                XFixesSetSelectionOwnerNotifyMask |
                                XFixesSelectionWindowDestroyNotifyMask |
                                XFixesSelectionClientCloseNotifyMask);

    /* Save the window in the screen privates */
    g_iClipboardWindow = iWindow;
    /* Initialize monitored selection state */
    winClipboardInitMonitoredSelections();
    /* Create Windows messaging window */
    hwnd = winClipboardCreateMessagingWindow(pDisplay, iWindow, &atoms);

    /* Save copy of HWND */
    g_hwndClipboard = hwnd;

    /* Assert ownership of selections if Win32 clipboard is owned */
    if (NULL != GetClipboardOwner()) {
        /* PRIMARY */
        iReturn = XSetSelectionOwner(pDisplay, XA_PRIMARY,
                                     iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, XA_PRIMARY) != iWindow) {
            ErrorF("winClipboardProc - Could not set PRIMARY owner\n");
            goto thread_errorexit;
        }

        /* CLIPBOARD */
        iReturn = XSetSelectionOwner(pDisplay, atoms.atomClipboard,
                                     iWindow, CurrentTime);
        if (iReturn == BadAtom || iReturn == BadWindow ||
            XGetSelectionOwner(pDisplay, atoms.atomClipboard) != iWindow) {
            ErrorF("winClipboardProc - Could not set CLIPBOARD owner\n");
            goto thread_errorexit;
        }
    }

    data.fUseUnicode = fUseUnicode;
    winDebug ("winClipboardProc - Started\n");
    /* Signal that the clipboard client has started */
    g_fClipboardStarted = TRUE;

    /* Loop for events */
    while (1) {

        /* Process X events */
        winClipboardFlushXEvents(hwnd,
                                 iWindow, pDisplay, &data, &atoms);

        /* Process Windows messages */
        if (!winClipboardFlushWindowsMessageQueue(hwnd)) {
          ErrorF("winClipboardProc - winClipboardFlushWindowsMessageQueue trapped "
                       "WM_QUIT message, exiting main loop.\n");
          break;
        }

        /* We need to ensure that all pending requests are sent */
        XFlush(pDisplay);

        /* Setup the file descriptor set */
        /*
         * NOTE: You have to do this before every call to select
         *       because select modifies the mask to indicate
         *       which descriptors are ready.
         */
        FD_ZERO(&fdsRead);
        FD_SET(iConnectionNumber, &fdsRead);
#ifdef HAS_DEVWINDOWS
        FD_SET(fdMessageQueue, &fdsRead);
#else
        tvTimeout.tv_sec = 0;
        tvTimeout.tv_usec = 100;
#endif

        /* Wait for a Windows event or an X event */
        iReturn = select(iMaxDescriptor,        /* Highest fds number */
                         &fdsRead,      /* Read mask */
                         NULL,  /* No write mask */
                         NULL,  /* No exception mask */
#ifdef HAS_DEVWINDOWS
                         NULL   /* No timeout */
#else
                         &tvTimeout     /* Set timeout */
#endif
            );

#ifndef HAS_WINSOCK
        iSelectError = errno;
#else
        iSelectError = WSAGetLastError();
#endif

        if (iReturn < 0) {
#ifndef HAS_WINSOCK
            if (iSelectError == EINTR)
#else
            if (iSelectError == WSAEINTR)
#endif
                continue;

            ErrorF("winClipboardProc - Call to select () failed: %d.  "
                   "Bailing.\n", iReturn);
            break;
        }

        if (FD_ISSET(iConnectionNumber, &fdsRead)) {
            winDebug
                ("winClipboardProc - X connection ready, pumping X event queue\n");
        }

#ifdef HAS_DEVWINDOWS
        /* Check for Windows event ready */
        if (FD_ISSET(fdMessageQueue, &fdsRead))
#else
        if (1)
#endif
        {
            winDebug
                ("winClipboardProc - /dev/windows ready, pumping Windows message queue\n");
        }

#ifdef HAS_DEVWINDOWS
        if (!(FD_ISSET(iConnectionNumber, &fdsRead)) &&
            !(FD_ISSET(fdMessageQueue, &fdsRead))) {
            winDebug("winClipboardProc - Spurious wake, select() returned %d\n", iReturn);
        }
#endif
    }

    /* Close our X window */
    if (pDisplay && iWindow) {
        iReturn = XDestroyWindow(pDisplay, iWindow);
        if (iReturn == BadWindow)
            ErrorF("winClipboardProc - XDestroyWindow returned BadWindow.\n");
#ifdef WINDBG
        else
            winDebug("winClipboardProc - XDestroyWindow succeeded.\n");
#endif
    }

#ifdef HAS_DEVWINDOWS
    /* Close our Win32 message handle */
    if (fdMessageQueue)
        close(fdMessageQueue);
#endif

#if 0
    /*
     * FIXME: XCloseDisplay hangs if we call it
     *
     * XCloseDisplay() calls XSync(), so any outstanding errors are reported.
     * If we are built into the server, this can deadlock if the server is
     * in the process of exiting and waiting for this thread to exit.
     */

    /* Discard any remaining events */
    XSync(pDisplay, TRUE);

    /* Select event types to watch */
    XSelectInput(pDisplay, DefaultRootWindow(pDisplay), None);

    /* Close our X display */
    if (pDisplay) {
        XCloseDisplay(pDisplay);
    }
#endif

  goto commonexit;

thread_errorexit:
    if (g_pClipboardDisplay && g_iClipboardWindow)
    {
        iReturn = XDestroyWindow (g_pClipboardDisplay, g_iClipboardWindow);
        if (iReturn == BadWindow)
            ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n");
#ifdef WINDBG
        else
            winDebug ("winClipboardProc - XDestroyWindow succeeded.\n");
#endif
    }
    winDebug ("Clipboard thread died.\n");

commonexit:
    g_iClipboardWindow = None;
    g_pClipboardDisplay = NULL;
    g_fClipboardLaunched = FALSE;
    g_fClipboardStarted = FALSE;

    pthread_cleanup_pop(0);

    return fShutDown;
}

/*
 * Create the Windows window that we use to receive Windows messages
 */

static HWND
winClipboardCreateMessagingWindow(Display *pDisplay, Window iWindow, ClipboardAtoms *atoms)
{
    WNDCLASSEX wc;
    ClipboardWindowCreationParams cwcp;
    HWND hwnd;

    /* Setup our window class */
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = winClipboardWindowProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = GetModuleHandle(NULL);
    wc.hIcon = 0;
    wc.hCursor = 0;
    wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = WIN_CLIPBOARD_WINDOW_CLASS;
    wc.hIconSm = 0;
    RegisterClassEx(&wc);

    /* Information to be passed to WM_CREATE */
    cwcp.pClipboardDisplay = pDisplay;
    cwcp.iClipboardWindow = iWindow;
    cwcp.atoms = atoms;

    /* Create the window */
    hwnd = CreateWindowExA(0,   /* Extended styles */
                           WIN_CLIPBOARD_WINDOW_CLASS,  /* Class name */
                           WIN_CLIPBOARD_WINDOW_TITLE,  /* Window name */
                           WS_OVERLAPPED,       /* Not visible anyway */
                           CW_USEDEFAULT,       /* Horizontal position */
                           CW_USEDEFAULT,       /* Vertical position */
                           CW_USEDEFAULT,       /* Right edge */
                           CW_USEDEFAULT,       /* Bottom edge */
                           (HWND) NULL, /* No parent or owner window */
                           (HMENU) NULL,        /* No menu */
                           GetModuleHandle(NULL),       /* Instance handle */
                           &cwcp);       /* Creation data */
    assert(hwnd != NULL);

    /* I'm not sure, but we may need to call this to start message processing */
    ShowWindow(hwnd, SW_HIDE);

    /* Similarly, we may need a call to this even though we don't paint */
    UpdateWindow(hwnd);

    return hwnd;
}

/*
 * winClipboardErrorHandler - Our application specific error handler
 */

static int
winClipboardErrorHandler(Display * pDisplay, XErrorEvent * pErr)
{
    char pszErrorMsg[100];

    XGetErrorText(pDisplay, pErr->error_code, pszErrorMsg, sizeof(pszErrorMsg));
    ErrorF("winClipboardErrorHandler - ERROR: \n\t%s\n"
          "  errorCode %d\n"
          "  serial %lu\n"
          "  resourceID 0x%x\n"
          "  majorCode %d\n"
          "  minorCode %d\n"
          , pszErrorMsg
          , pErr->error_code
          , pErr->serial
          , pErr->resourceid
          , pErr->request_code
          , pErr->minor_code);
    return 0;
}

/*
 * winClipboardIOErrorHandler - Our application specific IO error handler
 */

static int
winClipboardIOErrorHandler(Display * pDisplay)
{
    ErrorF("winClipboardIOErrorHandler!\n");

    if (pthread_equal(pthread_self(), g_winClipboardProcThread)) {
        /* Restart at the main entry point */
        longjmp(g_jmpEntry, WIN_JMP_ERROR_IO);
    }

    if (g_winClipboardOldIOErrorHandler)
        g_winClipboardOldIOErrorHandler(pDisplay);

    return 0;
}

/*
 * winClipboardThreadExit - Thread exit handler
 */

static void
winClipboardThreadExit(void *arg)
{
  /* clipboard thread has exited, stop server as well */
  AbortDDX(EXIT_ERR_ABORT);
  TerminateProcess(GetCurrentProcess(),1);
}


void
winFixClipboardChain(int Removed)
{
    if (g_fClipboard && g_hwndClipboard) {
        PostMessage (g_hwndClipboard, WM_WM_REINIT, Removed, 0);
    }
}