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