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