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