ole32: Remove some superfluous casts of void pointers and zero.
[wine] / dlls / ole32 / ole2.c
1 /*
2  *      OLE2 library
3  *
4  * Copyright 1995 Martin von Loewis
5  * Copyright 1999 Francis Beaudet
6  * Copyright 1999 Noel Borthwick
7  * Copyright 1999, 2000 Marcus Meissner
8  * Copyright 2005 Juan Lang
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26
27 #include <assert.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <string.h>
32
33 #define COBJMACROS
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
36
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "wingdi.h"
41 #include "winuser.h"
42 #include "winnls.h"
43 #include "winreg.h"
44 #include "ole2.h"
45 #include "ole2ver.h"
46
47 #include "wine/unicode.h"
48 #include "compobj_private.h"
49 #include "wine/list.h"
50
51 #include "wine/debug.h"
52
53 WINE_DEFAULT_DEBUG_CHANNEL(ole);
54 WINE_DECLARE_DEBUG_CHANNEL(accel);
55
56 /******************************************************************************
57  * These are static/global variables and internal data structures that the
58  * OLE module uses to maintain it's state.
59  */
60 typedef struct tagDropTargetNode
61 {
62   HWND          hwndTarget;
63   IDropTarget*  dropTarget;
64   struct list   entry;
65 } DropTargetNode;
66
67 typedef struct tagTrackerWindowInfo
68 {
69   IDataObject* dataObject;
70   IDropSource* dropSource;
71   DWORD        dwOKEffect;
72   DWORD*       pdwEffect;
73   BOOL       trackingDone;
74   HRESULT      returnValue;
75
76   BOOL       escPressed;
77   HWND       curTargetHWND;     /* window the mouse is hovering over */
78   HWND       curDragTargetHWND; /* might be a ancestor of curTargetHWND */
79   IDropTarget* curDragTarget;
80   POINTL     curMousePos;       /* current position of the mouse in screen coordinates */
81   DWORD      dwKeyState;        /* current state of the shift and ctrl keys and the mouse buttons */
82 } TrackerWindowInfo;
83
84 typedef struct tagOleMenuDescriptor  /* OleMenuDescriptor */
85 {
86   HWND               hwndFrame;         /* The containers frame window */
87   HWND               hwndActiveObject;  /* The active objects window */
88   OLEMENUGROUPWIDTHS mgw;               /* OLE menu group widths for the shared menu */
89   HMENU              hmenuCombined;     /* The combined menu */
90   BOOL               bIsServerItem;     /* True if the currently open popup belongs to the server */
91 } OleMenuDescriptor;
92
93 typedef struct tagOleMenuHookItem   /* OleMenu hook item in per thread hook list */
94 {
95   DWORD tid;                /* Thread Id  */
96   HANDLE hHeap;             /* Heap this is allocated from */
97   HHOOK GetMsg_hHook;       /* message hook for WH_GETMESSAGE */
98   HHOOK CallWndProc_hHook;  /* message hook for WH_CALLWNDPROC */
99   struct tagOleMenuHookItem *next;
100 } OleMenuHookItem;
101
102 static OleMenuHookItem *hook_list;
103
104 /*
105  * This is the lock count on the OLE library. It is controlled by the
106  * OLEInitialize/OLEUninitialize methods.
107  */
108 static LONG OLE_moduleLockCount = 0;
109
110 /*
111  * Name of our registered window class.
112  */
113 static const char OLEDD_DRAGTRACKERCLASS[] = "WineDragDropTracker32";
114
115 /*
116  * This is the head of the Drop target container.
117  */
118 static struct list targetListHead = LIST_INIT(targetListHead);
119
120 /******************************************************************************
121  * These are the prototypes of miscellaneous utility methods
122  */
123 static void OLEUTL_ReadRegistryDWORDValue(HKEY regKey, DWORD* pdwValue);
124
125 /******************************************************************************
126  * These are the prototypes of the utility methods used to manage a shared menu
127  */
128 static void OLEMenu_Initialize(void);
129 static void OLEMenu_UnInitialize(void);
130 static BOOL OLEMenu_InstallHooks( DWORD tid );
131 static BOOL OLEMenu_UnInstallHooks( DWORD tid );
132 static OleMenuHookItem * OLEMenu_IsHookInstalled( DWORD tid );
133 static BOOL OLEMenu_FindMainMenuIndex( HMENU hMainMenu, HMENU hPopupMenu, UINT *pnPos );
134 static BOOL OLEMenu_SetIsServerMenu( HMENU hmenu, OleMenuDescriptor *pOleMenuDescriptor );
135 static LRESULT CALLBACK OLEMenu_CallWndProc(INT code, WPARAM wParam, LPARAM lParam);
136 static LRESULT CALLBACK OLEMenu_GetMsgProc(INT code, WPARAM wParam, LPARAM lParam);
137
138 /******************************************************************************
139  * These are the prototypes of the OLE Clipboard initialization methods (in clipboard.c)
140  */
141 extern void OLEClipbrd_UnInitialize(void);
142 extern void OLEClipbrd_Initialize(void);
143
144 /******************************************************************************
145  * These are the prototypes of the utility methods used for OLE Drag n Drop
146  */
147 static void            OLEDD_Initialize(void);
148 static DropTargetNode* OLEDD_FindDropTarget(
149                          HWND hwndOfTarget);
150 static void            OLEDD_FreeDropTarget(DropTargetNode*, BOOL);
151 static LRESULT WINAPI  OLEDD_DragTrackerWindowProc(
152                          HWND   hwnd,
153                          UINT   uMsg,
154                          WPARAM wParam,
155                          LPARAM   lParam);
156 static void OLEDD_TrackMouseMove(
157                          TrackerWindowInfo* trackerInfo);
158 static void OLEDD_TrackStateChange(
159                          TrackerWindowInfo* trackerInfo);
160 static DWORD OLEDD_GetButtonState(void);
161
162
163 /******************************************************************************
164  *              OleBuildVersion [OLE2.1]
165  *              OleBuildVersion [OLE32.@]
166  */
167 DWORD WINAPI OleBuildVersion(void)
168 {
169     TRACE("Returning version %d, build %d.\n", rmm, rup);
170     return (rmm<<16)+rup;
171 }
172
173 /***********************************************************************
174  *           OleInitialize       (OLE2.2)
175  *           OleInitialize       (OLE32.@)
176  */
177 HRESULT WINAPI OleInitialize(LPVOID reserved)
178 {
179   HRESULT hr;
180
181   TRACE("(%p)\n", reserved);
182
183   /*
184    * The first duty of the OleInitialize is to initialize the COM libraries.
185    */
186   hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
187
188   /*
189    * If the CoInitializeEx call failed, the OLE libraries can't be
190    * initialized.
191    */
192   if (FAILED(hr))
193     return hr;
194
195   /*
196    * Then, it has to initialize the OLE specific modules.
197    * This includes:
198    *     Clipboard
199    *     Drag and Drop
200    *     Object linking and Embedding
201    *     In-place activation
202    */
203   if (!COM_CurrentInfo()->ole_inits++ &&
204       InterlockedIncrement(&OLE_moduleLockCount) == 1)
205   {
206     /*
207      * Initialize the libraries.
208      */
209     TRACE("() - Initializing the OLE libraries\n");
210
211     /*
212      * OLE Clipboard
213      */
214     OLEClipbrd_Initialize();
215
216     /*
217      * Drag and Drop
218      */
219     OLEDD_Initialize();
220
221     /*
222      * OLE shared menu
223      */
224     OLEMenu_Initialize();
225   }
226
227   return hr;
228 }
229
230 /******************************************************************************
231  *              OleUninitialize [OLE2.3]
232  *              OleUninitialize [OLE32.@]
233  */
234 void WINAPI OleUninitialize(void)
235 {
236   TRACE("()\n");
237
238   /*
239    * If we hit the bottom of the lock stack, free the libraries.
240    */
241   if (!--COM_CurrentInfo()->ole_inits && !InterlockedDecrement(&OLE_moduleLockCount))
242   {
243     /*
244      * Actually free the libraries.
245      */
246     TRACE("() - Freeing the last reference count\n");
247
248     /*
249      * OLE Clipboard
250      */
251     OLEClipbrd_UnInitialize();
252
253     /*
254      * OLE shared menu
255      */
256     OLEMenu_UnInitialize();
257   }
258
259   /*
260    * Then, uninitialize the COM libraries.
261    */
262   CoUninitialize();
263 }
264
265 /******************************************************************************
266  *              OleInitializeWOW        [OLE32.@]
267  */
268 HRESULT WINAPI OleInitializeWOW(DWORD x, DWORD y) {
269         FIXME("(0x%08x, 0x%08x),stub!\n",x, y);
270         return 0;
271 }
272
273 /***********************************************************************
274  *           RegisterDragDrop (OLE32.@)
275  */
276 HRESULT WINAPI RegisterDragDrop(
277         HWND hwnd,
278         LPDROPTARGET pDropTarget)
279 {
280   DropTargetNode* dropTargetInfo;
281
282   TRACE("(%p,%p)\n", hwnd, pDropTarget);
283
284   if (!COM_CurrentApt())
285   {
286     ERR("COM not initialized\n");
287     return E_OUTOFMEMORY;
288   }
289
290   if (!pDropTarget)
291     return E_INVALIDARG;
292
293   if (!IsWindow(hwnd))
294   {
295     ERR("invalid hwnd %p\n", hwnd);
296     return DRAGDROP_E_INVALIDHWND;
297   }
298
299   /*
300    * First, check if the window is already registered.
301    */
302   dropTargetInfo = OLEDD_FindDropTarget(hwnd);
303
304   if (dropTargetInfo!=NULL)
305     return DRAGDROP_E_ALREADYREGISTERED;
306
307   /*
308    * If it's not there, we can add it. We first create a node for it.
309    */
310   dropTargetInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(DropTargetNode));
311
312   if (dropTargetInfo==NULL)
313     return E_OUTOFMEMORY;
314
315   dropTargetInfo->hwndTarget     = hwnd;
316
317   /*
318    * Don't forget that this is an interface pointer, need to nail it down since
319    * we keep a copy of it.
320    */
321   IDropTarget_AddRef(pDropTarget);
322   dropTargetInfo->dropTarget  = pDropTarget;
323
324   list_add_tail(&targetListHead, &dropTargetInfo->entry);
325
326   return S_OK;
327 }
328
329 /***********************************************************************
330  *           RevokeDragDrop (OLE32.@)
331  */
332 HRESULT WINAPI RevokeDragDrop(
333         HWND hwnd)
334 {
335   DropTargetNode* dropTargetInfo;
336
337   TRACE("(%p)\n", hwnd);
338
339   if (!IsWindow(hwnd))
340   {
341     ERR("invalid hwnd %p\n", hwnd);
342     return DRAGDROP_E_INVALIDHWND;
343   }
344
345   /*
346    * First, check if the window is already registered.
347    */
348   dropTargetInfo = OLEDD_FindDropTarget(hwnd);
349
350   /*
351    * If it ain't in there, it's an error.
352    */
353   if (dropTargetInfo==NULL)
354     return DRAGDROP_E_NOTREGISTERED;
355
356   OLEDD_FreeDropTarget(dropTargetInfo, TRUE);
357
358   return S_OK;
359 }
360
361 /***********************************************************************
362  *           OleRegGetUserType (OLE32.@)
363  *
364  * This implementation of OleRegGetUserType ignores the dwFormOfType
365  * parameter and always returns the full name of the object. This is
366  * not too bad since this is the case for many objects because of the
367  * way they are registered.
368  */
369 HRESULT WINAPI OleRegGetUserType(
370         REFCLSID clsid,
371         DWORD dwFormOfType,
372         LPOLESTR* pszUserType)
373 {
374   char    keyName[60];
375   DWORD   dwKeyType;
376   DWORD   cbData;
377   HKEY    clsidKey;
378   LONG    hres;
379   LPSTR   buffer;
380   HRESULT retVal;
381   /*
382    * Initialize the out parameter.
383    */
384   *pszUserType = NULL;
385
386   /*
387    * Build the key name we're looking for
388    */
389   sprintf( keyName, "CLSID\\{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\",
390            clsid->Data1, clsid->Data2, clsid->Data3,
391            clsid->Data4[0], clsid->Data4[1], clsid->Data4[2], clsid->Data4[3],
392            clsid->Data4[4], clsid->Data4[5], clsid->Data4[6], clsid->Data4[7] );
393
394   TRACE("(%s, %d, %p)\n", keyName, dwFormOfType, pszUserType);
395
396   /*
397    * Open the class id Key
398    */
399   hres = RegOpenKeyA(HKEY_CLASSES_ROOT,
400                      keyName,
401                      &clsidKey);
402
403   if (hres != ERROR_SUCCESS)
404     return REGDB_E_CLASSNOTREG;
405
406   /*
407    * Retrieve the size of the name string.
408    */
409   cbData = 0;
410
411   hres = RegQueryValueExA(clsidKey,
412                           "",
413                           NULL,
414                           &dwKeyType,
415                           NULL,
416                           &cbData);
417
418   if (hres!=ERROR_SUCCESS)
419   {
420     RegCloseKey(clsidKey);
421     return REGDB_E_READREGDB;
422   }
423
424   /*
425    * Allocate a buffer for the registry value.
426    */
427   *pszUserType = CoTaskMemAlloc(cbData*2);
428
429   if (*pszUserType==NULL)
430   {
431     RegCloseKey(clsidKey);
432     return E_OUTOFMEMORY;
433   }
434
435   buffer = HeapAlloc(GetProcessHeap(), 0, cbData);
436
437   if (buffer == NULL)
438   {
439     RegCloseKey(clsidKey);
440     CoTaskMemFree(*pszUserType);
441     *pszUserType=NULL;
442     return E_OUTOFMEMORY;
443   }
444
445   hres = RegQueryValueExA(clsidKey,
446                           "",
447                           NULL,
448                           &dwKeyType,
449                           (LPBYTE) buffer,
450                           &cbData);
451
452   RegCloseKey(clsidKey);
453
454
455   if (hres!=ERROR_SUCCESS)
456   {
457     CoTaskMemFree(*pszUserType);
458     *pszUserType=NULL;
459
460     retVal = REGDB_E_READREGDB;
461   }
462   else
463   {
464     MultiByteToWideChar( CP_ACP, 0, buffer, -1, *pszUserType, cbData /*FIXME*/ );
465     retVal = S_OK;
466   }
467   HeapFree(GetProcessHeap(), 0, buffer);
468
469   return retVal;
470 }
471
472 /***********************************************************************
473  * DoDragDrop [OLE32.@]
474  */
475 HRESULT WINAPI DoDragDrop (
476   IDataObject *pDataObject,  /* [in] ptr to the data obj           */
477   IDropSource* pDropSource,  /* [in] ptr to the source obj         */
478   DWORD       dwOKEffect,    /* [in] effects allowed by the source */
479   DWORD       *pdwEffect)    /* [out] ptr to effects of the source */
480 {
481   TrackerWindowInfo trackerInfo;
482   HWND            hwndTrackWindow;
483   MSG             msg;
484
485   TRACE("(DataObject %p, DropSource %p)\n", pDataObject, pDropSource);
486
487   /*
488    * Setup the drag n drop tracking window.
489    */
490   if (!IsValidInterface((LPUNKNOWN)pDropSource))
491       return E_INVALIDARG;
492
493   trackerInfo.dataObject        = pDataObject;
494   trackerInfo.dropSource        = pDropSource;
495   trackerInfo.dwOKEffect        = dwOKEffect;
496   trackerInfo.pdwEffect         = pdwEffect;
497   trackerInfo.trackingDone      = FALSE;
498   trackerInfo.escPressed        = FALSE;
499   trackerInfo.curDragTargetHWND = 0;
500   trackerInfo.curTargetHWND     = 0;
501   trackerInfo.curDragTarget     = 0;
502
503   hwndTrackWindow = CreateWindowA(OLEDD_DRAGTRACKERCLASS,
504                                     "TrackerWindow",
505                                     WS_POPUP,
506                                     CW_USEDEFAULT, CW_USEDEFAULT,
507                                     CW_USEDEFAULT, CW_USEDEFAULT,
508                                     0,
509                                     0,
510                                     0,
511                                     (LPVOID)&trackerInfo);
512
513   if (hwndTrackWindow!=0)
514   {
515     /*
516      * Capture the mouse input
517      */
518     SetCapture(hwndTrackWindow);
519
520     msg.message = 0;
521
522     /*
523      * Pump messages. All mouse input should go to the capture window.
524      */
525     while (!trackerInfo.trackingDone && GetMessageA(&msg, 0, 0, 0) )
526     {
527       trackerInfo.curMousePos.x = msg.pt.x;
528       trackerInfo.curMousePos.y = msg.pt.y;
529       trackerInfo.dwKeyState = OLEDD_GetButtonState();
530             
531       if ( (msg.message >= WM_KEYFIRST) &&
532            (msg.message <= WM_KEYLAST) )
533       {
534         /*
535          * When keyboard messages are sent to windows on this thread, we
536          * want to ignore notify the drop source that the state changed.
537          * in the case of the Escape key, we also notify the drop source
538          * we give it a special meaning.
539          */
540         if ( (msg.message==WM_KEYDOWN) &&
541              (msg.wParam==VK_ESCAPE) )
542         {
543           trackerInfo.escPressed = TRUE;
544         }
545
546         /*
547          * Notify the drop source.
548          */
549         OLEDD_TrackStateChange(&trackerInfo);
550       }
551       else
552       {
553         /*
554          * Dispatch the messages only when it's not a keyboard message.
555          */
556         DispatchMessageA(&msg);
557       }
558     }
559
560     /* re-post the quit message to outer message loop */
561     if (msg.message == WM_QUIT)
562         PostQuitMessage(msg.wParam);
563     /*
564      * Destroy the temporary window.
565      */
566     DestroyWindow(hwndTrackWindow);
567
568     return trackerInfo.returnValue;
569   }
570
571   return E_FAIL;
572 }
573
574 /***********************************************************************
575  * OleQueryLinkFromData [OLE32.@]
576  */
577 HRESULT WINAPI OleQueryLinkFromData(
578   IDataObject* pSrcDataObject)
579 {
580   FIXME("(%p),stub!\n", pSrcDataObject);
581   return S_OK;
582 }
583
584 /***********************************************************************
585  * OleRegGetMiscStatus [OLE32.@]
586  */
587 HRESULT WINAPI OleRegGetMiscStatus(
588   REFCLSID clsid,
589   DWORD    dwAspect,
590   DWORD*   pdwStatus)
591 {
592   char    keyName[60];
593   HKEY    clsidKey;
594   HKEY    miscStatusKey;
595   HKEY    aspectKey;
596   LONG    result;
597
598   /*
599    * Initialize the out parameter.
600    */
601   *pdwStatus = 0;
602
603   /*
604    * Build the key name we're looking for
605    */
606   sprintf( keyName, "CLSID\\{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\",
607            clsid->Data1, clsid->Data2, clsid->Data3,
608            clsid->Data4[0], clsid->Data4[1], clsid->Data4[2], clsid->Data4[3],
609            clsid->Data4[4], clsid->Data4[5], clsid->Data4[6], clsid->Data4[7] );
610
611   TRACE("(%s, %d, %p)\n", keyName, dwAspect, pdwStatus);
612
613   /*
614    * Open the class id Key
615    */
616   result = RegOpenKeyA(HKEY_CLASSES_ROOT,
617                        keyName,
618                        &clsidKey);
619
620   if (result != ERROR_SUCCESS)
621     return REGDB_E_CLASSNOTREG;
622
623   /*
624    * Get the MiscStatus
625    */
626   result = RegOpenKeyA(clsidKey,
627                        "MiscStatus",
628                        &miscStatusKey);
629
630
631   if (result != ERROR_SUCCESS)
632   {
633     RegCloseKey(clsidKey);
634     return REGDB_E_READREGDB;
635   }
636
637   /*
638    * Read the default value
639    */
640   OLEUTL_ReadRegistryDWORDValue(miscStatusKey, pdwStatus);
641
642   /*
643    * Open the key specific to the requested aspect.
644    */
645   sprintf(keyName, "%d", dwAspect);
646
647   result = RegOpenKeyA(miscStatusKey,
648                        keyName,
649                        &aspectKey);
650
651   if (result == ERROR_SUCCESS)
652   {
653     OLEUTL_ReadRegistryDWORDValue(aspectKey, pdwStatus);
654     RegCloseKey(aspectKey);
655   }
656
657   /*
658    * Cleanup
659    */
660   RegCloseKey(miscStatusKey);
661   RegCloseKey(clsidKey);
662
663   return S_OK;
664 }
665
666 static HRESULT EnumOLEVERB_Construct(HKEY hkeyVerb, ULONG index, IEnumOLEVERB **ppenum);
667
668 typedef struct
669 {
670     const IEnumOLEVERBVtbl *lpvtbl;
671     LONG ref;
672
673     HKEY hkeyVerb;
674     ULONG index;
675 } EnumOLEVERB;
676
677 static HRESULT WINAPI EnumOLEVERB_QueryInterface(
678     IEnumOLEVERB *iface, REFIID riid, void **ppv)
679 {
680     TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
681     if (IsEqualIID(riid, &IID_IUnknown) ||
682         IsEqualIID(riid, &IID_IEnumOLEVERB))
683     {
684         IUnknown_AddRef(iface);
685         *ppv = iface;
686         return S_OK;
687     }
688     return E_NOINTERFACE;
689 }
690
691 static ULONG WINAPI EnumOLEVERB_AddRef(
692     IEnumOLEVERB *iface)
693 {
694     EnumOLEVERB *This = (EnumOLEVERB *)iface;
695     TRACE("()\n");
696     return InterlockedIncrement(&This->ref);
697 }
698
699 static ULONG WINAPI EnumOLEVERB_Release(
700     IEnumOLEVERB *iface)
701 {
702     EnumOLEVERB *This = (EnumOLEVERB *)iface;
703     LONG refs = InterlockedDecrement(&This->ref);
704     TRACE("()\n");
705     if (!refs)
706     {
707         RegCloseKey(This->hkeyVerb);
708         HeapFree(GetProcessHeap(), 0, This);
709     }
710     return refs;
711 }
712
713 static HRESULT WINAPI EnumOLEVERB_Next(
714     IEnumOLEVERB *iface, ULONG celt, LPOLEVERB rgelt,
715     ULONG *pceltFetched)
716 {
717     EnumOLEVERB *This = (EnumOLEVERB *)iface;
718     HRESULT hr = S_OK;
719
720     TRACE("(%d, %p, %p)\n", celt, rgelt, pceltFetched);
721
722     if (pceltFetched)
723         *pceltFetched = 0;
724
725     for (; celt; celt--, rgelt++)
726     {
727         WCHAR wszSubKey[20];
728         LONG cbData;
729         LPWSTR pwszOLEVERB;
730         LPWSTR pwszMenuFlags;
731         LPWSTR pwszAttribs;
732         LONG res = RegEnumKeyW(This->hkeyVerb, This->index, wszSubKey, sizeof(wszSubKey)/sizeof(wszSubKey[0]));
733         if (res == ERROR_NO_MORE_ITEMS)
734         {
735             hr = S_FALSE;
736             break;
737         }
738         else if (res != ERROR_SUCCESS)
739         {
740             ERR("RegEnumKeyW failed with error %d\n", res);
741             hr = REGDB_E_READREGDB;
742             break;
743         }
744         res = RegQueryValueW(This->hkeyVerb, wszSubKey, NULL, &cbData);
745         if (res != ERROR_SUCCESS)
746         {
747             ERR("RegQueryValueW failed with error %d\n", res);
748             hr = REGDB_E_READREGDB;
749             break;
750         }
751         pwszOLEVERB = CoTaskMemAlloc(cbData);
752         if (!pwszOLEVERB)
753         {
754             hr = E_OUTOFMEMORY;
755             break;
756         }
757         res = RegQueryValueW(This->hkeyVerb, wszSubKey, pwszOLEVERB, &cbData);
758         if (res != ERROR_SUCCESS)
759         {
760             ERR("RegQueryValueW failed with error %d\n", res);
761             hr = REGDB_E_READREGDB;
762             CoTaskMemFree(pwszOLEVERB);
763             break;
764         }
765
766         TRACE("verb string: %s\n", debugstr_w(pwszOLEVERB));
767         pwszMenuFlags = strchrW(pwszOLEVERB, ',');
768         if (!pwszMenuFlags)
769         {
770             hr = OLEOBJ_E_INVALIDVERB;
771             CoTaskMemFree(pwszOLEVERB);
772             break;
773         }
774         /* nul terminate the name string and advance to first character */
775         *pwszMenuFlags = '\0';
776         pwszMenuFlags++;
777         pwszAttribs = strchrW(pwszMenuFlags, ',');
778         if (!pwszAttribs)
779         {
780             hr = OLEOBJ_E_INVALIDVERB;
781             CoTaskMemFree(pwszOLEVERB);
782             break;
783         }
784         /* nul terminate the menu string and advance to first character */
785         *pwszAttribs = '\0';
786         pwszAttribs++;
787
788         /* fill out structure for this verb */
789         rgelt->lVerb = atolW(wszSubKey);
790         rgelt->lpszVerbName = pwszOLEVERB; /* user should free */
791         rgelt->fuFlags = atolW(pwszMenuFlags);
792         rgelt->grfAttribs = atolW(pwszAttribs);
793
794         if (pceltFetched)
795             (*pceltFetched)++;
796         This->index++;
797     }
798     return hr;
799 }
800
801 static HRESULT WINAPI EnumOLEVERB_Skip(
802     IEnumOLEVERB *iface, ULONG celt)
803 {
804     EnumOLEVERB *This = (EnumOLEVERB *)iface;
805
806     TRACE("(%d)\n", celt);
807
808     This->index += celt;
809     return S_OK;
810 }
811
812 static HRESULT WINAPI EnumOLEVERB_Reset(
813     IEnumOLEVERB *iface)
814 {
815     EnumOLEVERB *This = (EnumOLEVERB *)iface;
816
817     TRACE("()\n");
818
819     This->index = 0;
820     return S_OK;
821 }
822
823 static HRESULT WINAPI EnumOLEVERB_Clone(
824     IEnumOLEVERB *iface,
825     IEnumOLEVERB **ppenum)
826 {
827     EnumOLEVERB *This = (EnumOLEVERB *)iface;
828     HKEY hkeyVerb;
829     TRACE("(%p)\n", ppenum);
830     if (!DuplicateHandle(GetCurrentProcess(), This->hkeyVerb, GetCurrentProcess(), (HANDLE *)&hkeyVerb, 0, FALSE, DUPLICATE_SAME_ACCESS))
831         return HRESULT_FROM_WIN32(GetLastError());
832     return EnumOLEVERB_Construct(hkeyVerb, This->index, ppenum);
833 }
834
835 static const IEnumOLEVERBVtbl EnumOLEVERB_VTable =
836 {
837     EnumOLEVERB_QueryInterface,
838     EnumOLEVERB_AddRef,
839     EnumOLEVERB_Release,
840     EnumOLEVERB_Next,
841     EnumOLEVERB_Skip,
842     EnumOLEVERB_Reset,
843     EnumOLEVERB_Clone
844 };
845
846 static HRESULT EnumOLEVERB_Construct(HKEY hkeyVerb, ULONG index, IEnumOLEVERB **ppenum)
847 {
848     EnumOLEVERB *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
849     if (!This)
850     {
851         RegCloseKey(hkeyVerb);
852         return E_OUTOFMEMORY;
853     }
854     This->lpvtbl = &EnumOLEVERB_VTable;
855     This->ref = 1;
856     This->index = index;
857     This->hkeyVerb = hkeyVerb;
858     *ppenum = (IEnumOLEVERB *)&This->lpvtbl;
859     return S_OK;    
860 }
861
862 /***********************************************************************
863  *           OleRegEnumVerbs    [OLE32.@]
864  *
865  * Enumerates verbs associated with a class stored in the registry.
866  *
867  * PARAMS
868  *  clsid  [I] Class ID to enumerate the verbs for.
869  *  ppenum [O] Enumerator.
870  *
871  * RETURNS
872  *  S_OK: Success.
873  *  REGDB_E_CLASSNOTREG: The specified class does not have a key in the registry.
874  *  REGDB_E_READREGDB: The class key could not be opened for some other reason.
875  *  OLE_E_REGDB_KEY: The Verb subkey for the class is not present.
876  *  OLEOBJ_E_NOVERBS: The Verb subkey for the class is empty.
877  */
878 HRESULT WINAPI OleRegEnumVerbs (REFCLSID clsid, LPENUMOLEVERB* ppenum)
879 {
880     LONG res;
881     HKEY hkeyVerb;
882     DWORD dwSubKeys;
883     static const WCHAR wszVerb[] = {'V','e','r','b',0};
884
885     TRACE("(%s, %p)\n", debugstr_guid(clsid), ppenum);
886
887     res = COM_OpenKeyForCLSID(clsid, wszVerb, KEY_READ, &hkeyVerb);
888     if (FAILED(res))
889     {
890         if (res == REGDB_E_CLASSNOTREG)
891             ERR("CLSID %s not registered\n", debugstr_guid(clsid));
892         else if (res == REGDB_E_KEYMISSING)
893             ERR("no Verbs key for class %s\n", debugstr_guid(clsid));
894         else
895             ERR("failed to open Verbs key for CLSID %s with error %d\n",
896                 debugstr_guid(clsid), res);
897         return res;
898     }
899
900     res = RegQueryInfoKeyW(hkeyVerb, NULL, NULL, NULL, &dwSubKeys, NULL,
901                           NULL, NULL, NULL, NULL, NULL, NULL);
902     if (res != ERROR_SUCCESS)
903     {
904         ERR("failed to get subkey count with error %d\n", GetLastError());
905         return REGDB_E_READREGDB;
906     }
907
908     if (!dwSubKeys)
909     {
910         WARN("class %s has no verbs\n", debugstr_guid(clsid));
911         RegCloseKey(hkeyVerb);
912         return OLEOBJ_E_NOVERBS;
913     }
914
915     return EnumOLEVERB_Construct(hkeyVerb, 0, ppenum);
916 }
917
918 /******************************************************************************
919  *              OleSetContainedObject        [OLE32.@]
920  */
921 HRESULT WINAPI OleSetContainedObject(
922   LPUNKNOWN pUnknown,
923   BOOL      fContained)
924 {
925   IRunnableObject* runnable = NULL;
926   HRESULT          hres;
927
928   TRACE("(%p,%x)\n", pUnknown, fContained);
929
930   hres = IUnknown_QueryInterface(pUnknown,
931                                  &IID_IRunnableObject,
932                                  (void**)&runnable);
933
934   if (SUCCEEDED(hres))
935   {
936     hres = IRunnableObject_SetContainedObject(runnable, fContained);
937
938     IRunnableObject_Release(runnable);
939
940     return hres;
941   }
942
943   return S_OK;
944 }
945
946 /******************************************************************************
947  *              OleRun        [OLE32.@]
948  *
949  * Set the OLE object to the running state.
950  *
951  * PARAMS
952  *  pUnknown [I] OLE object to run.
953  *
954  * RETURNS
955  *  Success: S_OK.
956  *  Failure: Any HRESULT code.
957  */
958 HRESULT WINAPI OleRun(LPUNKNOWN pUnknown)
959 {
960     IRunnableObject *runable;
961     HRESULT hres;
962
963     TRACE("(%p)\n", pUnknown);
964
965     hres = IUnknown_QueryInterface(pUnknown, &IID_IRunnableObject, (void**)&runable);
966     if (FAILED(hres))
967         return S_OK; /* Appears to return no error. */
968
969     hres = IRunnableObject_Run(runable, NULL);
970     IRunnableObject_Release(runable);
971     return hres;
972 }
973
974 /******************************************************************************
975  *              OleLoad        [OLE32.@]
976  */
977 HRESULT WINAPI OleLoad(
978   LPSTORAGE       pStg,
979   REFIID          riid,
980   LPOLECLIENTSITE pClientSite,
981   LPVOID*         ppvObj)
982 {
983   IPersistStorage* persistStorage = NULL;
984   IUnknown*        pUnk;
985   IOleObject*      pOleObject      = NULL;
986   STATSTG          storageInfo;
987   HRESULT          hres;
988
989   TRACE("(%p, %s, %p, %p)\n", pStg, debugstr_guid(riid), pClientSite, ppvObj);
990
991   *ppvObj = NULL;
992
993   /*
994    * TODO, Conversion ... OleDoAutoConvert
995    */
996
997   /*
998    * Get the class ID for the object.
999    */
1000   hres = IStorage_Stat(pStg, &storageInfo, STATFLAG_NONAME);
1001
1002   /*
1003    * Now, try and create the handler for the object
1004    */
1005   hres = CoCreateInstance(&storageInfo.clsid,
1006                           NULL,
1007                           CLSCTX_INPROC_HANDLER|CLSCTX_INPROC_SERVER,
1008                           riid,
1009                           (void**)&pUnk);
1010
1011   /*
1012    * If that fails, as it will most times, load the default
1013    * OLE handler.
1014    */
1015   if (FAILED(hres))
1016   {
1017     hres = OleCreateDefaultHandler(&storageInfo.clsid,
1018                                    NULL,
1019                                    riid,
1020                                    (void**)&pUnk);
1021   }
1022
1023   /*
1024    * If we couldn't find a handler... this is bad. Abort the whole thing.
1025    */
1026   if (FAILED(hres))
1027     return hres;
1028
1029   if (pClientSite)
1030   {
1031     hres = IUnknown_QueryInterface(pUnk, &IID_IOleObject, (void **)&pOleObject);
1032     if (SUCCEEDED(hres))
1033     {
1034         DWORD dwStatus;
1035         hres = IOleObject_GetMiscStatus(pOleObject, DVASPECT_CONTENT, &dwStatus);
1036     }
1037   }
1038
1039   if (SUCCEEDED(hres))
1040     /*
1041      * Initialize the object with it's IPersistStorage interface.
1042      */
1043     hres = IOleObject_QueryInterface(pUnk,
1044                                      &IID_IPersistStorage,
1045                                      (void**)&persistStorage);
1046
1047   if (SUCCEEDED(hres))
1048   {
1049     hres = IPersistStorage_Load(persistStorage, pStg);
1050
1051     IPersistStorage_Release(persistStorage);
1052     persistStorage = NULL;
1053   }
1054
1055   if (SUCCEEDED(hres) && pClientSite)
1056     /*
1057      * Inform the new object of it's client site.
1058      */
1059     hres = IOleObject_SetClientSite(pOleObject, pClientSite);
1060
1061   /*
1062    * Cleanup interfaces used internally
1063    */
1064   if (pOleObject)
1065     IOleObject_Release(pOleObject);
1066
1067   if (SUCCEEDED(hres))
1068   {
1069     IOleLink *pOleLink;
1070     HRESULT hres1;
1071     hres1 = IUnknown_QueryInterface(pUnk, &IID_IOleLink, (void **)&pOleLink);
1072     if (SUCCEEDED(hres1))
1073     {
1074       FIXME("handle OLE link\n");
1075       IOleLink_Release(pOleLink);
1076     }
1077   }
1078
1079   if (FAILED(hres))
1080   {
1081     IUnknown_Release(pUnk);
1082     pUnk = NULL;
1083   }
1084
1085   *ppvObj = pUnk;
1086
1087   return hres;
1088 }
1089
1090 /***********************************************************************
1091  *           OleSave     [OLE32.@]
1092  */
1093 HRESULT WINAPI OleSave(
1094   LPPERSISTSTORAGE pPS,
1095   LPSTORAGE        pStg,
1096   BOOL             fSameAsLoad)
1097 {
1098   HRESULT hres;
1099   CLSID   objectClass;
1100
1101   TRACE("(%p,%p,%x)\n", pPS, pStg, fSameAsLoad);
1102
1103   /*
1104    * First, we transfer the class ID (if available)
1105    */
1106   hres = IPersistStorage_GetClassID(pPS, &objectClass);
1107
1108   if (SUCCEEDED(hres))
1109   {
1110     WriteClassStg(pStg, &objectClass);
1111   }
1112
1113   /*
1114    * Then, we ask the object to save itself to the
1115    * storage. If it is successful, we commit the storage.
1116    */
1117   hres = IPersistStorage_Save(pPS, pStg, fSameAsLoad);
1118
1119   if (SUCCEEDED(hres))
1120   {
1121     IStorage_Commit(pStg,
1122                     STGC_DEFAULT);
1123   }
1124
1125   return hres;
1126 }
1127
1128
1129 /******************************************************************************
1130  *              OleLockRunning        [OLE32.@]
1131  */
1132 HRESULT WINAPI OleLockRunning(LPUNKNOWN pUnknown, BOOL fLock, BOOL fLastUnlockCloses)
1133 {
1134   IRunnableObject* runnable = NULL;
1135   HRESULT          hres;
1136
1137   TRACE("(%p,%x,%x)\n", pUnknown, fLock, fLastUnlockCloses);
1138
1139   hres = IUnknown_QueryInterface(pUnknown,
1140                                  &IID_IRunnableObject,
1141                                  (void**)&runnable);
1142
1143   if (SUCCEEDED(hres))
1144   {
1145     hres = IRunnableObject_LockRunning(runnable, fLock, fLastUnlockCloses);
1146
1147     IRunnableObject_Release(runnable);
1148
1149     return hres;
1150   }
1151   else
1152     return E_INVALIDARG;
1153 }
1154
1155
1156 /**************************************************************************
1157  * Internal methods to manage the shared OLE menu in response to the
1158  * OLE***MenuDescriptor API
1159  */
1160
1161 /***
1162  * OLEMenu_Initialize()
1163  *
1164  * Initializes the OLEMENU data structures.
1165  */
1166 static void OLEMenu_Initialize(void)
1167 {
1168 }
1169
1170 /***
1171  * OLEMenu_UnInitialize()
1172  *
1173  * Releases the OLEMENU data structures.
1174  */
1175 static void OLEMenu_UnInitialize(void)
1176 {
1177 }
1178
1179 /*************************************************************************
1180  * OLEMenu_InstallHooks
1181  * Install thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC
1182  *
1183  * RETURNS: TRUE if message hooks were successfully installed
1184  *          FALSE on failure
1185  */
1186 static BOOL OLEMenu_InstallHooks( DWORD tid )
1187 {
1188   OleMenuHookItem *pHookItem = NULL;
1189
1190   /* Create an entry for the hook table */
1191   if ( !(pHookItem = HeapAlloc(GetProcessHeap(), 0,
1192                                sizeof(OleMenuHookItem)) ) )
1193     return FALSE;
1194
1195   pHookItem->tid = tid;
1196   pHookItem->hHeap = GetProcessHeap();
1197
1198   /* Install a thread scope message hook for WH_GETMESSAGE */
1199   pHookItem->GetMsg_hHook = SetWindowsHookExA( WH_GETMESSAGE, OLEMenu_GetMsgProc,
1200                                                0, GetCurrentThreadId() );
1201   if ( !pHookItem->GetMsg_hHook )
1202     goto CLEANUP;
1203
1204   /* Install a thread scope message hook for WH_CALLWNDPROC */
1205   pHookItem->CallWndProc_hHook = SetWindowsHookExA( WH_CALLWNDPROC, OLEMenu_CallWndProc,
1206                                                     0, GetCurrentThreadId() );
1207   if ( !pHookItem->CallWndProc_hHook )
1208     goto CLEANUP;
1209
1210   /* Insert the hook table entry */
1211   pHookItem->next = hook_list;
1212   hook_list = pHookItem;
1213
1214   return TRUE;
1215
1216 CLEANUP:
1217   /* Unhook any hooks */
1218   if ( pHookItem->GetMsg_hHook )
1219     UnhookWindowsHookEx( pHookItem->GetMsg_hHook );
1220   if ( pHookItem->CallWndProc_hHook )
1221     UnhookWindowsHookEx( pHookItem->CallWndProc_hHook );
1222   /* Release the hook table entry */
1223   HeapFree(pHookItem->hHeap, 0, pHookItem );
1224
1225   return FALSE;
1226 }
1227
1228 /*************************************************************************
1229  * OLEMenu_UnInstallHooks
1230  * UnInstall thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC
1231  *
1232  * RETURNS: TRUE if message hooks were successfully installed
1233  *          FALSE on failure
1234  */
1235 static BOOL OLEMenu_UnInstallHooks( DWORD tid )
1236 {
1237   OleMenuHookItem *pHookItem = NULL;
1238   OleMenuHookItem **ppHook = &hook_list;
1239
1240   while (*ppHook)
1241   {
1242       if ((*ppHook)->tid == tid)
1243       {
1244           pHookItem = *ppHook;
1245           *ppHook = pHookItem->next;
1246           break;
1247       }
1248       ppHook = &(*ppHook)->next;
1249   }
1250   if (!pHookItem) return FALSE;
1251
1252   /* Uninstall the hooks installed for this thread */
1253   if ( !UnhookWindowsHookEx( pHookItem->GetMsg_hHook ) )
1254     goto CLEANUP;
1255   if ( !UnhookWindowsHookEx( pHookItem->CallWndProc_hHook ) )
1256     goto CLEANUP;
1257
1258   /* Release the hook table entry */
1259   HeapFree(pHookItem->hHeap, 0, pHookItem );
1260
1261   return TRUE;
1262
1263 CLEANUP:
1264   /* Release the hook table entry */
1265   HeapFree(pHookItem->hHeap, 0, pHookItem );
1266
1267   return FALSE;
1268 }
1269
1270 /*************************************************************************
1271  * OLEMenu_IsHookInstalled
1272  * Tests if OLEMenu hooks have been installed for a thread
1273  *
1274  * RETURNS: The pointer and index of the hook table entry for the tid
1275  *          NULL and -1 for the index if no hooks were installed for this thread
1276  */
1277 static OleMenuHookItem * OLEMenu_IsHookInstalled( DWORD tid )
1278 {
1279   OleMenuHookItem *pHookItem = NULL;
1280
1281   /* Do a simple linear search for an entry whose tid matches ours.
1282    * We really need a map but efficiency is not a concern here. */
1283   for (pHookItem = hook_list; pHookItem; pHookItem = pHookItem->next)
1284   {
1285     if ( tid == pHookItem->tid )
1286       return pHookItem;
1287   }
1288
1289   return NULL;
1290 }
1291
1292 /***********************************************************************
1293  *           OLEMenu_FindMainMenuIndex
1294  *
1295  * Used by OLEMenu API to find the top level group a menu item belongs to.
1296  * On success pnPos contains the index of the item in the top level menu group
1297  *
1298  * RETURNS: TRUE if the ID was found, FALSE on failure
1299  */
1300 static BOOL OLEMenu_FindMainMenuIndex( HMENU hMainMenu, HMENU hPopupMenu, UINT *pnPos )
1301 {
1302   INT i, nItems;
1303
1304   nItems = GetMenuItemCount( hMainMenu );
1305
1306   for (i = 0; i < nItems; i++)
1307   {
1308     HMENU hsubmenu;
1309
1310     /*  Is the current item a submenu? */
1311     if ( (hsubmenu = GetSubMenu(hMainMenu, i)) )
1312     {
1313       /* If the handle is the same we're done */
1314       if ( hsubmenu == hPopupMenu )
1315       {
1316         if (pnPos)
1317           *pnPos = i;
1318         return TRUE;
1319       }
1320       /* Recursively search without updating pnPos */
1321       else if ( OLEMenu_FindMainMenuIndex( hsubmenu, hPopupMenu, NULL ) )
1322       {
1323         if (pnPos)
1324           *pnPos = i;
1325         return TRUE;
1326       }
1327     }
1328   }
1329
1330   return FALSE;
1331 }
1332
1333 /***********************************************************************
1334  *           OLEMenu_SetIsServerMenu
1335  *
1336  * Checks whether a popup menu belongs to a shared menu group which is
1337  * owned by the server, and sets the menu descriptor state accordingly.
1338  * All menu messages from these groups should be routed to the server.
1339  *
1340  * RETURNS: TRUE if the popup menu is part of a server owned group
1341  *          FALSE if the popup menu is part of a container owned group
1342  */
1343 static BOOL OLEMenu_SetIsServerMenu( HMENU hmenu, OleMenuDescriptor *pOleMenuDescriptor )
1344 {
1345   UINT nPos = 0, nWidth, i;
1346
1347   pOleMenuDescriptor->bIsServerItem = FALSE;
1348
1349   /* Don't bother searching if the popup is the combined menu itself */
1350   if ( hmenu == pOleMenuDescriptor->hmenuCombined )
1351     return FALSE;
1352
1353   /* Find the menu item index in the shared OLE menu that this item belongs to */
1354   if ( !OLEMenu_FindMainMenuIndex( pOleMenuDescriptor->hmenuCombined, hmenu,  &nPos ) )
1355     return FALSE;
1356
1357   /* The group widths array has counts for the number of elements
1358    * in the groups File, Edit, Container, Object, Window, Help.
1359    * The Edit, Object & Help groups belong to the server object
1360    * and the other three belong to the container.
1361    * Loop through the group widths and locate the group we are a member of.
1362    */
1363   for ( i = 0, nWidth = 0; i < 6; i++ )
1364   {
1365     nWidth += pOleMenuDescriptor->mgw.width[i];
1366     if ( nPos < nWidth )
1367     {
1368       /* Odd elements are server menu widths */
1369       pOleMenuDescriptor->bIsServerItem = (i%2) ? TRUE : FALSE;
1370       break;
1371     }
1372   }
1373
1374   return pOleMenuDescriptor->bIsServerItem;
1375 }
1376
1377 /*************************************************************************
1378  * OLEMenu_CallWndProc
1379  * Thread scope WH_CALLWNDPROC hook proc filter function (callback)
1380  * This is invoked from a message hook installed in OleSetMenuDescriptor.
1381  */
1382 static LRESULT CALLBACK OLEMenu_CallWndProc(INT code, WPARAM wParam, LPARAM lParam)
1383 {
1384   LPCWPSTRUCT pMsg = NULL;
1385   HOLEMENU hOleMenu = 0;
1386   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1387   OleMenuHookItem *pHookItem = NULL;
1388   WORD fuFlags;
1389
1390   TRACE("%i, %04lx, %08lx\n", code, wParam, lParam );
1391
1392   /* Check if we're being asked to process the message */
1393   if ( HC_ACTION != code )
1394     goto NEXTHOOK;
1395
1396   /* Retrieve the current message being dispatched from lParam */
1397   pMsg = (LPCWPSTRUCT)lParam;
1398
1399   /* Check if the message is destined for a window we are interested in:
1400    * If the window has an OLEMenu property we may need to dispatch
1401    * the menu message to its active objects window instead. */
1402
1403   hOleMenu = GetPropA( pMsg->hwnd, "PROP_OLEMenuDescriptor" );
1404   if ( !hOleMenu )
1405     goto NEXTHOOK;
1406
1407   /* Get the menu descriptor */
1408   pOleMenuDescriptor = GlobalLock( hOleMenu );
1409   if ( !pOleMenuDescriptor ) /* Bad descriptor! */
1410     goto NEXTHOOK;
1411
1412   /* Process menu messages */
1413   switch( pMsg->message )
1414   {
1415     case WM_INITMENU:
1416     {
1417       /* Reset the menu descriptor state */
1418       pOleMenuDescriptor->bIsServerItem = FALSE;
1419
1420       /* Send this message to the server as well */
1421       SendMessageA( pOleMenuDescriptor->hwndActiveObject,
1422                   pMsg->message, pMsg->wParam, pMsg->lParam );
1423       goto NEXTHOOK;
1424     }
1425
1426     case WM_INITMENUPOPUP:
1427     {
1428       /* Save the state for whether this is a server owned menu */
1429       OLEMenu_SetIsServerMenu( (HMENU)pMsg->wParam, pOleMenuDescriptor );
1430       break;
1431     }
1432
1433     case WM_MENUSELECT:
1434     {
1435       fuFlags = HIWORD(pMsg->wParam);  /* Get flags */
1436       if ( fuFlags & MF_SYSMENU )
1437          goto NEXTHOOK;
1438
1439       /* Save the state for whether this is a server owned popup menu */
1440       else if ( fuFlags & MF_POPUP )
1441         OLEMenu_SetIsServerMenu( (HMENU)pMsg->lParam, pOleMenuDescriptor );
1442
1443       break;
1444     }
1445
1446     case WM_DRAWITEM:
1447     {
1448       LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT) pMsg->lParam;
1449       if ( pMsg->wParam != 0 || lpdis->CtlType != ODT_MENU )
1450         goto NEXTHOOK;  /* Not a menu message */
1451
1452       break;
1453     }
1454
1455     default:
1456       goto NEXTHOOK;
1457   }
1458
1459   /* If the message was for the server dispatch it accordingly */
1460   if ( pOleMenuDescriptor->bIsServerItem )
1461   {
1462     SendMessageA( pOleMenuDescriptor->hwndActiveObject,
1463                   pMsg->message, pMsg->wParam, pMsg->lParam );
1464   }
1465
1466 NEXTHOOK:
1467   if ( pOleMenuDescriptor )
1468     GlobalUnlock( hOleMenu );
1469
1470   /* Lookup the hook item for the current thread */
1471   if ( !( pHookItem = OLEMenu_IsHookInstalled( GetCurrentThreadId() ) ) )
1472   {
1473     /* This should never fail!! */
1474     WARN("could not retrieve hHook for current thread!\n" );
1475     return 0;
1476   }
1477
1478   /* Pass on the message to the next hooker */
1479   return CallNextHookEx( pHookItem->CallWndProc_hHook, code, wParam, lParam );
1480 }
1481
1482 /*************************************************************************
1483  * OLEMenu_GetMsgProc
1484  * Thread scope WH_GETMESSAGE hook proc filter function (callback)
1485  * This is invoked from a message hook installed in OleSetMenuDescriptor.
1486  */
1487 static LRESULT CALLBACK OLEMenu_GetMsgProc(INT code, WPARAM wParam, LPARAM lParam)
1488 {
1489   LPMSG pMsg = NULL;
1490   HOLEMENU hOleMenu = 0;
1491   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1492   OleMenuHookItem *pHookItem = NULL;
1493   WORD wCode;
1494
1495   TRACE("%i, %04lx, %08lx\n", code, wParam, lParam );
1496
1497   /* Check if we're being asked to process a  messages */
1498   if ( HC_ACTION != code )
1499     goto NEXTHOOK;
1500
1501   /* Retrieve the current message being dispatched from lParam */
1502   pMsg = (LPMSG)lParam;
1503
1504   /* Check if the message is destined for a window we are interested in:
1505    * If the window has an OLEMenu property we may need to dispatch
1506    * the menu message to its active objects window instead. */
1507
1508   hOleMenu = GetPropA( pMsg->hwnd, "PROP_OLEMenuDescriptor" );
1509   if ( !hOleMenu )
1510     goto NEXTHOOK;
1511
1512   /* Process menu messages */
1513   switch( pMsg->message )
1514   {
1515     case WM_COMMAND:
1516     {
1517       wCode = HIWORD(pMsg->wParam);  /* Get notification code */
1518       if ( wCode )
1519         goto NEXTHOOK;  /* Not a menu message */
1520       break;
1521     }
1522     default:
1523       goto NEXTHOOK;
1524   }
1525
1526   /* Get the menu descriptor */
1527   pOleMenuDescriptor = GlobalLock( hOleMenu );
1528   if ( !pOleMenuDescriptor ) /* Bad descriptor! */
1529     goto NEXTHOOK;
1530
1531   /* If the message was for the server dispatch it accordingly */
1532   if ( pOleMenuDescriptor->bIsServerItem )
1533   {
1534     /* Change the hWnd in the message to the active objects hWnd.
1535      * The message loop which reads this message will automatically
1536      * dispatch it to the embedded objects window. */
1537     pMsg->hwnd = pOleMenuDescriptor->hwndActiveObject;
1538   }
1539
1540 NEXTHOOK:
1541   if ( pOleMenuDescriptor )
1542     GlobalUnlock( hOleMenu );
1543
1544   /* Lookup the hook item for the current thread */
1545   if ( !( pHookItem = OLEMenu_IsHookInstalled( GetCurrentThreadId() ) ) )
1546   {
1547     /* This should never fail!! */
1548     WARN("could not retrieve hHook for current thread!\n" );
1549     return FALSE;
1550   }
1551
1552   /* Pass on the message to the next hooker */
1553   return CallNextHookEx( pHookItem->GetMsg_hHook, code, wParam, lParam );
1554 }
1555
1556 /***********************************************************************
1557  * OleCreateMenuDescriptor [OLE32.@]
1558  * Creates an OLE menu descriptor for OLE to use when dispatching
1559  * menu messages and commands.
1560  *
1561  * PARAMS:
1562  *    hmenuCombined  -  Handle to the objects combined menu
1563  *    lpMenuWidths   -  Pointer to array of 6 LONG's indicating menus per group
1564  *
1565  */
1566 HOLEMENU WINAPI OleCreateMenuDescriptor(
1567   HMENU                hmenuCombined,
1568   LPOLEMENUGROUPWIDTHS lpMenuWidths)
1569 {
1570   HOLEMENU hOleMenu;
1571   OleMenuDescriptor *pOleMenuDescriptor;
1572   int i;
1573
1574   if ( !hmenuCombined || !lpMenuWidths )
1575     return 0;
1576
1577   /* Create an OLE menu descriptor */
1578   if ( !(hOleMenu = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT,
1579                                 sizeof(OleMenuDescriptor) ) ) )
1580   return 0;
1581
1582   pOleMenuDescriptor = GlobalLock( hOleMenu );
1583   if ( !pOleMenuDescriptor )
1584     return 0;
1585
1586   /* Initialize menu group widths and hmenu */
1587   for ( i = 0; i < 6; i++ )
1588     pOleMenuDescriptor->mgw.width[i] = lpMenuWidths->width[i];
1589
1590   pOleMenuDescriptor->hmenuCombined = hmenuCombined;
1591   pOleMenuDescriptor->bIsServerItem = FALSE;
1592   GlobalUnlock( hOleMenu );
1593
1594   return hOleMenu;
1595 }
1596
1597 /***********************************************************************
1598  * OleDestroyMenuDescriptor [OLE32.@]
1599  * Destroy the shared menu descriptor
1600  */
1601 HRESULT WINAPI OleDestroyMenuDescriptor(
1602   HOLEMENU hmenuDescriptor)
1603 {
1604   if ( hmenuDescriptor )
1605     GlobalFree( hmenuDescriptor );
1606         return S_OK;
1607 }
1608
1609 /***********************************************************************
1610  * OleSetMenuDescriptor [OLE32.@]
1611  * Installs or removes OLE dispatching code for the containers frame window.
1612  *
1613  * PARAMS
1614  *     hOleMenu         Handle to composite menu descriptor
1615  *     hwndFrame        Handle to containers frame window
1616  *     hwndActiveObject Handle to objects in-place activation window
1617  *     lpFrame          Pointer to IOleInPlaceFrame on containers window
1618  *     lpActiveObject   Pointer to IOleInPlaceActiveObject on active in-place object
1619  *
1620  * RETURNS
1621  *      S_OK                               - menu installed correctly
1622  *      E_FAIL, E_INVALIDARG, E_UNEXPECTED - failure
1623  *
1624  * FIXME
1625  *      The lpFrame and lpActiveObject parameters are currently ignored
1626  *      OLE should install context sensitive help F1 filtering for the app when
1627  *      these are non null.
1628  */
1629 HRESULT WINAPI OleSetMenuDescriptor(
1630   HOLEMENU               hOleMenu,
1631   HWND                   hwndFrame,
1632   HWND                   hwndActiveObject,
1633   LPOLEINPLACEFRAME        lpFrame,
1634   LPOLEINPLACEACTIVEOBJECT lpActiveObject)
1635 {
1636   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1637
1638   /* Check args */
1639   if ( !hwndFrame || (hOleMenu && !hwndActiveObject) )
1640     return E_INVALIDARG;
1641
1642   if ( lpFrame || lpActiveObject )
1643   {
1644      FIXME("(%p, %p, %p, %p, %p), Context sensitive help filtering not implemented!\n",
1645         hOleMenu,
1646         hwndFrame,
1647         hwndActiveObject,
1648         lpFrame,
1649         lpActiveObject);
1650   }
1651
1652   /* Set up a message hook to intercept the containers frame window messages.
1653    * The message filter is responsible for dispatching menu messages from the
1654    * shared menu which are intended for the object.
1655    */
1656
1657   if ( hOleMenu )  /* Want to install dispatching code */
1658   {
1659     /* If OLEMenu hooks are already installed for this thread, fail
1660      * Note: This effectively means that OleSetMenuDescriptor cannot
1661      * be called twice in succession on the same frame window
1662      * without first calling it with a null hOleMenu to uninstall */
1663     if ( OLEMenu_IsHookInstalled( GetCurrentThreadId() ) )
1664   return E_FAIL;
1665
1666     /* Get the menu descriptor */
1667     pOleMenuDescriptor = GlobalLock( hOleMenu );
1668     if ( !pOleMenuDescriptor )
1669       return E_UNEXPECTED;
1670
1671     /* Update the menu descriptor */
1672     pOleMenuDescriptor->hwndFrame = hwndFrame;
1673     pOleMenuDescriptor->hwndActiveObject = hwndActiveObject;
1674
1675     GlobalUnlock( hOleMenu );
1676     pOleMenuDescriptor = NULL;
1677
1678     /* Add a menu descriptor windows property to the frame window */
1679     SetPropA( hwndFrame, "PROP_OLEMenuDescriptor", hOleMenu );
1680
1681     /* Install thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC */
1682     if ( !OLEMenu_InstallHooks( GetCurrentThreadId() ) )
1683       return E_FAIL;
1684   }
1685   else  /* Want to uninstall dispatching code */
1686   {
1687     /* Uninstall the hooks */
1688     if ( !OLEMenu_UnInstallHooks( GetCurrentThreadId() ) )
1689       return E_FAIL;
1690
1691     /* Remove the menu descriptor property from the frame window */
1692     RemovePropA( hwndFrame, "PROP_OLEMenuDescriptor" );
1693   }
1694
1695   return S_OK;
1696 }
1697
1698 /******************************************************************************
1699  *              IsAccelerator        [OLE32.@]
1700  * Mostly copied from controls/menu.c TranslateAccelerator implementation
1701  */
1702 BOOL WINAPI IsAccelerator(HACCEL hAccel, int cAccelEntries, LPMSG lpMsg, WORD* lpwCmd)
1703 {
1704     LPACCEL lpAccelTbl;
1705     int i;
1706
1707     if(!lpMsg) return FALSE;
1708     if (!hAccel)
1709     {
1710         WARN_(accel)("NULL accel handle\n");
1711         return FALSE;
1712     }
1713     if((lpMsg->message != WM_KEYDOWN &&
1714         lpMsg->message != WM_SYSKEYDOWN &&
1715         lpMsg->message != WM_SYSCHAR &&
1716         lpMsg->message != WM_CHAR)) return FALSE;
1717     lpAccelTbl = HeapAlloc(GetProcessHeap(), 0, cAccelEntries * sizeof(ACCEL));
1718     if (NULL == lpAccelTbl)
1719     {
1720         return FALSE;
1721     }
1722     if (CopyAcceleratorTableW(hAccel, lpAccelTbl, cAccelEntries) != cAccelEntries)
1723     {
1724         WARN_(accel)("CopyAcceleratorTableW failed\n");
1725         HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1726         return FALSE;
1727     }
1728
1729     TRACE_(accel)("hAccel=%p, cAccelEntries=%d,"
1730                 "msg->hwnd=%p, msg->message=%04x, wParam=%08lx, lParam=%08lx\n",
1731                 hAccel, cAccelEntries,
1732                 lpMsg->hwnd, lpMsg->message, lpMsg->wParam, lpMsg->lParam);
1733     for(i = 0; i < cAccelEntries; i++)
1734     {
1735         if(lpAccelTbl[i].key != lpMsg->wParam)
1736             continue;
1737
1738         if(lpMsg->message == WM_CHAR)
1739         {
1740             if(!(lpAccelTbl[i].fVirt & FALT) && !(lpAccelTbl[i].fVirt & FVIRTKEY))
1741             {
1742                 TRACE_(accel)("found accel for WM_CHAR: ('%c')\n", LOWORD(lpMsg->wParam) & 0xff);
1743                 goto found;
1744             }
1745         }
1746         else
1747         {
1748             if(lpAccelTbl[i].fVirt & FVIRTKEY)
1749             {
1750                 INT mask = 0;
1751                 TRACE_(accel)("found accel for virt_key %04lx (scan %04x)\n",
1752                                 lpMsg->wParam, HIWORD(lpMsg->lParam) & 0xff);
1753                 if(GetKeyState(VK_SHIFT) & 0x8000) mask |= FSHIFT;
1754                 if(GetKeyState(VK_CONTROL) & 0x8000) mask |= FCONTROL;
1755                 if(GetKeyState(VK_MENU) & 0x8000) mask |= FALT;
1756                 if(mask == (lpAccelTbl[i].fVirt & (FSHIFT | FCONTROL | FALT))) goto found;
1757                 TRACE_(accel)("incorrect SHIFT/CTRL/ALT-state\n");
1758             }
1759             else
1760             {
1761                 if(!(lpMsg->lParam & 0x01000000))  /* no special_key */
1762                 {
1763                     if((lpAccelTbl[i].fVirt & FALT) && (lpMsg->lParam & 0x20000000))
1764                     {                                                  /* ^^ ALT pressed */
1765                         TRACE_(accel)("found accel for Alt-%c\n", LOWORD(lpMsg->wParam) & 0xff);
1766                         goto found;
1767                     }
1768                 }
1769             }
1770         }
1771     }
1772
1773     WARN_(accel)("couldn't translate accelerator key\n");
1774     HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1775     return FALSE;
1776
1777 found:
1778     if(lpwCmd) *lpwCmd = lpAccelTbl[i].cmd;
1779     HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1780     return TRUE;
1781 }
1782
1783 /***********************************************************************
1784  * ReleaseStgMedium [OLE32.@]
1785  */
1786 void WINAPI ReleaseStgMedium(
1787   STGMEDIUM* pmedium)
1788 {
1789   switch (pmedium->tymed)
1790   {
1791     case TYMED_HGLOBAL:
1792     {
1793       if ( (pmedium->pUnkForRelease==0) &&
1794            (pmedium->u.hGlobal!=0) )
1795         GlobalFree(pmedium->u.hGlobal);
1796       break;
1797     }
1798     case TYMED_FILE:
1799     {
1800       if (pmedium->u.lpszFileName!=0)
1801       {
1802         if (pmedium->pUnkForRelease==0)
1803         {
1804           DeleteFileW(pmedium->u.lpszFileName);
1805         }
1806
1807         CoTaskMemFree(pmedium->u.lpszFileName);
1808       }
1809       break;
1810     }
1811     case TYMED_ISTREAM:
1812     {
1813       if (pmedium->u.pstm!=0)
1814       {
1815         IStream_Release(pmedium->u.pstm);
1816       }
1817       break;
1818     }
1819     case TYMED_ISTORAGE:
1820     {
1821       if (pmedium->u.pstg!=0)
1822       {
1823         IStorage_Release(pmedium->u.pstg);
1824       }
1825       break;
1826     }
1827     case TYMED_GDI:
1828     {
1829       if ( (pmedium->pUnkForRelease==0) &&
1830            (pmedium->u.hBitmap!=0) )
1831         DeleteObject(pmedium->u.hBitmap);
1832       break;
1833     }
1834     case TYMED_MFPICT:
1835     {
1836       if ( (pmedium->pUnkForRelease==0) &&
1837            (pmedium->u.hMetaFilePict!=0) )
1838       {
1839         LPMETAFILEPICT pMP = GlobalLock(pmedium->u.hMetaFilePict);
1840         DeleteMetaFile(pMP->hMF);
1841         GlobalUnlock(pmedium->u.hMetaFilePict);
1842         GlobalFree(pmedium->u.hMetaFilePict);
1843       }
1844       break;
1845     }
1846     case TYMED_ENHMF:
1847     {
1848       if ( (pmedium->pUnkForRelease==0) &&
1849            (pmedium->u.hEnhMetaFile!=0) )
1850       {
1851         DeleteEnhMetaFile(pmedium->u.hEnhMetaFile);
1852       }
1853       break;
1854     }
1855     case TYMED_NULL:
1856     default:
1857       break;
1858   }
1859   pmedium->tymed=TYMED_NULL;
1860
1861   /*
1862    * After cleaning up, the unknown is released
1863    */
1864   if (pmedium->pUnkForRelease!=0)
1865   {
1866     IUnknown_Release(pmedium->pUnkForRelease);
1867     pmedium->pUnkForRelease = 0;
1868   }
1869 }
1870
1871 /***
1872  * OLEDD_Initialize()
1873  *
1874  * Initializes the OLE drag and drop data structures.
1875  */
1876 static void OLEDD_Initialize(void)
1877 {
1878     WNDCLASSA wndClass;
1879
1880     ZeroMemory (&wndClass, sizeof(WNDCLASSA));
1881     wndClass.style         = CS_GLOBALCLASS;
1882     wndClass.lpfnWndProc   = OLEDD_DragTrackerWindowProc;
1883     wndClass.cbClsExtra    = 0;
1884     wndClass.cbWndExtra    = sizeof(TrackerWindowInfo*);
1885     wndClass.hCursor       = 0;
1886     wndClass.hbrBackground = 0;
1887     wndClass.lpszClassName = OLEDD_DRAGTRACKERCLASS;
1888
1889     RegisterClassA (&wndClass);
1890 }
1891
1892 /***
1893  * OLEDD_FreeDropTarget()
1894  *
1895  * Frees the drag and drop data structure
1896  */
1897 static void OLEDD_FreeDropTarget(DropTargetNode *dropTargetInfo, BOOL release_drop_target)
1898 {
1899   list_remove(&dropTargetInfo->entry);
1900   if (release_drop_target) IDropTarget_Release(dropTargetInfo->dropTarget);
1901   HeapFree(GetProcessHeap(), 0, dropTargetInfo);
1902 }
1903
1904 /***
1905  * OLEDD_UnInitialize()
1906  *
1907  * Releases the OLE drag and drop data structures.
1908  */
1909 void OLEDD_UnInitialize(void)
1910 {
1911   /*
1912    * Simply empty the list.
1913    */
1914   while (!list_empty(&targetListHead))
1915   {
1916     DropTargetNode* curNode = LIST_ENTRY(list_head(&targetListHead), DropTargetNode, entry);
1917     OLEDD_FreeDropTarget(curNode, FALSE);
1918   }
1919 }
1920
1921 /***
1922  * OLEDD_FindDropTarget()
1923  *
1924  * Finds information about the drop target.
1925  */
1926 static DropTargetNode* OLEDD_FindDropTarget(HWND hwndOfTarget)
1927 {
1928   DropTargetNode*  curNode;
1929
1930   /*
1931    * Iterate the list to find the HWND value.
1932    */
1933   LIST_FOR_EACH_ENTRY(curNode, &targetListHead, DropTargetNode, entry)
1934     if (hwndOfTarget==curNode->hwndTarget)
1935       return curNode;
1936
1937   /*
1938    * If we get here, the item is not in the list
1939    */
1940   return NULL;
1941 }
1942
1943 /***
1944  * OLEDD_DragTrackerWindowProc()
1945  *
1946  * This method is the WindowProcedure of the drag n drop tracking
1947  * window. During a drag n Drop operation, an invisible window is created
1948  * to receive the user input and act upon it. This procedure is in charge
1949  * of this behavior.
1950  */
1951
1952 #define DRAG_TIMER_ID 1
1953
1954 static LRESULT WINAPI OLEDD_DragTrackerWindowProc(
1955                          HWND   hwnd,
1956                          UINT   uMsg,
1957                          WPARAM wParam,
1958                          LPARAM   lParam)
1959 {
1960   switch (uMsg)
1961   {
1962     case WM_CREATE:
1963     {
1964       LPCREATESTRUCTA createStruct = (LPCREATESTRUCTA)lParam;
1965
1966       SetWindowLongA(hwnd, 0, (LONG)createStruct->lpCreateParams);
1967       SetTimer(hwnd, DRAG_TIMER_ID, 50, NULL);
1968
1969       break;
1970     }
1971     case WM_TIMER:
1972     case WM_MOUSEMOVE:
1973     {
1974       OLEDD_TrackMouseMove((TrackerWindowInfo*)GetWindowLongA(hwnd, 0));
1975       break;
1976     }
1977     case WM_LBUTTONUP:
1978     case WM_MBUTTONUP:
1979     case WM_RBUTTONUP:
1980     case WM_LBUTTONDOWN:
1981     case WM_MBUTTONDOWN:
1982     case WM_RBUTTONDOWN:
1983     {
1984       OLEDD_TrackStateChange((TrackerWindowInfo*)GetWindowLongA(hwnd, 0));
1985       break;
1986     }
1987     case WM_DESTROY:
1988     {
1989       KillTimer(hwnd, DRAG_TIMER_ID);
1990       break;
1991     }
1992   }
1993
1994   /*
1995    * This is a window proc after all. Let's call the default.
1996    */
1997   return DefWindowProcA (hwnd, uMsg, wParam, lParam);
1998 }
1999
2000 /***
2001  * OLEDD_TrackMouseMove()
2002  *
2003  * This method is invoked while a drag and drop operation is in effect.
2004  * it will generate the appropriate callbacks in the drop source
2005  * and drop target. It will also provide the expected feedback to
2006  * the user.
2007  *
2008  * params:
2009  *    trackerInfo - Pointer to the structure identifying the
2010  *                  drag & drop operation that is currently
2011  *                  active.
2012  */
2013 static void OLEDD_TrackMouseMove(TrackerWindowInfo* trackerInfo)
2014 {
2015   HWND   hwndNewTarget = 0;
2016   HRESULT  hr = S_OK;
2017   POINT pt;
2018
2019   /*
2020    * Get the handle of the window under the mouse
2021    */
2022   pt.x = trackerInfo->curMousePos.x;
2023   pt.y = trackerInfo->curMousePos.y;
2024   hwndNewTarget = WindowFromPoint(pt);
2025
2026   /*
2027    * Every time, we re-initialize the effects passed to the
2028    * IDropTarget to the effects allowed by the source.
2029    */
2030   *trackerInfo->pdwEffect = trackerInfo->dwOKEffect;
2031
2032   /*
2033    * If we are hovering over the same target as before, send the
2034    * DragOver notification
2035    */
2036   if ( (trackerInfo->curDragTarget != 0) &&
2037        (trackerInfo->curTargetHWND == hwndNewTarget) )
2038   {
2039     IDropTarget_DragOver(trackerInfo->curDragTarget,
2040                          trackerInfo->dwKeyState,
2041                          trackerInfo->curMousePos,
2042                          trackerInfo->pdwEffect);
2043   }
2044   else
2045   {
2046     DropTargetNode* newDropTargetNode = 0;
2047
2048     /*
2049      * If we changed window, we have to notify our old target and check for
2050      * the new one.
2051      */
2052     if (trackerInfo->curDragTarget!=0)
2053     {
2054       IDropTarget_DragLeave(trackerInfo->curDragTarget);
2055     }
2056
2057     /*
2058      * Make sure we're hovering over a window.
2059      */
2060     if (hwndNewTarget!=0)
2061     {
2062       /*
2063        * Find-out if there is a drag target under the mouse
2064        */
2065       HWND nexttar = hwndNewTarget;
2066       trackerInfo->curTargetHWND = hwndNewTarget;
2067
2068       do {
2069         newDropTargetNode = OLEDD_FindDropTarget(nexttar);
2070       } while (!newDropTargetNode && (nexttar = GetParent(nexttar)) != 0);
2071       if(nexttar) hwndNewTarget = nexttar;
2072
2073       trackerInfo->curDragTargetHWND = hwndNewTarget;
2074       trackerInfo->curDragTarget     = newDropTargetNode ? newDropTargetNode->dropTarget : 0;
2075
2076       /*
2077        * If there is, notify it that we just dragged-in
2078        */
2079       if (trackerInfo->curDragTarget!=0)
2080       {
2081         IDropTarget_DragEnter(trackerInfo->curDragTarget,
2082                               trackerInfo->dataObject,
2083                               trackerInfo->dwKeyState,
2084                               trackerInfo->curMousePos,
2085                               trackerInfo->pdwEffect);
2086       }
2087     }
2088     else
2089     {
2090       /*
2091        * The mouse is not over a window so we don't track anything.
2092        */
2093       trackerInfo->curDragTargetHWND = 0;
2094       trackerInfo->curTargetHWND     = 0;
2095       trackerInfo->curDragTarget     = 0;
2096     }
2097   }
2098
2099   /*
2100    * Now that we have done that, we have to tell the source to give
2101    * us feedback on the work being done by the target.  If we don't
2102    * have a target, simulate no effect.
2103    */
2104   if (trackerInfo->curDragTarget==0)
2105   {
2106     *trackerInfo->pdwEffect = DROPEFFECT_NONE;
2107   }
2108
2109   hr = IDropSource_GiveFeedback(trackerInfo->dropSource,
2110                                 *trackerInfo->pdwEffect);
2111
2112   /*
2113    * When we ask for feedback from the drop source, sometimes it will
2114    * do all the necessary work and sometimes it will not handle it
2115    * when that's the case, we must display the standard drag and drop
2116    * cursors.
2117    */
2118   if (hr==DRAGDROP_S_USEDEFAULTCURSORS)
2119   {
2120     if (*trackerInfo->pdwEffect & DROPEFFECT_MOVE)
2121     {
2122       SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(1)));
2123     }
2124     else if (*trackerInfo->pdwEffect & DROPEFFECT_COPY)
2125     {
2126       SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(2)));
2127     }
2128     else if (*trackerInfo->pdwEffect & DROPEFFECT_LINK)
2129     {
2130       SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(3)));
2131     }
2132     else
2133     {
2134       SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(0)));
2135     }
2136   }
2137 }
2138
2139 /***
2140  * OLEDD_TrackStateChange()
2141  *
2142  * This method is invoked while a drag and drop operation is in effect.
2143  * It is used to notify the drop target/drop source callbacks when
2144  * the state of the keyboard or mouse button change.
2145  *
2146  * params:
2147  *    trackerInfo - Pointer to the structure identifying the
2148  *                  drag & drop operation that is currently
2149  *                  active.
2150  */
2151 static void OLEDD_TrackStateChange(TrackerWindowInfo* trackerInfo)
2152 {
2153   /*
2154    * Ask the drop source what to do with the operation.
2155    */
2156   trackerInfo->returnValue = IDropSource_QueryContinueDrag(
2157                                trackerInfo->dropSource,
2158                                trackerInfo->escPressed,
2159                                trackerInfo->dwKeyState);
2160
2161   /*
2162    * All the return valued will stop the operation except the S_OK
2163    * return value.
2164    */
2165   if (trackerInfo->returnValue!=S_OK)
2166   {
2167     /*
2168      * Make sure the message loop in DoDragDrop stops
2169      */
2170     trackerInfo->trackingDone = TRUE;
2171
2172     /*
2173      * Release the mouse in case the drop target decides to show a popup
2174      * or a menu or something.
2175      */
2176     ReleaseCapture();
2177
2178     /*
2179      * If we end-up over a target, drop the object in the target or
2180      * inform the target that the operation was cancelled.
2181      */
2182     if (trackerInfo->curDragTarget!=0)
2183     {
2184       switch (trackerInfo->returnValue)
2185       {
2186         /*
2187          * If the source wants us to complete the operation, we tell
2188          * the drop target that we just dropped the object in it.
2189          */
2190         case DRAGDROP_S_DROP:
2191         {
2192           IDropTarget_Drop(trackerInfo->curDragTarget,
2193                            trackerInfo->dataObject,
2194                            trackerInfo->dwKeyState,
2195                            trackerInfo->curMousePos,
2196                            trackerInfo->pdwEffect);
2197           break;
2198         }
2199         /*
2200          * If the source told us that we should cancel, fool the drop
2201          * target by telling it that the mouse left it's window.
2202          * Also set the drop effect to "NONE" in case the application
2203          * ignores the result of DoDragDrop.
2204          */
2205         case DRAGDROP_S_CANCEL:
2206           IDropTarget_DragLeave(trackerInfo->curDragTarget);
2207           *trackerInfo->pdwEffect = DROPEFFECT_NONE;
2208           break;
2209       }
2210     }
2211   }
2212 }
2213
2214 /***
2215  * OLEDD_GetButtonState()
2216  *
2217  * This method will use the current state of the keyboard to build
2218  * a button state mask equivalent to the one passed in the
2219  * WM_MOUSEMOVE wParam.
2220  */
2221 static DWORD OLEDD_GetButtonState(void)
2222 {
2223   BYTE  keyboardState[256];
2224   DWORD keyMask = 0;
2225
2226   GetKeyboardState(keyboardState);
2227
2228   if ( (keyboardState[VK_SHIFT] & 0x80) !=0)
2229     keyMask |= MK_SHIFT;
2230
2231   if ( (keyboardState[VK_CONTROL] & 0x80) !=0)
2232     keyMask |= MK_CONTROL;
2233
2234   if ( (keyboardState[VK_LBUTTON] & 0x80) !=0)
2235     keyMask |= MK_LBUTTON;
2236
2237   if ( (keyboardState[VK_RBUTTON] & 0x80) !=0)
2238     keyMask |= MK_RBUTTON;
2239
2240   if ( (keyboardState[VK_MBUTTON] & 0x80) !=0)
2241     keyMask |= MK_MBUTTON;
2242
2243   return keyMask;
2244 }
2245
2246 /***
2247  * OLEDD_GetButtonState()
2248  *
2249  * This method will read the default value of the registry key in
2250  * parameter and extract a DWORD value from it. The registry key value
2251  * can be in a string key or a DWORD key.
2252  *
2253  * params:
2254  *     regKey   - Key to read the default value from
2255  *     pdwValue - Pointer to the location where the DWORD
2256  *                value is returned. This value is not modified
2257  *                if the value is not found.
2258  */
2259
2260 static void OLEUTL_ReadRegistryDWORDValue(
2261   HKEY   regKey,
2262   DWORD* pdwValue)
2263 {
2264   char  buffer[20];
2265   DWORD dwKeyType;
2266   DWORD cbData = 20;
2267   LONG  lres;
2268
2269   lres = RegQueryValueExA(regKey,
2270                           "",
2271                           NULL,
2272                           &dwKeyType,
2273                           (LPBYTE)buffer,
2274                           &cbData);
2275
2276   if (lres==ERROR_SUCCESS)
2277   {
2278     switch (dwKeyType)
2279     {
2280       case REG_DWORD:
2281         *pdwValue = *(DWORD*)buffer;
2282         break;
2283       case REG_EXPAND_SZ:
2284       case REG_MULTI_SZ:
2285       case REG_SZ:
2286         *pdwValue = (DWORD)strtoul(buffer, NULL, 10);
2287         break;
2288     }
2289   }
2290 }
2291
2292 /******************************************************************************
2293  * OleDraw (OLE32.@)
2294  *
2295  * The operation of this function is documented literally in the WinAPI
2296  * documentation to involve a QueryInterface for the IViewObject interface,
2297  * followed by a call to IViewObject::Draw.
2298  */
2299 HRESULT WINAPI OleDraw(
2300         IUnknown *pUnk,
2301         DWORD dwAspect,
2302         HDC hdcDraw,
2303         LPCRECT lprcBounds)
2304 {
2305   HRESULT hres;
2306   IViewObject *viewobject;
2307
2308   hres = IUnknown_QueryInterface(pUnk,
2309                                  &IID_IViewObject,
2310                                  (void**)&viewobject);
2311
2312   if (SUCCEEDED(hres))
2313   {
2314     RECTL rectl;
2315
2316     rectl.left = lprcBounds->left;
2317     rectl.right = lprcBounds->right;
2318     rectl.top = lprcBounds->top;
2319     rectl.bottom = lprcBounds->bottom;
2320     hres = IViewObject_Draw(viewobject, dwAspect, -1, 0, 0, 0, hdcDraw, &rectl, 0, 0, 0);
2321
2322     IViewObject_Release(viewobject);
2323     return hres;
2324   }
2325   else
2326   {
2327     return DV_E_NOIVIEWOBJECT;
2328   }
2329 }
2330
2331 /***********************************************************************
2332  *             OleTranslateAccelerator [OLE32.@]
2333  */
2334 HRESULT WINAPI OleTranslateAccelerator (LPOLEINPLACEFRAME lpFrame,
2335                    LPOLEINPLACEFRAMEINFO lpFrameInfo, LPMSG lpmsg)
2336 {
2337     WORD wID;
2338
2339     TRACE("(%p,%p,%p)\n", lpFrame, lpFrameInfo, lpmsg);
2340
2341     if (IsAccelerator(lpFrameInfo->haccel,lpFrameInfo->cAccelEntries,lpmsg,&wID))
2342         return IOleInPlaceFrame_TranslateAccelerator(lpFrame,lpmsg,wID);
2343
2344     return S_FALSE;
2345 }
2346
2347 /******************************************************************************
2348  *              OleCreate        [OLE32.@]
2349  *
2350  */
2351 HRESULT WINAPI OleCreate(
2352         REFCLSID rclsid,
2353         REFIID riid,
2354         DWORD renderopt,
2355         LPFORMATETC pFormatEtc,
2356         LPOLECLIENTSITE pClientSite,
2357         LPSTORAGE pStg,
2358         LPVOID* ppvObj)
2359 {
2360     HRESULT hres;
2361     IUnknown * pUnk = NULL;
2362     IOleObject *pOleObject = NULL;
2363
2364     TRACE("(%s, %s, %d, %p, %p, %p, %p)\n", debugstr_guid(rclsid),
2365         debugstr_guid(riid), renderopt, pFormatEtc, pClientSite, pStg, ppvObj);
2366
2367     hres = CoCreateInstance(rclsid, 0, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER, riid, (LPVOID*)&pUnk);
2368
2369     if (SUCCEEDED(hres))
2370         hres = IStorage_SetClass(pStg, rclsid);
2371
2372     if (pClientSite && SUCCEEDED(hres))
2373     {
2374         hres = IUnknown_QueryInterface(pUnk, &IID_IOleObject, (LPVOID*)&pOleObject);
2375         if (SUCCEEDED(hres))
2376         {
2377             DWORD dwStatus;
2378             hres = IOleObject_GetMiscStatus(pOleObject, DVASPECT_CONTENT, &dwStatus);
2379         }
2380     }
2381
2382     if (SUCCEEDED(hres))
2383     {
2384         IPersistStorage * pPS;
2385         if (SUCCEEDED((hres = IUnknown_QueryInterface(pUnk, &IID_IPersistStorage, (LPVOID*)&pPS))))
2386         {
2387             TRACE("trying to set stg %p\n", pStg);
2388             hres = IPersistStorage_InitNew(pPS, pStg);
2389             TRACE("-- result 0x%08x\n", hres);
2390             IPersistStorage_Release(pPS);
2391         }
2392     }
2393
2394     if (pClientSite && SUCCEEDED(hres))
2395     {
2396         TRACE("trying to set clientsite %p\n", pClientSite);
2397         hres = IOleObject_SetClientSite(pOleObject, pClientSite);
2398         TRACE("-- result 0x%08x\n", hres);
2399     }
2400
2401     if (pOleObject)
2402         IOleObject_Release(pOleObject);
2403
2404     if (((renderopt == OLERENDER_DRAW) || (renderopt == OLERENDER_FORMAT)) &&
2405         SUCCEEDED(hres))
2406     {
2407         IRunnableObject *pRunnable;
2408         IOleCache *pOleCache;
2409         HRESULT hres2;
2410
2411         hres2 = IUnknown_QueryInterface(pUnk, &IID_IRunnableObject, (void **)&pRunnable);
2412         if (SUCCEEDED(hres2))
2413         {
2414             hres = IRunnableObject_Run(pRunnable, NULL);
2415             IRunnableObject_Release(pRunnable);
2416         }
2417
2418         if (SUCCEEDED(hres))
2419         {
2420             hres2 = IUnknown_QueryInterface(pUnk, &IID_IOleCache, (void **)&pOleCache);
2421             if (SUCCEEDED(hres2))
2422             {
2423                 DWORD dwConnection;
2424                 hres = IOleCache_Cache(pOleCache, pFormatEtc, ADVF_PRIMEFIRST, &dwConnection);
2425                 IOleCache_Release(pOleCache);
2426             }
2427         }
2428     }
2429
2430     if (FAILED(hres) && pUnk)
2431     {
2432         IUnknown_Release(pUnk);
2433         pUnk = NULL;
2434     }
2435
2436     *ppvObj = pUnk;
2437
2438     TRACE("-- %p\n", pUnk);
2439     return hres;
2440 }
2441
2442 /******************************************************************************
2443  *              OleGetAutoConvert        [OLE32.@]
2444  */
2445 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
2446 {
2447     static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2448     HKEY hkey = NULL;
2449     WCHAR buf[CHARS_IN_GUID];
2450     LONG len;
2451     HRESULT res = S_OK;
2452
2453     res = COM_OpenKeyForCLSID(clsidOld, wszAutoConvertTo, KEY_READ, &hkey);
2454     if (FAILED(res))
2455         goto done;
2456
2457     len = sizeof(buf);
2458     if (RegQueryValueW(hkey, NULL, buf, &len))
2459     {
2460         res = REGDB_E_KEYMISSING;
2461         goto done;
2462     }
2463     res = CLSIDFromString(buf, pClsidNew);
2464 done:
2465     if (hkey) RegCloseKey(hkey);
2466     return res;
2467 }
2468
2469 /******************************************************************************
2470  *              OleSetAutoConvert        [OLE32.@]
2471  */
2472 HRESULT WINAPI OleSetAutoConvert(REFCLSID clsidOld, REFCLSID clsidNew)
2473 {
2474     static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2475     HKEY hkey = NULL;
2476     WCHAR szClsidNew[CHARS_IN_GUID];
2477     HRESULT res = S_OK;
2478
2479     TRACE("(%s,%s)\n", debugstr_guid(clsidOld), debugstr_guid(clsidNew));
2480     
2481     res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2482     if (FAILED(res))
2483         goto done;
2484     StringFromGUID2(clsidNew, szClsidNew, CHARS_IN_GUID);
2485     if (RegSetValueW(hkey, wszAutoConvertTo, REG_SZ, szClsidNew, (strlenW(szClsidNew)+1) * sizeof(WCHAR)))
2486     {
2487         res = REGDB_E_WRITEREGDB;
2488         goto done;
2489     }
2490
2491 done:
2492     if (hkey) RegCloseKey(hkey);
2493     return res;
2494 }
2495
2496 /******************************************************************************
2497  *              OleDoAutoConvert        [OLE32.@]
2498  */
2499 HRESULT WINAPI OleDoAutoConvert(LPSTORAGE pStg, LPCLSID pClsidNew)
2500 {
2501     FIXME("(%p,%p) : stub\n",pStg,pClsidNew);
2502     return E_NOTIMPL;
2503 }
2504
2505 /******************************************************************************
2506  *              OleIsRunning        [OLE32.@]
2507  */
2508 BOOL WINAPI OleIsRunning(LPOLEOBJECT pObject)
2509 {
2510     IRunnableObject *pRunnable;
2511     HRESULT hr;
2512     BOOL running;
2513
2514     TRACE("(%p)\n", pObject);
2515
2516     hr = IOleObject_QueryInterface(pObject, &IID_IRunnableObject, (void **)&pRunnable);
2517     if (FAILED(hr))
2518         return TRUE;
2519     running = IRunnableObject_IsRunning(pRunnable);
2520     IRunnableObject_Release(pRunnable);
2521     return running;
2522 }
2523
2524 /***********************************************************************
2525  *           OleNoteObjectVisible                           [OLE32.@]
2526  */
2527 HRESULT WINAPI OleNoteObjectVisible(LPUNKNOWN pUnknown, BOOL bVisible)
2528 {
2529     TRACE("(%p, %s)\n", pUnknown, bVisible ? "TRUE" : "FALSE");
2530     return CoLockObjectExternal(pUnknown, bVisible, TRUE);
2531 }
2532
2533
2534 /***********************************************************************
2535  *           OLE_FreeClipDataArray   [internal]
2536  *
2537  * NOTES:
2538  *  frees the data associated with an array of CLIPDATAs
2539  */
2540 static void OLE_FreeClipDataArray(ULONG count, CLIPDATA * pClipDataArray)
2541 {
2542     ULONG i;
2543     for (i = 0; i < count; i++)
2544         if (pClipDataArray[i].pClipData)
2545             CoTaskMemFree(pClipDataArray[i].pClipData);
2546 }
2547
2548 /***********************************************************************
2549  *           PropSysAllocString                     [OLE32.@]
2550  * NOTES:
2551  *  Basically a copy of SysAllocStringLen.
2552  */
2553 BSTR WINAPI PropSysAllocString(LPCOLESTR str)
2554 {
2555     DWORD  bufferSize;
2556     DWORD* newBuffer;
2557     WCHAR* stringBuffer;
2558     int len;
2559
2560     if (!str) return 0;
2561
2562     len = lstrlenW(str);
2563     /*
2564      * Find the length of the buffer passed-in, in bytes.
2565      */
2566     bufferSize = len * sizeof (WCHAR);
2567
2568     /*
2569      * Allocate a new buffer to hold the string.
2570      * Don't forget to keep an empty spot at the beginning of the
2571      * buffer for the character count and an extra character at the
2572      * end for the NULL.
2573      */
2574     newBuffer = HeapAlloc(GetProcessHeap(), 0,
2575                           bufferSize + sizeof(WCHAR) + sizeof(DWORD));
2576
2577     /*
2578      * If the memory allocation failed, return a null pointer.
2579      */
2580     if (newBuffer==0)
2581       return 0;
2582
2583     /*
2584      * Copy the length of the string in the placeholder.
2585      */
2586     *newBuffer = bufferSize;
2587
2588     /*
2589      * Skip the byte count.
2590      */
2591     newBuffer++;
2592
2593     memcpy(newBuffer, str, bufferSize);
2594
2595     /*
2596      * Make sure that there is a nul character at the end of the
2597      * string.
2598      */
2599     stringBuffer = (WCHAR*)newBuffer;
2600     stringBuffer[len] = '\0';
2601
2602     return (LPWSTR)stringBuffer;
2603 }
2604
2605 /***********************************************************************
2606  *           PropSysFreeString                      [OLE32.@]
2607  * NOTES
2608  *  Copy of SysFreeString.
2609  */
2610 void WINAPI PropSysFreeString(LPOLESTR str)
2611 {
2612     DWORD* bufferPointer;
2613
2614     /* NULL is a valid parameter */
2615     if(!str) return;
2616
2617     /*
2618      * We have to be careful when we free a BSTR pointer, it points to
2619      * the beginning of the string but it skips the byte count contained
2620      * before the string.
2621      */
2622     bufferPointer = (DWORD*)str;
2623
2624     bufferPointer--;
2625
2626     /*
2627      * Free the memory from its "real" origin.
2628      */
2629     HeapFree(GetProcessHeap(), 0, bufferPointer);
2630 }
2631
2632 /******************************************************************************
2633  * Check if a PROPVARIANT's type is valid.
2634  */
2635 static inline HRESULT PROPVARIANT_ValidateType(VARTYPE vt)
2636 {
2637     switch (vt)
2638     {
2639     case VT_EMPTY:
2640     case VT_NULL:
2641     case VT_I2:
2642     case VT_I4:
2643     case VT_R4:
2644     case VT_R8:
2645     case VT_CY:
2646     case VT_DATE:
2647     case VT_BSTR:
2648     case VT_ERROR:
2649     case VT_BOOL:
2650     case VT_UI1:
2651     case VT_UI2:
2652     case VT_UI4:
2653     case VT_I8:
2654     case VT_UI8:
2655     case VT_LPSTR:
2656     case VT_LPWSTR:
2657     case VT_FILETIME:
2658     case VT_BLOB:
2659     case VT_STREAM:
2660     case VT_STORAGE:
2661     case VT_STREAMED_OBJECT:
2662     case VT_STORED_OBJECT:
2663     case VT_BLOB_OBJECT:
2664     case VT_CF:
2665     case VT_CLSID:
2666     case VT_I2|VT_VECTOR:
2667     case VT_I4|VT_VECTOR:
2668     case VT_R4|VT_VECTOR:
2669     case VT_R8|VT_VECTOR:
2670     case VT_CY|VT_VECTOR:
2671     case VT_DATE|VT_VECTOR:
2672     case VT_BSTR|VT_VECTOR:
2673     case VT_ERROR|VT_VECTOR:
2674     case VT_BOOL|VT_VECTOR:
2675     case VT_VARIANT|VT_VECTOR:
2676     case VT_UI1|VT_VECTOR:
2677     case VT_UI2|VT_VECTOR:
2678     case VT_UI4|VT_VECTOR:
2679     case VT_I8|VT_VECTOR:
2680     case VT_UI8|VT_VECTOR:
2681     case VT_LPSTR|VT_VECTOR:
2682     case VT_LPWSTR|VT_VECTOR:
2683     case VT_FILETIME|VT_VECTOR:
2684     case VT_CF|VT_VECTOR:
2685     case VT_CLSID|VT_VECTOR:
2686         return S_OK;
2687     }
2688     WARN("Bad type %d\n", vt);
2689     return STG_E_INVALIDPARAMETER;
2690 }
2691
2692 /***********************************************************************
2693  *           PropVariantClear                       [OLE32.@]
2694  */
2695 HRESULT WINAPI PropVariantClear(PROPVARIANT * pvar) /* [in/out] */
2696 {
2697     HRESULT hr;
2698
2699     TRACE("(%p)\n", pvar);
2700
2701     if (!pvar)
2702         return S_OK;
2703
2704     hr = PROPVARIANT_ValidateType(pvar->vt);
2705     if (FAILED(hr))
2706         return hr;
2707
2708     switch(pvar->vt)
2709     {
2710     case VT_EMPTY:
2711     case VT_NULL:
2712     case VT_I2:
2713     case VT_I4:
2714     case VT_R4:
2715     case VT_R8:
2716     case VT_CY:
2717     case VT_DATE:
2718     case VT_ERROR:
2719     case VT_BOOL:
2720     case VT_UI1:
2721     case VT_UI2:
2722     case VT_UI4:
2723     case VT_I8:
2724     case VT_UI8:
2725     case VT_FILETIME:
2726         break;
2727     case VT_STREAM:
2728     case VT_STREAMED_OBJECT:
2729     case VT_STORAGE:
2730     case VT_STORED_OBJECT:
2731         if (pvar->u.pStream)
2732             IUnknown_Release(pvar->u.pStream);
2733         break;
2734     case VT_CLSID:
2735     case VT_LPSTR:
2736     case VT_LPWSTR:
2737         /* pick an arbitrary typed pointer - we don't care about the type
2738          * as we are just freeing it */
2739         CoTaskMemFree(pvar->u.puuid);
2740         break;
2741     case VT_BLOB:
2742     case VT_BLOB_OBJECT:
2743         CoTaskMemFree(pvar->u.blob.pBlobData);
2744         break;
2745     case VT_BSTR:
2746         if (pvar->u.bstrVal)
2747             PropSysFreeString(pvar->u.bstrVal);
2748         break;
2749     case VT_CF:
2750         if (pvar->u.pclipdata)
2751         {
2752             OLE_FreeClipDataArray(1, pvar->u.pclipdata);
2753             CoTaskMemFree(pvar->u.pclipdata);
2754         }
2755         break;
2756     default:
2757         if (pvar->vt & VT_VECTOR)
2758         {
2759             ULONG i;
2760
2761             switch (pvar->vt & ~VT_VECTOR)
2762             {
2763             case VT_VARIANT:
2764                 FreePropVariantArray(pvar->u.capropvar.cElems, pvar->u.capropvar.pElems);
2765                 break;
2766             case VT_CF:
2767                 OLE_FreeClipDataArray(pvar->u.caclipdata.cElems, pvar->u.caclipdata.pElems);
2768                 break;
2769             case VT_BSTR:
2770                 for (i = 0; i < pvar->u.cabstr.cElems; i++)
2771                     PropSysFreeString(pvar->u.cabstr.pElems[i]);
2772                 break;
2773             case VT_LPSTR:
2774                 for (i = 0; i < pvar->u.calpstr.cElems; i++)
2775                     CoTaskMemFree(pvar->u.calpstr.pElems[i]);
2776                 break;
2777             case VT_LPWSTR:
2778                 for (i = 0; i < pvar->u.calpwstr.cElems; i++)
2779                     CoTaskMemFree(pvar->u.calpwstr.pElems[i]);
2780                 break;
2781             }
2782             if (pvar->vt & ~VT_VECTOR)
2783             {
2784                 /* pick an arbitrary VT_VECTOR structure - they all have the same
2785                  * memory layout */
2786                 CoTaskMemFree(pvar->u.capropvar.pElems);
2787             }
2788         }
2789         else
2790             WARN("Invalid/unsupported type %d\n", pvar->vt);
2791     }
2792
2793     ZeroMemory(pvar, sizeof(*pvar));
2794
2795     return S_OK;
2796 }
2797
2798 /***********************************************************************
2799  *           PropVariantCopy                        [OLE32.@]
2800  */
2801 HRESULT WINAPI PropVariantCopy(PROPVARIANT *pvarDest,      /* [out] */
2802                                const PROPVARIANT *pvarSrc) /* [in] */
2803 {
2804     ULONG len;
2805     HRESULT hr;
2806
2807     TRACE("(%p, %p)\n", pvarDest, pvarSrc);
2808
2809     hr = PROPVARIANT_ValidateType(pvarSrc->vt);
2810     if (FAILED(hr))
2811         return hr;
2812
2813     /* this will deal with most cases */
2814     *pvarDest = *pvarSrc;
2815
2816     switch(pvarSrc->vt)
2817     {
2818     case VT_FILETIME:
2819         break;
2820     case VT_STREAM:
2821     case VT_STREAMED_OBJECT:
2822     case VT_STORAGE:
2823     case VT_STORED_OBJECT:
2824         IUnknown_AddRef((LPUNKNOWN)pvarDest->u.pStream);
2825         break;
2826     case VT_CLSID:
2827         pvarDest->u.puuid = CoTaskMemAlloc(sizeof(CLSID));
2828         *pvarDest->u.puuid = *pvarSrc->u.puuid;
2829         break;
2830     case VT_LPSTR:
2831         len = strlen(pvarSrc->u.pszVal);
2832         pvarDest->u.pszVal = CoTaskMemAlloc((len+1)*sizeof(CHAR));
2833         CopyMemory(pvarDest->u.pszVal, pvarSrc->u.pszVal, (len+1)*sizeof(CHAR));
2834         break;
2835     case VT_LPWSTR:
2836         len = lstrlenW(pvarSrc->u.pwszVal);
2837         pvarDest->u.pwszVal = CoTaskMemAlloc((len+1)*sizeof(WCHAR));
2838         CopyMemory(pvarDest->u.pwszVal, pvarSrc->u.pwszVal, (len+1)*sizeof(WCHAR));
2839         break;
2840     case VT_BLOB:
2841     case VT_BLOB_OBJECT:
2842         if (pvarSrc->u.blob.pBlobData)
2843         {
2844             len = pvarSrc->u.blob.cbSize;
2845             pvarDest->u.blob.pBlobData = CoTaskMemAlloc(len);
2846             CopyMemory(pvarDest->u.blob.pBlobData, pvarSrc->u.blob.pBlobData, len);
2847         }
2848         break;
2849     case VT_BSTR:
2850         pvarDest->u.bstrVal = PropSysAllocString(pvarSrc->u.bstrVal);
2851         break;
2852     case VT_CF:
2853         if (pvarSrc->u.pclipdata)
2854         {
2855             len = pvarSrc->u.pclipdata->cbSize - sizeof(pvarSrc->u.pclipdata->ulClipFmt);
2856             pvarDest->u.pclipdata = CoTaskMemAlloc(sizeof (CLIPDATA));
2857             pvarDest->u.pclipdata->cbSize = pvarSrc->u.pclipdata->cbSize;
2858             pvarDest->u.pclipdata->ulClipFmt = pvarSrc->u.pclipdata->ulClipFmt;
2859             pvarDest->u.pclipdata->pClipData = CoTaskMemAlloc(len);
2860             CopyMemory(pvarDest->u.pclipdata->pClipData, pvarSrc->u.pclipdata->pClipData, len);
2861         }
2862         break;
2863     default:
2864         if (pvarSrc->vt & VT_VECTOR)
2865         {
2866             int elemSize;
2867             ULONG i;
2868
2869             switch(pvarSrc->vt & ~VT_VECTOR)
2870             {
2871             case VT_I1:       elemSize = sizeof(pvarSrc->u.cVal); break;
2872             case VT_UI1:      elemSize = sizeof(pvarSrc->u.bVal); break;
2873             case VT_I2:       elemSize = sizeof(pvarSrc->u.iVal); break;
2874             case VT_UI2:      elemSize = sizeof(pvarSrc->u.uiVal); break;
2875             case VT_BOOL:     elemSize = sizeof(pvarSrc->u.boolVal); break;
2876             case VT_I4:       elemSize = sizeof(pvarSrc->u.lVal); break;
2877             case VT_UI4:      elemSize = sizeof(pvarSrc->u.ulVal); break;
2878             case VT_R4:       elemSize = sizeof(pvarSrc->u.fltVal); break;
2879             case VT_R8:       elemSize = sizeof(pvarSrc->u.dblVal); break;
2880             case VT_ERROR:    elemSize = sizeof(pvarSrc->u.scode); break;
2881             case VT_I8:       elemSize = sizeof(pvarSrc->u.hVal); break;
2882             case VT_UI8:      elemSize = sizeof(pvarSrc->u.uhVal); break;
2883             case VT_CY:       elemSize = sizeof(pvarSrc->u.cyVal); break;
2884             case VT_DATE:     elemSize = sizeof(pvarSrc->u.date); break;
2885             case VT_FILETIME: elemSize = sizeof(pvarSrc->u.filetime); break;
2886             case VT_CLSID:    elemSize = sizeof(*pvarSrc->u.puuid); break;
2887             case VT_CF:       elemSize = sizeof(*pvarSrc->u.pclipdata); break;
2888             case VT_BSTR:     elemSize = sizeof(*pvarSrc->u.bstrVal); break;
2889             case VT_LPSTR:    elemSize = sizeof(*pvarSrc->u.pszVal); break;
2890             case VT_LPWSTR:   elemSize = sizeof(*pvarSrc->u.pwszVal); break;
2891             case VT_VARIANT:  elemSize = sizeof(*pvarSrc->u.pvarVal); break;
2892
2893             default:
2894                 FIXME("Invalid element type: %ul\n", pvarSrc->vt & ~VT_VECTOR);
2895                 return E_INVALIDARG;
2896             }
2897             len = pvarSrc->u.capropvar.cElems;
2898             pvarDest->u.capropvar.pElems = CoTaskMemAlloc(len * elemSize);
2899             if (pvarSrc->vt == (VT_VECTOR | VT_VARIANT))
2900             {
2901                 for (i = 0; i < len; i++)
2902                     PropVariantCopy(&pvarDest->u.capropvar.pElems[i], &pvarSrc->u.capropvar.pElems[i]);
2903             }
2904             else if (pvarSrc->vt == (VT_VECTOR | VT_CF))
2905             {
2906                 FIXME("Copy clipformats\n");
2907             }
2908             else if (pvarSrc->vt == (VT_VECTOR | VT_BSTR))
2909             {
2910                 for (i = 0; i < len; i++)
2911                     pvarDest->u.cabstr.pElems[i] = PropSysAllocString(pvarSrc->u.cabstr.pElems[i]);
2912             }
2913             else if (pvarSrc->vt == (VT_VECTOR | VT_LPSTR))
2914             {
2915                 size_t strLen;
2916                 for (i = 0; i < len; i++)
2917                 {
2918                     strLen = lstrlenA(pvarSrc->u.calpstr.pElems[i]) + 1;
2919                     pvarDest->u.calpstr.pElems[i] = CoTaskMemAlloc(strLen);
2920                     memcpy(pvarDest->u.calpstr.pElems[i],
2921                      pvarSrc->u.calpstr.pElems[i], strLen);
2922                 }
2923             }
2924             else if (pvarSrc->vt == (VT_VECTOR | VT_LPWSTR))
2925             {
2926                 size_t strLen;
2927                 for (i = 0; i < len; i++)
2928                 {
2929                     strLen = (lstrlenW(pvarSrc->u.calpwstr.pElems[i]) + 1) *
2930                      sizeof(WCHAR);
2931                     pvarDest->u.calpstr.pElems[i] = CoTaskMemAlloc(strLen);
2932                     memcpy(pvarDest->u.calpstr.pElems[i],
2933                      pvarSrc->u.calpstr.pElems[i], strLen);
2934                 }
2935             }
2936             else
2937                 CopyMemory(pvarDest->u.capropvar.pElems, pvarSrc->u.capropvar.pElems, len * elemSize);
2938         }
2939         else
2940             WARN("Invalid/unsupported type %d\n", pvarSrc->vt);
2941     }
2942
2943     return S_OK;
2944 }
2945
2946 /***********************************************************************
2947  *           FreePropVariantArray                           [OLE32.@]
2948  */
2949 HRESULT WINAPI FreePropVariantArray(ULONG cVariants, /* [in] */
2950                                     PROPVARIANT *rgvars)    /* [in/out] */
2951 {
2952     ULONG i;
2953
2954     TRACE("(%u, %p)\n", cVariants, rgvars);
2955
2956     if (!rgvars)
2957         return E_INVALIDARG;
2958
2959     for(i = 0; i < cVariants; i++)
2960         PropVariantClear(&rgvars[i]);
2961
2962     return S_OK;
2963 }
2964
2965 /******************************************************************************
2966  * DllDebugObjectRPCHook (OLE32.@)
2967  * turns on and off internal debugging,  pointer is only used on macintosh
2968  */
2969
2970 BOOL WINAPI DllDebugObjectRPCHook(BOOL b, void *dummy)
2971 {
2972   FIXME("stub\n");
2973   return TRUE;
2974 }