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