ole32: Don't release pUnk in OleCreate if CoCreateInstance failed.
[wine/dibdrv.git] / dlls / ole32 / ole2.c
blob151957ccc4012d541809596c444dd7fe951b26b5
1 /*
2 * OLE2 library
4 * Copyright 1995 Martin von Loewis
5 * Copyright 1999 Francis Beaudet
6 * Copyright 1999 Noel Borthwick
7 * Copyright 1999, 2000 Marcus Meissner
8 * Copyright 2005 Juan Lang
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include "config.h"
27 #include <assert.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <string.h>
33 #define COBJMACROS
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "wingdi.h"
41 #include "winuser.h"
42 #include "winnls.h"
43 #include "winreg.h"
44 #include "commctrl.h"
45 #include "ole2.h"
46 #include "ole2ver.h"
47 #include "wownt32.h"
49 #include "wine/unicode.h"
50 #include "compobj_private.h"
51 #include "wine/list.h"
53 #include "wine/debug.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(ole);
56 WINE_DECLARE_DEBUG_CHANNEL(accel);
58 /******************************************************************************
59 * These are static/global variables and internal data structures that the
60 * OLE module uses to maintain it's state.
62 typedef struct tagDropTargetNode
64 HWND hwndTarget;
65 IDropTarget* dropTarget;
66 struct list entry;
67 } DropTargetNode;
69 typedef struct tagTrackerWindowInfo
71 IDataObject* dataObject;
72 IDropSource* dropSource;
73 DWORD dwOKEffect;
74 DWORD* pdwEffect;
75 BOOL trackingDone;
76 HRESULT returnValue;
78 BOOL escPressed;
79 HWND curTargetHWND; /* window the mouse is hovering over */
80 HWND curDragTargetHWND; /* might be a ancestor of curTargetHWND */
81 IDropTarget* curDragTarget;
82 POINTL curMousePos; /* current position of the mouse in screen coordinates */
83 DWORD dwKeyState; /* current state of the shift and ctrl keys and the mouse buttons */
84 } TrackerWindowInfo;
86 typedef struct tagOleMenuDescriptor /* OleMenuDescriptor */
88 HWND hwndFrame; /* The containers frame window */
89 HWND hwndActiveObject; /* The active objects window */
90 OLEMENUGROUPWIDTHS mgw; /* OLE menu group widths for the shared menu */
91 HMENU hmenuCombined; /* The combined menu */
92 BOOL bIsServerItem; /* True if the currently open popup belongs to the server */
93 } OleMenuDescriptor;
95 typedef struct tagOleMenuHookItem /* OleMenu hook item in per thread hook list */
97 DWORD tid; /* Thread Id */
98 HANDLE hHeap; /* Heap this is allocated from */
99 HHOOK GetMsg_hHook; /* message hook for WH_GETMESSAGE */
100 HHOOK CallWndProc_hHook; /* message hook for WH_CALLWNDPROC */
101 struct tagOleMenuHookItem *next;
102 } OleMenuHookItem;
104 static OleMenuHookItem *hook_list;
107 * This is the lock count on the OLE library. It is controlled by the
108 * OLEInitialize/OLEUninitialize methods.
110 static ULONG OLE_moduleLockCount = 0;
113 * Name of our registered window class.
115 static const char OLEDD_DRAGTRACKERCLASS[] = "WineDragDropTracker32";
118 * This is the head of the Drop target container.
120 static struct list targetListHead = LIST_INIT(targetListHead);
122 /******************************************************************************
123 * These are the prototypes of miscelaneous utility methods
125 static void OLEUTL_ReadRegistryDWORDValue(HKEY regKey, DWORD* pdwValue);
127 /******************************************************************************
128 * These are the prototypes of the utility methods used to manage a shared menu
130 static void OLEMenu_Initialize(void);
131 static void OLEMenu_UnInitialize(void);
132 static BOOL OLEMenu_InstallHooks( DWORD tid );
133 static BOOL OLEMenu_UnInstallHooks( DWORD tid );
134 static OleMenuHookItem * OLEMenu_IsHookInstalled( DWORD tid );
135 static BOOL OLEMenu_FindMainMenuIndex( HMENU hMainMenu, HMENU hPopupMenu, UINT *pnPos );
136 static BOOL OLEMenu_SetIsServerMenu( HMENU hmenu, OleMenuDescriptor *pOleMenuDescriptor );
137 static LRESULT CALLBACK OLEMenu_CallWndProc(INT code, WPARAM wParam, LPARAM lParam);
138 static LRESULT CALLBACK OLEMenu_GetMsgProc(INT code, WPARAM wParam, LPARAM lParam);
140 /******************************************************************************
141 * These are the prototypes of the OLE Clipboard initialization methods (in clipboard.c)
143 extern void OLEClipbrd_UnInitialize(void);
144 extern void OLEClipbrd_Initialize(void);
146 /******************************************************************************
147 * These are the prototypes of the utility methods used for OLE Drag n Drop
149 static void OLEDD_Initialize(void);
150 static void OLEDD_UnInitialize(void);
151 static DropTargetNode* OLEDD_FindDropTarget(
152 HWND hwndOfTarget);
153 static void OLEDD_FreeDropTarget(DropTargetNode*);
154 static LRESULT WINAPI OLEDD_DragTrackerWindowProc(
155 HWND hwnd,
156 UINT uMsg,
157 WPARAM wParam,
158 LPARAM lParam);
159 static void OLEDD_TrackMouseMove(
160 TrackerWindowInfo* trackerInfo);
161 static void OLEDD_TrackStateChange(
162 TrackerWindowInfo* trackerInfo);
163 static DWORD OLEDD_GetButtonState(void);
166 /******************************************************************************
167 * OleBuildVersion [OLE2.1]
168 * OleBuildVersion [OLE32.@]
170 DWORD WINAPI OleBuildVersion(void)
172 TRACE("Returning version %d, build %d.\n", rmm, rup);
173 return (rmm<<16)+rup;
176 /***********************************************************************
177 * OleInitialize (OLE2.2)
178 * OleInitialize (OLE32.@)
180 HRESULT WINAPI OleInitialize(LPVOID reserved)
182 HRESULT hr;
184 TRACE("(%p)\n", reserved);
187 * The first duty of the OleInitialize is to initialize the COM libraries.
189 hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
192 * If the CoInitializeEx call failed, the OLE libraries can't be
193 * initialized.
195 if (FAILED(hr))
196 return hr;
199 * Then, it has to initialize the OLE specific modules.
200 * This includes:
201 * Clipboard
202 * Drag and Drop
203 * Object linking and Embedding
204 * In-place activation
206 if (OLE_moduleLockCount==0)
209 * Initialize the libraries.
211 TRACE("() - Initializing the OLE libraries\n");
214 * OLE Clipboard
216 OLEClipbrd_Initialize();
219 * Drag and Drop
221 OLEDD_Initialize();
224 * OLE shared menu
226 OLEMenu_Initialize();
230 * Then, we increase the lock count on the OLE module.
232 OLE_moduleLockCount++;
234 return hr;
237 /******************************************************************************
238 * OleUninitialize [OLE2.3]
239 * OleUninitialize [OLE32.@]
241 void WINAPI OleUninitialize(void)
243 TRACE("()\n");
246 * Decrease the lock count on the OLE module.
248 OLE_moduleLockCount--;
251 * If we hit the bottom of the lock stack, free the libraries.
253 if (OLE_moduleLockCount==0)
256 * Actually free the libraries.
258 TRACE("() - Freeing the last reference count\n");
261 * OLE Clipboard
263 OLEClipbrd_UnInitialize();
266 * Drag and Drop
268 OLEDD_UnInitialize();
271 * OLE shared menu
273 OLEMenu_UnInitialize();
277 * Then, uninitialize the COM libraries.
279 CoUninitialize();
282 /******************************************************************************
283 * OleInitializeWOW [OLE32.@]
285 HRESULT WINAPI OleInitializeWOW(DWORD x, DWORD y) {
286 FIXME("(0x%08x, 0x%08x),stub!\n",x, y);
287 return 0;
290 /***********************************************************************
291 * RegisterDragDrop (OLE32.@)
293 HRESULT WINAPI RegisterDragDrop(
294 HWND hwnd,
295 LPDROPTARGET pDropTarget)
297 DropTargetNode* dropTargetInfo;
299 TRACE("(%p,%p)\n", hwnd, pDropTarget);
301 if (!pDropTarget)
302 return E_INVALIDARG;
305 * First, check if the window is already registered.
307 dropTargetInfo = OLEDD_FindDropTarget(hwnd);
309 if (dropTargetInfo!=NULL)
310 return DRAGDROP_E_ALREADYREGISTERED;
313 * If it's not there, we can add it. We first create a node for it.
315 dropTargetInfo = HeapAlloc(GetProcessHeap(), 0, sizeof(DropTargetNode));
317 if (dropTargetInfo==NULL)
318 return E_OUTOFMEMORY;
320 dropTargetInfo->hwndTarget = hwnd;
323 * Don't forget that this is an interface pointer, need to nail it down since
324 * we keep a copy of it.
326 IDropTarget_AddRef(pDropTarget);
327 dropTargetInfo->dropTarget = pDropTarget;
329 list_add_tail(&targetListHead, &dropTargetInfo->entry);
331 return S_OK;
334 /***********************************************************************
335 * RevokeDragDrop (OLE32.@)
337 HRESULT WINAPI RevokeDragDrop(
338 HWND hwnd)
340 DropTargetNode* dropTargetInfo;
342 TRACE("(%p)\n", hwnd);
345 * First, check if the window is already registered.
347 dropTargetInfo = OLEDD_FindDropTarget(hwnd);
350 * If it ain't in there, it's an error.
352 if (dropTargetInfo==NULL)
353 return DRAGDROP_E_NOTREGISTERED;
355 OLEDD_FreeDropTarget(dropTargetInfo);
357 return S_OK;
360 /***********************************************************************
361 * OleRegGetUserType (OLE32.@)
363 * This implementation of OleRegGetUserType ignores the dwFormOfType
364 * parameter and always returns the full name of the object. This is
365 * not too bad since this is the case for many objects because of the
366 * way they are registered.
368 HRESULT WINAPI OleRegGetUserType(
369 REFCLSID clsid,
370 DWORD dwFormOfType,
371 LPOLESTR* pszUserType)
373 char keyName[60];
374 DWORD dwKeyType;
375 DWORD cbData;
376 HKEY clsidKey;
377 LONG hres;
378 LPSTR buffer;
379 HRESULT retVal;
381 * Initialize the out parameter.
383 *pszUserType = NULL;
386 * Build the key name we're looking for
388 sprintf( keyName, "CLSID\\{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\",
389 clsid->Data1, clsid->Data2, clsid->Data3,
390 clsid->Data4[0], clsid->Data4[1], clsid->Data4[2], clsid->Data4[3],
391 clsid->Data4[4], clsid->Data4[5], clsid->Data4[6], clsid->Data4[7] );
393 TRACE("(%s, %d, %p)\n", keyName, dwFormOfType, pszUserType);
396 * Open the class id Key
398 hres = RegOpenKeyA(HKEY_CLASSES_ROOT,
399 keyName,
400 &clsidKey);
402 if (hres != ERROR_SUCCESS)
403 return REGDB_E_CLASSNOTREG;
406 * Retrieve the size of the name string.
408 cbData = 0;
410 hres = RegQueryValueExA(clsidKey,
412 NULL,
413 &dwKeyType,
414 NULL,
415 &cbData);
417 if (hres!=ERROR_SUCCESS)
419 RegCloseKey(clsidKey);
420 return REGDB_E_READREGDB;
424 * Allocate a buffer for the registry value.
426 *pszUserType = CoTaskMemAlloc(cbData*2);
428 if (*pszUserType==NULL)
430 RegCloseKey(clsidKey);
431 return E_OUTOFMEMORY;
434 buffer = HeapAlloc(GetProcessHeap(), 0, cbData);
436 if (buffer == NULL)
438 RegCloseKey(clsidKey);
439 CoTaskMemFree(*pszUserType);
440 *pszUserType=NULL;
441 return E_OUTOFMEMORY;
444 hres = RegQueryValueExA(clsidKey,
446 NULL,
447 &dwKeyType,
448 (LPBYTE) buffer,
449 &cbData);
451 RegCloseKey(clsidKey);
454 if (hres!=ERROR_SUCCESS)
456 CoTaskMemFree(*pszUserType);
457 *pszUserType=NULL;
459 retVal = REGDB_E_READREGDB;
461 else
463 MultiByteToWideChar( CP_ACP, 0, buffer, -1, *pszUserType, cbData /*FIXME*/ );
464 retVal = S_OK;
466 HeapFree(GetProcessHeap(), 0, buffer);
468 return retVal;
471 /***********************************************************************
472 * DoDragDrop [OLE32.@]
474 HRESULT WINAPI DoDragDrop (
475 IDataObject *pDataObject, /* [in] ptr to the data obj */
476 IDropSource* pDropSource, /* [in] ptr to the source obj */
477 DWORD dwOKEffect, /* [in] effects allowed by the source */
478 DWORD *pdwEffect) /* [out] ptr to effects of the source */
480 TrackerWindowInfo trackerInfo;
481 HWND hwndTrackWindow;
482 MSG msg;
484 TRACE("(DataObject %p, DropSource %p)\n", pDataObject, pDropSource);
487 * Setup the drag n drop tracking window.
489 if (!IsValidInterface((LPUNKNOWN)pDropSource))
490 return E_INVALIDARG;
492 trackerInfo.dataObject = pDataObject;
493 trackerInfo.dropSource = pDropSource;
494 trackerInfo.dwOKEffect = dwOKEffect;
495 trackerInfo.pdwEffect = pdwEffect;
496 trackerInfo.trackingDone = FALSE;
497 trackerInfo.escPressed = FALSE;
498 trackerInfo.curDragTargetHWND = 0;
499 trackerInfo.curTargetHWND = 0;
500 trackerInfo.curDragTarget = 0;
502 hwndTrackWindow = CreateWindowA(OLEDD_DRAGTRACKERCLASS,
503 "TrackerWindow",
504 WS_POPUP,
505 CW_USEDEFAULT, CW_USEDEFAULT,
506 CW_USEDEFAULT, CW_USEDEFAULT,
510 (LPVOID)&trackerInfo);
512 if (hwndTrackWindow!=0)
515 * Capture the mouse input
517 SetCapture(hwndTrackWindow);
519 msg.message = 0;
522 * Pump messages. All mouse input should go the the capture window.
524 while (!trackerInfo.trackingDone && GetMessageA(&msg, 0, 0, 0) )
526 trackerInfo.curMousePos.x = msg.pt.x;
527 trackerInfo.curMousePos.y = msg.pt.y;
528 trackerInfo.dwKeyState = OLEDD_GetButtonState();
530 if ( (msg.message >= WM_KEYFIRST) &&
531 (msg.message <= WM_KEYLAST) )
534 * When keyboard messages are sent to windows on this thread, we
535 * want to ignore notify the drop source that the state changed.
536 * in the case of the Escape key, we also notify the drop source
537 * we give it a special meaning.
539 if ( (msg.message==WM_KEYDOWN) &&
540 (msg.wParam==VK_ESCAPE) )
542 trackerInfo.escPressed = TRUE;
546 * Notify the drop source.
548 OLEDD_TrackStateChange(&trackerInfo);
550 else
553 * Dispatch the messages only when it's not a keyboard message.
555 DispatchMessageA(&msg);
559 /* re-post the quit message to outer message loop */
560 if (msg.message == WM_QUIT)
561 PostQuitMessage(msg.wParam);
563 * Destroy the temporary window.
565 DestroyWindow(hwndTrackWindow);
567 return trackerInfo.returnValue;
570 return E_FAIL;
573 /***********************************************************************
574 * OleQueryLinkFromData [OLE32.@]
576 HRESULT WINAPI OleQueryLinkFromData(
577 IDataObject* pSrcDataObject)
579 FIXME("(%p),stub!\n", pSrcDataObject);
580 return S_OK;
583 /***********************************************************************
584 * OleRegGetMiscStatus [OLE32.@]
586 HRESULT WINAPI OleRegGetMiscStatus(
587 REFCLSID clsid,
588 DWORD dwAspect,
589 DWORD* pdwStatus)
591 char keyName[60];
592 HKEY clsidKey;
593 HKEY miscStatusKey;
594 HKEY aspectKey;
595 LONG result;
598 * Initialize the out parameter.
600 *pdwStatus = 0;
603 * Build the key name we're looking for
605 sprintf( keyName, "CLSID\\{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\\",
606 clsid->Data1, clsid->Data2, clsid->Data3,
607 clsid->Data4[0], clsid->Data4[1], clsid->Data4[2], clsid->Data4[3],
608 clsid->Data4[4], clsid->Data4[5], clsid->Data4[6], clsid->Data4[7] );
610 TRACE("(%s, %d, %p)\n", keyName, dwAspect, pdwStatus);
613 * Open the class id Key
615 result = RegOpenKeyA(HKEY_CLASSES_ROOT,
616 keyName,
617 &clsidKey);
619 if (result != ERROR_SUCCESS)
620 return REGDB_E_CLASSNOTREG;
623 * Get the MiscStatus
625 result = RegOpenKeyA(clsidKey,
626 "MiscStatus",
627 &miscStatusKey);
630 if (result != ERROR_SUCCESS)
632 RegCloseKey(clsidKey);
633 return REGDB_E_READREGDB;
637 * Read the default value
639 OLEUTL_ReadRegistryDWORDValue(miscStatusKey, pdwStatus);
642 * Open the key specific to the requested aspect.
644 sprintf(keyName, "%d", dwAspect);
646 result = RegOpenKeyA(miscStatusKey,
647 keyName,
648 &aspectKey);
650 if (result == ERROR_SUCCESS)
652 OLEUTL_ReadRegistryDWORDValue(aspectKey, pdwStatus);
653 RegCloseKey(aspectKey);
657 * Cleanup
659 RegCloseKey(miscStatusKey);
660 RegCloseKey(clsidKey);
662 return S_OK;
665 static HRESULT EnumOLEVERB_Construct(HKEY hkeyVerb, ULONG index, IEnumOLEVERB **ppenum);
667 typedef struct
669 const IEnumOLEVERBVtbl *lpvtbl;
670 LONG ref;
672 HKEY hkeyVerb;
673 ULONG index;
674 } EnumOLEVERB;
676 static HRESULT WINAPI EnumOLEVERB_QueryInterface(
677 IEnumOLEVERB *iface, REFIID riid, void **ppv)
679 TRACE("(%s, %p)\n", debugstr_guid(riid), ppv);
680 if (IsEqualIID(riid, &IID_IUnknown) ||
681 IsEqualIID(riid, &IID_IEnumOLEVERB))
683 IUnknown_AddRef(iface);
684 *ppv = iface;
685 return S_OK;
687 return E_NOINTERFACE;
690 static ULONG WINAPI EnumOLEVERB_AddRef(
691 IEnumOLEVERB *iface)
693 EnumOLEVERB *This = (EnumOLEVERB *)iface;
694 TRACE("()\n");
695 return InterlockedIncrement(&This->ref);
698 static ULONG WINAPI EnumOLEVERB_Release(
699 IEnumOLEVERB *iface)
701 EnumOLEVERB *This = (EnumOLEVERB *)iface;
702 LONG refs = InterlockedDecrement(&This->ref);
703 TRACE("()\n");
704 if (!refs)
706 RegCloseKey(This->hkeyVerb);
707 HeapFree(GetProcessHeap(), 0, This);
709 return refs;
712 static HRESULT WINAPI EnumOLEVERB_Next(
713 IEnumOLEVERB *iface, ULONG celt, LPOLEVERB rgelt,
714 ULONG *pceltFetched)
716 EnumOLEVERB *This = (EnumOLEVERB *)iface;
717 HRESULT hr = S_OK;
719 TRACE("(%d, %p, %p)\n", celt, rgelt, pceltFetched);
721 if (pceltFetched)
722 *pceltFetched = 0;
724 for (; celt; celt--, rgelt++)
726 WCHAR wszSubKey[20];
727 LONG cbData;
728 LPWSTR pwszOLEVERB;
729 LPWSTR pwszMenuFlags;
730 LPWSTR pwszAttribs;
731 LONG res = RegEnumKeyW(This->hkeyVerb, This->index, wszSubKey, sizeof(wszSubKey)/sizeof(wszSubKey[0]));
732 if (res == ERROR_NO_MORE_ITEMS)
734 hr = S_FALSE;
735 break;
737 else if (res != ERROR_SUCCESS)
739 ERR("RegEnumKeyW failed with error %d\n", res);
740 hr = REGDB_E_READREGDB;
741 break;
743 res = RegQueryValueW(This->hkeyVerb, wszSubKey, NULL, &cbData);
744 if (res != ERROR_SUCCESS)
746 ERR("RegQueryValueW failed with error %d\n", res);
747 hr = REGDB_E_READREGDB;
748 break;
750 pwszOLEVERB = CoTaskMemAlloc(cbData);
751 if (!pwszOLEVERB)
753 hr = E_OUTOFMEMORY;
754 break;
756 res = RegQueryValueW(This->hkeyVerb, wszSubKey, pwszOLEVERB, &cbData);
757 if (res != ERROR_SUCCESS)
759 ERR("RegQueryValueW failed with error %d\n", res);
760 hr = REGDB_E_READREGDB;
761 CoTaskMemFree(pwszOLEVERB);
762 break;
765 TRACE("verb string: %s\n", debugstr_w(pwszOLEVERB));
766 pwszMenuFlags = strchrW(pwszOLEVERB, ',');
767 if (!pwszMenuFlags)
769 hr = OLEOBJ_E_INVALIDVERB;
770 CoTaskMemFree(pwszOLEVERB);
771 break;
773 /* nul terminate the name string and advance to first character */
774 *pwszMenuFlags = '\0';
775 pwszMenuFlags++;
776 pwszAttribs = strchrW(pwszMenuFlags, ',');
777 if (!pwszAttribs)
779 hr = OLEOBJ_E_INVALIDVERB;
780 CoTaskMemFree(pwszOLEVERB);
781 break;
783 /* nul terminate the menu string and advance to first character */
784 *pwszAttribs = '\0';
785 pwszAttribs++;
787 /* fill out structure for this verb */
788 rgelt->lVerb = atolW(wszSubKey);
789 rgelt->lpszVerbName = pwszOLEVERB; /* user should free */
790 rgelt->fuFlags = atolW(pwszMenuFlags);
791 rgelt->grfAttribs = atolW(pwszAttribs);
793 if (pceltFetched)
794 (*pceltFetched)++;
795 This->index++;
797 return hr;
800 static HRESULT WINAPI EnumOLEVERB_Skip(
801 IEnumOLEVERB *iface, ULONG celt)
803 EnumOLEVERB *This = (EnumOLEVERB *)iface;
805 TRACE("(%d)\n", celt);
807 This->index += celt;
808 return S_OK;
811 static HRESULT WINAPI EnumOLEVERB_Reset(
812 IEnumOLEVERB *iface)
814 EnumOLEVERB *This = (EnumOLEVERB *)iface;
816 TRACE("()\n");
818 This->index = 0;
819 return S_OK;
822 static HRESULT WINAPI EnumOLEVERB_Clone(
823 IEnumOLEVERB *iface,
824 IEnumOLEVERB **ppenum)
826 EnumOLEVERB *This = (EnumOLEVERB *)iface;
827 HKEY hkeyVerb;
828 TRACE("(%p)\n", ppenum);
829 if (!DuplicateHandle(GetCurrentProcess(), This->hkeyVerb, GetCurrentProcess(), (HANDLE *)&hkeyVerb, 0, FALSE, DUPLICATE_SAME_ACCESS))
830 return HRESULT_FROM_WIN32(GetLastError());
831 return EnumOLEVERB_Construct(hkeyVerb, This->index, ppenum);
834 static const IEnumOLEVERBVtbl EnumOLEVERB_VTable =
836 EnumOLEVERB_QueryInterface,
837 EnumOLEVERB_AddRef,
838 EnumOLEVERB_Release,
839 EnumOLEVERB_Next,
840 EnumOLEVERB_Skip,
841 EnumOLEVERB_Reset,
842 EnumOLEVERB_Clone
845 static HRESULT EnumOLEVERB_Construct(HKEY hkeyVerb, ULONG index, IEnumOLEVERB **ppenum)
847 EnumOLEVERB *This = HeapAlloc(GetProcessHeap(), 0, sizeof(*This));
848 if (!This)
850 RegCloseKey(hkeyVerb);
851 return E_OUTOFMEMORY;
853 This->lpvtbl = &EnumOLEVERB_VTable;
854 This->ref = 1;
855 This->index = index;
856 This->hkeyVerb = hkeyVerb;
857 *ppenum = (IEnumOLEVERB *)&This->lpvtbl;
858 return S_OK;
861 /***********************************************************************
862 * OleRegEnumVerbs [OLE32.@]
864 * Enumerates verbs associated with a class stored in the registry.
866 * PARAMS
867 * clsid [I] Class ID to enumerate the verbs for.
868 * ppenum [O] Enumerator.
870 * RETURNS
871 * S_OK: Success.
872 * REGDB_E_CLASSNOTREG: The specified class does not have a key in the registry.
873 * REGDB_E_READREGDB: The class key could not be opened for some other reason.
874 * OLE_E_REGDB_KEY: The Verb subkey for the class is not present.
875 * OLEOBJ_E_NOVERBS: The Verb subkey for the class is empty.
877 HRESULT WINAPI OleRegEnumVerbs (REFCLSID clsid, LPENUMOLEVERB* ppenum)
879 LONG res;
880 HKEY hkeyVerb;
881 DWORD dwSubKeys;
882 static const WCHAR wszVerb[] = {'V','e','r','b',0};
884 TRACE("(%s, %p)\n", debugstr_guid(clsid), ppenum);
886 res = COM_OpenKeyForCLSID(clsid, wszVerb, KEY_READ, &hkeyVerb);
887 if (FAILED(res))
889 if (res == REGDB_E_CLASSNOTREG)
890 ERR("CLSID %s not registered\n", debugstr_guid(clsid));
891 else if (res == REGDB_E_KEYMISSING)
892 ERR("no Verbs key for class %s\n", debugstr_guid(clsid));
893 else
894 ERR("failed to open Verbs key for CLSID %s with error %d\n",
895 debugstr_guid(clsid), res);
896 return res;
899 res = RegQueryInfoKeyW(hkeyVerb, NULL, NULL, NULL, &dwSubKeys, NULL,
900 NULL, NULL, NULL, NULL, NULL, NULL);
901 if (res != ERROR_SUCCESS)
903 ERR("failed to get subkey count with error %d\n", GetLastError());
904 return REGDB_E_READREGDB;
907 if (!dwSubKeys)
909 WARN("class %s has no verbs\n", debugstr_guid(clsid));
910 RegCloseKey(hkeyVerb);
911 return OLEOBJ_E_NOVERBS;
914 return EnumOLEVERB_Construct(hkeyVerb, 0, ppenum);
917 /******************************************************************************
918 * OleSetContainedObject [OLE32.@]
920 HRESULT WINAPI OleSetContainedObject(
921 LPUNKNOWN pUnknown,
922 BOOL fContained)
924 IRunnableObject* runnable = NULL;
925 HRESULT hres;
927 TRACE("(%p,%x)\n", pUnknown, fContained);
929 hres = IUnknown_QueryInterface(pUnknown,
930 &IID_IRunnableObject,
931 (void**)&runnable);
933 if (SUCCEEDED(hres))
935 hres = IRunnableObject_SetContainedObject(runnable, fContained);
937 IRunnableObject_Release(runnable);
939 return hres;
942 return S_OK;
945 /******************************************************************************
946 * OleLoad [OLE32.@]
948 HRESULT WINAPI OleLoad(
949 LPSTORAGE pStg,
950 REFIID riid,
951 LPOLECLIENTSITE pClientSite,
952 LPVOID* ppvObj)
954 IPersistStorage* persistStorage = NULL;
955 IUnknown* pUnk;
956 IOleObject* pOleObject = NULL;
957 STATSTG storageInfo;
958 HRESULT hres;
960 TRACE("(%p,%p,%p,%p)\n", pStg, riid, pClientSite, ppvObj);
962 *ppvObj = NULL;
965 * TODO, Conversion ... OleDoAutoConvert
969 * Get the class ID for the object.
971 hres = IStorage_Stat(pStg, &storageInfo, STATFLAG_NONAME);
974 * Now, try and create the handler for the object
976 hres = CoCreateInstance(&storageInfo.clsid,
977 NULL,
978 CLSCTX_INPROC_HANDLER,
979 riid,
980 (void**)&pUnk);
983 * If that fails, as it will most times, load the default
984 * OLE handler.
986 if (FAILED(hres))
988 hres = OleCreateDefaultHandler(&storageInfo.clsid,
989 NULL,
990 riid,
991 (void**)&pUnk);
995 * If we couldn't find a handler... this is bad. Abort the whole thing.
997 if (FAILED(hres))
998 return hres;
1000 if (pClientSite)
1002 hres = IUnknown_QueryInterface(pUnk, &IID_IOleObject, (void **)&pOleObject);
1003 if (SUCCEEDED(hres))
1005 DWORD dwStatus;
1006 hres = IOleObject_GetMiscStatus(pOleObject, DVASPECT_CONTENT, &dwStatus);
1010 if (SUCCEEDED(hres))
1012 * Initialize the object with it's IPersistStorage interface.
1014 hres = IOleObject_QueryInterface(pUnk,
1015 &IID_IPersistStorage,
1016 (void**)&persistStorage);
1018 if (SUCCEEDED(hres))
1020 hres = IPersistStorage_Load(persistStorage, pStg);
1022 IPersistStorage_Release(persistStorage);
1023 persistStorage = NULL;
1026 if (SUCCEEDED(hres) && pClientSite)
1028 * Inform the new object of it's client site.
1030 hres = IOleObject_SetClientSite(pOleObject, pClientSite);
1033 * Cleanup interfaces used internally
1035 if (pOleObject)
1036 IOleObject_Release(pOleObject);
1038 if (SUCCEEDED(hres))
1040 IOleLink *pOleLink;
1041 HRESULT hres1;
1042 hres1 = IUnknown_QueryInterface(pUnk, &IID_IOleLink, (void **)&pOleLink);
1043 if (SUCCEEDED(hres1))
1045 FIXME("handle OLE link\n");
1046 IOleLink_Release(pOleLink);
1050 if (FAILED(hres))
1052 IUnknown_Release(pUnk);
1053 pUnk = NULL;
1056 *ppvObj = pUnk;
1058 return hres;
1061 /***********************************************************************
1062 * OleSave [OLE32.@]
1064 HRESULT WINAPI OleSave(
1065 LPPERSISTSTORAGE pPS,
1066 LPSTORAGE pStg,
1067 BOOL fSameAsLoad)
1069 HRESULT hres;
1070 CLSID objectClass;
1072 TRACE("(%p,%p,%x)\n", pPS, pStg, fSameAsLoad);
1075 * First, we transfer the class ID (if available)
1077 hres = IPersistStorage_GetClassID(pPS, &objectClass);
1079 if (SUCCEEDED(hres))
1081 WriteClassStg(pStg, &objectClass);
1085 * Then, we ask the object to save itself to the
1086 * storage. If it is successful, we commit the storage.
1088 hres = IPersistStorage_Save(pPS, pStg, fSameAsLoad);
1090 if (SUCCEEDED(hres))
1092 IStorage_Commit(pStg,
1093 STGC_DEFAULT);
1096 return hres;
1100 /******************************************************************************
1101 * OleLockRunning [OLE32.@]
1103 HRESULT WINAPI OleLockRunning(LPUNKNOWN pUnknown, BOOL fLock, BOOL fLastUnlockCloses)
1105 IRunnableObject* runnable = NULL;
1106 HRESULT hres;
1108 TRACE("(%p,%x,%x)\n", pUnknown, fLock, fLastUnlockCloses);
1110 hres = IUnknown_QueryInterface(pUnknown,
1111 &IID_IRunnableObject,
1112 (void**)&runnable);
1114 if (SUCCEEDED(hres))
1116 hres = IRunnableObject_LockRunning(runnable, fLock, fLastUnlockCloses);
1118 IRunnableObject_Release(runnable);
1120 return hres;
1122 else
1123 return E_INVALIDARG;
1127 /**************************************************************************
1128 * Internal methods to manage the shared OLE menu in response to the
1129 * OLE***MenuDescriptor API
1132 /***
1133 * OLEMenu_Initialize()
1135 * Initializes the OLEMENU data structures.
1137 static void OLEMenu_Initialize(void)
1141 /***
1142 * OLEMenu_UnInitialize()
1144 * Releases the OLEMENU data structures.
1146 static void OLEMenu_UnInitialize(void)
1150 /*************************************************************************
1151 * OLEMenu_InstallHooks
1152 * Install thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC
1154 * RETURNS: TRUE if message hooks were successfully installed
1155 * FALSE on failure
1157 static BOOL OLEMenu_InstallHooks( DWORD tid )
1159 OleMenuHookItem *pHookItem = NULL;
1161 /* Create an entry for the hook table */
1162 if ( !(pHookItem = HeapAlloc(GetProcessHeap(), 0,
1163 sizeof(OleMenuHookItem)) ) )
1164 return FALSE;
1166 pHookItem->tid = tid;
1167 pHookItem->hHeap = GetProcessHeap();
1169 /* Install a thread scope message hook for WH_GETMESSAGE */
1170 pHookItem->GetMsg_hHook = SetWindowsHookExA( WH_GETMESSAGE, OLEMenu_GetMsgProc,
1171 0, GetCurrentThreadId() );
1172 if ( !pHookItem->GetMsg_hHook )
1173 goto CLEANUP;
1175 /* Install a thread scope message hook for WH_CALLWNDPROC */
1176 pHookItem->CallWndProc_hHook = SetWindowsHookExA( WH_CALLWNDPROC, OLEMenu_CallWndProc,
1177 0, GetCurrentThreadId() );
1178 if ( !pHookItem->CallWndProc_hHook )
1179 goto CLEANUP;
1181 /* Insert the hook table entry */
1182 pHookItem->next = hook_list;
1183 hook_list = pHookItem;
1185 return TRUE;
1187 CLEANUP:
1188 /* Unhook any hooks */
1189 if ( pHookItem->GetMsg_hHook )
1190 UnhookWindowsHookEx( pHookItem->GetMsg_hHook );
1191 if ( pHookItem->CallWndProc_hHook )
1192 UnhookWindowsHookEx( pHookItem->CallWndProc_hHook );
1193 /* Release the hook table entry */
1194 HeapFree(pHookItem->hHeap, 0, pHookItem );
1196 return FALSE;
1199 /*************************************************************************
1200 * OLEMenu_UnInstallHooks
1201 * UnInstall thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC
1203 * RETURNS: TRUE if message hooks were successfully installed
1204 * FALSE on failure
1206 static BOOL OLEMenu_UnInstallHooks( DWORD tid )
1208 OleMenuHookItem *pHookItem = NULL;
1209 OleMenuHookItem **ppHook = &hook_list;
1211 while (*ppHook)
1213 if ((*ppHook)->tid == tid)
1215 pHookItem = *ppHook;
1216 *ppHook = pHookItem->next;
1217 break;
1219 ppHook = &(*ppHook)->next;
1221 if (!pHookItem) return FALSE;
1223 /* Uninstall the hooks installed for this thread */
1224 if ( !UnhookWindowsHookEx( pHookItem->GetMsg_hHook ) )
1225 goto CLEANUP;
1226 if ( !UnhookWindowsHookEx( pHookItem->CallWndProc_hHook ) )
1227 goto CLEANUP;
1229 /* Release the hook table entry */
1230 HeapFree(pHookItem->hHeap, 0, pHookItem );
1232 return TRUE;
1234 CLEANUP:
1235 /* Release the hook table entry */
1236 HeapFree(pHookItem->hHeap, 0, pHookItem );
1238 return FALSE;
1241 /*************************************************************************
1242 * OLEMenu_IsHookInstalled
1243 * Tests if OLEMenu hooks have been installed for a thread
1245 * RETURNS: The pointer and index of the hook table entry for the tid
1246 * NULL and -1 for the index if no hooks were installed for this thread
1248 static OleMenuHookItem * OLEMenu_IsHookInstalled( DWORD tid )
1250 OleMenuHookItem *pHookItem = NULL;
1252 /* Do a simple linear search for an entry whose tid matches ours.
1253 * We really need a map but efficiency is not a concern here. */
1254 for (pHookItem = hook_list; pHookItem; pHookItem = pHookItem->next)
1256 if ( tid == pHookItem->tid )
1257 return pHookItem;
1260 return NULL;
1263 /***********************************************************************
1264 * OLEMenu_FindMainMenuIndex
1266 * Used by OLEMenu API to find the top level group a menu item belongs to.
1267 * On success pnPos contains the index of the item in the top level menu group
1269 * RETURNS: TRUE if the ID was found, FALSE on failure
1271 static BOOL OLEMenu_FindMainMenuIndex( HMENU hMainMenu, HMENU hPopupMenu, UINT *pnPos )
1273 UINT i, nItems;
1275 nItems = GetMenuItemCount( hMainMenu );
1277 for (i = 0; i < nItems; i++)
1279 HMENU hsubmenu;
1281 /* Is the current item a submenu? */
1282 if ( (hsubmenu = GetSubMenu(hMainMenu, i)) )
1284 /* If the handle is the same we're done */
1285 if ( hsubmenu == hPopupMenu )
1287 if (pnPos)
1288 *pnPos = i;
1289 return TRUE;
1291 /* Recursively search without updating pnPos */
1292 else if ( OLEMenu_FindMainMenuIndex( hsubmenu, hPopupMenu, NULL ) )
1294 if (pnPos)
1295 *pnPos = i;
1296 return TRUE;
1301 return FALSE;
1304 /***********************************************************************
1305 * OLEMenu_SetIsServerMenu
1307 * Checks whether a popup menu belongs to a shared menu group which is
1308 * owned by the server, and sets the menu descriptor state accordingly.
1309 * All menu messages from these groups should be routed to the server.
1311 * RETURNS: TRUE if the popup menu is part of a server owned group
1312 * FALSE if the popup menu is part of a container owned group
1314 static BOOL OLEMenu_SetIsServerMenu( HMENU hmenu, OleMenuDescriptor *pOleMenuDescriptor )
1316 UINT nPos = 0, nWidth, i;
1318 pOleMenuDescriptor->bIsServerItem = FALSE;
1320 /* Don't bother searching if the popup is the combined menu itself */
1321 if ( hmenu == pOleMenuDescriptor->hmenuCombined )
1322 return FALSE;
1324 /* Find the menu item index in the shared OLE menu that this item belongs to */
1325 if ( !OLEMenu_FindMainMenuIndex( pOleMenuDescriptor->hmenuCombined, hmenu, &nPos ) )
1326 return FALSE;
1328 /* The group widths array has counts for the number of elements
1329 * in the groups File, Edit, Container, Object, Window, Help.
1330 * The Edit, Object & Help groups belong to the server object
1331 * and the other three belong to the container.
1332 * Loop through the group widths and locate the group we are a member of.
1334 for ( i = 0, nWidth = 0; i < 6; i++ )
1336 nWidth += pOleMenuDescriptor->mgw.width[i];
1337 if ( nPos < nWidth )
1339 /* Odd elements are server menu widths */
1340 pOleMenuDescriptor->bIsServerItem = (i%2) ? TRUE : FALSE;
1341 break;
1345 return pOleMenuDescriptor->bIsServerItem;
1348 /*************************************************************************
1349 * OLEMenu_CallWndProc
1350 * Thread scope WH_CALLWNDPROC hook proc filter function (callback)
1351 * This is invoked from a message hook installed in OleSetMenuDescriptor.
1353 static LRESULT CALLBACK OLEMenu_CallWndProc(INT code, WPARAM wParam, LPARAM lParam)
1355 LPCWPSTRUCT pMsg = NULL;
1356 HOLEMENU hOleMenu = 0;
1357 OleMenuDescriptor *pOleMenuDescriptor = NULL;
1358 OleMenuHookItem *pHookItem = NULL;
1359 WORD fuFlags;
1361 TRACE("%i, %04x, %08x\n", code, wParam, (unsigned)lParam );
1363 /* Check if we're being asked to process the message */
1364 if ( HC_ACTION != code )
1365 goto NEXTHOOK;
1367 /* Retrieve the current message being dispatched from lParam */
1368 pMsg = (LPCWPSTRUCT)lParam;
1370 /* Check if the message is destined for a window we are interested in:
1371 * If the window has an OLEMenu property we may need to dispatch
1372 * the menu message to its active objects window instead. */
1374 hOleMenu = (HOLEMENU)GetPropA( pMsg->hwnd, "PROP_OLEMenuDescriptor" );
1375 if ( !hOleMenu )
1376 goto NEXTHOOK;
1378 /* Get the menu descriptor */
1379 pOleMenuDescriptor = (OleMenuDescriptor *) GlobalLock( hOleMenu );
1380 if ( !pOleMenuDescriptor ) /* Bad descriptor! */
1381 goto NEXTHOOK;
1383 /* Process menu messages */
1384 switch( pMsg->message )
1386 case WM_INITMENU:
1388 /* Reset the menu descriptor state */
1389 pOleMenuDescriptor->bIsServerItem = FALSE;
1391 /* Send this message to the server as well */
1392 SendMessageA( pOleMenuDescriptor->hwndActiveObject,
1393 pMsg->message, pMsg->wParam, pMsg->lParam );
1394 goto NEXTHOOK;
1397 case WM_INITMENUPOPUP:
1399 /* Save the state for whether this is a server owned menu */
1400 OLEMenu_SetIsServerMenu( (HMENU)pMsg->wParam, pOleMenuDescriptor );
1401 break;
1404 case WM_MENUSELECT:
1406 fuFlags = HIWORD(pMsg->wParam); /* Get flags */
1407 if ( fuFlags & MF_SYSMENU )
1408 goto NEXTHOOK;
1410 /* Save the state for whether this is a server owned popup menu */
1411 else if ( fuFlags & MF_POPUP )
1412 OLEMenu_SetIsServerMenu( (HMENU)pMsg->lParam, pOleMenuDescriptor );
1414 break;
1417 case WM_DRAWITEM:
1419 LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT) pMsg->lParam;
1420 if ( pMsg->wParam != 0 || lpdis->CtlType != ODT_MENU )
1421 goto NEXTHOOK; /* Not a menu message */
1423 break;
1426 default:
1427 goto NEXTHOOK;
1430 /* If the message was for the server dispatch it accordingly */
1431 if ( pOleMenuDescriptor->bIsServerItem )
1433 SendMessageA( pOleMenuDescriptor->hwndActiveObject,
1434 pMsg->message, pMsg->wParam, pMsg->lParam );
1437 NEXTHOOK:
1438 if ( pOleMenuDescriptor )
1439 GlobalUnlock( hOleMenu );
1441 /* Lookup the hook item for the current thread */
1442 if ( !( pHookItem = OLEMenu_IsHookInstalled( GetCurrentThreadId() ) ) )
1444 /* This should never fail!! */
1445 WARN("could not retrieve hHook for current thread!\n" );
1446 return 0;
1449 /* Pass on the message to the next hooker */
1450 return CallNextHookEx( pHookItem->CallWndProc_hHook, code, wParam, lParam );
1453 /*************************************************************************
1454 * OLEMenu_GetMsgProc
1455 * Thread scope WH_GETMESSAGE hook proc filter function (callback)
1456 * This is invoked from a message hook installed in OleSetMenuDescriptor.
1458 static LRESULT CALLBACK OLEMenu_GetMsgProc(INT code, WPARAM wParam, LPARAM lParam)
1460 LPMSG pMsg = NULL;
1461 HOLEMENU hOleMenu = 0;
1462 OleMenuDescriptor *pOleMenuDescriptor = NULL;
1463 OleMenuHookItem *pHookItem = NULL;
1464 WORD wCode;
1466 TRACE("%i, %04x, %08x\n", code, wParam, (unsigned)lParam );
1468 /* Check if we're being asked to process a messages */
1469 if ( HC_ACTION != code )
1470 goto NEXTHOOK;
1472 /* Retrieve the current message being dispatched from lParam */
1473 pMsg = (LPMSG)lParam;
1475 /* Check if the message is destined for a window we are interested in:
1476 * If the window has an OLEMenu property we may need to dispatch
1477 * the menu message to its active objects window instead. */
1479 hOleMenu = (HOLEMENU)GetPropA( pMsg->hwnd, "PROP_OLEMenuDescriptor" );
1480 if ( !hOleMenu )
1481 goto NEXTHOOK;
1483 /* Process menu messages */
1484 switch( pMsg->message )
1486 case WM_COMMAND:
1488 wCode = HIWORD(pMsg->wParam); /* Get notification code */
1489 if ( wCode )
1490 goto NEXTHOOK; /* Not a menu message */
1491 break;
1493 default:
1494 goto NEXTHOOK;
1497 /* Get the menu descriptor */
1498 pOleMenuDescriptor = (OleMenuDescriptor *) GlobalLock( hOleMenu );
1499 if ( !pOleMenuDescriptor ) /* Bad descriptor! */
1500 goto NEXTHOOK;
1502 /* If the message was for the server dispatch it accordingly */
1503 if ( pOleMenuDescriptor->bIsServerItem )
1505 /* Change the hWnd in the message to the active objects hWnd.
1506 * The message loop which reads this message will automatically
1507 * dispatch it to the embedded objects window. */
1508 pMsg->hwnd = pOleMenuDescriptor->hwndActiveObject;
1511 NEXTHOOK:
1512 if ( pOleMenuDescriptor )
1513 GlobalUnlock( hOleMenu );
1515 /* Lookup the hook item for the current thread */
1516 if ( !( pHookItem = OLEMenu_IsHookInstalled( GetCurrentThreadId() ) ) )
1518 /* This should never fail!! */
1519 WARN("could not retrieve hHook for current thread!\n" );
1520 return FALSE;
1523 /* Pass on the message to the next hooker */
1524 return CallNextHookEx( pHookItem->GetMsg_hHook, code, wParam, lParam );
1527 /***********************************************************************
1528 * OleCreateMenuDescriptor [OLE32.@]
1529 * Creates an OLE menu descriptor for OLE to use when dispatching
1530 * menu messages and commands.
1532 * PARAMS:
1533 * hmenuCombined - Handle to the objects combined menu
1534 * lpMenuWidths - Pointer to array of 6 LONG's indicating menus per group
1537 HOLEMENU WINAPI OleCreateMenuDescriptor(
1538 HMENU hmenuCombined,
1539 LPOLEMENUGROUPWIDTHS lpMenuWidths)
1541 HOLEMENU hOleMenu;
1542 OleMenuDescriptor *pOleMenuDescriptor;
1543 int i;
1545 if ( !hmenuCombined || !lpMenuWidths )
1546 return 0;
1548 /* Create an OLE menu descriptor */
1549 if ( !(hOleMenu = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT,
1550 sizeof(OleMenuDescriptor) ) ) )
1551 return 0;
1553 pOleMenuDescriptor = (OleMenuDescriptor *) GlobalLock( hOleMenu );
1554 if ( !pOleMenuDescriptor )
1555 return 0;
1557 /* Initialize menu group widths and hmenu */
1558 for ( i = 0; i < 6; i++ )
1559 pOleMenuDescriptor->mgw.width[i] = lpMenuWidths->width[i];
1561 pOleMenuDescriptor->hmenuCombined = hmenuCombined;
1562 pOleMenuDescriptor->bIsServerItem = FALSE;
1563 GlobalUnlock( hOleMenu );
1565 return hOleMenu;
1568 /***********************************************************************
1569 * OleDestroyMenuDescriptor [OLE32.@]
1570 * Destroy the shared menu descriptor
1572 HRESULT WINAPI OleDestroyMenuDescriptor(
1573 HOLEMENU hmenuDescriptor)
1575 if ( hmenuDescriptor )
1576 GlobalFree( hmenuDescriptor );
1577 return S_OK;
1580 /***********************************************************************
1581 * OleSetMenuDescriptor [OLE32.@]
1582 * Installs or removes OLE dispatching code for the containers frame window.
1584 * PARAMS
1585 * hOleMenu Handle to composite menu descriptor
1586 * hwndFrame Handle to containers frame window
1587 * hwndActiveObject Handle to objects in-place activation window
1588 * lpFrame Pointer to IOleInPlaceFrame on containers window
1589 * lpActiveObject Pointer to IOleInPlaceActiveObject on active in-place object
1591 * RETURNS
1592 * S_OK - menu installed correctly
1593 * E_FAIL, E_INVALIDARG, E_UNEXPECTED - failure
1595 * FIXME
1596 * The lpFrame and lpActiveObject parameters are currently ignored
1597 * OLE should install context sensitive help F1 filtering for the app when
1598 * these are non null.
1600 HRESULT WINAPI OleSetMenuDescriptor(
1601 HOLEMENU hOleMenu,
1602 HWND hwndFrame,
1603 HWND hwndActiveObject,
1604 LPOLEINPLACEFRAME lpFrame,
1605 LPOLEINPLACEACTIVEOBJECT lpActiveObject)
1607 OleMenuDescriptor *pOleMenuDescriptor = NULL;
1609 /* Check args */
1610 if ( !hwndFrame || (hOleMenu && !hwndActiveObject) )
1611 return E_INVALIDARG;
1613 if ( lpFrame || lpActiveObject )
1615 FIXME("(%p, %p, %p, %p, %p), Context sensitive help filtering not implemented!\n",
1616 hOleMenu,
1617 hwndFrame,
1618 hwndActiveObject,
1619 lpFrame,
1620 lpActiveObject);
1623 /* Set up a message hook to intercept the containers frame window messages.
1624 * The message filter is responsible for dispatching menu messages from the
1625 * shared menu which are intended for the object.
1628 if ( hOleMenu ) /* Want to install dispatching code */
1630 /* If OLEMenu hooks are already installed for this thread, fail
1631 * Note: This effectively means that OleSetMenuDescriptor cannot
1632 * be called twice in succession on the same frame window
1633 * without first calling it with a null hOleMenu to uninstall */
1634 if ( OLEMenu_IsHookInstalled( GetCurrentThreadId() ) )
1635 return E_FAIL;
1637 /* Get the menu descriptor */
1638 pOleMenuDescriptor = (OleMenuDescriptor *) GlobalLock( hOleMenu );
1639 if ( !pOleMenuDescriptor )
1640 return E_UNEXPECTED;
1642 /* Update the menu descriptor */
1643 pOleMenuDescriptor->hwndFrame = hwndFrame;
1644 pOleMenuDescriptor->hwndActiveObject = hwndActiveObject;
1646 GlobalUnlock( hOleMenu );
1647 pOleMenuDescriptor = NULL;
1649 /* Add a menu descriptor windows property to the frame window */
1650 SetPropA( hwndFrame, "PROP_OLEMenuDescriptor", hOleMenu );
1652 /* Install thread scope message hooks for WH_GETMESSAGE and WH_CALLWNDPROC */
1653 if ( !OLEMenu_InstallHooks( GetCurrentThreadId() ) )
1654 return E_FAIL;
1656 else /* Want to uninstall dispatching code */
1658 /* Uninstall the hooks */
1659 if ( !OLEMenu_UnInstallHooks( GetCurrentThreadId() ) )
1660 return E_FAIL;
1662 /* Remove the menu descriptor property from the frame window */
1663 RemovePropA( hwndFrame, "PROP_OLEMenuDescriptor" );
1666 return S_OK;
1669 /******************************************************************************
1670 * IsAccelerator [OLE32.@]
1671 * Mostly copied from controls/menu.c TranslateAccelerator implementation
1673 BOOL WINAPI IsAccelerator(HACCEL hAccel, int cAccelEntries, LPMSG lpMsg, WORD* lpwCmd)
1675 LPACCEL lpAccelTbl;
1676 int i;
1678 if(!lpMsg) return FALSE;
1679 if (!hAccel)
1681 WARN_(accel)("NULL accel handle\n");
1682 return FALSE;
1684 if((lpMsg->message != WM_KEYDOWN &&
1685 lpMsg->message != WM_KEYUP &&
1686 lpMsg->message != WM_SYSKEYDOWN &&
1687 lpMsg->message != WM_SYSKEYUP &&
1688 lpMsg->message != WM_CHAR)) return FALSE;
1689 lpAccelTbl = HeapAlloc(GetProcessHeap(), 0, cAccelEntries * sizeof(ACCEL));
1690 if (NULL == lpAccelTbl)
1692 return FALSE;
1694 if (CopyAcceleratorTableW(hAccel, lpAccelTbl, cAccelEntries) != cAccelEntries)
1696 WARN_(accel)("CopyAcceleratorTableW failed\n");
1697 HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1698 return FALSE;
1701 TRACE_(accel)("hAccel=%p, cAccelEntries=%d,"
1702 "msg->hwnd=%p, msg->message=%04x, wParam=%08x, lParam=%08lx\n",
1703 hAccel, cAccelEntries,
1704 lpMsg->hwnd, lpMsg->message, lpMsg->wParam, lpMsg->lParam);
1705 for(i = 0; i < cAccelEntries; i++)
1707 if(lpAccelTbl[i].key != lpMsg->wParam)
1708 continue;
1710 if(lpMsg->message == WM_CHAR)
1712 if(!(lpAccelTbl[i].fVirt & FALT) && !(lpAccelTbl[i].fVirt & FVIRTKEY))
1714 TRACE_(accel)("found accel for WM_CHAR: ('%c')\n", lpMsg->wParam & 0xff);
1715 goto found;
1718 else
1720 if(lpAccelTbl[i].fVirt & FVIRTKEY)
1722 INT mask = 0;
1723 TRACE_(accel)("found accel for virt_key %04x (scan %04x)\n",
1724 lpMsg->wParam, HIWORD(lpMsg->lParam) & 0xff);
1725 if(GetKeyState(VK_SHIFT) & 0x8000) mask |= FSHIFT;
1726 if(GetKeyState(VK_CONTROL) & 0x8000) mask |= FCONTROL;
1727 if(GetKeyState(VK_MENU) & 0x8000) mask |= FALT;
1728 if(mask == (lpAccelTbl[i].fVirt & (FSHIFT | FCONTROL | FALT))) goto found;
1729 TRACE_(accel)("incorrect SHIFT/CTRL/ALT-state\n");
1731 else
1733 if(!(lpMsg->lParam & 0x01000000)) /* no special_key */
1735 if((lpAccelTbl[i].fVirt & FALT) && (lpMsg->lParam & 0x20000000))
1736 { /* ^^ ALT pressed */
1737 TRACE_(accel)("found accel for Alt-%c\n", lpMsg->wParam & 0xff);
1738 goto found;
1745 WARN_(accel)("couldn't translate accelerator key\n");
1746 HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1747 return FALSE;
1749 found:
1750 if(lpwCmd) *lpwCmd = lpAccelTbl[i].cmd;
1751 HeapFree(GetProcessHeap(), 0, lpAccelTbl);
1752 return TRUE;
1755 /***********************************************************************
1756 * ReleaseStgMedium [OLE32.@]
1758 void WINAPI ReleaseStgMedium(
1759 STGMEDIUM* pmedium)
1761 switch (pmedium->tymed)
1763 case TYMED_HGLOBAL:
1765 if ( (pmedium->pUnkForRelease==0) &&
1766 (pmedium->u.hGlobal!=0) )
1767 GlobalFree(pmedium->u.hGlobal);
1768 break;
1770 case TYMED_FILE:
1772 if (pmedium->u.lpszFileName!=0)
1774 if (pmedium->pUnkForRelease==0)
1776 DeleteFileW(pmedium->u.lpszFileName);
1779 CoTaskMemFree(pmedium->u.lpszFileName);
1781 break;
1783 case TYMED_ISTREAM:
1785 if (pmedium->u.pstm!=0)
1787 IStream_Release(pmedium->u.pstm);
1789 break;
1791 case TYMED_ISTORAGE:
1793 if (pmedium->u.pstg!=0)
1795 IStorage_Release(pmedium->u.pstg);
1797 break;
1799 case TYMED_GDI:
1801 if ( (pmedium->pUnkForRelease==0) &&
1802 (pmedium->u.hBitmap!=0) )
1803 DeleteObject(pmedium->u.hBitmap);
1804 break;
1806 case TYMED_MFPICT:
1808 if ( (pmedium->pUnkForRelease==0) &&
1809 (pmedium->u.hMetaFilePict!=0) )
1811 LPMETAFILEPICT pMP = GlobalLock(pmedium->u.hMetaFilePict);
1812 DeleteMetaFile(pMP->hMF);
1813 GlobalUnlock(pmedium->u.hMetaFilePict);
1814 GlobalFree(pmedium->u.hMetaFilePict);
1816 break;
1818 case TYMED_ENHMF:
1820 if ( (pmedium->pUnkForRelease==0) &&
1821 (pmedium->u.hEnhMetaFile!=0) )
1823 DeleteEnhMetaFile(pmedium->u.hEnhMetaFile);
1825 break;
1827 case TYMED_NULL:
1828 default:
1829 break;
1831 pmedium->tymed=TYMED_NULL;
1834 * After cleaning up, the unknown is released
1836 if (pmedium->pUnkForRelease!=0)
1838 IUnknown_Release(pmedium->pUnkForRelease);
1839 pmedium->pUnkForRelease = 0;
1843 /***
1844 * OLEDD_Initialize()
1846 * Initializes the OLE drag and drop data structures.
1848 static void OLEDD_Initialize(void)
1850 WNDCLASSA wndClass;
1852 ZeroMemory (&wndClass, sizeof(WNDCLASSA));
1853 wndClass.style = CS_GLOBALCLASS;
1854 wndClass.lpfnWndProc = OLEDD_DragTrackerWindowProc;
1855 wndClass.cbClsExtra = 0;
1856 wndClass.cbWndExtra = sizeof(TrackerWindowInfo*);
1857 wndClass.hCursor = 0;
1858 wndClass.hbrBackground = 0;
1859 wndClass.lpszClassName = OLEDD_DRAGTRACKERCLASS;
1861 RegisterClassA (&wndClass);
1864 /***
1865 * OLEDD_FreeDropTarget()
1867 * Frees the drag and drop data structure
1869 static void OLEDD_FreeDropTarget(DropTargetNode *dropTargetInfo)
1871 list_remove(&dropTargetInfo->entry);
1872 IDropTarget_Release(dropTargetInfo->dropTarget);
1873 HeapFree(GetProcessHeap(), 0, dropTargetInfo);
1876 /***
1877 * OLEDD_UnInitialize()
1879 * Releases the OLE drag and drop data structures.
1881 static void OLEDD_UnInitialize(void)
1884 * Simply empty the list.
1886 while (!list_empty(&targetListHead))
1888 DropTargetNode* curNode;
1889 curNode = LIST_ENTRY(list_head(&targetListHead), DropTargetNode, entry);
1890 OLEDD_FreeDropTarget(curNode);
1894 /***
1895 * OLEDD_FindDropTarget()
1897 * Finds information about the drop target.
1899 static DropTargetNode* OLEDD_FindDropTarget(HWND hwndOfTarget)
1901 DropTargetNode* curNode;
1904 * Iterate the list to find the HWND value.
1906 LIST_FOR_EACH_ENTRY(curNode, &targetListHead, DropTargetNode, entry)
1907 if (hwndOfTarget==curNode->hwndTarget)
1908 return curNode;
1911 * If we get here, the item is not in the list
1913 return NULL;
1916 /***
1917 * OLEDD_DragTrackerWindowProc()
1919 * This method is the WindowProcedure of the drag n drop tracking
1920 * window. During a drag n Drop operation, an invisible window is created
1921 * to receive the user input and act upon it. This procedure is in charge
1922 * of this behavior.
1925 #define DRAG_TIMER_ID 1
1927 static LRESULT WINAPI OLEDD_DragTrackerWindowProc(
1928 HWND hwnd,
1929 UINT uMsg,
1930 WPARAM wParam,
1931 LPARAM lParam)
1933 switch (uMsg)
1935 case WM_CREATE:
1937 LPCREATESTRUCTA createStruct = (LPCREATESTRUCTA)lParam;
1939 SetWindowLongA(hwnd, 0, (LONG)createStruct->lpCreateParams);
1940 SetTimer(hwnd, DRAG_TIMER_ID, 50, NULL);
1942 break;
1944 case WM_TIMER:
1945 case WM_MOUSEMOVE:
1947 OLEDD_TrackMouseMove((TrackerWindowInfo*)GetWindowLongA(hwnd, 0));
1948 break;
1950 case WM_LBUTTONUP:
1951 case WM_MBUTTONUP:
1952 case WM_RBUTTONUP:
1953 case WM_LBUTTONDOWN:
1954 case WM_MBUTTONDOWN:
1955 case WM_RBUTTONDOWN:
1957 OLEDD_TrackStateChange((TrackerWindowInfo*)GetWindowLongA(hwnd, 0));
1958 break;
1960 case WM_DESTROY:
1962 KillTimer(hwnd, DRAG_TIMER_ID);
1963 break;
1968 * This is a window proc after all. Let's call the default.
1970 return DefWindowProcA (hwnd, uMsg, wParam, lParam);
1973 /***
1974 * OLEDD_TrackMouseMove()
1976 * This method is invoked while a drag and drop operation is in effect.
1977 * it will generate the appropriate callbacks in the drop source
1978 * and drop target. It will also provide the expected feedback to
1979 * the user.
1981 * params:
1982 * trackerInfo - Pointer to the structure identifying the
1983 * drag & drop operation that is currently
1984 * active.
1986 static void OLEDD_TrackMouseMove(TrackerWindowInfo* trackerInfo)
1988 HWND hwndNewTarget = 0;
1989 HRESULT hr = S_OK;
1990 POINT pt;
1993 * Get the handle of the window under the mouse
1995 pt.x = trackerInfo->curMousePos.x;
1996 pt.y = trackerInfo->curMousePos.y;
1997 hwndNewTarget = WindowFromPoint(pt);
2000 * Every time, we re-initialize the effects passed to the
2001 * IDropTarget to the effects allowed by the source.
2003 *trackerInfo->pdwEffect = trackerInfo->dwOKEffect;
2006 * If we are hovering over the same target as before, send the
2007 * DragOver notification
2009 if ( (trackerInfo->curDragTarget != 0) &&
2010 (trackerInfo->curTargetHWND == hwndNewTarget) )
2012 IDropTarget_DragOver(trackerInfo->curDragTarget,
2013 trackerInfo->dwKeyState,
2014 trackerInfo->curMousePos,
2015 trackerInfo->pdwEffect);
2017 else
2019 DropTargetNode* newDropTargetNode = 0;
2022 * If we changed window, we have to notify our old target and check for
2023 * the new one.
2025 if (trackerInfo->curDragTarget!=0)
2027 IDropTarget_DragLeave(trackerInfo->curDragTarget);
2031 * Make sure we're hovering over a window.
2033 if (hwndNewTarget!=0)
2036 * Find-out if there is a drag target under the mouse
2038 HWND nexttar = hwndNewTarget;
2039 trackerInfo->curTargetHWND = hwndNewTarget;
2041 do {
2042 newDropTargetNode = OLEDD_FindDropTarget(nexttar);
2043 } while (!newDropTargetNode && (nexttar = GetParent(nexttar)) != 0);
2044 if(nexttar) hwndNewTarget = nexttar;
2046 trackerInfo->curDragTargetHWND = hwndNewTarget;
2047 trackerInfo->curDragTarget = newDropTargetNode ? newDropTargetNode->dropTarget : 0;
2050 * If there is, notify it that we just dragged-in
2052 if (trackerInfo->curDragTarget!=0)
2054 IDropTarget_DragEnter(trackerInfo->curDragTarget,
2055 trackerInfo->dataObject,
2056 trackerInfo->dwKeyState,
2057 trackerInfo->curMousePos,
2058 trackerInfo->pdwEffect);
2061 else
2064 * The mouse is not over a window so we don't track anything.
2066 trackerInfo->curDragTargetHWND = 0;
2067 trackerInfo->curTargetHWND = 0;
2068 trackerInfo->curDragTarget = 0;
2073 * Now that we have done that, we have to tell the source to give
2074 * us feedback on the work being done by the target. If we don't
2075 * have a target, simulate no effect.
2077 if (trackerInfo->curDragTarget==0)
2079 *trackerInfo->pdwEffect = DROPEFFECT_NONE;
2082 hr = IDropSource_GiveFeedback(trackerInfo->dropSource,
2083 *trackerInfo->pdwEffect);
2086 * When we ask for feedback from the drop source, sometimes it will
2087 * do all the necessary work and sometimes it will not handle it
2088 * when that's the case, we must display the standard drag and drop
2089 * cursors.
2091 if (hr==DRAGDROP_S_USEDEFAULTCURSORS)
2093 if (*trackerInfo->pdwEffect & DROPEFFECT_MOVE)
2095 SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(1)));
2097 else if (*trackerInfo->pdwEffect & DROPEFFECT_COPY)
2099 SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(2)));
2101 else if (*trackerInfo->pdwEffect & DROPEFFECT_LINK)
2103 SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(3)));
2105 else
2107 SetCursor(LoadCursorA(OLE32_hInstance, MAKEINTRESOURCEA(0)));
2112 /***
2113 * OLEDD_TrackStateChange()
2115 * This method is invoked while a drag and drop operation is in effect.
2116 * It is used to notify the drop target/drop source callbacks when
2117 * the state of the keyboard or mouse button change.
2119 * params:
2120 * trackerInfo - Pointer to the structure identifying the
2121 * drag & drop operation that is currently
2122 * active.
2124 static void OLEDD_TrackStateChange(TrackerWindowInfo* trackerInfo)
2127 * Ask the drop source what to do with the operation.
2129 trackerInfo->returnValue = IDropSource_QueryContinueDrag(
2130 trackerInfo->dropSource,
2131 trackerInfo->escPressed,
2132 trackerInfo->dwKeyState);
2135 * All the return valued will stop the operation except the S_OK
2136 * return value.
2138 if (trackerInfo->returnValue!=S_OK)
2141 * Make sure the message loop in DoDragDrop stops
2143 trackerInfo->trackingDone = TRUE;
2146 * Release the mouse in case the drop target decides to show a popup
2147 * or a menu or something.
2149 ReleaseCapture();
2152 * If we end-up over a target, drop the object in the target or
2153 * inform the target that the operation was cancelled.
2155 if (trackerInfo->curDragTarget!=0)
2157 switch (trackerInfo->returnValue)
2160 * If the source wants us to complete the operation, we tell
2161 * the drop target that we just dropped the object in it.
2163 case DRAGDROP_S_DROP:
2165 IDropTarget_Drop(trackerInfo->curDragTarget,
2166 trackerInfo->dataObject,
2167 trackerInfo->dwKeyState,
2168 trackerInfo->curMousePos,
2169 trackerInfo->pdwEffect);
2170 break;
2173 * If the source told us that we should cancel, fool the drop
2174 * target by telling it that the mouse left it's window.
2175 * Also set the drop effect to "NONE" in case the application
2176 * ignores the result of DoDragDrop.
2178 case DRAGDROP_S_CANCEL:
2179 IDropTarget_DragLeave(trackerInfo->curDragTarget);
2180 *trackerInfo->pdwEffect = DROPEFFECT_NONE;
2181 break;
2187 /***
2188 * OLEDD_GetButtonState()
2190 * This method will use the current state of the keyboard to build
2191 * a button state mask equivalent to the one passed in the
2192 * WM_MOUSEMOVE wParam.
2194 static DWORD OLEDD_GetButtonState(void)
2196 BYTE keyboardState[256];
2197 DWORD keyMask = 0;
2199 GetKeyboardState(keyboardState);
2201 if ( (keyboardState[VK_SHIFT] & 0x80) !=0)
2202 keyMask |= MK_SHIFT;
2204 if ( (keyboardState[VK_CONTROL] & 0x80) !=0)
2205 keyMask |= MK_CONTROL;
2207 if ( (keyboardState[VK_LBUTTON] & 0x80) !=0)
2208 keyMask |= MK_LBUTTON;
2210 if ( (keyboardState[VK_RBUTTON] & 0x80) !=0)
2211 keyMask |= MK_RBUTTON;
2213 if ( (keyboardState[VK_MBUTTON] & 0x80) !=0)
2214 keyMask |= MK_MBUTTON;
2216 return keyMask;
2219 /***
2220 * OLEDD_GetButtonState()
2222 * This method will read the default value of the registry key in
2223 * parameter and extract a DWORD value from it. The registry key value
2224 * can be in a string key or a DWORD key.
2226 * params:
2227 * regKey - Key to read the default value from
2228 * pdwValue - Pointer to the location where the DWORD
2229 * value is returned. This value is not modified
2230 * if the value is not found.
2233 static void OLEUTL_ReadRegistryDWORDValue(
2234 HKEY regKey,
2235 DWORD* pdwValue)
2237 char buffer[20];
2238 DWORD dwKeyType;
2239 DWORD cbData = 20;
2240 LONG lres;
2242 lres = RegQueryValueExA(regKey,
2244 NULL,
2245 &dwKeyType,
2246 (LPBYTE)buffer,
2247 &cbData);
2249 if (lres==ERROR_SUCCESS)
2251 switch (dwKeyType)
2253 case REG_DWORD:
2254 *pdwValue = *(DWORD*)buffer;
2255 break;
2256 case REG_EXPAND_SZ:
2257 case REG_MULTI_SZ:
2258 case REG_SZ:
2259 *pdwValue = (DWORD)strtoul(buffer, NULL, 10);
2260 break;
2265 /******************************************************************************
2266 * OleDraw (OLE32.@)
2268 * The operation of this function is documented literally in the WinAPI
2269 * documentation to involve a QueryInterface for the IViewObject interface,
2270 * followed by a call to IViewObject::Draw.
2272 HRESULT WINAPI OleDraw(
2273 IUnknown *pUnk,
2274 DWORD dwAspect,
2275 HDC hdcDraw,
2276 LPCRECT lprcBounds)
2278 HRESULT hres;
2279 IViewObject *viewobject;
2281 hres = IUnknown_QueryInterface(pUnk,
2282 &IID_IViewObject,
2283 (void**)&viewobject);
2285 if (SUCCEEDED(hres))
2287 RECTL rectl;
2289 rectl.left = lprcBounds->left;
2290 rectl.right = lprcBounds->right;
2291 rectl.top = lprcBounds->top;
2292 rectl.bottom = lprcBounds->bottom;
2293 hres = IViewObject_Draw(viewobject, dwAspect, -1, 0, 0, 0, hdcDraw, &rectl, 0, 0, 0);
2295 IViewObject_Release(viewobject);
2296 return hres;
2298 else
2300 return DV_E_NOIVIEWOBJECT;
2304 /***********************************************************************
2305 * OleTranslateAccelerator [OLE32.@]
2307 HRESULT WINAPI OleTranslateAccelerator (LPOLEINPLACEFRAME lpFrame,
2308 LPOLEINPLACEFRAMEINFO lpFrameInfo, LPMSG lpmsg)
2310 WORD wID;
2312 TRACE("(%p,%p,%p)\n", lpFrame, lpFrameInfo, lpmsg);
2314 if (IsAccelerator(lpFrameInfo->haccel,lpFrameInfo->cAccelEntries,lpmsg,&wID))
2315 return IOleInPlaceFrame_TranslateAccelerator(lpFrame,lpmsg,wID);
2317 return S_FALSE;
2320 /******************************************************************************
2321 * OleCreate [OLE32.@]
2324 HRESULT WINAPI OleCreate(
2325 REFCLSID rclsid,
2326 REFIID riid,
2327 DWORD renderopt,
2328 LPFORMATETC pFormatEtc,
2329 LPOLECLIENTSITE pClientSite,
2330 LPSTORAGE pStg,
2331 LPVOID* ppvObj)
2333 HRESULT hres;
2334 IUnknown * pUnk = NULL;
2335 IOleObject *pOleObject = NULL;
2337 FIXME("\n\t%s\n\t%s semi-stub!\n", debugstr_guid(rclsid), debugstr_guid(riid));
2339 hres = CoCreateInstance(rclsid, 0, CLSCTX_INPROC_SERVER|CLSCTX_INPROC_HANDLER|CLSCTX_LOCAL_SERVER , riid, (LPVOID*)&pUnk);
2341 if (SUCCEEDED(hres))
2342 hres = IStorage_SetClass(pStg, rclsid);
2344 if (pClientSite && SUCCEEDED(hres))
2346 hres = IUnknown_QueryInterface(pUnk, &IID_IOleObject, (LPVOID*)&pOleObject);
2347 if (SUCCEEDED(hres))
2349 DWORD dwStatus;
2350 hres = IOleObject_GetMiscStatus(pOleObject, DVASPECT_CONTENT, &dwStatus);
2354 if (SUCCEEDED(hres))
2356 IPersistStorage * pPS;
2357 if (SUCCEEDED((hres = IUnknown_QueryInterface(pUnk, &IID_IPersistStorage, (LPVOID*)&pPS))))
2359 TRACE("trying to set stg %p\n", pStg);
2360 hres = IPersistStorage_InitNew(pPS, pStg);
2361 TRACE("-- result 0x%08x\n", hres);
2362 IPersistStorage_Release(pPS);
2366 if (pClientSite && SUCCEEDED(hres))
2368 TRACE("trying to set clientsite %p\n", pClientSite);
2369 hres = IOleObject_SetClientSite(pOleObject, pClientSite);
2370 TRACE("-- result 0x%08x\n", hres);
2373 if (pOleObject)
2374 IOleObject_Release(pOleObject);
2376 if (((renderopt == OLERENDER_DRAW) || (renderopt == OLERENDER_FORMAT)) &&
2377 SUCCEEDED(hres))
2379 IRunnableObject *pRunnable;
2380 IOleCache *pOleCache;
2381 HRESULT hres2;
2383 hres2 = IUnknown_QueryInterface(pUnk, &IID_IRunnableObject, (void **)&pRunnable);
2384 if (SUCCEEDED(hres2))
2386 hres = IRunnableObject_Run(pRunnable, NULL);
2387 IRunnableObject_Release(pRunnable);
2390 if (SUCCEEDED(hres))
2392 hres2 = IUnknown_QueryInterface(pUnk, &IID_IOleCache, (void **)&pOleCache);
2393 if (SUCCEEDED(hres2))
2395 DWORD dwConnection;
2396 hres = IOleCache_Cache(pOleCache, pFormatEtc, ADVF_PRIMEFIRST, &dwConnection);
2397 IOleCache_Release(pOleCache);
2402 if (FAILED(hres) && pUnk)
2404 IUnknown_Release(pUnk);
2405 pUnk = NULL;
2408 *ppvObj = pUnk;
2410 TRACE("-- %p\n", pUnk);
2411 return hres;
2414 /******************************************************************************
2415 * OleGetAutoConvert [OLE32.@]
2417 HRESULT WINAPI OleGetAutoConvert(REFCLSID clsidOld, LPCLSID pClsidNew)
2419 static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2420 HKEY hkey = NULL;
2421 WCHAR buf[CHARS_IN_GUID];
2422 LONG len;
2423 HRESULT res = S_OK;
2425 res = COM_OpenKeyForCLSID(clsidOld, wszAutoConvertTo, KEY_READ, &hkey);
2426 if (FAILED(res))
2427 goto done;
2429 len = sizeof(buf);
2430 if (RegQueryValueW(hkey, NULL, buf, &len))
2432 res = REGDB_E_KEYMISSING;
2433 goto done;
2435 res = CLSIDFromString(buf, pClsidNew);
2436 done:
2437 if (hkey) RegCloseKey(hkey);
2438 return res;
2441 /******************************************************************************
2442 * OleSetAutoConvert [OLE32.@]
2444 HRESULT WINAPI OleSetAutoConvert(REFCLSID clsidOld, REFCLSID clsidNew)
2446 static const WCHAR wszAutoConvertTo[] = {'A','u','t','o','C','o','n','v','e','r','t','T','o',0};
2447 HKEY hkey = NULL;
2448 WCHAR szClsidNew[CHARS_IN_GUID];
2449 HRESULT res = S_OK;
2451 TRACE("(%s,%s)\n", debugstr_guid(clsidOld), debugstr_guid(clsidNew));
2453 res = COM_OpenKeyForCLSID(clsidOld, NULL, KEY_READ | KEY_WRITE, &hkey);
2454 if (FAILED(res))
2455 goto done;
2456 StringFromGUID2(clsidNew, szClsidNew, CHARS_IN_GUID);
2457 if (RegSetValueW(hkey, wszAutoConvertTo, REG_SZ, szClsidNew, (strlenW(szClsidNew)+1) * sizeof(WCHAR)))
2459 res = REGDB_E_WRITEREGDB;
2460 goto done;
2463 done:
2464 if (hkey) RegCloseKey(hkey);
2465 return res;
2468 /******************************************************************************
2469 * OleDoAutoConvert [OLE32.@]
2471 HRESULT WINAPI OleDoAutoConvert(LPSTORAGE pStg, LPCLSID pClsidNew)
2473 FIXME("(%p,%p) : stub\n",pStg,pClsidNew);
2474 return E_NOTIMPL;
2477 /******************************************************************************
2478 * OleIsRunning [OLE32.@]
2480 BOOL WINAPI OleIsRunning(LPOLEOBJECT pObject)
2482 IRunnableObject *pRunnable;
2483 HRESULT hr;
2484 BOOL running;
2486 TRACE("(%p)\n", pObject);
2488 hr = IOleObject_QueryInterface(pObject, &IID_IRunnableObject, (void **)&pRunnable);
2489 if (FAILED(hr))
2490 return FALSE;
2491 running = IRunnableObject_IsRunning(pRunnable);
2492 IRunnableObject_Release(pRunnable);
2493 return running;
2496 /***********************************************************************
2497 * OleNoteObjectVisible [OLE32.@]
2499 HRESULT WINAPI OleNoteObjectVisible(LPUNKNOWN pUnknown, BOOL bVisible)
2501 TRACE("(%p, %s)\n", pUnknown, bVisible ? "TRUE" : "FALSE");
2502 return CoLockObjectExternal(pUnknown, bVisible, TRUE);
2506 /***********************************************************************
2507 * OLE_FreeClipDataArray [internal]
2509 * NOTES:
2510 * frees the data associated with an array of CLIPDATAs
2512 static void OLE_FreeClipDataArray(ULONG count, CLIPDATA * pClipDataArray)
2514 ULONG i;
2515 for (i = 0; i < count; i++)
2516 if (pClipDataArray[i].pClipData)
2517 CoTaskMemFree(pClipDataArray[i].pClipData);
2520 /***********************************************************************
2521 * PropSysAllocString [OLE32.@]
2522 * NOTES:
2523 * Basically a copy of SysAllocStringLen.
2525 BSTR WINAPI PropSysAllocString(LPCOLESTR str)
2527 DWORD bufferSize;
2528 DWORD* newBuffer;
2529 WCHAR* stringBuffer;
2530 int len;
2532 if (!str) return 0;
2534 len = lstrlenW(str);
2536 * Find the length of the buffer passed-in, in bytes.
2538 bufferSize = len * sizeof (WCHAR);
2541 * Allocate a new buffer to hold the string.
2542 * Don't forget to keep an empty spot at the beginning of the
2543 * buffer for the character count and an extra character at the
2544 * end for the NULL.
2546 newBuffer = HeapAlloc(GetProcessHeap(), 0,
2547 bufferSize + sizeof(WCHAR) + sizeof(DWORD));
2550 * If the memory allocation failed, return a null pointer.
2552 if (newBuffer==0)
2553 return 0;
2556 * Copy the length of the string in the placeholder.
2558 *newBuffer = bufferSize;
2561 * Skip the byte count.
2563 newBuffer++;
2566 * Copy the information in the buffer.
2567 * Since it is valid to pass a NULL pointer here, we'll initialize the
2568 * buffer to nul if it is the case.
2570 if (str != 0)
2571 memcpy(newBuffer, str, bufferSize);
2572 else
2573 memset(newBuffer, 0, bufferSize);
2576 * Make sure that there is a nul character at the end of the
2577 * string.
2579 stringBuffer = (WCHAR*)newBuffer;
2580 stringBuffer[len] = L'\0';
2582 return (LPWSTR)stringBuffer;
2585 /***********************************************************************
2586 * PropSysFreeString [OLE32.@]
2587 * NOTES
2588 * Copy of SysFreeString.
2590 void WINAPI PropSysFreeString(LPOLESTR str)
2592 DWORD* bufferPointer;
2594 /* NULL is a valid parameter */
2595 if(!str) return;
2598 * We have to be careful when we free a BSTR pointer, it points to
2599 * the beginning of the string but it skips the byte count contained
2600 * before the string.
2602 bufferPointer = (DWORD*)str;
2604 bufferPointer--;
2607 * Free the memory from its "real" origin.
2609 HeapFree(GetProcessHeap(), 0, bufferPointer);
2612 /******************************************************************************
2613 * Check if a PROPVARIANT's type is valid.
2615 static inline HRESULT PROPVARIANT_ValidateType(VARTYPE vt)
2617 switch (vt)
2619 case VT_EMPTY:
2620 case VT_NULL:
2621 case VT_I2:
2622 case VT_I4:
2623 case VT_R4:
2624 case VT_R8:
2625 case VT_CY:
2626 case VT_DATE:
2627 case VT_BSTR:
2628 case VT_ERROR:
2629 case VT_BOOL:
2630 case VT_UI1:
2631 case VT_UI2:
2632 case VT_UI4:
2633 case VT_I8:
2634 case VT_UI8:
2635 case VT_LPSTR:
2636 case VT_LPWSTR:
2637 case VT_FILETIME:
2638 case VT_BLOB:
2639 case VT_STREAM:
2640 case VT_STORAGE:
2641 case VT_STREAMED_OBJECT:
2642 case VT_STORED_OBJECT:
2643 case VT_BLOB_OBJECT:
2644 case VT_CF:
2645 case VT_CLSID:
2646 case VT_I2|VT_VECTOR:
2647 case VT_I4|VT_VECTOR:
2648 case VT_R4|VT_VECTOR:
2649 case VT_R8|VT_VECTOR:
2650 case VT_CY|VT_VECTOR:
2651 case VT_DATE|VT_VECTOR:
2652 case VT_BSTR|VT_VECTOR:
2653 case VT_ERROR|VT_VECTOR:
2654 case VT_BOOL|VT_VECTOR:
2655 case VT_VARIANT|VT_VECTOR:
2656 case VT_UI1|VT_VECTOR:
2657 case VT_UI2|VT_VECTOR:
2658 case VT_UI4|VT_VECTOR:
2659 case VT_I8|VT_VECTOR:
2660 case VT_UI8|VT_VECTOR:
2661 case VT_LPSTR|VT_VECTOR:
2662 case VT_LPWSTR|VT_VECTOR:
2663 case VT_FILETIME|VT_VECTOR:
2664 case VT_CF|VT_VECTOR:
2665 case VT_CLSID|VT_VECTOR:
2666 return S_OK;
2668 WARN("Bad type %d\n", vt);
2669 return STG_E_INVALIDPARAMETER;
2672 /***********************************************************************
2673 * PropVariantClear [OLE32.@]
2675 HRESULT WINAPI PropVariantClear(PROPVARIANT * pvar) /* [in/out] */
2677 HRESULT hr;
2679 TRACE("(%p)\n", pvar);
2681 if (!pvar)
2682 return S_OK;
2684 hr = PROPVARIANT_ValidateType(pvar->vt);
2685 if (FAILED(hr))
2686 return hr;
2688 switch(pvar->vt)
2690 case VT_EMPTY:
2691 case VT_NULL:
2692 case VT_I2:
2693 case VT_I4:
2694 case VT_R4:
2695 case VT_R8:
2696 case VT_CY:
2697 case VT_DATE:
2698 case VT_ERROR:
2699 case VT_BOOL:
2700 case VT_UI1:
2701 case VT_UI2:
2702 case VT_UI4:
2703 case VT_I8:
2704 case VT_UI8:
2705 case VT_FILETIME:
2706 break;
2707 case VT_STREAM:
2708 case VT_STREAMED_OBJECT:
2709 case VT_STORAGE:
2710 case VT_STORED_OBJECT:
2711 if (pvar->u.pStream)
2712 IUnknown_Release(pvar->u.pStream);
2713 break;
2714 case VT_CLSID:
2715 case VT_LPSTR:
2716 case VT_LPWSTR:
2717 /* pick an arbitary typed pointer - we don't care about the type
2718 * as we are just freeing it */
2719 CoTaskMemFree(pvar->u.puuid);
2720 break;
2721 case VT_BLOB:
2722 case VT_BLOB_OBJECT:
2723 CoTaskMemFree(pvar->u.blob.pBlobData);
2724 break;
2725 case VT_BSTR:
2726 if (pvar->u.bstrVal)
2727 PropSysFreeString(pvar->u.bstrVal);
2728 break;
2729 case VT_CF:
2730 if (pvar->u.pclipdata)
2732 OLE_FreeClipDataArray(1, pvar->u.pclipdata);
2733 CoTaskMemFree(pvar->u.pclipdata);
2735 break;
2736 default:
2737 if (pvar->vt & VT_VECTOR)
2739 ULONG i;
2741 switch (pvar->vt & ~VT_VECTOR)
2743 case VT_VARIANT:
2744 FreePropVariantArray(pvar->u.capropvar.cElems, pvar->u.capropvar.pElems);
2745 break;
2746 case VT_CF:
2747 OLE_FreeClipDataArray(pvar->u.caclipdata.cElems, pvar->u.caclipdata.pElems);
2748 break;
2749 case VT_BSTR:
2750 for (i = 0; i < pvar->u.cabstr.cElems; i++)
2751 PropSysFreeString(pvar->u.cabstr.pElems[i]);
2752 break;
2753 case VT_LPSTR:
2754 for (i = 0; i < pvar->u.calpstr.cElems; i++)
2755 CoTaskMemFree(pvar->u.calpstr.pElems[i]);
2756 break;
2757 case VT_LPWSTR:
2758 for (i = 0; i < pvar->u.calpwstr.cElems; i++)
2759 CoTaskMemFree(pvar->u.calpwstr.pElems[i]);
2760 break;
2762 if (pvar->vt & ~VT_VECTOR)
2764 /* pick an arbitary VT_VECTOR structure - they all have the same
2765 * memory layout */
2766 CoTaskMemFree(pvar->u.capropvar.pElems);
2769 else
2770 WARN("Invalid/unsupported type %d\n", pvar->vt);
2773 ZeroMemory(pvar, sizeof(*pvar));
2775 return S_OK;
2778 /***********************************************************************
2779 * PropVariantCopy [OLE32.@]
2781 HRESULT WINAPI PropVariantCopy(PROPVARIANT *pvarDest, /* [out] */
2782 const PROPVARIANT *pvarSrc) /* [in] */
2784 ULONG len;
2785 HRESULT hr;
2787 TRACE("(%p, %p)\n", pvarDest, pvarSrc);
2789 hr = PROPVARIANT_ValidateType(pvarSrc->vt);
2790 if (FAILED(hr))
2791 return hr;
2793 /* this will deal with most cases */
2794 CopyMemory(pvarDest, pvarSrc, sizeof(*pvarDest));
2796 switch(pvarSrc->vt)
2798 case VT_FILETIME:
2799 break;
2800 case VT_STREAM:
2801 case VT_STREAMED_OBJECT:
2802 case VT_STORAGE:
2803 case VT_STORED_OBJECT:
2804 IUnknown_AddRef((LPUNKNOWN)pvarDest->u.pStream);
2805 break;
2806 case VT_CLSID:
2807 pvarDest->u.puuid = CoTaskMemAlloc(sizeof(CLSID));
2808 CopyMemory(pvarDest->u.puuid, pvarSrc->u.puuid, sizeof(CLSID));
2809 break;
2810 case VT_LPSTR:
2811 len = strlen(pvarSrc->u.pszVal);
2812 pvarDest->u.pszVal = CoTaskMemAlloc((len+1)*sizeof(CHAR));
2813 CopyMemory(pvarDest->u.pszVal, pvarSrc->u.pszVal, (len+1)*sizeof(CHAR));
2814 break;
2815 case VT_LPWSTR:
2816 len = lstrlenW(pvarSrc->u.pwszVal);
2817 pvarDest->u.pwszVal = CoTaskMemAlloc((len+1)*sizeof(WCHAR));
2818 CopyMemory(pvarDest->u.pwszVal, pvarSrc->u.pwszVal, (len+1)*sizeof(WCHAR));
2819 break;
2820 case VT_BLOB:
2821 case VT_BLOB_OBJECT:
2822 if (pvarSrc->u.blob.pBlobData)
2824 len = pvarSrc->u.blob.cbSize;
2825 pvarDest->u.blob.pBlobData = CoTaskMemAlloc(len);
2826 CopyMemory(pvarDest->u.blob.pBlobData, pvarSrc->u.blob.pBlobData, len);
2828 break;
2829 case VT_BSTR:
2830 pvarDest->u.bstrVal = PropSysAllocString(pvarSrc->u.bstrVal);
2831 break;
2832 case VT_CF:
2833 if (pvarSrc->u.pclipdata)
2835 len = pvarSrc->u.pclipdata->cbSize - sizeof(pvarSrc->u.pclipdata->ulClipFmt);
2836 pvarDest->u.pclipdata = CoTaskMemAlloc(sizeof (CLIPDATA));
2837 pvarDest->u.pclipdata->cbSize = pvarSrc->u.pclipdata->cbSize;
2838 pvarDest->u.pclipdata->ulClipFmt = pvarSrc->u.pclipdata->ulClipFmt;
2839 pvarDest->u.pclipdata->pClipData = CoTaskMemAlloc(len);
2840 CopyMemory(pvarDest->u.pclipdata->pClipData, pvarSrc->u.pclipdata->pClipData, len);
2842 break;
2843 default:
2844 if (pvarSrc->vt & VT_VECTOR)
2846 int elemSize;
2847 ULONG i;
2849 switch(pvarSrc->vt & ~VT_VECTOR)
2851 case VT_I1: elemSize = sizeof(pvarSrc->u.cVal); break;
2852 case VT_UI1: elemSize = sizeof(pvarSrc->u.bVal); break;
2853 case VT_I2: elemSize = sizeof(pvarSrc->u.iVal); break;
2854 case VT_UI2: elemSize = sizeof(pvarSrc->u.uiVal); break;
2855 case VT_BOOL: elemSize = sizeof(pvarSrc->u.boolVal); break;
2856 case VT_I4: elemSize = sizeof(pvarSrc->u.lVal); break;
2857 case VT_UI4: elemSize = sizeof(pvarSrc->u.ulVal); break;
2858 case VT_R4: elemSize = sizeof(pvarSrc->u.fltVal); break;
2859 case VT_R8: elemSize = sizeof(pvarSrc->u.dblVal); break;
2860 case VT_ERROR: elemSize = sizeof(pvarSrc->u.scode); break;
2861 case VT_I8: elemSize = sizeof(pvarSrc->u.hVal); break;
2862 case VT_UI8: elemSize = sizeof(pvarSrc->u.uhVal); break;
2863 case VT_CY: elemSize = sizeof(pvarSrc->u.cyVal); break;
2864 case VT_DATE: elemSize = sizeof(pvarSrc->u.date); break;
2865 case VT_FILETIME: elemSize = sizeof(pvarSrc->u.filetime); break;
2866 case VT_CLSID: elemSize = sizeof(*pvarSrc->u.puuid); break;
2867 case VT_CF: elemSize = sizeof(*pvarSrc->u.pclipdata); break;
2868 case VT_BSTR: elemSize = sizeof(*pvarSrc->u.bstrVal); break;
2869 case VT_LPSTR: elemSize = sizeof(*pvarSrc->u.pszVal); break;
2870 case VT_LPWSTR: elemSize = sizeof(*pvarSrc->u.pwszVal); break;
2872 case VT_VARIANT:
2873 default:
2874 FIXME("Invalid element type: %ul\n", pvarSrc->vt & ~VT_VECTOR);
2875 return E_INVALIDARG;
2877 len = pvarSrc->u.capropvar.cElems;
2878 pvarDest->u.capropvar.pElems = CoTaskMemAlloc(len * elemSize);
2879 if (pvarSrc->vt == (VT_VECTOR | VT_VARIANT))
2881 for (i = 0; i < len; i++)
2882 PropVariantCopy(&pvarDest->u.capropvar.pElems[i], &pvarSrc->u.capropvar.pElems[i]);
2884 else if (pvarSrc->vt == (VT_VECTOR | VT_CF))
2886 FIXME("Copy clipformats\n");
2888 else if (pvarSrc->vt == (VT_VECTOR | VT_BSTR))
2890 for (i = 0; i < len; i++)
2891 pvarDest->u.cabstr.pElems[i] = PropSysAllocString(pvarSrc->u.cabstr.pElems[i]);
2893 else if (pvarSrc->vt == (VT_VECTOR | VT_LPSTR))
2895 size_t strLen;
2896 for (i = 0; i < len; i++)
2898 strLen = lstrlenA(pvarSrc->u.calpstr.pElems[i]) + 1;
2899 pvarDest->u.calpstr.pElems[i] = CoTaskMemAlloc(strLen);
2900 memcpy(pvarDest->u.calpstr.pElems[i],
2901 pvarSrc->u.calpstr.pElems[i], strLen);
2904 else if (pvarSrc->vt == (VT_VECTOR | VT_LPWSTR))
2906 size_t strLen;
2907 for (i = 0; i < len; i++)
2909 strLen = (lstrlenW(pvarSrc->u.calpwstr.pElems[i]) + 1) *
2910 sizeof(WCHAR);
2911 pvarDest->u.calpstr.pElems[i] = CoTaskMemAlloc(strLen);
2912 memcpy(pvarDest->u.calpstr.pElems[i],
2913 pvarSrc->u.calpstr.pElems[i], strLen);
2916 else
2917 CopyMemory(pvarDest->u.capropvar.pElems, pvarSrc->u.capropvar.pElems, len * elemSize);
2919 else
2920 WARN("Invalid/unsupported type %d\n", pvarSrc->vt);
2923 return S_OK;
2926 /***********************************************************************
2927 * FreePropVariantArray [OLE32.@]
2929 HRESULT WINAPI FreePropVariantArray(ULONG cVariants, /* [in] */
2930 PROPVARIANT *rgvars) /* [in/out] */
2932 ULONG i;
2934 TRACE("(%u, %p)\n", cVariants, rgvars);
2936 if (!rgvars)
2937 return E_INVALIDARG;
2939 for(i = 0; i < cVariants; i++)
2940 PropVariantClear(&rgvars[i]);
2942 return S_OK;
2945 /******************************************************************************
2946 * DllDebugObjectRPCHook (OLE32.@)
2947 * turns on and off internal debugging, pointer is only used on macintosh
2950 BOOL WINAPI DllDebugObjectRPCHook(BOOL b, void *dummy)
2952 FIXME("stub\n");
2953 return TRUE;