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