winex11: Make sure that all glX functions are called under the X11 lock.
[wine] / dlls / winex11.drv / xdnd.c
1 /*
2  * XDND handler code
3  *
4  * Copyright 2003 Ulrich Czekalla
5  * Copyright 2007 Damjan Jovanovic
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <string.h>
26 #ifdef HAVE_UNISTD_H
27 # include <unistd.h>
28 #endif
29 #include <stdarg.h>
30 #include <stdio.h>
31
32 #include "windef.h"
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "winuser.h"
36
37 #include "x11drv.h"
38 #include "shlobj.h"  /* DROPFILES */
39
40 #include "wine/unicode.h"
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(xdnd);
44
45 /* Maximum wait time for selection notify */
46 #define SELECTION_RETRIES 500  /* wait for .1 seconds */
47 #define SELECTION_WAIT    1000 /* us */
48
49 typedef struct tagXDNDDATA
50 {
51     int cf_win;
52     Atom cf_xdnd;
53     void *data;
54     unsigned int size;
55     struct tagXDNDDATA *next;
56 } XDNDDATA, *LPXDNDDATA;
57
58 static LPXDNDDATA XDNDData = NULL;
59 static POINT XDNDxy = { 0, 0 };
60
61 static void X11DRV_XDND_InsertXDNDData(int property, int format, void* data, unsigned int len);
62 static int X11DRV_XDND_DeconstructTextURIList(int property, void* data, int len);
63 static int X11DRV_XDND_DeconstructTextPlain(int property, void* data, int len);
64 static int X11DRV_XDND_DeconstructTextHTML(int property, void* data, int len);
65 static int X11DRV_XDND_MapFormat(unsigned int property, unsigned char *data, int len);
66 static void X11DRV_XDND_ResolveProperty(Display *display, Window xwin, Time tm,
67     Atom *types, unsigned long *count);
68 static void X11DRV_XDND_SendDropFiles(HWND hwnd);
69 static void X11DRV_XDND_FreeDragDropOp(void);
70 static unsigned int X11DRV_XDND_UnixToDos(char** lpdest, char* lpsrc, int len);
71 static WCHAR* X11DRV_XDND_URIToDOS(char *encodedURI);
72
73 static CRITICAL_SECTION xdnd_cs;
74 static CRITICAL_SECTION_DEBUG critsect_debug =
75 {
76     0, 0, &xdnd_cs,
77     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
78       0, 0, { (DWORD_PTR)(__FILE__ ": xdnd_cs") }
79 };
80 static CRITICAL_SECTION xdnd_cs = { &critsect_debug, -1, 0, 0, 0, 0 };
81
82
83 /**************************************************************************
84  * X11DRV_XDND_EnterEvent
85  *
86  * Handle an XdndEnter event.
87  */
88 void X11DRV_XDND_EnterEvent( HWND hWnd, XClientMessageEvent *event )
89 {
90     Atom *xdndtypes;
91     unsigned long count = 0;
92
93     TRACE("ver(%ld) check-XdndTypeList(%ld) data=%ld,%ld,%ld,%ld,%ld\n",
94           (event->data.l[1] & 0xFF000000) >> 24, (event->data.l[1] & 1),
95           event->data.l[0], event->data.l[1], event->data.l[2],
96           event->data.l[3], event->data.l[4]);
97
98     /* If the source supports more than 3 data types we retrieve
99      * the entire list. */
100     if (event->data.l[1] & 1)
101     {
102         Atom acttype;
103         int actfmt;
104         unsigned long bytesret;
105
106         /* Request supported formats from source window */
107         wine_tsx11_lock();
108         XGetWindowProperty(event->display, event->data.l[0], x11drv_atom(XdndTypeList),
109                            0, 65535, FALSE, AnyPropertyType, &acttype, &actfmt, &count,
110                            &bytesret, (unsigned char**)&xdndtypes);
111         wine_tsx11_unlock();
112     }
113     else
114     {
115         count = 3;
116         xdndtypes = (Atom*) &event->data.l[2];
117     }
118
119     if (TRACE_ON(xdnd))
120     {
121         unsigned int i = 0;
122
123         wine_tsx11_lock();
124         for (; i < count; i++)
125         {
126             if (xdndtypes[i] != 0)
127             {
128                 char * pn = XGetAtomName(event->display, xdndtypes[i]);
129                 TRACE("XDNDEnterAtom %ld: %s\n", xdndtypes[i], pn);
130                 XFree(pn);
131             }
132         }
133         wine_tsx11_unlock();
134     }
135
136     /* Do a one-time data read and cache results */
137     X11DRV_XDND_ResolveProperty(event->display, event->window,
138                                 event->data.l[1], xdndtypes, &count);
139
140     if (event->data.l[1] & 1)
141         XFree(xdndtypes);
142 }
143
144 /**************************************************************************
145  * X11DRV_XDND_PositionEvent
146  *
147  * Handle an XdndPosition event.
148  */
149 void X11DRV_XDND_PositionEvent( HWND hWnd, XClientMessageEvent *event )
150 {
151     XClientMessageEvent e;
152     int accept = 0; /* Assume we're not accepting */
153
154     XDNDxy.x = event->data.l[2] >> 16;
155     XDNDxy.y = event->data.l[2] & 0xFFFF;
156
157     /* FIXME: Notify OLE of DragEnter. Result determines if we accept */
158
159     if (GetWindowLongW( hWnd, GWL_EXSTYLE ) & WS_EX_ACCEPTFILES)
160         accept = 1;
161
162     TRACE("action req: %ld accept(%d) at x(%d),y(%d)\n",
163           event->data.l[4], accept, XDNDxy.x, XDNDxy.y);
164
165     /*
166      * Let source know if we're accepting the drop by
167      * sending a status message.
168      */
169     e.type = ClientMessage;
170     e.display = event->display;
171     e.window = event->data.l[0];
172     e.message_type = x11drv_atom(XdndStatus);
173     e.format = 32;
174     e.data.l[0] = event->window;
175     e.data.l[1] = accept;
176     e.data.l[2] = 0; /* Empty Rect */
177     e.data.l[3] = 0; /* Empty Rect */
178     if (accept)
179         e.data.l[4] = event->data.l[4];
180     else
181         e.data.l[4] = None;
182     wine_tsx11_lock();
183     XSendEvent(event->display, event->data.l[0], False, NoEventMask, (XEvent*)&e);
184     wine_tsx11_unlock();
185
186     /* FIXME: if drag accepted notify OLE of DragOver */
187 }
188
189 /**************************************************************************
190  * X11DRV_XDND_DropEvent
191  *
192  * Handle an XdndDrop event.
193  */
194 void X11DRV_XDND_DropEvent( HWND hWnd, XClientMessageEvent *event )
195 {
196     XClientMessageEvent e;
197
198     TRACE("\n");
199
200     /* If we have a HDROP type we send a WM_ACCEPTFILES.*/
201     if (GetWindowLongW( hWnd, GWL_EXSTYLE ) & WS_EX_ACCEPTFILES)
202         X11DRV_XDND_SendDropFiles( hWnd );
203
204     /* FIXME: Notify OLE of Drop */
205     X11DRV_XDND_FreeDragDropOp();
206
207     /* Tell the target we are finished. */
208     memset(&e, 0, sizeof(e));
209     e.type = ClientMessage;
210     e.display = event->display;
211     e.window = event->data.l[0];
212     e.message_type = x11drv_atom(XdndFinished);
213     e.format = 32;
214     e.data.l[0] = event->window;
215     wine_tsx11_lock();
216     XSendEvent(event->display, event->data.l[0], False, NoEventMask, (XEvent*)&e);
217     wine_tsx11_unlock();
218 }
219
220 /**************************************************************************
221  * X11DRV_XDND_LeaveEvent
222  *
223  * Handle an XdndLeave event.
224  */
225 void X11DRV_XDND_LeaveEvent( HWND hWnd, XClientMessageEvent *event )
226 {
227     TRACE("DND Operation canceled\n");
228
229     X11DRV_XDND_FreeDragDropOp();
230
231     /* FIXME: Notify OLE of DragLeave */
232 }
233
234
235 /**************************************************************************
236  * X11DRV_XDND_ResolveProperty
237  *
238  * Resolve all MIME types to windows clipboard formats. All data is cached.
239  */
240 static void X11DRV_XDND_ResolveProperty(Display *display, Window xwin, Time tm,
241                                         Atom *types, unsigned long *count)
242 {
243     unsigned int i, j;
244     BOOL res;
245     XEvent xe;
246     Atom acttype;
247     int actfmt;
248     unsigned long bytesret, icount;
249     int entries = 0;
250     unsigned char* data = NULL;
251
252     TRACE("count(%ld)\n", *count);
253
254     X11DRV_XDND_FreeDragDropOp(); /* Clear previously cached data */
255
256     for (i = 0; i < *count; i++)
257     {
258         TRACE("requesting atom %ld from xwin %ld\n", types[i], xwin);
259
260         if (types[i] == 0)
261             continue;
262
263         wine_tsx11_lock();
264         XConvertSelection(display, x11drv_atom(XdndSelection), types[i],
265                           x11drv_atom(XdndTarget), xwin, /*tm*/CurrentTime);
266         wine_tsx11_unlock();
267
268         /*
269          * Wait for SelectionNotify
270          */
271         for (j = 0; j < SELECTION_RETRIES; j++)
272         {
273             wine_tsx11_lock();
274             res = XCheckTypedWindowEvent(display, xwin, SelectionNotify, &xe);
275             wine_tsx11_unlock();
276             if (res && xe.xselection.selection == x11drv_atom(XdndSelection)) break;
277
278             usleep(SELECTION_WAIT);
279         }
280
281         if (xe.xselection.property == None)
282             continue;
283
284         wine_tsx11_lock();
285         XGetWindowProperty(display, xwin, x11drv_atom(XdndTarget), 0, 65535, FALSE,
286             AnyPropertyType, &acttype, &actfmt, &icount, &bytesret, &data);
287         wine_tsx11_unlock();
288
289         entries += X11DRV_XDND_MapFormat(types[i], data, get_property_size( actfmt, icount ));
290         wine_tsx11_lock();
291         XFree(data);
292         wine_tsx11_unlock();
293     }
294
295     *count = entries;
296 }
297
298
299 /**************************************************************************
300  * X11DRV_XDND_InsertXDNDData
301  *
302  * Cache available XDND property
303  */
304 static void X11DRV_XDND_InsertXDNDData(int property, int format, void* data, unsigned int len)
305 {
306     LPXDNDDATA current = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(XDNDDATA));
307
308     if (current)
309     {
310         EnterCriticalSection(&xdnd_cs);
311         current->next = XDNDData;
312         current->cf_xdnd = property;
313         current->cf_win = format;
314         current->data = data;
315         current->size = len;
316         XDNDData = current;
317         LeaveCriticalSection(&xdnd_cs);
318     }
319 }
320
321
322 /**************************************************************************
323  * X11DRV_XDND_MapFormat
324  *
325  * Map XDND MIME format to windows clipboard format.
326  */
327 static int X11DRV_XDND_MapFormat(unsigned int property, unsigned char *data, int len)
328 {
329     void* xdata;
330     int count = 0;
331
332     TRACE("%d: %s\n", property, data);
333
334     /* Always include the raw type */
335     xdata = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
336     memcpy(xdata, data, len);
337     X11DRV_XDND_InsertXDNDData(property, property, xdata, len);
338     count++;
339
340     if (property == x11drv_atom(text_uri_list))
341         count += X11DRV_XDND_DeconstructTextURIList(property, data, len);
342     else if (property == x11drv_atom(text_plain))
343         count += X11DRV_XDND_DeconstructTextPlain(property, data, len);
344     else if (property == x11drv_atom(text_html))
345         count += X11DRV_XDND_DeconstructTextHTML(property, data, len);
346
347     return count;
348 }
349
350
351 /**************************************************************************
352  * X11DRV_XDND_DeconstructTextURIList
353  *
354  * Interpret text/uri-list data and add records to <dndfmt> linked list
355  */
356 static int X11DRV_XDND_DeconstructTextURIList(int property, void* data, int len)
357 {
358     char *uriList = (char*) data;
359     char *uri;
360     WCHAR *path;
361
362     char *out = NULL;
363     int size = 0;
364     int capacity = 4096;
365
366     int count = 0;
367     int start = 0;
368     int end = 0;
369
370     out = HeapAlloc(GetProcessHeap(), 0, capacity);
371     if (out == NULL)
372         return 0;
373
374     while (end < len)
375     {
376         while (end < len && uriList[end] != '\r')
377             ++end;
378         if (end == len)
379             break;
380         if (uriList[end+1] != '\n')
381         {
382             WARN("URI list line doesn't end in \\r\\n\n");
383             break;
384         }
385
386         uri = HeapAlloc(GetProcessHeap(), 0, end - start + 1);
387         if (uri == NULL)
388             break;
389         lstrcpynA(uri, &uriList[start], end - start + 1);
390         path = X11DRV_XDND_URIToDOS(uri);
391         TRACE("converted URI %s to DOS path %s\n", debugstr_a(uri), debugstr_w(path));
392         HeapFree(GetProcessHeap(), 0, uri);
393
394         if (path)
395         {
396             int pathSize = strlenW(path) + 1;
397             if (pathSize > capacity-size)
398             {
399                 capacity = 2*capacity + pathSize;
400                 out = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, out, capacity + 1);
401                 if (out == NULL)
402                     goto done;
403             }
404             WideCharToMultiByte(CP_ACP, 0, path, -1, &out[size], pathSize, 0, 0);
405             size += pathSize;
406         done:
407             HeapFree(GetProcessHeap(), 0, path);
408             if (out == NULL)
409                 break;
410         }
411
412         start = end + 2;
413         end = start;
414     }
415     if (out && end == len)
416     {
417         DROPFILES *dropFiles;
418         dropFiles = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DROPFILES) + size + 1);
419         if (dropFiles)
420         {
421             dropFiles->pFiles = sizeof(DROPFILES);
422             dropFiles->pt.x = XDNDxy.x;
423             dropFiles->pt.y = XDNDxy.y;
424             dropFiles->fNC = 0;
425             dropFiles->fWide = FALSE;
426             out[size] = '\0';
427             memcpy(((char*)dropFiles) + dropFiles->pFiles, out, size + 1);
428             X11DRV_XDND_InsertXDNDData(property, CF_HDROP, dropFiles, sizeof(DROPFILES) + size + 1);
429             count = 1;
430         }
431     }
432     HeapFree(GetProcessHeap(), 0, out);
433     return count;
434 }
435
436
437 /**************************************************************************
438  * X11DRV_XDND_DeconstructTextPlain
439  *
440  * Interpret text/plain Data and add records to <dndfmt> linked list
441  */
442 static int X11DRV_XDND_DeconstructTextPlain(int property, void* data, int len)
443 {
444     char* dostext;
445
446     /* Always supply plain text */
447     X11DRV_XDND_UnixToDos(&dostext, (char*)data, len);
448     X11DRV_XDND_InsertXDNDData(property, CF_TEXT, dostext, strlen(dostext));
449
450     TRACE("CF_TEXT (%d): %s\n", CF_TEXT, dostext);
451
452     return 1;
453 }
454
455
456 /**************************************************************************
457  * X11DRV_XDND_DeconstructTextHTML
458  *
459  * Interpret text/html data and add records to <dndfmt> linked list
460  */
461 static int X11DRV_XDND_DeconstructTextHTML(int property, void* data, int len)
462 {
463     char* dostext;
464
465     X11DRV_XDND_UnixToDos(&dostext, data, len);
466
467     X11DRV_XDND_InsertXDNDData(property,
468         RegisterClipboardFormatA("UniformResourceLocator"), dostext, strlen(dostext));
469
470     TRACE("UniformResourceLocator: %s\n", dostext);
471
472     return 1;
473 }
474
475
476 /**************************************************************************
477  * X11DRV_XDND_SendDropFiles
478  */
479 static void X11DRV_XDND_SendDropFiles(HWND hwnd)
480 {
481     LPXDNDDATA current;
482
483     EnterCriticalSection(&xdnd_cs);
484
485     current = XDNDData;
486
487     /* Find CF_HDROP type if any */
488     while (current != NULL)
489     {
490         if (current->cf_win == CF_HDROP)
491             break;
492         current = current->next;
493     }
494
495     if (current != NULL)
496     {
497         DROPFILES *lpDrop = (DROPFILES*) current->data;
498
499         if (lpDrop)
500         {
501             lpDrop->pt.x = XDNDxy.x;
502             lpDrop->pt.y = XDNDxy.y;
503
504             TRACE("Sending WM_DROPFILES: hWnd(0x%p) %p(%s)\n", hwnd,
505                 ((char*)lpDrop) + lpDrop->pFiles, ((char*)lpDrop) + lpDrop->pFiles);
506
507             PostMessageA(hwnd, WM_DROPFILES, (WPARAM)lpDrop, 0L);
508         }
509     }
510
511     LeaveCriticalSection(&xdnd_cs);
512 }
513
514
515 /**************************************************************************
516  * X11DRV_XDND_FreeDragDropOp
517  */
518 static void X11DRV_XDND_FreeDragDropOp(void)
519 {
520     LPXDNDDATA next;
521     LPXDNDDATA current;
522
523     TRACE("\n");
524
525     EnterCriticalSection(&xdnd_cs);
526
527     current = XDNDData;
528
529     /** Free data cache */
530     while (current != NULL)
531     {
532         next = current->next;
533         HeapFree(GetProcessHeap(), 0, current);
534         current = next;
535     }
536
537     XDNDData = NULL;
538     XDNDxy.x = XDNDxy.y = 0;
539
540     LeaveCriticalSection(&xdnd_cs);
541 }
542
543
544
545 /**************************************************************************
546  * X11DRV_XDND_UnixToDos
547  */
548 static unsigned int X11DRV_XDND_UnixToDos(char** lpdest, char* lpsrc, int len)
549 {
550     int i;
551     unsigned int destlen, lines;
552
553     for (i = 0, lines = 0; i <= len; i++)
554     {
555         if (lpsrc[i] == '\n')
556             lines++;
557     }
558
559     destlen = len + lines + 1;
560
561     if (lpdest)
562     {
563         char* lpstr = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, destlen);
564         for (i = 0, lines = 0; i <= len; i++)
565         {
566             if (lpsrc[i] == '\n')
567                 lpstr[++lines + i] = '\r';
568             lpstr[lines + i] = lpsrc[i];
569         }
570
571         *lpdest = lpstr;
572     }
573
574     return lines;
575 }
576
577
578 /**************************************************************************
579  * X11DRV_XDND_URIToDOS
580  */
581 static WCHAR* X11DRV_XDND_URIToDOS(char *encodedURI)
582 {
583     WCHAR *ret = NULL;
584     int i;
585     int j = 0;
586     char *uri = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, strlen(encodedURI) + 1);
587     if (uri == NULL)
588         return NULL;
589     for (i = 0; encodedURI[i]; ++i)
590     {
591         if (encodedURI[i] == '%')
592         { 
593             if (encodedURI[i+1] && encodedURI[i+2])
594             {
595                 char buffer[3];
596                 int number;
597                 buffer[0] = encodedURI[i+1];
598                 buffer[1] = encodedURI[i+2];
599                 buffer[2] = '\0';
600                 sscanf(buffer, "%x", &number);
601                 uri[j++] = number;
602                 i += 2;
603             }
604             else
605             {
606                 WARN("invalid URI encoding in %s\n", debugstr_a(encodedURI));
607                 HeapFree(GetProcessHeap(), 0, uri);
608                 return NULL;
609             }
610         }
611         else
612             uri[j++] = encodedURI[i];
613     }
614
615     /* Read http://www.freedesktop.org/wiki/Draganddropwarts and cry... */
616     if (strncmp(uri, "file:/", 6) == 0)
617     {
618         if (uri[6] == '/')
619         {
620             if (uri[7] == '/')
621             {
622                 /* file:///path/to/file (nautilus, thunar) */
623                 ret = wine_get_dos_file_name(&uri[7]);
624             }
625             else if (uri[7])
626             {
627                 /* file://hostname/path/to/file (X file drag spec) */
628                 char hostname[256];
629                 char *path = strchr(&uri[7], '/');
630                 if (path)
631                 {
632                     *path = '\0';
633                     if (strcmp(&uri[7], "localhost") == 0)
634                     {
635                         *path = '/';
636                         ret = wine_get_dos_file_name(path);
637                     }
638                     else if (gethostname(hostname, sizeof(hostname)) == 0)
639                     {
640                         if (strcmp(hostname, &uri[7]) == 0)
641                         {
642                             *path = '/';
643                             ret = wine_get_dos_file_name(path);
644                         }
645                     }
646                 }
647             }
648         }
649         else if (uri[6])
650         {
651             /* file:/path/to/file (konqueror) */
652             ret = wine_get_dos_file_name(&uri[5]);
653         }
654     }
655     HeapFree(GetProcessHeap(), 0, uri);
656     return ret;
657 }