code
stringlengths
1
2.06M
language
stringclasses
1 value
#include "PhotoSwitch.h" #define defaultSteeringGain 0.3 #define defaultLeftSpeed -0.5 #define defaultRightSpeed -0.5 #define lineStyle 0 //1 for Dark, 0 for Light PhotoSwitch::PhotoSwitch(Drive *y) { p1 = new DigitalInput(1);//dark 1 p2 = new DigitalInput(2);//dark 2 p3 = new DigitalInput(3);//dark 3 p4 = new DigitalInput(4);//light 1 p5 = new DigitalInput(5);//light 2 p6 = new DigitalInput(6);//light 3 sensor = new Sensor(y); binary = 0; steeringGain = 0; leftSpeed = 0; rightSpeed = 0; //s1 = p1->Get(); //s2 = p2->Get(); //s3 = p3->Get(); //printf("Left Dark: %f\n" , p1->Get()); //printf("Center Dark: %f\n" , p2->Get()); //printf("Right Dark: %f\n" , p3->Get()); //printf("Left Light: %f\n" , p4->Get()); //printf("Center Light: %f\n" , p5->Get()); //printf("Right Light: %f\n" , p6->Get()); } float PhotoSwitch::drive(int x)//parameter of fork selection: 0 for left, 1 for right { if(lineStyle == 1){ binary = ((onDark()) + (onDark3()*3) + (dRight()*2) + (onDark1() *2) + (dLeft()*3) + ((allDark()*4) )); if (binary == 4){ binary += x; }//end of embedded if }else if (lineStyle == 0){ binary = onLight() + (lRight()*2) + (lLeft()*3) + ((allLight()*4) + x); }else{ binary = 0; }//end of else switch(binary){ case 1: //on line printf("Case 1\n"); leftSpeed = defaultLeftSpeed; rightSpeed = defaultRightSpeed; //printf("leftSpeed: %f\n", leftSpeed); //printf("rightSpeed: %f\n", rightSpeed); //drive straight break; case 2: //error to the left printf("Case 2\n"); leftSpeed = 0.0; rightSpeed = -0.7;//correct to the right //printf("Right Speed: %i \n", rightSpeed); break; case 3: //error to the right printf("Case 3\n"); leftSpeed = -0.7; rightSpeed = 0.0;//correct to the left //printf("Left Speed: %i \n", leftSpeed); break; case 4: //ALL Dark; fork to the left printf("Case 4\n"); leftSpeed = 0.0; rightSpeed = 0.0; //sensor->gyroSubroutine(0); break; case 5: //ALL Dark; fork to the right printf("Case 5\n"); leftSpeed = 0.0; rightSpeed = 0.0; //sensor->gyroSubroutine(1); break; case 6: case 0: printf("Case 0\n"); //no sensors - do nothing leftSpeed = -0.2; rightSpeed = -0.2; break; default: //what is wrong?? printf("Default\n"); leftSpeed = 0; rightSpeed = 0; //do nothing break; }//end of binary switch return steeringGain; }//end of drive float PhotoSwitch::getLeftSpeed() { return leftSpeed; } float PhotoSwitch::getRightSpeed() { return rightSpeed; } int PhotoSwitch::onDark()//following Dark line accurately { if((p2->Get()== 0) && (p1->Get() == 1) && (p3->Get() == 1)) { return 1; } else { return 0; } }//end of onDark int PhotoSwitch::onDark1()//follow Dark line { if((p1->Get() == 0) && (p2->Get() == 1) && (p3->Get() == 1)) { return 1; } else { return 0; } } int PhotoSwitch::onDark3()//follow Dark line { if((p1->Get() == 1) && (p2->Get() == 1) && (p3->Get() == 0)) { return 1; } else { return 0; } } int PhotoSwitch::dLeft()//error to the left { if((p2->Get()== 0) && (p1->Get() == 1) && (p3->Get() == 0)) { return 1; } else { return 0; } }//end of dLeft int PhotoSwitch::dRight()//error to the right { if((p2->Get()== 0) && (p1->Get() == 0) && (p3->Get() == 1)) { return 1; } else { return 0; } }//end of dRgiht int PhotoSwitch::onLight()//following Light line accurately { if((p5->Get()== 0) && (p4->Get() == 1) && (p6->Get() == 1)) { return 1; } else { return 0; } }//end of onLight int PhotoSwitch::lLeft()//error to the left { if((p5->Get()== 0) && (p4->Get() == 1) && (p6->Get() == 0)) { return 1; } else { return 0; } }//end of lLeft int PhotoSwitch::lRight()//error to the right { if((p5->Get()== 0) && (p4->Get() == 0) && (p6->Get() == 1)) { return 1; } else { return 0; } }//end of lRight int PhotoSwitch::allDark()//Dark fork { if((p2->Get()== 0) && (p1->Get() == 0) && (p3->Get() == 0)) { return 1; } else { return 0; } }//end of allDark int PhotoSwitch::allLight()//Light fork { if((p5->Get()== 0) && (p4->Get() == 0) && (p6->Get() == 0)) { return 1; } else { return 0; } }//end of allLight PhotoSwitch::~PhotoSwitch() { printf("*****Photoswitch Deconstructor Called*****"); delete sensor; sensor = NULL; }//end of deconstructor
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <npruntime.h> #include <npapi.h> #include "npactivex.h" class NPVariantProxy : public NPVariant { public: NPVariantProxy() { VOID_TO_NPVARIANT(*this); } ~NPVariantProxy() { NPNFuncs.releasevariantvalue(this); } }; class NPObjectProxy { private: NPObject *object; public: NPObjectProxy() { object = NULL; } NPObjectProxy(NPObject *obj) { object = obj; } void reset() { if (object) NPNFuncs.releaseobject(object); object = NULL; } ~NPObjectProxy() { reset(); } operator NPObject*&() { return object; } NPObjectProxy& operator =(NPObject* obj) { reset(); object = obj; return *this; } };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <comdef.h> #include "npactivex.h" #include "scriptable.h" #include "common/PropertyList.h" #include "common/PropertyBag.h" #include "common/ItemContainer.h" #include "common/ControlSite.h" #include "common/ControlSiteIPFrame.h" #include "common/ControlEventSink.h" #include "axhost.h" #include "HTMLDocumentContainer.h" #ifdef NO_REGISTRY_AUTHORIZE static const char *WellKnownProgIds[] = { NULL }; static const char *WellKnownClsIds[] = { NULL }; #endif static const bool AcceptOnlyWellKnown = false; static const bool TrustWellKnown = true; static bool isWellKnownProgId(const char *progid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!progid) { return false; } while (WellKnownProgIds[i]) { if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i]))) return true; ++i; } return false; #else return true; #endif } static bool isWellKnownClsId(const char *clsid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!clsid) { return false; } while (WellKnownClsIds[i]) { if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i]))) return true; ++i; } return false; #else return true; #endif } static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { LRESULT result; CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA); if (!host) { return DefWindowProc(hWnd, msg, wParam, lParam); } switch (msg) { case WM_SETFOCUS: case WM_KILLFOCUS: case WM_SIZE: if (host->Site) { host->Site->OnDefWindowMessage(msg, wParam, lParam, &result); return result; } else { return DefWindowProc(hWnd, msg, wParam, lParam); } // Window being destroyed case WM_DESTROY: break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return true; } CAxHost::CAxHost(NPP inst): CHost(inst), ClsID(CLSID_NULL), isValidClsID(false), Sink(NULL), Site(NULL), Window(NULL), OldProc(NULL), Props_(new PropertyList), isKnown(false), CodeBaseUrl(NULL), noWindow(false) { } CAxHost::~CAxHost() { np_log(instance, 0, "AxHost.~AXHost: destroying the control..."); if (Window){ if (OldProc) { ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); OldProc = NULL; } ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } Clear(); delete Props_; } void CAxHost::Clear() { if (Sink) { Sink->UnsubscribeFromEvents(); Sink->Release(); Sink = NULL; } if (Site) { Site->Detach(); Site->Release(); Site = NULL; } if (Props_) { Props_->Clear(); } CoFreeUnusedLibraries(); } CLSID CAxHost::ParseCLSIDFromSetting(LPCSTR str, int length) { CLSID ret; CStringW input(str, length); if (SUCCEEDED(CLSIDFromString(input, &ret))) return ret; int pos = input.Find(':'); if (pos != -1) { CStringW wolestr(_T("{")); wolestr.Append(input.Mid(pos + 1)); wolestr.Append(_T("}")); if (SUCCEEDED(CLSIDFromString(wolestr.GetString(), &ret))) return ret; } return CLSID_NULL; } void CAxHost::setWindow(HWND win) { if (win != Window) { if (win) { // subclass window so we can intercept window messages and // do our drawing to it OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc); // associate window with our CAxHost object so we can access // it in the window procedure ::SetWindowLong(win, GWL_USERDATA, (LONG)this); } else { if (OldProc) ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } Window = win; } } void CAxHost::ResetWindow() { UpdateRect(lastRect); } HWND CAxHost::getWinfow() { return Window; } void CAxHost::UpdateRect(RECT rcPos) { HRESULT hr = -1; lastRect = rcPos; if (Site && Window && !noWindow) { if (Site->GetParentWindow() == NULL) { hr = Site->Attach(Window, rcPos, NULL); if (FAILED(hr)) { np_log(instance, 0, "AxHost.UpdateRect: failed to attach control"); SIZEL zero = {0, 0}; SetRectSize(&zero); } } if (Site->CheckAndResetNeedUpdateContainerSize()) { UpdateRectSize(&rcPos); } else { Site->SetPosition(rcPos); } // Ensure clipping on parent to keep child controls happy ::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN); } } void CAxHost::setNoWindow(bool noWindow) { this->noWindow = noWindow; } void CAxHost::UpdateRectSize(LPRECT origRect) { if (noWindow) { return; } SIZEL szControl; if (!Site->IsVisibleAtRuntime()) { szControl.cx = 0; szControl.cy = 0; } else { if (FAILED(Site->GetControlSize(&szControl))) { return; } } SIZEL szIn; szIn.cx = origRect->right - origRect->left; szIn.cy = origRect->bottom - origRect->top; if (szControl.cx != szIn.cx || szControl.cy != szIn.cy) { SetRectSize(&szControl); } } void CAxHost::SetRectSize(LPSIZEL size) { np_log(instance, 1, "Set object size: x = %d, y = %d", size->cx, size->cy); NPObjectProxy object; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &object); static NPIdentifier style = NPNFuncs.getstringidentifier("style"); static NPIdentifier height = NPNFuncs.getstringidentifier("height"); static NPIdentifier width = NPNFuncs.getstringidentifier("width"); NPVariant sHeight, sWidth; CStringA strHeight, strWidth; strHeight.Format("%dpx", size->cy); strWidth.Format("%dpx", size->cx); STRINGZ_TO_NPVARIANT(strHeight, sHeight); STRINGZ_TO_NPVARIANT(strWidth, sWidth); NPVariantProxy styleValue; NPNFuncs.getproperty(instance, object, style, &styleValue); NPObject *styleObject = NPVARIANT_TO_OBJECT(styleValue); NPNFuncs.setproperty(instance, styleObject, height, &sHeight); NPNFuncs.setproperty(instance, styleObject, width, &sWidth); } void CAxHost::SetNPWindow(NPWindow *window) { RECT rcPos; setWindow((HWND)window->window); rcPos.left = 0; rcPos.top = 0; rcPos.right = window->width; rcPos.bottom = window->height; UpdateRect(rcPos); } bool CAxHost::verifyClsID(LPOLESTR oleClsID) { CRegKey keyExplorer; if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"), KEY_READ)) { CRegKey keyCLSID; if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) { DWORD dwType = REG_DWORD; DWORD dwFlags = 0; DWORD dwBufSize = sizeof(dwFlags); if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID, _T("Compatibility Flags"), NULL, &dwType, (LPBYTE) &dwFlags, &dwBufSize)) { // Flags for this reg key const DWORD kKillBit = 0x00000400; if (dwFlags & kKillBit) { np_log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits"); return false; } } } } return true; } bool CAxHost::setClsID(const char *clsid) { HRESULT hr = -1; USES_CONVERSION; LPOLESTR oleClsID = A2OLE(clsid); if (isWellKnownClsId(clsid)) { isKnown = true; } else if (AcceptOnlyWellKnown) { np_log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list"); return false; } // Check the Internet Explorer list of vulnerable controls if (oleClsID && verifyClsID(oleClsID)) { CLSID vclsid; hr = CLSIDFromString(oleClsID, &vclsid); if (SUCCEEDED(hr)) { return setClsID(vclsid); } } np_log(instance, 0, "AxHost.setClsID: failed to set the requested clsid"); return false; } bool CAxHost::setClsID(const CLSID& clsid) { if (clsid != CLSID_NULL) { this->ClsID = clsid; isValidClsID = true; //np_log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid); return true; } return false; } void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl) { CodeBaseUrl = codeBaseUrl; } bool CAxHost::setClsIDFromProgID(const char *progid) { HRESULT hr = -1; CLSID clsid = CLSID_NULL; USES_CONVERSION; LPOLESTR oleClsID = NULL; LPOLESTR oleProgID = A2OLE(progid); if (AcceptOnlyWellKnown) { if (isWellKnownProgId(progid)) { isKnown = true; } else { np_log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list"); return false; } } hr = CLSIDFromProgID(oleProgID, &clsid); if (FAILED(hr)) { np_log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID"); return false; } hr = StringFromCLSID(clsid, &oleClsID); // Check the Internet Explorer list of vulnerable controls if ( SUCCEEDED(hr) && oleClsID && verifyClsID(oleClsID)) { ClsID = clsid; if (!::IsEqualCLSID(ClsID, CLSID_NULL)) { isValidClsID = true; np_log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid); return true; } } np_log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID"); return false; } bool CAxHost::hasValidClsID() { return isValidClsID; } static void HTMLContainerDeleter(IUnknown *unk) { CComAggObject<HTMLDocumentContainer>* val = (CComAggObject<HTMLDocumentContainer>*)(unk); val->InternalRelease(); } bool CAxHost::CreateControl(bool subscribeToEvents) { if (!isValidClsID) { np_log(instance, 0, "AxHost.CreateControl: current location is not trusted"); return false; } // Create the control site CComObject<CControlSite>::CreateInstance(&Site); if (Site == NULL) { np_log(instance, 0, "AxHost.CreateControl: CreateInstance failed"); return false; } Site->AddRef(); Site->m_bSupportWindowlessActivation = false; if (TrustWellKnown && isKnown) { Site->SetSecurityPolicy(NULL); Site->m_bSafeForScriptingObjectsOnly = false; } else { Site->m_bSafeForScriptingObjectsOnly = true; } CComAggObject<HTMLDocumentContainer> *document; CComAggObject<HTMLDocumentContainer>::CreateInstance(Site->GetUnknown(), &document); document->m_contained.Init(instance, pHtmlLib); Site->SetInnerWindow(document, HTMLContainerDeleter); BSTR url; document->m_contained.get_LocationURL(&url); Site->SetUrl(url); SysFreeString(url); // Create the object HRESULT hr; hr = Site->Create(ClsID, *Props(), CodeBaseUrl); if (FAILED(hr)) { np_log(instance, 0, "AxHost.CreateControl: failed to create site for 0x%08x", hr); return false; } #if 0 IUnknown *control = NULL; Site->GetControlUnknown(&control); if (!control) { np_log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)"); return false; } // Create the event sink CComObject<CControlEventSink>::CreateInstance(&Sink); Sink->AddRef(); Sink->instance = instance; hr = Sink->SubscribeToEvents(control); control->Release(); if (FAILED(hr) && subscribeToEvents) { np_log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed"); // return false; // It doesn't matter. } #endif np_log(instance, 1, "AxHost.CreateControl: control created successfully"); return true; } bool CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler) { HRESULT hr; DISPID id = 0; USES_CONVERSION; LPOLESTR oleName = name; if (!Sink) { np_log(instance, 0, "AxHost.AddEventHandler: no valid sink"); return false; } hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id); if (FAILED(hr)) { np_log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name"); return false; } Sink->events[id] = handler; np_log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name); return true; } int16 CAxHost::HandleEvent(void *event) { NPEvent *npEvent = (NPEvent *)event; LRESULT result = 0; if (!npEvent) { return 0; } // forward all events to the hosted control return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result); } ScriptBase * CAxHost::CreateScriptableObject() { Scriptable *obj = Scriptable::FromAxHost(instance, this); if (Site == NULL) { return obj; } static int markedSafe = 0; if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe == 0) { if (MessageBox(NULL, _T("Some objects are not script-safe, would you continue?"), _T("Warining"), MB_YESNO | MB_ICONINFORMATION | MB_ICONASTERISK) == IDYES) markedSafe = 1; else markedSafe = 2; } if (!Site->m_bSafeForScriptingObjectsOnly && markedSafe != 1) { // Disable scripting. obj->Invalidate(); } return obj; } HRESULT CAxHost::GetControlUnknown(IUnknown **pObj) { if (Site == NULL) { return E_FAIL; } return Site->GetControlUnknown(pObj); } NPP CAxHost::ResetNPP(NPP npp) { NPP ret = CHost::ResetNPP(npp); setWindow(NULL); Site->Detach(); if (Sink) Sink->instance = npp; return ret; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // npactivex.cpp : Defines the exported functions for the DLL application. // #include "npactivex.h" #include "axhost.h" #include "atlutil.h" #include "objectProxy.h" #include "authorize.h" #include "common\PropertyList.h" #include "common\ControlSite.h" #include "ObjectManager.h" // A list of trusted domains // Each domain name may start with a '*' to specify that sub domains are // trusted as well // Note that a '.' is not enforced after the '*' static const char *TrustedLocations[] = {NULL}; static const unsigned int numTrustedLocations = 0; static const char *LocalhostName = "localhost"; static const bool TrustLocalhost = true; // // Gecko API // static const char PARAM_ID[] = "id"; static const char PARAM_NAME[] = "name"; static const char PARAM_CLSID[] = "clsid"; static const char PARAM_CLASSID[] = "classid"; static const char PARAM_PROGID[] = "progid"; static const char PARAM_DYNAMIC[] = "dynamic"; static const char PARAM_DEBUG[] = "debugLevel"; static const char PARAM_CODEBASEURL [] = "codeBase"; static const char PARAM_ONEVENT[] = "Event_"; static unsigned int log_level = -1; // For catch breakpoints. HRESULT NotImpl() { return E_NOTIMPL; } void log_activex_logging(NPP instance, unsigned int level, const char* filename, int line, char *message, ...) { if (instance == NULL || level > log_level) { return; } NPObjectProxy globalObj = NULL; NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log"); NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (!NPNFuncs.hasmethod(instance, globalObj, commandId)) { return; } int size = 0; va_list list; ATL::CStringA str; ATL::CStringA str2; va_start(list, message); str.FormatV(message, list); str2.Format("0x%08x %s:%d %s", instance, filename, line, str.GetString()); va_end(list); NPVariant vars[1]; const char* formatted = str2.GetString(); STRINGZ_TO_NPVARIANT(formatted, vars[0]); NPVariantProxy result1; NPNFuncs.invoke(instance, globalObj, commandId, vars, 1, &result1); } void InstallLogAction(NPP instance) { NPVariantProxy result1; NPObjectProxy globalObj = NULL; NPIdentifier commandId = NPNFuncs.getstringidentifier("__npactivex_log"); NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (NPNFuncs.hasmethod(instance, globalObj, commandId)) { return; } const char* definition = "function __npactivex_log(message)" "{var controlLogEvent='__npactivex_log_event__';" "var e=document.createEvent('TextEvent');e.initTextEvent(controlLogEvent,false,false,null,message);window.dispatchEvent(e)}"; NPString def; def.UTF8Characters = definition; def.UTF8Length = strlen(definition); NPNFuncs.evaluate(instance, globalObj, &def, &result1); } void log_internal_console(NPP instance, unsigned int level, char *message, ...) { NPVariantProxy result1, result2; NPVariant args; NPObjectProxy globalObj = NULL, consoleObj = NULL; bool rc = false; char *formatted = NULL; char *new_formatted = NULL; int buff_len = 0; int size = 0; va_list list; if (level > log_level) { return; } buff_len = strlen(message); char *new_message = (char *)malloc(buff_len + 10); sprintf(new_message, "%%s %%d: %s", message); buff_len += buff_len / 10; formatted = (char *)calloc(1, buff_len); while (true) { va_start(list, message); size = vsnprintf_s(formatted, buff_len, _TRUNCATE, new_message, list); va_end(list); if (size > -1 && size < buff_len) break; buff_len *= 2; new_formatted = (char *)realloc(formatted, buff_len); if (NULL == new_formatted) { free(formatted); return; } formatted = new_formatted; new_formatted = NULL; } free(new_message); if (instance == NULL) { free(formatted); return; } NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); if (NPNFuncs.getproperty(instance, globalObj, NPNFuncs.getstringidentifier("console"), &result1)) { consoleObj = NPVARIANT_TO_OBJECT(result1); NPIdentifier handler = NPNFuncs.getstringidentifier("log"); STRINGZ_TO_NPVARIANT(formatted, args); bool success = NPNFuncs.invoke(instance, consoleObj, handler, &args, 1, &result2); } free(formatted); } static bool MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl) { USES_CONVERSION; BOOL rc = false; CUrl url; if (!numTrustedLocations) { return true; } rc = url.CrackUrl(matchUrl, ATL_URL_DECODE); if (!rc) { np_log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL"); return false; } if ( (url.GetScheme() == ATL_URL_SCHEME_FILE) || (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){ return TrustLocalhost; } for (unsigned int i = 0; i < numTrustedLocations; ++i) { if (TrustedLocations[i][0] == '*') { // sub domains are trusted unsigned int len = strlen(TrustedLocations[i]); bool match = 0; if (url.GetHostNameLength() < len) { // can't be a match continue; } --len; // skip the '*' match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name TrustedLocations[i] + 1, // skip the '*' len) == 0 ? true : false; if (match) { return true; } } else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) { return true; } } return false; } static bool VerifySiteLock(NPP instance) { // This approach is not used. return true; #if 0 USES_CONVERSION; NPObjectProxy globalObj; NPIdentifier identifier; NPVariantProxy varLocation; NPVariantProxy varHref; bool rc = false; // Get the window object. NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation); if (!rc){ np_log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref); if (!rc) { np_log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property"); return false; } rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters)); if (false == rc) { np_log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted"); } return rc; #endif } static bool FillProperties(CAxHost *host, NPP instance) { NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); // Traverse through childs NPVariantProxy var_childNodes; NPVariantProxy var_length; NPVariant str_name, str_value; if (!NPNFuncs.getproperty(instance, embed, NPNFuncs.getstringidentifier("childNodes"), &var_childNodes)) return true; if (!NPVARIANT_IS_OBJECT(var_childNodes)) return true; NPObject *childNodes = NPVARIANT_TO_OBJECT(var_childNodes); VOID_TO_NPVARIANT(var_length); if (!NPNFuncs.getproperty(instance, childNodes, NPNFuncs.getstringidentifier("length"), &var_length)) return true; USES_CONVERSION; int length = 0; if (NPVARIANT_IS_INT32(var_length)) length = NPVARIANT_TO_INT32(var_length); if (NPVARIANT_IS_DOUBLE(var_length)) length = static_cast<int>(NPVARIANT_TO_DOUBLE(var_length)); NPIdentifier idname = NPNFuncs.getstringidentifier("nodeName"); NPIdentifier idAttr = NPNFuncs.getstringidentifier("getAttribute"); STRINGZ_TO_NPVARIANT("name", str_name); STRINGZ_TO_NPVARIANT("value", str_value); for (int i = 0; i < length; ++i) { NPIdentifier id = NPNFuncs.getintidentifier(i); NPVariantProxy var_par; NPVariantProxy var_nodeName, var_parName, var_parValue; if (!NPNFuncs.getproperty(instance, childNodes, id, &var_par)) continue; if (!NPVARIANT_IS_OBJECT(var_par)) continue; NPObject *param_obj = NPVARIANT_TO_OBJECT(var_par); if (!NPNFuncs.getproperty(instance, param_obj, idname, &var_nodeName)) continue; if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "embed", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) == 0) { NPVariantProxy type; NPVariant typestr; STRINGZ_TO_NPVARIANT("type", typestr); if (!NPNFuncs.invoke(instance, param_obj, idAttr, &typestr, 1, &type)) continue; if (!NPVARIANT_IS_STRING(type)) continue; CStringA command, mimetype(NPVARIANT_TO_STRING(type).UTF8Characters, NPVARIANT_TO_STRING(type).UTF8Length); command.Format("navigator.mimeTypes[\'%s\'] != null", mimetype); NPString str = {command.GetString(), command.GetLength()}; NPVariantProxy value; NPObjectProxy window; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &window); NPNFuncs.evaluate(instance, window, &str, &value); if (NPVARIANT_IS_BOOLEAN(value) && NPVARIANT_TO_BOOLEAN(value)) { // The embed is supported by chrome. Fallback automatically. np_log(instance, 1, "This control has a valid embed element %s", mimetype.GetString()); return false; } } if (_strnicmp(NPVARIANT_TO_STRING(var_nodeName).UTF8Characters, "param", NPVARIANT_TO_STRING(var_nodeName).UTF8Length) != 0) continue; if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_name, 1, &var_parName)) continue; if (!NPNFuncs.invoke(instance, param_obj, idAttr, &str_value, 1, &var_parValue)) continue; if (!NPVARIANT_IS_STRING(var_parName) || !NPVARIANT_IS_STRING(var_parValue)) continue; CComBSTR paramName(NPVARIANT_TO_STRING(var_parName).UTF8Length, NPVARIANT_TO_STRING(var_parName).UTF8Characters); CComBSTR paramValue(NPVARIANT_TO_STRING(var_parValue).UTF8Length, NPVARIANT_TO_STRING(var_parValue).UTF8Characters); // Add named parameter to list CComVariant v(paramValue); host->Props()->AddOrReplaceNamedProperty(paramName, v); } return true; } NPError CreateControl(NPP instance, int16 argc, char *argn[], char *argv[], CAxHost **phost) { // Create a plugin instance, the actual control will be created once we // are given a window handle USES_CONVERSION; PropertyList events; CAxHost *host = new CAxHost(instance); *phost = host; if (!host) { np_log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host"); return NPERR_OUT_OF_MEMORY_ERROR; } // Iterate over the arguments we've been passed for (int i = 0; i < argc; ++i) { // search for any needed information: clsid, event handling directives, etc. if (strnicmp(argn[i], PARAM_CLASSID, sizeof(PARAM_CLASSID)) == 0) { char clsid[100]; strncpy(clsid, argv[i], 80); strcat(clsid, "}"); char* id = strchr(clsid, ':'); if (id == NULL) continue; *id = '{'; host->setClsID(id); } else if (0 == strnicmp(argn[i], PARAM_NAME, sizeof(PARAM_NAME)) || 0 == strnicmp(argn[i], PARAM_ID, sizeof(PARAM_ID))) { np_log(instance, 1, "instance %s: %s", argn[i], argv[i]); } else if (0 == strnicmp(argn[i], PARAM_CLSID, sizeof(PARAM_CLSID))) { // The class id of the control we are asked to load host->setClsID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_PROGID, sizeof(PARAM_PROGID))) { // The class id of the control we are asked to load host->setClsIDFromProgID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_DEBUG, sizeof(PARAM_DEBUG))) { // Logging verbosity log_level = atoi(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_ONEVENT, sizeof(PARAM_ONEVENT))) { // A request to handle one of the activex's events in JS events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i]))); } else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, sizeof(PARAM_CODEBASEURL))) { if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) { host->setCodeBaseUrl(A2W(argv[i])); } else { np_log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location"); } } else if (0 == strnicmp(argn[i], PARAM_DYNAMIC, sizeof(PARAM_DYNAMIC))) { host->setNoWindow(true); } } if (!FillProperties(host, instance)) { return NPERR_GENERIC_ERROR; } // Make sure we have all the information we need to initialize a new instance if (!host->hasValidClsID()) { np_log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID"); // create later. return NPERR_NO_ERROR; } instance->pdata = host; // if no events were requested, don't fail if subscribing fails if (!host->CreateControl(events.GetSize() ? true : false)) { np_log(instance, 0, "AxHost.NPP_New: failed to create the control"); return NPERR_GENERIC_ERROR; } for (unsigned int j = 0; j < events.GetSize(); j++) { if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) { //rc = NPERR_GENERIC_ERROR; //break; } } np_log(instance, 1, "%08x AxHost.NPP_New: Create control finished", instance); return NPERR_NO_ERROR; } /* * Create a new plugin instance, most probably through an embed/object HTML * element. * * Any private data we want to keep for this instance can be saved into * [instance->pdata]. * [saved] might hold information a previous instance that was invoked from the * same URL has saved for us. */ NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { NPError rc = NPERR_NO_ERROR; NPObject *browser = NULL; int16 i = 0; if (!instance || (0 == NPNFuncs.size)) { return NPERR_INVALID_PARAM; } instance->pdata = NULL; #ifdef NO_REGISTRY_AUTHORIZE // Verify that we're running from a trusted location if (!VerifySiteLock(instance)) { return NPERR_GENERIC_ERROR; } #else if (!TestAuthorization (instance, argc, argn, argv, pluginType)) { return NPERR_GENERIC_ERROR; } #endif InstallLogAction(instance); if (stricmp(pluginType, "application/x-itst-activex") == 0) { CAxHost *host = NULL; /* ObjectManager* manager = ObjectManager::GetManager(instance); if (manager && !(host = dynamic_cast<CAxHost*>(manager->GetPreviousObject(instance)))) { // Object is created before manager->RequestObjectOwnership(instance, host); } else */ { rc = CreateControl(instance, argc, argn, argv, &host); if (NPERR_NO_ERROR != rc) { delete host; instance->pdata = NULL; host = NULL; return rc; } } if (host) { host->RegisterObject(); instance->pdata = host; } } else if (stricmp(pluginType, "application/activex-manager") == 0) { // disabled now!! return rc = NPERR_GENERIC_ERROR; ObjectManager *manager = new ObjectManager(instance); manager->RegisterObject(); instance->pdata = manager; } return rc; } /* * Destroy an existing plugin instance. * * [save] can be used to save information for a future instance of our plugin * that'll be invoked by the same URL. */ NPError NPP_Destroy(NPP instance, NPSavedData **save) { if (!instance) { return NPERR_INVALID_PARAM; } CHost *host = (CHost *)instance->pdata; if (host) { np_log(instance, 0, "NPP_Destroy: destroying the control..."); //host->UnRegisterObject(); host->Release(); instance->pdata = NULL; /* ObjectManager *manager = ObjectManager::GetManager(instance); CAxHost *axHost = dynamic_cast<CAxHost*>(host); if (manager && axHost) { manager->RetainOwnership(axHost); } else { np_log(instance, 0, "NPP_Destroy: destroying the control..."); host->Release(); instance->pdata = NULL; }*/ } return NPERR_NO_ERROR; } /* * Sets an instance's window parameters. */ NPError NPP_SetWindow(NPP instance, NPWindow *window) { CAxHost *host = NULL; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } host = dynamic_cast<CAxHost*>((CHost *)instance->pdata); if (host) { host->SetNPWindow(window); } return NPERR_NO_ERROR; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "ObjectManager.h" #include "npactivex.h" #include "host.h" #include "axhost.h" #include "objectProxy.h" #include "scriptable.h" #define MANAGER_OBJECT_ID "__activex_manager_IIID_" NPClass ObjectManager::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ ObjectManager::_Allocate, /* deallocate */ ObjectManager::Deallocate, /* invalidate */ NULL, /* hasMethod */ ObjectManager::HasMethod, /* invoke */ ObjectManager::Invoke, /* invokeDefault */ NULL, /* hasProperty */ ObjectManager::HasProperty, /* getProperty */ ObjectManager::GetProperty, /* setProperty */ ObjectManager::SetProperty, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL }; ObjectManager::ObjectManager(NPP npp_) : CHost(npp_) { } ObjectManager::~ObjectManager(void) { for (uint i = 0; i < hosts.size(); ++i) { hosts[i]->Release(); } for (uint i = 0; i < dynamic_hosts.size(); ++i) { dynamic_hosts[i]->Release(); } } ObjectManager* ObjectManager::GetManager(NPP npp) { NPObjectProxy window; NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window); NPVariantProxy document, obj; NPVariant par; STRINGZ_TO_NPVARIANT(MANAGER_OBJECT_ID, par); if (!NPNFuncs.getproperty(npp, window, NPNFuncs.getstringidentifier("document"), &document)) return NULL; if (!NPNFuncs.invoke(npp, document.value.objectValue, NPNFuncs.getstringidentifier("getElementById"), &par, 1, &obj)) return NULL; if (NPVARIANT_IS_OBJECT(obj)) { NPObject *manager = NPVARIANT_TO_OBJECT(obj); CHost *host = GetInternalObject(npp, manager); if (host) return dynamic_cast<ObjectManager*>(host); } return NULL; } CHost* ObjectManager::GetPreviousObject(NPP npp) { NPObjectProxy embed; NPNFuncs.getvalue(npp, NPNVPluginElementNPObject, &embed); return GetMyScriptObject()->host; } bool ObjectManager::HasMethod(NPObject *npobj, NPIdentifier name) { return name == NPNFuncs.getstringidentifier("CreateControlByProgId"); } bool ObjectManager::Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { ScriptManager *obj = static_cast<ScriptManager*>(npobj); if (name == NPNFuncs.getstringidentifier("CreateControlByProgId")) { if (argCount != 1 || !NPVARIANT_IS_STRING(args[0])) { NPNFuncs.setexception(npobj, "Invalid arguments"); return false; } CAxHost* host = new CAxHost(obj->instance); CStringA str(NPVARIANT_TO_STRING(args[0]).UTF8Characters, NPVARIANT_TO_STRING(args[0]).UTF8Length); host->setClsIDFromProgID(str.GetString()); if (!host->CreateControl(false)) { NPNFuncs.setexception(npobj, "Error creating object"); return false; } ObjectManager *manager = static_cast<ObjectManager*>(obj->host); manager->dynamic_hosts.push_back(host); OBJECT_TO_NPVARIANT(host->CreateScriptableObject(), *result); return true; } return false; } bool ObjectManager::HasProperty(NPObject *npObj, NPIdentifier name) { if (name == NPNFuncs.getstringidentifier("internalId")) return true; if (name == NPNFuncs.getstringidentifier("isValid")) return true; return false; } bool ObjectManager::GetProperty(NPObject *npObj, NPIdentifier name, NPVariant *value) { if (name == NPNFuncs.getstringidentifier("internalId")) { int len = strlen(MANAGER_OBJECT_ID); char *stra = (char*)NPNFuncs.memalloc(len + 1); strcpy(stra, MANAGER_OBJECT_ID); STRINGN_TO_NPVARIANT(stra, len, *value); return true; } if (name == NPNFuncs.getstringidentifier("isValid")) { BOOLEAN_TO_NPVARIANT(TRUE, *value); return true; } return false; } bool ObjectManager::SetProperty(NPObject *npObj, NPIdentifier name, const NPVariant *value) { return false; } bool ObjectManager::RequestObjectOwnership(NPP newNpp, CAxHost* host) { // reference count of host not changed. for (uint i = 0; i < hosts.size(); ++i) { if (hosts[i] == host) { hosts[i] = hosts.back(); hosts.pop_back(); host->ResetNPP(newNpp); newNpp->pdata = host; return true; } } return false; } void ObjectManager::RetainOwnership(CAxHost* host) { hosts.push_back(host); host->ResetNPP(instance); } ScriptBase* ObjectManager::CreateScriptableObject() { ScriptBase* obj = static_cast<ScriptBase*>(NPNFuncs.createobject(instance, &npClass)); return obj; } void ObjectManager::Deallocate(NPObject *obj) { delete static_cast<ScriptManager*>(obj); }
C++
// stdafx.cpp : source file that includes just the standard includes // npactivex.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "npactivex.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
C++
#include "ScriptFunc.h" NPClass ScriptFunc::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ ScriptFunc::_Allocate, /* deallocate */ ScriptFunc::_Deallocate, /* invalidate */ NULL, /* hasMethod */ NULL, //Scriptable::_HasMethod, /* invoke */ NULL, //Scriptable::_Invoke, /* invokeDefault */ ScriptFunc::_InvokeDefault, /* hasProperty */ NULL, /* getProperty */ NULL, /* setProperty */ NULL, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL }; map<pair<Scriptable*, MEMBERID>, ScriptFunc*> ScriptFunc::M; ScriptFunc::ScriptFunc(NPP inst) { } ScriptFunc::~ScriptFunc(void) { if (script) { pair<Scriptable*, MEMBERID> index(script, dispid); NPNFuncs.releaseobject(script); M.erase(index); } } ScriptFunc* ScriptFunc::GetFunctionObject(NPP npp, Scriptable *script, MEMBERID dispid) { pair<Scriptable*, MEMBERID> index(script, dispid); if (M[index] == NULL) { ScriptFunc *new_obj = (ScriptFunc*)NPNFuncs.createobject(npp, &npClass); NPNFuncs.retainobject(script); new_obj->setControl(script, dispid); M[index] = new_obj; } else { NPNFuncs.retainobject(M[index]); } return M[index]; } bool ScriptFunc::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (!script) return false; bool ret = script->InvokeID(dispid, args, argCount, result); if (!ret) { np_log(script->instance, 0, "Invoke failed, DISPID 0x%08x", dispid); } return ret; }
C++
// Copyright qiuc12@gmail.com // This file is generated autmatically by python. DONT MODIFY IT! #pragma once #include <OleAuto.h> class FakeDispatcher; HRESULT DualProcessCommand(int commandId, FakeDispatcher *disp, ...); extern "C" void DualProcessCommandWrap(); class FakeDispatcherBase : public IDispatch { private: virtual HRESULT __stdcall fv0(); virtual HRESULT __stdcall fv1(); virtual HRESULT __stdcall fv2(); virtual HRESULT __stdcall fv3(); virtual HRESULT __stdcall fv4(); virtual HRESULT __stdcall fv5(); virtual HRESULT __stdcall fv6(); virtual HRESULT __stdcall fv7(); virtual HRESULT __stdcall fv8(); virtual HRESULT __stdcall fv9(); virtual HRESULT __stdcall fv10(); virtual HRESULT __stdcall fv11(); virtual HRESULT __stdcall fv12(); virtual HRESULT __stdcall fv13(); virtual HRESULT __stdcall fv14(); virtual HRESULT __stdcall fv15(); virtual HRESULT __stdcall fv16(); virtual HRESULT __stdcall fv17(); virtual HRESULT __stdcall fv18(); virtual HRESULT __stdcall fv19(); virtual HRESULT __stdcall fv20(); virtual HRESULT __stdcall fv21(); virtual HRESULT __stdcall fv22(); virtual HRESULT __stdcall fv23(); virtual HRESULT __stdcall fv24(); virtual HRESULT __stdcall fv25(); virtual HRESULT __stdcall fv26(); virtual HRESULT __stdcall fv27(); virtual HRESULT __stdcall fv28(); virtual HRESULT __stdcall fv29(); virtual HRESULT __stdcall fv30(); virtual HRESULT __stdcall fv31(); virtual HRESULT __stdcall fv32(); virtual HRESULT __stdcall fv33(); virtual HRESULT __stdcall fv34(); virtual HRESULT __stdcall fv35(); virtual HRESULT __stdcall fv36(); virtual HRESULT __stdcall fv37(); virtual HRESULT __stdcall fv38(); virtual HRESULT __stdcall fv39(); virtual HRESULT __stdcall fv40(); virtual HRESULT __stdcall fv41(); virtual HRESULT __stdcall fv42(); virtual HRESULT __stdcall fv43(); virtual HRESULT __stdcall fv44(); virtual HRESULT __stdcall fv45(); virtual HRESULT __stdcall fv46(); virtual HRESULT __stdcall fv47(); virtual HRESULT __stdcall fv48(); virtual HRESULT __stdcall fv49(); virtual HRESULT __stdcall fv50(); virtual HRESULT __stdcall fv51(); virtual HRESULT __stdcall fv52(); virtual HRESULT __stdcall fv53(); virtual HRESULT __stdcall fv54(); virtual HRESULT __stdcall fv55(); virtual HRESULT __stdcall fv56(); virtual HRESULT __stdcall fv57(); virtual HRESULT __stdcall fv58(); virtual HRESULT __stdcall fv59(); virtual HRESULT __stdcall fv60(); virtual HRESULT __stdcall fv61(); virtual HRESULT __stdcall fv62(); virtual HRESULT __stdcall fv63(); virtual HRESULT __stdcall fv64(); virtual HRESULT __stdcall fv65(); virtual HRESULT __stdcall fv66(); virtual HRESULT __stdcall fv67(); virtual HRESULT __stdcall fv68(); virtual HRESULT __stdcall fv69(); virtual HRESULT __stdcall fv70(); virtual HRESULT __stdcall fv71(); virtual HRESULT __stdcall fv72(); virtual HRESULT __stdcall fv73(); virtual HRESULT __stdcall fv74(); virtual HRESULT __stdcall fv75(); virtual HRESULT __stdcall fv76(); virtual HRESULT __stdcall fv77(); virtual HRESULT __stdcall fv78(); virtual HRESULT __stdcall fv79(); virtual HRESULT __stdcall fv80(); virtual HRESULT __stdcall fv81(); virtual HRESULT __stdcall fv82(); virtual HRESULT __stdcall fv83(); virtual HRESULT __stdcall fv84(); virtual HRESULT __stdcall fv85(); virtual HRESULT __stdcall fv86(); virtual HRESULT __stdcall fv87(); virtual HRESULT __stdcall fv88(); virtual HRESULT __stdcall fv89(); virtual HRESULT __stdcall fv90(); virtual HRESULT __stdcall fv91(); virtual HRESULT __stdcall fv92(); virtual HRESULT __stdcall fv93(); virtual HRESULT __stdcall fv94(); virtual HRESULT __stdcall fv95(); virtual HRESULT __stdcall fv96(); virtual HRESULT __stdcall fv97(); virtual HRESULT __stdcall fv98(); virtual HRESULT __stdcall fv99(); virtual HRESULT __stdcall fv100(); virtual HRESULT __stdcall fv101(); virtual HRESULT __stdcall fv102(); virtual HRESULT __stdcall fv103(); virtual HRESULT __stdcall fv104(); virtual HRESULT __stdcall fv105(); virtual HRESULT __stdcall fv106(); virtual HRESULT __stdcall fv107(); virtual HRESULT __stdcall fv108(); virtual HRESULT __stdcall fv109(); virtual HRESULT __stdcall fv110(); virtual HRESULT __stdcall fv111(); virtual HRESULT __stdcall fv112(); virtual HRESULT __stdcall fv113(); virtual HRESULT __stdcall fv114(); virtual HRESULT __stdcall fv115(); virtual HRESULT __stdcall fv116(); virtual HRESULT __stdcall fv117(); virtual HRESULT __stdcall fv118(); virtual HRESULT __stdcall fv119(); virtual HRESULT __stdcall fv120(); virtual HRESULT __stdcall fv121(); virtual HRESULT __stdcall fv122(); virtual HRESULT __stdcall fv123(); virtual HRESULT __stdcall fv124(); virtual HRESULT __stdcall fv125(); virtual HRESULT __stdcall fv126(); virtual HRESULT __stdcall fv127(); virtual HRESULT __stdcall fv128(); virtual HRESULT __stdcall fv129(); virtual HRESULT __stdcall fv130(); virtual HRESULT __stdcall fv131(); virtual HRESULT __stdcall fv132(); virtual HRESULT __stdcall fv133(); virtual HRESULT __stdcall fv134(); virtual HRESULT __stdcall fv135(); virtual HRESULT __stdcall fv136(); virtual HRESULT __stdcall fv137(); virtual HRESULT __stdcall fv138(); virtual HRESULT __stdcall fv139(); virtual HRESULT __stdcall fv140(); virtual HRESULT __stdcall fv141(); virtual HRESULT __stdcall fv142(); virtual HRESULT __stdcall fv143(); virtual HRESULT __stdcall fv144(); virtual HRESULT __stdcall fv145(); virtual HRESULT __stdcall fv146(); virtual HRESULT __stdcall fv147(); virtual HRESULT __stdcall fv148(); virtual HRESULT __stdcall fv149(); virtual HRESULT __stdcall fv150(); virtual HRESULT __stdcall fv151(); virtual HRESULT __stdcall fv152(); virtual HRESULT __stdcall fv153(); virtual HRESULT __stdcall fv154(); virtual HRESULT __stdcall fv155(); virtual HRESULT __stdcall fv156(); virtual HRESULT __stdcall fv157(); virtual HRESULT __stdcall fv158(); virtual HRESULT __stdcall fv159(); virtual HRESULT __stdcall fv160(); virtual HRESULT __stdcall fv161(); virtual HRESULT __stdcall fv162(); virtual HRESULT __stdcall fv163(); virtual HRESULT __stdcall fv164(); virtual HRESULT __stdcall fv165(); virtual HRESULT __stdcall fv166(); virtual HRESULT __stdcall fv167(); virtual HRESULT __stdcall fv168(); virtual HRESULT __stdcall fv169(); virtual HRESULT __stdcall fv170(); virtual HRESULT __stdcall fv171(); virtual HRESULT __stdcall fv172(); virtual HRESULT __stdcall fv173(); virtual HRESULT __stdcall fv174(); virtual HRESULT __stdcall fv175(); virtual HRESULT __stdcall fv176(); virtual HRESULT __stdcall fv177(); virtual HRESULT __stdcall fv178(); virtual HRESULT __stdcall fv179(); virtual HRESULT __stdcall fv180(); virtual HRESULT __stdcall fv181(); virtual HRESULT __stdcall fv182(); virtual HRESULT __stdcall fv183(); virtual HRESULT __stdcall fv184(); virtual HRESULT __stdcall fv185(); virtual HRESULT __stdcall fv186(); virtual HRESULT __stdcall fv187(); virtual HRESULT __stdcall fv188(); virtual HRESULT __stdcall fv189(); virtual HRESULT __stdcall fv190(); virtual HRESULT __stdcall fv191(); virtual HRESULT __stdcall fv192(); virtual HRESULT __stdcall fv193(); virtual HRESULT __stdcall fv194(); virtual HRESULT __stdcall fv195(); virtual HRESULT __stdcall fv196(); virtual HRESULT __stdcall fv197(); virtual HRESULT __stdcall fv198(); virtual HRESULT __stdcall fv199(); protected: const static int kMaxVf = 200; };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <npapi.h> #include <npruntime.h> #include <map> #include <vector> #include "Host.h" class CAxHost; class ObjectManager : public CHost { public: ObjectManager(NPP npp2); ~ObjectManager(void); static NPClass npClass; CHost* GetPreviousObject(NPP npp); static ObjectManager* GetManager(NPP npp); virtual ScriptBase *CreateScriptableObject(); void RetainOwnership(CAxHost *obj); bool RequestObjectOwnership(NPP newNpp, CAxHost* obj); private: struct ScriptManager : public ScriptBase { ScriptManager(NPP npp) : ScriptBase(npp) { } }; std::vector<CHost*> hosts; std::vector<CHost*> dynamic_hosts; static NPObject* _Allocate(NPP npp, NPClass *aClass) { ScriptManager *obj = new ScriptManager(npp); return obj; } static bool Invoke(NPObject *obj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool HasMethod(NPObject *obj, NPIdentifier name); static bool HasProperty(NPObject *obj, NPIdentifier name); static bool GetProperty(NPObject *obj, NPIdentifier name, NPVariant *value); static bool SetProperty(NPObject *obj, NPIdentifier name, const NPVariant *value); static void Deallocate(NPObject *obj); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "oleidl.h" #include <npapi.h> #include <npruntime.h> #include "npactivex.h" #include "objectProxy.h" #include "FakeDispatcher.h" class HTMLDocumentContainer : public CComObjectRoot, public IOleContainer, public IServiceProviderImpl<HTMLDocumentContainer>, public IWebBrowser2 { public: HTMLDocumentContainer(); void Init(NPP instance, ITypeLib *htmlLib); ~HTMLDocumentContainer(void); // IOleContainer virtual HRESULT STDMETHODCALLTYPE EnumObjects( /* [in] */ DWORD grfFlags, /* [out] */ __RPC__deref_out_opt IEnumUnknown **ppenum) { return LogNotImplemented(npp); } virtual HRESULT STDMETHODCALLTYPE ParseDisplayName( /* [unique][in] */ __RPC__in_opt IBindCtx *pbc, /* [in] */ __RPC__in LPOLESTR pszDisplayName, /* [out] */ __RPC__out ULONG *pchEaten, /* [out] */ __RPC__deref_out_opt IMoniker **ppmkOut) { return LogNotImplemented(npp); } virtual HRESULT STDMETHODCALLTYPE LockContainer( /* [in] */ BOOL fLock) { return LogNotImplemented(npp); } // IWebBrowser2 virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate2( /* [in] */ __RPC__in VARIANT *URL, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags, /* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName, /* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE QueryStatusWB( /* [in] */ OLECMDID cmdID, /* [retval][out] */ __RPC__out OLECMDF *pcmdf) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ExecWB( /* [in] */ OLECMDID cmdID, /* [in] */ OLECMDEXECOPT cmdexecopt, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvaIn, /* [unique][optional][out][in] */ __RPC__inout_opt VARIANT *pvaOut) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ShowBrowserBar( /* [in] */ __RPC__in VARIANT *pvaClsid, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarShow, /* [unique][optional][in] */ __RPC__in_opt VARIANT *pvarSize) {return LogNotImplemented(npp);}; virtual /* [bindable][propget][id] */ HRESULT STDMETHODCALLTYPE get_ReadyState( /* [out][retval] */ __RPC__out READYSTATE *plReadyState) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Offline( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbOffline) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Offline( /* [in] */ VARIANT_BOOL bOffline) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Silent( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbSilent) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Silent( /* [in] */ VARIANT_BOOL bSilent) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsBrowser( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsBrowser( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_RegisterAsDropTarget( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_RegisterAsDropTarget( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TheaterMode( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_TheaterMode( /* [in] */ VARIANT_BOOL bRegister) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_AddressBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {*Value = True;return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_AddressBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Resizable( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Resizable( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Quit( void) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE ClientToWindow( /* [out][in] */ __RPC__inout int *pcx, /* [out][in] */ __RPC__inout int *pcy) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE PutProperty( /* [in] */ __RPC__in BSTR Property, /* [in] */ VARIANT vtValue) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GetProperty( /* [in] */ __RPC__in BSTR Property, /* [retval][out] */ __RPC__out VARIANT *pvtValue) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Name( /* [retval][out] */ __RPC__deref_out_opt BSTR *Name) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_HWND( /* [retval][out] */ __RPC__out SHANDLE_PTR *pHWND) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullName( /* [retval][out] */ __RPC__deref_out_opt BSTR *FullName) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Path( /* [retval][out] */ __RPC__deref_out_opt BSTR *Path) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Visible( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_Visible( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_StatusText( /* [retval][out] */ __RPC__deref_out_opt BSTR *StatusText) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_StatusText( /* [in] */ __RPC__in BSTR StatusText) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_ToolBar( /* [retval][out] */ __RPC__out int *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_ToolBar( /* [in] */ int Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_MenuBar( /* [retval][out] */ __RPC__out VARIANT_BOOL *Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_MenuBar( /* [in] */ VARIANT_BOOL Value) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_FullScreen( /* [retval][out] */ __RPC__out VARIANT_BOOL *pbFullScreen) {*pbFullScreen = FALSE; return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_FullScreen( /* [in] */ VARIANT_BOOL bFullScreen) {return LogNotImplemented(npp);}; virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoBack( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoForward( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoHome( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE GoSearch( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Navigate( /* [in] */ __RPC__in BSTR URL, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Flags, /* [unique][optional][in] */ __RPC__in_opt VARIANT *TargetFrameName, /* [unique][optional][in] */ __RPC__in_opt VARIANT *PostData, /* [unique][optional][in] */ __RPC__in_opt VARIANT *Headers) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Refresh2( /* [unique][optional][in] */ __RPC__in_opt VARIANT *Level) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][id] */ HRESULT STDMETHODCALLTYPE Stop( void) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Application( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Parent( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Container( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Document( /* [retval][out] */ __RPC__deref_out_opt IDispatch **ppDisp); virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_TopLevelContainer( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Type( /* [retval][out] */ __RPC__deref_out_opt BSTR *Type) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Left( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Left( /* [in] */ long Left) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Top( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Top( /* [in] */ long Top) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Width( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Width( /* [in] */ long Width) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Height( /* [retval][out] */ __RPC__out long *pl) {return LogNotImplemented(npp);} virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_Height( /* [in] */ long Height) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationName( /* [retval][out] */ __RPC__deref_out_opt BSTR *LocationName) {return LogNotImplemented(npp);} virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_LocationURL( /* [retval][out] */ __RPC__deref_out_opt BSTR *LocationURL); virtual /* [helpcontext][helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_Busy( /* [retval][out] */ __RPC__out VARIANT_BOOL *pBool) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( /* [out] */ __RPC__out UINT *pctinfo) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) {return LogNotImplemented(npp);} virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId) {return LogNotImplemented(npp);} virtual /* [local] */ HRESULT STDMETHODCALLTYPE 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) {return LogNotImplemented(npp);} BEGIN_COM_MAP(HTMLDocumentContainer) COM_INTERFACE_ENTRY(IOleContainer) COM_INTERFACE_ENTRY(IServiceProvider) COM_INTERFACE_ENTRY(IWebBrowser2) COM_INTERFACE_ENTRY_IID(IID_IWebBrowserApp, IWebBrowser2) COM_INTERFACE_ENTRY_IID(IID_IWebBrowser, IWebBrowser2) COM_INTERFACE_ENTRY_AGGREGATE_BLIND(dispatcher) END_COM_MAP() static const GUID IID_TopLevelBrowser; BEGIN_SERVICE_MAP(HTMLDocumentContainer) SERVICE_ENTRY(IID_IWebBrowserApp) SERVICE_ENTRY(IID_IWebBrowser2) SERVICE_ENTRY(IID_IWebBrowser) SERVICE_ENTRY(SID_SContainerDispatch); SERVICE_ENTRY(IID_TopLevelBrowser) END_SERVICE_MAP() private: FakeDispatcher *dispatcher; NPObjectProxy document_; NPP npp; };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" #include "FakeDispatcher.h" #include "Host.h" extern NPNetscapeFuncs NPNFuncs; class CAxHost; struct Scriptable: public ScriptBase { private: Scriptable(const Scriptable &); // This method iterates all members of the current interface, looking for the member with the // id of member_id. If not found within this interface, it will iterate all base interfaces // recursively, until a match is found, or all the hierarchy was searched. bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind); DISPID ResolveName(NPIdentifier name, unsigned int invKind); //bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult); CComQIPtr<IDispatch> disp; bool invalid; DISPID dispid; void setControl(IUnknown *unk) { disp = unk; } bool IsProperty(DISPID member_id); public: Scriptable(NPP npp): ScriptBase(npp), invalid(false) { dispid = -1; } ~Scriptable() { } static NPClass npClass; static Scriptable* FromIUnknown(NPP npp, IUnknown *unk) { Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass); new_obj->setControl(unk); return new_obj; } static Scriptable* FromAxHost(NPP npp, CAxHost* host); HRESULT getControl(IUnknown **obj) { if (disp) { *obj = disp.p; (*obj)->AddRef(); return S_OK; } return E_NOT_SET; } void Invalidate() {invalid = true;} bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool Enumerate(NPIdentifier **value, uint32_t *count); private: // Some wrappers to adapt NPAPI's interface. static NPObject* _Allocate(NPP npp, NPClass *aClass); static void _Deallocate(NPObject *obj); static void _Invalidate(NPObject *obj) { if (obj) { ((Scriptable *)obj)->Invalidate(); } } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((Scriptable *)npobj)->Invoke(name, args, argCount, result); } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((Scriptable *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((Scriptable *)npobj)->SetProperty(name, value); } static bool _Enumerate(NPObject *npobj, NPIdentifier **value, uint32_t *count) { return ((Scriptable *)npobj)->Enumerate(value, count); } };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <Windows.h> #include <OleAuto.h> #include <npapi.h> #include <npruntime.h> #include "FakeDispatcherBase.h" #include "objectProxy.h" extern ITypeLib *pHtmlLib; class CAxHost; EXTERN_C const IID IID_IFakeDispatcher; class FakeDispatcher : public FakeDispatcherBase { private: class FakeDispatcherEx: IDispatchEx { private: FakeDispatcher *target; public: FakeDispatcherEx(FakeDispatcher *target) : target(target) { } virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) { return target->QueryInterface(riid, ppvObject); } virtual ULONG STDMETHODCALLTYPE AddRef( void) { return target->AddRef(); } virtual ULONG STDMETHODCALLTYPE Release( void) { return target->Release(); } virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( __RPC__out UINT *pctinfo) { return target->GetTypeInfoCount(pctinfo); } virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( UINT iTInfo, LCID lcid, __RPC__deref_out_opt ITypeInfo **ppTInfo) { return target->GetTypeInfo(iTInfo, lcid, ppTInfo); } virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( __RPC__in REFIID riid, __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, __RPC__in_range(0,16384) UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId) { return target->GetIDsOfNames(riid, rgszNames, cNames, lcid, rgDispId); } virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { return target->Invoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); } virtual HRESULT STDMETHODCALLTYPE GetDispID( __RPC__in BSTR bstrName, DWORD grfdex, __RPC__out DISPID *pid); virtual HRESULT STDMETHODCALLTYPE InvokeEx( __in DISPID id, __in LCID lcid, __in WORD wFlags, __in DISPPARAMS *pdp, __out_opt VARIANT *pvarRes, __out_opt EXCEPINFO *pei, __in_opt IServiceProvider *pspCaller); virtual HRESULT STDMETHODCALLTYPE DeleteMemberByName( __RPC__in BSTR bstrName, DWORD grfdex); virtual HRESULT STDMETHODCALLTYPE DeleteMemberByDispID(DISPID id); virtual HRESULT STDMETHODCALLTYPE GetMemberProperties( DISPID id, DWORD grfdexFetch, __RPC__out DWORD *pgrfdex); virtual HRESULT STDMETHODCALLTYPE GetMemberName( DISPID id, __RPC__deref_out_opt BSTR *pbstrName); virtual HRESULT STDMETHODCALLTYPE GetNextDispID( DWORD grfdex, DISPID id, __RPC__out DISPID *pid); virtual HRESULT STDMETHODCALLTYPE GetNameSpaceParent( __RPC__deref_out_opt IUnknown **ppunk); }; public: virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( void) { ++ref; return ref; } virtual ULONG STDMETHODCALLTYPE Release( void) { --ref; if (ref == 0) delete this; return ref; } virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount( __RPC__out UINT *pctinfo) { *pctinfo = 1; return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetTypeInfo( UINT iTInfo, LCID lcid, __RPC__deref_out_opt ITypeInfo **ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames( __RPC__in REFIID riid, __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, __RPC__in_range(0,16384) UINT cNames, LCID lcid, __RPC__out_ecount_full(cNames) DISPID *rgDispId); virtual HRESULT STDMETHODCALLTYPE Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); NPObject *getObject() { return npObject; } FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object); ~FakeDispatcher(void); HRESULT ProcessCommand(int ID, int *parlength,va_list &list); //friend HRESULT __cdecl DualProcessCommand(int parlength, int commandId, FakeDispatcher *disp, ...); private: static ITypeInfo* npTypeInfo; const static int DISPATCH_VTABLE = 7; FakeDispatcherEx *extended; NPP npInstance; NPObject *npObject; ITypeLib *typeLib; ITypeInfo *typeInfo; CAxHost *internalObj; bool HasValidTypeInfo(); int ref; DWORD dualType; #ifdef DEBUG char name[50]; char tag[100]; GUID interfaceid; #endif UINT FindFuncByVirtualId(int vtbId); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <atlstr.h> #include "npactivex.h" #include "scriptable.h" #include "axhost.h" #include "ObjectManager.h" #include "FakeDispatcher.h" // {1DDBD54F-2F8A-4186-972B-2A84FE1135FE} static const GUID IID_IFakeDispatcher = { 0x1ddbd54f, 0x2f8a, 0x4186, { 0x97, 0x2b, 0x2a, 0x84, 0xfe, 0x11, 0x35, 0xfe } }; ITypeInfo* FakeDispatcher::npTypeInfo = (ITypeInfo*)-1; #define DispatchLog(level, message, ...) np_log(this->npInstance, level, "Disp 0x%08x " message, this, ##__VA_ARGS__) FakeDispatcher::FakeDispatcher(NPP npInstance, ITypeLib *typeLib, NPObject *object) : npInstance(npInstance), typeLib(typeLib), npObject(object), typeInfo(NULL), internalObj(NULL), extended(NULL) { ref = 1; typeLib->AddRef(); NPNFuncs.retainobject(object); internalObj = (CAxHost*)ObjectManager::GetInternalObject(npInstance, object); #ifdef DEBUG name[0] = 0; tag[0] = 0; interfaceid = GUID_NULL; #endif NPVariantProxy npName, npTag; ATL::CStringA sname, stag; NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("id"), &npName); if (npName.type != NPVariantType_String || npName.value.stringValue.UTF8Length == 0) NPNFuncs.getproperty(npInstance, object, NPNFuncs.getstringidentifier("name"), &npName); if (npName.type == NPVariantType_String) { sname = CStringA(npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length); #ifdef DEBUG strncpy(name, npName.value.stringValue.UTF8Characters, npName.value.stringValue.UTF8Length); name[npName.value.stringValue.UTF8Length] = 0; #endif } if (NPNFuncs.hasmethod(npInstance, object, NPNFuncs.getstringidentifier("toString"))) { NPNFuncs.invoke(npInstance, object, NPNFuncs.getstringidentifier("toString"), &npTag, 0, &npTag); if (npTag.type == NPVariantType_String) { stag = CStringA(npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length); #ifdef DEBUG strncpy(tag, npTag.value.stringValue.UTF8Characters, npTag.value.stringValue.UTF8Length); tag[npTag.value.stringValue.UTF8Length] = 0; #endif } } DispatchLog(1, "Type: %s, Name: %s", stag.GetString(), sname.GetString()); } /* [local] */ HRESULT STDMETHODCALLTYPE FakeDispatcher::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) { USES_CONVERSION; // Convert variants int nArgs = pDispParams->cArgs; NPVariantProxy *npvars = new NPVariantProxy[nArgs]; for (int i = 0; i < nArgs; ++i) { Variant2NPVar(&pDispParams->rgvarg[nArgs - 1 - i], &npvars[i], npInstance); } // Determine method to call. HRESULT hr = E_FAIL; BSTR pBstrName; NPVariantProxy result; NPIdentifier identifier = NULL; NPIdentifier itemIdentifier = NULL; if (HasValidTypeInfo() && SUCCEEDED(typeInfo->GetDocumentation(dispIdMember, &pBstrName, NULL, NULL, NULL))) { LPSTR str = OLE2A(pBstrName); SysFreeString(pBstrName); DispatchLog(2, "Invoke 0x%08x %d %s", dispIdMember, wFlags, str); if (dispIdMember == 0x401 && strcmp(str, "url") == 0) { str = "baseURI"; } else if (dispIdMember == 0x40A && strcmp(str, "parentWindow") == 0) { str = "defaultView"; } identifier = NPNFuncs.getstringidentifier(str); if (dispIdMember == 0 && (wFlags & DISPATCH_METHOD) && strcmp(str, "item") == 0) { // Item can be evaluated as the default property. if (NPVARIANT_IS_INT32(npvars[0])) itemIdentifier = NPNFuncs.getintidentifier(npvars[0].value.intValue); else if (NPVARIANT_IS_STRING(npvars[0])) itemIdentifier = NPNFuncs.getstringidentifier(npvars[0].value.stringValue.UTF8Characters); } else if (dispIdMember == 0x3E9 && (wFlags & DISPATCH_PROPERTYGET) && strcmp(str, "Script") == 0) { identifier = NPNFuncs.getstringidentifier("defaultView"); } } else if (typeInfo == npTypeInfo && dispIdMember != NULL && dispIdMember != -1) { identifier = (NPIdentifier) dispIdMember; } if (FAILED(hr) && itemIdentifier != NULL) { if (NPNFuncs.hasproperty(npInstance, npObject, itemIdentifier)) { if (NPNFuncs.getproperty(npInstance, npObject, itemIdentifier, &result)) { hr = S_OK; } } } if (FAILED(hr) && (wFlags & DISPATCH_METHOD)) { if (NPNFuncs.invoke(npInstance, npObject, identifier, npvars, nArgs, &result)) { hr = S_OK; } } if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYGET)) { if (NPNFuncs.hasproperty(npInstance, npObject, identifier)) { if (NPNFuncs.getproperty(npInstance, npObject, identifier, &result)) { hr = S_OK; } } } if (FAILED(hr) && (wFlags & DISPATCH_PROPERTYPUT)) { if (nArgs == 1 && NPNFuncs.setproperty(npInstance, npObject, identifier, npvars)) hr = S_OK; } if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_METHOD)) { // Call default method. if (NPNFuncs.invokeDefault(npInstance, npObject, npvars, nArgs, &result)) { hr = S_OK; } } if (FAILED(hr) && dispIdMember == 0 && (wFlags & DISPATCH_PROPERTYGET) && pDispParams->cArgs == 0) { // Return toString() static NPIdentifier strIdentify = NPNFuncs.getstringidentifier("toString"); if (NPNFuncs.invoke(npInstance, npObject, strIdentify, NULL, 0, &result)) hr = S_OK; } if (SUCCEEDED(hr)) { NPVar2Variant(&result, pVarResult, npInstance); } else { DispatchLog(2, "Invoke failed 0x%08x %d", dispIdMember, wFlags); } delete [] npvars; return hr; } HRESULT STDMETHODCALLTYPE FakeDispatcher::QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) { HRESULT hr = E_FAIL; if (riid == IID_IDispatch || riid == IID_IUnknown) { *ppvObject = this; AddRef(); hr = S_OK; } else if (riid == IID_IDispatchEx) { if (extended == NULL) extended = new FakeDispatcherEx(this); *ppvObject = extended; AddRef(); hr = S_OK; } else if (riid == IID_IFakeDispatcher) { *ppvObject = this; AddRef(); hr = S_OK; } else if (!typeInfo) { hr = typeLib->GetTypeInfoOfGuid(riid, &typeInfo); if (SUCCEEDED(hr)) { TYPEATTR *attr; typeInfo->GetTypeAttr(&attr); dualType = attr->wTypeFlags; if (!(dualType & TYPEFLAG_FDISPATCHABLE)) { hr = E_NOINTERFACE; } else { *ppvObject = static_cast<FakeDispatcher*>(this); AddRef(); } typeInfo->ReleaseTypeAttr(attr); } } else { FakeDispatcher *another_obj = new FakeDispatcher(npInstance, typeLib, npObject); hr = another_obj->QueryInterface(riid, ppvObject); another_obj->Release(); } if (FAILED(hr) && internalObj) { IUnknown *unk; internalObj->GetControlUnknown(&unk); hr = unk->QueryInterface(riid, ppvObject); unk->Release(); /* // Try to find the internal object NPIdentifier object_id = NPNFuncs.getstringidentifier(object_property); NPVariant npVar; if (NPNFuncs.getproperty(npInstance, npObject, object_id, &npVar) && npVar.type == NPVariantType_Int32) { IUnknown *internalObject = (IUnknown*)NPVARIANT_TO_INT32(npVar); hr = internalObject->QueryInterface(riid, ppvObject); }*/ } #ifdef DEBUG if (hr == S_OK) { interfaceid = riid; } else { // Unsupported Interface! } #endif USES_CONVERSION; LPOLESTR clsid; StringFromCLSID(riid, &clsid); if (FAILED(hr)) { DispatchLog(0, "Unsupported Interface %s", OLE2A(clsid)); } else { DispatchLog(0, "QueryInterface %s", OLE2A(clsid)); } return hr; } FakeDispatcher::~FakeDispatcher(void) { if (HasValidTypeInfo()) { typeInfo->Release(); } if (extended) { delete extended; } NPNFuncs.releaseobject(npObject); typeLib->Release(); } // This function is used because the symbol of FakeDispatcher::ProcessCommand is not determined in asm file. extern "C" HRESULT __cdecl DualProcessCommand(int parlength, int commandId, int returnAddr, FakeDispatcher *disp, ...){ // returnAddr is a placeholder for the calling proc. va_list va; va_start(va, disp); // The parlength is on the stack, the modification will be reflect. HRESULT ret = disp->ProcessCommand(commandId, &parlength, va); va_end(va); return ret; } HRESULT FakeDispatcher::GetTypeInfo( /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) { if (iTInfo == 0 && HasValidTypeInfo()) { *ppTInfo = typeInfo; typeInfo->AddRef(); return S_OK; } return E_INVALIDARG; } HRESULT FakeDispatcher::GetIDsOfNames( /* [in] */ __RPC__in REFIID riid, /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames, /* [range][in] */ __RPC__in_range(0,16384) UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId){ if (HasValidTypeInfo()) { return typeInfo->GetIDsOfNames(rgszNames, cNames, rgDispId); } else { USES_CONVERSION; typeInfo = npTypeInfo; for (UINT i = 0; i < cNames; ++i) { DispatchLog(2, "GetIDsOfNames %s", OLE2A(rgszNames[i])); rgDispId[i] = (DISPID) NPNFuncs.getstringidentifier(OLE2A(rgszNames[i])); } return S_OK; } } HRESULT FakeDispatcher::ProcessCommand(int vfid, int *parlength, va_list &args) { // This exception is critical if we can't find the size of parameters. if (!HasValidTypeInfo()) { DispatchLog(0, "VT interface %d called without type info", vfid); __asm int 3; } UINT index = FindFuncByVirtualId(vfid); if (index == (UINT)-1) { DispatchLog(0, "Unknown VT interface id"); __asm int 3; } FUNCDESC *func; // We should count pointer of "this" first. *parlength = sizeof(LPVOID); if (FAILED(typeInfo->GetFuncDesc(index, &func))) __asm int 3; DISPPARAMS varlist; // We don't need to clear them. VARIANT *list = new VARIANT[func->cParams]; varlist.cArgs = func->cParams; varlist.cNamedArgs = 0; varlist.rgdispidNamedArgs = NULL; varlist.rgvarg = list; // Thanks that there won't be any out variants in HTML. for (int i = 0; i < func->cParams; ++i) { int listPos = func->cParams - 1 - i; ELEMDESC *desc = &func->lprgelemdescParam[listPos]; memset(&list[listPos], 0, sizeof(list[listPos])); RawTypeToVariant(desc->tdesc, args, &list[listPos]); size_t varsize = VariantSize(desc->tdesc.vt); size_t intvarsz = (varsize + sizeof(int) - 1) & (~(sizeof(int) - 1)); args += intvarsz; *parlength += intvarsz; } // We needn't clear it. Caller takes ownership. VARIANT result; HRESULT ret = Invoke(func->memid, IID_NULL, NULL, func->invkind, &varlist, &result, NULL, NULL); if (SUCCEEDED(ret)) ret = ConvertVariantToGivenType(typeInfo, func->elemdescFunc.tdesc, result, args); size_t varsize = VariantSize(func->elemdescFunc.tdesc.vt); // It should always be a pointer. It always should be counted. size_t intvarsz = varsize ? sizeof(LPVOID) : 0; *parlength += intvarsz; delete[] list; return ret; } UINT FakeDispatcher::FindFuncByVirtualId(int vtbId) { if (dualType & TYPEFLAG_FDUAL) return vtbId + DISPATCH_VTABLE; else return vtbId; } bool FakeDispatcher::HasValidTypeInfo() { return typeInfo && typeInfo != npTypeInfo; } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetDispID( __RPC__in BSTR bstrName, DWORD grfdex, __RPC__out DISPID *pid) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::InvokeEx( __in DISPID id, __in LCID lcid, __in WORD wFlags, __in DISPPARAMS *pdp, __out_opt VARIANT *pvarRes, __out_opt EXCEPINFO *pei, __in_opt IServiceProvider *pspCaller) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByName( __RPC__in BSTR bstrName, DWORD grfdex) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::DeleteMemberByDispID(DISPID id) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberProperties( DISPID id, DWORD grfdexFetch, __RPC__out DWORD *pgrfdex) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetMemberName( DISPID id, __RPC__deref_out_opt BSTR *pbstrName) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNextDispID( DWORD grfdex, DISPID id, __RPC__out DISPID *pid) { return LogNotImplemented(target->npInstance); } HRESULT STDMETHODCALLTYPE FakeDispatcher::FakeDispatcherEx::GetNameSpaceParent( __RPC__deref_out_opt IUnknown **ppunk) { return LogNotImplemented(target->npInstance); }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // dllmain.cpp : Defines the entry point for the DLL application. #include "npactivex.h" #include "axhost.h" #include "atlthunk.h" #include "FakeDispatcher.h" CComModule _Module; NPNetscapeFuncs NPNFuncs; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } // ============================== // ! Scriptability related code ! // ============================== // // here the plugin is asked by Mozilla to tell if it is scriptable // we should return a valid interface id and a pointer to // nsScriptablePeer interface which we should have implemented // and which should be defined in the corressponding *.xpt file // in the bin/components folder NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; if(instance == NULL) return NPERR_GENERIC_ERROR; CAxHost *host = (CAxHost *)instance->pdata; if(host == NULL) return NPERR_GENERIC_ERROR; switch (variable) { case NPPVpluginNameString: *((char **)value) = "ITSTActiveX"; break; case NPPVpluginDescriptionString: *((char **)value) = "IT Structures ActiveX for Firefox"; break; case NPPVpluginScriptableNPObject: *(NPObject **)value = host->GetScriptableObject(); break; default: rv = NPERR_GENERIC_ERROR; } return rv; } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int32_t NPP_WriteReady (NPP instance, NPStream *stream) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = 0x0fffffff; return rv; } int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = len; return rv; } NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname) { if(instance == NULL) return; } void NPP_Print (NPP instance, NPPrint* printInfo) { if(instance == NULL) return; } void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) { if(instance == NULL) return; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int16 NPP_HandleEvent(NPP instance, void* event) { if(instance == NULL) return 0; int16 rv = 0; CAxHost *host = dynamic_cast<CAxHost*>((CHost *)instance->pdata); if (host) rv = host->HandleEvent(event); return rv; } NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) { if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; if(pFuncs->size < sizeof(NPPluginFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; pFuncs->newp = NPP_New; pFuncs->destroy = NPP_Destroy; pFuncs->setwindow = NPP_SetWindow; pFuncs->newstream = NPP_NewStream; pFuncs->destroystream = NPP_DestroyStream; pFuncs->asfile = NPP_StreamAsFile; pFuncs->writeready = NPP_WriteReady; pFuncs->write = NPP_Write; pFuncs->print = NPP_Print; pFuncs->event = NPP_HandleEvent; pFuncs->urlnotify = NPP_URLNotify; pFuncs->getvalue = NPP_GetValue; pFuncs->setvalue = NPP_SetValue; pFuncs->javaClass = NULL; return NPERR_NO_ERROR; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) /* * Initialize the plugin. Called the first time the browser comes across a * MIME Type this plugin is registered to handle. */ NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs) { #ifdef DEBUG CString text; text.Format(_T("NPActiveX Pid %d"), GetCurrentProcessId()); MessageBox(NULL, text, _T(""), MB_OK); #endif CoInitialize(NULL); InstallAtlThunkEnumeration(); if (pHtmlLib == NULL) { OLECHAR path[MAX_PATH]; GetEnvironmentVariableW(OLESTR("SYSTEMROOT"), path, MAX_PATH - 30); StrCatW(path, L"\\system32\\mshtml.tlb"); HRESULT hr = LoadTypeLib(path, &pHtmlLib); } if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; #ifdef NDEF // The following statements prevented usage of newer Mozilla sources than installed browser at runtime if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR) return NPERR_INCOMPATIBLE_VERSION_ERROR; if(pFuncs->size < sizeof(NPNetscapeFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; #endif if (!AtlAxWinInit()) { return NPERR_GENERIC_ERROR; } _pAtlModule = &_Module; memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs)); memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs))); return NPERR_NO_ERROR; } /* * Shutdown the plugin. Called when no more instanced of this plugin exist and * the browser wants to unload it. */ NPError OSCALL NP_Shutdown(void) { AtlAxWinTerm(); UninstallAtlThunkEnumeration(); return NPERR_NO_ERROR; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "scriptable.h" #include "axhost.h" #include "ScriptFunc.h" #include "npactivex.h" NPClass Scriptable::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ Scriptable::_Allocate, /* deallocate */ Scriptable::_Deallocate, /* invalidate */ Scriptable::_Invalidate, /* hasMethod */ Scriptable::_HasMethod, /* invoke */ Scriptable::_Invoke, /* invokeDefault */ NULL, /* hasProperty */ Scriptable::_HasProperty, /* getProperty */ Scriptable::_GetProperty, /* setProperty */ Scriptable::_SetProperty, /* removeProperty */ NULL, /* enumerate */ Scriptable::_Enumerate, /* construct */ NULL }; bool Scriptable::find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) { bool found = false; unsigned int i = 0; FUNCDESC *fDesc; for (i = 0; (i < attr->cFuncs) && !found; ++i) { HRESULT hr = info->GetFuncDesc(i, &fDesc); if (SUCCEEDED(hr) && fDesc && (fDesc->memid == member_id)) { if (invKind & fDesc->invkind) found = true; } info->ReleaseFuncDesc(fDesc); } if (!found && (invKind & ~INVOKE_FUNC)) { VARDESC *vDesc; for (i = 0; (i < attr->cVars) && !found; ++i) { HRESULT hr = info->GetVarDesc(i, &vDesc); if ( SUCCEEDED(hr) && vDesc && (vDesc->memid == member_id)) { found = true; } info->ReleaseVarDesc(vDesc); } } if (!found) { // iterate inherited interfaces HREFTYPE refType = NULL; for (i = 0; (i < attr->cImplTypes) && !found; ++i) { ITypeInfoPtr baseInfo; TYPEATTR *baseAttr; if (FAILED(info->GetRefTypeOfImplType(0, &refType))) { continue; } if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) { continue; } baseInfo->AddRef(); if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) { continue; } found = find_member(baseInfo, baseAttr, member_id, invKind); baseInfo->ReleaseTypeAttr(baseAttr); } } return found; } bool Scriptable::IsProperty(DISPID member_id) { ITypeInfo *typeinfo; if (FAILED(disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &typeinfo))) { return false; } TYPEATTR *typeAttr; typeinfo->GetTypeAttr(&typeAttr); bool ret = find_member(typeinfo, typeAttr, member_id, DISPATCH_METHOD); typeinfo->ReleaseTypeAttr(typeAttr); typeinfo->Release(); return !ret; } DISPID Scriptable::ResolveName(NPIdentifier name, unsigned int invKind) { bool found = false; DISPID dID = -1; USES_CONVERSION; if (!name || !invKind) { return -1; } if (!disp) { return -1; } if (!NPNFuncs.identifierisstring(name)) { return -1; } NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name); LPOLESTR oleName = A2W(npname); disp->GetIDsOfNames(IID_NULL, &oleName, 1, 0, &dID); return dID; #if 0 int funcInv; if (FindElementInvKind(disp, dID, &funcInv)) { if (funcInv & invKind) return dID; else return -1; } else { if ((dID != -1) && (invKind & INVOKE_PROPERTYGET)) { // Try to get property to check. // Use two parameters. It will definitely fail in property get/set, but it will return other orrer if it's not property. CComVariant var[2]; DISPPARAMS par = {var, NULL, 2, 0}; CComVariant result; HRESULT hr = disp->Invoke(dID, IID_NULL, 1, invKind, &par, &result, NULL, NULL); if (hr == DISP_E_MEMBERNOTFOUND || hr == DISP_E_TYPEMISMATCH) return -1; } } return dID; #endif if (dID != -1) { ITypeInfoPtr info; disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info); if (!info) { return dID; } TYPEATTR *attr; if (FAILED(info->GetTypeAttr(&attr))) { return dID; } found = find_member(info, attr, dID, invKind); info->ReleaseTypeAttr(attr); } return found ? dID : -1; } bool Scriptable::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; np_log(instance, 2, "Invoke %s", NPNFuncs.utf8fromidentifier(name)); DISPID id = ResolveName(name, INVOKE_FUNC); bool ret = InvokeID(id, args, argCount, result); if (!ret) { np_log(instance, 0, "Invoke failed: %s", NPNFuncs.utf8fromidentifier(name)); } return ret; } bool Scriptable::InvokeID(DISPID id, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (-1 == id) { return false; } CComVariant *vArgs = NULL; if (argCount) { vArgs = new CComVariant[argCount]; if (!vArgs) { return false; } for (unsigned int i = 0; i < argCount; ++i) { // copy the arguments in reverse order NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance); } } DISPPARAMS params = {NULL, NULL, 0, 0}; params.cArgs = argCount; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = vArgs; CComVariant vResult; HRESULT rc = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &params, &vResult, NULL, NULL); if (vArgs) { delete []vArgs; } if (FAILED(rc)) { np_log(instance, 0, "Invoke failed: 0x%08x, dispid: 0x%08x", rc, id); return false; } Variant2NPVar(&vResult, result, instance); return true; } bool Scriptable::HasMethod(NPIdentifier name) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_FUNC); return (id != -1) ? true : false; } bool Scriptable::HasProperty(NPIdentifier name) { static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); static NPIdentifier readyStateId = NPNFuncs.getstringidentifier("readyState"); static NPIdentifier objectId = NPNFuncs.getstringidentifier("object"); static NPIdentifier instanceId = NPNFuncs.getstringidentifier("__npp_instance__"); if (name == classid || name == readyStateId || name == instanceId || name == objectId) { return true; } if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT); return (id != -1) ? true : false; } bool Scriptable::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); static NPIdentifier readyStateId = NPNFuncs.getstringidentifier("readyState"); static NPIdentifier objectId = NPNFuncs.getstringidentifier("object"); static NPIdentifier instanceId = NPNFuncs.getstringidentifier("__npp_instance__"); if (name == classid) { CAxHost *host = (CAxHost*)this->host; if (this->disp == NULL) { char* cstr = (char*)NPNFuncs.memalloc(1); cstr[0] = 0; STRINGZ_TO_NPVARIANT(cstr, *result); return true; } else { USES_CONVERSION; char* cstr = (char*)NPNFuncs.memalloc(50); strcpy(cstr, "CLSID:"); LPOLESTR clsidstr; StringFromCLSID(host->getClsID(), &clsidstr); // Remove braces. clsidstr[lstrlenW(clsidstr) - 1] = '\0'; strcat(cstr, OLE2A(clsidstr + 1)); CoTaskMemFree(clsidstr); STRINGZ_TO_NPVARIANT(cstr, *result); return true; } } else if (name == readyStateId) { INT32_TO_NPVARIANT(4, *result); return true; } else if (name == instanceId) { INT32_TO_NPVARIANT((int32)instance, *result); return true; } else if (name == objectId) { OBJECT_TO_NPVARIANT(this, *result); NPNFuncs.retainobject(this); return true; } DISPID id = ResolveName(name, INVOKE_PROPERTYGET); if (-1 == id) { np_log(instance, 0, "Cannot find property: %s", NPNFuncs.utf8fromidentifier(name)); return false; } DISPPARAMS params; params.cArgs = 0; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = NULL; CComVariant vResult; if (IsProperty(id)) { HRESULT hr = disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_PROPERTYGET, &params, &vResult, NULL, NULL); if (SUCCEEDED(hr)) { Variant2NPVar(&vResult, result, instance); np_log(instance, 2, "GetProperty %s", NPNFuncs.utf8fromidentifier(name)); return true; } } np_log(instance, 2, "GetMethodObject %s", NPNFuncs.utf8fromidentifier(name)); OBJECT_TO_NPVARIANT(ScriptFunc::GetFunctionObject(instance, this, id), *result); return true; } bool Scriptable::SetProperty(NPIdentifier name, const NPVariant *value) { static NPIdentifier classid = NPNFuncs.getstringidentifier("classid"); if (name == classid) { np_log(instance, 1, "Set classid property: %s", value->value.stringValue); CAxHost* axhost = (CAxHost*)host; CLSID newCLSID = CAxHost::ParseCLSIDFromSetting(value->value.stringValue.UTF8Characters, value->value.stringValue.UTF8Length); if (newCLSID != GUID_NULL && (!axhost->hasValidClsID() || newCLSID != axhost->getClsID())) { axhost->Clear(); if (axhost->setClsID(newCLSID)) { axhost->CreateControl(false); IUnknown *unk; if (SUCCEEDED(axhost->GetControlUnknown(&unk))) { this->setControl(unk); unk->Release(); } axhost->ResetWindow(); } } return true; } if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYPUT); if (-1 == id) { return false; } CComVariant val; NPVar2Variant(value, &val, instance); DISPPARAMS params; // Special initialization needed when using propery put. DISPID dispidNamed = DISPID_PROPERTYPUT; params.cNamedArgs = 1; params.rgdispidNamedArgs = &dispidNamed; params.cArgs = 1; params.rgvarg = &val; CComVariant vResult; WORD wFlags = DISPATCH_PROPERTYPUT; if (val.vt == VT_DISPATCH) { wFlags |= DISPATCH_PROPERTYPUTREF; } const char* pname = NPNFuncs.utf8fromidentifier(name); if (FAILED(disp->Invoke(id, GUID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, &params, &vResult, NULL, NULL))) { np_log(instance, 0, "SetProperty failed %s", pname); return false; } np_log(instance, 0, "SetProperty %s", pname); return true; } Scriptable* Scriptable::FromAxHost(NPP npp, CAxHost* host) { Scriptable *new_obj = (Scriptable*)NPNFuncs.createobject(npp, &npClass); IUnknown *unk; if (SUCCEEDED(host->GetControlUnknown(&unk))) { new_obj->setControl(unk); new_obj->host = host; unk->Release(); } return new_obj; } NPObject* Scriptable::_Allocate(NPP npp, NPClass *aClass) { return new Scriptable(npp); } void Scriptable::_Deallocate(NPObject *obj) { if (obj) { Scriptable *a = static_cast<Scriptable*>(obj); //np_log(a->instance, 3, "Dealocate obj"); delete a; } } bool Scriptable::Enumerate(NPIdentifier **value, uint32_t *count) { UINT cnt; if (!disp || FAILED(disp->GetTypeInfoCount(&cnt))) return false; *count = 0; for (UINT i = 0; i < cnt; ++i) { CComPtr<ITypeInfo> info; disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info); TYPEATTR *attr; info->GetTypeAttr(&attr); *count += attr->cFuncs; info->ReleaseTypeAttr(attr); } uint32_t pos = 0; NPIdentifier *v = (NPIdentifier*) NPNFuncs.memalloc(sizeof(NPIdentifier) * *count); USES_CONVERSION; for (UINT i = 0; i < cnt; ++i) { CComPtr<ITypeInfo> info; disp->GetTypeInfo(i, LOCALE_SYSTEM_DEFAULT, &info); TYPEATTR *attr; info->GetTypeAttr(&attr); BSTR name; for (uint j = 0; j < attr->cFuncs; ++j) { FUNCDESC *desc; info->GetFuncDesc(j, &desc); if (SUCCEEDED(info->GetDocumentation(desc->memid, &name, NULL, NULL, NULL))) { LPCSTR str = OLE2A(name); v[pos++] = NPNFuncs.getstringidentifier(str); SysFreeString(name); } info->ReleaseFuncDesc(desc); } info->ReleaseTypeAttr(attr); } *count = pos; *value = v; return true; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <map> #include <vector> #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; extern NPClass GenericNPObjectClass; typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); struct ltnum { bool operator()(long n1, long n2) const { return n1 < n2; } }; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); class GenericNPObject: public NPObject { private: GenericNPObject(const GenericNPObject &); bool invalid; DefaultInvoker defInvoker; void *defInvokerObject; std::vector<NPVariant> numeric_mapper; // the members of alpha mapper can be reassigned to anything the user wishes std::map<const char *, NPVariant, ltstr> alpha_mapper; // these cannot accept other types than they are initially defined with std::map<const char *, NPVariant, ltstr> immutables; public: friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *); GenericNPObject(NPP instance); GenericNPObject(NPP instance, bool isMethodObj); ~GenericNPObject(); void Invalidate() {invalid = true;} void SetDefaultInvoker(DefaultInvoker di, void *context) { defInvoker = di; defInvokerObject = context; } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result); } static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (((GenericNPObject *)npobj)->defInvoker) { return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result); } else { return false; } } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((GenericNPObject *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((GenericNPObject *)npobj)->SetProperty(name, value); } static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->RemoveProperty(name); } static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) { return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount); } bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool RemoveProperty(NPIdentifier name); bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "atlthunk.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <stdio.h> #include "ApiHook\Hook.h" typedef struct tagEXCEPTION_REGISTER { tagEXCEPTION_REGISTER *prev; _except_handler_type handler; }EXCEPTION_REGISTER, *LPEXCEPTION_REGISTER; /* Supported patterns: C7 44 24 04 XX XX XX XX mov [esp+4], imm32 E9 YY YY YY YY jmp imm32 B9 XX XX XX XX mov ecx, imm32 E9 YY YY YY YY jmp imm32 BA XX XX XX XX mov edx, imm32 B9 YY YY YY YY mov ecx, imm32 FF E1 jmp ecx B9 XX XX XX XX mov ecx, imm32 B8 YY YY YY YY mov eax, imm32 FF E0 jmp eax 59 pop ecx 58 pop eax 51 push ecx FF 60 04 jmp [eax+4] */ /* Pattern 1: C7 44 24 04 XX XX XX XX mov [esp+4], imm32 E9 YY YY YY YY jmp imm32 */ BYTE pattern1[] = {0xC7, 0x44, 0x24, 0x04, 0, 0, 0, 0, 0xE9, 0, 0, 0, 0}; void _process_pattern1(struct _CONTEXT *ContextRecord) { LPDWORD esp = (LPDWORD)(ContextRecord->Esp); DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 4); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 9); esp[1] = imm1; ContextRecord->Eip += imm2 + 13; } /* Pattern 2: B9 XX XX XX XX mov ecx, imm32 E9 YY YY YY YY jmp imm32 */ BYTE pattern2[] = {0xB9, 0, 0, 0, 0, 0xE9, 0, 0, 0, 0}; void _process_pattern2(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Ecx = imm1; ContextRecord->Eip += imm2 + 10; } /* Pattern 3: BA XX XX XX XX mov edx, imm32 B9 YY YY YY YY mov ecx, imm32 FF E1 jmp ecx */ BYTE pattern3[] = {0xBA, 0, 0, 0, 0, 0xB9, 0, 0, 0, 0, 0xFF, 0xE1}; void _process_pattern3(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Edx = imm1; ContextRecord->Ecx = imm2; ContextRecord->Eip += imm2; } /* B9 XX XX XX XX mov ecx, imm32 B8 YY YY YY YY mov eax, imm32 FF E0 jmp eax */ BYTE pattern4[] = {0xB9, 0, 0, 0, 0, 0xB8, 0, 0, 0, 0, 0xFF, 0xE0}; void _process_pattern4(struct _CONTEXT *ContextRecord) { DWORD imm1 = *(LPDWORD)(ContextRecord->Eip + 1); DWORD imm2 = *(LPDWORD)(ContextRecord->Eip + 6); ContextRecord->Ecx = imm1; ContextRecord->Eax = imm2; ContextRecord->Eip += imm2; } /* 59 pop ecx 58 pop eax 51 push ecx FF 60 04 jmp [eax+4] */ BYTE pattern5[] = {0x59, 0x58, 0x51, 0xFF, 0x60, 0x04}; void _process_pattern5(struct _CONTEXT *ContextRecord) { LPDWORD stack = (LPDWORD)(ContextRecord->Esp); ContextRecord->Ecx = stack[0]; ContextRecord->Eax = stack[1]; stack[1] = stack[0]; ContextRecord->Esp += 4; ContextRecord->Eip = *(LPDWORD)(ContextRecord->Eax + 4); } ATL_THUNK_PATTERN patterns[] = { {pattern1, sizeof(pattern1), _process_pattern1}, {pattern2, sizeof(pattern2), _process_pattern2}, {pattern3, sizeof(pattern3), _process_pattern3}, {pattern4, sizeof(pattern4), _process_pattern4}, {pattern5, sizeof(pattern5), _process_pattern5} }; ATL_THUNK_PATTERN *match_patterns(LPVOID eip) { LPBYTE codes = (LPBYTE)eip; for (int i = 0; i < sizeof(patterns) / sizeof(patterns[0]); ++i) { BOOL match = TRUE; for (int j = 0; j < patterns[i].pattern_size && match; ++j) { if (patterns[i].pattern[j] != 0 && patterns[i].pattern[j] != codes[j]) match = FALSE; } if (match) { return &patterns[i]; } } return NULL; } EXCEPTION_DISPOSITION __cdecl _except_handler_atl_thunk( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { if ((ExceptionRecord->ExceptionFlags) || ExceptionRecord->ExceptionCode != STATUS_ACCESS_VIOLATION || ExceptionRecord->ExceptionAddress != (LPVOID)ContextRecord->Eip) { // Not expected Access violation exception return ExceptionContinueSearch; } // Try to match patterns ATL_THUNK_PATTERN *pattern = match_patterns((LPVOID)ContextRecord->Eip); if (pattern) { //DWORD old; // We can't always protect the ATL by except_handler, so we mark it executable. //BOOL ret = VirtualProtect((LPVOID)ContextRecord->Eip, pattern->pattern_size, PAGE_EXECUTE_READWRITE, &old); pattern->enumerator(ContextRecord); return ExceptionContinueExecution; } else { return ExceptionContinueSearch; } } #ifndef ATL_THUNK_APIHOOK _except_handler_type original_handler4; #else HOOKINFO hook_handler; #endif #if 0 EXCEPTION_DISPOSITION __cdecl my_except_handler4( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { //assert(original_handler); EXCEPTION_DISPOSITION step1 = _except_handler_atl_thunk(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); if (step1 == ExceptionContinueExecution) return step1; #ifndef ATL_THUNK_APIHOOK _except_handler_type original_handler = original_handler4; #else _except_handler_type original_handler = (_except_handler_type)hook_handler4.Stub; #endif return original_handler(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); } EXCEPTION_DISPOSITION __cdecl my_except_handler3( struct _EXCEPTION_RECORD *ExceptionRecord, void * EstablisherFrame, struct _CONTEXT *ContextRecord, void * DispatcherContext ) { //assert(original_handler); EXCEPTION_DISPOSITION step1 = _except_handler_atl_thunk(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); if (step1 == ExceptionContinueExecution) return step1; #ifndef ATL_THUNK_APIHOOK // We won't wrap handler3, this shouldn't be used.. _except_handler_type original_handler = original_handler3; #else _except_handler_type original_handler = (_except_handler_type)hook_handler4.Stub; #endif return original_handler(ExceptionRecord, EstablisherFrame, ContextRecord, DispatcherContext); } #endif BOOL CheckDEPEnabled() { // In case of running in a XP SP2. HMODULE hInst = LoadLibrary(TEXT("Kernel32.dll")); typedef BOOL (WINAPI *SetProcessDEPPolicyType)( __in DWORD dwFlags ); typedef BOOL (WINAPI *GetProcessDEPPolicyType)( __in HANDLE hProcess, __out LPDWORD lpFlags, __out PBOOL lpPermanent ); SetProcessDEPPolicyType setProc = (SetProcessDEPPolicyType)GetProcAddress(hInst, "SetProcessDEPPolicy"); GetProcessDEPPolicyType getProc = (GetProcessDEPPolicyType)GetProcAddress(hInst, "GetProcessDEPPolicy"); if (setProc) { // This is likely to fail, but we set it first. setProc(PROCESS_DEP_ENABLE); } BOOL enabled = FALSE; DWORD lpFlags; BOOL lpPermanent; if (getProc && getProc(GetCurrentProcess(), &lpFlags, &lpPermanent)) { enabled = (lpFlags == (PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION | PROCESS_DEP_ENABLE)); } return enabled; } extern "C" void _KiUserExceptionDispatcher_hook(); extern "C" DWORD _KiUserExceptionDispatcher_origin; extern "C" DWORD _KiUserExceptionDispatcher_ATL_p; typedef void (__stdcall *ZwContinueType)(struct _CONTEXT *, int); ZwContinueType ZwContinue; int __cdecl _KiUserExceptionDispatcher_ATL( struct _EXCEPTION_RECORD *ExceptionRecord, struct _CONTEXT *ContextRecord) { if (_except_handler_atl_thunk(ExceptionRecord, NULL, ContextRecord, NULL) == ExceptionContinueExecution) { ZwContinue(ContextRecord, 0); } return 0; } bool atlThunkInstalled = false; void InstallAtlThunkEnumeration() { if (atlThunkInstalled) return; if (CheckDEPEnabled()) { #ifndef ATL_THUNK_APIHOOK // Chrome is protected by DEP. EXCEPTION_REGISTER *reg; __asm { mov eax, fs:[0] mov reg, eax } while ((DWORD)reg->prev != 0xFFFFFFFF) reg = reg->prev; // replace the old handler original_handler = reg->handler; reg->handler = _except_handler; #else _KiUserExceptionDispatcher_ATL_p = (DWORD)_KiUserExceptionDispatcher_ATL; ZwContinue = (ZwContinueType) GetProcAddress(GetModuleHandle(TEXT("ntdll")), "ZwContinue"); HEInitHook(&hook_handler, GetProcAddress(GetModuleHandle(TEXT("ntdll")), "KiUserExceptionDispatcher") , _KiUserExceptionDispatcher_hook); HEStartHook(&hook_handler); _KiUserExceptionDispatcher_origin = (DWORD)hook_handler.Stub; atlThunkInstalled = true; #endif } } void UninstallAtlThunkEnumeration() { #ifdef ATL_THUNK_APIHOOK if (!atlThunkInstalled) return; HEStopHook(&hook_handler); atlThunkInstalled = false; #endif }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "HTMLDocumentContainer.h" #include "npactivex.h" #include <MsHTML.h> const GUID HTMLDocumentContainer::IID_TopLevelBrowser = {0x4C96BE40, 0x915C, 0x11CF, {0x99, 0xD3, 0x00, 0xAA, 0x00, 0x4A, 0xE8, 0x37}}; HTMLDocumentContainer::HTMLDocumentContainer() : dispatcher(NULL) { } void HTMLDocumentContainer::Init(NPP instance, ITypeLib *htmlLib) { NPObjectProxy npWindow; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &npWindow); NPVariantProxy documentVariant; if (NPNFuncs.getproperty(instance, npWindow, NPNFuncs.getstringidentifier("document"), &documentVariant) && NPVARIANT_IS_OBJECT(documentVariant)) { NPObject *npDocument = NPVARIANT_TO_OBJECT(documentVariant); dispatcher = new FakeDispatcher(instance, htmlLib, npDocument); } npp = instance; } HRESULT HTMLDocumentContainer::get_LocationURL(BSTR *str) { NPObjectProxy npWindow; NPNFuncs.getvalue(npp, NPNVWindowNPObject, &npWindow); NPVariantProxy LocationVariant; if (!NPNFuncs.getproperty(npp, npWindow, NPNFuncs.getstringidentifier("location"), &LocationVariant) || !NPVARIANT_IS_OBJECT(LocationVariant)) { return E_FAIL; } NPObject *npLocation = NPVARIANT_TO_OBJECT(LocationVariant); NPVariantProxy npStr; if (!NPNFuncs.getproperty(npp, npLocation, NPNFuncs.getstringidentifier("href"), &npStr)) return E_FAIL; CComBSTR bstr(npStr.value.stringValue.UTF8Length, npStr.value.stringValue.UTF8Characters); *str = bstr.Detach(); return S_OK; } HRESULT STDMETHODCALLTYPE HTMLDocumentContainer::get_Document( __RPC__deref_out_opt IDispatch **ppDisp) { if (dispatcher) return dispatcher->QueryInterface(DIID_DispHTMLDocument, (LPVOID*)ppDisp); return E_FAIL; } HTMLDocumentContainer::~HTMLDocumentContainer(void) { }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "NPSafeArray.h" #include "npactivex.h" #include "objectProxy.h" #include <OleAuto.h> NPClass NPSafeArray::npClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ NPSafeArray::Allocate, /* deallocate */ NPSafeArray::Deallocate, /* invalidate */ NPSafeArray::Invalidate, /* hasMethod */ NPSafeArray::HasMethod, /* invoke */ NPSafeArray::Invoke, /* invokeDefault */ NPSafeArray::InvokeDefault, /* hasProperty */ NPSafeArray::HasProperty, /* getProperty */ NPSafeArray::GetProperty, /* setProperty */ NPSafeArray::SetProperty, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NPSafeArray::InvokeDefault }; NPSafeArray::NPSafeArray(NPP npp): ScriptBase(npp) { NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window); } NPSafeArray::~NPSafeArray(void) { } // Some wrappers to adapt NPAPI's interface. NPObject* NPSafeArray::Allocate(NPP npp, NPClass *aClass) { return new NPSafeArray(npp); } void NPSafeArray::Deallocate(NPObject *obj){ delete static_cast<NPSafeArray*>(obj); } LPSAFEARRAY NPSafeArray::GetArrayPtr() { return arr_.m_psa; } NPInvokeDefaultFunctionPtr NPSafeArray::GetFuncPtr(NPIdentifier name) { if (name == NPNFuncs.getstringidentifier("getItem")) { return NPSafeArray::GetItem; } else if (name == NPNFuncs.getstringidentifier("toArray")) { return NPSafeArray::ToArray; } else if (name == NPNFuncs.getstringidentifier("lbound")) { return NPSafeArray::LBound; } else if (name == NPNFuncs.getstringidentifier("ubound")) { return NPSafeArray::UBound; } else if (name == NPNFuncs.getstringidentifier("dimensions")) { return NPSafeArray::Dimensions; } else { return NULL; } } void NPSafeArray::Invalidate(NPObject *obj) { NPSafeArray *safe = static_cast<NPSafeArray*>(obj); safe->arr_.Destroy(); } bool NPSafeArray::HasMethod(NPObject *npobj, NPIdentifier name) { return GetFuncPtr(name) != NULL; } void NPSafeArray::RegisterVBArray(NPP npp) { NPObjectProxy window; NPNFuncs.getvalue(npp, NPNVWindowNPObject, &window); NPIdentifier vbarray = NPNFuncs.getstringidentifier("VBArray"); if (!NPNFuncs.hasproperty(npp, window, vbarray)) { NPVariantProxy var; NPObject *def = NPNFuncs.createobject(npp, &npClass); OBJECT_TO_NPVARIANT(def, var); NPNFuncs.setproperty(npp, window, vbarray, &var); } } NPSafeArray *NPSafeArray::CreateFromArray(NPP instance, SAFEARRAY *array) { NPSafeArray *ret = (NPSafeArray *)NPNFuncs.createobject(instance, &npClass); ret->arr_.Attach(array); return ret; } bool NPSafeArray::Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; NPInvokeDefaultFunctionPtr ptr = GetFuncPtr(name); if (ptr) { return ptr(npobj, args, argCount, result); } else { return false; } } bool NPSafeArray::InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa != NULL) return false; if (argCount < 1) return false; if (!NPVARIANT_IS_OBJECT(*args)) { return false; } NPObject *obj = NPVARIANT_TO_OBJECT(*args); if (obj->_class != &NPSafeArray::npClass) { return false; } NPSafeArray *safe_original = static_cast<NPSafeArray*>(obj); if (safe_original->arr_.m_psa == NULL) { return false; } NPSafeArray *ret = CreateFromArray(safe->instance, safe_original->arr_); OBJECT_TO_NPVARIANT(ret, *result); return true; } bool NPSafeArray::GetItem(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; LONG dim = safe->arr_.GetDimensions(); if (argCount < safe->arr_.GetDimensions()) { return false; } CAutoVectorPtr<LONG>pos(new LONG[dim]); for (int i = 0; i < dim; ++i) { if (NPVARIANT_IS_DOUBLE(args[i])) { pos[i] = (LONG)NPVARIANT_TO_DOUBLE(args[i]); } else if (NPVARIANT_IS_INT32(args[i])) { pos[i] = NPVARIANT_TO_INT32(args[i]); } else { return false; } } VARIANT var; if (!SUCCEEDED(safe->arr_.MultiDimGetAt(pos, var))) { return false; } Variant2NPVar(&var, result, safe->instance); return true; } bool NPSafeArray::Dimensions(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; INT32_TO_NPVARIANT(safe->arr_.GetDimensions(), *result); return true; } bool NPSafeArray::UBound(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; int dim = 1; if (argCount >= 1) { if (NPVARIANT_IS_INT32(*args)) { dim = NPVARIANT_TO_INT32(*args); } else if (NPVARIANT_IS_DOUBLE(*args)) { dim = (LONG)NPVARIANT_TO_DOUBLE(*args); } else { return false; } } try{ INT32_TO_NPVARIANT(safe->arr_.GetUpperBound(dim - 1), *result); } catch (...) { return false; } return true; } bool NPSafeArray::LBound(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; int dim = 1; if (argCount >= 1) { if (NPVARIANT_IS_INT32(*args)) { dim = NPVARIANT_TO_INT32(*args); } else if (NPVARIANT_IS_DOUBLE(*args)) { dim = (LONG)NPVARIANT_TO_DOUBLE(*args); } else { return false; } } try{ INT32_TO_NPVARIANT(safe->arr_.GetLowerBound(dim - 1), *result); } catch (...) { return false; } return true; } bool NPSafeArray::ToArray(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { NPSafeArray *safe = static_cast<NPSafeArray*>(npobj); if (safe->arr_.m_psa == NULL) return false; long count = 1, dim = safe->arr_.GetDimensions(); for (int d = 0; d < dim; ++d) { count *= safe->arr_.GetCount(d); } NPString command = {"[]", 2}; if (!NPNFuncs.evaluate(safe->instance, safe->window, &command, result)) return false; VARIANT* vars = (VARIANT*)safe->arr_.m_psa->pvData; NPIdentifier push = NPNFuncs.getstringidentifier("push"); for (long i = 0; i < count; ++i) { NPVariantProxy v; NPVariant arg; Variant2NPVar(&vars[i], &arg, safe->instance); if (!NPNFuncs.invoke(safe->instance, NPVARIANT_TO_OBJECT(*result), push, &arg, 1, &v)) { return false; } } return true; } bool NPSafeArray::HasProperty(NPObject *npobj, NPIdentifier name) { return false; } bool NPSafeArray::GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return false; } bool NPSafeArray::SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return false; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // This function is totally disabled now. #if 0 #include <stdio.h> #include <windows.h> #include <winreg.h> #include "npactivex.h" #include "atlutil.h" #include "authorize.h" // ---------------------------------------------------------------------------- #define SUB_KEY L"SOFTWARE\\MozillaPlugins\\@itstructures.com/npactivex\\MimeTypes\\application/x-itst-activex" // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId); BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId); BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value); HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType); // --------------------------------------------------------------------------- HKEY BaseKeys[] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }; // ---------------------------------------------------------------------------- BOOL TestAuthorization (NPP Instance, int16 ArgC, char *ArgN[], char *ArgV[], const char *MimeType) { BOOL ret = FALSE; NPObject *globalObj = NULL; NPIdentifier identifier; NPVariant varLocation; NPVariant varHref; bool rc = false; int16 i; char *wrkHref; #ifdef NDEF _asm{int 3}; #endif if (Instance == NULL) { return (FALSE); } // Determine owning document // Get the window object. NPNFuncs.getvalue(Instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(Instance, globalObj, identifier, &varLocation); NPNFuncs.releaseobject(globalObj); if (!rc){ np_log(Instance, 0, "AxHost.TestAuthorization: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(Instance, locationObj, identifier, &varHref); NPNFuncs.releasevariantvalue(&varLocation); if (!rc) { np_log(Instance, 0, "AxHost.TestAuthorization: could not get the href from the location property"); return false; } ret = TRUE; wrkHref = (char *) alloca(varHref.value.stringValue.UTF8Length + 1); memcpy(wrkHref, varHref.value.stringValue.UTF8Characters, varHref.value.stringValue.UTF8Length); wrkHref[varHref.value.stringValue.UTF8Length] = 0x00; NPNFuncs.releasevariantvalue(&varHref); for (i = 0; i < ArgC; ++i) { // search for any needed information: clsid, event handling directives, etc. if (0 == strnicmp(ArgN[i], PARAM_CLSID, strlen(PARAM_CLSID))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CLSID, wrkHref, ArgV[i]); } else if (0 == strnicmp(ArgN[i], PARAM_PROGID, strlen(PARAM_PROGID))) { // The class id of the control we are asked to load ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_PROGID, wrkHref, ArgV[i]); } else if( 0 == strnicmp(ArgN[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CODEBASEURL, wrkHref, ArgV[i]); } } np_log(Instance, 1, "AxHost.TestAuthorization: returning %s", ret ? "True" : "False"); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId) { USES_CONVERSION; BOOL ret; ret = TestExplicitAuthorization(A2W(MimeType), A2W(AuthorizationType), A2W(DocumentUrl), A2W(ProgramId)); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId) { BOOL ret = FALSE; #ifndef NO_REGISTRY_AUTHORIZE HKEY hKey; HKEY hSubKey; ULONG i; ULONG j; ULONG keyNameLen; ULONG valueNameLen; wchar_t keyName[_MAX_PATH]; wchar_t valueName[_MAX_PATH]; if (DocumentUrl == NULL) { return (FALSE); } if (ProgramId == NULL) { return (FALSE); } #ifdef NDEF MessageBox(NULL, DocumentUrl, ProgramId, MB_OK); #endif if ((hKey = FindKey(MimeType, AuthorizationType)) != NULL) { for (i = 0; !ret; i++) { keyNameLen = sizeof(keyName); if (RegEnumKey(hKey, i, keyName, keyNameLen) == ERROR_SUCCESS) { if (WildcardMatch(keyName, DocumentUrl)) { if (RegOpenKeyEx(hKey, keyName, 0, KEY_QUERY_VALUE, &hSubKey) == ERROR_SUCCESS) { for (j = 0; ; j++) { valueNameLen = sizeof(valueName); if (RegEnumValue(hSubKey, j, valueName, &valueNameLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { break; } if (WildcardMatch(valueName, ProgramId)) { ret = TRUE; break; } } RegCloseKey(hSubKey); } if (ret) { break; } } } else { break; } } RegCloseKey(hKey); } #endif return (ret); } // ---------------------------------------------------------------------------- BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value) { size_t i; size_t j = 0; size_t maskLen; size_t valueLen; maskLen = wcslen(Mask); valueLen = wcslen(Value); for (i = 0; i < maskLen + 1; i++) { if (Mask[i] == '?') { j++; continue; } if (Mask[i] == '*') { for (; j < valueLen + 1; j++) { if (WildcardMatch(Mask + i + 1, Value + j)) { return (TRUE); } } return (FALSE); } if ((j <= valueLen) && (Mask[i] == tolower(Value[j]))) { j++; continue; } return (FALSE); } return (TRUE); } // ---------------------------------------------------------------------------- HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType) { HKEY ret = NULL; HKEY plugins; wchar_t searchKey[_MAX_PATH]; wchar_t pluginName[_MAX_PATH]; DWORD j; size_t i; for (i = 0; i < ARRAYSIZE(BaseKeys); i++) { if (RegOpenKeyEx(BaseKeys[i], L"SOFTWARE\\MozillaPlugins", 0, KEY_ENUMERATE_SUB_KEYS, &plugins) == ERROR_SUCCESS) { for (j = 0; ret == NULL; j++) { if (RegEnumKey(plugins, j, pluginName, sizeof(pluginName)) != ERROR_SUCCESS) { break; } wsprintf(searchKey, L"%s\\MimeTypes\\%s\\%s", pluginName, MimeType, AuthorizationType); if (RegOpenKeyEx(plugins, searchKey, 0, KEY_ENUMERATE_SUB_KEYS, &ret) == ERROR_SUCCESS) { break; } ret = NULL; } RegCloseKey(plugins); if (ret != NULL) { break; } } } return (ret); } #endif
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <atlbase.h> #include <atlsafe.h> #include <npapi.h> #include <npfunctions.h> #include "FakeDispatcher.h" #include <npruntime.h> #include "scriptable.h" #include "GenericNPObject.h" #include <OleAuto.h> #include "variants.h" #include "NPSafeArray.h" void BSTR2NPVar(BSTR bstr, NPVariant *npvar, NPP instance) { char *npStr = NULL; size_t sourceLen; size_t bytesNeeded; sourceLen = lstrlenW(bstr); bytesNeeded = WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, NULL, 0, NULL, NULL); bytesNeeded += 1; // complete lack of documentation on Mozilla's part here, I have no // idea how this string is supposed to be freed npStr = (char *)NPNFuncs.memalloc(bytesNeeded); if (npStr) { int len = WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, npStr, bytesNeeded - 1, NULL, NULL); npStr[len] = 0; STRINGN_TO_NPVARIANT(npStr, len, (*npvar)); } else { VOID_TO_NPVARIANT(*npvar); } } BSTR NPStringToBstr(const NPString npstr) { size_t bytesNeeded; bytesNeeded = MultiByteToWideChar( CP_UTF8, 0, npstr.UTF8Characters, npstr.UTF8Length, NULL, 0); bytesNeeded += 1; BSTR bstr = (BSTR)CoTaskMemAlloc(sizeof(OLECHAR) * bytesNeeded); if (bstr) { int len = MultiByteToWideChar( CP_UTF8, 0, npstr.UTF8Characters, npstr.UTF8Length, bstr, bytesNeeded); bstr[len] = 0; return bstr; } return NULL; } void Unknown2NPVar(IUnknown *unk, NPVariant *npvar, NPP instance) { FakeDispatcher *disp = NULL; if (!unk) { NULL_TO_NPVARIANT(*npvar); } else if (SUCCEEDED(unk->QueryInterface(IID_IFakeDispatcher, (void**)&disp))) { OBJECT_TO_NPVARIANT(disp->getObject(), *npvar); NPNFuncs.retainobject(disp->getObject()); disp->Release(); } else { NPObject *obj = Scriptable::FromIUnknown(instance, unk); OBJECT_TO_NPVARIANT(obj, (*npvar)); } } #define GETVALUE(var, val) (((var->vt) & VT_BYREF) ? *(var->p##val) : (var->val)) void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; if (!var || !npvar) { return; } VOID_TO_NPVARIANT(*npvar); USES_CONVERSION; switch (var->vt & ~VT_BYREF) { case VT_ARRAY | VT_VARIANT: NPSafeArray::RegisterVBArray(instance); NPSafeArray *obj; obj = NPSafeArray::CreateFromArray(instance, var->parray); OBJECT_TO_NPVARIANT(obj, (*npvar)); break; case VT_EMPTY: VOID_TO_NPVARIANT((*npvar)); break; case VT_NULL: NULL_TO_NPVARIANT((*npvar)); break; case VT_LPSTR: // not sure it can even appear in a VARIANT, but... STRINGZ_TO_NPVARIANT(var->pcVal, (*npvar)); break; case VT_BSTR: BSTR2NPVar(GETVALUE(var, bstrVal), npvar, instance); break; case VT_I1: INT32_TO_NPVARIANT((INT32)GETVALUE(var, cVal), (*npvar)); break; case VT_I2: INT32_TO_NPVARIANT((INT32)GETVALUE(var, iVal), (*npvar)); break; case VT_I4: INT32_TO_NPVARIANT((INT32)GETVALUE(var, lVal), (*npvar)); break; case VT_UI1: INT32_TO_NPVARIANT((INT32)GETVALUE(var, bVal), (*npvar)); break; case VT_UI2: INT32_TO_NPVARIANT((INT32)GETVALUE(var, uiVal), (*npvar)); break; case VT_UI4: case VT_UINT: INT32_TO_NPVARIANT((INT32)GETVALUE(var, ulVal), (*npvar)); break; case VT_INT: INT32_TO_NPVARIANT((INT32)GETVALUE(var, lVal), (*npvar)); break; case VT_BOOL: BOOLEAN_TO_NPVARIANT((GETVALUE(var, boolVal) == VARIANT_TRUE) ? true : false, (*npvar)); break; case VT_R4: DOUBLE_TO_NPVARIANT((double)GETVALUE(var, fltVal), (*npvar)); break; case VT_R8: DOUBLE_TO_NPVARIANT(GETVALUE(var, dblVal), (*npvar)); break; case VT_DATE: DOUBLE_TO_NPVARIANT(GETVALUE(var, date), (*npvar)); break; case VT_DISPATCH: case VT_USERDEFINED: case VT_UNKNOWN: Unknown2NPVar(GETVALUE(var, punkVal), npvar, instance); break; case VT_VARIANT: Variant2NPVar(var->pvarVal, npvar, instance); break; default: // Some unsupported type np_log(instance, 0, "Unsupported variant type %d", var->vt); VOID_TO_NPVARIANT(*npvar); break; } } #undef GETVALUE ITypeLib *pHtmlLib; void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance) { if (!var || !npvar) { return; } var->vt = VT_EMPTY; switch (npvar->type) { case NPVariantType_Void: var->vt = VT_EMPTY; var->ulVal = 0; break; case NPVariantType_Null: var->vt = VT_NULL; var->byref = NULL; break; case NPVariantType_Bool: var->vt = VT_BOOL; var->boolVal = npvar->value.boolValue ? VARIANT_TRUE : VARIANT_FALSE; break; case NPVariantType_Int32: var->vt = VT_I4; var->ulVal = npvar->value.intValue; break; case NPVariantType_Double: var->vt = VT_R8; var->dblVal = npvar->value.doubleValue; break; case NPVariantType_String: (CComVariant&)*var = NPStringToBstr(npvar->value.stringValue); break; case NPVariantType_Object: NPObject *object = NPVARIANT_TO_OBJECT(*npvar); var->vt = VT_DISPATCH; if (object->_class == &Scriptable::npClass) { Scriptable* scriptObj = (Scriptable*)object; scriptObj->getControl(&var->punkVal); } else if (object->_class == &NPSafeArray::npClass) { NPSafeArray* arrayObj = (NPSafeArray*)object; var->vt = VT_ARRAY | VT_VARIANT; var->parray = arrayObj->GetArrayPtr(); } else { IUnknown *val = new FakeDispatcher(instance, pHtmlLib, object); var->punkVal = val; } break; } } size_t VariantSize(VARTYPE vt) { if ((vt & VT_BYREF) || (vt & VT_ARRAY)) return sizeof(LPVOID); switch (vt) { case VT_EMPTY: case VT_NULL: case VT_VOID: return 0; case VT_I1: case VT_UI1: return 1; case VT_I2: case VT_UI2: return 2; case VT_R8: case VT_DATE: case VT_I8: case VT_UI8: case VT_CY: return 8; case VT_I4: case VT_R4: case VT_UI4: case VT_BOOL: return 4; case VT_BSTR: case VT_DISPATCH: case VT_ERROR: case VT_UNKNOWN: case VT_DECIMAL: case VT_INT: case VT_UINT: case VT_HRESULT: case VT_PTR: case VT_SAFEARRAY: case VT_CARRAY: case VT_USERDEFINED: case VT_LPSTR: case VT_LPWSTR: case VT_INT_PTR: case VT_UINT_PTR: return sizeof(LPVOID); case VT_VARIANT: return sizeof(VARIANT); default: return 0; } } HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest) { // var is converted from NPVariant, so only limited types are possible. HRESULT hr = S_OK; switch (vt.vt) { case VT_EMPTY: case VT_VOID: case VT_NULL: return S_OK; case VT_I1: case VT_UI1: case VT_I2: case VT_UI2: case VT_I4: case VT_R4: case VT_UI4: case VT_BOOL: case VT_INT: case VT_UINT: int intvalue; intvalue = NULL; if (var.vt == VT_R8) intvalue = (int)var.dblVal; else if (var.vt == VT_BOOL) intvalue = (int)var.boolVal; else if (var.vt == VT_UI4) intvalue = var.intVal; else return E_FAIL; **(int**)dest = intvalue; hr = S_OK; break; case VT_R8: double dblvalue; dblvalue = 0.0; if (var.vt == VT_R8) dblvalue = (double)var.dblVal; else if (var.vt == VT_BOOL) dblvalue = (double)var.boolVal; else if (var.vt == VT_UI4) dblvalue = var.intVal; else return E_FAIL; **(double**)dest = dblvalue; hr = S_OK; break; case VT_DATE: case VT_I8: case VT_UI8: case VT_CY: // I don't know how to deal with these types.. __asm{int 3}; case VT_BSTR: case VT_DISPATCH: case VT_ERROR: case VT_UNKNOWN: case VT_DECIMAL: case VT_HRESULT: case VT_SAFEARRAY: case VT_CARRAY: case VT_LPSTR: case VT_LPWSTR: case VT_INT_PTR: case VT_UINT_PTR: **(ULONG***)dest = var.pulVal; break; case VT_USERDEFINED: { if (var.vt != VT_UNKNOWN && var.vt != VT_DISPATCH) { return E_FAIL; } else { ITypeInfo *newType; baseType->GetRefTypeInfo(vt.hreftype, &newType); IUnknown *unk = var.punkVal; TYPEATTR *attr; newType->GetTypeAttr(&attr); hr = unk->QueryInterface(attr->guid, (LPVOID*)dest); unk->Release(); newType->ReleaseTypeAttr(attr); newType->Release(); } } break; case VT_PTR: return ConvertVariantToGivenType(baseType, *vt.lptdesc, var, *(LPVOID*)dest); break; case VT_VARIANT: memcpy(*(VARIANT**)dest, &var, sizeof(var)); default: _asm{int 3} } return hr; } void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var) { BOOL pointer = FALSE; switch (desc.vt) { case VT_BSTR: case VT_DISPATCH: case VT_ERROR: case VT_UNKNOWN: case VT_SAFEARRAY: case VT_CARRAY: case VT_LPSTR: case VT_LPWSTR: case VT_INT_PTR: case VT_UINT_PTR: case VT_PTR: // These are pointers pointer = TRUE; break; default: if (var->vt & VT_BYREF) pointer = TRUE; } if (pointer) { var->vt = desc.vt; var->pulVal = *(PULONG*)source; } else if (desc.vt == VT_VARIANT) { // It passed by object, but we use as a pointer var->vt = desc.vt; var->pulVal = (PULONG)source; } else { var->vt = desc.vt | VT_BYREF; var->pulVal = (PULONG)source; } }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <algorithm> #include <string> #include "GenericNPObject.h" static NPObject* AllocateGenericNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, false); } static NPObject* AllocateMethodNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, true); } static void DeallocateGenericNPObject(NPObject *obj) { if (!obj) { return; } GenericNPObject *m = (GenericNPObject *)obj; delete m; } static void InvalidateGenericNPObject(NPObject *obj) { if (!obj) { return; } ((GenericNPObject *)obj)->Invalidate(); } NPClass GenericNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateGenericNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; NPClass MethodNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateMethodNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; // Some standard JavaScript methods bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) { GenericNPObject *map = (GenericNPObject *)object; if (!map || map->invalid) return false; // no args expected or cared for... std::string out; std::vector<NPVariant>::iterator it; for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) { if (NPVARIANT_IS_VOID(*it)) { out += ","; } else if (NPVARIANT_IS_NULL(*it)) { out += ","; } else if (NPVARIANT_IS_BOOLEAN(*it)) { if ((*it).value.boolValue) { out += "true,"; } else { out += "false,"; } } else if (NPVARIANT_IS_INT32(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%d,", (*it).value.intValue); out += tmp; } else if (NPVARIANT_IS_DOUBLE(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%f,", (*it).value.doubleValue); out += tmp; } else if (NPVARIANT_IS_STRING(*it)) { out += std::string((*it).value.stringValue.UTF8Characters, (*it).value.stringValue.UTF8Characters + (*it).value.stringValue.UTF8Length); out += ","; } else if (NPVARIANT_IS_OBJECT(*it)) { out += "[object],"; } } // calculate how much space we need std::string::size_type size = out.length(); char *s = (char *)NPNFuncs.memalloc(size * sizeof(char)); if (NULL == s) { return false; } memcpy(s, out.c_str(), size); s[size - 1] = 0; // overwrite the last "," STRINGZ_TO_NPVARIANT(s, (*result)); return true; } // Some helpers static void free_numeric_element(NPVariant elem) { NPNFuncs.releasevariantvalue(&elem); } static void free_alpha_element(std::pair<const char *, NPVariant> elem) { NPNFuncs.releasevariantvalue(&(elem.second)); } // And now the GenericNPObject implementation GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj): invalid(false), defInvoker(NULL), defInvokerObject(NULL) { NPVariant val; INT32_TO_NPVARIANT(0, val); immutables["length"] = val; if (!isMethodObj) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &MethodNPObjectClass); if (NULL == obj) { throw NULL; } ((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this); OBJECT_TO_NPVARIANT(obj, val); immutables["toString"] = val; } } GenericNPObject::~GenericNPObject() { for_each(immutables.begin(), immutables.end(), free_alpha_element); for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element); for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element); } bool GenericNPObject::HasMethod(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL != immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault); } } } return false; } bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(immutables[key]) && immutables[key].value.objectValue->_class->invokeDefault) { return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result); } } else if (alpha_mapper.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(alpha_mapper[key]) && alpha_mapper[key].value.objectValue->_class->invokeDefault) { return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result); } } } return true; } bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (defInvoker) { defInvoker(defInvokerObject, args, argCount, result); } return true; } // This method is also called before the JS engine attempts to add a new // property, most likely it's trying to check that the key is supported. // It only returns false if the string name was not found, or does not // hold a callable object bool GenericNPObject::HasProperty(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL == immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault); } } return false; } return true; } static bool CopyNPVariant(NPVariant *dst, const NPVariant *src) { dst->type = src->type; if (NPVARIANT_IS_STRING(*src)) { NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8)); if (NULL == str) { return false; } dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length; memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length); str[dst->value.stringValue.UTF8Length] = 0; dst->value.stringValue.UTF8Characters = str; } else if (NPVARIANT_IS_OBJECT(*src)) { NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src)); dst->value.objectValue = src->value.objectValue; } else { dst->value = src->value; } return true; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (!CopyNPVariant(result, &(immutables[key]))) { return false; } } else if (alpha_mapper.count(key) > 0) { if (!CopyNPVariant(result, &(alpha_mapper[key]))) { return false; } } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { if (!CopyNPVariant(result, &(numeric_mapper[key]))) { return false; } } } } catch (...) { } return true; } bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { // the key is already defined as immutable, check the new value type if (value->type != immutables[key].type) { return false; } // Seems ok, copy the new value if (!CopyNPVariant(&(immutables[key]), value)) { return false; } } else if (!CopyNPVariant(&(alpha_mapper[key]), value)) { return false; } } else { // assume int... NPVariant var; if (!CopyNPVariant(&var, value)) { return false; } unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (key >= numeric_mapper.size()) { // there's a gap we need to fill NPVariant pad; VOID_TO_NPVARIANT(pad); numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad); } numeric_mapper.at(key) = var; NPVARIANT_TO_INT32(immutables["length"])++; } } catch (...) { } return true; } bool GenericNPObject::RemoveProperty(NPIdentifier name) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (alpha_mapper.count(key) > 0) { NPNFuncs.releasevariantvalue(&(alpha_mapper[key])); alpha_mapper.erase(key); } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { NPNFuncs.releasevariantvalue(&(numeric_mapper[key])); numeric_mapper.erase(numeric_mapper.begin() + key); } NPVARIANT_TO_INT32(immutables["length"])--; } } catch (...) { } return true; } bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) { if (invalid) return false; try { *identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size()); if (NULL == *identifiers) { return false; } *identifierCount = 0; std::vector<NPVariant>::iterator it; unsigned int i = 0; char str[10] = ""; for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) { // skip empty (padding) elements if (NPVARIANT_IS_VOID(*it)) continue; _snprintf(str, sizeof(str), "%u", i); (*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str); } } catch (...) { } return true; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "Host.h" #include "npactivex.h" #include "ObjectManager.h" #include "objectProxy.h" #include <npapi.h> #include <npruntime.h> CHost::CHost(NPP npp) : ref_cnt_(1), instance(npp), lastObj(NULL) { } CHost::~CHost(void) { UnRegisterObject(); np_log(instance, 3, "CHost::~CHost"); } void CHost::AddRef() { ++ref_cnt_; } void CHost::Release() { --ref_cnt_; if (!ref_cnt_) delete this; } NPObject *CHost::GetScriptableObject() { return lastObj; } NPObject *CHost::RegisterObject() { lastObj = CreateScriptableObject(); if (!lastObj) return NULL; lastObj->host = this; // It doesn't matter which npp in setting. return lastObj; } void CHost::UnRegisterObject() { return; NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); NPVariant var; VOID_TO_NPVARIANT(var); NPNFuncs.removeproperty(instance, embed, NPNFuncs.getstringidentifier("object")); np_log(instance, 3, "UnRegisterObject"); lastObj = NULL; } NPP CHost::ResetNPP(NPP newNPP) { // Doesn't support now.. _asm{int 3}; NPP ret = instance; UnRegisterObject(); instance = newNPP; np_log(newNPP, 3, "Reset NPP from 0x%08x to 0x%08x", ret, newNPP); RegisterObject(); return ret; } CHost *CHost::GetInternalObject(NPP npp, NPObject *embed_element) { NPVariantProxy var; if (!NPNFuncs.getproperty(npp, embed_element, NPNFuncs.getstringidentifier("__npp_instance__"), &var)) return NULL; if (NPVARIANT_IS_INT32(var)) { return (CHost*)((NPP)var.value.intValue)->pdata; } else if (NPVARIANT_IS_DOUBLE(var)) { return (CHost*)((NPP)((int32)var.value.doubleValue))->pdata; } return NULL; } ScriptBase *CHost::GetMyScriptObject() { NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); return GetInternalObject(instance, embed)->lastObj; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "Host.h" namespace ATL { template <typename T> class CComObject; } class CControlEventSink; class CControlSite; class PropertyList; class CAxHost : public CHost{ private: CAxHost(const CAxHost &); bool isValidClsID; bool isKnown; bool noWindow; protected: // The window handle to our plugin area in the browser HWND Window; WNDPROC OldProc; // The class/prog id of the control CLSID ClsID; LPCWSTR CodeBaseUrl; CComObject<CControlEventSink> *Sink; RECT lastRect; PropertyList *Props_; public: CAxHost(NPP inst); ~CAxHost(); static CLSID ParseCLSIDFromSetting(LPCSTR clsid, int length); virtual NPP ResetNPP(NPP npp); CComObject<CControlSite> *Site; void SetNPWindow(NPWindow *window); void ResetWindow(); PropertyList *Props() { return Props_; } void Clear(); void setWindow(HWND win); HWND getWinfow(); void UpdateRect(RECT rcPos); bool verifyClsID(LPOLESTR oleClsID); bool setClsID(const char *clsid); bool setClsID(const CLSID& clsid); CLSID getClsID() { return this->ClsID; } void setNoWindow(bool value); bool setClsIDFromProgID(const char *progid); void setCodeBaseUrl(LPCWSTR clsid); bool hasValidClsID(); bool CreateControl(bool subscribeToEvents); void UpdateRectSize(LPRECT origRect); void SetRectSize(LPSIZEL size); bool AddEventHandler(wchar_t *name, wchar_t *handler); HRESULT GetControlUnknown(IUnknown **pObj); short HandleEvent(void *event); ScriptBase *CreateScriptableObject(); };
C++
#pragma once #include <npapi.h> #include <npruntime.h> #include <OleAuto.h> #include "scriptable.h" #include "npactivex.h" #include <map> using std::map; using std::pair; class ScriptFunc : public NPObject { private: static NPClass npClass; Scriptable *script; MEMBERID dispid; void setControl(Scriptable *script, MEMBERID dispid) { NPNFuncs.retainobject(script); this->script = script; this->dispid = dispid; } static map<pair<Scriptable*, MEMBERID>, ScriptFunc*> M; bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result); public: ScriptFunc(NPP inst); ~ScriptFunc(void); static NPObject *_Allocate(NPP npp, NPClass *npClass) { return new ScriptFunc(npp); } static void _Deallocate(NPObject *object) { ScriptFunc *obj = (ScriptFunc*)(object); delete obj; } static ScriptFunc* GetFunctionObject(NPP npp, Scriptable *script, MEMBERID dispid); static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((ScriptFunc *)npobj)->InvokeDefault(args, argCount, result); } };
C++
// (c) Code By Extreme // Description:Inline Hook Engine // Last update:2010-6-26 #include <Windows.h> #include <stdio.h> #include "Hook.h" #define JMPSIZE 5 #define NOP 0x90 extern DWORD ade_getlength(LPVOID Start, DWORD WantLength); static VOID BuildJmp(PBYTE Buffer,DWORD JmpFrom, DWORD JmpTo) { DWORD JmpAddr; JmpAddr = JmpFrom - JmpTo - JMPSIZE; Buffer[0] = 0xE9; Buffer[1] = (BYTE)(JmpAddr & 0xFF); Buffer[2] = (BYTE)((JmpAddr >> 8) & 0xFF); Buffer[3] = (BYTE)((JmpAddr >> 16) & 0xFF); Buffer[4] = (BYTE)((JmpAddr >> 24) & 0xFF); } VOID HEInitHook(PHOOKINFO HookInfo, LPVOID FuncAddr, LPVOID FakeAddr) { HookInfo->FakeAddr = FakeAddr; HookInfo->FuncAddr = FuncAddr; return; } BOOL HEStartHook(PHOOKINFO HookInfo) { BOOL CallRet; BOOL FuncRet = 0; PVOID BufAddr; DWORD dwTmp; DWORD OldProtect; LPVOID FuncAddr; DWORD CodeLength; // Init the basic value FuncAddr = HookInfo->FuncAddr; CodeLength = ade_getlength(FuncAddr, JMPSIZE); HookInfo->CodeLength = CodeLength; if (HookInfo->FakeAddr == NULL || FuncAddr == NULL || CodeLength == NULL) { FuncRet = 1; goto Exit1; } // Alloc buffer to store the code then write them to the head of the function BufAddr = malloc(CodeLength); if (BufAddr == NULL) { FuncRet = 2; goto Exit1; } // Alloc buffer to store original code HookInfo->Stub = (PBYTE)malloc(CodeLength + JMPSIZE); if (HookInfo->Stub == NULL) { FuncRet = 3; goto Exit2; } // Fill buffer to nop. This could make hook stable FillMemory(BufAddr, CodeLength, NOP); // Build buffers BuildJmp((PBYTE)BufAddr, (DWORD)HookInfo->FakeAddr, (DWORD)FuncAddr); BuildJmp(&(HookInfo->Stub[CodeLength]), (DWORD)((PBYTE)FuncAddr + CodeLength), (DWORD)((PBYTE)HookInfo->Stub + CodeLength)); // [V1.1] Bug fixed: VirtualProtect Stub CallRet = VirtualProtect(HookInfo->Stub, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect); if (!CallRet) { FuncRet = 4; goto Exit3; } // Set the block of memory could be read and write CallRet = VirtualProtect(FuncAddr, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect); if (!CallRet) { FuncRet = 4; goto Exit3; } // Copy the head of function to stub CallRet = ReadProcessMemory(GetCurrentProcess(), FuncAddr, HookInfo->Stub, CodeLength, &dwTmp); if (!CallRet || dwTmp != CodeLength) { FuncRet = 5; goto Exit3; } // Write hook code back to the head of the function CallRet = WriteProcessMemory(GetCurrentProcess(), FuncAddr, BufAddr, CodeLength, &dwTmp); if (!CallRet || dwTmp != CodeLength) { FuncRet = 6; goto Exit3; } // Make hook stable FlushInstructionCache(GetCurrentProcess(), FuncAddr, CodeLength); VirtualProtect(FuncAddr, CodeLength, OldProtect, &dwTmp); // All done goto Exit2; // Error handle Exit3: free(HookInfo->Stub); Exit2: free (BufAddr); Exit1: return FuncRet; } BOOL HEStopHook(PHOOKINFO HookInfo) { BOOL CallRet; DWORD dwTmp; DWORD OldProtect; LPVOID FuncAddr = HookInfo->FuncAddr; DWORD CodeLength = HookInfo->CodeLength; CallRet = VirtualProtect(FuncAddr, CodeLength, PAGE_EXECUTE_READWRITE, &OldProtect); if (!CallRet) { return 1; } CallRet = WriteProcessMemory(GetCurrentProcess(), FuncAddr, HookInfo->Stub, CodeLength, &dwTmp); if (!CallRet || dwTmp != CodeLength) { return 2; } FlushInstructionCache(GetCurrentProcess(), FuncAddr, CodeLength); VirtualProtect(FuncAddr, CodeLength, OldProtect, &dwTmp); free(HookInfo->Stub); return 0; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "PropertyBag.h" CPropertyBag::CPropertyBag() { } CPropertyBag::~CPropertyBag() { } /////////////////////////////////////////////////////////////////////////////// // IPropertyBag implementation HRESULT STDMETHODCALLTYPE CPropertyBag::Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } VARTYPE vt = pVar->vt; VariantInit(pVar); for (unsigned long i = 0; i < m_PropertyList.GetSize(); i++) { if (wcsicmp(m_PropertyList.GetNameOf(i), pszPropName) == 0) { const VARIANT *pvSrc = m_PropertyList.GetValueOf(i); if (!pvSrc) { return E_FAIL; } CComVariant vNew; HRESULT hr = (vt == VT_EMPTY) ? vNew.Copy(pvSrc) : vNew.ChangeType(vt, pvSrc); if (FAILED(hr)) { return E_FAIL; } // Copy the new value vNew.Detach(pVar); return S_OK; } } // Property does not exist in the bag return E_FAIL; } HRESULT STDMETHODCALLTYPE CPropertyBag::Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } CComBSTR bstrName(pszPropName); m_PropertyList.AddOrReplaceNamedProperty(bstrName, *pVar); return S_OK; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYBAG_H #define PROPERTYBAG_H #include "PropertyList.h" // Object wrapper for property list. This class can be set up with a // list of properties and used to initialise a control with them class CPropertyBag : public CComObjectRootEx<CComSingleThreadModel>, public IPropertyBag { // List of properties in the bag PropertyList m_PropertyList; public: // Constructor CPropertyBag(); // Destructor virtual ~CPropertyBag(); BEGIN_COM_MAP(CPropertyBag) COM_INTERFACE_ENTRY(IPropertyBag) END_COM_MAP() // IPropertyBag methods virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog); virtual HRESULT STDMETHODCALLTYPE Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar); }; typedef CComObject<CPropertyBag> CPropertyBagInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITE_H #define CONTROLSITE_H #include "IOleCommandTargetImpl.h" #include <atlstr.h> #include "PropertyList.h" // Temoporarily removed by bug 200680. Stops controls misbehaving and calling // windowless methods when they shouldn't. // COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteWindowless, IOleInPlaceSiteWindowless) \ // Class that defines the control's security policy with regards to // what controls it hosts etc. class CControlSiteSecurityPolicy { public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid) = 0; // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) = 0; // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) = 0; }; // // Class for hosting an ActiveX control // // This class supports both windowed and windowless classes. The normal // steps to hosting a control are this: // // CControlSiteInstance *pSite = NULL; // CControlSiteInstance::CreateInstance(&pSite); // pSite->AddRef(); // pSite->Create(clsidControlToCreate); // pSite->Attach(hwndParentWindow, rcPosition); // // Where propertyList is a named list of values to initialise the new object // with, hwndParentWindow is the window in which the control is being created, // and rcPosition is the position in window coordinates where the control will // be rendered. // // Destruction is this: // // pSite->Detach(); // pSite->Release(); // pSite = NULL; class CControlSite : public CComObjectRootEx<CComSingleThreadModel>, public IOleClientSite, public IOleInPlaceSiteWindowless, public IOleControlSite, public IAdviseSinkEx, public IDispatch, public IOleCommandTargetImpl<CControlSite>, public IBindStatusCallback, public IWindowForBindingUI { private: // Site management values // Handle to parent window HWND m_hWndParent; // Position of the site and the contained object RECT m_rcObjectPos; // Flag indicating if client site should be set early or late unsigned m_bSetClientSiteFirst:1; // Flag indicating whether control is visible or not unsigned m_bVisibleAtRuntime:1; // Flag indicating if control is in-place active unsigned m_bInPlaceActive:1; // Flag indicating if control is UI active unsigned m_bUIActive:1; // Flag indicating if control is in-place locked and cannot be deactivated unsigned m_bInPlaceLocked:1; // Flag indicating if the site allows windowless controls unsigned m_bSupportWindowlessActivation:1; // Flag indicating if control is windowless (after being created) unsigned m_bWindowless:1; // Flag indicating if only safely scriptable controls are allowed unsigned m_bSafeForScriptingObjectsOnly:1; // Return the default security policy object static CControlSiteSecurityPolicy *GetDefaultControlSecurityPolicy(); // The URL for creating Moniker CString url; friend class CAxHost; protected: // Pointers to object interfaces // Raw pointer to the object CComPtr<IUnknown> m_spObject; // Pointer to objects IViewObject interface CComQIPtr<IViewObject, &IID_IViewObject> m_spIViewObject; // Pointer to object's IOleObject interface CComQIPtr<IOleObject, &IID_IOleObject> m_spIOleObject; // Pointer to object's IOleInPlaceObject interface CComQIPtr<IOleInPlaceObject, &IID_IOleInPlaceObject> m_spIOleInPlaceObject; // Pointer to object's IOleInPlaceObjectWindowless interface CComQIPtr<IOleInPlaceObjectWindowless, &IID_IOleInPlaceObjectWindowless> m_spIOleInPlaceObjectWindowless; // CLSID of the control CComQIPtr<IOleControl> m_spIOleControl; CLSID m_CLSID; // Parameter list PropertyList m_ParameterList; // Pointer to the security policy CControlSiteSecurityPolicy *m_pSecurityPolicy; // Document and Service provider IUnknown *m_spInner; void (*m_spInnerDeallocater)(IUnknown *m_spInner); // Binding variables // Flag indicating whether binding is in progress unsigned m_bBindingInProgress; // Result from the binding operation HRESULT m_hrBindResult; // Double buffer drawing variables used for windowless controls // Area of buffer RECT m_rcBuffer; // Bitmap to buffer HBITMAP m_hBMBuffer; // Bitmap to buffer HBITMAP m_hBMBufferOld; // Device context HDC m_hDCBuffer; // Clipping area of site HRGN m_hRgnBuffer; // Flags indicating how the buffer was painted DWORD m_dwBufferFlags; // The last control size passed by GetExtent SIZEL m_currentSize; // Ambient properties // Locale ID LCID m_nAmbientLocale; // Foreground colour COLORREF m_clrAmbientForeColor; // Background colour COLORREF m_clrAmbientBackColor; // Flag indicating if control should hatch itself bool m_bAmbientShowHatching:1; // Flag indicating if control should have grab handles bool m_bAmbientShowGrabHandles:1; // Flag indicating if control is in edit/user mode bool m_bAmbientUserMode:1; // Flag indicating if control has a 3d border or not bool m_bAmbientAppearance:1; // Flag indicating if the size passed in is different from the control. bool m_needUpdateContainerSize:1; protected: // Notifies the attached control of a change to an ambient property virtual void FireAmbientPropertyChange(DISPID id); public: // Construction and destruction // Constructor CControlSite(); // Destructor virtual ~CControlSite(); BEGIN_COM_MAP(CControlSite) COM_INTERFACE_ENTRY(IOleWindow) COM_INTERFACE_ENTRY(IOleClientSite) COM_INTERFACE_ENTRY(IOleInPlaceSite) COM_INTERFACE_ENTRY(IOleInPlaceSiteWindowless) COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSite, IOleInPlaceSiteWindowless) COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteEx, IOleInPlaceSiteWindowless) COM_INTERFACE_ENTRY(IOleControlSite) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_IID(IID_IAdviseSink, IAdviseSinkEx) COM_INTERFACE_ENTRY_IID(IID_IAdviseSink2, IAdviseSinkEx) COM_INTERFACE_ENTRY_IID(IID_IAdviseSinkEx, IAdviseSinkEx) COM_INTERFACE_ENTRY(IOleCommandTarget) COM_INTERFACE_ENTRY(IBindStatusCallback) COM_INTERFACE_ENTRY(IWindowForBindingUI) COM_INTERFACE_ENTRY_AGGREGATE_BLIND(m_spInner) END_COM_MAP() BEGIN_OLECOMMAND_TABLE() END_OLECOMMAND_TABLE() // Returns the window used when processing ole commands HWND GetCommandTargetWindow() { return NULL; // TODO } // Object creation and management functions // Creates and initialises an object virtual HRESULT Create(REFCLSID clsid, PropertyList &pl = PropertyList(), LPCWSTR szCodebase = NULL, IBindCtx *pBindContext = NULL); // Attaches the object to the site virtual HRESULT Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream = NULL); // Detaches the object from the site virtual HRESULT Detach(); // Returns the IUnknown pointer for the object virtual HRESULT GetControlUnknown(IUnknown **ppObject); // Sets the bounding rectangle for the object virtual HRESULT SetPosition(const RECT &rcPos); // Draws the object using the provided DC virtual HRESULT Draw(HDC hdc); // Performs the specified action on the object virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL); // Sets an advise sink up for changes to the object virtual HRESULT Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie); // Removes an advise sink virtual HRESULT Unadvise(const IID &iid, DWORD dwCookie); // Get the control size, in pixels. virtual HRESULT GetControlSize(LPSIZEL size); // Set the control size, in pixels. virtual HRESULT SetControlSize(const LPSIZEL size, LPSIZEL out); void SetUrl(BSTR url); void SetInnerWindow(IUnknown *unk, void (*Deleter)(IUnknown *unk)) { m_spInner = unk; m_spInnerDeallocater = Deleter; } // Set the security policy object. Ownership of this object remains with the caller and the security // policy object is meant to exist for as long as it is set here. virtual void SetSecurityPolicy(CControlSiteSecurityPolicy *pSecurityPolicy) { m_pSecurityPolicy = pSecurityPolicy; } virtual CControlSiteSecurityPolicy *GetSecurityPolicy() const { return m_pSecurityPolicy; } // Methods to set ambient properties virtual void SetAmbientUserMode(BOOL bUser); // Inline helper methods // Returns the object's CLSID virtual const CLSID &GetObjectCLSID() const { return m_CLSID; } // Tests if the object is valid or not virtual BOOL IsObjectValid() const { return (m_spObject) ? TRUE : FALSE; } // Returns the parent window to this one virtual HWND GetParentWindow() const { return m_hWndParent; } // Returns the inplace active state of the object virtual BOOL IsInPlaceActive() const { return m_bInPlaceActive; } // Returns the m_bVisibleAtRuntime virtual BOOL IsVisibleAtRuntime() const { return m_bVisibleAtRuntime; } // Return and reset m_needUpdateContainerSize virtual BOOL CheckAndResetNeedUpdateContainerSize() { BOOL ret = m_needUpdateContainerSize; m_needUpdateContainerSize = false; return ret; } // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); // IAdviseSink implementation virtual /* [local] */ void STDMETHODCALLTYPE OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed); virtual /* [local] */ void STDMETHODCALLTYPE OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex); virtual /* [local] */ void STDMETHODCALLTYPE OnRename(/* [in] */ IMoniker __RPC_FAR *pmk); virtual /* [local] */ void STDMETHODCALLTYPE OnSave(void); virtual /* [local] */ void STDMETHODCALLTYPE OnClose(void); // IAdviseSink2 virtual /* [local] */ void STDMETHODCALLTYPE OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk); // IAdviseSinkEx implementation virtual /* [local] */ void STDMETHODCALLTYPE OnViewStatusChange(/* [in] */ DWORD dwViewStatus); // IOleWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleClientSite implementation virtual HRESULT STDMETHODCALLTYPE SaveObject(void); virtual HRESULT STDMETHODCALLTYPE GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk); virtual HRESULT STDMETHODCALLTYPE GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer); virtual HRESULT STDMETHODCALLTYPE ShowObject(void); virtual HRESULT STDMETHODCALLTYPE OnShowWindow(/* [in] */ BOOL fShow); virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void); // IOleInPlaceSite implementation virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void); virtual HRESULT STDMETHODCALLTYPE GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo); virtual HRESULT STDMETHODCALLTYPE Scroll(/* [in] */ SIZE scrollExtant); virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate(/* [in] */ BOOL fUndoable); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void); virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void); virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void); virtual HRESULT STDMETHODCALLTYPE OnPosRectChange(/* [in] */ LPCRECT lprcPosRect); // IOleInPlaceSiteEx implementation virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw); virtual HRESULT STDMETHODCALLTYPE RequestUIActivate(void); // IOleInPlaceSiteWindowless implementation virtual HRESULT STDMETHODCALLTYPE CanWindowlessActivate(void); virtual HRESULT STDMETHODCALLTYPE GetCapture(void); virtual HRESULT STDMETHODCALLTYPE SetCapture(/* [in] */ BOOL fCapture); virtual HRESULT STDMETHODCALLTYPE GetFocus(void); virtual HRESULT STDMETHODCALLTYPE SetFocus(/* [in] */ BOOL fFocus); virtual HRESULT STDMETHODCALLTYPE GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC); virtual HRESULT STDMETHODCALLTYPE ReleaseDC(/* [in] */ HDC hDC); virtual HRESULT STDMETHODCALLTYPE InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip); virtual HRESULT STDMETHODCALLTYPE AdjustRect(/* [out][in] */ LPRECT prc); virtual HRESULT STDMETHODCALLTYPE OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult); // IOleControlSite implementation virtual HRESULT STDMETHODCALLTYPE OnControlInfoChanged(void); virtual HRESULT STDMETHODCALLTYPE LockInPlaceActive(/* [in] */ BOOL fLock); virtual HRESULT STDMETHODCALLTYPE GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp); virtual HRESULT STDMETHODCALLTYPE TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers); virtual HRESULT STDMETHODCALLTYPE OnFocus(/* [in] */ BOOL fGotFocus); virtual HRESULT STDMETHODCALLTYPE ShowPropertyFrame( void); // IBindStatusCallback virtual HRESULT STDMETHODCALLTYPE OnStartBinding(/* [in] */ DWORD dwReserved, /* [in] */ IBinding __RPC_FAR *pib); virtual HRESULT STDMETHODCALLTYPE GetPriority(/* [out] */ LONG __RPC_FAR *pnPriority); virtual HRESULT STDMETHODCALLTYPE OnLowResource(/* [in] */ DWORD reserved); virtual HRESULT STDMETHODCALLTYPE OnProgress(/* [in] */ ULONG ulProgress, /* [in] */ ULONG ulProgressMax, /* [in] */ ULONG ulStatusCode, /* [in] */ LPCWSTR szStatusText); virtual HRESULT STDMETHODCALLTYPE OnStopBinding(/* [in] */ HRESULT hresult, /* [unique][in] */ LPCWSTR szError); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindInfo( /* [out] */ DWORD __RPC_FAR *grfBINDF, /* [unique][out][in] */ BINDINFO __RPC_FAR *pbindinfo); virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnDataAvailable(/* [in] */ DWORD grfBSCF, /* [in] */ DWORD dwSize, /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ STGMEDIUM __RPC_FAR *pstgmed); virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(/* [in] */ REFIID riid, /* [iid_is][in] */ IUnknown __RPC_FAR *punk); // IWindowForBindingUI virtual HRESULT STDMETHODCALLTYPE GetWindow(/* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd); }; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "ItemContainer.h" CItemContainer::CItemContainer() { } CItemContainer::~CItemContainer() { } /////////////////////////////////////////////////////////////////////////////// // IParseDisplayName implementation HRESULT STDMETHODCALLTYPE CItemContainer::ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut) { // TODO return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum) { HRESULT hr = E_NOTIMPL; /* if (ppenum == NULL) { return E_POINTER; } *ppenum = NULL; typedef CComObject<CComEnumOnSTL<IEnumUnknown, &IID_IEnumUnknown, IUnknown*, _CopyInterface<IUnknown>, CNamedObjectList > > enumunk; enumunk* p = NULL; p = new enumunk; if(p == NULL) { return E_OUTOFMEMORY; } hr = p->Init(); if (SUCCEEDED(hr)) { hr = p->QueryInterface(IID_IEnumUnknown, (void**) ppenum); } if (FAILED(hRes)) { delete p; } */ return hr; } HRESULT STDMETHODCALLTYPE CItemContainer::LockContainer(/* [in] */ BOOL fLock) { // TODO return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleItemContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject) { if (pszItem == NULL) { return E_INVALIDARG; } if (ppvObject == NULL) { return E_INVALIDARG; } *ppvObject = NULL; return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage) { // TODO return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::IsRunning(/* [in] */ LPOLESTR pszItem) { // TODO return MK_E_NOOBJECT; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLEVENTSINK_H #define CONTROLEVENTSINK_H #include <map> // This class listens for events from the specified control class CControlEventSink : public CComObjectRootEx<CComSingleThreadModel>, public IDispatch { public: CControlEventSink(); // Current event connection point CComPtr<IConnectionPoint> m_spEventCP; CComPtr<ITypeInfo> m_spEventSinkTypeInfo; DWORD m_dwEventCookie; IID m_EventIID; typedef std::map<DISPID, wchar_t *> EventMap; EventMap events; NPP instance; protected: virtual ~CControlEventSink(); bool m_bSubscribed; static HRESULT WINAPI SinkQI(void* pv, REFIID riid, LPVOID* ppv, DWORD dw) { CControlEventSink *pThis = (CControlEventSink *) pv; if (!IsEqualIID(pThis->m_EventIID, GUID_NULL) && IsEqualIID(pThis->m_EventIID, riid)) { return pThis->QueryInterface(__uuidof(IDispatch), ppv); } return E_NOINTERFACE; } public: BEGIN_COM_MAP(CControlEventSink) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_FUNC_BLIND(0, SinkQI) END_COM_MAP() virtual HRESULT SubscribeToEvents(IUnknown *pControl); virtual void UnsubscribeFromEvents(); virtual BOOL GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo); virtual HRESULT InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); }; typedef CComObject<CControlEventSink> CControlEventSinkInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "stdafx.h" #include "ControlSiteIPFrame.h" CControlSiteIPFrame::CControlSiteIPFrame() { m_hwndFrame = NULL; } CControlSiteIPFrame::~CControlSiteIPFrame() { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { if (phwnd == NULL) { return E_INVALIDARG; } *phwnd = m_hwndFrame; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceUIWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceFrame implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID) { ATLTRACE("Not implemnted"); return E_NOTIMPL; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #if !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_) #define AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // under MSVC shut off copious warnings about debug symbol too long #ifdef _MSC_VER #pragma warning( disable: 4786 ) #endif //#include "jstypes.h" //#include "prtypes.h" // Mozilla headers //#include "jscompat.h" //#include "prthread.h" //#include "prprf.h" //#include "nsID.h" //#include "nsIComponentManager.h" //#include "nsIServiceManager.h" //#include "nsStringAPI.h" //#include "nsCOMPtr.h" //#include "nsComponentManagerUtils.h" //#include "nsServiceManagerUtils.h" //#include "nsIDocument.h" //#include "nsIDocumentObserver.h" //#include "nsVoidArray.h" //#include "nsIDOMNode.h" //#include "nsIDOMNodeList.h" //#include "nsIDOMDocument.h" //#include "nsIDOMDocumentType.h" //#include "nsIDOMElement.h" //#undef _WIN32_WINNT //#define _WIN32_WINNT 0x0400 #define _ATL_APARTMENT_THREADED //#define _ATL_STATIC_REGISTRY // #define _ATL_DEBUG_INTERFACES // ATL headers // The ATL headers that come with the platform SDK have bad for scoping #if _MSC_VER >= 1400 #pragma conform(forScope, push, atlhack, off) #endif #include <atlbase.h> //You may derive a class from CComModule and use it if you want to override //something, but do not change the name of _Module extern CComModule _Module; #include <atlcom.h> #include <atlctl.h> #if _MSC_VER >= 1400 #pragma conform(forScope, pop, atlhack) #endif #include <mshtml.h> #include <mshtmhst.h> #include <docobj.h> //#include <winsock2.h> #include <comdef.h> #include <vector> #include <list> #include <string> // New winsock2.h doesn't define this anymore typedef long int32; #define NS_SCRIPTABLE #include "nscore.h" #include "npapi.h" //#include "npupp.h" #include "npfunctions.h" #include "nsID.h" #include <npruntime.h> #include "../variants.h" #include "PropertyList.h" #include "PropertyBag.h" #include "ItemContainer.h" #include "ControlSite.h" #include "ControlSiteIPFrame.h" #include "ControlEventSink.h" extern NPNetscapeFuncs NPNFuncs; // Turn off warnings about debug symbols for templates being too long #pragma warning(disable : 4786) #define TRACE_METHOD(fn) \ { \ ATLTRACE(_T("0x%04x %s()\n"), (int) GetCurrentThreadId(), _T(#fn)); \ } #define TRACE_METHOD_ARGS(fn, pattern, args) \ { \ ATLTRACE(_T("0x%04x %s(") _T(pattern) _T(")\n"), (int) GetCurrentThreadId(), _T(#fn), args); \ } //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #define NS_ASSERTION(x, y) #endif // !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED)
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "../npactivex.h" #include "ControlEventSink.h" CControlEventSink::CControlEventSink() : m_dwEventCookie(0), m_bSubscribed(false), m_EventIID(GUID_NULL), events() { } CControlEventSink::~CControlEventSink() { UnsubscribeFromEvents(); } BOOL CControlEventSink::GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo) { iid = GUID_NULL; if (!pControl) { return FALSE; } // IProvideClassInfo2 way is easiest // CComQIPtr<IProvideClassInfo2> classInfo2 = pControl; // if (classInfo2) // { // classInfo2->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid); // if (!::IsEqualIID(iid, GUID_NULL)) // { // return TRUE; // } // } // Yuck, the hard way CComQIPtr<IProvideClassInfo> classInfo = pControl; if (!classInfo) { np_log(instance, 0, "no classInfo"); return FALSE; } // Search the class type information for the default source interface // which is the outgoing event sink. CComPtr<ITypeInfo> classTypeInfo; classInfo->GetClassInfo(&classTypeInfo); if (!classTypeInfo) { np_log(instance, 0, "noclassTypeinfo"); return FALSE; } TYPEATTR *classAttr = NULL; if (FAILED(classTypeInfo->GetTypeAttr(&classAttr))) { np_log(instance, 0, "noclassTypeinfo->GetTypeAttr"); return FALSE; } INT implFlags = 0; for (UINT i = 0; i < classAttr->cImplTypes; i++) { // Search for the interface with the [default, source] attr if (SUCCEEDED(classTypeInfo->GetImplTypeFlags(i, &implFlags)) && implFlags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE)) { CComPtr<ITypeInfo> eventSinkTypeInfo; HREFTYPE hRefType; if (SUCCEEDED(classTypeInfo->GetRefTypeOfImplType(i, &hRefType)) && SUCCEEDED(classTypeInfo->GetRefTypeInfo(hRefType, &eventSinkTypeInfo))) { TYPEATTR *eventSinkAttr = NULL; if (SUCCEEDED(eventSinkTypeInfo->GetTypeAttr(&eventSinkAttr))) { iid = eventSinkAttr->guid; if (typeInfo) { *typeInfo = eventSinkTypeInfo.p; (*typeInfo)->AddRef(); } eventSinkTypeInfo->ReleaseTypeAttr(eventSinkAttr); } } break; } } classTypeInfo->ReleaseTypeAttr(classAttr); return (!::IsEqualIID(iid, GUID_NULL)); } void CControlEventSink::UnsubscribeFromEvents() { if (m_bSubscribed) { DWORD tmpCookie = m_dwEventCookie; m_dwEventCookie = 0; m_bSubscribed = false; // Unsubscribe and reset - This seems to complete release and destroy us... m_spEventCP->Unadvise(tmpCookie); // Unadvise handles the Release m_spEventCP.Release(); } else { m_spEventCP.Release(); } } HRESULT CControlEventSink::SubscribeToEvents(IUnknown *pControl) { if (!pControl) { np_log(instance, 0, "not valid control"); return E_INVALIDARG; } // Throw away any existing connections UnsubscribeFromEvents(); // Grab the outgoing event sink IID which will be used to subscribe // to events via the connection point container. IID iidEventSink; CComPtr<ITypeInfo> typeInfo; if (!GetEventSinkIID(pControl, iidEventSink, &typeInfo)) { np_log(instance, 0, "Can't get event sink iid"); return E_FAIL; } // Get the connection point CComQIPtr<IConnectionPointContainer> ccp = pControl; CComPtr<IConnectionPoint> cp; if (!ccp) { np_log(instance, 0, "not valid ccp"); return E_FAIL; } // Custom IID m_EventIID = iidEventSink; DWORD dwCookie = 0;/* CComPtr<IEnumConnectionPoints> e; ccp->EnumConnectionPoints(&e); e->Next(1, &cp, &dwCookie);*/ if (FAILED(ccp->FindConnectionPoint(m_EventIID, &cp))) { np_log(instance, 0, "failed to find connection point"); return E_FAIL; } if (FAILED(cp->Advise(this, &dwCookie))) { np_log(instance, 0, "failed to advise"); return E_FAIL; } m_bSubscribed = true; m_spEventCP = cp; m_dwEventCookie = dwCookie; m_spEventSinkTypeInfo = typeInfo; return S_OK; } HRESULT CControlEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { USES_CONVERSION; if (DISPATCH_METHOD != wFlags) { // any other reason to call us?! return S_FALSE; } EventMap::iterator cur = events.find(dispIdMember); if (events.end() != cur) { // invoke this event handler NPVariant result; NPVariant *args = NULL; if (pDispParams->cArgs > 0) { args = (NPVariant *)calloc(pDispParams->cArgs, sizeof(NPVariant)); if (!args) { return S_FALSE; } for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments in reverse order Variant2NPVar(&pDispParams->rgvarg[i], &args[pDispParams->cArgs - i - 1], instance); } } NPObject *globalObj = NULL; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); NPIdentifier handler = NPNFuncs.getstringidentifier(W2A((*cur).second)); bool success = NPNFuncs.invoke(instance, globalObj, handler, args, pDispParams->cArgs, &result); NPNFuncs.releaseobject(globalObj); for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments if (args[i].type == NPVariantType_String) { // was allocated earlier by Variant2NPVar NPNFuncs.memfree((void *)args[i].value.stringValue.UTF8Characters); } } if (!success) { return S_FALSE; } if (pVarResult) { // set the result NPVar2Variant(&result, pVarResult, instance); } NPNFuncs.releasevariantvalue(&result); } return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * Brent Booker * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include <Objsafe.h> #include "ControlSite.h" #include "PropertyBag.h" #include "ControlSiteIPFrame.h" class CDefaultControlSiteSecurityPolicy : public CControlSiteSecurityPolicy { // Test if the specified class id implements the specified category BOOL ClassImplementsCategory(const CLSID & clsid, const CATID &catid, BOOL &bClassExists); public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid); // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid); }; BOOL CDefaultControlSiteSecurityPolicy::ClassImplementsCategory(const CLSID &clsid, const CATID &catid, BOOL &bClassExists) { bClassExists = FALSE; // Test if there is a CLSID entry. If there isn't then obviously // the object doesn't exist and therefore doesn't implement any category. // In this situation, the function returns REGDB_E_CLASSNOTREG. CRegKey key; if (key.Open(HKEY_CLASSES_ROOT, _T("CLSID"), KEY_READ) != ERROR_SUCCESS) { // Must fail if we can't even open this! return FALSE; } LPOLESTR szCLSID = NULL; if (FAILED(StringFromCLSID(clsid, &szCLSID))) { return FALSE; } USES_CONVERSION; CRegKey keyCLSID; LONG lResult = keyCLSID.Open(key, W2CT(szCLSID), KEY_READ); CoTaskMemFree(szCLSID); if (lResult != ERROR_SUCCESS) { // Class doesn't exist return FALSE; } keyCLSID.Close(); // CLSID exists, so try checking what categories it implements bClassExists = TRUE; CComQIPtr<ICatInformation> spCatInfo; HRESULT hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (LPVOID*) &spCatInfo); if (spCatInfo == NULL) { // Must fail if we can't open the category manager return FALSE; } // See what categories the class implements CComQIPtr<IEnumCATID> spEnumCATID; if (FAILED(spCatInfo->EnumImplCategoriesOfClass(clsid, &spEnumCATID))) { // Can't enumerate classes in category so fail return FALSE; } // Search for matching categories BOOL bFound = FALSE; CATID catidNext = GUID_NULL; while (spEnumCATID->Next(1, &catidNext, NULL) == S_OK) { if (::IsEqualCATID(catid, catidNext)) { return TRUE; } } return FALSE; } // Test if the class is safe to host BOOL CDefaultControlSiteSecurityPolicy::IsClassSafeToHost(const CLSID & clsid) { return TRUE; } // Test if the specified class is marked safe for scripting BOOL CDefaultControlSiteSecurityPolicy::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) { // Test the category the object belongs to return ClassImplementsCategory(clsid, CATID_SafeForScripting, bClassExists); } // Test if the instantiated object is safe for scripting on the specified interface BOOL CDefaultControlSiteSecurityPolicy::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) { if (!pObject) { return FALSE; } // Ask the control if its safe for scripting CComQIPtr<IObjectSafety> spObjectSafety = pObject; if (!spObjectSafety) { return FALSE; } DWORD dwSupported = 0; // Supported options (mask) DWORD dwEnabled = 0; // Enabled options // Assume scripting via IDispatch, now we doesn't support IDispatchEx if (SUCCEEDED(spObjectSafety->GetInterfaceSafetyOptions( iid, &dwSupported, &dwEnabled))) { if (dwEnabled & dwSupported & INTERFACESAFE_FOR_UNTRUSTED_CALLER) { // Object is safe return TRUE; } } // Set it to support untrusted caller. if(FAILED(spObjectSafety->SetInterfaceSafetyOptions( iid, INTERFACESAFE_FOR_UNTRUSTED_CALLER, INTERFACESAFE_FOR_UNTRUSTED_CALLER))) { return FALSE; } return TRUE; } /////////////////////////////////////////////////////////////////////////////// // Constructor CControlSite::CControlSite() { TRACE_METHOD(CControlSite::CControlSite); m_hWndParent = NULL; m_CLSID = CLSID_NULL; m_bSetClientSiteFirst = FALSE; m_bVisibleAtRuntime = TRUE; memset(&m_rcObjectPos, 0, sizeof(m_rcObjectPos)); m_bInPlaceActive = FALSE; m_bUIActive = FALSE; m_bInPlaceLocked = FALSE; m_bWindowless = FALSE; m_bSupportWindowlessActivation = TRUE; m_bSafeForScriptingObjectsOnly = FALSE; m_pSecurityPolicy = GetDefaultControlSecurityPolicy(); // Initialise ambient properties m_nAmbientLocale = 0; m_clrAmbientForeColor = ::GetSysColor(COLOR_WINDOWTEXT); m_clrAmbientBackColor = ::GetSysColor(COLOR_WINDOW); m_bAmbientUserMode = true; m_bAmbientShowHatching = true; m_bAmbientShowGrabHandles = true; m_bAmbientAppearance = true; // 3d // Windowless variables m_hDCBuffer = NULL; m_hRgnBuffer = NULL; m_hBMBufferOld = NULL; m_hBMBuffer = NULL; m_spInner = NULL; m_needUpdateContainerSize = false; m_currentSize.cx = m_currentSize.cy = -1; } // Destructor CControlSite::~CControlSite() { TRACE_METHOD(CControlSite::~CControlSite); Detach(); if (m_spInner && m_spInnerDeallocater) { m_spInnerDeallocater(m_spInner); } } // Create the specified control, optionally providing properties to initialise // it with and a name. HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl, LPCWSTR szCodebase, IBindCtx *pBindContext) { TRACE_METHOD(CControlSite::Create); m_CLSID = clsid; m_ParameterList = pl; // See if security policy will allow the control to be hosted if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid)) { return E_FAIL; } // See if object is script safe BOOL checkForObjectSafety = FALSE; if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly) { BOOL bClassExists = FALSE; BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists); if (!bClassExists && szCodebase) { // Class doesn't exist, so allow code below to fetch it } else if (!bIsSafe) { // The class is not flagged as safe for scripting, so // we'll have to create it to ask it if its safe. checkForObjectSafety = TRUE; } } //Now Check if the control version needs to be updated. BOOL bUpdateControlVersion = FALSE; wchar_t *szURL = NULL; DWORD dwFileVersionMS = 0xffffffff; DWORD dwFileVersionLS = 0xffffffff; if(szCodebase) { HKEY hk = NULL; wchar_t wszKey[60] = L""; wchar_t wszData[MAX_PATH]; LPWSTR pwszClsid = NULL; DWORD dwSize = 255; DWORD dwHandle, dwLength, dwRegReturn; DWORD dwExistingFileVerMS = 0xffffffff; DWORD dwExistingFileVerLS = 0xffffffff; BOOL bFoundLocalVerInfo = FALSE; StringFromCLSID(clsid, (LPOLESTR*)&pwszClsid); swprintf(wszKey, L"%s%s%s\0", L"CLSID\\", pwszClsid, L"\\InprocServer32"); if ( RegOpenKeyExW( HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hk ) == ERROR_SUCCESS ) { dwRegReturn = RegQueryValueExW( hk, L"", NULL, NULL, (LPBYTE)wszData, &dwSize ); RegCloseKey( hk ); } if(dwRegReturn == ERROR_SUCCESS) { VS_FIXEDFILEINFO *pFileInfo; UINT uLen; dwLength = GetFileVersionInfoSizeW( wszData , &dwHandle ); LPBYTE lpData = new BYTE[dwLength]; GetFileVersionInfoW(wszData, 0, dwLength, lpData ); bFoundLocalVerInfo = VerQueryValueW( lpData, L"\\", (LPVOID*)&pFileInfo, &uLen ); if(bFoundLocalVerInfo) { dwExistingFileVerMS = pFileInfo->dwFileVersionMS; dwExistingFileVerLS = pFileInfo->dwFileVersionLS; } delete [] lpData; } // Test if the code base ends in #version=a,b,c,d const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#')); if (szHash) { if (wcsnicmp(szHash, L"#version=", 9) == 0) { int a, b, c, d; if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4) { dwFileVersionMS = MAKELONG(b,a); dwFileVersionLS = MAKELONG(d,c); //If local version info was found compare it if(bFoundLocalVerInfo) { if(dwFileVersionMS > dwExistingFileVerMS) bUpdateControlVersion = TRUE; if((dwFileVersionMS == dwExistingFileVerMS) && (dwFileVersionLS > dwExistingFileVerLS)) bUpdateControlVersion = TRUE; } } } szURL = _wcsdup(szCodebase); // Terminate at the hash mark if (szURL) szURL[szHash - szCodebase] = wchar_t('\0'); } else { szURL = _wcsdup(szCodebase); } } CComPtr<IUnknown> spObject; HRESULT hr; //If the control needs to be updated do not call CoCreateInstance otherwise you will lock files //and force a reboot on CoGetClassObjectFromURL if(!bUpdateControlVersion) { // Create the object hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject); if (SUCCEEDED(hr) && checkForObjectSafety) { m_bSafeForScriptingObjectsOnly = m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch)); // Drop through, success! } } // Do we need to download the control? if ((FAILED(hr) && szCodebase) || (bUpdateControlVersion)) { if (!szURL) return E_OUTOFMEMORY; CComPtr<IBindCtx> spBindContext; CComPtr<IBindStatusCallback> spBindStatusCallback; CComPtr<IBindStatusCallback> spOldBSC; // Create our own bind context or use the one provided? BOOL useInternalBSC = FALSE; if (!pBindContext) { useInternalBSC = TRUE; hr = CreateBindCtx(0, &spBindContext); if (FAILED(hr)) { free(szURL); return hr; } spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this); hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0); if (FAILED(hr)) { free(szURL); return hr; } } else { spBindContext = pBindContext; } //If the version from the CODEBASE value is greater than the installed control //Call CoGetClassObjectFromURL with CLSID_NULL to prevent system change reboot prompt if(bUpdateControlVersion) { hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS, NULL, spBindContext, CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_SERVER, 0, IID_IClassFactory, NULL); } else { hr = CoGetClassObjectFromURL(CLSID_NULL, szURL, dwFileVersionMS, dwFileVersionLS, NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown, NULL); } free(szURL); // Handle the internal binding synchronously so the object exists // or an error code is available when the method returns. if (useInternalBSC) { if (MK_S_ASYNCHRONOUS == hr) { m_bBindingInProgress = TRUE; m_hrBindResult = E_FAIL; // Spin around waiting for binding to complete HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); while (m_bBindingInProgress) { MSG msg; // Process pending messages while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (!::GetMessage(&msg, NULL, 0, 0)) { m_bBindingInProgress = FALSE; break; } ::TranslateMessage(&msg); ::DispatchMessage(&msg); } if (!m_bBindingInProgress) break; // Sleep for a bit or the next msg to appear ::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS); } ::CloseHandle(hFakeEvent); // Set the result hr = m_hrBindResult; } // Destroy the bind status callback & context if (spBindStatusCallback) { RevokeBindStatusCallback(spBindContext, spBindStatusCallback); spBindStatusCallback.Release(); spBindContext.Release(); } } //added to create control if (SUCCEEDED(hr)) { // Create the object hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject); if (SUCCEEDED(hr) && checkForObjectSafety) { // Assume scripting via IDispatch m_bSafeForScriptingObjectsOnly = m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch)); } } //EOF test code } if (spObject) { m_spObject = spObject; CComQIPtr<IObjectWithSite> site = m_spObject; if (site) { site->SetSite(GetUnknown()); } } return hr; } // Attach the created control to a window and activate it HRESULT CControlSite::Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream) { TRACE_METHOD(CControlSite::Attach); if (hwndParent == NULL) { NS_ASSERTION(0, "No parent hwnd"); return E_INVALIDARG; } m_hWndParent = hwndParent; m_rcObjectPos = rcPos; // Object must have been created if (m_spObject == NULL) { return E_UNEXPECTED; } m_spIOleControl = m_spObject; m_spIViewObject = m_spObject; m_spIOleObject = m_spObject; if (m_spIOleObject == NULL) { return E_FAIL; } if (m_spIOleControl) { m_spIOleControl->FreezeEvents(true); } DWORD dwMiscStatus; m_spIOleObject->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus); if (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST) { m_bSetClientSiteFirst = TRUE; } if (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME) { m_bVisibleAtRuntime = FALSE; } // Some objects like to have the client site as the first thing // to be initialised (for ambient properties and so forth) if (m_bSetClientSiteFirst) { m_spIOleObject->SetClientSite(this); } // If there is a parameter list for the object and no init stream then // create one here. CPropertyBagInstance *pPropertyBag = NULL; if (pInitStream == NULL && m_ParameterList.GetSize() > 0) { CPropertyBagInstance::CreateInstance(&pPropertyBag); pPropertyBag->AddRef(); for (unsigned long i = 0; i < m_ParameterList.GetSize(); i++) { pPropertyBag->Write(m_ParameterList.GetNameOf(i), const_cast<VARIANT *>(m_ParameterList.GetValueOf(i))); } pInitStream = (IPersistPropertyBag *) pPropertyBag; } // Initialise the control from store if one is provided if (pInitStream) { CComQIPtr<IPropertyBag, &IID_IPropertyBag> spPropertyBag = pInitStream; CComQIPtr<IStream, &IID_IStream> spStream = pInitStream; CComQIPtr<IPersistStream, &IID_IPersistStream> spIPersistStream = m_spIOleObject; CComQIPtr<IPersistPropertyBag, &IID_IPersistPropertyBag> spIPersistPropertyBag = m_spIOleObject; if (spIPersistPropertyBag && spPropertyBag) { spIPersistPropertyBag->Load(spPropertyBag, NULL); } else if (spIPersistStream && spStream) { spIPersistStream->Load(spStream); } } else { // Initialise the object if possible CComQIPtr<IPersistStreamInit, &IID_IPersistStreamInit> spIPersistStreamInit = m_spIOleObject; if (spIPersistStreamInit) { spIPersistStreamInit->InitNew(); } } SIZEL size, sizein; sizein.cx = m_rcObjectPos.right - m_rcObjectPos.left; sizein.cy = m_rcObjectPos.bottom - m_rcObjectPos.top; SetControlSize(&sizein, &size); m_rcObjectPos.right = m_rcObjectPos.left + size.cx; m_rcObjectPos.bottom = m_rcObjectPos.top + size.cy; m_spIOleInPlaceObject = m_spObject; if (m_spIOleControl) { m_spIOleControl->FreezeEvents(false); } // In-place activate the object if (m_bVisibleAtRuntime) { DoVerb(OLEIVERB_INPLACEACTIVATE); } m_spIOleInPlaceObjectWindowless = m_spObject; // For those objects which haven't had their client site set yet, // it's done here. if (!m_bSetClientSiteFirst) { m_spIOleObject->SetClientSite(this); } return S_OK; } // Set the control size, in pixels. HRESULT CControlSite::SetControlSize(const LPSIZEL size, LPSIZEL out) { if (!size || !out) { return E_POINTER; } if (!m_spIOleObject) { return E_FAIL; } SIZEL szInitialHiMetric, szCustomHiMetric, szFinalHiMetric; SIZEL szCustomPixel, szFinalPixel; szFinalPixel = *size; szCustomPixel = *size; if (m_currentSize.cx == size->cx && m_currentSize.cy == size->cy) { // Don't need to change. return S_OK; } if (SUCCEEDED(m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szInitialHiMetric))) { if (m_currentSize.cx == -1 && szCustomPixel.cx == 300 && szCustomPixel.cy == 150) { szFinalHiMetric = szInitialHiMetric; } else { AtlPixelToHiMetric(&szCustomPixel, &szCustomHiMetric); szFinalHiMetric = szCustomHiMetric; } } if (SUCCEEDED(m_spIOleObject->SetExtent(DVASPECT_CONTENT, &szFinalHiMetric))) { if (SUCCEEDED(m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szFinalHiMetric))) { AtlHiMetricToPixel(&szFinalHiMetric, &szFinalPixel); } } m_currentSize = szFinalPixel; if (szCustomPixel.cx != szFinalPixel.cx && szCustomPixel.cy != szFinalPixel.cy) { m_needUpdateContainerSize = true; } *out = szFinalPixel; return S_OK; } // Unhook the control from the window and throw it all away HRESULT CControlSite::Detach() { TRACE_METHOD(CControlSite::Detach); if (m_spIOleInPlaceObjectWindowless) { m_spIOleInPlaceObjectWindowless.Release(); } CComQIPtr<IObjectWithSite> site = m_spObject; if (site) { site->SetSite(NULL); } if (m_spIOleInPlaceObject) { m_spIOleInPlaceObject->InPlaceDeactivate(); m_spIOleInPlaceObject.Release(); } if (m_spIOleObject) { m_spIOleObject->Close(OLECLOSE_NOSAVE); m_spIOleObject->SetClientSite(NULL); m_spIOleObject.Release(); } m_spIViewObject.Release(); m_spObject.Release(); return S_OK; } // Return the IUnknown of the contained control HRESULT CControlSite::GetControlUnknown(IUnknown **ppObject) { *ppObject = NULL; if (m_spObject) { m_spObject->QueryInterface(IID_IUnknown, (void **) ppObject); return S_OK; } else { return E_FAIL; } } // Subscribe to an event sink on the control HRESULT CControlSite::Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie) { if (m_spObject == NULL) { return E_UNEXPECTED; } if (pIUnkSink == NULL || pdwCookie == NULL) { return E_INVALIDARG; } return AtlAdvise(m_spObject, pIUnkSink, iid, pdwCookie); } // Unsubscribe event sink from the control HRESULT CControlSite::Unadvise(const IID &iid, DWORD dwCookie) { if (m_spObject == NULL) { return E_UNEXPECTED; } return AtlUnadvise(m_spObject, iid, dwCookie); } // Draw the control HRESULT CControlSite::Draw(HDC hdc) { TRACE_METHOD(CControlSite::Draw); // Draw only when control is windowless or deactivated if (m_spIViewObject) { if (m_bWindowless || !m_bInPlaceActive) { RECTL *prcBounds = (m_bWindowless) ? NULL : (RECTL *) &m_rcObjectPos; m_spIViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdc, prcBounds, NULL, NULL, 0); } } else { // Draw something to indicate no control is there HBRUSH hbr = CreateSolidBrush(RGB(200,200,200)); FillRect(hdc, &m_rcObjectPos, hbr); DeleteObject(hbr); } return S_OK; } // Execute the specified verb HRESULT CControlSite::DoVerb(LONG nVerb, LPMSG lpMsg) { TRACE_METHOD(CControlSite::DoVerb); if (m_spIOleObject == NULL) { return E_FAIL; } // InstallAtlThunk(); return m_spIOleObject->DoVerb(nVerb, lpMsg, this, 0, m_hWndParent, &m_rcObjectPos); } // Set the position on the control HRESULT CControlSite::SetPosition(const RECT &rcPos) { HWND hwnd; TRACE_METHOD(CControlSite::SetPosition); m_rcObjectPos = rcPos; if (m_spIOleInPlaceObject && SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&hwnd))) { m_spIOleInPlaceObject->SetObjectRects(&m_rcObjectPos, &m_rcObjectPos); } return S_OK; } HRESULT CControlSite::GetControlSize(LPSIZEL size){ if (m_spIOleObject) { SIZEL szHiMetric; HRESULT hr = m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szHiMetric); AtlHiMetricToPixel(&szHiMetric, size); return hr; } return E_FAIL; } void CControlSite::FireAmbientPropertyChange(DISPID id) { if (m_spObject) { CComQIPtr<IOleControl> spControl = m_spObject; if (spControl) { spControl->OnAmbientPropertyChange(id); } } } void CControlSite::SetAmbientUserMode(BOOL bUserMode) { bool bNewMode = bUserMode ? true : false; if (m_bAmbientUserMode != bNewMode) { m_bAmbientUserMode = bNewMode; FireAmbientPropertyChange(DISPID_AMBIENT_USERMODE); } } /////////////////////////////////////////////////////////////////////////////// // CControlSiteSecurityPolicy implementation CControlSiteSecurityPolicy *CControlSite::GetDefaultControlSecurityPolicy() { static CDefaultControlSiteSecurityPolicy defaultControlSecurityPolicy; return &defaultControlSecurityPolicy; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { if (wFlags & DISPATCH_PROPERTYGET) { CComVariant vResult; switch (dispIdMember) { case DISPID_AMBIENT_APPEARANCE: vResult = CComVariant(m_bAmbientAppearance); break; case DISPID_AMBIENT_FORECOLOR: vResult = CComVariant((long) m_clrAmbientForeColor); break; case DISPID_AMBIENT_BACKCOLOR: vResult = CComVariant((long) m_clrAmbientBackColor); break; case DISPID_AMBIENT_LOCALEID: vResult = CComVariant((long) m_nAmbientLocale); break; case DISPID_AMBIENT_USERMODE: vResult = CComVariant(m_bAmbientUserMode); break; case DISPID_AMBIENT_SHOWGRABHANDLES: vResult = CComVariant(m_bAmbientShowGrabHandles); break; case DISPID_AMBIENT_SHOWHATCHING: vResult = CComVariant(m_bAmbientShowHatching); break; default: return DISP_E_MEMBERNOTFOUND; } VariantCopy(pVarResult, &vResult); return S_OK; } return E_FAIL; } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink implementation void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed) { } void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex) { // Redraw the control InvalidateRect(NULL, FALSE); } void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk) { } void STDMETHODCALLTYPE CControlSite::OnSave(void) { } void STDMETHODCALLTYPE CControlSite::OnClose(void) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink2 implementation void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSinkEx implementation void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus) { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { *phwnd = m_hWndParent; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleClientSite implementation HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk) { if (!ppmk) { return E_INVALIDARG; } if (dwWhichMoniker != OLEWHICHMK_CONTAINER) { return E_FAIL; } return CreateURLMoniker(NULL, url, ppmk); } void CControlSite::SetUrl(BSTR url) { this->url = url; } HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer) { if (!ppContainer) return E_INVALIDARG; CComQIPtr<IOleContainer> container(this->GetUnknown()); *ppContainer = container; if (*ppContainer) { (*ppContainer)->AddRef(); } return (*ppContainer) ? S_OK : E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE CControlSite::ShowObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnShowWindow(/* [in] */ BOOL fShow) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestNewObjectLayout(void) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSite implementation HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void) { m_bInPlaceActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void) { m_bUIActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo) { *lprcPosRect = m_rcObjectPos; *lprcClipRect = m_rcObjectPos; CControlSiteIPFrameInstance *pIPFrame = NULL; CControlSiteIPFrameInstance::CreateInstance(&pIPFrame); pIPFrame->AddRef(); *ppFrame = (IOleInPlaceFrame *) pIPFrame; *ppDoc = NULL; lpFrameInfo->fMDIApp = FALSE; lpFrameInfo->hwndFrame = NULL; lpFrameInfo->haccel = NULL; lpFrameInfo->cAccelEntries = 0; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable) { m_bUIActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect) { if (lprcPosRect == NULL) { return E_INVALIDARG; } SetPosition(m_rcObjectPos); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteEx implementation HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags) { m_bInPlaceActive = TRUE; if (pfNoRedraw) { *pfNoRedraw = FALSE; } if (dwFlags & ACTIVATE_WINDOWLESS) { if (!m_bSupportWindowlessActivation) { return E_INVALIDARG; } m_bWindowless = TRUE; } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void) { return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteWindowless implementation HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void) { // Allow windowless activation? return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC) { if (phDC == NULL) { return E_INVALIDARG; } // Can't do nested painting if (m_hDCBuffer != NULL) { return E_UNEXPECTED; } m_rcBuffer = m_rcObjectPos; if (pRect != NULL) { m_rcBuffer = *pRect; } m_hBMBuffer = NULL; m_dwBufferFlags = grfFlags; // See if the control wants a DC that is onscreen or offscreen if (m_dwBufferFlags & OLEDC_OFFSCREEN) { m_hDCBuffer = CreateCompatibleDC(NULL); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy); m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer); SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL); // TODO When OLEDC_PAINTBKGND we must draw every site behind this one } else { // TODO When OLEDC_PAINTBKGND we must draw every site behind this one // Get the window DC m_hDCBuffer = GetWindowDC(m_hWndParent); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } // Clip the control so it can't trash anywhere it isn't allowed to draw if (!(m_dwBufferFlags & OLEDC_NODRAW)) { m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer); // TODO Clip out opaque areas of sites behind this one SelectClipRgn(m_hDCBuffer, m_hRgnBuffer); } } *phDC = m_hDCBuffer; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC) { // Release the DC if (hDC == NULL || hDC != m_hDCBuffer) { return E_INVALIDARG; } // Test if the DC was offscreen or onscreen if ((m_dwBufferFlags & OLEDC_OFFSCREEN) && !(m_dwBufferFlags & OLEDC_NODRAW)) { // BitBlt the buffer into the control's object SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL); HDC hdc = GetWindowDC(m_hWndParent); long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY); ::ReleaseDC(m_hWndParent, hdc); } else { // TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one } // Clean up settings ready for next drawing if (m_hRgnBuffer) { SelectClipRgn(m_hDCBuffer, NULL); DeleteObject(m_hRgnBuffer); m_hRgnBuffer = NULL; } SelectObject(m_hDCBuffer, m_hBMBufferOld); if (m_hBMBuffer) { DeleteObject(m_hBMBuffer); m_hBMBuffer = NULL; } // Delete the DC if (m_dwBufferFlags & OLEDC_OFFSCREEN) { ::DeleteDC(m_hDCBuffer); } else { ::ReleaseDC(m_hWndParent, m_hDCBuffer); } m_hDCBuffer = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase) { // Clip the rectangle against the object's size and invalidate it RECT rcI = { 0, 0, 0, 0 }; if (pRect == NULL) { rcI = m_rcObjectPos; } else { IntersectRect(&rcI, &m_rcObjectPos, pRect); } ::InvalidateRect(m_hWndParent, &rcI, fErase); return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase) { if (hRGN == NULL) { ::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase); } else { // Clip the region with the object's bounding area HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos); if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR) { ::InvalidateRgn(m_hWndParent, hrgnClip, fErase); } DeleteObject(hrgnClip); } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc) { if (prc == NULL) { return E_INVALIDARG; } // Clip the rectangle against the object position RECT rcI = { 0, 0, 0, 0 }; IntersectRect(&rcI, &m_rcObjectPos, prc); *prc = rcI; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult) { if (plResult == NULL) { return E_INVALIDARG; } // Pass the message to the windowless control if (m_bWindowless && m_spIOleInPlaceObjectWindowless) { return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult); } else if (m_spIOleInPlaceObject) { HWND wnd; if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd))) SendMessage(wnd, msg, wParam, lParam); } return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleControlSite implementation HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock) { m_bInPlaceLocked = fLock; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags) { HRESULT hr = S_OK; if (pPtlHimetric == NULL) { return E_INVALIDARG; } if (pPtfContainer == NULL) { return E_INVALIDARG; } HDC hdc = ::GetDC(m_hWndParent); ::SetMapMode(hdc, MM_HIMETRIC); POINT rgptConvert[2]; rgptConvert[0].x = 0; rgptConvert[0].y = 0; if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER) { rgptConvert[1].x = pPtlHimetric->x; rgptConvert[1].y = pPtlHimetric->y; ::LPtoDP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x); pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y); } else if (dwFlags & XFORMCOORDS_POSITION) { pPtfContainer->x = (float)rgptConvert[1].x; pPtfContainer->y = (float)rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC) { rgptConvert[1].x = (int)(pPtfContainer->x); rgptConvert[1].y = (int)(pPtfContainer->y); ::DPtoLP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x; pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y; } else if (dwFlags & XFORMCOORDS_POSITION) { pPtlHimetric->x = rgptConvert[1].x; pPtlHimetric->y = rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else { hr = E_INVALIDARG; } ::ReleaseDC(m_hWndParent, hdc); return hr; } HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IBindStatusCallback implementation HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved, IBinding __RPC_FAR *pib) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError) { m_bBindingInProgress = FALSE; m_hrBindResult = hresult; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF, BINDINFO __RPC_FAR *pbindInfo) { *pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE; pbindInfo->cbSize = sizeof(BINDINFO); pbindInfo->szExtraInfo = NULL; memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM)); pbindInfo->grfBindInfoF = 0; pbindInfo->dwBindVerb = 0; pbindInfo->szCustomVerb = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC __RPC_FAR *pformatetc, STGMEDIUM __RPC_FAR *pstgmed) { ATLTRACE("Not implemnted"); return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid, IUnknown __RPC_FAR *punk) { return S_OK; } // IWindowForBindingUI HRESULT STDMETHODCALLTYPE CControlSite::GetWindow( /* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd) { *phwnd = NULL; return S_OK; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITEIPFRAME_H #define CONTROLSITEIPFRAME_H class CControlSiteIPFrame : public CComObjectRootEx<CComSingleThreadModel>, public IOleInPlaceFrame { public: CControlSiteIPFrame(); virtual ~CControlSiteIPFrame(); HWND m_hwndFrame; BEGIN_COM_MAP(CControlSiteIPFrame) COM_INTERFACE_ENTRY_IID(IID_IOleWindow, IOleInPlaceFrame) COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceUIWindow, IOleInPlaceFrame) COM_INTERFACE_ENTRY(IOleInPlaceFrame) END_COM_MAP() // IOleWindow virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleInPlaceUIWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetBorder(/* [out] */ LPRECT lprectBorder); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths); virtual HRESULT STDMETHODCALLTYPE SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName); // IOleInPlaceFrame implementation virtual HRESULT STDMETHODCALLTYPE InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject); virtual HRESULT STDMETHODCALLTYPE RemoveMenus(/* [in] */ HMENU hmenuShared); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetStatusText(/* [in] */ LPCOLESTR pszStatusText); virtual HRESULT STDMETHODCALLTYPE EnableModeless(/* [in] */ BOOL fEnable); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID); }; typedef CComObject<CControlSiteIPFrame> CControlSiteIPFrameInstance; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef IOLECOMMANDIMPL_H #define IOLECOMMANDIMPL_H // Implementation of the IOleCommandTarget interface. The template is // reasonably generic and reusable which is a good thing given how needlessly // complicated this interface is. Blame Microsoft for that and not me. // // To use this class, derive your class from it like this: // // class CComMyClass : public IOleCommandTargetImpl<CComMyClass> // { // ... Ensure IOleCommandTarget is listed in the interface map ... // BEGIN_COM_MAP(CComMyClass) // COM_INTERFACE_ENTRY(IOleCommandTarget) // // etc. // END_COM_MAP() // ... And then later on define the command target table ... // BEGIN_OLECOMMAND_TABLE() // OLECOMMAND_MESSAGE(OLECMDID_PRINT, NULL, ID_PRINT, L"Print", L"Print the page") // OLECOMMAND_MESSAGE(OLECMDID_SAVEAS, NULL, 0, L"SaveAs", L"Save the page") // OLECOMMAND_HANDLER(IDM_EDITMODE, &CGID_MSHTML, EditModeHandler, L"EditMode", L"Switch to edit mode") // END_OLECOMMAND_TABLE() // ... Now the window that OLECOMMAND_MESSAGE sends WM_COMMANDs to ... // HWND GetCommandTargetWindow() const // { // return m_hWnd; // } // ... Now procedures that OLECOMMAND_HANDLER calls ... // static HRESULT _stdcall EditModeHandler(CMozillaBrowser *pThis, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut); // } // // The command table defines which commands the object supports. Commands are // defined by a command id and a command group plus a WM_COMMAND id or procedure, // and a verb and short description. // // Notice that there are two macros for handling Ole Commands. The first, // OLECOMMAND_MESSAGE sends a WM_COMMAND message to the window returned from // GetCommandTargetWindow() (that the derived class must implement if it uses // this macro). // // The second, OLECOMMAND_HANDLER calls a static handler procedure that // conforms to the OleCommandProc typedef. The first parameter, pThis means // the static handler has access to the methods and variables in the class // instance. // // The OLECOMMAND_HANDLER macro is generally more useful when a command // takes parameters or needs to return a result to the caller. // template< class T > class IOleCommandTargetImpl : public IOleCommandTarget { struct OleExecData { const GUID *pguidCmdGroup; DWORD nCmdID; DWORD nCmdexecopt; VARIANT *pvaIn; VARIANT *pvaOut; }; public: typedef HRESULT (_stdcall *OleCommandProc)(T *pT, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut); struct OleCommandInfo { ULONG nCmdID; const GUID *pCmdGUID; ULONG nWindowsCmdID; OleCommandProc pfnCommandProc; wchar_t *szVerbText; wchar_t *szStatusText; }; // Query the status of the specified commands (test if is it supported etc.) virtual HRESULT STDMETHODCALLTYPE QueryStatus(const GUID __RPC_FAR *pguidCmdGroup, ULONG cCmds, OLECMD __RPC_FAR prgCmds[], OLECMDTEXT __RPC_FAR *pCmdText) { T* pT = static_cast<T*>(this); if (prgCmds == NULL) { return E_INVALIDARG; } OleCommandInfo *pCommands = pT->GetCommandTable(); ATLASSERT(pCommands); BOOL bCmdGroupFound = FALSE; BOOL bTextSet = FALSE; // Iterate through list of commands and flag them as supported/unsupported for (ULONG nCmd = 0; nCmd < cCmds; nCmd++) { // Unsupported by default prgCmds[nCmd].cmdf = 0; // Search the support command list for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++) { OleCommandInfo *pCI = &pCommands[nSupported]; if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0) { continue; } bCmdGroupFound = TRUE; if (pCI->nCmdID != prgCmds[nCmd].cmdID) { continue; } // Command is supported so flag it and possibly enable it prgCmds[nCmd].cmdf = OLECMDF_SUPPORTED; if (pCI->nWindowsCmdID != 0) { prgCmds[nCmd].cmdf |= OLECMDF_ENABLED; } // Copy the status/verb text for the first supported command only if (!bTextSet && pCmdText) { // See what text the caller wants wchar_t *pszTextToCopy = NULL; if (pCmdText->cmdtextf & OLECMDTEXTF_NAME) { pszTextToCopy = pCI->szVerbText; } else if (pCmdText->cmdtextf & OLECMDTEXTF_STATUS) { pszTextToCopy = pCI->szStatusText; } // Copy the text pCmdText->cwActual = 0; memset(pCmdText->rgwz, 0, pCmdText->cwBuf * sizeof(wchar_t)); if (pszTextToCopy) { // Don't exceed the provided buffer size size_t nTextLen = wcslen(pszTextToCopy); if (nTextLen > pCmdText->cwBuf) { nTextLen = pCmdText->cwBuf; } wcsncpy(pCmdText->rgwz, pszTextToCopy, nTextLen); pCmdText->cwActual = nTextLen; } bTextSet = TRUE; } break; } } // Was the command group found? if (!bCmdGroupFound) { OLECMDERR_E_UNKNOWNGROUP; } return S_OK; } // Execute the specified command virtual HRESULT STDMETHODCALLTYPE Exec(const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT __RPC_FAR *pvaIn, VARIANT __RPC_FAR *pvaOut) { T* pT = static_cast<T*>(this); BOOL bCmdGroupFound = FALSE; OleCommandInfo *pCommands = pT->GetCommandTable(); ATLASSERT(pCommands); // Search the support command list for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++) { OleCommandInfo *pCI = &pCommands[nSupported]; if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0) { continue; } bCmdGroupFound = TRUE; if (pCI->nCmdID != nCmdID) { continue; } // Send ourselves a WM_COMMAND windows message with the associated // identifier and exec data OleExecData cData; cData.pguidCmdGroup = pguidCmdGroup; cData.nCmdID = nCmdID; cData.nCmdexecopt = nCmdexecopt; cData.pvaIn = pvaIn; cData.pvaOut = pvaOut; if (pCI->pfnCommandProc) { pCI->pfnCommandProc(pT, pCI->pCmdGUID, pCI->nCmdID, nCmdexecopt, pvaIn, pvaOut); } else if (pCI->nWindowsCmdID != 0 && nCmdexecopt != OLECMDEXECOPT_SHOWHELP) { HWND hwndTarget = pT->GetCommandTargetWindow(); if (hwndTarget) { ::SendMessage(hwndTarget, WM_COMMAND, LOWORD(pCI->nWindowsCmdID), (LPARAM) &cData); } } else { // Command supported but not implemented continue; } return S_OK; } // Was the command group found? if (!bCmdGroupFound) { OLECMDERR_E_UNKNOWNGROUP; } return OLECMDERR_E_NOTSUPPORTED; } }; // Macros to be placed in any class derived from the IOleCommandTargetImpl // class. These define what commands are exposed from the object. #define BEGIN_OLECOMMAND_TABLE() \ OleCommandInfo *GetCommandTable() \ { \ static OleCommandInfo s_aSupportedCommands[] = \ { #define OLECOMMAND_MESSAGE(id, group, cmd, verb, desc) \ { id, group, cmd, NULL, verb, desc }, #define OLECOMMAND_HANDLER(id, group, handler, verb, desc) \ { id, group, 0, handler, verb, desc }, #define END_OLECOMMAND_TABLE() \ { 0, &GUID_NULL, 0, NULL, NULL, NULL } \ }; \ return s_aSupportedCommands; \ }; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYLIST_H #define PROPERTYLIST_H // A simple array class for managing name/value pairs typically fed to controls // during initialization by IPersistPropertyBag class PropertyList { struct Property { BSTR bstrName; VARIANT vValue; } *mProperties; unsigned long mListSize; unsigned long mMaxListSize; bool EnsureMoreSpace() { // Ensure enough space exists to accomodate a new item const unsigned long kGrowBy = 10; if (!mProperties) { mProperties = (Property *) malloc(sizeof(Property) * kGrowBy); if (!mProperties) return false; mMaxListSize = kGrowBy; } else if (mListSize == mMaxListSize) { Property *pNewProperties; pNewProperties = (Property *) realloc(mProperties, sizeof(Property) * (mMaxListSize + kGrowBy)); if (!pNewProperties) return false; mProperties = pNewProperties; mMaxListSize += kGrowBy; } return true; } public: PropertyList() : mProperties(NULL), mListSize(0), mMaxListSize(0) { } ~PropertyList() { } void Clear() { if (mProperties) { for (unsigned long i = 0; i < mListSize; i++) { SysFreeString(mProperties[i].bstrName); // Safe even if NULL VariantClear(&mProperties[i].vValue); } free(mProperties); mProperties = NULL; } mListSize = 0; mMaxListSize = 0; } unsigned long GetSize() const { return mListSize; } const BSTR GetNameOf(unsigned long nIndex) const { if (nIndex > mListSize) { return NULL; } return mProperties[nIndex].bstrName; } const VARIANT *GetValueOf(unsigned long nIndex) const { if (nIndex > mListSize) { return NULL; } return &mProperties[nIndex].vValue; } bool AddOrReplaceNamedProperty(const BSTR bstrName, const VARIANT &vValue) { if (!bstrName) return false; for (unsigned long i = 0; i < GetSize(); i++) { // Case insensitive if (wcsicmp(mProperties[i].bstrName, bstrName) == 0) { return SUCCEEDED( VariantCopy(&mProperties[i].vValue, const_cast<VARIANT *>(&vValue))); } } return AddNamedProperty(bstrName, vValue); } bool AddNamedProperty(const BSTR bstrName, const VARIANT &vValue) { if (!bstrName || !EnsureMoreSpace()) return false; Property *pProp = &mProperties[mListSize]; pProp->bstrName = ::SysAllocString(bstrName); if (!pProp->bstrName) { return false; } VariantInit(&pProp->vValue); if (FAILED(VariantCopy(&pProp->vValue, const_cast<VARIANT *>(&vValue)))) { SysFreeString(pProp->bstrName); return false; } mListSize++; return true; } }; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef ITEMCONTAINER_H #define ITEMCONTAINER_H // typedef std::map<tstring, CIUnkPtr> CNamedObjectList; // Class for managing a list of named objects. class CItemContainer : public CComObjectRootEx<CComSingleThreadModel>, public IOleItemContainer { // CNamedObjectList m_cNamedObjectList; public: CItemContainer(); virtual ~CItemContainer(); BEGIN_COM_MAP(CItemContainer) COM_INTERFACE_ENTRY_IID(IID_IParseDisplayName, IOleItemContainer) COM_INTERFACE_ENTRY_IID(IID_IOleContainer, IOleItemContainer) COM_INTERFACE_ENTRY_IID(IID_IOleItemContainer, IOleItemContainer) END_COM_MAP() // IParseDisplayName implementation virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut); // IOleContainer implementation virtual HRESULT STDMETHODCALLTYPE EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum); virtual HRESULT STDMETHODCALLTYPE LockContainer(/* [in] */ BOOL fLock); // IOleItemContainer implementation virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage); virtual HRESULT STDMETHODCALLTYPE IsRunning(/* [in] */ LPOLESTR pszItem); }; typedef CComObject<CItemContainer> CItemContainerInstance; #endif
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "Host.h" #include <atlsafe.h> #include "objectProxy.h" class NPSafeArray: public ScriptBase { public: NPSafeArray(NPP npp); ~NPSafeArray(void); static NPSafeArray* CreateFromArray(NPP instance, SAFEARRAY* array); static void RegisterVBArray(NPP npp); static NPClass npClass; SAFEARRAY* NPSafeArray::GetArrayPtr(); private: static NPInvokeDefaultFunctionPtr GetFuncPtr(NPIdentifier name); CComSafeArray<VARIANT> arr_; NPObjectProxy window; // Some wrappers to adapt NPAPI's interface. static NPObject* Allocate(NPP npp, NPClass *aClass); static void Deallocate(NPObject *obj); static void Invalidate(NPObject *obj); static bool HasMethod(NPObject *npobj, NPIdentifier name); static bool Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool GetItem(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool ToArray(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool UBound(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool LBound(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool Dimensions(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result); static bool HasProperty(NPObject *npobj, NPIdentifier name); static bool GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result); static bool SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <npapi.h> #include <npruntime.h> struct ScriptBase; class CHost { public: void AddRef(); void Release(); CHost(NPP npp); virtual ~CHost(void); NPObject *GetScriptableObject(); NPP GetInstance() { return instance; } static CHost *GetInternalObject(NPP npp, NPObject *embed_element); NPObject *RegisterObject(); void UnRegisterObject(); virtual NPP ResetNPP(NPP newNpp); protected: NPP instance; ScriptBase *lastObj; ScriptBase *GetMyScriptObject(); virtual ScriptBase *CreateScriptableObject() = 0; private: int ref_cnt_; }; struct ScriptBase: NPObject { NPP instance; CHost* host; ScriptBase(NPP instance_) : instance(instance_) { } };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <windows.h> #include <winbase.h> // ---------------------------------------------------------------------------- int main (int ArgC, char *ArgV[]) { const char *sourceName; const char *targetName; HANDLE targetHandle; void *versionPtr; DWORD versionLen; int lastError; int ret = 0; if (ArgC < 3) { fprintf(stderr, "Usage: %s <source> <target>\n", ArgV[0]); exit (1); } sourceName = ArgV[1]; targetName = ArgV[2]; if ((versionLen = GetFileVersionInfoSize(sourceName, NULL)) == 0) { fprintf(stderr, "Could not retrieve version len from %s\n", sourceName); exit (2); } if ((versionPtr = calloc(1, versionLen)) == NULL) { fprintf(stderr, "Error allocating temp memory\n"); exit (3); } if (!GetFileVersionInfo(sourceName, NULL, versionLen, versionPtr)) { fprintf(stderr, "Could not retrieve version info from %s\n", sourceName); exit (4); } if ((targetHandle = BeginUpdateResource(targetName, FALSE)) == INVALID_HANDLE_VALUE) { fprintf(stderr, "Could not begin update of %s\n", targetName); free(versionPtr); exit (5); } if (!UpdateResource(targetHandle, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), versionPtr, versionLen)) { lastError = GetLastError(); fprintf(stderr, "Error %d updating resource\n", lastError); ret = 6; } if (!EndUpdateResource(targetHandle, FALSE)) { fprintf(stderr, "Error finishing update\n"); ret = 7; } free(versionPtr); return (ret); }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <map> #include <vector> #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; extern NPClass GenericNPObjectClass; typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); struct ltnum { bool operator()(long n1, long n2) const { return n1 < n2; } }; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); class GenericNPObject: public NPObject { private: GenericNPObject(const GenericNPObject &); bool invalid; DefaultInvoker defInvoker; void *defInvokerObject; std::vector<NPVariant> numeric_mapper; // the members of alpha mapper can be reassigned to anything the user wishes std::map<const char *, NPVariant, ltstr> alpha_mapper; // these cannot accept other types than they are initially defined with std::map<const char *, NPVariant, ltstr> immutables; public: friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *); GenericNPObject(NPP instance); GenericNPObject(NPP instance, bool isMethodObj); ~GenericNPObject(); void Invalidate() {invalid = true;} void SetDefaultInvoker(DefaultInvoker di, void *context) { defInvoker = di; defInvokerObject = context; } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result); } static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (((GenericNPObject *)npobj)->defInvoker) { return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result); } else { return false; } } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((GenericNPObject *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((GenericNPObject *)npobj)->SetProperty(name, value); } static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->RemoveProperty(name); } static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) { return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount); } bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool RemoveProperty(NPIdentifier name); bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ class CAxHost { private: CAxHost(const CAxHost &); NPP instance; bool isValidClsID; bool isKnown; protected: // The window handle to our plugin area in the browser HWND Window; WNDPROC OldProc; // The class/prog id of the control CLSID ClsID; LPCWSTR CodeBaseUrl; CControlEventSinkInstance *Sink; public: CAxHost(NPP inst); ~CAxHost(); CControlSiteInstance *Site; PropertyList Props; void setWindow(HWND win); HWND getWinfow(); void UpdateRect(RECT rcPos); bool verifyClsID(LPOLESTR oleClsID); bool setClsID(const char *clsid); bool setClsIDFromProgID(const char *progid); void setCodeBaseUrl(LPCWSTR clsid); bool hasValidClsID(); bool CreateControl(bool subscribeToEvents); bool AddEventHandler(wchar_t *name, wchar_t *handler); int16 HandleEvent(void *event); NPObject *GetScriptableObject(); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // dllmain.cpp : Defines the entry point for the DLL application. #include "ffactivex.h" #include "axhost.h" CComModule _Module; NPNetscapeFuncs NPNFuncs; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } // ============================== // ! Scriptability related code ! // ============================== // // here the plugin is asked by Mozilla to tell if it is scriptable // we should return a valid interface id and a pointer to // nsScriptablePeer interface which we should have implemented // and which should be defined in the corressponding *.xpt file // in the bin/components folder NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; if(instance == NULL) return NPERR_GENERIC_ERROR; CAxHost *host = (CAxHost *)instance->pdata; if(host == NULL) return NPERR_GENERIC_ERROR; switch (variable) { case NPPVpluginNameString: *((char **)value) = "ITSTActiveX"; break; case NPPVpluginDescriptionString: *((char **)value) = "IT Structures ActiveX for Firefox"; break; case NPPVpluginScriptableNPObject: *(NPObject **)value = host->GetScriptableObject(); break; default: rv = NPERR_GENERIC_ERROR; } return rv; } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16* stype) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int32_t NPP_WriteReady (NPP instance, NPStream *stream) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = 0x0fffffff; return rv; } int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; int32 rv = len; return rv; } NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname) { if(instance == NULL) return; } void NPP_Print (NPP instance, NPPrint* printInfo) { if(instance == NULL) return; } void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) { if(instance == NULL) return; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; return rv; } int16 NPP_HandleEvent(NPP instance, void* event) { if(instance == NULL) return 0; int16 rv = 0; CAxHost *host = (CAxHost *)instance->pdata; if (host) rv = host->HandleEvent(event); return rv; } NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) { if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; if(pFuncs->size < sizeof(NPPluginFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; pFuncs->newp = NPP_New; pFuncs->destroy = NPP_Destroy; pFuncs->setwindow = NPP_SetWindow; pFuncs->newstream = NPP_NewStream; pFuncs->destroystream = NPP_DestroyStream; pFuncs->asfile = NPP_StreamAsFile; pFuncs->writeready = NPP_WriteReady; pFuncs->write = NPP_Write; pFuncs->print = NPP_Print; pFuncs->event = NPP_HandleEvent; pFuncs->urlnotify = NPP_URLNotify; pFuncs->getvalue = NPP_GetValue; pFuncs->setvalue = NPP_SetValue; pFuncs->javaClass = NULL; return NPERR_NO_ERROR; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) /* * Initialize the plugin. Called the first time the browser comes across a * MIME Type this plugin is registered to handle. */ NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs) { // _asm {int 3}; if(pFuncs == NULL) return NPERR_INVALID_FUNCTABLE_ERROR; #ifdef NDEF // The following statements prevented usage of newer Mozilla sources than installed browser at runtime if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR) return NPERR_INCOMPATIBLE_VERSION_ERROR; if(pFuncs->size < sizeof(NPNetscapeFuncs)) return NPERR_INVALID_FUNCTABLE_ERROR; #endif if (!AtlAxWinInit()) { return NPERR_GENERIC_ERROR; } CoInitialize(NULL); _pAtlModule = &_Module; memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs)); memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs))); return NPERR_NO_ERROR; } /* * Shutdown the plugin. Called when no more instanced of this plugin exist and * the browser wants to unload it. */ NPError OSCALL NP_Shutdown(void) { AtlAxWinTerm(); return NPERR_NO_ERROR; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; extern NPClass ScriptableNPClass; class Scriptable: public NPObject { private: Scriptable(const Scriptable &); // This method iterates all members of the current interface, looking for the member with the // id of member_id. If not found within this interface, it will iterate all base interfaces // recursively, until a match is found, or all the hierarchy was searched. bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) { bool found = false; unsigned int i = 0; FUNCDESC *fDesc; for (i = 0; (i < attr->cFuncs) && !found; ++i) { HRESULT hr = info->GetFuncDesc(i, &fDesc); if ( SUCCEEDED(hr) && fDesc && (fDesc->memid == member_id)) { if (invKind & fDesc->invkind) found = true; } info->ReleaseFuncDesc(fDesc); } if (!found && (invKind & ~INVOKE_FUNC)) { VARDESC *vDesc; for (i = 0; (i < attr->cVars) && !found; ++i) { HRESULT hr = info->GetVarDesc(i, &vDesc); if ( SUCCEEDED(hr) && vDesc && (vDesc->memid == member_id)) { found = true; } info->ReleaseVarDesc(vDesc); } } if (!found) { // iterate inherited interfaces HREFTYPE refType = NULL; for (i = 0; (i < attr->cImplTypes) && !found; ++i) { ITypeInfoPtr baseInfo; TYPEATTR *baseAttr; if (FAILED(info->GetRefTypeOfImplType(0, &refType))) { continue; } if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) { continue; } if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) { continue; } found = find_member(baseInfo, baseAttr, member_id, invKind); baseInfo->ReleaseTypeAttr(baseAttr); } } return found; } DISPID ResolveName(NPIdentifier name, unsigned int invKind) { bool found = false; DISPID dID = -1; USES_CONVERSION; if (!name || !invKind) { return -1; } if (!NPNFuncs.identifierisstring(name)) { return -1; } NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name); LPOLESTR oleName = A2W(npname); IDispatchPtr disp = control.GetInterfacePtr(); if (!disp) { return -1; } disp->GetIDsOfNames(IID_NULL, &oleName, 1, LOCALE_SYSTEM_DEFAULT, &dID); if (dID != -1) { ITypeInfoPtr info; disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info); if (!info) { return -1; } TYPEATTR *attr; if (FAILED(info->GetTypeAttr(&attr))) { return -1; } found = find_member(info, attr, dID, invKind); info->ReleaseTypeAttr(attr); } return found ? dID : -1; } bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult) { IDispatchPtr disp = control.GetInterfacePtr(); if (!disp) { return false; } HRESULT hr = disp->Invoke(id, IID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, pDispParams, pVarResult, NULL, NULL); return (SUCCEEDED(hr)) ? true : false; } IUnknownPtr control; NPP instance; bool invalid; public: Scriptable(): invalid(false), control(NULL), instance(NULL) { } ~Scriptable() {control->Release();} void setControl(IUnknown *unk) {control = unk;} void setControl(IDispatch *disp) {disp->QueryInterface(IID_IUnknown, (void **)&control);} void setInstance(NPP inst) {instance = inst;} void Invalidate() {invalid = true;} static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((Scriptable *)npobj)->Invoke(name, args, argCount, result); } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((Scriptable *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((Scriptable *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((Scriptable *)npobj)->SetProperty(name, value); } bool HasMethod(NPIdentifier name) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_FUNC); return (id != -1) ? true : false; } bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_FUNC); if (-1 == id) { return false; } VARIANT *vArgs = NULL; if (argCount) { vArgs = new VARIANT[argCount]; if (!vArgs) { return false; } for (unsigned int i = 0; i < argCount; ++i) { // copy the arguments in reverse order NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance); } } DISPPARAMS params = {NULL, NULL, 0, 0}; params.cArgs = argCount; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = vArgs; VARIANT vResult; bool rc = InvokeControl(id, DISPATCH_METHOD, &params, &vResult); if (vArgs) delete[] vArgs; if (!rc) { return false; } Variant2NPVar(&vResult, result, instance); return true; } bool HasProperty(NPIdentifier name) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT); return (id != -1) ? true : false; } bool GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYGET); if (-1 == id) { return false; } DISPPARAMS params; params.cArgs = 0; params.cNamedArgs = 0; params.rgdispidNamedArgs = NULL; params.rgvarg = NULL; VARIANT vResult; if (!InvokeControl(id, DISPATCH_PROPERTYGET, &params, &vResult)) { return false; } Variant2NPVar(&vResult, result, instance); return true; } bool SetProperty(NPIdentifier name, const NPVariant *value) { if (invalid) return false; DISPID id = ResolveName(name, INVOKE_PROPERTYPUT); if (-1 == id) { return false; } VARIANT val; NPVar2Variant(value, &val, instance); DISPPARAMS params; // Special initialization needed when using propery put. DISPID dispidNamed = DISPID_PROPERTYPUT; params.cNamedArgs = 1; params.rgdispidNamedArgs = &dispidNamed; params.cArgs = 1; params.rgvarg = &val; VARIANT vResult; if (!InvokeControl(id, DISPATCH_PROPERTYPUT, &params, &vResult)) { return false; } return true; } };
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYLIST_H #define PROPERTYLIST_H // A simple array class for managing name/value pairs typically fed to controls // during initialization by IPersistPropertyBag class PropertyList { struct Property { BSTR bstrName; VARIANT vValue; } *mProperties; unsigned long mListSize; unsigned long mMaxListSize; bool EnsureMoreSpace() { // Ensure enough space exists to accomodate a new item const unsigned long kGrowBy = 10; if (!mProperties) { mProperties = (Property *) malloc(sizeof(Property) * kGrowBy); if (!mProperties) return false; mMaxListSize = kGrowBy; } else if (mListSize == mMaxListSize) { Property *pNewProperties; pNewProperties = (Property *) realloc(mProperties, sizeof(Property) * (mMaxListSize + kGrowBy)); if (!pNewProperties) return false; mProperties = pNewProperties; mMaxListSize += kGrowBy; } return true; } public: PropertyList() : mProperties(NULL), mListSize(0), mMaxListSize(0) { } ~PropertyList() { } void Clear() { if (mProperties) { for (unsigned long i = 0; i < mListSize; i++) { SysFreeString(mProperties[i].bstrName); // Safe even if NULL VariantClear(&mProperties[i].vValue); } free(mProperties); mProperties = NULL; } mListSize = 0; mMaxListSize = 0; } unsigned long GetSize() const { return mListSize; } const BSTR GetNameOf(unsigned long nIndex) const { if (nIndex > mListSize) { return NULL; } return mProperties[nIndex].bstrName; } const VARIANT *GetValueOf(unsigned long nIndex) const { if (nIndex > mListSize) { return NULL; } return &mProperties[nIndex].vValue; } bool AddOrReplaceNamedProperty(const BSTR bstrName, const VARIANT &vValue) { if (!bstrName) return false; for (unsigned long i = 0; i < GetSize(); i++) { // Case insensitive if (wcsicmp(mProperties[i].bstrName, bstrName) == 0) { return SUCCEEDED( VariantCopy(&mProperties[i].vValue, const_cast<VARIANT *>(&vValue))); } } return AddNamedProperty(bstrName, vValue); } bool AddNamedProperty(const BSTR bstrName, const VARIANT &vValue) { if (!bstrName || !EnsureMoreSpace()) return false; Property *pProp = &mProperties[mListSize]; pProp->bstrName = ::SysAllocString(bstrName); if (!pProp->bstrName) { return false; } VariantInit(&pProp->vValue); if (FAILED(VariantCopy(&pProp->vValue, const_cast<VARIANT *>(&vValue)))) { SysFreeString(pProp->bstrName); return false; } mListSize++; return true; } }; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #if !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_) #define AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // under MSVC shut off copious warnings about debug symbol too long #ifdef _MSC_VER #pragma warning( disable: 4786 ) #endif //#include "jstypes.h" //#include "prtypes.h" // Mozilla headers //#include "jscompat.h" //#include "prthread.h" //#include "prprf.h" //#include "nsID.h" //#include "nsIComponentManager.h" //#include "nsIServiceManager.h" //#include "nsStringAPI.h" //#include "nsCOMPtr.h" //#include "nsComponentManagerUtils.h" //#include "nsServiceManagerUtils.h" //#include "nsIDocument.h" //#include "nsIDocumentObserver.h" //#include "nsVoidArray.h" //#include "nsIDOMNode.h" //#include "nsIDOMNodeList.h" //#include "nsIDOMDocument.h" //#include "nsIDOMDocumentType.h" //#include "nsIDOMElement.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_APARTMENT_THREADED //#define _ATL_STATIC_REGISTRY // #define _ATL_DEBUG_INTERFACES // ATL headers // The ATL headers that come with the platform SDK have bad for scoping #if _MSC_VER >= 1400 #pragma conform(forScope, push, atlhack, off) #endif #include <atlbase.h> //You may derive a class from CComModule and use it if you want to override //something, but do not change the name of _Module extern CComModule _Module; #include <atlcom.h> #include <atlctl.h> #if _MSC_VER >= 1400 #pragma conform(forScope, pop, atlhack) #endif #include <mshtml.h> #include <mshtmhst.h> #include <docobj.h> //#include <winsock2.h> #include <comdef.h> #include <vector> #include <list> #include <string> // New winsock2.h doesn't define this anymore typedef long int32; #define NS_SCRIPTABLE #include "nscore.h" #include "npapi.h" //#include "npupp.h" #include "npfunctions.h" #include "nsID.h" #include <npruntime.h> #include "../variants.h" #include "PropertyList.h" #include "PropertyBag.h" #include "ItemContainer.h" #include "ControlSite.h" #include "ControlSiteIPFrame.h" #include "ControlEventSink.h" extern NPNetscapeFuncs NPNFuncs; // Turn off warnings about debug symbols for templates being too long #pragma warning(disable : 4786) #define TRACE_METHOD(fn) \ { \ ATLTRACE(_T("0x%04x %s()\n"), (int) GetCurrentThreadId(), _T(#fn)); \ } #define TRACE_METHOD_ARGS(fn, pattern, args) \ { \ ATLTRACE(_T("0x%04x %s(") _T(pattern) _T(")\n"), (int) GetCurrentThreadId(), _T(#fn), args); \ } //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #define NS_ASSERTION(x, y) #endif // !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED)
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef ITEMCONTAINER_H #define ITEMCONTAINER_H // typedef std::map<tstring, CIUnkPtr> CNamedObjectList; // Class for managing a list of named objects. class CItemContainer : public CComObjectRootEx<CComSingleThreadModel>, public IOleItemContainer { // CNamedObjectList m_cNamedObjectList; public: CItemContainer(); virtual ~CItemContainer(); BEGIN_COM_MAP(CItemContainer) COM_INTERFACE_ENTRY_IID(IID_IParseDisplayName, IOleItemContainer) COM_INTERFACE_ENTRY_IID(IID_IOleContainer, IOleItemContainer) COM_INTERFACE_ENTRY_IID(IID_IOleItemContainer, IOleItemContainer) END_COM_MAP() // IParseDisplayName implementation virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut); // IOleContainer implementation virtual HRESULT STDMETHODCALLTYPE EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum); virtual HRESULT STDMETHODCALLTYPE LockContainer(/* [in] */ BOOL fLock); // IOleItemContainer implementation virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage); virtual HRESULT STDMETHODCALLTYPE IsRunning(/* [in] */ LPOLESTR pszItem); }; typedef CComObject<CItemContainer> CItemContainerInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "PropertyBag.h" CPropertyBag::CPropertyBag() { } CPropertyBag::~CPropertyBag() { } /////////////////////////////////////////////////////////////////////////////// // IPropertyBag implementation HRESULT STDMETHODCALLTYPE CPropertyBag::Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } VARTYPE vt = pVar->vt; VariantInit(pVar); for (unsigned long i = 0; i < m_PropertyList.GetSize(); i++) { if (wcsicmp(m_PropertyList.GetNameOf(i), pszPropName) == 0) { const VARIANT *pvSrc = m_PropertyList.GetValueOf(i); if (!pvSrc) { return E_FAIL; } CComVariant vNew; HRESULT hr = (vt == VT_EMPTY) ? vNew.Copy(pvSrc) : vNew.ChangeType(vt, pvSrc); if (FAILED(hr)) { return E_FAIL; } // Copy the new value vNew.Detach(pVar); return S_OK; } } // Property does not exist in the bag return E_FAIL; } HRESULT STDMETHODCALLTYPE CPropertyBag::Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } CComBSTR bstrName(pszPropName); m_PropertyList.AddOrReplaceNamedProperty(bstrName, *pVar); return S_OK; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * Brent Booker * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include <Objsafe.h> #include "ControlSite.h" #include "PropertyBag.h" #include "ControlSiteIPFrame.h" class CDefaultControlSiteSecurityPolicy : public CControlSiteSecurityPolicy { // Test if the specified class id implements the specified category BOOL ClassImplementsCategory(const CLSID & clsid, const CATID &catid, BOOL &bClassExists); public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid); // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid); }; BOOL CDefaultControlSiteSecurityPolicy::ClassImplementsCategory(const CLSID &clsid, const CATID &catid, BOOL &bClassExists) { bClassExists = FALSE; // Test if there is a CLSID entry. If there isn't then obviously // the object doesn't exist and therefore doesn't implement any category. // In this situation, the function returns REGDB_E_CLASSNOTREG. CRegKey key; if (key.Open(HKEY_CLASSES_ROOT, _T("CLSID"), KEY_READ) != ERROR_SUCCESS) { // Must fail if we can't even open this! return FALSE; } LPOLESTR szCLSID = NULL; if (FAILED(StringFromCLSID(clsid, &szCLSID))) { return FALSE; } USES_CONVERSION; CRegKey keyCLSID; LONG lResult = keyCLSID.Open(key, W2CT(szCLSID), KEY_READ); CoTaskMemFree(szCLSID); if (lResult != ERROR_SUCCESS) { // Class doesn't exist return FALSE; } keyCLSID.Close(); // CLSID exists, so try checking what categories it implements bClassExists = TRUE; CComQIPtr<ICatInformation> spCatInfo; HRESULT hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (LPVOID*) &spCatInfo); if (spCatInfo == NULL) { // Must fail if we can't open the category manager return FALSE; } // See what categories the class implements CComQIPtr<IEnumCATID> spEnumCATID; if (FAILED(spCatInfo->EnumImplCategoriesOfClass(clsid, &spEnumCATID))) { // Can't enumerate classes in category so fail return FALSE; } // Search for matching categories BOOL bFound = FALSE; CATID catidNext = GUID_NULL; while (spEnumCATID->Next(1, &catidNext, NULL) == S_OK) { if (::IsEqualCATID(catid, catidNext)) { return TRUE; } } return FALSE; } // Test if the class is safe to host BOOL CDefaultControlSiteSecurityPolicy::IsClassSafeToHost(const CLSID & clsid) { return TRUE; } // Test if the specified class is marked safe for scripting BOOL CDefaultControlSiteSecurityPolicy::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) { // Test the category the object belongs to return ClassImplementsCategory(clsid, CATID_SafeForScripting, bClassExists); } // Test if the instantiated object is safe for scripting on the specified interface BOOL CDefaultControlSiteSecurityPolicy::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) { if (!pObject) { return FALSE; } // Ask the control if its safe for scripting CComQIPtr<IObjectSafety> spObjectSafety = pObject; if (!spObjectSafety) { return FALSE; } DWORD dwSupported = 0; // Supported options (mask) DWORD dwEnabled = 0; // Enabled options // Assume scripting via IDispatch if (FAILED(spObjectSafety->GetInterfaceSafetyOptions( iid, &dwSupported, &dwEnabled))) { // Interface is not safe or failure. return FALSE; } // Test if safe for scripting if (!(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER) { // Object says it is not set to be safe, but supports unsafe calling, // try enabling it and asking again. if(!(dwSupported & INTERFACESAFE_FOR_UNTRUSTED_CALLER) || FAILED(spObjectSafety->SetInterfaceSafetyOptions( iid, INTERFACESAFE_FOR_UNTRUSTED_CALLER, INTERFACESAFE_FOR_UNTRUSTED_CALLER)) || FAILED(spObjectSafety->GetInterfaceSafetyOptions( iid, &dwSupported, &dwEnabled)) || !(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER) { return FALSE; } } return TRUE; } /////////////////////////////////////////////////////////////////////////////// // Constructor CControlSite::CControlSite() { TRACE_METHOD(CControlSite::CControlSite); m_hWndParent = NULL; m_CLSID = CLSID_NULL; m_bSetClientSiteFirst = FALSE; m_bVisibleAtRuntime = TRUE; memset(&m_rcObjectPos, 0, sizeof(m_rcObjectPos)); m_bInPlaceActive = FALSE; m_bUIActive = FALSE; m_bInPlaceLocked = FALSE; m_bWindowless = FALSE; m_bSupportWindowlessActivation = TRUE; m_bSafeForScriptingObjectsOnly = FALSE; m_pSecurityPolicy = GetDefaultControlSecurityPolicy(); // Initialise ambient properties m_nAmbientLocale = 0; m_clrAmbientForeColor = ::GetSysColor(COLOR_WINDOWTEXT); m_clrAmbientBackColor = ::GetSysColor(COLOR_WINDOW); m_bAmbientUserMode = true; m_bAmbientShowHatching = true; m_bAmbientShowGrabHandles = true; m_bAmbientAppearance = true; // 3d // Windowless variables m_hDCBuffer = NULL; m_hRgnBuffer = NULL; m_hBMBufferOld = NULL; m_hBMBuffer = NULL; } // Destructor CControlSite::~CControlSite() { TRACE_METHOD(CControlSite::~CControlSite); Detach(); } // Create the specified control, optionally providing properties to initialise // it with and a name. HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl, LPCWSTR szCodebase, IBindCtx *pBindContext) { TRACE_METHOD(CControlSite::Create); m_CLSID = clsid; m_ParameterList = pl; // See if security policy will allow the control to be hosted if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid)) { return E_FAIL; } // See if object is script safe BOOL checkForObjectSafety = FALSE; if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly) { BOOL bClassExists = FALSE; BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists); if (!bClassExists && szCodebase) { // Class doesn't exist, so allow code below to fetch it } else if (!bIsSafe) { // The class is not flagged as safe for scripting, so // we'll have to create it to ask it if its safe. checkForObjectSafety = TRUE; } } //Now Check if the control version needs to be updated. BOOL bUpdateControlVersion = FALSE; wchar_t *szURL = NULL; DWORD dwFileVersionMS = 0xffffffff; DWORD dwFileVersionLS = 0xffffffff; if(szCodebase) { HKEY hk = NULL; wchar_t wszKey[60] = L""; wchar_t wszData[MAX_PATH]; LPWSTR pwszClsid = NULL; DWORD dwSize = 255; DWORD dwHandle, dwLength, dwRegReturn; DWORD dwExistingFileVerMS = 0xffffffff; DWORD dwExistingFileVerLS = 0xffffffff; BOOL bFoundLocalVerInfo = FALSE; StringFromCLSID(clsid, (LPOLESTR*)&pwszClsid); swprintf(wszKey, L"%s%s%s\0", L"CLSID\\", pwszClsid, L"\\InprocServer32"); if ( RegOpenKeyExW( HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hk ) == ERROR_SUCCESS ) { dwRegReturn = RegQueryValueExW( hk, L"", NULL, NULL, (LPBYTE)wszData, &dwSize ); RegCloseKey( hk ); } if(dwRegReturn == ERROR_SUCCESS) { VS_FIXEDFILEINFO *pFileInfo; UINT uLen; dwLength = GetFileVersionInfoSizeW( wszData , &dwHandle ); LPBYTE lpData = new BYTE[dwLength]; GetFileVersionInfoW(wszData, 0, dwLength, lpData ); bFoundLocalVerInfo = VerQueryValueW( lpData, L"\\", (LPVOID*)&pFileInfo, &uLen ); if(bFoundLocalVerInfo) { dwExistingFileVerMS = pFileInfo->dwFileVersionMS; dwExistingFileVerLS = pFileInfo->dwFileVersionLS; } delete [] lpData; } // Test if the code base ends in #version=a,b,c,d const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#')); if (szHash) { if (wcsnicmp(szHash, L"#version=", 9) == 0) { int a, b, c, d; if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4) { dwFileVersionMS = MAKELONG(b,a); dwFileVersionLS = MAKELONG(d,c); //If local version info was found compare it if(bFoundLocalVerInfo) { if(dwFileVersionMS > dwExistingFileVerMS) bUpdateControlVersion = TRUE; if((dwFileVersionMS == dwExistingFileVerMS) && (dwFileVersionLS > dwExistingFileVerLS)) bUpdateControlVersion = TRUE; } } } szURL = _wcsdup(szCodebase); // Terminate at the hash mark if (szURL) szURL[szHash - szCodebase] = wchar_t('\0'); } else { szURL = _wcsdup(szCodebase); } } CComPtr<IUnknown> spObject; HRESULT hr; //If the control needs to be updated do not call CoCreateInstance otherwise you will lock files //and force a reboot on CoGetClassObjectFromURL if(!bUpdateControlVersion) { // Create the object hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject); if (SUCCEEDED(hr) && checkForObjectSafety) { // Assume scripting via IDispatch if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch))) { return E_FAIL; } // Drop through, success! } } // Do we need to download the control? if ((FAILED(hr) && szCodebase) || (bUpdateControlVersion)) { if (!szURL) return E_OUTOFMEMORY; CComPtr<IBindCtx> spBindContext; CComPtr<IBindStatusCallback> spBindStatusCallback; CComPtr<IBindStatusCallback> spOldBSC; // Create our own bind context or use the one provided? BOOL useInternalBSC = FALSE; if (!pBindContext) { useInternalBSC = TRUE; hr = CreateBindCtx(0, &spBindContext); if (FAILED(hr)) { free(szURL); return hr; } spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this); hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0); if (FAILED(hr)) { free(szURL); return hr; } } else { spBindContext = pBindContext; } //If the version from the CODEBASE value is greater than the installed control //Call CoGetClassObjectFromURL with CLSID_NULL to prevent system change reboot prompt if(bUpdateControlVersion) { hr = CoGetClassObjectFromURL(CLSID_NULL, szCodebase, dwFileVersionMS, dwFileVersionLS, NULL, spBindContext, CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_SERVER, 0, IID_IClassFactory, NULL); } else { hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS, NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown, NULL); } free(szURL); // Handle the internal binding synchronously so the object exists // or an error code is available when the method returns. if (useInternalBSC) { if (MK_S_ASYNCHRONOUS == hr) { m_bBindingInProgress = TRUE; m_hrBindResult = E_FAIL; // Spin around waiting for binding to complete HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); while (m_bBindingInProgress) { MSG msg; // Process pending messages while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (!::GetMessage(&msg, NULL, 0, 0)) { m_bBindingInProgress = FALSE; break; } ::TranslateMessage(&msg); ::DispatchMessage(&msg); } if (!m_bBindingInProgress) break; // Sleep for a bit or the next msg to appear ::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS); } ::CloseHandle(hFakeEvent); // Set the result hr = m_hrBindResult; } // Destroy the bind status callback & context if (spBindStatusCallback) { RevokeBindStatusCallback(spBindContext, spBindStatusCallback); spBindStatusCallback.Release(); spBindContext.Release(); } } //added to create control if (SUCCEEDED(hr)) { // Create the object hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject); if (SUCCEEDED(hr) && checkForObjectSafety) { // Assume scripting via IDispatch if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch))) { hr = E_FAIL; } } } //EOF test code } if (spObject) { m_spObject = spObject; } return hr; } // Attach the created control to a window and activate it HRESULT CControlSite::Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream) { TRACE_METHOD(CControlSite::Attach); if (hwndParent == NULL) { NS_ASSERTION(0, "No parent hwnd"); return E_INVALIDARG; } m_hWndParent = hwndParent; m_rcObjectPos = rcPos; // Object must have been created if (m_spObject == NULL) { return E_UNEXPECTED; } m_spIViewObject = m_spObject; m_spIOleObject = m_spObject; if (m_spIOleObject == NULL) { return E_FAIL; } DWORD dwMiscStatus; m_spIOleObject->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus); if (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST) { m_bSetClientSiteFirst = TRUE; } if (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME) { m_bVisibleAtRuntime = FALSE; } // Some objects like to have the client site as the first thing // to be initialised (for ambient properties and so forth) if (m_bSetClientSiteFirst) { m_spIOleObject->SetClientSite(this); } // If there is a parameter list for the object and no init stream then // create one here. CPropertyBagInstance *pPropertyBag = NULL; if (pInitStream == NULL && m_ParameterList.GetSize() > 0) { CPropertyBagInstance::CreateInstance(&pPropertyBag); pPropertyBag->AddRef(); for (unsigned long i = 0; i < m_ParameterList.GetSize(); i++) { pPropertyBag->Write(m_ParameterList.GetNameOf(i), const_cast<VARIANT *>(m_ParameterList.GetValueOf(i))); } pInitStream = (IPersistPropertyBag *) pPropertyBag; } // Initialise the control from store if one is provided if (pInitStream) { CComQIPtr<IPropertyBag, &IID_IPropertyBag> spPropertyBag = pInitStream; CComQIPtr<IStream, &IID_IStream> spStream = pInitStream; CComQIPtr<IPersistStream, &IID_IPersistStream> spIPersistStream = m_spIOleObject; CComQIPtr<IPersistPropertyBag, &IID_IPersistPropertyBag> spIPersistPropertyBag = m_spIOleObject; if (spIPersistPropertyBag && spPropertyBag) { spIPersistPropertyBag->Load(spPropertyBag, NULL); } else if (spIPersistStream && spStream) { spIPersistStream->Load(spStream); } } else { // Initialise the object if possible CComQIPtr<IPersistStreamInit, &IID_IPersistStreamInit> spIPersistStreamInit = m_spIOleObject; if (spIPersistStreamInit) { spIPersistStreamInit->InitNew(); } } m_spIOleInPlaceObject = m_spObject; m_spIOleInPlaceObjectWindowless = m_spObject; if (m_spIOleInPlaceObject) { SetPosition(m_rcObjectPos); } // In-place activate the object if (m_bVisibleAtRuntime) { DoVerb(OLEIVERB_INPLACEACTIVATE); } // For those objects which haven't had their client site set yet, // it's done here. if (!m_bSetClientSiteFirst) { m_spIOleObject->SetClientSite(this); } return S_OK; } // Unhook the control from the window and throw it all away HRESULT CControlSite::Detach() { TRACE_METHOD(CControlSite::Detach); if (m_spIOleInPlaceObjectWindowless) { m_spIOleInPlaceObjectWindowless.Release(); } if (m_spIOleInPlaceObject) { m_spIOleInPlaceObject->InPlaceDeactivate(); m_spIOleInPlaceObject.Release(); } if (m_spIOleObject) { m_spIOleObject->Close(OLECLOSE_NOSAVE); m_spIOleObject->SetClientSite(NULL); m_spIOleObject.Release(); } m_spIViewObject.Release(); m_spObject.Release(); return S_OK; } // Return the IUnknown of the contained control HRESULT CControlSite::GetControlUnknown(IUnknown **ppObject) { *ppObject = NULL; if (m_spObject) { m_spObject->QueryInterface(IID_IUnknown, (void **) ppObject); } return S_OK; } // Subscribe to an event sink on the control HRESULT CControlSite::Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie) { if (m_spObject == NULL) { return E_UNEXPECTED; } if (pIUnkSink == NULL || pdwCookie == NULL) { return E_INVALIDARG; } return AtlAdvise(m_spObject, pIUnkSink, iid, pdwCookie); } // Unsubscribe event sink from the control HRESULT CControlSite::Unadvise(const IID &iid, DWORD dwCookie) { if (m_spObject == NULL) { return E_UNEXPECTED; } return AtlUnadvise(m_spObject, iid, dwCookie); } // Draw the control HRESULT CControlSite::Draw(HDC hdc) { TRACE_METHOD(CControlSite::Draw); // Draw only when control is windowless or deactivated if (m_spIViewObject) { if (m_bWindowless || !m_bInPlaceActive) { RECTL *prcBounds = (m_bWindowless) ? NULL : (RECTL *) &m_rcObjectPos; m_spIViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdc, prcBounds, NULL, NULL, 0); } } else { // Draw something to indicate no control is there HBRUSH hbr = CreateSolidBrush(RGB(200,200,200)); FillRect(hdc, &m_rcObjectPos, hbr); DeleteObject(hbr); } return S_OK; } // Execute the specified verb HRESULT CControlSite::DoVerb(LONG nVerb, LPMSG lpMsg) { TRACE_METHOD(CControlSite::DoVerb); if (m_spIOleObject == NULL) { return E_FAIL; } return m_spIOleObject->DoVerb(nVerb, lpMsg, this, 0, m_hWndParent, &m_rcObjectPos); } // Set the position on the control HRESULT CControlSite::SetPosition(const RECT &rcPos) { HWND hwnd; TRACE_METHOD(CControlSite::SetPosition); m_rcObjectPos = rcPos; if (m_spIOleInPlaceObject && SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&hwnd))) { m_spIOleInPlaceObject->SetObjectRects(&m_rcObjectPos, &m_rcObjectPos); } return S_OK; } void CControlSite::FireAmbientPropertyChange(DISPID id) { if (m_spObject) { CComQIPtr<IOleControl> spControl = m_spObject; if (spControl) { spControl->OnAmbientPropertyChange(id); } } } void CControlSite::SetAmbientUserMode(BOOL bUserMode) { bool bNewMode = bUserMode ? true : false; if (m_bAmbientUserMode != bNewMode) { m_bAmbientUserMode = bNewMode; FireAmbientPropertyChange(DISPID_AMBIENT_USERMODE); } } /////////////////////////////////////////////////////////////////////////////// // CControlSiteSecurityPolicy implementation CControlSiteSecurityPolicy *CControlSite::GetDefaultControlSecurityPolicy() { static CDefaultControlSiteSecurityPolicy defaultControlSecurityPolicy; return &defaultControlSecurityPolicy; } // Test if the class is safe to host BOOL CControlSite::IsClassSafeToHost(const CLSID & clsid) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsClassSafeToHost(clsid); return TRUE; } // Test if the specified class is marked safe for scripting BOOL CControlSite::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists); return TRUE; } // Test if the instantiated object is safe for scripting on the specified interface BOOL CControlSite::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsObjectSafeForScripting(pObject, iid); return TRUE; } BOOL CControlSite::IsObjectSafeForScripting(const IID &iid) { return IsObjectSafeForScripting(m_spObject, iid); } /////////////////////////////////////////////////////////////////////////////// // IServiceProvider implementation HRESULT STDMETHODCALLTYPE CControlSite::QueryService(REFGUID guidService, REFIID riid, void** ppv) { if (m_spServiceProvider) return m_spServiceProvider->QueryService(guidService, riid, ppv); return E_NOINTERFACE; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { if (wFlags & DISPATCH_PROPERTYGET) { CComVariant vResult; switch (dispIdMember) { case DISPID_AMBIENT_APPEARANCE: vResult = CComVariant(m_bAmbientAppearance); break; case DISPID_AMBIENT_FORECOLOR: vResult = CComVariant((long) m_clrAmbientForeColor); break; case DISPID_AMBIENT_BACKCOLOR: vResult = CComVariant((long) m_clrAmbientBackColor); break; case DISPID_AMBIENT_LOCALEID: vResult = CComVariant((long) m_nAmbientLocale); break; case DISPID_AMBIENT_USERMODE: vResult = CComVariant(m_bAmbientUserMode); break; case DISPID_AMBIENT_SHOWGRABHANDLES: vResult = CComVariant(m_bAmbientShowGrabHandles); break; case DISPID_AMBIENT_SHOWHATCHING: vResult = CComVariant(m_bAmbientShowHatching); break; default: return DISP_E_MEMBERNOTFOUND; } VariantCopy(pVarResult, &vResult); return S_OK; } return E_FAIL; } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink implementation void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed) { } void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex) { // Redraw the control InvalidateRect(NULL, FALSE); } void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk) { } void STDMETHODCALLTYPE CControlSite::OnSave(void) { } void STDMETHODCALLTYPE CControlSite::OnClose(void) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink2 implementation void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSinkEx implementation void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus) { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { *phwnd = m_hWndParent; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleClientSite implementation HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer) { if (!ppContainer) return E_INVALIDARG; *ppContainer = m_spContainer; if (*ppContainer) { (*ppContainer)->AddRef(); } return (*ppContainer) ? S_OK : E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE CControlSite::ShowObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnShowWindow(/* [in] */ BOOL fShow) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestNewObjectLayout(void) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSite implementation HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void) { m_bInPlaceActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void) { m_bUIActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo) { *lprcPosRect = m_rcObjectPos; *lprcClipRect = m_rcObjectPos; CControlSiteIPFrameInstance *pIPFrame = NULL; CControlSiteIPFrameInstance::CreateInstance(&pIPFrame); pIPFrame->AddRef(); *ppFrame = (IOleInPlaceFrame *) pIPFrame; *ppDoc = NULL; lpFrameInfo->fMDIApp = FALSE; lpFrameInfo->hwndFrame = NULL; lpFrameInfo->haccel = NULL; lpFrameInfo->cAccelEntries = 0; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable) { m_bUIActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect) { if (lprcPosRect == NULL) { return E_INVALIDARG; } SetPosition(m_rcObjectPos); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteEx implementation HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags) { m_bInPlaceActive = TRUE; if (pfNoRedraw) { *pfNoRedraw = FALSE; } if (dwFlags & ACTIVATE_WINDOWLESS) { if (!m_bSupportWindowlessActivation) { return E_INVALIDARG; } m_bWindowless = TRUE; } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void) { return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteWindowless implementation HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void) { // Allow windowless activation? return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC) { if (phDC == NULL) { return E_INVALIDARG; } // Can't do nested painting if (m_hDCBuffer != NULL) { return E_UNEXPECTED; } m_rcBuffer = m_rcObjectPos; if (pRect != NULL) { m_rcBuffer = *pRect; } m_hBMBuffer = NULL; m_dwBufferFlags = grfFlags; // See if the control wants a DC that is onscreen or offscreen if (m_dwBufferFlags & OLEDC_OFFSCREEN) { m_hDCBuffer = CreateCompatibleDC(NULL); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy); m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer); SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL); // TODO When OLEDC_PAINTBKGND we must draw every site behind this one } else { // TODO When OLEDC_PAINTBKGND we must draw every site behind this one // Get the window DC m_hDCBuffer = GetWindowDC(m_hWndParent); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } // Clip the control so it can't trash anywhere it isn't allowed to draw if (!(m_dwBufferFlags & OLEDC_NODRAW)) { m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer); // TODO Clip out opaque areas of sites behind this one SelectClipRgn(m_hDCBuffer, m_hRgnBuffer); } } *phDC = m_hDCBuffer; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC) { // Release the DC if (hDC == NULL || hDC != m_hDCBuffer) { return E_INVALIDARG; } // Test if the DC was offscreen or onscreen if ((m_dwBufferFlags & OLEDC_OFFSCREEN) && !(m_dwBufferFlags & OLEDC_NODRAW)) { // BitBlt the buffer into the control's object SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL); HDC hdc = GetWindowDC(m_hWndParent); long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY); ::ReleaseDC(m_hWndParent, hdc); } else { // TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one } // Clean up settings ready for next drawing if (m_hRgnBuffer) { SelectClipRgn(m_hDCBuffer, NULL); DeleteObject(m_hRgnBuffer); m_hRgnBuffer = NULL; } SelectObject(m_hDCBuffer, m_hBMBufferOld); if (m_hBMBuffer) { DeleteObject(m_hBMBuffer); m_hBMBuffer = NULL; } // Delete the DC if (m_dwBufferFlags & OLEDC_OFFSCREEN) { ::DeleteDC(m_hDCBuffer); } else { ::ReleaseDC(m_hWndParent, m_hDCBuffer); } m_hDCBuffer = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase) { // Clip the rectangle against the object's size and invalidate it RECT rcI = { 0, 0, 0, 0 }; if (pRect == NULL) { rcI = m_rcObjectPos; } else { IntersectRect(&rcI, &m_rcObjectPos, pRect); } ::InvalidateRect(m_hWndParent, &rcI, fErase); return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase) { if (hRGN == NULL) { ::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase); } else { // Clip the region with the object's bounding area HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos); if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR) { ::InvalidateRgn(m_hWndParent, hrgnClip, fErase); } DeleteObject(hrgnClip); } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc) { if (prc == NULL) { return E_INVALIDARG; } // Clip the rectangle against the object position RECT rcI = { 0, 0, 0, 0 }; IntersectRect(&rcI, &m_rcObjectPos, prc); *prc = rcI; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult) { if (plResult == NULL) { return E_INVALIDARG; } // Pass the message to the windowless control if (m_bWindowless && m_spIOleInPlaceObjectWindowless) { return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult); } else if (m_spIOleInPlaceObject) { HWND wnd; if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd))) SendMessage(wnd, msg, wParam, lParam); } return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleControlSite implementation HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock) { m_bInPlaceLocked = fLock; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags) { HRESULT hr = S_OK; if (pPtlHimetric == NULL) { return E_INVALIDARG; } if (pPtfContainer == NULL) { return E_INVALIDARG; } HDC hdc = ::GetDC(m_hWndParent); ::SetMapMode(hdc, MM_HIMETRIC); POINT rgptConvert[2]; rgptConvert[0].x = 0; rgptConvert[0].y = 0; if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER) { rgptConvert[1].x = pPtlHimetric->x; rgptConvert[1].y = pPtlHimetric->y; ::LPtoDP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x); pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y); } else if (dwFlags & XFORMCOORDS_POSITION) { pPtfContainer->x = (float)rgptConvert[1].x; pPtfContainer->y = (float)rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC) { rgptConvert[1].x = (int)(pPtfContainer->x); rgptConvert[1].y = (int)(pPtfContainer->y); ::DPtoLP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x; pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y; } else if (dwFlags & XFORMCOORDS_POSITION) { pPtlHimetric->x = rgptConvert[1].x; pPtlHimetric->y = rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else { hr = E_INVALIDARG; } ::ReleaseDC(m_hWndParent, hdc); return hr; } HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IBindStatusCallback implementation HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved, IBinding __RPC_FAR *pib) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError) { m_bBindingInProgress = FALSE; m_hrBindResult = hresult; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF, BINDINFO __RPC_FAR *pbindInfo) { *pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE; pbindInfo->cbSize = sizeof(BINDINFO); pbindInfo->szExtraInfo = NULL; memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM)); pbindInfo->grfBindInfoF = 0; pbindInfo->dwBindVerb = 0; pbindInfo->szCustomVerb = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC __RPC_FAR *pformatetc, STGMEDIUM __RPC_FAR *pstgmed) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid, IUnknown __RPC_FAR *punk) { return S_OK; } // IWindowForBindingUI HRESULT STDMETHODCALLTYPE CControlSite::GetWindow( /* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd) { *phwnd = NULL; return S_OK; }
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef IOLECOMMANDIMPL_H #define IOLECOMMANDIMPL_H // Implementation of the IOleCommandTarget interface. The template is // reasonably generic and reusable which is a good thing given how needlessly // complicated this interface is. Blame Microsoft for that and not me. // // To use this class, derive your class from it like this: // // class CComMyClass : public IOleCommandTargetImpl<CComMyClass> // { // ... Ensure IOleCommandTarget is listed in the interface map ... // BEGIN_COM_MAP(CComMyClass) // COM_INTERFACE_ENTRY(IOleCommandTarget) // // etc. // END_COM_MAP() // ... And then later on define the command target table ... // BEGIN_OLECOMMAND_TABLE() // OLECOMMAND_MESSAGE(OLECMDID_PRINT, NULL, ID_PRINT, L"Print", L"Print the page") // OLECOMMAND_MESSAGE(OLECMDID_SAVEAS, NULL, 0, L"SaveAs", L"Save the page") // OLECOMMAND_HANDLER(IDM_EDITMODE, &CGID_MSHTML, EditModeHandler, L"EditMode", L"Switch to edit mode") // END_OLECOMMAND_TABLE() // ... Now the window that OLECOMMAND_MESSAGE sends WM_COMMANDs to ... // HWND GetCommandTargetWindow() const // { // return m_hWnd; // } // ... Now procedures that OLECOMMAND_HANDLER calls ... // static HRESULT _stdcall EditModeHandler(CMozillaBrowser *pThis, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut); // } // // The command table defines which commands the object supports. Commands are // defined by a command id and a command group plus a WM_COMMAND id or procedure, // and a verb and short description. // // Notice that there are two macros for handling Ole Commands. The first, // OLECOMMAND_MESSAGE sends a WM_COMMAND message to the window returned from // GetCommandTargetWindow() (that the derived class must implement if it uses // this macro). // // The second, OLECOMMAND_HANDLER calls a static handler procedure that // conforms to the OleCommandProc typedef. The first parameter, pThis means // the static handler has access to the methods and variables in the class // instance. // // The OLECOMMAND_HANDLER macro is generally more useful when a command // takes parameters or needs to return a result to the caller. // template< class T > class IOleCommandTargetImpl : public IOleCommandTarget { struct OleExecData { const GUID *pguidCmdGroup; DWORD nCmdID; DWORD nCmdexecopt; VARIANT *pvaIn; VARIANT *pvaOut; }; public: typedef HRESULT (_stdcall *OleCommandProc)(T *pT, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut); struct OleCommandInfo { ULONG nCmdID; const GUID *pCmdGUID; ULONG nWindowsCmdID; OleCommandProc pfnCommandProc; wchar_t *szVerbText; wchar_t *szStatusText; }; // Query the status of the specified commands (test if is it supported etc.) virtual HRESULT STDMETHODCALLTYPE QueryStatus(const GUID __RPC_FAR *pguidCmdGroup, ULONG cCmds, OLECMD __RPC_FAR prgCmds[], OLECMDTEXT __RPC_FAR *pCmdText) { T* pT = static_cast<T*>(this); if (prgCmds == NULL) { return E_INVALIDARG; } OleCommandInfo *pCommands = pT->GetCommandTable(); ATLASSERT(pCommands); BOOL bCmdGroupFound = FALSE; BOOL bTextSet = FALSE; // Iterate through list of commands and flag them as supported/unsupported for (ULONG nCmd = 0; nCmd < cCmds; nCmd++) { // Unsupported by default prgCmds[nCmd].cmdf = 0; // Search the support command list for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++) { OleCommandInfo *pCI = &pCommands[nSupported]; if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0) { continue; } bCmdGroupFound = TRUE; if (pCI->nCmdID != prgCmds[nCmd].cmdID) { continue; } // Command is supported so flag it and possibly enable it prgCmds[nCmd].cmdf = OLECMDF_SUPPORTED; if (pCI->nWindowsCmdID != 0) { prgCmds[nCmd].cmdf |= OLECMDF_ENABLED; } // Copy the status/verb text for the first supported command only if (!bTextSet && pCmdText) { // See what text the caller wants wchar_t *pszTextToCopy = NULL; if (pCmdText->cmdtextf & OLECMDTEXTF_NAME) { pszTextToCopy = pCI->szVerbText; } else if (pCmdText->cmdtextf & OLECMDTEXTF_STATUS) { pszTextToCopy = pCI->szStatusText; } // Copy the text pCmdText->cwActual = 0; memset(pCmdText->rgwz, 0, pCmdText->cwBuf * sizeof(wchar_t)); if (pszTextToCopy) { // Don't exceed the provided buffer size size_t nTextLen = wcslen(pszTextToCopy); if (nTextLen > pCmdText->cwBuf) { nTextLen = pCmdText->cwBuf; } wcsncpy(pCmdText->rgwz, pszTextToCopy, nTextLen); pCmdText->cwActual = nTextLen; } bTextSet = TRUE; } break; } } // Was the command group found? if (!bCmdGroupFound) { OLECMDERR_E_UNKNOWNGROUP; } return S_OK; } // Execute the specified command virtual HRESULT STDMETHODCALLTYPE Exec(const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT __RPC_FAR *pvaIn, VARIANT __RPC_FAR *pvaOut) { T* pT = static_cast<T*>(this); BOOL bCmdGroupFound = FALSE; OleCommandInfo *pCommands = pT->GetCommandTable(); ATLASSERT(pCommands); // Search the support command list for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++) { OleCommandInfo *pCI = &pCommands[nSupported]; if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0) { continue; } bCmdGroupFound = TRUE; if (pCI->nCmdID != nCmdID) { continue; } // Send ourselves a WM_COMMAND windows message with the associated // identifier and exec data OleExecData cData; cData.pguidCmdGroup = pguidCmdGroup; cData.nCmdID = nCmdID; cData.nCmdexecopt = nCmdexecopt; cData.pvaIn = pvaIn; cData.pvaOut = pvaOut; if (pCI->pfnCommandProc) { pCI->pfnCommandProc(pT, pCI->pCmdGUID, pCI->nCmdID, nCmdexecopt, pvaIn, pvaOut); } else if (pCI->nWindowsCmdID != 0 && nCmdexecopt != OLECMDEXECOPT_SHOWHELP) { HWND hwndTarget = pT->GetCommandTargetWindow(); if (hwndTarget) { ::SendMessage(hwndTarget, WM_COMMAND, LOWORD(pCI->nWindowsCmdID), (LPARAM) &cData); } } else { // Command supported but not implemented continue; } return S_OK; } // Was the command group found? if (!bCmdGroupFound) { OLECMDERR_E_UNKNOWNGROUP; } return OLECMDERR_E_NOTSUPPORTED; } }; // Macros to be placed in any class derived from the IOleCommandTargetImpl // class. These define what commands are exposed from the object. #define BEGIN_OLECOMMAND_TABLE() \ OleCommandInfo *GetCommandTable() \ { \ static OleCommandInfo s_aSupportedCommands[] = \ { #define OLECOMMAND_MESSAGE(id, group, cmd, verb, desc) \ { id, group, cmd, NULL, verb, desc }, #define OLECOMMAND_HANDLER(id, group, handler, verb, desc) \ { id, group, 0, handler, verb, desc }, #define END_OLECOMMAND_TABLE() \ { 0, &GUID_NULL, 0, NULL, NULL, NULL } \ }; \ return s_aSupportedCommands; \ }; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITE_H #define CONTROLSITE_H #include "IOleCommandTargetImpl.h" #include "PropertyList.h" // If you created a class derived from CControlSite, use the following macro // in the interface map of the derived class to include all the necessary // interfaces. #define CCONTROLSITE_INTERFACES() \ COM_INTERFACE_ENTRY(IOleWindow) \ COM_INTERFACE_ENTRY(IOleClientSite) \ COM_INTERFACE_ENTRY(IOleInPlaceSite) \ COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSite, IOleInPlaceSiteWindowless) \ COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteEx, IOleInPlaceSiteWindowless) \ COM_INTERFACE_ENTRY(IOleControlSite) \ COM_INTERFACE_ENTRY(IDispatch) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSink, IAdviseSinkEx) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSink2, IAdviseSinkEx) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSinkEx, IAdviseSinkEx) \ COM_INTERFACE_ENTRY(IOleCommandTarget) \ COM_INTERFACE_ENTRY(IServiceProvider) \ COM_INTERFACE_ENTRY(IBindStatusCallback) \ COM_INTERFACE_ENTRY(IWindowForBindingUI) // Temoporarily removed by bug 200680. Stops controls misbehaving and calling // windowless methods when they shouldn't. // COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteWindowless, IOleInPlaceSiteWindowless) \ // Class that defines the control's security policy with regards to // what controls it hosts etc. class CControlSiteSecurityPolicy { public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid) = 0; // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) = 0; // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) = 0; }; // // Class for hosting an ActiveX control // // This class supports both windowed and windowless classes. The normal // steps to hosting a control are this: // // CControlSiteInstance *pSite = NULL; // CControlSiteInstance::CreateInstance(&pSite); // pSite->AddRef(); // pSite->Create(clsidControlToCreate); // pSite->Attach(hwndParentWindow, rcPosition); // // Where propertyList is a named list of values to initialise the new object // with, hwndParentWindow is the window in which the control is being created, // and rcPosition is the position in window coordinates where the control will // be rendered. // // Destruction is this: // // pSite->Detach(); // pSite->Release(); // pSite = NULL; class CControlSite : public CComObjectRootEx<CComSingleThreadModel>, public CControlSiteSecurityPolicy, public IOleClientSite, public IOleInPlaceSiteWindowless, public IOleControlSite, public IAdviseSinkEx, public IDispatch, public IServiceProvider, public IOleCommandTargetImpl<CControlSite>, public IBindStatusCallback, public IWindowForBindingUI { public: // Site management values // Handle to parent window HWND m_hWndParent; // Position of the site and the contained object RECT m_rcObjectPos; // Flag indicating if client site should be set early or late unsigned m_bSetClientSiteFirst:1; // Flag indicating whether control is visible or not unsigned m_bVisibleAtRuntime:1; // Flag indicating if control is in-place active unsigned m_bInPlaceActive:1; // Flag indicating if control is UI active unsigned m_bUIActive:1; // Flag indicating if control is in-place locked and cannot be deactivated unsigned m_bInPlaceLocked:1; // Flag indicating if the site allows windowless controls unsigned m_bSupportWindowlessActivation:1; // Flag indicating if control is windowless (after being created) unsigned m_bWindowless:1; // Flag indicating if only safely scriptable controls are allowed unsigned m_bSafeForScriptingObjectsOnly:1; // Pointer to an externally registered service provider CComPtr<IServiceProvider> m_spServiceProvider; // Pointer to the OLE container CComPtr<IOleContainer> m_spContainer; // Return the default security policy object static CControlSiteSecurityPolicy *GetDefaultControlSecurityPolicy(); protected: // Pointers to object interfaces // Raw pointer to the object CComPtr<IUnknown> m_spObject; // Pointer to objects IViewObject interface CComQIPtr<IViewObject, &IID_IViewObject> m_spIViewObject; // Pointer to object's IOleObject interface CComQIPtr<IOleObject, &IID_IOleObject> m_spIOleObject; // Pointer to object's IOleInPlaceObject interface CComQIPtr<IOleInPlaceObject, &IID_IOleInPlaceObject> m_spIOleInPlaceObject; // Pointer to object's IOleInPlaceObjectWindowless interface CComQIPtr<IOleInPlaceObjectWindowless, &IID_IOleInPlaceObjectWindowless> m_spIOleInPlaceObjectWindowless; // CLSID of the control CLSID m_CLSID; // Parameter list PropertyList m_ParameterList; // Pointer to the security policy CControlSiteSecurityPolicy *m_pSecurityPolicy; // Binding variables // Flag indicating whether binding is in progress unsigned m_bBindingInProgress; // Result from the binding operation HRESULT m_hrBindResult; // Double buffer drawing variables used for windowless controls // Area of buffer RECT m_rcBuffer; // Bitmap to buffer HBITMAP m_hBMBuffer; // Bitmap to buffer HBITMAP m_hBMBufferOld; // Device context HDC m_hDCBuffer; // Clipping area of site HRGN m_hRgnBuffer; // Flags indicating how the buffer was painted DWORD m_dwBufferFlags; // Ambient properties // Locale ID LCID m_nAmbientLocale; // Foreground colour COLORREF m_clrAmbientForeColor; // Background colour COLORREF m_clrAmbientBackColor; // Flag indicating if control should hatch itself bool m_bAmbientShowHatching:1; // Flag indicating if control should have grab handles bool m_bAmbientShowGrabHandles:1; // Flag indicating if control is in edit/user mode bool m_bAmbientUserMode:1; // Flag indicating if control has a 3d border or not bool m_bAmbientAppearance:1; protected: // Notifies the attached control of a change to an ambient property virtual void FireAmbientPropertyChange(DISPID id); public: // Construction and destruction // Constructor CControlSite(); // Destructor virtual ~CControlSite(); BEGIN_COM_MAP(CControlSite) CCONTROLSITE_INTERFACES() END_COM_MAP() BEGIN_OLECOMMAND_TABLE() END_OLECOMMAND_TABLE() // Returns the window used when processing ole commands HWND GetCommandTargetWindow() { return NULL; // TODO } // Object creation and management functions // Creates and initialises an object virtual HRESULT Create(REFCLSID clsid, PropertyList &pl = PropertyList(), LPCWSTR szCodebase = NULL, IBindCtx *pBindContext = NULL); // Attaches the object to the site virtual HRESULT Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream = NULL); // Detaches the object from the site virtual HRESULT Detach(); // Returns the IUnknown pointer for the object virtual HRESULT GetControlUnknown(IUnknown **ppObject); // Sets the bounding rectangle for the object virtual HRESULT SetPosition(const RECT &rcPos); // Draws the object using the provided DC virtual HRESULT Draw(HDC hdc); // Performs the specified action on the object virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL); // Sets an advise sink up for changes to the object virtual HRESULT Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie); // Removes an advise sink virtual HRESULT Unadvise(const IID &iid, DWORD dwCookie); // Register an external service provider object virtual void SetServiceProvider(IServiceProvider *pSP) { m_spServiceProvider = pSP; } virtual void SetContainer(IOleContainer *pContainer) { m_spContainer = pContainer; } // Set the security policy object. Ownership of this object remains with the caller and the security // policy object is meant to exist for as long as it is set here. virtual void SetSecurityPolicy(CControlSiteSecurityPolicy *pSecurityPolicy) { m_pSecurityPolicy = pSecurityPolicy; } virtual CControlSiteSecurityPolicy *GetSecurityPolicy() const { return m_pSecurityPolicy; } // Methods to set ambient properties virtual void SetAmbientUserMode(BOOL bUser); // Inline helper methods // Returns the object's CLSID virtual const CLSID &GetObjectCLSID() const { return m_CLSID; } // Tests if the object is valid or not virtual BOOL IsObjectValid() const { return (m_spObject) ? TRUE : FALSE; } // Returns the parent window to this one virtual HWND GetParentWindow() const { return m_hWndParent; } // Returns the inplace active state of the object virtual BOOL IsInPlaceActive() const { return m_bInPlaceActive; } // CControlSiteSecurityPolicy // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid); // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(const IID &iid); // IServiceProvider virtual HRESULT STDMETHODCALLTYPE QueryService(REFGUID guidService, REFIID riid, void** ppv); // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); // IAdviseSink implementation virtual /* [local] */ void STDMETHODCALLTYPE OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed); virtual /* [local] */ void STDMETHODCALLTYPE OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex); virtual /* [local] */ void STDMETHODCALLTYPE OnRename(/* [in] */ IMoniker __RPC_FAR *pmk); virtual /* [local] */ void STDMETHODCALLTYPE OnSave(void); virtual /* [local] */ void STDMETHODCALLTYPE OnClose(void); // IAdviseSink2 virtual /* [local] */ void STDMETHODCALLTYPE OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk); // IAdviseSinkEx implementation virtual /* [local] */ void STDMETHODCALLTYPE OnViewStatusChange(/* [in] */ DWORD dwViewStatus); // IOleWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleClientSite implementation virtual HRESULT STDMETHODCALLTYPE SaveObject(void); virtual HRESULT STDMETHODCALLTYPE GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk); virtual HRESULT STDMETHODCALLTYPE GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer); virtual HRESULT STDMETHODCALLTYPE ShowObject(void); virtual HRESULT STDMETHODCALLTYPE OnShowWindow(/* [in] */ BOOL fShow); virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void); // IOleInPlaceSite implementation virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void); virtual HRESULT STDMETHODCALLTYPE GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo); virtual HRESULT STDMETHODCALLTYPE Scroll(/* [in] */ SIZE scrollExtant); virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate(/* [in] */ BOOL fUndoable); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void); virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void); virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void); virtual HRESULT STDMETHODCALLTYPE OnPosRectChange(/* [in] */ LPCRECT lprcPosRect); // IOleInPlaceSiteEx implementation virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw); virtual HRESULT STDMETHODCALLTYPE RequestUIActivate(void); // IOleInPlaceSiteWindowless implementation virtual HRESULT STDMETHODCALLTYPE CanWindowlessActivate(void); virtual HRESULT STDMETHODCALLTYPE GetCapture(void); virtual HRESULT STDMETHODCALLTYPE SetCapture(/* [in] */ BOOL fCapture); virtual HRESULT STDMETHODCALLTYPE GetFocus(void); virtual HRESULT STDMETHODCALLTYPE SetFocus(/* [in] */ BOOL fFocus); virtual HRESULT STDMETHODCALLTYPE GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC); virtual HRESULT STDMETHODCALLTYPE ReleaseDC(/* [in] */ HDC hDC); virtual HRESULT STDMETHODCALLTYPE InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip); virtual HRESULT STDMETHODCALLTYPE AdjustRect(/* [out][in] */ LPRECT prc); virtual HRESULT STDMETHODCALLTYPE OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult); // IOleControlSite implementation virtual HRESULT STDMETHODCALLTYPE OnControlInfoChanged(void); virtual HRESULT STDMETHODCALLTYPE LockInPlaceActive(/* [in] */ BOOL fLock); virtual HRESULT STDMETHODCALLTYPE GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp); virtual HRESULT STDMETHODCALLTYPE TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers); virtual HRESULT STDMETHODCALLTYPE OnFocus(/* [in] */ BOOL fGotFocus); virtual HRESULT STDMETHODCALLTYPE ShowPropertyFrame( void); // IBindStatusCallback virtual HRESULT STDMETHODCALLTYPE OnStartBinding(/* [in] */ DWORD dwReserved, /* [in] */ IBinding __RPC_FAR *pib); virtual HRESULT STDMETHODCALLTYPE GetPriority(/* [out] */ LONG __RPC_FAR *pnPriority); virtual HRESULT STDMETHODCALLTYPE OnLowResource(/* [in] */ DWORD reserved); virtual HRESULT STDMETHODCALLTYPE OnProgress(/* [in] */ ULONG ulProgress, /* [in] */ ULONG ulProgressMax, /* [in] */ ULONG ulStatusCode, /* [in] */ LPCWSTR szStatusText); virtual HRESULT STDMETHODCALLTYPE OnStopBinding(/* [in] */ HRESULT hresult, /* [unique][in] */ LPCWSTR szError); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindInfo( /* [out] */ DWORD __RPC_FAR *grfBINDF, /* [unique][out][in] */ BINDINFO __RPC_FAR *pbindinfo); virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnDataAvailable(/* [in] */ DWORD grfBSCF, /* [in] */ DWORD dwSize, /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ STGMEDIUM __RPC_FAR *pstgmed); virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(/* [in] */ REFIID riid, /* [iid_is][in] */ IUnknown __RPC_FAR *punk); // IWindowForBindingUI virtual HRESULT STDMETHODCALLTYPE GetWindow(/* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd); }; typedef CComObject<CControlSite> CControlSiteInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "ControlEventSink.h" CControlEventSink::CControlEventSink() : m_dwEventCookie(0), m_bSubscribed(false), m_EventIID(GUID_NULL), events() { } CControlEventSink::~CControlEventSink() { UnsubscribeFromEvents(); } BOOL CControlEventSink::GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo) { iid = GUID_NULL; if (!pControl) { return E_INVALIDARG; } // IProvideClassInfo2 way is easiest // CComQIPtr<IProvideClassInfo2> classInfo2 = pControl; // if (classInfo2) // { // classInfo2->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid); // if (!::IsEqualIID(iid, GUID_NULL)) // { // return TRUE; // } // } // Yuck, the hard way CComQIPtr<IProvideClassInfo> classInfo = pControl; if (!classInfo) { return FALSE; } // Search the class type information for the default source interface // which is the outgoing event sink. CComPtr<ITypeInfo> classTypeInfo; classInfo->GetClassInfo(&classTypeInfo); if (!classTypeInfo) { return FALSE; } TYPEATTR *classAttr = NULL; if (FAILED(classTypeInfo->GetTypeAttr(&classAttr))) { return FALSE; } INT implFlags = 0; for (UINT i = 0; i < classAttr->cImplTypes; i++) { // Search for the interface with the [default, source] attr if (SUCCEEDED(classTypeInfo->GetImplTypeFlags(i, &implFlags)) && implFlags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE)) { CComPtr<ITypeInfo> eventSinkTypeInfo; HREFTYPE hRefType; if (SUCCEEDED(classTypeInfo->GetRefTypeOfImplType(i, &hRefType)) && SUCCEEDED(classTypeInfo->GetRefTypeInfo(hRefType, &eventSinkTypeInfo))) { TYPEATTR *eventSinkAttr = NULL; if (SUCCEEDED(eventSinkTypeInfo->GetTypeAttr(&eventSinkAttr))) { iid = eventSinkAttr->guid; if (typeInfo) { *typeInfo = eventSinkTypeInfo.p; (*typeInfo)->AddRef(); } eventSinkTypeInfo->ReleaseTypeAttr(eventSinkAttr); } } break; } } classTypeInfo->ReleaseTypeAttr(classAttr); return (!::IsEqualIID(iid, GUID_NULL)); } void CControlEventSink::UnsubscribeFromEvents() { if (m_bSubscribed) { DWORD tmpCookie = m_dwEventCookie; m_dwEventCookie = 0; m_bSubscribed = false; // Unsubscribe and reset - This seems to complete release and destroy us... m_spEventCP->Unadvise(tmpCookie); // Unadvise handles the Release //m_spEventCP.Release(); } } HRESULT CControlEventSink::SubscribeToEvents(IUnknown *pControl) { if (!pControl) { return E_INVALIDARG; } // Throw away any existing connections UnsubscribeFromEvents(); // Grab the outgoing event sink IID which will be used to subscribe // to events via the connection point container. IID iidEventSink; CComPtr<ITypeInfo> typeInfo; if (!GetEventSinkIID(pControl, iidEventSink, &typeInfo)) { return E_FAIL; } // Get the connection point CComQIPtr<IConnectionPointContainer> ccp = pControl; CComPtr<IConnectionPoint> cp; if (!ccp) { return E_FAIL; } // Custom IID m_EventIID = iidEventSink; DWORD dwCookie = 0; if (!ccp || FAILED(ccp->FindConnectionPoint(m_EventIID, &cp)) || FAILED(cp->Advise(this, &dwCookie))) { return E_FAIL; } m_bSubscribed = true; m_spEventCP = cp; m_dwEventCookie = dwCookie; m_spEventSinkTypeInfo = typeInfo; return S_OK; } HRESULT CControlEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { USES_CONVERSION; if (DISPATCH_METHOD != wFlags) { // any other reason to call us?! return S_FALSE; } EventMap::iterator cur = events.find(dispIdMember); if (events.end() != cur) { // invoke this event handler NPVariant result; NPVariant *args = NULL; if (pDispParams->cArgs > 0) { args = (NPVariant *)calloc(pDispParams->cArgs, sizeof(NPVariant)); if (!args) { return S_FALSE; } for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments in reverse order Variant2NPVar(&pDispParams->rgvarg[i], &args[pDispParams->cArgs - i - 1], instance); } } NPObject *globalObj = NULL; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); NPIdentifier handler = NPNFuncs.getstringidentifier(W2A((*cur).second)); bool success = NPNFuncs.invoke(instance, globalObj, handler, args, pDispParams->cArgs, &result); NPNFuncs.releaseobject(globalObj); for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments if (args[i].type == NPVariantType_String) { // was allocated earlier by Variant2NPVar NPNFuncs.memfree((void *)args[i].value.stringValue.UTF8Characters); } } if (!success) { return S_FALSE; } if (pVarResult) { // set the result NPVar2Variant(&result, pVarResult, instance); } NPNFuncs.releasevariantvalue(&result); } return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLEVENTSINK_H #define CONTROLEVENTSINK_H #include <map> // This class listens for events from the specified control class CControlEventSink : public CComObjectRootEx<CComSingleThreadModel>, public IDispatch { public: CControlEventSink(); // Current event connection point CComPtr<IConnectionPoint> m_spEventCP; CComPtr<ITypeInfo> m_spEventSinkTypeInfo; DWORD m_dwEventCookie; IID m_EventIID; typedef std::map<DISPID, wchar_t *> EventMap; EventMap events; NPP instance; protected: virtual ~CControlEventSink(); bool m_bSubscribed; static HRESULT WINAPI SinkQI(void* pv, REFIID riid, LPVOID* ppv, DWORD dw) { CControlEventSink *pThis = (CControlEventSink *) pv; if (!IsEqualIID(pThis->m_EventIID, GUID_NULL) && IsEqualIID(pThis->m_EventIID, riid)) { return pThis->QueryInterface(__uuidof(IDispatch), ppv); } return E_NOINTERFACE; } public: BEGIN_COM_MAP(CControlEventSink) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_FUNC_BLIND(0, SinkQI) END_COM_MAP() virtual HRESULT SubscribeToEvents(IUnknown *pControl); virtual void UnsubscribeFromEvents(); virtual BOOL GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo); virtual HRESULT InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); }; typedef CComObject<CControlEventSink> CControlEventSinkInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITEIPFRAME_H #define CONTROLSITEIPFRAME_H class CControlSiteIPFrame : public CComObjectRootEx<CComSingleThreadModel>, public IOleInPlaceFrame { public: CControlSiteIPFrame(); virtual ~CControlSiteIPFrame(); HWND m_hwndFrame; BEGIN_COM_MAP(CControlSiteIPFrame) COM_INTERFACE_ENTRY_IID(IID_IOleWindow, IOleInPlaceFrame) COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceUIWindow, IOleInPlaceFrame) COM_INTERFACE_ENTRY(IOleInPlaceFrame) END_COM_MAP() // IOleWindow virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleInPlaceUIWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetBorder(/* [out] */ LPRECT lprectBorder); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths); virtual HRESULT STDMETHODCALLTYPE SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName); // IOleInPlaceFrame implementation virtual HRESULT STDMETHODCALLTYPE InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject); virtual HRESULT STDMETHODCALLTYPE RemoveMenus(/* [in] */ HMENU hmenuShared); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetStatusText(/* [in] */ LPCOLESTR pszStatusText); virtual HRESULT STDMETHODCALLTYPE EnableModeless(/* [in] */ BOOL fEnable); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID); }; typedef CComObject<CControlSiteIPFrame> CControlSiteIPFrameInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "stdafx.h" #include "ControlSiteIPFrame.h" CControlSiteIPFrame::CControlSiteIPFrame() { m_hwndFrame = NULL; } CControlSiteIPFrame::~CControlSiteIPFrame() { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { if (phwnd == NULL) { return E_INVALIDARG; } *phwnd = m_hwndFrame; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceUIWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceFrame implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID) { return E_NOTIMPL; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYBAG_H #define PROPERTYBAG_H #include "PropertyList.h" // Object wrapper for property list. This class can be set up with a // list of properties and used to initialise a control with them class CPropertyBag : public CComObjectRootEx<CComSingleThreadModel>, public IPropertyBag { // List of properties in the bag PropertyList m_PropertyList; public: // Constructor CPropertyBag(); // Destructor virtual ~CPropertyBag(); BEGIN_COM_MAP(CPropertyBag) COM_INTERFACE_ENTRY(IPropertyBag) END_COM_MAP() // IPropertyBag methods virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog); virtual HRESULT STDMETHODCALLTYPE Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar); }; typedef CComObject<CPropertyBag> CPropertyBagInstance; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "ItemContainer.h" CItemContainer::CItemContainer() { } CItemContainer::~CItemContainer() { } /////////////////////////////////////////////////////////////////////////////// // IParseDisplayName implementation HRESULT STDMETHODCALLTYPE CItemContainer::ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut) { // TODO return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum) { HRESULT hr = E_NOTIMPL; /* if (ppenum == NULL) { return E_POINTER; } *ppenum = NULL; typedef CComObject<CComEnumOnSTL<IEnumUnknown, &IID_IEnumUnknown, IUnknown*, _CopyInterface<IUnknown>, CNamedObjectList > > enumunk; enumunk* p = NULL; p = new enumunk; if(p == NULL) { return E_OUTOFMEMORY; } hr = p->Init(); if (SUCCEEDED(hr)) { hr = p->QueryInterface(IID_IEnumUnknown, (void**) ppenum); } if (FAILED(hRes)) { delete p; } */ return hr; } HRESULT STDMETHODCALLTYPE CItemContainer::LockContainer(/* [in] */ BOOL fLock) { // TODO return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleItemContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject) { if (pszItem == NULL) { return E_INVALIDARG; } if (ppvObject == NULL) { return E_INVALIDARG; } *ppvObject = NULL; return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage) { // TODO return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::IsRunning(/* [in] */ LPOLESTR pszItem) { // TODO return MK_E_NOOBJECT; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <windows.h> #include <winreg.h> #include "ffactivex.h" #include "common/stdafx.h" #include "axhost.h" #include "atlutil.h" #include "authorize.h" // ---------------------------------------------------------------------------- #define SUB_KEY L"SOFTWARE\\MozillaPlugins\\@itstructures.com/ffactivex\\MimeTypes\\application/x-itst-activex" // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId); BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId); BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value); HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType); // --------------------------------------------------------------------------- HKEY BaseKeys[] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }; // ---------------------------------------------------------------------------- BOOL TestAuthorization (NPP Instance, int16 ArgC, char *ArgN[], char *ArgV[], const char *MimeType) { BOOL ret = FALSE; NPObject *globalObj = NULL; NPIdentifier identifier; NPVariant varLocation; NPVariant varHref; bool rc = false; int16 i; char *wrkHref; #ifdef NDEF _asm{int 3}; #endif if (Instance == NULL) { return (FALSE); } // Determine owning document // Get the window object. NPNFuncs.getvalue(Instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(Instance, globalObj, identifier, &varLocation); NPNFuncs.releaseobject(globalObj); if (!rc){ log(Instance, 0, "AxHost.TestAuthorization: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(Instance, locationObj, identifier, &varHref); NPNFuncs.releasevariantvalue(&varLocation); if (!rc) { log(Instance, 0, "AxHost.TestAuthorization: could not get the href from the location property"); return false; } ret = TRUE; wrkHref = (char *) alloca(varHref.value.stringValue.UTF8Length + 1); memcpy(wrkHref, varHref.value.stringValue.UTF8Characters, varHref.value.stringValue.UTF8Length); wrkHref[varHref.value.stringValue.UTF8Length] = 0x00; NPNFuncs.releasevariantvalue(&varHref); for (i = 0; i < ArgC; ++i) { // search for any needed information: clsid, event handling directives, etc. if (0 == strnicmp(ArgN[i], PARAM_CLSID, strlen(PARAM_CLSID))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CLSID, wrkHref, ArgV[i]); } else if (0 == strnicmp(ArgN[i], PARAM_PROGID, strlen(PARAM_PROGID))) { // The class id of the control we are asked to load ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_PROGID, wrkHref, ArgV[i]); } else if( 0 == strnicmp(ArgN[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CODEBASEURL, wrkHref, ArgV[i]); } } log(Instance, 1, "AxHost.TestAuthorization: returning %s", ret ? "True" : "False"); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId) { USES_CONVERSION; BOOL ret; ret = TestExplicitAuthorization(A2W(MimeType), A2W(AuthorizationType), A2W(DocumentUrl), A2W(ProgramId)); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId) { BOOL ret = FALSE; #ifndef NO_REGISTRY_AUTHORIZE HKEY hKey; HKEY hSubKey; ULONG i; ULONG j; ULONG keyNameLen; ULONG valueNameLen; wchar_t keyName[_MAX_PATH]; wchar_t valueName[_MAX_PATH]; if (DocumentUrl == NULL) { return (FALSE); } if (ProgramId == NULL) { return (FALSE); } #ifdef NDEF MessageBox(NULL, DocumentUrl, ProgramId, MB_OK); #endif if ((hKey = FindKey(MimeType, AuthorizationType)) != NULL) { for (i = 0; !ret; i++) { keyNameLen = sizeof(keyName); if (RegEnumKey(hKey, i, keyName, keyNameLen) == ERROR_SUCCESS) { if (WildcardMatch(keyName, DocumentUrl)) { if (RegOpenKeyEx(hKey, keyName, 0, KEY_QUERY_VALUE, &hSubKey) == ERROR_SUCCESS) { for (j = 0; ; j++) { valueNameLen = sizeof(valueName); if (RegEnumValue(hSubKey, j, valueName, &valueNameLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { break; } if (WildcardMatch(valueName, ProgramId)) { ret = TRUE; break; } } RegCloseKey(hSubKey); } if (ret) { break; } } } else { break; } } RegCloseKey(hKey); } #endif return (ret); } // ---------------------------------------------------------------------------- BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value) { size_t i; size_t j = 0; size_t maskLen; size_t valueLen; maskLen = wcslen(Mask); valueLen = wcslen(Value); for (i = 0; i < maskLen + 1; i++) { if (Mask[i] == '?') { j++; continue; } if (Mask[i] == '*') { for (; j < valueLen + 1; j++) { if (WildcardMatch(Mask + i + 1, Value + j)) { return (TRUE); } } return (FALSE); } if ((j <= valueLen) && (Mask[i] == tolower(Value[j]))) { j++; continue; } return (FALSE); } return (TRUE); } // ---------------------------------------------------------------------------- HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType) { HKEY ret = NULL; HKEY plugins; wchar_t searchKey[_MAX_PATH]; wchar_t pluginName[_MAX_PATH]; DWORD j; size_t i; for (i = 0; i < ARRAYSIZE(BaseKeys); i++) { if (RegOpenKeyEx(BaseKeys[i], L"SOFTWARE\\MozillaPlugins", 0, KEY_ENUMERATE_SUB_KEYS, &plugins) == ERROR_SUCCESS) { for (j = 0; ret == NULL; j++) { if (RegEnumKey(plugins, j, pluginName, sizeof(pluginName)) != ERROR_SUCCESS) { break; } wsprintf(searchKey, L"%s\\MimeTypes\\%s\\%s", pluginName, MimeType, AuthorizationType); if (RegOpenKeyEx(plugins, searchKey, 0, KEY_ENUMERATE_SUB_KEYS, &ret) == ERROR_SUCCESS) { break; } ret = NULL; } RegCloseKey(plugins); if (ret != NULL) { break; } } } return (ret); }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <comdef.h> #include "ffactivex.h" #include "scriptable.h" #include "axhost.h" #ifdef NO_REGISTRY_AUTHORIZE static const char *WellKnownProgIds[] = { NULL }; static const char *WellKnownClsIds[] = { NULL }; #endif static const bool AcceptOnlyWellKnown = false; static const bool TrustWellKnown = true; static bool isWellKnownProgId(const char *progid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!progid) { return false; } while (WellKnownProgIds[i]) { if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i]))) return true; ++i; } return false; #else return true; #endif } static bool isWellKnownClsId(const char *clsid) { #ifdef NO_REGISTRY_AUTHORIZE unsigned int i = 0; if (!clsid) { return false; } while (WellKnownClsIds[i]) { if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i]))) return true; ++i; } return false; #else return true; #endif } static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { LRESULT result; CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA); if (!host) { return DefWindowProc(hWnd, msg, wParam, lParam); } switch (msg) { case WM_SETFOCUS: case WM_KILLFOCUS: case WM_SIZE: if (host->Site) { host->Site->OnDefWindowMessage(msg, wParam, lParam, &result); return result; } else { return DefWindowProc(hWnd, msg, wParam, lParam); } // Window being destroyed case WM_DESTROY: break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return true; } CAxHost::~CAxHost() { log(instance, 0, "AxHost.~AXHost: destroying the control..."); if (Window){ if (OldProc) ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } if (Sink) { Sink->UnsubscribeFromEvents(); Sink->Release(); } if (Site) { Site->Detach(); Site->Release(); } CoFreeUnusedLibraries(); } CAxHost::CAxHost(NPP inst): instance(inst), ClsID(CLSID_NULL), isValidClsID(false), Sink(NULL), Site(NULL), Window(NULL), OldProc(NULL), Props(), isKnown(false), CodeBaseUrl(NULL) { } void CAxHost::setWindow(HWND win) { if (win != Window) { if (win) { // subclass window so we can intercept window messages and // do our drawing to it OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc); // associate window with our CAxHost object so we can access // it in the window procedure ::SetWindowLong(win, GWL_USERDATA, (LONG)this); } else { if (OldProc) ::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc); ::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL); } Window = win; } } HWND CAxHost::getWinfow() { return Window; } void CAxHost::UpdateRect(RECT rcPos) { HRESULT hr = -1; if (Site && Window) { if (Site->GetParentWindow() == NULL) { hr = Site->Attach(Window, rcPos, NULL); if (FAILED(hr)) { log(instance, 0, "AxHost.UpdateRect: failed to attach control"); } } else { Site->SetPosition(rcPos); } // Ensure clipping on parent to keep child controls happy ::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN); } } bool CAxHost::verifyClsID(LPOLESTR oleClsID) { CRegKey keyExplorer; if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"), KEY_READ)) { CRegKey keyCLSID; if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) { DWORD dwType = REG_DWORD; DWORD dwFlags = 0; DWORD dwBufSize = sizeof(dwFlags); if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID, _T("Compatibility Flags"), NULL, &dwType, (LPBYTE) &dwFlags, &dwBufSize)) { // Flags for this reg key const DWORD kKillBit = 0x00000400; if (dwFlags & kKillBit) { log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits"); return false; } } } } log(instance, 1, "AxHost.verifyClsID: verified successfully"); return true; } bool CAxHost::setClsID(const char *clsid) { HRESULT hr = -1; USES_CONVERSION; LPOLESTR oleClsID = A2OLE(clsid); if (isWellKnownClsId(clsid)) { isKnown = true; } else if (AcceptOnlyWellKnown) { log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list"); return false; } // Check the Internet Explorer list of vulnerable controls if (oleClsID && verifyClsID(oleClsID)) { hr = CLSIDFromString(oleClsID, &ClsID); if (SUCCEEDED(hr) && !::IsEqualCLSID(ClsID, CLSID_NULL)) { isValidClsID = true; log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid); return true; } } log(instance, 0, "AxHost.setClsID: failed to set the requested clsid"); return false; } void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl) { CodeBaseUrl = codeBaseUrl; } bool CAxHost::setClsIDFromProgID(const char *progid) { HRESULT hr = -1; CLSID clsid = CLSID_NULL; USES_CONVERSION; LPOLESTR oleClsID = NULL; LPOLESTR oleProgID = A2OLE(progid); if (AcceptOnlyWellKnown) { if (isWellKnownProgId(progid)) { isKnown = true; } else { log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list"); return false; } } hr = CLSIDFromProgID(oleProgID, &clsid); if (FAILED(hr)) { log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID"); return false; } hr = StringFromCLSID(clsid, &oleClsID); // Check the Internet Explorer list of vulnerable controls if ( SUCCEEDED(hr) && oleClsID && verifyClsID(oleClsID)) { ClsID = clsid; if (!::IsEqualCLSID(ClsID, CLSID_NULL)) { isValidClsID = true; log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid); return true; } } log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID"); return false; } bool CAxHost::hasValidClsID() { return isValidClsID; } bool CAxHost::CreateControl(bool subscribeToEvents) { if (!isValidClsID) { log(instance, 0, "AxHost.CreateControl: current location is not trusted"); return false; } // Create the control site CControlSiteInstance::CreateInstance(&Site); if (Site == NULL) { log(instance, 0, "AxHost.CreateControl: CreateInstance failed"); return false; } Site->m_bSupportWindowlessActivation = false; if (TrustWellKnown && isKnown) { Site->SetSecurityPolicy(NULL); Site->m_bSafeForScriptingObjectsOnly = false; } else { Site->m_bSafeForScriptingObjectsOnly = true; } Site->AddRef(); // Create the object HRESULT hr; hr = Site->Create(ClsID, Props, CodeBaseUrl); if (FAILED(hr)) { LPSTR lpMsgBuf; DWORD dw = GetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &lpMsgBuf, 0, NULL ); log(instance, 0, lpMsgBuf); log(instance, 0, "AxHost.CreateControl: failed to create site"); return false; } IUnknown *control = NULL; Site->GetControlUnknown(&control); if (!control) { log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)"); return false; } // Create the event sink CControlEventSinkInstance::CreateInstance(&Sink); Sink->AddRef(); Sink->instance = instance; hr = Sink->SubscribeToEvents(control); control->Release(); if (FAILED(hr) && subscribeToEvents) { LPSTR lpMsgBuf; DWORD dw = GetLastError(); FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &lpMsgBuf, 0, NULL ); log(instance, 0, lpMsgBuf); log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed"); return false; } log(instance, 1, "AxHost.CreateControl: control created successfully"); return true; } bool CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler) { HRESULT hr; DISPID id = 0; USES_CONVERSION; LPOLESTR oleName = name; if (!Sink) { log(instance, 0, "AxHost.AddEventHandler: no valid sink"); return false; } hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id); if (FAILED(hr)) { log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name"); return false; } Sink->events[id] = handler; log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name); return true; } int16 CAxHost::HandleEvent(void *event) { NPEvent *npEvent = (NPEvent *)event; LRESULT result = 0; if (!npEvent) { return 0; } // forward all events to the hosted control return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result); } NPObject * CAxHost::GetScriptableObject() { IUnknown *unk; NPObject *obj = NPNFuncs.createobject(instance, &ScriptableNPClass); Site->GetControlUnknown(&unk); ((Scriptable *)obj)->setControl(unk); ((Scriptable *)obj)->setInstance(instance); return obj; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <algorithm> #include <string> #include "GenericNPObject.h" static NPObject* AllocateGenericNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, false); } static NPObject* AllocateMethodNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, true); } static void DeallocateGenericNPObject(NPObject *obj) { if (!obj) { return; } GenericNPObject *m = (GenericNPObject *)obj; delete m; } static void InvalidateGenericNPObject(NPObject *obj) { if (!obj) { return; } ((GenericNPObject *)obj)->Invalidate(); } NPClass GenericNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateGenericNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; NPClass MethodNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateMethodNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; // Some standard JavaScript methods bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) { GenericNPObject *map = (GenericNPObject *)object; if (!map || map->invalid) return false; // no args expected or cared for... std::string out; std::vector<NPVariant>::iterator it; for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) { if (NPVARIANT_IS_VOID(*it)) { out += ","; } else if (NPVARIANT_IS_NULL(*it)) { out += ","; } else if (NPVARIANT_IS_BOOLEAN(*it)) { if ((*it).value.boolValue) { out += "true,"; } else { out += "false,"; } } else if (NPVARIANT_IS_INT32(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%d,", (*it).value.intValue); out += tmp; } else if (NPVARIANT_IS_DOUBLE(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%f,", (*it).value.doubleValue); out += tmp; } else if (NPVARIANT_IS_STRING(*it)) { out += (*it).value.stringValue.UTF8Characters; out += ","; } else if (NPVARIANT_IS_OBJECT(*it)) { out += "[object],"; } } // calculate how much space we need std::string::size_type size = out.length(); char *s = (char *)NPNFuncs.memalloc(size * sizeof(char)); if (NULL == s) { return false; } memcpy(s, out.c_str(), size); s[size - 1] = 0; // overwrite the last "," STRINGZ_TO_NPVARIANT(s, (*result)); return true; } // Some helpers static void free_numeric_element(NPVariant elem) { NPNFuncs.releasevariantvalue(&elem); } static void free_alpha_element(std::pair<const char *, NPVariant> elem) { NPNFuncs.releasevariantvalue(&(elem.second)); } // And now the GenericNPObject implementation GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj): invalid(false), defInvoker(NULL), defInvokerObject(NULL) { NPVariant val; INT32_TO_NPVARIANT(0, val); immutables["length"] = val; if (!isMethodObj) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &MethodNPObjectClass); if (NULL == obj) { throw NULL; } ((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this); OBJECT_TO_NPVARIANT(obj, val); immutables["toString"] = val; } } GenericNPObject::~GenericNPObject() { for_each(immutables.begin(), immutables.end(), free_alpha_element); for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element); for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element); } bool GenericNPObject::HasMethod(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL != immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault); } } } return false; } bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(immutables[key]) && immutables[key].value.objectValue->_class->invokeDefault) { return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result); } } else if (alpha_mapper.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(alpha_mapper[key]) && alpha_mapper[key].value.objectValue->_class->invokeDefault) { return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result); } } } return true; } bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (defInvoker) { defInvoker(defInvokerObject, args, argCount, result); } return true; } // This method is also called before the JS engine attempts to add a new // property, most likely it's trying to check that the key is supported. // It only returns false if the string name was not found, or does not // hold a callable object bool GenericNPObject::HasProperty(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL == immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault); } } return false; } return true; } static bool CopyNPVariant(NPVariant *dst, const NPVariant *src) { dst->type = src->type; if (NPVARIANT_IS_STRING(*src)) { NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8)); if (NULL == str) { return false; } dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length; memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length); str[dst->value.stringValue.UTF8Length] = 0; dst->value.stringValue.UTF8Characters = str; } else if (NPVARIANT_IS_OBJECT(*src)) { NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src)); dst->value.objectValue = src->value.objectValue; } else { dst->value = src->value; } return true; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (!CopyNPVariant(result, &(immutables[key]))) { return false; } } else if (alpha_mapper.count(key) > 0) { if (!CopyNPVariant(result, &(alpha_mapper[key]))) { return false; } } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { if (!CopyNPVariant(result, &(numeric_mapper[key]))) { return false; } } } } catch (...) { } return true; } bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { // the key is already defined as immutable, check the new value type if (value->type != immutables[key].type) { return false; } // Seems ok, copy the new value if (!CopyNPVariant(&(immutables[key]), value)) { return false; } } else if (!CopyNPVariant(&(alpha_mapper[key]), value)) { return false; } } else { // assume int... NPVariant var; if (!CopyNPVariant(&var, value)) { return false; } unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (key >= numeric_mapper.size()) { // there's a gap we need to fill NPVariant pad; VOID_TO_NPVARIANT(pad); numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad); } numeric_mapper.at(key) = var; NPVARIANT_TO_INT32(immutables["length"])++; } } catch (...) { } return true; } bool GenericNPObject::RemoveProperty(NPIdentifier name) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (alpha_mapper.count(key) > 0) { NPNFuncs.releasevariantvalue(&(alpha_mapper[key])); alpha_mapper.erase(key); } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { NPNFuncs.releasevariantvalue(&(numeric_mapper[key])); numeric_mapper.erase(numeric_mapper.begin() + key); } NPVARIANT_TO_INT32(immutables["length"])--; } } catch (...) { } return true; } bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) { if (invalid) return false; try { *identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size()); if (NULL == *identifiers) { return false; } *identifierCount = 0; std::vector<NPVariant>::iterator it; unsigned int i = 0; char str[10] = ""; for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) { // skip empty (padding) elements if (NPVARIANT_IS_VOID(*it)) continue; _snprintf(str, sizeof(str), "%u", i); (*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str); } } catch (...) { } return true; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "scriptable.h" static NPObject* AllocateScriptable(NPP npp, NPClass *aClass) { return new Scriptable(); } static void DeallocateScriptable(NPObject *obj) { if (!obj) { return; } Scriptable *s = (Scriptable *)obj; delete s; } static void InvalidateScriptable(NPObject *obj) { if (!obj) { return; } ((Scriptable *)obj)->Invalidate(); } NPClass ScriptableNPClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateScriptable, /* deallocate */ DeallocateScriptable, /* invalidate */ InvalidateScriptable, /* hasMethod */ Scriptable::_HasMethod, /* invoke */ Scriptable::_Invoke, /* invokeDefault */ NULL, /* hasProperty */ Scriptable::_HasProperty, /* getProperty */ Scriptable::_GetProperty, /* setProperty */ Scriptable::_SetProperty, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // ffactivex.cpp : Defines the exported functions for the DLL application. // #include "ffactivex.h" #include "common/stdafx.h" #include "axhost.h" #include "atlutil.h" #include "authorize.h" // A list of trusted domains // Each domain name may start with a '*' to specify that sub domains are // trusted as well // Note that a '.' is not enforced after the '*' static const char *TrustedLocations[] = {NULL}; static const unsigned int numTrustedLocations = 0; static const char *LocalhostName = "localhost"; static const bool TrustLocalhost = true; void * ffax_calloc(unsigned int size) { void *ptr = NULL; ptr = NPNFuncs.memalloc(size); if (ptr) { memset(ptr, 0, size); } return ptr; } void ffax_free(void *ptr) { if (ptr) NPNFuncs.memfree(ptr); } // // Gecko API // static unsigned int log_level = 0; static char *logger = NULL; void log(NPP instance, unsigned int level, char *message, ...) { NPVariant result; NPVariant args; NPObject *globalObj = NULL; bool rc = false; char *formatted = NULL; char *new_formatted = NULL; int buff_len = 0; int size = 0; va_list list; if (!logger || (level > log_level)) { return; } buff_len = strlen(message); buff_len += buff_len / 10; formatted = (char *)calloc(1, buff_len); while (true) { va_start(list, message); size = vsnprintf_s(formatted, buff_len, _TRUNCATE, message, list); va_end(list); if (size > -1 && size < buff_len) break; buff_len *= 2; new_formatted = (char *)realloc(formatted, buff_len); if (NULL == new_formatted) { free(formatted); return; } formatted = new_formatted; new_formatted = NULL; } NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); NPIdentifier handler = NPNFuncs.getstringidentifier(logger); STRINGZ_TO_NPVARIANT(formatted, args); bool success = NPNFuncs.invoke(instance, globalObj, handler, &args, 1, &result); NPNFuncs.releasevariantvalue(&result); NPNFuncs.releaseobject(globalObj); free(formatted); } static bool MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl) { USES_CONVERSION; bool rc = false; CUrl url; if (!numTrustedLocations) { return true; } rc = url.CrackUrl(matchUrl, ATL_URL_DECODE); if (!rc) { log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL"); return false; } if ( (url.GetScheme() == ATL_URL_SCHEME_FILE) || (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){ return TrustLocalhost; } for (unsigned int i = 0; i < numTrustedLocations; ++i) { if (TrustedLocations[i][0] == '*') { // sub domains are trusted unsigned int len = strlen(TrustedLocations[i]); bool match = 0; if (url.GetHostNameLength() < len) { // can't be a match continue; } --len; // skip the '*' match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name TrustedLocations[i] + 1, // skip the '*' len) == 0 ? true : false; if (match) { return true; } } else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) { return true; } } return false; } static bool VerifySiteLock(NPP instance) { USES_CONVERSION; NPObject *globalObj = NULL; NPIdentifier identifier; NPVariant varLocation; NPVariant varHref; bool rc = false; // Get the window object. NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation); NPNFuncs.releaseobject(globalObj); if (!rc){ log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref); NPNFuncs.releasevariantvalue(&varLocation); if (!rc) { log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property"); return false; } rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters)); NPNFuncs.releasevariantvalue(&varHref); if (false == rc) { log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted"); } return rc; } /* * Create a new plugin instance, most probably through an embed/object HTML * element. * * Any private data we want to keep for this instance can be saved into * [instance->pdata]. * [saved] might hold information a previous instance that was invoked from the * same URL has saved for us. */ NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { NPError rc = NPERR_NO_ERROR; NPObject *browser = NULL; CAxHost *host = NULL; PropertyList events; int16 i = 0; USES_CONVERSION; //_asm {int 3}; if (!instance || (0 == NPNFuncs.size)) { return NPERR_INVALID_PARAM; } #ifdef NO_REGISTRY_AUTHORIZE // Verify that we're running from a trusted location if (!VerifySiteLock(instance)) { return NPERR_GENERIC_ERROR; } #endif instance->pdata = NULL; #ifndef NO_REGISTRY_AUTHORIZE if (!TestAuthorization (instance, argc, argn, argv, pluginType)) { return NPERR_GENERIC_ERROR; } #endif // TODO: Check the pluginType to make sure we're being called with the rigth MIME Type do { // Create a plugin instance, the actual control will be created once we // are given a window handle host = new CAxHost(instance); if (!host) { rc = NPERR_OUT_OF_MEMORY_ERROR; log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host"); break; } // Iterate over the arguments we've been passed for (i = 0; (i < argc) && (NPERR_NO_ERROR == rc); ++i) { // search for any needed information: clsid, event handling directives, etc. if (0 == strnicmp(argn[i], PARAM_CLSID, strlen(PARAM_CLSID))) { // The class id of the control we are asked to load host->setClsID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_PROGID, strlen(PARAM_PROGID))) { // The class id of the control we are asked to load host->setClsIDFromProgID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_DEBUG, strlen(PARAM_DEBUG))) { // Logging verbosity log_level = atoi(argv[i]); log(instance, 0, "AxHost.NPP_New: debug level set to %d", log_level); } else if (0 == strnicmp(argn[i], PARAM_LOGGER, strlen(PARAM_LOGGER))) { // Logger function logger = strdup(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_ONEVENT, strlen(PARAM_ONEVENT))) { // A request to handle one of the activex's events in JS events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i]))); } else if (0 == strnicmp(argn[i], PARAM_PARAM, strlen(PARAM_PARAM))) { CComBSTR paramName = argn[i] + strlen(PARAM_PARAM); CComBSTR paramValue(Utf8StringToBstr(argv[i], strlen(argv[i]))); // Check for existing params with the same name BOOL bFound = FALSE; for (unsigned long j = 0; j < host->Props.GetSize(); j++) { if (wcscmp(host->Props.GetNameOf(j), (BSTR) paramName) == 0) { bFound = TRUE; break; } } // If the parameter already exists, don't add it to the // list again. if (bFound) { continue; } // Add named parameter to list CComVariant v(paramValue); host->Props.AddNamedProperty(paramName, v); } else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) { if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) { host->setCodeBaseUrl(A2W(argv[i])); } else { log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location"); } } } if (NPERR_NO_ERROR != rc) break; // Make sure we have all the information we need to initialize a new instance if (!host->hasValidClsID()) { rc = NPERR_INVALID_PARAM; log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID"); break; } instance->pdata = host; // if no events were requested, don't fail if subscribing fails if (!host->CreateControl(events.GetSize() ? true : false)) { rc = NPERR_GENERIC_ERROR; log(instance, 0, "AxHost.NPP_New: failed to create the control"); break; } for (unsigned int j = 0; j < events.GetSize(); j++) { if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) { //rc = NPERR_GENERIC_ERROR; //break; } } if (NPERR_NO_ERROR != rc) break; } while (0); if (NPERR_NO_ERROR != rc) { delete host; } return rc; } /* * Destroy an existing plugin instance. * * [save] can be used to save information for a future instance of our plugin * that'll be invoked by the same URL. */ NPError NPP_Destroy(NPP instance, NPSavedData **save) { // _asm {int 3}; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } log(instance, 0, "NPP_Destroy: destroying the control..."); CAxHost *host = (CAxHost *)instance->pdata; delete host; instance->pdata = NULL; return NPERR_NO_ERROR; } /* * Sets an instance's window parameters. */ NPError NPP_SetWindow(NPP instance, NPWindow *window) { CAxHost *host = NULL; RECT rcPos; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } host = (CAxHost *)instance->pdata; host->setWindow((HWND)window->window); rcPos.left = 0; rcPos.top = 0; rcPos.right = window->width; rcPos.bottom = window->height; host->UpdateRect(rcPos); return NPERR_NO_ERROR; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <atlbase.h> #include <atlsafe.h> #include <npapi.h> #include <npfunctions.h> #include <prtypes.h> #include <npruntime.h> #include "scriptable.h" #include "GenericNPObject.h" #include "variants.h" extern NPNetscapeFuncs NPNFuncs; BSTR Utf8StringToBstr(LPCSTR szStr, int iSize) { BSTR bstrVal; // Chars required for string int iReq = 0; if (iSize > 0) { if ((iReq = MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, 0, 0)) == 0) { return (0); } } // Account for terminating 0. if (iReq != -1) { ++iReq; } if ((bstrVal = ::SysAllocStringLen(0, iReq)) == 0) { return (0); } memset(bstrVal, 0, iReq * sizeof(wchar_t)); if (iSize > 0) { // Convert into the buffer. if (MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, bstrVal, iReq) == 0) { ::SysFreeString(bstrVal); return 0; } } return (bstrVal); } void BSTR2NPVar(BSTR bstr, NPVariant *npvar, NPP instance) { USES_CONVERSION; char *npStr = NULL; size_t sourceLen; size_t bytesNeeded; sourceLen = lstrlenW(bstr); bytesNeeded = WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, NULL, 0, NULL, NULL); bytesNeeded += 1; // complete lack of documentation on Mozilla's part here, I have no // idea how this string is supposed to be freed npStr = (char *)NPNFuncs.memalloc(bytesNeeded); if (npStr) { memset(npStr, 0, bytesNeeded); WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, npStr, bytesNeeded - 1, NULL, NULL); STRINGZ_TO_NPVARIANT(npStr, (*npvar)); } else { STRINGZ_TO_NPVARIANT(NULL, (*npvar)); } } void Dispatch2NPVar(IDispatch *disp, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &ScriptableNPClass); ((Scriptable *)obj)->setControl(disp); ((Scriptable *)obj)->setInstance(instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } void Unknown2NPVar(IUnknown *unk, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &ScriptableNPClass); ((Scriptable *)obj)->setControl(unk); ((Scriptable *)obj)->setInstance(instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } NPObject * SafeArray2NPObject(SAFEARRAY *parray, unsigned short dim, unsigned long *pindices, NPP instance) { unsigned long *indices = pindices; NPObject *obj = NULL; bool rc = true; if (!parray || !instance) { return NULL; } obj = NPNFuncs.createobject(instance, &GenericNPObjectClass); if (NULL == obj) { return NULL; } do { if (NULL == indices) { // just getting started SafeArrayLock(parray); indices = (unsigned long *)calloc(1, parray->cDims * sizeof(unsigned long)); if (NULL == indices) { rc = false; break; } } NPIdentifier id = NULL; NPVariant val; VOID_TO_NPVARIANT(val); for(indices[dim] = 0; indices[dim] < parray->rgsabound[dim].cElements; indices[dim]++) { if (dim == (parray->cDims - 1)) { // single dimension (or the bottom of the recursion) if (parray->fFeatures & FADF_VARIANT) { VARIANT variant; VariantInit(&variant); if(FAILED(SafeArrayGetElement(parray, (long *)indices, &variant))) { rc = false; break; } Variant2NPVar(&variant, &val, instance); VariantClear(&variant); } else if (parray->fFeatures & FADF_BSTR) { BSTR bstr; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &bstr))) { rc = false; break; } BSTR2NPVar(bstr, &val, instance); } else if (parray->fFeatures & FADF_DISPATCH) { IDispatch *disp; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &disp))) { rc = false; break; } Dispatch2NPVar(disp, &val, instance); } else if (parray->fFeatures & FADF_UNKNOWN) { IUnknown *unk; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &unk))) { rc = false; break; } Unknown2NPVar(unk, &val, instance); } } else { // recurse NPObject *o = SafeArray2NPObject(parray, dim + 1, indices, instance); if (NULL == o) { rc = false; break; } OBJECT_TO_NPVARIANT(o, val); } id = NPNFuncs.getintidentifier(parray->rgsabound[dim].lLbound + indices[dim]); // setproperty will call retainobject or copy the internal string, we should // release variant NPNFuncs.setproperty(instance, obj, id, &val); NPNFuncs.releasevariantvalue(&val); VOID_TO_NPVARIANT(val); } } while (0); if (false == rc) { if (!pindices && indices) { free(indices); indices = NULL; SafeArrayUnlock(parray); } if (obj) { NPNFuncs.releaseobject(obj); obj = NULL; } } return obj; } #define GETVALUE(var, val) (((var->vt) & VT_BYREF) ? *(var->p##val) : (var->val)) void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; SAFEARRAY *parray = NULL; if (!var || !npvar) { return; } VOID_TO_NPVARIANT(*npvar); switch (var->vt & ~VT_BYREF) { case VT_EMPTY: VOID_TO_NPVARIANT((*npvar)); break; case VT_NULL: NULL_TO_NPVARIANT((*npvar)); break; case VT_LPSTR: // not sure it can even appear in a VARIANT, but... STRINGZ_TO_NPVARIANT(var->pcVal, (*npvar)); break; case VT_BSTR: BSTR2NPVar(GETVALUE(var, bstrVal), npvar, instance); break; case VT_I1: INT32_TO_NPVARIANT((int32)GETVALUE(var, cVal), (*npvar)); break; case VT_I2: INT32_TO_NPVARIANT((int32)GETVALUE(var, iVal), (*npvar)); break; case VT_I4: INT32_TO_NPVARIANT((int32)GETVALUE(var, lVal), (*npvar)); break; case VT_UI1: INT32_TO_NPVARIANT((int32)GETVALUE(var, bVal), (*npvar)); break; case VT_UI2: INT32_TO_NPVARIANT((int32)GETVALUE(var, uiVal), (*npvar)); break; case VT_UI4: INT32_TO_NPVARIANT((int32)GETVALUE(var, ulVal), (*npvar)); break; case VT_BOOL: BOOLEAN_TO_NPVARIANT((GETVALUE(var, boolVal) == VARIANT_TRUE) ? true : false, (*npvar)); break; case VT_R4: DOUBLE_TO_NPVARIANT((double)GETVALUE(var, fltVal), (*npvar)); break; case VT_R8: DOUBLE_TO_NPVARIANT(GETVALUE(var, dblVal), (*npvar)); break; case VT_DISPATCH: Dispatch2NPVar(GETVALUE(var, pdispVal), npvar, instance); break; case VT_UNKNOWN: Unknown2NPVar(GETVALUE(var, punkVal), npvar, instance); break; case VT_CY: DOUBLE_TO_NPVARIANT((double)GETVALUE(var, cyVal).int64 / 10000, (*npvar)); break; case VT_DATE: BSTR bstrVal; VarBstrFromDate(GETVALUE(var, date), 0, 0, &bstrVal); BSTR2NPVar(bstrVal, npvar, instance); break; default: if (var->vt & VT_ARRAY) { obj = SafeArray2NPObject(GETVALUE(var, parray), 0, NULL, instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } break; } } #undef GETVALUE void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance) { USES_CONVERSION; if (!var || !npvar) { return; } switch (npvar->type) { case NPVariantType_Void: var->vt = VT_VOID; var->ulVal = 0; break; case NPVariantType_Null: var->vt = VT_PTR; var->byref = NULL; break; case NPVariantType_Bool: var->vt = VT_BOOL; var->ulVal = npvar->value.boolValue; break; case NPVariantType_Int32: var->vt = VT_UI4; var->ulVal = npvar->value.intValue; break; case NPVariantType_Double: var->vt = VT_R8; var->dblVal = npvar->value.doubleValue; break; case NPVariantType_String: var->vt = VT_BSTR; var->bstrVal = Utf8StringToBstr(npvar->value.stringValue.UTF8Characters, npvar->value.stringValue.UTF8Length); break; case NPVariantType_Object: NPIdentifier *identifiers = NULL; uint32_t identifierCount = 0; NPObject *object = NPVARIANT_TO_OBJECT(*npvar); if (NPNFuncs.enumerate(instance, object, &identifiers, &identifierCount)) { CComSafeArray<VARIANT> variants; for (uint32_t index = 0; index < identifierCount; ++index) { NPVariant npVariant; if (NPNFuncs.getproperty(instance, object, identifiers[index], &npVariant)) { if (npVariant.type != NPVariantType_Object) { CComVariant variant; NPVar2Variant(&npVariant, &variant, instance); variants.Add(variant); } NPNFuncs.releasevariantvalue(&npVariant); } } NPNFuncs.memfree(identifiers); *reinterpret_cast<CComVariant*>(var) = variants; } else { var->vt = VT_VOID; var->ulVal = 0; } break; } }
C++
// stdafx.cpp : source file that includes just the standard includes // ffactivex.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <windows.h> #include <winbase.h> // ---------------------------------------------------------------------------- int main (int ArgC, char *ArgV[]) { const char *sourceName; const char *targetName; HANDLE targetHandle; void *versionPtr; DWORD versionLen; int lastError; int ret = 0; if (ArgC < 3) { fprintf(stderr, "Usage: %s <source> <target>\n", ArgV[0]); exit (1); } sourceName = ArgV[1]; targetName = ArgV[2]; if ((versionLen = GetFileVersionInfoSize(sourceName, NULL)) == 0) { fprintf(stderr, "Could not retrieve version len from %s\n", sourceName); exit (2); } if ((versionPtr = calloc(1, versionLen)) == NULL) { fprintf(stderr, "Error allocating temp memory\n"); exit (3); } if (!GetFileVersionInfo(sourceName, NULL, versionLen, versionPtr)) { fprintf(stderr, "Could not retrieve version info from %s\n", sourceName); exit (4); } if ((targetHandle = BeginUpdateResource(targetName, FALSE)) == INVALID_HANDLE_VALUE) { fprintf(stderr, "Could not begin update of %s\n", targetName); free(versionPtr); exit (5); } if (!UpdateResource(targetHandle, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), versionPtr, versionLen)) { lastError = GetLastError(); fprintf(stderr, "Error %d updating resource\n", lastError); ret = 6; } if (!EndUpdateResource(targetHandle, FALSE)) { fprintf(stderr, "Error finishing update\n"); ret = 7; } free(versionPtr); return (ret); }
C++
[Files] Source: {#xbasepath}\Release\npffax.dll; DestDir: {app}; DestName: npffax.dll; Flags: overwritereadonly restartreplace uninsrestartdelete [Registry] Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; Flags: uninsdeletekey Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Description; ValueData: {#MyAppName} {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: ProductName; ValueData: {#MyAppName} {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Path; ValueData: {app}\npffax.dll Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Version; ValueData: {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes; ValueType: string; ValueName: Dummy; ValueData: {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex; ValueType: string; ValueName: "Dummy"; ValueData: "{#xversion}"
C++
/* * Copyright (C) 2007 The Android Open Source Project * * 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 "com_google_ase_Exec.h" #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/wait.h> #include <termios.h> #include <unistd.h> #include "android/log.h" #define LOG_TAG "Exec" #define LOG(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) void JNU_ThrowByName(JNIEnv* env, const char* name, const char* msg) { jclass clazz = env->FindClass(name); if (clazz != NULL) { env->ThrowNew(clazz, msg); } env->DeleteLocalRef(clazz); } char* JNU_GetStringNativeChars(JNIEnv* env, jstring jstr) { if (jstr == NULL) { return NULL; } jbyteArray bytes = 0; jthrowable exc; char* result = 0; if (env->EnsureLocalCapacity(2) < 0) { return 0; /* out of memory error */ } jclass Class_java_lang_String = env->FindClass("java/lang/String"); jmethodID MID_String_getBytes = env->GetMethodID( Class_java_lang_String, "getBytes", "()[B"); bytes = (jbyteArray) env->CallObjectMethod(jstr, MID_String_getBytes); exc = env->ExceptionOccurred(); if (!exc) { jint len = env->GetArrayLength(bytes); result = (char*) malloc(len + 1); if (result == 0) { JNU_ThrowByName(env, "java/lang/OutOfMemoryError", 0); env->DeleteLocalRef(bytes); return 0; } env->GetByteArrayRegion(bytes, 0, len, (jbyte*) result); result[len] = 0; /* NULL-terminate */ } else { env->DeleteLocalRef(exc); } env->DeleteLocalRef(bytes); return result; } int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) { jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor"); jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor, "descriptor", "I"); return env->GetIntField(fileDescriptor, descriptor); } static int create_subprocess( const char* cmd, const char* arg0, const char* arg1, int* pProcessId) { char* devname; int ptm; pid_t pid; ptm = open("/dev/ptmx", O_RDWR); // | O_NOCTTY); if(ptm < 0){ LOG("[ cannot open /dev/ptmx - %s ]\n", strerror(errno)); return -1; } fcntl(ptm, F_SETFD, FD_CLOEXEC); if(grantpt(ptm) || unlockpt(ptm) || ((devname = (char*) ptsname(ptm)) == 0)){ LOG("[ trouble with /dev/ptmx - %s ]\n", strerror(errno)); return -1; } pid = fork(); if(pid < 0) { LOG("- fork failed: %s -\n", strerror(errno)); return -1; } if(pid == 0){ int pts; setsid(); pts = open(devname, O_RDWR); if(pts < 0) exit(-1); dup2(pts, 0); dup2(pts, 1); dup2(pts, 2); close(ptm); execl(cmd, cmd, arg0, arg1, NULL); exit(-1); } else { *pProcessId = (int) pid; return ptm; } } JNIEXPORT jobject JNICALL Java_com_google_ase_Exec_createSubprocess( JNIEnv* env, jclass clazz, jstring cmd, jstring arg0, jstring arg1, jintArray processIdArray) { char* cmd_8 = JNU_GetStringNativeChars(env, cmd); char* arg0_8 = JNU_GetStringNativeChars(env, arg0); char* arg1_8 = JNU_GetStringNativeChars(env, arg1); int procId; int ptm = create_subprocess(cmd_8, arg0_8, arg1_8, &procId); if (processIdArray) { int procIdLen = env->GetArrayLength(processIdArray); if (procIdLen > 0) { jboolean isCopy; int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy); if (pProcId) { *pProcId = procId; env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0); } } } jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor"); jmethodID init = env->GetMethodID(Class_java_io_FileDescriptor, "<init>", "()V"); jobject result = env->NewObject(Class_java_io_FileDescriptor, init); if (!result) { LOG("Couldn't create a FileDescriptor."); } else { jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor, "descriptor", "I"); env->SetIntField(result, descriptor, ptm); } return result; } JNIEXPORT void Java_com_google_ase_Exec_setPtyWindowSize( JNIEnv* env, jclass clazz, jobject fileDescriptor, jint row, jint col, jint xpixel, jint ypixel) { int fd; struct winsize sz; fd = jniGetFDFromFileDescriptor(env, fileDescriptor); if (env->ExceptionOccurred() != NULL) { return; } sz.ws_row = row; sz.ws_col = col; sz.ws_xpixel = xpixel; sz.ws_ypixel = ypixel; ioctl(fd, TIOCSWINSZ, &sz); } JNIEXPORT jint Java_com_google_ase_Exec_waitFor(JNIEnv* env, jclass clazz, jint procId) { int status; waitpid(procId, &status, 0); int result = 0; if (WIFEXITED(status)) { result = WEXITSTATUS(status); } return result; }
C++
#include <NTP.h> #include <DateTime.h> #include <ASocket.h> #include <Client.h> #include <Ethernet.h> #include <Server.h> #include <PString.h> #include <Dhcp.h> #include <Dns.h> #include <string.h> #include <WString.h> //MAC ID\uff08\u5404\u30b7\u30fc\u30eb\u30c9\u306b\u8a18\u8f09\uff09 #include "WProgram.h" void setup(); void loop(); void makeMsg(int post_count, int current, int ilum, int temp); void post(char msg[]); void getTime(); void printArray(Print *output, char* delimeter, byte* data, int len, int base); void basic_make(const char *user_and_passwd); static char mime_code(const char c); void mimeEncode(const char *buf); void alert(); byte mac[] = { 0x00, 0x50, 0xC2, 0x97, 0x23, 0x5E }; //ip\u304c\u901a\u3063\u305f\u304b boolean ipAcquired = false; //DNS\u30af\u30e9\u30b9 DnsClass targetDns; //ip\u683c\u7d0d\u7528\u30d0\u30c3\u30d5\u30a1 byte buffer[6]; //NTP\u30b5\u30fc\u30d0\u306eip byte ntp_dot_nist_dot_jp[] = {133, 243, 238, 243}; // ntp.nict.jp //\u5404\u30bb\u30f3\u30b5\u30d4\u30f3 int ledPin = 2; int CurrentPin = 0; int IlumPin = 1; int TempPin = 2; //base64\u30a8\u30f3\u30b3\u30fc\u30c9\u5f8c\u306e\u6587\u5b57\u5217\u683c\u7d0d\u7528 char mime[65]; void setup() { Serial.begin(9600); //\u5185\u90e8\u96fb\u5727\u8a2d\u5b9a analogReference( INTERNAL); pinMode(ledPin, OUTPUT); //////////////////////////////////// /////\u30d9\u30fc\u30b7\u30c3\u30af\u8a8d\u8a3c\u7528ID\uff06PASS/////// //////////////////////////////////// basic_make("tanikawa:tanikawa"); Serial.println("getting ip..."); int result = Dhcp.beginWithDHCP(mac); if(result == 1) { ipAcquired = true; Serial.println("ip acquired..."); Dhcp.getMacAddress(buffer); Serial.print("mac address: "); printArray(&Serial, ":", buffer, 6, 16); Dhcp.getLocalIp(buffer); Serial.print("ip address: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getSubnetMask(buffer); Serial.print("subnet mask: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getGatewayIp(buffer); Serial.print("gateway ip: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getDhcpServerIp(buffer); Serial.print("dhcp server ip: "); printArray(&Serial, ".", buffer, 4, 10); Dhcp.getDnsServerIp(buffer); Serial.print("dns server ip: "); printArray(&Serial, ".", buffer, 4, 10); //// Do DNS Lookup targetDns.init("100uhaco.appspot.com", buffer); //Buffer contains the IP address of the DNS server targetDns.resolve(); int results; while(!(results=targetDns.finished())) ; //wait for DNS to resolve the name if(results != 1) { Serial.print("DNS Error code: "); Serial.print(results,DEC); alert(); } targetDns.getIP(buffer); //buffer now contains the IP address for google.com Serial.print("target IP address: "); printArray(&Serial, ".", buffer, 4, 10); //NTP\u540c\u671f NTP ntp(ntp_dot_nist_dot_jp); DateTime.sync( (ntp.get_unix_gmt() + (9 * 60 * 60)) ); if( DateTime.available() ){ Serial.println("NTP OK"); } else{ Serial.println("NTP FALSE"); alert(); } } else{ Serial.println("unable to acquire ip address..."); alert(); } } void loop() { digitalWrite(ledPin, LOW); //\u30dd\u30b9\u30c8\u6e08\u307f\u30ca\u30f3\u30d0\u30fc static int posted =0; static int SAMPLE_COUNT =0; static int max_current = 0; static int current_tmp = 0; static int ilum_sum = 0; static int temp_sum =0; //\u88dc\u6b63\u7528sec int sec; getTime(); sec = (int)DateTime.Second; //\u73fe\u5728\u306epnum\u3092\u751f\u6210 int pnum = ((int)DateTime.Hour) * 6+ (int)DateTime.Minute / 10; if(pnum >= 144){ pnum = pnum - 144 ; } //10\u5206\u304a\u304d\u3001\u304b\u3064\u307e\u3060\u30dd\u30b9\u30c8\u3057\u3066\u3044\u306a\u304b\u3063\u305f\u5834\u5408 if( ((int)DateTime.Minute % 10) == 0 && (pnum != posted)){ int ilum_Value = 0; int temp_Value = 0; //\u5e73\u5747\u5316 if(SAMPLE_COUNT != 0){ ilum_Value = ilum_sum / SAMPLE_COUNT ; temp_Value = temp_sum / SAMPLE_COUNT ; } //HTTP\u901a\u4fe1 makeMsg(pnum, max_current, ilum_Value, temp_Value); //posted\u66f4\u65b0 posted = pnum; //\u521d\u671f\u5316 SAMPLE_COUNT =0; max_current = 0; current_tmp = 0; ilum_sum = 0; temp_sum =0; //\u70b9\u6ec5 digitalWrite(ledPin,HIGH); delay(1000); digitalWrite(ledPin, LOW); } //30\u79d2\u3054\u3068\u306b\u30c7\u30fc\u30bf\u3092\u53ce\u96c6 else if( ( 0 == sec)|| (sec == 30) ){ //\u96fb\u529b\u30c7\u30fc\u30bf current_tmp = analogRead(CurrentPin); if(max_current < current_tmp){ max_current = current_tmp; } //\u7167\u5ea6\u30c7\u30fc\u30bf ilum_sum +=analogRead(IlumPin); //\u6e29\u5ea6\u30c7\u30fc\u30bf temp_sum +=analogRead(TempPin); SAMPLE_COUNT++; Serial.println("logging"); Serial.println(max_current); Serial.println(ilum_sum); Serial.println(temp_sum); delay(30000); } } //\u30e1\u30c3\u30bb\u30fc\u30b8\u4f5c\u6210\u51e6\u7406 void makeMsg(int post_count, int current, int ilum, int temp) { char msg[200]; PString mystring(msg, sizeof(msg)); mystring.print("GET http://100uhaco.appspot.com/haco/record/"); mystring.print("?pnum="); mystring.print(post_count); mystring.print("&temp="); mystring.print(temp); mystring.print("&light="); mystring.print(ilum); mystring.print("&watt="); mystring.print(current); mystring.println(" HTTP/1.0 "); mystring.print("Authorization: Basic "); mystring.println(mime); post(msg); } //GAE\u306b\u30dd\u30b9\u30c8 void post(char msg[]) { // //HTTP request phase // Client client(buffer,80); Serial.println("HTTP connecting..."); if (client.connect()) { Serial.println("connected"); //client.write(msg); client.println(msg); client.println(); delay(100); Serial.println("disconnecting."); client.stop(); } } void getTime(){ if( DateTime.available() ) { //\u306a\u305c\u304b\u4e00\u30f6\u6708\u9045\u308c\u306a\u306e\u3067\u66ab\u5b9a\u7684\u306b+1 Serial.print((int)DateTime.Month + 1); Serial.print("/"); Serial.print((int)DateTime.Day); Serial.print(" "); Serial.print(((int)DateTime.Hour)); Serial.print(":"); Serial.print((int)DateTime.Minute); Serial.print(":"); Serial.print((int)DateTime.Second); Serial.println(" JST"); } } //IPadress\u7fa4\u3092\u51fa\u529b\u3059\u308b\u305f\u3081\u306e\u51e6\u7406 void printArray(Print *output, char* delimeter, byte* data, int len, int base) { char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for(int i = 0; i < len; i++) { if(i != 0) output->print(delimeter); output->print(itoa(data[i], buf, base)); } output->println(); } // //\u30d9\u30fc\u30b7\u30c3\u30af\u8a8d\u8a3c\u7528base64\u30a8\u30f3\u30b3\u30fc\u30c9\u95a2\u6570\u90e1 //(Twitter\u30e9\u30a4\u30d6\u30e9\u30ea\u304b\u3089\u62dd\u501f) // void basic_make(const char *user_and_passwd) { mimeEncode(user_and_passwd); } static char mime_code(const char c) { if (c < 26) return c+'A'; if (c < 52) return c-26+'a'; if (c < 62) return c-52+'0'; if (c == 62) return '+'; return '/'; } void mimeEncode(const char *buf) { int i = 0, j = 0, c[3]; while (j < 64 && buf[i]) { c[0] = buf[i++]; c[1] = buf[i] ? buf[i++] : 0; c[2] = buf[i] ? buf[i++] : 0; mime[j++] = mime_code(c[0]>>2); mime[j++] = mime_code(((c[0]<<4)&0x30) | (c[1]>>4)); mime[j++] = c[1] ? mime_code(((c[1]<<2)&0x3c) | (c[2]>>6)) : '='; mime[j++] = c[2] ? mime_code(c[2]&0x3f) : '='; } mime[j] = 0; } void alert(){ while(1){ //\u30a2\u30e9\u30fc\u30c8 digitalWrite(ledPin,HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); } } int main(void) { init(); setup(); for (;;) loop(); return 0; }
C++
open run.out logtime -e run.out monitor -n Smon active *E/X'sig monitor -n Smon active *E/D'sig --monitor -n Smon active *E/Qj'sig -- monitor -n Smon active *E/UUT/WS'sig -- monitor -n Smon active *E/UUT/WC'sig list > run.out run 33960 > run.out quit
C++
open run.out logtime -e run.out monitor -n Smon active *E/X'sig monitor -n Smon active *E/D'sig --monitor -n Smon active *E/Qj'sig -- monitor -n Smon active *E/UUT/WS'sig -- monitor -n Smon active *E/UUT/WC'sig list > run.out run 33960 > run.out quit
C++
#include <QCoreApplication> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); return a.exec(); }
C++
#include <QCoreApplication> #include <iostream> #include <climits> #include <cfloat> #include <cmath> using namespace std; int kvadrat(int a); int main() { cout<<kvadrat(5); return 0; }
C++
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Wiring project - http://wiring.org.co Copyright (c) 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ */ extern "C" { #include "stdlib.h" } void randomSeed(unsigned int seed) { if (seed != 0) { srandom(seed); } } long random(long howbig) { if (howbig == 0) { return 0; } return random() % howbig; } long random(long howsmall, long howbig) { if (howsmall >= howbig) { return howsmall; } long diff = howbig - howsmall; return random(diff) + howsmall; } long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } unsigned int makeWord(unsigned int w) { return w; } unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; }
C++
/* Print.h - Base class that provides print() and println() Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef Print_h #define Print_h #include <inttypes.h> #include <stdio.h> // for size_t #include "WString.h" #define DEC 10 #define HEX 16 #define OCT 8 #define BIN 2 #define BYTE 0 class Print { private: void printNumber(unsigned long, uint8_t); void printFloat(double, uint8_t); public: virtual void write(uint8_t) = 0; virtual void write(const char *str); virtual void write(const uint8_t *buffer, size_t size); void print(const String &); void print(const char[]); void print(char, int = BYTE); void print(unsigned char, int = BYTE); void print(int, int = DEC); void print(unsigned int, int = DEC); void print(long, int = DEC); void print(unsigned long, int = DEC); void print(double, int = 2); void println(const String &s); void println(const char[]); void println(char, int = BYTE); void println(unsigned char, int = BYTE); void println(int, int = DEC); void println(unsigned int, int = DEC); void println(long, int = DEC); void println(unsigned long, int = DEC); void println(double, int = 2); void println(void); }; #endif
C++
/* HardwareSerial.h - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef HardwareSerial_h #define HardwareSerial_h #include <inttypes.h> #include "Stream.h" struct ring_buffer; class HardwareSerial : public Stream { private: ring_buffer *_rx_buffer; volatile uint8_t *_ubrrh; volatile uint8_t *_ubrrl; volatile uint8_t *_ucsra; volatile uint8_t *_ucsrb; volatile uint8_t *_udr; uint8_t _rxen; uint8_t _txen; uint8_t _rxcie; uint8_t _udre; uint8_t _u2x; public: HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x); void begin(long); void end(); virtual int available(void); virtual int peek(void); virtual int read(void); virtual void flush(void); virtual void write(uint8_t); using Print::write; // pull in write(str) and write(buf, size) from Print }; extern HardwareSerial Serial; #if defined(__AVR_ATmega1280__) extern HardwareSerial Serial1; extern HardwareSerial Serial2; extern HardwareSerial Serial3; #endif #endif
C++
/* WString.h - String library for Wiring & Arduino Copyright (c) 2009-10 Hernando Barragan. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef String_h #define String_h //#include "WProgram.h" #include <stdlib.h> #include <string.h> #include <ctype.h> class String { public: // constructors String( const char *value = "" ); String( const String &value ); String( const char ); String( const unsigned char ); String( const int, const int base=10); String( const unsigned int, const int base=10 ); String( const long, const int base=10 ); //##RG.Labs.20100919 begin //String( const unsigned long, const int base=10 ); String( const unsigned long); //##RG.Labs.20100919 end ~String() { free(_buffer); _length = _capacity = 0;} //added _length = _capacity = 0; // operators const String & operator = ( const String &rhs ); const String & operator +=( const String &rhs ); //const String & operator +=( const char ); int operator ==( const String &rhs ) const; int operator !=( const String &rhs ) const; int operator < ( const String &rhs ) const; int operator > ( const String &rhs ) const; int operator <=( const String &rhs ) const; int operator >=( const String &rhs ) const; char operator []( unsigned int index ) const; char& operator []( unsigned int index ); //operator const char *() const { return _buffer; } // general methods char charAt( unsigned int index ) const; int compareTo( const String &anotherString ) const; unsigned char endsWith( const String &suffix ) const; unsigned char equals( const String &anObject ) const; unsigned char equalsIgnoreCase( const String &anotherString ) const; int indexOf( char ch ) const; int indexOf( char ch, unsigned int fromIndex ) const; int indexOf( const String &str ) const; int indexOf( const String &str, unsigned int fromIndex ) const; int lastIndexOf( char ch ) const; int lastIndexOf( char ch, unsigned int fromIndex ) const; int lastIndexOf( const String &str ) const; int lastIndexOf( const String &str, unsigned int fromIndex ) const; //##RG.Labs.20100919 begin //const unsigned int length( ) const { return _length; } unsigned int length( ) const { return _length; } //##RG.Labs.20100919 end void setCharAt(unsigned int index, const char ch); unsigned char startsWith( const String &prefix ) const; unsigned char startsWith( const String &prefix, unsigned int toffset ) const; String substring( unsigned int beginIndex ) const; String substring( unsigned int beginIndex, unsigned int endIndex ) const; String toLowerCase( ) const; String toUpperCase( ) const; String trim( ) const; void getBytes(unsigned char *buf, unsigned int bufsize); void toCharArray(char *buf, unsigned int bufsize); const String& concat( const String &str ); String replace( char oldChar, char newChar ); String replace( const String& match, const String& replace ); friend String operator + ( String lhs, const String &rhs ); protected: char *_buffer; // the actual char array unsigned int _capacity; // the array length minus one (for the '\0') unsigned int _length; // the String length (not counting the '\0') void getBuffer(unsigned int maxStrLen); private: }; // allocate buffer space inline void String::getBuffer(unsigned int maxStrLen) { _capacity = maxStrLen; _buffer = (char *) malloc(_capacity + 1); if (_buffer == NULL) _length = _capacity = 0; } inline String operator+( String lhs, const String &rhs ) { return lhs += rhs; } #endif
C++
/* HardwareSerial.cpp - Hardware serial library for Wiring Copyright (c) 2006 Nicholas Zambetti. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include "wiring.h" #include "wiring_private.h" #include "HardwareSerial.h" // Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which rx_buffer_head is the index of the // location to which to write the next incoming character and rx_buffer_tail // is the index of the location from which to read. #define RX_BUFFER_SIZE 128 struct ring_buffer { unsigned char buffer[RX_BUFFER_SIZE]; int head; int tail; }; ring_buffer rx_buffer = { { 0 }, 0, 0 }; #if defined(__AVR_ATmega1280__) ring_buffer rx_buffer1 = { { 0 }, 0, 0 }; ring_buffer rx_buffer2 = { { 0 }, 0, 0 }; ring_buffer rx_buffer3 = { { 0 }, 0, 0 }; #endif inline void store_char(unsigned char c, ring_buffer *rx_buffer) { int i = (rx_buffer->head + 1) % RX_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != rx_buffer->tail) { rx_buffer->buffer[rx_buffer->head] = c; rx_buffer->head = i; } } #if defined(__AVR_ATmega1280__) SIGNAL(SIG_USART0_RECV) { unsigned char c = UDR0; store_char(c, &rx_buffer); } SIGNAL(SIG_USART1_RECV) { unsigned char c = UDR1; store_char(c, &rx_buffer1); } SIGNAL(SIG_USART2_RECV) { unsigned char c = UDR2; store_char(c, &rx_buffer2); } SIGNAL(SIG_USART3_RECV) { unsigned char c = UDR3; store_char(c, &rx_buffer3); } #else #if defined(__AVR_ATmega8__) SIGNAL(SIG_UART_RECV) #else SIGNAL(USART_RX_vect) #endif { #if defined(__AVR_ATmega8__) unsigned char c = UDR; #else unsigned char c = UDR0; #endif store_char(c, &rx_buffer); } #endif // Constructors //////////////////////////////////////////////////////////////// HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x) { _rx_buffer = rx_buffer; _ubrrh = ubrrh; _ubrrl = ubrrl; _ucsra = ucsra; _ucsrb = ucsrb; _udr = udr; _rxen = rxen; _txen = txen; _rxcie = rxcie; _udre = udre; _u2x = u2x; } // Public Methods ////////////////////////////////////////////////////////////// void HardwareSerial::begin(long baud) { uint16_t baud_setting; bool use_u2x; // U2X mode is needed for baud rates higher than (CPU Hz / 16) //##RG.Labs.20100919 begin //if (baud > F_CPU / 16) { if (baud > (long)(F_CPU / 16)) { //##RG.Labs.20100919 end use_u2x = true; } else { // figure out if U2X mode would allow for a better connection // calculate the percent difference between the baud-rate specified and // the real baud rate for both U2X and non-U2X mode (0-255 error percent) uint8_t nonu2x_baud_error = abs((int)(255-((F_CPU/(16*(((F_CPU/8/baud-1)/2)+1))*255)/baud))); uint8_t u2x_baud_error = abs((int)(255-((F_CPU/(8*(((F_CPU/4/baud-1)/2)+1))*255)/baud))); // prefer non-U2X mode because it handles clock skew better use_u2x = (nonu2x_baud_error > u2x_baud_error); } if (use_u2x) { *_ucsra = 1 << _u2x; baud_setting = (F_CPU / 4 / baud - 1) / 2; } else { *_ucsra = 0; baud_setting = (F_CPU / 8 / baud - 1) / 2; } // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register) *_ubrrh = baud_setting >> 8; *_ubrrl = baud_setting; sbi(*_ucsrb, _rxen); sbi(*_ucsrb, _txen); sbi(*_ucsrb, _rxcie); } void HardwareSerial::end() { cbi(*_ucsrb, _rxen); cbi(*_ucsrb, _txen); cbi(*_ucsrb, _rxcie); } int HardwareSerial::available(void) { return (RX_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % RX_BUFFER_SIZE; } int HardwareSerial::peek(void) { if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { return _rx_buffer->buffer[_rx_buffer->tail]; } } int HardwareSerial::read(void) { // if the head isn't ahead of the tail, we don't have any characters if (_rx_buffer->head == _rx_buffer->tail) { return -1; } else { unsigned char c = _rx_buffer->buffer[_rx_buffer->tail]; _rx_buffer->tail = (_rx_buffer->tail + 1) % RX_BUFFER_SIZE; return c; } } void HardwareSerial::flush() { // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // don't reverse this or there may be problems if the RX interrupt // occurs after reading the value of rx_buffer_head but before writing // the value to rx_buffer_tail; the previous value of rx_buffer_head // may be written to rx_buffer_tail, making it appear as if the buffer // were full, not empty. _rx_buffer->head = _rx_buffer->tail; } void HardwareSerial::write(uint8_t c) { while (!((*_ucsra) & (1 << _udre))) ; *_udr = c; } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(__AVR_ATmega8__) HardwareSerial Serial(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X); #else HardwareSerial Serial(&rx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0); #endif #if defined(__AVR_ATmega1280__) HardwareSerial Serial1(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1); HardwareSerial Serial2(&rx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRE2, U2X2); HardwareSerial Serial3(&rx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRE3, U2X3); #endif
C++
/* Stream.h - base class for character-based streams. Copyright (c) 2010 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef Stream_h #define Stream_h #include <inttypes.h> #include "Print.h" class Stream : public Print { public: virtual int available() = 0; virtual int read() = 0; virtual void flush() = 0; }; #endif
C++
/* WString.cpp - String library for Wiring & Arduino Copyright (c) 2009-10 Hernando Barragan. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdlib.h> #include "WProgram.h" #include "WString.h" String::String( const char *value ) { if ( value == NULL ) value = ""; getBuffer( _length = strlen( value ) ); if ( _buffer != NULL ) strcpy( _buffer, value ); } String::String( const String &value ) { getBuffer( _length = value._length ); if ( _buffer != NULL ) strcpy( _buffer, value._buffer ); } String::String( const char value ) { _length = 1; getBuffer(1); if ( _buffer != NULL ) { _buffer[0] = value; _buffer[1] = 0; } } String::String( const unsigned char value ) { _length = 1; getBuffer(1); if ( _buffer != NULL) { _buffer[0] = value; _buffer[1] = 0; } } String::String( const int value, const int base ) { char buf[33]; itoa((signed long)value, buf, base); getBuffer( _length = strlen(buf) ); if ( _buffer != NULL ) strcpy( _buffer, buf ); } String::String( const unsigned int value, const int base ) { char buf[33]; ultoa((unsigned long)value, buf, base); getBuffer( _length = strlen(buf) ); if ( _buffer != NULL ) strcpy( _buffer, buf ); } String::String( const long value, const int base ) { char buf[33]; ltoa(value, buf, base); getBuffer( _length = strlen(buf) ); if ( _buffer != NULL ) strcpy( _buffer, buf ); } //##RG.Labs.20100919 begin //String::String( const unsigned long value, const int base ) //{ // char buf[33]; // ultoa(value, buf, 10); // getBuffer( _length = strlen(buf) ); // if ( _buffer != NULL ) // strcpy( _buffer, buf ); //} String::String( const unsigned long value) { char buf[33]; ultoa(value, buf, 10); getBuffer( _length = strlen(buf) ); if ( _buffer != NULL ) strcpy( _buffer, buf ); } //##RG.Labs.20100919 end char String::charAt( unsigned int loc ) const { return operator[]( loc ); } void String::setCharAt( unsigned int loc, const char aChar ) { if(_buffer == NULL) return; if(_length > loc) { _buffer[loc] = aChar; } } int String::compareTo( const String &s2 ) const { return strcmp( _buffer, s2._buffer ); } const String & String::concat( const String &s2 ) { return (*this) += s2; } const String & String::operator=( const String &rhs ) { if ( this == &rhs ) return *this; if ( rhs._length > _length ) { free(_buffer); getBuffer( rhs._length ); } if ( _buffer != NULL ) { _length = rhs._length; strcpy( _buffer, rhs._buffer ); } return *this; } //const String & String::operator+=( const char aChar ) //{ // if ( _length == _capacity ) // doubleBuffer(); // // _buffer[ _length++ ] = aChar; // _buffer[ _length ] = '\0'; // return *this; //} const String & String::operator+=( const String &other ) { _length += other._length; if ( _length > _capacity ) { char *temp = _buffer; getBuffer( _length ); if ( _buffer != NULL ) strcpy( _buffer, temp ); free(temp); } if ( _buffer != NULL ) strcat( _buffer, other._buffer ); return *this; } int String::operator==( const String &rhs ) const { return ( _length == rhs._length && strcmp( _buffer, rhs._buffer ) == 0 ); } int String::operator!=( const String &rhs ) const { return ( _length != rhs.length() || strcmp( _buffer, rhs._buffer ) != 0 ); } int String::operator<( const String &rhs ) const { return strcmp( _buffer, rhs._buffer ) < 0; } int String::operator>( const String &rhs ) const { return strcmp( _buffer, rhs._buffer ) > 0; } int String::operator<=( const String &rhs ) const { return strcmp( _buffer, rhs._buffer ) <= 0; } int String::operator>=( const String & rhs ) const { return strcmp( _buffer, rhs._buffer ) >= 0; } char & String::operator[]( unsigned int index ) { static char dummy_writable_char; if (index >= _length || !_buffer) { dummy_writable_char = 0; return dummy_writable_char; } return _buffer[ index ]; } char String::operator[]( unsigned int index ) const { // need to check for valid index, to do later return _buffer[ index ]; } boolean String::endsWith( const String &s2 ) const { if ( _length < s2._length ) return 0; return strcmp( &_buffer[ _length - s2._length], s2._buffer ) == 0; } boolean String::equals( const String &s2 ) const { return ( _length == s2._length && strcmp( _buffer,s2._buffer ) == 0 ); } boolean String::equalsIgnoreCase( const String &s2 ) const { if ( this == &s2 ) return true; //1; else if ( _length != s2._length ) return false; //0; return strcmp(toLowerCase()._buffer, s2.toLowerCase()._buffer) == 0; } String String::replace( char findChar, char replaceChar ) { if ( _buffer == NULL ) return *this; String theReturn = _buffer; char* temp = theReturn._buffer; while( (temp = strchr( temp, findChar )) != 0 ) *temp = replaceChar; return theReturn; } String String::replace( const String& match, const String& replace ) { if ( _buffer == NULL ) return *this; String temp = _buffer, newString; int loc; while ( (loc = temp.indexOf( match )) != -1 ) { newString += temp.substring( 0, loc ); newString += replace; temp = temp.substring( loc + match._length ); } newString += temp; return newString; } int String::indexOf( char temp ) const { return indexOf( temp, 0 ); } int String::indexOf( char ch, unsigned int fromIndex ) const { if ( fromIndex >= _length ) return -1; const char* temp = strchr( &_buffer[fromIndex], ch ); if ( temp == NULL ) return -1; return temp - _buffer; } int String::indexOf( const String &s2 ) const { return indexOf( s2, 0 ); } int String::indexOf( const String &s2, unsigned int fromIndex ) const { if ( fromIndex >= _length ) return -1; const char *theFind = strstr( &_buffer[ fromIndex ], s2._buffer ); if ( theFind == NULL ) return -1; return theFind - _buffer; // pointer subtraction } int String::lastIndexOf( char theChar ) const { return lastIndexOf( theChar, _length - 1 ); } int String::lastIndexOf( char ch, unsigned int fromIndex ) const { if ( fromIndex >= _length ) return -1; char tempchar = _buffer[fromIndex + 1]; _buffer[fromIndex + 1] = '\0'; char* temp = strrchr( _buffer, ch ); _buffer[fromIndex + 1] = tempchar; if ( temp == NULL ) return -1; return temp - _buffer; } int String::lastIndexOf( const String &s2 ) const { return lastIndexOf( s2, _length - s2._length ); } int String::lastIndexOf( const String &s2, unsigned int fromIndex ) const { // check for empty strings if ( s2._length == 0 || s2._length - 1 > fromIndex || fromIndex >= _length ) return -1; // matching first character char temp = s2[ 0 ]; for ( int i = fromIndex; i >= 0; i-- ) { if ( _buffer[ i ] == temp && (*this).substring( i, i + s2._length ).equals( s2 ) ) return i; } return -1; } boolean String::startsWith( const String &s2 ) const { if ( _length < s2._length ) return 0; return startsWith( s2, 0 ); } boolean String::startsWith( const String &s2, unsigned int offset ) const { if ( offset > _length - s2._length ) return 0; return strncmp( &_buffer[offset], s2._buffer, s2._length ) == 0; } String String::substring( unsigned int left ) const { return substring( left, _length ); } String String::substring( unsigned int left, unsigned int right ) const { if ( left > right ) { int temp = right; right = left; left = temp; } if ( right > _length ) { right = _length; } char temp = _buffer[ right ]; // save the replaced character _buffer[ right ] = '\0'; String outPut = ( _buffer + left ); // pointer arithmetic _buffer[ right ] = temp; //restore character return outPut; } String String::toLowerCase() const { String temp = _buffer; for ( unsigned int i = 0; i < _length; i++ ) temp._buffer[ i ] = (char)tolower( temp._buffer[ i ] ); return temp; } String String::toUpperCase() const { String temp = _buffer; for ( unsigned int i = 0; i < _length; i++ ) temp._buffer[ i ] = (char)toupper( temp._buffer[ i ] ); return temp; } String String::trim() const { if ( _buffer == NULL ) return *this; String temp = _buffer; unsigned int i,j; for ( i = 0; i < _length; i++ ) { if ( !isspace(_buffer[i]) ) break; } for ( j = temp._length - 1; j > i; j-- ) { if ( !isspace(_buffer[j]) ) break; } return temp.substring( i, j + 1); } void String::getBytes(unsigned char *buf, unsigned int bufsize) { if (!bufsize || !buf) return; unsigned int len = bufsize - 1; if (len > _length) len = _length; strncpy((char *)buf, _buffer, len); buf[len] = 0; } void String::toCharArray(char *buf, unsigned int bufsize) { if (!bufsize || !buf) return; unsigned int len = bufsize - 1; if (len > _length) len = _length; strncpy(buf, _buffer, len); buf[len] = 0; }
C++
/* Tone.cpp A Tone Generator Library Written by Brett Hagman This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Version Modified By Date Comments ------- ----------- -------- -------- 0001 B Hagman 09/08/02 Initial coding 0002 B Hagman 09/08/18 Multiple pins 0003 B Hagman 09/08/18 Moved initialization from constructor to begin() 0004 B Hagman 09/09/26 Fixed problems with ATmega8 0005 B Hagman 09/11/23 Scanned prescalars for best fit on 8 bit timers 09/11/25 Changed pin toggle method to XOR 09/11/25 Fixed timer0 from being excluded 0006 D Mellis 09/12/29 Replaced objects with functions *************************************************/ #include <avr/interrupt.h> #include <avr/pgmspace.h> #include <wiring.h> #include <pins_arduino.h> #if defined(__AVR_ATmega8__) #define TCCR2A TCCR2 #define TCCR2B TCCR2 #define COM2A1 COM21 #define COM2A0 COM20 #define OCR2A OCR2 #define TIMSK2 TIMSK #define OCIE2A OCIE2 #define TIMER2_COMPA_vect TIMER2_COMP_vect #define TIMSK1 TIMSK #endif // timerx_toggle_count: // > 0 - duration specified // = 0 - stopped // < 0 - infinitely (until stop() method called, or new play() called) #if !defined(__AVR_ATmega8__) volatile long timer0_toggle_count; volatile uint8_t *timer0_pin_port; volatile uint8_t timer0_pin_mask; #endif volatile long timer1_toggle_count; volatile uint8_t *timer1_pin_port; volatile uint8_t timer1_pin_mask; volatile long timer2_toggle_count; volatile uint8_t *timer2_pin_port; volatile uint8_t timer2_pin_mask; #if defined(__AVR_ATmega1280__) volatile long timer3_toggle_count; volatile uint8_t *timer3_pin_port; volatile uint8_t timer3_pin_mask; volatile long timer4_toggle_count; volatile uint8_t *timer4_pin_port; volatile uint8_t timer4_pin_mask; volatile long timer5_toggle_count; volatile uint8_t *timer5_pin_port; volatile uint8_t timer5_pin_mask; #endif #if defined(__AVR_ATmega1280__) #define AVAILABLE_TONE_PINS 1 const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 3, 4, 5, 1, 0 */ }; static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255, 255, 255, 255 */ }; #elif defined(__AVR_ATmega8__) #define AVAILABLE_TONE_PINS 1 const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1 */ }; static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ }; #else #define AVAILABLE_TONE_PINS 1 //##RG.Labs.20100919 begin // The warning in the next code line seems to be a gcc reported bug. // See: // http://gcc.gnu.org/ml/gcc-bugs/2008-01/msg00969.html // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734 // http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html // Leave timer 0 to last. //const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ }; const uint8_t __attribute__((section(".progmem.tone"))) tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ }; //##RG.Labs.20100919 end static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255 */ }; #endif static int8_t toneBegin(uint8_t _pin) { int8_t _timer = -1; // if we're already using the pin, the timer should be configured. for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { if (tone_pins[i] == _pin) { return pgm_read_byte(tone_pin_to_timer_PGM + i); } } // search for an unused timer. for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { if (tone_pins[i] == 255) { tone_pins[i] = _pin; _timer = pgm_read_byte(tone_pin_to_timer_PGM + i); break; } } if (_timer != -1) { // Set timer specific stuff // All timers in CTC mode // 8 bit timers will require changing prescalar values, // whereas 16 bit timers are set to either ck/1 or ck/64 prescalar switch (_timer) { #if !defined(__AVR_ATmega8__) case 0: // 8 bit timer TCCR0A = 0; TCCR0B = 0; bitWrite(TCCR0A, WGM01, 1); bitWrite(TCCR0B, CS00, 1); timer0_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer0_pin_mask = digitalPinToBitMask(_pin); break; #endif case 1: // 16 bit timer TCCR1A = 0; TCCR1B = 0; bitWrite(TCCR1B, WGM12, 1); bitWrite(TCCR1B, CS10, 1); timer1_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer1_pin_mask = digitalPinToBitMask(_pin); break; case 2: // 8 bit timer TCCR2A = 0; TCCR2B = 0; bitWrite(TCCR2A, WGM21, 1); bitWrite(TCCR2B, CS20, 1); timer2_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer2_pin_mask = digitalPinToBitMask(_pin); break; #if defined(__AVR_ATmega1280__) case 3: // 16 bit timer TCCR3A = 0; TCCR3B = 0; bitWrite(TCCR3B, WGM32, 1); bitWrite(TCCR3B, CS30, 1); timer3_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer3_pin_mask = digitalPinToBitMask(_pin); break; case 4: // 16 bit timer TCCR4A = 0; TCCR4B = 0; bitWrite(TCCR4B, WGM42, 1); bitWrite(TCCR4B, CS40, 1); timer4_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer4_pin_mask = digitalPinToBitMask(_pin); break; case 5: // 16 bit timer TCCR5A = 0; TCCR5B = 0; bitWrite(TCCR5B, WGM52, 1); bitWrite(TCCR5B, CS50, 1); timer5_pin_port = portOutputRegister(digitalPinToPort(_pin)); timer5_pin_mask = digitalPinToBitMask(_pin); break; #endif } } return _timer; } // frequency (in hertz) and duration (in milliseconds). void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) { uint8_t prescalarbits = 0b001; long toggle_count = 0; uint32_t ocr = 0; int8_t _timer; _timer = toneBegin(_pin); if (_timer >= 0) { // Set the pinMode as OUTPUT pinMode(_pin, OUTPUT); // if we are using an 8 bit timer, scan through prescalars to find the best fit if (_timer == 0 || _timer == 2) { ocr = F_CPU / frequency / 2 - 1; prescalarbits = 0b001; // ck/1: same for both timers if (ocr > 255) { ocr = F_CPU / frequency / 2 / 8 - 1; prescalarbits = 0b010; // ck/8: same for both timers if (_timer == 2 && ocr > 255) { ocr = F_CPU / frequency / 2 / 32 - 1; prescalarbits = 0b011; } if (ocr > 255) { ocr = F_CPU / frequency / 2 / 64 - 1; prescalarbits = _timer == 0 ? 0b011 : 0b100; if (_timer == 2 && ocr > 255) { ocr = F_CPU / frequency / 2 / 128 - 1; prescalarbits = 0b101; } if (ocr > 255) { ocr = F_CPU / frequency / 2 / 256 - 1; prescalarbits = _timer == 0 ? 0b100 : 0b110; if (ocr > 255) { // can't do any better than /1024 ocr = F_CPU / frequency / 2 / 1024 - 1; prescalarbits = _timer == 0 ? 0b101 : 0b111; } } } } #if !defined(__AVR_ATmega8__) if (_timer == 0) TCCR0B = prescalarbits; else #endif TCCR2B = prescalarbits; } else { // two choices for the 16 bit timers: ck/1 or ck/64 ocr = F_CPU / frequency / 2 - 1; prescalarbits = 0b001; if (ocr > 0xffff) { ocr = F_CPU / frequency / 2 / 64 - 1; prescalarbits = 0b011; } if (_timer == 1) TCCR1B = (TCCR1B & 0b11111000) | prescalarbits; #if defined(__AVR_ATmega1280__) else if (_timer == 3) TCCR3B = (TCCR3B & 0b11111000) | prescalarbits; else if (_timer == 4) TCCR4B = (TCCR4B & 0b11111000) | prescalarbits; else if (_timer == 5) TCCR5B = (TCCR5B & 0b11111000) | prescalarbits; #endif } // Calculate the toggle count if (duration > 0) { toggle_count = 2 * frequency * duration / 1000; } else { toggle_count = -1; } // Set the OCR for the given timer, // set the toggle count, // then turn on the interrupts switch (_timer) { #if !defined(__AVR_ATmega8__) case 0: OCR0A = ocr; timer0_toggle_count = toggle_count; bitWrite(TIMSK0, OCIE0A, 1); break; #endif case 1: OCR1A = ocr; timer1_toggle_count = toggle_count; bitWrite(TIMSK1, OCIE1A, 1); break; case 2: OCR2A = ocr; timer2_toggle_count = toggle_count; bitWrite(TIMSK2, OCIE2A, 1); break; #if defined(__AVR_ATmega1280__) case 3: OCR3A = ocr; timer3_toggle_count = toggle_count; bitWrite(TIMSK3, OCIE3A, 1); break; case 4: OCR4A = ocr; timer4_toggle_count = toggle_count; bitWrite(TIMSK4, OCIE4A, 1); break; case 5: OCR5A = ocr; timer5_toggle_count = toggle_count; bitWrite(TIMSK5, OCIE5A, 1); break; #endif } } } // XXX: this function only works properly for timer 2 (the only one we use // currently). for the others, it should end the tone, but won't restore // proper PWM functionality for the timer. void disableTimer(uint8_t _timer) { switch (_timer) { #if !defined(__AVR_ATmega8__) case 0: TIMSK0 = 0; break; #endif case 1: bitWrite(TIMSK1, OCIE1A, 0); break; case 2: bitWrite(TIMSK2, OCIE2A, 0); // disable interrupt TCCR2A = (1 << WGM20); TCCR2B = (TCCR2B & 0b11111000) | (1 << CS22); OCR2A = 0; break; #if defined(__AVR_ATmega1280__) case 3: TIMSK3 = 0; break; case 4: TIMSK4 = 0; break; case 5: TIMSK5 = 0; break; #endif } } void noTone(uint8_t _pin) { int8_t _timer = -1; for (int i = 0; i < AVAILABLE_TONE_PINS; i++) { if (tone_pins[i] == _pin) { _timer = pgm_read_byte(tone_pin_to_timer_PGM + i); tone_pins[i] = 255; } } disableTimer(_timer); digitalWrite(_pin, 0); } #if 0 #if !defined(__AVR_ATmega8__) ISR(TIMER0_COMPA_vect) { if (timer0_toggle_count != 0) { // toggle the pin *timer0_pin_port ^= timer0_pin_mask; if (timer0_toggle_count > 0) timer0_toggle_count--; } else { disableTimer(0); *timer0_pin_port &= ~(timer0_pin_mask); // keep pin low after stop } } #endif ISR(TIMER1_COMPA_vect) { if (timer1_toggle_count != 0) { // toggle the pin *timer1_pin_port ^= timer1_pin_mask; if (timer1_toggle_count > 0) timer1_toggle_count--; } else { disableTimer(1); *timer1_pin_port &= ~(timer1_pin_mask); // keep pin low after stop } } #endif ISR(TIMER2_COMPA_vect) { if (timer2_toggle_count != 0) { // toggle the pin *timer2_pin_port ^= timer2_pin_mask; if (timer2_toggle_count > 0) timer2_toggle_count--; } else { disableTimer(2); *timer2_pin_port &= ~(timer2_pin_mask); // keep pin low after stop } } //#if defined(__AVR_ATmega1280__) #if 0 ISR(TIMER3_COMPA_vect) { if (timer3_toggle_count != 0) { // toggle the pin *timer3_pin_port ^= timer3_pin_mask; if (timer3_toggle_count > 0) timer3_toggle_count--; } else { disableTimer(3); *timer3_pin_port &= ~(timer3_pin_mask); // keep pin low after stop } } ISR(TIMER4_COMPA_vect) { if (timer4_toggle_count != 0) { // toggle the pin *timer4_pin_port ^= timer4_pin_mask; if (timer4_toggle_count > 0) timer4_toggle_count--; } else { disableTimer(4); *timer4_pin_port &= ~(timer4_pin_mask); // keep pin low after stop } } ISR(TIMER5_COMPA_vect) { if (timer5_toggle_count != 0) { // toggle the pin *timer5_pin_port ^= timer5_pin_mask; if (timer5_toggle_count > 0) timer5_toggle_count--; } else { disableTimer(5); *timer5_pin_port &= ~(timer5_pin_mask); // keep pin low after stop } } #endif
C++
#include <WProgram.h> int main(void) { init(); setup(); for (;;) loop(); return 0; }
C++
extern "C" { //#include "avr/io.h" #include "stdlib.h" } #include "CPPLib.h" void __cxa_pure_virtual() { //abort(); //See http://www.arduino.cc/playground/Code/Eclipse cli(); for (;;); } void operator delete (void *ptr) throw () { //I know: The "if" is not necessary, according to the standard. //But it's just one more line of code, and I sleep better with it: if (ptr) free (ptr); } void operator delete[] (void *ptr) throw () { ::operator delete (ptr); } void *operator new (size_t size) throw() { return malloc(size); } void *operator new[] (size_t size) throw() { return ::operator new(size); } /* void * operator new[](size_t size) { return malloc(size); } void operator delete[](void * ptr) { free(ptr); } */
C++
/* Print.cpp - Base class that provides print() and println() Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "wiring.h" #include "Print.h" // Public Methods ////////////////////////////////////////////////////////////// /* default implementation: may be overridden */ void Print::write(const char *str) { while (*str) write(*str++); } /* default implementation: may be overridden */ void Print::write(const uint8_t *buffer, size_t size) { while (size--) write(*buffer++); } void Print::print(const String &s) { //##RG.Labs.20100919 begin //for (int i = 0; i < s.length(); i++) { for (unsigned int i = 0; i < s.length(); i++) { //##RG.Labs.20100919 end write(s[i]); } } void Print::print(const char str[]) { write(str); } void Print::print(char c, int base) { print((long) c, base); } void Print::print(unsigned char b, int base) { print((unsigned long) b, base); } void Print::print(int n, int base) { print((long) n, base); } void Print::print(unsigned int n, int base) { print((unsigned long) n, base); } void Print::print(long n, int base) { if (base == 0) { write(n); } else if (base == 10) { if (n < 0) { print('-'); n = -n; } printNumber(n, 10); } else { printNumber(n, base); } } void Print::print(unsigned long n, int base) { if (base == 0) write(n); else printNumber(n, base); } void Print::print(double n, int digits) { printFloat(n, digits); } void Print::println(void) { print('\r'); print('\n'); } void Print::println(const String &s) { print(s); println(); } void Print::println(const char c[]) { print(c); println(); } void Print::println(char c, int base) { print(c, base); println(); } void Print::println(unsigned char b, int base) { print(b, base); println(); } void Print::println(int n, int base) { print(n, base); println(); } void Print::println(unsigned int n, int base) { print(n, base); println(); } void Print::println(long n, int base) { print(n, base); println(); } void Print::println(unsigned long n, int base) { print(n, base); println(); } void Print::println(double n, int digits) { print(n, digits); println(); } // Private Methods ///////////////////////////////////////////////////////////// void Print::printNumber(unsigned long n, uint8_t base) { unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars. unsigned long i = 0; if (n == 0) { print('0'); return; } while (n > 0) { buf[i++] = n % base; n /= base; } for (; i > 0; i--) print((char) (buf[i - 1] < 10 ? '0' + buf[i - 1] : 'A' + buf[i - 1] - 10)); } void Print::printFloat(double number, uint8_t digits) { // Handle negative numbers if (number < 0.0) { print('-'); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for (uint8_t i=0; i<digits; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long)number; double remainder = number - (double)int_part; print(int_part); // Print the decimal point, but only if there are digits beyond if (digits > 0) print("."); // Extract digits from the remainder one at a time while (digits-- > 0) { remainder *= 10.0; int toPrint = int(remainder); print(toPrint); remainder -= toPrint; } }
C++
//#include "CPPLib.h" #include "WProgram.h" #include "main.pde" //Arduino-like main: int main(void) { init(); setup(); for (;;) loop(); return 0; } /* //WinAVR C++ conventional main: int main() { while(true) { } return 0; } */
C++
#ifndef __ext_ins__ #define __ext_ins__ #define wr0 0x0 #define wr2 0x1 #define wr4 0x2 #define wr6 0x3 #define iwr0 0x10 #define iwr2 0x11 #define iwr4 0x12 #define iwr6 0x13 add16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0x20 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0x10 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0x00 | x<<2 | y) #endif endm addc16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0x50 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0x40 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0x30 | x<<2 | y) #endif endm add16s macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0x80 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0x70 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0x60 | x<<2 | y) #endif endm addc16s macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0xb0 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0xa0 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0x90 | x<<2 | y) #endif endm sub16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0xe0 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0xd0 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0xc0 | x<<2 | y) #endif endm subc16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0x10 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0x00 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0xf0 | x<<2 | y) #endif endm sub16s macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0x40 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0x30 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0x20 | x<<2 | y) #endif endm subc16s macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0x70 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0x60 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0x50 | x<<2 | y) #endif endm anl16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0xa0 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0x90 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0x80 | x<<2 | y) #endif endm orl16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0xd0 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0xc0 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0xb0 | x<<2 | y) #endif endm xrl16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x02, (0x00 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0xf0 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0xe0 | x<<2 | y) #endif endm mac16 macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) db 0xa5, 0x02, (0x20 | x<<2 | (y & 0xf)) #else db 0xa5, 0x02, (0x10 | x<<2 | y) #endif endm mac16s macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) db 0xa5, 0x02, (0x40 | x<<2 | (y & 0xf)) #else db 0xa5, 0x02, (0x30 | x<<2 | y) #endif endm mov16b macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x02, (0x60 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x02, (0x50 | (y & 0xf) | x<<2) #else errors ... #endif endm lsl16k macro x, y #if (x > 0xf) errors ... #else db 0xa5, 0x03, (0x00 | (y & 0xc) << 2 | (y & 0x3) | x<<2) #endif endm lsr16k macro x, y #if (x > 0xf) errors ... #else db 0xa5, 0x03, (0x40 | (y & 0xc) << 2 | (y & 0x3) | x<<2) #endif endm rotl16k macro x, y #if (x > 0xf) errors ... #else db 0xa5, 0x03, (0x80 | (y & 0xc) << 2 | (y & 0x3) | x<<2) #endif endm asr16k macro x, y #if (x > 0xf) errors ... #else db 0xa5, 0x03, (0xc0 | (y & 0xc) << 2 | (y & 0x3) | x<<2) #endif endm rotl8 macro x, y db 0xa5, 0x04 endm rotr8 macro x, y db 0xa5, 0x05 endm rotl8k macro x,y #if (y > 0x7) errors ... #else db 0xa5, (0x08 | y) #endif endm inc16 macro x db 0xa5, (0x10 | x) endm inc216 macro x db 0xa5, (0x14 | x) endm dec16 macro x db 0xa5, (0x18 | x) endm dec216 macro x db 0xa5, (0x1c | x) endm rotl16 macro x, y #if (x > 0x3) db 0xa5, (0x28 | (x & 0xf)) #else db 0xa5, (0x20 | x) #endif endm rotr16 macro x, y #if (x > 0x3) db 0xa5, (0x2c | (x & 0xf)) #else db 0xa5, (0x24 | x) #endif endm lsr16 macro x,y #if (x > 0x3) db 0xa5, (0x38 | (x & 0xf)) #else db 0xa5, (0x30 | x) #endif endm lsl16 macro x, y #if (x > 0x3) db 0xa5, (0x3c | (x & 0xf)) #else db 0xa5, (0x34 | x) #endif endm asr16 macro x, y #if (x > 0x3) db 0xa5, (0x44 | (x & 0xf)) #else db 0xa5, (0x40 | x) #endif endm movsa macro x, y db 0xa5, (0x48 | x) endm movsb macro x, y db 0xa5, (0x4c | x) endm //mov8bta macro x, y // db 0xa5, (0x50 | (y & 0xf)) // endm // //movat8b macro x, y // db 0xa5, (0x54 | (x & 0xf)) // endm // //mov8bb macro x, y // db 0xa5, (0x70 | (x & 0xf)<<2 | (y & 0xf)) // endm cmp16 macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) errors ... #else db 0xa5, (0x60 | x<<2 | y) #endif endm mov16 macro x, y #if ((x > 0x3) & (y > 0x3)) db 0xa5, (0xb0 | (x & 0xf)<<2 | (y & 0xf)) #elif (x > 0x3) db 0xa5, (0x90 | ((x & 0xf)) | y<<2) #elif (y > 0x3) db 0xa5, (0xa0 | (x<<2) | (y & 0xf)) #else db 0xa5, (0x80 | x<<2 | y) #endif endm mul16 macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) db 0xa5, (0xd0 | x<<2 | (y & 0xf)) #else db 0xa5, (0xc0 | x<<2 | y) #endif endm mul16s macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) db 0xa5, (0xf0 | x<<2 | (y & 0xf)) #else db 0xa5, (0xe0 | x<<2 | y) #endif endm mul16wr macro x, y #if (x != wr4) errors ... #elseif (y != wr2) errors ... #else db 0xa5, 0x06 #endif endm mul16swr macro x, y #if (x != wr4) errors ... #elseif (y != wr2) errors ... #else db 0xa5, 0x07 #endif endm /*----------------------------------------------------------------------------*/ /** @brief: @param: @return: @author:Juntham @note: @date: 2012-05-29,19:30 */ /*----------------------------------------------------------------------------*/ uart_put macro reg LOCAL lab push ACC lab: mov a, UART_STA jnb ACC.7, lab pop ACC mov UART_BUF,reg endm #endif
C++
#ifndef __ext_ins__ #define __ext_ins__ #define wr0 0x0 #define wr2 0x1 #define wr4 0x2 #define wr6 0x3 #define iwr0 0x10 #define iwr2 0x11 #define iwr4 0x12 #define iwr6 0x13 add16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0x20 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0x10 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0x00 | x<<2 | y) #endif endm addc16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0x50 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0x40 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0x30 | x<<2 | y) #endif endm add16s macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0x80 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0x70 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0x60 | x<<2 | y) #endif endm addc16s macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0xb0 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0xa0 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0x90 | x<<2 | y) #endif endm sub16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x00, (0xe0 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x00, (0xd0 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0xc0 | x<<2 | y) #endif endm subc16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0x10 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0x00 | (y & 0xf) | x<<2) #else db 0xa5, 0x00, (0xf0 | x<<2 | y) #endif endm sub16s macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0x40 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0x30 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0x20 | x<<2 | y) #endif endm subc16s macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0x70 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0x60 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0x50 | x<<2 | y) #endif endm anl16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0xa0 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0x90 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0x80 | x<<2 | y) #endif endm orl16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x01, (0xd0 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0xc0 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0xb0 | x<<2 | y) #endif endm xrl16 macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x02, (0x00 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x01, (0xf0 | (y & 0xf) | x<<2) #else db 0xa5, 0x01, (0xe0 | x<<2 | y) #endif endm mac16 macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) db 0xa5, 0x02, (0x20 | x<<2 | (y & 0xf)) #else db 0xa5, 0x02, (0x10 | x<<2 | y) #endif endm mac16s macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) db 0xa5, 0x02, (0x40 | x<<2 | (y & 0xf)) #else db 0xa5, 0x02, (0x30 | x<<2 | y) #endif endm mov16b macro x, y #if (((x > 0x3) + (y > 0x3)) > 1) errors ... #elif (x > 0x3) db 0xa5, 0x02, (0x60 | (x & 0xf) | y<<2) #elif (y > 0x3) db 0xa5, 0x02, (0x50 | (y & 0xf) | x<<2) #else errors ... #endif endm lsl16k macro x, y #if (x > 0xf) errors ... #else db 0xa5, 0x03, (0x00 | (y & 0xc) << 2 | (y & 0x3) | x<<2) #endif endm lsr16k macro x, y #if (x > 0xf) errors ... #else db 0xa5, 0x03, (0x40 | (y & 0xc) << 2 | (y & 0x3) | x<<2) #endif endm rotl16k macro x, y #if (x > 0xf) errors ... #else db 0xa5, 0x03, (0x80 | (y & 0xc) << 2 | (y & 0x3) | x<<2) #endif endm asr16k macro x, y #if (x > 0xf) errors ... #else db 0xa5, 0x03, (0xc0 | (y & 0xc) << 2 | (y & 0x3) | x<<2) #endif endm rotl8 macro x, y db 0xa5, 0x04 endm rotr8 macro x, y db 0xa5, 0x05 endm rotl8k macro x,y #if (y > 0x7) errors ... #else db 0xa5, (0x08 | y) #endif endm inc16 macro x db 0xa5, (0x10 | x) endm inc216 macro x db 0xa5, (0x14 | x) endm dec16 macro x db 0xa5, (0x18 | x) endm dec216 macro x db 0xa5, (0x1c | x) endm rotl16 macro x, y #if (x > 0x3) db 0xa5, (0x28 | (x & 0xf)) #else db 0xa5, (0x20 | x) #endif endm rotr16 macro x, y #if (x > 0x3) db 0xa5, (0x2c | (x & 0xf)) #else db 0xa5, (0x24 | x) #endif endm lsr16 macro x,y #if (x > 0x3) db 0xa5, (0x38 | (x & 0xf)) #else db 0xa5, (0x30 | x) #endif endm lsl16 macro x, y #if (x > 0x3) db 0xa5, (0x3c | (x & 0xf)) #else db 0xa5, (0x34 | x) #endif endm asr16 macro x, y #if (x > 0x3) db 0xa5, (0x44 | (x & 0xf)) #else db 0xa5, (0x40 | x) #endif endm movsa macro x, y db 0xa5, (0x48 | x) endm movsb macro x, y db 0xa5, (0x4c | x) endm //mov8bta macro x, y // db 0xa5, (0x50 | (y & 0xf)) // endm // //movat8b macro x, y // db 0xa5, (0x54 | (x & 0xf)) // endm // //mov8bb macro x, y // db 0xa5, (0x70 | (x & 0xf)<<2 | (y & 0xf)) // endm cmp16 macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) errors ... #else db 0xa5, (0x60 | x<<2 | y) #endif endm mov16 macro x, y #if ((x > 0x3) & (y > 0x3)) db 0xa5, (0xb0 | (x & 0xf)<<2 | (y & 0xf)) #elif (x > 0x3) db 0xa5, (0x90 | ((x & 0xf)) | y<<2) #elif (y > 0x3) db 0xa5, (0xa0 | (x<<2) | (y & 0xf)) #else db 0xa5, (0x80 | x<<2 | y) #endif endm mul16 macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) db 0xa5, (0xd0 | x<<2 | (y & 0xf)) #else db 0xa5, (0xc0 | x<<2 | y) #endif endm mul16s macro x, y #if (x > 0x3) errors ... #elif (y > 0x3) db 0xa5, (0xf0 | x<<2 | (y & 0xf)) #else db 0xa5, (0xe0 | x<<2 | y) #endif endm mul16wr macro x, y #if (x != wr4) errors ... #elseif (y != wr2) errors ... #else db 0xa5, 0x06 #endif endm mul16swr macro x, y #if (x != wr4) errors ... #elseif (y != wr2) errors ... #else db 0xa5, 0x07 #endif endm /*----------------------------------------------------------------------------*/ /** @brief: @param: @return: @author:Juntham @note: @date: 2012-05-29,19:30 */ /*----------------------------------------------------------------------------*/ uart_put macro reg LOCAL lab push ACC lab: mov a, UART_STA jnb ACC.7, lab pop ACC mov UART_BUF,reg endm #endif
C++
// // Class: CButtonST // // Compiler: Visual C++ // Tested on: Visual C++ 5.0 // Visual C++ 6.0 // // Version: See GetVersionC() or GetVersionI() // // Created: xx/xxxx/1998 // Updated: 25/November/2002 // // Author: Davide Calabro' davide_calabro@yahoo.com // http://www.softechsoftware.it // // Note: Code for the PreSubclassWindow and OnSetStyle functions // has been taken from the COddButton class // published by Paolo Messina and Jerzy Kaczorowski // // Disclaimer // ---------- // THIS SOFTWARE AND THE ACCOMPANYING FILES ARE DISTRIBUTED "AS IS" AND WITHOUT // ANY WARRANTIES WHETHER EXPRESSED OR IMPLIED. NO REPONSIBILITIES FOR POSSIBLE // DAMAGES OR EVEN FUNCTIONALITY CAN BE TAKEN. THE USER MUST ASSUME THE ENTIRE // RISK OF USING THIS SOFTWARE. // // Terms of use // ------------ // THIS SOFTWARE IS FREE FOR PERSONAL USE OR FREEWARE APPLICATIONS. // IF YOU USE THIS SOFTWARE IN COMMERCIAL OR SHAREWARE APPLICATIONS YOU // ARE GENTLY ASKED TO DONATE 5$ (FIVE U.S. DOLLARS) TO THE AUTHOR: // // Davide Calabro' // P.O. Box 65 // 21019 Somma Lombardo (VA) // Italy // // Modified by jingzhou xu, Add background color support // #ifndef _BTNST_H #define _BTNST_H // Uncomment the following line to enable support for sound effects #define BTNST_USE_SOUND #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // Return values #ifndef BTNST_OK #define BTNST_OK 0 #endif #ifndef BTNST_INVALIDRESOURCE #define BTNST_INVALIDRESOURCE 1 #endif #ifndef BTNST_FAILEDMASK #define BTNST_FAILEDMASK 2 #endif #ifndef BTNST_INVALIDINDEX #define BTNST_INVALIDINDEX 3 #endif #ifndef BTNST_INVALIDALIGN #define BTNST_INVALIDALIGN 4 #endif #ifndef BTNST_BADPARAM #define BTNST_BADPARAM 5 #endif #ifndef BTNST_INVALIDPRESSEDSTYLE #define BTNST_INVALIDPRESSEDSTYLE 6 #endif // Dummy identifier for grayscale icon #ifndef BTNST_AUTO_GRAY #define BTNST_AUTO_GRAY (HICON)(0xffffffff - 1L) #endif class CButtonST : public CButton { public: CButtonST(); ~CButtonST(); enum { ST_ALIGN_HORIZ = 0, // Icon/bitmap on the left, text on the right ST_ALIGN_VERT, // Icon/bitmap on the top, text on the bottom ST_ALIGN_HORIZ_RIGHT, // Icon/bitmap on the right, text on the left ST_ALIGN_OVERLAP // Icon/bitmap on the same space as text }; enum { BTNST_COLOR_BK_IN = 0, // Background color when mouse is INside BTNST_COLOR_FG_IN, // Text color when mouse is INside BTNST_COLOR_BK_OUT, // Background color when mouse is OUTside BTNST_COLOR_FG_OUT, // Text color when mouse is OUTside BTNST_COLOR_BK_FOCUS, // Background color when the button is focused BTNST_COLOR_FG_FOCUS, // Text color when the button is focused BTNST_MAX_COLORS }; enum { BTNST_PRESSED_LEFTRIGHT = 0, // Pressed style from left to right (as usual) BTNST_PRESSED_TOPBOTTOM // Pressed style from top to bottom }; // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CButtonST) public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); virtual BOOL PreTranslateMessage(MSG* pMsg); protected: virtual void PreSubclassWindow(); //}}AFX_VIRTUAL public: DWORD SetDefaultColors(BOOL bRepaint = TRUE); DWORD SetColor(BYTE byColorIndex, COLORREF crColor, BOOL bRepaint = TRUE); DWORD GetColor(BYTE byColorIndex, COLORREF* crpColor); DWORD OffsetColor(BYTE byColorIndex, short shOffset, BOOL bRepaint = TRUE); // Background color support, jingzhou xu void SetBkColor(COLORREF clrBk); COLORREF GetBkColor(); DWORD SetCheck(int nCheck, BOOL bRepaint = TRUE); int GetCheck(); DWORD SetURL(LPCTSTR lpszURL = NULL); void DrawTransparent(BOOL bRepaint = FALSE); DWORD SetBk(CDC* pDC); BOOL GetDefault(); DWORD SetAlwaysTrack(BOOL bAlwaysTrack = TRUE); void SetTooltipText(int nText, BOOL bActivate = TRUE); void SetTooltipText(LPCTSTR lpszText, BOOL bActivate = TRUE); void ActivateTooltip(BOOL bEnable = TRUE); DWORD EnableBalloonTooltip(); DWORD SetBtnCursor(int nCursorId = NULL, BOOL bRepaint = TRUE); DWORD SetFlat(BOOL bFlat = TRUE, BOOL bRepaint = TRUE); DWORD SetAlign(BYTE byAlign, BOOL bRepaint = TRUE); DWORD SetPressedStyle(BYTE byStyle, BOOL bRepaint = TRUE); DWORD DrawBorder(BOOL bDrawBorder = TRUE, BOOL bRepaint = TRUE); DWORD DrawFlatFocus(BOOL bDrawFlatFocus, BOOL bRepaint = TRUE); DWORD SetIcon(int nIconIn, int nIconOut = NULL); DWORD SetIcon(HICON hIconIn, HICON hIconOut = NULL); DWORD SetBitmaps(int nBitmapIn, COLORREF crTransColorIn, int nBitmapOut = NULL, COLORREF crTransColorOut = 0); DWORD SetBitmaps(HBITMAP hBitmapIn, COLORREF crTransColorIn, HBITMAP hBitmapOut = NULL, COLORREF crTransColorOut = 0); void SizeToContent(); #ifdef BTNST_USE_BCMENU DWORD SetMenu(UINT nMenu, HWND hParentWnd, BOOL bWinXPStyle = TRUE, UINT nToolbarID = NULL, CSize sizeToolbarIcon = CSize(16, 16), COLORREF crToolbarBk = RGB(255, 0, 255), BOOL bRepaint = TRUE); #else DWORD SetMenu(UINT nMenu, HWND hParentWnd, BOOL bRepaint = TRUE); #endif DWORD SetMenuCallback(HWND hWnd, UINT nMessage, LPARAM lParam = 0); #ifdef BTNST_USE_SOUND DWORD SetSound(LPCTSTR lpszSound, HMODULE hMod = NULL, BOOL bPlayOnClick = FALSE, BOOL bPlayAsync = TRUE); #endif static short GetVersionI() {return 38;} static LPCTSTR GetVersionC() {return (LPCTSTR)_T("3.8");} BOOL m_bShowDisabledBitmap; POINT m_ptImageOrg; POINT m_ptPressedOffset; protected: //{{AFX_MSG(CButtonST) afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message); afx_msg void OnKillFocus(CWnd* pNewWnd); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnSysColorChange(); afx_msg BOOL OnClicked(); afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized); afx_msg void OnEnable(BOOL bEnable); afx_msg void OnCancelMode(); afx_msg UINT OnGetDlgCode(); //}}AFX_MSG #ifdef BTNST_USE_BCMENU afx_msg LRESULT OnMenuChar(UINT nChar, UINT nFlags, CMenu* pMenu); afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct); #endif afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor); HICON CreateGrayscaleIcon(HICON hIcon); virtual DWORD OnDrawBackground(CDC* pDC, CRect* pRect); virtual DWORD OnDrawBorder(CDC* pDC, CRect* pRect); COLORREF m_clrBkColor; // Background color, jingzhou xu BOOL m_bIsFlat; // Is a flat button? BOOL m_bMouseOnButton; // Is mouse over the button? BOOL m_bDrawTransparent; // Draw transparent? BOOL m_bIsPressed; // Is button pressed? BOOL m_bIsFocused; // Is button focused? BOOL m_bIsDisabled; // Is button disabled? BOOL m_bIsDefault; // Is default button? BOOL m_bIsCheckBox; // Is the button a checkbox? BYTE m_byAlign; // Align mode BOOL m_bDrawBorder; // Draw border? BOOL m_bDrawFlatFocus; // Draw focus rectangle for flat button? COLORREF m_crColors[BTNST_MAX_COLORS]; // Colors to be used HWND m_hParentWndMenu; // Handle to window for menu selection BOOL m_bMenuDisplayed; // Is menu displayed ? #ifdef BTNST_USE_BCMENU BCMenu m_menuPopup; // BCMenu class instance #else HMENU m_hMenu; // Handle to associated menu #endif private: LRESULT OnSetCheck(WPARAM wParam, LPARAM lParam); LRESULT OnGetCheck(WPARAM wParam, LPARAM lParam); LRESULT OnSetStyle(WPARAM wParam, LPARAM lParam); LRESULT OnMouseLeave(WPARAM wParam, LPARAM lParam); void CancelHover(); void FreeResources(BOOL bCheckForNULL = TRUE); void PrepareImageRect(BOOL bHasTitle, RECT* rpItem, CRect* rpTitle, BOOL bIsPressed, DWORD dwWidth, DWORD dwHeight, CRect* rpImage); HBITMAP CreateBitmapMask(HBITMAP hSourceBitmap, DWORD dwWidth, DWORD dwHeight, COLORREF crTransColor); virtual void DrawTheIcon(CDC* pDC, BOOL bHasTitle, RECT* rpItem, CRect* rpCaption, BOOL bIsPressed, BOOL bIsDisabled); virtual void DrawTheBitmap(CDC* pDC, BOOL bHasTitle, RECT* rpItem, CRect* rpCaption, BOOL bIsPressed, BOOL bIsDisabled); virtual void DrawTheText(CDC* pDC, LPCTSTR lpszText, RECT* rpItem, CRect* rpCaption, BOOL bIsPressed, BOOL bIsDisabled); void PaintBk(CDC* pDC); void InitToolTip(); HCURSOR m_hCursor; // Handle to cursor CToolTipCtrl m_ToolTip; // Tooltip CDC m_dcBk; CBitmap m_bmpBk; CBitmap* m_pbmpOldBk; BOOL m_bAlwaysTrack; // Always hilight button? int m_nCheck; // Current value for checkbox UINT m_nTypeStyle; // Button style DWORD m_dwToolTipStyle; // Style of tooltip control TCHAR m_szURL[_MAX_PATH]; // URL to open when clicked #pragma pack(1) typedef struct _STRUCT_ICONS { HICON hIcon; // Handle to icon DWORD dwWidth; // Width of icon DWORD dwHeight; // Height of icon } STRUCT_ICONS; #pragma pack() #pragma pack(1) typedef struct _STRUCT_BITMAPS { HBITMAP hBitmap; // Handle to bitmap DWORD dwWidth; // Width of bitmap DWORD dwHeight; // Height of bitmap HBITMAP hMask; // Handle to mask bitmap COLORREF crTransparent; // Transparent color } STRUCT_BITMAPS; #pragma pack() #pragma pack(1) typedef struct _STRUCT_CALLBACK { HWND hWnd; // Handle to window UINT nMessage; // Message identifier WPARAM wParam; LPARAM lParam; } STRUCT_CALLBACK; #pragma pack() STRUCT_ICONS m_csIcons[2]; STRUCT_BITMAPS m_csBitmaps[2]; STRUCT_CALLBACK m_csCallbacks; #ifdef BTNST_USE_SOUND #pragma pack(1) typedef struct _STRUCT_SOUND { TCHAR szSound[_MAX_PATH]; LPCTSTR lpszSound; HMODULE hMod; DWORD dwFlags; } STRUCT_SOUND; #pragma pack() STRUCT_SOUND m_csSounds[2]; // Index 0 = Over 1 = Clicked #endif DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif
C++
#include "stdafx.h" #include "WinXPButtonST.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif CWinXPButtonST::CWinXPButtonST() { // No rounded borders m_bIsRounded = FALSE; } CWinXPButtonST::~CWinXPButtonST() { } // This function is called every time the button border needs to be painted. // This is a virtual function that can be rewritten in CButtonST-derived classes // to produce a whole range of buttons not available by default. // // Parameters: // [IN] pDC // Pointer to a CDC object that indicates the device context. // [IN] pRect // Pointer to a CRect object that indicates the bounds of the // area to be painted. // // Return value: // BTNST_OK // Function executed successfully. // DWORD CWinXPButtonST::OnDrawBorder(CDC* pDC, CRect* pRect) { return BTNST_OK; } // End of OnDrawBorder // This function is called every time the button background needs to be painted. // If the button is in transparent mode this function will NOT be called. // This is a virtual function that can be rewritten in CButtonST-derived classes // to produce a whole range of buttons not available by default. // // Parameters: // [IN] pDC // Pointer to a CDC object that indicates the device context. // [IN] pRect // Pointer to a CRect object that indicates the bounds of the // area to be painted. // // Return value: // BTNST_OK // Function executed successfully. // DWORD CWinXPButtonST::OnDrawBackground(CDC* pDC, CRect* pRect) { COLORREF crBackColor = m_crColors[BTNST_COLOR_BK_IN]; COLORREF crBorderColor = RGB(0, 0, 0); if (!m_bMouseOnButton && !m_bIsPressed) { crBackColor = GetSysColor(COLOR_BTNFACE); crBorderColor = GetSysColor(COLOR_BTNSHADOW); // return BASE_BUTTONST::OnDrawBackground(pDC, pRect); } // Create and select a solid brush for button background CBrush brushBK(crBackColor); CBrush* pOldBrush = pDC->SelectObject(&brushBK); // Create and select a thick black pen for button border CPen penBorder; penBorder.CreatePen(PS_SOLID, 1, crBorderColor); CPen* pOldPen = pDC->SelectObject(&penBorder); if (m_bIsRounded) pDC->RoundRect(pRect, CPoint(8, 8)); else pDC->Rectangle(pRect); // Put back the old objects pDC->SelectObject(pOldBrush); pDC->SelectObject(pOldPen); return BTNST_OK; } // End of OnDrawBackground // This function enables or disables the rounded border for the button. // // Parameters: // [IN] bRounded // If TRUE the button will have a round border. // [IN] bRepaint // If TRUE the button will be repainted. // // Return value: // BTNST_OK // Function executed successfully. // DWORD CWinXPButtonST::SetRounded(BOOL bRounded, BOOL bRepaint) { m_bIsRounded = bRounded; if (bRepaint) Invalidate(); return BTNST_OK; } // End of SetRounded #undef BASE_BUTTONST
C++
#if !defined(AFX_HOVEREDIT_H__372AC76D_6B84_435C_8300_9519EB021C8C__INCLUDED_) #define AFX_HOVEREDIT_H__372AC76D_6B84_435C_8300_9519EB021C8C__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // HoverEdit.h : header file // //#include "TrackControl.h" ///////////////////////////////////////////////////////////////////////////// // CHoverEdit window template<class BaseClass> ///////////////////////////////////////////////////////////////////////////// // CTrackControl window class CTrackControl : public BaseClass { // Construction public: CTrackControl() { m_bTracking=m_bHover=FALSE; } virtual ~CTrackControl() {} BOOLEAN IsHover() { return m_bHover; } // Implementation public: virtual void OnHoverEnter()=0; virtual void OnHoverLeave()=0; // Generated message map functions protected: virtual LRESULT WindowProc(UINT nMessage, WPARAM wParam, LPARAM lParam) { LRESULT nResult=BaseClass::WindowProc(nMessage,wParam,lParam); switch(nMessage) { case WM_MOUSEMOVE: { if (!m_bTracking) { TRACKMOUSEEVENT Tme; Tme.cbSize = sizeof(Tme); Tme.hwndTrack = GetSafeHwnd(); Tme.dwFlags = TME_LEAVE|TME_HOVER; Tme.dwHoverTime = 1; if (_TrackMouseEvent(&Tme)) m_bTracking=TRUE; } break; } case WM_MOUSEHOVER: m_bHover=TRUE; OnHoverEnter(); break; case WM_MOUSELEAVE: m_bTracking=m_bHover=FALSE; OnHoverLeave(); break; } return nResult; } private: BOOLEAN m_bTracking; BOOLEAN m_bHover; }; class CHoverEdit : public CTrackControl<CEdit> { // Construction public: CHoverEdit(); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CHoverEdit) //}}AFX_VIRTUAL // Implementation public: virtual void OnHoverLeave(); virtual void OnHoverEnter(); virtual ~CHoverEdit(); // Generated message map functions protected: //{{AFX_MSG(CHoverEdit) afx_msg void OnNcPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: inline void Redraw(); }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_HOVEREDIT_H__372AC76D_6B84_435C_8300_9519EB021C8C__INCLUDED_)
C++
// // Class: CWinXPButtonST // // Compiler: Visual C++ // eMbedded Visual C++ // Tested on: Visual C++ 6.0 // Windows CE 3.0 // // Created: 03/September/2001 // Updated: 25/November/2002 // // Author: Davide Calabro' davide_calabro@yahoo.com // Modified by jingzhou xu. // // Disclaimer // ---------- // THIS SOFTWARE AND THE ACCOMPANYING FILES ARE DISTRIBUTED "AS IS" AND WITHOUT // ANY WARRANTIES WHETHER EXPRESSED OR IMPLIED. NO REPONSIBILITIES FOR POSSIBLE // DAMAGES OR EVEN FUNCTIONALITY CAN BE TAKEN. THE USER MUST ASSUME THE ENTIRE // RISK OF USING THIS SOFTWARE. // // Terms of use // ------------ // THIS SOFTWARE IS FREE FOR PERSONAL USE OR FREEWARE APPLICATIONS. // IF YOU USE THIS SOFTWARE IN COMMERCIAL OR SHAREWARE APPLICATIONS YOU // ARE GENTLY ASKED TO DONATE 5$ (FIVE U.S. DOLLARS) TO THE AUTHOR: // // Davide Calabro' // P.O. Box 65 // 21019 Somma Lombardo (VA) // Italy // #ifndef _WINXPBUTTONST_H_ #define _WINXPBUTTONST_H_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifdef UNDER_CE #include "CeBtnST.h" #define BASE_BUTTONST CCeButtonST #else #include "BtnST.h" #define BASE_BUTTONST CButtonST #endif class CWinXPButtonST : public BASE_BUTTONST { public: CWinXPButtonST(); virtual ~CWinXPButtonST(); DWORD SetRounded(BOOL bRounded, BOOL bRepaint = TRUE); protected: virtual DWORD OnDrawBackground(CDC* pDC, CRect* pRect); virtual DWORD OnDrawBorder(CDC* pDC, CRect* pRect); private: BOOL m_bIsRounded; // Borders must be rounded? }; #endif
C++
// HoverEdit.cpp : implementation file // #include "stdafx.h" #include "HoverEdit.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CHoverEdit CHoverEdit::CHoverEdit() { } CHoverEdit::~CHoverEdit() { } BEGIN_MESSAGE_MAP(CHoverEdit, CEdit) //{{AFX_MSG_MAP(CHoverEdit) ON_WM_NCPAINT() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CHoverEdit message handlers void CHoverEdit::OnHoverEnter() { Redraw(); } void CHoverEdit::OnHoverLeave() { Redraw(); } void CHoverEdit::Redraw() { RedrawWindow(NULL,NULL,RDW_FRAME|RDW_INVALIDATE); } void CHoverEdit::OnNcPaint() { CWindowDC DC(this); CRect Rect; GetWindowRect(&Rect); if (IsHover()) { DC.Rectangle(0,0,Rect.Width(),Rect.Height()); } else { DC.DrawEdge(CRect(0,0,Rect.Width(),Rect.Height()),EDGE_SUNKEN,BF_FLAT|BF_RECT); } }
C++
//////////////////////////////////////////////////////////////// // PixieLib(TM) Copyright 1997-2005 Paul DiLascia // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // Compiles with Visual Studio.NET 7.1 or greater. Set tabsize=3. // ////////////////// // Helper class to build a dialog template in memory. Only supports what's // needed for CStringDialog. // class CDlgTemplateBuilder { protected: WORD* m_pBuffer; // internal buffer holds dialog template WORD* m_pNext; // next WORD to copy stuff WORD* m_pEndBuf; // end of buffer // align ptr to nearest DWORD WORD* AlignDWORD(WORD* ptr) { ptr++; // round up to nearest DWORD LPARAM lp = (LPARAM)ptr; // convert to long lp &= 0xFFFFFFFC; // make sure on DWORD boundary return (WORD*)lp; } void AddItemTemplate(WORD wType, DWORD dwStyle, const CRect& rc, WORD nID, DWORD dwStyleEx); public: // Windows predefined atom names enum { BUTTON=0x0080, EDIT, STATIC, LISTBOX, SCROLLBAR, COMBOBOX }; CDlgTemplateBuilder(UINT nBufLen=1024); ~CDlgTemplateBuilder(); DLGTEMPLATE* GetTemplate() { return (DLGTEMPLATE*)m_pBuffer; } // functions to build the template DLGTEMPLATE* Begin(DWORD dwStyle, const CRect& rc, LPCTSTR caption, DWORD dwStyleEx=0); WORD* AddText(WORD* buf, LPCTSTR text); void AddItem(WORD wType, DWORD dwStyle, const CRect& rc, LPCTSTR text, WORD nID=-1, DWORD dwStyleEx=0); void AddItem(WORD wType, DWORD dwStyle, const CRect& rc, WORD nResID, WORD nID=-1, DWORD dwStyleEx=0); }; ////////////////// // Class to implement a simple string input dialog. Kind of like MessageBox // but it accepts a single string input from user. You provide the prompt. To // use: // // CStringDialog dlg; // string dialog // dlg.m_bRequired = m_bRequired; // if string is required // dlg.Init(_T("Title"), _T("Enter a string:"), this, IDI_QUESTION); // dlg.DoModal(); // run dialog // CString result = dlg.m_str; // whatever the user typed // class CStringDialog : public CDialog { public: CString m_str; // the string returned [in,out] BOOL m_bRequired; // string required? HICON m_hIcon; // icon if not supplied CStringDialog() { } ~CStringDialog() { } // Call this to create the template with given caption and prompt. BOOL Init(LPCTSTR caption, LPCTSTR prompt, CWnd* pParent=NULL, WORD nIDIcon=(WORD)IDI_QUESTION); protected: CDlgTemplateBuilder m_dtb; // place to build/hold the dialog template enum { IDICON=1, IDEDIT }; // control IDs // MFC virtual overrides virtual BOOL OnInitDialog(); virtual void OnOK(); virtual void DoDataExchange(CDataExchange* pDX) { DDX_Text(pDX, IDEDIT, m_str); DDV_MaxChars(pDX, m_str, 256); } };
C++
// gh0stDoc.h : interface of the CGh0stDoc class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_GH0STDOC_H__57FB1788_3C2A_40A9_BAB7_3F192505E38E__INCLUDED_) #define AFX_GH0STDOC_H__57FB1788_3C2A_40A9_BAB7_3F192505E38E__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CGh0stDoc : public CDocument { protected: // create from serialization only CGh0stDoc(); DECLARE_DYNCREATE(CGh0stDoc) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CGh0stDoc) public: virtual void Serialize(CArchive& ar); virtual void DeleteContents(); //}}AFX_VIRTUAL // Implementation public: virtual ~CGh0stDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CGh0stDoc) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_GH0STDOC_H__57FB1788_3C2A_40A9_BAB7_3F192505E38E__INCLUDED_)
C++
// IniFile.cpp: implementation of the CIniFile class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "gh0st.h" #include "IniFile.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define MAX_LENGTH 256 ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CIniFile::CIniFile() { char szAppName[MAX_PATH]; int len; ::GetModuleFileName(AfxGetInstanceHandle(), szAppName, sizeof(szAppName)); len = strlen(szAppName); for(int i=len; i>0; i--) { if(szAppName[i] == '.') { szAppName[i+1] = '\0'; break; } } strcat(szAppName, "ini"); IniFileName = szAppName; } CIniFile::~CIniFile() { } CString CIniFile::GetString(CString AppName,CString KeyName,CString Default) { TCHAR buf[MAX_LENGTH]; ::GetPrivateProfileString(AppName, KeyName, Default, buf, sizeof(buf), IniFileName); return buf; } int CIniFile::GetInt(CString AppName,CString KeyName,int Default) { return ::GetPrivateProfileInt(AppName, KeyName, Default, IniFileName); } unsigned long CIniFile::GetDWORD(CString AppName,CString KeyName,unsigned long Default) { TCHAR buf[MAX_LENGTH]; CString temp; temp.Format("%u",Default); ::GetPrivateProfileString(AppName, KeyName, temp, buf, sizeof(buf), IniFileName); return atol(buf); } BOOL CIniFile::SetString(CString AppName,CString KeyName,CString Data) { return ::WritePrivateProfileString(AppName, KeyName, Data, IniFileName); } BOOL CIniFile::SetInt(CString AppName,CString KeyName,int Data) { CString temp; temp.Format("%d", Data); return ::WritePrivateProfileString(AppName, KeyName, temp, IniFileName); } BOOL CIniFile::SetDouble(CString AppName,CString KeyName,double Data) { CString temp; temp.Format("%f",Data); return ::WritePrivateProfileString(AppName, KeyName, temp, IniFileName); } BOOL CIniFile::SetDWORD(CString AppName,CString KeyName,unsigned long Data) { CString temp; temp.Format("%u",Data); return ::WritePrivateProfileString(AppName, KeyName, temp, IniFileName); }
C++
#pragma once /********************************************************************** ** ** CustomTabCtrl.h : include file ** ** by Andrzej Markowski June 2004 ** **********************************************************************/ #include <Afxtempl.h> #include <afxcmn.h> #include "themeutil.h" #ifndef WS_EX_LAYOUTRTL #define WS_EX_LAYOUTRTL 0x400000 #endif // CustomTabCtrlItem #define TAB_SHAPE1 0 // Invisible #define TAB_SHAPE2 1 // __ // | / // |/ #define TAB_SHAPE3 2 // |\ // |/ #define TAB_SHAPE4 3 // ____________ // \ / // \________/ #define TAB_SHAPE5 4 // ___________ // \ \ // \________/ #define RECALC_PREV_PRESSED 0 #define RECALC_NEXT_PRESSED 1 #define RECALC_ITEM_SELECTED 2 #define RECALC_RESIZED 3 #define RECALC_FIRST_PRESSED 4 #define RECALC_LAST_PRESSED 5 #define RECALC_EDIT_RESIZED 6 #define RECALC_CLOSE_PRESSED 7 #define MAX_LABEL_TEXT 30 typedef struct _CTC_NMHDR { NMHDR hdr; int nItem; TCHAR pszText[MAX_LABEL_TEXT]; LPARAM lParam; RECT rItem; POINT ptHitTest; BOOL fSelected; BOOL fHighlighted; } CTC_NMHDR; class CCustomTabCtrlItem { friend class CCustomTabCtrl; private: CCustomTabCtrlItem(CString sText, LPARAM lParam); void ComputeRgn(BOOL fOnTop); void Draw(CDC& dc, CFont& font, BOOL fOnTop, BOOL fRTL); BOOL HitTest(CPoint pt) { return (m_bShape && m_rgn.PtInRegion(pt)) ? TRUE : FALSE; } void GetRegionPoints(const CRect& rc, CPoint* pts, BOOL fOnTop) const; void GetDrawPoints(const CRect& rc, CPoint* pts, BOOL fOnTop) const; void operator=(const CCustomTabCtrlItem &other); private: CString m_sText; LPARAM m_lParam; CRect m_rect; CRect m_rectText; CRgn m_rgn; BYTE m_bShape; BOOL m_fSelected; BOOL m_fHighlighted; BOOL m_fHighlightChanged; }; // CCustomTabCtrl // styles #define CTCS_FIXEDWIDTH 1 // Makes all tabs the same width. #define CTCS_FOURBUTTONS 2 // Four buttons (First, Prev, Next, Last) #define CTCS_AUTOHIDEBUTTONS 4 // Auto hide buttons #define CTCS_TOOLTIPS 8 // Tooltips #define CTCS_MULTIHIGHLIGHT 16 // Multi highlighted items #define CTCS_EDITLABELS 32 // Allows item text to be edited in place #define CTCS_DRAGMOVE 64 // Allows move items #define CTCS_DRAGCOPY 128 // Allows copy items #define CTCS_CLOSEBUTTON 256 // Close button #define CTCS_BUTTONSAFTER 512 // Button after items #define CTCS_TOP 1024 // Location on top #define CTCS_RIGHT 2048 // Location on right #define CTCS_LEFT 3072 // Location on left // hit test #define CTCHT_ONFIRSTBUTTON -1 #define CTCHT_ONPREVBUTTON -2 #define CTCHT_ONNEXTBUTTON -3 #define CTCHT_ONLASTBUTTON -4 #define CTCHT_ONCLOSEBUTTON -5 #define CTCHT_NOWHERE -6 // notification messages #define CTCN_CLICK NM_CLICK #define CTCN_RCLICK NM_RCLICK #define CTCN_DBLCLK NM_DBLCLK #define CTCN_RDBLCLK NM_RDBLCLK #define CTCN_OUTOFMEMORY NM_OUTOFMEMORY #define CTCN_SELCHANGE NM_FIRST #define CTCN_HIGHLIGHTCHANGE NM_FIRST + 1 #define CTCN_ITEMMOVE NM_FIRST + 2 #define CTCN_ITEMCOPY NM_FIRST + 3 #define CTCN_LABELUPDATE NM_FIRST + 4 #define CTCID_FIRSTBUTTON -1 #define CTCID_PREVBUTTON -2 #define CTCID_NEXTBUTTON -3 #define CTCID_LASTBUTTON -4 #define CTCID_CLOSEBUTTON -5 #define CTCID_NOBUTTON -6 #define CTCID_EDITCTRL 1 #define REPEAT_TIMEOUT 250 // error codes #define CTCERR_NOERROR 0 #define CTCERR_OUTOFMEMORY -1 #define CTCERR_INDEXOUTOFRANGE -2 #define CTCERR_NOEDITLABELSTYLE -3 #define CTCERR_NOMULTIHIGHLIGHTSTYLE -4 #define CTCERR_ITEMNOTSELECTED -5 #define CTCERR_ALREADYINEDITMODE -6 #define CTCERR_TEXTTOOLONG -7 #define CTCERR_NOTOOLTIPSSTYLE -8 #define CTCERR_CREATETOOLTIPFAILED -9 #define CTCERR_EDITNOTSUPPORTED -10 // button states #define BNST_INVISIBLE 0 #define BNST_NORMAL DNHZS_NORMAL #define BNST_HOT DNHZS_HOT #define BNST_PRESSED DNHZS_PRESSED #define CustomTabCtrl_CLASSNAME _T("CCustomTabCtrl") // Window class name class CCustomTabCtrl : public CWnd { public: // Construction CCustomTabCtrl(); virtual ~CCustomTabCtrl(); BOOL Create(UINT dwStyle, const CRect & rect, CWnd * pParentWnd, UINT nID); // Attributes int GetItemCount() {return m_aItems.GetSize();} int GetCurSel() { return m_nItemSelected; } int SetCurSel(int nItem); int IsItemHighlighted(int nItem); int HighlightItem(int nItem, BOOL fHighlight); int GetItemData(int nItem, DWORD& dwData); int SetItemData(int nItem, DWORD dwData); int GetItemText(int nItem, CString& sText); int SetItemText(int nItem, CString sText); int GetItemRect(int nItem, CRect& rect) const; int SetItemTooltipText(int nItem, CString sText); void SetDragCursors(HCURSOR hCursorMove, HCURSOR hCursorCopy); BOOL ModifyStyle(DWORD dwRemove, DWORD dwAdd, UINT nFlags=0); BOOL ModifyStyleEx(DWORD dwRemove, DWORD dwAdd, UINT nFlags=0); void SetControlFont(const LOGFONT& lf, BOOL fRedraw=FALSE); static const LOGFONT& GetDefaultFont() {return lf_default;} BOOL IsVertical() { return (GetStyle()&CTCS_TOP && GetStyle()&CTCS_RIGHT) || GetStyle()&CTCS_RIGHT;} // Operations int InsertItem(int nItem, CString sText, LPARAM lParam=0); int DeleteItem(int nItem); void DeleteAllItems(); int MoveItem(int nItemSrc, int nItemDst); int CopyItem(int nItemSrc, int nItemDst); int HitTest(CPoint pt); int EditLabel(int nItem); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CCustomTabCtrl) protected: virtual void PreSubclassWindow(); virtual BOOL PreTranslateMessage(MSG* pMsg); //}}AFX_VIRTUAL protected: //{{AFX_MSG(CCustomTabCtrl) afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg LONG OnMouseLeave(WPARAM wParam, LPARAM lParam); afx_msg LONG OnThemeChanged(WPARAM wParam, LPARAM lParam); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnPaint(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point); afx_msg void OnTimer(UINT nIDEvent); afx_msg void OnUpdateEdit(); afx_msg void OnRButtonDblClk(UINT nFlags, CPoint point); //}}AFX_MSG afx_msg LRESULT OnSizeParent(WPARAM, LPARAM lParam); DECLARE_MESSAGE_MAP() private: void RecalcLayout(int nRecalcType,int nItem); void RecalcEditResized(int nOffset, int nItem); void RecalcOffset(int nOffset); int RecalcRectangles(); BOOL RegisterWindowClass(); int ProcessLButtonDown(int nHitTest, UINT nFlags, CPoint point); int MoveItem(int nItemSrc, int nItemDst, BOOL fMouseSel); int CopyItem(int nItemSrc, int nItemDst, BOOL fMouseSel); int SetCurSel(int nItem, BOOL fMouseSel, BOOL fCtrlPressed); int HighlightItem(int nItem, BOOL fMouseSel, BOOL fCtrlPressed); void DrawGlyph(CDC& dc, CPoint& pt, int nImageNdx, int nColorNdx); void DrawBk(CDC& dc, CRect& r, HBITMAP hBmp, BOOL fIsImageHorLayout, MY_MARGINS& mrgn, int nImageNdx); BOOL NotifyParent(UINT code, int nItem, CPoint pt); int EditLabel(int nItem, BOOL fMouseSel); private: static LOGFONT lf_default; static BYTE m_bBitsGlyphs[]; HCURSOR m_hCursorMove; HCURSOR m_hCursorCopy; CFont m_Font; CFont m_FontSelected; int m_nItemSelected; int m_nItemNdxOffset; int m_nItemDragDest; int m_nPrevState; int m_nNextState; int m_nFirstState; int m_nLastState; int m_nCloseState; int m_nButtonIDDown; DWORD m_dwLastRepeatTime; COLORREF m_rgbGlyph[4]; CBitmap m_bmpGlyphsMono; HBITMAP m_hBmpBkLeftSpin; HBITMAP m_hBmpBkRightSpin; BOOL m_fIsLeftImageHorLayout; BOOL m_fIsRightImageHorLayout; MY_MARGINS m_mrgnLeft; MY_MARGINS m_mrgnRight; CToolTipCtrl m_ctrlToolTip; CEdit m_ctrlEdit; CArray <CCustomTabCtrlItem*,CCustomTabCtrlItem*> m_aItems; };
C++
// ShellTree.cpp : implementation file // #include "stdafx.h" #include "ShellTree.h" #include "SHFileInfo.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CShellTree // // This source is part of CShellTree - Selom Ofori // // Version: 1.02 (any previously unversioned copies are older/inferior // // This code is free for all to use. Mutatilate it as much as you want // See MFCENUM sample from microsoft // ========================================================================== // HISTORY: // ========================================================================== // 1.01 24 Feb 1999 - Overloaded PopulateTree(LPCTSTR lpPath) in the // class CShellTree to fill the tree based upon // path. Takehiko Mizoguti [mizoguti@m2.sys.to.casio.co.jp] // ========================================================================== ///////////////////////////////////////////////////////////////////////////// CShellTree::CShellTree() { } CShellTree::~CShellTree() { } BEGIN_MESSAGE_MAP(CShellTree, CTreeCtrl) //{{AFX_MSG_MAP(CShellTree) //}}AFX_MSG_MAP END_MESSAGE_MAP() /**************************************************************************** * * FUNCTION: PopulateTree() * * PURPOSE: Processes the File.Fill/RefreshTree command * ****************************************************************************/ void CShellTree::PopulateTree() { LPSHELLFOLDER lpsf=NULL; LPITEMIDLIST lpi=NULL; HRESULT hr; TV_SORTCB tvscb; // Get a pointer to the desktop folder. hr=SHGetDesktopFolder(&lpsf); if (SUCCEEDED(hr)) { // Initialize the tree view to be empty. DeleteAllItems(); // Fill in the tree view from the root. FillTreeView(lpsf, NULL, TVI_ROOT); //TunnelFillTree(lpsf, NULL, TVI_ROOT); // Release the folder pointer. lpsf->Release(); } tvscb.hParent = TVI_ROOT; tvscb.lParam = 0; tvscb.lpfnCompare = TreeViewCompareProc; // Sort the items in the tree view SortChildrenCB(&tvscb/*, FALSE*/); HTREEITEM hItem; hItem = GetRootItem(); Expand(hItem,TVE_EXPAND); Select(GetRootItem(),TVGN_CARET); } /**************************************************************************** * * FUNCTION: PopulateTree() * * PURPOSE: Processes the File.Fill/RefreshTree command * This overload has the ability to open from a * special folderlocation like SHBrowseForFolder() * * WARNING: TunnelTree() will not work if you use a special * folderlocation * ****************************************************************************/ void CShellTree::PopulateTree(int nFolder) { LPSHELLFOLDER lpsf=NULL,lpsf2=NULL; LPITEMIDLIST lpi=NULL; HRESULT hr; TV_SORTCB tvscb; // Get a pointer to the desktop folder. hr=SHGetDesktopFolder(&lpsf); if (SUCCEEDED(hr)) { // Initialize the tree view to be empty. DeleteAllItems(); if (!SUCCEEDED(SHGetSpecialFolderLocation( m_hWnd, nFolder, &lpi))) { lpi=NULL; FillTreeView(lpsf,NULL,TVI_ROOT); } else { hr=lpsf->BindToObject(lpi, 0, IID_IShellFolder,(LPVOID *)&lpsf2); if(SUCCEEDED(hr)) { // Fill in the tree view from the root. FillTreeView(lpsf2, lpi, TVI_ROOT); lpsf2->Release(); } else FillTreeView(lpsf,NULL,TVI_ROOT); } // Release the folder pointer. lpsf->Release(); } tvscb.hParent = TVI_ROOT; tvscb.lParam = 0; tvscb.lpfnCompare = TreeViewCompareProc; // Sort the items in the tree view SortChildrenCB(&tvscb/*, FALSE*/); HTREEITEM hItem; hItem = GetRootItem(); Expand(hItem,TVE_EXPAND); Select(GetRootItem(),TVGN_CARET); } /**************************************************************************** * * FUNCTION: FillTreeView( LPSHELLFOLDER lpsf, * LPITEMIDLIST lpifq, * HTREEITEM hParent) * * PURPOSE: Fills a branch of the TreeView control. Given the * shell folder, enumerate the subitems of this folder, * and add the appropriate items to the tree. * * PARAMETERS: * lpsf - Pointer to shell folder that we want to enumerate items * lpifq - Fully qualified item id list to the item that we are enumerating * items for. In other words, this is the PIDL to the item * identified by the lpsf parameter. * hParent - Parent node * * COMMENTS: * This function enumerates the items in the folder identifed by lpsf. * Note that since we are filling the left hand pane, we will only add * items that are folders and/or have sub-folders. We *could* put all * items in here if we wanted, but that's not the intent. * ****************************************************************************/ void CShellTree::FillTreeView(LPSHELLFOLDER lpsf, LPITEMIDLIST lpifq, HTREEITEM hParent) { TV_ITEM tvi; // TreeView Item. TV_INSERTSTRUCT tvins; // TreeView Insert Struct. HTREEITEM hPrev = NULL; // Previous Item Added. LPSHELLFOLDER lpsf2=NULL; LPENUMIDLIST lpe=NULL; LPITEMIDLIST lpi=NULL, lpiTemp=NULL, lpifqThisItem=NULL; LPTVITEMDATA lptvid=NULL; LPMALLOC lpMalloc=NULL; ULONG ulFetched; UINT uCount=0; HRESULT hr; char szBuff[256]; HWND hwnd=::GetParent(m_hWnd); // Allocate a shell memory object. hr=::SHGetMalloc(&lpMalloc); if (FAILED(hr)) return; if (SUCCEEDED(hr)) { // Get the IEnumIDList object for the given folder. hr=lpsf->EnumObjects(hwnd, SHCONTF_FOLDERS | SHCONTF_NONFOLDERS, &lpe); if (SUCCEEDED(hr)) { // Enumerate throught the list of folder and non-folder objects. while (S_OK==lpe->Next(1, &lpi, &ulFetched)) { //Create a fully qualified path to the current item //The SH* shell api's take a fully qualified path pidl, //(see GetIcon above where I call SHGetFileInfo) whereas the //interface methods take a relative path pidl. ULONG ulAttrs = SFGAO_HASSUBFOLDER | SFGAO_FOLDER; // Determine what type of object we have. lpsf->GetAttributesOf(1, (const struct _ITEMIDLIST **)&lpi, &ulAttrs); if (ulAttrs & (SFGAO_HASSUBFOLDER | SFGAO_FOLDER)) { //We need this next if statement so that we don't add things like //the MSN to our tree. MSN is not a folder, but according to the //shell it has subfolders. if (ulAttrs & SFGAO_FOLDER) { tvi.mask= TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM; if (ulAttrs & SFGAO_HASSUBFOLDER) { //This item has sub-folders, so let's put the + in the TreeView. //The first time the user clicks on the item, we'll populate the //sub-folders. tvi.cChildren=1; tvi.mask |= TVIF_CHILDREN; } //OK, let's get some memory for our ITEMDATA struct lptvid = (LPTVITEMDATA)lpMalloc->Alloc(sizeof(TVITEMDATA)); if (!lptvid) goto Done; // Error - could not allocate memory. //Now get the friendly name that we'll put in the treeview. if (!GetName(lpsf, lpi, SHGDN_NORMAL, szBuff)) goto Done; // Error - could not get friendly name. tvi.pszText = szBuff; tvi.cchTextMax = MAX_PATH; lpifqThisItem=ConcatPidls(lpifq, lpi); //Now, make a copy of the ITEMIDLIST lptvid->lpi=CopyITEMID(lpMalloc, lpi); GetNormalAndSelectedIcons(lpifqThisItem, &tvi); lptvid->lpsfParent=lpsf; //Store the parent folders SF lpsf->AddRef(); lptvid->lpifq=ConcatPidls(lpifq, lpi); tvi.lParam = (LPARAM)lptvid; // Populate the TreeVeiw Insert Struct // The item is the one filled above. // Insert it after the last item inserted at this level. // And indicate this is a root entry. tvins.item = tvi; tvins.hInsertAfter = hPrev; tvins.hParent = hParent; // Add the item to the tree hPrev = InsertItem(&tvins); } // Free this items task allocator. lpMalloc->Free(lpifqThisItem); lpifqThisItem=0; } lpMalloc->Free(lpi); //Free the pidl that the shell gave us. lpi=0; } } } else return; Done: if (lpe) lpe->Release(); //The following 2 if statements will only be TRUE if we got here on an //error condition from the "goto" statement. Otherwise, we free this memory //at the end of the while loop above. if (lpi && lpMalloc) lpMalloc->Free(lpi); if (lpifqThisItem && lpMalloc) lpMalloc->Free(lpifqThisItem); if (lpMalloc) lpMalloc->Release(); } /**************************************************************************** * * FUNCTION: GetNormalAndSelectedIcons(LPITEMIDLIST lpifq, LPTV_ITEM lptvitem) * * PURPOSE: Gets the index for the normal and selected icons for the current item. * * PARAMETERS: * lpifq - Fully qualified item id list for current item. * lptvitem - Pointer to treeview item we are about to add to the tree. * ****************************************************************************/ void CShellTree::GetNormalAndSelectedIcons(LPITEMIDLIST lpifq, LPTV_ITEM lptvitem) { //Note that we don't check the return value here because if GetIcon() //fails, then we're in big trouble... lptvitem->iImage = GetItemIcon(lpifq, SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON); lptvitem->iSelectedImage = GetItemIcon(lpifq, SHGFI_PIDL | SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_OPENICON); return; } /**************************************************************************** * * FUNCTION: TreeViewCompareProc(LPARAM, LPARAM, LPARAM) * * PURPOSE: Callback routine for sorting the tree * ****************************************************************************/ int CALLBACK CShellTree::TreeViewCompareProc(LPARAM lparam1, LPARAM lparam2, LPARAM lparamSort) { LPTVITEMDATA lptvid1=(LPTVITEMDATA)lparam1; LPTVITEMDATA lptvid2=(LPTVITEMDATA)lparam2; HRESULT hr; hr = lptvid1->lpsfParent->CompareIDs(0,lptvid1->lpi,lptvid2->lpi); if (FAILED(hr)) return 0; return (short)SCODE_CODE(GetScode(hr)); } ///////////////////////////////////////////////////////////////////////////// // CShellTree message handlers /**************************************************************************** * * FUNCTION: OnFolderExpanding(NMHDR* pNMHDR, LRESULT* pResult) * * PURPOSE: Reponds to an TVN_ITEMEXPANDING message in order to fill up * subdirectories. Pass the parameters from OnItemExpanding() to * this function. You need to do that or your folders won't * expand. * * OTHER: It can also be used to update a corresponding listview. Seem MFCENUM * * MESSAGEMAP: TVN_ITEMEXPANDING * ****************************************************************************/ void CShellTree::OnFolderExpanding(NMHDR* pNMHDR, LRESULT* pResult) { LPTVITEMDATA lptvid; //Long pointer to TreeView item data HRESULT hr; LPSHELLFOLDER lpsf2=NULL; static char szBuff[MAX_PATH]; TV_SORTCB tvscb; NM_TREEVIEW* pnmtv = (NM_TREEVIEW*)pNMHDR; // TODO: Add your control notification handler code here if ((pnmtv->itemNew.state & TVIS_EXPANDEDONCE)) return; lptvid=(LPTVITEMDATA)pnmtv->itemNew.lParam; if (lptvid) { hr=lptvid->lpsfParent->BindToObject(lptvid->lpi, 0, IID_IShellFolder,(LPVOID *)&lpsf2); if (SUCCEEDED(hr)) { FillTreeView(lpsf2, lptvid->lpifq, pnmtv->itemNew.hItem); } tvscb.hParent = pnmtv->itemNew.hItem; tvscb.lParam = 0; tvscb.lpfnCompare = TreeViewCompareProc; SortChildrenCB(&tvscb /*, FALSE*/); } *pResult = 0; } /**************************************************************************** * * FUNCTION: GetContextMenu(NMHDR* pNMHDR, LRESULT* pResult) * * PURPOSE: Diplays a popup menu for the folder selected. Pass the * parameters from Rclick() to this function. * * MESSAGEMAP: NM_RCLICK; * ****************************************************************************/ void CShellTree::GetContextMenu(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here POINT pt; LPTVITEMDATA lptvid; //Long pointer to TreeView item data LPSHELLFOLDER lpsf2=NULL; static char szBuff[MAX_PATH]; TV_HITTESTINFO tvhti; TV_ITEM tvi; // TODO: Add your control notification handler code here ::GetCursorPos((LPPOINT)&pt); ScreenToClient(&pt); tvhti.pt=pt; HitTest(&tvhti); SelectItem(tvhti.hItem); if (tvhti.flags & (TVHT_ONITEMLABEL|TVHT_ONITEMICON)) { ClientToScreen(&pt); tvi.mask=TVIF_PARAM; tvi.hItem=tvhti.hItem; if (!GetItem(&tvi)){ return; } lptvid=(LPTVITEMDATA)tvi.lParam; DoTheMenuThing(::GetParent(m_hWnd), lptvid->lpsfParent, lptvid->lpi, &pt); } *pResult = 0; } /**************************************************************************** * * FUNCTION: OnFolderSelected(NMHDR* pNMHDR, LRESULT* pResult, CString &szFolderPath) * * PURPOSE: Call this function if for example you want to put the path of the folder * selected inside a combobox or an edit window. You would pass the * parameters from OnSelChanged() to this function along with a CString object * that will hold the folder path. If the path is not * in the filesystem(eg MyComputer) it returns false. * * MESSAGEMAP: TVN_SELCHANGED * ****************************************************************************/ BOOL CShellTree::OnFolderSelected(NMHDR* pNMHDR, LRESULT* pResult, CString &szFolderPath) { // TODO: Add your control notification handler code here LPTVITEMDATA lptvid; //Long pointer to TreeView item data LPSHELLFOLDER lpsf2=NULL; static char szBuff[MAX_PATH]; HRESULT hr; BOOL bRet=false; TV_SORTCB tvscb; HTREEITEM hItem=NULL; if((hItem = GetSelectedItem())) { lptvid=(LPTVITEMDATA)GetItemData(hItem); if (lptvid && lptvid->lpsfParent && lptvid->lpi) { hr=lptvid->lpsfParent->BindToObject(lptvid->lpi, 0,IID_IShellFolder,(LPVOID *)&lpsf2); if (SUCCEEDED(hr)) { ULONG ulAttrs = SFGAO_FILESYSTEM; // Determine what type of object we have. lptvid->lpsfParent->GetAttributesOf(1, (const struct _ITEMIDLIST **)&lptvid->lpi, &ulAttrs); if (ulAttrs & (SFGAO_FILESYSTEM)) { if(SHGetPathFromIDList(lptvid->lpifq,szBuff)){ szFolderPath = szBuff; bRet = true; } } //non standard from here(NEW CODE) NM_TREEVIEW* pnmtv = (NM_TREEVIEW*)pNMHDR; if ((pnmtv->itemNew.cChildren == 1) && !(pnmtv->itemNew.state & TVIS_EXPANDEDONCE)){ FillTreeView(lpsf2,lptvid->lpifq,pnmtv->itemNew.hItem); tvscb.hParent = pnmtv->itemNew.hItem; tvscb.lParam = 0; tvscb.lpfnCompare = TreeViewCompareProc; SortChildrenCB(&tvscb); pnmtv->itemNew.state |= TVIS_EXPANDEDONCE; pnmtv->itemNew.stateMask |= TVIS_EXPANDEDONCE; pnmtv->itemNew.mask |= TVIF_STATE; SetItem(&pnmtv->itemNew); } } } if(lpsf2) lpsf2->Release(); } *pResult = 0; return bRet; } /**************************************************************************** * * FUNCTION: OnDeleteShellItem(NMHDR* pNMHDR, LRESULT* pResult) * * PURPOSE: Releases the memory allocated by the shell folders * * MESSAGEMAP: TVN_DELETEITEM * * MISC: failure to call this function will result in a memory leak * ****************************************************************************/ void CShellTree::OnDeleteShellItem(NMHDR* pNMHDR, LRESULT* pResult) { LPTVITEMDATA lptvid=NULL; HRESULT hr; LPMALLOC lpMalloc; NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; //Let's free the memory for the TreeView item data... hr=SHGetMalloc(&lpMalloc); if (FAILED(hr)) return; lptvid=(LPTVITEMDATA)pNMTreeView->itemOld.lParam; lptvid->lpsfParent->Release(); lpMalloc->Free(lptvid->lpi); lpMalloc->Free(lptvid->lpifq); lpMalloc->Free(lptvid); lpMalloc->Release(); } /**************************************************************************** * * FUNCTION: EnableImages() * * PURPOSE: Obtains a handle to the system image list and attaches it * to the tree control. DO NOT DELETE the imagelist * * MESSAGEMAP: NONE * ****************************************************************************/ void CShellTree::EnableImages() { // Get the handle to the system image list, for our icons HIMAGELIST hImageList; SHFILEINFO sfi; hImageList = (HIMAGELIST)SHGetFileInfo((LPCSTR)_T("C:\\"), 0, &sfi, sizeof(SHFILEINFO), SHGFI_SYSICONINDEX | SHGFI_SMALLICON); // Attach ImageList to TreeView if (hImageList) ::SendMessage(m_hWnd, TVM_SETIMAGELIST, (WPARAM) TVSIL_NORMAL, (LPARAM)hImageList); } /**************************************************************************** * * FUNCTION: GetSelectedFolderPath(CString &szFolderPath) * * PURPOSE: Retrieves the path of the currently selected string. * Pass a CString object that will hold the folder path. * If the path is not in the filesystem(eg MyComputer) * or none is selected it returns false. * * MESSAGEMAP: NONE * ****************************************************************************/ BOOL CShellTree::GetSelectedFolderPath(CString &szFolderPath) { LPTVITEMDATA lptvid; //Long pointer to TreeView item data LPSHELLFOLDER lpsf2=NULL; static char szBuff[MAX_PATH]; HTREEITEM hItem=NULL; HRESULT hr; BOOL bRet=false; if((hItem = GetSelectedItem())) { lptvid=(LPTVITEMDATA)GetItemData(hItem); if (lptvid && lptvid->lpsfParent && lptvid->lpi) { hr=lptvid->lpsfParent->BindToObject(lptvid->lpi, 0,IID_IShellFolder,(LPVOID *)&lpsf2); if (SUCCEEDED(hr)) { ULONG ulAttrs = SFGAO_FILESYSTEM; // Determine what type of object we have. lptvid->lpsfParent->GetAttributesOf(1, (const struct _ITEMIDLIST **)&lptvid->lpi, &ulAttrs); if (ulAttrs & (SFGAO_FILESYSTEM)) { if(SHGetPathFromIDList(lptvid->lpifq,szBuff)){ szFolderPath = szBuff; bRet = true; } } } } if(lpsf2) lpsf2->Release(); } return bRet; } /**************************************************************************** * * FUNCTION: GetParentShellFolder(HTREEITEM folderNode) * * PURPOSE: Retrieves the pointer to the ISHELLFOLDER interface * of the tree node passed as the paramter. * * MESSAGEMAP: NONE * ****************************************************************************/ LPSHELLFOLDER CShellTree::GetParentShellFolder(HTREEITEM folderNode) { LPTVITEMDATA lptvid; //Long pointer to TreeView item data lptvid=(LPTVITEMDATA)GetItemData(folderNode); if(lptvid) return lptvid->lpsfParent; else return NULL; } /**************************************************************************** * * FUNCTION: GetRelativeIDLIST(HTREEITEM folderNode) * * PURPOSE: Retrieves the Pointer to an ITEMIDLIST structure that * identifies the subfolder relative to its parent folder. * see GetParentShellFolder(); * * MESSAGEMAP: NONE * ****************************************************************************/ LPITEMIDLIST CShellTree::GetRelativeIDLIST(HTREEITEM folderNode) { LPTVITEMDATA lptvid; //Long pointer to TreeView item data lptvid=(LPTVITEMDATA)GetItemData(folderNode); if(lptvid) return lptvid->lpifq; else return NULL; } /**************************************************************************** * * FUNCTION: GetFullyQualifiedIDLIST(HTREEITEM folderNode) * * PURPOSE: Retrieves the Retrieves the Pointer to an ITEMIDLIST * structure that identifies the subfolder relative to the * desktop. This is a fully qualified Item Identifier * * MESSAGEMAP: NONE * ****************************************************************************/ LPITEMIDLIST CShellTree::GetFullyQualifiedID(HTREEITEM folderNode) { LPTVITEMDATA lptvid; //Long pointer to TreeView item data lptvid=(LPTVITEMDATA)GetItemData(folderNode); if(lptvid) return lptvid->lpifq; else return NULL; } /**************************************************************************** * * FUNCTION: SearchTree( HTREEITEM treeNode, * CString szSearchName ) * * PURPOSE: Too crude to explain, just use it * * WARNING: Only works if you use the default PopulateTree() * Not guaranteed to work on any future or existing * version of windows. Use with caution. Pretty much * ok if you're using on local drives * ****************************************************************************/ bool CShellTree::SearchTree(HTREEITEM treeNode, CString szSearchName, FindAttribs attr) { LPTVITEMDATA lptvid; //Long pointer to TreeView item data LPSHELLFOLDER lpsf2=NULL; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; bool bRet=false; HRESULT hr; CString szCompare; szSearchName.MakeUpper(); while(treeNode && bRet==false) { lptvid=(LPTVITEMDATA)GetItemData(treeNode); if (lptvid && lptvid->lpsfParent && lptvid->lpi) { hr=lptvid->lpsfParent->BindToObject(lptvid->lpi, 0,IID_IShellFolder,(LPVOID *)&lpsf2); if (SUCCEEDED(hr)) { ULONG ulAttrs = SFGAO_FILESYSTEM; lptvid->lpsfParent->GetAttributesOf(1, (const struct _ITEMIDLIST **)&lptvid->lpi, &ulAttrs); if (ulAttrs & (SFGAO_FILESYSTEM)) { if(SHGetPathFromIDList(lptvid->lpifq,szCompare.GetBuffer(MAX_PATH))) { switch(attr) { case type_drive: _splitpath(szCompare,drive,dir,fname,ext); szCompare=drive; break; case type_folder: szCompare = GetItemText(treeNode); break; } szCompare.MakeUpper(); if(szCompare == szSearchName) { EnsureVisible(treeNode); SelectItem(treeNode); bRet=true; } } } lpsf2->Release(); } } treeNode = GetNextSiblingItem(treeNode); } return bRet; } /**************************************************************************** * * FUNCTION: TunnelTree(CString szFindPath) * * PURPOSE: Too crude to explain, just use it * * WARNING: Only works if you use the default PopulateTree() * Not guaranteed to work on any future or existing * version of windows. Use with caution. Pretty much * ok if you're using on local drives * ****************************************************************************/ void CShellTree::TunnelTree(CString szFindPath) { HTREEITEM subNode = GetRootItem(); CString szPathHop; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; char delimiter[]=_T("\\"); CSHFileInfo checkPath(szFindPath); if(!checkPath.Exist()) { MessageBox(szFindPath,_T("Folder not found"),MB_ICONERROR); return; } if(szFindPath.ReverseFind(_T('\\')) != szFindPath.GetLength()-1) { szFindPath += _T("\\"); } _splitpath(szFindPath,drive,dir,fname,ext); //search the drive first szPathHop=drive; subNode=GetChildItem(subNode); if(subNode) { if(SearchTree(subNode,szPathHop, CShellTree::type_drive)) { //break down subfolders and search char *p=strtok(dir,delimiter); while(p) { subNode = GetSelectedItem(); subNode = GetChildItem(subNode); if(SearchTree(subNode,p,CShellTree::type_folder)) p=strtok(NULL,delimiter); else p=NULL; } } } } /**************************************************************************** * * FUNCTION: PopulateTree(LPCTSTR lpPath) * * PURPOSE: Populates tree based upon path. * * AUTHOR: Takehiko Mizoguti [mizoguti@m2.sys.to.casio.co.jp] * ****************************************************************************/ void CShellTree::PopulateTree(LPCTSTR lpPath) { LPSHELLFOLDER lpsf=NULL,lpsf2=NULL; LPITEMIDLIST lpi=NULL; HRESULT hr; TV_SORTCB tvscb; LPTSTR lpFolder = (LPTSTR)lpPath; LPTSTR lpNextFolder; TCHAR strPath[_MAX_PATH]; LPMALLOC pMalloc; if (::SHGetMalloc(&pMalloc) == NOERROR) { // Get a pointer to the desktop folder. hr=SHGetDesktopFolder(&lpsf); if (SUCCEEDED(hr)) { USES_CONVERSION; // Initialize the tree view to be empty. DeleteAllItems(); do{ // Get the Next Component lpNextFolder = PathFindNextComponent( lpFolder ); if( lpNextFolder && *lpNextFolder ){ memcpy( strPath, lpFolder, ( lpNextFolder - lpFolder ) ); strPath[lpNextFolder - lpFolder] = _T('\0'); } else{ _tcscpy( strPath, lpFolder ); lpNextFolder = NULL; } // Get ShellFolder Pidl ULONG eaten; hr = lpsf->ParseDisplayName( NULL, NULL, T2OLE(strPath), &eaten, &lpi, NULL ); if( FAILED( hr ) ){ break; } hr=lpsf->BindToObject(lpi, 0, IID_IShellFolder,(LPVOID *)&lpsf2); if( FAILED( hr ) ){ break; } pMalloc->Free( lpi ); // Release the Parent Folder pointer. lpsf->Release(); // Chenge Folder Info lpsf = lpsf2; lpFolder = lpNextFolder; } while( lpNextFolder ); FillTreeView(lpsf,NULL,TVI_ROOT); } } tvscb.hParent = TVI_ROOT; tvscb.lParam = 0; tvscb.lpfnCompare = TreeViewCompareProc; // Sort the items in the tree view SortChildrenCB(&tvscb/*, FALSE*/); HTREEITEM hItem; hItem = GetRootItem(); Expand(hItem,TVE_EXPAND); Select(GetRootItem(),TVGN_CARET); }
C++
// CJSizeDockBar.cpp : implementation file // // Copyright ?1998-99 Kirk Stowell // mailto:kstowell@codejockeys.com // http://www.codejockeys.com/kstowell/ // // This source code may be used in compiled form in any way you desire. // Source file(s) may be redistributed unmodified by any means PROVIDING // they are not sold for profit without the authors expressed written consent, // and providing that this notice and the authors name and all copyright // notices remain intact. If the source code is used in any commercial // applications then a statement along the lines of: // // "Portions Copyright ?1998-99 Kirk Stowell" must be included in the // startup banner, "About" box or printed documentation. An email letting // me know that you are using it would be nice as well. That's not much to ask // considering the amount of work that went into this. // // This software is provided "as is" without express or implied warranty. Use // it at your own risk! The author accepts no liability for any damage/loss of // business that this product may cause. // // ========================================================================== // // Acknowledgements: // <> Many thanks to all of you, who have encouraged me to update my articles // and code, and who sent in bug reports and fixes. // <> Many thanks Zafir Anjum (zafir@codeguru.com) for the tremendous job that // he has done with codeguru, enough can not be said! // <> Many thanks to Microsoft for making the source code availiable for MFC. // Since most of this work is a modification from existing classes and // methods, this library would not have been possible. // // ========================================================================== // HISTORY: // ========================================================================== // 1.00 12 Jan 1999 - Initial release to add side-by-side // docking support for CCJControlBar class. // 1.01 29 Jan 1999 - Made some cosmetic enhancements to more // closely match DevStudio docking windows. // ========================================================================== // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CJSizeDockBar.h" #include "CJControlBar.h" #include "CJToolBar.h" #include "resource.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCJSizeDockBar CCJSizeDockBar::CCJSizeDockBar() { m_iTrackBorderSize = 4; m_cxLeftBorder = 0; m_cyTopBorder = 0; m_cxRightBorder = 0; m_cyBottomBorder = 0; m_iActualSize = 100; m_iSafeSpace = 25; m_bOkToDrag = FALSE; m_bDragging = FALSE; m_bAutoDelete = TRUE; m_clrBtnHilite = ::GetSysColor(COLOR_BTNHILIGHT); m_clrBtnShadow = ::GetSysColor(COLOR_BTNSHADOW); m_clrBtnFace = ::GetSysColor(COLOR_BTNFACE); } CCJSizeDockBar::~CCJSizeDockBar() { // TODO: add destruction code here. } IMPLEMENT_DYNAMIC(CCJSizeDockBar, CDockBar) BEGIN_MESSAGE_MAP(CCJSizeDockBar, CDockBar) //{{AFX_MSG_MAP(CCJSizeDockBar) ON_WM_NCPAINT() ON_WM_NCCALCSIZE() ON_WM_SETCURSOR() ON_WM_NCHITTEST() ON_WM_NCLBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_SYSCOLORCHANGE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCJSizeDockBar overrides CSize CCJSizeDockBar::CalcDynamicLayout(int nLength, DWORD nMode) { int ActualSize = 0; for(int i=0;i<= m_arrBars.GetUpperBound();++i) { CCJControlBar *pBar = (CCJControlBar *)GetDockedControlBar(i); if (pBar != NULL && pBar->IsVisible()) { ActualSize = m_iActualSize; break; } } int cx,cy; if (nMode & LM_VERTDOCK) { cx = ActualSize ; cy = 32767; } if (nMode & LM_HORZDOCK) { cx= 32767; cy = ActualSize; } CalcSizeBarLayout(); return CSize(cx,cy); } void CCJSizeDockBar::DoPaint(CDC *pDC) { CDockBar::DoPaint(pDC); } BOOL CCJSizeDockBar::IsDockBar() const { return FALSE; } BOOL CCJSizeDockBar::IsDockSizeBar() const { return TRUE; } void CCJSizeDockBar::OnInvertTracker(const CRect& rect) { ASSERT_VALID(this); ASSERT(!rect.IsRectEmpty()); CDC* pDC = GetDockingFrame()->GetDC(); CBrush* pBrush = CDC::GetHalftoneBrush(); HBRUSH hOldBrush = NULL; if (pBrush != NULL) hOldBrush = (HBRUSH)SelectObject(pDC->m_hDC, pBrush->m_hObject); pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT); if (hOldBrush != NULL) SelectObject(pDC->m_hDC, hOldBrush); GetDockingFrame()->ReleaseDC(pDC); } void CCJSizeDockBar::HitTest(const CPoint & point) { UINT nID = ((UINT)(WORD)::GetDlgCtrlID(m_hWnd)); CRect rcWin; GetWindowRect(&rcWin); HCURSOR hCur; static BOOL bHitting,bUnItting; bHitting = FALSE; bUnItting = TRUE; BOOL bHit = FALSE; if (nID == AFX_IDW_SIZEBAR_LEFT) { rcWin.left = rcWin.right-m_iTrackBorderSize; hCur = AfxGetApp()->LoadCursor(AFX_IDC_HSPLITBAR); bHit = rcWin.PtInRect(point); } else if (nID == AFX_IDW_SIZEBAR_TOP) { rcWin.top = rcWin.bottom-m_iTrackBorderSize; hCur = AfxGetApp()->LoadCursor(AFX_IDC_VSPLITBAR); bHit = rcWin.PtInRect(point); } else if (nID == AFX_IDW_SIZEBAR_RIGHT) { rcWin.right = rcWin.left+m_iTrackBorderSize; hCur = AfxGetApp()->LoadCursor(AFX_IDC_HSPLITBAR); bHit = rcWin.PtInRect(point); } else if (nID == AFX_IDW_SIZEBAR_BOTTOM) { rcWin.bottom = rcWin.top+m_iTrackBorderSize; hCur = AfxGetApp()->LoadCursor(AFX_IDC_VSPLITBAR); bHit = rcWin.PtInRect(point); } if (bHit) { SetCursor(hCur); } else { hCur = ::LoadCursor(NULL,IDC_ARROW); SetCursor(hCur); } m_bOkToDrag = bHit; } ///////////////////////////////////////////////////////////////////////////// // CCJSizeDockBar message handlers void CCJSizeDockBar::OnNcPaint() { EraseNonClient(); } void CCJSizeDockBar::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp) { UINT nID = ((UINT)(WORD)::GetDlgCtrlID(m_hWnd)); if (nID == AFX_IDW_SIZEBAR_LEFT) { m_cyBottomBorder += m_iTrackBorderSize; CDockBar::OnNcCalcSize(bCalcValidRects, lpncsp); m_cyBottomBorder -= m_iTrackBorderSize; } else if (nID == AFX_IDW_SIZEBAR_TOP) { m_cyBottomBorder += m_iTrackBorderSize; CDockBar::OnNcCalcSize(bCalcValidRects, lpncsp); m_cyBottomBorder -= m_iTrackBorderSize; } else if (nID == AFX_IDW_SIZEBAR_RIGHT) { m_cyTopBorder += m_iTrackBorderSize; CDockBar::OnNcCalcSize(bCalcValidRects, lpncsp); m_cyTopBorder -= m_iTrackBorderSize; } else if (nID == AFX_IDW_SIZEBAR_BOTTOM) { m_cyTopBorder += m_iTrackBorderSize; CDockBar::OnNcCalcSize(bCalcValidRects, lpncsp); m_cyTopBorder -= m_iTrackBorderSize; } } BOOL CCJSizeDockBar::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { return (nHitTest == HTCLIENT)? CDockBar::OnSetCursor(pWnd, nHitTest, message):FALSE; } LRESULT CCJSizeDockBar::OnNcHitTest(CPoint point) { HitTest(point); return (m_bOkToDrag)?HTBORDER:CDockBar::OnNcHitTest(point); } void CCJSizeDockBar::OnNcLButtonDown(UINT nHitTest, CPoint point) { if( m_bOkToDrag ) { UINT nID = ((UINT)(WORD)::GetDlgCtrlID(m_hWnd)); CFrameWnd *pFrame=GetDockingFrame(); GetWindowRect(m_rcTrack); if (nID == AFX_IDW_SIZEBAR_LEFT) m_rcTrack.left = m_rcTrack.right-m_iTrackBorderSize; else if (nID == AFX_IDW_SIZEBAR_TOP) m_rcTrack.top = m_rcTrack.bottom-m_iTrackBorderSize; else if (nID == AFX_IDW_SIZEBAR_RIGHT) m_rcTrack.right = m_rcTrack.left+m_iTrackBorderSize; else if (nID == AFX_IDW_SIZEBAR_BOTTOM) m_rcTrack.bottom = m_rcTrack.top+m_iTrackBorderSize; pFrame->ScreenToClient(&m_rcTrack); pFrame->ScreenToClient(&point); m_ptStartDrag = point; m_ptCurDrag = point; SetCapture(); m_bDragging = TRUE; OnInvertTracker(m_rcTrack); } CDockBar::OnNcLButtonDown(nHitTest, point); } void CCJSizeDockBar::OnLButtonUp(UINT nFlags, CPoint point) { if( m_bDragging ) { CRect rectWin; CRect rectAvail; GetWindowRect(&rectWin); ReleaseCapture(); m_bDragging = FALSE; OnInvertTracker(m_rcTrack); GetAvailableRect(rectAvail); UINT nID = ((UINT)(WORD)::GetDlgCtrlID(m_hWnd)); if (nID == AFX_IDW_SIZEBAR_LEFT ) { int maxWidth = rectAvail.Width()-m_iSafeSpace; int newWidth = m_rcTrack.left-m_ptStartDrag.x; m_iActualSize = newWidth>maxWidth ? maxWidth: newWidth; m_iActualSize += rectWin.Width(); } else if (nID == AFX_IDW_SIZEBAR_TOP) { int maxHeight = rectAvail.Height()-m_iSafeSpace; int newHeight = m_rcTrack.top-m_ptStartDrag.y; m_iActualSize = newHeight>maxHeight ? maxHeight : newHeight; m_iActualSize += rectWin.Height(); } else if (nID == AFX_IDW_SIZEBAR_RIGHT) { int maxWidth = rectAvail.Width()-m_iSafeSpace; int newWidth = m_ptStartDrag.x-m_rcTrack.left; m_iActualSize = newWidth>maxWidth ? maxWidth: newWidth; m_iActualSize += rectWin.Width(); } else if (nID == AFX_IDW_SIZEBAR_BOTTOM) { int maxHeight = rectAvail.Height()-m_iSafeSpace; int newHeight = m_ptStartDrag.y-m_rcTrack.top; m_iActualSize = newHeight>maxHeight ? maxHeight : newHeight; m_iActualSize += rectWin.Height(); } if(m_iActualSize<m_iTrackBorderSize ) m_iActualSize = m_iTrackBorderSize; GetDockingFrame()->RecalcLayout(); RecalcAllExcept(NULL); } CDockBar::OnLButtonUp(nFlags, point); } void CCJSizeDockBar::OnMouseMove(UINT nFlags, CPoint point) { if( m_bDragging ) { CRect rectWin; GetWindowRect(&rectWin); CRect rectAvail; GetAvailableRect(rectAvail); CFrameWnd *pFrame=GetDockingFrame(); ClientToScreen(&point); pFrame->ScreenToClient(&point); UINT nID = ((UINT)(WORD)::GetDlgCtrlID(m_hWnd)); if (nID == AFX_IDW_SIZEBAR_LEFT) { point.x = point.x>rectAvail.right ? rectAvail.right:point.x; point.x = point.x<m_iTrackBorderSize ? m_iTrackBorderSize:point.x; } else if (nID == AFX_IDW_SIZEBAR_TOP) { point.y = point.y>rectAvail.bottom ? rectAvail.bottom:point.y; point.y = point.y<m_iTrackBorderSize ? m_iTrackBorderSize:point.y; } else if (nID == AFX_IDW_SIZEBAR_RIGHT) { point.x = point.x<rectAvail.left ? rectAvail.left:point.x; point.x = point.x>rectAvail.right+m_iActualSize-m_iTrackBorderSize ? rectAvail.right-m_iTrackBorderSize+m_iActualSize:point.x; } else if (nID == AFX_IDW_SIZEBAR_BOTTOM) { point.y = point.y<rectAvail.top ? rectAvail.top:point.y; point.y = point.y>rectAvail.bottom+m_iActualSize-m_iTrackBorderSize ? rectAvail.bottom-m_iTrackBorderSize+m_iActualSize:point.y; } int deltaX = point.x-m_ptCurDrag.x; int deltaY = point.y-m_ptCurDrag.y; m_ptCurDrag = point; if (nID == AFX_IDW_SIZEBAR_LEFT || nID == AFX_IDW_SIZEBAR_RIGHT && deltaX) { OnInvertTracker(m_rcTrack); m_rcTrack.left+=deltaX; m_rcTrack.right+=deltaX; OnInvertTracker(m_rcTrack); } else if( nID == AFX_IDW_SIZEBAR_TOP || nID == AFX_IDW_SIZEBAR_BOTTOM && deltaY) { OnInvertTracker(m_rcTrack); m_rcTrack.top+=deltaY; m_rcTrack.bottom+=deltaY; OnInvertTracker(m_rcTrack); } } CDockBar::OnMouseMove(nFlags, point); } void CCJSizeDockBar::OnSysColorChange() { CDockBar::OnSysColorChange(); m_clrBtnHilite = ::GetSysColor(COLOR_BTNHILIGHT); m_clrBtnShadow = ::GetSysColor(COLOR_BTNSHADOW); m_clrBtnFace = ::GetSysColor(COLOR_BTNFACE); } ///////////////////////////////////////////////////////////////////////////// // CCJControlBar operations void CCJSizeDockBar::GetAvailableRect(CRect &rect) { GetDockingFrame()->GetClientRect(&rect); GetDockingFrame()->RepositionBars(0xffff, 0xffff, AFX_IDW_PANE_FIRST,reposQuery, &rect, &rect, TRUE); } BOOL CCJSizeDockBar::IsLastControlBar(int index) { for( int i=index; i<m_arrBars.GetSize(); ++i) { CCJControlBar *pOther = (CCJControlBar *)GetDockedControlBar(i); if (pOther != NULL && pOther->IsVisible()) { return FALSE; } } return TRUE; } CCJControlBar* CCJSizeDockBar::GetDockedSizeBar(int nPos) { return (CCJControlBar*)GetDockedControlBar(nPos); } void CCJSizeDockBar::RecalcAllExcept(CCJSizeDockBar *pBar) { CFrameWnd *pFrame = (CFrameWnd*)AfxGetApp()->m_pMainWnd; ASSERT_VALID(pFrame); for (int i = 0; i < 4; i++) { CCJSizeDockBar* pDock = (CCJSizeDockBar*)pFrame->GetControlBar(dwSizeBarMap[i][0]); if (pDock != NULL && pDock != pBar) { pDock->CalcSizeBarLayout(); } } } void CCJSizeDockBar::DrawBorders(CDC *pDC, CRect &rect) { int cxBorderLeft = 0; int cxBorderRight = 0; int cyBorderTop = 0; int cyBorderBottom = 0; CRect rc; rc.CopyRect(&rect); if (m_dwStyle & CBRS_BORDER_TOP) { pDC->FillSolidRect(rc.left,rc.top,rc.Width(),1,m_clrBtnShadow); pDC->FillSolidRect(rc.left,rc.top+1,rc.Width(),1,m_clrBtnHilite); cyBorderTop+=2; } if (m_dwStyle & CBRS_BORDER_BOTTOM) { pDC->FillSolidRect(rc.left,rc.bottom-1,rc.Width(),1,m_clrBtnHilite); pDC->FillSolidRect(rc.left,rc.bottom-2,rc.Width(),1,m_clrBtnShadow); cyBorderBottom+=2; } if (m_dwStyle & CBRS_BORDER_LEFT) { pDC->FillSolidRect(rc.left,rc.top,1,rc.Height(),m_clrBtnShadow); pDC->FillSolidRect(rc.left+1,rc.top,1,rc.Height(),m_clrBtnHilite); cxBorderLeft+=2; } if (m_dwStyle & CBRS_BORDER_RIGHT) { pDC->FillSolidRect(rc.right-2,rc.top,1,rc.Height(),m_clrBtnShadow); pDC->FillSolidRect(rc.right-1,rc.top,1,rc.Height(),m_clrBtnHilite); cxBorderRight+=2; } UINT nID = ((UINT)(WORD)::GetDlgCtrlID(m_hWnd)); CRect rcTrack; rcTrack.CopyRect(&rc); if (nID == AFX_IDW_SIZEBAR_LEFT) { rcTrack.left = rc.right-m_iTrackBorderSize; rcTrack.right += 1; rcTrack.top += 1; rcTrack.bottom -= 1; pDC->FillSolidRect(rcTrack,m_clrBtnFace); pDC->Draw3dRect(rcTrack,m_clrBtnHilite,m_clrBtnShadow); cxBorderRight = m_iTrackBorderSize; } else if (nID == AFX_IDW_SIZEBAR_TOP) { rcTrack.top = rc.bottom-m_iTrackBorderSize; rcTrack.bottom+=1; pDC->FillSolidRect(rcTrack,m_clrBtnFace); pDC->Draw3dRect(rcTrack,m_clrBtnHilite,m_clrBtnShadow); cyBorderBottom = m_iTrackBorderSize; } else if (nID == AFX_IDW_SIZEBAR_RIGHT) { rcTrack.right = rc.left+m_iTrackBorderSize; rcTrack.left -= 1; rcTrack.top += 1; rcTrack.bottom -= 1; pDC->FillSolidRect(rcTrack,m_clrBtnFace); pDC->Draw3dRect(rcTrack,m_clrBtnHilite,m_clrBtnShadow); cxBorderLeft = m_iTrackBorderSize; } else if (nID == AFX_IDW_SIZEBAR_BOTTOM) { rcTrack.bottom = rc.top+m_iTrackBorderSize; rcTrack.top-=1; pDC->FillSolidRect(rcTrack,m_clrBtnFace); pDC->Draw3dRect(rcTrack,m_clrBtnHilite,m_clrBtnShadow); cyBorderTop = m_iTrackBorderSize; } rect.left += cxBorderLeft; rect.right -= cxBorderRight; rect.top += cyBorderTop; rect.bottom -= cyBorderBottom; } void CCJSizeDockBar::EraseNonClient() { CWindowDC dc(this); CRect rectClient; GetClientRect(rectClient); CRect rectWindow; GetWindowRect(rectWindow); ScreenToClient(rectWindow); rectClient.OffsetRect(-rectWindow.left, -rectWindow.top); dc.ExcludeClipRect(rectClient); rectWindow.OffsetRect(-rectWindow.left, -rectWindow.top); DrawBorders(&dc, rectWindow); dc.IntersectClipRect(rectWindow); SendMessage(WM_ERASEBKGND, (WPARAM)dc.m_hDC); } void CCJSizeDockBar::SetActualSize(int iSize) { m_iActualSize=iSize; } void CCJSizeDockBar::CalcSizeBarLayout() { HDWP hDWP = ::BeginDeferWindowPos(m_arrBars.GetSize()); CRect rectAvail; GetClientRect(&rectAvail); int nCount = 0; int lastLeft = 0; int lastRight = 0; int lastBottom = 0; int lastTop = 0; for( int i=0; i<m_arrBars.GetSize(); ++i) { CCJControlBar *pBar = (CCJControlBar *)GetDockedControlBar(i); if (pBar != NULL && pBar->IsVisible()) { CRect rectBar; ++nCount; pBar->GetWindowRect(&rectBar); pBar->m_bUnique = FALSE; ScreenToClient(&rectBar); CSize sizeIdeal = pBar->CalcDynamicLayout(-1,0); if( pBar->IsLeftDocked() ) { rectBar.top = lastLeft; rectBar.left = 0; rectBar.right = rectAvail.Width(); rectBar.bottom = rectBar.top + sizeIdeal.cy; if (rectBar.top>lastLeft) rectBar.top = lastLeft; lastLeft = rectBar.bottom; if (IsLastControlBar(i+1)) { rectBar.bottom = rectAvail.bottom; pBar->m_bToFit = TRUE; if( nCount == 1 ) pBar->m_bUnique = TRUE; } else pBar->m_bToFit = FALSE; } else if (pBar->IsTopDocked()) { rectBar.left = lastTop; rectBar.top = 0; rectBar.bottom = rectAvail.Height(); rectBar.right = rectBar.left + sizeIdeal.cx; if( rectBar.left>lastTop ) rectBar.left = lastTop; lastTop = rectBar.right; if (IsLastControlBar(i+1)) { rectBar.right = rectAvail.right; pBar->m_bToFit = TRUE; if (nCount == 1) pBar->m_bUnique = TRUE; } else pBar->m_bToFit = FALSE; } else if (pBar->IsRightDocked()) { rectBar.top = lastRight; rectBar.left = 0; rectBar.right = rectAvail.Width(); rectBar.bottom = rectBar.top + sizeIdeal.cy; if (rectBar.top>lastRight) rectBar.top = lastRight; lastRight = rectBar.bottom; if (IsLastControlBar(i+1)) { rectBar.bottom = rectAvail.bottom; pBar->m_bToFit = TRUE; if (nCount == 1) pBar->m_bUnique = TRUE; } else pBar->m_bToFit = FALSE; } else if (pBar->IsBottomDocked()) { rectBar.left = lastBottom; rectBar.top = 0; rectBar.bottom = rectAvail.Height(); rectBar.right = rectBar.left + sizeIdeal.cx; if( rectBar.left>lastBottom ) rectBar.left = lastBottom; lastBottom = rectBar.right; if (IsLastControlBar(i+1)) { rectBar.right = rectAvail.right; pBar->m_bToFit = TRUE; if( nCount == 1 ) pBar->m_bUnique = TRUE; } else pBar->m_bToFit = FALSE; } pBar->SetWindowPos(NULL,rectBar.left,rectBar.top,rectBar.Width(),rectBar.Height(),SWP_NOZORDER); // pBar->Invalidate(); } } ::EndDeferWindowPos(hDWP); } void CCJSizeDockBar::Maximize(CCJControlBar* pBar) { int iExt=0; CRect rectAvail; GetClientRect(rectAvail); for (int i=0; i<m_arrBars.GetSize(); ++i) { CCJControlBar *pBarDock = (CCJControlBar *)GetDockedControlBar(i); if (pBarDock && pBarDock->IsVisible() && pBarDock != pBar) { pBarDock->Minimize(); iExt += pBarDock->GetMinExt(); } } if (pBar->IsLeftDocked() || pBar->IsRightDocked()) { iExt = rectAvail.Height()-iExt; } if (pBar->IsTopDocked() || pBar->IsBottomDocked()) { iExt = rectAvail.Width()-iExt; } pBar->Maximize(iExt); CalcSizeBarLayout(); } void CCJSizeDockBar::Normalize(CCJControlBar *) { for( int i=0; i<m_arrBars.GetSize(); ++i) { CCJControlBar *pBarDock = (CCJControlBar*)GetDockedControlBar(i); if (pBarDock && pBarDock->IsVisible()) pBarDock->Normalize(); } CalcSizeBarLayout(); }
C++
// CJControlBar.cpp : implementation file // // DevStudio Style Resizable Docking Control Bar. // // Copyright ?1998-99 Kirk Stowell // mailto:kstowell@codejockeys.com // http://www.codejockeys.com/kstowell/ // // This source code may be used in compiled form in any way you desire. // Source file(s) may be redistributed unmodified by any means PROVIDING // they are not sold for profit without the authors expressed written consent, // and providing that this notice and the authors name and all copyright // notices remain intact. If the source code is used in any commercial // applications then a statement along the lines of: // // "Portions Copyright ?1998-99 Kirk Stowell" must be included in the // startup banner, "About" box or printed documentation. An email letting // me know that you are using it would be nice as well. That's not much to ask // considering the amount of work that went into this. // // This software is provided "as is" without express or implied warranty. Use // it at your own risk! The author accepts no liability for any damage/loss of // business that this product may cause. // // ========================================================================== // // Acknowledgements: // <> Many thanks to all of you, who have encouraged me to update my articles // and code, and who sent in bug reports and fixes. // <> Many thanks Zafir Anjum (zafir@codeguru.com) for the tremendous job that // he has done with codeguru, enough can not be said! // <> Many thanks to Microsoft for making the source code availiable for MFC. // Since most of this work is a modification from existing classes and // methods, this library would not have been possible. // // ========================================================================== // HISTORY: // ========================================================================== // 1.00 17 Oct 1998 - Initial re-write and release. // 1.01 20 Oct 1998 - Fixed problem with gripper and buttons // disappearing when docking toggled. Overloaded // IsFloating() method from base class. // 1.02 22 Nov 1998 - Modified set cursor to display normal size // cursor when static linked. // 2.00 12 Jan 1999 - Total class re-write, added multiple/side-by-side // controlbar docking. No longer uses CSizingControlBar // base class. // 2.01 31 Jan 1999 - Removed extra line (typo) from OnLButtonUp(). // Thanks to Ioannis Stamatopoulos (ystamat@mail.datamedia.gr) // for pointing this out. // 2.02 28 Feb 1999 - Calls default wnd proc if no context menu is defined // Gonzalo Pereyra [persys@adinet.com.uy] // 2.03 10 Mar 1999 - Added AfxRegisterWndClass() to create method to // handle double clicks. Thanks to Takehiko Mizoguti [mizoguti@m2.sys.to.casio.co.jp] // for some thoughts on this. // - Fixed memory leak with button tooltips. // 2.04 13 Mar 1999 - Patrick Bergeron [patb@softimage.com] fixed the // following bugs: // // - When nesting a CDialog based window inside a // CJControlBar, the 3D rect drawn by ::OnEraseBkgnd would // be overwritten by the top and left dialog borders. The // problem was caused by the fact that in the // ::OnWindowPosChanged() method, the rectangle which is // used to move the window contains the border. // // A simple call to rc.DeflateRect(1,1) solved this problem. // // - Added a call to UpdateWindow() in ::OnEraseBkgnd(). // This helps with the flickering a bit, but I Am not sure // this is the correct way to go. Incorporate at your own risks. // // - Added 2 ASSERT()s in ::OnMouseMove(). This was not to // fix a bug, but at one point I was seeing strange things // that lead me to add these asserts. They don't do // anything bad, so why remove them? // // ========================================================================== // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CJControlBar.h" #include "CJDockContext.h" #include "CJSizeDockBar.h" #include "resource.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define GRIP_LEFTSPACING 3 #define GRIP_STARTGRIP 8 #define GRIP_SIZE 3 #define GRIP_BUTTONSPACING 3 #define GRIP_INTRASPACING 1 #define _HIDECROSS 0 #define _MAXORZDISABLE 1 #define _MAXORZENABLE 2 #define _MAXVERTDISABLE 3 #define _MAXVERTENABLE 4 #define _NORMORZDISABLE 5 #define _NORMORZENABLE 6 #define _NORMVERTDISABLE 7 #define _NORMVERTENABLE 8 ///////////////////////////////////////////////////////////////////////////// // CCJControlBar CCJControlBar::CCJControlBar() { m_iTrackBorderSize = 4; m_iAuxImage = -1; m_menuID = -1; m_bToFit = FALSE; m_bOkToDrag = FALSE; m_bDragging = FALSE; m_bMaximized = FALSE; m_bUnique = FALSE; m_bGripper = TRUE; m_bButtons = TRUE; m_sizeDesired = CSize(200,100); m_sizeNormal = CSize(200,100); m_cxOffset = 5; m_cyOffset = 3; // Create the image list used by frame buttons. m_ImageList.Create(IDB_BUTTON_IMAGES, 10, 1, RGB(255,255,255)); m_pChildWnd = NULL; m_clrBtnHilite = ::GetSysColor(COLOR_BTNHILIGHT); m_clrBtnShadow = ::GetSysColor(COLOR_BTNSHADOW); m_clrBtnFace = ::GetSysColor(COLOR_BTNFACE); } CCJControlBar::~CCJControlBar() { m_ImageList.DeleteImageList(); } IMPLEMENT_DYNAMIC(CCJControlBar, CControlBar) BEGIN_MESSAGE_MAP(CCJControlBar, CControlBar) //{{AFX_MSG_MAP(CCJControlBar) ON_WM_NCPAINT() ON_WM_PAINT() ON_WM_MOUSEMOVE() ON_WM_SETCURSOR() ON_WM_LBUTTONUP() ON_WM_NCHITTEST() ON_WM_ERASEBKGND() ON_WM_SYSCOLORCHANGE() ON_WM_CREATE() ON_WM_WINDOWPOSCHANGED() ON_WM_CONTEXTMENU() ON_WM_LBUTTONDOWN() ON_COMMAND(IDC_BUTTON_HIDE, OnButtonClose) ON_UPDATE_COMMAND_UI(IDC_BUTTON_HIDE, OnUpdateButtonClose) ON_COMMAND(IDC_BUTTON_MINI, OnButtonMinimize) ON_UPDATE_COMMAND_UI(IDC_BUTTON_MINI, OnUpdateButtonMinimize) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCJControlBar overrides BOOL CCJControlBar::Create(CWnd *pParentWnd, UINT nID, LPCTSTR lpszWindowName, CSize sizeDefault, DWORD dwStyle) { ASSERT_VALID(pParentWnd); // must have a parent // Set initial control bar style. SetBarStyle(dwStyle & CBRS_ALL|CBRS_HIDE_INPLACE|CBRS_SIZE_DYNAMIC|CBRS_FLOAT_MULTI); dwStyle &= ~CBRS_ALL; dwStyle |= WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN; m_sizeDesired = m_sizeNormal = sizeDefault; CString wndClass = ::AfxRegisterWndClass( CS_DBLCLKS, 0, ::GetSysColorBrush(COLOR_BTNFACE)); return CWnd::Create(wndClass, lpszWindowName, dwStyle, CRect(0,0,0,0), pParentWnd, nID); } BOOL CCJControlBar::PreTranslateMessage(MSG* pMsg) { if (m_bButtons) m_ToolTip.RelayEvent(pMsg); return CControlBar::PreTranslateMessage(pMsg); } void CCJControlBar::OnUpdateCmdUI(CFrameWnd* pTarget, BOOL bDisableIfNoHndler) { if (m_bButtons) { UINT NewImage; BOOL bEnable = FALSE; if (IsHorzDocked()) { if (m_bUnique) { m_ToolTip.UpdateTipText (IDS_EXPAND, &m_btnMinim); NewImage = _MAXORZDISABLE; bEnable = FALSE; } else if (!m_bMaximized) { m_ToolTip.UpdateTipText (IDS_EXPAND, &m_btnMinim); NewImage = _MAXORZENABLE; bEnable = TRUE; } else { m_ToolTip.UpdateTipText (IDS_CONTRACT, &m_btnMinim); NewImage = _NORMORZENABLE; bEnable = TRUE; } } else if(IsVertDocked()) { if (m_bUnique) { m_ToolTip.UpdateTipText (IDS_EXPAND, &m_btnMinim); NewImage = _MAXVERTDISABLE; bEnable = FALSE; } else if (!m_bMaximized) { m_ToolTip.UpdateTipText (IDS_EXPAND, &m_btnMinim); NewImage = _MAXVERTENABLE; bEnable = TRUE; } else { m_ToolTip.UpdateTipText (IDS_CONTRACT, &m_btnMinim); NewImage = _NORMVERTENABLE; bEnable = TRUE; } } if (NewImage != m_iAuxImage) { m_iAuxImage = NewImage; m_btnMinim.SetIcon(m_ImageList.ExtractIcon(m_iAuxImage), CSize(10,10)); m_btnMinim.EnableWindow(bEnable); } } } CSize CCJControlBar::CalcDynamicLayout(int nLength, DWORD nMode) { CSize sizeResult = m_sizeDesired; // sizeResult.cx += GetMinExt(); // sizeResult.cy += GetMinExt(); if(IsFloating()) { if (nMode == LM_HORZ) { if (nLength < 50) nLength = 50; m_sizeDesired.cx = nLength; } if (nMode == (LM_LENGTHY | LM_HORZ)) { if (nLength < 50) nLength = 50; m_sizeDesired.cy = nLength; } sizeResult = m_sizeDesired; } return sizeResult; } ///////////////////////////////////////////////////////////////////////////// // CCJControlBar message handlers void CCJControlBar::OnNcPaint() { EraseNonClient(); } void CCJControlBar::OnPaint() { CPaintDC dc(this); // device context for painting CRect rc; m_iAuxImage = -1; GetClientRect(&rc); CRect rect; GetChildRect(rect); dc.ExcludeClipRect(rect); DrawBorders(&dc,rc); } void CCJControlBar::OnMouseMove(UINT nFlags, CPoint point) { HitTest(point); CRect rectDock; if( m_bDragging ) { ASSERT(GetParent() != NULL); GetParent()->GetClientRect(&rectDock); ClientToScreen(&rectDock); ClientToScreen(&point); CFrameWnd *pFrame=GetDockingFrame(); ASSERT(pFrame != NULL); pFrame -> ScreenToClient(&point); pFrame->ScreenToClient(&rectDock); point.x = point.x>rectDock.right ? rectDock.right:point.x; point.x = point.x<rectDock.left ? rectDock.left:point.x; point.y = point.y>rectDock.bottom ? rectDock.bottom:point.y; point.y = point.y<rectDock.top ? rectDock.top:point.y; OnInvertTracker(m_rcTrack); int deltaX = point.x-m_ptCurDrag.x; int deltaY = point.y-m_ptCurDrag.y; if(IsVertDocked()) { m_rcTrack.top += deltaY; m_rcTrack.bottom += deltaY; } else if (IsHorzDocked()) { m_rcTrack.left += deltaX; m_rcTrack.right += deltaX; } OnInvertTracker(m_rcTrack); m_ptCurDrag = point; } CControlBar::OnMouseMove(nFlags, point); } BOOL CCJControlBar::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { return (!m_bOkToDrag && !m_bDragging)? CControlBar::OnSetCursor(pWnd, nHitTest, message):FALSE; } void CCJControlBar::OnLButtonUp(UINT nFlags, CPoint point) { CRect rectAvail; GetParent()->GetClientRect(&rectAvail); if( m_bDragging ) { ReleaseCapture(); OnInvertTracker(m_rcTrack); m_bDragging = FALSE; if(IsVertDocked()) { int newHeight = m_rcTrack.top-m_ptStartDrag.y; m_sizeDesired.cy += newHeight; m_sizeDesired.cy = m_sizeDesired.cy > GetMinExt() ? m_sizeDesired.cy : GetMinExt(); m_sizeDesired.cy = m_sizeDesired.cy > rectAvail.Height() ? rectAvail.Height() : m_sizeDesired.cy; } else if (IsHorzDocked()) { int newWidth = m_rcTrack.left-m_ptStartDrag.x; m_sizeDesired.cx += newWidth; m_sizeDesired.cx = m_sizeDesired.cx > GetMinExt() ? m_sizeDesired.cx : GetMinExt(); m_sizeDesired.cx = m_sizeDesired.cx > rectAvail.Width() ? rectAvail.Width() : m_sizeDesired.cx; } ((CCJSizeDockBar *)GetParent())->CalcSizeBarLayout(); } CControlBar::OnLButtonUp(nFlags, point); } LRESULT CCJControlBar::OnNcHitTest(CPoint point) { return HTCLIENT; } BOOL CCJControlBar::OnEraseBkgnd(CDC* pDC) { int result = CControlBar::OnEraseBkgnd(pDC); CRect rect; GetChildRect(rect); rect.DeflateRect(1,1); pDC->Draw3dRect(rect, m_clrBtnShadow, m_clrBtnHilite); UpdateWindow(); // Reduce some of the flickering. Really not convinced this is a good solution. return result; } void CCJControlBar::OnSysColorChange() { CControlBar::OnSysColorChange(); m_clrBtnHilite = ::GetSysColor(COLOR_BTNHILIGHT); m_clrBtnShadow = ::GetSysColor(COLOR_BTNSHADOW); m_clrBtnFace = ::GetSysColor(COLOR_BTNFACE); } int CCJControlBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CControlBar::OnCreate(lpCreateStruct) == -1) return -1; if (m_bButtons) { if(!m_btnClose.Create(NULL, WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_NOTIFY | BS_OWNERDRAW | BS_ICON, CRect(0,0,0,0), this, IDC_BUTTON_HIDE )) { TRACE0(_T("Unable to create close button\n")); return -1; } if(!m_btnMinim.Create(NULL, WS_CHILD | WS_VISIBLE | WS_TABSTOP | BS_NOTIFY | BS_OWNERDRAW | BS_ICON, CRect(0,0,0,0), this, IDC_BUTTON_MINI )) { TRACE0(_T("Unable to create minimize button\n")); return -1; } m_btnClose.DisableFlatLook(); m_btnMinim.DisableFlatLook(); m_btnClose.SetIcon(m_ImageList.ExtractIcon(0), CSize(10,10)); // Create the ToolTip control. m_ToolTip.Create(this); m_ToolTip.Activate(TRUE); m_ToolTip.AddTool (&m_btnClose, IDS_HIDE); m_ToolTip.AddTool (&m_btnMinim, IDS_EXPAND); } return 0; } void CCJControlBar::OnWindowPosChanged(WINDOWPOS FAR* lpwndpos) { CControlBar::OnWindowPosChanged(lpwndpos); if (m_bButtons) { if (IsFloating()) { m_btnClose.ShowWindow(SW_HIDE); m_btnMinim.ShowWindow(SW_HIDE); } else { m_btnClose.ShowWindow(SW_SHOW); m_btnMinim.ShowWindow(SW_SHOW); CRect rcClose(GetButtonRect()); CRect rcMinim(GetButtonRect()); if (IsHorzDocked()) { rcMinim.OffsetRect(0,14); } else { rcClose.OffsetRect(14,0); } m_btnClose.MoveWindow(rcClose); m_btnMinim.MoveWindow(rcMinim); Invalidate(); // Added } } if (m_pChildWnd->GetSafeHwnd()) { CRect rc; GetChildRect(rc); rc.DeflateRect(1,1); m_pChildWnd->MoveWindow(rc); } } void CCJControlBar::OnContextMenu(CWnd* pWnd, CPoint point) { // if no menu, just return. if (m_menuID == -1 ) { // Gonzalo Pereyra DefWindowProc(WM_CONTEXTMENU, LONG(m_hWnd), MAKELPARAM(point.x,point.y)); TRACE0(_T("Warning: No control bar menu defined.\n")); return; } if (point.x == -1 && point.y == -1) { //keystroke invocation CRect rect; GetClientRect(rect); ClientToScreen(rect); point = rect.TopLeft(); point.Offset(5, 5); } CMenu menu; VERIFY(menu.LoadMenu(m_menuID)); CMenu* pPopup = menu.GetSubMenu(0); ASSERT(pPopup != NULL); CWnd* pWndPopupOwner = this; while (pWndPopupOwner->GetStyle() & WS_CHILD) pWndPopupOwner = pWndPopupOwner->GetParent(); pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, pWndPopupOwner); } void CCJControlBar::OnLButtonDown(UINT nFlags, CPoint point) { if (m_bOkToDrag) { CFrameWnd *pFrame=GetDockingFrame(); GetClientRect(m_rcTrack); if (IsVertDocked()) { m_rcTrack.top = m_rcTrack.bottom-m_iTrackBorderSize-2; m_rcTrack.bottom-=2; } else if (IsHorzDocked()) { m_rcTrack.left = m_rcTrack.right-m_iTrackBorderSize-2; m_rcTrack.right-=2; } ClientToScreen(&m_rcTrack); pFrame->ScreenToClient(&m_rcTrack); ClientToScreen(&point); pFrame->ScreenToClient(&point); m_ptStartDrag = point; m_ptCurDrag = point; SetCapture(); m_bDragging = TRUE; OnInvertTracker(m_rcTrack); } else if (m_pDockBar) { if (OnToolHitTest(point, NULL) == -1) { ClientToScreen(&point); ((CCJDockContext*)m_pDockContext)->StartDragDockBar(point); } } else { CControlBar::OnLButtonDown(nFlags, point); } } void CCJControlBar::OnButtonClose() { GetDockingFrame()->ShowControlBar(this,FALSE,FALSE); } void CCJControlBar::OnUpdateButtonClose(CCmdUI* pCmdUI) { pCmdUI->Enable(); } void CCJControlBar::OnButtonMinimize() { if (!m_bMaximized) { ((CCJSizeDockBar *)GetParent())->Maximize(this); m_bMaximized = TRUE; } else { ((CCJSizeDockBar *)GetParent())->Normalize(this); m_bMaximized = FALSE; } } void CCJControlBar::OnUpdateButtonMinimize(CCmdUI* pCmdUI) { pCmdUI->Enable(); } ///////////////////////////////////////////////////////////////////////////// // CCJControlBar operations UINT CCJControlBar::GetMenuID() { return m_menuID; } void CCJControlBar::SetMenuID(UINT nID) { m_menuID = nID; } void CCJControlBar::ShowFrameControls(BOOL bGripper, BOOL bButtons) { m_bGripper = bGripper; m_bButtons = bButtons; } void CCJControlBar::EnableDockingOnSizeBar(DWORD dwDockStyle) { ASSERT(m_pDockContext == NULL); m_dwDockStyle = dwDockStyle; if (m_pDockContext == NULL) m_pDockContext = new CCJDockContext(this); if (m_hWndOwner == NULL) m_hWndOwner = ::GetParent(m_hWnd); } void CCJControlBar::Maximize(int size) { m_sizeNormal = m_sizeDesired; if (IsHorzDocked()) { m_sizeDesired.cx = size; } else if (IsVertDocked()) { m_sizeDesired.cy = size; } m_bMaximized = TRUE; } void CCJControlBar::Minimize() { m_sizeNormal = m_sizeDesired; if (IsHorzDocked()) { m_sizeDesired.cx = GetMinExt(); } else if (IsVertDocked()) { m_sizeDesired.cy = GetMinExt(); } m_bMaximized = FALSE; } void CCJControlBar::Normalize() { if (IsHorzDocked()) { m_sizeDesired.cx = m_sizeNormal.cx; } else if (IsVertDocked()) { m_sizeDesired.cy = m_sizeNormal.cy; } m_bMaximized = FALSE; } void CCJControlBar::SetNormalSize(const CSize &cs) { m_sizeDesired = m_sizeNormal = cs; } BOOL CCJControlBar::IsVertDocked() { return (IsLeftDocked() || IsRightDocked()); } BOOL CCJControlBar::IsHorzDocked() { return (IsTopDocked() || IsBottomDocked()); } BOOL CCJControlBar::IsBottomDocked() { return m_pDockBar?(m_pDockBar->GetDlgCtrlID() == AFX_IDW_SIZEBAR_BOTTOM):FALSE; } BOOL CCJControlBar::IsTopDocked() { return m_pDockBar?(m_pDockBar->GetDlgCtrlID() == AFX_IDW_SIZEBAR_TOP):FALSE; } BOOL CCJControlBar::IsRightDocked() { return m_pDockBar?(m_pDockBar->GetDlgCtrlID() == AFX_IDW_SIZEBAR_RIGHT):FALSE; } BOOL CCJControlBar::IsLeftDocked() { return m_pDockBar?(m_pDockBar->GetDlgCtrlID() == AFX_IDW_SIZEBAR_LEFT):FALSE; } int CCJControlBar::GetMinExt() { int nRet = m_iTrackBorderSize; if (m_bGripper || m_bButtons) { nRet += GRIP_STARTGRIP; nRet += GRIP_SIZE*2; nRet += GRIP_INTRASPACING*3+2; } else nRet += 2; return nRet; } void CCJControlBar::GetChildRect(CRect &rect) { GetClientRect(&rect); if (!IsFloating()) { if (IsVertDocked()) { rect.left += m_cxOffset; rect.right -= m_cxOffset; rect.top += (GetMinExt()-5); rect.bottom -= (m_iTrackBorderSize+4); } else if(IsHorzDocked()) { rect.left += (GetMinExt()-5); rect.right -= (m_iTrackBorderSize+4); rect.top += m_cyOffset; rect.bottom -= m_cyOffset; } if( rect.left > rect.right || rect.top > rect.bottom ) rect = CRect(0,0,0,0); } } void CCJControlBar::EraseNonClient() { CWindowDC dc(this); CRect rectClient; GetClientRect(rectClient); CRect rectWindow; GetWindowRect(rectWindow); ScreenToClient(rectWindow); rectClient.OffsetRect(-rectWindow.left, -rectWindow.top); dc.ExcludeClipRect(rectClient); rectWindow.OffsetRect(-rectWindow.left, -rectWindow.top); dc.IntersectClipRect(rectWindow); SendMessage(WM_ERASEBKGND, (WPARAM)dc.m_hDC); } void CCJControlBar::DrawBorders(CDC *pDC, CRect &rect) { CRect rc; rc.CopyRect(&rect); CRect rcTrack; rcTrack.CopyRect(&rc); if(IsVertDocked()) { if (!m_bToFit) { rcTrack.top = rc.bottom-m_iTrackBorderSize; rcTrack.top-=2; rcTrack.bottom-=1; pDC->FillSolidRect(rcTrack, m_clrBtnFace); pDC->Draw3dRect(rcTrack, m_clrBtnHilite, m_clrBtnShadow); } } else if (IsHorzDocked()) { if (!m_bToFit) { rcTrack.left = rc.right-m_iTrackBorderSize; rcTrack.left-=2; rcTrack.right-=1; pDC->FillSolidRect(rcTrack, m_clrBtnFace); pDC->Draw3dRect(rcTrack, m_clrBtnHilite, m_clrBtnShadow); } } DrawGripper(pDC); } void CCJControlBar::HitTest(CPoint &point) { CRect rcWin; GetClientRect(&rcWin); HCURSOR hCur; BOOL bHit = FALSE; if (IsVertDocked()) { rcWin.top = rcWin.bottom-m_iTrackBorderSize; hCur = AfxGetApp()->LoadCursor(AFX_IDC_VSPLITBAR); bHit = rcWin.PtInRect(point) && !m_bToFit; } else if (IsHorzDocked()) { rcWin.left = rcWin.right-m_iTrackBorderSize; hCur = AfxGetApp()->LoadCursor(AFX_IDC_HSPLITBAR); bHit = rcWin.PtInRect(point) && !m_bToFit; } if( bHit ) SetCursor(hCur); else { hCur = ::LoadCursor(NULL,IDC_ARROW); SetCursor(hCur); } m_bOkToDrag = bHit; } void CCJControlBar::OnInvertTracker(const CRect &rect) { ASSERT_VALID(this); ASSERT(!rect.IsRectEmpty()); CFrameWnd *pFrame=GetDockingFrame(); CDC* pDC = pFrame->GetDC(); CBrush* pBrush = CDC::GetHalftoneBrush(); HBRUSH hOldBrush = NULL; if (pBrush != NULL) hOldBrush = (HBRUSH)SelectObject(pDC->m_hDC, pBrush->m_hObject); pDC->PatBlt(rect.left, rect.top, rect.Width(), rect.Height(), PATINVERT); if (hOldBrush != NULL) SelectObject(pDC->m_hDC, hOldBrush); pFrame->ReleaseDC(pDC); } void CCJControlBar::SetChild(CWnd *pWnd) { m_pChildWnd = pWnd; } void CCJControlBar::DrawGripper(CDC *pDC) { if (!IsFloating() && m_bGripper) { // draw the gripper. CRect pRect(GetGripperRect()); pDC->Draw3dRect( pRect, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW) ); if (IsHorzDocked()) pRect.OffsetRect(4,0); else pRect.OffsetRect(0,4); pDC->Draw3dRect( pRect, ::GetSysColor(COLOR_BTNHIGHLIGHT), ::GetSysColor(COLOR_BTNSHADOW) ); } } CRect CCJControlBar::GetButtonRect() { CRect rect; GetClientRect(&rect); rect.OffsetRect(-rect.left,-rect.top); if (IsHorzDocked()) { rect.top += 3; rect.bottom = rect.top+12; rect.left += 2; rect.right = rect.left+12; } else { rect.right -= 19; rect.left = rect.right-12; rect.top += 3; rect.bottom = rect.top+12; } return rect; } CRect CCJControlBar::GetGripperRect() { CRect rect; GetClientRect(&rect); rect.OffsetRect(-rect.left,-rect.top); if (IsHorzDocked()) { rect.DeflateRect(3,3); rect.left += 1; rect.right = rect.left+3; rect.bottom -= 1; rect.top += m_bButtons?30:1; } else { rect.DeflateRect(4,4); rect.top += 2; rect.bottom = rect.top+3; rect.right -= m_bButtons?30:2; } return rect; }
C++