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