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