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