code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* ***** 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); }
zzhongster-wxtlactivex
ffactivex/ObjectManager.cpp
C++
mpl11
5,998
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by npactivex.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
zzhongster-wxtlactivex
ffactivex/resource.h
C
mpl11
403
/* ***** 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; }
zzhongster-wxtlactivex
ffactivex/npactivex.cpp
C++
mpl11
18,456
maxVf = 200 # Generating the header head = """// 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:""" pattern = """ \tvirtual HRESULT __stdcall fv{0}(char x) {{ \t\tva_list va = &x; \t\tHRESULT ret = ProcessCommand({0}, va); \t\tva_end(va); \t\treturn ret; \t}} """ pattern = """ \tvirtual HRESULT __stdcall fv{0}();""" end = """ protected: \tconst static int kMaxVf = {0}; }}; """ f = open("FakeDispatcherBase.h", "w") f.write(head) for i in range(0, maxVf): f.write(pattern.format(i)) f.write(end.format(maxVf)) f.close() head = """; Copyright qiuc12@gmail.com ; This file is generated automatically by python. DON'T MODIFY IT! """ f = open("FakeDispatcherBase.asm", "w") f.write(head) f.write(".386\n") f.write(".model flat\n") f.write("_DualProcessCommandWrap proto\n") ObjFormat = "?fv{0}@FakeDispatcherBase@@EAGJXZ" for i in range(0, maxVf): f.write("PUBLIC " + ObjFormat.format(i) + "\n") f.write(".code\n") for i in range(0, maxVf): f.write(ObjFormat.format(i) + " proc\n") f.write(" push {0}\n".format(i)) f.write(" jmp _DualProcessCommandWrap\n") f.write(ObjFormat.format(i) + " endp\n") f.write("\nend\n") f.close()
zzhongster-wxtlactivex
ffactivex/FakeDispatcherBase_gen.py
Python
mpl11
1,484
comment ? /* ***** 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 ***** */ ? .386 .model flat PUBLIC _DualProcessCommandWrap _DualProcessCommand proto .code _DualProcessCommandWrap proc push 0 call _DualProcessCommand ; Thanks god we can use ecx, edx for free pop ecx ; length of par pop edx ; command id pop edx ; return address add esp, ecx jmp edx _DualProcessCommandWrap endp end
zzhongster-wxtlactivex
ffactivex/FakeDispatcherWrap.asm
Assembly
mpl11
1,879
/* ***** 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); };
zzhongster-wxtlactivex
ffactivex/FakeDispatcher.h
C++
mpl11
6,240
// 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
zzhongster-wxtlactivex
ffactivex/stdafx.cpp
C++
mpl11
299
#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); } };
zzhongster-wxtlactivex
ffactivex/ScriptFunc.h
C++
mpl11
1,139
/* -*- 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
zzhongster-wxtlactivex
ffactivex/authorize.cpp
C++
mpl11
10,040
#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; }
zzhongster-wxtlactivex
ffactivex/ScriptFunc.cpp
C++
mpl11
1,507
/* ***** 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; }
zzhongster-wxtlactivex
ffactivex/axhost.cpp
C++
mpl11
15,111
// (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; }
zzhongster-wxtlactivex
ffactivex/ApiHook/Hook.cpp
C++
mpl11
3,588
#ifndef _HOOK_H_ #define _HOOK_H_ typedef struct _HOOKINFO_ { PBYTE Stub; DWORD CodeLength; LPVOID FuncAddr; LPVOID FakeAddr; }HOOKINFO, *PHOOKINFO; VOID HEInitHook(PHOOKINFO HookInfo, LPVOID FuncAddr, LPVOID FakeAddr); BOOL HEStartHook(PHOOKINFO HookInfo); BOOL HEStopHook(PHOOKINFO HookInfo); #endif
zzhongster-wxtlactivex
ffactivex/ApiHook/Hook.h
C
mpl11
323
/* ***** 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 }
zzhongster-wxtlactivex
ffactivex/AtlThunk.cpp
C++
mpl11
10,401
; Copyright qiuc12@gmail.com ; This file is generated automatically by python. DON'T MODIFY IT! .386 .model flat _DualProcessCommandWrap proto PUBLIC ?fv0@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv1@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv2@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv3@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv4@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv5@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv6@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv7@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv8@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv9@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv10@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv11@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv12@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv13@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv14@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv15@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv16@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv17@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv18@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv19@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv20@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv21@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv22@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv23@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv24@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv25@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv26@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv27@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv28@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv29@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv30@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv31@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv32@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv33@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv34@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv35@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv36@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv37@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv38@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv39@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv40@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv41@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv42@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv43@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv44@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv45@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv46@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv47@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv48@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv49@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv50@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv51@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv52@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv53@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv54@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv55@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv56@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv57@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv58@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv59@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv60@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv61@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv62@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv63@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv64@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv65@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv66@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv67@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv68@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv69@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv70@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv71@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv72@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv73@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv74@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv75@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv76@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv77@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv78@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv79@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv80@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv81@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv82@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv83@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv84@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv85@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv86@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv87@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv88@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv89@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv90@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv91@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv92@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv93@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv94@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv95@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv96@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv97@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv98@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv99@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv100@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv101@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv102@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv103@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv104@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv105@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv106@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv107@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv108@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv109@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv110@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv111@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv112@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv113@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv114@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv115@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv116@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv117@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv118@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv119@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv120@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv121@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv122@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv123@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv124@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv125@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv126@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv127@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv128@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv129@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv130@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv131@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv132@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv133@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv134@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv135@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv136@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv137@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv138@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv139@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv140@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv141@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv142@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv143@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv144@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv145@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv146@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv147@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv148@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv149@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv150@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv151@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv152@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv153@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv154@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv155@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv156@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv157@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv158@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv159@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv160@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv161@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv162@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv163@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv164@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv165@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv166@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv167@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv168@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv169@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv170@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv171@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv172@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv173@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv174@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv175@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv176@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv177@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv178@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv179@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv180@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv181@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv182@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv183@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv184@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv185@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv186@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv187@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv188@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv189@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv190@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv191@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv192@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv193@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv194@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv195@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv196@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv197@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv198@FakeDispatcherBase@@EAGJXZ PUBLIC ?fv199@FakeDispatcherBase@@EAGJXZ .code ?fv0@FakeDispatcherBase@@EAGJXZ proc push 0 jmp _DualProcessCommandWrap ?fv0@FakeDispatcherBase@@EAGJXZ endp ?fv1@FakeDispatcherBase@@EAGJXZ proc push 1 jmp _DualProcessCommandWrap ?fv1@FakeDispatcherBase@@EAGJXZ endp ?fv2@FakeDispatcherBase@@EAGJXZ proc push 2 jmp _DualProcessCommandWrap ?fv2@FakeDispatcherBase@@EAGJXZ endp ?fv3@FakeDispatcherBase@@EAGJXZ proc push 3 jmp _DualProcessCommandWrap ?fv3@FakeDispatcherBase@@EAGJXZ endp ?fv4@FakeDispatcherBase@@EAGJXZ proc push 4 jmp _DualProcessCommandWrap ?fv4@FakeDispatcherBase@@EAGJXZ endp ?fv5@FakeDispatcherBase@@EAGJXZ proc push 5 jmp _DualProcessCommandWrap ?fv5@FakeDispatcherBase@@EAGJXZ endp ?fv6@FakeDispatcherBase@@EAGJXZ proc push 6 jmp _DualProcessCommandWrap ?fv6@FakeDispatcherBase@@EAGJXZ endp ?fv7@FakeDispatcherBase@@EAGJXZ proc push 7 jmp _DualProcessCommandWrap ?fv7@FakeDispatcherBase@@EAGJXZ endp ?fv8@FakeDispatcherBase@@EAGJXZ proc push 8 jmp _DualProcessCommandWrap ?fv8@FakeDispatcherBase@@EAGJXZ endp ?fv9@FakeDispatcherBase@@EAGJXZ proc push 9 jmp _DualProcessCommandWrap ?fv9@FakeDispatcherBase@@EAGJXZ endp ?fv10@FakeDispatcherBase@@EAGJXZ proc push 10 jmp _DualProcessCommandWrap ?fv10@FakeDispatcherBase@@EAGJXZ endp ?fv11@FakeDispatcherBase@@EAGJXZ proc push 11 jmp _DualProcessCommandWrap ?fv11@FakeDispatcherBase@@EAGJXZ endp ?fv12@FakeDispatcherBase@@EAGJXZ proc push 12 jmp _DualProcessCommandWrap ?fv12@FakeDispatcherBase@@EAGJXZ endp ?fv13@FakeDispatcherBase@@EAGJXZ proc push 13 jmp _DualProcessCommandWrap ?fv13@FakeDispatcherBase@@EAGJXZ endp ?fv14@FakeDispatcherBase@@EAGJXZ proc push 14 jmp _DualProcessCommandWrap ?fv14@FakeDispatcherBase@@EAGJXZ endp ?fv15@FakeDispatcherBase@@EAGJXZ proc push 15 jmp _DualProcessCommandWrap ?fv15@FakeDispatcherBase@@EAGJXZ endp ?fv16@FakeDispatcherBase@@EAGJXZ proc push 16 jmp _DualProcessCommandWrap ?fv16@FakeDispatcherBase@@EAGJXZ endp ?fv17@FakeDispatcherBase@@EAGJXZ proc push 17 jmp _DualProcessCommandWrap ?fv17@FakeDispatcherBase@@EAGJXZ endp ?fv18@FakeDispatcherBase@@EAGJXZ proc push 18 jmp _DualProcessCommandWrap ?fv18@FakeDispatcherBase@@EAGJXZ endp ?fv19@FakeDispatcherBase@@EAGJXZ proc push 19 jmp _DualProcessCommandWrap ?fv19@FakeDispatcherBase@@EAGJXZ endp ?fv20@FakeDispatcherBase@@EAGJXZ proc push 20 jmp _DualProcessCommandWrap ?fv20@FakeDispatcherBase@@EAGJXZ endp ?fv21@FakeDispatcherBase@@EAGJXZ proc push 21 jmp _DualProcessCommandWrap ?fv21@FakeDispatcherBase@@EAGJXZ endp ?fv22@FakeDispatcherBase@@EAGJXZ proc push 22 jmp _DualProcessCommandWrap ?fv22@FakeDispatcherBase@@EAGJXZ endp ?fv23@FakeDispatcherBase@@EAGJXZ proc push 23 jmp _DualProcessCommandWrap ?fv23@FakeDispatcherBase@@EAGJXZ endp ?fv24@FakeDispatcherBase@@EAGJXZ proc push 24 jmp _DualProcessCommandWrap ?fv24@FakeDispatcherBase@@EAGJXZ endp ?fv25@FakeDispatcherBase@@EAGJXZ proc push 25 jmp _DualProcessCommandWrap ?fv25@FakeDispatcherBase@@EAGJXZ endp ?fv26@FakeDispatcherBase@@EAGJXZ proc push 26 jmp _DualProcessCommandWrap ?fv26@FakeDispatcherBase@@EAGJXZ endp ?fv27@FakeDispatcherBase@@EAGJXZ proc push 27 jmp _DualProcessCommandWrap ?fv27@FakeDispatcherBase@@EAGJXZ endp ?fv28@FakeDispatcherBase@@EAGJXZ proc push 28 jmp _DualProcessCommandWrap ?fv28@FakeDispatcherBase@@EAGJXZ endp ?fv29@FakeDispatcherBase@@EAGJXZ proc push 29 jmp _DualProcessCommandWrap ?fv29@FakeDispatcherBase@@EAGJXZ endp ?fv30@FakeDispatcherBase@@EAGJXZ proc push 30 jmp _DualProcessCommandWrap ?fv30@FakeDispatcherBase@@EAGJXZ endp ?fv31@FakeDispatcherBase@@EAGJXZ proc push 31 jmp _DualProcessCommandWrap ?fv31@FakeDispatcherBase@@EAGJXZ endp ?fv32@FakeDispatcherBase@@EAGJXZ proc push 32 jmp _DualProcessCommandWrap ?fv32@FakeDispatcherBase@@EAGJXZ endp ?fv33@FakeDispatcherBase@@EAGJXZ proc push 33 jmp _DualProcessCommandWrap ?fv33@FakeDispatcherBase@@EAGJXZ endp ?fv34@FakeDispatcherBase@@EAGJXZ proc push 34 jmp _DualProcessCommandWrap ?fv34@FakeDispatcherBase@@EAGJXZ endp ?fv35@FakeDispatcherBase@@EAGJXZ proc push 35 jmp _DualProcessCommandWrap ?fv35@FakeDispatcherBase@@EAGJXZ endp ?fv36@FakeDispatcherBase@@EAGJXZ proc push 36 jmp _DualProcessCommandWrap ?fv36@FakeDispatcherBase@@EAGJXZ endp ?fv37@FakeDispatcherBase@@EAGJXZ proc push 37 jmp _DualProcessCommandWrap ?fv37@FakeDispatcherBase@@EAGJXZ endp ?fv38@FakeDispatcherBase@@EAGJXZ proc push 38 jmp _DualProcessCommandWrap ?fv38@FakeDispatcherBase@@EAGJXZ endp ?fv39@FakeDispatcherBase@@EAGJXZ proc push 39 jmp _DualProcessCommandWrap ?fv39@FakeDispatcherBase@@EAGJXZ endp ?fv40@FakeDispatcherBase@@EAGJXZ proc push 40 jmp _DualProcessCommandWrap ?fv40@FakeDispatcherBase@@EAGJXZ endp ?fv41@FakeDispatcherBase@@EAGJXZ proc push 41 jmp _DualProcessCommandWrap ?fv41@FakeDispatcherBase@@EAGJXZ endp ?fv42@FakeDispatcherBase@@EAGJXZ proc push 42 jmp _DualProcessCommandWrap ?fv42@FakeDispatcherBase@@EAGJXZ endp ?fv43@FakeDispatcherBase@@EAGJXZ proc push 43 jmp _DualProcessCommandWrap ?fv43@FakeDispatcherBase@@EAGJXZ endp ?fv44@FakeDispatcherBase@@EAGJXZ proc push 44 jmp _DualProcessCommandWrap ?fv44@FakeDispatcherBase@@EAGJXZ endp ?fv45@FakeDispatcherBase@@EAGJXZ proc push 45 jmp _DualProcessCommandWrap ?fv45@FakeDispatcherBase@@EAGJXZ endp ?fv46@FakeDispatcherBase@@EAGJXZ proc push 46 jmp _DualProcessCommandWrap ?fv46@FakeDispatcherBase@@EAGJXZ endp ?fv47@FakeDispatcherBase@@EAGJXZ proc push 47 jmp _DualProcessCommandWrap ?fv47@FakeDispatcherBase@@EAGJXZ endp ?fv48@FakeDispatcherBase@@EAGJXZ proc push 48 jmp _DualProcessCommandWrap ?fv48@FakeDispatcherBase@@EAGJXZ endp ?fv49@FakeDispatcherBase@@EAGJXZ proc push 49 jmp _DualProcessCommandWrap ?fv49@FakeDispatcherBase@@EAGJXZ endp ?fv50@FakeDispatcherBase@@EAGJXZ proc push 50 jmp _DualProcessCommandWrap ?fv50@FakeDispatcherBase@@EAGJXZ endp ?fv51@FakeDispatcherBase@@EAGJXZ proc push 51 jmp _DualProcessCommandWrap ?fv51@FakeDispatcherBase@@EAGJXZ endp ?fv52@FakeDispatcherBase@@EAGJXZ proc push 52 jmp _DualProcessCommandWrap ?fv52@FakeDispatcherBase@@EAGJXZ endp ?fv53@FakeDispatcherBase@@EAGJXZ proc push 53 jmp _DualProcessCommandWrap ?fv53@FakeDispatcherBase@@EAGJXZ endp ?fv54@FakeDispatcherBase@@EAGJXZ proc push 54 jmp _DualProcessCommandWrap ?fv54@FakeDispatcherBase@@EAGJXZ endp ?fv55@FakeDispatcherBase@@EAGJXZ proc push 55 jmp _DualProcessCommandWrap ?fv55@FakeDispatcherBase@@EAGJXZ endp ?fv56@FakeDispatcherBase@@EAGJXZ proc push 56 jmp _DualProcessCommandWrap ?fv56@FakeDispatcherBase@@EAGJXZ endp ?fv57@FakeDispatcherBase@@EAGJXZ proc push 57 jmp _DualProcessCommandWrap ?fv57@FakeDispatcherBase@@EAGJXZ endp ?fv58@FakeDispatcherBase@@EAGJXZ proc push 58 jmp _DualProcessCommandWrap ?fv58@FakeDispatcherBase@@EAGJXZ endp ?fv59@FakeDispatcherBase@@EAGJXZ proc push 59 jmp _DualProcessCommandWrap ?fv59@FakeDispatcherBase@@EAGJXZ endp ?fv60@FakeDispatcherBase@@EAGJXZ proc push 60 jmp _DualProcessCommandWrap ?fv60@FakeDispatcherBase@@EAGJXZ endp ?fv61@FakeDispatcherBase@@EAGJXZ proc push 61 jmp _DualProcessCommandWrap ?fv61@FakeDispatcherBase@@EAGJXZ endp ?fv62@FakeDispatcherBase@@EAGJXZ proc push 62 jmp _DualProcessCommandWrap ?fv62@FakeDispatcherBase@@EAGJXZ endp ?fv63@FakeDispatcherBase@@EAGJXZ proc push 63 jmp _DualProcessCommandWrap ?fv63@FakeDispatcherBase@@EAGJXZ endp ?fv64@FakeDispatcherBase@@EAGJXZ proc push 64 jmp _DualProcessCommandWrap ?fv64@FakeDispatcherBase@@EAGJXZ endp ?fv65@FakeDispatcherBase@@EAGJXZ proc push 65 jmp _DualProcessCommandWrap ?fv65@FakeDispatcherBase@@EAGJXZ endp ?fv66@FakeDispatcherBase@@EAGJXZ proc push 66 jmp _DualProcessCommandWrap ?fv66@FakeDispatcherBase@@EAGJXZ endp ?fv67@FakeDispatcherBase@@EAGJXZ proc push 67 jmp _DualProcessCommandWrap ?fv67@FakeDispatcherBase@@EAGJXZ endp ?fv68@FakeDispatcherBase@@EAGJXZ proc push 68 jmp _DualProcessCommandWrap ?fv68@FakeDispatcherBase@@EAGJXZ endp ?fv69@FakeDispatcherBase@@EAGJXZ proc push 69 jmp _DualProcessCommandWrap ?fv69@FakeDispatcherBase@@EAGJXZ endp ?fv70@FakeDispatcherBase@@EAGJXZ proc push 70 jmp _DualProcessCommandWrap ?fv70@FakeDispatcherBase@@EAGJXZ endp ?fv71@FakeDispatcherBase@@EAGJXZ proc push 71 jmp _DualProcessCommandWrap ?fv71@FakeDispatcherBase@@EAGJXZ endp ?fv72@FakeDispatcherBase@@EAGJXZ proc push 72 jmp _DualProcessCommandWrap ?fv72@FakeDispatcherBase@@EAGJXZ endp ?fv73@FakeDispatcherBase@@EAGJXZ proc push 73 jmp _DualProcessCommandWrap ?fv73@FakeDispatcherBase@@EAGJXZ endp ?fv74@FakeDispatcherBase@@EAGJXZ proc push 74 jmp _DualProcessCommandWrap ?fv74@FakeDispatcherBase@@EAGJXZ endp ?fv75@FakeDispatcherBase@@EAGJXZ proc push 75 jmp _DualProcessCommandWrap ?fv75@FakeDispatcherBase@@EAGJXZ endp ?fv76@FakeDispatcherBase@@EAGJXZ proc push 76 jmp _DualProcessCommandWrap ?fv76@FakeDispatcherBase@@EAGJXZ endp ?fv77@FakeDispatcherBase@@EAGJXZ proc push 77 jmp _DualProcessCommandWrap ?fv77@FakeDispatcherBase@@EAGJXZ endp ?fv78@FakeDispatcherBase@@EAGJXZ proc push 78 jmp _DualProcessCommandWrap ?fv78@FakeDispatcherBase@@EAGJXZ endp ?fv79@FakeDispatcherBase@@EAGJXZ proc push 79 jmp _DualProcessCommandWrap ?fv79@FakeDispatcherBase@@EAGJXZ endp ?fv80@FakeDispatcherBase@@EAGJXZ proc push 80 jmp _DualProcessCommandWrap ?fv80@FakeDispatcherBase@@EAGJXZ endp ?fv81@FakeDispatcherBase@@EAGJXZ proc push 81 jmp _DualProcessCommandWrap ?fv81@FakeDispatcherBase@@EAGJXZ endp ?fv82@FakeDispatcherBase@@EAGJXZ proc push 82 jmp _DualProcessCommandWrap ?fv82@FakeDispatcherBase@@EAGJXZ endp ?fv83@FakeDispatcherBase@@EAGJXZ proc push 83 jmp _DualProcessCommandWrap ?fv83@FakeDispatcherBase@@EAGJXZ endp ?fv84@FakeDispatcherBase@@EAGJXZ proc push 84 jmp _DualProcessCommandWrap ?fv84@FakeDispatcherBase@@EAGJXZ endp ?fv85@FakeDispatcherBase@@EAGJXZ proc push 85 jmp _DualProcessCommandWrap ?fv85@FakeDispatcherBase@@EAGJXZ endp ?fv86@FakeDispatcherBase@@EAGJXZ proc push 86 jmp _DualProcessCommandWrap ?fv86@FakeDispatcherBase@@EAGJXZ endp ?fv87@FakeDispatcherBase@@EAGJXZ proc push 87 jmp _DualProcessCommandWrap ?fv87@FakeDispatcherBase@@EAGJXZ endp ?fv88@FakeDispatcherBase@@EAGJXZ proc push 88 jmp _DualProcessCommandWrap ?fv88@FakeDispatcherBase@@EAGJXZ endp ?fv89@FakeDispatcherBase@@EAGJXZ proc push 89 jmp _DualProcessCommandWrap ?fv89@FakeDispatcherBase@@EAGJXZ endp ?fv90@FakeDispatcherBase@@EAGJXZ proc push 90 jmp _DualProcessCommandWrap ?fv90@FakeDispatcherBase@@EAGJXZ endp ?fv91@FakeDispatcherBase@@EAGJXZ proc push 91 jmp _DualProcessCommandWrap ?fv91@FakeDispatcherBase@@EAGJXZ endp ?fv92@FakeDispatcherBase@@EAGJXZ proc push 92 jmp _DualProcessCommandWrap ?fv92@FakeDispatcherBase@@EAGJXZ endp ?fv93@FakeDispatcherBase@@EAGJXZ proc push 93 jmp _DualProcessCommandWrap ?fv93@FakeDispatcherBase@@EAGJXZ endp ?fv94@FakeDispatcherBase@@EAGJXZ proc push 94 jmp _DualProcessCommandWrap ?fv94@FakeDispatcherBase@@EAGJXZ endp ?fv95@FakeDispatcherBase@@EAGJXZ proc push 95 jmp _DualProcessCommandWrap ?fv95@FakeDispatcherBase@@EAGJXZ endp ?fv96@FakeDispatcherBase@@EAGJXZ proc push 96 jmp _DualProcessCommandWrap ?fv96@FakeDispatcherBase@@EAGJXZ endp ?fv97@FakeDispatcherBase@@EAGJXZ proc push 97 jmp _DualProcessCommandWrap ?fv97@FakeDispatcherBase@@EAGJXZ endp ?fv98@FakeDispatcherBase@@EAGJXZ proc push 98 jmp _DualProcessCommandWrap ?fv98@FakeDispatcherBase@@EAGJXZ endp ?fv99@FakeDispatcherBase@@EAGJXZ proc push 99 jmp _DualProcessCommandWrap ?fv99@FakeDispatcherBase@@EAGJXZ endp ?fv100@FakeDispatcherBase@@EAGJXZ proc push 100 jmp _DualProcessCommandWrap ?fv100@FakeDispatcherBase@@EAGJXZ endp ?fv101@FakeDispatcherBase@@EAGJXZ proc push 101 jmp _DualProcessCommandWrap ?fv101@FakeDispatcherBase@@EAGJXZ endp ?fv102@FakeDispatcherBase@@EAGJXZ proc push 102 jmp _DualProcessCommandWrap ?fv102@FakeDispatcherBase@@EAGJXZ endp ?fv103@FakeDispatcherBase@@EAGJXZ proc push 103 jmp _DualProcessCommandWrap ?fv103@FakeDispatcherBase@@EAGJXZ endp ?fv104@FakeDispatcherBase@@EAGJXZ proc push 104 jmp _DualProcessCommandWrap ?fv104@FakeDispatcherBase@@EAGJXZ endp ?fv105@FakeDispatcherBase@@EAGJXZ proc push 105 jmp _DualProcessCommandWrap ?fv105@FakeDispatcherBase@@EAGJXZ endp ?fv106@FakeDispatcherBase@@EAGJXZ proc push 106 jmp _DualProcessCommandWrap ?fv106@FakeDispatcherBase@@EAGJXZ endp ?fv107@FakeDispatcherBase@@EAGJXZ proc push 107 jmp _DualProcessCommandWrap ?fv107@FakeDispatcherBase@@EAGJXZ endp ?fv108@FakeDispatcherBase@@EAGJXZ proc push 108 jmp _DualProcessCommandWrap ?fv108@FakeDispatcherBase@@EAGJXZ endp ?fv109@FakeDispatcherBase@@EAGJXZ proc push 109 jmp _DualProcessCommandWrap ?fv109@FakeDispatcherBase@@EAGJXZ endp ?fv110@FakeDispatcherBase@@EAGJXZ proc push 110 jmp _DualProcessCommandWrap ?fv110@FakeDispatcherBase@@EAGJXZ endp ?fv111@FakeDispatcherBase@@EAGJXZ proc push 111 jmp _DualProcessCommandWrap ?fv111@FakeDispatcherBase@@EAGJXZ endp ?fv112@FakeDispatcherBase@@EAGJXZ proc push 112 jmp _DualProcessCommandWrap ?fv112@FakeDispatcherBase@@EAGJXZ endp ?fv113@FakeDispatcherBase@@EAGJXZ proc push 113 jmp _DualProcessCommandWrap ?fv113@FakeDispatcherBase@@EAGJXZ endp ?fv114@FakeDispatcherBase@@EAGJXZ proc push 114 jmp _DualProcessCommandWrap ?fv114@FakeDispatcherBase@@EAGJXZ endp ?fv115@FakeDispatcherBase@@EAGJXZ proc push 115 jmp _DualProcessCommandWrap ?fv115@FakeDispatcherBase@@EAGJXZ endp ?fv116@FakeDispatcherBase@@EAGJXZ proc push 116 jmp _DualProcessCommandWrap ?fv116@FakeDispatcherBase@@EAGJXZ endp ?fv117@FakeDispatcherBase@@EAGJXZ proc push 117 jmp _DualProcessCommandWrap ?fv117@FakeDispatcherBase@@EAGJXZ endp ?fv118@FakeDispatcherBase@@EAGJXZ proc push 118 jmp _DualProcessCommandWrap ?fv118@FakeDispatcherBase@@EAGJXZ endp ?fv119@FakeDispatcherBase@@EAGJXZ proc push 119 jmp _DualProcessCommandWrap ?fv119@FakeDispatcherBase@@EAGJXZ endp ?fv120@FakeDispatcherBase@@EAGJXZ proc push 120 jmp _DualProcessCommandWrap ?fv120@FakeDispatcherBase@@EAGJXZ endp ?fv121@FakeDispatcherBase@@EAGJXZ proc push 121 jmp _DualProcessCommandWrap ?fv121@FakeDispatcherBase@@EAGJXZ endp ?fv122@FakeDispatcherBase@@EAGJXZ proc push 122 jmp _DualProcessCommandWrap ?fv122@FakeDispatcherBase@@EAGJXZ endp ?fv123@FakeDispatcherBase@@EAGJXZ proc push 123 jmp _DualProcessCommandWrap ?fv123@FakeDispatcherBase@@EAGJXZ endp ?fv124@FakeDispatcherBase@@EAGJXZ proc push 124 jmp _DualProcessCommandWrap ?fv124@FakeDispatcherBase@@EAGJXZ endp ?fv125@FakeDispatcherBase@@EAGJXZ proc push 125 jmp _DualProcessCommandWrap ?fv125@FakeDispatcherBase@@EAGJXZ endp ?fv126@FakeDispatcherBase@@EAGJXZ proc push 126 jmp _DualProcessCommandWrap ?fv126@FakeDispatcherBase@@EAGJXZ endp ?fv127@FakeDispatcherBase@@EAGJXZ proc push 127 jmp _DualProcessCommandWrap ?fv127@FakeDispatcherBase@@EAGJXZ endp ?fv128@FakeDispatcherBase@@EAGJXZ proc push 128 jmp _DualProcessCommandWrap ?fv128@FakeDispatcherBase@@EAGJXZ endp ?fv129@FakeDispatcherBase@@EAGJXZ proc push 129 jmp _DualProcessCommandWrap ?fv129@FakeDispatcherBase@@EAGJXZ endp ?fv130@FakeDispatcherBase@@EAGJXZ proc push 130 jmp _DualProcessCommandWrap ?fv130@FakeDispatcherBase@@EAGJXZ endp ?fv131@FakeDispatcherBase@@EAGJXZ proc push 131 jmp _DualProcessCommandWrap ?fv131@FakeDispatcherBase@@EAGJXZ endp ?fv132@FakeDispatcherBase@@EAGJXZ proc push 132 jmp _DualProcessCommandWrap ?fv132@FakeDispatcherBase@@EAGJXZ endp ?fv133@FakeDispatcherBase@@EAGJXZ proc push 133 jmp _DualProcessCommandWrap ?fv133@FakeDispatcherBase@@EAGJXZ endp ?fv134@FakeDispatcherBase@@EAGJXZ proc push 134 jmp _DualProcessCommandWrap ?fv134@FakeDispatcherBase@@EAGJXZ endp ?fv135@FakeDispatcherBase@@EAGJXZ proc push 135 jmp _DualProcessCommandWrap ?fv135@FakeDispatcherBase@@EAGJXZ endp ?fv136@FakeDispatcherBase@@EAGJXZ proc push 136 jmp _DualProcessCommandWrap ?fv136@FakeDispatcherBase@@EAGJXZ endp ?fv137@FakeDispatcherBase@@EAGJXZ proc push 137 jmp _DualProcessCommandWrap ?fv137@FakeDispatcherBase@@EAGJXZ endp ?fv138@FakeDispatcherBase@@EAGJXZ proc push 138 jmp _DualProcessCommandWrap ?fv138@FakeDispatcherBase@@EAGJXZ endp ?fv139@FakeDispatcherBase@@EAGJXZ proc push 139 jmp _DualProcessCommandWrap ?fv139@FakeDispatcherBase@@EAGJXZ endp ?fv140@FakeDispatcherBase@@EAGJXZ proc push 140 jmp _DualProcessCommandWrap ?fv140@FakeDispatcherBase@@EAGJXZ endp ?fv141@FakeDispatcherBase@@EAGJXZ proc push 141 jmp _DualProcessCommandWrap ?fv141@FakeDispatcherBase@@EAGJXZ endp ?fv142@FakeDispatcherBase@@EAGJXZ proc push 142 jmp _DualProcessCommandWrap ?fv142@FakeDispatcherBase@@EAGJXZ endp ?fv143@FakeDispatcherBase@@EAGJXZ proc push 143 jmp _DualProcessCommandWrap ?fv143@FakeDispatcherBase@@EAGJXZ endp ?fv144@FakeDispatcherBase@@EAGJXZ proc push 144 jmp _DualProcessCommandWrap ?fv144@FakeDispatcherBase@@EAGJXZ endp ?fv145@FakeDispatcherBase@@EAGJXZ proc push 145 jmp _DualProcessCommandWrap ?fv145@FakeDispatcherBase@@EAGJXZ endp ?fv146@FakeDispatcherBase@@EAGJXZ proc push 146 jmp _DualProcessCommandWrap ?fv146@FakeDispatcherBase@@EAGJXZ endp ?fv147@FakeDispatcherBase@@EAGJXZ proc push 147 jmp _DualProcessCommandWrap ?fv147@FakeDispatcherBase@@EAGJXZ endp ?fv148@FakeDispatcherBase@@EAGJXZ proc push 148 jmp _DualProcessCommandWrap ?fv148@FakeDispatcherBase@@EAGJXZ endp ?fv149@FakeDispatcherBase@@EAGJXZ proc push 149 jmp _DualProcessCommandWrap ?fv149@FakeDispatcherBase@@EAGJXZ endp ?fv150@FakeDispatcherBase@@EAGJXZ proc push 150 jmp _DualProcessCommandWrap ?fv150@FakeDispatcherBase@@EAGJXZ endp ?fv151@FakeDispatcherBase@@EAGJXZ proc push 151 jmp _DualProcessCommandWrap ?fv151@FakeDispatcherBase@@EAGJXZ endp ?fv152@FakeDispatcherBase@@EAGJXZ proc push 152 jmp _DualProcessCommandWrap ?fv152@FakeDispatcherBase@@EAGJXZ endp ?fv153@FakeDispatcherBase@@EAGJXZ proc push 153 jmp _DualProcessCommandWrap ?fv153@FakeDispatcherBase@@EAGJXZ endp ?fv154@FakeDispatcherBase@@EAGJXZ proc push 154 jmp _DualProcessCommandWrap ?fv154@FakeDispatcherBase@@EAGJXZ endp ?fv155@FakeDispatcherBase@@EAGJXZ proc push 155 jmp _DualProcessCommandWrap ?fv155@FakeDispatcherBase@@EAGJXZ endp ?fv156@FakeDispatcherBase@@EAGJXZ proc push 156 jmp _DualProcessCommandWrap ?fv156@FakeDispatcherBase@@EAGJXZ endp ?fv157@FakeDispatcherBase@@EAGJXZ proc push 157 jmp _DualProcessCommandWrap ?fv157@FakeDispatcherBase@@EAGJXZ endp ?fv158@FakeDispatcherBase@@EAGJXZ proc push 158 jmp _DualProcessCommandWrap ?fv158@FakeDispatcherBase@@EAGJXZ endp ?fv159@FakeDispatcherBase@@EAGJXZ proc push 159 jmp _DualProcessCommandWrap ?fv159@FakeDispatcherBase@@EAGJXZ endp ?fv160@FakeDispatcherBase@@EAGJXZ proc push 160 jmp _DualProcessCommandWrap ?fv160@FakeDispatcherBase@@EAGJXZ endp ?fv161@FakeDispatcherBase@@EAGJXZ proc push 161 jmp _DualProcessCommandWrap ?fv161@FakeDispatcherBase@@EAGJXZ endp ?fv162@FakeDispatcherBase@@EAGJXZ proc push 162 jmp _DualProcessCommandWrap ?fv162@FakeDispatcherBase@@EAGJXZ endp ?fv163@FakeDispatcherBase@@EAGJXZ proc push 163 jmp _DualProcessCommandWrap ?fv163@FakeDispatcherBase@@EAGJXZ endp ?fv164@FakeDispatcherBase@@EAGJXZ proc push 164 jmp _DualProcessCommandWrap ?fv164@FakeDispatcherBase@@EAGJXZ endp ?fv165@FakeDispatcherBase@@EAGJXZ proc push 165 jmp _DualProcessCommandWrap ?fv165@FakeDispatcherBase@@EAGJXZ endp ?fv166@FakeDispatcherBase@@EAGJXZ proc push 166 jmp _DualProcessCommandWrap ?fv166@FakeDispatcherBase@@EAGJXZ endp ?fv167@FakeDispatcherBase@@EAGJXZ proc push 167 jmp _DualProcessCommandWrap ?fv167@FakeDispatcherBase@@EAGJXZ endp ?fv168@FakeDispatcherBase@@EAGJXZ proc push 168 jmp _DualProcessCommandWrap ?fv168@FakeDispatcherBase@@EAGJXZ endp ?fv169@FakeDispatcherBase@@EAGJXZ proc push 169 jmp _DualProcessCommandWrap ?fv169@FakeDispatcherBase@@EAGJXZ endp ?fv170@FakeDispatcherBase@@EAGJXZ proc push 170 jmp _DualProcessCommandWrap ?fv170@FakeDispatcherBase@@EAGJXZ endp ?fv171@FakeDispatcherBase@@EAGJXZ proc push 171 jmp _DualProcessCommandWrap ?fv171@FakeDispatcherBase@@EAGJXZ endp ?fv172@FakeDispatcherBase@@EAGJXZ proc push 172 jmp _DualProcessCommandWrap ?fv172@FakeDispatcherBase@@EAGJXZ endp ?fv173@FakeDispatcherBase@@EAGJXZ proc push 173 jmp _DualProcessCommandWrap ?fv173@FakeDispatcherBase@@EAGJXZ endp ?fv174@FakeDispatcherBase@@EAGJXZ proc push 174 jmp _DualProcessCommandWrap ?fv174@FakeDispatcherBase@@EAGJXZ endp ?fv175@FakeDispatcherBase@@EAGJXZ proc push 175 jmp _DualProcessCommandWrap ?fv175@FakeDispatcherBase@@EAGJXZ endp ?fv176@FakeDispatcherBase@@EAGJXZ proc push 176 jmp _DualProcessCommandWrap ?fv176@FakeDispatcherBase@@EAGJXZ endp ?fv177@FakeDispatcherBase@@EAGJXZ proc push 177 jmp _DualProcessCommandWrap ?fv177@FakeDispatcherBase@@EAGJXZ endp ?fv178@FakeDispatcherBase@@EAGJXZ proc push 178 jmp _DualProcessCommandWrap ?fv178@FakeDispatcherBase@@EAGJXZ endp ?fv179@FakeDispatcherBase@@EAGJXZ proc push 179 jmp _DualProcessCommandWrap ?fv179@FakeDispatcherBase@@EAGJXZ endp ?fv180@FakeDispatcherBase@@EAGJXZ proc push 180 jmp _DualProcessCommandWrap ?fv180@FakeDispatcherBase@@EAGJXZ endp ?fv181@FakeDispatcherBase@@EAGJXZ proc push 181 jmp _DualProcessCommandWrap ?fv181@FakeDispatcherBase@@EAGJXZ endp ?fv182@FakeDispatcherBase@@EAGJXZ proc push 182 jmp _DualProcessCommandWrap ?fv182@FakeDispatcherBase@@EAGJXZ endp ?fv183@FakeDispatcherBase@@EAGJXZ proc push 183 jmp _DualProcessCommandWrap ?fv183@FakeDispatcherBase@@EAGJXZ endp ?fv184@FakeDispatcherBase@@EAGJXZ proc push 184 jmp _DualProcessCommandWrap ?fv184@FakeDispatcherBase@@EAGJXZ endp ?fv185@FakeDispatcherBase@@EAGJXZ proc push 185 jmp _DualProcessCommandWrap ?fv185@FakeDispatcherBase@@EAGJXZ endp ?fv186@FakeDispatcherBase@@EAGJXZ proc push 186 jmp _DualProcessCommandWrap ?fv186@FakeDispatcherBase@@EAGJXZ endp ?fv187@FakeDispatcherBase@@EAGJXZ proc push 187 jmp _DualProcessCommandWrap ?fv187@FakeDispatcherBase@@EAGJXZ endp ?fv188@FakeDispatcherBase@@EAGJXZ proc push 188 jmp _DualProcessCommandWrap ?fv188@FakeDispatcherBase@@EAGJXZ endp ?fv189@FakeDispatcherBase@@EAGJXZ proc push 189 jmp _DualProcessCommandWrap ?fv189@FakeDispatcherBase@@EAGJXZ endp ?fv190@FakeDispatcherBase@@EAGJXZ proc push 190 jmp _DualProcessCommandWrap ?fv190@FakeDispatcherBase@@EAGJXZ endp ?fv191@FakeDispatcherBase@@EAGJXZ proc push 191 jmp _DualProcessCommandWrap ?fv191@FakeDispatcherBase@@EAGJXZ endp ?fv192@FakeDispatcherBase@@EAGJXZ proc push 192 jmp _DualProcessCommandWrap ?fv192@FakeDispatcherBase@@EAGJXZ endp ?fv193@FakeDispatcherBase@@EAGJXZ proc push 193 jmp _DualProcessCommandWrap ?fv193@FakeDispatcherBase@@EAGJXZ endp ?fv194@FakeDispatcherBase@@EAGJXZ proc push 194 jmp _DualProcessCommandWrap ?fv194@FakeDispatcherBase@@EAGJXZ endp ?fv195@FakeDispatcherBase@@EAGJXZ proc push 195 jmp _DualProcessCommandWrap ?fv195@FakeDispatcherBase@@EAGJXZ endp ?fv196@FakeDispatcherBase@@EAGJXZ proc push 196 jmp _DualProcessCommandWrap ?fv196@FakeDispatcherBase@@EAGJXZ endp ?fv197@FakeDispatcherBase@@EAGJXZ proc push 197 jmp _DualProcessCommandWrap ?fv197@FakeDispatcherBase@@EAGJXZ endp ?fv198@FakeDispatcherBase@@EAGJXZ proc push 198 jmp _DualProcessCommandWrap ?fv198@FakeDispatcherBase@@EAGJXZ endp ?fv199@FakeDispatcherBase@@EAGJXZ proc push 199 jmp _DualProcessCommandWrap ?fv199@FakeDispatcherBase@@EAGJXZ endp end
zzhongster-wxtlactivex
ffactivex/FakeDispatcherBase.asm
Assembly
mpl11
32,722
/* ***** 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); } };
zzhongster-wxtlactivex
ffactivex/scriptable.h
C++
mpl11
4,934
/* ***** 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_) { } };
zzhongster-wxtlactivex
ffactivex/Host.h
C++
mpl11
2,241
/* ***** 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; }
zzhongster-wxtlactivex
ffactivex/scriptable.cpp
C++
mpl11
13,344
/* ***** 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; }
zzhongster-wxtlactivex
ffactivex/dllmain.cpp
C++
mpl11
7,451
/* ***** 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; }
zzhongster-wxtlactivex
ffactivex/NPSafeArray.cpp
C++
mpl11
8,634
/* ***** 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; } }
zzhongster-wxtlactivex
ffactivex/variants.cpp
C++
mpl11
11,038
/* ***** 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 ***** */ #pragma once #include "npapi.h" #include <npfunctions.h> #include <prtypes.h> #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <atlbase.h> #include <atlstr.h> #include <atlcom.h> #include <atlctl.h> #include <varargs.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; //#define NO_REGISTRY_AUTHORIZE #define np_log(instance, level, message, ...) log_activex_logging(instance, level, __FILE__, __LINE__, message, ##__VA_ARGS__) // For catch breakpoints. HRESULT NotImpl(); #define LogNotImplemented(instance) (np_log(instance, 0, "Not Implemented operation!!"), NotImpl()) void log_activex_logging(NPP instance, unsigned int level, const char* file, int line, char *message, ...); NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved); NPError NPP_Destroy(NPP instance, NPSavedData **save); NPError NPP_SetWindow(NPP instance, NPWindow *window); #define REGISTER_MANAGER
zzhongster-wxtlactivex
ffactivex/npactivex.h
C
mpl11
2,994
/* ***** 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); };
zzhongster-wxtlactivex
ffactivex/NPSafeArray.h
C++
mpl11
3,324
/* ***** 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 struct ITypeInfo; void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance); void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance); size_t VariantSize(VARTYPE vt); HRESULT ConvertVariantToGivenType(ITypeInfo *baseType, const TYPEDESC &vt, const VARIANT &var, LPVOID dest); void RawTypeToVariant(const TYPEDESC &desc, LPVOID source, VARIANT* var);
zzhongster-wxtlactivex
ffactivex/variants.h
C
mpl11
2,086
/* ***** 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; };
zzhongster-wxtlactivex
ffactivex/HTMLDocumentContainer.h
C++
mpl11
17,424
/* ***** 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); };
zzhongster-wxtlactivex
ffactivex/GenericNPObject.h
C++
mpl11
5,100
#pragma once // The following macros define the minimum required platform. The minimum required platform // is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run // your application. The macros work by enabling all features available on platform versions up to and // including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. #ifndef WINVER // Specifies that the minimum required platform is Windows Vista. #define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. #define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. #define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. #endif #ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. #define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. #endif
zzhongster-wxtlactivex
ffactivex/targetver.h
C
mpl11
1,428
/* ***** 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); }
zzhongster-wxtlactivex
ffactivex/FakeDispatcher.cpp
C++
mpl11
14,420
// 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; };
zzhongster-wxtlactivex
ffactivex/FakeDispatcherBase.h
C++
mpl11
7,671
/* -*- 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; }
zzhongster-wxtlactivex
ffactivex/common/ItemContainer.cpp
C++
mpl11
4,191
/* -*- 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
zzhongster-wxtlactivex
ffactivex/common/ControlEventSink.h
C++
mpl11
4,288
/* -*- 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
zzhongster-wxtlactivex
ffactivex/common/IOleCommandTargetImpl.h
C++
mpl11
10,589
/* -*- 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; }
zzhongster-wxtlactivex
ffactivex/common/ControlSite.cpp
C++
mpl11
45,015
/* -*- 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
zzhongster-wxtlactivex
ffactivex/common/PropertyList.h
C++
mpl11
5,004
/* -*- 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); }
zzhongster-wxtlactivex
ffactivex/common/ControlEventSink.cpp
C++
mpl11
9,226
/* -*- 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; }
zzhongster-wxtlactivex
ffactivex/common/ControlSiteIPFrame.cpp
C++
mpl11
4,135
/* -*- 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
zzhongster-wxtlactivex
ffactivex/common/ItemContainer.h
C++
mpl11
3,631
/* -*- 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
zzhongster-wxtlactivex
ffactivex/common/ControlSite.h
C++
mpl11
18,194
/* -*- 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; }
zzhongster-wxtlactivex
ffactivex/common/PropertyBag.cpp
C++
mpl11
3,426
/* -*- 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
zzhongster-wxtlactivex
ffactivex/common/ControlSiteIPFrame.h
C++
mpl11
3,891
/* -*- 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
zzhongster-wxtlactivex
ffactivex/common/PropertyBag.h
C++
mpl11
2,769
/* -*- 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)
zzhongster-wxtlactivex
ffactivex/common/StdAfx.h
C++
mpl11
4,966
/* ***** 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 ***** */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit #include <atlbase.h> #include <atlstr.h> // TODO: reference additional headers your program requires here
zzhongster-wxtlactivex
ffactivex/stdafx.h
C
mpl11
2,250
/* ***** 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); };
zzhongster-wxtlactivex
ffactivex/ObjectManager.h
C++
mpl11
2,783
/* ***** 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; } };
zzhongster-wxtlactivex
ffactivex/objectProxy.h
C++
mpl11
2,216
<html> <head> <script> function stringHash(str) { var hash = 0; if (str.length == 0) return hash; for (var i = 0; i < str.length; i++) { ch = str.charCodeAt(i); hash = ((hash << 5) - hash) + ch; hash = hash & hash; // Convert to 32bit integer } return hash; } function compute() { result.innerText = stringHash(text.value); } </script> </head> <body> <textarea id="text" style="width: 700px; height:500px; margin:auto"></textarea> <div id="result"></div> <button onclick="compute()">Compute</button> </body> </html>
zzhongster-wxtlactivex
web/stringhash.html
HTML
mpl11
672
<?php function load() { $postData = ''; foreach ($_POST as $key => $value) { $value = urlencode(stripslashes($value)); $postData .= "&$key=$value"; } $postData = substr($postData, 1); if (!isset($_POST['item_number']) || $_POST['item_number'] != 'npax') { echo 'Not relevant item'; return; } chdir('../../donation-dir'); echo exec('paypal.bat "' . $postData . '"'); } load(); ?>
zzhongster-wxtlactivex
web/paypal.php
PHP
mpl11
430
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta> <style> .line { clear: both; margin: 4px 0px; } .item { margin: 4px 3px; float: left; } </style> <script> var link = "https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn" var text = '在Chrome中直接使用各类网银、快播等ActiveX控件,无需使用IE Tab等IE内核插件!数万用户的实践验证!点击链接下载'; </script> </head> <body> <div id="header" style="height:100px"> </div> <div class="line"> <!-- Place this tag where you want the +1 button to render --> <g:plusone annotation="inline" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn"></g:plusone> <!-- Place this render call where appropriate --> <script type="text/javascript"> (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); </script> </div> <div class="line"> <div class="item"> <script type="text/javascript" charset="utf-8"> (function(){ var _w = 106 , _h = 24; var param = { url:link, type:'5', count:'', /**是否显示分享数,1显示(可选)*/ appkey:'', /**您申请的应用appkey,显示分享来源(可选)*/ title:text, pic:'', /**分享图片的路径(可选)*/ ralateUid:'2356524070', /**关联用户的UID,分享微博会@该用户(可选)*/ language:'zh_cn', /**设置语言,zh_cn|zh_tw(可选)*/ rnd:new Date().valueOf() } var temp = []; for( var p in param ){ temp.push(p + '=' + encodeURIComponent( param[p] || '' ) ) } document.write('<iframe allowTransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?' + temp.join('&') + '" width="'+ _w+'" height="'+_h+'"></iframe>') })() </script> </div> <div class="item"> <a name="xn_share" type="button_count_right" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn/">分享到人人</a><script src="http://static.connect.renren.com/js/share.js" type="text/javascript"></script></div> <div class="item"> <a href="javascript:void(0)" onclick="postToWb();return false;" class="tmblog"><img src="http://v.t.qq.com/share/images/s/b24.png" border="0" alt="转播到腾讯微博" ></a><script type="text/javascript"> function postToWb(){ var _url = encodeURIComponent(link); var _assname = encodeURI("");//你注册的帐号,不是昵称 var _appkey = encodeURI("");//你从腾讯获得的appkey var _pic = encodeURI('');//(例如:var _pic='图片url1|图片url2|图片url3....) var _t = '';//标题和描述信息 var metainfo = document.getElementsByTagName("meta"); for(var metai = 0;metai < metainfo.length;metai++){ if((new RegExp('description','gi')).test(metainfo[metai].getAttribute("name"))){ _t = metainfo[metai].attributes["content"].value; } } _t = text; if(_t.length > 120){ _t= _t.substr(0,117)+'...'; } _t = encodeURI(_t); var _u = 'http://share.v.t.qq.com/index.php?c=share&a=index&url='+_url+'&appkey='+_appkey+'&pic='+_pic+'&assname='+_assname+'&title='+_t; window.open( _u,'', 'width=700, height=680, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no' ); } </script> </div> </div> <div id="footer" style="height:100px;clear:both"> </div> </body> </html>
zzhongster-wxtlactivex
web/share.html
HTML
mpl11
3,718
<?php function load() { header('Content-Type: text/text; charset=GBK'); $code = $_GET['code']; if ($code == "") { header('Location: https://oauth.taobao.com/authorize?response_type=code&redirect_uri=http://eagleonhill.oicp.net/editor/taobao.php&client_id=21134472'); } else { chdir('../../donation-dir'); echo passthru('taobao.bat "' . $code . '"'); } } load(); ?>
zzhongster-wxtlactivex
web/taobao.php
PHP
mpl11
400
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. List.types.input = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<input></input>').addClass('valinput'); this.label = $('<span></span>').addClass('valdisp'); this.label.click(function(e) { setTimeout(function(){ input.focus(); }, 10); }); this.input.focus(function(e) { input.select(); }); this.input.keypress(function(e) { p.trigger('change'); }); this.input.keyup(function(e) { p.trigger('change'); }); this.input.change(function(e) { p.trigger('change'); }); p.append(this.input).append(this.label); }; List.types.input.prototype.__defineSetter__('value', function(val) { this.input.val(val); this.label.text(val); }); List.types.input.prototype.__defineGetter__('value', function() { return this.input.val(); }); List.types.select = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<select></select>').addClass('valinput'); this.label = $('<span></span>').addClass('valdisp'); if (prop.option == 'static') { this.loadOptions(prop.options); } var select = this; this.input.change(function(e) { if (p.hasClass('readonly')) { select.value = select.lastval; } else { p.trigger('change'); } }); this.label.click(function(e) { setTimeout(function(){ input.focus(); }, 10); }); p.append(this.input).append(this.label); }; List.types.select.prototype.loadOptions = function(options) { this.options = options; this.mapping = {}; this.input.html(""); for (var i = 0; i < options.length; ++i) { this.mapping[options[i].value] = options[i].text; var o = $('<option></option>').val(options[i].value).text(options[i].text) this.input.append(o); } } List.types.select.prototype.__defineGetter__('value', function() { return this.input.val(); }); List.types.select.prototype.__defineSetter__('value', function(val) { this.lastval = val; this.input.val(val); this.label.text(this.mapping[val]); }); List.types.checkbox = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<input type="checkbox">').addClass('valcheck'); var box = this; this.input.change(function(e) { if (p.hasClass('readonly')) { box.value = box.lastval; } else { p.trigger('change'); } }); p.append(this.input); }; List.types.checkbox.prototype.__defineGetter__('value', function() { return this.input[0].checked; }); List.types.checkbox.prototype.__defineSetter__('value', function(val) { this.lastval = val; this.input[0].checked = val; }); List.types.button = function(p, prop) { p[0].listdata = this; this.p = p; var input = this.input = $('<button>'); if (prop.caption) { input.text(prop.caption); } input.click(function(e) { p.trigger('command'); return false; }); p.append(this.input); }; List.types.button.prototype.__defineGetter__('value', function() { return undefined; });
zzhongster-wxtlactivex
web/listtypes.js
JavaScript
mpl11
3,295
.itemline.newline:not(.editing) { display:none; } .list { width: 100%; height: 520px; } div[property=title] { width: 200px } div[property=type] { width: 60px } div[property=value] { width: 240px } div[property=enabled] { width: 60px } div[property=userAgent] { width: 70px } div[property=script] { width: 200px } div[property=description] { width: 300px } div[property=url] { width: 300px } div[property=compute], div[property=compute] button{ width: 80px } div[property=checksum] { width: 80px } [property=status] button { width: 70px; } #scriptEditor { display: block; width: 100%; height: 361px; }
zzhongster-wxtlactivex
web/editor.css
CSS
mpl11
694
.list { width: 800px; height: 400px; font-family: Arial, sans-serif; overflow-x: hidden; border: 3px solid #0D5995; background-color: #0D5995; padding: 1px; padding-top: 10px; border-top-left-radius: 15px; border-top-right-radius: 15px; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; } .listscroll { overflow-x: scroll; overflow-y: scroll; background-color: white; } .listitems { display: inline-block; } .listvalue, .header { display: inline-block; width: 80px; margin: 0px 6px; } .headers { background-color: transparent; position: relative; white-space: nowrap; display: inline-block; color:white; padding: 5px 0px; } .header{ white-space: normal; } .itemline { height: 32px; } .itemline:nth-child(odd) { background-color: white; } .itemline:nth-child(even) { background-color: whitesmoke; } .itemline.selected { background-color: #aaa; } .itemline:hover { background-color: #bbcee9 } .itemline.error, .itemline.error:hover { background-color: salmon; } .itemline > div { white-space: nowrap; padding: 4px 0px 0 0; } .itemline.editing > div{ padding: 3px 0px 0 0; } .valdisp, .valinput { background-color: transparent; width: 100%; display: block; } .listvalue { overflow-x: hidden; } .itemline.editing .listvalue:not(.readonly) .valdisp { display: none; } .valdisp { font-size: 13px; } .itemline:not(.editing) .valinput, .listvalue.readonly .valinput { display: none; } .itemline :focus { outline: none; } .valinput { border:1px solid #aaa; background-color: white; padding: 3px; margin: 0; } .itemline .valinput:focus { outline-color: rgba(0, 128, 256, 0.5); outline: 5px auto rgba(0, 128, 256, 0.5); }
zzhongster-wxtlactivex
web/list.css
CSS
mpl11
1,865
<html> <head> <link rel="stylesheet" type="text/css" href="list.css" /> <link rel="stylesheet" type="text/css" href="editor.css" /> <link type="text/css" href="jquery-ui-1.8.17.custom.css" rel="stylesheet" /> <script src="jquery-1.7.min.js"></script> <script src="jquery-ui-1.8.17.custom.min.js"></script> <script src="list.js"></script> <script src="listtypes.js"></script> <script src="editor.js"></script> </head> <body> <div id="tabs"> <ul> <li><a href="#rules">Rules</a></li> <li><a href="#scripts">Scripts</a></li> <li><a href="#issues">Issues</a></li> </ul> <div id="rules"> <div id="ruleTable"> </div> <div> <button id="addRule">Add</button> <button id="deleteRule">Delete</button> <button class="doSave">Save</button> </div> </div> <div id="scripts"> <div id="scriptTable"> </div> <div> <button id="addScript">Add</button> <button id="deleteScript">Delete</button> <button class="doSave">Save</button> </div> </div> <div id="issues"> <div id="issueTable"> </div> <div> <button id="addIssue">Add</button> <button id="deleteIssue">Delete</button> <button class="doSave">Save</button> </div> </div> </div> <div id="scriptDialog"> <textarea id="scriptEditor"></textarea> </div> </body> </html>
zzhongster-wxtlactivex
web/editor.html
HTML
mpl11
1,570
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. var baseDir = '/setting/'; var rules = []; var scripts = []; var issues = []; var dirty = false; function setScriptAutoComplete(e) { var last = /[^\s]*$/; var obj = $('input', e.target); $(obj).bind("keydown", function(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { event.preventDefault(); } }) .autocomplete({ minLength: 0, source: function(request, response) { // delegate back to autocomplete, but extract the last term response($.ui.autocomplete.filter( scriptItems, last.exec(request.term)[0])); }, focus: function() { // prevent value inserted on focus return false; }, select: function(event, ui) { this.value = this.value.replace(last, ui.item.value); return false; } }); } var ruleProps = [ { header: "Identifier", property: "identifier", type: "input" }, { header: "Name", property: "title", type: "input" }, { header: "Mode", property: "type", type: "select", option: "static", options: [ {value: "wild", text: "WildChar"}, {value: "regex", text: "RegEx"}, {value: "clsid", text: "CLSID"} ] }, { header: "Pattern", property: "value", type: "input" }, { header: "Keyword", property: "keyword", type: "input" }, { header: "testURL", property: "testUrl", type: "input" }, { header: "UserAgent", property: "userAgent", type: "select", option: "static", options: [ {value: "", text: "Chrome"}, {value: "ie9", text: "MSIE9"}, {value: "ie8", text: "MSIE8"}, {value: "ie7", text: "MSIE7"}, {value: "ff7win", text: "Firefox 7 Windows"}, {value: "ff7mac", text: "Firefox 7 Mac"}, {value: "ip5", text: "iPhone"}, {value: "ipad5", text: "iPad"} ] }, { header: "Helper Script", property: "script", type: "input", events: { create: setScriptAutoComplete } }]; var currentScript = -1; function showScript(id) { var url = baseDir + scripts[id].url; currentScript = id; $(scriptEditor).val(''); $.ajax(url, { success: function(value) { origScript = value; $(scriptEditor).val(value); } }); $('#scriptDialog').dialog('open'); } function saveToFile(file, value) { $.ajax(baseDir + 'upload.php', { type: "POST", data: { file: file, data: value } }); } var origScript; function saveScript(id) { var value = $('#scriptEditor').val(); if (value == origScript) { return; } var file = scripts[id].url; scriptList.updateLine(scriptList.getLine(id)); saveToFile(file, value); dirty = true; } var scriptProps = [{ property: "identifier", header: "Identifier", type: "input" }, { property: "url", header: "URL", type: "input" }, { property: "context", header: "Context", type: "select", option: "static", options: [ {value: "page", text: "Page"}, {value: "extension", text: "Extension"} ] }, { property: "show", header: "Show", type: "button", events: { create: function(e) { $('button', this).text('Show'); }, command: function(e) { showScript(Number(e.data.line.attr('row')), true); } } }]; var issueProps = [{ header: "Identifier", property: "identifier", type: "input" }, { header: "Mode", property: "type", type: "select", option: "static", options: [ {value: "wild", text: "WildChar"}, {value: "regex", text: "RegEx"}, {value: "clsid", text: "CLSID"} ] }, { header: "Pattern", property: "value", type: "input" }, { header: "Description", property: "description", type: "input" }, { header: "IssueId", property: "issueId", type: "input" }, { header: "url", property: "url", type: "input" }]; // The JSON formatter is from http://joncom.be/code/javascript-json-formatter/ function FormatJSON(oData, sIndent) { function RealTypeOf(v) { if (typeof(v) == "object") { if (v === null) return "null"; if (v.constructor == Array) return "array"; if (v.constructor == Date) return "date"; if (v.constructor == RegExp) return "regex"; return "object"; } return typeof(v); } if (arguments.length < 2) { var sIndent = ""; } var sIndentStyle = " "; var sDataType = RealTypeOf(oData); // open object if (sDataType == "array") { if (oData.length == 0) { return "[]"; } var sHTML = "["; } else { var iCount = 0; $.each(oData, function() { iCount++; return; }); if (iCount == 0) { // object is empty return "{}"; } var sHTML = "{"; } // loop through items var iCount = 0; $.each(oData, function(sKey, vValue) { if (iCount > 0) { sHTML += ","; } if (sDataType == "array") { sHTML += ("\n" + sIndent + sIndentStyle); } else { sHTML += ("\n" + sIndent + sIndentStyle + "\"" + sKey + "\"" + ": "); } // display relevant data type switch (RealTypeOf(vValue)) { case "array": case "object": sHTML += FormatJSON(vValue, (sIndent + sIndentStyle)); break; case "boolean": case "number": sHTML += vValue.toString(); break; case "null": sHTML += "null"; break; case "string": sHTML += ("\"" + vValue + "\""); break; default: sHTML += JSON.stringify(vValue); } // loop iCount++; }); // close object if (sDataType == "array") { sHTML += ("\n" + sIndent + "]"); } else { sHTML += ("\n" + sIndent + "}"); } // return return sHTML; } function loadRules(value) { rules = []; for (var i in value) { rules.push(value[i]); } ruleList.refresh(); freezeIdentifier(ruleList); } function loadIssues(value) { issues = []; for (var i in value) { issues.push(value[i]); } issueList.refresh(); freezeIdentifier(issueList); } function loadScripts(value) { scripts = []; for (var i in value) { scripts.push(value[i]); } scriptList.refresh(); freezeIdentifier(scriptList); updateScriptItems(); } function serialize(list) { var obj = {}; for (var i = 0; i < list.length; ++i) { obj[list[i].identifier] = list[i]; } return FormatJSON(obj); } function save() { saveToFile('setting.json', serialize(rules)); saveToFile('scripts.json', serialize(scripts)); saveToFile('issues.json', serialize(issues)); dirty= false; freezeIdentifier(ruleList); freezeIdentifier(scriptList); } function reload() { $.ajax(baseDir + 'setting.json', { success: loadRules }); $.ajax(baseDir + 'scripts.json', { success: loadScripts }); $.ajax(baseDir + 'issues.json', { success: loadIssues }); dirty = false; } function freezeIdentifier(list) { $('.itemline:not(.newline) div[property=identifier]', list.contents) .addClass('readonly'); } var scriptList, ruleList, issueList; var scriptItems = []; function updateScriptItems() { scriptItems = []; for (var i = 0; i < scripts.length; ++i) { scriptItems.push(scripts[i].identifier); } } $(document).ready(function() { window.onbeforeunload=function() { if (dirty) { return 'Page not saved. Continue?'; } } $('#addRule').click(function() { ruleList.editNewLine(); }).button(); $('#deleteRule').click(function() { ruleList.remove(ruleList.selectedLine); }).button(); $('#addScript').click(function() { scriptList.editNewLine(); }).button(); $('#deleteScript').click(function() { scriptList.remove(scriptList.selectedLine); }).button(); $('#addIssue').click(function() { issueList.editNewLine(); }).button(); $('#deleteIssue').click(function() { issueList.remove(issueList.selectedLine); }).button(); $('.doSave').each(function() { $(this).click(save).button(); }); $('#tabs').tabs(); $('#scriptDialog').dialog({ modal: true, autoOpen: false, height: 500, width: 700, buttons: { "Save": function() { saveScript(currentScript); $(this).dialog('close'); }, "Cancel": function() { $(this).dialog('close'); } } }); $.ajaxSetup({ cache: false }); scriptList = new List({ props: scriptProps, main: $('#scriptTable'), getItems: function() {return scripts;} }); $(scriptList).bind('updated', function() { dirty = true; updateScriptItems(); }); scriptList.init(); ruleList = new List({ props: ruleProps, main: $('#ruleTable'), getItems: function() {return rules;} }); ruleList.init(); $(ruleList).bind('updated', function() { dirty = true; }); issueList = new List({ props: issueProps, main: $('#issueTable'), getItems: function() {return issues;} }); issueList.init(); $(issueList).bind('updated', function() { dirty = true; }); reload(); });
zzhongster-wxtlactivex
web/editor.js
JavaScript
mpl11
9,473
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved. // Use of this source code is governed by a Mozilla-1.1 license that can be // found in the LICENSE file. /* prop = { header, // String property, // String events, // type, // checkbox, select, input.type, button extra // depend on type } */ function List(config) { this.config = config; this.props = config.props; this.main = config.main; this.selectedLine = -2; this.lines = []; if (!config.getItems) { config.getItems = function() { return config.items; } } if (!config.getItemProp) { config.getItemProp = function(id, prop) { return config.getItem(id)[prop]; } } if (!config.setItemProp) { config.setItemProp = function(id, prop, value) { config.getItem(id)[prop] = value; } } if (!config.getItem) { config.getItem = function(id) { return config.getItems()[id]; } } if (!config.move) { config.move = function(a, b) { if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) { var list = config.getItems(); var tmp = list[a]; // remove a list.splice(a, 1); // insert b list.splice(b, 0, tmp); } } }; if (!config.insert) { config.insert = function(id, newItem) { config.getItems().splice(id, 0, newItem); } } if (!config.remove) { config.remove = function(a) { config.move(a, config.count() - 1); config.getItems().pop(); } } if (!config.validate) { config.validate = function() {return true;}; } if (!config.count) { config.count = function() { return config.getItems().length; } } if (!config.patch) { config.patch = function(id, newVal) { for (var name in newVal) { config.setItemProp(id, name, newVal[name]); } } } if (!config.defaultValue) { config.defaultValue = {}; } config.main.addClass('list'); } List.ids = { noline: -1, }; List.types = {}; List.prototype = { init: function() { with (this) { if (this.inited) { return; } this.inited = true; this.headergroup = $('<div class="headers"></div>'); for (var i = 0; i < props.length; ++i) { var header = $('<div class="header"></div>'). attr('property', props[i].property).html(props[i].header); headergroup.append(header); } this.scrolls = $('<div>').addClass('listscroll'); this.contents = $('<div class="listitems"></div>').appendTo(scrolls); scrolls.scroll(function() { headergroup.css('left', -(scrolls.scrollLeft()) + 'px'); }); contents.click(function(e) { if (e.target == contents[0]) { selectLine(List.ids.noline); } }); $(main).append(headergroup).append(scrolls); var height = this.main.height() - this.headergroup.outerHeight(); this.scrolls.height(height); load(); selectLine(List.ids.noline); } }, editNewLine: function() { this.startEdit(this.lines[this.lines.length - 1]); }, updatePropDisplay : function(line, prop) { var name = prop.property; obj = $('[property=' + name + ']', line); var ctrl = obj[0].listdata; var id = Number(line.attr('row')); if (id == this.config.count()) { var value = this.config.defaultValue[name]; if (value) { ctrl.value = value; } obj.trigger('createNew'); } else { ctrl.value = this.config.getItemProp(id, name); obj.trigger('update'); } }, updateLine: function(line) { for (var i = 0; i < this.props.length; ++i) { this.updatePropDisplay(line, this.props[i]); } if (Number(line.attr('row')) < this.config.count()) { line.trigger('update'); } else { line.addClass('newline'); } }, createLine: function() { with (this) { var line = $('<div></div>').addClass('itemline'); var inner = $('<div>'); line.append(inner); // create input boxes for (var i = 0; i < props.length; ++i) { var prop = props[i]; var ctrl = $('<div></div>').attr('property', prop.property) .addClass('listvalue').attr('tabindex', -1); var valueobj = new List.types[prop.type](ctrl, prop); var data = {list: this, line: line, prop: prop}; for (var e in prop.events) { ctrl.bind(e, data, prop.events[e]); } ctrl.bind('change', function(e) { validate(line); return true; }); ctrl.bind('keyup', function(e) { if (e.keyCode == 27) { cancelEdit(line); } }); ctrl.trigger('create'); inner.append(ctrl); } // Event listeners line.click(function(e) { startEdit(line); }); line.focusin(function(e) { startEdit(line); }); line.focusout(function(e) { finishEdit(line); }); for (var e in this.config.lineEvents) { line.bind(e, {list: this, line: line}, this.config.lineEvents[e]); } var list = this; line.bind('updating', function() { $(list).trigger('updating'); }); line.bind('updated', function() { $(list).trigger('updated'); }); this.bindId(line, this.lines.length); this.lines.push(line); line.appendTo(this.contents); return line; } }, refresh: function(lines) { var all = false; if (lines === undefined) { all = true; lines = []; } for (var i = this.lines.length; i <= this.config.count(); ++i) { var line = this.createLine(); lines.push(i); } while (this.lines.length > this.config.count() + 1) { this.lines.pop().remove(); } $('.newline', this.contents).removeClass('newline'); this.lines[this.lines.length - 1].addClass('newline'); if (all) { for (var i = 0; i < this.lines.length; ++i) { this.updateLine(this.lines[i]); } } else { for (var i = 0; i < lines.length; ++i) { this.updateLine(this.lines[lines[i]]); } } }, load: function() { this.contents.empty(); this.lines = []; this.refresh(); }, bindId: function(line, id) { line.attr('row', id); }, getLineNewValue: function(line) { var ret = {}; for (var i = 0; i < this.props.length; ++i) { this.getPropValue(line, ret, this.props[i]); } return ret; }, getPropValue: function(line, item, prop) { var name = prop.property; obj = $('[property=' + name + ']', line); var ctrl = obj[0].listdata; var value = ctrl.value; if (value !== undefined) { item[name] = value; } return value; }, startEdit: function(line) { if (line.hasClass('editing')) { return; } line.addClass('editing'); this.showLine(line); this.selectLine(line); var list = this; setTimeout(function() { if (!line[0].contains(document.activeElement)) { $('.valinput', line).first().focus(); } list.validate(line); }, 50); }, finishEdit: function(line) { var list = this; function doFinishEdit() { with(list) { if (line[0].contains(document.activeElement)) { return; } var valid = isValid(line); if (valid) { var id = Number(line.attr('row')); var newval = getLineNewValue(line); if (line.hasClass('newline')) { $(list).trigger('updating'); if(!config.insert(id, newval)) { line.removeClass('newline'); list.selectLine(line); $(list).trigger('add', id); addNewLine(); } } else { line.trigger('updating'); config.patch(id, newval); } line.trigger('updated'); } cancelEdit(line); } }; setTimeout(doFinishEdit, 50); }, cancelEdit: function(line) { line.removeClass('editing'); line.removeClass('error'); var id = Number(line.attr('row')); if (id == this.config.count() && this.selectedLine == id) { this.selectedLine = List.ids.noline; } this.updateLine(line); }, addNewLine: function() { with(this) { var line = $('.newline', contents); if (!line.length) { line = createLine().addClass('newline'); } return line; } }, isValid: function(line) { var id = Number(line.attr('row')); var obj = this.getLineNewValue(line); return valid = this.config.validate(id, obj); }, validate: function(line) { if (this.isValid(line)) { line.removeClass('error'); } else { line.addClass('error'); } }, move: function(a, b, keepSelect) { var len = this.config.count(); if (a == b || a < 0 || b < 0 || a >= len || b >= len) { return; } this.config.move(a, b); for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) { this.updateLine(this.getLine(i)); } if (keepSelect) { if (this.selectedLine == a) { this.selectLine(b); } else if (this.selectedLine == b) { this.selectLine(a); } } }, getLine: function(id) { if (id < 0 || id >= this.lines.length) { return null; } return this.lines[id]; }, remove: function(id) { id = Number(id); if (id < 0 || id >= this.config.count()) { return; } $(this).trigger('updating'); var len = this.lines.length; this.getLine(id).trigger('removing'); if (this.config.remove(id)) { return; } this.getLine(len - 1).remove(); this.lines.pop(); for (var i = id; i < len - 1; ++i) { this.updateLine(this.getLine(i)); } if (id >= len - 2) { this.selectLine(id); } else { this.selectLine(List.ids.noline); } $(this).trigger('updated'); }, selectLine: function(id) { var line = id; if (typeof id == "number") { line = this.getLine(id); } else { id = Number(line.attr('row')); } // Can't select the new line. if (line && line.hasClass('newline')) { line = null; id = List.ids.noline; } if (this.selectedLine == id) { return; } var oldline = this.getLine(this.selectedLine); if (oldline) { this.cancelEdit(oldline); oldline.removeClass('selected'); oldline.trigger('deselect'); this.selectedLine = List.ids.noline; } this.selectedLine = id; if (line != null) { line.addClass('selected'); line.trigger('select'); this.showLine(line); } $(this).trigger('select'); }, showLine: function(line) { var showtop = this.scrolls.scrollTop(); var showbottom = showtop + this.scrolls.height(); var top = line.offset().top - this.contents.offset().top; // Include the scroll bar var bottom = top + line.height() + 20; if (top < showtop) { // show at top this.scrolls.scrollTop(top); } else if (bottom > showbottom) { // show at bottom this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height())); } } };
zzhongster-wxtlactivex
web/list.js
JavaScript
mpl11
11,700
package com.example.pphotocapsule; import com.nhn.android.maps.NMapOverlay; import com.nhn.android.maps.NMapOverlayItem; import com.nhn.android.maps.NMapView; import com.nhn.android.mapviewer.overlay.NMapCalloutOverlay; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; public class NMapCalloutBasicOverlay extends NMapCalloutOverlay { private static final int CALLOUT_TEXT_PADDING_X = 10; private static final int CALLOUT_TEXT_PADDING_Y = 10; private static final int CALLOUT_TAG_WIDTH = 10; private static final int CALLOUT_TAG_HEIGHT = 10; private static final int CALLOUT_ROUND_RADIUS_X = 5; private static final int CALLOUT_ROUND_RADIUS_Y = 5; private final Paint mInnerPaint, mBorderPaint, mTextPaint; private final Path mPath; private float mOffsetX, mOffsetY; public NMapCalloutBasicOverlay(NMapOverlay itemOverlay, NMapOverlayItem item, Rect itemBounds) { super(itemOverlay, item, itemBounds); mInnerPaint = new Paint(); mInnerPaint.setARGB(225, 75, 75, 75); //gray mInnerPaint.setAntiAlias(true); mBorderPaint = new Paint(); mBorderPaint.setARGB(255, 255, 255, 255); mBorderPaint.setAntiAlias(true); mBorderPaint.setStyle(Style.STROKE); mBorderPaint.setStrokeWidth(2); mTextPaint = new Paint(); mTextPaint.setARGB(255, 255, 255, 255); mTextPaint.setAntiAlias(true); mPath = new Path(); mPath.setFillType(Path.FillType.WINDING); } @Override protected boolean isTitleTruncated() { return false; } @Override protected int getMarginX() { return 10; } @Override protected Rect getBounds(NMapView mapView) { adjustTextBounds(mapView); mTempRect.set((int)mTempRectF.left, (int)mTempRectF.top, (int)mTempRectF.right, (int)mTempRectF.bottom); mTempRect.union(mTempPoint.x, mTempPoint.y); return mTempRect; } @Override protected PointF getSclaingPivot() { PointF pivot = new PointF(); pivot.x = mTempRectF.centerX(); pivot.y = mTempRectF.bottom + CALLOUT_TAG_HEIGHT; return pivot; } @Override protected void drawCallout(Canvas canvas, NMapView mapView, boolean shadow, long when) { adjustTextBounds(mapView); stepAnimations(canvas, mapView, when); // Draw inner info window canvas.drawRoundRect(mTempRectF, CALLOUT_ROUND_RADIUS_X, CALLOUT_ROUND_RADIUS_Y, mInnerPaint); // Draw border for info window canvas.drawRoundRect(mTempRectF, CALLOUT_ROUND_RADIUS_X, CALLOUT_ROUND_RADIUS_Y, mBorderPaint); // Draw bottom tag if (CALLOUT_TAG_WIDTH > 0 && CALLOUT_TAG_HEIGHT > 0) { float x = mTempRectF.centerX(); float y = mTempRectF.bottom; Path path = mPath; path.reset(); path.moveTo(x - CALLOUT_TAG_WIDTH, y); path.lineTo(x, y + CALLOUT_TAG_HEIGHT); path.lineTo(x + CALLOUT_TAG_WIDTH, y); path.close(); canvas.drawPath(path, mInnerPaint); canvas.drawPath(path, mBorderPaint); } // Draw title canvas.drawText(mOverlayItem.getTitle(), mOffsetX, mOffsetY, mTextPaint); } /* Internal Functions */ private void adjustTextBounds(NMapView mapView) { // Determine the screen coordinates of the selected MapLocation mapView.getMapProjection().toPixels(mOverlayItem.getPointInUtmk(), mTempPoint); final String title = mOverlayItem.getTitle(); mTextPaint.getTextBounds(title, 0, title.length(), mTempRect); // Setup the callout with the appropriate size & location mTempRectF.set(mTempRect); mTempRectF.inset(-CALLOUT_TEXT_PADDING_X, -CALLOUT_TEXT_PADDING_Y); mOffsetX = mTempPoint.x - mTempRect.width() / 2; mOffsetY = mTempPoint.y - mTempRect.height() - mItemBounds.height() - CALLOUT_TEXT_PADDING_Y; mTempRectF.offset(mOffsetX, mOffsetY); } @Override protected Drawable getDrawable(int rank, int itemState) { // TODO Auto-generated method stub return null; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/NMapCalloutBasicOverlay.java
Java
epl
4,062
package com.example.pphotocapsule; import java.util.ArrayList; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.AdapterView.OnItemClickListener; public class AlbumActivity extends Activity { private Context mContext; GridView album_gridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_album); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+Environment.getExternalStorageDirectory()+"/Pictures/PhotoCapsule"))); mContext = this; final ImageAdapter ia = new ImageAdapter(this); album_gridView = (GridView)findViewById(R.id.album_gridView); album_gridView.setAdapter(ia); album_gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ia.callImageViewer(position); } }); } public class ImageAdapter extends BaseAdapter { private String imgData; private String geoData; private ArrayList<String> thumbsDataList; private ArrayList<String> thumbsIDList; ImageAdapter(Context c) { mContext = c; thumbsDataList = new ArrayList<String>(); thumbsIDList = new ArrayList<String>(); getThumbInfo(thumbsIDList, thumbsDataList); } public final void callImageViewer(int selectedIndex) { Intent intent_imagepopup = new Intent(mContext, MergeActivity.class); String imgPath = getImageInfo(imgData, geoData, thumbsIDList.get(selectedIndex)); intent_imagepopup.putExtra("filename", imgPath); startActivityForResult(intent_imagepopup, 1); } public boolean deleteSelected(int sIndex) { return true; } @Override public int getCount() { return thumbsIDList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(150, 150)); imageView.setAdjustViewBounds(false); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(5, 2, 2, 10); } else { imageView = (ImageView)convertView; } BitmapFactory.Options bo = new BitmapFactory.Options(); bo.inSampleSize = 8; Bitmap bmp = BitmapFactory.decodeFile(thumbsDataList.get(position), bo); Bitmap resized = Bitmap.createScaledBitmap(bmp, 150, 150, true); imageView.setImageBitmap(resized); imageView.setRotation(90); return imageView; } private void getThumbInfo(ArrayList<String> thumbsIDs, ArrayList<String> thumbsDatas){ String[] proj = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.SIZE}; Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, "bucket_display_name='PhotoCapsule'", null, null); if (imageCursor != null && imageCursor.moveToFirst()){ String thumbsID; String thumbsImageID; String thumbsData; String imgSize; int thumbsIDCol = imageCursor.getColumnIndex(MediaStore.Images.Media._ID); int thumbsDataCol = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA); int thumbsImageIDCol = imageCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); int thumbsSizeCol = imageCursor.getColumnIndex(MediaStore.Images.Media.SIZE); int num = 0; do { thumbsID = imageCursor.getString(thumbsIDCol); thumbsData = imageCursor.getString(thumbsDataCol); thumbsImageID = imageCursor.getString(thumbsImageIDCol); imgSize = imageCursor.getString(thumbsSizeCol); num++; if (thumbsImageID != null){ thumbsIDs.add(thumbsID); thumbsDatas.add(thumbsData); } }while (imageCursor.moveToNext()); imageCursor.close(); } return; } private String getImageInfo(String ImageData, String Location, String thumbID){ String imageDataPath = null; String[] proj = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.SIZE}; Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, "_ID=" + thumbID + "", null, null); if (imageCursor != null && imageCursor.moveToFirst()){ if (imageCursor.getCount() > 0){ int imgData = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA); imageDataPath = imageCursor.getString(imgData); } } imageCursor.close(); return imageDataPath; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.album, menu); return true; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/AlbumActivity.java
Java
epl
6,380
package com.example.pphotocapsule; import java.io.IOException; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.app.NotificationManager; import android.content.Intent; import android.database.Cursor; import android.view.Menu; public class SplashActivity extends Activity { public static Database db; static Cursor result = null; int check = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); // Cancel Notification nm.cancel(1234); db = new Database(this); try { db.createDataBase(); } catch (IOException e) { e.printStackTrace(); } db.openDataBase(); result = db.getExplanation(); if (result.moveToFirst()) check = result.getInt(0); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (check == 1) { Intent intent_main = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent_main); } else { Intent intent_intro = new Intent(SplashActivity.this, IntroActivity.class); startActivity(intent_intro); } finish(); } }, 4000); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.splash, menu); return true; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/SplashActivity.java
Java
epl
1,618
package com.example.pphotocapsule; import java.io.ByteArrayOutputStream; import java.io.IOException; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Bitmap.CompressFormat; import android.view.Menu; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; public class MergeActivity extends Activity { ImageView merge_imageView; ImageButton merge_imageButton_merge, merge_imageButton_location; Intent intent; String filename; private final int imgWidth = 480; private final int imgHeight = 500; public static byte[] image; public static Bitmap resized; public static Database db; static Cursor result = null; double mLat, mLong; String s; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_merge); db = new Database(this); try { db.createDataBase(); } catch (IOException e) { e.printStackTrace(); } db.openDataBase(); intent = getIntent(); filename = intent.getStringExtra("filename"); result = db.getInformationThroughFileName(filename); if(result.moveToFirst()){ mLat = result.getDouble(7); mLong = result.getDouble(8); s = result.getString(9); } BitmapFactory.Options bfo = new BitmapFactory.Options(); bfo.inSampleSize = 2; Bitmap bm = BitmapFactory.decodeFile(filename, bfo); resized = Bitmap.createScaledBitmap(bm, imgWidth, imgHeight, true); merge_imageView = (ImageView)findViewById(R.id.merge_imageView_photo); merge_imageView.setImageBitmap(resized); merge_imageView.setRotation(90); ByteArrayOutputStream stream = new ByteArrayOutputStream(); resized.compress(CompressFormat.JPEG, 100, stream); image = stream.toByteArray(); merge_imageButton_merge = (ImageButton)findViewById(R.id.merge_imageButton_merge); merge_imageButton_merge.setOnClickListener(imageButtonClickListener); merge_imageButton_location = (ImageButton)findViewById(R.id.merge_imageButton_location); merge_imageButton_location.setOnClickListener(imageButtonClickListener); } ImageButton.OnClickListener imageButtonClickListener = new ImageButton.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()) { case R.id.merge_imageButton_merge : db.updateRegisterMergedImageToOne(filename); Intent intent_nfc = new Intent(MergeActivity.this, NfcMergeImageActivity.class); startActivity(intent_nfc); break; case R.id.merge_imageButton_location : Intent intent_location = new Intent(MergeActivity.this, LocationActivity.class); intent_location.putExtra("lat", mLat); intent_location.putExtra("lng", mLong); intent_location.putExtra("s", s); startActivity(intent_location); break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.merge, menu); return true; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/MergeActivity.java
Java
epl
3,241
package com.example.pphotocapsule; import android.graphics.Bitmap; public class DivideImage { public static Bitmap croppedBmpLeft; public static Bitmap croppedBmpright; public void segmentImage(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int halfheight = height / 2; croppedBmpLeft = Bitmap.createBitmap(bitmap, 0, 0, width, halfheight); croppedBmpright = Bitmap.createBitmap(bitmap, 0, halfheight, width, halfheight); } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/DivideImage.java
Java
epl
498
package com.example.pphotocapsule; public class NMapPOIflagType { public static final int UNKNOWN = 0x0000; // Single POI icons private static final int SINGLE_POI_BASE = 0x0100; // Spot, Pin icons public static final int SPOT = SINGLE_POI_BASE + 1; public static final int PIN = SPOT + 1; // Direction POI icons: From, To private static final int DIRECTION_POI_BASE = 0x0200; public static final int FROM = DIRECTION_POI_BASE + 1; public static final int TO = FROM + 1; // end of single marker icon public static final int SINGLE_MARKER_END = 0x04FF; // Direction Number icons private static final int MAX_NUMBER_COUNT = 1000; public static final int NUMBER_BASE = 0x1000; // set NUMBER_BASE + 1 for '1' number public static final int NUMBER_END = NUMBER_BASE + MAX_NUMBER_COUNT; // Custom POI icons private static final int MAX_CUSTOM_COUNT = 1000; public static final int CUSTOM_BASE = NUMBER_END; public static final int CUSTOM_END = CUSTOM_BASE + MAX_CUSTOM_COUNT; // Clickable callout public static final int CLICKABLE_ARROW = CUSTOM_END + 1; public static boolean isBoundsCentered(int markerId) { boolean boundsCentered = false; switch (markerId) { default: if (markerId >= NMapPOIflagType.NUMBER_BASE && markerId < NMapPOIflagType.NUMBER_END) { boundsCentered = true; } break; } return boundsCentered; } public static int getMarkerId(int poiFlagType, int iconIndex) { int markerId = poiFlagType + iconIndex; return markerId; } public static int getPOIflagType(int markerId) { int poiFlagType = UNKNOWN; // Alphabet POI icons if (markerId >= NUMBER_BASE && markerId < NUMBER_END) { // Direction Number icons poiFlagType = NUMBER_BASE; } else if (markerId >= CUSTOM_BASE && markerId < CUSTOM_END) { // Custom POI icons poiFlagType = CUSTOM_BASE; } else if (markerId > SINGLE_POI_BASE) { poiFlagType = markerId; } return poiFlagType; } public static int getPOIflagIconIndex(int markerId) { int iconIndex = 0; if (markerId >= NUMBER_BASE && markerId < NUMBER_END) { // Direction Number icons iconIndex = markerId - (NUMBER_BASE + 1); } else if (markerId >= CUSTOM_BASE && markerId < CUSTOM_END) { // Custom POI icons iconIndex = markerId - (CUSTOM_BASE + 1); } else if (markerId > SINGLE_POI_BASE) { iconIndex = 0; } return iconIndex; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/NMapPOIflagType.java
Java
epl
2,450
package com.example.pphotocapsule; import java.io.IOException; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.CheckBox; import android.widget.ImageButton; public class IntroActivity extends Activity { public static Database db; ImageButton intro_imageButton_ok; CheckBox intro_checkBox_check; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intro); db = new Database(this); try { db.createDataBase(); } catch (IOException e) { e.printStackTrace(); } db.openDataBase(); intro_imageButton_ok = (ImageButton)findViewById(R.id.intro_imageButton_ok); intro_imageButton_ok.setOnClickListener(imageButtonClickListener); intro_checkBox_check = (CheckBox)findViewById(R.id.intro_checkBox_check); } ImageButton.OnClickListener imageButtonClickListener = new ImageButton.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.intro_imageButton_ok : if (intro_checkBox_check.isChecked()) db.updateExplanation(); Intent intent_main = new Intent(IntroActivity.this, MainActivity.class); startActivity(intent_main); finish(); break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.intro, menu); return true; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/IntroActivity.java
Java
epl
1,653
package com.example.pphotocapsule; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import android.app.Activity; import android.app.AlarmManager; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.view.Menu; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.DatePicker; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TimePicker; import android.widget.Toast; public class CameraActivity extends Activity implements LocationListener { public static final int MEDIA_TYPE_IMAGE = 1; private Camera mCamera; private CameraPreview mPreview; private ImageView camera_imageView_capture, camera_imageView_date, camera_imageView_send; private FrameLayout preview; private LinearLayout camera_linearlayout_capture, camera_linearlayout_date, camera_linearlayout_send; public static int mYear, mMonth, mDay; static final int DATE_DIALOG_ID = 0; public static String date; public static int mHour, mMinute; static final int TIME_DIALOG_ID = 1; public static byte[] photo; private Bitmap photo_bitmap; public static byte[] photo_left; public static byte[] photo_right; public static Bitmap photo_left_bitmap; public static Bitmap photo_right_bitmap; private LocationManager locationManager; private String bestProvider; public static String s = ""; public static double lat; public static double lng; public static String timeStamp; private AlarmManager alarmManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); mCamera = getCameraInstance(); mPreview = new CameraPreview(this); preview = (FrameLayout)findViewById(R.id.camera_framelayout); preview.addView(mPreview); camera_imageView_capture = (ImageView)findViewById(R.id.camera_imageView_capture); camera_imageView_capture.setOnClickListener(new ImageView.OnClickListener() { @Override public void onClick(View v) { mCamera.takePicture(new Camera.ShutterCallback() { @Override public void onShutter() { } }, null, mPicture); } }); final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); mHour = c.get(Calendar.HOUR_OF_DAY); mMinute = c.get(Calendar.MINUTE); camera_imageView_date = (ImageView)findViewById(R.id.camera_imageView_date); camera_imageView_date.setOnClickListener(new ImageView.OnClickListener() { @Override public void onClick(View v) { showDialog(DATE_DIALOG_ID); } }); camera_imageView_send = (ImageView)findViewById(R.id.camera_imageView_send); camera_imageView_send.setOnClickListener(new ImageView.OnClickListener() { @Override public void onClick(View v) { GregorianCalendar gregorianCalendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00")); gregorianCalendar.set(mYear, mMonth, mDay, mHour, mMinute, 00); Intent intent = new Intent(CameraActivity.this, AlarmedTimeShowActivity.class); PendingIntent pi = PendingIntent.getActivity(CameraActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, gregorianCalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi); Intent intent_nfc = new Intent(CameraActivity.this, NfcSendInformationActivity.class); startActivity(intent_nfc); } }); camera_linearlayout_capture = (LinearLayout)findViewById(R.id.camera_linearlayout_capture); camera_linearlayout_date = (LinearLayout)findViewById(R.id.camera_linearlayout_date); camera_linearlayout_send = (LinearLayout)findViewById(R.id.camera_linearlayout_send); locationManager = (LocationManager)getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); bestProvider = locationManager.getBestProvider(criteria, false); Location location = locationManager.getLastKnownLocation(bestProvider); if (location != null) { s += getAddress(location.getLatitude(), location.getLongitude()); lat = location.getLatitude(); lng = location.getLongitude(); } alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmManager.setTimeZone("GMT+09:00"); } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear + 1; mDay = dayOfMonth; date = mYear + "-" + mMonth + "-" + mDay; showDialog(TIME_DIALOG_ID); } }; private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { mHour = hourOfDay; mMinute = minute; camera_linearlayout_date.setVisibility(LinearLayout.INVISIBLE); camera_linearlayout_send.setVisibility(LinearLayout.VISIBLE); } }; @Override protected Dialog onCreateDialog(int id) { switch(id) { case DATE_DIALOG_ID : DatePickerDialog date = new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); DatePicker dp = date.getDatePicker(); Calendar cal = Calendar.getInstance(); cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); long time = cal.getTimeInMillis(); dp.setMinDate(time); return date; case TIME_DIALOG_ID : TimePickerDialog alarm = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, true); return alarm; } return null; } public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder mHolder; public CameraPreview(Context context) { super(context); mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { if(mHolder.getSurface() == null) { return; } try { mCamera.stopPreview(); } catch (Exception e) { } try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e) { e.getMessage(); } } @Override public void surfaceCreated(SurfaceHolder holder) { try { if (mCamera == null) { mCamera = getCameraInstance(); } mCamera.setDisplayOrientation(90); mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { e.getMessage(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { } } public static Camera getCameraInstance() { Camera c = null; try { c = Camera.open(); } catch(Exception e) { } return c; } @Override protected void onPause() { super.onPause(); releaseCamera(); } private void releaseCamera() { if (mCamera != null) { mCamera.release(); mCamera = null; } } @Override protected void onResume() { super.onResume(); if (!checkCameraHardware(this)) { finish(); } } private boolean checkCameraHardware(Context context) { if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) return true; else return false; } private PictureCallback mPicture = new PictureCallback() { @Override public void onPictureTaken(byte[] data, final Camera camera) { File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); if (pictureFile == null) { return; } photo = data; photo_bitmap = BitmapFactory.decodeByteArray(photo, 0, photo.length); DivideImage divide = new DivideImage(); divide.segmentImage(photo_bitmap); ByteArrayOutputStream stream = new ByteArrayOutputStream(); DivideImage.croppedBmpright.compress(CompressFormat.JPEG, 100, stream); photo_right = stream.toByteArray(); photo_right_bitmap = BitmapFactory.decodeByteArray(photo_right, 0, photo_right.length); ByteArrayOutputStream stream1 = new ByteArrayOutputStream(); DivideImage.croppedBmpLeft.compress(CompressFormat.JPEG, 100, stream1); photo_left = stream1.toByteArray(); photo_left_bitmap = BitmapFactory.decodeByteArray(photo_left, 0, photo_left.length); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { camera_linearlayout_capture.setVisibility(LinearLayout.INVISIBLE); camera_linearlayout_date.setVisibility(LinearLayout.VISIBLE); } }, 0); } }; public static File getOutputMediaFile(int type) { File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "PhotoCapsule"); if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { return null; } } timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; if(type == MEDIA_TYPE_IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } else { return null; } return mediaFile; } public String getAddress(double lat, double lon) { Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); String result = ""; List<Address> list; try { list = geocoder.getFromLocation(lat, lon, 1); if (list != null && list.size() > 0) { Address address = list.get(0); result = address.getAddressLine(0) + ", " + address.getLocality(); } } catch (IOException e) { e.printStackTrace(); } return result; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.camera, menu); return true; } @Override public void onLocationChanged(Location arg0) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/CameraActivity.java
Java
epl
11,732
package com.example.pphotocapsule; import java.util.Date; import java.util.Properties; import javax.activation.CommandMap; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.activation.MailcapCommandMap; import javax.mail.BodyPart; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class Mail extends javax.mail.Authenticator { private String _user; private String _pass; private String[] _to; private String _from; private String _port; private String _sport; private String _host; private String _subject; private String _body; private boolean _auth; private boolean _debuggable; private Multipart _multipart; public Mail() { _host = "smtp.gmail.com"; // default smtp server _port = "465"; // default smtp port; alternative is 587 _sport = "465"; // default socketfactory port; alternative is 587 _user = ""; // username _pass = ""; // password _from = ""; // email sent from _subject = ""; // email subject _body = ""; // email body _debuggable = false; // debug mode on or off - default off _auth = true; // smtp authentication - default on _multipart = new MimeMultipart(); // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); } public Mail(String user, String pass) { this(); _user = user; _pass = pass; } public boolean send() throws Exception { Properties props = _setProperties(); if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { Session session = Session.getInstance(props, this); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(_from)); InternetAddress[] addressTo = new InternetAddress[_to.length]; for (int i = 0; i < _to.length; i++) { addressTo[i] = new InternetAddress(_to[i]); } msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); msg.setSubject(_subject); msg.setSentDate(new Date()); // setup message body BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(_body); _multipart.addBodyPart(messageBodyPart); // Put parts in message msg.setContent(_multipart); // send email Transport.send(msg); return true; } else { return false; } } public void addAttachment(String filename) throws Exception { BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); _multipart.addBodyPart(messageBodyPart); } @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(_user, _pass); } private Properties _setProperties() { Properties props = new Properties(); props.put("mail.smtp.host", _host); if(_debuggable) { props.put("mail.debug", "true"); } if(_auth) { props.put("mail.smtp.auth", "true"); } props.put("mail.smtp.port", _port); props.put("mail.smtp.socketFactory.port", _sport); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); return props; } // the getters and setters public String getBody() { return _body; } public void setBody(String _body) { this._body = _body; } public void setTo(String[] toArr) { this._to = toArr; } public void setFrom(String string) { this._from = string; } public void setSubject(String string) { this._subject = string; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/Mail.java
Java
epl
4,866
package com.example.pphotocapsule; import java.io.ByteArrayOutputStream; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; public class ReceiveMergedImageActivity extends Activity { ImageView receive_merged_imageView_photo; ImageButton receive_merged_imagebutton_send; Intent intent; int result_intent; public static byte[] photo_byte; Bitmap photo_bit; Bitmap resized; private final int imgWidth = 480; private final int imgHeight = 500; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_receive_merged_image); receive_merged_imageView_photo = (ImageView)findViewById(R.id.receive_merged_imageView_photo); receive_merged_imageView_photo.setRotation(90); receive_merged_imagebutton_send = (ImageButton)findViewById(R.id.receive_merged_imagebutton_send); receive_merged_imagebutton_send.setOnClickListener(imageButtonClickListener); intent = getIntent(); result_intent = intent.getIntExtra("Receive", 0); if (result_intent == 1) { Intent intent_nfc_receive_mergedImage = new Intent(ReceiveMergedImageActivity.this, NfcReceiveMergedImageActivity.class); startActivity(intent_nfc_receive_mergedImage); } else if (result_intent == 2) { resized = Bitmap.createScaledBitmap(NfcMergeImageActivity.result_photo_bit, imgWidth, imgHeight, true); receive_merged_imageView_photo.setImageDrawable(new BitmapDrawable(getResources(), resized)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); resized.compress(CompressFormat.JPEG, 100, stream); photo_byte = stream.toByteArray(); } } ImageButton.OnClickListener imageButtonClickListener = new ImageButton.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()) { case R.id.receive_merged_imagebutton_send : Intent intent_nfc_receive_mergedImage = new Intent(ReceiveMergedImageActivity.this, NfcReceiveMergedImageActivity.class); startActivity(intent_nfc_receive_mergedImage); break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.receive_merged_image, menu); return true; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/ReceiveMergedImageActivity.java
Java
epl
2,622
package com.example.pphotocapsule; import android.graphics.Bitmap; import android.graphics.Canvas; public class MergeImage { public Bitmap mergedImage(Bitmap c, Bitmap s) { Bitmap cs = null; int width, height = 0; width = c.getWidth(); height = c.getHeight() + s.getHeight(); cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas comboImage = new Canvas(cs); comboImage.drawBitmap(c, 0f, 0f, null); comboImage.drawBitmap(s, 0f, c.getHeight(), null); return cs; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/MergeImage.java
Java
epl
549
package com.example.pphotocapsule; import android.graphics.Canvas; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.text.TextPaint; import android.text.TextUtils; import android.util.Log; import com.nhn.android.maps.NMapOverlay; import com.nhn.android.maps.NMapOverlayItem; import com.nhn.android.maps.NMapView; import com.nhn.android.mapviewer.overlay.NMapCalloutOverlay; import com.nhn.android.mapviewer.overlay.NMapResourceProvider; public class NMapCalloutCustomOldOverlay extends NMapCalloutOverlay { private static final String LOG_TAG = "NMapCalloutCustomOverlay"; private static final boolean DEBUG = false; private static final int CALLOUT_TEXT_COLOR = 0xFFFFFFFF; private static final float CALLOUT_TEXT_SIZE = 16.0F; private static final Typeface CALLOUT_TEXT_TYPEFACE = null;//Typeface.DEFAULT_BOLD; private static final float CALLOUT_RIGHT_BUTTON_WIDTH = 50.67F; private static final float CALLOUT_RIGHT_BUTTON_HEIGHT = 34.67F; private static final float CALLOUT_MARGIN_X = 9.33F; private static final float CALLOUT_PADDING_X = 9.33F; private static final float CALLOUT_PADDING_OFFSET = 0.45F; private static final float CALLOUT_PADDING_Y = 17.33F; private static final float CALLOUT_MIMIMUM_WIDTH = 63.33F; private static final float CALLOUT_TOTAL_HEIGHT = 64.0F; private static final float CALLOUT_BACKGROUND_HEIGHT = CALLOUT_PADDING_Y + CALLOUT_TEXT_SIZE + CALLOUT_PADDING_Y; private static final float CALLOUT_ITEM_GAP_Y = 0.0F; private static final float CALLOUT_TAIL_GAP_X = 6.67F; private static final float CALLOUT_TITLE_OFFSET_Y = -2.0F; private final TextPaint mTextPaint = new TextPaint(); private float mOffsetX, mOffsetY; private final float mMarginX; private final float mPaddingX, mPaddingY, mPaddingOffset; private final float mMinimumWidth; private final float mTotalHeight; private final float mBackgroundHeight; private final float mItemGapY; private final float mTailGapX; private final float mTitleOffsetY; private final Drawable mBackgroundDrawable; protected final Rect mTemp2Rect = new Rect(); private final Rect mRightButtonRect; private final String mRightButtonText; private final int mCalloutRightButtonWidth; private final int mCalloutRightButtonHeight; private Drawable[] mDrawableRightButton; private final int mCalloutButtonCount = 1; private String mTitleTruncated; private int mWidthTitleTruncated; private final String mTailText; private float mTailTextWidth; /** * Resource provider should implement this interface */ public static interface ResourceProvider { public Drawable getCalloutBackground(NMapOverlayItem item); public String getCalloutRightButtonText(NMapOverlayItem item); public Drawable[] getCalloutRightButton(NMapOverlayItem item); public Drawable[] getCalloutRightAccessory(NMapOverlayItem item); } public NMapCalloutCustomOldOverlay(NMapOverlay itemOverlay, NMapOverlayItem item, Rect itemBounds, NMapCalloutCustomOldOverlay.ResourceProvider resourceProvider) { super(itemOverlay, item, itemBounds); mTextPaint.setAntiAlias(true); // set font style mTextPaint.setColor(CALLOUT_TEXT_COLOR); // set font size mTextPaint.setTextSize(CALLOUT_TEXT_SIZE * NMapResourceProvider.getScaleFactor()); // set font type if (CALLOUT_TEXT_TYPEFACE != null) { mTextPaint.setTypeface(CALLOUT_TEXT_TYPEFACE); } mMarginX = NMapResourceProvider.toPixelFromDIP(CALLOUT_MARGIN_X); mPaddingX = NMapResourceProvider.toPixelFromDIP(CALLOUT_PADDING_X); mPaddingOffset = NMapResourceProvider.toPixelFromDIP(CALLOUT_PADDING_OFFSET); mPaddingY = NMapResourceProvider.toPixelFromDIP(CALLOUT_PADDING_Y); mMinimumWidth = NMapResourceProvider.toPixelFromDIP(CALLOUT_MIMIMUM_WIDTH); mTotalHeight = NMapResourceProvider.toPixelFromDIP(CALLOUT_TOTAL_HEIGHT); mBackgroundHeight = NMapResourceProvider.toPixelFromDIP(CALLOUT_BACKGROUND_HEIGHT); mItemGapY = NMapResourceProvider.toPixelFromDIP(CALLOUT_ITEM_GAP_Y); mTailGapX = NMapResourceProvider.toPixelFromDIP(CALLOUT_TAIL_GAP_X); mTailText = item.getTailText(); mTitleOffsetY = NMapResourceProvider.toPixelFromDIP(CALLOUT_TITLE_OFFSET_Y); if (resourceProvider == null) { throw new IllegalArgumentException( "NMapCalloutCustomOverlay.ResourceProvider should be provided on creation of NMapCalloutCustomOverlay."); } mBackgroundDrawable = resourceProvider.getCalloutBackground(item); boolean hasRightAccessory = false; mDrawableRightButton = resourceProvider.getCalloutRightAccessory(item); if (mDrawableRightButton != null && mDrawableRightButton.length > 0) { hasRightAccessory = true; mRightButtonText = null; } else { mDrawableRightButton = resourceProvider.getCalloutRightButton(item); mRightButtonText = resourceProvider.getCalloutRightButtonText(item); } if (mDrawableRightButton != null) { if (hasRightAccessory) { mCalloutRightButtonWidth = mDrawableRightButton[0].getIntrinsicWidth(); mCalloutRightButtonHeight = mDrawableRightButton[0].getIntrinsicHeight(); } else { mCalloutRightButtonWidth = NMapResourceProvider.toPixelFromDIP(CALLOUT_RIGHT_BUTTON_WIDTH); mCalloutRightButtonHeight = NMapResourceProvider.toPixelFromDIP(CALLOUT_RIGHT_BUTTON_HEIGHT); } mRightButtonRect = new Rect(); super.setItemCount(mCalloutButtonCount); } else { mCalloutRightButtonWidth = 0; mCalloutRightButtonHeight = 0; mRightButtonRect = null; } mTitleTruncated = null; mWidthTitleTruncated = 0; } @Override protected boolean hitTest(int hitX, int hitY) { // hit test for right button only ? // if (mRightButtonRect != null) { // return mRightButtonRect.contains(hitX, hitY); // } return super.hitTest(hitX, hitY); } @Override protected boolean isTitleTruncated() { return (mTitleTruncated != mOverlayItem.getTitle()); } @Override protected int getMarginX() { return (int)(mMarginX); } @Override protected Rect getBounds(NMapView mapView) { adjustTextBounds(mapView); mTempRect.set((int)mTempRectF.left, (int)mTempRectF.top, (int)mTempRectF.right, (int)mTempRectF.bottom); mTempRect.union(mTempPoint.x, mTempPoint.y); return mTempRect; } @Override protected PointF getSclaingPivot() { PointF pivot = new PointF(); pivot.x = mTempRectF.centerX(); pivot.y = mTempRectF.top + mTotalHeight; return pivot; } @Override protected void drawCallout(Canvas canvas, NMapView mapView, boolean shadow, long when) { adjustTextBounds(mapView); stepAnimations(canvas, mapView, when); drawBackground(canvas); float left, top; // draw title mOffsetX = mTempPoint.x - mTempRect.width() / 2; mOffsetX -= mPaddingOffset; mOffsetY = mTempRectF.top + mPaddingY + mTextPaint.getTextSize() + mTitleOffsetY; canvas.drawText(mTitleTruncated, mOffsetX, mOffsetY, mTextPaint); // draw right button if (mDrawableRightButton != null) { left = mTempRectF.right - mPaddingX - mCalloutRightButtonWidth; top = mTempRectF.top + (mBackgroundHeight - mCalloutRightButtonHeight) / 2; // Use background drawables depends on current state mRightButtonRect.left = (int)(left + 0.5F); mRightButtonRect.top = (int)(top + 0.5F); mRightButtonRect.right = (int)(left + mCalloutRightButtonWidth + 0.5F); mRightButtonRect.bottom = (int)(top + mCalloutRightButtonHeight + 0.5F); int itemState = super.getItemState(0); Drawable drawable = getDrawable(0, itemState); if (drawable != null) { drawable.setBounds(mRightButtonRect); drawable.draw(canvas); } if (mRightButtonText != null) { mTextPaint.getTextBounds(mRightButtonText, 0, mRightButtonText.length(), mTempRect); left = mRightButtonRect.left + (mCalloutRightButtonWidth - mTempRect.width()) / 2; top = mRightButtonRect.top + (mCalloutRightButtonHeight - mTempRect.height()) / 2 + mTempRect.height() + mTitleOffsetY; canvas.drawText(mRightButtonText, left, top, mTextPaint); } } // draw tail text if (mTailText != null) { if (mRightButtonRect != null) { left = mRightButtonRect.left; } else { left = mTempRectF.right; } left -= mPaddingX + mTailTextWidth; top = mOffsetY; canvas.drawText(mTailText, left, top, mTextPaint); } } /* Internal Functions */ private void drawBackground(Canvas canvas) { mTemp2Rect.left = (int)(mTempRectF.left + 0.5F); mTemp2Rect.top = (int)(mTempRectF.top + 0.5F); mTemp2Rect.right = (int)(mTempRectF.right + 0.5F); mTemp2Rect.bottom = (int)(mTempRectF.top + mTotalHeight + 0.5F); mBackgroundDrawable.setBounds(mTemp2Rect); mBackgroundDrawable.draw(canvas); } private void adjustTextBounds(NMapView mapView) { // First determine the screen coordinates of the selected MapLocation mapView.getMapProjection().toPixels(mOverlayItem.getPointInUtmk(), mTempPoint); int mapViewWidth = mapView.getMapController().getViewFrameVisibleWidth(); if (mTitleTruncated == null || mWidthTitleTruncated != mapViewWidth) { mWidthTitleTruncated = mapViewWidth; float maxWidth = mWidthTitleTruncated - 2 * mMarginX - 2 * mPaddingX; if (DEBUG) { Log.i(LOG_TAG, "adjustTextBounds: maxWidth=" + maxWidth + ", mMarginX=" + mMarginX + ", mPaddingX=" + mPaddingX); } if (mDrawableRightButton != null) { maxWidth -= mPaddingX + mCalloutRightButtonWidth; } if (mTailText != null) { mTextPaint.getTextBounds(mTailText, 0, mTailText.length(), mTempRect); mTailTextWidth = mTempRect.width(); maxWidth -= mTailGapX + mTailTextWidth; } final String title = TextUtils.ellipsize(mOverlayItem.getTitle(), mTextPaint, maxWidth, TextUtils.TruncateAt.END).toString(); mTitleTruncated = title; if (DEBUG) { Log.i(LOG_TAG, "adjustTextBounds: mTitleTruncated=" + mTitleTruncated + ", length=" + mTitleTruncated.length()); } } mTextPaint.getTextBounds(mTitleTruncated, 0, mTitleTruncated.length(), mTempRect); if (mDrawableRightButton != null) { mTempRect.right += mPaddingX + mCalloutRightButtonWidth; } if (mTailText != null) { mTempRect.right += mTailGapX + mTailTextWidth; } if (DEBUG) { Log.i(LOG_TAG, "adjustTextBounds: mTempRect.width=" + mTempRect.width() + ", mTempRect.height=" + mTempRect.height()); } // Setup the callout with the right size & location mTempRectF.set(mTempRect); final float dy = (mBackgroundHeight - mTempRect.height()) / 2; mTempRectF.inset(-mPaddingX, -dy); //mTempRectF.inset(-mPaddingX, -mPaddingY); // set minimum size if (mTempRectF.width() < mMinimumWidth) { final float dx = (mMinimumWidth - mTempRectF.width()) / 2; mTempRectF.inset(-dx, 0); } // set position float left = mTempPoint.x - (int)(mTempRectF.width() * mOverlayItem.getAnchorXRatio()); float top = mTempPoint.y - (int)(mItemBounds.height() * mOverlayItem.getAnchorYRatio()) - mItemGapY - mTotalHeight; mTempRectF.set(left, top, left + mTempRectF.width(), top + mTempRectF.height()); } @Override protected Drawable getDrawable(int rank, int itemState) { if (mDrawableRightButton != null && mDrawableRightButton.length >= 3) { int idxDrawable = 0; if (NMapOverlayItem.isPressedState(itemState)) { idxDrawable = 1; } else if (NMapOverlayItem.isSelectedState(itemState)) { idxDrawable = 2; } else if (NMapOverlayItem.isFocusedState(itemState)) { idxDrawable = 2; } Drawable drawable = mDrawableRightButton[idxDrawable]; return drawable; } return null; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/NMapCalloutCustomOldOverlay.java
Java
epl
11,924
package com.example.pphotocapsule; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; public class Database extends SQLiteOpenHelper { private static String DB_PATH = "/data/data/com.example.pphotocapsule/databases/"; private static String DB_NAME = "photocapsule.sqlite"; private SQLiteDatabase myDatabase; private final Context myContext; public Database(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; } public void createDataBase() throws IOException{ SQLiteDatabase checkDB = null; try{ String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); }catch(SQLiteException e){ } if(checkDB != null){ checkDB.close(); } boolean dbExist = checkDB != null? true : false; if(dbExist){ } else{ this.getReadableDatabase(); try{ InputStream myInput = myContext.getAssets().open(DB_NAME); String outFileName = DB_PATH + DB_NAME; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while((length = myInput.read(buffer)) > 0){ myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); myInput.close(); }catch(IOException e){ throw new Error("Error copying database"); } } } public void openDataBase(){ String myPath = DB_PATH + DB_NAME; myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); } public synchronized void close(){ if(myDatabase != null) myDatabase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public Cursor getExplanation() { Cursor c = myDatabase.rawQuery("SELECT checked FROM explanation WHERE id = 1;", null); if (c != null && c.getCount() != 0) c.moveToFirst(); return c; } public void updateExplanation() { myDatabase.execSQL("UPDATE explanation SET checked = 1 WHERE id = 1;"); } public void insertRegister(int mYear, int mMonth, int mDay, int mHour, int mMinute, double lat, double lng, String street) { myDatabase.execSQL("INSERT INTO register (year, month, date, hour, minute, latitude, longitude, street) VALUES ("+mYear+", "+mMonth+", "+mDay+", "+mHour+", "+mMinute+", " +lat+", "+lng+", '"+street+"');"); } public void insertRegisterNewImage(String fileName, int mYear, int mMonth, int mDay, int mHour, int mMinute, double lat, double lng, String street) { myDatabase.execSQL("INSERT INTO register (title, year, month, date, hour, minute, latitude, longitude, street) VALUES ('"+fileName+"', "+mYear+", "+mMonth+", "+mDay+", "+mHour+", "+mMinute+", " +lat+", "+lng+", '"+street+"');"); } public void updateRegister(int id, String filename) { myDatabase.execSQL("UPDATE register SET title = '"+filename+"' WHERE id = "+id+";"); } public void updateRegisterMergedImageToOne(String filename) { myDatabase.execSQL("UPDATE register SET mergedImage = 1 WHERE title = '"+filename+"';"); } public void updateRegisterMergedImageToZero(String filename) { myDatabase.execSQL("UPDATE register SET mergedImage = 0 WHERE title = '"+filename+"';"); } public Cursor getMaxId() { Cursor c = myDatabase.rawQuery("SELECT MAX(id) FROM register;", null); if (c != null && c.getCount() != 0) c.moveToFirst(); return c; } public Cursor getInformation(int id) { Cursor c = myDatabase.rawQuery("SELECT * FROM register WHERE id = "+ id + ";", null); if (c != null && c.getCount() != 0) c.moveToFirst(); return c; } public Cursor getInformationThroughFileName(String fileName) { Cursor c = myDatabase.rawQuery("SELECT * FROM register WHERE title = '"+ fileName + "';", null); if (c != null && c.getCount() != 0) c.moveToFirst(); return c; } public Cursor getFileName() { Cursor c = myDatabase.rawQuery("SELECT title FROM register WHERE mergedImage = 1;", null); if (c != null && c.getCount() != 0) c.moveToFirst(); return c; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/Database.java
Java
epl
4,551
package com.example.pphotocapsule; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Log; import android.widget.ImageView; import android.widget.ListView; import com.nhn.android.maps.NMapOverlayItem; import com.nhn.android.maps.overlay.NMapPOIitem; import com.nhn.android.mapviewer.overlay.NMapResourceProvider; public class NMapViewerResourceProvider extends NMapResourceProvider implements NMapCalloutCustomOldOverlay.ResourceProvider { private static final String LOG_TAG = "NMapViewerResourceProvider"; private static final boolean DEBUG = false; private static final Bitmap.Config BITMAP_CONFIG_DEFAULT = Bitmap.Config.ARGB_8888; private static final int POI_FONT_COLOR_NUMBER = 0xFF909090; private static final float POI_FONT_SIZE_NUMBER = 10.0F; private static final int POI_FONT_COLOR_ALPHABET = 0xFFFFFFFF; private static final float POI_FONT_OFFSET_ALPHABET = 6.0F; private static final Typeface POI_FONT_TYPEFACE = null;//Typeface.DEFAULT_BOLD; private static final int CALLOUT_TEXT_COLOR_NORMAL = 0xFFFFFFFF; private static final int CALLOUT_TEXT_COLOR_PRESSED = 0xFF9CA1AA; private static final int CALLOUT_TEXT_COLOR_SELECTED = 0xFFFFFFFF; private static final int CALLOUT_TEXT_COLOR_FOCUSED = 0xFFFFFFFF; private final Rect mTempRect = new Rect(); private final Paint mTextPaint = new Paint(); public NMapViewerResourceProvider(Context context) { super(context); mTextPaint.setAntiAlias(true); } /** * Get drawable for markerId at focused state * * @param markerId unique id for POI or Number icons. * @param focused true for focused state, false otherwise. * @return */ public Drawable getDrawable(int markerId, boolean focused, NMapOverlayItem item) { Drawable marker = null; int resourceId = findResourceIdForMarker(markerId, focused); if (resourceId > 0) { marker = mContext.getResources().getDrawable(resourceId); } else { resourceId = 4 * markerId; if (focused) { resourceId += 1; } marker = getDrawableForMarker(markerId, focused, item); } // set bounds if (marker != null) { setBounds(marker, markerId, item); } return marker; } public Bitmap getBitmap(int markerId, boolean focused, NMapOverlayItem item) { Bitmap bitmap = null; Drawable marker = getDrawable(markerId, focused, item); if (marker != null) { bitmap = getBitmap(marker); } return bitmap; } public Bitmap getBitmap(Drawable marker) { Bitmap bitmap = null; if (marker != null) { int width = marker.getIntrinsicWidth(); int height = marker.getIntrinsicHeight(); bitmap = Bitmap.createBitmap(width, height, BITMAP_CONFIG_DEFAULT); marker.setBounds(0, 0, width, height); Canvas canvas = new Canvas(bitmap); canvas.drawColor(0x00000000); marker.draw(canvas); } return bitmap; } public Bitmap getBitmap(int resourceId) { Bitmap bitmap = null; Drawable marker = null; if (resourceId > 0) { marker = mContext.getResources().getDrawable(resourceId); } if (marker != null) { bitmap = getBitmap(marker); } return bitmap; } public Bitmap getBitmapWithNumber(int resourceId, String strNumber, float offsetY, int fontColor, float fontSize) { Bitmap bitmap = null; Drawable marker = getDrawableWithNumber(resourceId, strNumber, offsetY, fontColor, fontSize); if (marker != null) { bitmap = getBitmap(marker); } return bitmap; } @Override public Drawable getDrawableForInfoLayer(NMapOverlayItem item) { return null; } /** * Class to find resource Ids on map view */ private class ResourceIdsOnMap { int markerId; int resourceId; int resourceIdFocused; ResourceIdsOnMap(int markerId, int resourceId, int resourceIdFocused) { this.markerId = markerId; this.resourceId = resourceId; this.resourceIdFocused = resourceIdFocused; } } // Resource Ids for single icons private final ResourceIdsOnMap mResourceIdsForMarkerOnMap[] = { // Spot, Pin icons new ResourceIdsOnMap(NMapPOIflagType.PIN, R.drawable.ic_pin_01, R.drawable.ic_pin_02), new ResourceIdsOnMap(NMapPOIflagType.SPOT, R.drawable.ic_pin_01, R.drawable.ic_pin_02), // Direction POI icons: From, To new ResourceIdsOnMap(NMapPOIflagType.FROM, R.drawable.ic_map_start, R.drawable.ic_map_start_over), new ResourceIdsOnMap(NMapPOIflagType.TO, R.drawable.ic_map_arrive, R.drawable.ic_map_arrive_over), }; /** * Find resource id corresponding to the markerId. * * @param markerId marker id for a NMapPOIitem. * @param focused flag to indicated focused or normal state of this marker. * * @return resource id for the given markerId. * * @see NMapPOIflagType */ @Override protected int findResourceIdForMarker(int markerId, boolean focused) { int resourceId = 0; if (DEBUG) { Log.i(LOG_TAG, "getResourceIdForMarker: markerId=" + markerId + ", focused=" + focused); } if (markerId < NMapPOIflagType.SINGLE_MARKER_END) { resourceId = getResourceIdOnMapView(markerId, focused, mResourceIdsForMarkerOnMap); if (resourceId > 0) { return resourceId; } } if (markerId >= NMapPOIflagType.NUMBER_BASE && markerId < NMapPOIflagType.NUMBER_END) { // Direction Number icons } else if (markerId >= NMapPOIflagType.CUSTOM_BASE && markerId < NMapPOIflagType.CUSTOM_END) { // Custom POI icons } return resourceId; } /** * Set bounds for this marker depending on its shape. * */ @Override protected void setBounds(Drawable marker, int markerId, NMapOverlayItem item) { // check shape of the marker to set bounds correctly. if (NMapPOIflagType.isBoundsCentered(markerId)) { if (marker.getBounds().isEmpty()) { NMapOverlayItem.boundCenter(marker); } if (null != item) { item.setAnchorRatio(0.5f, 0.5f); } } else { if (marker.getBounds().isEmpty()) { NMapOverlayItem.boundCenterBottom(marker); } if (null != item) { item.setAnchorRatio(0.5f, 1.0f); } } } @Override public Drawable[] getLocationDot() { Drawable[] drawable = new Drawable[2]; drawable[0] = mContext.getResources().getDrawable(R.drawable.pubtrans_ic_mylocation_off); drawable[1] = mContext.getResources().getDrawable(R.drawable.pubtrans_ic_mylocation_on); for (int i = 0; i < drawable.length; i++) { int w = drawable[i].getIntrinsicWidth() / 2; int h = drawable[i].getIntrinsicHeight() / 2; drawable[i].setBounds(-w, -h, w, h); } return drawable; } @Override public Drawable getDirectionArrow() { Drawable drawable = mContext.getResources().getDrawable(R.drawable.ic_angle); if (drawable != null) { int w = drawable.getIntrinsicWidth() / 2; int h = drawable.getIntrinsicHeight() / 2; drawable.setBounds(-w, -h, w, h); } return drawable; } public Drawable getDrawableWithNumber(int resourceId, String strNumber, float offsetY, int fontColor, float fontSize) { Bitmap textBitmap = getBitmapWithText(resourceId, strNumber, fontColor, fontSize, offsetY); //Log.i(LOG_TAG, "getDrawableWithNumber: width=" + textBitmap.getWidth() + ", height=" + textBitmap.getHeight() + ", density=" + textBitmap.getDensity()); // set bounds Drawable marker = new BitmapDrawable(mContext.getResources(), textBitmap); if (marker != null) { NMapOverlayItem.boundCenter(marker); } //Log.i(LOG_TAG, "getDrawableWithNumber: width=" + marker.getIntrinsicWidth() + ", height=" + marker.getIntrinsicHeight()); return marker; } public Drawable getDrawableWithAlphabet(int resourceId, String strAlphabet, int fontColor, float fontSize) { Bitmap textBitmap = getBitmapWithText(resourceId, strAlphabet, fontColor, fontSize, POI_FONT_OFFSET_ALPHABET); // set bounds Drawable marker = new BitmapDrawable(mContext.getResources(), textBitmap); if (marker != null) { NMapOverlayItem.boundCenterBottom(marker); } return marker; } @Override protected Drawable getDrawableForMarker(int markerId, boolean focused, NMapOverlayItem item) { Drawable drawable = null; if (markerId >= NMapPOIflagType.NUMBER_BASE && markerId < NMapPOIflagType.NUMBER_END) { // Direction Number icons int resourceId = (focused) ? R.drawable.ic_map_no_02 : R.drawable.ic_map_no_01; int fontColor = (focused) ? POI_FONT_COLOR_ALPHABET : POI_FONT_COLOR_NUMBER; String strNumber = String.valueOf(markerId - NMapPOIflagType.NUMBER_BASE); drawable = getDrawableWithNumber(resourceId, strNumber, 0.0F, fontColor, POI_FONT_SIZE_NUMBER); } else if (markerId >= NMapPOIflagType.CUSTOM_BASE && markerId < NMapPOIflagType.CUSTOM_END) { // Custom POI icons } return drawable; } private Bitmap getBitmapWithText(int resourceId, String strNumber, int fontColor, float fontSize, float offsetY) { Bitmap bitmapBackground = BitmapFactory.decodeResource(mContext.getResources(), resourceId); int width = bitmapBackground.getWidth(); int height = bitmapBackground.getHeight(); //Log.i(LOG_TAG, "getBitmapWithText: width=" + width + ", height=" + height + ", density=" + bitmapBackground.getDensity()); Bitmap textBitmap = Bitmap.createBitmap(width, height, BITMAP_CONFIG_DEFAULT); Canvas canvas = new Canvas(textBitmap); canvas.drawBitmap(bitmapBackground, 0, 0, null); // set font style mTextPaint.setColor(fontColor); // set font size mTextPaint.setTextSize(fontSize * mScaleFactor); // set font type if (POI_FONT_TYPEFACE != null) { mTextPaint.setTypeface(POI_FONT_TYPEFACE); } // get text offset mTextPaint.getTextBounds(strNumber, 0, strNumber.length(), mTempRect); float offsetX = (width - mTempRect.width()) / 2 - mTempRect.left; if (offsetY == 0.0F) { offsetY = (height - mTempRect.height()) / 2 + mTempRect.height(); } else { offsetY = offsetY * mScaleFactor + mTempRect.height(); } //Log.i(LOG_TAG, "getBitmapWithText: number=" + number + ", focused=" + focused); //Log.i(LOG_TAG, "getBitmapWithText: offsetX=" + offsetX + ", offsetY=" + offsetY + ", boundsWidth=" + mTempRect.width() + ", boundsHeight=" + mTempRect.height()); // draw text canvas.drawText(strNumber, offsetX, offsetY, mTextPaint); return textBitmap; } @Override public Drawable getCalloutBackground(NMapOverlayItem item) { if (item instanceof NMapPOIitem) { NMapPOIitem poiItem = (NMapPOIitem)item; if (poiItem.showRightButton()) { Drawable drawable = mContext.getResources().getDrawable(R.drawable.bg_speech); return drawable; } } Drawable drawable = mContext.getResources().getDrawable(R.drawable.pin_ballon_bg); return drawable; } @Override public String getCalloutRightButtonText(NMapOverlayItem item) { if (item instanceof NMapPOIitem) { NMapPOIitem poiItem = (NMapPOIitem)item; if (poiItem.showRightButton()) { return mContext.getResources().getString(R.string.str_done); } } return null; } @Override public Drawable[] getCalloutRightButton(NMapOverlayItem item) { if (item instanceof NMapPOIitem) { NMapPOIitem poiItem = (NMapPOIitem)item; if (poiItem.showRightButton()) { Drawable[] drawable = new Drawable[3]; drawable[0] = mContext.getResources().getDrawable(R.drawable.btn_green_normal); drawable[1] = mContext.getResources().getDrawable(R.drawable.btn_green_pressed); drawable[2] = mContext.getResources().getDrawable(R.drawable.btn_green_highlight); return drawable; } } return null; } @Override public Drawable[] getCalloutRightAccessory(NMapOverlayItem item) { if (item instanceof NMapPOIitem) { NMapPOIitem poiItem = (NMapPOIitem)item; if (poiItem.hasRightAccessory() && (poiItem.getRightAccessoryId() > 0)) { Drawable[] drawable = new Drawable[3]; switch (poiItem.getRightAccessoryId()) { case NMapPOIflagType.CLICKABLE_ARROW: drawable[0] = mContext.getResources().getDrawable(R.drawable.pin_ballon_arrow); drawable[1] = mContext.getResources().getDrawable(R.drawable.pin_ballon_on_arrow); drawable[2] = mContext.getResources().getDrawable(R.drawable.pin_ballon_on_arrow); break; } return drawable; } } return null; } /** * * * @param item * @return * @see com.nhn.android.mapviewer.overlay.NMapCalloutCustomOverlay.ResourceProvider#getCalloutTextColors(com.nhn.android.maps.NMapOverlayItem) */ @Override public int[] getCalloutTextColors(NMapOverlayItem item) { int[] colors = new int[4]; colors[0] = CALLOUT_TEXT_COLOR_NORMAL; colors[1] = CALLOUT_TEXT_COLOR_PRESSED; colors[2] = CALLOUT_TEXT_COLOR_SELECTED; colors[3] = CALLOUT_TEXT_COLOR_FOCUSED; return colors; } @Override public int getParentLayoutIdForOverlappedListView() { // not supported return 0; } @Override public int getOverlappedListViewId() { // not supported return 0; } @Override public int getLayoutIdForOverlappedListView() { // not supported return 0; } @Override public int getListItemLayoutIdForOverlappedListView() { // not supported return 0; } @Override public int getListItemTextViewId() { // not supported return 0; } @Override public int getListItemTailTextViewId() { // not supported return 0; } @Override public int getListItemImageViewId() { // not supported return 0; } @Override public int getListItemDividerId() { // not supported return 0; } @Override public void setOverlappedListViewLayout(ListView listView, int itemCount, int width, int height) { // not supported } @Override public void setOverlappedItemResource(NMapPOIitem poiItem, ImageView imageView) { // not supported } private int getResourceIdOnMapView(int markerId, boolean focused, ResourceIdsOnMap resourceIdsArray[]) { int resourceId = 0; for (ResourceIdsOnMap resourceIds : resourceIdsArray) { if (resourceIds.markerId == markerId) { resourceId = (focused) ? resourceIds.resourceIdFocused : resourceIds.resourceId; break; } } return resourceId; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/NMapViewerResourceProvider.java
Java
epl
14,657
package com.example.pphotocapsule; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.ImageView; public class MainActivity extends Activity { ImageView main_imageView_camera, main_imageView_album; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_imageView_camera = (ImageView)findViewById(R.id.main_imageView_camera); main_imageView_album = (ImageView)findViewById(R.id.main_imageView_album); main_imageView_camera.setOnClickListener(imageViewClickListener); main_imageView_album.setOnClickListener(imageViewClickListener); } ImageView.OnClickListener imageViewClickListener = new ImageView.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()){ case R.id.main_imageView_camera: Intent intent_camera = new Intent(MainActivity.this, CameraActivity.class); startActivity(intent_camera); break; case R.id.main_imageView_album: Intent intent_album = new Intent(MainActivity.this, AlbumActivity.class); startActivity(intent_album); break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
zzikgong
trunk/PphotoCapsule/src/com/example/pphotocapsule/MainActivity.java
Java
epl
1,496
package com.example.photocapsule; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import com.nhn.android.maps.NMapOverlay; import com.nhn.android.maps.NMapOverlayItem; import com.nhn.android.maps.NMapView; import com.nhn.android.mapviewer.overlay.NMapCalloutOverlay; public class NMapCalloutBasicOverlay extends NMapCalloutOverlay{ private static final int CALLOUT_TEXT_PADDING_X = 10; private static final int CALLOUT_TEXT_PADDING_Y = 10; private static final int CALLOUT_TAG_WIDTH = 10; private static final int CALLOUT_TAG_HEIGHT = 10; private static final int CALLOUT_ROUND_RADIUS_X = 5; private static final int CALLOUT_ROUND_RADIUS_Y = 5; private final Paint mInnerPaint, mBorderPaint, mTextPaint; private final Path mPath; private float mOffsetX, mOffsetY; public NMapCalloutBasicOverlay(NMapOverlay itemOverlay, NMapOverlayItem item, Rect itemBounds) { super(itemOverlay, item, itemBounds); mInnerPaint = new Paint(); mInnerPaint.setARGB(225, 75, 75, 75); //gray mInnerPaint.setAntiAlias(true); mBorderPaint = new Paint(); mBorderPaint.setARGB(255, 255, 255, 255); mBorderPaint.setAntiAlias(true); mBorderPaint.setStyle(Style.STROKE); mBorderPaint.setStrokeWidth(2); mTextPaint = new Paint(); mTextPaint.setARGB(255, 255, 255, 255); mTextPaint.setAntiAlias(true); mPath = new Path(); mPath.setFillType(Path.FillType.WINDING); } @Override protected boolean isTitleTruncated() { return false; } @Override protected int getMarginX() { return 10; } @Override protected Rect getBounds(NMapView mapView) { adjustTextBounds(mapView); mTempRect.set((int)mTempRectF.left, (int)mTempRectF.top, (int)mTempRectF.right, (int)mTempRectF.bottom); mTempRect.union(mTempPoint.x, mTempPoint.y); return mTempRect; } @Override protected PointF getSclaingPivot() { PointF pivot = new PointF(); pivot.x = mTempRectF.centerX(); pivot.y = mTempRectF.bottom + CALLOUT_TAG_HEIGHT; return pivot; } @Override protected void drawCallout(Canvas canvas, NMapView mapView, boolean shadow, long when) { adjustTextBounds(mapView); stepAnimations(canvas, mapView, when); // Draw inner info window canvas.drawRoundRect(mTempRectF, CALLOUT_ROUND_RADIUS_X, CALLOUT_ROUND_RADIUS_Y, mInnerPaint); // Draw border for info window canvas.drawRoundRect(mTempRectF, CALLOUT_ROUND_RADIUS_X, CALLOUT_ROUND_RADIUS_Y, mBorderPaint); // Draw bottom tag if (CALLOUT_TAG_WIDTH > 0 && CALLOUT_TAG_HEIGHT > 0) { float x = mTempRectF.centerX(); float y = mTempRectF.bottom; Path path = mPath; path.reset(); path.moveTo(x - CALLOUT_TAG_WIDTH, y); path.lineTo(x, y + CALLOUT_TAG_HEIGHT); path.lineTo(x + CALLOUT_TAG_WIDTH, y); path.close(); canvas.drawPath(path, mInnerPaint); canvas.drawPath(path, mBorderPaint); } // Draw title canvas.drawText(mOverlayItem.getTitle(), mOffsetX, mOffsetY, mTextPaint); } /* Internal Functions */ private void adjustTextBounds(NMapView mapView) { // Determine the screen coordinates of the selected MapLocation mapView.getMapProjection().toPixels(mOverlayItem.getPointInUtmk(), mTempPoint); final String title = mOverlayItem.getTitle(); mTextPaint.getTextBounds(title, 0, title.length(), mTempRect); // Setup the callout with the appropriate size & location mTempRectF.set(mTempRect); mTempRectF.inset(-CALLOUT_TEXT_PADDING_X, -CALLOUT_TEXT_PADDING_Y); mOffsetX = mTempPoint.x - mTempRect.width() / 2; mOffsetY = mTempPoint.y - mTempRect.height() - mItemBounds.height() - CALLOUT_TEXT_PADDING_Y; mTempRectF.offset(mOffsetX, mOffsetY); } @Override protected Drawable getDrawable(int rank, int itemState) { // TODO Auto-generated method stub return null; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/NMapCalloutBasicOverlay.java
Java
epl
4,060
package com.example.photocapsule; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.provider.MediaStore; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.ImageView; public class AlbumActivity extends Activity { private Context mContext; GridView album_gridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_album); mContext = this; final ImageAdapter ia = new ImageAdapter(this); album_gridView = (GridView)findViewById(R.id.album_gridView); album_gridView.setAdapter(ia); album_gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { ia.callImageViewer(position); } }); } public class ImageAdapter extends BaseAdapter { private String imgData; private String geoData; private ArrayList<String> thumbsDataList; private ArrayList<String> thumbsIDList; ImageAdapter(Context c) { mContext = c; thumbsDataList = new ArrayList<String>(); thumbsIDList = new ArrayList<String>(); getThumbInfo(thumbsIDList, thumbsDataList); } public final void callImageViewer(int selectedIndex) { Intent intent_imagepopup = new Intent(mContext, ImagePopupActivity.class); String imgPath = getImageInfo(imgData, geoData, thumbsIDList.get(selectedIndex)); intent_imagepopup.putExtra("filename", imgPath); startActivityForResult(intent_imagepopup, 1); } public boolean deleteSelected(int sIndex) { return true; } @Override public int getCount() { // TODO Auto-generated method stub return thumbsIDList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ImageView imageView; if (convertView == null) { imageView = new ImageView(mContext); imageView.setLayoutParams(new GridView.LayoutParams(95, 95)); imageView.setAdjustViewBounds(false); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setPadding(2, 2, 2, 2); } else { imageView = (ImageView)convertView; } BitmapFactory.Options bo = new BitmapFactory.Options(); bo.inSampleSize = 8; Bitmap bmp = BitmapFactory.decodeFile(thumbsDataList.get(position), bo); Bitmap resized = Bitmap.createScaledBitmap(bmp, 95, 95, true); imageView.setImageBitmap(resized); return imageView; } private void getThumbInfo(ArrayList<String> thumbsIDs, ArrayList<String> thumbsDatas){ String[] proj = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.SIZE}; Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, "bucket_display_name='PhotoCapsule'", null, null); if (imageCursor != null && imageCursor.moveToFirst()){ String title; String thumbsID; String thumbsImageID; String thumbsData; String data; String imgSize; int thumbsIDCol = imageCursor.getColumnIndex(MediaStore.Images.Media._ID); int thumbsDataCol = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA); int thumbsImageIDCol = imageCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME); int thumbsSizeCol = imageCursor.getColumnIndex(MediaStore.Images.Media.SIZE); int num = 0; do { thumbsID = imageCursor.getString(thumbsIDCol); thumbsData = imageCursor.getString(thumbsDataCol); thumbsImageID = imageCursor.getString(thumbsImageIDCol); imgSize = imageCursor.getString(thumbsSizeCol); num++; if (thumbsImageID != null){ thumbsIDs.add(thumbsID); thumbsDatas.add(thumbsData); } }while (imageCursor.moveToNext()); imageCursor.close(); } return; } private String getImageInfo(String ImageData, String Location, String thumbID){ String imageDataPath = null; String[] proj = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.SIZE}; Cursor imageCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, "bucket_display_name='PhotoCapsule'", null, null); if (imageCursor != null && imageCursor.moveToFirst()){ if (imageCursor.getCount() > 0){ int imgData = imageCursor.getColumnIndex(MediaStore.Images.Media.DATA); imageDataPath = imageCursor.getString(imgData); } } imageCursor.close(); return imageDataPath; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.album, menu); return true; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/AlbumActivity.java
Java
epl
6,367
package com.example.photocapsule; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.content.Intent; import android.view.Menu; public class SplashActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Intent intent = new Intent(SplashActivity.this, IntroActivity.class); startActivity(intent); finish(); } }, 4000); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.splash, menu); return true; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/SplashActivity.java
Java
epl
906
package com.example.photocapsule; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; public class ImagePopupActivity extends Activity { ImageView imagepopup_imageView; ImageButton imagepopup_imageButton_merge; Intent intent; String filename; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_popup); intent = getIntent(); filename = intent.getStringExtra("filename"); BitmapFactory.Options bfo = new BitmapFactory.Options(); bfo.inSampleSize = 2; Bitmap bm = BitmapFactory.decodeFile(filename, bfo); imagepopup_imageView = (ImageView)findViewById(R.id.imagepopup_imageView); imagepopup_imageView.setImageBitmap(bm); imagepopup_imageButton_merge = (ImageButton)findViewById(R.id.imagepopup_imageButton_merge); imagepopup_imageButton_merge.setOnClickListener(imageButtonClickListener); } ImageButton.OnClickListener imageButtonClickListener = new ImageButton.OnClickListener() { @Override public void onClick(View v) { switch(v.getId()) { case R.id.imagepopup_imageButton_merge : break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.image_popup, menu); return true; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/ImagePopupActivity.java
Java
epl
1,647
package com.example.photocapsule; import android.graphics.Bitmap; public class DivideImage { public static Bitmap croppedBmpLeft; public static Bitmap croppedBmpright; public void segmentImage(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int halfWidth = width / 2; croppedBmpLeft = Bitmap.createBitmap(bitmap, 0, 0, halfWidth, height); croppedBmpright = Bitmap.createBitmap(bitmap, halfWidth, 0, halfWidth, height); } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/DivideImage.java
Java
epl
494
package com.example.photocapsule; public class NMapPOIflagType { public static final int UNKNOWN = 0x0000; // Single POI icons private static final int SINGLE_POI_BASE = 0x0100; // Spot, Pin icons public static final int SPOT = SINGLE_POI_BASE + 1; public static final int PIN = SPOT + 1; // Direction POI icons: From, To private static final int DIRECTION_POI_BASE = 0x0200; public static final int FROM = DIRECTION_POI_BASE + 1; public static final int TO = FROM + 1; // end of single marker icon public static final int SINGLE_MARKER_END = 0x04FF; // Direction Number icons private static final int MAX_NUMBER_COUNT = 1000; public static final int NUMBER_BASE = 0x1000; // set NUMBER_BASE + 1 for '1' number public static final int NUMBER_END = NUMBER_BASE + MAX_NUMBER_COUNT; // Custom POI icons private static final int MAX_CUSTOM_COUNT = 1000; public static final int CUSTOM_BASE = NUMBER_END; public static final int CUSTOM_END = CUSTOM_BASE + MAX_CUSTOM_COUNT; // Clickable callout public static final int CLICKABLE_ARROW = CUSTOM_END + 1; public static boolean isBoundsCentered(int markerId) { boolean boundsCentered = false; switch (markerId) { default: if (markerId >= NMapPOIflagType.NUMBER_BASE && markerId < NMapPOIflagType.NUMBER_END) { boundsCentered = true; } break; } return boundsCentered; } public static int getMarkerId(int poiFlagType, int iconIndex) { int markerId = poiFlagType + iconIndex; return markerId; } public static int getPOIflagType(int markerId) { int poiFlagType = UNKNOWN; // Alphabet POI icons if (markerId >= NUMBER_BASE && markerId < NUMBER_END) { // Direction Number icons poiFlagType = NUMBER_BASE; } else if (markerId >= CUSTOM_BASE && markerId < CUSTOM_END) { // Custom POI icons poiFlagType = CUSTOM_BASE; } else if (markerId > SINGLE_POI_BASE) { poiFlagType = markerId; } return poiFlagType; } public static int getPOIflagIconIndex(int markerId) { int iconIndex = 0; if (markerId >= NUMBER_BASE && markerId < NUMBER_END) { // Direction Number icons iconIndex = markerId - (NUMBER_BASE + 1); } else if (markerId >= CUSTOM_BASE && markerId < CUSTOM_END) { // Custom POI icons iconIndex = markerId - (CUSTOM_BASE + 1); } else if (markerId > SINGLE_POI_BASE) { iconIndex = 0; } return iconIndex; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/NMapPOIflagType.java
Java
epl
2,449
package com.example.photocapsule; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.ImageButton; public class IntroActivity extends Activity { ImageButton intro_imageButton_ok; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intro); intro_imageButton_ok = (ImageButton)findViewById(R.id.intro_imageButton_ok); intro_imageButton_ok.setOnClickListener(imageButtonClickListener); } ImageButton.OnClickListener imageButtonClickListener = new ImageButton.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.intro_imageButton_ok : Intent intent_main = new Intent(IntroActivity.this, MainActivity.class); startActivity(intent_main); break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.intro, menu); return true; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/IntroActivity.java
Java
epl
1,214
package com.example.photocapsule; import java.util.Date; import java.util.Properties; import javax.activation.CommandMap; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.activation.MailcapCommandMap; import javax.mail.BodyPart; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class Mail extends javax.mail.Authenticator { private String _user; private String _pass; private String[] _to; private String _from; private String _port; private String _sport; private String _host; private String _subject; private String _body; private boolean _auth; private boolean _debuggable; private Multipart _multipart; public Mail() { _host = "smtp.gmail.com"; // default smtp server _port = "465"; // default smtp port; alternative is 587 _sport = "465"; // default socketfactory port; alternative is 587 _user = ""; // username _pass = ""; // password _from = ""; // email sent from _subject = ""; // email subject _body = ""; // email body _debuggable = false; // debug mode on or off - default off _auth = true; // smtp authentication - default on _multipart = new MimeMultipart(); // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); } public Mail(String user, String pass) { this(); _user = user; _pass = pass; } public boolean send() throws Exception { Properties props = _setProperties(); if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { Session session = Session.getInstance(props, this); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(_from)); InternetAddress[] addressTo = new InternetAddress[_to.length]; for (int i = 0; i < _to.length; i++) { addressTo[i] = new InternetAddress(_to[i]); } msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); msg.setSubject(_subject); msg.setSentDate(new Date()); // setup message body BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(_body); _multipart.addBodyPart(messageBodyPart); // Put parts in message msg.setContent(_multipart); // send email Transport.send(msg); return true; } else { return false; } } public void addAttachment(String filename) throws Exception { BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); _multipart.addBodyPart(messageBodyPart); } @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(_user, _pass); } private Properties _setProperties() { Properties props = new Properties(); props.put("mail.smtp.host", _host); if(_debuggable) { props.put("mail.debug", "true"); } if(_auth) { props.put("mail.smtp.auth", "true"); } props.put("mail.smtp.port", _port); props.put("mail.smtp.socketFactory.port", _sport); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); return props; } // the getters and setters public String getBody() { return _body; } public void setBody(String _body) { this._body = _body; } public void setTo(String[] toArr) { this._to = toArr; } public void setFrom(String string) { this._from = string; } public void setSubject(String string) { this._subject = string; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/Mail.java
Java
epl
4,865
package com.example.photocapsule; import android.graphics.Bitmap; public class MergeImage { public Bitmap combineImages(Bitmap c, Bitmap s) { Bitmap cs = null; int width, height = 0; width = c.getWidth() + s.getWidth(); height = c.getHeight(); cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); return cs; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/MergeImage.java
Java
epl
363
package com.example.photocapsule; import android.graphics.Canvas; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.text.TextPaint; import android.text.TextUtils; import android.util.Log; import com.nhn.android.maps.NMapOverlay; import com.nhn.android.maps.NMapOverlayItem; import com.nhn.android.maps.NMapView; import com.nhn.android.mapviewer.overlay.NMapCalloutOverlay; import com.nhn.android.mapviewer.overlay.NMapResourceProvider; public class NMapCalloutCustomOldOverlay extends NMapCalloutOverlay { private static final String LOG_TAG = "NMapCalloutCustomOverlay"; private static final boolean DEBUG = false; private static final int CALLOUT_TEXT_COLOR = 0xFFFFFFFF; private static final float CALLOUT_TEXT_SIZE = 16.0F; private static final Typeface CALLOUT_TEXT_TYPEFACE = null;//Typeface.DEFAULT_BOLD; private static final float CALLOUT_RIGHT_BUTTON_WIDTH = 50.67F; private static final float CALLOUT_RIGHT_BUTTON_HEIGHT = 34.67F; private static final float CALLOUT_MARGIN_X = 9.33F; private static final float CALLOUT_PADDING_X = 9.33F; private static final float CALLOUT_PADDING_OFFSET = 0.45F; private static final float CALLOUT_PADDING_Y = 17.33F; private static final float CALLOUT_MIMIMUM_WIDTH = 63.33F; private static final float CALLOUT_TOTAL_HEIGHT = 64.0F; private static final float CALLOUT_BACKGROUND_HEIGHT = CALLOUT_PADDING_Y + CALLOUT_TEXT_SIZE + CALLOUT_PADDING_Y; private static final float CALLOUT_ITEM_GAP_Y = 0.0F; private static final float CALLOUT_TAIL_GAP_X = 6.67F; private static final float CALLOUT_TITLE_OFFSET_Y = -2.0F; private final TextPaint mTextPaint = new TextPaint(); private float mOffsetX, mOffsetY; private final float mMarginX; private final float mPaddingX, mPaddingY, mPaddingOffset; private final float mMinimumWidth; private final float mTotalHeight; private final float mBackgroundHeight; private final float mItemGapY; private final float mTailGapX; private final float mTitleOffsetY; private final Drawable mBackgroundDrawable; protected final Rect mTemp2Rect = new Rect(); private final Rect mRightButtonRect; private final String mRightButtonText; private final int mCalloutRightButtonWidth; private final int mCalloutRightButtonHeight; private Drawable[] mDrawableRightButton; private final int mCalloutButtonCount = 1; private String mTitleTruncated; private int mWidthTitleTruncated; private final String mTailText; private float mTailTextWidth; /** * Resource provider should implement this interface */ public static interface ResourceProvider { public Drawable getCalloutBackground(NMapOverlayItem item); public String getCalloutRightButtonText(NMapOverlayItem item); public Drawable[] getCalloutRightButton(NMapOverlayItem item); public Drawable[] getCalloutRightAccessory(NMapOverlayItem item); } public NMapCalloutCustomOldOverlay(NMapOverlay itemOverlay, NMapOverlayItem item, Rect itemBounds, NMapCalloutCustomOldOverlay.ResourceProvider resourceProvider) { super(itemOverlay, item, itemBounds); mTextPaint.setAntiAlias(true); // set font style mTextPaint.setColor(CALLOUT_TEXT_COLOR); // set font size mTextPaint.setTextSize(CALLOUT_TEXT_SIZE * NMapResourceProvider.getScaleFactor()); // set font type if (CALLOUT_TEXT_TYPEFACE != null) { mTextPaint.setTypeface(CALLOUT_TEXT_TYPEFACE); } mMarginX = NMapResourceProvider.toPixelFromDIP(CALLOUT_MARGIN_X); mPaddingX = NMapResourceProvider.toPixelFromDIP(CALLOUT_PADDING_X); mPaddingOffset = NMapResourceProvider.toPixelFromDIP(CALLOUT_PADDING_OFFSET); mPaddingY = NMapResourceProvider.toPixelFromDIP(CALLOUT_PADDING_Y); mMinimumWidth = NMapResourceProvider.toPixelFromDIP(CALLOUT_MIMIMUM_WIDTH); mTotalHeight = NMapResourceProvider.toPixelFromDIP(CALLOUT_TOTAL_HEIGHT); mBackgroundHeight = NMapResourceProvider.toPixelFromDIP(CALLOUT_BACKGROUND_HEIGHT); mItemGapY = NMapResourceProvider.toPixelFromDIP(CALLOUT_ITEM_GAP_Y); mTailGapX = NMapResourceProvider.toPixelFromDIP(CALLOUT_TAIL_GAP_X); mTailText = item.getTailText(); mTitleOffsetY = NMapResourceProvider.toPixelFromDIP(CALLOUT_TITLE_OFFSET_Y); if (resourceProvider == null) { throw new IllegalArgumentException( "NMapCalloutCustomOverlay.ResourceProvider should be provided on creation of NMapCalloutCustomOverlay."); } mBackgroundDrawable = resourceProvider.getCalloutBackground(item); boolean hasRightAccessory = false; mDrawableRightButton = resourceProvider.getCalloutRightAccessory(item); if (mDrawableRightButton != null && mDrawableRightButton.length > 0) { hasRightAccessory = true; mRightButtonText = null; } else { mDrawableRightButton = resourceProvider.getCalloutRightButton(item); mRightButtonText = resourceProvider.getCalloutRightButtonText(item); } if (mDrawableRightButton != null) { if (hasRightAccessory) { mCalloutRightButtonWidth = mDrawableRightButton[0].getIntrinsicWidth(); mCalloutRightButtonHeight = mDrawableRightButton[0].getIntrinsicHeight(); } else { mCalloutRightButtonWidth = NMapResourceProvider.toPixelFromDIP(CALLOUT_RIGHT_BUTTON_WIDTH); mCalloutRightButtonHeight = NMapResourceProvider.toPixelFromDIP(CALLOUT_RIGHT_BUTTON_HEIGHT); } mRightButtonRect = new Rect(); super.setItemCount(mCalloutButtonCount); } else { mCalloutRightButtonWidth = 0; mCalloutRightButtonHeight = 0; mRightButtonRect = null; } mTitleTruncated = null; mWidthTitleTruncated = 0; } @Override protected boolean hitTest(int hitX, int hitY) { // hit test for right button only ? // if (mRightButtonRect != null) { // return mRightButtonRect.contains(hitX, hitY); // } return super.hitTest(hitX, hitY); } @Override protected boolean isTitleTruncated() { return (mTitleTruncated != mOverlayItem.getTitle()); } @Override protected int getMarginX() { return (int)(mMarginX); } @Override protected Rect getBounds(NMapView mapView) { adjustTextBounds(mapView); mTempRect.set((int)mTempRectF.left, (int)mTempRectF.top, (int)mTempRectF.right, (int)mTempRectF.bottom); mTempRect.union(mTempPoint.x, mTempPoint.y); return mTempRect; } @Override protected PointF getSclaingPivot() { PointF pivot = new PointF(); pivot.x = mTempRectF.centerX(); pivot.y = mTempRectF.top + mTotalHeight; return pivot; } @Override protected void drawCallout(Canvas canvas, NMapView mapView, boolean shadow, long when) { adjustTextBounds(mapView); stepAnimations(canvas, mapView, when); drawBackground(canvas); float left, top; // draw title mOffsetX = mTempPoint.x - mTempRect.width() / 2; mOffsetX -= mPaddingOffset; mOffsetY = mTempRectF.top + mPaddingY + mTextPaint.getTextSize() + mTitleOffsetY; canvas.drawText(mTitleTruncated, mOffsetX, mOffsetY, mTextPaint); // draw right button if (mDrawableRightButton != null) { left = mTempRectF.right - mPaddingX - mCalloutRightButtonWidth; top = mTempRectF.top + (mBackgroundHeight - mCalloutRightButtonHeight) / 2; // Use background drawables depends on current state mRightButtonRect.left = (int)(left + 0.5F); mRightButtonRect.top = (int)(top + 0.5F); mRightButtonRect.right = (int)(left + mCalloutRightButtonWidth + 0.5F); mRightButtonRect.bottom = (int)(top + mCalloutRightButtonHeight + 0.5F); int itemState = super.getItemState(0); Drawable drawable = getDrawable(0, itemState); if (drawable != null) { drawable.setBounds(mRightButtonRect); drawable.draw(canvas); } if (mRightButtonText != null) { mTextPaint.getTextBounds(mRightButtonText, 0, mRightButtonText.length(), mTempRect); left = mRightButtonRect.left + (mCalloutRightButtonWidth - mTempRect.width()) / 2; top = mRightButtonRect.top + (mCalloutRightButtonHeight - mTempRect.height()) / 2 + mTempRect.height() + mTitleOffsetY; canvas.drawText(mRightButtonText, left, top, mTextPaint); } } // draw tail text if (mTailText != null) { if (mRightButtonRect != null) { left = mRightButtonRect.left; } else { left = mTempRectF.right; } left -= mPaddingX + mTailTextWidth; top = mOffsetY; canvas.drawText(mTailText, left, top, mTextPaint); } } /* Internal Functions */ private void drawBackground(Canvas canvas) { mTemp2Rect.left = (int)(mTempRectF.left + 0.5F); mTemp2Rect.top = (int)(mTempRectF.top + 0.5F); mTemp2Rect.right = (int)(mTempRectF.right + 0.5F); mTemp2Rect.bottom = (int)(mTempRectF.top + mTotalHeight + 0.5F); mBackgroundDrawable.setBounds(mTemp2Rect); mBackgroundDrawable.draw(canvas); } private void adjustTextBounds(NMapView mapView) { // First determine the screen coordinates of the selected MapLocation mapView.getMapProjection().toPixels(mOverlayItem.getPointInUtmk(), mTempPoint); int mapViewWidth = mapView.getMapController().getViewFrameVisibleWidth(); if (mTitleTruncated == null || mWidthTitleTruncated != mapViewWidth) { mWidthTitleTruncated = mapViewWidth; float maxWidth = mWidthTitleTruncated - 2 * mMarginX - 2 * mPaddingX; if (DEBUG) { Log.i(LOG_TAG, "adjustTextBounds: maxWidth=" + maxWidth + ", mMarginX=" + mMarginX + ", mPaddingX=" + mPaddingX); } if (mDrawableRightButton != null) { maxWidth -= mPaddingX + mCalloutRightButtonWidth; } if (mTailText != null) { mTextPaint.getTextBounds(mTailText, 0, mTailText.length(), mTempRect); mTailTextWidth = mTempRect.width(); maxWidth -= mTailGapX + mTailTextWidth; } final String title = TextUtils.ellipsize(mOverlayItem.getTitle(), mTextPaint, maxWidth, TextUtils.TruncateAt.END).toString(); mTitleTruncated = title; if (DEBUG) { Log.i(LOG_TAG, "adjustTextBounds: mTitleTruncated=" + mTitleTruncated + ", length=" + mTitleTruncated.length()); } } mTextPaint.getTextBounds(mTitleTruncated, 0, mTitleTruncated.length(), mTempRect); if (mDrawableRightButton != null) { mTempRect.right += mPaddingX + mCalloutRightButtonWidth; } if (mTailText != null) { mTempRect.right += mTailGapX + mTailTextWidth; } if (DEBUG) { Log.i(LOG_TAG, "adjustTextBounds: mTempRect.width=" + mTempRect.width() + ", mTempRect.height=" + mTempRect.height()); } // Setup the callout with the right size & location mTempRectF.set(mTempRect); final float dy = (mBackgroundHeight - mTempRect.height()) / 2; mTempRectF.inset(-mPaddingX, -dy); //mTempRectF.inset(-mPaddingX, -mPaddingY); // set minimum size if (mTempRectF.width() < mMinimumWidth) { final float dx = (mMinimumWidth - mTempRectF.width()) / 2; mTempRectF.inset(-dx, 0); } // set position float left = mTempPoint.x - (int)(mTempRectF.width() * mOverlayItem.getAnchorXRatio()); float top = mTempPoint.y - (int)(mItemBounds.height() * mOverlayItem.getAnchorYRatio()) - mItemGapY - mTotalHeight; mTempRectF.set(left, top, left + mTempRectF.width(), top + mTempRectF.height()); } @Override protected Drawable getDrawable(int rank, int itemState) { if (mDrawableRightButton != null && mDrawableRightButton.length >= 3) { int idxDrawable = 0; if (NMapOverlayItem.isPressedState(itemState)) { idxDrawable = 1; } else if (NMapOverlayItem.isSelectedState(itemState)) { idxDrawable = 2; } else if (NMapOverlayItem.isFocusedState(itemState)) { idxDrawable = 2; } Drawable drawable = mDrawableRightButton[idxDrawable]; return drawable; } return null; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/NMapCalloutCustomOldOverlay.java
Java
epl
11,925
package com.example.photocapsule; public class Database { }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/Database.java
Java
epl
67
package com.example.photocapsule; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Log; import android.widget.ImageView; import android.widget.ListView; import com.nhn.android.maps.NMapOverlayItem; import com.nhn.android.maps.overlay.NMapPOIitem; import com.nhn.android.mapviewer.overlay.NMapResourceProvider; public class NMapViewerResourceProvider extends NMapResourceProvider implements NMapCalloutCustomOldOverlay.ResourceProvider { private static final String LOG_TAG = "NMapViewerResourceProvider"; private static final boolean DEBUG = false; private static final Bitmap.Config BITMAP_CONFIG_DEFAULT = Bitmap.Config.ARGB_8888; private static final int POI_FONT_COLOR_NUMBER = 0xFF909090; private static final float POI_FONT_SIZE_NUMBER = 10.0F; private static final int POI_FONT_COLOR_ALPHABET = 0xFFFFFFFF; private static final float POI_FONT_OFFSET_ALPHABET = 6.0F; private static final Typeface POI_FONT_TYPEFACE = null;//Typeface.DEFAULT_BOLD; private static final int CALLOUT_TEXT_COLOR_NORMAL = 0xFFFFFFFF; private static final int CALLOUT_TEXT_COLOR_PRESSED = 0xFF9CA1AA; private static final int CALLOUT_TEXT_COLOR_SELECTED = 0xFFFFFFFF; private static final int CALLOUT_TEXT_COLOR_FOCUSED = 0xFFFFFFFF; private final Rect mTempRect = new Rect(); private final Paint mTextPaint = new Paint(); public NMapViewerResourceProvider(Context context) { super(context); mTextPaint.setAntiAlias(true); } /** * Get drawable for markerId at focused state * * @param markerId unique id for POI or Number icons. * @param focused true for focused state, false otherwise. * @return */ public Drawable getDrawable(int markerId, boolean focused, NMapOverlayItem item) { Drawable marker = null; int resourceId = findResourceIdForMarker(markerId, focused); if (resourceId > 0) { marker = mContext.getResources().getDrawable(resourceId); } else { resourceId = 4 * markerId; if (focused) { resourceId += 1; } marker = getDrawableForMarker(markerId, focused, item); } // set bounds if (marker != null) { setBounds(marker, markerId, item); } return marker; } public Bitmap getBitmap(int markerId, boolean focused, NMapOverlayItem item) { Bitmap bitmap = null; Drawable marker = getDrawable(markerId, focused, item); if (marker != null) { bitmap = getBitmap(marker); } return bitmap; } public Bitmap getBitmap(Drawable marker) { Bitmap bitmap = null; if (marker != null) { int width = marker.getIntrinsicWidth(); int height = marker.getIntrinsicHeight(); bitmap = Bitmap.createBitmap(width, height, BITMAP_CONFIG_DEFAULT); marker.setBounds(0, 0, width, height); Canvas canvas = new Canvas(bitmap); canvas.drawColor(0x00000000); marker.draw(canvas); } return bitmap; } public Bitmap getBitmap(int resourceId) { Bitmap bitmap = null; Drawable marker = null; if (resourceId > 0) { marker = mContext.getResources().getDrawable(resourceId); } if (marker != null) { bitmap = getBitmap(marker); } return bitmap; } public Bitmap getBitmapWithNumber(int resourceId, String strNumber, float offsetY, int fontColor, float fontSize) { Bitmap bitmap = null; Drawable marker = getDrawableWithNumber(resourceId, strNumber, offsetY, fontColor, fontSize); if (marker != null) { bitmap = getBitmap(marker); } return bitmap; } @Override public Drawable getDrawableForInfoLayer(NMapOverlayItem item) { return null; } /** * Class to find resource Ids on map view */ private class ResourceIdsOnMap { int markerId; int resourceId; int resourceIdFocused; ResourceIdsOnMap(int markerId, int resourceId, int resourceIdFocused) { this.markerId = markerId; this.resourceId = resourceId; this.resourceIdFocused = resourceIdFocused; } } // Resource Ids for single icons private final ResourceIdsOnMap mResourceIdsForMarkerOnMap[] = { // Spot, Pin icons new ResourceIdsOnMap(NMapPOIflagType.PIN, R.drawable.ic_pin_01, R.drawable.ic_pin_02), new ResourceIdsOnMap(NMapPOIflagType.SPOT, R.drawable.ic_pin_01, R.drawable.ic_pin_02), // Direction POI icons: From, To new ResourceIdsOnMap(NMapPOIflagType.FROM, R.drawable.ic_map_start, R.drawable.ic_map_start_over), new ResourceIdsOnMap(NMapPOIflagType.TO, R.drawable.ic_map_arrive, R.drawable.ic_map_arrive_over), }; /** * Find resource id corresponding to the markerId. * * @param markerId marker id for a NMapPOIitem. * @param focused flag to indicated focused or normal state of this marker. * * @return resource id for the given markerId. * * @see NMapPOIflagType */ @Override protected int findResourceIdForMarker(int markerId, boolean focused) { int resourceId = 0; if (DEBUG) { Log.i(LOG_TAG, "getResourceIdForMarker: markerId=" + markerId + ", focused=" + focused); } if (markerId < NMapPOIflagType.SINGLE_MARKER_END) { resourceId = getResourceIdOnMapView(markerId, focused, mResourceIdsForMarkerOnMap); if (resourceId > 0) { return resourceId; } } if (markerId >= NMapPOIflagType.NUMBER_BASE && markerId < NMapPOIflagType.NUMBER_END) { // Direction Number icons } else if (markerId >= NMapPOIflagType.CUSTOM_BASE && markerId < NMapPOIflagType.CUSTOM_END) { // Custom POI icons } return resourceId; } /** * Set bounds for this marker depending on its shape. * */ @Override protected void setBounds(Drawable marker, int markerId, NMapOverlayItem item) { // check shape of the marker to set bounds correctly. if (NMapPOIflagType.isBoundsCentered(markerId)) { if (marker.getBounds().isEmpty()) { NMapOverlayItem.boundCenter(marker); } if (null != item) { item.setAnchorRatio(0.5f, 0.5f); } } else { if (marker.getBounds().isEmpty()) { NMapOverlayItem.boundCenterBottom(marker); } if (null != item) { item.setAnchorRatio(0.5f, 1.0f); } } } @Override public Drawable[] getLocationDot() { Drawable[] drawable = new Drawable[2]; drawable[0] = mContext.getResources().getDrawable(R.drawable.pubtrans_ic_mylocation_off); drawable[1] = mContext.getResources().getDrawable(R.drawable.pubtrans_ic_mylocation_on); for (int i = 0; i < drawable.length; i++) { int w = drawable[i].getIntrinsicWidth() / 2; int h = drawable[i].getIntrinsicHeight() / 2; drawable[i].setBounds(-w, -h, w, h); } return drawable; } @Override public Drawable getDirectionArrow() { Drawable drawable = mContext.getResources().getDrawable(R.drawable.ic_angle); if (drawable != null) { int w = drawable.getIntrinsicWidth() / 2; int h = drawable.getIntrinsicHeight() / 2; drawable.setBounds(-w, -h, w, h); } return drawable; } public Drawable getDrawableWithNumber(int resourceId, String strNumber, float offsetY, int fontColor, float fontSize) { Bitmap textBitmap = getBitmapWithText(resourceId, strNumber, fontColor, fontSize, offsetY); //Log.i(LOG_TAG, "getDrawableWithNumber: width=" + textBitmap.getWidth() + ", height=" + textBitmap.getHeight() + ", density=" + textBitmap.getDensity()); // set bounds Drawable marker = new BitmapDrawable(mContext.getResources(), textBitmap); if (marker != null) { NMapOverlayItem.boundCenter(marker); } //Log.i(LOG_TAG, "getDrawableWithNumber: width=" + marker.getIntrinsicWidth() + ", height=" + marker.getIntrinsicHeight()); return marker; } public Drawable getDrawableWithAlphabet(int resourceId, String strAlphabet, int fontColor, float fontSize) { Bitmap textBitmap = getBitmapWithText(resourceId, strAlphabet, fontColor, fontSize, POI_FONT_OFFSET_ALPHABET); // set bounds Drawable marker = new BitmapDrawable(mContext.getResources(), textBitmap); if (marker != null) { NMapOverlayItem.boundCenterBottom(marker); } return marker; } @Override protected Drawable getDrawableForMarker(int markerId, boolean focused, NMapOverlayItem item) { Drawable drawable = null; if (markerId >= NMapPOIflagType.NUMBER_BASE && markerId < NMapPOIflagType.NUMBER_END) { // Direction Number icons int resourceId = (focused) ? R.drawable.ic_map_no_02 : R.drawable.ic_map_no_01; int fontColor = (focused) ? POI_FONT_COLOR_ALPHABET : POI_FONT_COLOR_NUMBER; String strNumber = String.valueOf(markerId - NMapPOIflagType.NUMBER_BASE); drawable = getDrawableWithNumber(resourceId, strNumber, 0.0F, fontColor, POI_FONT_SIZE_NUMBER); } else if (markerId >= NMapPOIflagType.CUSTOM_BASE && markerId < NMapPOIflagType.CUSTOM_END) { // Custom POI icons } return drawable; } private Bitmap getBitmapWithText(int resourceId, String strNumber, int fontColor, float fontSize, float offsetY) { Bitmap bitmapBackground = BitmapFactory.decodeResource(mContext.getResources(), resourceId); int width = bitmapBackground.getWidth(); int height = bitmapBackground.getHeight(); //Log.i(LOG_TAG, "getBitmapWithText: width=" + width + ", height=" + height + ", density=" + bitmapBackground.getDensity()); Bitmap textBitmap = Bitmap.createBitmap(width, height, BITMAP_CONFIG_DEFAULT); Canvas canvas = new Canvas(textBitmap); canvas.drawBitmap(bitmapBackground, 0, 0, null); // set font style mTextPaint.setColor(fontColor); // set font size mTextPaint.setTextSize(fontSize * mScaleFactor); // set font type if (POI_FONT_TYPEFACE != null) { mTextPaint.setTypeface(POI_FONT_TYPEFACE); } // get text offset mTextPaint.getTextBounds(strNumber, 0, strNumber.length(), mTempRect); float offsetX = (width - mTempRect.width()) / 2 - mTempRect.left; if (offsetY == 0.0F) { offsetY = (height - mTempRect.height()) / 2 + mTempRect.height(); } else { offsetY = offsetY * mScaleFactor + mTempRect.height(); } //Log.i(LOG_TAG, "getBitmapWithText: number=" + number + ", focused=" + focused); //Log.i(LOG_TAG, "getBitmapWithText: offsetX=" + offsetX + ", offsetY=" + offsetY + ", boundsWidth=" + mTempRect.width() + ", boundsHeight=" + mTempRect.height()); // draw text canvas.drawText(strNumber, offsetX, offsetY, mTextPaint); return textBitmap; } @Override public Drawable getCalloutBackground(NMapOverlayItem item) { if (item instanceof NMapPOIitem) { NMapPOIitem poiItem = (NMapPOIitem)item; if (poiItem.showRightButton()) { Drawable drawable = mContext.getResources().getDrawable(R.drawable.bg_speech); return drawable; } } Drawable drawable = mContext.getResources().getDrawable(R.drawable.pin_ballon_bg); return drawable; } @Override public String getCalloutRightButtonText(NMapOverlayItem item) { if (item instanceof NMapPOIitem) { NMapPOIitem poiItem = (NMapPOIitem)item; if (poiItem.showRightButton()) { return mContext.getResources().getString(R.string.str_done); } } return null; } @Override public Drawable[] getCalloutRightButton(NMapOverlayItem item) { if (item instanceof NMapPOIitem) { NMapPOIitem poiItem = (NMapPOIitem)item; if (poiItem.showRightButton()) { Drawable[] drawable = new Drawable[3]; drawable[0] = mContext.getResources().getDrawable(R.drawable.btn_green_normal); drawable[1] = mContext.getResources().getDrawable(R.drawable.btn_green_pressed); drawable[2] = mContext.getResources().getDrawable(R.drawable.btn_green_highlight); return drawable; } } return null; } @Override public Drawable[] getCalloutRightAccessory(NMapOverlayItem item) { if (item instanceof NMapPOIitem) { NMapPOIitem poiItem = (NMapPOIitem)item; if (poiItem.hasRightAccessory() && (poiItem.getRightAccessoryId() > 0)) { Drawable[] drawable = new Drawable[3]; switch (poiItem.getRightAccessoryId()) { case NMapPOIflagType.CLICKABLE_ARROW: drawable[0] = mContext.getResources().getDrawable(R.drawable.pin_ballon_arrow); drawable[1] = mContext.getResources().getDrawable(R.drawable.pin_ballon_on_arrow); drawable[2] = mContext.getResources().getDrawable(R.drawable.pin_ballon_on_arrow); break; } return drawable; } } return null; } /** * * * @param item * @return * @see com.nhn.android.mapviewer.overlay.NMapCalloutCustomOverlay.ResourceProvider#getCalloutTextColors(com.nhn.android.maps.NMapOverlayItem) */ @Override public int[] getCalloutTextColors(NMapOverlayItem item) { int[] colors = new int[4]; colors[0] = CALLOUT_TEXT_COLOR_NORMAL; colors[1] = CALLOUT_TEXT_COLOR_PRESSED; colors[2] = CALLOUT_TEXT_COLOR_SELECTED; colors[3] = CALLOUT_TEXT_COLOR_FOCUSED; return colors; } @Override public int getParentLayoutIdForOverlappedListView() { // not supported return 0; } @Override public int getOverlappedListViewId() { // not supported return 0; } @Override public int getLayoutIdForOverlappedListView() { // not supported return 0; } @Override public int getListItemLayoutIdForOverlappedListView() { // not supported return 0; } @Override public int getListItemTextViewId() { // not supported return 0; } @Override public int getListItemTailTextViewId() { // not supported return 0; } @Override public int getListItemImageViewId() { // not supported return 0; } @Override public int getListItemDividerId() { // not supported return 0; } @Override public void setOverlappedListViewLayout(ListView listView, int itemCount, int width, int height) { // not supported } @Override public void setOverlappedItemResource(NMapPOIitem poiItem, ImageView imageView) { // not supported } private int getResourceIdOnMapView(int markerId, boolean focused, ResourceIdsOnMap resourceIdsArray[]) { int resourceId = 0; for (ResourceIdsOnMap resourceIds : resourceIdsArray) { if (resourceIds.markerId == markerId) { resourceId = (focused) ? resourceIds.resourceIdFocused : resourceIds.resourceId; break; } } return resourceId; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/NMapViewerResourceProvider.java
Java
epl
14,656
package com.example.photocapsule; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.ImageView; public class MainActivity extends Activity { ImageView main_imageButton_camera, main_imageButton_album; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_imageButton_camera = (ImageView)findViewById(R.id.main_imageButton_camera); main_imageButton_album = (ImageView)findViewById(R.id.main_imageButton_album); main_imageButton_camera.setOnClickListener(imageButtonClickListener); main_imageButton_album.setOnClickListener(imageButtonClickListener); } ImageView.OnClickListener imageButtonClickListener = new ImageView.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.main_imageButton_camera: Intent intent_camera = new Intent(MainActivity.this, CameraActivity.class); startActivity(intent_camera); break; case R.id.main_imageButton_album: Intent intent_album = new Intent(MainActivity.this, AlbumActivity.class); startActivity(intent_album); break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
zzikgong
trunk/PhotoCapsule/src/com/example/photocapsule/MainActivity.java
Java
epl
1,560
package com.example.mobilemultimediacontents_timecapsule; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class AlbumActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_album); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.album, menu); return true; } }
zzikgong
trunk/MobileMultimediaContents_TimeCapsule/src/com/example/mobilemultimediacontents_timecapsule/AlbumActivity.java
Java
epl
565
package com.example.mobilemultimediacontents_timecapsule; import android.os.Bundle; import android.os.Handler; import android.app.Activity; import android.content.Intent; import android.view.Menu; public class SplashActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub Intent intent = new Intent(SplashActivity.this, IntroActivity.class); startActivity(intent); finish(); } }, 4000); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.splash, menu); return true; } }
zzikgong
trunk/MobileMultimediaContents_TimeCapsule/src/com/example/mobilemultimediacontents_timecapsule/SplashActivity.java
Java
epl
930
package com.example.mobilemultimediacontents_timecapsule; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.ImageButton; public class IntroActivity extends Activity { ImageButton intro_imageButton_ok; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intro); intro_imageButton_ok = (ImageButton)findViewById(R.id.intro_imageButton_ok); intro_imageButton_ok.setOnClickListener(imageButtonClickListener); } ImageButton.OnClickListener imageButtonClickListener = new ImageButton.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()) { case R.id.intro_imageButton_ok : Intent intent_main = new Intent(IntroActivity.this, MainActivity.class); startActivity(intent_main); break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.intro, menu); return true; } }
zzikgong
trunk/MobileMultimediaContents_TimeCapsule/src/com/example/mobilemultimediacontents_timecapsule/IntroActivity.java
Java
epl
1,238
package com.example.mobilemultimediacontents_timecapsule; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.widget.ImageButton; public class MainActivity extends Activity { ImageButton main_imageButton_camera, main_imageButton_album; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); main_imageButton_camera = (ImageButton)findViewById(R.id.main_imageButton_camera); main_imageButton_album = (ImageButton)findViewById(R.id.main_imageButton_album); main_imageButton_camera.setOnClickListener(imageButtonClickListener); main_imageButton_album.setOnClickListener(imageButtonClickListener); } ImageButton.OnClickListener imageButtonClickListener = new ImageButton.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.main_imageButton_camera: Intent intent_camera = new Intent(MainActivity.this, CameraActivity.class); startActivity(intent_camera); break; case R.id.main_imageButton_album: Intent intent_album = new Intent(MainActivity.this, AlbumActivity.class); startActivity(intent_album); break; } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
zzikgong
trunk/MobileMultimediaContents_TimeCapsule/src/com/example/mobilemultimediacontents_timecapsule/MainActivity.java
Java
epl
1,596
<!DOCTYPE html> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%> <html> <head> <meta charset="utf-8"> <title>Welcome</title> </head> <body> <c:url value="/showMessage.html" var="messageUrl" /> <a href="${messageUrl}">Click to enter</a> </body> </html>
zzizily-examples
sswm/src/main/webapp/index.jsp
Java Server Pages
asf20
446
<!DOCTYPE html> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta charset="utf-8"> <title>Welcome</title> </head> <body> <h2>${message}</h2> </body> </html>
zzizily-examples
sswm/src/main/webapp/WEB-INF/view/showMessage.jsp
Java Server Pages
asf20
231
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ /* * File: type.h * Author: zhouzhao * * Created on November 23, 2010, 5:28 PM */ #ifndef MAIN_H #define MAIN_H //macro definition #define NUMFUNCS 5 #define MAXLINE 81 #define MAXNAME 31 #define FLIPFLOP 256 #define Upcase(x) ((isalpha(x) && islower(x))? toupper(x) : (x)) #define Lowcase(x) ((isalpha(x) && isupper(x))? tolower(x) : (x)) //type definition enum e_com {READ, PC, HELP, QUIT, LEV}; enum e_ntype {GATE, PI, FB, PO, PPI, PPO}; //gate=0, primary input=1, fanout branch=2, primary output=3, PPI=4, PPO=5 typedef struct logicEvent{ Node* line; int logic; struct logicEvent* nextEvent; } LEVENT; typedef struct graphEvent{ int time; int logic; } GEVENT; typedef struct timeStamp{ int time; struct logicEvent* eventHead; struct logicEvent* eventTail; struct timeStamp* nextStamp; } TSTAMP; typedef struct assignment{ Node* line; e_logic logic; e_direction direct; struct assignment* next; } ASSIGN; #endif /* MAIN_H */
zzfall2010ee658
type.h
C
gpl3
1,741
fpgaTest.exe: Command.o Node.o atpg.o fileRead.o fileWrite.o global.o logicSim.o main.o preprocess.o g++ Command.o Node.o atpg.o fileRead.o fileWrite.o global.o logicSim.o main.o preprocess.o -o fpgaTest.exe Command.o: Command.cpp Command.h g++ -c Command.cpp Node.o: Node.cpp Node.h atpg.h g++ -c Node.cpp atpg.o: atpg.cpp Node.h Command.h global.h type.h preprocess.h atpg.h fileRead.h fileWrite.h g++ -c atpg.cpp fileRead.o: fileRead.cpp Node.h Command.h global.h type.h fileRead.h preprocess.h g++ -c fileRead.cpp fileWrite.o: fileWrite.cpp Node.h Command.h global.h type.h fileWrite.h g++ -c fileWrite.cpp global.o: global.cpp Node.h Command.h global.h g++ -c global.cpp logicSim.o: logicSim.cpp Node.h Command.h global.h type.h logicSim.h fileRead.h fileWrite.h g++ -c logicSim.cpp main.o: main.cpp Node.h Command.h fileRead.h global.h type.h logicSim.h preprocess.h fileWrite.h atpg.h g++ -c main.cpp preprocess.o: preprocess.cpp Node.h Command.h global.h type.h preprocess.h fileRead.h fileWrite.h g++ -c preprocess.cpp clean: rm -f *.o *.exe
zzfall2010ee658
Makefile
Makefile
gpl3
1,064
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ /* * File: command.cpp * Author: zhouzhao * * Created on October 15, 2010, 11:21 AM */ #include "Command.h" Command::Command() { } Command::Command(const Command& orig) { } Command::~Command() { } char * Command::getName(){ return this->name; } e_state Command::getState(){ return this->state; }
zzfall2010ee658
Command.cpp
C++
gpl3
1,067
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ /* * File: fileWrite.h * Author: zhouzhao * * Created on November 23, 2010, 9:28 PM */ #ifndef FILEWRITE_H #define FILEWRITE_H int printWaveform(); //print waveform file int printPO_FF(); //print PO and FF status file during each clock int printGlitch(); //print glitch file void printDisplayBuffer(); //print waveform data structure in stdout void printCompareBuffer(); //print compare data structure in stdout int printDominance(); //print dominance relationship int printScanNetlist(); //print scan netlist file int printLevel(); //print level of netlist int printFilteredFault(); //print fault list after collapsing int printTestPattern(); #endif /* FILEWRITE_H */
zzfall2010ee658
fileWrite.h
C
gpl3
1,422
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ /* * File: node.h * Author: zhouzhao * * Created on October 15, 2010, 11:30 AM */ #ifndef NODE_H #define NODE_H #include <string> #include <iostream> #include <vector> #include <map> using namespace std; enum e_logic {ZERO=0,DBAR=1,D=2,ONE=3,X=4}; //enum logic for ATPG enum e_direction{BACKWARD, FORWARD}; //propagate direction string translate(unsigned int value); //B:=boolean struct B_number{ unsigned number; unsigned dashes; bool used; }; //D:=D cube struct D_number{ unsigned int numberA; unsigned int numberB; e_logic output; }; //F:= fault typedef struct F_number{ unsigned int fault; vector< struct F_number* > domPointer; } FSTRUCT; class Node { private: //data struture for preprocessing unsigned int index; unsigned int type; unsigned int number; unsigned int gate; vector<unsigned int> faultList; unsigned int fanout; unsigned int fanin; Node ** upperNodes; int upperCounter; Node ** downNodes; int downCounter; unsigned int level; int nodeReady; int inputReady; //data structure for fault dominance vector<F_number> domRelation; //data structure for logic simulation int logicValue; int lsv; //lsv:=last scheduled value unsigned int inertialDelay; unsigned int riseDelay; unsigned int fallDelay; //data structure for ATPG e_logic e_logicValue; int logicReady; unsigned int goodCLB[8]; unsigned int badCLB[8]; unsigned int dCLB[8]; unsigned int dbarCLB[8]; vector< vector<B_number> > table; //first table for logic minimization vector< vector<B_number> > p_group; //second table vector< vector<B_number> > final_group; //third table vector<B_number> printed_numbers; //internal data structure vector<B_number> stored_numbers; //internal data structure vector< vector<e_logic> > outputOne; //primitive one cube vector< vector<e_logic> > outputZero; //primitive zero cube vector< vector<e_logic> > detectD; //primitive cube to detect D vector< vector<e_logic> > detectDbar; //primitive cube to detect Dbar vector<D_number> dcube; //internal data structure vector< vector<e_logic> > ddrive; //primitive cube to drive D //private methods called by primitve cube process unsigned count_1s(unsigned number); //count the number of 1s in a number void print_binary(unsigned number); //print the number in binary void create_table(unsigned int*, unsigned int); //create original table sorted by the number of 1s void print_table(); //print the table B_number init_B_number(unsigned n,int d, bool u); //initialize a B_number void create_p_group(); //create mid process table void print_p_group(); //print it void print_p_binary(unsigned n, unsigned d); //print the mid table (with -'s) void create_final_group(); //create final table void print_final_group(); //print final table with -'s and unused terms bool is_printed(B_number n); //dont print terms that were already printed void getinput(); //get input from user unsigned count_bits(unsigned n); //min bits to represent a number void create_p_table(vector< vector<e_logic> >*); //create primitive cube table void print_p_table(vector< vector<e_logic> >*); //print primitive cube table void create_d_array(); //create D cube array void process(unsigned int* clb, unsigned int flag, vector< vector<e_logic> >* table); //internal process //private methods called by D cube process void decimal2binary(unsigned int number, unsigned int* bits, int digit); //convert decimal to binary unsigned int binary2decimal(unsigned int* bits, int digit); //convert binary to decimal D_number init_D_number(unsigned int na, unsigned int nb, e_logic out); //constructor for D cube void d_drive(int digit, e_logic fault); //drive D through CLB void print_d_table(); //print D cube table void create_d_table(); //create D cube table //private methods to find dominance relationship void create_dom_table(); //create tree structure of dominance F_number* findFault(unsigned int fault); //find fault in the tree int findDominance(int fa, int fb); //find dominance relationship between two faults public: void nodeClear(); Node(); int pCubeProcess(); int fCubeProcess(int faultNum); int findFaultNum(unsigned int fault); int dCubeProcess(int digit, e_logic fault); int domProcess(){ create_dom_table(); return 1; } void print_dom_table(); F_number* getDomRelation(int index); unsigned int getIndex(); void setIndex(unsigned int); unsigned int getType(); void setType(unsigned int); unsigned int getNumber(); void setNumber(unsigned int); unsigned int getGate(); void setGate(unsigned int); unsigned int getFaultList(int index); unsigned int getFaultListCount(); void setFaultList(unsigned int fault); unsigned int getFanin(); void setFanin(unsigned int); unsigned int getFanout(); void setFanout(unsigned int); Node ** getUpperNodes(); void setUpperNodes(Node **); int getUpperCounter(); void setUpperCounter(int); Node ** getDownNodes(); void setDownNodes(Node **); int getDownCounter(); void setDownCounter(int); unsigned int getLevel(); void setLevel(unsigned int); int getNodeReady(); void setNodeReady(int); int getInputReady(); void setInputReady(int); int getLogicValue(); int getLogicOutput(int index); void setLogicValue(int); int getLSV(); void setLSV(int value); unsigned int getInertialDelay(); void setInertialDelay(unsigned int); unsigned int getRiseDelay(); void setRiseDelay(unsigned int); unsigned int getFallDelay(); void setFallDelay(unsigned int); e_logic getLogicValue_E(); void setLogicValue_E(e_logic value); int getLogicReady(); void setLogicReady(int value); int searchOutputOne(vector<e_logic> pattern); int searchOutputZero(vector<e_logic> pattern); vector< vector<e_logic> > getOutputOne(); vector< vector<e_logic> > getOutputZero(); vector< vector<e_logic> > getDetectD(); vector< vector<e_logic> > getDectectDbar(); vector< vector<e_logic> > getDDrive(); }; #endif /* NODE_H */
zzfall2010ee658
Node.h
C++
gpl3
7,135
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ /* * File: node.cpp * Author: zhouzhao * * Created on October 14, 2010, 9:43 PM */ #include "Node.h" #include "atpg.h" #define MIN_BITS 3 Node::Node(){ //data structure for preprocssing index = 0; type = 0; number = 0; gate = 0; faultList.clear(); fanin = 0; fanout = 0; upperNodes = 0; upperCounter = 0; downNodes = 0; downCounter = 0; level = 0; nodeReady = 0; inputReady = 0; //data structure for fault domiance domRelation.clear(); //data structure for logic simulation logicValue = 2; //variable is used for logic simulation lsv = 2; //last scheduled value inertialDelay = 0; riseDelay = 0; fallDelay = 0; //data structure for ATPG e_logicValue = X; //variable is used for ATPG logicReady = 0; for(int i=0;i<8;i++){ goodCLB[i]=0; badCLB[i]=0; dCLB[i]=0; dbarCLB[i]=0; } table.clear(); //first table for logic minimization p_group.clear(); //second table final_group.clear(); //third table printed_numbers.clear(); //internal data structure stored_numbers.clear(); //internal data structure outputOne.clear(); //primitive one cube outputZero.clear(); //primitive zero cube detectD.clear(); //primitive cube to detect D detectDbar.clear(); //primitive cube to detect Dbar dcube.clear(); //internal data structure ddrive.clear(); //primitive cube to drive D } unsigned int Node::getIndex(){ return this->index; } void Node::setIndex(unsigned int index){ this->index = index; } unsigned int Node::getType(){ return this->type; } void Node::setType(unsigned int type){ this->type = type; } unsigned int Node::getNumber(){ return this->number; } void Node::setNumber(unsigned int number){ this->number = number; } unsigned int Node::getGate(){ return this->gate; } void Node::setGate(unsigned int gate){ this->gate = gate; } unsigned int Node::getFaultList(int index){ return this->faultList[index]; } unsigned int Node::getFaultListCount(){ return this->faultList.size(); } void Node::setFaultList(unsigned int fault){ int i; for(i=0;i<faultList.size();i++){ if(faultList[i]==fault){ //reduce fault redundancy return; } } faultList.push_back(fault); } unsigned int Node::getFanin(){ return this->fanin; } void Node::setFanin(unsigned int fanin){ this->fanin = fanin; } unsigned int Node::getFanout(){ return this->fanout; } void Node::setFanout(unsigned int fanout){ this->fanout = fanout; } Node ** Node::getUpperNodes(){ return this->upperNodes; } void Node::setUpperNodes(Node ** upperNodes){ this->upperNodes = upperNodes; } int Node::getUpperCounter(){ return this->upperCounter; } void Node::setUpperCounter(int upperCounter){ this->upperCounter = upperCounter; } Node ** Node::getDownNodes(){ return this->downNodes; } void Node::setDownNodes(Node ** downNodes){ this->downNodes = downNodes; } int Node::getDownCounter(){ return this->downCounter; } void Node::setDownCounter(int downCounter){ this->downCounter = downCounter; } unsigned int Node::getLevel(){ return this->level; } void Node::setLevel(unsigned int level){ this->level = level; } int Node::getNodeReady(){ return this->nodeReady; } void Node::setNodeReady(int nodeReady){ this->nodeReady = nodeReady; } int Node::getInputReady(){ return this->inputReady; } void Node::setInputReady(int inputReady){ this->inputReady = inputReady; } int Node::getLogicValue(){ return this->logicValue; } int Node::getLogicOutput(int index){ return this->goodCLB[index]; } void Node::setLogicValue(int logicValue){ this->logicValue = logicValue; } int Node::getLSV(){ return this->lsv; } void Node::setLSV(int value){ this->lsv = value; } unsigned int Node::getInertialDelay(){ return this->inertialDelay; } void Node::setInertialDelay(unsigned int inertialDelay){ this->inertialDelay = inertialDelay; } unsigned int Node::getRiseDelay(){ return this->riseDelay; } void Node::setRiseDelay(unsigned int riseDelay){ this->riseDelay = riseDelay; } unsigned int Node::getFallDelay(){ return this->fallDelay; } void Node::setFallDelay(unsigned int fallDelay){ this->fallDelay = fallDelay; } e_logic Node::getLogicValue_E(){ return this->e_logicValue; } void Node::setLogicValue_E(e_logic value){ this->e_logicValue = value; } //create D cube array void Node::create_d_array(){ int i; for(i=0;i<8;i++){ dCLB[i]=0; dbarCLB[i]=0; if(goodCLB[i] != badCLB[i]){ if(goodCLB[i]==1){ dCLB[i]=1; dbarCLB[i]=0; }else{ dCLB[i]=0; dbarCLB[i]=1; } } } /* for(i=0;i<8;i++){ cout<<dCLB[i]<<" "; } cout<<endl; for(i=0;i<8;i++){ cout<<dbarCLB[i]<<" "; } cout<<endl; */ } //gateway method to process primitive cube for each node int Node::pCubeProcess(){ cout<<"Node: "<<this->number<<endl; decimal2binary(gate,goodCLB, 8); //generate binary form of CLB number cout<<"One cube:"<<endl; process(goodCLB,1,&outputOne); //process primitive one cube cout<<"Zero cube:"<<endl; process(goodCLB,0,&outputZero); //process primitive zero cube return 0; } //gateway method to process primitve cube to detect a fault Note that int Node::fCubeProcess(int index){ cout<<"Node: "<<this->number<<endl; if(faultList.size()>0){ decimal2binary(faultList[index], badCLB, 8); create_d_array(); cout<<"D cube"<<endl; cout<<"----------------"<<endl; cout<<"1 2 3 | fault"<<endl; cout<<"----------------"<<endl; process(dCLB,1,&detectD); //process primitive cube to detect D at output cout<<"Dbar cube"<<endl; process(dbarCLB,1,&detectDbar); //process primitive cube to detect Dbar at output } return 0; } int Node::findFaultNum(unsigned int fault){ int i; for(i=0;i<faultList.size();i++){ if(faultList[i]==fault){ return i; } } cout<<"fault "<<fault<<" can not be found."<<endl; } //main process void Node::process(unsigned int* clb, unsigned int flag, vector<vector<e_logic> >* tab){ table.clear(); table.resize(1); p_group.clear(); p_group.resize(1); final_group.clear(); final_group.resize(1); printed_numbers.clear(); stored_numbers.clear(); create_table(clb,flag); // print_table(); create_p_group(); // print_p_group(); create_final_group(); print_final_group(); create_p_table(tab); print_p_table(tab); } //count the number of 1 in a number /* counts 1s by getting the LSB (%2) and then shifting until 0 */ unsigned Node::count_1s(unsigned number){ short bit =0; int count = 0; while(number>0) { bit = number%2; number>>=1; if(bit) { count++; } } return count; } //print a number in binary format /*get LSB, arrange it in array, the print array in reverse order so MSB is on the left */ void Node::print_binary(unsigned number){ unsigned bits[MIN_BITS]; int count = 0; while(number>0||count<MIN_BITS) { bits[count] = number%2; number>>= 1; count++; } for(int i=count-1;i>=0;i--) cout<<bits[i]; } //creat table based on the number of 1 in minterm /*creating first table: append current number to the array located in table[number of 1s f this number]*/ void Node::create_table(unsigned int* clb, unsigned int flag){ int i; short tmp; B_number temp_num; for(i=0;i<8;i++) { if(clb[i] == flag){ tmp = count_1s(i); if(tmp+1>table.size()) table.resize(tmp+1); temp_num = init_B_number(i,0,false); table[tmp].push_back(temp_num); } } // cout<<"table is created successfully."<<endl; } //print the first table void Node::print_table(){ cout<<endl<<"COMPUTING:"<<endl; for(int i=0;i<table.size();i++) { cout<<i; for(int j=0;j<table[i].size();j++) { cout<<"\tm"<<table[i][j].number<<"\t"; print_binary(table[i][j].number); cout<<endl; } cout<<"\n-------------------------------------"<<endl; } } //constructor of struct B_number /* initialize a B_number variable - like a constructor */ B_number Node::init_B_number(unsigned n,int d, bool u){ struct B_number num; num.number = n; num.dashes = d; num.used = u; return num; } //creat p_group in the middle process /*like the original table, but the paring of numbers from the original table- dashes are represented by a 1. for example original A=0011 B=1011, new number is -011 which is represented as C.number=A&B=0011,C.dashes=A^B=1000*/ void Node::create_p_group() { short tmp; B_number temp_num; unsigned temp_number, temp_dashes; for(int i=0;i<table.size()-1;i++) { for(int j=0;j<table[i].size();j++) { for(int k=0;k<table[i+1].size();k++) { temp_number = table[i][j].number & table[i+1][k].number; temp_dashes = table[i][j].number ^ table[i+1][k].number; if(count_1s(temp_dashes)==1) { table[i][j].used = true; table[i+1][k].used = true; tmp = count_1s(temp_number); if(tmp+1>p_group.size()) p_group.resize(tmp+1); temp_num = init_B_number(temp_number, temp_dashes, false); p_group[tmp].push_back(temp_num); } } } } // cout<<"primitive group is created successfully."<<endl; } //print the table of p_group void Node::print_p_group() { cout<<endl<<"MID PROCESS COMPUTATION:"<<endl; for(int i=0;i<p_group.size();i++) { cout<<i; for(int j=0;j<p_group[i].size();j++) { cout<<"\t\t"; print_p_binary(p_group[i][j].number,p_group[i][j].dashes); cout<<endl; } cout<<"\n-------------------------------------"<<endl; } } /*print a number such as -001; this allocates bits in an array dash=2 then prints reverse array */ void Node::print_p_binary(unsigned n, unsigned d) { unsigned bits[MIN_BITS]; int count = 0; while(n>0||count<MIN_BITS) { if(!(d%2)) bits[count] = n%2; else bits[count] = 2; n >>= 1; d >>= 1; count++; } for(int i=count-1;i>=0;i--) { if(bits[i]!=2) cout<<bits[i]; else cout<<"-"; } } //create primitive table void Node::create_p_table(vector< vector<e_logic> >* table){ unsigned bits[MIN_BITS]; int count; int i,j; unsigned n; unsigned d; table->resize(stored_numbers.size()); for(i=0;i<stored_numbers.size();i++){ n = stored_numbers[i].number; d = stored_numbers[i].dashes; count=0; while(n>0 || count<MIN_BITS){ if(!(d%2)){ bits[count] = n%2; }else{ bits[count] = 2; } n >>= 1; d >>= 1; count++; } for(j=MIN_BITS-1;j>=0;j--){ switch (bits[j]){ case 0: (*table)[i].push_back(ZERO); break; case 1: (*table)[i].push_back(ONE); break; case 2: (*table)[i].push_back(X); break; default: printf(""); } } } // cout<<"table of primitive cube is created successfully."<<endl; } //print primitive table void Node::print_p_table(vector< vector<e_logic> >* table){ int i,j; for(i=0;i<table->size();i++){ for(j=0;j<(*table)[i].size();j++){ cout<<translate((*table)[i][j])<<" "; } cout<<endl; } } /*creates final table. works like p_group(). example; in p_group you have: A=-001 B=-011 -> C= -0-1 which will be represented as C.number=A&B=0001&0011=0001, and C.dashes=A^B^A.dashes=0001^0011^1000=1010. Computation is done only when A.dashes = b.dashes*/ void Node::create_final_group() { short tmp; B_number temp_num; unsigned temp_number, temp_dashes; for(int i=0;i<p_group.size()-1;i++) { for(int j=0;j<p_group[i].size();j++) { for(int k=0;k<p_group[i+1].size();k++) { if(p_group[i][j].dashes == p_group[i+1][k].dashes) { temp_number = p_group[i][j].number & p_group[i+1][k].number; temp_dashes = p_group[i][j].number ^ p_group[i+1][k].number; if(count_1s(temp_dashes)==1) { temp_dashes^= p_group[i][j].dashes; p_group[i][j].used = true; p_group[i+1][k].used = true; tmp = count_1s(temp_number); if(tmp+1>final_group.size()) final_group.resize(tmp+1); temp_num = init_B_number(temp_number, temp_dashes, true); final_group[tmp].push_back(temp_num); } } } } } // cout<<"final group is created successfully."<<endl; } /*print all the values from the final table, except for duplicates. print all the unused numbers from original table and mid process table*/ void Node::print_final_group() { // cout<<endl<<"FINAL:\n-------------------------------------"<<endl; int i,j; for(i=0;i<final_group.size();i++) { for(j=0;j<final_group[i].size();j++) { if(!is_printed(final_group[i][j])) { print_p_binary(final_group[i][j].number,final_group[i][j].dashes); cout<<endl; printed_numbers.push_back(final_group[i][j]); stored_numbers.push_back(final_group[i][j]); } } } for(i=0;i<p_group.size();i++) { for(j=0;j<p_group[i].size();j++) { if(!p_group[i][j].used) { print_p_binary(p_group[i][j].number,p_group[i][j].dashes); cout<<endl; stored_numbers.push_back(p_group[i][j]); } } } for(i=0;i<table.size();i++) { for(j=0;j<table[i].size();j++) { if(!table[i][j].used) { print_p_binary(table[i][j].number,table[i][j].dashes); cout<<endl; stored_numbers.push_back(table[i][j]); } } } // cout<<"-------------------------------------"<<endl; } /*used to avoid printing duplicates that can exist in the final table*/ bool Node::is_printed(B_number n) { for(int i=0;i<printed_numbers.size();i++) if(n.number==printed_numbers[i].number && n.dashes == printed_numbers[i].dashes) return true; return false; } /*return min number of bits a number is represented by. used for best output*/ unsigned Node::count_bits(unsigned n) { short bit =0; int count = 0; while(n>0) { bit = n%2; n>>=1; count++; } return count; } //------------------------------------------------------------------------------ //create D cube table void Node::create_d_table(){ int i,j; unsigned int n; unsigned int d; unsigned int tempA, tempB; int count; unsigned int bits[MIN_BITS]; ddrive.resize(dcube.size()); for(i=0;i<dcube.size();i++){ tempA = dcube[i].numberA; tempB = dcube[i].numberB; n = tempA & tempB; d = tempA ^ tempB; count = 0; while(n>0 || count<MIN_BITS){ if(!(d%2)){ bits[count] = n%2; }else{ if(tempA%2){ bits[count] = 2; }else{ bits[count] = 3; } } n >>= 1; d >>= 1; tempA >>= 1; tempB >>= 1; count++; } for(j=MIN_BITS-1;j>=0;j--){ switch (bits[j]){ case 0: ddrive[i].push_back(ZERO); break; case 1: ddrive[i].push_back(ONE); break; case 2: ddrive[i].push_back(D); break; case 3: ddrive[i].push_back(DBAR); default: printf(""); } } ddrive[i].push_back(dcube[i].output); } } //print D cube table void Node::print_d_table(){ int i,j; cout<<"---------------"<<endl; cout<<"1 2 3 | output"<<endl; cout<<"---------------"<<endl; for(i=0;i<ddrive.size();i++){ for(j=0;j<ddrive[i].size();j++){ cout<<translate(ddrive[i][j])<<" "; } cout<<endl; } cout<<"---------------"<<endl; } //drive D or Dbar through CLB //digit is input bit of CLB 0=LSB 2=MSB void Node::d_drive(int digit, e_logic fault){ unsigned int bitsA[MIN_BITS]; unsigned int bitsB[MIN_BITS]; unsigned int buffer[MIN_BITS-1]; int i; unsigned int valueA, valueB; D_number temp; e_logic temp_logic; switch (fault){ case D: bitsA[digit]=1; bitsB[digit]=0; break; case DBAR: bitsA[digit]=0; bitsB[digit]=1; break; default: cout<<""<<endl; } for(i=0;i<4;i++){ decimal2binary(i,buffer,MIN_BITS); switch (digit){ case 0: bitsA[1]=buffer[0]; bitsB[1]=buffer[0]; bitsA[2]=buffer[1]; bitsB[2]=buffer[1]; valueA = binary2decimal(bitsA,MIN_BITS); valueB = binary2decimal(bitsB,MIN_BITS); if(goodCLB[valueA] != goodCLB[valueB]){ if(goodCLB[valueA] == 1){ temp_logic = D; }else{ temp_logic = DBAR; } temp = init_D_number(valueA,valueB,temp_logic); dcube.push_back(temp); } break; case 1: bitsA[0]=buffer[0]; bitsB[0]=buffer[0]; bitsA[2]=buffer[1]; bitsB[2]=buffer[1]; valueA = binary2decimal(bitsA,MIN_BITS); valueB = binary2decimal(bitsB,MIN_BITS); if(goodCLB[valueA] != goodCLB[valueB]){ if(goodCLB[valueA] == 1){ temp_logic = D; }else{ temp_logic = DBAR; } temp = init_D_number(valueA,valueB,temp_logic); dcube.push_back(temp); } break; case 2: bitsA[0]=buffer[0]; bitsB[0]=buffer[0]; bitsA[1]=buffer[1]; bitsB[1]=buffer[1]; valueA = binary2decimal(bitsA,MIN_BITS); valueB = binary2decimal(bitsB,MIN_BITS); if(goodCLB[valueA] != goodCLB[valueB]){ if(goodCLB[valueA] == 1){ temp_logic = D; }else{ temp_logic = DBAR; } temp = init_D_number(valueA,valueB,temp_logic); dcube.push_back(temp); } break; default: cout<<""<<endl; } } /* for(i=0;i<dcube.size();i++){ cout<<dcube[i].numberA<<" "<<dcube[i].numberB<<" "<<dcube[i].output<<endl; } */ } //constructor for D cube struct D_number Node::init_D_number(unsigned int na, unsigned int nb, e_logic out){ struct D_number num; num.numberA = na; num.numberB = nb; num.output = out; return num; } //convert binary index into decimal index unsigned int Node::binary2decimal(unsigned int* bits, int digit){ int i; unsigned int result = 0; unsigned int weight = 1; for(i=0;i<digit;i++){ result += bits[i]*weight; weight *=2; } return result; } //convert decimal index into binary index void Node::decimal2binary(unsigned int number, unsigned int* bits, int digit) { int count = 0; while(number>0||count<digit) { bits[count] = number%2; number>>= 1; count++; } } //gateway methods for process D cube int Node::dCubeProcess(int digit, e_logic fault){ d_drive(digit, fault); create_d_table(); print_d_table(); return 0; } //private methods called by dominace process void Node::create_dom_table(){ int i,j; unsigned int fault; //build up data structure of dominance for(i=0;i<faultList.size();i++){ fault=faultList[i]; vector<F_number*> temp; FSTRUCT* fp = new FSTRUCT; fp->fault=fault; fp->domPointer = temp; domRelation.push_back(*fp); } for(i=0;i<faultList.size();i++){ fault = faultList[i]; for(j=0;j<faultList.size();j++){ if(faultList[j]!=fault){ if(findDominance(fault,faultList[j])){ findFault(fault)->domPointer.push_back(findFault(faultList[j])); } } } } } //find a fault in data structure of dominance tree F_number* Node::findFault(unsigned int fault){ int i; for(i=0;i<domRelation.size();i++){ if(domRelation[i].fault == fault){ return &domRelation[i]; } } return NULL; } //find dominance relationship betweeen two faults int Node::findDominance(int fa, int fb){ unsigned int detecta[8]; unsigned int detectb[8]; int i; decimal2binary(gate^fa,detecta,8); decimal2binary(gate^fb,detectb,8); for(i=0;i<8;i++){ if(detectb[i]==1 && detecta[i]!=1){ return 0; } } return 1; } //print data structure of dominance relationship void Node::print_dom_table(){ int i,j; vector<F_number*> temp; for(i=0;i<domRelation.size();i++){ if(domRelation[i].domPointer.size()!=0){ cout<<"fault "<<domRelation[i].fault<<" dom "; temp = domRelation[i].domPointer; for(j=0;j<temp.size();j++){ cout<<temp[j]->fault<<" "; } cout<<endl; } } } F_number* Node::getDomRelation(int index){ return &domRelation[index]; } //atpg-------------------------------------------------------------------------- int Node::searchOutputOne(vector<e_logic> pattern){ int i; for(i=0;i<outputOne.size();i++){ if(outputOne[i] == pattern || compatible_V(outputOne[i], pattern)){ return 1; } } return 0; } int Node::searchOutputZero(vector<e_logic> pattern){ int i; for(i=0;i<outputZero.size();i++){ if(outputZero[i] == pattern || compatible_V(outputZero[i], pattern)){ return 1; } } return 0; } vector< vector<e_logic> > Node::getOutputOne(){ return this->outputOne; } vector< vector<e_logic> > Node::getOutputZero(){ return this->outputZero; } vector< vector<e_logic> > Node::getDetectD(){ return this->detectD; } vector< vector<e_logic> > Node::getDectectDbar(){ return this->detectDbar; } vector< vector<e_logic> > Node::getDDrive(){ return this->ddrive; } //translate enum type into string string translate(unsigned int value){ switch (value){ case 0: return ("0"); case 1: return ("Dbar"); case 2: return ("D"); case 3: return ("1"); case 4: return ("x"); default: printf(" "); } } int Node::getLogicReady(){ return this->logicReady; } void Node::setLogicReady(int value){ this->logicReady = value; } void Node::nodeClear(){ int i; this->e_logicValue = X; this->logicReady = 0; this->table.clear(); this->p_group.clear(); this->final_group.clear(); this->printed_numbers.clear(); this->stored_numbers.clear(); this->outputOne.clear(); this->outputZero.clear(); this->detectD.clear(); this->detectDbar.clear(); this->dcube.clear(); this->ddrive.clear(); }
zzfall2010ee658
Node.cpp
C++
gpl3
24,791
/* * File: atpg.h * Author: zhouzhao * * Created on November 25, 2010, 5:32 PM */ #ifndef ATPG_H #define ATPG_H #include "type.h" #include "Node.h" int implyCheck(Node* np); int implyProcess(int num, e_logic logic, e_direction direction); int propagate(Node* node, e_logic value, e_direction direction); e_logic atpgEvaluate(Node* node); void atpgPush(Node* node, e_logic value, e_direction direction); int compatible_V(vector<e_logic> va, vector<e_logic> vb); int compatible(e_logic va, e_logic vb); ASSIGN* atpgPop(); void atpgQueue(ASSIGN* ps); void atpgElement(ASSIGN* ap); vector<Node*> findDFrontier(); int findD_Dbar(Node* np); //void addDFrontier(Node* np); int D_alg(Node* np); vector<Node*> findJFrontier(); //void addJFrontier(Node* np); int startupATPG(int number, int fault); int inputAllSpecified(); int initialATPG(); int storeTestPattern(); int atpg(); #endif /* ATPG_H */
zzfall2010ee658
atpg.h
C
gpl3
903
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <iostream> #include <vector> #include <map> #include "Node.h" #include "Command.h" #include "global.h" #include "type.h" #include "preprocess.h" #include "atpg.h" #include "fileRead.h" #include "fileWrite.h" using namespace std; int atpg(){ char filteredFaultFile[] = "filtered_fault_list.txt"; map<int, vector<int> >::iterator i; int j,k; vector<int> temp; iread(filteredFaultFile); for(i=filteredFault.begin();i!=filteredFault.end();i++){ temp = i->second; cout<<i->first<<": "; for(j=0;j<temp.size();j++){ cout<<temp[j]<<" "; } cout<<endl; } for(i=filteredFault.begin();i!=filteredFault.end();i++){ temp = i->second; for(j=0;j<temp.size();j++){ cout<<"CLB "<<i->first<<" with fault "<<temp[j]<<" is run for ATPG."<<endl; initialATPG(); startupATPG(i->first,temp[j]); storeTestPattern(); } } for(j=0;j<testPattern.size();j++){ for(k=0;k<testPattern[j].size();k++){ cout<<translate(testPattern[j][k])<<" "; } cout<<endl; } printTestPattern(); return 1; } int initialATPG(){ int i; for(i=0;i<NumberNodes;i++){ NodePointer[i].nodeClear(); } return 1; } int storeTestPattern(){ int i; vector<e_logic> temp; for(i=0;i<NumberPPI;i++){ temp.push_back(PPIList[i]->getLogicValue_E()); } for(i=0;i<NumberPI;i++){ temp.push_back(PrimaryInput[i]->getLogicValue_E()); } testPattern.push_back(temp); return 1; } int startupATPG(int number, int fault){ Node* np; vector< vector<e_logic> > temp; int i,j; np=findNode(number); np->fCubeProcess(np->findFaultNum(fault)); temp = np->getDetectD(); if(temp.size()!=0){ for(i=0;i<temp.size();i++){ for(j=0;j<temp[i].size();j++){ np->getUpperNodes()[j]->setLogicValue_E(temp[i][j]); } np->setLogicValue_E(D); if(D_alg(np)){ //store test pattern return 1; } } } temp = np->getDectectDbar(); if(temp.size()!=0){ for(i=0;i<temp.size();i++){ for(j=0;j<temp[i].size();j++){ np->getUpperNodes()[j]->setLogicValue_E(temp[i][j]); } np->setLogicValue_E(DBAR); if(D_alg(np)){ //store test pattern return 1; } } } return 0; } vector<Node*> findJFrontier(){ int i,j; Node* np; e_ntype type; vector<e_logic> temp; vector<Node*> jFrontier; for(i=0;i<NumberNodes;i++){ np = &NodePointer[i]; type = (e_ntype)np->getType(); if(type==GATE || type==PO || type==PPO){ for(j=0;j<np->getFanin();j++){ temp.push_back(np->getUpperNodes()[j]->getLogicValue_E()); } if(np->getLogicValue_E()==ONE && !(np->searchOutputOne(temp))){ jFrontier.push_back(np); } if(np->getLogicValue_E()==ZERO && !(np->searchOutputZero(temp))){ jFrontier.push_back(np); } } } cout<<"J-frontier: "; for(i=0;i<jFrontier.size();i++){ cout<<jFrontier[i]->getNumber()<<" "; } cout<<endl; return jFrontier; } //find node of D-frontier in the netlist vector<Node*> findDFrontier(){ int i; e_ntype type; vector<Node*> dFrontier; for(i=0;i<NumberNodes;i++){ type = (e_ntype)NodePointer[i].getType(); if(type==GATE || type==PO || type==PPO){ if(findD_Dbar(&NodePointer[i]) && NodePointer[i].getLogicValue_E()==X){ dFrontier.push_back(&NodePointer[i]); } } } cout<<"D-frontier: "; for(i=0;i<dFrontier.size();i++){ cout<<dFrontier[i]->getNumber()<<" "; } cout<<endl; return dFrontier; } //find D or Dbar on the fanin of the node and return index+1 int findD_Dbar(Node* np){ int i; e_logic logic; for(i=0;i<np->getFanin();i++){ logic = np->getUpperNodes()[i]->getLogicValue_E(); if(logic==D || logic==DBAR){ return i+1; //trick code } } return 0; } int faultAtPO_PPO(){ int i; e_logic temp; for(i=0;i<NumberPO;i++){ temp = PrimaryOutput[i]->getLogicValue_E(); if(temp==D || temp==DBAR){ return 1; } } for(i=0;i<NumberPPO;i++){ temp = PPOList[i]->getLogicValue_E(); if(temp==D || temp==DBAR){ return 1; } } return 0; } int inputAllSpecified(){ int i; for(i=0;i<NumberPI;i++){ if(PrimaryInput[i]->getLogicReady()==0){ return 0; } } for(i=0;i<NumberPPI;i++){ if(PPIList[i]->getLogicReady()==0){ return 0; } } return 1; } //core code of D-algorithm for ATPG 1=success 0=failure as shown in Fig. 6.23 of textbook int D_alg(Node* np){ Node* dp; Node* jp; int i,j,index; vector<Node*> localDFrontier; vector<Node*> localJFrontier; vector< vector<e_logic> > temp; //if imply and check fail then retrun fail if(!implyCheck(np)){ return 0; } localDFrontier=findDFrontier(); //update set of D-frontier //D-drive procedure if(!faultAtPO_PPO()){ //check if error is at PO if(localDFrontier.size()==0){ //if D-frontier is null then return fail return 0; } while(localDFrontier.size()!=0){ //select one untried CLB from D-frontier dp=localDFrontier[localDFrontier.size()-1]; cout<<"Node "<<dp->getNumber()<<" is selected for D drive."<<endl; localDFrontier.pop_back(); //D cube process for the selected node index = findD_Dbar(dp)-1; dp->dCubeProcess(2-index, dp->getUpperNodes()[index]->getLogicValue_E()); //trick code 2-index temp = dp->getDDrive(); //drive fault through the selected CLB if(temp.size()!=0){ for(i=0;i<temp.size();i++){ for(j=0;j<temp[i].size()-1;j++){ dp->getUpperNodes()[j]->setLogicValue_E(temp[i][j]); } dp->setLogicValue_E(temp[i][3]); if(D_alg(dp)){ //if recursive D_alg success then return success return 1; } } } } return 0; } //error propagate to one of POs //line justification procedure localJFrontier = findJFrontier(); if(localJFrontier.size()==0){ //if J-frontier is null then return success return 1; } jp=localJFrontier[localJFrontier.size()-1]; localJFrontier.pop_back(); while(!inputAllSpecified()){ if(jp->getLogicValue_E()==ONE){ temp = jp->getOutputOne(); }else{ temp = jp->getOutputZero(); } if(temp.size()!=0){ for(i=0;i<temp.size();i++){ for(j=0;j<temp[i].size();j++){ jp->getUpperNodes()[j]->setLogicValue_E(temp[i][j]); } if(D_alg(jp)){ return 1; } } } return 0; } return 0; //? } int implyCheck(Node* np){ int i; for(i=0;i<np->getFanin();i++){ if(!implyProcess(np->getUpperNodes()[i]->getNumber(), np->getUpperNodes()[i]->getLogicValue_E(), BACKWARD)){ return 0; } } if(!implyProcess(np->getNumber(), np->getLogicValue_E(), FORWARD)){ return 0; } return 1; } int implyProcess(int num, e_logic logic, e_direction direction){ ASSIGN* temp; atpgPush(findNode(num), logic, direction); while(temp=atpgPop()){ if(!propagate(temp->line, temp->logic, temp->direct)){ delete temp; return 0; } delete temp; } return 1; } int propagate(Node* node, e_logic value, e_direction direction){ int i; e_logic logic = node->getLogicValue_E(); e_logic temp; //check consistancy if(logic!=X && logic!=value){ cout<<"An inconsistancy is detected at line "<<node->getNumber()<<endl; return 0; }else{ node->setLogicValue_E(value); //implied value is consistant } //propagate signal with direction if(node->getType()==PI || node->getType()==PPI){ node->setLogicReady(1); if(direction == FORWARD){ if(node->getFanout() > 1){ for(i=0;i<node->getFanout();i++){ atpgPush(node->getDownNodes()[i], value, FORWARD); } }else{ temp = atpgEvaluate(node->getDownNodes()[0]); if(temp != X){ atpgPush(node->getDownNodes()[0], temp, FORWARD); } } }else{ cout<<"PI or PPI can not propagate backward."<<endl; } }else{ if(node->getType()==FB){ if(direction == FORWARD){ temp = atpgEvaluate(node->getDownNodes()[0]); if(temp != X){ atpgPush(node->getDownNodes()[0], temp, FORWARD); } }else{ atpgPush(node->getUpperNodes()[0], value, BACKWARD); for(i=0;i<node->getUpperNodes()[0]->getFanout();i++){ if(node->getUpperNodes()[0]->getDownNodes()[i]->getNumber() != node->getNumber()){ atpgPush(node->getUpperNodes()[0]->getDownNodes()[i], value, FORWARD); } } } }else{ if(direction == FORWARD){ if(node->getFanout() > 1){ for(i=0;i<node->getFanout();i++){ atpgPush(node->getDownNodes()[i], value, FORWARD); } }else{ if(node->getFanout()==1){ temp = atpgEvaluate(node->getDownNodes()[0]); if(temp != X){ atpgPush(node->getDownNodes()[0], temp, FORWARD); } } } }else{ if(value==ONE && node->getOutputOne().size()==1){ for(i=0;i<node->getFanin();i++){ atpgPush(node->getUpperNodes()[i], node->getOutputOne()[0][i], BACKWARD); } } if(value==ZERO && node->getOutputZero().size()==1){ for(i=0;i<node->getFanin();i++){ atpgPush(node->getUpperNodes()[i], node->getOutputZero()[0][i], BACKWARD); } } if(value==X){ for(i=0;i<node->getFanin();i++){ atpgPush(node->getUpperNodes()[i], X, BACKWARD); } } } } } return 1; } e_logic atpgEvaluate(Node* node){ vector<e_logic> temp; int i; e_logic logic = X;; if(node->getType()==PI || node->getType()==PPI){ logic = node->getLogicValue_E(); }else{ if(node->getType()==FB){ logic = node->getUpperNodes()[0]->getLogicValue_E(); }else{ for(i=0;i<node->getFanin();i++){ temp.push_back(node->getUpperNodes()[i]->getLogicValue_E()); } if(node->searchOutputOne(temp)){ logic = ONE; } if(node->searchOutputZero(temp)){ logic = ZERO; } } } return logic; } //va=primitive cube vb=pattern int compatible_V(vector<e_logic> va, vector<e_logic> vb){ int i; if(va.size()!=vb.size()){ return 0; } for(i=0;i<va.size();i++){ if(!compatible(va[i], vb[i])){ return 0; } } return 1; } int compatible(e_logic va, e_logic vb){ // if(va==X){ return 1; } if(va==vb){ return 1; }else{ return 0; } } void atpgPush(Node* node, e_logic value, e_direction direction){ ASSIGN* ap = new ASSIGN; ap->line = node; ap->logic = value; ap->direct = direction; ap->next = NULL; if(assignHead==NULL && assignTail==NULL){ cout<<"assignment queue is empty for first push"<<endl; assignHead = ap; assignTail = ap; }else{ assignTail->next = ap; assignTail = ap; } atpgQueue(assignHead); } ASSIGN* atpgPop(){ ASSIGN* temp; if(assignHead==NULL && assignTail==NULL){ cout<<"assignment queue is empty for final pop"<<endl; return NULL; } if(assignHead==assignTail){ temp=assignHead; assignHead = NULL; assignTail = NULL; return temp; } temp = assignHead; assignHead = assignHead->next; return temp; } void atpgQueue(ASSIGN* ps){ while(ps != NULL){ atpgElement(ps); ps = ps->next; } cout<<"END"<<endl; } void atpgElement(ASSIGN* ap){ if(ap){ cout<<"Number="<<ap->line->getNumber()<<" Value="<<translate(ap->logic)<<endl; }else{ cout<<"NULL assign pointer can not be printed"<<endl; } }
zzfall2010ee658
atpg.cpp
C++
gpl3
14,235
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ /* * File: command.h * Author: zhouzhao * * Created on October 15, 2010, 11:22 AM */ #ifndef COMMAND_H #define COMMAND_H enum e_state {EXEC, CKTLD}; /* Gstate values */ class Command { public: Command(); Command(const Command& orig); Command(char *name, int (*fptr)(), e_state state){ this->name = name; this->fptr1 = fptr; this->state = state; } Command(char *name, int (*fptr)(char *cptr), e_state state){ this->name = name; this->fptr2 = fptr; this->state = state; } virtual ~Command(); char * getName(); e_state getState(); private: char *name; /* command syntax */ int (*fptr1)(); /* function pointer of the commands */ int (*fptr2)(char *cptr); e_state state; /* execution state sequence */ }; #endif /* COMMAND_H */
zzfall2010ee658
Command.h
C++
gpl3
1,606
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ /* * File: preprocess.h * Author: zhouzhao * * Created on November 23, 2010, 6:00 PM */ #ifndef PREPROCESS_H #define PREPROCESS_H #include "Node.h" int preprocess(); int connectPointer(Node*, int); //build up fanin and fanout pointers between nodes int allocate(); //allocate memory int pc(); //print circuit int clear(); //deallocate memory Node* findNode(int); //find node in the node array int initialPI_PPI(); //initial level of PI and PPI for levelization int checkPO_PPO(); //check PO and PPO for levelization int levelComp(Node*); //levelize netlist int help(); //print help info int quit(); //quit process int lev(); //levelize netlist int removeFF(); //strip off flip flop #endif /* PREPROCESS_H */
zzfall2010ee658
preprocess.h
C
gpl3
1,462
/** * Copyright 2010 Zhou Zhao * * This file is part of FPGA test system for EE658 at USC * FPGA test system is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FPGA test system 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 General Public License for more details. You should have received a copy of the GNU General Public License along with the FPGA test system. If not, see <http://www.gnu.org/licenses/>. */ #include <string> #include <iostream> #include <vector> #include <map> #include "Node.h" #include "Command.h" #include "global.h" #include "type.h" #include "fileWrite.h" using namespace std; void printDisplayBuffer(){ map<int, vector<GEVENT> >::iterator i; int j; vector<GEVENT> temp; for(i=displayBuffer.begin();i!=displayBuffer.end();i++){ cout<<"line "<<i->first<<": "; temp = i->second; for(j=0;j<temp.size();j++){ cout<<"("<<temp[j].logic<<" @ "<<temp[j].time<<")"; } cout<<endl; } } void printCompareBuffer(){ map<int, vector<int> >::iterator i; int j; vector<int> temp; for(i=compareBuffer.begin();i!=compareBuffer.end();i++){ cout<<"line "<<i->first<<": "; temp = i->second; for(j=0;j<temp.size();j++){ cout<<temp[j]<<" "; } cout<<endl; } } int printScanNetlist(){ int i,j; char fileName[] = "scan_version_netlist.txt"; FILE* fileID; Node* np; fileID = fopen(fileName, "w"); if(fileID==NULL){ cout<<"scan file can not be opened."<<endl; return 0; } for(i=0;i<NumberNodes;i++){ np=&NodePointer[i]; if(np->getType()==PI || np->getType()==PPI){ fprintf(fileID, "%d %d %d %d %d\n", np->getType(), np->getNumber(), np->getGate(), np->getFanout(), np->getFanin()); }else{ if(np->getType()==PO || np->getType()==GATE || np->getType()==PPO){ fprintf(fileID, "%d %d %d %d %d ", np->getType(), np->getNumber(), np->getGate(), np->getFanout(), np->getFanin()); for(j=0;j<np->getFanin();j++){ fprintf(fileID, "%d ", np->getUpperNodes()[j]->getNumber()); } fprintf(fileID, "\n"); }else{ if(np->getType()==FB){ fprintf(fileID, "%d %d %d %d\n", np->getType(), np->getNumber(), np->getGate(), np->getUpperNodes()[0]->getNumber()); }else{ cout<<"print unknown type node."<<endl; } } } } fclose(fileID); return 1; } int printLevel(){ int i; char fileName[] = "logic_level.txt"; FILE* fileID; Node* np; fileID = fopen(fileName, "w"); if(fileID==NULL){ cout<<"level file can not be opened."<<endl; return 0; } for(i=0;i<NumberNodes;i++){ np=&NodePointer[i]; fprintf(fileID, "%d %d\n", np->getNumber(), np->getLevel()); } fclose(fileID); return 1; } int printWaveform(){ map<int, vector<GEVENT> >::iterator i; char fileName[] = "waveform.txt"; FILE* fileID; int j; vector<GEVENT> temp; fileID = fopen(fileName, "w"); if(fileID==NULL){ cout<<"waveform file can not be opened."<<endl; return 0; } for(i=displayBuffer.begin();i!=displayBuffer.end();i++){ fprintf(fileID, "%d ", i->first); temp = i->second; if(temp[0].time!=0){ fprintf(fileID, "x(%d-%d), ", 0, temp[0].time); } for(j=0;j<temp.size()-1;j++){ fprintf(fileID, "%d(%d-%d), ", temp[j].logic, temp[j].time, temp[j+1].time); } fprintf(fileID, "%d(%d-%d)\n", temp[j].logic, temp[j].time, (int)InputSequence.size()*ClockPeriod); } fclose(fileID); return 1; } int printPO_FF(){ char fileName[] = "PO_FF_state.txt"; FILE* fileID; int i,j,k; vector<GEVENT> temp; int cycle=InputSequence.size(); int ppi[NumberPPI][cycle]; int po[NumberPO][cycle]; for(i=0;i<NumberPPI;i++){ for(j=0;j<cycle;j++){ ppi[i][j]=2; } } for(i=0;i<NumberPO;i++){ for(j=0;j<cycle;j++){ po[i][j]=2; } } //process ppi array for(i=0;i<NumberPPI;i++){ temp=displayBuffer.find(PPIList[i]->getNumber())->second; for(j=0;j<temp.size();j++){ ppi[i][temp[j].time/ClockPeriod]=temp[j].logic; } k=ppi[i][0]; for(j=0;j<cycle;j++){ if(ppi[i][j]==2){ ppi[i][j]=k; }else{ k=ppi[i][j]; } } } //process po array for(i=0;i<NumberPO;i++){ temp=displayBuffer.find(PrimaryOutput[i]->getNumber())->second; for(j=0;j<temp.size();j++){ po[i][temp[j].time/ClockPeriod]=temp[j].logic; } k=po[i][0]; for(j=0;j<cycle;j++){ if(po[i][j]==2){ po[i][j]=k; }else{ k=po[i][j]; } } } //data pre-process is ready fileID = fopen(fileName, "w"); if(fileID==NULL){ cout<<"PO and FF state file can not be opened."<<endl; return 0; } for(i=0;i<NumberPPI;i++){ fprintf(fileID,"%d ", PPIList[i]->getNumber()); for(j=0;j<cycle;j++){ fprintf(fileID,"%d ", ppi[i][j]); } fprintf(fileID, "\n"); } for(i=0;i<NumberPO;i++){ fprintf(fileID, "%d ", PrimaryOutput[i]->getNumber()); for(j=0;j<cycle;j++){ fprintf(fileID,"%d ", po[i][j]); } fprintf(fileID, "\n"); } fclose(fileID); return 1; } int printGlitch(){ char fileName[] = "report_on_glitches.txt"; FILE* fileID; int i,j; vector<GEVENT> temp; int cycle = InputSequence.size(); int ppo[NumberPPO][cycle]; //pre-process ppo array for(i=0;i<NumberPPO;i++){ for(j=0;j<cycle;j++){ ppo[i][j]=2; } } for(i=0;i<NumberPPO;i++){ temp=displayBuffer.find(PPOList[i]->getNumber())->second; for(j=0;j<temp.size();j++){ if(temp[j].time%ClockPeriod==0 || (temp[j].time+1)%ClockPeriod==0){ ppo[i][temp[j].time/ClockPeriod]=temp[j].logic; } } } fileID = fopen(fileName, "w"); if(fileID==NULL){ cout<<"waveform file can not be opened."<<endl; return 0; } for(i=0;i<NumberPPO;i++){ fprintf(fileID, "%d ", PPOList[i]->getNumber()); for(j=0;j<cycle;j++){ switch (ppo[i][j]){ case 0: fprintf(fileID, "F "); break; case 1: fprintf(fileID, "R "); break; case 2: fprintf(fileID, "- "); break; } } fprintf(fileID, "\n"); } fclose(fileID); return 1; } int printDominance(){ char fileName[] = "equivalence_and_dominance_relationship.txt"; FILE* fileID; int i,j,k; F_number* temp; Node* np; fileID = fopen(fileName, "w"); if(fileID==NULL){ cout<<"dominance file can not be opened."<<endl; return 0; } for(i=0;i<NumberNodes;i++){ np = &NodePointer[i]; if(np->getFaultListCount()!=0){ for(j=0;j<np->getFaultListCount();j++){ temp=np->getDomRelation(j); for(k=0;k<temp->domPointer.size();k++){ fprintf(fileID, "DOM CLB %d %d CLB %d %d\n", np->getNumber(), temp->fault, np->getNumber(), temp->domPointer[k]->fault); } } } } fclose(fileID); return 1; } int printFilteredFault(){ char fileName[] = "filtered_fault_list.txt"; FILE* fileID; int i,j,k; F_number* temp; Node* np; fileID = fopen(fileName, "w"); if(fileID==NULL){ cout<<"filtered fault file can not be opened."<<endl; return 0; } for(i=0;i<NumberNodes;i++){ np=&NodePointer[i]; if(np->getFaultListCount()!=0){ for(j=0;j<np->getFaultListCount();j++){ temp=np->getDomRelation(j); if(temp->domPointer.size()==0){ fprintf(fileID, "CLB %d %d\n", np->getNumber(), temp->fault); } } } } fclose(fileID); return 1; } int printTestPattern(){ char fileName[] = "atpg_for_faults.txt"; FILE* fileID; int i,j,k,counter=0; map<int, vector<int> >::iterator it; vector<int> temp; fileID = fopen(fileName, "w"); if(fileID==NULL){ cout<<"test pattern file can not be opened."<<endl; return 0; } for(it=filteredFault.begin();it!=filteredFault.end();it++){ temp = it->second; for(i=0;i<temp.size();i++){ fprintf(fileID, "CLB %d %d\n", it->first, temp[i]); for(j=0;j<NumberPPI;j++){ fprintf(fileID, "%d %s ", PPIList[j]->getNumber(), translate(testPattern[counter][j]).c_str()); } fprintf(fileID, "\n"); for(;j<testPattern[counter].size();j++){ fprintf(fileID, "%s ", translate(testPattern[counter][j]).c_str()); } fprintf(fileID, "\n"); counter++; } } fclose(fileID); return 1; }
zzfall2010ee658
fileWrite.cpp
C++
gpl3
9,765