shdocvw: Replaced iexplore.bmp with a tango compliant toolstrip.
[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   if (SUCCEEDED(hres))
1185     /*
1186      * Initialize the object with it's IPersistStorage interface.
1187      */
1188     hres = IOleObject_QueryInterface(pUnk,
1189                                      &IID_IPersistStorage,
1190                                      (void**)&persistStorage);
1191
1192   if (SUCCEEDED(hres))
1193   {
1194     hres = IPersistStorage_Load(persistStorage, pStg);
1195
1196     IPersistStorage_Release(persistStorage);
1197     persistStorage = NULL;
1198   }
1199
1200   if (SUCCEEDED(hres) && pClientSite)
1201     /*
1202      * Inform the new object of it's client site.
1203      */
1204     hres = IOleObject_SetClientSite(pOleObject, pClientSite);
1205
1206   /*
1207    * Cleanup interfaces used internally
1208    */
1209   if (pOleObject)
1210     IOleObject_Release(pOleObject);
1211
1212   if (SUCCEEDED(hres))
1213   {
1214     IOleLink *pOleLink;
1215     HRESULT hres1;
1216     hres1 = IUnknown_QueryInterface(pUnk, &IID_IOleLink, (void **)&pOleLink);
1217     if (SUCCEEDED(hres1))
1218     {
1219       FIXME("handle OLE link\n");
1220       IOleLink_Release(pOleLink);
1221     }
1222   }
1223
1224   if (FAILED(hres))
1225   {
1226     IUnknown_Release(pUnk);
1227     pUnk = NULL;
1228   }
1229
1230   *ppvObj = pUnk;
1231
1232   return hres;
1233 }
1234
1235 /***********************************************************************
1236  *           OleSave     [OLE32.@]
1237  */
1238 HRESULT WINAPI OleSave(
1239   LPPERSISTSTORAGE pPS,
1240   LPSTORAGE        pStg,
1241   BOOL             fSameAsLoad)
1242 {
1243   HRESULT hres;
1244   CLSID   objectClass;
1245
1246   TRACE("(%p,%p,%x)\n", pPS, pStg, fSameAsLoad);
1247
1248   /*
1249    * First, we transfer the class ID (if available)
1250    */
1251   hres = IPersistStorage_GetClassID(pPS, &objectClass);
1252
1253   if (SUCCEEDED(hres))
1254   {
1255     WriteClassStg(pStg, &objectClass);
1256   }
1257
1258   /*
1259    * Then, we ask the object to save itself to the
1260    * storage. If it is successful, we commit the storage.
1261    */
1262   hres = IPersistStorage_Save(pPS, pStg, fSameAsLoad);
1263
1264   if (SUCCEEDED(hres))
1265   {
1266     IStorage_Commit(pStg,
1267                     STGC_DEFAULT);
1268   }
1269
1270   return hres;
1271 }
1272
1273
1274 /******************************************************************************
1275  *              OleLockRunning        [OLE32.@]
1276  */
1277 HRESULT WINAPI OleLockRunning(LPUNKNOWN pUnknown, BOOL fLock, BOOL fLastUnlockCloses)
1278 {
1279   IRunnableObject* runnable = NULL;
1280   HRESULT          hres;
1281
1282   TRACE("(%p,%x,%x)\n", pUnknown, fLock, fLastUnlockCloses);
1283
1284   hres = IUnknown_QueryInterface(pUnknown,
1285                                  &IID_IRunnableObject,
1286                                  (void**)&runnable);
1287
1288   if (SUCCEEDED(hres))
1289   {
1290     hres = IRunnableObject_LockRunning(runnable, fLock, fLastUnlockCloses);
1291
1292     IRunnableObject_Release(runnable);
1293
1294     return hres;
1295   }
1296
1297   return S_OK;
1298 }
1299
1300
1301 /**************************************************************************
1302  * Internal methods to manage the shared OLE menu in response to the
1303  * OLE***MenuDescriptor API
1304  */
1305
1306 /***
1307  * OLEMenu_Initialize()
1308  *
1309  * Initializes the OLEMENU data structures.
1310  */
1311 static void OLEMenu_Initialize(void)
1312 {
1313 }
1314
1315 /***
1316  * OLEMenu_UnInitialize()
1317  *
1318  * Releases the OLEMENU data structures.
1319  */
1320 static void OLEMenu_UnInitialize(void)
1321 {
1322 }
1323
1324 /*************************************************************************
1325  * OLEMenu_InstallHooks
1326  * Install thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC
1327  *
1328  * RETURNS: TRUE if message hooks were successfully installed
1329  *          FALSE on failure
1330  */
1331 static BOOL OLEMenu_InstallHooks( DWORD tid )
1332 {
1333   OleMenuHookItem *pHookItem;
1334
1335   /* Create an entry for the hook table */
1336   if ( !(pHookItem = HeapAlloc(GetProcessHeap(), 0,
1337                                sizeof(OleMenuHookItem)) ) )
1338     return FALSE;
1339
1340   pHookItem->tid = tid;
1341   pHookItem->hHeap = GetProcessHeap();
1342   pHookItem->CallWndProc_hHook = NULL;
1343
1344   /* Install a thread scope message hook for WH_GETMESSAGE */
1345   pHookItem->GetMsg_hHook = SetWindowsHookExW( WH_GETMESSAGE, OLEMenu_GetMsgProc,
1346                                                0, GetCurrentThreadId() );
1347   if ( !pHookItem->GetMsg_hHook )
1348     goto CLEANUP;
1349
1350   /* Install a thread scope message hook for WH_CALLWNDPROC */
1351   pHookItem->CallWndProc_hHook = SetWindowsHookExW( WH_CALLWNDPROC, OLEMenu_CallWndProc,
1352                                                     0, GetCurrentThreadId() );
1353   if ( !pHookItem->CallWndProc_hHook )
1354     goto CLEANUP;
1355
1356   /* Insert the hook table entry */
1357   pHookItem->next = hook_list;
1358   hook_list = pHookItem;
1359
1360   return TRUE;
1361
1362 CLEANUP:
1363   /* Unhook any hooks */
1364   if ( pHookItem->GetMsg_hHook )
1365     UnhookWindowsHookEx( pHookItem->GetMsg_hHook );
1366   if ( pHookItem->CallWndProc_hHook )
1367     UnhookWindowsHookEx( pHookItem->CallWndProc_hHook );
1368   /* Release the hook table entry */
1369   HeapFree(pHookItem->hHeap, 0, pHookItem );
1370
1371   return FALSE;
1372 }
1373
1374 /*************************************************************************
1375  * OLEMenu_UnInstallHooks
1376  * UnInstall thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC
1377  *
1378  * RETURNS: TRUE if message hooks were successfully installed
1379  *          FALSE on failure
1380  */
1381 static BOOL OLEMenu_UnInstallHooks( DWORD tid )
1382 {
1383   OleMenuHookItem *pHookItem = NULL;
1384   OleMenuHookItem **ppHook = &hook_list;
1385
1386   while (*ppHook)
1387   {
1388       if ((*ppHook)->tid == tid)
1389       {
1390           pHookItem = *ppHook;
1391           *ppHook = pHookItem->next;
1392           break;
1393       }
1394       ppHook = &(*ppHook)->next;
1395   }
1396   if (!pHookItem) return FALSE;
1397
1398   /* Uninstall the hooks installed for this thread */
1399   if ( !UnhookWindowsHookEx( pHookItem->GetMsg_hHook ) )
1400     goto CLEANUP;
1401   if ( !UnhookWindowsHookEx( pHookItem->CallWndProc_hHook ) )
1402     goto CLEANUP;
1403
1404   /* Release the hook table entry */
1405   HeapFree(pHookItem->hHeap, 0, pHookItem );
1406
1407   return TRUE;
1408
1409 CLEANUP:
1410   /* Release the hook table entry */
1411   HeapFree(pHookItem->hHeap, 0, pHookItem );
1412
1413   return FALSE;
1414 }
1415
1416 /*************************************************************************
1417  * OLEMenu_IsHookInstalled
1418  * Tests if OLEMenu hooks have been installed for a thread
1419  *
1420  * RETURNS: The pointer and index of the hook table entry for the tid
1421  *          NULL and -1 for the index if no hooks were installed for this thread
1422  */
1423 static OleMenuHookItem * OLEMenu_IsHookInstalled( DWORD tid )
1424 {
1425   OleMenuHookItem *pHookItem;
1426
1427   /* Do a simple linear search for an entry whose tid matches ours.
1428    * We really need a map but efficiency is not a concern here. */
1429   for (pHookItem = hook_list; pHookItem; pHookItem = pHookItem->next)
1430   {
1431     if ( tid == pHookItem->tid )
1432       return pHookItem;
1433   }
1434
1435   return NULL;
1436 }
1437
1438 /***********************************************************************
1439  *           OLEMenu_FindMainMenuIndex
1440  *
1441  * Used by OLEMenu API to find the top level group a menu item belongs to.
1442  * On success pnPos contains the index of the item in the top level menu group
1443  *
1444  * RETURNS: TRUE if the ID was found, FALSE on failure
1445  */
1446 static BOOL OLEMenu_FindMainMenuIndex( HMENU hMainMenu, HMENU hPopupMenu, UINT *pnPos )
1447 {
1448   INT i, nItems;
1449
1450   nItems = GetMenuItemCount( hMainMenu );
1451
1452   for (i = 0; i < nItems; i++)
1453   {
1454     HMENU hsubmenu;
1455
1456     /*  Is the current item a submenu? */
1457     if ( (hsubmenu = GetSubMenu(hMainMenu, i)) )
1458     {
1459       /* If the handle is the same we're done */
1460       if ( hsubmenu == hPopupMenu )
1461       {
1462         if (pnPos)
1463           *pnPos = i;
1464         return TRUE;
1465       }
1466       /* Recursively search without updating pnPos */
1467       else if ( OLEMenu_FindMainMenuIndex( hsubmenu, hPopupMenu, NULL ) )
1468       {
1469         if (pnPos)
1470           *pnPos = i;
1471         return TRUE;
1472       }
1473     }
1474   }
1475
1476   return FALSE;
1477 }
1478
1479 /***********************************************************************
1480  *           OLEMenu_SetIsServerMenu
1481  *
1482  * Checks whether a popup menu belongs to a shared menu group which is
1483  * owned by the server, and sets the menu descriptor state accordingly.
1484  * All menu messages from these groups should be routed to the server.
1485  *
1486  * RETURNS: TRUE if the popup menu is part of a server owned group
1487  *          FALSE if the popup menu is part of a container owned group
1488  */
1489 static BOOL OLEMenu_SetIsServerMenu( HMENU hmenu, OleMenuDescriptor *pOleMenuDescriptor )
1490 {
1491   UINT nPos = 0, nWidth, i;
1492
1493   pOleMenuDescriptor->bIsServerItem = FALSE;
1494
1495   /* Don't bother searching if the popup is the combined menu itself */
1496   if ( hmenu == pOleMenuDescriptor->hmenuCombined )
1497     return FALSE;
1498
1499   /* Find the menu item index in the shared OLE menu that this item belongs to */
1500   if ( !OLEMenu_FindMainMenuIndex( pOleMenuDescriptor->hmenuCombined, hmenu,  &nPos ) )
1501     return FALSE;
1502
1503   /* The group widths array has counts for the number of elements
1504    * in the groups File, Edit, Container, Object, Window, Help.
1505    * The Edit, Object & Help groups belong to the server object
1506    * and the other three belong to the container.
1507    * Loop through the group widths and locate the group we are a member of.
1508    */
1509   for ( i = 0, nWidth = 0; i < 6; i++ )
1510   {
1511     nWidth += pOleMenuDescriptor->mgw.width[i];
1512     if ( nPos < nWidth )
1513     {
1514       /* Odd elements are server menu widths */
1515       pOleMenuDescriptor->bIsServerItem = (i%2) ? TRUE : FALSE;
1516       break;
1517     }
1518   }
1519
1520   return pOleMenuDescriptor->bIsServerItem;
1521 }
1522
1523 /*************************************************************************
1524  * OLEMenu_CallWndProc
1525  * Thread scope WH_CALLWNDPROC hook proc filter function (callback)
1526  * This is invoked from a message hook installed in OleSetMenuDescriptor.
1527  */
1528 static LRESULT CALLBACK OLEMenu_CallWndProc(INT code, WPARAM wParam, LPARAM lParam)
1529 {
1530   LPCWPSTRUCT pMsg;
1531   HOLEMENU hOleMenu = 0;
1532   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1533   OleMenuHookItem *pHookItem = NULL;
1534   WORD fuFlags;
1535
1536   TRACE("%i, %04lx, %08lx\n", code, wParam, lParam );
1537
1538   /* Check if we're being asked to process the message */
1539   if ( HC_ACTION != code )
1540     goto NEXTHOOK;
1541
1542   /* Retrieve the current message being dispatched from lParam */
1543   pMsg = (LPCWPSTRUCT)lParam;
1544
1545   /* Check if the message is destined for a window we are interested in:
1546    * If the window has an OLEMenu property we may need to dispatch
1547    * the menu message to its active objects window instead. */
1548
1549   hOleMenu = GetPropW( pMsg->hwnd, prop_olemenuW );
1550   if ( !hOleMenu )
1551     goto NEXTHOOK;
1552
1553   /* Get the menu descriptor */
1554   pOleMenuDescriptor = GlobalLock( hOleMenu );
1555   if ( !pOleMenuDescriptor ) /* Bad descriptor! */
1556     goto NEXTHOOK;
1557
1558   /* Process menu messages */
1559   switch( pMsg->message )
1560   {
1561     case WM_INITMENU:
1562     {
1563       /* Reset the menu descriptor state */
1564       pOleMenuDescriptor->bIsServerItem = FALSE;
1565
1566       /* Send this message to the server as well */
1567       SendMessageW( pOleMenuDescriptor->hwndActiveObject,
1568                   pMsg->message, pMsg->wParam, pMsg->lParam );
1569       goto NEXTHOOK;
1570     }
1571
1572     case WM_INITMENUPOPUP:
1573     {
1574       /* Save the state for whether this is a server owned menu */
1575       OLEMenu_SetIsServerMenu( (HMENU)pMsg->wParam, pOleMenuDescriptor );
1576       break;
1577     }
1578
1579     case WM_MENUSELECT:
1580     {
1581       fuFlags = HIWORD(pMsg->wParam);  /* Get flags */
1582       if ( fuFlags & MF_SYSMENU )
1583          goto NEXTHOOK;
1584
1585       /* Save the state for whether this is a server owned popup menu */
1586       else if ( fuFlags & MF_POPUP )
1587         OLEMenu_SetIsServerMenu( (HMENU)pMsg->lParam, pOleMenuDescriptor );
1588
1589       break;
1590     }
1591
1592     case WM_DRAWITEM:
1593     {
1594       LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT) pMsg->lParam;
1595       if ( pMsg->wParam != 0 || lpdis->CtlType != ODT_MENU )
1596         goto NEXTHOOK;  /* Not a menu message */
1597
1598       break;
1599     }
1600
1601     default:
1602       goto NEXTHOOK;
1603   }
1604
1605   /* If the message was for the server dispatch it accordingly */
1606   if ( pOleMenuDescriptor->bIsServerItem )
1607   {
1608     SendMessageW( pOleMenuDescriptor->hwndActiveObject,
1609                   pMsg->message, pMsg->wParam, pMsg->lParam );
1610   }
1611
1612 NEXTHOOK:
1613   if ( pOleMenuDescriptor )
1614     GlobalUnlock( hOleMenu );
1615
1616   /* Lookup the hook item for the current thread */
1617   if ( !( pHookItem = OLEMenu_IsHookInstalled( GetCurrentThreadId() ) ) )
1618   {
1619     /* This should never fail!! */
1620     WARN("could not retrieve hHook for current thread!\n" );
1621     return 0;
1622   }
1623
1624   /* Pass on the message to the next hooker */
1625   return CallNextHookEx( pHookItem->CallWndProc_hHook, code, wParam, lParam );
1626 }
1627
1628 /*************************************************************************
1629  * OLEMenu_GetMsgProc
1630  * Thread scope WH_GETMESSAGE hook proc filter function (callback)
1631  * This is invoked from a message hook installed in OleSetMenuDescriptor.
1632  */
1633 static LRESULT CALLBACK OLEMenu_GetMsgProc(INT code, WPARAM wParam, LPARAM lParam)
1634 {
1635   LPMSG pMsg;
1636   HOLEMENU hOleMenu = 0;
1637   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1638   OleMenuHookItem *pHookItem = NULL;
1639   WORD wCode;
1640
1641   TRACE("%i, %04lx, %08lx\n", code, wParam, lParam );
1642
1643   /* Check if we're being asked to process a  messages */
1644   if ( HC_ACTION != code )
1645     goto NEXTHOOK;
1646
1647   /* Retrieve the current message being dispatched from lParam */
1648   pMsg = (LPMSG)lParam;
1649
1650   /* Check if the message is destined for a window we are interested in:
1651    * If the window has an OLEMenu property we may need to dispatch
1652    * the menu message to its active objects window instead. */
1653
1654   hOleMenu = GetPropW( pMsg->hwnd, prop_olemenuW );
1655   if ( !hOleMenu )
1656     goto NEXTHOOK;
1657
1658   /* Process menu messages */
1659   switch( pMsg->message )
1660   {
1661     case WM_COMMAND:
1662     {
1663       wCode = HIWORD(pMsg->wParam);  /* Get notification code */
1664       if ( wCode )
1665         goto NEXTHOOK;  /* Not a menu message */
1666       break;
1667     }
1668     default:
1669       goto NEXTHOOK;
1670   }
1671
1672   /* Get the menu descriptor */
1673   pOleMenuDescriptor = GlobalLock( hOleMenu );
1674   if ( !pOleMenuDescriptor ) /* Bad descriptor! */
1675     goto NEXTHOOK;
1676
1677   /* If the message was for the server dispatch it accordingly */
1678   if ( pOleMenuDescriptor->bIsServerItem )
1679   {
1680     /* Change the hWnd in the message to the active objects hWnd.
1681      * The message loop which reads this message will automatically
1682      * dispatch it to the embedded objects window. */
1683     pMsg->hwnd = pOleMenuDescriptor->hwndActiveObject;
1684   }
1685
1686 NEXTHOOK:
1687   if ( pOleMenuDescriptor )
1688     GlobalUnlock( hOleMenu );
1689
1690   /* Lookup the hook item for the current thread */
1691   if ( !( pHookItem = OLEMenu_IsHookInstalled( GetCurrentThreadId() ) ) )
1692   {
1693     /* This should never fail!! */
1694     WARN("could not retrieve hHook for current thread!\n" );
1695     return FALSE;
1696   }
1697
1698   /* Pass on the message to the next hooker */
1699   return CallNextHookEx( pHookItem->GetMsg_hHook, code, wParam, lParam );
1700 }
1701
1702 /***********************************************************************
1703  * OleCreateMenuDescriptor [OLE32.@]
1704  * Creates an OLE menu descriptor for OLE to use when dispatching
1705  * menu messages and commands.
1706  *
1707  * PARAMS:
1708  *    hmenuCombined  -  Handle to the objects combined menu
1709  *    lpMenuWidths   -  Pointer to array of 6 LONG's indicating menus per group
1710  *
1711  */
1712 HOLEMENU WINAPI OleCreateMenuDescriptor(
1713   HMENU                hmenuCombined,
1714   LPOLEMENUGROUPWIDTHS lpMenuWidths)
1715 {
1716   HOLEMENU hOleMenu;
1717   OleMenuDescriptor *pOleMenuDescriptor;
1718   int i;
1719
1720   if ( !hmenuCombined || !lpMenuWidths )
1721     return 0;
1722
1723   /* Create an OLE menu descriptor */
1724   if ( !(hOleMenu = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT,
1725                                 sizeof(OleMenuDescriptor) ) ) )
1726   return 0;
1727
1728   pOleMenuDescriptor = GlobalLock( hOleMenu );
1729   if ( !pOleMenuDescriptor )
1730     return 0;
1731
1732   /* Initialize menu group widths and hmenu */
1733   for ( i = 0; i < 6; i++ )
1734     pOleMenuDescriptor->mgw.width[i] = lpMenuWidths->width[i];
1735
1736   pOleMenuDescriptor->hmenuCombined = hmenuCombined;
1737   pOleMenuDescriptor->bIsServerItem = FALSE;
1738   GlobalUnlock( hOleMenu );
1739
1740   return hOleMenu;
1741 }
1742
1743 /***********************************************************************
1744  * OleDestroyMenuDescriptor [OLE32.@]
1745  * Destroy the shared menu descriptor
1746  */
1747 HRESULT WINAPI OleDestroyMenuDescriptor(
1748   HOLEMENU hmenuDescriptor)
1749 {
1750   if ( hmenuDescriptor )
1751     GlobalFree( hmenuDescriptor );
1752         return S_OK;
1753 }
1754
1755 /***********************************************************************
1756  * OleSetMenuDescriptor [OLE32.@]
1757  * Installs or removes OLE dispatching code for the containers frame window.
1758  *
1759  * PARAMS
1760  *     hOleMenu         Handle to composite menu descriptor
1761  *     hwndFrame        Handle to containers frame window
1762  *     hwndActiveObject Handle to objects in-place activation window
1763  *     lpFrame          Pointer to IOleInPlaceFrame on containers window
1764  *     lpActiveObject   Pointer to IOleInPlaceActiveObject on active in-place object
1765  *
1766  * RETURNS
1767  *      S_OK                               - menu installed correctly
1768  *      E_FAIL, E_INVALIDARG, E_UNEXPECTED - failure
1769  *
1770  * FIXME
1771  *      The lpFrame and lpActiveObject parameters are currently ignored
1772  *      OLE should install context sensitive help F1 filtering for the app when
1773  *      these are non null.
1774  */
1775 HRESULT WINAPI OleSetMenuDescriptor(
1776   HOLEMENU               hOleMenu,
1777   HWND                   hwndFrame,
1778   HWND                   hwndActiveObject,
1779   LPOLEINPLACEFRAME        lpFrame,
1780   LPOLEINPLACEACTIVEOBJECT lpActiveObject)
1781 {
1782   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1783
1784   /* Check args */
1785   if ( !hwndFrame || (hOleMenu && !hwndActiveObject) )
1786     return E_INVALIDARG;
1787
1788   if ( lpFrame || lpActiveObject )
1789   {
1790      FIXME("(%p, %p, %p, %p, %p), Context sensitive help filtering not implemented!\n",
1791         hOleMenu,
1792         hwndFrame,
1793         hwndActiveObject,
1794         lpFrame,
1795         lpActiveObject);
1796   }
1797
1798   /* Set up a message hook to intercept the containers frame window messages.
1799    * The message filter is responsible for dispatching menu messages from the
1800    * shared menu which are intended for the object.
1801    */
1802
1803   if ( hOleMenu )  /* Want to install dispatching code */
1804   {
1805     /* If OLEMenu hooks are already installed for this thread, fail
1806      * Note: This effectively means that OleSetMenuDescriptor cannot
1807      * be called twice in succession on the same frame window
1808      * without first calling it with a null hOleMenu to uninstall */
1809     if ( OLEMenu_IsHookInstalled( GetCurrentThreadId() ) )
1810   return E_FAIL;
1811
1812     /* Get the menu descriptor */
1813     pOleMenuDescriptor = GlobalLock( hOleMenu );
1814     if ( !pOleMenuDescriptor )
1815       return E_UNEXPECTED;
1816
1817     /* Update the menu descriptor */
1818     pOleMenuDescriptor->hwndFrame = hwndFrame;
1819     pOleMenuDescriptor->hwndActiveObject = hwndActiveObject;
1820
1821     GlobalUnlock( hOleMenu );
1822     pOleMenuDescriptor = NULL;
1823
1824     /* Add a menu descriptor windows property to the frame window */
1825     SetPropW( hwndFrame, prop_olemenuW, hOleMenu );
1826
1827     /* Install thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC */
1828     if ( !OLEMenu_InstallHooks( GetCurrentThreadId() ) )
1829       return E_FAIL;
1830   }
1831   else  /* Want to uninstall dispatching code */
1832   {
1833     /* Uninstall the hooks */
1834     if ( !OLEMenu_UnInstallHooks( GetCurrentThreadId() ) )
1835       return E_FAIL;
1836
1837     /* Remove the menu descriptor property from the frame window */
1838     RemovePropW( hwndFrame, prop_olemenuW );
1839   }
1840
1841   return S_OK;
1842 }
1843
1844 /******************************************************************************
1845  *              IsAccelerator        [OLE32.@]
1846  * Mostly copied from controls/menu.c TranslateAccelerator implementation
1847  */
1848 BOOL WINAPI IsAccelerator(HACCEL hAccel, int cAccelEntries, LPMSG lpMsg, WORD* lpwCmd)
1849 {
1850     LPACCEL lpAccelTbl;
1851     int i;
1852
1853     if(!lpMsg) return FALSE;
1854     if (!hAccel)
1855     {
1856         WARN_(accel)("NULL accel handle\n");
1857         return FALSE;
1858     }
1859     if((lpMsg->message != WM_KEYDOWN &&
1860         lpMsg->message != WM_SYSKEYDOWN &&
1861         lpMsg->message != WM_SYSCHAR &&
1862         lpMsg->message != WM_CHAR)) return FALSE;
1863     lpAccelTbl = HeapAlloc(GetProcessHeap(), 0, cAccelEntries * sizeof(ACCEL));
1864     if (NULL == lpAccelTbl)
1865     {
1866         return FALSE;
1867     }
1868     if (CopyAcceleratorTableW(hAccel, lpAccelTbl, cAccelEntries) != cAccelEntries)
1869     {
1870         WARN_(accel)("CopyAcceleratorTableW failed\n");
1871         HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1872         return FALSE;
1873     }
1874
1875     TRACE_(accel)("hAccel=%p, cAccelEntries=%d,"
1876                 "msg->hwnd=%p, msg->message=%04x, wParam=%08lx, lParam=%08lx\n",
1877                 hAccel, cAccelEntries,
1878                 lpMsg->hwnd, lpMsg->message, lpMsg->wParam, lpMsg->lParam);
1879     for(i = 0; i < cAccelEntries; i++)
1880     {
1881         if(lpAccelTbl[i].key != lpMsg->wParam)
1882             continue;
1883
1884         if(lpMsg->message == WM_CHAR)
1885         {
1886             if(!(lpAccelTbl[i].fVirt & FALT) && !(lpAccelTbl[i].fVirt & FVIRTKEY))
1887             {
1888                 TRACE_(accel)("found accel for WM_CHAR: ('%c')\n", LOWORD(lpMsg->wParam) & 0xff);
1889                 goto found;
1890             }
1891         }
1892         else
1893         {
1894             if(lpAccelTbl[i].fVirt & FVIRTKEY)
1895             {
1896                 INT mask = 0;
1897                 TRACE_(accel)("found accel for virt_key %04lx (scan %04x)\n",
1898                                 lpMsg->wParam, HIWORD(lpMsg->lParam) & 0xff);
1899                 if(GetKeyState(VK_SHIFT) & 0x8000) mask |= FSHIFT;
1900                 if(GetKeyState(VK_CONTROL) & 0x8000) mask |= FCONTROL;
1901                 if(GetKeyState(VK_MENU) & 0x8000) mask |= FALT;
1902                 if(mask == (lpAccelTbl[i].fVirt & (FSHIFT | FCONTROL | FALT))) goto found;
1903                 TRACE_(accel)("incorrect SHIFT/CTRL/ALT-state\n");
1904             }
1905             else
1906             {
1907                 if(!(lpMsg->lParam & 0x01000000))  /* no special_key */
1908                 {
1909                     if((lpAccelTbl[i].fVirt & FALT) && (lpMsg->lParam & 0x20000000))
1910                     {                                                  /* ^^ ALT pressed */
1911                         TRACE_(accel)("found accel for Alt-%c\n", LOWORD(lpMsg->wParam) & 0xff);
1912                         goto found;
1913                     }
1914                 }
1915             }
1916         }
1917     }
1918
1919     WARN_(accel)("couldn't translate accelerator key\n");
1920     HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1921     return FALSE;
1922
1923 found:
1924     if(lpwCmd) *lpwCmd = lpAccelTbl[i].cmd;
1925     HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1926     return TRUE;
1927 }
1928
1929 /***********************************************************************
1930  * ReleaseStgMedium [OLE32.@]
1931  */
1932 void WINAPI ReleaseStgMedium(
1933   STGMEDIUM* pmedium)
1934 {
1935   switch (pmedium->tymed)
1936   {
1937     case TYMED_HGLOBAL:
1938     {
1939       if ( (pmedium->pUnkForRelease==0) &&
1940            (pmedium->u.hGlobal!=0) )
1941         GlobalFree(pmedium->u.hGlobal);
1942       break;
1943     }
1944     case TYMED_FILE:
1945     {
1946       if (pmedium->u.lpszFileName!=0)
1947       {
1948         if (pmedium->pUnkForRelease==0)
1949         {
1950           DeleteFileW(pmedium->u.lpszFileName);
1951         }
1952
1953         CoTaskMemFree(pmedium->u.lpszFileName);
1954       }
1955       break;
1956     }
1957     case TYMED_ISTREAM:
1958     {
1959       if (pmedium->u.pstm!=0)
1960       {
1961         IStream_Release(pmedium->u.pstm);
1962       }
1963       break;
1964     }
1965     case TYMED_ISTORAGE:
1966     {
1967       if (pmedium->u.pstg!=0)
1968       {
1969         IStorage_Release(pmedium->u.pstg);
1970       }
1971       break;
1972     }
1973     case TYMED_GDI:
1974     {
1975       if ( (pmedium->pUnkForRelease==0) &&
1976            (pmedium->u.hBitmap!=0) )
1977         DeleteObject(pmedium->u.hBitmap);
1978       break;
1979     }
1980     case TYMED_MFPICT:
1981     {
1982       if ( (pmedium->pUnkForRelease==0) &&
1983            (pmedium->u.hMetaFilePict!=0) )
1984       {
1985         LPMETAFILEPICT pMP = GlobalLock(pmedium->u.hMetaFilePict);
1986         DeleteMetaFile(pMP->hMF);
1987         GlobalUnlock(pmedium->u.hMetaFilePict);
1988         GlobalFree(pmedium->u.hMetaFilePict);
1989       }
1990       break;
1991     }
1992     case TYMED_ENHMF:
1993     {
1994       if ( (pmedium->pUnkForRelease==0) &&
1995            (pmedium->u.hEnhMetaFile!=0) )
1996       {
1997         DeleteEnhMetaFile(pmedium->u.hEnhMetaFile);
1998       }
1999       break;
2000     }
2001     case TYMED_NULL:
2002     default:
2003       break;
2004   }
2005   pmedium->tymed=TYMED_NULL;
2006
2007   /*
2008    * After cleaning up, the unknown is released
2009    */
2010   if (pmedium->pUnkForRelease!=0)
2011   {
2012     IUnknown_Release(pmedium->pUnkForRelease);
2013     pmedium->pUnkForRelease = 0;
2014   }
2015 }
2016
2017 /***
2018  * OLEDD_Initialize()
2019  *
2020  * Initializes the OLE drag and drop data structures.
2021  */
2022 static void OLEDD_Initialize(void)
2023 {
2024     WNDCLASSW wndClass;
2025
2026     ZeroMemory (&wndClass, sizeof(WNDCLASSW));
2027     wndClass.style         = CS_GLOBALCLASS;
2028     wndClass.lpfnWndProc   = OLEDD_DragTrackerWindowProc;
2029     wndClass.cbClsExtra    = 0;
2030     wndClass.cbWndExtra    = sizeof(TrackerWindowInfo*);
2031     wndClass.hCursor       = 0;
2032     wndClass.hbrBackground = 0;
2033     wndClass.lpszClassName = OLEDD_DRAGTRACKERCLASS;
2034
2035     RegisterClassW (&wndClass);
2036 }
2037
2038 /***
2039  * OLEDD_DragTrackerWindowProc()
2040  *
2041  * This method is the WindowProcedure of the drag n drop tracking
2042  * window. During a drag n Drop operation, an invisible window is created
2043  * to receive the user input and act upon it. This procedure is in charge
2044  * of this behavior.
2045  */
2046
2047 #define DRAG_TIMER_ID 1
2048
2049 static LRESULT WINAPI OLEDD_DragTrackerWindowProc(
2050                          HWND   hwnd,
2051                          UINT   uMsg,
2052                          WPARAM wParam,
2053                          LPARAM   lParam)
2054 {
2055   switch (uMsg)
2056   {
2057     case WM_CREATE:
2058     {
2059       LPCREATESTRUCTA createStruct = (LPCREATESTRUCTA)lParam;
2060
2061       SetWindowLongPtrW(hwnd, 0, (LONG_PTR)createStruct->lpCreateParams);
2062       SetTimer(hwnd, DRAG_TIMER_ID, 50, NULL);
2063
2064       break;
2065     }
2066     case WM_TIMER:
2067     case WM_MOUSEMOVE:
2068     {
2069       OLEDD_TrackMouseMove((TrackerWindowInfo*)GetWindowLongPtrA(hwnd, 0));
2070       break;
2071     }
2072     case WM_LBUTTONUP:
2073     case WM_MBUTTONUP:
2074     case WM_RBUTTONUP:
2075     case WM_LBUTTONDOWN:
2076     case WM_MBUTTONDOWN:
2077     case WM_RBUTTONDOWN:
2078     {
2079       OLEDD_TrackStateChange((TrackerWindowInfo*)GetWindowLongPtrA(hwnd, 0));
2080       break;
2081     }
2082     case WM_DESTROY:
2083     {
2084       KillTimer(hwnd, DRAG_TIMER_ID);
2085       break;
2086     }
2087   }
2088
2089   /*
2090    * This is a window proc after all. Let's call the default.
2091    */
2092   return DefWindowProcW (hwnd, uMsg, wParam, lParam);
2093 }
2094
2095 /***
2096  * OLEDD_TrackMouseMove()
2097  *
2098  * This method is invoked while a drag and drop operation is in effect.
2099  * it will generate the appropriate callbacks in the drop source
2100  * and drop target. It will also provide the expected feedback to
2101  * the user.
2102  *
2103  * params:
2104  *    trackerInfo - Pointer to the structure identifying the
2105  *                  drag & drop operation that is currently
2106  *                  active.
2107  */
2108 static void OLEDD_TrackMouseMove(TrackerWindowInfo* trackerInfo)
2109 {
2110   HWND   hwndNewTarget = 0;
2111   HRESULT  hr = S_OK;
2112   POINT pt;
2113
2114   /*
2115    * Get the handle of the window under the mouse
2116    */
2117   pt.x = trackerInfo->curMousePos.x;
2118   pt.y = trackerInfo->curMousePos.y;
2119   hwndNewTarget = WindowFromPoint(pt);
2120
2121   /*
2122    * Every time, we re-initialize the effects passed to the
2123    * IDropTarget to the effects allowed by the source.
2124    */
2125   *trackerInfo->pdwEffect = trackerInfo->dwOKEffect;
2126
2127   /*
2128    * If we are hovering over the same target as before, send the
2129    * DragOver notification
2130    */
2131   if ( (trackerInfo->curDragTarget != 0) &&
2132        (trackerInfo->curTargetHWND == hwndNewTarget) )
2133   {
2134     IDropTarget_DragOver(trackerInfo->curDragTarget,
2135                          trackerInfo->dwKeyState,
2136                          trackerInfo->curMousePos,
2137                          trackerInfo->pdwEffect);
2138   }
2139   else
2140   {
2141     /*
2142      * If we changed window, we have to notify our old target and check for
2143      * the new one.
2144      */
2145     if (trackerInfo->curDragTarget)
2146       IDropTarget_DragLeave(trackerInfo->curDragTarget);
2147
2148     /*
2149      * Make sure we're hovering over a window.
2150      */
2151     if (hwndNewTarget)
2152     {
2153       /*
2154        * Find-out if there is a drag target under the mouse
2155        */
2156       HWND next_target_wnd = hwndNewTarget;
2157
2158       trackerInfo->curTargetHWND = hwndNewTarget;
2159
2160       while (next_target_wnd && !is_droptarget(next_target_wnd))
2161           next_target_wnd = GetParent(next_target_wnd);
2162
2163       if (next_target_wnd) hwndNewTarget = next_target_wnd;
2164
2165       trackerInfo->curDragTargetHWND = hwndNewTarget;
2166       if(trackerInfo->curDragTarget) IDropTarget_Release(trackerInfo->curDragTarget);
2167       trackerInfo->curDragTarget     = get_droptarget_pointer(hwndNewTarget);
2168
2169       /*
2170        * If there is, notify it that we just dragged-in
2171        */
2172       if (trackerInfo->curDragTarget)
2173       {
2174         hr = IDropTarget_DragEnter(trackerInfo->curDragTarget,
2175                                    trackerInfo->dataObject,
2176                                    trackerInfo->dwKeyState,
2177                                    trackerInfo->curMousePos,
2178                                    trackerInfo->pdwEffect);
2179
2180         /* failed DragEnter() means invalid target */
2181         if (hr != S_OK)
2182         {
2183           trackerInfo->curDragTargetHWND = 0;
2184           trackerInfo->curTargetHWND     = 0;
2185           IDropTarget_Release(trackerInfo->curDragTarget);
2186           trackerInfo->curDragTarget     = 0;
2187         }
2188       }
2189     }
2190     else
2191     {
2192       /*
2193        * The mouse is not over a window so we don't track anything.
2194        */
2195       trackerInfo->curDragTargetHWND = 0;
2196       trackerInfo->curTargetHWND     = 0;
2197       if(trackerInfo->curDragTarget) IDropTarget_Release(trackerInfo->curDragTarget);
2198       trackerInfo->curDragTarget     = 0;
2199     }
2200   }
2201
2202   /*
2203    * Now that we have done that, we have to tell the source to give
2204    * us feedback on the work being done by the target.  If we don't
2205    * have a target, simulate no effect.
2206    */
2207   if (trackerInfo->curDragTarget==0)
2208   {
2209     *trackerInfo->pdwEffect = DROPEFFECT_NONE;
2210   }
2211
2212   hr = IDropSource_GiveFeedback(trackerInfo->dropSource,
2213                                 *trackerInfo->pdwEffect);
2214
2215   /*
2216    * When we ask for feedback from the drop source, sometimes it will
2217    * do all the necessary work and sometimes it will not handle it
2218    * when that's the case, we must display the standard drag and drop
2219    * cursors.
2220    */
2221   if (hr == DRAGDROP_S_USEDEFAULTCURSORS)
2222   {
2223     HCURSOR hCur;
2224
2225     if (*trackerInfo->pdwEffect & DROPEFFECT_MOVE)
2226     {
2227       hCur = LoadCursorW(hProxyDll, MAKEINTRESOURCEW(1));
2228     }
2229     else if (*trackerInfo->pdwEffect & DROPEFFECT_COPY)
2230     {
2231       hCur = LoadCursorW(hProxyDll, MAKEINTRESOURCEW(2));
2232     }
2233     else if (*trackerInfo->pdwEffect & DROPEFFECT_LINK)
2234     {
2235       hCur = LoadCursorW(hProxyDll, MAKEINTRESOURCEW(3));
2236     }
2237     else
2238     {
2239       hCur = LoadCursorW(hProxyDll, MAKEINTRESOURCEW(0));
2240     }
2241
2242     SetCursor(hCur);
2243   }
2244 }
2245
2246 /***
2247  * OLEDD_TrackStateChange()
2248  *
2249  * This method is invoked while a drag and drop operation is in effect.
2250  * It is used to notify the drop target/drop source callbacks when
2251  * the state of the keyboard or mouse button change.
2252  *
2253  * params:
2254  *    trackerInfo - Pointer to the structure identifying the
2255  *                  drag & drop operation that is currently
2256  *                  active.
2257  */
2258 static void OLEDD_TrackStateChange(TrackerWindowInfo* trackerInfo)
2259 {
2260   /*
2261    * Ask the drop source what to do with the operation.
2262    */
2263   trackerInfo->returnValue = IDropSource_QueryContinueDrag(
2264                                trackerInfo->dropSource,
2265                                trackerInfo->escPressed,
2266                                trackerInfo->dwKeyState);
2267
2268   /*
2269    * All the return valued will stop the operation except the S_OK
2270    * return value.
2271    */
2272   if (trackerInfo->returnValue!=S_OK)
2273   {
2274     /*
2275      * Make sure the message loop in DoDragDrop stops
2276      */
2277     trackerInfo->trackingDone = TRUE;
2278
2279     /*
2280      * Release the mouse in case the drop target decides to show a popup
2281      * or a menu or something.
2282      */
2283     ReleaseCapture();
2284
2285     /*
2286      * If we end-up over a target, drop the object in the target or
2287      * inform the target that the operation was cancelled.
2288      */
2289     if (trackerInfo->curDragTarget)
2290     {
2291       switch (trackerInfo->returnValue)
2292       {
2293         /*
2294          * If the source wants us to complete the operation, we tell
2295          * the drop target that we just dropped the object in it.
2296          */
2297         case DRAGDROP_S_DROP:
2298           if (*trackerInfo->pdwEffect != DROPEFFECT_NONE)
2299             IDropTarget_Drop(trackerInfo->curDragTarget,
2300                              trackerInfo->dataObject,
2301                              trackerInfo->dwKeyState,
2302                              trackerInfo->curMousePos,
2303                              trackerInfo->pdwEffect);
2304           else
2305             IDropTarget_DragLeave(trackerInfo->curDragTarget);
2306           break;
2307
2308         /*
2309          * If the source told us that we should cancel, fool the drop
2310          * target by telling it that the mouse left it's window.
2311          * Also set the drop effect to "NONE" in case the application
2312          * ignores the result of DoDragDrop.
2313          */
2314         case DRAGDROP_S_CANCEL:
2315           IDropTarget_DragLeave(trackerInfo->curDragTarget);
2316           *trackerInfo->pdwEffect = DROPEFFECT_NONE;
2317           break;
2318       }
2319     }
2320   }
2321 }
2322
2323 /***
2324  * OLEDD_GetButtonState()
2325  *
2326  * This method will use the current state of the keyboard to build
2327  * a button state mask equivalent to the one passed in the
2328  * WM_MOUSEMOVE wParam.
2329  */
2330 static DWORD OLEDD_GetButtonState(void)
2331 {
2332   BYTE  keyboardState[256];
2333   DWORD keyMask = 0;
2334
2335   GetKeyboardState(keyboardState);
2336
2337   if ( (keyboardState[VK_SHIFT] & 0x80) !=0)
2338     keyMask |= MK_SHIFT;
2339
2340   if ( (keyboardState[VK_CONTROL] & 0x80) !=0)
2341     keyMask |= MK_CONTROL;
2342
2343   if ( (keyboardState[VK_LBUTTON] & 0x80) !=0)
2344     keyMask |= MK_LBUTTON;
2345
2346   if ( (keyboardState[VK_RBUTTON] & 0x80) !=0)
2347     keyMask |= MK_RBUTTON;
2348
2349   if ( (keyboardState[VK_MBUTTON] & 0x80) !=0)
2350     keyMask |= MK_MBUTTON;
2351
2352   return keyMask;
2353 }
2354
2355 /***
2356  * OLEDD_GetButtonState()
2357  *
2358  * This method will read the default value of the registry key in
2359  * parameter and extract a DWORD value from it. The registry key value
2360  * can be in a string key or a DWORD key.
2361  *
2362  * params:
2363  *     regKey   - Key to read the default value from
2364  *     pdwValue - Pointer to the location where the DWORD
2365  *                value is returned. This value is not modified
2366  *                if the value is not found.
2367  */
2368
2369 static void OLEUTL_ReadRegistryDWORDValue(
2370   HKEY   regKey,
2371   DWORD* pdwValue)
2372 {
2373   WCHAR buffer[20];
2374   DWORD cbData = sizeof(buffer);
2375   DWORD dwKeyType;
2376   LONG  lres;
2377
2378   lres = RegQueryValueExW(regKey,
2379                           emptyW,
2380                           NULL,
2381                           &dwKeyType,
2382                           (LPBYTE)buffer,
2383                           &cbData);
2384
2385   if (lres==ERROR_SUCCESS)
2386   {
2387     switch (dwKeyType)
2388     {
2389       case REG_DWORD:
2390         *pdwValue = *(DWORD*)buffer;
2391         break;
2392       case REG_EXPAND_SZ:
2393       case REG_MULTI_SZ:
2394       case REG_SZ:
2395         *pdwValue = (DWORD)strtoulW(buffer, NULL, 10);
2396         break;
2397     }
2398   }
2399 }
2400
2401 /******************************************************************************
2402  * OleDraw (OLE32.@)
2403  *
2404  * The operation of this function is documented literally in the WinAPI
2405  * documentation to involve a QueryInterface for the IViewObject interface,
2406  * followed by a call to IViewObject::Draw.
2407  */
2408 HRESULT WINAPI OleDraw(
2409         IUnknown *pUnk,
2410         DWORD dwAspect,
2411         HDC hdcDraw,
2412         LPCRECT lprcBounds)
2413 {
2414   HRESULT hres;
2415   IViewObject *viewobject;
2416
2417   hres = IUnknown_QueryInterface(pUnk,
2418                                  &IID_IViewObject,
2419                                  (void**)&viewobject);
2420
2421   if (SUCCEEDED(hres))
2422   {
2423     RECTL rectl;
2424
2425     rectl.left = lprcBounds->left;
2426     rectl.right = lprcBounds->right;
2427     rectl.top = lprcBounds->top;
2428     rectl.bottom = lprcBounds->bottom;
2429     hres = IViewObject_Draw(viewobject, dwAspect, -1, 0, 0, 0, hdcDraw, &rectl, 0, 0, 0);
2430
2431     IViewObject_Release(viewobject);
2432     return hres;
2433   }
2434   else
2435   {
2436     return DV_E_NOIVIEWOBJECT;
2437   }
2438 }
2439
2440 /***********************************************************************
2441  *             OleTranslateAccelerator [OLE32.@]
2442  */
2443 HRESULT WINAPI OleTranslateAccelerator (LPOLEINPLACEFRAME lpFrame,
2444                    LPOLEINPLACEFRAMEINFO lpFrameInfo, LPMSG lpmsg)
2445 {
2446     WORD wID;
2447
2448     TRACE("(%p,%p,%p)\n", lpFrame, lpFrameInfo, lpmsg);
2449
2450     if (IsAccelerator(lpFrameInfo->haccel,lpFrameInfo->cAccelEntries,lpmsg,&wID))
2451         return IOleInPlaceFrame_TranslateAccelerator(lpFrame,lpmsg,wID);
2452
2453     return S_FALSE;
2454 }
2455
2456 /******************************************************************************
2457  *              OleCreate        [OLE32.@]
2458  *
2459  */
2460 HRESULT WINAPI OleCreate(
2461         REFCLSID rclsid,
2462         REFIID riid,
2463         DWORD renderopt,
2464         LPFORMATETC pFormatEtc,
2465         LPOLECLIENTSITE pClientSite,
2466         LPSTORAGE pStg,
2467         LPVOID* ppvObj)
2468 {
2469     HRESULT hres;
2470     IUnknown * pUnk = NULL;
2471     IOleObject *pOleObject = NULL;
2472
2473     TRACE("(%s, %s, %d, %p, %p, %p, %p)\n", debugstr_guid(rclsid),
2474         debugstr_guid(riid), renderopt, pFormatEtc, pClientSite, pStg, ppvObj);
2475
2476     hres = CoCreateInstance(rclsid, 0, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER, riid, (LPVOID*)&pUnk);
2477
2478     if (SUCCEEDED(hres))
2479         hres = IStorage_SetClass(pStg, rclsid);
2480
2481     if (pClientSite && SUCCEEDED(hres))
2482     {
2483         hres = IUnknown_QueryInterface(pUnk, &IID_IOleObject, (LPVOID*)&pOleObject);
2484         if (SUCCEEDED(hres))
2485         {
2486             DWORD dwStatus;
2487             hres = IOleObject_GetMiscStatus(pOleObject, DVASPECT_CONTENT, &dwStatus);
2488         }
2489     }
2490
2491     if (SUCCEEDED(hres))
2492     {
2493         IPersistStorage * pPS;
2494         if (SUCCEEDED((hres = IUnknown_QueryInterface(pUnk, &IID_IPersistStorage, (LPVOID*)&pPS))))
2495         {
2496             TRACE("trying to set stg %p\n", pStg);
2497             hres = IPersistStorage_InitNew(pPS, pStg);
2498             TRACE("-- result 0x%08x\n", hres);
2499             IPersistStorage_Release(pPS);
2500         }
2501     }
2502
2503     if (pClientSite && SUCCEEDED(hres))
2504     {
2505         TRACE("trying to set clientsite %p\n", pClientSite);
2506         hres = IOleObject_SetClientSite(pOleObject, pClientSite);
2507         TRACE("-- result 0x%08x\n", hres);
2508     }
2509
2510     if (pOleObject)
2511         IOleObject_Release(pOleObject);
2512
2513     if (((renderopt == OLERENDER_DRAW) || (renderopt == OLERENDER_FORMAT)) &&
2514         SUCCEEDED(hres))
2515     {
2516         IRunnableObject *pRunnable;
2517         IOleCache *pOleCache;
2518         HRESULT hres2;
2519
2520         hres2 = IUnknown_QueryInterface(pUnk, &IID_IRunnableObject, (void **)&pRunnable);
2521         if (SUCCEEDED(hres2))
2522         {
2523             hres = IRunnableObject_Run(pRunnable, NULL);
2524             IRunnableObject_Release(pRunnable);
2525         }
2526
2527         if (SUCCEEDED(hres))
2528         {
2529             hres2 = IUnknown_QueryInterface(pUnk, &IID_IOleCache, (void **)&pOleCache);
2530             if (SUCCEEDED(hres2))
2531             {
2532                 DWORD dwConnection;
2533                 if (renderopt == OLERENDER_DRAW && !pFormatEtc) {
2534                     FORMATETC pfe;
2535                     pfe.cfFormat = 0;
2536                     pfe.ptd = NULL;
2537                     pfe.dwAspect = DVASPECT_CONTENT;
2538                     pfe.lindex = -1;
2539                     pfe.tymed = TYMED_NULL;
2540                     hres = IOleCache_Cache(pOleCache, &pfe, ADVF_PRIMEFIRST, &dwConnection);
2541                 }
2542                 else
2543                     hres = IOleCache_Cache(pOleCache, pFormatEtc, ADVF_PRIMEFIRST, &dwConnection);
2544                 IOleCache_Release(pOleCache);
2545             }
2546         }
2547     }
2548
2549     if (FAILED(hres) && pUnk)
2550     {
2551         IUnknown_Release(pUnk);
2552         pUnk = NULL;
2553     }
2554
2555     *ppvObj = pUnk;
2556
2557     TRACE("-- %p\n", pUnk);
2558     return hres;
2559 }
2560
2561 /******************************************************************************
2562  *              OleGetAutoConvert        [OLE32.@]
2563  */
2564 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
2565 {
2566     static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2567     HKEY hkey = NULL;
2568     WCHAR buf[CHARS_IN_GUID];
2569     LONG len;
2570     HRESULT res = S_OK;
2571
2572     res = COM_OpenKeyForCLSID(clsidOld, wszAutoConvertTo, KEY_READ, &hkey);
2573     if (FAILED(res))
2574         goto done;
2575
2576     len = sizeof(buf);
2577     if (RegQueryValueW(hkey, NULL, buf, &len))
2578     {
2579         res = REGDB_E_KEYMISSING;
2580         goto done;
2581     }
2582     res = CLSIDFromString(buf, pClsidNew);
2583 done:
2584     if (hkey) RegCloseKey(hkey);
2585     return res;
2586 }
2587
2588 /******************************************************************************
2589  *              OleSetAutoConvert        [OLE32.@]
2590  */
2591 HRESULT WINAPI OleSetAutoConvert(REFCLSID clsidOld, REFCLSID clsidNew)
2592 {
2593     static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2594     HKEY hkey = NULL;
2595     WCHAR szClsidNew[CHARS_IN_GUID];
2596     HRESULT res = S_OK;
2597
2598     TRACE("(%s,%s)\n", debugstr_guid(clsidOld), debugstr_guid(clsidNew));
2599     
2600     res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2601     if (FAILED(res))
2602         goto done;
2603     StringFromGUID2(clsidNew, szClsidNew, CHARS_IN_GUID);
2604     if (RegSetValueW(hkey, wszAutoConvertTo, REG_SZ, szClsidNew, (strlenW(szClsidNew)+1) * sizeof(WCHAR)))
2605     {
2606         res = REGDB_E_WRITEREGDB;
2607         goto done;
2608     }
2609
2610 done:
2611     if (hkey) RegCloseKey(hkey);
2612     return res;
2613 }
2614
2615 /******************************************************************************
2616  *              OleDoAutoConvert        [OLE32.@]
2617  */
2618 HRESULT WINAPI OleDoAutoConvert(LPSTORAGE pStg, LPCLSID pClsidNew)
2619 {
2620     FIXME("(%p,%p) : stub\n",pStg,pClsidNew);
2621     return E_NOTIMPL;
2622 }
2623
2624 /******************************************************************************
2625  *              OleIsRunning        [OLE32.@]
2626  */
2627 BOOL WINAPI OleIsRunning(LPOLEOBJECT pObject)
2628 {
2629     IRunnableObject *pRunnable;
2630     HRESULT hr;
2631     BOOL running;
2632
2633     TRACE("(%p)\n", pObject);
2634
2635     hr = IOleObject_QueryInterface(pObject, &IID_IRunnableObject, (void **)&pRunnable);
2636     if (FAILED(hr))
2637         return TRUE;
2638     running = IRunnableObject_IsRunning(pRunnable);
2639     IRunnableObject_Release(pRunnable);
2640     return running;
2641 }
2642
2643 /***********************************************************************
2644  *           OleNoteObjectVisible                           [OLE32.@]
2645  */
2646 HRESULT WINAPI OleNoteObjectVisible(LPUNKNOWN pUnknown, BOOL bVisible)
2647 {
2648     TRACE("(%p, %s)\n", pUnknown, bVisible ? "TRUE" : "FALSE");
2649     return CoLockObjectExternal(pUnknown, bVisible, TRUE);
2650 }
2651
2652
2653 /***********************************************************************
2654  *           OLE_FreeClipDataArray   [internal]
2655  *
2656  * NOTES:
2657  *  frees the data associated with an array of CLIPDATAs
2658  */
2659 static void OLE_FreeClipDataArray(ULONG count, CLIPDATA * pClipDataArray)
2660 {
2661     ULONG i;
2662     for (i = 0; i < count; i++)
2663         if (pClipDataArray[i].pClipData)
2664             CoTaskMemFree(pClipDataArray[i].pClipData);
2665 }
2666
2667 /***********************************************************************
2668  *           PropSysAllocString                     [OLE32.@]
2669  * NOTES:
2670  *  Basically a copy of SysAllocStringLen.
2671  */
2672 BSTR WINAPI PropSysAllocString(LPCOLESTR str)
2673 {
2674     DWORD  bufferSize;
2675     DWORD* newBuffer;
2676     WCHAR* stringBuffer;
2677     int len;
2678
2679     if (!str) return 0;
2680
2681     len = lstrlenW(str);
2682     /*
2683      * Find the length of the buffer passed-in, in bytes.
2684      */
2685     bufferSize = len * sizeof (WCHAR);
2686
2687     /*
2688      * Allocate a new buffer to hold the string.
2689      * Don't forget to keep an empty spot at the beginning of the
2690      * buffer for the character count and an extra character at the
2691      * end for the NULL.
2692      */
2693     newBuffer = HeapAlloc(GetProcessHeap(), 0,
2694                           bufferSize + sizeof(WCHAR) + sizeof(DWORD));
2695
2696     /*
2697      * If the memory allocation failed, return a null pointer.
2698      */
2699     if (newBuffer==0)
2700       return 0;
2701
2702     /*
2703      * Copy the length of the string in the placeholder.
2704      */
2705     *newBuffer = bufferSize;
2706
2707     /*
2708      * Skip the byte count.
2709      */
2710     newBuffer++;
2711
2712     memcpy(newBuffer, str, bufferSize);
2713
2714     /*
2715      * Make sure that there is a nul character at the end of the
2716      * string.
2717      */
2718     stringBuffer = (WCHAR*)newBuffer;
2719     stringBuffer[len] = '\0';
2720
2721     return stringBuffer;
2722 }
2723
2724 /***********************************************************************
2725  *           PropSysFreeString                      [OLE32.@]
2726  * NOTES
2727  *  Copy of SysFreeString.
2728  */
2729 void WINAPI PropSysFreeString(LPOLESTR str)
2730 {
2731     DWORD* bufferPointer;
2732
2733     /* NULL is a valid parameter */
2734     if(!str) return;
2735
2736     /*
2737      * We have to be careful when we free a BSTR pointer, it points to
2738      * the beginning of the string but it skips the byte count contained
2739      * before the string.
2740      */
2741     bufferPointer = (DWORD*)str;
2742
2743     bufferPointer--;
2744
2745     /*
2746      * Free the memory from its "real" origin.
2747      */
2748     HeapFree(GetProcessHeap(), 0, bufferPointer);
2749 }
2750
2751 /******************************************************************************
2752  * Check if a PROPVARIANT's type is valid.
2753  */
2754 static inline HRESULT PROPVARIANT_ValidateType(VARTYPE vt)
2755 {
2756     switch (vt)
2757     {
2758     case VT_EMPTY:
2759     case VT_NULL:
2760     case VT_I2:
2761     case VT_I4:
2762     case VT_R4:
2763     case VT_R8:
2764     case VT_CY:
2765     case VT_DATE:
2766     case VT_BSTR:
2767     case VT_ERROR:
2768     case VT_BOOL:
2769     case VT_DECIMAL:
2770     case VT_UI1:
2771     case VT_UI2:
2772     case VT_UI4:
2773     case VT_I8:
2774     case VT_UI8:
2775     case VT_LPSTR:
2776     case VT_LPWSTR:
2777     case VT_FILETIME:
2778     case VT_BLOB:
2779     case VT_STREAM:
2780     case VT_STORAGE:
2781     case VT_STREAMED_OBJECT:
2782     case VT_STORED_OBJECT:
2783     case VT_BLOB_OBJECT:
2784     case VT_CF:
2785     case VT_CLSID:
2786     case VT_I2|VT_VECTOR:
2787     case VT_I4|VT_VECTOR:
2788     case VT_R4|VT_VECTOR:
2789     case VT_R8|VT_VECTOR:
2790     case VT_CY|VT_VECTOR:
2791     case VT_DATE|VT_VECTOR:
2792     case VT_BSTR|VT_VECTOR:
2793     case VT_ERROR|VT_VECTOR:
2794     case VT_BOOL|VT_VECTOR:
2795     case VT_VARIANT|VT_VECTOR:
2796     case VT_UI1|VT_VECTOR:
2797     case VT_UI2|VT_VECTOR:
2798     case VT_UI4|VT_VECTOR:
2799     case VT_I8|VT_VECTOR:
2800     case VT_UI8|VT_VECTOR:
2801     case VT_LPSTR|VT_VECTOR:
2802     case VT_LPWSTR|VT_VECTOR:
2803     case VT_FILETIME|VT_VECTOR:
2804     case VT_CF|VT_VECTOR:
2805     case VT_CLSID|VT_VECTOR:
2806         return S_OK;
2807     }
2808     WARN("Bad type %d\n", vt);
2809     return STG_E_INVALIDPARAMETER;
2810 }
2811
2812 /***********************************************************************
2813  *           PropVariantClear                       [OLE32.@]
2814  */
2815 HRESULT WINAPI PropVariantClear(PROPVARIANT * pvar) /* [in/out] */
2816 {
2817     HRESULT hr;
2818
2819     TRACE("(%p)\n", pvar);
2820
2821     if (!pvar)
2822         return S_OK;
2823
2824     hr = PROPVARIANT_ValidateType(pvar->vt);
2825     if (FAILED(hr))
2826         return hr;
2827
2828     switch(pvar->vt)
2829     {
2830     case VT_EMPTY:
2831     case VT_NULL:
2832     case VT_I2:
2833     case VT_I4:
2834     case VT_R4:
2835     case VT_R8:
2836     case VT_CY:
2837     case VT_DATE:
2838     case VT_ERROR:
2839     case VT_BOOL:
2840     case VT_DECIMAL:
2841     case VT_UI1:
2842     case VT_UI2:
2843     case VT_UI4:
2844     case VT_I8:
2845     case VT_UI8:
2846     case VT_FILETIME:
2847         break;
2848     case VT_STREAM:
2849     case VT_STREAMED_OBJECT:
2850     case VT_STORAGE:
2851     case VT_STORED_OBJECT:
2852         if (pvar->u.pStream)
2853             IUnknown_Release(pvar->u.pStream);
2854         break;
2855     case VT_CLSID:
2856     case VT_LPSTR:
2857     case VT_LPWSTR:
2858         /* pick an arbitrary typed pointer - we don't care about the type
2859          * as we are just freeing it */
2860         CoTaskMemFree(pvar->u.puuid);
2861         break;
2862     case VT_BLOB:
2863     case VT_BLOB_OBJECT:
2864         CoTaskMemFree(pvar->u.blob.pBlobData);
2865         break;
2866     case VT_BSTR:
2867         if (pvar->u.bstrVal)
2868             PropSysFreeString(pvar->u.bstrVal);
2869         break;
2870     case VT_CF:
2871         if (pvar->u.pclipdata)
2872         {
2873             OLE_FreeClipDataArray(1, pvar->u.pclipdata);
2874             CoTaskMemFree(pvar->u.pclipdata);
2875         }
2876         break;
2877     default:
2878         if (pvar->vt & VT_VECTOR)
2879         {
2880             ULONG i;
2881
2882             switch (pvar->vt & ~VT_VECTOR)
2883             {
2884             case VT_VARIANT:
2885                 FreePropVariantArray(pvar->u.capropvar.cElems, pvar->u.capropvar.pElems);
2886                 break;
2887             case VT_CF:
2888                 OLE_FreeClipDataArray(pvar->u.caclipdata.cElems, pvar->u.caclipdata.pElems);
2889                 break;
2890             case VT_BSTR:
2891                 for (i = 0; i < pvar->u.cabstr.cElems; i++)
2892                     PropSysFreeString(pvar->u.cabstr.pElems[i]);
2893                 break;
2894             case VT_LPSTR:
2895                 for (i = 0; i < pvar->u.calpstr.cElems; i++)
2896                     CoTaskMemFree(pvar->u.calpstr.pElems[i]);
2897                 break;
2898             case VT_LPWSTR:
2899                 for (i = 0; i < pvar->u.calpwstr.cElems; i++)
2900                     CoTaskMemFree(pvar->u.calpwstr.pElems[i]);
2901                 break;
2902             }
2903             if (pvar->vt & ~VT_VECTOR)
2904             {
2905                 /* pick an arbitrary VT_VECTOR structure - they all have the same
2906                  * memory layout */
2907                 CoTaskMemFree(pvar->u.capropvar.pElems);
2908             }
2909         }
2910         else
2911             WARN("Invalid/unsupported type %d\n", pvar->vt);
2912     }
2913
2914     ZeroMemory(pvar, sizeof(*pvar));
2915
2916     return S_OK;
2917 }
2918
2919 /***********************************************************************
2920  *           PropVariantCopy                        [OLE32.@]
2921  */
2922 HRESULT WINAPI PropVariantCopy(PROPVARIANT *pvarDest,      /* [out] */
2923                                const PROPVARIANT *pvarSrc) /* [in] */
2924 {
2925     ULONG len;
2926     HRESULT hr;
2927
2928     TRACE("(%p, %p vt %04x)\n", pvarDest, pvarSrc, pvarSrc->vt);
2929
2930     hr = PROPVARIANT_ValidateType(pvarSrc->vt);
2931     if (FAILED(hr))
2932         return hr;
2933
2934     /* this will deal with most cases */
2935     *pvarDest = *pvarSrc;
2936
2937     switch(pvarSrc->vt)
2938     {
2939     case VT_EMPTY:
2940     case VT_NULL:
2941     case VT_I1:
2942     case VT_UI1:
2943     case VT_I2:
2944     case VT_UI2:
2945     case VT_BOOL:
2946     case VT_DECIMAL:
2947     case VT_I4:
2948     case VT_UI4:
2949     case VT_R4:
2950     case VT_ERROR:
2951     case VT_I8:
2952     case VT_UI8:
2953     case VT_R8:
2954     case VT_CY:
2955     case VT_DATE:
2956     case VT_FILETIME:
2957         break;
2958     case VT_STREAM:
2959     case VT_STREAMED_OBJECT:
2960     case VT_STORAGE:
2961     case VT_STORED_OBJECT:
2962         IUnknown_AddRef((LPUNKNOWN)pvarDest->u.pStream);
2963         break;
2964     case VT_CLSID:
2965         pvarDest->u.puuid = CoTaskMemAlloc(sizeof(CLSID));
2966         *pvarDest->u.puuid = *pvarSrc->u.puuid;
2967         break;
2968     case VT_LPSTR:
2969         len = strlen(pvarSrc->u.pszVal);
2970         pvarDest->u.pszVal = CoTaskMemAlloc((len+1)*sizeof(CHAR));
2971         CopyMemory(pvarDest->u.pszVal, pvarSrc->u.pszVal, (len+1)*sizeof(CHAR));
2972         break;
2973     case VT_LPWSTR:
2974         len = lstrlenW(pvarSrc->u.pwszVal);
2975         pvarDest->u.pwszVal = CoTaskMemAlloc((len+1)*sizeof(WCHAR));
2976         CopyMemory(pvarDest->u.pwszVal, pvarSrc->u.pwszVal, (len+1)*sizeof(WCHAR));
2977         break;
2978     case VT_BLOB:
2979     case VT_BLOB_OBJECT:
2980         if (pvarSrc->u.blob.pBlobData)
2981         {
2982             len = pvarSrc->u.blob.cbSize;
2983             pvarDest->u.blob.pBlobData = CoTaskMemAlloc(len);
2984             CopyMemory(pvarDest->u.blob.pBlobData, pvarSrc->u.blob.pBlobData, len);
2985         }
2986         break;
2987     case VT_BSTR:
2988         pvarDest->u.bstrVal = PropSysAllocString(pvarSrc->u.bstrVal);
2989         break;
2990     case VT_CF:
2991         if (pvarSrc->u.pclipdata)
2992         {
2993             len = pvarSrc->u.pclipdata->cbSize - sizeof(pvarSrc->u.pclipdata->ulClipFmt);
2994             pvarDest->u.pclipdata = CoTaskMemAlloc(sizeof (CLIPDATA));
2995             pvarDest->u.pclipdata->cbSize = pvarSrc->u.pclipdata->cbSize;
2996             pvarDest->u.pclipdata->ulClipFmt = pvarSrc->u.pclipdata->ulClipFmt;
2997             pvarDest->u.pclipdata->pClipData = CoTaskMemAlloc(len);
2998             CopyMemory(pvarDest->u.pclipdata->pClipData, pvarSrc->u.pclipdata->pClipData, len);
2999         }
3000         break;
3001     default:
3002         if (pvarSrc->vt & VT_VECTOR)
3003         {
3004             int elemSize;
3005             ULONG i;
3006
3007             switch(pvarSrc->vt & ~VT_VECTOR)
3008             {
3009             case VT_I1:       elemSize = sizeof(pvarSrc->u.cVal); break;
3010             case VT_UI1:      elemSize = sizeof(pvarSrc->u.bVal); break;
3011             case VT_I2:       elemSize = sizeof(pvarSrc->u.iVal); break;
3012             case VT_UI2:      elemSize = sizeof(pvarSrc->u.uiVal); break;
3013             case VT_BOOL:     elemSize = sizeof(pvarSrc->u.boolVal); break;
3014             case VT_I4:       elemSize = sizeof(pvarSrc->u.lVal); break;
3015             case VT_UI4:      elemSize = sizeof(pvarSrc->u.ulVal); break;
3016             case VT_R4:       elemSize = sizeof(pvarSrc->u.fltVal); break;
3017             case VT_R8:       elemSize = sizeof(pvarSrc->u.dblVal); break;
3018             case VT_ERROR:    elemSize = sizeof(pvarSrc->u.scode); break;
3019             case VT_I8:       elemSize = sizeof(pvarSrc->u.hVal); break;
3020             case VT_UI8:      elemSize = sizeof(pvarSrc->u.uhVal); break;
3021             case VT_CY:       elemSize = sizeof(pvarSrc->u.cyVal); break;
3022             case VT_DATE:     elemSize = sizeof(pvarSrc->u.date); break;
3023             case VT_FILETIME: elemSize = sizeof(pvarSrc->u.filetime); break;
3024             case VT_CLSID:    elemSize = sizeof(*pvarSrc->u.puuid); break;
3025             case VT_CF:       elemSize = sizeof(*pvarSrc->u.pclipdata); break;
3026             case VT_BSTR:     elemSize = sizeof(pvarSrc->u.bstrVal); break;
3027             case VT_LPSTR:    elemSize = sizeof(pvarSrc->u.pszVal); break;
3028             case VT_LPWSTR:   elemSize = sizeof(pvarSrc->u.pwszVal); break;
3029             case VT_VARIANT:  elemSize = sizeof(*pvarSrc->u.pvarVal); break;
3030
3031             default:
3032                 FIXME("Invalid element type: %ul\n", pvarSrc->vt & ~VT_VECTOR);
3033                 return E_INVALIDARG;
3034             }
3035             len = pvarSrc->u.capropvar.cElems;
3036             pvarDest->u.capropvar.pElems = CoTaskMemAlloc(len * elemSize);
3037             if (pvarSrc->vt == (VT_VECTOR | VT_VARIANT))
3038             {
3039                 for (i = 0; i < len; i++)
3040                     PropVariantCopy(&pvarDest->u.capropvar.pElems[i], &pvarSrc->u.capropvar.pElems[i]);
3041             }
3042             else if (pvarSrc->vt == (VT_VECTOR | VT_CF))
3043             {
3044                 FIXME("Copy clipformats\n");
3045             }
3046             else if (pvarSrc->vt == (VT_VECTOR | VT_BSTR))
3047             {
3048                 for (i = 0; i < len; i++)
3049                     pvarDest->u.cabstr.pElems[i] = PropSysAllocString(pvarSrc->u.cabstr.pElems[i]);
3050             }
3051             else if (pvarSrc->vt == (VT_VECTOR | VT_LPSTR))
3052             {
3053                 size_t strLen;
3054                 for (i = 0; i < len; i++)
3055                 {
3056                     strLen = lstrlenA(pvarSrc->u.calpstr.pElems[i]) + 1;
3057                     pvarDest->u.calpstr.pElems[i] = CoTaskMemAlloc(strLen);
3058                     memcpy(pvarDest->u.calpstr.pElems[i],
3059                      pvarSrc->u.calpstr.pElems[i], strLen);
3060                 }
3061             }
3062             else if (pvarSrc->vt == (VT_VECTOR | VT_LPWSTR))
3063             {
3064                 size_t strLen;
3065                 for (i = 0; i < len; i++)
3066                 {
3067                     strLen = (lstrlenW(pvarSrc->u.calpwstr.pElems[i]) + 1) *
3068                      sizeof(WCHAR);
3069                     pvarDest->u.calpstr.pElems[i] = CoTaskMemAlloc(strLen);
3070                     memcpy(pvarDest->u.calpstr.pElems[i],
3071                      pvarSrc->u.calpstr.pElems[i], strLen);
3072                 }
3073             }
3074             else
3075                 CopyMemory(pvarDest->u.capropvar.pElems, pvarSrc->u.capropvar.pElems, len * elemSize);
3076         }
3077         else
3078             WARN("Invalid/unsupported type %d\n", pvarSrc->vt);
3079     }
3080
3081     return S_OK;
3082 }
3083
3084 /***********************************************************************
3085  *           FreePropVariantArray                           [OLE32.@]
3086  */
3087 HRESULT WINAPI FreePropVariantArray(ULONG cVariants, /* [in] */
3088                                     PROPVARIANT *rgvars)    /* [in/out] */
3089 {
3090     ULONG i;
3091
3092     TRACE("(%u, %p)\n", cVariants, rgvars);
3093
3094     if (!rgvars)
3095         return E_INVALIDARG;
3096
3097     for(i = 0; i < cVariants; i++)
3098         PropVariantClear(&rgvars[i]);
3099
3100     return S_OK;
3101 }
3102
3103 /******************************************************************************
3104  * DllDebugObjectRPCHook (OLE32.@)
3105  * turns on and off internal debugging,  pointer is only used on macintosh
3106  */
3107
3108 BOOL WINAPI DllDebugObjectRPCHook(BOOL b, void *dummy)
3109 {
3110   FIXME("stub\n");
3111   return TRUE;
3112 }