msvcr80: Add some 64-bit only exports.
[wine] / dlls / user32 / dde_misc.c
1 /*
2  * DDEML library
3  *
4  * Copyright 1997 Alexandre Julliard
5  * Copyright 1997 Len White
6  * Copyright 1999 Keith Matthews
7  * Copyright 2000 Corel
8  * Copyright 2001 Eric Pouech
9  * Copyright 2003, 2004, 2005 Dmitry Timoshkov
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28
29 #include <string.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include "windef.h"
33 #include "winbase.h"
34 #include "wingdi.h"
35 #include "winuser.h"
36 #include "dde.h"
37 #include "ddeml.h"
38 #include "win.h"
39 #include "dde_private.h"
40 #include "wine/unicode.h"
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(ddeml);
44
45 /* convert between ATOM and HSZ avoiding compiler warnings */
46 #define ATOM2HSZ(atom)  ((HSZ)  (ULONG_PTR)(atom))
47 #define HSZ2ATOM(hsz)   ((ATOM) (ULONG_PTR)(hsz))
48
49 static WDML_INSTANCE*   WDML_InstanceList = NULL;
50 static LONG             WDML_MaxInstanceID = 0;  /* OK for present, have to worry about wrap-around later */
51 const WCHAR             WDML_szEventClass[] = {'W','i','n','e','D','d','e','E','v','e','n','t','C','l','a','s','s',0};
52
53 /* protection for instance list */
54 static CRITICAL_SECTION WDML_CritSect;
55 static CRITICAL_SECTION_DEBUG critsect_debug =
56 {
57     0, 0, &WDML_CritSect,
58     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
59       0, 0, { (DWORD_PTR)(__FILE__ ": WDML_CritSect") }
60 };
61 static CRITICAL_SECTION WDML_CritSect = { &critsect_debug, -1, 0, 0, 0, 0 };
62
63 /* ================================================================
64  *
65  *                      Pure DDE (non DDEML) management
66  *
67  * ================================================================ */
68
69
70 /*****************************************************************
71  *            PackDDElParam (USER32.@)
72  *
73  * RETURNS
74  *   the packed lParam
75  */
76 LPARAM WINAPI PackDDElParam(UINT msg, UINT_PTR uiLo, UINT_PTR uiHi)
77 {
78     HGLOBAL hMem;
79     UINT_PTR *params;
80
81     switch (msg)
82     {
83     case WM_DDE_ACK:
84     case WM_DDE_ADVISE:
85     case WM_DDE_DATA:
86     case WM_DDE_POKE:
87         if (!(hMem = GlobalAlloc(GMEM_DDESHARE, sizeof(UINT_PTR) * 2)))
88         {
89             ERR("GlobalAlloc failed\n");
90             return 0;
91         }
92         if (!(params = GlobalLock(hMem)))
93         {
94             ERR("GlobalLock failed (%p)\n", hMem);
95             return 0;
96         }
97         params[0] = uiLo;
98         params[1] = uiHi;
99         GlobalUnlock(hMem);
100         return (LPARAM)hMem;
101
102     case WM_DDE_EXECUTE:
103         return uiHi;
104
105     default:
106         return MAKELONG(uiLo, uiHi);
107     }
108 }
109
110
111 /*****************************************************************
112  *            UnpackDDElParam (USER32.@)
113  *
114  * RETURNS
115  *   success: nonzero
116  *   failure: zero
117  */
118 BOOL WINAPI UnpackDDElParam(UINT msg, LPARAM lParam,
119                             PUINT_PTR uiLo, PUINT_PTR uiHi)
120 {
121     UINT_PTR *params;
122
123     switch (msg)
124     {
125     case WM_DDE_ACK:
126     case WM_DDE_ADVISE:
127     case WM_DDE_DATA:
128     case WM_DDE_POKE:
129         if (!lParam || !(params = GlobalLock((HGLOBAL)lParam)))
130         {
131             if (uiLo) *uiLo = 0;
132             if (uiHi) *uiHi = 0;
133             return FALSE;
134         }
135         if (uiLo) *uiLo = params[0];
136         if (uiHi) *uiHi = params[1];
137         GlobalUnlock( (HGLOBAL)lParam );
138         return TRUE;
139
140     case WM_DDE_EXECUTE:
141         if (uiLo) *uiLo = 0;
142         if (uiHi) *uiHi = lParam;
143         return TRUE;
144
145     default:
146         if (uiLo) *uiLo = LOWORD(lParam);
147         if (uiHi) *uiHi = HIWORD(lParam);
148         return TRUE;
149     }
150 }
151
152
153 /*****************************************************************
154  *            FreeDDElParam (USER32.@)
155  *
156  * RETURNS
157  *   success: nonzero
158  *   failure: zero
159  */
160 BOOL WINAPI FreeDDElParam(UINT msg, LPARAM lParam)
161 {
162     switch (msg)
163     {
164     case WM_DDE_ACK:
165     case WM_DDE_ADVISE:
166     case WM_DDE_DATA:
167     case WM_DDE_POKE:
168         /* first check if it's a global handle */
169         if (!GlobalHandle( (LPVOID)lParam )) return TRUE;
170         return !GlobalFree( (HGLOBAL)lParam );
171
172     default:
173         return TRUE;
174      }
175 }
176
177
178 /*****************************************************************
179  *            ReuseDDElParam (USER32.@)
180  *
181  * RETURNS
182  *   the packed lParam
183  */
184 LPARAM WINAPI ReuseDDElParam(LPARAM lParam, UINT msgIn, UINT msgOut,
185                              UINT_PTR uiLo, UINT_PTR uiHi)
186 {
187     UINT_PTR *params;
188
189     switch (msgIn)
190     {
191     case WM_DDE_ACK:
192     case WM_DDE_ADVISE:
193     case WM_DDE_DATA:
194     case WM_DDE_POKE:
195         switch(msgOut)
196         {
197         case WM_DDE_ACK:
198         case WM_DDE_ADVISE:
199         case WM_DDE_DATA:
200         case WM_DDE_POKE:
201             if (!lParam) return 0;
202             if (!(params = GlobalLock( (HGLOBAL)lParam )))
203             {
204                 ERR("GlobalLock failed\n");
205                 return 0;
206             }
207             params[0] = uiLo;
208             params[1] = uiHi;
209             TRACE("Reusing pack %08lx %08lx\n", uiLo, uiHi);
210             GlobalUnlock( (HGLOBAL)lParam );
211             return lParam;
212
213         case WM_DDE_EXECUTE:
214             FreeDDElParam( msgIn, lParam );
215             return uiHi;
216
217         default:
218             FreeDDElParam( msgIn, lParam );
219             return MAKELPARAM(uiLo, uiHi);
220         }
221
222     default:
223         return PackDDElParam( msgOut, uiLo, uiHi );
224     }
225 }
226
227 /*****************************************************************
228  *            ImpersonateDdeClientWindow (USER32.@)
229  *
230  * PARAMS
231  * hWndClient     [I] handle to DDE client window
232  * hWndServer     [I] handle to DDE server window
233  */
234 BOOL WINAPI ImpersonateDdeClientWindow(HWND hWndClient, HWND hWndServer)
235 {
236      FIXME("(%p %p): stub\n", hWndClient, hWndServer);
237      return FALSE;
238 }
239
240 /*****************************************************************
241  *            DdeSetQualityOfService (USER32.@)
242  */
243
244 BOOL WINAPI DdeSetQualityOfService(HWND hwndClient, CONST SECURITY_QUALITY_OF_SERVICE *pqosNew,
245                                    PSECURITY_QUALITY_OF_SERVICE pqosPrev)
246 {
247      FIXME("(%p %p %p): stub\n", hwndClient, pqosNew, pqosPrev);
248      return TRUE;
249 }
250
251 /* ================================================================
252  *
253  *                      WDML Error management
254  *
255  * ================================================================ */
256
257 /******************************************************************************
258  * DdeGetLastError [USER32.@]  Gets most recent error code
259  *
260  * PARAMS
261  *    idInst [I] Instance identifier
262  *
263  * RETURNS
264  *    Last error code
265  */
266 UINT WINAPI DdeGetLastError(DWORD idInst)
267 {
268     DWORD               error_code;
269     WDML_INSTANCE*      pInstance;
270
271     /*  First check instance
272      */
273     pInstance = WDML_GetInstance(idInst);
274     if  (pInstance == NULL)
275     {
276         error_code = DMLERR_INVALIDPARAMETER;
277     }
278     else
279     {
280         error_code = pInstance->lastError;
281         pInstance->lastError = 0;
282     }
283
284     return error_code;
285 }
286
287 /******************************************************************
288  *              WDML_SetAllLastError
289  *
290  *
291  */
292 static void     WDML_SetAllLastError(DWORD lastError)
293 {
294     DWORD               threadID;
295     WDML_INSTANCE*      pInstance;
296     threadID = GetCurrentThreadId();
297     pInstance = WDML_InstanceList;
298     while (pInstance)
299     {
300         if (pInstance->threadID == threadID)
301             pInstance->lastError = lastError;
302         pInstance = pInstance->next;
303     }
304 }
305
306 /* ================================================================
307  *
308  *                      String management
309  *
310  * ================================================================ */
311
312
313 /******************************************************************
314  *              WDML_FindNode
315  *
316  *
317  */
318 static HSZNode* WDML_FindNode(WDML_INSTANCE* pInstance, HSZ hsz)
319 {
320     HSZNode*    pNode;
321
322     if (pInstance == NULL) return NULL;
323
324     for (pNode = pInstance->nodeList; pNode != NULL; pNode = pNode->next)
325     {
326         if (pNode->hsz == hsz) break;
327     }
328     if (!pNode) WARN("HSZ %p not found\n", hsz);
329     return pNode;
330 }
331
332 /******************************************************************
333  *              WDML_MakeAtomFromHsz
334  *
335  * Creates a global atom from an existing HSZ
336  * Generally used before sending an HSZ as an atom to a remote app
337  */
338 ATOM    WDML_MakeAtomFromHsz(HSZ hsz)
339 {
340     WCHAR nameBuffer[MAX_BUFFER_LEN];
341
342     if (GetAtomNameW(HSZ2ATOM(hsz), nameBuffer, MAX_BUFFER_LEN))
343         return GlobalAddAtomW(nameBuffer);
344     WARN("HSZ %p not found\n", hsz);
345     return 0;
346 }
347
348 /******************************************************************
349  *              WDML_MakeHszFromAtom
350  *
351  * Creates a HSZ from an existing global atom
352  * Generally used while receiving a global atom and transforming it
353  * into an HSZ
354  */
355 HSZ     WDML_MakeHszFromAtom(const WDML_INSTANCE* pInstance, ATOM atom)
356 {
357     WCHAR nameBuffer[MAX_BUFFER_LEN];
358
359     if (!atom) return NULL;
360
361     if (GlobalGetAtomNameW(atom, nameBuffer, MAX_BUFFER_LEN))
362     {
363         TRACE("%x => %s\n", atom, debugstr_w(nameBuffer));
364         return DdeCreateStringHandleW(pInstance->instanceID, nameBuffer, CP_WINUNICODE);
365     }
366     WARN("ATOM 0x%x not found\n", atom);
367     return 0;
368 }
369
370 /******************************************************************
371  *              WDML_IncHSZ
372  *
373  *
374  */
375 BOOL WDML_IncHSZ(WDML_INSTANCE* pInstance, HSZ hsz)
376 {
377     HSZNode*    pNode;
378
379     pNode = WDML_FindNode(pInstance, hsz);
380     if (!pNode) return FALSE;
381
382     pNode->refCount++;
383     return TRUE;
384 }
385
386 /******************************************************************************
387  *           WDML_DecHSZ    (INTERNAL)
388  *
389  * Decrease the ref count of an HSZ. If it reaches 0, the node is removed from the list
390  * of HSZ nodes
391  * Returns -1 is the HSZ isn't found, otherwise it's the current (after --) of the ref count
392  */
393 BOOL WDML_DecHSZ(WDML_INSTANCE* pInstance, HSZ hsz)
394 {
395     HSZNode*    pPrev = NULL;
396     HSZNode*    pCurrent;
397
398     for (pCurrent = pInstance->nodeList; pCurrent != NULL; pCurrent = (pPrev = pCurrent)->next)
399     {
400         /* If we found the node we were looking for and its ref count is one,
401          * we can remove it
402          */
403         if (pCurrent->hsz == hsz)
404         {
405             if (--pCurrent->refCount == 0)
406             {
407                 if (pCurrent == pInstance->nodeList)
408                 {
409                     pInstance->nodeList = pCurrent->next;
410                 }
411                 else
412                 {
413                     pPrev->next = pCurrent->next;
414                 }
415                 HeapFree(GetProcessHeap(), 0, pCurrent);
416                 DeleteAtom(HSZ2ATOM(hsz));
417             }
418             return TRUE;
419         }
420     }
421     WARN("HSZ %p not found\n", hsz);
422
423     return FALSE;
424 }
425
426 /******************************************************************************
427  *            WDML_FreeAllHSZ    (INTERNAL)
428  *
429  * Frees up all the strings still allocated in the list and
430  * remove all the nodes from the list of HSZ nodes.
431  */
432 static void WDML_FreeAllHSZ(WDML_INSTANCE* pInstance)
433 {
434     /* Free any strings created in this instance.
435      */
436     while (pInstance->nodeList != NULL)
437     {
438         DdeFreeStringHandle(pInstance->instanceID, pInstance->nodeList->hsz);
439     }
440 }
441
442 /******************************************************************************
443  *            InsertHSZNode    (INTERNAL)
444  *
445  * Insert a node to the head of the list.
446  */
447 static void WDML_InsertHSZNode(WDML_INSTANCE* pInstance, HSZ hsz)
448 {
449     if (hsz != 0)
450     {
451         HSZNode* pNew = NULL;
452         /* Create a new node for this HSZ.
453          */
454         pNew = HeapAlloc(GetProcessHeap(), 0, sizeof(HSZNode));
455         if (pNew != NULL)
456         {
457             pNew->hsz      = hsz;
458             pNew->next     = pInstance->nodeList;
459             pNew->refCount = 1;
460             pInstance->nodeList = pNew;
461         }
462         else
463         {
464             ERR("Primary HSZ Node allocation failed - out of memory\n");
465         }
466     }
467 }
468
469 /******************************************************************
470  *              WDML_QueryString
471  *
472  *
473  */
474 static int      WDML_QueryString(WDML_INSTANCE* pInstance, HSZ hsz, LPVOID ptr, DWORD cchMax,
475                                  int codepage)
476 {
477     WCHAR       pString[MAX_BUFFER_LEN];
478     int         ret;
479     /* If psz is null, we have to return only the length
480      * of the string.
481      */
482     if (ptr == NULL)
483     {
484         ptr = pString;
485         cchMax = MAX_BUFFER_LEN;
486     }
487
488     /* if there is no input windows returns a NULL string */
489     if (hsz == NULL)
490     {
491         CHAR *t_ptr = ptr;
492         *t_ptr = '\0';
493         return 1;
494     }
495
496     switch (codepage)
497     {
498     case CP_WINANSI:
499         ret = GetAtomNameA(HSZ2ATOM(hsz), ptr, cchMax);
500         break;
501     case CP_WINUNICODE:
502         ret = GetAtomNameW(HSZ2ATOM(hsz), ptr, cchMax);
503         break;
504     default:
505         ERR("Unknown code page %d\n", codepage);
506         ret = 0;
507     }
508     return ret;
509 }
510
511 /*****************************************************************
512  * DdeQueryStringA [USER32.@]
513  */
514 DWORD WINAPI DdeQueryStringA(DWORD idInst, HSZ hsz, LPSTR psz, DWORD cchMax, INT iCodePage)
515 {
516     DWORD               ret = 0;
517     WDML_INSTANCE*      pInstance;
518
519     TRACE("(%d, %p, %p, %d, %d)\n", idInst, hsz, psz, cchMax, iCodePage);
520
521     /*  First check instance
522      */
523     pInstance = WDML_GetInstance(idInst);
524     if (pInstance != NULL)
525     {
526         if (iCodePage == 0) iCodePage = CP_WINANSI;
527         ret = WDML_QueryString(pInstance, hsz, psz, cchMax, iCodePage);
528     }
529
530     TRACE("returning %d (%s)\n", ret, debugstr_a(psz));
531     return ret;
532 }
533
534 /*****************************************************************
535  * DdeQueryStringW [USER32.@]
536  */
537
538 DWORD WINAPI DdeQueryStringW(DWORD idInst, HSZ hsz, LPWSTR psz, DWORD cchMax, INT iCodePage)
539 {
540     DWORD               ret = 0;
541     WDML_INSTANCE*      pInstance;
542
543     TRACE("(%d, %p, %p, %d, %d)\n", idInst, hsz, psz, cchMax, iCodePage);
544
545     /*  First check instance
546      */
547     pInstance = WDML_GetInstance(idInst);
548     if (pInstance != NULL)
549     {
550         if (iCodePage == 0) iCodePage = CP_WINUNICODE;
551         ret = WDML_QueryString(pInstance, hsz, psz, cchMax, iCodePage);
552     }
553
554     TRACE("returning %d (%s)\n", ret, debugstr_w(psz));
555     return ret;
556 }
557
558 /******************************************************************
559  *              DML_CreateString
560  *
561  *
562  */
563 static  HSZ     WDML_CreateString(WDML_INSTANCE* pInstance, LPCVOID ptr, int codepage)
564 {
565     HSZ         hsz;
566
567     switch (codepage)
568     {
569     case CP_WINANSI:
570         hsz = ATOM2HSZ(AddAtomA(ptr));
571         TRACE("added atom %s with HSZ %p,\n", debugstr_a(ptr), hsz);
572         break;
573     case CP_WINUNICODE:
574         hsz = ATOM2HSZ(AddAtomW(ptr));
575         TRACE("added atom %s with HSZ %p,\n", debugstr_w(ptr), hsz);
576         break;
577     default:
578         ERR("Unknown code page %d\n", codepage);
579         return 0;
580     }
581     WDML_InsertHSZNode(pInstance, hsz);
582     return hsz;
583 }
584
585 /*****************************************************************
586  * DdeCreateStringHandleA [USER32.@]
587  *
588  * See DdeCreateStringHandleW.
589  */
590 HSZ WINAPI DdeCreateStringHandleA(DWORD idInst, LPCSTR psz, INT codepage)
591 {
592     HSZ                 hsz = 0;
593     WDML_INSTANCE*      pInstance;
594
595     TRACE("(%d,%s,%d)\n", idInst, debugstr_a(psz), codepage);
596
597     pInstance = WDML_GetInstance(idInst);
598     if (pInstance == NULL)
599         WDML_SetAllLastError(DMLERR_INVALIDPARAMETER);
600     else
601     {
602         if (codepage == 0) codepage = CP_WINANSI;
603         hsz = WDML_CreateString(pInstance, psz, codepage);
604     }
605
606     return hsz;
607 }
608
609
610 /******************************************************************************
611  * DdeCreateStringHandleW [USER32.@]  Creates handle to identify string
612  *
613  * PARAMS
614  *      idInst   [I] Instance identifier
615  *      psz      [I] Pointer to string
616  *      codepage [I] Code page identifier
617  * RETURNS
618  *    Success: String handle
619  *    Failure: 0
620  */
621 HSZ WINAPI DdeCreateStringHandleW(DWORD idInst, LPCWSTR psz, INT codepage)
622 {
623     WDML_INSTANCE*      pInstance;
624     HSZ                 hsz = 0;
625
626     pInstance = WDML_GetInstance(idInst);
627     if (pInstance == NULL)
628         WDML_SetAllLastError(DMLERR_INVALIDPARAMETER);
629     else
630     {
631         if (codepage == 0) codepage = CP_WINUNICODE;
632         hsz = WDML_CreateString(pInstance, psz, codepage);
633     }
634
635     return hsz;
636 }
637
638 /*****************************************************************
639  *            DdeFreeStringHandle   (USER32.@)
640  * RETURNS
641  *  success: nonzero
642  *  fail:    zero
643  */
644 BOOL WINAPI DdeFreeStringHandle(DWORD idInst, HSZ hsz)
645 {
646     WDML_INSTANCE*      pInstance;
647     BOOL                ret = FALSE;
648
649     TRACE("(%d,%p):\n", idInst, hsz);
650
651     /*  First check instance
652      */
653     pInstance = WDML_GetInstance(idInst);
654     if (pInstance)
655         ret = WDML_DecHSZ(pInstance, hsz);
656
657     return ret;
658 }
659
660 /*****************************************************************
661  *            DdeKeepStringHandle  (USER32.@)
662  *
663  * RETURNS
664  *  success: nonzero
665  *  fail:    zero
666  */
667 BOOL WINAPI DdeKeepStringHandle(DWORD idInst, HSZ hsz)
668 {
669     WDML_INSTANCE*      pInstance;
670     BOOL                ret = FALSE;
671
672     TRACE("(%d,%p):\n", idInst, hsz);
673
674     /*  First check instance
675      */
676     pInstance = WDML_GetInstance(idInst);
677     if (pInstance)
678         ret = WDML_IncHSZ(pInstance, hsz);
679
680     return ret;
681 }
682
683 /*****************************************************************
684  *            DdeCmpStringHandles (USER32.@)
685  *
686  * Compares the value of two string handles.  This comparison is
687  * not case sensitive.
688  *
689  * PARAMS
690  *  hsz1    [I] Handle to the first string
691  *  hsz2    [I] Handle to the second string
692  *
693  * RETURNS
694  *  -1 The value of hsz1 is zero or less than hsz2
695  *  0  The values of hsz 1 and 2 are the same or both zero.
696  *  1  The value of hsz2 is zero of less than hsz1
697  */
698 INT WINAPI DdeCmpStringHandles(HSZ hsz1, HSZ hsz2)
699 {
700     WCHAR       psz1[MAX_BUFFER_LEN];
701     WCHAR       psz2[MAX_BUFFER_LEN];
702     int         ret = 0;
703     int         ret1, ret2;
704
705     ret1 = GetAtomNameW(HSZ2ATOM(hsz1), psz1, MAX_BUFFER_LEN);
706     ret2 = GetAtomNameW(HSZ2ATOM(hsz2), psz2, MAX_BUFFER_LEN);
707
708     TRACE("(%p<%s> %p<%s>);\n", hsz1, debugstr_w(psz1), hsz2, debugstr_w(psz2));
709
710     /* Make sure we found both strings. */
711     if (ret1 == 0 && ret2 == 0)
712     {
713         /* If both are not found, return both  "zero strings". */
714         ret = 0;
715     }
716     else if (ret1 == 0)
717     {
718         /* If hsz1 is a not found, return hsz1 is "zero string". */
719         ret = -1;
720     }
721     else if (ret2 == 0)
722     {
723         /* If hsz2 is a not found, return hsz2 is "zero string". */
724         ret = 1;
725     }
726     else
727     {
728         /* Compare the two strings we got (case insensitive). */
729         ret = lstrcmpiW(psz1, psz2);
730         /* Since strcmp returns any number smaller than
731          * 0 when the first string is found to be less than
732          * the second one we must make sure we are returning
733          * the proper values.
734          */
735         if (ret < 0)
736         {
737             ret = -1;
738         }
739         else if (ret > 0)
740         {
741             ret = 1;
742         }
743     }
744
745     return ret;
746 }
747
748 /* ================================================================
749  *
750  *                      Instance management
751  *
752  * ================================================================ */
753
754 /******************************************************************************
755  *              IncrementInstanceId
756  *
757  *      generic routine to increment the max instance Id and allocate a new application instance
758  */
759 static void WDML_IncrementInstanceId(WDML_INSTANCE* pInstance)
760 {
761     DWORD       id = InterlockedIncrement(&WDML_MaxInstanceID);
762
763     pInstance->instanceID = id;
764     TRACE("New instance id %d allocated\n", id);
765 }
766
767 /******************************************************************
768  *              WDML_EventProc
769  *
770  *
771  */
772 static LRESULT CALLBACK WDML_EventProc(HWND hwndEvent, UINT uMsg, WPARAM wParam, LPARAM lParam)
773 {
774     WDML_INSTANCE*      pInstance;
775     HSZ                 hsz1, hsz2;
776
777     switch (uMsg)
778     {
779     case WM_WDML_REGISTER:
780         pInstance = WDML_GetInstanceFromWnd(hwndEvent);
781         /* try calling the Callback */
782         if (pInstance && !(pInstance->CBFflags & CBF_SKIP_REGISTRATIONS))
783         {
784             hsz1 = WDML_MakeHszFromAtom(pInstance, wParam);
785             hsz2 = WDML_MakeHszFromAtom(pInstance, lParam);
786             WDML_InvokeCallback(pInstance, XTYP_REGISTER, 0, 0, hsz1, hsz2, 0, 0, 0);
787             WDML_DecHSZ(pInstance, hsz1);
788             WDML_DecHSZ(pInstance, hsz2);
789         }
790         break;
791
792     case WM_WDML_UNREGISTER:
793         pInstance = WDML_GetInstanceFromWnd(hwndEvent);
794         if (pInstance && !(pInstance->CBFflags & CBF_SKIP_UNREGISTRATIONS))
795         {
796             hsz1 = WDML_MakeHszFromAtom(pInstance, wParam);
797             hsz2 = WDML_MakeHszFromAtom(pInstance, lParam);
798             WDML_InvokeCallback(pInstance, XTYP_UNREGISTER, 0, 0, hsz1, hsz2, 0, 0, 0);
799             WDML_DecHSZ(pInstance, hsz1);
800             WDML_DecHSZ(pInstance, hsz2);
801         }
802         break;
803
804     case WM_WDML_CONNECT_CONFIRM:
805         pInstance = WDML_GetInstanceFromWnd(hwndEvent);
806         if (pInstance && !(pInstance->CBFflags & CBF_SKIP_CONNECT_CONFIRMS))
807         {
808             WDML_CONV*  pConv;
809             /* confirm connection...
810              * lookup for this conv handle
811              */
812             HWND client = WIN_GetFullHandle( (HWND)wParam );
813             HWND server = WIN_GetFullHandle( (HWND)lParam );
814             for (pConv = pInstance->convs[WDML_SERVER_SIDE]; pConv != NULL; pConv = pConv->next)
815             {
816                 if (pConv->hwndClient == client && pConv->hwndServer == server)
817                     break;
818             }
819             if (pConv)
820             {
821                 pConv->wStatus |= ST_ISLOCAL;
822
823                 WDML_InvokeCallback(pInstance, XTYP_CONNECT_CONFIRM, 0, (HCONV)pConv,
824                                     pConv->hszTopic, pConv->hszService, 0, 0,
825                                     (pConv->wStatus & ST_ISSELF) ? 1 : 0);
826             }
827         }
828         break;
829     default:
830         return DefWindowProcW(hwndEvent, uMsg, wParam, lParam);
831     }
832     return 0;
833 }
834
835 /******************************************************************
836  *              WDML_Initialize
837  *
838  *
839  */
840 static UINT WDML_Initialize(LPDWORD pidInst, PFNCALLBACK pfnCallback,
841                             DWORD afCmd, DWORD ulRes, BOOL bUnicode)
842 {
843     WDML_INSTANCE*              pInstance;
844     WDML_INSTANCE*              reference_inst;
845     UINT                        ret;
846     WNDCLASSEXW                 wndclass;
847
848     TRACE("(%p,%p,0x%x,%d,0x%x)\n",
849           pidInst, pfnCallback, afCmd, ulRes, bUnicode);
850
851     if (ulRes)
852     {
853         ERR("Reserved value not zero?  What does this mean?\n");
854         /* trap this and no more until we know more */
855         return DMLERR_NO_ERROR;
856     }
857
858     /* grab enough heap for one control struct - not really necessary for re-initialise
859      *  but allows us to use same validation routines */
860     pInstance = HeapAlloc(GetProcessHeap(), 0, sizeof(WDML_INSTANCE));
861     if (pInstance == NULL)
862     {
863         /* catastrophe !! warn user & abort */
864         ERR("Instance create failed - out of memory\n");
865         return DMLERR_SYS_ERROR;
866     }
867     pInstance->next = NULL;
868     pInstance->monitor = (afCmd | APPCLASS_MONITOR);
869
870     /* messy bit, spec implies that 'Client Only' can be set in 2 different ways, catch 1 here */
871
872     pInstance->clientOnly = afCmd & APPCMD_CLIENTONLY;
873     pInstance->instanceID = *pidInst; /* May need to add calling proc Id */
874     pInstance->threadID = GetCurrentThreadId();
875     pInstance->callback = *pfnCallback;
876     pInstance->unicode = bUnicode;
877     pInstance->nodeList = NULL; /* node will be added later */
878     pInstance->monitorFlags = afCmd & MF_MASK;
879     pInstance->wStatus = 0;
880     pInstance->lastError = DMLERR_NO_ERROR;
881     pInstance->servers = NULL;
882     pInstance->convs[0] = NULL;
883     pInstance->convs[1] = NULL;
884     pInstance->links[0] = NULL;
885     pInstance->links[1] = NULL;
886
887     /* isolate CBF flags in one go, expect this will go the way of all attempts to be clever !! */
888
889     pInstance->CBFflags = afCmd^((afCmd&MF_MASK)|((afCmd&APPCMD_MASK)|(afCmd&APPCLASS_MASK)));
890
891     if (!pInstance->clientOnly)
892     {
893         /* Check for other way of setting Client-only !! */
894         pInstance->clientOnly =
895             (pInstance->CBFflags & CBF_FAIL_ALLSVRXACTIONS) == CBF_FAIL_ALLSVRXACTIONS;
896     }
897
898     TRACE("instance created - checking validity\n");
899
900     if (*pidInst == 0)
901     {
902         /*  Initialisation of new Instance Identifier */
903         TRACE("new instance, callback %p flags %X\n",pfnCallback,afCmd);
904
905         EnterCriticalSection(&WDML_CritSect);
906
907         if (WDML_InstanceList == NULL)
908         {
909             /* can't be another instance in this case, assign to the base pointer */
910             WDML_InstanceList = pInstance;
911
912             /* since first must force filter of XTYP_CONNECT and XTYP_WILDCONNECT for
913              *          present
914              *  -------------------------------      NOTE NOTE NOTE    --------------------------
915              *
916              *  the manual is not clear if this condition
917              *  applies to the first call to DdeInitialize from an application, or the
918              *  first call for a given callback !!!
919              */
920
921             pInstance->CBFflags = pInstance->CBFflags|APPCMD_FILTERINITS;
922             TRACE("First application instance detected OK\n");
923             /*  allocate new instance ID */
924             WDML_IncrementInstanceId(pInstance);
925         }
926         else
927         {
928             /* really need to chain the new one in to the latest here, but after checking conditions
929              *  such as trying to start a conversation from an application trying to monitor */
930             reference_inst = WDML_InstanceList;
931             TRACE("Subsequent application instance - starting checks\n");
932             while (reference_inst->next != NULL)
933             {
934                 /*
935                  *      This set of tests will work if application uses same instance Id
936                  *      at application level once allocated - which is what manual implies
937                  *      should happen. If someone tries to be
938                  *      clever (lazy ?) it will fail to pick up that later calls are for
939                  *      the same application - should we trust them ?
940                  */
941                 if (pInstance->instanceID == reference_inst->instanceID)
942                 {
943                     /* Check 1 - must be same Client-only state */
944
945                     if (pInstance->clientOnly != reference_inst->clientOnly)
946                     {
947                         ret = DMLERR_DLL_USAGE;
948                         goto theError;
949                     }
950
951                     /* Check 2 - cannot use 'Monitor' with any non-monitor modes */
952
953                     if (pInstance->monitor != reference_inst->monitor)
954                     {
955                         ret = DMLERR_INVALIDPARAMETER;
956                         goto theError;
957                     }
958
959                     /* Check 3 - must supply different callback address */
960
961                     if (pInstance->callback == reference_inst->callback)
962                     {
963                         ret = DMLERR_DLL_USAGE;
964                         goto theError;
965                     }
966                 }
967                 reference_inst = reference_inst->next;
968             }
969             /*  All cleared, add to chain */
970
971             TRACE("Application Instance checks finished\n");
972             WDML_IncrementInstanceId(pInstance);
973             reference_inst->next = pInstance;
974         }
975         LeaveCriticalSection(&WDML_CritSect);
976
977         *pidInst = pInstance->instanceID;
978
979         /* for deadlock issues, windows must always be created when outside the critical section */
980         wndclass.cbSize        = sizeof(wndclass);
981         wndclass.style         = 0;
982         wndclass.lpfnWndProc   = WDML_EventProc;
983         wndclass.cbClsExtra    = 0;
984         wndclass.cbWndExtra    = sizeof(ULONG_PTR);
985         wndclass.hInstance     = 0;
986         wndclass.hIcon         = 0;
987         wndclass.hCursor       = 0;
988         wndclass.hbrBackground = 0;
989         wndclass.lpszMenuName  = NULL;
990         wndclass.lpszClassName = WDML_szEventClass;
991         wndclass.hIconSm       = 0;
992
993         RegisterClassExW(&wndclass);
994
995         pInstance->hwndEvent = CreateWindowW(WDML_szEventClass, NULL,
996                                                 WS_POPUP, 0, 0, 0, 0,
997                                                 0, 0, 0, 0);
998
999         SetWindowLongPtrW(pInstance->hwndEvent, GWL_WDML_INSTANCE, (ULONG_PTR)pInstance);
1000
1001         TRACE("New application instance processing finished OK\n");
1002     }
1003     else
1004     {
1005         /* Reinitialisation situation   --- FIX  */
1006         TRACE("reinitialisation of (%p,%p,0x%x,%d): stub\n", pidInst, pfnCallback, afCmd, ulRes);
1007
1008         EnterCriticalSection(&WDML_CritSect);
1009
1010         if (WDML_InstanceList == NULL)
1011         {
1012             ret = DMLERR_INVALIDPARAMETER;
1013             goto theError;
1014         }
1015         /* can't reinitialise if we have initialised nothing !! */
1016         reference_inst = WDML_InstanceList;
1017         /* must first check if we have been given a valid instance to re-initialise !!  how do we do that ? */
1018         /*
1019          *      MS allows initialisation without specifying a callback, should we allow addition of the
1020          *      callback by a later call to initialise ? - if so this lot will have to change
1021          */
1022         while (reference_inst->next != NULL)
1023         {
1024             if (*pidInst == reference_inst->instanceID && pfnCallback == reference_inst->callback)
1025             {
1026                 /* Check 1 - cannot change client-only mode if set via APPCMD_CLIENTONLY */
1027
1028                 if (reference_inst->clientOnly)
1029                 {
1030                     if  ((reference_inst->CBFflags & CBF_FAIL_ALLSVRXACTIONS) != CBF_FAIL_ALLSVRXACTIONS)
1031                     {
1032                                 /* i.e. Was set to Client-only and through APPCMD_CLIENTONLY */
1033
1034                         if (!(afCmd & APPCMD_CLIENTONLY))
1035                         {
1036                             ret = DMLERR_INVALIDPARAMETER;
1037                             goto theError;
1038                         }
1039                     }
1040                 }
1041                 /* Check 2 - cannot change monitor modes */
1042
1043                 if (pInstance->monitor != reference_inst->monitor)
1044                 {
1045                     ret = DMLERR_INVALIDPARAMETER;
1046                     goto theError;
1047                 }
1048
1049                 /* Check 3 - trying to set Client-only via APPCMD when not set so previously */
1050
1051                 if ((afCmd&APPCMD_CLIENTONLY) && !reference_inst->clientOnly)
1052                 {
1053                     ret = DMLERR_INVALIDPARAMETER;
1054                     goto theError;
1055                 }
1056                 break;
1057             }
1058             reference_inst = reference_inst->next;
1059         }
1060         if (reference_inst->next == NULL)
1061         {
1062             ret = DMLERR_INVALIDPARAMETER;
1063             goto theError;
1064         }
1065         /* All checked - change relevant flags */
1066
1067         reference_inst->CBFflags = pInstance->CBFflags;
1068         reference_inst->clientOnly = pInstance->clientOnly;
1069         reference_inst->monitorFlags = pInstance->monitorFlags;
1070
1071         HeapFree(GetProcessHeap(), 0, pInstance); /* finished - release heap space used as work store */
1072
1073         LeaveCriticalSection(&WDML_CritSect);
1074     }
1075
1076     return DMLERR_NO_ERROR;
1077  theError:
1078     HeapFree(GetProcessHeap(), 0, pInstance);
1079     LeaveCriticalSection(&WDML_CritSect);
1080     return ret;
1081 }
1082
1083 /******************************************************************************
1084  *            DdeInitializeA   (USER32.@)
1085  *
1086  * See DdeInitializeW.
1087  */
1088 UINT WINAPI DdeInitializeA(LPDWORD pidInst, PFNCALLBACK pfnCallback,
1089                            DWORD afCmd, DWORD ulRes)
1090 {
1091     return WDML_Initialize(pidInst, pfnCallback, afCmd, ulRes, FALSE);
1092 }
1093
1094 /******************************************************************************
1095  * DdeInitializeW [USER32.@]
1096  * Registers an application with the DDEML
1097  *
1098  * PARAMS
1099  *    pidInst     [I] Pointer to instance identifier
1100  *    pfnCallback [I] Pointer to callback function
1101  *    afCmd       [I] Set of command and filter flags
1102  *    ulRes       [I] Reserved
1103  *
1104  * RETURNS
1105  *    Success: DMLERR_NO_ERROR
1106  *    Failure: DMLERR_DLL_USAGE, DMLERR_INVALIDPARAMETER, DMLERR_SYS_ERROR
1107  */
1108 UINT WINAPI DdeInitializeW(LPDWORD pidInst, PFNCALLBACK pfnCallback,
1109                            DWORD afCmd, DWORD ulRes)
1110 {
1111     return WDML_Initialize(pidInst, pfnCallback, afCmd, ulRes, TRUE);
1112 }
1113
1114 /*****************************************************************
1115  * DdeUninitialize [USER32.@]  Frees DDEML resources
1116  *
1117  * PARAMS
1118  *    idInst [I] Instance identifier
1119  *
1120  * RETURNS
1121  *    Success: TRUE
1122  *    Failure: FALSE
1123  */
1124
1125 BOOL WINAPI DdeUninitialize(DWORD idInst)
1126 {
1127     /*  Stage one - check if we have a handle for this instance
1128      */
1129     WDML_INSTANCE*              pInstance;
1130     WDML_CONV*                  pConv;
1131     WDML_CONV*                  pConvNext;
1132
1133     TRACE("(%d)\n", idInst);
1134
1135     /*  First check instance
1136      */
1137     pInstance = WDML_GetInstance(idInst);
1138     if (pInstance == NULL)
1139     {
1140         /*
1141          *      Needs something here to record NOT_INITIALIZED ready for DdeGetLastError
1142          */
1143         return FALSE;
1144     }
1145
1146     /* first terminate all conversations client side
1147      * this shall close existing links...
1148      */
1149     for (pConv = pInstance->convs[WDML_CLIENT_SIDE]; pConv != NULL; pConv = pConvNext)
1150     {
1151         pConvNext = pConv->next;
1152         DdeDisconnect((HCONV)pConv);
1153     }
1154     if (pInstance->convs[WDML_CLIENT_SIDE])
1155         FIXME("still pending conversations\n");
1156
1157     /* then unregister all known service names */
1158     DdeNameService(idInst, 0, 0, DNS_UNREGISTER);
1159
1160     /* Free the nodes that were not freed by this instance
1161      * and remove the nodes from the list of HSZ nodes.
1162      */
1163     WDML_FreeAllHSZ(pInstance);
1164
1165     DestroyWindow(pInstance->hwndEvent);
1166
1167     /* OK now delete the instance handle itself */
1168
1169     if (WDML_InstanceList == pInstance)
1170     {
1171         /* special case - the first/only entry */
1172         WDML_InstanceList = pInstance->next;
1173     }
1174     else
1175     {
1176         /* general case, remove entry */
1177         WDML_INSTANCE*  inst;
1178
1179         for (inst = WDML_InstanceList; inst->next != pInstance; inst = inst->next);
1180         inst->next = pInstance->next;
1181     }
1182     /* release the heap entry
1183      */
1184     HeapFree(GetProcessHeap(), 0, pInstance);
1185
1186     return TRUE;
1187 }
1188
1189 /******************************************************************
1190  *              WDML_NotifyThreadExit
1191  *
1192  *
1193  */
1194 void WDML_NotifyThreadDetach(void)
1195 {
1196     WDML_INSTANCE*      pInstance;
1197     WDML_INSTANCE*      next;
1198     DWORD               tid = GetCurrentThreadId();
1199
1200     EnterCriticalSection(&WDML_CritSect);
1201     for (pInstance = WDML_InstanceList; pInstance != NULL; pInstance = next)
1202     {
1203         next = pInstance->next;
1204         if (pInstance->threadID == tid)
1205         {
1206             LeaveCriticalSection(&WDML_CritSect);
1207             DdeUninitialize(pInstance->instanceID);
1208             EnterCriticalSection(&WDML_CritSect);
1209         }
1210     }
1211     LeaveCriticalSection(&WDML_CritSect);
1212 }
1213
1214 /******************************************************************
1215  *              WDML_InvokeCallback
1216  *
1217  *
1218  */
1219 HDDEDATA        WDML_InvokeCallback(WDML_INSTANCE* pInstance, UINT uType, UINT uFmt, HCONV hConv,
1220                                     HSZ hsz1, HSZ hsz2, HDDEDATA hdata,
1221                                     ULONG_PTR dwData1, ULONG_PTR dwData2)
1222 {
1223     HDDEDATA    ret;
1224
1225     if (pInstance == NULL)
1226         return NULL;
1227
1228     TRACE("invoking CB[%p] (%x %x %p %p %p %p %lx %lx)\n",
1229           pInstance->callback, uType, uFmt,
1230           hConv, hsz1, hsz2, hdata, dwData1, dwData2);
1231     ret = pInstance->callback(uType, uFmt, hConv, hsz1, hsz2, hdata, dwData1, dwData2);
1232     TRACE("done => %p\n", ret);
1233     return ret;
1234 }
1235
1236 /*****************************************************************************
1237  *      WDML_GetInstance
1238  *
1239  *      generic routine to return a pointer to the relevant DDE_HANDLE_ENTRY
1240  *      for an instance Id, or NULL if the entry does not exist
1241  *
1242  */
1243 WDML_INSTANCE*  WDML_GetInstance(DWORD instId)
1244 {
1245     WDML_INSTANCE*      pInstance;
1246
1247     EnterCriticalSection(&WDML_CritSect);
1248
1249     for (pInstance = WDML_InstanceList; pInstance != NULL; pInstance = pInstance->next)
1250     {
1251         if (pInstance->instanceID == instId)
1252         {
1253             if (GetCurrentThreadId() != pInstance->threadID)
1254             {
1255                 FIXME("Tried to get instance from wrong thread\n");
1256                 continue;
1257             }
1258             break;
1259         }
1260     }
1261
1262     LeaveCriticalSection(&WDML_CritSect);
1263
1264     if (!pInstance)
1265         WARN("Instance entry missing for id %04x\n", instId);
1266     return pInstance;
1267 }
1268
1269 /******************************************************************
1270  *              WDML_GetInstanceFromWnd
1271  *
1272  *
1273  */
1274 WDML_INSTANCE*  WDML_GetInstanceFromWnd(HWND hWnd)
1275 {
1276     return (WDML_INSTANCE*)GetWindowLongPtrW(hWnd, GWL_WDML_INSTANCE);
1277 }
1278
1279 /* ================================================================
1280  *
1281  *                      Data handle management
1282  *
1283  * ================================================================ */
1284
1285 /*****************************************************************
1286  *            DdeCreateDataHandle (USER32.@)
1287  */
1288 HDDEDATA WINAPI DdeCreateDataHandle(DWORD idInst, LPBYTE pSrc, DWORD cb, DWORD cbOff,
1289                                     HSZ hszItem, UINT wFmt, UINT afCmd)
1290 {
1291
1292     /* Other than check for validity we will ignore for now idInst, hszItem.
1293      * The purpose of these arguments still need to be investigated.
1294      */
1295
1296     WDML_INSTANCE*              pInstance;
1297     HGLOBAL                     hMem;
1298     LPBYTE                      pByte;
1299     DDE_DATAHANDLE_HEAD*        pDdh;
1300     WCHAR psz[MAX_BUFFER_LEN];
1301
1302     pInstance = WDML_GetInstance(idInst);
1303     if (pInstance == NULL)
1304     {
1305         WDML_SetAllLastError(DMLERR_INVALIDPARAMETER);
1306         return NULL;
1307     }
1308
1309     if (!GetAtomNameW(HSZ2ATOM(hszItem), psz, MAX_BUFFER_LEN))
1310     {
1311         psz[0] = HSZ2ATOM(hszItem);
1312         psz[1] = 0;
1313     }
1314
1315     TRACE("(%d,%p,cb %d, cbOff %d,%p <%s>,fmt %04x,%x)\n",
1316           idInst, pSrc, cb, cbOff, hszItem, debugstr_w(psz), wFmt, afCmd);
1317
1318     if (afCmd != 0 && afCmd != HDATA_APPOWNED)
1319         return 0;
1320
1321     /* we use the first 4 bytes to store the size */
1322     if (!(hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, cb + cbOff + sizeof(DDE_DATAHANDLE_HEAD))))
1323     {
1324         ERR("GlobalAlloc failed\n");
1325         return 0;
1326     }
1327
1328     pDdh = GlobalLock(hMem);
1329     if (!pDdh)
1330     {
1331         GlobalFree(hMem);
1332         return 0;
1333     }
1334
1335     pDdh->cfFormat = wFmt;
1336     pDdh->bAppOwned = (afCmd == HDATA_APPOWNED);
1337
1338     pByte = (LPBYTE)(pDdh + 1);
1339     if (pSrc)
1340     {
1341         memcpy(pByte, pSrc + cbOff, cb);
1342     }
1343     GlobalUnlock(hMem);
1344
1345     TRACE("=> %p\n", hMem);
1346     return hMem;
1347 }
1348
1349 /*****************************************************************
1350  *
1351  *            DdeAddData (USER32.@)
1352  */
1353 HDDEDATA WINAPI DdeAddData(HDDEDATA hData, LPBYTE pSrc, DWORD cb, DWORD cbOff)
1354 {
1355     DWORD       old_sz, new_sz;
1356     LPBYTE      pDst;
1357
1358     TRACE("(%p,%p,cb %d, cbOff %d)\n", hData, pSrc, cb, cbOff);
1359
1360     pDst = DdeAccessData(hData, &old_sz);
1361     if (!pDst) return 0;
1362
1363     new_sz = cb + cbOff;
1364     if (new_sz > old_sz)
1365     {
1366         DdeUnaccessData(hData);
1367         hData = GlobalReAlloc(hData, new_sz + sizeof(DDE_DATAHANDLE_HEAD),
1368                               GMEM_MOVEABLE | GMEM_DDESHARE);
1369         pDst = DdeAccessData(hData, &old_sz);
1370     }
1371
1372     if (!pDst) return 0;
1373
1374     memcpy(pDst + cbOff, pSrc, cb);
1375     DdeUnaccessData(hData);
1376     return hData;
1377 }
1378
1379 /******************************************************************************
1380  * DdeGetData [USER32.@]  Copies data from DDE object to local buffer
1381  *
1382  *
1383  * PARAMS
1384  * hData        [I] Handle to DDE object
1385  * pDst         [I] Pointer to destination buffer
1386  * cbMax        [I] Amount of data to copy
1387  * cbOff        [I] Offset to beginning of data
1388  *
1389  * RETURNS
1390  *    Size of memory object associated with handle
1391  */
1392 DWORD WINAPI DdeGetData(HDDEDATA hData, LPBYTE pDst, DWORD cbMax, DWORD cbOff)
1393 {
1394     DWORD   dwSize, dwRet;
1395     LPBYTE  pByte;
1396
1397     TRACE("(%p,%p,%d,%d)\n", hData, pDst, cbMax, cbOff);
1398
1399     pByte = DdeAccessData(hData, &dwSize);
1400
1401     if (pByte)
1402     {
1403         if (!pDst)
1404         {
1405             dwRet = dwSize;
1406         }
1407         else if (cbOff + cbMax < dwSize)
1408         {
1409             dwRet = cbMax;
1410         }
1411         else if (cbOff < dwSize)
1412         {
1413             dwRet = dwSize - cbOff;
1414         }
1415         else
1416         {
1417             dwRet = 0;
1418         }
1419         if (pDst && dwRet != 0)
1420         {
1421             memcpy(pDst, pByte + cbOff, dwRet);
1422         }
1423         DdeUnaccessData(hData);
1424     }
1425     else
1426     {
1427         dwRet = 0;
1428     }
1429     return dwRet;
1430 }
1431
1432 /*****************************************************************
1433  *            DdeAccessData (USER32.@)
1434  */
1435 LPBYTE WINAPI DdeAccessData(HDDEDATA hData, LPDWORD pcbDataSize)
1436 {
1437     HGLOBAL                     hMem = hData;
1438     DDE_DATAHANDLE_HEAD*        pDdh;
1439
1440     TRACE("(%p,%p)\n", hData, pcbDataSize);
1441
1442     pDdh = GlobalLock(hMem);
1443     if (pDdh == NULL)
1444     {
1445         ERR("Failed on GlobalLock(%p)\n", hMem);
1446         return 0;
1447     }
1448
1449     if (pcbDataSize != NULL)
1450     {
1451         *pcbDataSize = GlobalSize(hMem) - sizeof(DDE_DATAHANDLE_HEAD);
1452     }
1453     TRACE("=> %p (%lu) fmt %04x\n", pDdh + 1, GlobalSize(hMem) - sizeof(DDE_DATAHANDLE_HEAD), pDdh->cfFormat);
1454     return (LPBYTE)(pDdh + 1);
1455 }
1456
1457 /*****************************************************************
1458  *            DdeUnaccessData (USER32.@)
1459  */
1460 BOOL WINAPI DdeUnaccessData(HDDEDATA hData)
1461 {
1462     HGLOBAL hMem = hData;
1463
1464     TRACE("(%p)\n", hData);
1465
1466     GlobalUnlock(hMem);
1467
1468     return TRUE;
1469 }
1470
1471 /*****************************************************************
1472  *            DdeFreeDataHandle   (USER32.@)
1473  */
1474 BOOL WINAPI DdeFreeDataHandle(HDDEDATA hData)
1475 {
1476     TRACE("(%p)\n", hData);
1477
1478     /* 1 is the handle value returned by an asynchronous operation. */
1479     if (hData == (HDDEDATA)1)
1480         return TRUE;
1481
1482     return GlobalFree(hData) == 0;
1483 }
1484
1485 /******************************************************************
1486  *              WDML_IsAppOwned
1487  *
1488  *
1489  */
1490 BOOL WDML_IsAppOwned(HDDEDATA hData)
1491 {
1492     DDE_DATAHANDLE_HEAD*        pDdh;
1493     BOOL                        ret = FALSE;
1494
1495     pDdh = GlobalLock(hData);
1496     if (pDdh != NULL)
1497     {
1498         ret = pDdh->bAppOwned;
1499         GlobalUnlock(hData);
1500     }
1501     return ret;
1502 }
1503
1504 /* ================================================================
1505  *
1506  *                  Global <=> Data handle management
1507  *
1508  * ================================================================ */
1509
1510 /* Note: we use a DDEDATA, but layout of DDEDATA, DDEADVISE and DDEPOKE structures is similar:
1511  *    offset      size
1512  *    (bytes)    (bits) comment
1513  *      0          16   bit fields for options (release, ackreq, response...)
1514  *      2          16   clipboard format
1515  *      4          ?    data to be used
1516  */
1517 HDDEDATA        WDML_Global2DataHandle(WDML_CONV* pConv, HGLOBAL hMem, WINE_DDEHEAD* p)
1518 {
1519     DDEDATA*    pDd;
1520     HDDEDATA    ret = 0;
1521     DWORD       size;
1522
1523     if (hMem)
1524     {
1525         pDd = GlobalLock(hMem);
1526         size = GlobalSize(hMem) - sizeof(WINE_DDEHEAD);
1527         if (pDd)
1528         {
1529             if (p) memcpy(p, pDd, sizeof(WINE_DDEHEAD));
1530             switch (pDd->cfFormat)
1531             {
1532             default:
1533                 FIXME("Unsupported format (%04x) for data %p, passing raw information\n",
1534                       pDd->cfFormat, hMem);
1535                 /* fall through */
1536             case 0:
1537             case CF_TEXT:
1538                 ret = DdeCreateDataHandle(pConv->instance->instanceID, pDd->Value, size, 0, 0, pDd->cfFormat, 0);
1539                 break;
1540             case CF_BITMAP:
1541                 if (size >= sizeof(BITMAP))
1542                 {
1543                     BITMAP*     bmp = (BITMAP*)pDd->Value;
1544                     int         count = bmp->bmWidthBytes * bmp->bmHeight * bmp->bmPlanes;
1545                     if (size >= sizeof(BITMAP) + count)
1546                     {
1547                         HBITMAP hbmp;
1548
1549                         if ((hbmp = CreateBitmap(bmp->bmWidth, bmp->bmHeight,
1550                                                  bmp->bmPlanes, bmp->bmBitsPixel,
1551                                                  pDd->Value + sizeof(BITMAP))))
1552                         {
1553                             ret = DdeCreateDataHandle(pConv->instance->instanceID, (LPBYTE)&hbmp, sizeof(hbmp),
1554                                                       0, 0, CF_BITMAP, 0);
1555                         }
1556                         else ERR("Can't create bmp\n");
1557                     }
1558                     else
1559                     {
1560                         ERR("Wrong count: %u / %d\n", size, count);
1561                     }
1562                 } else ERR("No bitmap header\n");
1563                 break;
1564             }
1565             GlobalUnlock(hMem);
1566         }
1567     }
1568     return ret;
1569 }
1570
1571 /******************************************************************
1572  *              WDML_DataHandle2Global
1573  *
1574  *
1575  */
1576 HGLOBAL WDML_DataHandle2Global(HDDEDATA hDdeData, BOOL fResponse, BOOL fRelease,
1577                                BOOL fDeferUpd, BOOL fAckReq)
1578 {
1579     DDE_DATAHANDLE_HEAD*        pDdh;
1580     DWORD                       dwSize;
1581     HGLOBAL                     hMem = 0;
1582
1583     dwSize = GlobalSize(hDdeData) - sizeof(DDE_DATAHANDLE_HEAD);
1584     pDdh = GlobalLock(hDdeData);
1585     if (dwSize && pDdh)
1586     {
1587         WINE_DDEHEAD*    wdh = NULL;
1588
1589         switch (pDdh->cfFormat)
1590         {
1591         default:
1592             FIXME("Unsupported format (%04x) for data %p, passing raw information\n",
1593                    pDdh->cfFormat, hDdeData);
1594             /* fall through */
1595         case 0:
1596         case CF_TEXT:
1597             hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, sizeof(WINE_DDEHEAD) + dwSize);
1598             if (hMem && (wdh = GlobalLock(hMem)))
1599             {
1600                 memcpy(wdh + 1, pDdh + 1, dwSize);
1601             }
1602             break;
1603         case CF_BITMAP:
1604             if (dwSize >= sizeof(HBITMAP))
1605             {
1606                 BITMAP  bmp;
1607                 DWORD   count;
1608                 HBITMAP hbmp = *(HBITMAP*)(pDdh + 1);
1609
1610                 if (GetObjectW(hbmp, sizeof(bmp), &bmp))
1611                 {
1612                     count = bmp.bmWidthBytes * bmp.bmHeight;
1613                     hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1614                                        sizeof(WINE_DDEHEAD) + sizeof(bmp) + count);
1615                     if (hMem && (wdh = GlobalLock(hMem)))
1616                     {
1617                         memcpy(wdh + 1, &bmp, sizeof(bmp));
1618                         GetBitmapBits(hbmp, count, ((char*)(wdh + 1)) + sizeof(bmp));
1619                     }
1620                 }
1621             }
1622             break;
1623         }
1624         if (wdh)
1625         {
1626             wdh->unused = 0;
1627             wdh->fResponse = fResponse;
1628             wdh->fRelease = fRelease;
1629             wdh->fDeferUpd = fDeferUpd;
1630             wdh->fAckReq = fAckReq;
1631             wdh->cfFormat = pDdh->cfFormat;
1632             GlobalUnlock(hMem);
1633         }
1634         GlobalUnlock(hDdeData);
1635     }
1636
1637     return hMem;
1638 }
1639
1640 /* ================================================================
1641  *
1642  *                      Server management
1643  *
1644  * ================================================================ */
1645
1646 /******************************************************************
1647  *              WDML_AddServer
1648  *
1649  *
1650  */
1651 WDML_SERVER*    WDML_AddServer(WDML_INSTANCE* pInstance, HSZ hszService, HSZ hszTopic)
1652 {
1653     static const WCHAR fmtW[] = {'%','s','(','0','x','%','*','x',')',0};
1654     WDML_SERVER*        pServer;
1655     WCHAR               buf1[256];
1656     WCHAR               buf2[256];
1657
1658     pServer = HeapAlloc(GetProcessHeap(), 0, sizeof(WDML_SERVER));
1659     if (pServer == NULL) return NULL;
1660
1661     pServer->hszService = hszService;
1662     WDML_IncHSZ(pInstance, hszService);
1663
1664     DdeQueryStringW(pInstance->instanceID, hszService, buf1, 256, CP_WINUNICODE);
1665     snprintfW(buf2, 256, fmtW, buf1, 2*sizeof(ULONG_PTR), GetCurrentProcessId());
1666     pServer->hszServiceSpec = DdeCreateStringHandleW(pInstance->instanceID, buf2, CP_WINUNICODE);
1667
1668     pServer->atomService = WDML_MakeAtomFromHsz(pServer->hszService);
1669     pServer->atomServiceSpec = WDML_MakeAtomFromHsz(pServer->hszServiceSpec);
1670
1671     pServer->filterOn = TRUE;
1672
1673     pServer->next = pInstance->servers;
1674     pInstance->servers = pServer;
1675     return pServer;
1676 }
1677
1678 /******************************************************************
1679  *              WDML_RemoveServer
1680  *
1681  *
1682  */
1683 void WDML_RemoveServer(WDML_INSTANCE* pInstance, HSZ hszService, HSZ hszTopic)
1684 {
1685     WDML_SERVER*        pPrev = NULL;
1686     WDML_SERVER*        pServer = NULL;
1687     WDML_CONV*          pConv;
1688     WDML_CONV*          pConvNext;
1689
1690     pServer = pInstance->servers;
1691
1692     while (pServer != NULL)
1693     {
1694         if (DdeCmpStringHandles(pServer->hszService, hszService) == 0)
1695         {
1696             WDML_BroadcastDDEWindows(WDML_szEventClass, WM_WDML_UNREGISTER,
1697                                      pServer->atomService, pServer->atomServiceSpec);
1698             /* terminate all conversations for given topic */
1699             for (pConv = pInstance->convs[WDML_SERVER_SIDE]; pConv != NULL; pConv = pConvNext)
1700             {
1701                 pConvNext = pConv->next;
1702                 if (DdeCmpStringHandles(pConv->hszService, hszService) == 0)
1703                 {
1704                     HWND client = pConv->hwndClient, server = pConv->hwndServer;
1705                     WDML_RemoveConv(pConv, WDML_SERVER_SIDE);
1706                     /* don't care about return code (whether client window is present or not) */
1707                     PostMessageW(client, WM_DDE_TERMINATE, (WPARAM)server, 0);
1708                 }
1709             }
1710             if (pServer == pInstance->servers)
1711             {
1712                 pInstance->servers = pServer->next;
1713             }
1714             else
1715             {
1716                 pPrev->next = pServer->next;
1717             }
1718
1719             DestroyWindow(pServer->hwndServer);
1720             WDML_DecHSZ(pInstance, pServer->hszServiceSpec);
1721             WDML_DecHSZ(pInstance, pServer->hszService);
1722
1723             GlobalDeleteAtom(pServer->atomService);
1724             GlobalDeleteAtom(pServer->atomServiceSpec);
1725
1726             HeapFree(GetProcessHeap(), 0, pServer);
1727             break;
1728         }
1729
1730         pPrev = pServer;
1731         pServer = pServer->next;
1732     }
1733 }
1734
1735 /*****************************************************************************
1736  *      WDML_FindServer
1737  *
1738  *      generic routine to return a pointer to the relevant ServiceNode
1739  *      for a given service name, or NULL if the entry does not exist
1740  *
1741  */
1742 WDML_SERVER*    WDML_FindServer(WDML_INSTANCE* pInstance, HSZ hszService, HSZ hszTopic)
1743 {
1744     WDML_SERVER*        pServer;
1745
1746     for (pServer = pInstance->servers; pServer != NULL; pServer = pServer->next)
1747     {
1748         if (hszService == pServer->hszService)
1749         {
1750             return pServer;
1751         }
1752     }
1753     TRACE("Service name missing\n");
1754     return NULL;
1755 }
1756
1757 /* ================================================================
1758  *
1759  *                      Link (hot & warm) management
1760  *
1761  * ================================================================ */
1762
1763 /******************************************************************
1764  *              WDML_AddLink
1765  *
1766  *
1767  */
1768 void WDML_AddLink(WDML_INSTANCE* pInstance, HCONV hConv, WDML_SIDE side,
1769                   UINT wType, HSZ hszItem, UINT wFmt)
1770 {
1771     WDML_LINK*  pLink;
1772
1773     pLink = HeapAlloc(GetProcessHeap(), 0, sizeof(WDML_LINK));
1774     if (pLink == NULL)
1775     {
1776         ERR("OOM\n");
1777         return;
1778     }
1779
1780     pLink->hConv = hConv;
1781     pLink->transactionType = wType;
1782     WDML_IncHSZ(pInstance, pLink->hszItem = hszItem);
1783     pLink->uFmt = wFmt;
1784     pLink->next = pInstance->links[side];
1785     pInstance->links[side] = pLink;
1786 }
1787
1788 /******************************************************************
1789  *              WDML_RemoveLink
1790  *
1791  *
1792  */
1793 void WDML_RemoveLink(WDML_INSTANCE* pInstance, HCONV hConv, WDML_SIDE side,
1794                      HSZ hszItem, UINT uFmt)
1795 {
1796     WDML_LINK* pPrev = NULL;
1797     WDML_LINK* pCurrent = NULL;
1798
1799     pCurrent = pInstance->links[side];
1800
1801     while (pCurrent != NULL)
1802     {
1803         if (pCurrent->hConv == hConv &&
1804             DdeCmpStringHandles(pCurrent->hszItem, hszItem) == 0 &&
1805             pCurrent->uFmt == uFmt)
1806         {
1807             if (pCurrent == pInstance->links[side])
1808             {
1809                 pInstance->links[side] = pCurrent->next;
1810             }
1811             else
1812             {
1813                 pPrev->next = pCurrent->next;
1814             }
1815
1816             WDML_DecHSZ(pInstance, pCurrent->hszItem);
1817             HeapFree(GetProcessHeap(), 0, pCurrent);
1818             break;
1819         }
1820
1821         pPrev = pCurrent;
1822         pCurrent = pCurrent->next;
1823     }
1824 }
1825
1826 /* this function is called to remove all links related to the conv.
1827    It should be called from both client and server when terminating
1828    the conversation.
1829 */
1830 /******************************************************************
1831  *              WDML_RemoveAllLinks
1832  *
1833  *
1834  */
1835 static void WDML_RemoveAllLinks(WDML_INSTANCE* pInstance, WDML_CONV* pConv, WDML_SIDE side)
1836 {
1837     WDML_LINK* pPrev = NULL;
1838     WDML_LINK* pCurrent = NULL;
1839     WDML_LINK* pNext = NULL;
1840
1841     pCurrent = pInstance->links[side];
1842
1843     while (pCurrent != NULL)
1844     {
1845         if (pCurrent->hConv == (HCONV)pConv)
1846         {
1847             if (pCurrent == pInstance->links[side])
1848             {
1849                 pInstance->links[side] = pCurrent->next;
1850                 pNext = pCurrent->next;
1851             }
1852             else
1853             {
1854                 pPrev->next = pCurrent->next;
1855                 pNext = pCurrent->next;
1856             }
1857
1858             WDML_DecHSZ(pInstance, pCurrent->hszItem);
1859
1860             HeapFree(GetProcessHeap(), 0, pCurrent);
1861             pCurrent = NULL;
1862         }
1863
1864         if (pCurrent)
1865         {
1866             pPrev = pCurrent;
1867             pCurrent = pCurrent->next;
1868         }
1869         else
1870         {
1871             pCurrent = pNext;
1872         }
1873     }
1874 }
1875
1876 /******************************************************************
1877  *              WDML_FindLink
1878  *
1879  *
1880  */
1881 WDML_LINK*      WDML_FindLink(WDML_INSTANCE* pInstance, HCONV hConv, WDML_SIDE side,
1882                               HSZ hszItem, BOOL use_fmt, UINT uFmt)
1883 {
1884     WDML_LINK*  pCurrent = NULL;
1885
1886     for (pCurrent = pInstance->links[side]; pCurrent != NULL; pCurrent = pCurrent->next)
1887     {
1888         /* we don't need to check for transaction type as it can be altered */
1889
1890         if (pCurrent->hConv == hConv &&
1891             DdeCmpStringHandles(pCurrent->hszItem, hszItem) == 0 &&
1892             (!use_fmt || pCurrent->uFmt == uFmt))
1893         {
1894             break;
1895         }
1896
1897     }
1898
1899     return pCurrent;
1900 }
1901
1902 /* ================================================================
1903  *
1904  *                      Transaction management
1905  *
1906  * ================================================================ */
1907
1908 /******************************************************************
1909  *              WDML_AllocTransaction
1910  *
1911  * Alloc a transaction structure for handling the message ddeMsg
1912  */
1913 WDML_XACT*      WDML_AllocTransaction(WDML_INSTANCE* pInstance, UINT ddeMsg,
1914                                       UINT wFmt, HSZ hszItem)
1915 {
1916     WDML_XACT*          pXAct;
1917     static WORD         tid = 1;        /* FIXME: wrap around */
1918
1919     pXAct = HeapAlloc(GetProcessHeap(), 0, sizeof(WDML_XACT));
1920     if (!pXAct)
1921     {
1922         pInstance->lastError = DMLERR_MEMORY_ERROR;
1923         return NULL;
1924     }
1925
1926     pXAct->xActID = tid++;
1927     pXAct->ddeMsg = ddeMsg;
1928     pXAct->hDdeData = 0;
1929     pXAct->hUser = 0;
1930     pXAct->next = NULL;
1931     pXAct->wType = 0;
1932     pXAct->wFmt = wFmt;
1933     if ((pXAct->hszItem = hszItem)) WDML_IncHSZ(pInstance, pXAct->hszItem);
1934     pXAct->atom = 0;
1935     pXAct->hMem = 0;
1936     pXAct->lParam = 0;
1937
1938     return pXAct;
1939 }
1940
1941 /******************************************************************
1942  *              WDML_QueueTransaction
1943  *
1944  * Adds a transaction to the list of transaction
1945  */
1946 void    WDML_QueueTransaction(WDML_CONV* pConv, WDML_XACT* pXAct)
1947 {
1948     WDML_XACT** pt;
1949
1950     /* advance to last in queue */
1951     for (pt = &pConv->transactions; *pt != NULL; pt = &(*pt)->next);
1952     *pt = pXAct;
1953 }
1954
1955 /******************************************************************
1956  *              WDML_UnQueueTransaction
1957  *
1958  *
1959  */
1960 BOOL    WDML_UnQueueTransaction(WDML_CONV* pConv, WDML_XACT*  pXAct)
1961 {
1962     WDML_XACT** pt;
1963
1964     for (pt = &pConv->transactions; *pt; pt = &(*pt)->next)
1965     {
1966         if (*pt == pXAct)
1967         {
1968             *pt = pXAct->next;
1969             return TRUE;
1970         }
1971     }
1972     return FALSE;
1973 }
1974
1975 /******************************************************************
1976  *              WDML_FreeTransaction
1977  *
1978  *
1979  */
1980 void    WDML_FreeTransaction(WDML_INSTANCE* pInstance, WDML_XACT* pXAct, BOOL doFreePmt)
1981 {
1982     /* free pmt(s) in pXAct too. check against one for not deleting TRUE return values */
1983     if (doFreePmt && (ULONG_PTR)pXAct->hMem > 1)
1984     {
1985         GlobalFree(pXAct->hMem);
1986     }
1987     if (pXAct->hszItem) WDML_DecHSZ(pInstance, pXAct->hszItem);
1988
1989     HeapFree(GetProcessHeap(), 0, pXAct);
1990 }
1991
1992 /******************************************************************
1993  *              WDML_FindTransaction
1994  *
1995  *
1996  */
1997 static WDML_XACT* WDML_FindTransaction(WDML_CONV* pConv, DWORD tid)
1998 {
1999     WDML_XACT* pXAct;
2000
2001     tid = HIWORD(tid);
2002     for (pXAct = pConv->transactions; pXAct; pXAct = pXAct->next)
2003     {
2004         if (pXAct->xActID == tid)
2005             break;
2006     }
2007     return pXAct;
2008 }
2009
2010 /* ================================================================
2011  *
2012  *              Conversation management
2013  *
2014  * ================================================================ */
2015
2016 /******************************************************************
2017  *              WDML_AddConv
2018  *
2019  *
2020  */
2021 WDML_CONV*      WDML_AddConv(WDML_INSTANCE* pInstance, WDML_SIDE side,
2022                              HSZ hszService, HSZ hszTopic, HWND hwndClient, HWND hwndServer)
2023 {
2024     WDML_CONV*  pConv;
2025
2026     /* no conversation yet, add it */
2027     pConv = HeapAlloc(GetProcessHeap(), 0, sizeof(WDML_CONV));
2028     if (!pConv) return NULL;
2029
2030     pConv->instance = pInstance;
2031     WDML_IncHSZ(pInstance, pConv->hszService = hszService);
2032     WDML_IncHSZ(pInstance, pConv->hszTopic = hszTopic);
2033     pConv->magic = WDML_CONV_MAGIC;
2034     pConv->hwndServer = hwndServer;
2035     pConv->hwndClient = hwndClient;
2036     pConv->transactions = NULL;
2037     pConv->hUser = 0;
2038     pConv->wStatus = (side == WDML_CLIENT_SIDE) ? ST_CLIENT : 0L;
2039     pConv->wStatus |= pInstance->wStatus;
2040     /* check if both side of the conversation are of the same instance */
2041     if (GetWindowThreadProcessId(hwndClient, NULL) == GetWindowThreadProcessId(hwndServer, NULL) &&
2042         WDML_GetInstanceFromWnd(hwndClient) == WDML_GetInstanceFromWnd(hwndServer))
2043     {
2044         pConv->wStatus |= ST_ISSELF;
2045     }
2046     pConv->wConvst = XST_NULL;
2047
2048     pConv->next = pInstance->convs[side];
2049     pInstance->convs[side] = pConv;
2050
2051     TRACE("pConv->wStatus %04x pInstance(%p)\n", pConv->wStatus, pInstance);
2052
2053     return pConv;
2054 }
2055
2056 /******************************************************************
2057  *              WDML_FindConv
2058  *
2059  *
2060  */
2061 WDML_CONV*      WDML_FindConv(WDML_INSTANCE* pInstance, WDML_SIDE side,
2062                               HSZ hszService, HSZ hszTopic)
2063 {
2064     WDML_CONV*  pCurrent = NULL;
2065
2066     for (pCurrent = pInstance->convs[side]; pCurrent != NULL; pCurrent = pCurrent->next)
2067     {
2068         if (DdeCmpStringHandles(pCurrent->hszService, hszService) == 0 &&
2069             DdeCmpStringHandles(pCurrent->hszTopic, hszTopic) == 0)
2070         {
2071             return pCurrent;
2072         }
2073
2074     }
2075     return NULL;
2076 }
2077
2078 /******************************************************************
2079  *              WDML_RemoveConv
2080  *
2081  *
2082  */
2083 void WDML_RemoveConv(WDML_CONV* pRef, WDML_SIDE side)
2084 {
2085     WDML_CONV*  pPrev = NULL;
2086     WDML_CONV*  pCurrent;
2087     WDML_XACT*  pXAct;
2088     WDML_XACT*  pXActNext;
2089     HWND        hWnd;
2090
2091     if (!pRef)
2092         return;
2093
2094     /* remove any pending transaction */
2095     for (pXAct = pRef->transactions; pXAct != NULL; pXAct = pXActNext)
2096     {
2097         pXActNext = pXAct->next;
2098         WDML_FreeTransaction(pRef->instance, pXAct, TRUE);
2099     }
2100
2101     WDML_RemoveAllLinks(pRef->instance, pRef, side);
2102
2103     /* FIXME: should we keep the window around ? it seems so (at least on client side
2104      * to let QueryConvInfo work after conv termination, but also to implement
2105      * DdeReconnect...
2106      */
2107     /* destroy conversation window, but first remove pConv from hWnd.
2108      * this would help the wndProc do appropriate handling upon a WM_DESTROY message
2109      */
2110     hWnd = (side == WDML_CLIENT_SIDE) ? pRef->hwndClient : pRef->hwndServer;
2111     SetWindowLongPtrW(hWnd, GWL_WDML_CONVERSATION, 0);
2112
2113     DestroyWindow((side == WDML_CLIENT_SIDE) ? pRef->hwndClient : pRef->hwndServer);
2114
2115     WDML_DecHSZ(pRef->instance, pRef->hszService);
2116     WDML_DecHSZ(pRef->instance, pRef->hszTopic);
2117
2118     for (pCurrent = pRef->instance->convs[side]; pCurrent != NULL; pCurrent = (pPrev = pCurrent)->next)
2119     {
2120         if (pCurrent == pRef)
2121         {
2122             if (pCurrent == pRef->instance->convs[side])
2123             {
2124                 pRef->instance->convs[side] = pCurrent->next;
2125             }
2126             else
2127             {
2128                 pPrev->next = pCurrent->next;
2129             }
2130             pCurrent->magic = 0;
2131             HeapFree(GetProcessHeap(), 0, pCurrent);
2132             break;
2133         }
2134     }
2135 }
2136
2137 /******************************************************************
2138  *              WDML_EnableCallback
2139  */
2140 static BOOL WDML_EnableCallback(WDML_CONV *pConv, UINT wCmd)
2141 {
2142     if (wCmd == EC_DISABLE)
2143     {
2144         pConv->wStatus |= ST_BLOCKED;
2145         TRACE("EC_DISABLE: conv %p status flags %04x\n", pConv, pConv->wStatus);
2146         return TRUE;
2147     }
2148
2149     if (wCmd == EC_QUERYWAITING)
2150         return pConv->transactions != NULL;
2151
2152     if (wCmd != EC_ENABLEALL && wCmd != EC_ENABLEONE)
2153     {
2154         FIXME("Unknown command code %04x\n", wCmd);
2155         return FALSE;
2156     }
2157
2158     if (wCmd == EC_ENABLEALL)
2159     {
2160         pConv->wStatus &= ~ST_BLOCKED;
2161         TRACE("EC_ENABLEALL: conv %p status flags %04x\n", pConv, pConv->wStatus);
2162     }
2163
2164     while (pConv->transactions)
2165     {
2166         WDML_XACT *pXAct = pConv->transactions;
2167
2168         if (pConv->wStatus & ST_CLIENT)
2169         {
2170             /* transaction should be in the queue until handled */
2171             WDML_ClientHandle(pConv, pXAct, 0, NULL);
2172             WDML_UnQueueTransaction(pConv, pXAct);
2173         }
2174         else
2175         {
2176             /* transaction should be removed from the queue before handling */
2177             WDML_UnQueueTransaction(pConv, pXAct);
2178             WDML_ServerHandle(pConv, pXAct);
2179         }
2180
2181         WDML_FreeTransaction(pConv->instance, pXAct, TRUE);
2182
2183         if (wCmd == EC_ENABLEONE) break;
2184     }
2185     return TRUE;
2186 }
2187
2188 /*****************************************************************
2189  *            DdeEnableCallback (USER32.@)
2190  */
2191 BOOL WINAPI DdeEnableCallback(DWORD idInst, HCONV hConv, UINT wCmd)
2192 {
2193     BOOL ret = FALSE;
2194     WDML_CONV *pConv;
2195
2196     TRACE("(%d, %p, %04x)\n", idInst, hConv, wCmd);
2197
2198     if (hConv)
2199     {
2200         pConv = WDML_GetConv(hConv, TRUE);
2201
2202         if (pConv && pConv->instance->instanceID == idInst)
2203             ret = WDML_EnableCallback(pConv, wCmd);
2204     }
2205     else
2206     {
2207         WDML_INSTANCE *pInstance = WDML_GetInstance(idInst);
2208
2209         if (!pInstance)
2210             return FALSE;
2211
2212         TRACE("adding flags %04x to instance %p\n", wCmd, pInstance);
2213         pInstance->wStatus |= wCmd;
2214
2215         if (wCmd == EC_DISABLE)
2216         {
2217             pInstance->wStatus |= ST_BLOCKED;
2218             TRACE("EC_DISABLE: inst %p status flags %04x\n", pInstance, pInstance->wStatus);
2219         }
2220         else if (wCmd == EC_ENABLEALL)
2221         {
2222             pInstance->wStatus &= ~ST_BLOCKED;
2223             TRACE("EC_ENABLEALL: inst %p status flags %04x\n", pInstance, pInstance->wStatus);
2224         }
2225
2226         ret = TRUE;
2227
2228         for (pConv = pInstance->convs[WDML_CLIENT_SIDE]; pConv != NULL; pConv = pConv->next)
2229         {
2230             ret = WDML_EnableCallback(pConv, wCmd);
2231             if (ret && wCmd == EC_QUERYWAITING) break;
2232         }
2233     }
2234
2235     return ret;
2236 }
2237
2238 /******************************************************************
2239  *              WDML_GetConv
2240  *
2241  *
2242  */
2243 WDML_CONV*      WDML_GetConv(HCONV hConv, BOOL checkConnected)
2244 {
2245     WDML_CONV*  pConv = (WDML_CONV*)hConv;
2246
2247     /* FIXME: should do better checking */
2248     if (pConv == NULL || pConv->magic != WDML_CONV_MAGIC) return NULL;
2249
2250     if (!pConv->instance)
2251     {
2252         WARN("wrong thread ID, no instance\n");
2253         return NULL;
2254     }
2255
2256     if (pConv->instance->threadID != GetCurrentThreadId())
2257     {
2258         WARN("wrong thread ID\n");
2259         pConv->instance->lastError = DMLERR_INVALIDPARAMETER; /* FIXME: check */
2260         return NULL;
2261     }
2262
2263     if (checkConnected && !(pConv->wStatus & ST_CONNECTED))
2264     {
2265         WARN("found conv but ain't connected\n");
2266         pConv->instance->lastError = DMLERR_NO_CONV_ESTABLISHED;
2267         return NULL;
2268     }
2269
2270     return pConv;
2271 }
2272
2273 /******************************************************************
2274  *              WDML_GetConvFromWnd
2275  *
2276  *
2277  */
2278 WDML_CONV*      WDML_GetConvFromWnd(HWND hWnd)
2279 {
2280     return (WDML_CONV*)GetWindowLongPtrW(hWnd, GWL_WDML_CONVERSATION);
2281 }
2282
2283 /******************************************************************
2284  *              WDML_PostAck
2285  *
2286  *
2287  */
2288 BOOL            WDML_PostAck(WDML_CONV* pConv, WDML_SIDE side, WORD appRetCode,
2289                              BOOL fBusy, BOOL fAck, UINT_PTR pmt, LPARAM lParam, UINT oldMsg)
2290 {
2291     DDEACK      ddeAck;
2292     HWND        from, to;
2293
2294     if (side == WDML_SERVER_SIDE)
2295     {
2296         from = pConv->hwndServer;
2297         to   = pConv->hwndClient;
2298     }
2299     else
2300     {
2301         to   = pConv->hwndServer;
2302         from = pConv->hwndClient;
2303     }
2304
2305     ddeAck.bAppReturnCode = appRetCode;
2306     ddeAck.reserved       = 0;
2307     ddeAck.fBusy          = fBusy;
2308     ddeAck.fAck           = fAck;
2309
2310     TRACE("Posting a %s ack\n", ddeAck.fAck ? "positive" : "negative");
2311
2312     lParam = (lParam) ? ReuseDDElParam(lParam, oldMsg, WM_DDE_ACK, *(WORD*)&ddeAck, pmt) :
2313         PackDDElParam(WM_DDE_ACK, *(WORD*)&ddeAck, pmt);
2314     if (!PostMessageW(to, WM_DDE_ACK, (WPARAM)from, lParam))
2315     {
2316         pConv->wStatus &= ~ST_CONNECTED;
2317         pConv->instance->lastError = DMLERR_POSTMSG_FAILED;
2318         FreeDDElParam(WM_DDE_ACK, lParam);
2319         return FALSE;
2320     }
2321     return TRUE;
2322 }
2323
2324 /*****************************************************************
2325  *            DdeSetUserHandle (USER32.@)
2326  */
2327 BOOL WINAPI DdeSetUserHandle(HCONV hConv, DWORD id, DWORD hUser)
2328 {
2329     WDML_CONV*  pConv;
2330
2331     pConv = WDML_GetConv(hConv, FALSE);
2332     if (pConv == NULL)
2333         return FALSE;
2334
2335     if (id == QID_SYNC)
2336     {
2337         pConv->hUser = hUser;
2338     }
2339     else
2340     {
2341         WDML_XACT*      pXAct;
2342
2343         pXAct = WDML_FindTransaction(pConv, id);
2344         if (pXAct)
2345         {
2346             pXAct->hUser = hUser;
2347         }
2348         else
2349         {
2350             pConv->instance->lastError = DMLERR_UNFOUND_QUEUE_ID;
2351             return  FALSE;
2352         }
2353     }
2354     return TRUE;
2355 }
2356
2357 /******************************************************************
2358  *              WDML_GetLocalConvInfo
2359  *
2360  *
2361  */
2362 static  BOOL    WDML_GetLocalConvInfo(WDML_CONV* pConv, CONVINFO* ci, DWORD id)
2363 {
2364     BOOL        ret = TRUE;
2365     WDML_LINK*  pLink;
2366     WDML_SIDE   side;
2367
2368     ci->hConvPartner = (pConv->wStatus & ST_ISLOCAL) ? (HCONV)((ULONG_PTR)pConv | 1) : 0;
2369     ci->hszSvcPartner = pConv->hszService;
2370     ci->hszServiceReq = pConv->hszService; /* FIXME: they shouldn't be the same, should they ? */
2371     ci->hszTopic = pConv->hszTopic;
2372     ci->wStatus = pConv->wStatus;
2373
2374     side = (pConv->wStatus & ST_CLIENT) ? WDML_CLIENT_SIDE : WDML_SERVER_SIDE;
2375
2376     for (pLink = pConv->instance->links[side]; pLink != NULL; pLink = pLink->next)
2377     {
2378         if (pLink->hConv == (HCONV)pConv)
2379         {
2380             ci->wStatus |= ST_ADVISE;
2381             break;
2382         }
2383     }
2384
2385     /* FIXME: non handled status flags:
2386        ST_BLOCKED
2387        ST_BLOCKNEXT
2388        ST_INLIST
2389     */
2390
2391     ci->wConvst = pConv->wConvst; /* FIXME */
2392
2393     ci->wLastError = 0; /* FIXME: note it's not the instance last error */
2394     ci->hConvList = 0;
2395     ci->ConvCtxt = pConv->convContext;
2396     if (ci->wStatus & ST_CLIENT)
2397     {
2398         ci->hwnd = pConv->hwndClient;
2399         ci->hwndPartner = pConv->hwndServer;
2400     }
2401     else
2402     {
2403         ci->hwnd = pConv->hwndServer;
2404         ci->hwndPartner = pConv->hwndClient;
2405     }
2406     if (id == QID_SYNC)
2407     {
2408         ci->hUser = pConv->hUser;
2409         ci->hszItem = 0;
2410         ci->wFmt = 0;
2411         ci->wType = 0;
2412     }
2413     else
2414     {
2415         WDML_XACT*      pXAct;
2416
2417         pXAct = WDML_FindTransaction(pConv, id);
2418         if (pXAct)
2419         {
2420             ci->hUser = pXAct->hUser;
2421             ci->hszItem = pXAct->hszItem;
2422             ci->wFmt = pXAct->wFmt;
2423             ci->wType = pXAct->wType;
2424         }
2425         else
2426         {
2427             ret = 0;
2428             pConv->instance->lastError = DMLERR_UNFOUND_QUEUE_ID;
2429         }
2430     }
2431     return ret;
2432 }
2433
2434 /******************************************************************
2435  *              DdeQueryConvInfo (USER32.@)
2436  *
2437  * FIXME: Set last DDE error on failure.
2438  */
2439 UINT WINAPI DdeQueryConvInfo(HCONV hConv, DWORD id, PCONVINFO lpConvInfo)
2440 {
2441     UINT        ret = lpConvInfo->cb;
2442     CONVINFO    ci;
2443     WDML_CONV*  pConv;
2444
2445     TRACE("(%p,%x,%p)\n", hConv, id, lpConvInfo);
2446
2447     if (!hConv)
2448     {
2449         FIXME("hConv is NULL\n");
2450         return 0;
2451     }
2452
2453     pConv = WDML_GetConv(hConv, FALSE);
2454     if (pConv != NULL)
2455     {
2456         if (!WDML_GetLocalConvInfo(pConv, &ci, id))
2457             ret = 0;
2458     }
2459     else
2460     {
2461         if ((ULONG_PTR)hConv & 1)
2462         {
2463             pConv = WDML_GetConv((HCONV)((ULONG_PTR)hConv & ~1), FALSE);
2464             if (pConv != NULL)
2465                 FIXME("Request on remote conversation information is not implemented yet\n");
2466         }
2467         ret = 0;
2468     }
2469
2470     if (ret != 0)
2471         memcpy(lpConvInfo, &ci, min((size_t)lpConvInfo->cb, sizeof(ci)));
2472     return ret;
2473 }
2474
2475 /* ================================================================
2476  *
2477  *         Information broadcast across DDEML implementations
2478  *
2479  * ================================================================ */
2480
2481 struct tagWDML_BroadcastPmt
2482 {
2483     LPCWSTR     clsName;
2484     UINT        uMsg;
2485     WPARAM      wParam;
2486     LPARAM      lParam;
2487 };
2488
2489 /******************************************************************
2490  *              WDML_BroadcastEnumProc
2491  *
2492  *
2493  */
2494 static  BOOL CALLBACK WDML_BroadcastEnumProc(HWND hWnd, LPARAM lParam)
2495 {
2496     struct tagWDML_BroadcastPmt*        s = (struct tagWDML_BroadcastPmt*)lParam;
2497     WCHAR                               buffer[128];
2498
2499     if (GetClassNameW(hWnd, buffer, 128) > 0 &&
2500         lstrcmpiW(buffer, s->clsName) == 0)
2501     {
2502         PostMessageW(hWnd, s->uMsg, s->wParam, s->lParam);
2503     }
2504     return TRUE;
2505 }
2506
2507 /******************************************************************
2508  *              WDML_BroadcastDDEWindows
2509  *
2510  *
2511  */
2512 void WDML_BroadcastDDEWindows(LPCWSTR clsName, UINT uMsg, WPARAM wParam, LPARAM lParam)
2513 {
2514     struct tagWDML_BroadcastPmt s;
2515
2516     s.clsName = clsName;
2517     s.uMsg    = uMsg;
2518     s.wParam  = wParam;
2519     s.lParam  = lParam;
2520     EnumWindows(WDML_BroadcastEnumProc, (LPARAM)&s);
2521 }