Removed W->A from DEFWND_ImmIsUIMessageW.
[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  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24
25 #include <assert.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30
31 #define COBJMACROS
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
34
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winerror.h"
38 #include "wingdi.h"
39 #include "winuser.h"
40 #include "winnls.h"
41 #include "winreg.h"
42 #include "commctrl.h"
43 #include "ole2.h"
44 #include "ole2ver.h"
45 #include "wownt32.h"
46
47 #include "wine/winbase16.h"
48 #include "wine/wingdi16.h"
49 #include "wine/winuser16.h"
50 #include "ole32_main.h"
51
52 #include "wine/debug.h"
53
54 WINE_DEFAULT_DEBUG_CHANNEL(ole);
55 WINE_DECLARE_DEBUG_CHANNEL(accel);
56
57 #define HICON_16(h32)           (LOWORD(h32))
58 #define HICON_32(h16)           ((HICON)(ULONG_PTR)(h16))
59 #define HINSTANCE_32(h16)       ((HINSTANCE)(ULONG_PTR)(h16))
60
61 /******************************************************************************
62  * These are static/global variables and internal data structures that the
63  * OLE module uses to maintain it's state.
64  */
65 typedef struct tagDropTargetNode
66 {
67   HWND          hwndTarget;
68   IDropTarget*    dropTarget;
69   struct tagDropTargetNode* prevDropTarget;
70   struct tagDropTargetNode* nextDropTarget;
71 } DropTargetNode;
72
73 typedef struct tagTrackerWindowInfo
74 {
75   IDataObject* dataObject;
76   IDropSource* dropSource;
77   DWORD        dwOKEffect;
78   DWORD*       pdwEffect;
79   BOOL       trackingDone;
80   HRESULT      returnValue;
81
82   BOOL       escPressed;
83   HWND       curTargetHWND;     /* window the mouse is hovering over */
84   HWND       curDragTargetHWND; /* might be a ancestor of curTargetHWND */
85   IDropTarget* curDragTarget;
86 } TrackerWindowInfo;
87
88 typedef struct tagOleMenuDescriptor  /* OleMenuDescriptor */
89 {
90   HWND               hwndFrame;         /* The containers frame window */
91   HWND               hwndActiveObject;  /* The active objects window */
92   OLEMENUGROUPWIDTHS mgw;               /* OLE menu group widths for the shared menu */
93   HMENU              hmenuCombined;     /* The combined menu */
94   BOOL               bIsServerItem;     /* True if the currently open popup belongs to the server */
95 } OleMenuDescriptor;
96
97 typedef struct tagOleMenuHookItem   /* OleMenu hook item in per thread hook list */
98 {
99   DWORD tid;                /* Thread Id  */
100   HANDLE hHeap;             /* Heap this is allocated from */
101   HHOOK GetMsg_hHook;       /* message hook for WH_GETMESSAGE */
102   HHOOK CallWndProc_hHook;  /* message hook for WH_CALLWNDPROC */
103   struct tagOleMenuHookItem *next;
104 } OleMenuHookItem;
105
106 static OleMenuHookItem *hook_list;
107
108 /*
109  * This is the lock count on the OLE library. It is controlled by the
110  * OLEInitialize/OLEUninitialize methods.
111  */
112 static ULONG OLE_moduleLockCount = 0;
113
114 /*
115  * Name of our registered window class.
116  */
117 static const char OLEDD_DRAGTRACKERCLASS[] = "WineDragDropTracker32";
118
119 /*
120  * This is the head of the Drop target container.
121  */
122 static DropTargetNode* targetListHead = NULL;
123
124 /******************************************************************************
125  * These are the prototypes of miscelaneous utility methods
126  */
127 static void OLEUTL_ReadRegistryDWORDValue(HKEY regKey, DWORD* pdwValue);
128
129 /******************************************************************************
130  * These are the prototypes of the utility methods used to manage a shared menu
131  */
132 static void OLEMenu_Initialize();
133 static void OLEMenu_UnInitialize();
134 BOOL OLEMenu_InstallHooks( DWORD tid );
135 BOOL OLEMenu_UnInstallHooks( DWORD tid );
136 OleMenuHookItem * OLEMenu_IsHookInstalled( DWORD tid );
137 static BOOL OLEMenu_FindMainMenuIndex( HMENU hMainMenu, HMENU hPopupMenu, UINT *pnPos );
138 BOOL OLEMenu_SetIsServerMenu( HMENU hmenu, OleMenuDescriptor *pOleMenuDescriptor );
139 LRESULT CALLBACK OLEMenu_CallWndProc(INT code, WPARAM wParam, LPARAM lParam);
140 LRESULT CALLBACK OLEMenu_GetMsgProc(INT code, WPARAM wParam, LPARAM lParam);
141
142 /******************************************************************************
143  * These are the prototypes of the OLE Clipboard initialization methods (in clipboard.c)
144  */
145 void OLEClipbrd_UnInitialize();
146 void OLEClipbrd_Initialize();
147
148 /******************************************************************************
149  * These are the prototypes of the utility methods used for OLE Drag n Drop
150  */
151 static void            OLEDD_Initialize();
152 static void            OLEDD_UnInitialize();
153 static void            OLEDD_InsertDropTarget(
154                          DropTargetNode* nodeToAdd);
155 static DropTargetNode* OLEDD_ExtractDropTarget(
156                          HWND hwndOfTarget);
157 static DropTargetNode* OLEDD_FindDropTarget(
158                          HWND hwndOfTarget);
159 static LRESULT WINAPI  OLEDD_DragTrackerWindowProc(
160                          HWND   hwnd,
161                          UINT   uMsg,
162                          WPARAM wParam,
163                          LPARAM   lParam);
164 static void OLEDD_TrackMouseMove(
165                          TrackerWindowInfo* trackerInfo,
166                          POINT            mousePos,
167                          DWORD              keyState);
168 static void OLEDD_TrackStateChange(
169                          TrackerWindowInfo* trackerInfo,
170                          POINT            mousePos,
171                          DWORD              keyState);
172 static DWORD OLEDD_GetButtonState();
173
174
175 /******************************************************************************
176  *              OleBuildVersion [OLE2.1]
177  *              OleBuildVersion [OLE32.@]
178  */
179 DWORD WINAPI OleBuildVersion(void)
180 {
181     TRACE("Returning version %d, build %d.\n", rmm, rup);
182     return (rmm<<16)+rup;
183 }
184
185 /***********************************************************************
186  *           OleInitialize       (OLE2.2)
187  *           OleInitialize       (OLE32.@)
188  */
189 HRESULT WINAPI OleInitialize(LPVOID reserved)
190 {
191   HRESULT hr;
192
193   TRACE("(%p)\n", reserved);
194
195   /*
196    * The first duty of the OleInitialize is to initialize the COM libraries.
197    */
198   hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
199
200   /*
201    * If the CoInitializeEx call failed, the OLE libraries can't be
202    * initialized.
203    */
204   if (FAILED(hr))
205     return hr;
206
207   /*
208    * Then, it has to initialize the OLE specific modules.
209    * This includes:
210    *     Clipboard
211    *     Drag and Drop
212    *     Object linking and Embedding
213    *     In-place activation
214    */
215   if (OLE_moduleLockCount==0)
216   {
217     /*
218      * Initialize the libraries.
219      */
220     TRACE("() - Initializing the OLE libraries\n");
221
222     /*
223      * OLE Clipboard
224      */
225     OLEClipbrd_Initialize();
226
227     /*
228      * Drag and Drop
229      */
230     OLEDD_Initialize();
231
232     /*
233      * OLE shared menu
234      */
235     OLEMenu_Initialize();
236   }
237
238   /*
239    * Then, we increase the lock count on the OLE module.
240    */
241   OLE_moduleLockCount++;
242
243   return hr;
244 }
245
246 /******************************************************************************
247  *              CoGetCurrentProcess     [COMPOBJ.34]
248  *              CoGetCurrentProcess     [OLE32.@]
249  *
250  * NOTES
251  *   Is DWORD really the correct return type for this function?
252  */
253 DWORD WINAPI CoGetCurrentProcess(void)
254 {
255         return GetCurrentProcessId();
256 }
257
258 /******************************************************************************
259  *              OleUninitialize [OLE2.3]
260  *              OleUninitialize [OLE32.@]
261  */
262 void WINAPI OleUninitialize(void)
263 {
264   TRACE("()\n");
265
266   /*
267    * Decrease the lock count on the OLE module.
268    */
269   OLE_moduleLockCount--;
270
271   /*
272    * If we hit the bottom of the lock stack, free the libraries.
273    */
274   if (OLE_moduleLockCount==0)
275   {
276     /*
277      * Actually free the libraries.
278      */
279     TRACE("() - Freeing the last reference count\n");
280
281     /*
282      * OLE Clipboard
283      */
284     OLEClipbrd_UnInitialize();
285
286     /*
287      * Drag and Drop
288      */
289     OLEDD_UnInitialize();
290
291     /*
292      * OLE shared menu
293      */
294     OLEMenu_UnInitialize();
295   }
296
297   /*
298    * Then, uninitialize the COM libraries.
299    */
300   CoUninitialize();
301 }
302
303 /******************************************************************************
304  *              CoRegisterMessageFilter [OLE32.@]
305  */
306 HRESULT WINAPI CoRegisterMessageFilter(
307     LPMESSAGEFILTER lpMessageFilter,    /* [in] Pointer to interface */
308     LPMESSAGEFILTER *lplpMessageFilter  /* [out] Indirect pointer to prior instance if non-NULL */
309 ) {
310     FIXME("stub\n");
311     if (lplpMessageFilter) {
312         *lplpMessageFilter = NULL;
313     }
314     return S_OK;
315 }
316
317 /******************************************************************************
318  *              OleInitializeWOW        [OLE32.@]
319  */
320 HRESULT WINAPI OleInitializeWOW(DWORD x) {
321         FIXME("(0x%08lx),stub!\n",x);
322         return 0;
323 }
324
325 /***********************************************************************
326  *           RegisterDragDrop (OLE32.@)
327  */
328 HRESULT WINAPI RegisterDragDrop(
329         HWND hwnd,
330         LPDROPTARGET pDropTarget)
331 {
332   DropTargetNode* dropTargetInfo;
333
334   TRACE("(%p,%p)\n", hwnd, pDropTarget);
335
336   if (!pDropTarget)
337     return E_INVALIDARG;
338   
339   /*
340    * First, check if the window is already registered.
341    */
342   dropTargetInfo = OLEDD_FindDropTarget(hwnd);
343
344   if (dropTargetInfo!=NULL)
345     return DRAGDROP_E_ALREADYREGISTERED;
346
347   /*
348    * If it's not there, we can add it. We first create a node for it.
349    */
350   dropTargetInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(DropTargetNode));
351
352   if (dropTargetInfo==NULL)
353     return E_OUTOFMEMORY;
354
355   dropTargetInfo->hwndTarget     = hwnd;
356   dropTargetInfo->prevDropTarget = NULL;
357   dropTargetInfo->nextDropTarget = NULL;
358
359   /*
360    * Don't forget that this is an interface pointer, need to nail it down since
361    * we keep a copy of it.
362    */
363   dropTargetInfo->dropTarget  = pDropTarget;
364   IDropTarget_AddRef(dropTargetInfo->dropTarget);
365
366   OLEDD_InsertDropTarget(dropTargetInfo);
367
368         return S_OK;
369 }
370
371 /***********************************************************************
372  *           RevokeDragDrop (OLE32.@)
373  */
374 HRESULT WINAPI RevokeDragDrop(
375         HWND hwnd)
376 {
377   DropTargetNode* dropTargetInfo;
378
379   TRACE("(%p)\n", hwnd);
380
381   /*
382    * First, check if the window is already registered.
383    */
384   dropTargetInfo = OLEDD_ExtractDropTarget(hwnd);
385
386   /*
387    * If it ain't in there, it's an error.
388    */
389   if (dropTargetInfo==NULL)
390     return DRAGDROP_E_NOTREGISTERED;
391
392   /*
393    * If it's in there, clean-up it's used memory and
394    * references
395    */
396   IDropTarget_Release(dropTargetInfo->dropTarget);
397   HeapFree(GetProcessHeap(), 0, dropTargetInfo);
398
399         return S_OK;
400 }
401
402 /***********************************************************************
403  *           OleRegGetUserType (OLE32.@)
404  *
405  * This implementation of OleRegGetUserType ignores the dwFormOfType
406  * parameter and always returns the full name of the object. This is
407  * not too bad since this is the case for many objects because of the
408  * way they are registered.
409  */
410 HRESULT WINAPI OleRegGetUserType(
411         REFCLSID clsid,
412         DWORD dwFormOfType,
413         LPOLESTR* pszUserType)
414 {
415   char    keyName[60];
416   DWORD   dwKeyType;
417   DWORD   cbData;
418   HKEY    clsidKey;
419   LONG    hres;
420   LPBYTE  buffer;
421   HRESULT retVal;
422   /*
423    * Initialize the out parameter.
424    */
425   *pszUserType = NULL;
426
427   /*
428    * Build the key name we're looking for
429    */
430   sprintf( keyName, "CLSID\\{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\",
431            clsid->Data1, clsid->Data2, clsid->Data3,
432            clsid->Data4[0], clsid->Data4[1], clsid->Data4[2], clsid->Data4[3],
433            clsid->Data4[4], clsid->Data4[5], clsid->Data4[6], clsid->Data4[7] );
434
435   TRACE("(%s, %ld, %p)\n", keyName, dwFormOfType, pszUserType);
436
437   /*
438    * Open the class id Key
439    */
440   hres = RegOpenKeyA(HKEY_CLASSES_ROOT,
441                      keyName,
442                      &clsidKey);
443
444   if (hres != ERROR_SUCCESS)
445     return REGDB_E_CLASSNOTREG;
446
447   /*
448    * Retrieve the size of the name string.
449    */
450   cbData = 0;
451
452   hres = RegQueryValueExA(clsidKey,
453                           "",
454                           NULL,
455                           &dwKeyType,
456                           NULL,
457                           &cbData);
458
459   if (hres!=ERROR_SUCCESS)
460   {
461     RegCloseKey(clsidKey);
462     return REGDB_E_READREGDB;
463   }
464
465   /*
466    * Allocate a buffer for the registry value.
467    */
468   *pszUserType = CoTaskMemAlloc(cbData*2);
469
470   if (*pszUserType==NULL)
471   {
472     RegCloseKey(clsidKey);
473     return E_OUTOFMEMORY;
474   }
475
476   buffer = HeapAlloc(GetProcessHeap(), 0, cbData);
477
478   if (buffer == NULL)
479   {
480     RegCloseKey(clsidKey);
481     CoTaskMemFree(*pszUserType);
482     *pszUserType=NULL;
483     return E_OUTOFMEMORY;
484   }
485
486   hres = RegQueryValueExA(clsidKey,
487                           "",
488                           NULL,
489                           &dwKeyType,
490                           buffer,
491                           &cbData);
492
493   RegCloseKey(clsidKey);
494
495
496   if (hres!=ERROR_SUCCESS)
497   {
498     CoTaskMemFree(*pszUserType);
499     *pszUserType=NULL;
500
501     retVal = REGDB_E_READREGDB;
502   }
503   else
504   {
505     MultiByteToWideChar( CP_ACP, 0, buffer, -1, *pszUserType, cbData /*FIXME*/ );
506     retVal = S_OK;
507   }
508   HeapFree(GetProcessHeap(), 0, buffer);
509
510   return retVal;
511 }
512
513 /***********************************************************************
514  * DoDragDrop [OLE32.@]
515  */
516 HRESULT WINAPI DoDragDrop (
517   IDataObject *pDataObject,  /* [in] ptr to the data obj           */
518   IDropSource* pDropSource,  /* [in] ptr to the source obj         */
519   DWORD       dwOKEffect,    /* [in] effects allowed by the source */
520   DWORD       *pdwEffect)    /* [out] ptr to effects of the source */
521 {
522   TrackerWindowInfo trackerInfo;
523   HWND            hwndTrackWindow;
524   MSG             msg;
525
526   TRACE("(DataObject %p, DropSource %p)\n", pDataObject, pDropSource);
527
528   /*
529    * Setup the drag n drop tracking window.
530    */
531   if (!IsValidInterface((LPUNKNOWN)pDropSource))
532       return E_INVALIDARG;
533
534   trackerInfo.dataObject        = pDataObject;
535   trackerInfo.dropSource        = pDropSource;
536   trackerInfo.dwOKEffect        = dwOKEffect;
537   trackerInfo.pdwEffect         = pdwEffect;
538   trackerInfo.trackingDone      = FALSE;
539   trackerInfo.escPressed        = FALSE;
540   trackerInfo.curDragTargetHWND = 0;
541   trackerInfo.curTargetHWND     = 0;
542   trackerInfo.curDragTarget     = 0;
543
544   hwndTrackWindow = CreateWindowA(OLEDD_DRAGTRACKERCLASS,
545                                     "TrackerWindow",
546                                     WS_POPUP,
547                                     CW_USEDEFAULT, CW_USEDEFAULT,
548                                     CW_USEDEFAULT, CW_USEDEFAULT,
549                                     0,
550                                     0,
551                                     0,
552                                     (LPVOID)&trackerInfo);
553
554   if (hwndTrackWindow!=0)
555   {
556     /*
557      * Capture the mouse input
558      */
559     SetCapture(hwndTrackWindow);
560
561     /*
562      * Pump messages. All mouse input should go the the capture window.
563      */
564     while (!trackerInfo.trackingDone && GetMessageA(&msg, 0, 0, 0) )
565     {
566       if ( (msg.message >= WM_KEYFIRST) &&
567            (msg.message <= WM_KEYLAST) )
568       {
569         /*
570          * When keyboard messages are sent to windows on this thread, we
571          * want to ignore notify the drop source that the state changed.
572          * in the case of the Escape key, we also notify the drop source
573          * we give it a special meaning.
574          */
575         if ( (msg.message==WM_KEYDOWN) &&
576              (msg.wParam==VK_ESCAPE) )
577         {
578           trackerInfo.escPressed = TRUE;
579         }
580
581         /*
582          * Notify the drop source.
583          */
584         OLEDD_TrackStateChange(&trackerInfo,
585                                msg.pt,
586                                OLEDD_GetButtonState());
587       }
588       else
589       {
590         /*
591          * Dispatch the messages only when it's not a keyboard message.
592          */
593         DispatchMessageA(&msg);
594       }
595     }
596
597     /*
598      * Destroy the temporary window.
599      */
600     DestroyWindow(hwndTrackWindow);
601
602     return trackerInfo.returnValue;
603   }
604
605   return E_FAIL;
606 }
607
608 /***********************************************************************
609  * OleQueryLinkFromData [OLE32.@]
610  */
611 HRESULT WINAPI OleQueryLinkFromData(
612   IDataObject* pSrcDataObject)
613 {
614   FIXME("(%p),stub!\n", pSrcDataObject);
615   return S_OK;
616 }
617
618 /***********************************************************************
619  * OleRegGetMiscStatus [OLE32.@]
620  */
621 HRESULT WINAPI OleRegGetMiscStatus(
622   REFCLSID clsid,
623   DWORD    dwAspect,
624   DWORD*   pdwStatus)
625 {
626   char    keyName[60];
627   HKEY    clsidKey;
628   HKEY    miscStatusKey;
629   HKEY    aspectKey;
630   LONG    result;
631
632   /*
633    * Initialize the out parameter.
634    */
635   *pdwStatus = 0;
636
637   /*
638    * Build the key name we're looking for
639    */
640   sprintf( keyName, "CLSID\\{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\",
641            clsid->Data1, clsid->Data2, clsid->Data3,
642            clsid->Data4[0], clsid->Data4[1], clsid->Data4[2], clsid->Data4[3],
643            clsid->Data4[4], clsid->Data4[5], clsid->Data4[6], clsid->Data4[7] );
644
645   TRACE("(%s, %ld, %p)\n", keyName, dwAspect, pdwStatus);
646
647   /*
648    * Open the class id Key
649    */
650   result = RegOpenKeyA(HKEY_CLASSES_ROOT,
651                        keyName,
652                        &clsidKey);
653
654   if (result != ERROR_SUCCESS)
655     return REGDB_E_CLASSNOTREG;
656
657   /*
658    * Get the MiscStatus
659    */
660   result = RegOpenKeyA(clsidKey,
661                        "MiscStatus",
662                        &miscStatusKey);
663
664
665   if (result != ERROR_SUCCESS)
666   {
667     RegCloseKey(clsidKey);
668     return REGDB_E_READREGDB;
669   }
670
671   /*
672    * Read the default value
673    */
674   OLEUTL_ReadRegistryDWORDValue(miscStatusKey, pdwStatus);
675
676   /*
677    * Open the key specific to the requested aspect.
678    */
679   sprintf(keyName, "%ld", dwAspect);
680
681   result = RegOpenKeyA(miscStatusKey,
682                        keyName,
683                        &aspectKey);
684
685   if (result == ERROR_SUCCESS)
686   {
687     OLEUTL_ReadRegistryDWORDValue(aspectKey, pdwStatus);
688     RegCloseKey(aspectKey);
689   }
690
691   /*
692    * Cleanup
693    */
694   RegCloseKey(miscStatusKey);
695   RegCloseKey(clsidKey);
696
697   return S_OK;
698 }
699
700 /******************************************************************************
701  *              OleSetContainedObject        [OLE32.@]
702  */
703 HRESULT WINAPI OleSetContainedObject(
704   LPUNKNOWN pUnknown,
705   BOOL      fContained)
706 {
707   IRunnableObject* runnable = NULL;
708   HRESULT          hres;
709
710   TRACE("(%p,%x), stub!\n", pUnknown, fContained);
711
712   hres = IUnknown_QueryInterface(pUnknown,
713                                  &IID_IRunnableObject,
714                                  (void**)&runnable);
715
716   if (SUCCEEDED(hres))
717   {
718     hres = IRunnableObject_SetContainedObject(runnable, fContained);
719
720     IRunnableObject_Release(runnable);
721
722     return hres;
723   }
724
725   return S_OK;
726 }
727
728 /******************************************************************************
729  *              OleLoad        [OLE32.@]
730  */
731 HRESULT WINAPI OleLoad(
732   LPSTORAGE       pStg,
733   REFIID          riid,
734   LPOLECLIENTSITE pClientSite,
735   LPVOID*         ppvObj)
736 {
737   IPersistStorage* persistStorage = NULL;
738   IOleObject*      oleObject      = NULL;
739   STATSTG          storageInfo;
740   HRESULT          hres;
741
742   TRACE("(%p,%p,%p,%p)\n", pStg, riid, pClientSite, ppvObj);
743
744   /*
745    * TODO, Conversion ... OleDoAutoConvert
746    */
747
748   /*
749    * Get the class ID for the object.
750    */
751   hres = IStorage_Stat(pStg, &storageInfo, STATFLAG_NONAME);
752
753   /*
754    * Now, try and create the handler for the object
755    */
756   hres = CoCreateInstance(&storageInfo.clsid,
757                           NULL,
758                           CLSCTX_INPROC_HANDLER,
759                           &IID_IOleObject,
760                           (void**)&oleObject);
761
762   /*
763    * If that fails, as it will most times, load the default
764    * OLE handler.
765    */
766   if (FAILED(hres))
767   {
768     hres = OleCreateDefaultHandler(&storageInfo.clsid,
769                                    NULL,
770                                    &IID_IOleObject,
771                                    (void**)&oleObject);
772   }
773
774   /*
775    * If we couldn't find a handler... this is bad. Abort the whole thing.
776    */
777   if (FAILED(hres))
778     return hres;
779
780   /*
781    * Inform the new object of it's client site.
782    */
783   hres = IOleObject_SetClientSite(oleObject, pClientSite);
784
785   /*
786    * Initialize the object with it's IPersistStorage interface.
787    */
788   hres = IOleObject_QueryInterface(oleObject,
789                                    &IID_IPersistStorage,
790                                    (void**)&persistStorage);
791
792   if (SUCCEEDED(hres))
793   {
794     IPersistStorage_Load(persistStorage, pStg);
795
796     IPersistStorage_Release(persistStorage);
797     persistStorage = NULL;
798   }
799
800   /*
801    * Return the requested interface to the caller.
802    */
803   hres = IOleObject_QueryInterface(oleObject, riid, ppvObj);
804
805   /*
806    * Cleanup interfaces used internally
807    */
808   IOleObject_Release(oleObject);
809
810   return hres;
811 }
812
813 /***********************************************************************
814  *           OleSave     [OLE32.@]
815  */
816 HRESULT WINAPI OleSave(
817   LPPERSISTSTORAGE pPS,
818   LPSTORAGE        pStg,
819   BOOL             fSameAsLoad)
820 {
821   HRESULT hres;
822   CLSID   objectClass;
823
824   TRACE("(%p,%p,%x)\n", pPS, pStg, fSameAsLoad);
825
826   /*
827    * First, we transfer the class ID (if available)
828    */
829   hres = IPersistStorage_GetClassID(pPS, &objectClass);
830
831   if (SUCCEEDED(hres))
832   {
833     WriteClassStg(pStg, &objectClass);
834   }
835
836   /*
837    * Then, we ask the object to save itself to the
838    * storage. If it is successful, we commit the storage.
839    */
840   hres = IPersistStorage_Save(pPS, pStg, fSameAsLoad);
841
842   if (SUCCEEDED(hres))
843   {
844     IStorage_Commit(pStg,
845                     STGC_DEFAULT);
846   }
847
848   return hres;
849 }
850
851
852 /******************************************************************************
853  *              OleLockRunning        [OLE32.@]
854  */
855 HRESULT WINAPI OleLockRunning(LPUNKNOWN pUnknown, BOOL fLock, BOOL fLastUnlockCloses)
856 {
857   IRunnableObject* runnable = NULL;
858   HRESULT          hres;
859
860   TRACE("(%p,%x,%x)\n", pUnknown, fLock, fLastUnlockCloses);
861
862   hres = IUnknown_QueryInterface(pUnknown,
863                                  &IID_IRunnableObject,
864                                  (void**)&runnable);
865
866   if (SUCCEEDED(hres))
867   {
868     hres = IRunnableObject_LockRunning(runnable, fLock, fLastUnlockCloses);
869
870     IRunnableObject_Release(runnable);
871
872     return hres;
873   }
874   else
875     return E_INVALIDARG;
876 }
877
878
879 /**************************************************************************
880  * Internal methods to manage the shared OLE menu in response to the
881  * OLE***MenuDescriptor API
882  */
883
884 /***
885  * OLEMenu_Initialize()
886  *
887  * Initializes the OLEMENU data structures.
888  */
889 static void OLEMenu_Initialize()
890 {
891 }
892
893 /***
894  * OLEMenu_UnInitialize()
895  *
896  * Releases the OLEMENU data structures.
897  */
898 static void OLEMenu_UnInitialize()
899 {
900 }
901
902 /*************************************************************************
903  * OLEMenu_InstallHooks
904  * Install thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC
905  *
906  * RETURNS: TRUE if message hooks were successfully installed
907  *          FALSE on failure
908  */
909 BOOL OLEMenu_InstallHooks( DWORD tid )
910 {
911   OleMenuHookItem *pHookItem = NULL;
912
913   /* Create an entry for the hook table */
914   if ( !(pHookItem = HeapAlloc(GetProcessHeap(), 0,
915                                sizeof(OleMenuHookItem)) ) )
916     return FALSE;
917
918   pHookItem->tid = tid;
919   pHookItem->hHeap = GetProcessHeap();
920
921   /* Install a thread scope message hook for WH_GETMESSAGE */
922   pHookItem->GetMsg_hHook = SetWindowsHookExA( WH_GETMESSAGE, OLEMenu_GetMsgProc,
923                                                0, GetCurrentThreadId() );
924   if ( !pHookItem->GetMsg_hHook )
925     goto CLEANUP;
926
927   /* Install a thread scope message hook for WH_CALLWNDPROC */
928   pHookItem->CallWndProc_hHook = SetWindowsHookExA( WH_CALLWNDPROC, OLEMenu_CallWndProc,
929                                                     0, GetCurrentThreadId() );
930   if ( !pHookItem->CallWndProc_hHook )
931     goto CLEANUP;
932
933   /* Insert the hook table entry */
934   pHookItem->next = hook_list;
935   hook_list = pHookItem;
936
937   return TRUE;
938
939 CLEANUP:
940   /* Unhook any hooks */
941   if ( pHookItem->GetMsg_hHook )
942     UnhookWindowsHookEx( pHookItem->GetMsg_hHook );
943   if ( pHookItem->CallWndProc_hHook )
944     UnhookWindowsHookEx( pHookItem->CallWndProc_hHook );
945   /* Release the hook table entry */
946   HeapFree(pHookItem->hHeap, 0, pHookItem );
947
948   return FALSE;
949 }
950
951 /*************************************************************************
952  * OLEMenu_UnInstallHooks
953  * UnInstall thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC
954  *
955  * RETURNS: TRUE if message hooks were successfully installed
956  *          FALSE on failure
957  */
958 BOOL OLEMenu_UnInstallHooks( DWORD tid )
959 {
960   OleMenuHookItem *pHookItem = NULL;
961   OleMenuHookItem **ppHook = &hook_list;
962
963   while (*ppHook)
964   {
965       if ((*ppHook)->tid == tid)
966       {
967           pHookItem = *ppHook;
968           *ppHook = pHookItem->next;
969           break;
970       }
971       ppHook = &(*ppHook)->next;
972   }
973   if (!pHookItem) return FALSE;
974
975   /* Uninstall the hooks installed for this thread */
976   if ( !UnhookWindowsHookEx( pHookItem->GetMsg_hHook ) )
977     goto CLEANUP;
978   if ( !UnhookWindowsHookEx( pHookItem->CallWndProc_hHook ) )
979     goto CLEANUP;
980
981   /* Release the hook table entry */
982   HeapFree(pHookItem->hHeap, 0, pHookItem );
983
984   return TRUE;
985
986 CLEANUP:
987   /* Release the hook table entry */
988   if (pHookItem)
989     HeapFree(pHookItem->hHeap, 0, pHookItem );
990
991   return FALSE;
992 }
993
994 /*************************************************************************
995  * OLEMenu_IsHookInstalled
996  * Tests if OLEMenu hooks have been installed for a thread
997  *
998  * RETURNS: The pointer and index of the hook table entry for the tid
999  *          NULL and -1 for the index if no hooks were installed for this thread
1000  */
1001 OleMenuHookItem * OLEMenu_IsHookInstalled( DWORD tid )
1002 {
1003   OleMenuHookItem *pHookItem = NULL;
1004
1005   /* Do a simple linear search for an entry whose tid matches ours.
1006    * We really need a map but efficiency is not a concern here. */
1007   for (pHookItem = hook_list; pHookItem; pHookItem = pHookItem->next)
1008   {
1009     if ( tid == pHookItem->tid )
1010       return pHookItem;
1011   }
1012
1013   return NULL;
1014 }
1015
1016 /***********************************************************************
1017  *           OLEMenu_FindMainMenuIndex
1018  *
1019  * Used by OLEMenu API to find the top level group a menu item belongs to.
1020  * On success pnPos contains the index of the item in the top level menu group
1021  *
1022  * RETURNS: TRUE if the ID was found, FALSE on failure
1023  */
1024 static BOOL OLEMenu_FindMainMenuIndex( HMENU hMainMenu, HMENU hPopupMenu, UINT *pnPos )
1025 {
1026   UINT i, nItems;
1027
1028   nItems = GetMenuItemCount( hMainMenu );
1029
1030   for (i = 0; i < nItems; i++)
1031   {
1032     HMENU hsubmenu;
1033
1034     /*  Is the current item a submenu? */
1035     if ( (hsubmenu = GetSubMenu(hMainMenu, i)) )
1036     {
1037       /* If the handle is the same we're done */
1038       if ( hsubmenu == hPopupMenu )
1039       {
1040         if (pnPos)
1041           *pnPos = i;
1042         return TRUE;
1043       }
1044       /* Recursively search without updating pnPos */
1045       else if ( OLEMenu_FindMainMenuIndex( hsubmenu, hPopupMenu, NULL ) )
1046       {
1047         if (pnPos)
1048           *pnPos = i;
1049         return TRUE;
1050       }
1051     }
1052   }
1053
1054   return FALSE;
1055 }
1056
1057 /***********************************************************************
1058  *           OLEMenu_SetIsServerMenu
1059  *
1060  * Checks whether a popup menu belongs to a shared menu group which is
1061  * owned by the server, and sets the menu descriptor state accordingly.
1062  * All menu messages from these groups should be routed to the server.
1063  *
1064  * RETURNS: TRUE if the popup menu is part of a server owned group
1065  *          FASE if the popup menu is part of a container owned group
1066  */
1067 BOOL OLEMenu_SetIsServerMenu( HMENU hmenu, OleMenuDescriptor *pOleMenuDescriptor )
1068 {
1069   UINT nPos = 0, nWidth, i;
1070
1071   pOleMenuDescriptor->bIsServerItem = FALSE;
1072
1073   /* Don't bother searching if the popup is the combined menu itself */
1074   if ( hmenu == pOleMenuDescriptor->hmenuCombined )
1075     return FALSE;
1076
1077   /* Find the menu item index in the shared OLE menu that this item belongs to */
1078   if ( !OLEMenu_FindMainMenuIndex( pOleMenuDescriptor->hmenuCombined, hmenu,  &nPos ) )
1079     return FALSE;
1080
1081   /* The group widths array has counts for the number of elements
1082    * in the groups File, Edit, Container, Object, Window, Help.
1083    * The Edit, Object & Help groups belong to the server object
1084    * and the other three belong to the container.
1085    * Loop through the group widths and locate the group we are a member of.
1086    */
1087   for ( i = 0, nWidth = 0; i < 6; i++ )
1088   {
1089     nWidth += pOleMenuDescriptor->mgw.width[i];
1090     if ( nPos < nWidth )
1091     {
1092       /* Odd elements are server menu widths */
1093       pOleMenuDescriptor->bIsServerItem = (i%2) ? TRUE : FALSE;
1094       break;
1095     }
1096   }
1097
1098   return pOleMenuDescriptor->bIsServerItem;
1099 }
1100
1101 /*************************************************************************
1102  * OLEMenu_CallWndProc
1103  * Thread scope WH_CALLWNDPROC hook proc filter function (callback)
1104  * This is invoked from a message hook installed in OleSetMenuDescriptor.
1105  */
1106 LRESULT CALLBACK OLEMenu_CallWndProc(INT code, WPARAM wParam, LPARAM lParam)
1107 {
1108   LPCWPSTRUCT pMsg = NULL;
1109   HOLEMENU hOleMenu = 0;
1110   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1111   OleMenuHookItem *pHookItem = NULL;
1112   WORD fuFlags;
1113
1114   TRACE("%i, %04x, %08x\n", code, wParam, (unsigned)lParam );
1115
1116   /* Check if we're being asked to process the message */
1117   if ( HC_ACTION != code )
1118     goto NEXTHOOK;
1119
1120   /* Retrieve the current message being dispatched from lParam */
1121   pMsg = (LPCWPSTRUCT)lParam;
1122
1123   /* Check if the message is destined for a window we are interested in:
1124    * If the window has an OLEMenu property we may need to dispatch
1125    * the menu message to its active objects window instead. */
1126
1127   hOleMenu = (HOLEMENU)GetPropA( pMsg->hwnd, "PROP_OLEMenuDescriptor" );
1128   if ( !hOleMenu )
1129     goto NEXTHOOK;
1130
1131   /* Get the menu descriptor */
1132   pOleMenuDescriptor = (OleMenuDescriptor *) GlobalLock( hOleMenu );
1133   if ( !pOleMenuDescriptor ) /* Bad descriptor! */
1134     goto NEXTHOOK;
1135
1136   /* Process menu messages */
1137   switch( pMsg->message )
1138   {
1139     case WM_INITMENU:
1140     {
1141       /* Reset the menu descriptor state */
1142       pOleMenuDescriptor->bIsServerItem = FALSE;
1143
1144       /* Send this message to the server as well */
1145       SendMessageA( pOleMenuDescriptor->hwndActiveObject,
1146                   pMsg->message, pMsg->wParam, pMsg->lParam );
1147       goto NEXTHOOK;
1148     }
1149
1150     case WM_INITMENUPOPUP:
1151     {
1152       /* Save the state for whether this is a server owned menu */
1153       OLEMenu_SetIsServerMenu( (HMENU)pMsg->wParam, pOleMenuDescriptor );
1154       break;
1155     }
1156
1157     case WM_MENUSELECT:
1158     {
1159       fuFlags = HIWORD(pMsg->wParam);  /* Get flags */
1160       if ( fuFlags & MF_SYSMENU )
1161          goto NEXTHOOK;
1162
1163       /* Save the state for whether this is a server owned popup menu */
1164       else if ( fuFlags & MF_POPUP )
1165         OLEMenu_SetIsServerMenu( (HMENU)pMsg->lParam, pOleMenuDescriptor );
1166
1167       break;
1168     }
1169
1170     case WM_DRAWITEM:
1171     {
1172       LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT) pMsg->lParam;
1173       if ( pMsg->wParam != 0 || lpdis->CtlType != ODT_MENU )
1174         goto NEXTHOOK;  /* Not a menu message */
1175
1176       break;
1177     }
1178
1179     default:
1180       goto NEXTHOOK;
1181   }
1182
1183   /* If the message was for the server dispatch it accordingly */
1184   if ( pOleMenuDescriptor->bIsServerItem )
1185   {
1186     SendMessageA( pOleMenuDescriptor->hwndActiveObject,
1187                   pMsg->message, pMsg->wParam, pMsg->lParam );
1188   }
1189
1190 NEXTHOOK:
1191   if ( pOleMenuDescriptor )
1192     GlobalUnlock( hOleMenu );
1193
1194   /* Lookup the hook item for the current thread */
1195   if ( !( pHookItem = OLEMenu_IsHookInstalled( GetCurrentThreadId() ) ) )
1196   {
1197     /* This should never fail!! */
1198     WARN("could not retrieve hHook for current thread!\n" );
1199     return 0;
1200   }
1201
1202   /* Pass on the message to the next hooker */
1203   return CallNextHookEx( pHookItem->CallWndProc_hHook, code, wParam, lParam );
1204 }
1205
1206 /*************************************************************************
1207  * OLEMenu_GetMsgProc
1208  * Thread scope WH_GETMESSAGE hook proc filter function (callback)
1209  * This is invoked from a message hook installed in OleSetMenuDescriptor.
1210  */
1211 LRESULT CALLBACK OLEMenu_GetMsgProc(INT code, WPARAM wParam, LPARAM lParam)
1212 {
1213   LPMSG pMsg = NULL;
1214   HOLEMENU hOleMenu = 0;
1215   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1216   OleMenuHookItem *pHookItem = NULL;
1217   WORD wCode;
1218
1219   TRACE("%i, %04x, %08x\n", code, wParam, (unsigned)lParam );
1220
1221   /* Check if we're being asked to process a  messages */
1222   if ( HC_ACTION != code )
1223     goto NEXTHOOK;
1224
1225   /* Retrieve the current message being dispatched from lParam */
1226   pMsg = (LPMSG)lParam;
1227
1228   /* Check if the message is destined for a window we are interested in:
1229    * If the window has an OLEMenu property we may need to dispatch
1230    * the menu message to its active objects window instead. */
1231
1232   hOleMenu = (HOLEMENU)GetPropA( pMsg->hwnd, "PROP_OLEMenuDescriptor" );
1233   if ( !hOleMenu )
1234     goto NEXTHOOK;
1235
1236   /* Process menu messages */
1237   switch( pMsg->message )
1238   {
1239     case WM_COMMAND:
1240     {
1241       wCode = HIWORD(pMsg->wParam);  /* Get notification code */
1242       if ( wCode )
1243         goto NEXTHOOK;  /* Not a menu message */
1244       break;
1245     }
1246     default:
1247       goto NEXTHOOK;
1248   }
1249
1250   /* Get the menu descriptor */
1251   pOleMenuDescriptor = (OleMenuDescriptor *) GlobalLock( hOleMenu );
1252   if ( !pOleMenuDescriptor ) /* Bad descriptor! */
1253     goto NEXTHOOK;
1254
1255   /* If the message was for the server dispatch it accordingly */
1256   if ( pOleMenuDescriptor->bIsServerItem )
1257   {
1258     /* Change the hWnd in the message to the active objects hWnd.
1259      * The message loop which reads this message will automatically
1260      * dispatch it to the embedded objects window. */
1261     pMsg->hwnd = pOleMenuDescriptor->hwndActiveObject;
1262   }
1263
1264 NEXTHOOK:
1265   if ( pOleMenuDescriptor )
1266     GlobalUnlock( hOleMenu );
1267
1268   /* Lookup the hook item for the current thread */
1269   if ( !( pHookItem = OLEMenu_IsHookInstalled( GetCurrentThreadId() ) ) )
1270   {
1271     /* This should never fail!! */
1272     WARN("could not retrieve hHook for current thread!\n" );
1273     return FALSE;
1274   }
1275
1276   /* Pass on the message to the next hooker */
1277   return CallNextHookEx( pHookItem->GetMsg_hHook, code, wParam, lParam );
1278 }
1279
1280 /***********************************************************************
1281  * OleCreateMenuDescriptor [OLE32.@]
1282  * Creates an OLE menu descriptor for OLE to use when dispatching
1283  * menu messages and commands.
1284  *
1285  * PARAMS:
1286  *    hmenuCombined  -  Handle to the objects combined menu
1287  *    lpMenuWidths   -  Pointer to array of 6 LONG's indicating menus per group
1288  *
1289  */
1290 HOLEMENU WINAPI OleCreateMenuDescriptor(
1291   HMENU                hmenuCombined,
1292   LPOLEMENUGROUPWIDTHS lpMenuWidths)
1293 {
1294   HOLEMENU hOleMenu;
1295   OleMenuDescriptor *pOleMenuDescriptor;
1296   int i;
1297
1298   if ( !hmenuCombined || !lpMenuWidths )
1299     return 0;
1300
1301   /* Create an OLE menu descriptor */
1302   if ( !(hOleMenu = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT,
1303                                 sizeof(OleMenuDescriptor) ) ) )
1304   return 0;
1305
1306   pOleMenuDescriptor = (OleMenuDescriptor *) GlobalLock( hOleMenu );
1307   if ( !pOleMenuDescriptor )
1308     return 0;
1309
1310   /* Initialize menu group widths and hmenu */
1311   for ( i = 0; i < 6; i++ )
1312     pOleMenuDescriptor->mgw.width[i] = lpMenuWidths->width[i];
1313
1314   pOleMenuDescriptor->hmenuCombined = hmenuCombined;
1315   pOleMenuDescriptor->bIsServerItem = FALSE;
1316   GlobalUnlock( hOleMenu );
1317
1318   return hOleMenu;
1319 }
1320
1321 /***********************************************************************
1322  * OleDestroyMenuDescriptor [OLE32.@]
1323  * Destroy the shared menu descriptor
1324  */
1325 HRESULT WINAPI OleDestroyMenuDescriptor(
1326   HOLEMENU hmenuDescriptor)
1327 {
1328   if ( hmenuDescriptor )
1329     GlobalFree( hmenuDescriptor );
1330         return S_OK;
1331 }
1332
1333 /***********************************************************************
1334  * OleSetMenuDescriptor [OLE32.@]
1335  * Installs or removes OLE dispatching code for the containers frame window
1336  * FIXME: The lpFrame and lpActiveObject parameters are currently ignored
1337  * OLE should install context sensitive help F1 filtering for the app when
1338  * these are non null.
1339  *
1340  * PARAMS:
1341  *     hOleMenu         Handle to composite menu descriptor
1342  *     hwndFrame        Handle to containers frame window
1343  *     hwndActiveObject Handle to objects in-place activation window
1344  *     lpFrame          Pointer to IOleInPlaceFrame on containers window
1345  *     lpActiveObject   Pointer to IOleInPlaceActiveObject on active in-place object
1346  *
1347  * RETURNS:
1348  *      S_OK                               - menu installed correctly
1349  *      E_FAIL, E_INVALIDARG, E_UNEXPECTED - failure
1350  */
1351 HRESULT WINAPI OleSetMenuDescriptor(
1352   HOLEMENU               hOleMenu,
1353   HWND                   hwndFrame,
1354   HWND                   hwndActiveObject,
1355   LPOLEINPLACEFRAME        lpFrame,
1356   LPOLEINPLACEACTIVEOBJECT lpActiveObject)
1357 {
1358   OleMenuDescriptor *pOleMenuDescriptor = NULL;
1359
1360   /* Check args */
1361   if ( !hwndFrame || (hOleMenu && !hwndActiveObject) )
1362     return E_INVALIDARG;
1363
1364   if ( lpFrame || lpActiveObject )
1365   {
1366      FIXME("(%x, %p, %p, %p, %p), Context sensitive help filtering not implemented!\n",
1367         (unsigned int)hOleMenu,
1368         hwndFrame,
1369         hwndActiveObject,
1370         lpFrame,
1371         lpActiveObject);
1372   }
1373
1374   /* Set up a message hook to intercept the containers frame window messages.
1375    * The message filter is responsible for dispatching menu messages from the
1376    * shared menu which are intended for the object.
1377    */
1378
1379   if ( hOleMenu )  /* Want to install dispatching code */
1380   {
1381     /* If OLEMenu hooks are already installed for this thread, fail
1382      * Note: This effectively means that OleSetMenuDescriptor cannot
1383      * be called twice in succession on the same frame window
1384      * without first calling it with a null hOleMenu to uninstall */
1385     if ( OLEMenu_IsHookInstalled( GetCurrentThreadId() ) )
1386   return E_FAIL;
1387
1388     /* Get the menu descriptor */
1389     pOleMenuDescriptor = (OleMenuDescriptor *) GlobalLock( hOleMenu );
1390     if ( !pOleMenuDescriptor )
1391       return E_UNEXPECTED;
1392
1393     /* Update the menu descriptor */
1394     pOleMenuDescriptor->hwndFrame = hwndFrame;
1395     pOleMenuDescriptor->hwndActiveObject = hwndActiveObject;
1396
1397     GlobalUnlock( hOleMenu );
1398     pOleMenuDescriptor = NULL;
1399
1400     /* Add a menu descriptor windows property to the frame window */
1401     SetPropA( hwndFrame, "PROP_OLEMenuDescriptor", hOleMenu );
1402
1403     /* Install thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC */
1404     if ( !OLEMenu_InstallHooks( GetCurrentThreadId() ) )
1405       return E_FAIL;
1406   }
1407   else  /* Want to uninstall dispatching code */
1408   {
1409     /* Uninstall the hooks */
1410     if ( !OLEMenu_UnInstallHooks( GetCurrentThreadId() ) )
1411       return E_FAIL;
1412
1413     /* Remove the menu descriptor property from the frame window */
1414     RemovePropA( hwndFrame, "PROP_OLEMenuDescriptor" );
1415   }
1416
1417   return S_OK;
1418 }
1419
1420 /******************************************************************************
1421  *              IsAccelerator        [OLE32.@]
1422  * Mostly copied from controls/menu.c TranslateAccelerator implementation
1423  */
1424 BOOL WINAPI IsAccelerator(HACCEL hAccel, int cAccelEntries, LPMSG lpMsg, WORD* lpwCmd)
1425 {
1426     LPACCEL lpAccelTbl;
1427     int i;
1428
1429     if(!lpMsg) return FALSE;
1430     if (!hAccel)
1431     {
1432         WARN_(accel)("NULL accel handle\n");
1433         return FALSE;
1434     }
1435     if((lpMsg->message != WM_KEYDOWN &&
1436         lpMsg->message != WM_KEYUP &&
1437         lpMsg->message != WM_SYSKEYDOWN &&
1438         lpMsg->message != WM_SYSKEYUP &&
1439         lpMsg->message != WM_CHAR)) return FALSE;
1440     lpAccelTbl = HeapAlloc(GetProcessHeap(), 0, cAccelEntries * sizeof(ACCEL));
1441     if (NULL == lpAccelTbl)
1442     {
1443         return FALSE;
1444     }
1445     if (CopyAcceleratorTableW(hAccel, lpAccelTbl, cAccelEntries) != cAccelEntries)
1446     {
1447         WARN_(accel)("CopyAcceleratorTableW failed\n");
1448         HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1449         return FALSE;
1450     }
1451
1452     TRACE_(accel)("hAccel=%p, cAccelEntries=%d,"
1453                 "msg->hwnd=%p, msg->message=%04x, wParam=%08x, lParam=%08lx\n",
1454                 hAccel, cAccelEntries,
1455                 lpMsg->hwnd, lpMsg->message, lpMsg->wParam, lpMsg->lParam);
1456     for(i = 0; i < cAccelEntries; i++)
1457     {
1458         if(lpAccelTbl[i].key != lpMsg->wParam)
1459             continue;
1460
1461         if(lpMsg->message == WM_CHAR)
1462         {
1463             if(!(lpAccelTbl[i].fVirt & FALT) && !(lpAccelTbl[i].fVirt & FVIRTKEY))
1464             {
1465                 TRACE_(accel)("found accel for WM_CHAR: ('%c')\n", lpMsg->wParam & 0xff);
1466                 goto found;
1467             }
1468         }
1469         else
1470         {
1471             if(lpAccelTbl[i].fVirt & FVIRTKEY)
1472             {
1473                 INT mask = 0;
1474                 TRACE_(accel)("found accel for virt_key %04x (scan %04x)\n",
1475                                 lpMsg->wParam, HIWORD(lpMsg->lParam) & 0xff);
1476                 if(GetKeyState(VK_SHIFT) & 0x8000) mask |= FSHIFT;
1477                 if(GetKeyState(VK_CONTROL) & 0x8000) mask |= FCONTROL;
1478                 if(GetKeyState(VK_MENU) & 0x8000) mask |= FALT;
1479                 if(mask == (lpAccelTbl[i].fVirt & (FSHIFT | FCONTROL | FALT))) goto found;
1480                 TRACE_(accel)("incorrect SHIFT/CTRL/ALT-state\n");
1481             }
1482             else
1483             {
1484                 if(!(lpMsg->lParam & 0x01000000))  /* no special_key */
1485                 {
1486                     if((lpAccelTbl[i].fVirt & FALT) && (lpMsg->lParam & 0x20000000))
1487                     {                                                  /* ^^ ALT pressed */
1488                         TRACE_(accel)("found accel for Alt-%c\n", lpMsg->wParam & 0xff);
1489                         goto found;
1490                     }
1491                 }
1492             }
1493         }
1494     }
1495
1496     WARN_(accel)("couldn't translate accelerator key\n");
1497     HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1498     return FALSE;
1499
1500 found:
1501     if(lpwCmd) *lpwCmd = lpAccelTbl[i].cmd;
1502     HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1503     return TRUE;
1504 }
1505
1506 /***********************************************************************
1507  * ReleaseStgMedium [OLE32.@]
1508  */
1509 void WINAPI ReleaseStgMedium(
1510   STGMEDIUM* pmedium)
1511 {
1512   switch (pmedium->tymed)
1513   {
1514     case TYMED_HGLOBAL:
1515     {
1516       if ( (pmedium->pUnkForRelease==0) &&
1517            (pmedium->u.hGlobal!=0) )
1518         GlobalFree(pmedium->u.hGlobal);
1519       break;
1520     }
1521     case TYMED_FILE:
1522     {
1523       if (pmedium->u.lpszFileName!=0)
1524       {
1525         if (pmedium->pUnkForRelease==0)
1526         {
1527           DeleteFileW(pmedium->u.lpszFileName);
1528         }
1529
1530         CoTaskMemFree(pmedium->u.lpszFileName);
1531       }
1532       break;
1533     }
1534     case TYMED_ISTREAM:
1535     {
1536       if (pmedium->u.pstm!=0)
1537       {
1538         IStream_Release(pmedium->u.pstm);
1539       }
1540       break;
1541     }
1542     case TYMED_ISTORAGE:
1543     {
1544       if (pmedium->u.pstg!=0)
1545       {
1546         IStorage_Release(pmedium->u.pstg);
1547       }
1548       break;
1549     }
1550     case TYMED_GDI:
1551     {
1552       if ( (pmedium->pUnkForRelease==0) &&
1553            (pmedium->u.hBitmap!=0) )
1554         DeleteObject(pmedium->u.hBitmap);
1555       break;
1556     }
1557     case TYMED_MFPICT:
1558     {
1559       if ( (pmedium->pUnkForRelease==0) &&
1560            (pmedium->u.hMetaFilePict!=0) )
1561       {
1562         LPMETAFILEPICT pMP = GlobalLock(pmedium->u.hMetaFilePict);
1563         DeleteMetaFile(pMP->hMF);
1564         GlobalUnlock(pmedium->u.hMetaFilePict);
1565         GlobalFree(pmedium->u.hMetaFilePict);
1566       }
1567       break;
1568     }
1569     case TYMED_ENHMF:
1570     {
1571       if ( (pmedium->pUnkForRelease==0) &&
1572            (pmedium->u.hEnhMetaFile!=0) )
1573       {
1574         DeleteEnhMetaFile(pmedium->u.hEnhMetaFile);
1575       }
1576       break;
1577     }
1578     case TYMED_NULL:
1579     default:
1580       break;
1581   }
1582   pmedium->tymed=TYMED_NULL;
1583
1584   /*
1585    * After cleaning up, the unknown is released
1586    */
1587   if (pmedium->pUnkForRelease!=0)
1588   {
1589     IUnknown_Release(pmedium->pUnkForRelease);
1590     pmedium->pUnkForRelease = 0;
1591   }
1592 }
1593
1594 /***
1595  * OLEDD_Initialize()
1596  *
1597  * Initializes the OLE drag and drop data structures.
1598  */
1599 static void OLEDD_Initialize()
1600 {
1601     WNDCLASSA wndClass;
1602
1603     ZeroMemory (&wndClass, sizeof(WNDCLASSA));
1604     wndClass.style         = CS_GLOBALCLASS;
1605     wndClass.lpfnWndProc   = (WNDPROC)OLEDD_DragTrackerWindowProc;
1606     wndClass.cbClsExtra    = 0;
1607     wndClass.cbWndExtra    = sizeof(TrackerWindowInfo*);
1608     wndClass.hCursor       = 0;
1609     wndClass.hbrBackground = 0;
1610     wndClass.lpszClassName = OLEDD_DRAGTRACKERCLASS;
1611
1612     RegisterClassA (&wndClass);
1613 }
1614
1615 /***
1616  * OLEDD_UnInitialize()
1617  *
1618  * Releases the OLE drag and drop data structures.
1619  */
1620 static void OLEDD_UnInitialize()
1621 {
1622   /*
1623    * Simply empty the list.
1624    */
1625   while (targetListHead!=NULL)
1626   {
1627     RevokeDragDrop(targetListHead->hwndTarget);
1628   }
1629 }
1630
1631 /***
1632  * OLEDD_InsertDropTarget()
1633  *
1634  * Insert the target node in the tree.
1635  */
1636 static void OLEDD_InsertDropTarget(DropTargetNode* nodeToAdd)
1637 {
1638   DropTargetNode*  curNode;
1639   DropTargetNode** parentNodeLink;
1640
1641   /*
1642    * Iterate the tree to find the insertion point.
1643    */
1644   curNode        = targetListHead;
1645   parentNodeLink = &targetListHead;
1646
1647   while (curNode!=NULL)
1648   {
1649     if (nodeToAdd->hwndTarget<curNode->hwndTarget)
1650     {
1651       /*
1652        * If the node we want to add has a smaller HWND, go left
1653        */
1654       parentNodeLink = &curNode->prevDropTarget;
1655       curNode        =  curNode->prevDropTarget;
1656     }
1657     else if (nodeToAdd->hwndTarget>curNode->hwndTarget)
1658     {
1659       /*
1660        * If the node we want to add has a larger HWND, go right
1661        */
1662       parentNodeLink = &curNode->nextDropTarget;
1663       curNode        =  curNode->nextDropTarget;
1664     }
1665     else
1666     {
1667       /*
1668        * The item was found in the list. It shouldn't have been there
1669        */
1670       assert(FALSE);
1671       return;
1672     }
1673   }
1674
1675   /*
1676    * If we get here, we have found a spot for our item. The parentNodeLink
1677    * pointer points to the pointer that we have to modify.
1678    * The curNode should be NULL. We just have to establish the link and Voila!
1679    */
1680   assert(curNode==NULL);
1681   assert(parentNodeLink!=NULL);
1682   assert(*parentNodeLink==NULL);
1683
1684   *parentNodeLink=nodeToAdd;
1685 }
1686
1687 /***
1688  * OLEDD_ExtractDropTarget()
1689  *
1690  * Removes the target node from the tree.
1691  */
1692 static DropTargetNode* OLEDD_ExtractDropTarget(HWND hwndOfTarget)
1693 {
1694   DropTargetNode*  curNode;
1695   DropTargetNode** parentNodeLink;
1696
1697   /*
1698    * Iterate the tree to find the insertion point.
1699    */
1700   curNode        = targetListHead;
1701   parentNodeLink = &targetListHead;
1702
1703   while (curNode!=NULL)
1704   {
1705     if (hwndOfTarget<curNode->hwndTarget)
1706     {
1707       /*
1708        * If the node we want to add has a smaller HWND, go left
1709        */
1710       parentNodeLink = &curNode->prevDropTarget;
1711       curNode        =  curNode->prevDropTarget;
1712     }
1713     else if (hwndOfTarget>curNode->hwndTarget)
1714     {
1715       /*
1716        * If the node we want to add has a larger HWND, go right
1717        */
1718       parentNodeLink = &curNode->nextDropTarget;
1719       curNode        =  curNode->nextDropTarget;
1720     }
1721     else
1722     {
1723       /*
1724        * The item was found in the list. Detach it from it's parent and
1725        * re-insert it's kids in the tree.
1726        */
1727       assert(parentNodeLink!=NULL);
1728       assert(*parentNodeLink==curNode);
1729
1730       /*
1731        * We arbitrately re-attach the left sub-tree to the parent.
1732        */
1733       *parentNodeLink = curNode->prevDropTarget;
1734
1735       /*
1736        * And we re-insert the right subtree
1737        */
1738       if (curNode->nextDropTarget!=NULL)
1739       {
1740         OLEDD_InsertDropTarget(curNode->nextDropTarget);
1741       }
1742
1743       /*
1744        * The node we found is still a valid node once we complete
1745        * the unlinking of the kids.
1746        */
1747       curNode->nextDropTarget=NULL;
1748       curNode->prevDropTarget=NULL;
1749
1750       return curNode;
1751     }
1752   }
1753
1754   /*
1755    * If we get here, the node is not in the tree
1756    */
1757   return NULL;
1758 }
1759
1760 /***
1761  * OLEDD_FindDropTarget()
1762  *
1763  * Finds information about the drop target.
1764  */
1765 static DropTargetNode* OLEDD_FindDropTarget(HWND hwndOfTarget)
1766 {
1767   DropTargetNode*  curNode;
1768
1769   /*
1770    * Iterate the tree to find the HWND value.
1771    */
1772   curNode        = targetListHead;
1773
1774   while (curNode!=NULL)
1775   {
1776     if (hwndOfTarget<curNode->hwndTarget)
1777     {
1778       /*
1779        * If the node we want to add has a smaller HWND, go left
1780        */
1781       curNode =  curNode->prevDropTarget;
1782     }
1783     else if (hwndOfTarget>curNode->hwndTarget)
1784     {
1785       /*
1786        * If the node we want to add has a larger HWND, go right
1787        */
1788       curNode =  curNode->nextDropTarget;
1789     }
1790     else
1791     {
1792       /*
1793        * The item was found in the list.
1794        */
1795       return curNode;
1796     }
1797   }
1798
1799   /*
1800    * If we get here, the item is not in the list
1801    */
1802   return NULL;
1803 }
1804
1805 /***
1806  * OLEDD_DragTrackerWindowProc()
1807  *
1808  * This method is the WindowProcedure of the drag n drop tracking
1809  * window. During a drag n Drop operation, an invisible window is created
1810  * to receive the user input and act upon it. This procedure is in charge
1811  * of this behavior.
1812  */
1813 static LRESULT WINAPI OLEDD_DragTrackerWindowProc(
1814                          HWND   hwnd,
1815                          UINT   uMsg,
1816                          WPARAM wParam,
1817                          LPARAM   lParam)
1818 {
1819   switch (uMsg)
1820   {
1821     case WM_CREATE:
1822     {
1823       LPCREATESTRUCTA createStruct = (LPCREATESTRUCTA)lParam;
1824
1825       SetWindowLongA(hwnd, 0, (LONG)createStruct->lpCreateParams);
1826
1827
1828       break;
1829     }
1830     case WM_MOUSEMOVE:
1831     {
1832       TrackerWindowInfo* trackerInfo = (TrackerWindowInfo*)GetWindowLongA(hwnd, 0);
1833       POINT            mousePos;
1834
1835       /*
1836        * Get the current mouse position in screen coordinates.
1837        */
1838       mousePos.x = LOWORD(lParam);
1839       mousePos.y = HIWORD(lParam);
1840       ClientToScreen(hwnd, &mousePos);
1841
1842       /*
1843        * Track the movement of the mouse.
1844        */
1845       OLEDD_TrackMouseMove(trackerInfo, mousePos, wParam);
1846
1847       break;
1848     }
1849     case WM_LBUTTONUP:
1850     case WM_MBUTTONUP:
1851     case WM_RBUTTONUP:
1852     case WM_LBUTTONDOWN:
1853     case WM_MBUTTONDOWN:
1854     case WM_RBUTTONDOWN:
1855     {
1856       TrackerWindowInfo* trackerInfo = (TrackerWindowInfo*)GetWindowLongA(hwnd, 0);
1857       POINT            mousePos;
1858
1859       /*
1860        * Get the current mouse position in screen coordinates.
1861        */
1862       mousePos.x = LOWORD(lParam);
1863       mousePos.y = HIWORD(lParam);
1864       ClientToScreen(hwnd, &mousePos);
1865
1866       /*
1867        * Notify everyone that the button state changed
1868        * TODO: Check if the "escape" key was pressed.
1869        */
1870       OLEDD_TrackStateChange(trackerInfo, mousePos, wParam);
1871
1872       break;
1873     }
1874   }
1875
1876   /*
1877    * This is a window proc after all. Let's call the default.
1878    */
1879   return DefWindowProcA (hwnd, uMsg, wParam, lParam);
1880 }
1881
1882 /***
1883  * OLEDD_TrackMouseMove()
1884  *
1885  * This method is invoked while a drag and drop operation is in effect.
1886  * it will generate the appropriate callbacks in the drop source
1887  * and drop target. It will also provide the expected feedback to
1888  * the user.
1889  *
1890  * params:
1891  *    trackerInfo - Pointer to the structure identifying the
1892  *                  drag & drop operation that is currently
1893  *                  active.
1894  *    mousePos    - Current position of the mouse in screen
1895  *                  coordinates.
1896  *    keyState    - Contains the state of the shift keys and the
1897  *                  mouse buttons (MK_LBUTTON and the like)
1898  */
1899 static void OLEDD_TrackMouseMove(
1900   TrackerWindowInfo* trackerInfo,
1901   POINT            mousePos,
1902   DWORD              keyState)
1903 {
1904   HWND   hwndNewTarget = 0;
1905   HRESULT  hr = S_OK;
1906
1907   /*
1908    * Get the handle of the window under the mouse
1909    */
1910   hwndNewTarget = WindowFromPoint(mousePos);
1911
1912   /*
1913    * Every time, we re-initialize the effects passed to the
1914    * IDropTarget to the effects allowed by the source.
1915    */
1916   *trackerInfo->pdwEffect = trackerInfo->dwOKEffect;
1917
1918   /*
1919    * If we are hovering over the same target as before, send the
1920    * DragOver notification
1921    */
1922   if ( (trackerInfo->curDragTarget != 0) &&
1923        (trackerInfo->curTargetHWND == hwndNewTarget) )
1924   {
1925     POINTL  mousePosParam;
1926
1927     /*
1928      * The documentation tells me that the coordinate should be in the target
1929      * window's coordinate space. However, the tests I made tell me the
1930      * coordinates should be in screen coordinates.
1931      */
1932     mousePosParam.x = mousePos.x;
1933     mousePosParam.y = mousePos.y;
1934
1935     IDropTarget_DragOver(trackerInfo->curDragTarget,
1936                          keyState,
1937                          mousePosParam,
1938                          trackerInfo->pdwEffect);
1939   }
1940   else
1941   {
1942     DropTargetNode* newDropTargetNode = 0;
1943
1944     /*
1945      * If we changed window, we have to notify our old target and check for
1946      * the new one.
1947      */
1948     if (trackerInfo->curDragTarget!=0)
1949     {
1950       IDropTarget_DragLeave(trackerInfo->curDragTarget);
1951     }
1952
1953     /*
1954      * Make sure we're hovering over a window.
1955      */
1956     if (hwndNewTarget!=0)
1957     {
1958       /*
1959        * Find-out if there is a drag target under the mouse
1960        */
1961       HWND nexttar = hwndNewTarget;
1962       trackerInfo->curTargetHWND = hwndNewTarget;
1963
1964       do {
1965         newDropTargetNode = OLEDD_FindDropTarget(nexttar);
1966       } while (!newDropTargetNode && (nexttar = GetParent(nexttar)) != 0);
1967       if(nexttar) hwndNewTarget = nexttar;
1968
1969       trackerInfo->curDragTargetHWND = hwndNewTarget;
1970       trackerInfo->curDragTarget     = newDropTargetNode ? newDropTargetNode->dropTarget : 0;
1971
1972       /*
1973        * If there is, notify it that we just dragged-in
1974        */
1975       if (trackerInfo->curDragTarget!=0)
1976       {
1977         POINTL  mousePosParam;
1978
1979         /*
1980          * The documentation tells me that the coordinate should be in the target
1981          * window's coordinate space. However, the tests I made tell me the
1982          * coordinates should be in screen coordinates.
1983          */
1984         mousePosParam.x = mousePos.x;
1985         mousePosParam.y = mousePos.y;
1986
1987         IDropTarget_DragEnter(trackerInfo->curDragTarget,
1988                               trackerInfo->dataObject,
1989                               keyState,
1990                               mousePosParam,
1991                               trackerInfo->pdwEffect);
1992       }
1993     }
1994     else
1995     {
1996       /*
1997        * The mouse is not over a window so we don't track anything.
1998        */
1999       trackerInfo->curDragTargetHWND = 0;
2000       trackerInfo->curTargetHWND     = 0;
2001       trackerInfo->curDragTarget     = 0;
2002     }
2003   }
2004
2005   /*
2006    * Now that we have done that, we have to tell the source to give
2007    * us feedback on the work being done by the target.  If we don't
2008    * have a target, simulate no effect.
2009    */
2010   if (trackerInfo->curDragTarget==0)
2011   {
2012     *trackerInfo->pdwEffect = DROPEFFECT_NONE;
2013   }
2014
2015   hr = IDropSource_GiveFeedback(trackerInfo->dropSource,
2016                                 *trackerInfo->pdwEffect);
2017
2018   /*
2019    * When we ask for feedback from the drop source, sometimes it will
2020    * do all the necessary work and sometimes it will not handle it
2021    * when that's the case, we must display the standard drag and drop
2022    * cursors.
2023    */
2024   if (hr==DRAGDROP_S_USEDEFAULTCURSORS)
2025   {
2026     if (*trackerInfo->pdwEffect & DROPEFFECT_MOVE)
2027     {
2028       SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(1)));
2029     }
2030     else if (*trackerInfo->pdwEffect & DROPEFFECT_COPY)
2031     {
2032       SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(2)));
2033     }
2034     else if (*trackerInfo->pdwEffect & DROPEFFECT_LINK)
2035     {
2036       SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(3)));
2037     }
2038     else
2039     {
2040       SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(0)));
2041     }
2042   }
2043 }
2044
2045 /***
2046  * OLEDD_TrackStateChange()
2047  *
2048  * This method is invoked while a drag and drop operation is in effect.
2049  * It is used to notify the drop target/drop source callbacks when
2050  * the state of the keyboard or mouse button change.
2051  *
2052  * params:
2053  *    trackerInfo - Pointer to the structure identifying the
2054  *                  drag & drop operation that is currently
2055  *                  active.
2056  *    mousePos    - Current position of the mouse in screen
2057  *                  coordinates.
2058  *    keyState    - Contains the state of the shift keys and the
2059  *                  mouse buttons (MK_LBUTTON and the like)
2060  */
2061 static void OLEDD_TrackStateChange(
2062   TrackerWindowInfo* trackerInfo,
2063   POINT            mousePos,
2064   DWORD              keyState)
2065 {
2066   /*
2067    * Ask the drop source what to do with the operation.
2068    */
2069   trackerInfo->returnValue = IDropSource_QueryContinueDrag(
2070                                trackerInfo->dropSource,
2071                                trackerInfo->escPressed,
2072                                keyState);
2073
2074   /*
2075    * All the return valued will stop the operation except the S_OK
2076    * return value.
2077    */
2078   if (trackerInfo->returnValue!=S_OK)
2079   {
2080     /*
2081      * Make sure the message loop in DoDragDrop stops
2082      */
2083     trackerInfo->trackingDone = TRUE;
2084
2085     /*
2086      * Release the mouse in case the drop target decides to show a popup
2087      * or a menu or something.
2088      */
2089     ReleaseCapture();
2090
2091     /*
2092      * If we end-up over a target, drop the object in the target or
2093      * inform the target that the operation was cancelled.
2094      */
2095     if (trackerInfo->curDragTarget!=0)
2096     {
2097       switch (trackerInfo->returnValue)
2098       {
2099         /*
2100          * If the source wants us to complete the operation, we tell
2101          * the drop target that we just dropped the object in it.
2102          */
2103         case DRAGDROP_S_DROP:
2104         {
2105           POINTL  mousePosParam;
2106
2107           /*
2108            * The documentation tells me that the coordinate should be
2109            * in the target window's coordinate space. However, the tests
2110            * I made tell me the coordinates should be in screen coordinates.
2111            */
2112           mousePosParam.x = mousePos.x;
2113           mousePosParam.y = mousePos.y;
2114
2115           IDropTarget_Drop(trackerInfo->curDragTarget,
2116                            trackerInfo->dataObject,
2117                            keyState,
2118                            mousePosParam,
2119                            trackerInfo->pdwEffect);
2120           break;
2121         }
2122         /*
2123          * If the source told us that we should cancel, fool the drop
2124          * target by telling it that the mouse left it's window.
2125          * Also set the drop effect to "NONE" in case the application
2126          * ignores the result of DoDragDrop.
2127          */
2128         case DRAGDROP_S_CANCEL:
2129           IDropTarget_DragLeave(trackerInfo->curDragTarget);
2130           *trackerInfo->pdwEffect = DROPEFFECT_NONE;
2131           break;
2132       }
2133     }
2134   }
2135 }
2136
2137 /***
2138  * OLEDD_GetButtonState()
2139  *
2140  * This method will use the current state of the keyboard to build
2141  * a button state mask equivalent to the one passed in the
2142  * WM_MOUSEMOVE wParam.
2143  */
2144 static DWORD OLEDD_GetButtonState()
2145 {
2146   BYTE  keyboardState[256];
2147   DWORD keyMask = 0;
2148
2149   GetKeyboardState(keyboardState);
2150
2151   if ( (keyboardState[VK_SHIFT] & 0x80) !=0)
2152     keyMask |= MK_SHIFT;
2153
2154   if ( (keyboardState[VK_CONTROL] & 0x80) !=0)
2155     keyMask |= MK_CONTROL;
2156
2157   if ( (keyboardState[VK_LBUTTON] & 0x80) !=0)
2158     keyMask |= MK_LBUTTON;
2159
2160   if ( (keyboardState[VK_RBUTTON] & 0x80) !=0)
2161     keyMask |= MK_RBUTTON;
2162
2163   if ( (keyboardState[VK_MBUTTON] & 0x80) !=0)
2164     keyMask |= MK_MBUTTON;
2165
2166   return keyMask;
2167 }
2168
2169 /***
2170  * OLEDD_GetButtonState()
2171  *
2172  * This method will read the default value of the registry key in
2173  * parameter and extract a DWORD value from it. The registry key value
2174  * can be in a string key or a DWORD key.
2175  *
2176  * params:
2177  *     regKey   - Key to read the default value from
2178  *     pdwValue - Pointer to the location where the DWORD
2179  *                value is returned. This value is not modified
2180  *                if the value is not found.
2181  */
2182
2183 static void OLEUTL_ReadRegistryDWORDValue(
2184   HKEY   regKey,
2185   DWORD* pdwValue)
2186 {
2187   char  buffer[20];
2188   DWORD dwKeyType;
2189   DWORD cbData = 20;
2190   LONG  lres;
2191
2192   lres = RegQueryValueExA(regKey,
2193                           "",
2194                           NULL,
2195                           &dwKeyType,
2196                           (LPBYTE)buffer,
2197                           &cbData);
2198
2199   if (lres==ERROR_SUCCESS)
2200   {
2201     switch (dwKeyType)
2202     {
2203       case REG_DWORD:
2204         *pdwValue = *(DWORD*)buffer;
2205         break;
2206       case REG_EXPAND_SZ:
2207       case REG_MULTI_SZ:
2208       case REG_SZ:
2209         *pdwValue = (DWORD)strtoul(buffer, NULL, 10);
2210         break;
2211     }
2212   }
2213 }
2214
2215 /******************************************************************************
2216  * OleDraw (OLE32.@)
2217  *
2218  * The operation of this function is documented literally in the WinAPI
2219  * documentation to involve a QueryInterface for the IViewObject interface,
2220  * followed by a call to IViewObject::Draw.
2221  */
2222 HRESULT WINAPI OleDraw(
2223         IUnknown *pUnk,
2224         DWORD dwAspect,
2225         HDC hdcDraw,
2226         LPCRECT lprcBounds)
2227 {
2228   HRESULT hres;
2229   IViewObject *viewobject;
2230
2231   hres = IUnknown_QueryInterface(pUnk,
2232                                  &IID_IViewObject,
2233                                  (void**)&viewobject);
2234
2235   if (SUCCEEDED(hres))
2236   {
2237     RECTL rectl;
2238
2239     rectl.left = lprcBounds->left;
2240     rectl.right = lprcBounds->right;
2241     rectl.top = lprcBounds->top;
2242     rectl.bottom = lprcBounds->bottom;
2243     hres = IViewObject_Draw(viewobject, dwAspect, -1, 0, 0, 0, hdcDraw, &rectl, 0, 0, 0);
2244
2245     IViewObject_Release(viewobject);
2246     return hres;
2247   }
2248   else
2249   {
2250     return DV_E_NOIVIEWOBJECT;
2251   }
2252 }
2253
2254 /***********************************************************************
2255  *             OleTranslateAccelerator [OLE32.@]
2256  */
2257 HRESULT WINAPI OleTranslateAccelerator (LPOLEINPLACEFRAME lpFrame,
2258                    LPOLEINPLACEFRAMEINFO lpFrameInfo, LPMSG lpmsg)
2259 {
2260     WORD wID;
2261
2262     TRACE("(%p,%p,%p)\n", lpFrame, lpFrameInfo, lpmsg);
2263
2264     if (IsAccelerator(lpFrameInfo->haccel,lpFrameInfo->cAccelEntries,lpmsg,&wID))
2265         return IOleInPlaceFrame_TranslateAccelerator(lpFrame,lpmsg,wID);
2266
2267     return S_FALSE;
2268 }
2269
2270 /******************************************************************************
2271  *              OleCreate        [OLE32.@]
2272  *
2273  */
2274 HRESULT WINAPI OleCreate(
2275         REFCLSID rclsid,
2276         REFIID riid,
2277         DWORD renderopt,
2278         LPFORMATETC pFormatEtc,
2279         LPOLECLIENTSITE pClientSite,
2280         LPSTORAGE pStg,
2281         LPVOID* ppvObj)
2282 {
2283     HRESULT hres, hres1;
2284     IUnknown * pUnk = NULL;
2285
2286     FIXME("\n\t%s\n\t%s semi-stub!\n", debugstr_guid(rclsid), debugstr_guid(riid));
2287
2288     if (SUCCEEDED((hres = CoCreateInstance(rclsid, 0, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER|CLSCTX_LOCAL_SERVER , riid, (LPVOID*)&pUnk))))
2289     {
2290         if (pClientSite)
2291         {
2292             IOleObject * pOE;
2293             IPersistStorage * pPS;
2294             if (SUCCEEDED((hres = IUnknown_QueryInterface( pUnk, &IID_IOleObject, (LPVOID*)&pOE))))
2295             {
2296                 TRACE("trying to set clientsite %p\n", pClientSite);
2297                 hres1 = IOleObject_SetClientSite(pOE, pClientSite);
2298                 TRACE("-- result 0x%08lx\n", hres1);
2299                 IOleObject_Release(pOE);
2300             }
2301             if (SUCCEEDED((hres = IUnknown_QueryInterface( pUnk, &IID_IPersistStorage, (LPVOID*)&pPS))))
2302             {
2303                 TRACE("trying to set stg %p\n", pStg);
2304                 hres1 = IPersistStorage_InitNew(pPS, pStg);
2305                 TRACE("-- result 0x%08lx\n", hres1);
2306                 IPersistStorage_Release(pPS);
2307             }
2308         }
2309     }
2310
2311     *ppvObj = pUnk;
2312
2313     TRACE("-- %p \n", pUnk);
2314     return hres;
2315 }
2316
2317 /***********************************************************************
2318  *           OLE_FreeClipDataArray   [internal]
2319  *
2320  * NOTES:
2321  *  frees the data associated with an array of CLIPDATAs
2322  */
2323 static void OLE_FreeClipDataArray(ULONG count, CLIPDATA * pClipDataArray)
2324 {
2325     ULONG i;
2326     for (i = 0; i < count; i++)
2327         if (pClipDataArray[i].pClipData)
2328             CoTaskMemFree(pClipDataArray[i].pClipData);
2329 }
2330
2331 /******************************************************************************
2332  * Check if a PROPVARIANT's type is valid.
2333  */
2334 static inline HRESULT PROPVARIANT_ValidateType(VARTYPE vt)
2335 {
2336     switch (vt)
2337     {
2338     case VT_EMPTY:
2339     case VT_NULL:
2340     case VT_I2:
2341     case VT_I4:
2342     case VT_R4:
2343     case VT_R8:
2344     case VT_CY:
2345     case VT_DATE:
2346     case VT_BSTR:
2347     case VT_ERROR:
2348     case VT_BOOL:
2349     case VT_UI1:
2350     case VT_UI2:
2351     case VT_UI4:
2352     case VT_I8:
2353     case VT_UI8:
2354     case VT_LPSTR:
2355     case VT_LPWSTR:
2356     case VT_FILETIME:
2357     case VT_BLOB:
2358     case VT_STREAM:
2359     case VT_STORAGE:
2360     case VT_STREAMED_OBJECT:
2361     case VT_STORED_OBJECT:
2362     case VT_BLOB_OBJECT:
2363     case VT_CF:
2364     case VT_CLSID:
2365     case VT_I2|VT_VECTOR:
2366     case VT_I4|VT_VECTOR:
2367     case VT_R4|VT_VECTOR:
2368     case VT_R8|VT_VECTOR:
2369     case VT_CY|VT_VECTOR:
2370     case VT_DATE|VT_VECTOR:
2371     case VT_BSTR|VT_VECTOR:
2372     case VT_ERROR|VT_VECTOR:
2373     case VT_BOOL|VT_VECTOR:
2374     case VT_VARIANT|VT_VECTOR:
2375     case VT_UI1|VT_VECTOR:
2376     case VT_UI2|VT_VECTOR:
2377     case VT_UI4|VT_VECTOR:
2378     case VT_I8|VT_VECTOR:
2379     case VT_UI8|VT_VECTOR:
2380     case VT_LPSTR|VT_VECTOR:
2381     case VT_LPWSTR|VT_VECTOR:
2382     case VT_FILETIME|VT_VECTOR:
2383     case VT_CF|VT_VECTOR:
2384     case VT_CLSID|VT_VECTOR:
2385         return S_OK;
2386     }
2387     WARN("Bad type %d\n", vt);
2388     return STG_E_INVALIDPARAMETER;
2389 }
2390
2391 /***********************************************************************
2392  *           PropVariantClear                       [OLE32.@]
2393  */
2394 HRESULT WINAPI PropVariantClear(PROPVARIANT * pvar) /* [in/out] */
2395 {
2396     HRESULT hr;
2397
2398     TRACE("(%p)\n", pvar);
2399
2400     if (!pvar)
2401         return S_OK;
2402
2403     hr = PROPVARIANT_ValidateType(pvar->vt);
2404     if (FAILED(hr))
2405         return hr;
2406
2407     switch(pvar->vt)
2408     {
2409     case VT_STREAM:
2410     case VT_STREAMED_OBJECT:
2411     case VT_STORAGE:
2412     case VT_STORED_OBJECT:
2413         if (pvar->u.pStream)
2414             IUnknown_Release(pvar->u.pStream);
2415         break;
2416     case VT_CLSID:
2417     case VT_LPSTR:
2418     case VT_LPWSTR:
2419         /* pick an arbitary typed pointer - we don't care about the type
2420          * as we are just freeing it */
2421         CoTaskMemFree(pvar->u.puuid);
2422         break;
2423     case VT_BLOB:
2424     case VT_BLOB_OBJECT:
2425         CoTaskMemFree(pvar->u.blob.pBlobData);
2426         break;
2427     case VT_BSTR:
2428         if (pvar->u.bstrVal)
2429         {
2430             FIXME("Need to load OLEAUT32 for SysFreeString\n");
2431             /* SysFreeString(pvar->u.bstrVal); */
2432         }
2433         break;
2434    case VT_CF:
2435         if (pvar->u.pclipdata)
2436         {
2437             OLE_FreeClipDataArray(1, pvar->u.pclipdata);
2438             CoTaskMemFree(pvar->u.pclipdata);
2439         }
2440         break;
2441     default:
2442         switch (pvar->vt & ~VT_VECTOR)
2443         {
2444         case VT_VARIANT:
2445             FreePropVariantArray(pvar->u.capropvar.cElems, pvar->u.capropvar.pElems);
2446             break;
2447         case VT_CF:
2448             OLE_FreeClipDataArray(pvar->u.caclipdata.cElems, pvar->u.caclipdata.pElems);
2449             break;
2450         case VT_BSTR:
2451         case VT_LPSTR:
2452         case VT_LPWSTR:
2453         case VT_CLSID:
2454             FIXME("Freeing of vector sub-type not supported yet\n");
2455         }
2456         if (pvar->vt & ~VT_VECTOR)
2457         {
2458             /* pick an arbitary VT_VECTOR structure - they all have the same
2459              * memory layout */
2460             CoTaskMemFree(pvar->u.capropvar.pElems);
2461         }
2462     }
2463
2464     ZeroMemory(pvar, sizeof(*pvar));
2465
2466     return S_OK;
2467 }
2468
2469 /***********************************************************************
2470  *           PropVariantCopy                        [OLE32.@]
2471  */
2472 HRESULT WINAPI PropVariantCopy(PROPVARIANT *pvarDest,      /* [out] */
2473                                const PROPVARIANT *pvarSrc) /* [in] */
2474 {
2475     ULONG len;
2476     HRESULT hr;
2477
2478     TRACE("(%p, %p)\n", pvarDest, pvarSrc);
2479
2480     hr = PROPVARIANT_ValidateType(pvarSrc->vt);
2481     if (FAILED(hr))
2482         return hr;
2483
2484     /* this will deal with most cases */
2485     CopyMemory(pvarDest, pvarSrc, sizeof(*pvarDest));
2486
2487     switch(pvarSrc->vt)
2488     {
2489     case VT_STREAM:
2490     case VT_STREAMED_OBJECT:
2491     case VT_STORAGE:
2492     case VT_STORED_OBJECT:
2493         IUnknown_AddRef((LPUNKNOWN)pvarDest->u.pStream);
2494         break;
2495     case VT_CLSID:
2496         pvarDest->u.puuid = CoTaskMemAlloc(sizeof(CLSID));
2497         CopyMemory(pvarDest->u.puuid, pvarSrc->u.puuid, sizeof(CLSID));
2498         break;
2499     case VT_LPSTR:
2500         len = strlen(pvarSrc->u.pszVal);
2501         pvarDest->u.pszVal = CoTaskMemAlloc((len+1)*sizeof(CHAR));
2502         CopyMemory(pvarDest->u.pszVal, pvarSrc->u.pszVal, (len+1)*sizeof(CHAR));
2503         break;
2504     case VT_LPWSTR:
2505         len = lstrlenW(pvarSrc->u.pwszVal);
2506         pvarDest->u.pwszVal = CoTaskMemAlloc((len+1)*sizeof(WCHAR));
2507         CopyMemory(pvarDest->u.pwszVal, pvarSrc->u.pwszVal, (len+1)*sizeof(WCHAR));
2508         break;
2509     case VT_BLOB:
2510     case VT_BLOB_OBJECT:
2511         if (pvarSrc->u.blob.pBlobData)
2512         {
2513             len = pvarSrc->u.blob.cbSize;
2514             pvarDest->u.blob.pBlobData = CoTaskMemAlloc(len);
2515             CopyMemory(pvarDest->u.blob.pBlobData, pvarSrc->u.blob.pBlobData, len);
2516         }
2517         break;
2518     case VT_BSTR:
2519         FIXME("Need to copy BSTR\n");
2520         break;
2521     case VT_CF:
2522         if (pvarSrc->u.pclipdata)
2523         {
2524             len = pvarSrc->u.pclipdata->cbSize - sizeof(pvarSrc->u.pclipdata->ulClipFmt);
2525             CoTaskMemAlloc(len);
2526             CopyMemory(pvarDest->u.pclipdata->pClipData, pvarSrc->u.pclipdata->pClipData, len);
2527         }
2528         break;
2529     default:
2530         if (pvarSrc->vt & VT_VECTOR)
2531         {
2532             int elemSize;
2533             switch(pvarSrc->vt & VT_VECTOR)
2534             {
2535             case VT_I1:       elemSize = sizeof(pvarSrc->u.cVal); break;
2536             case VT_UI1:      elemSize = sizeof(pvarSrc->u.bVal); break;
2537             case VT_I2:       elemSize = sizeof(pvarSrc->u.iVal); break;
2538             case VT_UI2:      elemSize = sizeof(pvarSrc->u.uiVal); break;
2539             case VT_BOOL:     elemSize = sizeof(pvarSrc->u.boolVal); break;
2540             case VT_I4:       elemSize = sizeof(pvarSrc->u.lVal); break;
2541             case VT_UI4:      elemSize = sizeof(pvarSrc->u.ulVal); break;
2542             case VT_R4:       elemSize = sizeof(pvarSrc->u.fltVal); break;
2543             case VT_R8:       elemSize = sizeof(pvarSrc->u.dblVal); break;
2544             case VT_ERROR:    elemSize = sizeof(pvarSrc->u.scode); break;
2545             case VT_I8:       elemSize = sizeof(pvarSrc->u.hVal); break;
2546             case VT_UI8:      elemSize = sizeof(pvarSrc->u.uhVal); break;
2547             case VT_CY:       elemSize = sizeof(pvarSrc->u.cyVal); break;
2548             case VT_DATE:     elemSize = sizeof(pvarSrc->u.date); break;
2549             case VT_FILETIME: elemSize = sizeof(pvarSrc->u.filetime); break;
2550             case VT_CLSID:    elemSize = sizeof(*pvarSrc->u.puuid); break;
2551             case VT_CF:       elemSize = sizeof(*pvarSrc->u.pclipdata); break;
2552
2553             case VT_BSTR:
2554             case VT_LPSTR:
2555             case VT_LPWSTR:
2556             case VT_VARIANT:
2557             default:
2558                 FIXME("Invalid element type: %ul\n", pvarSrc->vt & VT_VECTOR);
2559                 return E_INVALIDARG;
2560             }
2561             len = pvarSrc->u.capropvar.cElems;
2562             pvarDest->u.capropvar.pElems = CoTaskMemAlloc(len * elemSize);
2563             if (pvarSrc->vt == (VT_VECTOR | VT_VARIANT))
2564             {
2565                 ULONG i;
2566                 for (i = 0; i < len; i++)
2567                     PropVariantCopy(&pvarDest->u.capropvar.pElems[i], &pvarSrc->u.capropvar.pElems[i]);
2568             }
2569             else if (pvarSrc->vt == (VT_VECTOR | VT_CF))
2570             {
2571                 FIXME("Copy clipformats\n");
2572             }
2573             else if (pvarSrc->vt == (VT_VECTOR | VT_BSTR))
2574             {
2575                 FIXME("Copy BSTRs\n");
2576             }
2577             else if (pvarSrc->vt == (VT_VECTOR | VT_LPSTR))
2578             {
2579                 FIXME("Copy LPSTRs\n");
2580             }
2581             else if (pvarSrc->vt == (VT_VECTOR | VT_LPSTR))
2582             {
2583                 FIXME("Copy LPWSTRs\n");
2584             }
2585             else
2586                 CopyMemory(pvarDest->u.capropvar.pElems, pvarSrc->u.capropvar.pElems, len * elemSize);
2587         }
2588     }
2589
2590     return S_OK;
2591 }
2592
2593 /***********************************************************************
2594  *           FreePropVariantArray                           [OLE32.@]
2595  */
2596 HRESULT WINAPI FreePropVariantArray(ULONG cVariants, /* [in] */
2597                                     PROPVARIANT *rgvars)    /* [in/out] */
2598 {
2599     ULONG i;
2600
2601     TRACE("(%lu, %p)\n", cVariants, rgvars);
2602
2603     for(i = 0; i < cVariants; i++)
2604         PropVariantClear(&rgvars[i]);
2605
2606     return S_OK;
2607 }
2608
2609 /******************************************************************************
2610  * DllDebugObjectRPCHook (OLE32.@)
2611  * turns on and off internal debugging,  pointer is only used on macintosh
2612  */
2613
2614 BOOL WINAPI DllDebugObjectRPCHook(BOOL b, void *dummy)
2615 {
2616   FIXME("stub\n");
2617   return TRUE;
2618 }