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