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