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