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