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