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