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