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