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