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