text:
#include "StdAfx.h"
#include "WndBase.h"
#include "DuiActiveX.h"
#include "exdispid.h"
#include <comdef.h>
#include <mshtmhst.h>	// IDocHostUIHandlerʹÓÃ
#include "../activex/duicomcli.h"
#include "../activex/flash10t.tlh"
#include "../activex/wmp.tlh"

/////////////////////////////////////////////////////////////////////////////////////
//

class CActiveXCtrl;

/////////////////////////////////////////////////////////////////////////////////////
// CActiveXWnd

class CActiveXWnd : public CWindowWnd
{
public:
    HWND Init(CActiveXCtrl* pOwner, HWND hWndParent);

    virtual LPCTSTR GetWindowClassName() const;
    virtual void OnFinalMessage(HWND hWnd);

protected:
    void DoVerb(LONG iVerb);

	virtual LRESULT OnMouseActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
	virtual LRESULT OnSetFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
	virtual LRESULT OnKillFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
	virtual LRESULT OnEraseBkgnd(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
	virtual LRESULT OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);

protected:
    CActiveXCtrl* m_pOwner;
};

/////////////////////////////////////////////////////////////////////////////////////
// CActiveXEnum

class CActiveXEnum : public IEnumUnknown
{
public:
    CActiveXEnum(IUnknown* pUnk) : m_pUnk(pUnk), m_dwRef(1), m_iPos(0)
    {
        m_pUnk->AddRef();
    }
    ~CActiveXEnum()
    {
        m_pUnk->Release();
    }

    LONG m_iPos;
    ULONG m_dwRef;
    IUnknown* m_pUnk;

    STDMETHOD_(ULONG,AddRef)()
    {
        return ++m_dwRef;
    }
    STDMETHOD_(ULONG,Release)()
    {
        LONG lRef = --m_dwRef;
        if( lRef == 0 ) delete this;
        return lRef;
    }
    STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppvObject)
    {
        *ppvObject = NULL;
        if( riid == IID_IUnknown ) *ppvObject = static_cast<IEnumUnknown*>(this);
        else if( riid == IID_IEnumUnknown ) *ppvObject = static_cast<IEnumUnknown*>(this);
        if( *ppvObject != NULL ) AddRef();
        return *ppvObject == NULL ? E_NOINTERFACE : S_OK;
    }
    STDMETHOD(Next)(ULONG celt, IUnknown **rgelt, ULONG *pceltFetched)
    {
        if( pceltFetched != NULL ) *pceltFetched = 0;
        if( ++m_iPos > 1 ) return S_FALSE;
        *rgelt = m_pUnk;
        (*rgelt)->AddRef();
        if( pceltFetched != NULL ) *pceltFetched = 1;
        return S_OK;
    }
    STDMETHOD(Skip)(ULONG celt)
    {
        m_iPos += celt;
        return S_OK;
    }
    STDMETHOD(Reset)(void)
    {
        m_iPos = 0;
        return S_OK;
    }
    STDMETHOD(Clone)(IEnumUnknown **ppenum)
    {
        return E_NOTIMPL;
    }
};

/////////////////////////////////////////////////////////////////////////////////////
// CActiveXFrameWnd

class CActiveXFrameWnd : public IOleInPlaceFrame
{
public:
    CActiveXFrameWnd(CDuiActiveX* pOwner)
		: m_dwRef(1), m_pOwner(pOwner), m_pActiveObject(NULL)
    {
    }
    ~CActiveXFrameWnd()
    {
        if( m_pActiveObject != NULL ) m_pActiveObject->Release();
    }

    ULONG						m_dwRef;
    CDuiActiveX*				m_pOwner;
    IOleInPlaceActiveObject*	m_pActiveObject;

    // IUnknown
    STDMETHOD_(ULONG,AddRef)()
    {
        return ++m_dwRef;
    }
    STDMETHOD_(ULONG,Release)()
    {
        ULONG lRef = --m_dwRef;
        if( lRef == 0 ) delete this;
        return lRef;
    }
    STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppvObject)
    {
        *ppvObject = NULL;
        if( riid == IID_IUnknown ) *ppvObject = static_cast<IOleInPlaceFrame*>(this);
        else if( riid == IID_IOleWindow ) *ppvObject = static_cast<IOleWindow*>(this);
        else if( riid == IID_IOleInPlaceFrame ) *ppvObject = static_cast<IOleInPlaceFrame*>(this);
        else if( riid == IID_IOleInPlaceUIWindow ) *ppvObject = static_cast<IOleInPlaceUIWindow*>(this);
        if( *ppvObject != NULL ) AddRef();
        return *ppvObject == NULL ? E_NOINTERFACE : S_OK;
    }
    // IOleInPlaceFrameWindow
    STDMETHOD(InsertMenus)(HMENU /*hmenuShared*/, LPOLEMENUGROUPWIDTHS /*lpMenuWidths*/)
    {
        return S_OK;
    }
    STDMETHOD(SetMenu)(HMENU /*hmenuShared*/, HOLEMENU /*holemenu*/, HWND /*hwndActiveObject*/)
    {
        return S_OK;
    }
    STDMETHOD(RemoveMenus)(HMENU /*hmenuShared*/)
    {
        return S_OK;
    }
    STDMETHOD(SetStatusText)(LPCOLESTR /*pszStatusText*/)
    {
        return S_OK;
    }
    STDMETHOD(EnableModeless)(BOOL /*fEnable*/)
    {
        return S_OK;
    }
    STDMETHOD(TranslateAccelerator)(LPMSG /*lpMsg*/, WORD /*wID*/)
    {
        return S_FALSE;
    }
    // IOleWindow
    STDMETHOD(GetWindow)(HWND* phwnd)
    {
        if( m_pOwner == NULL ) return E_UNEXPECTED;
        *phwnd = m_pOwner->GetPaintHWnd();
        return S_OK;
    }
    STDMETHOD(ContextSensitiveHelp)(BOOL /*fEnterMode*/)
    {
        return S_OK;
    }
    // IOleInPlaceUIWindow
    STDMETHOD(GetBorder)(LPRECT /*lprectBorder*/)
    {
        return S_OK;
    }
    STDMETHOD(RequestBorderSpace)(LPCBORDERWIDTHS /*pborderwidths*/)
    {
        return INPLACE_E_NOTOOLSPACE;
    }
    STDMETHOD(SetBorderSpace)(LPCBORDERWIDTHS /*pborderwidths*/)
    {
        return S_OK;
    }
    STDMETHOD(SetActiveObject)(IOleInPlaceActiveObject* pActiveObject, LPCOLESTR /*pszObjName*/)
    {
        if( pActiveObject != NULL ) pActiveObject->AddRef();
        if( m_pActiveObject != NULL ) m_pActiveObject->Release();
        m_pActiveObject = pActiveObject;
        return S_OK;
    }
};

/////////////////////////////////////////////////////////////////////////////
// CActiveXCommandHandler -- activex¿Ø¼þµÄÃüÁî´¦ÀíÀà,ÓÃÓڿؼþºÍËÞÖ÷³ÌÐòµÄ½»»¥µ÷ÓÃ

// ¶¨ÒåDISPID
#define DISPID_EX_HANDLER	1

class CActiveXCommandHandler : public IDispatch
{
	long		refcount;
	_bstr_t		m_bstrParam;	// ²ÎÊýÃû
public:

	CActiveXCommandHandler() {refcount = 0;}
	//virtual ~CActiveXCommandHandler() {}

	STDMETHOD(QueryInterface)(REFIID iid, LPVOID* ppvObj)
	{
		if (iid == IID_IDispatch)
		{
			*ppvObj = (IDispatch*)this;
			AddRef();
		}else
		{
			return E_NOINTERFACE;
			//return E_NOTIMPL;
		}
		return S_OK;
	}

	STDMETHOD_(ULONG,AddRef)()
	{
		InterlockedIncrement(&refcount);
		return refcount;
	}

	STDMETHOD_(ULONG,Release)()
	{
		InterlockedDecrement(&refcount);
		if (refcount == 0)
			delete this;
		return refcount;
	}

	STDMETHOD(GetTypeInfoCount)(/* [out] */ UINT *pctinfo)
	{
		return S_OK;
	}

	STDMETHOD(GetTypeInfo)(
      /* [in] */ UINT iTInfo,
      /* [in] */ LCID lcid,
      /* [out] */ ITypeInfo **ppTInfo)
	{
		return S_OK;
	}

	STDMETHOD(GetIDsOfNames)(
            /* [in] */ REFIID riid,
            /* [size_is][in] */ LPOLESTR *rgszNames,
            /* [in] */ UINT cNames,
            /* [in] */ LCID lcid,
            /* [size_is][out] */ DISPID *rgDispId)
	{
		m_bstrParam = *rgszNames;
		*rgDispId = DISPID_EX_HANDLER;
		return S_OK;
	}

	STDMETHOD(Invoke)(
            /* [in] */ DISPID dispIdMember,
            /* [in] */ REFIID riid,
            /* [in] */ LCID lcid,
            /* [in] */ WORD wFlags,
            /* [out][in] */ DISPPARAMS *pDispParams,
            /* [out] */ VARIANT *pVarResult,
            /* [out] */ EXCEPINFO *pExcepInfo,
            /* [out] */ UINT *puArgErr)
	{
		if(dispIdMember==DISPID_EX_HANDLER)
		{
			if(wFlags == DISPATCH_PROPERTYGET)	// »ñÈ¡ÊôÐÔ
			{
				/*IInterp* pInterp = GetCurrentInterp();
				if(pInterp)
				{
					CString strValue = pInterp->GetVar(m_bstrParam);
					COleVariant* pRetVal = (COleVariant*)pVarResult;
					*pRetVal = strValue;
				}*/
			}else
			if(wFlags == DISPATCH_PROPERTYPUT)	// ÉèÖÃÊôÐÔ
			{
				/*IInterp* pInterp = GetCurrentInterp();
				if(pInterp)
				{
					if(pDispParams->cArgs > 0)
					{
						COleVariant* pRetVal = (COleVariant*)(pDispParams->rgvarg);
						CString str(pRetVal->bstrVal);
						pInterp->SetVar(m_bstrParam, str);
					}
				}*/
			}else
			if((wFlags & DISPATCH_METHOD) != 0)	// µ÷Ó÷½·¨
			{
				/*IInterp* pInterp = GetCurrentInterp();
				if(pInterp)
				{
					CStringArray asParam;
					// ˵Ã÷:²ÎÊýÊý×épDispParamsΪµ¹Ðò,ÇÒÃüÃû²ÎÊýÔÚÇ°Ãæ,´Ë´¦Ê¡ÂÔÃüÃû²ÎÊý
					int nArgs = pDispParams->cArgs + pDispParams->cNamedArgs;
					int nNamedArgs = pDispParams->cNamedArgs;
					for(int i = nArgs-1; i >= nNamedArgs; i--)
					{
						COleVariant* pRetVal = (COleVariant*)(&(pDispParams->rgvarg[i]));
						CString str(pRetVal->bstrVal);
						asParam.Add(str);
					}
					CString strRes = "";
					if(pInterp->CallMethod(m_bstrParam, asParam))
					{
						strRes = pInterp->GetResult();
					}else
					{
						strRes = pInterp->GetResult();
					}
					if((wFlags & DISPATCH_PROPERTYGET) != 0)
					{
						// ¿ÉÒÔ»ñÈ¡·µ»ØÖµ
						COleVariant* pRetVal = (COleVariant*)pVarResult;
						*pRetVal = strRes;
					}
				}*/
			}

              //MessageBox(0,"Hello World","Hello",0); //place your code here
			  //frmweb->Edit1->Text="Hello World(ÕâÒ²¿ÉÒÔ£¿)";
		}

		return S_OK;
	}

};

/////////////////////////////////////////////////////////////////////////////////////
// CActiveXCtrl

class CActiveXCtrl :
    public IOleClientSite,
    public IOleInPlaceSiteWindowless,
    public IOleControlSite,
    public IObjectWithSite,
    public IOleContainer,
	public IDocHostUIHandler
{
    friend CDuiActiveX;
    friend CActiveXWnd;
public:
    CActiveXCtrl();
    ~CActiveXCtrl();

public:
    // IUnknown
    STDMETHOD_(ULONG,AddRef)();
    STDMETHOD_(ULONG,Release)();
    STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppvObject);

    // IObjectWithSite
    STDMETHOD(SetSite)(IUnknown *pUnkSite);
    STDMETHOD(GetSite)(REFIID riid, LPVOID* ppvSite);

    // IOleClientSite
    STDMETHOD(SaveObject)(void);
    STDMETHOD(GetMoniker)(DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk);
    STDMETHOD(GetContainer)(IOleContainer** ppContainer);
    STDMETHOD(ShowObject)(void);
    STDMETHOD(OnShowWindow)(BOOL fShow);
    STDMETHOD(RequestNewObjectLayout)(void);

    // IOleInPlaceSiteWindowless
    STDMETHOD(CanWindowlessActivate)(void);
    STDMETHOD(GetCapture)(void);
    STDMETHOD(SetCapture)(BOOL fCapture);
    STDMETHOD(GetFocus)(void);
    STDMETHOD(SetFocus)(BOOL fFocus);
    STDMETHOD(GetDC)(LPCRECT pRect, DWORD grfFlags, HDC* phDC);
    STDMETHOD(ReleaseDC)(HDC hDC);
    STDMETHOD(InvalidateRect)(LPCRECT pRect, BOOL fErase);
    STDMETHOD(InvalidateRgn)(HRGN hRGN, BOOL fErase);
    STDMETHOD(ScrollRect)(INT dx, INT dy, LPCRECT pRectScroll, LPCRECT pRectClip);
    STDMETHOD(AdjustRect)(LPRECT prc);
    STDMETHOD(OnDefWindowMessage)(UINT msg, WPARAM wParam, LPARAM lParam, LRESULT* plResult);

    // IOleInPlaceSiteEx
    STDMETHOD(OnInPlaceActivateEx)(BOOL *pfNoRedraw, DWORD dwFlags);
    STDMETHOD(OnInPlaceDeactivateEx)(BOOL fNoRedraw);
    STDMETHOD(RequestUIActivate)(void);

    // IOleInPlaceSite
    STDMETHOD(CanInPlaceActivate)(void);
    STDMETHOD(OnInPlaceActivate)(void);
    STDMETHOD(OnUIActivate)(void);
    STDMETHOD(GetWindowContext)(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo);
    STDMETHOD(Scroll)(SIZE scrollExtant);
    STDMETHOD(OnUIDeactivate)(BOOL fUndoable);
    STDMETHOD(OnInPlaceDeactivate)(void);
    STDMETHOD(DiscardUndoState)( void);
    STDMETHOD(DeactivateAndUndo)( void);
    STDMETHOD(OnPosRectChange)(LPCRECT lprcPosRect);

    // IOleWindow
    STDMETHOD(GetWindow)(HWND* phwnd);
    STDMETHOD(ContextSensitiveHelp)(BOOL fEnterMode);

    // IOleControlSite
    STDMETHOD(OnControlInfoChanged)(void);
    STDMETHOD(LockInPlaceActive)(BOOL fLock);
    STDMETHOD(GetExtendedControl)(IDispatch** ppDisp);
    STDMETHOD(TransformCoords)(POINTL* pPtlHimetric, POINTF* pPtfContainer, DWORD dwFlags);
    STDMETHOD(TranslateAccelerator)(MSG* pMsg, DWORD grfModifiers);
    STDMETHOD(OnFocus)(BOOL fGotFocus);
    STDMETHOD(ShowPropertyFrame)(void);

    // IOleContainer
    STDMETHOD(EnumObjects)(DWORD grfFlags, IEnumUnknown** ppenum);
    STDMETHOD(LockContainer)(BOOL fLock);

    // IParseDisplayName
    STDMETHOD(ParseDisplayName)(IBindCtx* pbc, LPOLESTR pszDisplayName, ULONG* pchEaten, IMoniker** ppmkOut);
/*
	//DWebBrowserEvents2
    //IDispatch methods
    STDMETHOD(GetTypeInfoCount)(UINT FAR* pctinfo);
    STDMETHOD(GetTypeInfo)(UINT itinfo,LCID lcid,ITypeInfo FAR* FAR* pptinfo);
    STDMETHOD(GetIDsOfNames)(REFIID riid,OLECHAR FAR* FAR* rgszNames,UINT cNames,LCID lcid, DISPID FAR* rgdispid);
    STDMETHOD(Invoke)(DISPID dispidMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS FAR* pdispparams, VARIANT FAR* pvarResult,EXCEPINFO FAR* pexcepinfo,UINT FAR* puArgErr);
*/
	// IDocHostUIHandler
	STDMETHOD(ShowContextMenu)(/* [in] */ DWORD dwID,
            /* [in] */ POINT __RPC_FAR *ppt,
            /* [in] */ IUnknown __RPC_FAR *pcmdtReserved,
            /* [in] */ IDispatch __RPC_FAR *pdispReserved);
	STDMETHOD(GetHostInfo)(
            /* [out][in] */ DOCHOSTUIINFO __RPC_FAR *pInfo);
	STDMETHOD(ShowUI)(
            /* [in] */ DWORD dwID,
            /* [in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject,
            /* [in] */ IOleCommandTarget __RPC_FAR *pCommandTarget,
            /* [in] */ IOleInPlaceFrame __RPC_FAR *pFrame,
            /* [in] */ IOleInPlaceUIWindow __RPC_FAR *pDoc);
	STDMETHOD(HideUI)(void);
	STDMETHOD(UpdateUI)(void);
	STDMETHOD(EnableModeless)(/* [in] */ BOOL fEnable);
	STDMETHOD(OnDocWindowActivate)(/* [in] */ BOOL fEnable);
	STDMETHOD(OnFrameWindowActivate)(/* [in] */ BOOL fEnable);
	STDMETHOD(ResizeBorder)(
            /* [in] */ LPCRECT prcBorder,
            /* [in] */ IOleInPlaceUIWindow __RPC_FAR *pUIWindow,
            /* [in] */ BOOL fRameWindow);
	STDMETHOD(TranslateAccelerator)(
            /* [in] */ LPMSG lpMsg,
            /* [in] */ const GUID __RPC_FAR *pguidCmdGroup,
            /* [in] */ DWORD nCmdID);
	STDMETHOD(GetOptionKeyPath)(
            /* [out] */ LPOLESTR __RPC_FAR *pchKey,
            /* [in] */ DWORD dw);
	STDMETHOD(GetDropTarget)(
            /* [in] */ IDropTarget __RPC_FAR *pDropTarget,
            /* [out] */ IDropTarget __RPC_FAR *__RPC_FAR *ppDropTarget);
    STDMETHOD(GetExternal)(
            /* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDispatch);
    STDMETHOD(TranslateUrl)(
            /* [in] */ DWORD dwTranslate,
            /* [in] */ OLECHAR __RPC_FAR *pchURLIn,
            /* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppchURLOut);
    STDMETHOD(FilterDataObject)(
            /* [in] */ IDataObject __RPC_FAR *pDO,
            /* [out] */ IDataObject __RPC_FAR *__RPC_FAR *ppDORet);

protected:
    HRESULT CreateActiveXWnd();

protected:
    LONG			m_dwRef;
    CDuiActiveX*	m_pOwner;
    CActiveXWnd*	m_pWindow;
    IUnknown*		m_pUnkSite;
    IViewObject*	m_pViewObject;
    IOleInPlaceObjectWindowless* m_pInPlaceObject;
    bool			m_bLocked;
    bool			m_bFocused;
    bool			m_bCaptured;
    bool			m_bUIActivated;
    bool			m_bInPlaceActive;
    bool			m_bWindowless;
};

CActiveXCtrl::CActiveXCtrl() :
	m_dwRef(1),
	m_pOwner(NULL),
	m_pWindow(NULL),
	m_pUnkSite(NULL),
	m_pViewObject(NULL),
	m_pInPlaceObject(NULL),
	m_bLocked(false),
	m_bFocused(false),
	m_bCaptured(false),
	m_bWindowless(false),
	m_bUIActivated(false),
	m_bInPlaceActive(false)
{
}

CActiveXCtrl::~CActiveXCtrl()
{
    if( m_pWindow != NULL )
	{
        ::DestroyWindow(*m_pWindow);
        delete m_pWindow;
    }
    if( m_pUnkSite != NULL ) m_pUnkSite->Release();
    if( m_pViewObject != NULL ) m_pViewObject->Release();
    if( m_pInPlaceObject != NULL ) m_pInPlaceObject->Release();
}

STDMETHODIMP CActiveXCtrl::QueryInterface(REFIID riid, LPVOID *ppvObject)
{
    *ppvObject = NULL;
    if( riid == IID_IUnknown )                       *ppvObject = static_cast<IOleWindow*>(this);
    else if( riid == IID_IOleClientSite )            *ppvObject = static_cast<IOleClientSite*>(this);
    else if( riid == IID_IOleInPlaceSiteWindowless ) *ppvObject = static_cast<IOleInPlaceSiteWindowless*>(this);
    else if( riid == IID_IOleInPlaceSiteEx )         *ppvObject = static_cast<IOleInPlaceSiteEx*>(this);
    else if( riid == IID_IOleInPlaceSite )           *ppvObject = static_cast<IOleInPlaceSite*>(this);
    else if( riid == IID_IOleWindow )                *ppvObject = static_cast<IOleWindow*>(this);
    else if( riid == IID_IOleControlSite )           *ppvObject = static_cast<IOleControlSite*>(this);
    else if( riid == IID_IOleContainer )             *ppvObject = static_cast<IOleContainer*>(this);
    else if( riid == IID_IObjectWithSite )           *ppvObject = static_cast<IObjectWithSite*>(this);
	else if( riid == IID_IDocHostUIHandler )         *ppvObject = static_cast<IDocHostUIHandler*>(this);
    if( *ppvObject != NULL ) AddRef();
    return *ppvObject == NULL ? E_NOINTERFACE : S_OK;
}

STDMETHODIMP_(ULONG) CActiveXCtrl::AddRef()
{
    return ++m_dwRef;
}

STDMETHODIMP_(ULONG) CActiveXCtrl::Release()
{
    LONG lRef = --m_dwRef;
    if( lRef == 0 ) delete this;
    return lRef;
}

STDMETHODIMP CActiveXCtrl::SetSite(IUnknown *pUnkSite)
{
    TRACE(_T("AX: CActiveXCtrl::SetSite\n"));
    if( m_pUnkSite != NULL )
	{
        m_pUnkSite->Release();
        m_pUnkSite = NULL;
    }
    if( pUnkSite != NULL )
	{
        m_pUnkSite = pUnkSite;
        m_pUnkSite->AddRef();
    }
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::GetSite(REFIID riid, LPVOID* ppvSite)
{
    TRACE(_T("AX: CActiveXCtrl::GetSite\n"));
    if( ppvSite == NULL ) return E_POINTER;
    *ppvSite = NULL;
    if( m_pUnkSite == NULL ) return E_FAIL;
    return m_pUnkSite->QueryInterface(riid, ppvSite);
}

STDMETHODIMP CActiveXCtrl::SaveObject(void)
{
    TRACE(_T("AX: CActiveXCtrl::SaveObject\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::GetMoniker(DWORD dwAssign, DWORD dwWhichMoniker, IMoniker** ppmk)
{
    TRACE(_T("AX: CActiveXCtrl::GetMoniker\n"));
    if( ppmk != NULL ) *ppmk = NULL;
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::GetContainer(IOleContainer** ppContainer)
{
    TRACE(_T("AX: CActiveXCtrl::GetContainer\n"));
    if( ppContainer == NULL ) return E_POINTER;
    *ppContainer = NULL;
    HRESULT Hr = E_NOTIMPL;
    if( m_pUnkSite != NULL )
	{
		Hr = m_pUnkSite->QueryInterface(IID_IOleContainer, (LPVOID*) ppContainer);
	}
    if( FAILED(Hr) )
	{
		Hr = QueryInterface(IID_IOleContainer, (LPVOID*) ppContainer);
	}
    return Hr;
}

STDMETHODIMP CActiveXCtrl::ShowObject(void)
{
    TRACE(_T("AX: CActiveXCtrl::ShowObject\n"));
    if( m_pOwner == NULL ) return E_UNEXPECTED;
    HDC hDC = ::GetDC(m_pOwner->m_hwndHost);
    if( hDC == NULL ) return E_FAIL;
    if( m_pViewObject != NULL )
	{
		m_pViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hDC, (RECTL*) &m_pOwner->m_rc, (RECTL*) &m_pOwner->m_rc, NULL, NULL);
	}
    ::ReleaseDC(m_pOwner->m_hwndHost, hDC);
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::OnShowWindow(BOOL fShow)
{
    TRACE(_T("AX: CActiveXCtrl::OnShowWindow\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::RequestNewObjectLayout(void)
{
    TRACE(_T("AX: CActiveXCtrl::RequestNewObjectLayout\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::CanWindowlessActivate(void)
{
    TRACE(_T("AX: CActiveXCtrl::CanWindowlessActivate\n"));
    return S_OK;  // Yes, we can!!
}

STDMETHODIMP CActiveXCtrl::GetCapture(void)
{
	if( m_pOwner == NULL ) return E_UNEXPECTED;
	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

    TRACE(_T("AX: CActiveXCtrl::GetCapture\n"));
    return m_bCaptured ? S_OK : S_FALSE;
}

STDMETHODIMP CActiveXCtrl::SetCapture(BOOL fCapture)
{
	if( m_pOwner == NULL ) return E_UNEXPECTED;
	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

    TRACE(_T("AX: CActiveXCtrl::SetCapture\n"));
    m_bCaptured = (fCapture == TRUE);
    if( fCapture ) ::SetCapture(m_pOwner->m_hwndHost); else ::ReleaseCapture();
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::GetFocus(void)
{
	if( m_pOwner == NULL ) return E_UNEXPECTED;
	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

    TRACE(_T("AX: CActiveXCtrl::GetFocus\n"));
    return m_bFocused ? S_OK : S_FALSE;
}

STDMETHODIMP CActiveXCtrl::SetFocus(BOOL fFocus)
{
	if( m_pOwner == NULL ) return E_UNEXPECTED;
	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

    TRACE(_T("AX: CActiveXCtrl::SetFocus\n"));
    if( fFocus ) m_pOwner->SetControlFocus(fFocus);
    m_bFocused = (fFocus == TRUE);
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::GetDC(LPCRECT pRect, DWORD grfFlags, HDC* phDC)
{
	if( phDC == NULL ) return E_POINTER;
    if( m_pOwner == NULL ) return E_UNEXPECTED;
	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

    TRACE(_T("AX: CActiveXCtrl::GetDC\n"));
	*phDC = ::GetDC(m_pOwner->m_hwndHost);
    if( (grfFlags & OLEDC_PAINTBKGND) != 0 )
	{
        CRect rcItem = m_pOwner->GetRect();
        if( !m_bWindowless ) rcItem.MoveToXY(0, 0);
        ::FillRect(*phDC, &rcItem, (HBRUSH) (COLOR_WINDOW + 1));
    }
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::ReleaseDC(HDC hDC)
{
	if( m_pOwner == NULL ) return E_UNEXPECTED;
	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

    TRACE(_T("AX: CActiveXCtrl::ReleaseDC\n"));
    ::ReleaseDC(m_pOwner->m_hwndHost, hDC);
    return S_OK;
}

// ¿Ø¼þµÄˢнçÃæ²Ù×÷
STDMETHODIMP CActiveXCtrl::InvalidateRect(LPCRECT pRect, BOOL fErase)
{
	if( m_pOwner == NULL ) return E_UNEXPECTED;
	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

    TRACE(_T("AX: CActiveXCtrl::InvalidateRect\n"));
    if( m_pOwner->m_hwndHost == NULL ) return E_FAIL;
	//return ::InvalidateRect(m_pOwner->m_hwndHost, pRect, fErase) ? S_OK : E_FAIL;
	// µ÷ÓöÔÓ¦DUI¿Ø¼þµÄˢк¯Êý
	m_pOwner->UpdateControl();
	return S_OK;
}

STDMETHODIMP CActiveXCtrl::InvalidateRgn(HRGN hRGN, BOOL fErase)
{
	if( m_pOwner == NULL ) return E_UNEXPECTED;
	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

    TRACE(_T("AX: CActiveXCtrl::InvalidateRgn\n"));
    return ::InvalidateRgn(m_pOwner->m_hwndHost, hRGN, fErase) ? S_OK : E_FAIL;
}

STDMETHODIMP CActiveXCtrl::ScrollRect(INT dx, INT dy, LPCRECT pRectScroll, LPCRECT pRectClip)
{
    TRACE(_T("AX: CActiveXCtrl::ScrollRect\n"));
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::AdjustRect(LPRECT prc)
{
    TRACE(_T("AX: CActiveXCtrl::AdjustRect\n"));
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::OnDefWindowMessage(UINT msg, WPARAM wParam, LPARAM lParam, LRESULT* plResult)
{
    TRACE(_T("AX: CActiveXCtrl::OnDefWindowMessage\n"));
    if( m_pOwner == NULL ) return E_UNEXPECTED;
    *plResult = ::DefWindowProc(m_pOwner->m_hwndHost, msg, wParam, lParam);
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::OnInPlaceActivateEx(BOOL* pfNoRedraw, DWORD dwFlags)
{
    TRACE(_T("AX: CActiveXCtrl::OnInPlaceActivateEx\n"));
    ASSERT(m_pInPlaceObject==NULL);
    if( m_pOwner == NULL ) return E_UNEXPECTED;
    if( m_pOwner->m_pUnk == NULL ) return E_UNEXPECTED;
    ::OleLockRunning(m_pOwner->m_pUnk, TRUE, FALSE);
    HWND hWndFrame = m_pOwner->GetPaintHWnd();
    HRESULT Hr = E_FAIL;
    if( (dwFlags & ACTIVATE_WINDOWLESS) != 0 )
	{
		// ´´½¨ÎÞ´°¿ÚʵÀý
        m_bWindowless = true;
        Hr = m_pOwner->m_pUnk->QueryInterface(IID_IOleInPlaceObjectWindowless, (LPVOID*) &m_pInPlaceObject);
        m_pOwner->m_hwndHost = hWndFrame;
        //m_pOwner->GetManager()->AddMessageFilter(m_pOwner);
		Hr = CreateActiveXWnd();
        if( FAILED(Hr) ) return Hr;
    }
    if( FAILED(Hr) )
	{
		// ´´½¨´°¿Ú
        m_bWindowless = false;
        Hr = CreateActiveXWnd();
        if( FAILED(Hr) ) return Hr;
        Hr = m_pOwner->m_pUnk->QueryInterface(IID_IOleInPlaceObject, (LPVOID*) &m_pInPlaceObject);
    }
    if( m_pInPlaceObject != NULL )
	{
        CRect rcItem = m_pOwner->m_rc;
        if( !m_bWindowless ) rcItem.MoveToXY(0, 0);
        m_pInPlaceObject->SetObjectRects(&rcItem, &rcItem);
    }
    m_bInPlaceActive = SUCCEEDED(Hr);
    return Hr;
}

STDMETHODIMP CActiveXCtrl::OnInPlaceDeactivateEx(BOOL fNoRedraw)
{
    TRACE(_T("AX: CActiveXCtrl::OnInPlaceDeactivateEx\n"));
    m_bInPlaceActive = false;
    if( m_pInPlaceObject != NULL )
	{
        m_pInPlaceObject->Release();
        m_pInPlaceObject = NULL;
    }
    if( m_pWindow != NULL )
	{
        ::DestroyWindow(*m_pWindow);
        delete m_pWindow;
        m_pWindow = NULL;
    }
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::RequestUIActivate(void)
{
    TRACE(_T("AX: CActiveXCtrl::RequestUIActivate\n"));
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::CanInPlaceActivate(void)
{
    TRACE(_T("AX: CActiveXCtrl::CanInPlaceActivate\n"));
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::OnInPlaceActivate(void)
{
    TRACE(_T("AX: CActiveXCtrl::OnInPlaceActivate\n"));
    BOOL bDummy = FALSE;
    return OnInPlaceActivateEx(&bDummy, 0);
}

STDMETHODIMP CActiveXCtrl::OnUIActivate(void)
{
    TRACE(_T("AX: CActiveXCtrl::OnUIActivate\n"));
    m_bUIActivated = true;
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::GetWindowContext(IOleInPlaceFrame** ppFrame, IOleInPlaceUIWindow** ppDoc, LPRECT lprcPosRect, LPRECT lprcClipRect, LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
    TRACE(_T("AX: CActiveXCtrl::GetWindowContext\n"));
    if( ppDoc == NULL ) return E_POINTER;
    if( ppFrame == NULL ) return E_POINTER;
    if( lprcPosRect == NULL ) return E_POINTER;
    if( lprcClipRect == NULL ) return E_POINTER;

	CRect rcItem = m_pOwner->GetRect();
	memcpy(lprcPosRect, &rcItem, sizeof(rcItem));
	memcpy(lprcClipRect, &rcItem, sizeof(rcItem));

    *ppFrame = new CActiveXFrameWnd(m_pOwner);
    *ppDoc = NULL;
    ACCEL ac = { 0 };
    HACCEL hac = ::CreateAcceleratorTable(&ac, 1);
    lpFrameInfo->cb = sizeof(OLEINPLACEFRAMEINFO);
    lpFrameInfo->fMDIApp = FALSE;
    lpFrameInfo->hwndFrame = m_pOwner->GetPaintHWnd();
    lpFrameInfo->haccel = hac;
    lpFrameInfo->cAccelEntries = 1;
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::Scroll(SIZE scrollExtant)
{
    TRACE(_T("AX: CActiveXCtrl::Scroll\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::OnUIDeactivate(BOOL fUndoable)
{
    TRACE(_T("AX: CActiveXCtrl::OnUIDeactivate\n"));
    m_bUIActivated = false;
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::OnInPlaceDeactivate(void)
{
    TRACE(_T("AX: CActiveXCtrl::OnInPlaceDeactivate\n"));
    return OnInPlaceDeactivateEx(TRUE);
}

STDMETHODIMP CActiveXCtrl::DiscardUndoState(void)
{
    TRACE(_T("AX: CActiveXCtrl::DiscardUndoState\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::DeactivateAndUndo(void)
{
    TRACE(_T("AX: CActiveXCtrl::DeactivateAndUndo\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::OnPosRectChange(LPCRECT lprcPosRect)
{
    TRACE(_T("AX: CActiveXCtrl::OnPosRectChange\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::GetWindow(HWND* phwnd)
{
    if( m_pOwner == NULL ) return E_UNEXPECTED;

	if(!m_pOwner->IsControlVisible())
	{
		return S_FALSE;
	}

	TRACE(_T("AX: CActiveXCtrl::GetWindow\n"));

    if( m_pOwner->m_hwndHost == NULL ) CreateActiveXWnd();
    if( m_pOwner->m_hwndHost == NULL ) return E_FAIL;
    *phwnd = m_pOwner->m_hwndHost;
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::ContextSensitiveHelp(BOOL fEnterMode)
{
    TRACE(_T("AX: CActiveXCtrl::ContextSensitiveHelp\n"));
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::OnControlInfoChanged(void)
{
    TRACE(_T("AX: CActiveXCtrl::OnControlInfoChanged\n"));
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::LockInPlaceActive(BOOL fLock)
{
    TRACE(_T("AX: CActiveXCtrl::LockInPlaceActive\n"));
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::GetExtendedControl(IDispatch** ppDisp)
{
    TRACE(_T("AX: CActiveXCtrl::GetExtendedControl\n"));
    if( ppDisp == NULL ) return E_POINTER;
    if( m_pOwner == NULL ) return E_UNEXPECTED;
    if( m_pOwner->m_pUnk == NULL ) return E_UNEXPECTED;
    return m_pOwner->m_pUnk->QueryInterface(IID_IDispatch, (LPVOID*) ppDisp);
}

STDMETHODIMP CActiveXCtrl::TransformCoords(POINTL* pPtlHimetric, POINTF* pPtfContainer, DWORD dwFlags)
{
    TRACE(_T("AX: CActiveXCtrl::TransformCoords\n"));
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::TranslateAccelerator(MSG *pMsg, DWORD grfModifiers)
{
    TRACE(_T("AX: CActiveXCtrl::TranslateAccelerator\n"));
    return S_FALSE;
}

STDMETHODIMP CActiveXCtrl::OnFocus(BOOL fGotFocus)
{
    TRACE(_T("AX: CActiveXCtrl::OnFocus\n"));
    m_bFocused = (fGotFocus == TRUE);
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::ShowPropertyFrame(void)
{
    TRACE(_T("AX: CActiveXCtrl::ShowPropertyFrame\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::EnumObjects(DWORD grfFlags, IEnumUnknown** ppenum)
{
    TRACE(_T("AX: CActiveXCtrl::EnumObjects\n"));
    if( ppenum == NULL ) return E_POINTER;
    if( m_pOwner == NULL ) return E_UNEXPECTED;
    *ppenum = new CActiveXEnum(m_pOwner->m_pUnk);
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::LockContainer(BOOL fLock)
{
    TRACE(_T("AX: CActiveXCtrl::LockContainer\n"));
    m_bLocked = fLock != FALSE;
    return S_OK;
}

STDMETHODIMP CActiveXCtrl::ParseDisplayName(IBindCtx *pbc, LPOLESTR pszDisplayName, ULONG* pchEaten, IMoniker** ppmkOut)
{
    TRACE(_T("AX: CActiveXCtrl::ParseDisplayName\n"));
    return E_NOTIMPL;
}

STDMETHODIMP  CActiveXCtrl::GetHostInfo( DOCHOSTUIINFO* pInfo )
{
	TRACE(_T("AX: CActiveXCtrl::GetHostInfo\n"));
	// ÏÔʾΪÐÂʽÓû§½çÃæ
	//pInfo->dwFlags = DOCHOSTUIFLAG_ENABLE_FORMS_AUTOCOMPLETE |DOCHOSTUIFLAG_FLAT_SCROLLBAR|0x40000;
	pInfo->dwFlags |= DOCHOSTUIFLAG_NO3DBORDER;	// È¥³ý3D±ß¿ò
	if(m_pOwner && !m_pOwner->GetShowScroll())
	{
		pInfo->dwFlags |= DOCHOSTUIFLAG_SCROLL_NO;	// ²»ÏÔʾ¹ö¶¯Ìõ
	}
    pInfo->dwDoubleClick = DOCHOSTUIDBLCLK_DEFAULT;
    return S_OK;
}

STDMETHODIMP  CActiveXCtrl::ShowUI(
				DWORD /*dwID*/,
				IOleInPlaceActiveObject * /*pActiveObject*/,
				IOleCommandTarget * /*pCommandTarget*/,
				IOleInPlaceFrame * /*pFrame*/,
				IOleInPlaceUIWindow * /*pDoc*/)
{
	TRACE(_T("AX: CActiveXCtrl::ShowUI\n"));
    return S_OK;
}

STDMETHODIMP  CActiveXCtrl::HideUI(void)
{
	TRACE(_T("AX: CActiveXCtrl::HideUI\n"));
    return S_OK;
}

STDMETHODIMP  CActiveXCtrl::UpdateUI(void)
{
	TRACE(_T("AX: CActiveXCtrl::UpdateUI\n"));
	return S_OK;
}

STDMETHODIMP  CActiveXCtrl::EnableModeless(BOOL /*fEnable*/)
{
	TRACE(_T("AX: CActiveXCtrl::EnableModeless\n"));
    return E_NOTIMPL;
}

STDMETHODIMP  CActiveXCtrl::OnDocWindowActivate(BOOL /*fActivate*/)
{
	TRACE(_T("AX: CActiveXCtrl::OnDocWindowActivate\n"));
    return E_NOTIMPL;
}

STDMETHODIMP  CActiveXCtrl::OnFrameWindowActivate(BOOL /*fActivate*/)
{
	TRACE(_T("AX: CActiveXCtrl::OnFrameWindowActivate\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::ResizeBorder(
				LPCRECT /*prcBorder*/,
				IOleInPlaceUIWindow* /*pUIWindow*/,
				BOOL /*fRameWindow*/)
{
	TRACE(_T("AX: CActiveXCtrl::ResizeBorder\n"));
    return E_NOTIMPL;
}

STDMETHODIMP  CActiveXCtrl::ShowContextMenu(
				DWORD /*dwID*/,
				POINT* /*pptPosition*/,
				IUnknown* /*pCommandTarget*/,
				IDispatch* /*pDispatchObjectHit*/)
{
	TRACE(_T("AX: CActiveXCtrl::ShowContextMenu\n"));
	if(m_pOwner)
	{
		return m_pOwner->GetShowContentMenu() ? S_FALSE : S_OK;
	}
	return E_NOTIMPL;
}

STDMETHODIMP  CActiveXCtrl::TranslateAccelerator(LPMSG /*lpMsg*/,
            /* [in] */ const GUID __RPC_FAR* /*pguidCmdGroup*/,
            /* [in] */ DWORD /*nCmdID*/)
{
	TRACE(_T("AX: CActiveXCtrl::TranslateAccelerator\n"));
    return S_FALSE;
}

STDMETHODIMP  CActiveXCtrl::GetOptionKeyPath(BSTR* /*pbstrKey*/, DWORD)
{
	TRACE(_T("AX: CActiveXCtrl::GetOptionKeyPath\n"));
	return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::GetDropTarget(
            /* [in] */ IDropTarget __RPC_FAR* /*pDropTarget*/,
            /* [out] */ IDropTarget __RPC_FAR *__RPC_FAR* /*ppDropTarget*/)
{
	TRACE(_T("AX: CActiveXCtrl::GetDropTarget\n"));
	return E_NOTIMPL;
}

// »ñÈ¡À©Õ¹µÄÃüÁî´¦Àí¶ÔÏó,ÓÃÓڿؼþºÍËÞÖ÷³ÌÐòµÄ½»»¥,µ÷ÓÃËÞÖ÷³ÌÐòµÄº¯Êý
STDMETHODIMP CActiveXCtrl::GetExternal(
            /* [out] */ IDispatch __RPC_FAR *__RPC_FAR* ppDispatch)
{
	TRACE(_T("AX: CActiveXCtrl::GetExternal\n"));
	// ´´½¨À©Õ¹ÃüÁî´¦ÀíÆ÷¶ÔÏó
	CActiveXCommandHandler* pHandler = new CActiveXCommandHandler();
	pHandler->QueryInterface(IID_IDispatch, (void**)ppDispatch);
	return S_OK;
	//return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::TranslateUrl(
            /* [in] */ DWORD /*dwTranslate*/,
            /* [in] */ OLECHAR __RPC_FAR* /*pchURLIn*/,
            /* [out] */ OLECHAR __RPC_FAR *__RPC_FAR* /*ppchURLOut*/)
{
	TRACE(_T("AX: CActiveXCtrl::TranslateUrl\n"));
    return E_NOTIMPL;
}

STDMETHODIMP CActiveXCtrl::FilterDataObject(
            /* [in] */ IDataObject __RPC_FAR* /*pDO*/,
            /* [out] */ IDataObject __RPC_FAR *__RPC_FAR* /*ppDORet*/)
{
	TRACE(_T("AX: CActiveXCtrl::FilterDataObject\n"));
    return E_NOTIMPL;
}

// ´´½¨ActiveX´°¿Ú
HRESULT CActiveXCtrl::CreateActiveXWnd()
{
    if( m_pWindow != NULL )
	{
		return S_OK;
	}
    m_pWindow = new CActiveXWnd;
    if( m_pWindow == NULL )
	{
		return E_OUTOFMEMORY;
	}
    m_pOwner->m_hwndHost = m_pWindow->Init(this, m_pOwner->GetPaintHWnd());
    return S_OK;
}

class CWebBrowserCtrl :
    public CActiveXCtrl,
	public DWebBrowserEvents2
{
    friend CDuiActiveX;
    friend CActiveXWnd;
public:
    CWebBrowserCtrl();
    ~CWebBrowserCtrl();

public:
    // IUnknown
    STDMETHOD_(ULONG,AddRef)();
    STDMETHOD_(ULONG,Release)();
    STDMETHOD(QueryInterface)(REFIID riid, LPVOID *ppvObject);

	//DWebBrowserEvents2
    //IDispatch methods
    STDMETHOD(GetTypeInfoCount)(UINT FAR* pctinfo);
    STDMETHOD(GetTypeInfo)(UINT itinfo,LCID lcid,ITypeInfo FAR* FAR* pptinfo);
    STDMETHOD(GetIDsOfNames)(REFIID riid,OLECHAR FAR* FAR* rgszNames,UINT cNames,LCID lcid, DISPID FAR* rgdispid);
    STDMETHOD(Invoke)(DISPID dispidMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS FAR* pdispparams, VARIANT FAR* pvarResult,EXCEPINFO FAR* pexcepinfo,UINT FAR* puArgErr);
};

/////////////////////////////////////////////////////////////////
// ä¯ÀÀÆ÷¿Ø¼þ
CWebBrowserCtrl::CWebBrowserCtrl() :
	CActiveXCtrl()
{
}

CWebBrowserCtrl::~CWebBrowserCtrl()
{
}

STDMETHODIMP_(ULONG) CWebBrowserCtrl::AddRef()
{
    return ++m_dwRef;
}

STDMETHODIMP_(ULONG) CWebBrowserCtrl::Release()
{
    LONG lRef = --m_dwRef;
    if( lRef == 0 ) delete this;
    return lRef;
}

STDMETHODIMP CWebBrowserCtrl::QueryInterface(REFIID riid, LPVOID *ppvObject)
{
	CActiveXCtrl::QueryInterface(riid, ppvObject);
	if(*ppvObject)
	{
		return S_OK;
	}

	if ((riid == DIID_DWebBrowserEvents2) || (riid == IID_IDispatch))	*ppvObject = static_cast<DWebBrowserEvents2*>(this);
    if( *ppvObject != NULL ) CActiveXCtrl::AddRef();
    return *ppvObject == NULL ? E_NOINTERFACE : S_OK;
}

//---------------------------------------------------------------------------------
//Description:
// DWebBrowserEvents and IDispatch methods
//
//----------------------------------------------------------------------------------
STDMETHODIMP CWebBrowserCtrl::GetTypeInfoCount(UINT FAR* pctinfo)
{
	TRACE(_T("AX: CWebBrowserCtrl::GetTypeInfoCount\n"));
	return E_NOTIMPL;
}

//---------------------------------------------------------------------------------
//Description:
// DWebBrowserEvents and IDispatch methods
//
//----------------------------------------------------------------------------------
STDMETHODIMP CWebBrowserCtrl::GetTypeInfo(UINT itinfo,LCID lcid,ITypeInfo FAR* FAR* pptinfo)
{
	TRACE(_T("AX: CWebBrowserCtrl::GetTypeInfo\n"));
	return E_NOTIMPL;
}

//---------------------------------------------------------------------------------
//Description:
// DWebBrowserEvents and IDispatch methods
//
//----------------------------------------------------------------------------------
STDMETHODIMP CWebBrowserCtrl::GetIDsOfNames(REFIID riid,OLECHAR FAR* FAR* rgszNames,UINT cNames,LCID lcid, DISPID FAR* rgdispid)
{
	TRACE(_T("AX: CWebBrowserCtrl::GetIDsOfNames\n"));
	return E_NOTIMPL;
}

//---------------------------------------------------------------------------------
//Description:
// DWebBrowserEvents and IDispatch methods
//
//----------------------------------------------------------------------------------
STDMETHODIMP CWebBrowserCtrl::Invoke(DISPID dispidMember,REFIID riid,LCID lcid,WORD wFlags,DISPPARAMS FAR* pdispparams, VARIANT FAR* pvarResult,EXCEPINFO FAR* pexcepinfo,UINT FAR* puArgErr)
{
	TRACE(_T("AX: CWebBrowserCtrl::Invoke\n"));
	// ·¢ËÍInvokeÏûÏ¢µ½DUIÏûÏ¢
	if(((CDuiWebBrowserCtrl*)m_pOwner)->IsDuiMsgInvoke())
	{
		return m_pOwner->SendMessage(dispidMember, (WPARAM)pdispparams, (LPARAM)pvarResult);
	}

	switch (dispidMember)
	{
		// The parameter for this DISPID:
		// [0]: Document title - VT_BSTR
		case DISPID_TITLECHANGE:	// webÒ³Ãæ±êÌâ±ä¸ü
		{
			if (pdispparams && pdispparams->rgvarg[0].vt == VT_BSTR)
			{
				//WCHAR szTitle[MAX_URL];
				//int len = wcslen(pdispparams->rgvarg[0].bstrVal);
				//wcsncpy(szTitle, pdispparams->rgvarg[0].bstrVal, MAX_URL - 5);
				//if(len > MAX_URL - 5)
				//{
				//	wcscat(szTitle, L"...");
				//}

				//OnTitleChange(szTitle);
			}
			return S_OK;
		}

		// The user has told Internet Explorer to close.
		case DISPID_ONQUIT:
		{
			//OnQuit();
			return S_OK;
		}

		// The parameters for this DISPID:
		// [0]: New status bar text - VT_BSTR
		case DISPID_STATUSTEXTCHANGE:	// ״̬À¸ÎÄ×Ö±ä¸ü
		{
			if (pdispparams && pdispparams->rgvarg[0].vt == VT_BSTR)
			{
				//WCHAR szStatus[MAX_URL];
				//int len = wcslen(pdispparams->rgvarg[0].bstrVal);
				//wcsncpy(szStatus, pdispparams->rgvarg[0].bstrVal, MAX_URL - 5);
				//if(len > MAX_URL - 5)
				//{
				//	wcscat(szStatus, L"...");
				//}

				//OnStatusTextChange(szStatus);
			}
			return S_OK;
		}

		// The parameters for this DISPID:
		// [0]: Maximum progress - VT_I4				-- ×î´ó½ø¶ÈÖµ
		// [1]: Amount of total progress - VT_I4		-- µ±Ç°½ø¶ÈÖµ
		case DISPID_PROGRESSCHANGE:	// Ò³Ãæ¼ÓÔؽø¶È±ä¸ü
		{
			//OnProgressChange(pdispparams->rgvarg[1].lVal,pdispparams->rgvarg[0].lVal);
			return S_OK;
		}

		// The parameter for this DISPID:
		// [0]: Name of property that changed - VT_BSTR
		case DISPID_PROPERTYCHANGE:	// ÊôÐÔ±ä¸ü
		{
			if ((pdispparams->cArgs > 0) && (pdispparams->rgvarg[0].vt == VT_BSTR))
			{
#ifdef _UNICODE
				CString strProp = OLE2T(pdispparams->rgvarg[0].bstrVal);
#else
				CString strProp = COLE2T(pdispparams->rgvarg[0].bstrVal);
#endif
			}
			return S_OK;
		}

		case DISPID_FILEDOWNLOAD:	// ÎļþÏÂÔØ
		{
			BOOL bCancel = FALSE;
			//OnFileDownload(&bCancel);
			if(bCancel == TRUE)
			{
				*pdispparams->rgvarg[0].pboolVal = VARIANT_TRUE;
			}
			else
			{
				*pdispparams->rgvarg[0].pboolVal = VARIANT_FALSE;
			}
			return S_OK;
		}

		case DISPID_DOWNLOADBEGIN:	// ¿ªÊ¼ÏÂÔØ
		{
			//OnDownloadBegin();
			return S_OK;
		}

		case DISPID_DOWNLOADCOMPLETE:	// ÏÂÔØÍê³É
		{
			//OnDownloadComplete();
			return S_OK;
		}

		// The parameters for this DISPID:
		// [0]: Enabled state - VT_BOOL
		// [1]: Command identifier - VT_I4
		case DISPID_COMMANDSTATECHANGE:
		{
			return S_OK;
		}

		// The parameters for this DISPID are as follows:
		// [0]: Cancel flag  - VT_BYREF|VT_BOOL
		// [1]: HTTP headers - VT_BYREF|VT_VARIANT
		// [2]: Address of HTTP POST data  - VT_BYREF|VT_VARIANT
		// [3]: Target frame name - VT_BYREF|VT_VARIANT
		// [4]: Option flags - VT_BYREF|VT_VARIANT
		// [5]: URL to navigate to - VT_BYREF|VT_VARIANT
		// [6]: An object that evaluates to the top-level or frame
		//      WebBrowser object corresponding to the event
		case DISPID_BEFORENAVIGATE2:	// µ¼º½µ½Ö¸¶¨URL֮ǰ
		{
			if ((pdispparams->cArgs >= 5) && (pdispparams->rgvarg[5].vt == (VT_BYREF|VT_VARIANT)))
			{
				CComVariant varURL(*pdispparams->rgvarg[5].pvarVal);
				varURL.ChangeType(VT_BSTR);
#ifdef _UNICODE
				CString strUrl = OLE2T(varURL.bstrVal);
#else
				CString strUrl = COLE2T(varURL.bstrVal);
#endif
				//DuiSystem::DuiMessageBox(NULL, strUrl);
			}
			return S_OK;
		}

		// The parameters for this DISPID:
		// [0]: URL navigated to - VT_BYREF|VT_VARIANT
		// [1]: An object that evaluates to the top-level or frame
		//      WebBrowser object corresponding to the event.
		case DISPID_NAVIGATECOMPLETE2:	// µ¼º½Íê³É
		{
			if (pdispparams->rgvarg[0].vt == (VT_BYREF|VT_VARIANT))
			{
				CComVariant varURL(*pdispparams->rgvarg[0].pvarVal);
				varURL.ChangeType(VT_BSTR);
#ifdef _UNICODE
				CString strUrl = OLE2T(varURL.bstrVal);
#else
				CString strUrl = COLE2T(varURL.bstrVal);
#endif
			}
			return S_OK;
		}

		case DISPID_DOCUMENTCOMPLETE:	// Ò³Ãæ¼ÓÔØÍê³É
		{
			return S_OK;
		}

		// The parameters for this DISPID are as follows:
		// [0]: Cancel flag - VT_BYREF|VT_BOOL
		// [1]: HTTP headers - VT_BYREF|VT_VARIANT
		// [2]: Address of HTTP POST data - VT_BYREF|VT_VARIANT
		// [3]: Target frame name - VT_BYREF|VT_VARIANT
		// [4]: Option flags - VT_BYREF|VT_VARIANT
		// [5]: URL to navigate to - VT_BYREF|VT_VARIANT
		// [6]: An object that evaluates to the top-level or frame
		//      WebBrowser object corresponding to the event.
		// ʵ¼ÊÇé¿ö:DISPID_NEWWINDOW2Ö»ÓÐÁ½¸ö²ÎÊý,ºóÃæ5¸ö²ÎÊý¶¼Ã»ÓÐ
		case DISPID_NEWWINDOW2:	// н¨´°¿Ú
		{
			return S_OK;
		}

		// The parameters for this DISPID are as follows:
		//0 : bstrUrl         µ¯³ö´°¿ÚµÄURL
		//1 : bstrContext     ËùÔÚÍøÒ³µÄURL
		//2 : dwFlags
		//3 : *bCancel        ÊÇ·ñÔÊÐí´ò¿ª¸Ã´°¿Ú
		//4 : **pDisp
		case DISPID_NEWWINDOW3:	// н¨´°¿Ú
		{
			return S_OK;
		}

		default:
			return E_NOTIMPL;
	}

	return E_NOTIMPL;
}

/////////////////////////////////////////////////////////////////////////////////////
// CActiveXWnd

HWND CActiveXWnd::Init(CActiveXCtrl* pOwner, HWND hWndParent)
{
    m_pOwner = pOwner;
    UINT uStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
    Create(hWndParent, _T("DuiActiveX"), uStyle, 0L, 0,0,0,0, NULL);
    return m_hWnd;
}

LPCTSTR CActiveXWnd::GetWindowClassName() const
{
    return _T("ActiveXWnd");
}

void CActiveXWnd::OnFinalMessage(HWND hWnd)
{
    //delete this; // ÕâÀï²»ÐèÒªÇåÀí£¬CDuiActiveX»áÇåÀíµÄ
}

void CActiveXWnd::DoVerb(LONG iVerb)
{
    if( m_pOwner == NULL )
	{
		return;
	}
    if( m_pOwner->m_pOwner == NULL )
	{
		return;
	}
    IOleObject* pUnk = NULL;
    m_pOwner->m_pOwner->GetControl(IID_IOleObject, (LPVOID*) &pUnk);
    if( pUnk == NULL )
	{
		return;
	}
    CSafeRelease<IOleObject> RefOleObject = pUnk;
    IOleClientSite* pOleClientSite = NULL;
    m_pOwner->QueryInterface(IID_IOleClientSite, (LPVOID*) &pOleClientSite);
    CSafeRelease<IOleClientSite> RefOleClientSite = pOleClientSite;
    pUnk->DoVerb(iVerb, NULL, pOleClientSite, 0, m_hWnd, &m_pOwner->m_pOwner->GetRect());
}

LRESULT CActiveXWnd::OnEraseBkgnd(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    if( m_pOwner->m_pViewObject == NULL )
	{
		bHandled = FALSE;
	}
    return 1;
}

LRESULT CActiveXWnd::OnMouseActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    IOleObject* pUnk = NULL;
    m_pOwner->m_pOwner->GetControl(IID_IOleObject, (LPVOID*) &pUnk);
    if( pUnk == NULL )
	{
		return 0;
	}
    CSafeRelease<IOleObject> RefOleObject = pUnk;
    DWORD dwMiscStatus = 0;
    pUnk->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus);
    if( (dwMiscStatus & OLEMISC_NOUIACTIVATE) != 0 )
	{
		return 0;
	}
    if( !m_pOwner->m_bInPlaceActive )
	{
		DoVerb(OLEIVERB_INPLACEACTIVATE);
	}
    bHandled = FALSE;
    return 0;
}

LRESULT CActiveXWnd::OnSetFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    bHandled = FALSE;
    m_pOwner->m_bFocused = true;
    if( !m_pOwner->m_bUIActivated ) DoVerb(OLEIVERB_UIACTIVATE);
    return 0;
}

LRESULT CActiveXWnd::OnKillFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    bHandled = FALSE;
    m_pOwner->m_bFocused = false;
    return 0;
}

LRESULT CActiveXWnd::OnPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
    PAINTSTRUCT ps = { 0 };
    ::BeginPaint(m_hWnd, &ps);
    ::EndPaint(m_hWnd, &ps);
    return 1;
}

/////////////////////////////////////////////////////////////////////////////////////
// CDuiActiveX

CDuiActiveX::CDuiActiveX(HWND hWnd, CDuiObject* pDuiObject)
	: CControlBase(hWnd, pDuiObject)
{
    m_clsid = IID_NULL;
	m_pUnk = NULL;
	m_pCP = NULL;
	m_pControl = NULL;
	m_bCreated = false;
	m_bDelayCreate = false;
	m_bShowContentMenu = true;
	m_bShowScroll = true;
	m_strModuleName = _T("");
	m_strUrl = _T("");
}

CDuiActiveX::~CDuiActiveX()
{
    ReleaseControl();
}

static void PixelToHiMetric(const SIZEL* lpSizeInPix, LPSIZEL lpSizeInHiMetric)
{
#define HIMETRIC_PER_INCH   2540
#define MAP_PIX_TO_LOGHIM(x,ppli)   MulDiv(HIMETRIC_PER_INCH, (x), (ppli))
#define MAP_LOGHIM_TO_PIX(x,ppli)   MulDiv((ppli), (x), HIMETRIC_PER_INCH)
    int nPixelsPerInchX;    // Pixels per logical inch along width
    int nPixelsPerInchY;    // Pixels per logical inch along height
    HDC hDCScreen = ::GetDC(NULL);
    nPixelsPerInchX = ::GetDeviceCaps(hDCScreen, LOGPIXELSX);
    nPixelsPerInchY = ::GetDeviceCaps(hDCScreen, LOGPIXELSY);
    ::ReleaseDC(NULL, hDCScreen);
    lpSizeInHiMetric->cx = MAP_PIX_TO_LOGHIM(lpSizeInPix->cx, nPixelsPerInchX);
    lpSizeInHiMetric->cy = MAP_PIX_TO_LOGHIM(lpSizeInPix->cy, nPixelsPerInchY);
}

// ActiveX¿Ø¼þ³õ'»¯
void CDuiActiveX::OnAxInit()
{
}

// ActiveX¿Ø¼þ¼¤»î
void CDuiActiveX::OnAxActivate(IUnknown *pUnknwn)
{
}

// ActiveX¿Ø¼þ´´½¨¿Ø¼þ¶ÔÏó
void CDuiActiveX::OnAxCreateCtrl()
{
	m_pControl = new CActiveXCtrl();
}

// ActiveX¿Ø¼þ³õ'»¯Íê³É
void CDuiActiveX::OnAxInitFinish()
{
}

// ÉèÖÿؼþÖеÄWindowsÔÉú¿Ø¼þÊÇ·ñ¿É¼ûµÄ״̬
void CDuiActiveX::SetControlWndVisible(BOOL bIsVisible)
{
	if( m_hwndHost != NULL )
	{
		::ShowWindow(m_hwndHost, bIsVisible ? SW_SHOW : SW_HIDE);
	}
}

void CDuiActiveX::SetControlRect(CRect rc)
{
	m_rc = rc;

	if( !m_bCreated ) DoCreateControl();

    if( m_pUnk == NULL ) return;
    if( m_pControl == NULL ) return;

    SIZEL hmSize = { 0 };
    SIZEL pxSize = { 0 };
    pxSize.cx = m_rc.right - m_rc.left;
    pxSize.cy = m_rc.bottom - m_rc.top;
    PixelToHiMetric(&pxSize, &hmSize);

    if( m_pUnk != NULL )
	{
        m_pUnk->SetExtent(DVASPECT_CONTENT, &hmSize);
    }
    if( m_pControl->m_pInPlaceObject != NULL )
	{
        CRect rcItem = m_rc;
        if( !m_pControl->m_bWindowless ) rcItem.MoveToXY(0, 0);
        m_pControl->m_pInPlaceObject->SetObjectRects(&rcItem, &rcItem);
    }
    if( !m_pControl->m_bWindowless )
	{
        ASSERT(m_pControl->m_pWindow);
        ::MoveWindow(*m_pControl->m_pWindow, m_rc.left, m_rc.top, m_rc.right - m_rc.left, m_rc.bottom - m_rc.top, TRUE);
    }
}

// ´ÓXMLÉèÖÃCLSIDÊôÐÔ
HRESULT CDuiActiveX::OnAttributeCLSID(const CString& strValue, BOOL bLoading)
{
	if (strValue.IsEmpty()) return E_FAIL;

	CreateControl(strValue);

	return bLoading?S_FALSE:S_OK;
}

// ´ÓXMLÉèÖÃDelayCreateÊôÐÔ
HRESULT CDuiActiveX::OnAttributeDelayCreate(const CString& strValue, BOOL bLoading)
{
	if (strValue.IsEmpty()) return E_FAIL;

	SetDelayCreate(strValue == _T("true"));

	return bLoading?S_FALSE:S_OK;
}

// ´ÓXMLÉèÖÃurlÊôÐÔ
HRESULT CDuiActiveX::OnAttributeUrl(const CString& strValue, BOOL bLoading)
{
	if (strValue.IsEmpty()) return E_FAIL;

	m_strUrl = strValue;
	if(m_pControl != NULL)
	{
		Navigate(m_strUrl);
	}

	return bLoading?S_FALSE:S_OK;
}

LRESULT CDuiActiveX::MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, bool& bHandled)
{
    if( m_pControl == NULL )
	{
		return 0;
	}
    ASSERT(m_pControl->m_bWindowless);
    if( !m_pControl->m_bInPlaceActive )
	{
		return 0;
	}
    if( m_pControl->m_pInPlaceObject == NULL )
	{
		return 0;
	}
    if( !GetRresponse() && uMsg >= WM_MOUSEFIRST && uMsg <= WM_MOUSELAST )
	{
		return 0;
	}

    bool bWasHandled = true;
    if( (uMsg >= WM_MOUSEFIRST && uMsg <= WM_MOUSELAST) || uMsg == WM_SETCURSOR )
	{
        // Mouse message only go when captured or inside rect
        DWORD dwHitResult = m_pControl->m_bCaptured ? HITRESULT_HIT : HITRESULT_OUTSIDE;
        if( dwHitResult == HITRESULT_OUTSIDE && m_pControl->m_pViewObject != NULL )
		{
            IViewObjectEx* pViewEx = NULL;
            m_pControl->m_pViewObject->QueryInterface(IID_IViewObjectEx, (LPVOID*) &pViewEx);
            if( pViewEx != NULL )
			{
                POINT ptMouse = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
                pViewEx->QueryHitPoint(DVASPECT_CONTENT, &m_rc, ptMouse, 0, &dwHitResult);
                pViewEx->Release();
            }
        }
        if( dwHitResult != HITRESULT_HIT ) return 0;
        if( uMsg == WM_SETCURSOR ) bWasHandled = false;
    }else
	if( uMsg >= WM_KEYFIRST && uMsg <= WM_KEYLAST )
	{
        // Keyboard messages just go when we have focus
        if( !IsFocusControl() ) return 0;
    }else
	{
        switch( uMsg )
		{
        case WM_HELP:
        case WM_CONTEXTMENU:
            bWasHandled = false;
            break;
        default:
            return 0;
        }
    }
    LRESULT lResult = 0;
    HRESULT Hr = m_pControl->m_pInPlaceObject->OnWindowMessage(uMsg, wParam, lParam, &lResult);
    if( Hr == S_OK ) bHandled = bWasHandled;
    return lResult;
}

bool CDuiActiveX::IsDelayCreate() const
{
    return m_bDelayCreate;
}

void CDuiActiveX::SetDelayCreate(bool bDelayCreate)
{
    if( m_bDelayCreate == bDelayCreate ) return;
    if( bDelayCreate == false ) {
        if( m_bCreated == false && m_clsid != IID_NULL ) DoCreateControl();
    }
    m_bDelayCreate = bDelayCreate;
}

bool CDuiActiveX::CreateControl(LPCTSTR pstrCLSID)
{
    CLSID clsid = { 0 };
    OLECHAR szCLSID[100] = { 0 };
#ifndef _UNICODE
    ::MultiByteToWideChar(::GetACP(), 0, pstrCLSID, -1, szCLSID, sizeof(szCLSID) - 1);
#else
    _tcsncpy(szCLSID, pstrCLSID, 99);
#endif
    if( pstrCLSID[0] == '{' )
	{
		::CLSIDFromString(szCLSID, &clsid);
	}else
	{
		::CLSIDFromProgID(szCLSID, &clsid);
	}
    return CreateControl(clsid);
}

bool CDuiActiveX::CreateControl(const CLSID clsid)
{
    ASSERT(clsid!=IID_NULL);
    if( clsid == IID_NULL )
	{
		return false;
	}
    m_bCreated = false;
    m_clsid = clsid;
    if( !m_bDelayCreate )
	{
		DoCreateControl();
	}
    return true;
}

void CDuiActiveX::ReleaseControl()
{
	if(m_pCP)
	{
		m_pCP->Unadvise(m_dwEventCookie);
		m_pCP->Release();
	}
	m_pCP = NULL;

    m_hwndHost = NULL;
    if( m_pUnk != NULL )
	{
        IObjectWithSite* pSite = NULL;
        m_pUnk->QueryInterface(IID_IObjectWithSite, (LPVOID*) &pSite);
        if( pSite != NULL )
		{
            pSite->SetSite(NULL);
            pSite->Release();
        }
        m_pUnk->Close(OLECLOSE_NOSAVE);
        m_pUnk->SetClientSite(NULL);
        m_pUnk->Release();
        m_pUnk = NULL;
    }
    if( m_pControl != NULL )
	{
        m_pControl->m_pOwner = NULL;
        m_pControl->Release();
        m_pControl = NULL;
    }
    //m_pManager->RemoveMessageFilter(this);
}

typedef HRESULT (__stdcall *DllGetClassObjectFunc)(REFCLSID rclsid, REFIID riid, LPVOID* ppv);

// ´´½¨ActiveX¿Ø¼þ
bool CDuiActiveX::DoCreateControl()
{
    ReleaseControl();
    // At this point we'll create the ActiveX control
    m_bCreated = true;
    IOleControl* pOleControl = NULL;

	// ¿Ø¼þ³õ'»¯
	OnAxInit();

    HRESULT Hr = -1;
    if( !m_strModuleName.IsEmpty() )
	{
        HMODULE hModule = ::LoadLibrary((LPCTSTR)m_strModuleName);
        if( hModule != NULL )
		{
            IClassFactory* aClassFactory = NULL;
            DllGetClassObjectFunc aDllGetClassObjectFunc = (DllGetClassObjectFunc)::GetProcAddress(hModule, "DllGetClassObject");
            Hr = aDllGetClassObjectFunc(m_clsid, IID_IClassFactory, (LPVOID*)&aClassFactory);
            if( SUCCEEDED(Hr) )
			{
                Hr = aClassFactory->CreateInstance(NULL, IID_IOleObject, (LPVOID*)&pOleControl);
            }
            aClassFactory->Release();
        }
    }
    if( FAILED(Hr) )
	{
        Hr = ::CoCreateInstance(m_clsid, NULL, CLSCTX_ALL, IID_IOleControl, (LPVOID*)&pOleControl);
		if( FAILED(Hr) )
		{
			LPOLESTR lpwClsid = NULL;
			Hr = StringFromCLSID(m_clsid, &lpwClsid);
			if (SUCCEEDED(Hr))
			{
				USES_CONVERSION;
				LPCTSTR lpszClsid = OLE2T(lpwClsid);
				DuiSystem::LogEvent(LOG_LEVEL_ERROR, _T("CoCreateInstance %s failed"), lpszClsid);
				IMalloc * pMalloc = NULL;
				Hr = ::CoGetMalloc(1, &pMalloc);	// È¡µÃ IMalloc
				if (SUCCEEDED(Hr))
				{
					pMalloc->Free(lpwClsid);		// ÊÍ·ÅProgIDÄÚ´æ
					pMalloc->Release();				// ÊÍ·ÅIMalloc
				}
			}
		}
		// ¿Ø¼þ¼¤»î
		OnAxActivate(pOleControl);
    }
    //ASSERT(SUCCEEDED(Hr));
    if( FAILED(Hr) ) return false;
    pOleControl->QueryInterface(IID_IOleObject, (LPVOID*) &m_pUnk);
    pOleControl->Release();
    if( m_pUnk == NULL ) return false;

    // Create the host too
	OnAxCreateCtrl();
	if(m_pControl != NULL)
	{
		m_pControl->m_pOwner = this;
	}

    // More control creation stuff
    DWORD dwMiscStatus = 0;
    m_pUnk->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus);
    IOleClientSite* pOleClientSite = NULL;
    m_pControl->QueryInterface(IID_IOleClientSite, (LPVOID*) &pOleClientSite);
    CSafeRelease<IOleClientSite> RefOleClientSite = pOleClientSite;

    // Initialize control,ÉèÖÃÓû§site
    if( (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST) != 0 ) m_pUnk->SetClientSite(pOleClientSite);
    IPersistStreamInit* pPersistStreamInit = NULL;
    m_pUnk->QueryInterface(IID_IPersistStreamInit, (LPVOID*) &pPersistStreamInit);
    if( pPersistStreamInit != NULL )
	{
        Hr = pPersistStreamInit->InitNew();
        pPersistStreamInit->Release();
    }
    if( FAILED(Hr) ) return false;
    if( (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST) == 0 ) m_pUnk->SetClientSite(pOleClientSite);

    // Grab the view...
    Hr = m_pUnk->QueryInterface(IID_IViewObjectEx, (LPVOID*) &m_pControl->m_pViewObject);
    if( FAILED(Hr) ) Hr = m_pUnk->QueryInterface(IID_IViewObject2, (LPVOID*) &m_pControl->m_pViewObject);
    if( FAILED(Hr) ) Hr = m_pUnk->QueryInterface(IID_IViewObject, (LPVOID*) &m_pControl->m_pViewObject);

    // Activate and done...,¼¤»îä¯ÀÀÆ÷¿Ø¼þ
    m_pUnk->SetHostNames(OLESTR("UIActiveX"), NULL);
    //if( m_pManager != NULL ) m_pManager->SendNotify((CControlUI*)this, _T("showactivex"), 0, 0, false);
    if( (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME) == 0 )
	{
        Hr = m_pUnk->DoVerb(OLEIVERB_INPLACEACTIVATE, NULL, pOleClientSite, 0, GetPaintHWnd(), &m_rc);
        //::RedrawWindow(GetPaintHWnd(), &m_rcItem, NULL, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE | RDW_INTERNALPAINT | RDW_FRAME);
    }
    IObjectWithSite* pSite = NULL;
    m_pUnk->QueryInterface(IID_IObjectWithSite, (LPVOID*) &pSite);
    if( pSite != NULL )
	{
        pSite->SetSite(static_cast<IOleClientSite*>(m_pControl));
        pSite->Release();
    }

	// ¿Ø¼þ³õ'»¯Íê³É
	OnAxInitFinish();

	// ÉèÖóõ'µÄURL,µ¼º½µ½URL
	if(!m_strUrl.IsEmpty())
	{
		Navigate(m_strUrl);
	}

    return SUCCEEDED(Hr);
}

// µ¼º½µ½Ö¸¶¨µÄURL
HRESULT CDuiActiveX::Navigate(CString strUrl)
{
	return S_FALSE;
}

// ¸ù¾ÝIID»ñÈ¡ActiveX¿Ø¼þ
HRESULT CDuiActiveX::GetControl(const IID iid, LPVOID* ppRet)
{
    ASSERT(ppRet!=NULL);
    ASSERT(*ppRet==NULL);
    if( ppRet == NULL )
	{
		return E_POINTER;
	}
    if( m_pUnk == NULL )
	{
		return E_PENDING;
	}
    return m_pUnk->QueryInterface(iid, (LPVOID*) ppRet);
}

CLSID CDuiActiveX::GetClisd() const
{
	return m_clsid;
}

CString CDuiActiveX::GetModuleName() const
{
    return m_strModuleName;
}

void CDuiActiveX::SetModuleName(LPCTSTR pstrText)
{
    m_strModuleName = pstrText;
}

// ¿Ø¼þ»Í¼º¯Êý
void CDuiActiveX::DrawControl(CDC &dc, CRect rcUpdate)
{
	if( !::IntersectRect(&rcUpdate, &rcUpdate, &m_rc) )
	{
		return;
	}

	if( m_pControl != NULL && m_pControl->m_bWindowless && m_pControl->m_pViewObject != NULL )
    {
		// ÎÞ´°¿Úģʽϵ÷ÓÃActiveX¿Ø¼þµÄView½Ó¿Ú»Í¼
        m_pControl->m_pViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, dc.m_hDC, (RECTL*) &m_rc, (RECTL*) &m_rc, NULL, NULL);
    }
}

// Îļþ·¾¶½âÎö
CString CDuiActiveX::ParseFilePath(CString strUrl)
{
	// ͨ¹ýSkin¶ÁÈ¡
	CString strSkin = _T("");
	if(strUrl.Find(_T("skin:")) == 0)
	{
		strSkin = DuiSystem::Instance()->GetSkin(strUrl);
		if (strSkin.IsEmpty()) return FALSE;
	}else
	{
		strSkin = strUrl;
	}

	if(strSkin.Find(_T(".")) != -1)	// ¼ÓÔØÎļþ
	{
		CString strFile = DuiSystem::GetSkinPath() + strSkin;
		if(strSkin.Find(_T(":")) != -1)
		{
			strFile = strSkin;
		}
		return strFile;
	}

	CString strFile = strSkin;
	return strFile;
}

/////////////////////////////////////////////////////////////////////////////////////
// CDuiWebBrowserCtrl

CDuiWebBrowserCtrl::CDuiWebBrowserCtrl(HWND hWnd, CDuiObject* pDuiObject)
	: CDuiActiveX(hWnd, pDuiObject)
{
	m_bDuiMsgInvoke = FALSE;
}

CDuiWebBrowserCtrl::~CDuiWebBrowserCtrl()
{
}

// ActiveX¿Ø¼þ³õ'»¯
void CDuiWebBrowserCtrl::OnAxInit()
{
	::CLSIDFromString(L"{8856F961-340A-11D0-A96B-00C04FD705A2}", &m_clsid);	// IEä¯ÀÀÆ÷¿Ø¼þID
}

// ActiveX¿Ø¼þ¼¤»î
void CDuiWebBrowserCtrl::OnAxActivate(IUnknown *pUnknwn)
{
}

// ÉèÖÿؼþµÄDUIÏûÏ¢·¢Ëͱêʶ
BOOL CDuiWebBrowserCtrl::OnControlSetDuiMsg(LPCTSTR lpszDuiMsg)
{
	if(__super::OnControlSetDuiMsg(lpszDuiMsg))
	{
		return TRUE;
	}

	CString strDuiMsg = lpszDuiMsg;
	if(strDuiMsg == _T("invoke"))	// ·¢ËÍInvokeµÄDUIÏûÏ¢
	{
		m_bDuiMsgInvoke = TRUE;
		return TRUE;
	}

	return FALSE;
}

// ActiveX¿Ø¼þ´´½¨¿Ø¼þ¶ÔÏó
void CDuiWebBrowserCtrl::OnAxCreateCtrl()
{
	m_pControl = new CWebBrowserCtrl();
}

// ActiveX¿Ø¼þ³õ'»¯Íê³É
void CDuiWebBrowserCtrl::OnAxInitFinish()
{
	// ³õ'»¯ä¯ÀÀÆ÷'þ´¦Àí
	InitEvents();
}

// »ñÈ¡IWebBrowser2½Ó¿ÚÖ¸Õë
IWebBrowser2* CDuiWebBrowserCtrl::GetIWebBrowser2()
{
	IWebBrowser2* pWebBrowser = NULL;
	GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
	return pWebBrowser;
}

// »ñÈ¡µ±Ç°µÄURL
CString CDuiWebBrowserCtrl::getURL()
{
	IWebBrowser2* pIWebBrowser = GetIWebBrowser2();
	if(pIWebBrowser != NULL)
	{
		BSTR bstrURL;
		HRESULT hr = pIWebBrowser->get_LocationURL(&bstrURL);
		if(SUCCEEDED(hr))
		{
#ifdef _UNICODE
			return bstrURL;
#else
			_bstr_t tout(bstrURL, FALSE);
			CString out = tout;
			return out;
#endif
		}
	}
	return _T("");
}

// µ¼º½µ½Ö¸¶¨µÄURL
HRESULT CDuiWebBrowserCtrl::Navigate(CString strUrl)
{
	HRESULT hr = -1;
	IWebBrowser2* pWebBrowser = NULL;
	GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
	if( pWebBrowser != NULL )
	{
		if(strUrl.Find(_T("file://")) == 0)
		{
			strUrl.Delete(0, 7);
			if(strUrl.Find(_T(":")) == -1)
			{
				strUrl = DuiSystem::GetSkinPath() + strUrl;
			}
		}
		BSTR bsUrl = strUrl.AllocSysString();
		hr = pWebBrowser->Navigate(bsUrl,NULL,NULL,NULL,NULL);
		pWebBrowser->Release();
		::SysFreeString(bsUrl);
	}

	return hr;
}

// µ¼º½µ½ÉÏÒ»¸öURL
HRESULT CDuiWebBrowserCtrl::GoBack()
{
	HRESULT hr = -1;
	IWebBrowser2* pWebBrowser = NULL;
	GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
	if( pWebBrowser != NULL )
	{
		hr = pWebBrowser->GoBack();
		pWebBrowser->Release();
	}

	return hr;
}

// µ¼º½µ½ÏÂÒ»¸öURL
HRESULT CDuiWebBrowserCtrl::GoForward()
{
	HRESULT hr = -1;
	IWebBrowser2* pWebBrowser = NULL;
	GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
	if( pWebBrowser != NULL )
	{
		hr = pWebBrowser->GoForward();
		pWebBrowser->Release();
	}

	return hr;
}

// Ë¢ÐÂÒ³Ãæ
HRESULT CDuiWebBrowserCtrl::Refresh()
{
	HRESULT hr = -1;
	IWebBrowser2* pWebBrowser = NULL;
	GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
	if( pWebBrowser != NULL )
	{
		hr = pWebBrowser->Refresh();
		pWebBrowser->Release();
	}

	return hr;
}

// Í£Ö¹¼ÓÔØÒ³Ãæ
HRESULT CDuiWebBrowserCtrl::Stop()
{
	HRESULT hr = -1;
	IWebBrowser2* pWebBrowser = NULL;
	GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
	if( pWebBrowser != NULL )
	{
		hr = pWebBrowser->Stop();
		pWebBrowser->Release();
	}

	return hr;
}

// »ñÈ¡Ò³ÃæÊÇ·ñÕýÔÚ¼ÓÔØ
HRESULT CDuiWebBrowserCtrl::GetBusy(BOOL& bBusy)
{
	HRESULT hr = -1;
	IWebBrowser2* pWebBrowser = NULL;
	GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
	VARIANT_BOOL pBusy = VARIANT_FALSE;
	if( pWebBrowser != NULL )
	{
		hr = pWebBrowser->get_Busy(&pBusy);
		pWebBrowser->Release();
	}

	bBusy = (pBusy == VARIANT_TRUE);

	return hr;
}

// ³õ'»¯ä¯ÀÀÆ÷¿Ø¼þµÄ'þ´¦Àí
HRESULT CDuiWebBrowserCtrl::InitEvents()
{
	HRESULT                     hr;
	IConnectionPointContainer  *pCPCont = NULL;
	DWebBrowserEvents          *pEvents = NULL;

	IWebBrowser2* pWebBrowser = NULL;
	GetControl(IID_IWebBrowser2, (void**)&pWebBrowser);
	if(!pWebBrowser)
	{
		return S_FALSE;
	}

	hr = pWebBrowser->QueryInterface(IID_IConnectionPointContainer, (LPVOID *)&pCPCont);
	if(FAILED(hr))
	{
		return S_FALSE;
	}

	hr = pCPCont->FindConnectionPoint(DIID_DWebBrowserEvents2, &m_pCP);
	if(FAILED(hr))
	{
		m_pCP = NULL;
		goto Cleanup;
	}

	hr = m_pControl->QueryInterface(DIID_DWebBrowserEvents2, (LPVOID *)(&pEvents));
	if(FAILED(hr))
		goto Cleanup;
	hr = m_pCP->Advise(pEvents, &(m_dwEventCookie));
	if(FAILED(hr))
		goto Cleanup;

Cleanup:
	if(pCPCont)
		pCPCont->Release();
	if(pEvents)
		pEvents->Release();
	return hr;
}

/////////////////////////////////////////////////////////////////////////////////////
// CDuiFlashCtrl
// ÖØÔØnew²Ù×÷·û£¬Åж¨Èç¹ûflashûÓа²×°£¬·µ»Ønull
void* CDuiFlashCtrl::operator new(size_t sz)
{
	static bool bIsExistFlashActiveX = false;
	static bool bCheckedFlashActivex = false;
	if (!bCheckedFlashActivex)
	{
		bIsExistFlashActiveX = isExistFlashActiveX();
		bCheckedFlashActivex = true;
	}

	if (!bIsExistFlashActiveX)
		return NULL;
	return ::operator new(sz);
}

CDuiFlashCtrl::CDuiFlashCtrl(HWND hWnd, CDuiObject* pDuiObject)
	: CDuiActiveX(hWnd, pDuiObject)
{
	m_bTransparent = false;
	m_strVars = _T("");
}

CDuiFlashCtrl::~CDuiFlashCtrl()
{
}

// ActiveX¿Ø¼þ³õ'»¯
void CDuiFlashCtrl::OnAxInit()
{
	m_clsid=__uuidof(ShockwaveFlashObjects::ShockwaveFlash);
}

// ActiveX¿Ø¼þ¼¤»î
void CDuiFlashCtrl::OnAxActivate(IUnknown *pUnknwn)
{
	// ±£´æflash¿Ø¼þ½Ó¿Ú
	flash_ = pUnknwn;
	CDuiComQIPtr<ShockwaveFlashObjects::IShockwaveFlash> flash = flash_;

	if(m_bTransparent)
	{
		// ´´½¨Í¸Ã÷ÎÞ´°ÌåµÄFlash¿Ø¼þ,ʹÓÃDUI¿Ø¼þµÄ´°¿Ú¾ä±ú»Í¼
		flash->put_WMode(bstr_t(_T("transparent")));
	}

	flash->DisableLocalSecurity();
	flash->put_AllowScriptAccess(bstr_t(_T("always")));
}

// ActiveX¿Ø¼þ³õ'»¯Íê³É
void CDuiFlashCtrl::OnAxInitFinish()
{
}

// µ¼º½µ½Ö¸¶¨µÄURL
HRESULT CDuiFlashCtrl::Navigate(CString strUrl)
{
	HRESULT hr = S_OK;
	if(flash_)
	{
		CDuiComQIPtr<ShockwaveFlashObjects::IShockwaveFlash> flash = flash_;
		if(!strUrl.IsEmpty())
		{
			m_strUrl = strUrl;
			flash->put_Movie(bstr_t(ParseFilePath(m_strUrl)));
			if(!m_strVars.IsEmpty())
			{
				flash->PutFlashVars(bstr_t(m_strVars));
			}
			flash->Play();
		}
	}

	return hr;
}

// ÉèÖÃFlash²ÎÊý
HRESULT CDuiFlashCtrl::PutFlashVars(CString strVars)
{
	HRESULT hr = S_OK;
	if(flash_)
	{
		if(!strVars.IsEmpty())
		{
			CDuiComQIPtr<ShockwaveFlashObjects::IShockwaveFlash> flash = flash_;
			flash->PutFlashVars(bstr_t(strVars));
		}
	}

	return hr;
}

// ¼ì²âÊÇ·ñ°²×°flash
bool CDuiFlashCtrl::isExistFlashActiveX()
{
	HKEY hKey = NULL;

	// Èç¹û×¢²á±íÖÐûÓÐFlashPlayerX£¬Ôò·µ»Øfalse
	if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("SOFTWARE\\Macromedia\\FlashPlayerActiveX"),0,KEY_READ,&hKey)!=ERROR_SUCCESS)
		return false;

	std::wstring strValueName;
	std::wstring strDataBuffer;
	strValueName.resize(1024);
	strDataBuffer.resize(1024);
	DWORD nValueNameBufferLength=1024, nValueType, nDataBudderSize=1024;

	int i=0;
	while(RegEnumValueW(hKey,i++, (LPWSTR)strValueName.c_str(), &nValueNameBufferLength, NULL, &nValueType, (BYTE*)strDataBuffer.c_str(), &nDataBudderSize) != ERROR_NO_MORE_ITEMS)
	{
		std::wstring strName(strValueName.c_str());
		if (strName.compare(L"PlayerPath") == 0)
		{

			if( (_waccess(std::wstring(strDataBuffer.c_str()).c_str(), 0 )) == -1 )
				return false;
		}

		nDataBudderSize=1024;
		nValueNameBufferLength=1024;
	}
	return true;
}

/////////////////////////////////////////////////////////////////////////////////////
// CDuiMediaPlayer

CDuiMediaPlayer::CDuiMediaPlayer(HWND hWnd, CDuiObject* pDuiObject)
	: CDuiActiveX(hWnd, pDuiObject)
{
}

CDuiMediaPlayer::~CDuiMediaPlayer()
{
}

// ActiveX¿Ø¼þ³õ'»¯
void CDuiMediaPlayer::OnAxInit()
{
	m_clsid=__uuidof(WMPLib::WindowsMediaPlayer);
}

// ActiveX¿Ø¼þ¼¤»î
void CDuiMediaPlayer::OnAxActivate(IUnknown *pUnknwn)
{
	// ±£´æmediaplayer¿Ø¼þ½Ó¿Ú
	wmp_ = pUnknwn;
	if(wmp_)
	{
		// ÉèÖÃΪÎÞ´°¿Úģʽ,ʹÓÃDUI¿Ø¼þµÄ´°¿Ú¾ä±ú»Í¼
		//wmp_->put_windowlessVideo(VARIANT_TRUE);
		// ÉìËõ»Ã棬ʹÆäÊʺϲ¥·Å´°¿Ú
		//wmp_->put_stretchToFit(TRUE);
		// ÔÊÐíÓÒ¼ü²Ëµ¥
		//wmp_->PutenableContextMenu(TRUE);
	}
}

// ActiveX¿Ø¼þ³õ'»¯Íê³É
void CDuiMediaPlayer::OnAxInitFinish()
{
}

// ÉèÖÿؼþÖеÄWindowsÔÉú¿Ø¼þÊÇ·ñ¿É¼ûµÄ״̬
void CDuiMediaPlayer::SetControlWndVisible(BOOL bIsVisible)
{
	if(( m_hwndHost != NULL ) && (wmp_ != NULL))
	{
		CDuiComQIPtr<WMPLib::IWMPPlayer4> wmp = wmp_;
		//::ShowWindow(m_hwndHost, bIsVisible ? SW_SHOW : SW_HIDE);
		//CString str = wmp_->GetuiMode();
		//TRACE("CDuiMediaPlayer::SetControlWndVisible %s\n", str);
		if(bIsVisible)
		{
			::ShowWindow(m_hwndHost, SW_SHOW);
			wmp->PutuiMode("full");
		}else
		{
			wmp->PutuiMode("Invisible");
		}
	}
}

// µ¼º½µ½Ö¸¶¨µÄURL
HRESULT CDuiMediaPlayer::Navigate(CString strUrl)
{
	HRESULT hr = S_OK;
	if(wmp_)
	{
		CDuiComQIPtr<WMPLib::IWMPPlayer4> wmp = wmp_;
		wmp->close();
		if(!strUrl.IsEmpty())
		{
			m_strUrl = strUrl;
			wmp->put_URL(bstr_t(ParseFilePath(m_strUrl)));
			//wmp_->openPlayer(bstr_t(ParseFilePath(m_strUrl)));	// ´ò¿ªµ¥¶ÀµÄ²¥·Å´°¿Ú
		}
	}

	return hr;
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax

    Friend Structure SeparatedSyntaxListBuilder(Of TNode As SyntaxNode)
        Private builder As SyntaxListBuilder
        Private expectSeparator As Boolean

        Public Shared Function Create() As SeparatedSyntaxListBuilder(Of TNode)
            Return New SeparatedSyntaxListBuilder(Of TNode)(8)
        End Function

        Public Sub New(size As Integer)
            Me.New(New SyntaxListBuilder(size))
        End Sub

        Friend Sub New(builder As SyntaxListBuilder)
            Me.builder = builder
        End Sub

        Public ReadOnly Property IsNull As Boolean
            Get
                Return (Me.builder Is Nothing)
            End Get
        End Property

        Public ReadOnly Property Count As Integer
            Get
                Return Me.builder.Count
            End Get
        End Property

        Public Sub Clear()
            Me.builder.Clear()
        End Sub

        Public Sub Add(node As TNode)
            If expectSeparator Then
                Throw New InvalidOperationException("separator is expected")
            End If
            expectSeparator = True
            Me.builder.Add(DirectCast(DirectCast(node, SyntaxNode), VisualBasicSyntaxNode))
        End Sub

        Friend Sub AddSeparator(separatorToken As InternalSyntax.SyntaxToken)
            If Not expectSeparator Then
                Throw New InvalidOperationException("element is expected")
            End If
            expectSeparator = False
            Me.builder.AddInternal(separatorToken)
        End Sub

        Public Sub AddSeparator(separatorToken As SyntaxToken)
            AddSeparator(DirectCast(separatorToken.Node, InternalSyntax.SyntaxToken))
        End Sub

        Public Sub AddRange(nodes As SeparatedSyntaxList(Of TNode))
            If expectSeparator Then
                Throw New InvalidOperationException("separator is expected")
            End If
            Dim list = nodes.GetWithSeparators
            Me.builder.AddRange(list)
            expectSeparator = ((Me.builder.Count And 1) <> 0)
        End Sub

        Friend Sub AddRange(nodes As SeparatedSyntaxList(Of TNode), count As Integer)
            If expectSeparator Then
                Throw New InvalidOperationException("separator is expected")
            End If
            Dim list = nodes.GetWithSeparators
            Me.builder.AddRange(list, Me.Count, Math.Min(count * 2, list.Count))
            expectSeparator = ((Me.builder.Count And 1) <> 0)
        End Sub

        Friend Sub RemoveLast()
            Me.builder.RemoveLast()
        End Sub

        Public Function Any(kind As SyntaxKind) As Boolean
            Return Me.builder.Any(kind)
        End Function

        Public Function ToList() As SeparatedSyntaxList(Of TNode)
            If builder Is Nothing Then
                Return New SeparatedSyntaxList(Of TNode)()
            End If
            Return builder.ToSeparatedList(Of TNode)()
        End Function

        Public Function ToList(Of TDerived As TNode)() As SeparatedSyntaxList(Of TDerived)
            If builder Is Nothing Then
                Return New SeparatedSyntaxList(Of TDerived)()
            End If
            Return builder.ToSeparatedList(Of TDerived)()
        End Function

        Public Shared Widening Operator CType(builder As SeparatedSyntaxListBuilder(Of TNode)) As SeparatedSyntaxList(Of TNode)
            Return builder.ToList
        End Operator

    End Structure
End Namespace

redpajama_set_name: RedPajamaGithub


text:
.. _util/index:

====
Util
====

The util/ directory is different than dojo/dijit/dojox in that it doesn't contain JavaScript code that accessed directly from web pages.   Rather, it contains utility scripts as listed below.

:ref:`Dojo Build System <build/index>`
--------------------------------------

:ref:`The Dojo build system <build/index>` is used to create efficient optimized packages of JavaScript and CSS, customized for a given application or website. You can take advantage of this powerful tool to help structure your development and speed up your applications.

:ref:`ShrinkSafe <util/shrinksafe/index>`
-----------------------------------------

:ref:`ShrinkSafe <util/shrinksafe/index>` is a standalone utility for compressing JavaScript,
used by the Dojo Build System as an optional compression step, though can be used on individual files manually.

:ref:`DOH <util/doh>`
------------------------

:ref:`DOH <util/doh>` is the test harness used by dojo, similar to JUnit. The util/doh/ directory also contains :ref:`DOH Robot <util/dohrobot>`, an API used in conjunction with DOH for automated keyboard/mouse testing.

:ref:`Checkstyle <util/checkstyle>`
-----------------------------------

:ref:`Checkstyle <util/checkstyle>` is a standalone utility for checking JavaScript files for violations of
the Dojo style guide. Also includes an online tool for automatically fixing the majority of style guide violations.

`Dojo Documentation System <http://dojotoolkit.org/api/>`_
------------------------------------------------------------

Dojo uses a custom inline comment syntax which produces well structured xml, and powers the official `API Docs <http://dojotoolkit.org/api/>`_ . The doc system is powered by js-doc-parse.   To get up and running quickly, check out `this quickstart tutorial <http://www.sitepen.com/blog/2013/01/18/generating-and-viewing-custom-api-docs/>`_ . For full js-doc-parse documentation, see https://github.com/wkeese/api-viewer/blob/master/README.rst .

Previously, the API docs were powered by the :ref:`doctools <util/doctools>` directory.
However, this is now deprecated and will be removed in 2.0.

Migration
-----------
The migration directory contains scripts for helping to migrate from older versions of dojo to newer ones.


text:
require 'spec_helper'

describe Twelve::API::Me do
  subject { Twelve.new(ACCESS_TOKEN) }

  def should_be_me(me)
    me['urls']['self'].should == 'https://secure.gaug.es/me'
    me['urls']['gauges'].should == 'https://secure.gaug.es/gauges'
    me['urls']['clients'].should == 'https://secure.gaug.es/clients'
    me['id'].size.should == 24
    me['email'].should_not be_nil
  end

  describe "#me" do
    context "without an arguement" do
      it "returns my information" do
        VCR.use_cassette('me') do
          me = subject.me
          should_be_me(me)
        end
      end
    end

    context "with a hash" do
      it "updates my information" do
        VCR.use_cassette('me_with_hash') do
          me = subject.me(:first_name => 'Jon')
          should_be_me(me)
          me['first_name'].should == "Jon"
        end
      end
    end
  end
end


text:
body {
  font-family: 'Lato', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  overflow-x: hidden; }

p {
  font-size: 20px; }

p.small {
  font-size: 16px; }

a,
a.active,
a:active,
a:focus,
a:hover {
  color: #18BC9C;
  outline: none; }

h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: 'Montserrat', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 700;
  text-transform: uppercase; }

hr.star-light,
hr.star-primary {
  max-width: 250px;
  margin: 25px auto 30px;
  padding: 0;
  text-align: center;
  border: none;
  border-top: solid 5px; }

hr.star-light:after,
hr.star-primary:after {
  font-family: FontAwesome;
  font-size: 2em;
  position: relative;
  top: -.8em;
  display: inline-block;
  padding: 0 0.25em;
  content: '\f005'; }

hr.star-light {
  border-color: white; }

hr.star-light:after {
  color: white;
  background-color: #18BC9C; }

hr.star-primary {
  border-color: #2C3E50; }

hr.star-primary:after {
  color: #2C3E50;
  background-color: white; }

.img-centered {
  margin: 0 auto; }

section {
  padding: 100px 0; }
  section h2 {
    font-size: 3em;
    margin: 0; }

section.success {
  color: white;
  background: #18BC9C;  }

a.success {
  color: white;
  background: #18BC9C;  }
a.list-group-item>p {
	font-size: 15px;
}

@media (max-width: 767px) {
  section {
    padding: 75px 0; }
  section.first {
    padding-top: 75px; } }

.scroll-top {
  position: fixed;
  z-index: 1049;
  right: 2%;
  bottom: 2%;
  width: 50px;
  height: 50px; }
  .scroll-top .btn {
    font-size: 16px;
    line-height: 28px;
    width: 50px;
    height: 50px;
    text-align: center;
    border-radius: 100%; }
    .scroll-top .btn:focus {
      outline: none; }

#mainNav {
  font-family: 'Montserrat', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 700;
  text-transform: uppercase;
  border: none;
  background: #2C3E50; }
  #mainNav a:focus {
    outline: none; }
  #mainNav .navbar-brand {
    font-size: 1.1rem;
    color: white; }
    #mainNav .navbar-brand.active, #mainNav .navbar-brand:active, #mainNav .navbar-brand:focus, #mainNav .navbar-brand:hover {
      color: white; }
  #mainNav .navbar-nav {
    letter-spacing: 1px; }
    #mainNav .navbar-nav li.nav-item a.nav-link {
      color: white; }
      #mainNav .navbar-nav li.nav-item a.nav-link:hover {
        color: #18BC9C;
        outline: none; }
      #mainNav .navbar-nav li.nav-item a.nav-link:active, #mainNav .navbar-nav li.nav-item a.nav-link:focus {
        color: white; }
  #mainNav .navbar-toggler {
    font-size: 14px;
    padding: 11px;
    text-transform: uppercase;
    color: white;
    border-color: white; }
    #mainNav .navbar-toggler:focus, #mainNav .navbar-toggler:hover {
      color: white;
      border-color: #18BC9C;
      background-color: #18BC9C; }

@media (min-width: 992px) {
  #mainNav {
    padding-top: 25px;
    padding-bottom: 25px;
    -webkit-transition: padding-top 0.3s, padding-bottom 0.3s;
    -moz-transition: padding-top 0.3s, padding-bottom 0.3s;
    transition: padding-top 0.3s, padding-bottom 0.3s; }
    #mainNav .navbar-brand {
      font-size: 2em;
      -webkit-transition: all 0.3s;
      -moz-transition: all 0.3s;
      transition: all 0.3s; }
    #mainNav .navbar-nav > li.nav-item > a.nav-link.active {
      color: white;
      border-radius: 3px;
      background: #18BC9C; }
      #mainNav .navbar-nav > li.nav-item > a.nav-link.active:active, #mainNav .navbar-nav > li.nav-item > a.nav-link.active:focus, #mainNav .navbar-nav > li.nav-item > a.nav-link.active:hover {
        color: white;
        background: #18BC9C; }
  #mainNav.navbar-shrink {
    padding-top: 10px;
    padding-bottom: 10px; }
    #mainNav.navbar-shrink .navbar-brand {
      font-size: 1.5em; } }

header.masthead {
  padding-top: 100px;
  padding-bottom: 50px;
  text-align: center;
  color: white;
  background: #18BC9C; }
  header.masthead img {
    display: block;
    margin: 0 auto 20px; }
  header.masthead .intro-text .name {
    font-family: 'Montserrat', 'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-size: 2em;
    font-weight: 700;
    display: block;
    text-transform: uppercase; }
  header.masthead .intro-text .skills {
    font-size: 1.25em;
    font-weight: 300; }

@media (min-width: 768px) {
  header.masthead {
    padding-top: 200px;
    padding-bottom: 100px; }
    header.masthead .intro-text .name {
      font-size: 4.75em; }
    header.masthead .intro-text .skills {
      font-size: 1.75em; } }

#portfolio .portfolio-item {
  right: 0;
  margin: 0 0 15px; }
  #portfolio .portfolio-item .portfolio-link {
    position: relative;
    display: block;
    max-width: 400px;
    margin: 0 auto;
    cursor: pointer;
	text-align: center;}
    #portfolio .portfolio-item .portfolio-link .caption {
      position: absolute;
      width: 100%;
      height: 100%;
      -webkit-transition: all ease 0.5s;
      -moz-transition: all ease 0.5s;
      transition: all ease 0.5s;
      opacity: 0;
      background: rgba(24, 188, 156, 0.9); }
      #portfolio .portfolio-item .portfolio-link .caption:hover {
        opacity: 1; }
      #portfolio .portfolio-item .portfolio-link .caption .caption-content {
        font-size: 20px;
        position: absolute;
        top: 50%;
        width: 100%;
        height: 20px;
        margin-top: -12px;
        text-align: center;
        color: white; }
        #portfolio .portfolio-item .portfolio-link .caption .caption-content i {
          margin-top: -12px; }
        #portfolio .portfolio-item .portfolio-link .caption .caption-content h3,
        #portfolio .portfolio-item .portfolio-link .caption .caption-content h4 {
          margin: 0; }

#portfolio * {
  z-index: 2; }

i {
font-size: 11em;}

@media (min-width: 767px) {
  #portfolio .portfolio-item {
    margin: 0 0 30px; } }

.portfolio-modal .modal-dialog {
  max-width: 100%;
  min-height: 100%;
  margin: 0;
  padding: 0;
  text-align: center;
  border: none;
  border-radius: 0;
  background-clip: border-box;
  -webkit-box-shadow: none;
  box-shadow: none; }
  .portfolio-modal .modal-dialog .modal-content {
    padding: 100px 0;
    border: 0;
    border-radius: 0; }
    .portfolio-modal .modal-dialog .modal-content h2 {
      font-size: 3em;
      margin: 0; }
    .portfolio-modal .modal-dialog .modal-content img {
      margin-bottom: 30px; }
    .portfolio-modal .modal-dialog .modal-content .item-details {
      margin: 30px 0; }

ul#concepts{
	margin:auto;
	text-align: left;
	width: 80%
}
.portfolio-modal .close-modal {
  position: absolute;
  top: 25px;
  right: 25px;
  width: 75px;
  height: 75px;
  cursor: pointer;
  background-color: transparent; }
  .portfolio-modal .close-modal:hover {
    opacity: 0.3; }
  .portfolio-modal .close-modal .lr {
    /* Safari and Chrome */
    z-index: 1051;
    width: 1px;
    height: 75px;
    margin-left: 35px;
    /* IE 9 */
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
    background-color: #2C3E50; }
    .portfolio-modal .close-modal .lr .rl {
      /* Safari and Chrome */
      z-index: 1052;
      width: 1px;
      height: 75px;
      /* IE 9 */
      -webkit-transform: rotate(90deg);
      -ms-transform: rotate(90deg);
      transform: rotate(90deg);
      background-color: #2C3E50; }

.portfolio-modal .modal-backdrop {
  display: none;
  opacity: 0; }

.floating-label-form-group {
  position: relative;
  margin-bottom: 0;
  padding-bottom: 0.5em;
  border-bottom: 1px solid #eeeeee; }
  .floating-label-form-group input,
  .floating-label-form-group textarea {
    font-size: 1.5em;
    position: relative;
    z-index: 1;
    padding-right: 0;
    padding-left: 0;
    resize: none;
    border: none;
    border-radius: 0;
    background: none;
    box-shadow: none !important; }
  .floating-label-form-group label {
    font-size: 0.85em;
    line-height: 1.764705882em;
    position: relative;
    z-index: 0;
    top: 2em;
    display: block;
    margin: 0;
    -webkit-transition: top 0.3s ease, opacity 0.3s ease;
    -moz-transition: top 0.3s ease, opacity 0.3s ease;
    -ms-transition: top 0.3s ease, opacity 0.3s ease;
    transition: top 0.3s ease, opacity 0.3s ease;
    vertical-align: middle;
    vertical-align: baseline;
    opacity: 0; }
  .floating-label-form-group:not(:first-child) {
    padding-left: 14px;
    border-left: 1px solid #eeeeee; }

.floating-label-form-group-with-value label {
  top: 0;
  opacity: 1; }

.floating-label-form-group-with-focus label {
  color: #18BC9C; }

form .row:first-child .floating-label-form-group {
  border-top: 1px solid #eeeeee; }

footer {
  color: white; }
  footer h3 {
    margin-bottom: 30px; }
  footer .footer-above {
    padding-top: 50px;
    background-color: #2C3E50; }
  footer .footer-col {
    margin-bottom: 50px; }
  footer .footer-below {
    padding: 25px 0;
    background-color: #2c3e50; }

.btn-outline {
  font-size: 20px;
  margin-top: 15px;
  transition: all 0.3s ease-in-out;
  color: white;
  border: solid 2px white;
  background: transparent; }
  .btn-outline.active, .btn-outline:active, .btn-outline:focus, .btn-outline:hover {
    color: #18BC9C;
    border: solid 2px white;
    background: white; }

.btn-social.btn-outline{
	margin-top: 0px;
}

.btn-primary {
  font-weight: 700;
  color: white;
  border-color: #2C3E50;
  background-color: #2C3E50; }
  .btn-primary.focus, .btn-primary:focus {
    color: white;
    border-color: black;
    background-color: #1a252f; }
  .btn-primary:hover {
    color: white;
    border-color: #161f29;
    background-color: #1a252f; }
  .btn-primary.active, .btn-primary:active,
  .open > .btn-primary.dropdown-toggle {
    color: white;
    border-color: #161f29;
    background-color: #1a252f; }
    .btn-primary.active.focus, .btn-primary.active:focus, .btn-primary.active:hover, .btn-primary:active.focus, .btn-primary:active:focus, .btn-primary:active:hover,
    .open > .btn-primary.dropdown-toggle.focus,
    .open > .btn-primary.dropdown-toggle:focus,
    .open > .btn-primary.dropdown-toggle:hover {
      color: white;
      border-color: black;
      background-color: #0d1318; }
  .btn-primary.active, .btn-primary:active,
  .open > .btn-primary.dropdown-toggle {
    background-image: none; }
  .btn-primary.disabled.focus, .btn-primary.disabled:focus, .btn-primary.disabled:hover, .btn-primary[disabled].focus, .btn-primary[disabled]:focus, .btn-primary[disabled]:hover,
  fieldset[disabled] .btn-primary.focus,
  fieldset[disabled] .btn-primary:focus,
  fieldset[disabled] .btn-primary:hover {
    border-color: #2C3E50;
    background-color: #2C3E50; }
  .btn-primary .badge {
    color: #2C3E50;
    background-color: white; }

.btn-success {
  font-weight: 700;
  color: white;
  border-color: #18BC9C;
  background-color: #18BC9C; }
  .btn-success.focus, .btn-success:focus {
    color: white;
    border-color: #0a4b3e;
    background-color: #128f76; }
  .btn-success:hover {
    color: white;
    border-color: #11866f;
    background-color: #128f76; }
  .btn-success.active, .btn-success:active,
  .open > .btn-success.dropdown-toggle {
    color: white;
    border-color: #11866f;
    background-color: #128f76; }
    .btn-success.active.focus, .btn-success.active:focus, .btn-success.active:hover, .btn-success:active.focus, .btn-success:active:focus, .btn-success:active:hover,
    .open > .btn-success.dropdown-toggle.focus,
    .open > .btn-success.dropdown-toggle:focus,
    .open > .btn-success.dropdown-toggle:hover {
      color: white;
      border-color: #0a4b3e;
      background-color: #0e6f5c; }
  .btn-success.active, .btn-success:active,
  .open > .btn-success.dropdown-toggle {
    background-image: none; }
  .btn-success.disabled.focus, .btn-success.disabled:focus, .btn-success.disabled:hover, .btn-success[disabled].focus, .btn-success[disabled]:focus, .btn-success[disabled]:hover,
  fieldset[disabled] .btn-success.focus,
  fieldset[disabled] .btn-success:focus,
  fieldset[disabled] .btn-success:hover {
    border-color: #18BC9C;
    background-color: #18BC9C; }
  .btn-success .badge {
    color: #18BC9C;
    background-color: white; }

.btn-social {
  font-size: 20px;
  line-height: 45px;
  display: inline-block;
  width: 50px;
  height: 50px;
  text-align: center;
  border: 2px solid white;
  border-radius: 100%; }

a.btn-social i {
   margin-top: 12px;
   /*vertical-align: middle; */
   /* display: inline-block; */
}

.btn.active,
.btn:active,
.btn:focus {
  outline: none; }


text:
package yoyorony.me.funcraftv2alerts;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import java.util.Calendar;

public class BootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (FunApp.preferences.getBoolean("activnotif", true)) {
            Notifs.setAlarm(context);
        }
        AutoMAJ.setAlarm(context);
    }
}


text:
<?php

namespace EMR\Bundle\CalendarBundle\Validator;

use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Validator\Constraint;

/**
 * @author Nick Fenzan <nickf@millervein.com>
 */
class CategoryColumnValidator extends ConstraintValidator {

    private $em;

    public function __construct(EntityManager $em) {
        $this->em = $em;
    }

    public function validate($object, Constraint $constraint) {
        /* @var $object \EMR\Bundle\CalendarBundle\Entity\Appointment\Appointment */
        $category = $object->getCategory();
        $column = $object->getColumn();
        $columnTagIds = array();
        foreach($column->getTags() as $tag){
            $columnTagIds[] = $tag->getId();
        }
        $categoryTagIds = array();
        foreach($category->getRequiredColumnTags() as $tag){
            $categoryTagIds[] = $tag->getId();
        }

        $intersect = array_intersect($categoryTagIds, $columnTagIds);
        if(empty($intersect)){
            $this->context->addViolation('This category is not valid for this category.');
        }
    }

}


text:
/**
 * Created by Josh on 12/7/2016.
 */

$(document).ready(function() {

    $.ajax({
        url: 'api/dictionaryEndpoints.php',
        type: 'GET',
        dataType: 'json',
        success: function (result) {
            var options = $("#deletedSelect");

            var i=0;
            if (result.length > 0) {
                $.each(result, function(i){
                    options.append($("<option />").val(result[i].class_id).text(result[i].class_name));
                    i++;
                });
            } else {
                options.append($("<option />").val(null).text("No Words"));
            }
        }
    })

    $("#deletedSelect").on('change', function () {
        var deletedSelect = $("#deletedSelect").val();
        $.ajax({
            url: 'api/manageEndpoints.php',
            type: 'GET',
            data: 'deletedSelect='+deletedSelect,
            success: function(result) {
                $('#manageWordsTable').bootstrapTable("load", result);
            }
        })
    })
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.cosmos.implementation;

/**
 * Represents a resource path's information in the Azure Cosmos DB database service.
 */
public final class PathInfo {
    public boolean isFeed;
    public String resourcePath;
    public String resourceIdOrFullName;
    public boolean isNameBased;

    public PathInfo(boolean isFeed, String resourcePath, String resourceIdOrFullName, boolean isNameBased) {
        this.isFeed = isFeed;
        this.resourcePath = resourcePath;
        this.resourceIdOrFullName = resourceIdOrFullName;
        this.isNameBased = isNameBased;
    }
}


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit - Output data to Treasure Data
 *  =========================================
 *  Copyright (C) 2015 Treasure Data Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#include <unistd.h>
#include <fluent-bit.h>

int main(int argc, char **argv)
{
    int i;
    int n;
    int ret;
    char tmp[256];
    struct flb_config *config;

    if (argc < 2) {
        fprintf(stderr, "Usage: td /path/to/configuration.file\n");
        exit(EXIT_FAILURE);
    }

    /* Create configuration context */
    config = flb_config_init();
    if (!config) {
        exit(EXIT_FAILURE);
    }

    /* Enable verbose messages */
    flb_config_verbose(FLB_TRUE);

    /* Load a configuration file (required by TD output plugin) */
    ret = flb_lib_config_file(config, argv[1]);

    /* Initialize library */
    ret = flb_lib_init(config, (char *) "td");
    if (ret != 0) {
        exit(EXIT_FAILURE);
    }

    /* Start the background worker */
    flb_lib_start(config);

    /* Push some data */
    for (i = 0; i < 100; i++) {
        n = snprintf(tmp, sizeof(tmp) - 1, "{\"key\": \"val %i\"}", i);
        flb_lib_push(config, tmp, n);
    }

    flb_lib_stop(config);

    return 0;
}


text:
"""A utility class for interacting with a local checkout of the Web Platform Tests."""

import logging

from blinkpy.common.path_finder import RELATIVE_WPT_TESTS
from blinkpy.common.system.executive import ScriptError
from blinkpy.w3c.common import (
    DEFAULT_WPT_COMMITTER_EMAIL,
    DEFAULT_WPT_COMMITTER_NAME,
    WPT_GH_SSH_URL_TEMPLATE,
    WPT_MIRROR_URL,
)

_log = logging.getLogger(__name__)

class LocalWPT(object):
    def __init__(self, host, gh_token=None, path='/tmp/wpt'):
        """Initializes a LocalWPT instance.

        Args:
            host: A Host object.
            path: Optional, the path to the web-platform-tests repo.
                If this directory already exists, it is assumed that the
                web-platform-tests repo is already checked out at this path.
        """
        self.host = host
        self.path = path
        self.gh_token = gh_token

    def fetch(self):
        """Fetches a copy of the web-platform-tests repo in `self.path`."""
        if self.host.filesystem.exists(self.path):
            _log.info('WPT checkout exists at %s, fetching latest', self.path)
            self.run(['git', 'fetch', 'origin'])
            self.run(['git', 'reset', '--hard', 'origin/master'])
            return

        _log.info('Cloning GitHub web-platform-tests/wpt into %s', self.path)
        if self.gh_token:
            remote_url = WPT_GH_SSH_URL_TEMPLATE.format(self.gh_token)
        else:
            remote_url = WPT_MIRROR_URL
            _log.info('No credentials given, using wpt mirror URL.')
            _log.info(
                'It is possible for the mirror to be delayed; see https://crbug.com/698272.'
            )
        # Do not use self.run here because self.path doesn't exist yet.
        self.host.executive.run_command(
            ['git', 'clone', remote_url, self.path])

        _log.info('Setting git user name & email in %s', self.path)
        self.run(['git', 'config', 'user.name', DEFAULT_WPT_COMMITTER_NAME])
        self.run(['git', 'config', 'user.email', DEFAULT_WPT_COMMITTER_EMAIL])

    def run(self, command, **kwargs):
        """Runs a command in the local WPT directory."""
        # TODO(robertma): Migrate to blinkpy.common.checkout.Git. (crbug.com/676399)
        return self.host.executive.run_command(
            command, cwd=self.path, **kwargs)

    def clean(self):
        """Resets git to a clean state, on origin/master with no changed files."""
        self.run(['git', 'reset', '--hard', 'HEAD'])
        self.run(['git', 'clean', '-fdx'])
        self.run(['git', 'checkout', 'origin/master'])

    def create_branch_with_patch(self,
                                 branch_name,
                                 message,
                                 patch,
                                 author,
                                 force_push=False):
        """Commits the given patch and pushes to the upstream repo.

        Args:
            branch_name: The local and remote git branch name.
            message: Commit message string.
            patch: A patch that can be applied by git apply.
            author: The git commit author.
            force_push: Applies the -f flag in `git push`.
        """
        self.clean()

        try:
            # This won't be exercised in production because wpt-exporter
            # always runs on a clean machine. But it's useful when running
            # locally since branches stick around.
            _log.info('Deleting old branch %s', branch_name)
            self.run(['git', 'branch', '-D', branch_name])
        except ScriptError:
            # This might mean the branch wasn't found. Ignore this error.
            pass

        _log.info('Creating local branch %s', branch_name)
        self.run(['git', 'checkout', '-b', branch_name])

        # Remove Chromium WPT directory prefix.
        patch = patch.replace(RELATIVE_WPT_TESTS, '')

        _log.info('Author: %s', author)
        if '<' in author:
            author_str = author
        else:
            author_str = '%s <%s>' % (author, author)

        # TODO(jeffcarp): Use git am -p<n> where n is len(RELATIVE_WPT_TESTS.split(/'))
        # or something not off-by-one.
        self.run(['git', 'apply', '-'], input=patch)
        self.run(['git', 'add', '.'])
        self.run(['git', 'commit', '--author', author_str, '-am', message])

        # Force push is necessary when updating a PR with a new patch
        # from Gerrit.
        if force_push:
            self.run(['git', 'push', '-f', 'origin', branch_name])
        else:
            self.run(['git', 'push', 'origin', branch_name])

    def test_patch(self, patch):
        """Tests whether a patch can be cleanly applied against origin/master.

        Args:
            patch: The patch to test against.

        Returns:
            (success, error): success is True if and only if the patch can be
            cleanly applied and produce non-empty diff; error is a string of
            error messages when the patch fails to apply, empty otherwise.
        """
        self.clean()
        error = self.apply_patch(patch)
        diff = self.run(['git', 'diff', 'origin/master'])
        self.clean()
        if error != '':
            return False, error
        if diff == '':
            # No error message is returned for empty diff. The patch might be
            # empty or has been exported.
            return False, ''
        return True, ''

    def apply_patch(self, patch):
        """Applies a Chromium patch to the local WPT repo and stages.

        Returns:
            A string containing error messages from git, empty if the patch applies cleanly.
        """
        # Remove Chromium WPT directory prefix.
        patch = patch.replace(RELATIVE_WPT_TESTS, '')
        try:
            self.run(['git', 'apply', '-'], input=patch)
            self.run(['git', 'add', '.'])
        except ScriptError as error:
            return error.message
        return ''

    def commits_behind_master(self, commit):
        """Returns the number of commits after the given commit on origin/master.

        This doesn't include the given commit, and this assumes that the given
        commit is on the the master branch.
        """
        return len(
            self.run(['git', 'rev-list',
                      '{}..origin/master'.format(commit)]).splitlines())

    def _most_recent_log_matching(self, grep_str):
        """Finds the most recent commit whose message contains the given pattern.

        Args:
            grep_str: A regular expression. (git uses basic regexp by default!)

        Returns:
            A string containing the commit log of the first matched commit
            (empty if not found).
        """
        return self.run(['git', 'log', '-1', '--grep', grep_str])

    def commits_in_range(self, revision_start, revision_end):
        """Finds all commits in the given range.

        Args:
            revision_start: The start of the revision range (exclusive).
            revision_end: The end of the revision range (inclusive).

        Return:
            A list of (SHA, commit subject) pairs ordered reverse-chronologically.
        """
        revision_range = revision_start + '..' + revision_end
        output = self.run(
            ['git', 'rev-list', '--pretty=oneline', revision_range])
        commits = []
        for line in output.splitlines():
            # Split at the first space.
            commits.append(tuple(line.strip().split(' ', 1)))
        return commits

    def is_commit_affecting_directory(self, commit, directory):
        """Checks if a commit affects a directory."""
        exit_code = self.run([
            'git', 'diff-tree', '--quiet', '--no-commit-id', '-r', commit,
            '--', directory
        ],
                             return_exit_code=True)
        return exit_code == 1

    # Note: the regexes in the two following methods use the start-of-line
    # anchor ^ to prevent matching quoted text in commit messages. The end-of-
    # line anchor $ is omitted to accommodate trailing whitespaces and non-
    # standard line endings caused by manual editing.

    def seek_change_id(self, change_id):
        """Finds the most recent commit with the given Chromium change ID.

        Returns:
            A string of the matched commit log, empty if not found.
        """
        return self._most_recent_log_matching('^Change-Id: %s' % change_id)

    def seek_commit_position(self, commit_position):
        """Finds the most recent commit with the given Chromium commit position.

        Returns:
            A string of the matched commit log, empty if not found.
        """
        return self._most_recent_log_matching(
            '^Cr-Commit-Position: %s' % commit_position)


text:
/**
 * Line Component
 * @author ryan.bian
 */
import React from 'react';
import classnames from 'classnames';
import { defaultProps, propTypes } from './propDefine';
import Icon from '../icon';
import styles from './Progress.css';

const Line = ({ percent, status, size, showInfo }) => {
  const lineProps = {
    className: classnames(
      styles[`progress__${showInfo ? 'showinfo' : 'line'}`],
      styles[`progress__line--${size}Size`],
      styles[`progress__line--${status}`],
    ),
  };
  const innerProps = {
    className: styles['progress__lineInner'],
    style: {
      width: `${percent}%`,
    },
  };
  let indicator;
  if (showInfo) {
    switch (status) {
      case 'success':
        indicator = <Icon name="success" size={14} />;
        break;
      case 'exception':
        indicator = <Icon name="error" size={14} />;
        break;
      case 'pause':
        indicator = <Icon name="clock" size={14} />;
        break;
      default:
        indicator = `${percent}%`;
        break;
    }
  }
  return (

      {
        showInfo ?

            {indicator}

          : null
      }

  );
};

Line.defaultProps = defaultProps;

Line.propTypes = propTypes;

export default Line;