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