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 "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; }
007slmg-np-activex
ffactivex/NPSafeArray.cpp
C++
mpl11
8,634
/* -*- 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
007slmg-np-activex
ffactivex/authorize.cpp
C++
mpl11
10,040
/* ***** 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 (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: 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_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->ulVal = npvar->value.boolValue; 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; } }
007slmg-np-activex
ffactivex/variants.cpp
C++
mpl11
10,855
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <algorithm> #include <string> #include "GenericNPObject.h" static NPObject* AllocateGenericNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, false); } static NPObject* AllocateMethodNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, true); } static void DeallocateGenericNPObject(NPObject *obj) { if (!obj) { return; } GenericNPObject *m = (GenericNPObject *)obj; delete m; } static void InvalidateGenericNPObject(NPObject *obj) { if (!obj) { return; } ((GenericNPObject *)obj)->Invalidate(); } NPClass GenericNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateGenericNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; NPClass MethodNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateMethodNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; // Some standard JavaScript methods bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) { GenericNPObject *map = (GenericNPObject *)object; if (!map || map->invalid) return false; // no args expected or cared for... std::string out; std::vector<NPVariant>::iterator it; for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) { if (NPVARIANT_IS_VOID(*it)) { out += ","; } else if (NPVARIANT_IS_NULL(*it)) { out += ","; } else if (NPVARIANT_IS_BOOLEAN(*it)) { if ((*it).value.boolValue) { out += "true,"; } else { out += "false,"; } } else if (NPVARIANT_IS_INT32(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%d,", (*it).value.intValue); out += tmp; } else if (NPVARIANT_IS_DOUBLE(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%f,", (*it).value.doubleValue); out += tmp; } else if (NPVARIANT_IS_STRING(*it)) { out += std::string((*it).value.stringValue.UTF8Characters, (*it).value.stringValue.UTF8Characters + (*it).value.stringValue.UTF8Length); out += ","; } else if (NPVARIANT_IS_OBJECT(*it)) { out += "[object],"; } } // calculate how much space we need std::string::size_type size = out.length(); char *s = (char *)NPNFuncs.memalloc(size * sizeof(char)); if (NULL == s) { return false; } memcpy(s, out.c_str(), size); s[size - 1] = 0; // overwrite the last "," STRINGZ_TO_NPVARIANT(s, (*result)); return true; } // Some helpers static void free_numeric_element(NPVariant elem) { NPNFuncs.releasevariantvalue(&elem); } static void free_alpha_element(std::pair<const char *, NPVariant> elem) { NPNFuncs.releasevariantvalue(&(elem.second)); } // And now the GenericNPObject implementation GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj): invalid(false), defInvoker(NULL), defInvokerObject(NULL) { NPVariant val; INT32_TO_NPVARIANT(0, val); immutables["length"] = val; if (!isMethodObj) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &MethodNPObjectClass); if (NULL == obj) { throw NULL; } ((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this); OBJECT_TO_NPVARIANT(obj, val); immutables["toString"] = val; } } GenericNPObject::~GenericNPObject() { for_each(immutables.begin(), immutables.end(), free_alpha_element); for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element); for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element); } bool GenericNPObject::HasMethod(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL != immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault); } } } return false; } bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(immutables[key]) && immutables[key].value.objectValue->_class->invokeDefault) { return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result); } } else if (alpha_mapper.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(alpha_mapper[key]) && alpha_mapper[key].value.objectValue->_class->invokeDefault) { return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result); } } } return true; } bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (defInvoker) { defInvoker(defInvokerObject, args, argCount, result); } return true; } // This method is also called before the JS engine attempts to add a new // property, most likely it's trying to check that the key is supported. // It only returns false if the string name was not found, or does not // hold a callable object bool GenericNPObject::HasProperty(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL == immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault); } } return false; } return true; } static bool CopyNPVariant(NPVariant *dst, const NPVariant *src) { dst->type = src->type; if (NPVARIANT_IS_STRING(*src)) { NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8)); if (NULL == str) { return false; } dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length; memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length); str[dst->value.stringValue.UTF8Length] = 0; dst->value.stringValue.UTF8Characters = str; } else if (NPVARIANT_IS_OBJECT(*src)) { NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src)); dst->value.objectValue = src->value.objectValue; } else { dst->value = src->value; } return true; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (!CopyNPVariant(result, &(immutables[key]))) { return false; } } else if (alpha_mapper.count(key) > 0) { if (!CopyNPVariant(result, &(alpha_mapper[key]))) { return false; } } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { if (!CopyNPVariant(result, &(numeric_mapper[key]))) { return false; } } } } catch (...) { } return true; } bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { // the key is already defined as immutable, check the new value type if (value->type != immutables[key].type) { return false; } // Seems ok, copy the new value if (!CopyNPVariant(&(immutables[key]), value)) { return false; } } else if (!CopyNPVariant(&(alpha_mapper[key]), value)) { return false; } } else { // assume int... NPVariant var; if (!CopyNPVariant(&var, value)) { return false; } unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (key >= numeric_mapper.size()) { // there's a gap we need to fill NPVariant pad; VOID_TO_NPVARIANT(pad); numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad); } numeric_mapper.at(key) = var; NPVARIANT_TO_INT32(immutables["length"])++; } } catch (...) { } return true; } bool GenericNPObject::RemoveProperty(NPIdentifier name) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (alpha_mapper.count(key) > 0) { NPNFuncs.releasevariantvalue(&(alpha_mapper[key])); alpha_mapper.erase(key); } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { NPNFuncs.releasevariantvalue(&(numeric_mapper[key])); numeric_mapper.erase(numeric_mapper.begin() + key); } NPVARIANT_TO_INT32(immutables["length"])--; } } catch (...) { } return true; } bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) { if (invalid) return false; try { *identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size()); if (NULL == *identifiers) { return false; } *identifierCount = 0; std::vector<NPVariant>::iterator it; unsigned int i = 0; char str[10] = ""; for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) { // skip empty (padding) elements if (NPVARIANT_IS_VOID(*it)) continue; _snprintf(str, sizeof(str), "%u", i); (*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str); } } catch (...) { } return true; }
007slmg-np-activex
ffactivex/GenericNPObject.cpp
C++
mpl11
13,001
//{{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
007slmg-np-activex
ffactivex/resource.h
C
mpl11
403
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()
007slmg-np-activex
ffactivex/FakeDispatcherBase_gen.py
Python
mpl11
1,484
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Contributor: * Chuan Qiu <qiuc12@gmail.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "Host.h" #include "npactivex.h" #include "ObjectManager.h" #include "objectProxy.h" #include <npapi.h> #include <npruntime.h> CHost::CHost(NPP npp) : ref_cnt_(1), instance(npp), lastObj(NULL) { } CHost::~CHost(void) { UnRegisterObject(); np_log(instance, 3, "CHost::~CHost"); } void CHost::AddRef() { ++ref_cnt_; } void CHost::Release() { --ref_cnt_; if (!ref_cnt_) delete this; } NPObject *CHost::GetScriptableObject() { return lastObj; } NPObject *CHost::RegisterObject() { lastObj = CreateScriptableObject(); if (!lastObj) return NULL; lastObj->host = this; NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); NPVariant var; OBJECT_TO_NPVARIANT(lastObj, var); // It doesn't matter which npp in setting. NPNFuncs.setproperty(instance, embed, NPNFuncs.getstringidentifier("object"), &var); return lastObj; } void CHost::UnRegisterObject() { return; NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); NPVariant var; VOID_TO_NPVARIANT(var); NPNFuncs.removeproperty(instance, embed, NPNFuncs.getstringidentifier("object")); np_log(instance, 3, "UnRegisterObject"); lastObj = NULL; } NPP CHost::ResetNPP(NPP newNPP) { // Doesn't support now.. _asm{int 3}; NPP ret = instance; UnRegisterObject(); instance = newNPP; np_log(newNPP, 3, "Reset NPP from 0x%08x to 0x%08x", ret, newNPP); RegisterObject(); return ret; } ScriptBase *CHost::GetInternalObject(NPP npp, NPObject *embed_element) { NPVariantProxy var; if (!NPNFuncs.getproperty(npp, embed_element, NPNFuncs.getstringidentifier("object"), &var)) return NULL; if (NPVARIANT_IS_OBJECT(var)) { ScriptBase *obj = static_cast<ScriptBase*>(NPVARIANT_TO_OBJECT(var)); NPNFuncs.retainobject(obj); return obj; } return NULL; } ScriptBase *CHost::GetMyScriptObject() { NPObjectProxy embed; NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed); return GetInternalObject(instance, embed); }
007slmg-np-activex
ffactivex/Host.cpp
C++
mpl11
5,125
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include "Host.h" namespace ATL { template <typename T> class CComObject; } class CControlEventSink; class CControlSite; class PropertyList; class CAxHost : public CHost{ private: CAxHost(const CAxHost &); bool isValidClsID; bool isKnown; bool noWindow; protected: // The window handle to our plugin area in the browser HWND Window; WNDPROC OldProc; // The class/prog id of the control CLSID ClsID; LPCWSTR CodeBaseUrl; CComObject<CControlEventSink> *Sink; RECT lastRect; PropertyList *Props_; public: CAxHost(NPP inst); ~CAxHost(); static CLSID ParseCLSIDFromSetting(LPCSTR clsid, int length); virtual NPP ResetNPP(NPP npp); CComObject<CControlSite> *Site; void SetNPWindow(NPWindow *window); void ResetWindow(); PropertyList *Props() { return Props_; } void Clear(); void setWindow(HWND win); HWND getWinfow(); void UpdateRect(RECT rcPos); bool verifyClsID(LPOLESTR oleClsID); bool setClsID(const char *clsid); bool setClsID(const CLSID& clsid); CLSID getClsID() { return this->ClsID; } void setNoWindow(bool value); bool setClsIDFromProgID(const char *progid); void setCodeBaseUrl(LPCWSTR clsid); bool hasValidClsID(); bool CreateControl(bool subscribeToEvents); void UpdateRectSize(LPRECT origRect); void SetRectSize(LPSIZEL size); bool AddEventHandler(wchar_t *name, wchar_t *handler); HRESULT GetControlUnknown(IUnknown **pObj); short HandleEvent(void *event); ScriptBase *CreateScriptableObject(); };
007slmg-np-activex
ffactivex/axhost.h
C++
mpl11
3,248
#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); } };
007slmg-np-activex
ffactivex/ScriptFunc.h
C++
mpl11
1,139
#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
007slmg-np-activex
ffactivex/ApiHook/Hook.h
C
mpl11
323
// (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; }
007slmg-np-activex
ffactivex/ApiHook/Hook.cpp
C++
mpl11
3,588
/* -*- 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; }
007slmg-np-activex
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@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
007slmg-np-activex
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@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITE_H #define CONTROLSITE_H #include "IOleCommandTargetImpl.h" #include "PropertyList.h" // 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(); 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 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
007slmg-np-activex
ffactivex/common/ControlSite.h
C++
mpl11
18,106
/* -*- 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; }
007slmg-np-activex
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
007slmg-np-activex
ffactivex/common/ControlEventSink.h
C++
mpl11
4,288
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "stdafx.h" #include "ControlSiteIPFrame.h" CControlSiteIPFrame::CControlSiteIPFrame() { m_hwndFrame = NULL; } CControlSiteIPFrame::~CControlSiteIPFrame() { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { if (phwnd == NULL) { return E_INVALIDARG; } *phwnd = m_hwndFrame; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceUIWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceFrame implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID) { return E_NOTIMPL; }
007slmg-np-activex
ffactivex/common/ControlSiteIPFrame.cpp
C++
mpl11
4,105
/* -*- 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)
007slmg-np-activex
ffactivex/common/StdAfx.h
C++
mpl11
4,966
/* -*- 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) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); }
007slmg-np-activex
ffactivex/common/ControlEventSink.cpp
C++
mpl11
9,136
/* -*- 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) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { if (wFlags & DISPATCH_PROPERTYGET) { CComVariant vResult; switch (dispIdMember) { case DISPID_AMBIENT_APPEARANCE: vResult = CComVariant(m_bAmbientAppearance); break; case DISPID_AMBIENT_FORECOLOR: vResult = CComVariant((long) m_clrAmbientForeColor); break; case DISPID_AMBIENT_BACKCOLOR: vResult = CComVariant((long) m_clrAmbientBackColor); break; case DISPID_AMBIENT_LOCALEID: vResult = CComVariant((long) m_nAmbientLocale); break; case DISPID_AMBIENT_USERMODE: vResult = CComVariant(m_bAmbientUserMode); break; case DISPID_AMBIENT_SHOWGRABHANDLES: vResult = CComVariant(m_bAmbientShowGrabHandles); break; case DISPID_AMBIENT_SHOWHATCHING: vResult = CComVariant(m_bAmbientShowHatching); break; default: return DISP_E_MEMBERNOTFOUND; } VariantCopy(pVarResult, &vResult); return S_OK; } return E_FAIL; } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink implementation void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed) { } void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex) { // Redraw the control InvalidateRect(NULL, FALSE); } void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk) { } void STDMETHODCALLTYPE CControlSite::OnSave(void) { } void STDMETHODCALLTYPE CControlSite::OnClose(void) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink2 implementation void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSinkEx implementation void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus) { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { *phwnd = m_hWndParent; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleClientSite implementation HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer) { if (!ppContainer) return E_INVALIDARG; 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) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSite implementation HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void) { m_bInPlaceActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void) { m_bUIActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo) { *lprcPosRect = m_rcObjectPos; *lprcClipRect = m_rcObjectPos; CControlSiteIPFrameInstance *pIPFrame = NULL; CControlSiteIPFrameInstance::CreateInstance(&pIPFrame); pIPFrame->AddRef(); *ppFrame = (IOleInPlaceFrame *) pIPFrame; *ppDoc = NULL; lpFrameInfo->fMDIApp = FALSE; lpFrameInfo->hwndFrame = NULL; lpFrameInfo->haccel = NULL; lpFrameInfo->cAccelEntries = 0; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable) { m_bUIActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect) { if (lprcPosRect == NULL) { return E_INVALIDARG; } SetPosition(m_rcObjectPos); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteEx implementation HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags) { m_bInPlaceActive = TRUE; if (pfNoRedraw) { *pfNoRedraw = FALSE; } if (dwFlags & ACTIVATE_WINDOWLESS) { if (!m_bSupportWindowlessActivation) { return E_INVALIDARG; } m_bWindowless = TRUE; } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void) { return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteWindowless implementation HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void) { // Allow windowless activation? return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC) { if (phDC == NULL) { return E_INVALIDARG; } // Can't do nested painting if (m_hDCBuffer != NULL) { return E_UNEXPECTED; } m_rcBuffer = m_rcObjectPos; if (pRect != NULL) { m_rcBuffer = *pRect; } m_hBMBuffer = NULL; m_dwBufferFlags = grfFlags; // See if the control wants a DC that is onscreen or offscreen if (m_dwBufferFlags & OLEDC_OFFSCREEN) { m_hDCBuffer = CreateCompatibleDC(NULL); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy); m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer); SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL); // TODO When OLEDC_PAINTBKGND we must draw every site behind this one } else { // TODO When OLEDC_PAINTBKGND we must draw every site behind this one // Get the window DC m_hDCBuffer = GetWindowDC(m_hWndParent); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } // Clip the control so it can't trash anywhere it isn't allowed to draw if (!(m_dwBufferFlags & OLEDC_NODRAW)) { m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer); // TODO Clip out opaque areas of sites behind this one SelectClipRgn(m_hDCBuffer, m_hRgnBuffer); } } *phDC = m_hDCBuffer; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC) { // Release the DC if (hDC == NULL || hDC != m_hDCBuffer) { return E_INVALIDARG; } // Test if the DC was offscreen or onscreen if ((m_dwBufferFlags & OLEDC_OFFSCREEN) && !(m_dwBufferFlags & OLEDC_NODRAW)) { // BitBlt the buffer into the control's object SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL); HDC hdc = GetWindowDC(m_hWndParent); long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY); ::ReleaseDC(m_hWndParent, hdc); } else { // TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one } // Clean up settings ready for next drawing if (m_hRgnBuffer) { SelectClipRgn(m_hDCBuffer, NULL); DeleteObject(m_hRgnBuffer); m_hRgnBuffer = NULL; } SelectObject(m_hDCBuffer, m_hBMBufferOld); if (m_hBMBuffer) { DeleteObject(m_hBMBuffer); m_hBMBuffer = NULL; } // Delete the DC if (m_dwBufferFlags & OLEDC_OFFSCREEN) { ::DeleteDC(m_hDCBuffer); } else { ::ReleaseDC(m_hWndParent, m_hDCBuffer); } m_hDCBuffer = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase) { // Clip the rectangle against the object's size and invalidate it RECT rcI = { 0, 0, 0, 0 }; if (pRect == NULL) { rcI = m_rcObjectPos; } else { IntersectRect(&rcI, &m_rcObjectPos, pRect); } ::InvalidateRect(m_hWndParent, &rcI, fErase); return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase) { if (hRGN == NULL) { ::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase); } else { // Clip the region with the object's bounding area HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos); if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR) { ::InvalidateRgn(m_hWndParent, hrgnClip, fErase); } DeleteObject(hrgnClip); } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc) { if (prc == NULL) { return E_INVALIDARG; } // Clip the rectangle against the object position RECT rcI = { 0, 0, 0, 0 }; IntersectRect(&rcI, &m_rcObjectPos, prc); *prc = rcI; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult) { if (plResult == NULL) { return E_INVALIDARG; } // Pass the message to the windowless control if (m_bWindowless && m_spIOleInPlaceObjectWindowless) { return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult); } else if (m_spIOleInPlaceObject) { HWND wnd; if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd))) SendMessage(wnd, msg, wParam, lParam); } return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleControlSite implementation HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock) { m_bInPlaceLocked = fLock; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags) { HRESULT hr = S_OK; if (pPtlHimetric == NULL) { return E_INVALIDARG; } if (pPtfContainer == NULL) { return E_INVALIDARG; } HDC hdc = ::GetDC(m_hWndParent); ::SetMapMode(hdc, MM_HIMETRIC); POINT rgptConvert[2]; rgptConvert[0].x = 0; rgptConvert[0].y = 0; if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER) { rgptConvert[1].x = pPtlHimetric->x; rgptConvert[1].y = pPtlHimetric->y; ::LPtoDP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x); pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y); } else if (dwFlags & XFORMCOORDS_POSITION) { pPtfContainer->x = (float)rgptConvert[1].x; pPtfContainer->y = (float)rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC) { rgptConvert[1].x = (int)(pPtfContainer->x); rgptConvert[1].y = (int)(pPtfContainer->y); ::DPtoLP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x; pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y; } else if (dwFlags & XFORMCOORDS_POSITION) { pPtlHimetric->x = rgptConvert[1].x; pPtlHimetric->y = rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else { hr = E_INVALIDARG; } ::ReleaseDC(m_hWndParent, hdc); return hr; } HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IBindStatusCallback implementation HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved, IBinding __RPC_FAR *pib) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError) { m_bBindingInProgress = FALSE; m_hrBindResult = hresult; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF, BINDINFO __RPC_FAR *pbindInfo) { *pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE; pbindInfo->cbSize = sizeof(BINDINFO); pbindInfo->szExtraInfo = NULL; memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM)); pbindInfo->grfBindInfoF = 0; pbindInfo->dwBindVerb = 0; pbindInfo->szCustomVerb = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC __RPC_FAR *pformatetc, STGMEDIUM __RPC_FAR *pstgmed) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid, IUnknown __RPC_FAR *punk) { return S_OK; } // IWindowForBindingUI HRESULT STDMETHODCALLTYPE CControlSite::GetWindow( /* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd) { *phwnd = NULL; return S_OK; }
007slmg-np-activex
ffactivex/common/ControlSite.cpp
C++
mpl11
44,576
/* -*- 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
007slmg-np-activex
ffactivex/common/ControlSiteIPFrame.h
C++
mpl11
3,891
/* -*- 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
007slmg-np-activex
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@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
007slmg-np-activex
ffactivex/common/PropertyList.h
C++
mpl11
5,004
/* -*- 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
007slmg-np-activex
ffactivex/common/ItemContainer.h
C++
mpl11
3,631
/* ***** 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); };
007slmg-np-activex
ffactivex/NPSafeArray.h
C++
mpl11
3,324
/* -*- 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 ***** */ BOOL TestAuthorization (NPP Instance, int16 ArgC, char *ArgN[], char *ArgV[], const char *MimeType);
007slmg-np-activex
ffactivex/authorize.h
C
mpl11
2,050
/* ***** 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 ScriptBase *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_) { } };
007slmg-np-activex
ffactivex/Host.h
C++
mpl11
2,246
<html> <head> <link rel="stylesheet" type="text/css" href="/list.css" /> <link rel="stylesheet" type="text/css" href="/options.css" /> <script src="/jquery-1.7.min.js"></script> <script src="/configure.js"></script> <script src="/i18n.js"></script> <script src="/list.js"></script> <script src="/listtypes.js"></script> <script src="/options.js"></script> <script src="/gas.js"></script> </head> <body> <div class="description"> <span i18n="option_help"></span> <a class="help" i18n="help" target="_blank"></a> </div> <div id="tbSetting"> </div> <div> <div style="float:left"> <div id="ruleCmds"> <button id="addRule" i18n="add"></button> <button id="deleteRule" i18n="delete"></button> <button id="moveUp" i18n="moveUp"></button> <button id="moveDown" i18n="moveDown"></button> </div> <div id="serverStatus" style="margin-top: 10px"> <span i18n="lastupdatetime"></span> <span width="400" id="lastUpdate"></span> <button id="doUpdate" i18n="doUpdate"></button> </div> <div> <input id="log_enable" type="checkbox"> <span i18n="log_enable"> </span> </input> <input id="tracking" type="checkbox"> <span i18n="tracking"> </span> </input> </div> </div> <div id="share"> </div> </div> <div id="footer" style="clear:both"> <span i18n="copyright"> </span> <a class="help" i18n="help" target="_blank"></a> <span id="follow"> </span> <a href="http://code.google.com/p/np-activex/issues/list" target="_blank"> <span i18n="issue_page"></span> </a> </div> </body> </html>
007slmg-np-activex
chrome/options.html
HTML
mpl11
1,877
// 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 tabStatus = {}; var version; var default_id = "lgllffgicojgllpmdbemgglaponefajn"; var debug = chrome.i18n.getMessage("@@extension_id") != default_id; var firstRun = false; var firstUpgrade = false; var blackList = [ /^https?:\/\/[^\/]*\.taobao\.com\/.*/i, /^https?:\/\/[^\/]*\.alipay\.com\/.*/i ]; var MAX_LOG = 400; (function getVersion() { $.ajax('manifest.json', { success: function (v){ v = JSON.parse(v); version = v.version; trackVersion(version); } }); })(); function startListener() { chrome.extension.onConnect.addListener(function(port) { if (!port.sender.tab) { console.error('Not connect from tab'); return; } initPort(port); }); chrome.extension.onRequest.addListener( function(request, sender, sendResponse) { if (!sender.tab) { console.error('Request from non-tab'); } else if (request.command == 'Configuration') { var config = setting.getPageConfig(request.href); sendResponse(config); if (request.top) { resetTabStatus(sender.tab.id); var dummy = {href: request.href, clsid: 'NULL'}; if (!config.pageRule && setting.getFirstMatchedRule( dummy, setting.defaultRules)) { detectControl(dummy, sender.tab.id, 0); } } //notifyUser(request, sender, config); } else { sendResponse({}); } } ); } var greenIcon = chrome.extension.getURL('icon16.png'); var grayIcon = chrome.extension.getURL('icon16-gray.png'); var errorIcon = chrome.extension.getURL('icon16-error.png'); var responseCommands = {}; function resetTabStatus(tabId) { tabStatus[tabId] = { count: 0, actived: 0, error: 0, issueId: null, logs: {"0":[]}, objs: {"0":[]}, frames: 1, tracking: false }; } function initPort(port) { var tabId = port.sender.tab.id; if (!(tabId in tabStatus)) { resetTabStatus(tabId); } var status = tabStatus[tabId]; var frameId = tabStatus[tabId].frames++; status.logs[frameId] = []; status.objs[frameId] = []; port.onMessage.addListener(function(request) { var resp = responseCommands[request.command]; if (resp) { delete request.command; resp(request, tabId, frameId); } else { console.error("Unknown command " + request.command); } }); port.onDisconnect.addListener(function() { for (var i = 0; i < status.objs[frameId].length; ++i) { countTabObject(status, status.objs[frameId][i], -1); } showTabStatus(tabId); if (status.tracking) { if (status.count == 0) { // Open the log page. window.open('log.html?tabid=' + tabId); status.tracking = false; } } else { // Clean up. status.logs[frameId] = []; status.objs[frameId] = []; } }); } chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) { if (tabStatus[tabId]) { tabStatus[tabId].removed = true; var TIMEOUT = 1000 * 60 * 5; // clean up after 5 mins. window.setTimeout(function() { delete tabStatus[tabId]; }, TIMEOUT); } }); function countTabObject(status, info, delta) { for (var i = 0; i < blackList.length; ++i) { if (info.href.match(blackList[i])) { return; } } if (info.actived) { status.actived += delta; if (delta > 0) { trackUse(info.rule); } } else if (delta > 0) { trackNotUse(info.href); } status.count += delta; var issue = setting.getMatchedIssue(info); if (issue) { status.error += delta; status.issueId = issue.identifier; if (delta > 0) { trackIssue(issue); } } } function showTabStatus(tabId) { if (tabStatus[tabId].removed) { return; } var status = tabStatus[tabId]; var title = ""; if (status.count == 0) { chrome.pageAction.hide(tabId); return; } else { chrome.pageAction.show(tabId); } chrome.pageAction.setPopup({ tabId: tabId, popup: 'popup.html?tabid=' + tabId }); if (status.count == 0) { // Do nothing.. } else if (status.error != 0) { chrome.pageAction.setIcon({ tabId: tabId, path: errorIcon }); title = $$('status_error'); } else if (status.count != status.actived) { // Disabled.. chrome.pageAction.setIcon({ tabId: tabId, path: grayIcon }); title = $$('status_disabled'); } else { // OK chrome.pageAction.setIcon({ tabId: tabId, path: greenIcon }); title = $$('status_ok'); } chrome.pageAction.setTitle({ tabId: tabId, title: title }); } function detectControl(request, tabId, frameId) { var status = tabStatus[tabId]; if (frameId != 0 && status.objs[0].length) { // Remove the item to identify the page. countTabObject(status, status.objs[0][0], -1); status.objs[0] = []; } status.objs[frameId].push(request); countTabObject(status, request, 1); showTabStatus(tabId); } responseCommands.DetectControl = detectControl; responseCommands.Log = function(request, tabId, frameId) { var logs = tabStatus[tabId].logs[frameId]; if (logs.length < MAX_LOG) { logs.push(request.message); } else if (logs.length == MAX_LOG) { logs.push('More logs clipped'); } } function generateLogFile(tabId) { var status = tabStatus[tabId]; if (!status) { return ''; } var ret = ''; ret += 'UserAgent: ' + navigator.userAgent + '\n'; ret += 'Extension version: ' + version + '\n'; ret += '\n'; for (var i = 0; i < status.frames; ++i) { if (i) { ret += '\n\n'; } ret += '------------ Frame ' + (i + 1) + ' ------------------\n'; ret += 'Objects:\n'; for (var j = 0; j < status.objs[i].length; ++j) { ret += JSON.stringify(status.objs[i][j]) + '\n'; } ret += '\n'; ret += 'Log:\n'; for (var j = 0; j < status.logs[i].length; ++j) { ret += status.logs[i][j] + '\n'; } } return ret; }
007slmg-np-activex
chrome/common.js
JavaScript
mpl11
6,395
// 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. // Permission for experimental not given. var handler = chrome.webRequest; function onBeforeSendHeaders(details) { var rule = setting.getFirstMatchedRule( {href: details.url}, setting.cache.userAgent); if (!rule || !(rule.userAgent in agents)) { return {}; } for (var i = 0; i < details.requestHeaders.length; ++i) { if (details.requestHeaders[i].name == 'User-Agent') { details.requestHeaders[i].value = agents[rule.userAgent]; break; } } return {requestHeaders: details.requestHeaders}; } function registerRequestListener() { if (!handler) { return; } var filters = { urls: ["<all_urls>"], types: ["main_frame", "sub_frame", "xmlhttprequest"] }; try{ handler.onBeforeSendHeaders.addListener( onBeforeSendHeaders, filters, ["requestHeaders", "blocking"]); } catch (e) { console.log('Your browser doesn\'t support webRequest'); } }
007slmg-np-activex
chrome/web.js
JavaScript
mpl11
1,133
body { background-color: #ffd; } body > div { margin: 10px; max-width: 1000px; } #tbSetting { width: 1000px; height: 500px; } .itemline.newline:not(.editing) { display:none; } div[property=status] { width: 75px } div[property=title] { width: 200px } div[property=type] { width: 60px } div[property=value] { width: 320px } div[property=userAgent] { width: 80px } div[property=script] { width: 350px } [property=status] button { width: 70px; } #ruleCmds button { width: 100px; margin: 4px 8px 3px 8px; } #tbServer, #tbServerStatus { float: left; } #tbServer { width: 600px; } #share { float:left; padding: 5px 0 0 40px; height: 100px; } #footer * { margin: 0 10px; }
007slmg-np-activex
chrome/options.css
CSS
mpl11
780
.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); }
007slmg-np-activex
chrome/list.css
CSS
mpl11
1,865
// 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. /* Rule: { identifier: an unique identifier title: description type: Can be "wild", "regex", "clsid" value: pattern, correspond to type userAgent: the useragent value. See var "agents" for options. script: script to inject. Separated by spaces } Order: { status: enabled / disabled / custom position: default / custom identifier: identifier of rule } Issue: { type: Can be "wild", "regex", "clsid" value: pattern, correspond to type description: The description of this issue issueId: Issue ID on issue tracking page url: optional, support page for issue tracking. Use code.google.com if omitted. } ServerSide: ActiveXConfig: { version: version rules: object of user-defined rules, propertied by identifiers defaultRules: ojbect of default rules scripts: mapping of workaround scripts, by identifiers. metadatas localScripts: metadatas of local scripts. order: the order of rules cache: to accerlerate processing issues: The bugs/unsuppoted sites that we have accepted. misc:{ lastUpdate: last timestamp of updating logEnabled: log tracking: Allow GaS tracking. verbose: verbose level of logging } } PageSide: ActiveXConfig: { pageSide: Flag of pageside. pageScript: Helper script to execute on context of page extScript: Helper script to execute on context of extension pageRule: If page is matched. clsidRules: If page is not matched or disabled. valid CLSID rules logEnabled: log verbose: verbose level of logging } */ // Update per 5 hours. var DEFAULT_INTERVAL = 1000 * 3600 * 5; function ActiveXConfig(input) { var settings; if (input === undefined) { var defaultSetting = { version: 3, rules: {}, defaultRules: {}, scripts: {}, localScripts: {}, order: [], notify: [], issues: [], misc: { lastUpdate: 0, logEnabled: false, tracking: true, verbose: 3 } }; input = defaultSetting; } if (input.version == '3') { settings = input; settings.__proto__ = ActiveXConfig.prototype; } else { settings = ActiveXConfig.convertVersion(input); } settings.updateCache(); return settings; } var settingKey = 'setting'; var scriptPrefix = 'script_'; clsidPattern = /[^0-9A-F][0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}[^0-9A-F]/; var agents = { ie9: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)", ie8: "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0)", ie7: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64;)", ff7win: "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1", ip5: "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3", ipad5: "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3" }; 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 getUserAgent(key) { // This script is always run under sandbox, so useragent should be always // correct. if (key == '' || !(key in agents)) { return ""; } var current = navigator.userAgent; var wow64 = current.indexOf('WOW64') >= 0; var value = agents[key]; if (!wow64) { value = value.replace(' WOW64;', ''); } return value; } ActiveXConfig.convertVersion = function(setting) { if (setting.version == 3) { return setting; } else if (setting.version == 2) { function parsePattern(pattern) { pattern = pattern.trim(); var title = pattern.match(/###(.*)/); if (title != null) { return { pattern: pattern.match(/(.*)###/)[1].trim(), title: title[1].trim() } } else { return { pattern: pattern, title: "Rule" } } } var ret = new ActiveXConfig(); if (setting.logEnabled) { ret.misc.logEnabled = true; } var urls = setting.url_plain.split('\n'); for (var i = 0; i < urls.length; ++i) { var rule = ret.createRule(); var pattern = parsePattern(urls[i]); rule.title = pattern.title; var url = pattern.pattern; if (url.substr(0, 2) == 'r/') { rule.type = 'regex'; rule.value = url.substr(2); } else { rule.type == 'wild'; rule.value = url; } ret.addCustomRule(rule, 'convert'); } var clsids = setting.trust_clsids.split('\n'); for (var i = 0; i < clsids.length; ++i) { var rule = ret.createRule(); rule.type = 'clsid'; var pattern = parsePattern(clsids[i]); rule.title = pattern.title; rule.value = pattern.pattern; ret.addCustomRule(rule, 'convert'); } firstUpgrade = true; return ret; } } ActiveXConfig.prototype = { // Only used for user-scripts shouldEnable: function(object) { if (this.pageRule) { return this.pageRule; } var clsidRule = this.getFirstMatchedRule(object, this.clsidRules); if (clsidRule) { return clsidRule; } else { return null; } }, createRule: function() { return { title: "Rule", type: "wild", value: "", userAgent: "", scriptItems: "", }; }, addCustomRule: function(newItem, auto) { if (!this.validateRule(newItem)) { return; } var identifier = this.createIdentifier(); newItem.identifier = identifier; this.rules[identifier] = newItem; this.order.push({ status: 'custom', position: 'custom', identifier: identifier }); this.update() trackAddCustomRule(newItem, auto); }, updateDefaultRules: function(newRules) { var deleteAll = false, ruleToDelete = {}; if (typeof this.defaultRules != 'object') { // There might be some errors! // Clear all defaultRules console.log('Corrupted default rules, reload all'); deleteAll = true; this.defaultRules = {}; } else { for (var i in this.defaultRules) { if (!(i in newRules)) { console.log('Remove rule ' + i); ruleToDelete[i] = true; delete this.defaultRules[i]; } } } var newOrder = []; for (var i = 0; i < this.order.length; ++i) { if (this.order[i].position == 'custom' || (!deleteAll && !ruleToDelete[this.order[i].identifier])) { newOrder.push(this.order[i]); } } this.order = newOrder; var position = 0; for (var i in newRules) { if (!(i in this.defaultRules)) { this.addDefaultRule(newRules[i], position++); } this.defaultRules[i] = newRules[i]; } }, updateConfig: function(session) { session.startUpdate(); console.log('Start updating'); var updated = { issues: false, setting: false, scripts: false }; var setting = this; session.updateFile({ url: 'setting.json', dataType: "json", success: function(nv, status, xhr) { console.log('Update default rules'); updated.setting = true; setting.updateDefaultRules(nv); if (updated.setting && updated.scripts) { setting.updateAllScripts(session); } setting.update(); } }); session.updateFile({ url: 'scripts.json', dataType: "json", success: function(nv, status, xhr) { updated.scripts = true; console.log('Update scripts'); setting.scripts = nv; if (updated.setting && updated.scripts) { setting.updateAllScripts(session); } setting.update(); } }); session.updateFile({ url: 'issues.json', dataType: "json", success: function(nv, status, xhr) { console.log('Update issues'); setting.issues = nv; setting.update(); } }); }, getPageConfig: function(href) { var ret = {}; ret.pageSide = true; ret.version = this.version; ret.verbose = this.misc.verbose; ret.logEnabled = this.misc.logEnabled; ret.pageRule = this.getFirstMatchedRule({href:href}); if (!ret.pageRule) { ret.clsidRules = this.cache.clsidRules; } else { var script = this.getScripts(ret.pageRule.script); ret.pageScript = script.page; ret.extScript = script.extension; } return ret; }, getFirstMatchedRule: function(object, rules) { var useCache = false; if (!rules) { rules = this.cache.validRules; useCache = true; } if (Array.isArray(rules)) { for (var i = 0; i < rules.length; ++i) { if (this.isRuleMatched(rules[i], object, useCache ? i : -1)) { return rules[i]; } } } else { for (var i in rules) { if (this.isRuleMatched(rules[i], object)) { return rules[i]; } } } return null; }, getMatchedIssue: function(filter) { return this.getFirstMatchedRule(filter, this.issues); }, activeRule: function(rule) { for (var i = 0; i < this.order.length; ++i) { if (this.order[i].identifier == rule.identifier) { if (this.order[i].status == 'disabled') { this.order[i].status = 'enabled'; trackAutoEnable(rule.identifier); } break; } } this.update(); }, validateRule: function(rule) { var ret = true; try { if (rule.type == 'wild') { ret &= this.convertUrlWildCharToRegex(rule.value) != null; } else if (rule.type == 'regex') { ret &= rule.value != ''; var r = new RegExp(rule.value, 'i'); } else if (rule.type == 'clsid') { var v = rule.value.toUpperCase(); if (!clsidPattern.test(v) || v.length > 55) ret = false; } } catch (e) { ret = false; } return ret; }, isRuleMatched: function(rule, object, id) { if (rule.type == "wild" || rule.type == "regex" ) { var regex; if (id >= 0) { regex = this.cache.regex[id]; } else if (rule.type == 'wild') { regex = this.convertUrlWildCharToRegex(rule.value); } else if (rule.type == 'regex') { regex = new RegExp('^' + rule.value + '$', 'i'); } if (object.href && regex.test(object.href)) { return true; } } else if (rule.type == "clsid") { if (object.clsid) { var v1 = clsidPattern.exec(rule.value.toUpperCase()); var v2 = clsidPattern.exec(object.clsid.toUpperCase()); if (v1 && v2 && v1[0] == v2[0]) { return true; } } } return false; }, getScripts: function(script) { var ret = { page: "", extension: "" }; if (!script) { return ret; } var items = script.split(' '); for (var i = 0; i < items.length; ++i) { if (items[i] == '' || !this.scripts[items[i]]) { continue; } var name = items[i]; var val = '// '; val += items[i] + '\n'; val += this.getScriptContent(name); val += '\n\n'; ret[this.scripts[name].context] += val; } return ret; }, getScriptContent: function(scriptid) { this.updateScript(scriptid, false); var local = this.localScripts[scriptid]; if (!local) { // The script not found. return ""; } var id = scriptPrefix + scriptid; return localStorage[id]; }, updateAllScripts: function(session) { console.log('updateAllScripts'); var scripts = {}; for (var i = 0; i < this.order.length; ++i) { if (this.order[i].status == 'disabled') { continue; } var rule = this.getItem(this.order[i]); var script = rule.script; if (!script) { continue; } var items = script.split(' '); for (var j = 0; j < items.length; ++j) { scripts[items[j]] = true; } } for (var i in scripts) { this.updateScript(i, true, session); } }, updateScript: function(id, async, session) { var remote = this.scripts[id]; var local = this.localScripts[id]; if (!remote || remote.updating) { return; } if (local && local.checksum == remote.checksum) { return; } remote.updating = true; var setting = this; var config = { url: remote.url + "?hash=" + remote.checksum, async: async, complete: function() { delete remote.updating; }, error: function() { console.log('Update script ' + remote.identifier + ' failed'); }, context: this, success: function(nv, status, xhr) { delete remote.updating; var hash = stringHash(nv); if (hash == remote.checksum) { localStorage[scriptPrefix + id] = nv; setting.localScripts[id] = remote; setting.save(); console.log('script updated ', id); } else { var message = 'Hashcode mismatch!!'; message += ' script: ' + remote.identifier; messsge += ' actual: ' + hash; message += ' expected: ' + remote.checksum; console.log(message); } }, // Don't evaluate this. dataType: "text" }; if (!UpdateSession && !session) { // Should run update from background throw "Not valid session"; } if (session) { session.updateFile(config); } else { UpdateSession.updateFile(config); } }, convertUrlWildCharToRegex: function(wild) { try { function escapeRegex(str, star) { if (!star) star = '*'; var escapeChars = /([\.\\\/\?\{\}\+\[\]])/g; return str.replace(escapeChars, "\\$1").replace('*', star); } wild = wild.toLowerCase(); if (wild == "<all_urls>") { wild = "*://*/*"; } var pattern = /^(.*?):\/\/(\*?[^\/\*]*)\/(.*)$/i; // pattern: [all, scheme, host, page] var parts = pattern.exec(wild); if (parts == null) { return null; } var scheme = parts[1]; var host = parts[2]; var page = parts[3]; var regex = '^' + escapeRegex(scheme, '[^:]*') + ':\\/\\/'; regex += escapeRegex(host, '[^\\/]*') + '/'; regex += escapeRegex(page, '.*'); return new RegExp(regex, 'i'); } catch (e) { return null; } }, update: function() { if (this.pageSide) { return; } this.updateCache(); if (this.cache.listener) { this.cache.listener.trigger('update'); } this.save(); }, // Please remember to call update() after all works are done. addDefaultRule: function(rule, position) { console.log("Add new default rule: ", rule); var custom = null; if (rule.type == 'clsid') { for (var i in this.rules) { var info = {href: "not-a-URL-/", clsid: rule.value}; if (this.isRuleMatched(this.rules[i], info, -1)) { custom = this.rules[i]; break; } } } else if (rule.keyword && rule.testUrl) { // Try to find matching custom rule for (var i in this.rules) { if (this.isRuleMatched(this.rules[i], {href: rule.testUrl}, -1)) { if (this.rules[i].value.toLowerCase().indexOf(rule.keyword) != -1) { custom = this.rules[i]; break; } } } } var newStatus = 'disabled'; if (custom) { console.log('Convert custom rule', custom, ' to default', rule); // Found a custom rule which is similiar to this default rule. newStatus = 'enabled'; // Remove old one delete this.rules[custom.identifier]; for (var i = 0; i < this.order.length; ++i) { if (this.order[i].identifier == custom.identifier) { this.order.splice(i, 1); break; } } } this.order.splice(position, 0, { position: 'default', status: newStatus, identifier: rule.identifier }); this.defaultRules[rule.identifier] = rule; }, updateCache: function() { if (this.pageSide) { return; } this.cache = { validRules: [], regex: [], clsidRules: [], userAgentRules: [], listener: (this.cache || {}).listener } for (var i = 0; i < this.order.length; ++i) { if (this.order[i].status == 'custom' || this.order[i].status == 'enabled') { var rule = this.getItem(this.order[i]); var cacheId = this.cache.validRules.push(rule) - 1; if (rule.type == 'clsid') { this.cache.clsidRules.push(rule); } else if (rule.type == 'wild') { this.cache.regex[cacheId] = this.convertUrlWildCharToRegex(rule.value); } else if (rule.type == 'regex') { this.cache.regex[cacheId] = new RegExp('^' + rule.value + '$', 'i'); } if (rule.userAgent != '') { this.cache.userAgentRules.push(rule); } } } }, save: function() { if (location.protocol == "chrome-extension:") { // Don't include cache in localStorage. var cache = this.cache; delete this.cache; localStorage[settingKey] = JSON.stringify(this); this.cache = cache; } }, createIdentifier: function() { var base = 'custom_' + Date.now() + "_" + this.order.length + "_"; var ret; do { ret = base + Math.round(Math.random() * 65536); } while (this.getItem(ret)); return ret; }, getItem: function(item) { var identifier = item; if (typeof identifier != 'string') { identifier = item.identifier; } if (identifier in this.rules) { return this.rules[identifier]; } else { return this.defaultRules[identifier]; } } }; function loadLocalSetting() { var setting = undefined; if (localStorage[settingKey]) { try{ setting = JSON.parse(localStorage[settingKey]); } catch (e){ setting = undefined; } } if (!setting) { firstRun = true; } return new ActiveXConfig(setting); } function clearSetting() { localStorage.removeItem(settingKey); setting = loadLocalSetting(); }
007slmg-np-activex
chrome/configure.js
JavaScript
mpl11
19,523
// 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. // Updater events: // error // updating // complete // success // itemupdated // progress // properties: // status // lastUpdate // Can be used for debugging. var defaultServer = "http://settings.np-activex.googlecode.com/hg/"; var server=localStorage.updateServer || defaultServer; function ObjectWithEvent() { this._events = {}; }; ObjectWithEvent.prototype = { bind: function(name, func) { if (!Array.isArray(this._events[name])) { this._events[name] = []; } this._events[name].push(func); }, unbind: function(name, func) { if (!Array.isArray(this._events[name])) { return; } for (var i = 0; i < this._events[name].length; ++i) { if (this._events[name][i] == func) { this._events[name].splice(i, 1); break; } } }, trigger: function(name, argument) { if (this._events[name]) { var handlers = this._events[name]; for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(this, argument); } } } }; function UpdateSession() { ObjectWithEvent.call(this); this.jqXHRs = []; this.reset(); } UpdateSession.prototype = { __proto__: ObjectWithEvent.prototype, updateProgress: function() { with(this) { if (finished == total) { if (error == 0) { this.trigger('success'); } this.trigger('complete'); } else { this.trigger('progress'); } } }, updateFile: function(request) { ++this.total; var session = this; var jqXHR = UpdateSession.updateFile(request) .fail(function(xhr, msg, thrown) { ++session.error; session.trigger('error', [xhr, msg, thrown]); session.updateProgress(); }).always(function() { ++session.finished; session.updateProgress(); }); this.jqXHRs.push(jqXHR); }, reset: function() { this.finished = this.total = this.error = 0; if (this.updateToken) { clearTimeout(this.updateToken); this.updateToken = undefined; } for (var i = 0; i < this.jqXHRs.length; ++i) { //this.jqXHRs[i].abort(); } this.jqXHRs = []; }, startUpdate: function() { this.reset(); this.trigger('updating'); } }; UpdateSession.prototype.__defineGetter__('status', function() { if (this.finished == this.total) { return "stop"; } else { return "updating"; } }); UpdateSession.setUpdateInterval= function(callback, session, interval) { session.bind('complete', function() { session.updateToken = setTimeout(callback, interval); }); callback(); }; UpdateSession.updateFile = function(request) { if (request.url.match(/^.*:\/\//) == null) { request.url = server + request.url; } trackUpdateFile(request.url); return $.ajax(request); };
007slmg-np-activex
chrome/configUpdate.js
JavaScript
mpl11
3,106
// 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 FLASH_CLSID = '{d27cdb6e-ae6d-11cf-96b8-444553540000}'; var typeId = "application/x-itst-activex"; function executeScript(script) { var scriptobj = document.createElement("script"); scriptobj.innerHTML = script; var element = document.head || document.body || document.documentElement || document; element.insertBefore(scriptobj, element.firstChild); element.removeChild(scriptobj); } function checkParents(obj) { var parent = obj; var level = 0; while (parent && parent.nodeType == 1) { if (getComputedStyle(parent).display == 'none') { var desp = obj.id + ' at level ' + level; if (scriptConfig.none2block) { parent.style.display = 'block'; parent.style.height = '0px'; parent.style.width = '0px'; log('Remove display:none for ' + desp); } else { log('Warning: Detected display:none for ' + desp); } } parent = parent.parentNode; ++level; } } function getLinkDest(url) { if (typeof url != 'string') { return url; } url = url.trim(); if (/^https?:\/\/.*/.exec(url)) { return url; } if (url[0] == '/') { if (url[1] == '/') { return location.protocol + url; } else { return location.origin + url; } } return location.href.replace(/\/[^\/]*$/, '/' + url); } var hostElement = null; function enableobj(obj) { // We can't use classid directly because it confuses the browser. obj.setAttribute("clsid", getClsid(obj)); obj.removeAttribute("classid"); checkParents(obj); var newObj = obj.cloneNode(true); newObj.type = typeId; // Remove all script nodes. They're executed. var scripts = newObj.getElementsByTagName('script'); for (var i = 0; i < scripts.length; ++i) { scripts[i].parentNode.removeChild(scripts[i]); } // Set codebase to full path. var codebase = newObj.getAttribute('codebase'); if (codebase && codebase != '') { newObj.setAttribute('codebase', getLinkDest(codebase)); } newObj.activex_process = true; obj.parentNode.insertBefore(newObj, obj); obj.parentNode.removeChild(obj); obj = newObj; if (obj.id) { var command = ''; if (obj.form && scriptConfig.formid) { var form = obj.form.name; command += "document.all." + form + "." + obj.id; command + " = document.all." + obj.id + ';\n'; log('Set form[obj.id]: form: ' + form + ', object: ' + obj.id) } // Allow access by document.obj.id if (obj.id && scriptConfig.documentid) { command += "delete document." + obj.id + ";\n"; command += "document." + obj.id + '=' + obj.id + ';\n'; } if (command) { executeScript(command); } } log("Enabled object, id: " + obj.id + " clsid: " + getClsid(obj)); return obj; } function getClsid(obj) { if (obj.hasAttribute("clsid")) return obj.getAttribute("clsid"); var clsid = obj.getAttribute("classid"); var compos = clsid.indexOf(":"); if (clsid.substring(0, compos).toLowerCase() != "clsid") return; clsid = clsid.substring(compos + 1); return "{" + clsid + "}"; } function notify(data) { connect(); data.command = 'DetectControl'; port.postMessage(data); } function process(obj) { if (obj.activex_process) return; if (onBeforeLoading.caller == enableobj || onBeforeLoading.caller == process || onBeforeLoading.caller == checkParents) { log("Nested onBeforeLoading " + obj.id); return; } if (obj.type == typeId) { if (!config || !config.pageRule) { // hack??? Deactive this object. log("Deactive unexpected object " + obj.outerHTML); return true; } log("Found objects created by client scripts"); notify({ href: location.href, clsid: clsid, actived: true, rule: config.pageRule.identifier }); obj.activex_process = true; return; } if (obj.type != "" || !obj.hasAttribute("classid")) return; if (getClsid(obj).toLowerCase() == FLASH_CLSID) { return; } if (config == null) { // Delay the process of this object. // Hope config will be load soon. log('Pending object ', obj.id); pendingObjects.push(obj); return; } obj.activex_process = true; connect(); var clsid = getClsid(obj); var rule = config.shouldEnable({href: location.href, clsid:clsid}); if (rule) { obj = enableobj(obj); notify({ href: location.href, clsid: clsid, actived: true, rule: rule.identifier }); } else { notify({href: location.href, clsid: clsid, actived: false}); } } function replaceDocument() { var s = document.querySelectorAll('object[classid]'); log("found " + s.length + " object(s) on page"); for (var i = 0; i < s.length; ++i) { process(s[i]); } }; function onBeforeLoading(event) { var obj = event.target; if (obj.nodeName == "OBJECT") { log("BeforeLoading " + obj.id); if (process(obj)) { event.preventDefault(); } } } function onError(event) { var message = 'Error: '; message += event.message; message += ' at '; message += event.filename; message += ':'; message += event.lineno; log(message); } function setUserAgent() { if (!config.pageRule) { return; } var agent = getUserAgent(config.pageRule.userAgent); if (agent && agent != '') { log("Set userAgent: " + config.pageRule.userAgent); var js = "(function(agent) {"; js += "delete navigator.userAgent;"; js += "navigator.userAgent = agent;"; js += "delete navigator.appVersion;"; js += "navigator.appVersion = agent.substr(agent.indexOf('/') + 1);"; js += "if (agent.indexOf('MSIE') >= 0) {"; js += "delete navigator.appName;"; js += 'navigator.appName = "Microsoft Internet Explorer";}})("'; js += agent; js += '")'; executeScript(js); } }
007slmg-np-activex
chrome/inject_actions.js
JavaScript
mpl11
6,232
body { background-color: #ffd; } .main { width: 500px; height: 340px; padding: 10px; } .status { font-size: 18px; margin: 0 20px; } #issue_view { margin: 15px 10px; } #issue_view > div { margin: 7px 0px; } #share { position: absolute; top: 250px; left: 30px; height: 90px; } button { width: 350px; height: 30px; margin: 4px; } button.defaultRule { background-color: #0A0; } button.customRule { background-color: #aaf; }
007slmg-np-activex
chrome/popup.css
CSS
mpl11
507
<html> <head> <title i18n="view_log"></title> <script src="/jquery-1.7.min.js"></script> <script src="/gas.js"></script> <script src="/i18n.js"></script> <script src="/log.js"></script> <style> #text { width: 800px; height: 400px; } div { font-size: large; margin: 10px 0px; } </style> </head> <body> <div i18n="log"> </div> <textarea id="text" wrap="off"> </textarea> <div i18n="issue_submit_desp"></div> <div><a i18n="issue_submit_goto" href="http://code.google.com/p/np-activex/issues/entry?template=Defect%20report%20from%20log" target="_blank"></a></div> </body> </html>
007slmg-np-activex
chrome/log.html
HTML
mpl11
719
// 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 controlLogFName="__npactivex_log"; var controlLogEvent="__npactivex_log_event__"; var config = null; var port = null; var logs = []; var scriptConfig = { none2block: false, formid: false, documentid: false }; function onControlLog(event) { var message = event.data; log(message); } window.addEventListener(controlLogEvent, onControlLog, false); function connect() { if (port) { return; } port = chrome.extension.connect(); for (var i = 0; i < logs.length; ++i) { port.postMessage({command: 'Log', message: logs[i]}); } if (port && config) { logs = undefined; } } function log(message) { var time = (new Date()).toLocaleTimeString(); message = time + ' ' + message; if (config && config.logEnabled) { console.log(message); } if (port) { port.postMessage({command: 'Log', message: message}); } if (!config || !port) { logs.push(message); } } log('PageURL: ' + location.href); var pendingObjects = []; function init(response) { config = new ActiveXConfig(response); if (config.logEnabled) { for (var i = 0; i < logs.length; ++i) { console.log(logs[i]); } } eval(config.extScript); executeScript(config.pageScript); setUserAgent(); log('Page rule:' + JSON.stringify(config.pageRule)); for (var i = 0; i < pendingObjects.length; ++i) { pendingObjects[i].activex_process = false; process(pendingObjects[i]); cacheConfig(); } delete pendingObjects; } function cacheConfig() { sessionStorage.activex_config_cache = JSON.stringify(config); } function loadConfig(response) { if (config) { config = new ActiveXConfig(response); var cache = sessionStorage.activex_config_cache; if (cache) { cacheConfig(); } } else { init(response); } if (config.pageRule) { cacheConfig(); } } function loadSessionConfig() { var cache = sessionStorage.activex_config_cache; if (cache) { log('Loading config from session cache'); init(JSON.parse(cache)); } } loadSessionConfig(); chrome.extension.sendRequest( {command:"Configuration", href:location.href, top: self == top}, loadConfig); window.addEventListener("beforeload", onBeforeLoading, true); window.addEventListener('error', onError, true);
007slmg-np-activex
chrome/inject_start.js
JavaScript
mpl11
2,553
// 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())); } } };
007slmg-np-activex
chrome/list.js
JavaScript
mpl11
11,700
// 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. replaceDocument(); window.addEventListener('load', replaceDocument, false);
007slmg-np-activex
chrome/inject_doreplace.js
JavaScript
mpl11
265
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta> <link rel="stylesheet" type="text/css" href="/popup.css" /> <script src="/jquery-1.7.min.js"></script> <script src="/popup.js"></script> <script src="/i18n.js"></script> <script src="/gas.js"></script> </head> <body> <div class="main"> <div> <div id="status_ok" class="status"> <span i18n="status_ok"></span> <button id="submitissue" i18n="submitissue"></button> </div> <div id="status_disabled" class="status" i18n="status_disabled"></div> <div id="status_error" class="status" i18n="status_error"></div> </div> <div id="enable_btns"> </div> <div id="issue_view"> <div i18n="issue_desp"> </div> <div id="issue_content"> </div> <div> <a id="issue_track" i18n="issue_track" href="#"></a> </div> </div> <div id="share"> </div> </div> </body> </html>
007slmg-np-activex
chrome/popup.html
HTML
mpl11
1,069
// 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 USE_RECORD_GAP = 3 * 60 * 1000; // 3 minutes var background = chrome.extension.getBackgroundPage(); var _gaq = background._gaq || _gaq || []; if (window == background) { _gaq.push(['_setAccount', 'UA-28870762-4']); } _gaq.push(['_trackPageview', location.href]); function initGAS() { var setting = setting || background.setting || {}; if (!debug && setting.misc.tracking) { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); } else if (!debug) { // dummy it. Non-debug && non-track _gaq.push = function() {}; } } var useHistory = {}; var issueHistory = {}; function trackCheckSpan(history, item) { var last = history[item]; if (last && Date.now() - last < USE_RECORD_GAP) { return false; } history[item] = Date.now(); return true; } function trackIssue(issue) { if (!trackCheckSpan(issueHistory, issue.identifier)) { return; } _gaq.push(['_trackEvent', 'usage', 'error', '' + issue.identifier]); } function trackVersion(version) { _gaq.push(['_trackEvent', 'option', 'version', version]); } function serializeRule(rule) { return rule.type[0] + ' ' + rule.value; } function trackUse(identifier) { if (!trackCheckSpan(useHistory, identifier)) { return; } if (identifier.substr(0, 7) == 'custom_') { var setting = setting || background.setting || {}; var rule = setting.getItem(identifier); _gaq.push(['_trackEvent', 'usage', 'use-custom', serializeRule(rule)]); } else { _gaq.push(['_trackEvent', 'usage', 'use', identifier]); } } var urlHistory = {} function trackNotUse(url) { if (!trackCheckSpan(urlHistory, url)) { return; } _gaq.push(['_trackEvent', 'usage', 'notuse', url]); } function trackDisable(identifier) { _gaq.push(['_trackEvent', 'option', 'disable', identifier]); } function trackAutoEnable(identifier) { _gaq.push(['_trackEvent', 'option', 'autoenable', identifier]); } function trackEnable(identifier) { _gaq.push(['_trackEvent', 'option', 'enable', identifier]); } function trackAddCustomRule(rule, auto) { var cmd = 'add'; if (auto) { cmd = 'add-' + auto; } _gaq.push(['_trackEvent', 'option', cmd, serializeRule(rule)]); } function trackManualUpdate() { _gaq.push(['_trackEvent', 'update', 'manual']); } function trackUpdateFile(url) { _gaq.push(['_trackEvent', 'update', 'file', url]); }
007slmg-np-activex
chrome/gas.js
JavaScript
mpl11
2,812
// 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 tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1')); if (isNaN(tabId)) { alert('Invalid tab id'); } var backgroundPage = chrome.extension.getBackgroundPage(); var tabInfo = backgroundPage.tabStatus[tabId]; var setting = backgroundPage.setting; if (!tabInfo) { alert('Cannot get tab tabInfo'); } $(document).ready(function() { $('.status').hide(); $('#submitissue').hide(); if (tabInfo.count == 0) { // Shouldn't have this popup } else if (tabInfo.error != 0) { $('#status_error').show(); } else if (tabInfo.count != tabInfo.actived) { $('#status_disabled').show(); } else { $('#status_ok').show(); $('#submitissue').show(); } }); $(document).ready(function() { $('#issue_view').hide(); if (tabInfo.error != 0) { var errorid = tabInfo.issueId; var issue = setting.issues[errorid]; $('#issue_content').text(issue.description); var url = issue.url; if (!url) { var issueUrl = "http://code.google.com/p/np-activex/issues/detail?id="; url = issueUrl + issue.issueId; } $('#issue_track').click(function() { chrome.tabs.create({url:url}); window.close(); }); $('#issue_view').show(); } }); function refresh() { alert($$('refresh_needed')); window.close(); } function showEnableBtns() { var list = $('#enable_btns'); list.hide(); if (tabInfo.count > tabInfo.actived) { list.show(); var info = {actived: true}; for (var i = 0; i < tabInfo.frames && info.actived; ++i) { for (var j = 0; j < tabInfo.objs[i].length && info.actived; ++j) { info = tabInfo.objs[i][j]; } } if (info.actived) { return; } var rule = setting.getFirstMatchedRule(info, setting.defaultRules); if (rule) { var button = $('<button>').addClass('defaultRule'); button.text($$('enable_default_rule', rule.title)); button.click(function() { setting.activeRule(rule); refresh(); }); list.append(button); } else { var site = info.href.replace(/[^:]*:\/\/([^\/]*).*/, '$1'); var sitepattern = info.href.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*'); var btn1 = $('<button>').addClass('customRule'). text($$('add_rule_site', site)).click(function() { var rule = setting.createRule(); rule.type = 'wild'; rule.value = sitepattern; setting.addCustomRule(rule, 'popup'); refresh(); }); var clsid = info.clsid; var btn2 = $('<button>').addClass('customRule'). text($$('add_rule_clsid')).click(function() { var rule = setting.createRule(); rule.type = 'clsid'; rule.value = clsid; setting.addCustomRule(rule, 'popup'); refresh(); }); list.append(btn1).append(btn2); } } } $(document).ready(function() { $('#submitissue').click(function() { tabInfo.tracking = true; alert($$('issue_submitting_desp')); window.close(); }); }); $(document).ready(showEnableBtns); $(window).load(function() { $('#share').load('share.html'); });
007slmg-np-activex
chrome/popup.js
JavaScript
mpl11
3,384
<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的亲们:只要安装了这个扩展,就可以直接在Chrome里使用各种网银、播放器等ActiveX控件了。而且不用切换内核,非常方便。下载地址:'; </script> </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/all.js#xfbml=1"; js.async = true; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="line"> <div class="fb-like" data-href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn" data-send="true" data-width="450" data-show-faces="false"></div> </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" expandTo="top"></g:plusone> <!-- Place this render call where appropriate --> <script type="text/javascript"> window.___gcfg = {lang: navigator.language}; (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"> <div id="weiboshare"> </div> <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] || '' ) ) } weiboshare.innerHTML = ('<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> </body> </html>
007slmg-np-activex
chrome/share.html
HTML
mpl11
4,378
// Copyright (c) 2010 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 $$ = chrome.i18n.getMessage; function loadI18n() { document.title = chrome.i18n.getMessage("option_title") var spans = document.querySelectorAll('[i18n]'); for (var i = 0; i < spans.length; ++i) { var obj = spans[i]; v = $$(obj.getAttribute("i18n")); if (v == "") v = obj.getAttribute('i18n'); if (obj.tagName == 'INPUT') { obj.value = v; } else { obj.innerText = v; } } } window.addEventListener("load", loadI18n, false);
007slmg-np-activex
chrome/i18n.js
JavaScript
mpl11
679
// 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 background = chrome.extension.getBackgroundPage(); var setting = background.setting; var updateSession = background.updateSession; function toggleRule(e) { var line = e.data.line; var index = line.attr('row'); var item = setting.order[index]; if (item.position == 'default') { if (item.status == 'enabled') { item.status = 'disabled'; trackDisable(item.identifier); } else if (item.status == 'disabled') { item.status = 'enabled'; trackEnable(item.identifier); } } line.blur(); e.data.list.finishEdit(line); e.data.list.updateLine(line); save(); } var settingProps = [ { header: "", property: "status", type: 'button', caption: "", events: { command: toggleRule, update: setStatus, createNew: setStatusNew } }, { header: $$("title"), 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: $$("user_agent"), 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"}, {value: "ip5", text: "iPhone"}, {value: "ipad5", text: "iPad"} ] }, { header: $$("helper_script"), property: "script", type: "input" } ]; var table; var dirty = false; function save() { dirty = true; } function doSave() { if (dirty) { dirty = false; setting.update(); } } function setReadonly(e) { var line = e.data.line; var id = line.attr('row'); if (id < 0) { return; } var order = setting.order[id]; var divs = $('.listvalue', line); if (order.position != 'custom') { divs.addClass('readonly'); } else { divs.removeClass('readonly'); } } $(window).blur(doSave); function refresh() { table.refresh(); } // Main setting $(document).ready(function() { table = new List({ props: settingProps, main: $('#tbSetting'), lineEvents: { update: setReadonly }, getItems: function() { return setting.order; }, getItemProp: function(i, prop) { if (prop in setting.order[i]) { return setting.order[i][prop]; } return setting.getItem(setting.order[i])[prop]; }, setItemProp: function(i, prop, value) { if (prop in setting.order[i]) { setting.order[i][prop] = value; } else { setting.getItem(setting.order[i])[prop] = value; } }, defaultValue: setting.createRule(), count: function() { return setting.order.length; }, insert: function(id, newItem) { setting.addCustomRule(newItem); this.move(setting.order.length - 1, id); }, remove: function(id) { if (setting.order[id].position != 'custom') { return true; } var identifier = setting.order[id].identifier; delete setting.rules[identifier]; setting.order.splice(id, 1); }, validate: function(id, rule) { return setting.validateRule(rule); } }); $(table).bind('updated', save); $('#addRule').bind('click', function() { table.editNewLine(); }); $(table).bind('select', function() { var line = table.selectedLine; if (line < 0) { $('#moveUp').attr('disabled', 'disabled'); $('#moveDown').attr('disabled', 'disabled'); $('#deleteRule').attr('disabled', 'disabled'); } else { if (line != 0) { $('#moveUp').removeAttr('disabled'); } else { $('#moveUp').attr('disabled', 'disabled'); } if (line != setting.order.length - 1) { $('#moveDown').removeAttr('disabled'); } else { $('#moveDown').attr('disabled', 'disabled'); } if (setting.order[line].position != 'custom') { $('#deleteRule').attr('disabled', 'disabled'); } else { $('#deleteRule').removeAttr('disabled'); } } }); $('#moveUp').click(function() { var line = table.selectedLine; table.move(line, line - 1, true); }); $('#moveDown').click(function() { var line = table.selectedLine; table.move(line, line + 1, true); }); $('#deleteRule').click(function() { var line = table.selectedLine; table.remove(line); }); table.init(); updateSession.bind('update', refresh); updateSession.bind('updating', showUpdatingState); updateSession.bind('progress', showUpdatingState); updateSession.bind('complete', showUpdatingState); }); window.onbeforeunload = function() { updateSession.unbind('update', refresh); updateSession.unbind('updating', showUpdatingState); updateSession.unbind('progress', showUpdatingState); updateSession.unbind('complete', showUpdatingState); } function setStatusNew(e) { with (e.data) { s = 'Custom'; color = '#33f'; $('button', line).text(s).css('background-color', color); } } function setStatus(e) { with (e.data) { var id = line.attr('row'); var order = setting.order[id]; var rule = setting.getItem(order); var s, color; if (order.status == 'enabled') { s = $$('Enabled'); color = '#0A0'; } else if (order.status == 'disabled') { s = $$('Disabled'); color = 'indianred'; } else { s = $$('Custom'); color = '#33f'; } $('button', line).text(s).css('background-color', color); } } function showTime(time) { var never = 'Never' if (time == 0) { return never; } var delta = Date.now() - time; if (delta < 0) { return never; } function getDelta(delta) { var sec = delta / 1000; if (sec < 60) { return [sec, 'second']; } var minute = sec / 60; if (minute < 60) { return [minute, 'minute']; } var hour = minute / 60; if (hour < 60) { return [hour, 'hour']; } var day = hour / 24; return [day, 'day']; } var disp = getDelta(delta); var v1 = Math.floor(disp[0]); return v1 + ' ' + disp[1] + (v1 != 1 ? 's' : '') + " ago"; } function showUpdatingState(e) { if (updateSession.status == 'stop') { $('#lastUpdate').text(showTime(setting.misc.lastUpdate)); } else { $('#lastUpdate').text($$("update_progress") + updateSession.finish + '/' + updateSession.total); } } $(document).ready(function() { showUpdatingState({}); $('#doUpdate').click(function() { setting.updateConfig(updateSession); trackManualUpdate(); }); $('#log_enable').change(function(e) { setting.misc.logEnabled = e.target.checked; save(); })[0].checked = setting.misc.logEnabled; $('#tracking').change(function(e) { setting.misc.tracking = e.target.checked; save(); })[0].checked = setting.misc.tracking; }); $(document).ready(function() { var help = 'http://code.google.com/p/np-activex/wiki/ExtensionHelp?wl='; help = help + $$('wikicode'); $('.help').each(function() { this.href = help; }); }); $(window).load(function() { $('#share').load('share.html'); if (background.firstUpgrade) { background.firstUpgrade = false; alert($$("upgrade_show")); } $('#follow').html('<iframe width="136" height="24" frameborder="0" allowtransparency="true" marginwidth="0" marginheight="0" scrolling="no" border="0" src="http://widget.weibo.com/relationship/followbutton.php?language=zh_cn&width=136&height=24&uid=2356524070&style=2&btn=red&dpc=1"></iframe>'); });
007slmg-np-activex
chrome/options.js
JavaScript
mpl11
8,110
<script src="jquery-1.7.min.js" > </script> <script src="i18n.js" > </script> <script src="common.js" > </script> <script src="configure.js"> </script> <script src="web.js"> </script> <script src="configUpdate.js"> </script> <script src="gas.js"> </script> <script> var setting = loadLocalSetting(); var updateSession = new UpdateSession(); setting.cache.listener = updateSession; updateSession.bind('success', function() { setting.misc.lastUpdate = Date.now(); }); updateSession.bind('complete', function() { setting.update(); console.log('Update completed'); }); UpdateSession.setUpdateInterval(function() { setting.updateConfig(updateSession); }, updateSession, DEFAULT_INTERVAL); startListener(); registerRequestListener(); initGAS(); if (firstRun || firstUpgrade) { firstRun = false; open('options.html'); } </script>
007slmg-np-activex
chrome/background.html
HTML
mpl11
916
// 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; });
007slmg-np-activex
chrome/listtypes.js
JavaScript
mpl11
3,295
// 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 tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1')); if (isNaN(tabId)) { alert('Invalid tab id'); } var backgroundPage = chrome.extension.getBackgroundPage(); $(document).ready(function() { var s = backgroundPage.generateLogFile(tabId); $("#text").val(s); });
007slmg-np-activex
chrome/log.js
JavaScript
mpl11
482
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <windows.h> #include <winbase.h> // ---------------------------------------------------------------------------- int main (int ArgC, char *ArgV[]) { const char *sourceName; const char *targetName; HANDLE targetHandle; void *versionPtr; DWORD versionLen; int lastError; int ret = 0; if (ArgC < 3) { fprintf(stderr, "Usage: %s <source> <target>\n", ArgV[0]); exit (1); } sourceName = ArgV[1]; targetName = ArgV[2]; if ((versionLen = GetFileVersionInfoSize(sourceName, NULL)) == 0) { fprintf(stderr, "Could not retrieve version len from %s\n", sourceName); exit (2); } if ((versionPtr = calloc(1, versionLen)) == NULL) { fprintf(stderr, "Error allocating temp memory\n"); exit (3); } if (!GetFileVersionInfo(sourceName, NULL, versionLen, versionPtr)) { fprintf(stderr, "Could not retrieve version info from %s\n", sourceName); exit (4); } if ((targetHandle = BeginUpdateResource(targetName, FALSE)) == INVALID_HANDLE_VALUE) { fprintf(stderr, "Could not begin update of %s\n", targetName); free(versionPtr); exit (5); } if (!UpdateResource(targetHandle, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), versionPtr, versionLen)) { lastError = GetLastError(); fprintf(stderr, "Error %d updating resource\n", lastError); ret = 6; } if (!EndUpdateResource(targetHandle, FALSE)) { fprintf(stderr, "Error finishing update\n"); ret = 7; } free(versionPtr); return (ret); }
007slmg-np-activex
transver/transver.cpp
C++
mpl11
3,963
<html> <title>Setup Instructions for the Google API Client Library for Java</title> <body> <h2>Setup Instructions for the Google API Client Library for Java</h2> <h3>Browse Online</h3> <ul> <li><a href="http://code.google.com/p/google-api-java-client/source/browse/">Browse Source</a></li> </ul> <h3>Checkout Instructions</h3> <p><b>Prerequisites:</b> install <a href="http://java.com">Java 6</a>, <a href="http://mercurial.selenic.com/">Mercurial</a> and <a href="http://maven.apache.org/download.html">Maven</a>. You may need to set your <code>JAVA_HOME</code>.</p> <pre><code>hg clone https://google-api-java-client.googlecode.com/hg/ google-api-java-client cd google-api-java-client mvn compile test install</code></pre> <h3>Setup Project in Eclipse 3.5</h3> <p><b>Prerequisites:</b> install <a href="http://www.eclipse.org/downloads/">Eclipse</a>, the <a href="http://javaforge.com/project/HGE">Mercurial plugin</a>, the <a href="http://m2eclipse.sonatype.org/installing-m2eclipse.html">Maven plugin</a>, and the <a href="http://developer.android.com/sdk/eclipse-adt.html#installing">Android plugin</a>.</p> <ul> <li>Setup Eclipse Preferences <ul> <li>Window &gt; Preferences... (or on Mac, Eclipse &gt; Preferences...)</li> <li>Select Maven <ul> <li>check on "Download Artifact Sources"</li> <li>check on "Download Artifact JavaDoc"</li> </ul> </li> <li>Select Android <ul> <li>setup SDK location</li> </ul> </li> </ul> </li> <li>Import <code>google-api-java-client</code> project <ul> <li>File &gt; Import...</li> <li>Select "General &gt; Existing Project into Workspace" and click "Next"</li> <li>Click "Browse" next to "Select root directory", find <code><i>[someDirectory]</i>/google-api-java-client</code> and click "Next"</li> <li>Click "Finish"</li> </ul> </li> <li>Import <code>google-api-client</code> project <ul> <li>File &gt; Import...</li> <li>Select "General &gt; Existing Project into Workspace" and click "Next"</li> <li>Click "Browse" next to "Select root directory", find <code><i>[someDirectory]</i>/google-api-java-client/google-api-client</code> and click "Next"</li> <li>Click "Finish"</li> </ul> </li> </ul> </body> </html>
11durong-mytest1
instructions.html
HTML
asf20
2,304
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.http; /** * Mock for {@link LowLevelHttpRequest}. * * @author Yaniv Inbar */ public class MockLowLevelHttpRequest extends LowLevelHttpRequest { @Override public void addHeader(String name, String value) { } @Override public LowLevelHttpResponse execute() { return new MockLowLevelHttpResponse(); } @Override public void setContent(HttpContent content) { } }
11durong-mytest1
google-api-client/test/com/google/api/client/http/MockLowLevelHttpRequest.java
Java
asf20
1,008
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.http; import java.io.IOException; import java.io.OutputStream; /** * Mock for {@link HttpContent}. * * @author Yaniv Inbar */ public class MockHttpContent implements HttpContent { public String encoding; public long length = -1; public String type; public byte[] content = "".getBytes(); public String getEncoding() { return encoding; } public long getLength() { return length; } public String getType() { return type; } public void writeTo(OutputStream out) throws IOException { out.write(content); } }
11durong-mytest1
google-api-client/test/com/google/api/client/http/MockHttpContent.java
Java
asf20
1,194
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.http; import java.io.IOException; import java.util.Set; import java.util.TreeSet; /** * Mock for {@link LowLevelHttpTransport}. * * @author Yaniv Inbar */ public class MockLowLevelHttpTransport extends LowLevelHttpTransport { public Set<String> supportedOptionalMethods = new TreeSet<String>(); @Override public LowLevelHttpRequest buildDeleteRequest(String url) { return new MockLowLevelHttpRequest(); } @Override public LowLevelHttpRequest buildGetRequest(String url) { return new MockLowLevelHttpRequest(); } @Override public LowLevelHttpRequest buildHeadRequest(String url) throws IOException { if (!supportsHead()) { return super.buildHeadRequest(url); } return new MockLowLevelHttpRequest(); } @Override public LowLevelHttpRequest buildPatchRequest(String url) throws IOException { if (!supportsPatch()) { return super.buildPatchRequest(url); } return new MockLowLevelHttpRequest(); } @Override public LowLevelHttpRequest buildPostRequest(String url) { return new MockLowLevelHttpRequest(); } @Override public LowLevelHttpRequest buildPutRequest(String url) { return new MockLowLevelHttpRequest(); } @Override public boolean supportsHead() { return supportedOptionalMethods.contains("HEAD"); } @Override public boolean supportsPatch() { return supportedOptionalMethods.contains("PATCH"); } }
11durong-mytest1
google-api-client/test/com/google/api/client/http/MockLowLevelHttpTransport.java
Java
asf20
2,044
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.http; import com.google.api.client.util.Strings; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; /** * Mock for {@link LowLevelHttpResponse}. * * @author Yaniv Inbar */ public class MockLowLevelHttpResponse extends LowLevelHttpResponse { public InputStream content = null; public String contentType = "application/json"; public int statusCode = 200; public ArrayList<String> headerNames = new ArrayList<String>(); public ArrayList<String> headerValues = new ArrayList<String>(); public void addHeader(String name, String value) { headerNames.add(name); headerValues.add(value); } public void setContent(String stringContent) { content = new ByteArrayInputStream(Strings.toBytesUtf8(stringContent)); } @Override public InputStream getContent() { return content; } @Override public String getContentEncoding() { return null; } @Override public long getContentLength() { return 0; } @Override public String getContentType() { return contentType; } @Override public int getHeaderCount() { return headerNames.size(); } @Override public String getHeaderName(int index) { return headerNames.get(index); } @Override public String getHeaderValue(int index) { return headerValues.get(index); } @Override public String getReasonPhrase() { return null; } @Override public int getStatusCode() { return statusCode; } @Override public String getStatusLine() { return null; } }
11durong-mytest1
google-api-client/test/com/google/api/client/http/MockLowLevelHttpResponse.java
Java
asf20
2,182
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.linewrap.LineWrapper; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Yaniv Inbar */ public class Generation { static void compute(List<AbstractFileGenerator> fileGenerators, File outputDirectory) throws IOException { int size = 0; List<FileComputer> fileComputers = new ArrayList<FileComputer>(); System.out.println(); System.out.println("Computing " + fileGenerators.size() + " file(s):"); Set<String> outputFilePaths = new HashSet<String>(); for (AbstractFileGenerator fileGenerator : fileGenerators) { FileComputer fileComputer = new FileComputer(fileGenerator, outputDirectory); if (!outputFilePaths.add(fileComputer.outputFilePath)) { System.err.println("Error: duplicate output file path: " + fileComputer.outputFilePath); System.exit(1); } fileComputers.add(fileComputer); fileComputer.compute(); System.out.print('.'); if (fileComputer.status != FileStatus.UNCHANGED) { size++; } } System.out.println(); System.out.println(); System.out.println("Output root directory: " + outputDirectory); System.out.println(); if (size != 0) { System.out.println(size + " update(s):"); int index = 0; for (FileComputer fileComputer : fileComputers) { if (fileComputer.status != FileStatus.UNCHANGED) { index++; System.out.println( fileComputer.outputFilePath + " (" + fileComputer.status.toString().toLowerCase() + ")"); } } } else { System.out.println("All files up to date."); } } static File getDirectory(String path) { File directory = new File(path); if (!directory.isDirectory()) { System.err.println("not a directory: " + path); System.exit(1); } return directory; } private enum FileStatus { UNCHANGED, ADDED, UPDATED, DELETED } private static class FileComputer { private final AbstractFileGenerator fileGenerator; FileStatus status = FileStatus.UNCHANGED; final String outputFilePath; private final File outputDirectory; FileComputer(AbstractFileGenerator fileGenerator, File outputDirectory) { this.fileGenerator = fileGenerator; this.outputDirectory = outputDirectory; outputFilePath = fileGenerator.getOutputFilePath(); } void compute() throws IOException { File file = new File(outputDirectory, outputFilePath); boolean exists = file.exists(); boolean isGenerated = fileGenerator.isGenerated(); if (isGenerated) { StringWriter stringWriter = new StringWriter(); PrintWriter stringPrintWriter = new PrintWriter(stringWriter); fileGenerator.generate(stringPrintWriter); String content = stringWriter.toString(); LineWrapper lineWrapper = fileGenerator.getLineWrapper(); if (lineWrapper != null) { content = lineWrapper.compute(content); } if (exists) { String currentContent = readFile(file); if (currentContent.equals(content)) { return; } } file.getParentFile().mkdirs(); FileWriter fileWriter = new FileWriter(file); fileWriter.write(content); fileWriter.close(); if (exists) { status = FileStatus.UPDATED; } else { status = FileStatus.ADDED; } } else if (exists) { file.delete(); status = FileStatus.DELETED; } } } static String readFile(File file) throws IOException { InputStream content = new FileInputStream(file); try { int length = (int) file.length(); byte[] buffer = new byte[length]; content.read(buffer); return new String(buffer, 0, length); } finally { content.close(); } } private Generation() { } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/Generation.java
Java
asf20
4,801
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.model; /** * @author Yaniv Inbar */ public final class DependencyModel implements Comparable<DependencyModel> { public String artifactId; public String groupId; public String scope; public String version; public int compareTo(DependencyModel other) { int compare = groupId.compareTo(other.groupId); if (compare != 0) { return compare; } return artifactId.compareTo(other.artifactId); } @Override public int hashCode() { return artifactId.hashCode() * 31 + groupId.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof DependencyModel)) { return false; } DependencyModel other = (DependencyModel) obj; return artifactId.equals(other.artifactId) && groupId.equals(other.groupId); } @Override public String toString() { return "DependencyModel [artifactId=" + artifactId + ", groupId=" + groupId + (scope != null ? ", scope=" + scope : "") + (version != null ? ", version=" + version : "") + "]"; } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/model/DependencyModel.java
Java
asf20
1,710
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.model; import com.google.api.client.http.InputStreamContent; import com.google.api.client.repackaged.com.google.common.base.Preconditions; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.SortedSet; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Yaniv Inbar */ public final class PackageModel implements Comparable<PackageModel> { public static final String VERSION = "1.2.3-alpha"; public static final String VERSION_SNAPSHOT = VERSION + "-SNAPSHOT"; private static final Pattern IMPORT_PATTERN = Pattern.compile("\nimport ([\\w.]+);"); public final String artifactId; public final String directoryPath; public final TreeSet<DependencyModel> dependencies = new TreeSet<DependencyModel>(); private PackageModel(String artifactId) { this.artifactId = artifactId; directoryPath = "com/" + artifactId.replace('-', '/'); } public int compareTo(PackageModel other) { return artifactId.compareTo(other.artifactId); } @Override public String toString() { return "PackageModel [artifactId=" + artifactId + ", directoryPath=" + directoryPath + ", dependencies=" + dependencies + "]"; } public static SortedSet<PackageModel> compute(File googleApiClientDirectory) throws IOException { SortedSet<PackageModel> pkgs = new TreeSet<PackageModel>(); File srcDirectory = new File(googleApiClientDirectory, "src/com"); int rootPathLength = srcDirectory.getCanonicalPath().length(); addPackageModels(rootPathLength, srcDirectory, pkgs); return pkgs; } private static void addPackageModels(int rootPathLength, File dir, SortedSet<PackageModel> pkgs) throws IOException { PackageModel pkg = null; for (File file : dir.listFiles()) { if (file.isDirectory()) { addPackageModels(rootPathLength, file, pkgs); } else { if (file.getName().endsWith(".java")) { if (pkg == null) { pkg = new PackageModel(file .getParentFile() .getCanonicalPath() .substring(1 + rootPathLength) .replace('/', '-')); pkgs.add(pkg); } String content = readFile(file); Matcher matcher = IMPORT_PATTERN.matcher(content); while (matcher.find()) { String className = matcher.group(1); String packageName = getPackageName(className); if (className.startsWith("com.google.")) { if (className.startsWith("com.google.api.client")) { DependencyModel dep = new DependencyModel(); dep.groupId = "com.google.api.client"; dep.artifactId = packageName.substring("com.".length()).replace('.', '-'); dep.version = VERSION_SNAPSHOT; if (!pkg.artifactId.equals(dep.artifactId)) { pkg.dependencies.add(dep); } } else if (className.startsWith("com.google.appengine")) { DependencyModel dep = new DependencyModel(); dep.groupId = "com.google.appengine"; dep.artifactId = "appengine-api-1.0-sdk"; dep.scope = "provided"; pkg.dependencies.add(dep); } } else if (className.startsWith("android.")) { DependencyModel dep = new DependencyModel(); dep.groupId = "com.google.android"; dep.artifactId = "android"; pkg.dependencies.add(dep); } else if (className.startsWith("org.apache.")) { DependencyModel dep = new DependencyModel(); dep.groupId = "org.apache.httpcomponents"; dep.artifactId = "httpclient"; pkg.dependencies.add(dep); } else if (className.startsWith("org.xmlpull.v1.")) { DependencyModel dep = new DependencyModel(); dep.groupId = dep.artifactId = "xpp3"; pkg.dependencies.add(dep); } else if (className.startsWith("org.codehaus.jackson.")) { DependencyModel dep = new DependencyModel(); dep.groupId = "org.codehaus.jackson"; dep.artifactId = "jackson-core-asl"; pkg.dependencies.add(dep); } else if (className.startsWith("java.") || className.startsWith("javax.")) { // ignore } else { throw new IllegalArgumentException("unrecognized package: " + packageName); } } } } } } public static String readFile(File file) throws IOException { InputStreamContent content = new InputStreamContent(); content.setFileInput(file); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); content.writeTo(byteStream); return new String(byteStream.toByteArray()); } /** * Returns the package name for the given Java class or package name, assuming that class names * always start with a capital letter and package names always start with a lowercase letter. */ public static String getPackageName(String classOrPackageName) { int lastDot = classOrPackageName.length(); if (lastDot == 0) { return ""; } while (true) { int nextDot = classOrPackageName.lastIndexOf('.', lastDot - 1); // check for error case of 2 dots in a row or starts/ends in dot Preconditions.checkArgument(nextDot + 1 < lastDot); if (Character.isLowerCase(classOrPackageName.charAt(nextDot + 1))) { // check for case that input string is already a package if (lastDot == classOrPackageName.length()) { return classOrPackageName; } return classOrPackageName.substring(0, lastDot); } if (nextDot == -1) { return ""; } lastDot = nextDot; } } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/model/PackageModel.java
Java
asf20
6,576
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Abstract super class for all language-specific line wrappers. * * @author Yaniv Inbar */ abstract class AbstractLineWrapper implements LineWrapper { private static final ThreadLocal<StringBuilder> LOCAL_OUT_BUFFER = new ThreadLocalStringBuilder(); private static final ThreadLocal<StringBuilder> LOCAL_PREFIX_BUFFER = new ThreadLocalStringBuilder(); /** * Computation state interface used for storing arbitrary data during the line wrapping * computation that can be shared across all lines. */ interface ComputationState { } /** Thread-local string builder instance. */ static class ThreadLocalStringBuilder extends ThreadLocal<StringBuilder> { @Override protected StringBuilder initialValue() { return new StringBuilder(); } } public final String compute(String text) { // parse into separate lines ComputationState computationState = computationState(); int nextNewLine = 0; int lineSeparatorLength = Strings.LINE_SEPARATOR.length(); int textLength = text.length(); int copyFromTextIndex = 0; StringBuilder prefix = LOCAL_PREFIX_BUFFER.get(); StringBuilder outBuffer = LOCAL_OUT_BUFFER.get(); outBuffer.setLength(0); for (int curIndex = 0; nextNewLine != -1 && curIndex < textLength; curIndex = nextNewLine + 1) { // find next line separator which we know ends in '\n' nextNewLine = text.indexOf('\n', curIndex); int highIndex = nextNewLine == -1 ? textLength - 1 : nextNewLine - lineSeparatorLength; // remove whitespace from end of line int lastNonSpace = Strings.lastIndexOfNonSpace(text, highIndex, curIndex); if (lastNonSpace == -1) { // empty line if (nextNewLine == -1) { // end of text but missing new line outBuffer.append(text, copyFromTextIndex, curIndex); outBuffer.append(Strings.LINE_SEPARATOR); copyFromTextIndex = textLength; } else if (nextNewLine != curIndex) { // line may up of >= 1 space outBuffer.append(text, copyFromTextIndex, curIndex); copyFromTextIndex = highIndex + 1; } continue; } // remove whitespace from beginning of line, remembering it as a "prefix" int firstNonSpace = Strings.indexOfNonSpace(text, curIndex, lastNonSpace); prefix.setLength(0); prefix.append(text, curIndex, firstNonSpace); // iterate over each line "cut" boolean firstCut = true; while (true) { // run the language-specific line-wrapping algorithm int originalPrefixLength = prefix.length(); String line = text.substring(firstNonSpace, lastNonSpace + 1); int cut = getCuttingPoint(computationState, line, prefix, firstCut); // remove spaces from end of cut cut = Strings.lastIndexOfNonSpace(line, cut - 1) + 1; // don't want infinite recursion! if (cut == 0) { throw new IllegalStateException( "illegal cutting point:" + "\nline (" + line.length() + "):" + line + "\nprefix (" + originalPrefixLength + "): " + prefix.substring(0, originalPrefixLength) + "\nfirstCut: " + firstCut); } if (cut == line.length() && nextNewLine != -1 && lastNonSpace == highIndex) { // preserve to the end of line if (!firstCut) { copyFromTextIndex = firstNonSpace; } } else { // make a cut if (firstCut) { outBuffer.append(text, copyFromTextIndex, firstNonSpace + cut); copyFromTextIndex = nextNewLine == -1 ? textLength : nextNewLine + 1; } else { outBuffer.append(text, firstNonSpace, firstNonSpace + cut); } // insert a line separator outBuffer.append(Strings.LINE_SEPARATOR); } // find next non-space character to start next line int next = Strings.indexOfNonSpace(line, cut); if (next == -1) { break; } // insert prefix for next line outBuffer.append(prefix); firstNonSpace += next; firstCut = false; } } // optimize for case where original text is unchanged if (copyFromTextIndex == 0) { return text; } return outBuffer.append(text, copyFromTextIndex, textLength).toString(); } /** * Instantiates a new computation state. By default just returns an empty object, but may be * overriden by subclasses. */ ComputationState computationState() { return new ComputationState() {}; } /** * Returns an index in the given string where the line should be broken. If no cut is desired or * no cut can be found, it should just return the line length. Also, this method is responsible * for updating the current line's prefix, i.e. any additional indent to use after any subsequent * cuts. * <p/> * The default implementation cuts on a space if the line length is greater than maximum width but * subclasses may override. * * @param computationState computation state * @param line current line content to be cut * @param prefix current line prefix to be updated if necessary * @param firstCut whether this is the first cut in the original input line * @return index of the character at which at cut {@code >= 1} and {@code <= line.length()} */ abstract int getCuttingPoint( ComputationState computationState, String line, StringBuilder prefix, boolean firstCut); /** * Returns a cut on a space or {@code -1} if no space found. It will try to return an index that * is {@code <= maxWidth}. */ static int getCutOnSpace(String line, int maxWidth) { int max = Math.min(line.length() - 1, maxWidth); int index = line.lastIndexOf(' ', max); if (index == -1) { index = line.indexOf(' ', max + 1); } return index; } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/AbstractLineWrapper.java
Java
asf20
6,552
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Utilities for strings. * * @author Yaniv Inbar */ public class Strings { /** * Line separator to use for this OS, i.e. {@code "\n"} or {@code "\r\n"}. */ public static final String LINE_SEPARATOR = System.getProperty("line.separator"); /** * Returns the index of the first non-space ({@code ' '}) character in the given string whose * index is greater than or equal to the given lower bound. * * @param string string or {@code null} for {@code -1} result * @param lowerBound lower bound for index * @return index or {@code -1} if not found or for {@code null} input */ public static int indexOfNonSpace(String string, int lowerBound) { if (string == null) { return -1; } return indexOfNonSpace(string, lowerBound, string.length() - 1); } /** * Returns the index of the first non-space ({@code ' '}) character in the given string whose * index is greater than or equal to the given lower bound and less than or equal to the given * upper bound. * * @param string string or {@code null} for {@code -1} result * @param lowerBound lower bound for index * @param upperBound upper bound for index * @return index or {@code -1} if not found or for {@code null} input */ public static int indexOfNonSpace(String string, int lowerBound, int upperBound) { if (string != null) { upperBound = Math.min(upperBound, string.length() - 1); for (int i = Math.max(0, lowerBound); i <= upperBound; i++) { if (' ' != string.charAt(i)) { return i; } } } return -1; } /** * Returns the index of the last non-space ({@code ' '}) character in the given string whose index * is less than or equal to the given upper bound. * * @param string string or {@code null} for {@code -1} result * @param upperBound upper bound for index * @return index or {@code -1} if not found or for {@code null} input */ public static int lastIndexOfNonSpace(String string, int upperBound) { return lastIndexOfNonSpace(string, upperBound, 0); } /** * Returns the index of the first non-space ({@code ' '}) character in the given string whose * index is greater than or equal to the given lower bound and less than or equal to the given * upper bound. * * @param string string or {@code null} for {@code -1} result * @param upperBound upper bound for index * @param lowerBound lower bound for index * @return index or {@code -1} if not found or for {@code null} input */ public static int lastIndexOfNonSpace(String string, int upperBound, int lowerBound) { if (string != null) { lowerBound = Math.max(0, lowerBound); for (int i = Math.min(upperBound, string.length() - 1); i >= lowerBound; i--) { if (' ' != string.charAt(i)) { return i; } } } return -1; } private Strings() { } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/Strings.java
Java
asf20
3,560
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Computes line wrapping on a section of text by inserting line separators and updating the * indentation as necessary. Implementations of this interface are thread-safe. * * @author Yaniv Inbar */ public interface LineWrapper { /** Computes line wrapping result for the given text. */ String compute(String text); }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/LineWrapper.java
Java
asf20
972
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Processes any single-line comments in the line. * * @author Yaniv Inbar */ final class SingleLineCommentProcessor { private final String commentPrefix; private boolean inComment; /** * @param commentPrefix prefix to recognize the start of a single-line comment, e.g. {@code "//"} * in Java. */ SingleLineCommentProcessor(String commentPrefix) { this.commentPrefix = commentPrefix; } /** * Process the given line to check if it starts with a single-line comment. * * @param line current line content to be cut * @param prefix current line prefix to be updated if necessary * @param firstCut whether this is the first cut in the original input line * @return whether the line starts with the single-line comment prefix */ boolean start(String line, StringBuilder prefix, boolean firstCut) { if (firstCut) { inComment = false; } if (!inComment && isCuttingPoint(line, 0)) { inComment = true; prefix.append(commentPrefix).append(' '); } return inComment; } /** * Returns wehther the given index is the location of the single-line comment prefix. * * @param line current line content to be cut */ boolean isCuttingPoint(String line, int index) { return line.startsWith(commentPrefix, index); } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/SingleLineCommentProcessor.java
Java
asf20
1,964
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Line wrapper for XML files. * * @author Yaniv Inbar */ public class XmlLineWrapper extends AbstractLineWrapper { /** Maximum XML line length. */ private static final int MAX_LINE_LENGTH = 80; private static final XmlLineWrapper INSTANCE = new XmlLineWrapper(); /** Returns the instance of the XML line wrapper. */ public static LineWrapper get() { return INSTANCE; } /** Computes line wrapping result for the given XML text. */ public static String wrap(String text) { return INSTANCE.compute(text); } @Override final int getCuttingPoint( ComputationState computationState, String line, StringBuilder prefix, boolean firstCut) { // if there's space, don't cut the line int maxWidth = MAX_LINE_LENGTH - prefix.length(); if (line.length() <= maxWidth) { return line.length(); } // indent on the first cut if (firstCut) { prefix.append(" "); } QuoteProcessor quoteProcessor = new QuoteProcessor(); int spaceCutWithinMaxWidth = -1; int elementEndCutWithinMaxWidth = -1; for (int i = 0; i < line.length(); i++) { char ch = line.charAt(i); if (!quoteProcessor.isSkipped(ch)) { switch (ch) { case ' ': // if past max width or found a space preceding an element start if (i > maxWidth || i + 1 < line.length() && line.charAt(i + 1) == '<') { // then cut here return i; } // else find maximum space cut within max width spaceCutWithinMaxWidth = i; break; case '/': // falls through case '>': // element close? // if first occurence of element end (not at beginning of line) if (elementEndCutWithinMaxWidth == -1 && i != 0 && (ch == '>' || i + 1 != line.length() && line.charAt(i + 1) == '>')) { // if past max width, cut here if (i > maxWidth) { return i; } // find last occurence within max width elementEndCutWithinMaxWidth = i; // can skip parsing the slash if (ch == '/') { i++; } } break; } } // check if over max space if (i >= maxWidth) { if (spaceCutWithinMaxWidth != -1) { return spaceCutWithinMaxWidth; } if (elementEndCutWithinMaxWidth != -1) { return elementEndCutWithinMaxWidth; } } } return line.length(); } XmlLineWrapper() { } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/XmlLineWrapper.java
Java
asf20
3,268
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Processes quotes in a line. Used to detect if there are any quotes. Both {@code '"'} and {@code * '\''} are valid quote characters. * * @author Yaniv Inbar */ final class QuoteProcessor { private boolean lastSlash = false; private char lastQuote = 0; /** * Returns whether to skip processing the given character because it is part of a quote. Note that * this method must be called for all previous characters on the line in order for the result to * be correct. */ boolean isSkipped(char ch) { if (lastSlash) { lastSlash = false; return true; } if (lastQuote != 0) { if (ch == lastQuote) { // end of quote sequence lastQuote = 0; } else if (ch == '\\') { // skip escaped character lastSlash = true; } return true; } if (ch == '\'' || ch == '"') { // start of quote sequence lastQuote = ch; return true; } return false; } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/QuoteProcessor.java
Java
asf20
1,615
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Line wrapper for HTML files. * * @author Yaniv Inbar */ public final class HtmlLineWrapper extends XmlLineWrapper { private static final HtmlLineWrapper INSTANCE = new HtmlLineWrapper(); /** Returns the instance of the HTML line wrapper. */ public static LineWrapper get() { return INSTANCE; } /** Computes line wrapping result for the given HTML text. */ public static String wrap(String text) { return INSTANCE.compute(text); } private HtmlLineWrapper() { } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/HtmlLineWrapper.java
Java
asf20
1,143
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Line wrapper for Java files. * * @author Yaniv Inbar */ public final class JavaLineWrapper extends AbstractLineWrapper { /** Maximum Java line length. */ static final int MAX_LINE_LENGTH = 80; private static final JavaLineWrapper INSTANCE = new JavaLineWrapper(); /** Java line wrapper computation state. */ static class JavaComputationState implements ComputationState { final JavaLikeCommentProcessor multiLineComment; final SingleLineCommentProcessor singleLineComment; JavaComputationState(boolean useJavaMultiLineCommentProcessor, String singleLineCommentPrefix) { multiLineComment = useJavaMultiLineCommentProcessor ? new JavaLikeCommentProcessor() : null; singleLineComment = new SingleLineCommentProcessor(singleLineCommentPrefix); } /** * Returns whether to cut on the line for a space character. Default implementation returns * {@code true}, but subclasses may override. */ boolean isSpaceCut(String line, int index) { return true; } } /** Returns the instance of the Java line wrapper. */ public static LineWrapper get() { return INSTANCE; } /** Computes line wrapping result for the given Java text. */ public static String wrap(String text) { return get().compute(text); } /** * {@inheritDoc} * * @return by default returns {@code new JavaComputationState(true, "//")}, but subclasses may * override. */ @Override ComputationState computationState() { return new JavaComputationState(true, "//"); } @Override int getCuttingPoint( ComputationState computationState, String line, StringBuilder prefix, boolean firstCut) { // don't cut an import if (firstCut && line.startsWith("import ")) { return line.length(); } return getCuttingPointImpl(computationState, line, prefix, firstCut, MAX_LINE_LENGTH, MAX_LINE_LENGTH); } /** Cutting algorithm for Java. */ static int getCuttingPointImpl( ComputationState computationState, String line, StringBuilder prefix, boolean firstCut) { return getCuttingPointImpl(computationState, line, prefix, firstCut, MAX_LINE_LENGTH, MAX_LINE_LENGTH); } /** Cutting algorithm for Java, with caller specified line lengths. */ static int getCuttingPointImpl(ComputationState computationState, String line, StringBuilder prefix, boolean firstCut, int maxLineLength, int maxDocLineLength) { // process for a multi-line comment JavaComputationState javaCompState = (JavaComputationState) computationState; JavaLikeCommentProcessor multiLineComment = javaCompState.multiLineComment; if (multiLineComment != null) { multiLineComment.processLine(line); } // process for single line comment int originalPrefixLength = prefix.length(); if ((multiLineComment == null || multiLineComment.getCommentStart() == null) && !javaCompState.singleLineComment.start(line, prefix, firstCut)) { // if there's space, don't cut the line int maxWidth = maxLineLength - originalPrefixLength; if (line.length() <= maxWidth) { return line.length(); } int spaceCutWithinMaxWidth = -1; int commaSpaceCutWithinMaxWidth = -1; int openParenCutWithinMaxWidth = -1; int result = line.length(); QuoteProcessor quoteProcessor = new QuoteProcessor(); for (int i = 0; i < result; i++) { char ch = line.charAt(i); // process for quotes if (!quoteProcessor.isSkipped(ch)) { // process for a single-line comment if (i >= 1 && javaCompState.singleLineComment.isCuttingPoint(line, i)) { return i; } switch (ch) { case ',': if (i + 1 < line.length() && line.charAt(i + 1) == ' ') { if (i + 1 <= maxWidth) { commaSpaceCutWithinMaxWidth = i + 1; } else { result = i + 1; } } break; case ' ': if (javaCompState.isSpaceCut(line, i)) { if (i <= maxWidth) { spaceCutWithinMaxWidth = i; } else { result = i; } } break; case '[': if (i + 1 <= maxWidth) { openParenCutWithinMaxWidth = i + 1; } else { result = i + 1; } break; case '(': int nextChIndex = Strings.indexOfNonSpace(line, i + 1); if (nextChIndex != -1) { if (line.charAt(nextChIndex) != ')') { if (i + 1 <= maxWidth) { openParenCutWithinMaxWidth = i + 1; } else { result = i + 1; } } i = nextChIndex - 1; } break; } } // check if over max space if (i >= maxWidth) { if (commaSpaceCutWithinMaxWidth != -1) { result = commaSpaceCutWithinMaxWidth; } else if (spaceCutWithinMaxWidth != -1) { result = spaceCutWithinMaxWidth; } else if (openParenCutWithinMaxWidth != -1) { result = openParenCutWithinMaxWidth; } } } // indent on the first cut if (firstCut) { prefix.append(" "); } return result; } // is it a JavaDoc comment start? boolean isJavaDoc = multiLineComment != null && "/**".equals(multiLineComment.getCommentStart()); int localLength = isJavaDoc ? maxDocLineLength : maxLineLength; // if there's space, don't cut the line int maxWidth = localLength - originalPrefixLength; if (line.length() <= maxWidth) { return line.length(); } // in a comment, so use default algorithm int index = getCutOnSpace(line, maxWidth); if (index != -1) { // update the prefix so next lines are properly indented if (firstCut && multiLineComment != null && multiLineComment.getCommentStart() != null) { if (line.startsWith("/*")) { prefix.append(' '); } prefix.append("* "); if (isJavaDoc && javaDocAtParamPattern(line)) { prefix.append(" "); } } return index; } return line.length(); } /** Returns whether it finds the {@code "@param"} in the JavaDoc. */ private static boolean javaDocAtParamPattern(String line) { int index = 0; if (line.startsWith("/*")) { index += 2; } if (line.charAt(index) != '*') { return false; } index = Strings.indexOfNonSpace(line, index + 1); return index != -1 && (line.startsWith("@param ", index) || line.startsWith("@return ", index)); } private JavaLineWrapper() { } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/JavaLineWrapper.java
Java
asf20
7,640
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator.linewrap; /** * Processes multi-line comments like the ones in Java, i.e. those that start with {@code "/*"}. The * current implementation of this processor is that {@code "/*"} must be at the beginning of the * line, and {@code "*\/"} must be at the end of the line. * * @author Yaniv Inbar */ final class JavaLikeCommentProcessor { /** * Multi-line comment start prefix or {@code null} if not inside a multi-line comment. */ private String commentStart = null; /** * Current line's multi-line comment start prefix or {@code null} for none. */ private String curCommentStart = null; /** * Processes the current line for a multi-line comment. Must be called regardless of whether the * line is going to be cut. */ void processLine(String line) { /* * TODO: support case where multi-line comments don't start at beginning of line or end at end * of line */ // check if we're in a multi-line comment if (commentStart == null && line.startsWith("/*")) { if (line.length() >= 3 && line.charAt(2) == '*') { // Javadoc comment commentStart = "/**"; } else { // non-Javadoc comment commentStart = "/*"; } } // cur line's comment curCommentStart = commentStart; // check for end of comment if (commentStart != null && line.endsWith("*/")) { commentStart = null; } } /** * Returns the current line's multi-line comment start prefix or {@code null} for none. */ String getCommentStart() { return curCommentStart; } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/linewrap/JavaLikeCommentProcessor.java
Java
asf20
2,206
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.linewrap.LineWrapper; import com.google.api.client.generator.linewrap.XmlLineWrapper; /** * @author Yaniv Inbar */ abstract class AbstractXmlFileGenerator extends AbstractFileGenerator { @Override public final LineWrapper getLineWrapper() { return XmlLineWrapper.get(); } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/AbstractXmlFileGenerator.java
Java
asf20
959
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.linewrap.HtmlLineWrapper; import com.google.api.client.generator.linewrap.LineWrapper; /** * @author Yaniv Inbar */ abstract class AbstractHtmlFileGenerator extends AbstractFileGenerator { @Override public final LineWrapper getLineWrapper() { return HtmlLineWrapper.get(); } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/AbstractHtmlFileGenerator.java
Java
asf20
962
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.model.PackageModel; import java.io.PrintWriter; import java.util.SortedSet; /** * @author Yaniv Inbar */ final class DistXmlFileGenerator extends AbstractFileGenerator { private final SortedSet<PackageModel> pkgs; DistXmlFileGenerator(SortedSet<PackageModel> pkgs) { this.pkgs = pkgs; } @Override public void generate(PrintWriter out) { out.println("<assembly xmlns=\"http://maven.apache.org/plugins/" + "maven-assembly-plugin/assembly/1.1.0\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:schemaLocation=\"http://maven.apache.org/plugins/" + "maven-assembly-plugin/assembly/1.1.0 " + "http://maven.apache.org/xsd/assembly-1.1.0.xsd\">"); out.println(" <id>java</id>"); out.println(" <formats>"); out.println(" <format>zip</format>"); out.println(" </formats>"); out.println(" <files>"); out.println(" <file>"); out.println(" <source>target/${project.artifactId}-${project.version}.jar</source>"); out.println(" </file>"); out.println(" <file>"); out.println( " <source>target/${project.artifactId}-${project.version}-sources.jar</source>"); out.println(" </file>"); out.println(" <file>"); out.println( " <source>target/${project.artifactId}-${project.version}-javadoc.jar</source>"); out.println(" </file>"); out.println(" <file>"); out.println(" <source>assemble/LICENSE</source>"); out.println(" </file>"); out.println(" <file>"); out.println(" <source>assemble/packages/readme.html</source>"); out.println(" <outputDirectory>packages</outputDirectory>"); out.println(" <filtered>true</filtered>"); out.println(" </file>"); out.println(" <file>"); out.println(" <source>assemble/readme.html</source>"); out.println(" <filtered>true</filtered>"); out.println(" </file>"); out.println(" <file>"); out.println(" <source>assemble/dependencies/readme.html</source>"); out.println(" <outputDirectory>dependencies</outputDirectory>"); out.println(" <filtered>true</filtered>"); out.println(" </file>"); for (PackageModel pkg : pkgs) { out.println(" <file>"); out.println(" <source>modules/" + pkg.artifactId + "/target/" + pkg.artifactId + "-" + PackageModel.VERSION + ".jar</source>"); out.println(" <outputDirectory>packages</outputDirectory>"); out.println(" </file>"); } out.println(" </files>"); out.println(" <fileSets>"); out.println(" <fileSet>"); out.println(" <directory>assemble/dependencies/java</directory>"); out.println(" <outputDirectory>dependencies/java</outputDirectory>"); out.println(" </fileSet>"); out.println(" </fileSets>"); out.println(" <dependencySets>"); out.println(" <dependencySet>"); out.println(" <outputDirectory>dependencies</outputDirectory>"); out.println(" <useProjectArtifact>false</useProjectArtifact>"); out.println(" </dependencySet>"); out.println(" </dependencySets>"); out.println("</assembly>"); out.close(); } @Override public String getOutputFilePath() { return "assemble/dist.xml"; } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/DistXmlFileGenerator.java
Java
asf20
4,010
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.linewrap.JavaLineWrapper; import com.google.api.client.generator.linewrap.LineWrapper; import java.io.PrintWriter; /** * @author Yaniv Inbar */ abstract class AbstractJavaFileGenerator extends AbstractFileGenerator { final String packageName; final String className; AbstractJavaFileGenerator(String packageName, String className) { this.packageName = packageName; this.className = className; } @Override public final LineWrapper getLineWrapper() { return JavaLineWrapper.get(); } @Override public final String getOutputFilePath() { return "src/" + packageName.replace('.', '/') + "/" + className + ".java"; } void generateHeader(PrintWriter out) { out.println("/*"); out.println(" * Copyright (c) 2010 Google Inc."); out.println(" *"); out.println(" * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not"); out.println(" * use this file except in compliance with the License. You may obtain a copy of"); out.println(" * the License at"); out.println(" *"); out.println(" * http://www.apache.org/licenses/LICENSE-2.0"); out.println(" *"); out.println(" * Unless required by applicable law or agreed to in writing, software"); out.println(" * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT"); out.println(" * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the"); out.println(" * License for the specific language governing permissions and limitations under"); out.println(" * the License."); out.println(" */"); out.println(); out.println("package " + packageName + ";"); out.println(); } String useClass(Class<?> clazz) { String fullName = clazz.getName(); int lastDot = fullName.lastIndexOf('.'); return fullName.substring(lastDot + 1).replace('$', '.'); } static String indent(int numSpaces) { return " ".substring(0, numSpaces); } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/AbstractJavaFileGenerator.java
Java
asf20
2,650
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.model.DependencyModel; import com.google.api.client.generator.model.PackageModel; import java.io.PrintWriter; /** * @author Yaniv Inbar */ final class ModulePomFileGenerator extends AbstractFileGenerator { private final PackageModel pkg; ModulePomFileGenerator(PackageModel pkg) { this.pkg = pkg; } @Override public void generate(PrintWriter out) { out.println("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 " + "http://maven.apache.org/maven-v4_0_0.xsd\">"); out.println(" <modelVersion>4.0.0</modelVersion>"); out.println(" <parent>"); out.println(" <groupId>com.google.api.client</groupId>"); out.println(" <artifactId>google-api-client-modules-parent</artifactId>"); out.println(" <version>" + PackageModel.VERSION_SNAPSHOT + "</version>"); out.println(" </parent>"); out.println(" <artifactId>" + pkg.artifactId + "</artifactId>"); out.println(" <build>"); out.println(" <plugins>"); out.println(" <plugin>"); out.println(" <artifactId>maven-source-plugin</artifactId>"); out.println(" <version>2.0.4</version>"); out.println(" <configuration>"); out.println(" <excludeResources>true</excludeResources>"); out.println(" </configuration>"); out.println(" </plugin>"); out.println(" </plugins>"); out.println(" <resources>"); out.println(" <resource>"); out.println(" <filtering>false</filtering>"); out.println(" <directory>../../target/classes</directory>"); out.println(" <includes>"); out.println(" <include>" + pkg.directoryPath + "/*</include>"); out.println(" </includes>"); out.println(" </resource>"); out.println(" </resources>"); out.println(" </build>"); out.println(" <dependencies>"); for (DependencyModel dep : pkg.dependencies) { out.println(" <dependency>"); out.println(" <groupId>" + dep.groupId + "</groupId>"); out.println(" <artifactId>" + dep.artifactId + "</artifactId>"); if (dep.version != null) { out.println(" <version>" + dep.version + "</version>"); } if (dep.scope != null) { out.println(" <scope>" + dep.scope + "</scope>"); } out.println(" </dependency>"); } out.println(" </dependencies>"); out.println("</project>"); out.close(); } @Override public String getOutputFilePath() { return "modules/" + pkg.artifactId + "/pom.xml"; } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/ModulePomFileGenerator.java
Java
asf20
3,375
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.model.PackageModel; import java.io.PrintWriter; import java.util.SortedSet; /** * @author Yaniv Inbar */ final class PomFileGenerator extends AbstractFileGenerator { private final SortedSet<PackageModel> pkgs; PomFileGenerator(SortedSet<PackageModel> pkgs) { this.pkgs = pkgs; } @Override public void generate(PrintWriter out) { out.println("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 " + "http://maven.apache.org/maven-v4_0_0.xsd\">"); out.println(" <modelVersion>4.0.0</modelVersion>"); out.println(" <parent>"); out.println(" <groupId>com.google.api.client</groupId>"); out.println(" <artifactId>google-api-client-parent</artifactId>"); out.println(" <version>" + PackageModel.VERSION_SNAPSHOT + "</version>"); out.println(" <relativePath>../../pom.xml</relativePath>"); out.println(" </parent>"); out.println(" <artifactId>google-api-client-modules-parent</artifactId>"); out.println(" <packaging>pom</packaging>"); out.println(" <description>A place to hold common settings for each module.</description>"); out.println(" <modules>"); for (PackageModel pkg : pkgs) { out.println(" <module>" + pkg.artifactId + "</module>"); } out.println(" </modules>"); out.println("</project>"); out.close(); } @Override public String getOutputFilePath() { return "modules/pom.xml"; } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/PomFileGenerator.java
Java
asf20
2,237
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.linewrap.LineWrapper; import java.io.PrintWriter; /** * Defines a single file generator, which manages a single generated file. * * @author Yaniv Inbar */ abstract class AbstractFileGenerator { /** Whether to generate this file. Default is to return {@code true}. */ boolean isGenerated() { return true; } /** Generates the content of the file into the given print writer. */ abstract void generate(PrintWriter out); /** * Returns the output file path relative to the root output directory. */ abstract String getOutputFilePath(); /** * Returns the line wrapper to use or {@code null} for none. Default is to return {@code null}. */ LineWrapper getLineWrapper() { return null; } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/AbstractFileGenerator.java
Java
asf20
1,402
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.generator; import com.google.api.client.generator.model.PackageModel; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; /** * @author Yaniv Inbar */ public class GeneratePom { public static void main(String[] args) throws IOException { File googleApiClientDirectory = Generation.getDirectory(args[0]); // package names SortedSet<PackageModel> pkgs = PackageModel.compute(googleApiClientDirectory); // compute file generators List<AbstractFileGenerator> fileGenerators = new ArrayList<AbstractFileGenerator>(); fileGenerators.add(new PomFileGenerator(pkgs)); fileGenerators.add(new DistXmlFileGenerator(pkgs)); for (PackageModel pkg : pkgs) { fileGenerators.add(new ModulePomFileGenerator(pkg)); } Generation.compute(fileGenerators, googleApiClientDirectory); } private GeneratePom() { } }
11durong-mytest1
google-api-client/generator/com/google/api/client/generator/GeneratePom.java
Java
asf20
1,549
<html> <title>Dependent libraries for the ${project.name} ${project.version}</title> <body> <h2>Dependent libraries for the ${project.name} ${project.version}</h2> <p>When building an application based on this client library, use these dependent library jars:</p> <ul> <li><a href="jackson-core-asl-1.5.3.jar">jackson-core-asl-1.5.3.jar</a>: needed for JSON, or formats based on JSON like JSON-C, JSON-RPC, or POCO. It can be downloaded from <a href="http://wiki.fasterxml.com/JacksonDownload">here</a>.</li> </ul> <p>When building an application for all Java environments <b>except</b> for Android (whose SDK already includes these), additionally use these dependent library jars:</p> <ul> <li><a href="java/kxml2-2.3.0.jar">kxml2-2.3.0.jar</a>: needed for XML, or formats based on XML like Atom. It can be downloaded from <a href="http://kxml.sourceforge.net/">here</a>.</li> <li><a href="java/commons-logging-1.1.1.jar">commons-logging-1.1.1.jar</a>, <a href="java/httpcore-4.0.1.jar">httpcore-4.0.1.jar</a>, and <a href="java/httpclient-4.0.1.jar">httpclient-4.0.1.jar</a>: needed only if you prefer to use the Apache HTTP library for the underlying HTTP transport (default is to use the built-in <code>java.net</code> package of the JDK). They can be downloaded from <a href="http://hc.apache.org/httpcomponents-client/">here</a>. <b>Warning:</b> Do not use the Apache HTTP library on App Engine because it won't work. The Apache HTTP library tries to open its own sockets which is not allowed on App Engine.</li> </ul> </body> </html>
11durong-mytest1
google-api-client/assemble/dependencies/readme.html
HTML
asf20
1,584
<html> <title>${project.name} ${project.version}</title> <body> <h2>${project.name} ${project.version}</h2> <p>High-level details about this library can be found at <a href="http://code.google.com/p/google-api-java-client">http://code.google.com/p/google-api-java-client</a>, including documentation, support, samples, and source code.</p> <p>This download contains the <a href="${project.artifactId}-${project.version}.jar">client library</a>, the <a href="${project.artifactId}-${project.version}-sources.jar">client library source</a>, the <a href="${project.artifactId}-${project.version}-javadoc.jar">JavaDoc</a>, the <a href="dependencies/readme.html">dependent library jars</a>, and the <a href="LICENSE">Apache 2 LICENSE</a>. It also includes an <a href="packages/readme.html">alternative packaging</a> of this client library where each Java package is in its own jar.</p> </body> </html>
11durong-mytest1
google-api-client/assemble/readme.html
HTML
asf20
910
<html> <title>Release Process</title> <body> <h2>Release Process</h2> <h3>First time set up</h3> <ul> <li>Make sure you have at least a Committer role</li> <li>Make sure you have permission to post to the <a href="http://google-api-java-client.blogspot.com/">Announcement Blog</a>.</li> <li>Check out the <code>google-api-java-client</code> project using <a href="http://google-api-java-client.googlecode.com/hg/instructions.html?r=1.2.3-alpha">these instructions</a>.</li> <li>Check out the <code>javadoc</code> project using <a href="http://javadoc.google-api-java-client.googlecode.com/hg/instructions.html">these instructions</a> into the same parent directory as the <code>google-api-java-client</code> project.</li> <li>Download <a href="http://sourceforge.net/projects/javadiff/">JDiff</a>.</li> <li>Set up for pushing to central Maven repository <ul> <li>Sign up for a Sonatype JIRA account at <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>. Click <i>Sign Up</i> in the Login box, fill out the simple form, and click <i>Sign Up</i>.</li> <li>Install a GPG client from <a href="http://www.gnupg.org/">http://www.gnupg.org/</a>, and then create a GPG key using <a href="http://www.sonatype.com/people/2010/01/how-to-generate-pgp-signatures-with-maven/">these instructions</a>, making sure to specify a passphrase to be used every time you release.</li> <li>Add these lines to your <code>~/.hgrc</code>: <pre><code>google-api-java-client.prefix = https://google-api-java-client.googlecode.com/hg/ google-api-java-client.username = <i>[username from <a href="https://code.google.com/hosting/settings">https://code.google.com/hosting/settings</a>]</i> google-api-java-client.password = <i>[password from <a href="https://code.google.com/hosting/settings">https://code.google.com/hosting/settings</a>]</i></code></pre></li> <li>Add these lines to your <code>~/.m2/settings.xml</code> (create this file if it does not already exist): <pre><code>&lt;settings&gt; &lt;servers&gt; &lt;server&gt; &lt;id&gt;google-snapshots&lt;/id&gt; &lt;username&gt;<i>[username for <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i>&lt;/username&gt; &lt;password&gt;<i>[password for <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i>&lt;/password&gt; &lt;/server&gt; &lt;server&gt; &lt;id&gt;google-releases&lt;/id&gt; &lt;username&gt;<i>[username for <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i>&lt;/username&gt; &lt;password&gt;<i>[password for <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i>&lt;/password&gt; &lt;/server&gt; &lt;server&gt; &lt;id&gt;sonatype-nexus-snapshots&lt;/id&gt; &lt;username&gt;<i>[username for <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i>&lt;/username&gt; &lt;password&gt;<i>[password for <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i>&lt;/password&gt; &lt;/server&gt; &lt;server&gt; &lt;id&gt;sonatype-nexus-staging&lt;/id&gt; &lt;username&gt;<i>[username for <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i>&lt;/username&gt; &lt;password&gt;<i>[password for <a href="https://issues.sonatype.org/">https://issues.sonatype.org</a>]</i>&lt;/password&gt; &lt;/server&gt; &lt;/servers&gt; &lt;/settings&gt;</code></pre></li> </ul> </li> </ul> <h3>Release version 1.2.3-alpha (bug fix release)</h3> <ul> <li>Prepare the project <ul> <li>Re-run <code>GeneratePom</code> in Eclipse <ul> <li>Select project <code>google-api-client</code></li> <li>Project &gt; Clean...</li> <li>OK</li> <li>Run <code>GeneratePom</code></li> <li>If any modules/*/pom.xml file is updated, make sure to also update the corresponding package.html file</li> </ul> </li> <li><code>hg commit</code> if you have any uncommitted changes</li> </ul> </li> <li>Push to central Maven repository (based on instructions from <a href="https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide">Sonatype OSS Maven Repository Usage Guide</a>): <ul> <li>Prepare:<pre><code>cd google-api-java-client mvn clean deploy mvn release:clean</code></pre></li> <li><code>mvn release:prepare -DautoVersionSubmodules=true</code> <ul> <li>Accept default for 'What is the release version for "Google API Client - Parent"?'</li> <li>Type <code>1.2.3-alpha</code> for 'What is SCM release tag or label for "Google API Client - Parent"?'</li> <li>Accept default for 'What is the new development version for "Google API Client - Parent"?'</li> </ul> </li> <li><code>mvn release:perform -Darguments=-Dgpg.passphrase=<i>[YOUR GPG PASSPHRASE]</i></code></li> <li>Release on oss.sonatype.org <ul> <li>Log in to <a href="https://oss.sonatype.org">https://oss.sonatype.org</a></li> <li>Click on "Staging Repositories"</li> <li>check box next to uploaded release</li> <li>click Close button; type <code>1.2.3-alpha</code> and click Close</li> <li>check box next to uploaded release</li> <li>click Release button; type <code>1.2.3-alpha</code> and click Release</li> </ul> </li> <li>Central Maven repository is synced hourly. Wait for the new version at: <a href="http://repo2.maven.org/maven2/com/google/api/client/google-api-client/">repo2.maven.org</a></li> </ul> </li> <li>Prepare the released library zip file and javadoc <ul> <li>change these constants from assemble/jdiff.xml for your environment: JDIFF_HOME, MAVEN_REPOSITORY_HOME, and PROJECT_ROOT_DIR</li> <li><pre><code>hg update -r 1.2.3-alpha mvn clean install cd google-api-client mvn source:jar javadoc:jar assembly:assembly cp -R target/apidocs ../../javadoc/1.2.3-alpha cd /tmp rm -rf google-api-java-client hg clone -r 1.1.1-alpha https://google-api-java-client.googlecode.com/hg/ google-api-java-client cd - ant -f assemble/jdiff.xml cd ../../javadoc hg add hg commit -m "1.2.3-alpha" hg push cd ../google-api-java-client </code></pre></li> </ul> </li> <li>Update to new version on <a href="http://code.google.com/p/google-api-java-client">http://code.google.com/p/google-api-java-client</a> <ul> <li>Upload to <a href="http://code.google.com/p/google-api-java-client/downloads/entry">http://code.google.com/p/google-api-java-client/downloads/entry</a> <ul> <li>Summary: Google API Client Library for Java, version 1.2.3-alpha</li> <li>File: <code>google-api-java-client/target/google-api-client-1.2.3-alpha-java.zip</code></li> <li>Labels: <code>Type-Archive</code>, <code>OpSys-All</code>, and <code>Featured</code></li> <li>click Submit file</li> </ul> </li> <li>Deprecate the library from any previous versions by removing any <code>Featured</code> label and adding the <code>Deprecated</code> label.</li> <li>Update the following pages changing any reference from the previous version to the new version <code>1.2.3-alpha</code>: <ul> <li><a href="http://code.google.com/p/google-api-java-client/admin">admin</a></li> <li><a href="http://code.google.com/p/google-api-java-client/w/edit/Setup">wiki/Setup</a></li> <li><a href="http://code.google.com/p/google-api-java-client/w/edit/SampleProgram">wiki/SampleProgram</a></li> </ul> </li> </ul> </li> <li><a href="http://www.blogger.com/post-create.g?blogID=4531100327392916335">New Post</a> on the <a href="http://google-api-java-client.blogspot.com/">announcement blog</a> about the new version, including links to: <ul> <li>Title: Version 1.2.3-alpha released</li> <li>Subject: <a href="http://code.google.com/p/google-api-java-client/issues/list?can=1&q=milestone=Version1.2.3%20type=Enhancement&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary">Features:</a> (bullet list) <a href="http://code.google.com/p/google-api-java-client/issues/list?can=1&q=milestone=Version1.2.3%20type=Defect&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary">Bugs Fixed</a> (bullet list)</li> </ul> </li> <li>Start development of next minor version <ul> <li><code>hg update</code></li> <li>For the following files, replace <code>1.2.3-alpha</code> with <code>1.2.4-alpha</code>: <ul> <li><code>google-api-client/assemble/jdiff.xml</code></li> <li><code>google-api-client/assemble/release.html</code> (though beforehand replace 1.2.4-alpha with next minor version)</li> <li><code>google-api-client/generator/com/google/api/client/generator/model/PackageModel.java</code></li> <li><code>google-api-client/src/com/google/api/client/http/HttpRequest.java</code></li> </ul> </li> <li>Re-run <code>GeneratePom</code> in Eclipse <ul> <li>Select project <code>google-api-client</code></li> <li>Project &gt; Clean...</li> <li>OK</li> <li>Run <code>GeneratePom</code></li> <li>If any modules/*/pom.xml file is updated, make sure to also update the corresponding package.html file</li> </ul> </li> <li><code>hg commit -m "start 1.2.4-alpha"</code></li> </ul> </li> </ul> </body> </html>
11durong-mytest1
google-api-client/assemble/release.html
HTML
asf20
9,580
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.appengine; import com.google.api.client.http.LowLevelHttpTransport; import com.google.appengine.api.urlfetch.FetchOptions; import java.io.IOException; import java.net.HttpURLConnection; /** * HTTP low-level transport for Google App Engine based on <a * href="http://code.google.com/appengine/docs/java/urlfetch/">URL Fetch</a>. * <p> * URL Fetch is only available on Google App Engine (not on any other Java environment), and is the * underlying HTTP transport used for App Engine. Their implementation of {@link HttpURLConnection} * is simply an abstraction layer on top of URL Fetch. By implementing a transport that directly * uses URL Fetch, we can optimize the behavior slightly, and can potentially take advantage of * features in URL Fetch that are not available in {@link HttpURLConnection}. Furthermore, there is * currently a serious bug in how HTTP headers are processed in the App Engine implementation of * {@link HttpURLConnection}, which we are able to avoid using this implementation. Therefore, this * is the recommended transport to use on App Engine. * * @since 1.2 * @author Yaniv Inbar */ public final class UrlFetchTransport extends LowLevelHttpTransport { /** Singleton instance of this transport. */ public static final UrlFetchTransport INSTANCE = new UrlFetchTransport(); /** * Sets the deadline in seconds or {@code null} for no deadline using * {@link FetchOptions#setDeadline(Double)}. By default it is 20 seconds. */ public Double deadline = 20.0; @Override public boolean supportsHead() { return true; } @Override public UrlFetchRequest buildDeleteRequest(String url) throws IOException { return new UrlFetchRequest(this, "DELETE", url); } @Override public UrlFetchRequest buildGetRequest(String url) throws IOException { return new UrlFetchRequest(this, "GET", url); } @Override public UrlFetchRequest buildHeadRequest(String url) throws IOException { return new UrlFetchRequest(this, "HEAD", url); } @Override public UrlFetchRequest buildPostRequest(String url) throws IOException { return new UrlFetchRequest(this, "POST", url); } @Override public UrlFetchRequest buildPutRequest(String url) throws IOException { return new UrlFetchRequest(this, "PUT", url); } }
11durong-mytest1
google-api-client/src/com/google/api/client/appengine/UrlFetchTransport.java
Java
asf20
2,920
<body> HTTP Transport library for Google API's based on <a href="http://code.google.com/appengine/docs/java/urlfetch/">URL Fetch in Google App Engine</a> . <p>This package depends on theses packages:</p> <ul> <li>{@link com.google.api.client.http}</li> <li>{@link com.google.appengine.api.urlfetch}</li> </ul> <p><b>Warning: this package is experimental, and its content may be changed in incompatible ways or possibly entirely removed in a future version of the library</b></p> @since 1.2 </body>
11durong-mytest1
google-api-client/src/com/google/api/client/appengine/package.html
HTML
asf20
505
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.appengine; import com.google.api.client.http.HttpContent; import com.google.api.client.http.LowLevelHttpRequest; import com.google.api.client.http.LowLevelHttpResponse; import com.google.appengine.api.urlfetch.FetchOptions; import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPMethod; import com.google.appengine.api.urlfetch.HTTPRequest; import com.google.appengine.api.urlfetch.HTTPResponse; import com.google.appengine.api.urlfetch.ResponseTooLargeException; import com.google.appengine.api.urlfetch.URLFetchService; import com.google.appengine.api.urlfetch.URLFetchServiceFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; /** * @author Yaniv Inbar */ final class UrlFetchRequest extends LowLevelHttpRequest { private HttpContent content; private final UrlFetchTransport transport; private final HTTPMethod method; private final HTTPRequest request; UrlFetchRequest(UrlFetchTransport transport, String requestMethod, String url) throws IOException { this.transport = transport; method = HTTPMethod.valueOf(requestMethod); FetchOptions options = FetchOptions.Builder.doNotFollowRedirects().disallowTruncate(); request = new HTTPRequest(new URL(url), method, options); } @Override public void addHeader(String name, String value) { request.addHeader(new HTTPHeader(name, value)); } @Override public LowLevelHttpResponse execute() throws IOException { // write content if (content != null) { addHeader("Content-Type", content.getType()); String contentEncoding = content.getEncoding(); if (contentEncoding != null) { addHeader("Content-Encoding", contentEncoding); } long contentLength = content.getLength(); if (contentLength >= 0) { addHeader("Content-Length", Long.toString(contentLength)); } ByteArrayOutputStream out = new ByteArrayOutputStream(); content.writeTo(out); request.setPayload(out.toByteArray()); } // connect double deadline = transport.deadline; if (deadline >= 0) { request.getFetchOptions().setDeadline(deadline); } URLFetchService service = URLFetchServiceFactory.getURLFetchService(); try { HTTPResponse response = service.fetch(request); return new UrlFetchResponse(response); } catch (ResponseTooLargeException e) { IOException ioException = new IOException(); ioException.initCause(e); throw ioException; } } @Override public void setContent(HttpContent content) { this.content = content; } }
11durong-mytest1
google-api-client/src/com/google/api/client/appengine/UrlFetchRequest.java
Java
asf20
3,256
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.appengine; import com.google.api.client.http.LowLevelHttpResponse; import com.google.appengine.api.urlfetch.HTTPHeader; import com.google.appengine.api.urlfetch.HTTPResponse; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; final class UrlFetchResponse extends LowLevelHttpResponse { private final ArrayList<String> headerNames = new ArrayList<String>(); private final ArrayList<String> headerValues = new ArrayList<String>(); private final HTTPResponse fetchResponse; private String contentEncoding; private String contentType; private long contentLength; UrlFetchResponse(HTTPResponse fetchResponse) { this.fetchResponse = fetchResponse; for (HTTPHeader header : fetchResponse.getHeaders()) { String name = header.getName(); String value = header.getValue(); // Note: URLFetch will merge any duplicate headers with the same key and join their values // using ", " as separator. However, ", " is also common inside values, such as in Expires or // Set-Cookie headers. if (name != null && value != null) { headerNames.add(name); headerValues.add(value); if ("content-type".equalsIgnoreCase(name)) { contentType = value; } else if ("content-encoding".equalsIgnoreCase(name)) { contentEncoding = value; } else if ("content-length".equalsIgnoreCase(name)) { try { contentLength = Long.parseLong(value); } catch (NumberFormatException e) { // ignore } } } } } @Override public int getStatusCode() { return fetchResponse.getResponseCode(); } @Override public InputStream getContent() { return new ByteArrayInputStream(fetchResponse.getContent()); } @Override public String getContentEncoding() { return contentEncoding; } @Override public long getContentLength() { return contentLength; } @Override public String getContentType() { return contentType; } @Override public String getReasonPhrase() { // unfortunately not available return null; } @Override public String getStatusLine() { // unfortunately not available return null; } @Override public int getHeaderCount() { return headerNames.size(); } @Override public String getHeaderName(int index) { return headerNames.get(index); } @Override public String getHeaderValue(int index) { return headerValues.get(index); } }
11durong-mytest1
google-api-client/src/com/google/api/client/appengine/UrlFetchResponse.java
Java
asf20
3,147
<body> XML. <p>This package depends on the {@link com.google.api.client.util}, {@link com.google.api.client.http}, and {@code org.xmlpull.v1} packages.</p> <p>This package depends on theses packages:</p> <ul> <li>{@link com.google.api.client.http}</li> <li>{@link com.google.api.client.util}</li> </ul> <p><b>Warning: this package is experimental, and its content may be changed in incompatible ways or possibly entirely removed in a future version of the library</b></p> @since 1.0 </body>
11durong-mytest1
google-api-client/src/com/google/api/client/xml/package.html
HTML
asf20
498
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml; import com.google.api.client.util.DataUtil; import com.google.api.client.util.DateTime; import com.google.api.client.util.FieldInfo; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; /** * XML namespace dictionary that maps namespace aliases to URI. * <p> * Sample usage: * * <pre>{@code static final XmlNamespaceDictionary NAMESPACE_DICTIONARY = new XmlNamespaceDictionary(); static { Map<String, String> map = NAMESPACE_DICTIONARY.namespaceAliasToUriMap; map.put("", "http://www.w3.org/2005/Atom"); map.put("activity", "http://activitystrea.ms/spec/1.0/"); map.put("georss", "http://www.georss.org/georss"); map.put("media", "http://search.yahoo.com/mrss/"); map.put("thr", "http://purl.org/syndication/thread/1.0"); } *}</pre> * * @since 1.0 * @author Yaniv Inbar */ public final class XmlNamespaceDictionary { /** * Map from XML namespace alias (or {@code ""} for the default namespace) to XML namespace URI. */ public final HashMap<String, String> namespaceAliasToUriMap = new HashMap<String, String>(); /** * Adds a known namespace of the given alias and URI. * * @param alias alias * @param uri namespace URI */ public void addNamespace(String alias, String uri) { if (alias == null || uri == null) { throw new NullPointerException(); } HashMap<String, String> namespaceAliasToUriMap = this.namespaceAliasToUriMap; String knownUri = namespaceAliasToUriMap.get(alias); if (!uri.equals(knownUri)) { if (knownUri != null) { throw new IllegalArgumentException( "expected namespace alias <" + alias + "> to be <" + knownUri + "> but encountered <" + uri + ">"); } namespaceAliasToUriMap.put(alias, uri); } } /** * Shows a debug string representation of an element data object of key/value pairs. * * @param element element data object ({@link GenericXml}, {@link Map}, or any object with public * fields) * @param elementName optional XML element local name prefixed by its namespace alias -- for * example {@code "atom:entry"} -- or {@code null} to make up something */ public String toStringOf(String elementName, Object element) { try { StringWriter writer = new StringWriter(); XmlSerializer serializer = Xml.createSerializer(); serializer.setOutput(writer); serialize(serializer, elementName, element, false); return writer.toString(); } catch (IOException e) { throw new IllegalArgumentException(e); } } /** * Shows a debug string representation of an element data object of key/value pairs. * * @param element element data object ({@link GenericXml}, {@link Map}, or any object with public * fields) * @param elementNamespaceUri XML namespace URI or {@code null} for no namespace * @param elementLocalName XML local name * @throws IOException I/O exception */ public void serialize( XmlSerializer serializer, String elementNamespaceUri, String elementLocalName, Object element) throws IOException { serialize(serializer, elementNamespaceUri, elementLocalName, element, true); } /** * Shows a debug string representation of an element data object of key/value pairs. * * @param element element data object ({@link GenericXml}, {@link Map}, or any object with public * fields) * @param elementName XML element local name prefixed by its namespace alias * @throws IOException I/O exception */ public void serialize(XmlSerializer serializer, String elementName, Object element) throws IOException { serialize(serializer, elementName, element, true); } private void serialize(XmlSerializer serializer, String elementNamespaceUri, String elementLocalName, Object element, boolean errorOnUnknown) throws IOException { startDoc(serializer, element, errorOnUnknown, elementNamespaceUri).serialize( serializer, elementNamespaceUri, elementLocalName); serializer.endDocument(); } private void serialize( XmlSerializer serializer, String elementName, Object element, boolean errorOnUnknown) throws IOException { startDoc(serializer, element, errorOnUnknown, null).serialize(serializer, elementName); serializer.endDocument(); } private ElementSerializer startDoc( XmlSerializer serializer, Object element, boolean errorOnUnknown, String extraNamespace) throws IOException { serializer.startDocument(null, null); SortedSet<String> aliases = new TreeSet<String>(); computeAliases(element, aliases); HashMap<String, String> namespaceAliasToUriMap = this.namespaceAliasToUriMap; boolean foundExtra = extraNamespace == null; for (String alias : aliases) { String uri = namespaceAliasToUriMap.get(alias); serializer.setPrefix(alias, uri); if (!foundExtra && uri.equals(extraNamespace)) { foundExtra = true; } } if (!foundExtra) { for (Map.Entry<String, String> entry : namespaceAliasToUriMap.entrySet()) { if (extraNamespace.equals(entry.getValue())) { serializer.setPrefix(entry.getKey(), extraNamespace); break; } } } return new ElementSerializer(element, errorOnUnknown); } private void computeAliases(Object element, SortedSet<String> aliases) { for (Map.Entry<String, Object> entry : DataUtil.mapOf(element).entrySet()) { Object value = entry.getValue(); if (value != null) { String name = entry.getKey(); if (!"text()".equals(name)) { int colon = name.indexOf(':'); boolean isAttribute = name.charAt(0) == '@'; if (colon != -1 || !isAttribute) { String alias = colon == -1 ? "" : name.substring(name.charAt(0) == '@' ? 1 : 0, colon); aliases.add(alias); } if (!isAttribute && !FieldInfo.isPrimitive(value)) { if (value instanceof Collection<?>) { for (Object subValue : (Collection<?>) value) { computeAliases(subValue, aliases); } } else { computeAliases(value, aliases); } } } } } } class ElementSerializer { private final boolean errorOnUnknown; Object textValue = null; final List<String> attributeNames = new ArrayList<String>(); final List<Object> attributeValues = new ArrayList<Object>(); final List<String> subElementNames = new ArrayList<String>(); final List<Object> subElementValues = new ArrayList<Object>(); ElementSerializer(Object elementValue, boolean errorOnUnknown) { this.errorOnUnknown = errorOnUnknown; Class<?> valueClass = elementValue.getClass(); if (FieldInfo.isPrimitive(valueClass)) { textValue = elementValue; } else { for (Map.Entry<String, Object> entry : DataUtil.mapOf(elementValue).entrySet()) { Object fieldValue = entry.getValue(); if (fieldValue != null) { String fieldName = entry.getKey(); if ("text()".equals(fieldName)) { textValue = fieldValue; } else if (fieldName.charAt(0) == '@') { attributeNames.add(fieldName.substring(1)); attributeValues.add(fieldValue); } else { subElementNames.add(fieldName); subElementValues.add(fieldValue); } } } } } String getNamespaceUriForAlias(String alias) { String result = namespaceAliasToUriMap.get(alias); if (result == null) { if (errorOnUnknown) { throw new IllegalArgumentException( "unrecognized alias: " + (alias.length() == 0 ? "(default)" : alias)); } return "http://unknown/" + alias; } return result; } void serialize(XmlSerializer serializer, String elementName) throws IOException { String elementLocalName = null; String elementNamespaceUri = null; if (elementName != null) { int colon = elementName.indexOf(':'); elementLocalName = elementName.substring(colon + 1); String alias = colon == -1 ? "" : elementName.substring(0, colon); elementNamespaceUri = getNamespaceUriForAlias(alias); if (elementNamespaceUri == null) { elementNamespaceUri = "http://unknown/" + alias; } } serialize(serializer, elementNamespaceUri, elementLocalName); } void serialize(XmlSerializer serializer, String elementNamespaceUri, String elementLocalName) throws IOException { boolean errorOnUnknown = this.errorOnUnknown; if (elementLocalName == null) { if (errorOnUnknown) { throw new IllegalArgumentException("XML name not specified"); } elementLocalName = "unknownName"; } serializer.startTag(elementNamespaceUri, elementLocalName); // attributes List<String> attributeNames = this.attributeNames; List<Object> attributeValues = this.attributeValues; int num = attributeNames.size(); for (int i = 0; i < num; i++) { String attributeName = attributeNames.get(i); int colon = attributeName.indexOf(':'); String attributeLocalName = attributeName.substring(colon + 1); String attributeNamespaceUri = colon == -1 ? null : getNamespaceUriForAlias(attributeName.substring(0, colon)); serializer.attribute( attributeNamespaceUri, attributeLocalName, toSerializedValue(attributeValues.get(i))); } // text Object textValue = this.textValue; if (textValue != null) { serializer.text(toSerializedValue(textValue)); } // elements List<String> subElementNames = this.subElementNames; List<Object> subElementValues = this.subElementValues; num = subElementNames.size(); for (int i = 0; i < num; i++) { Object subElementValue = subElementValues.get(i); String subElementName = subElementNames.get(i); if (subElementValue instanceof Collection<?>) { for (Object subElement : (Collection<?>) subElementValue) { new ElementSerializer(subElement, errorOnUnknown).serialize(serializer, subElementName); } } else { new ElementSerializer(subElementValue, errorOnUnknown).serialize( serializer, subElementName); } } serializer.endTag(elementNamespaceUri, elementLocalName); } } static String toSerializedValue(Object value) { if (value instanceof Float) { Float f = (Float) value; if (f.floatValue() == Float.POSITIVE_INFINITY) { return "INF"; } if (f.floatValue() == Float.NEGATIVE_INFINITY) { return "-INF"; } } if (value instanceof Double) { Double d = (Double) value; if (d.doubleValue() == Double.POSITIVE_INFINITY) { return "INF"; } if (d.doubleValue() == Double.NEGATIVE_INFINITY) { return "-INF"; } } if (value instanceof String || value instanceof Number || value instanceof Boolean) { return value.toString(); } if (value instanceof DateTime) { return ((DateTime) value).toStringRfc3339(); } throw new IllegalArgumentException("unrecognized value type: " + value.getClass()); } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/XmlNamespaceDictionary.java
Java
asf20
12,289
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; /** * Factory for creating new XML pull parsers and XML serializers. * * @since 1.0 * @author Yaniv Inbar */ public interface XmlParserFactory { /** * Creates a new XML pull parser. * * @throws XmlPullParserException if parser could not be created */ XmlPullParser createParser() throws XmlPullParserException; /** * Creates a new XML serializer. * * @throws XmlPullParserException if serializer could not be created */ XmlSerializer createSerializer() throws XmlPullParserException; }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/XmlParserFactory.java
Java
asf20
1,272
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; /** * Serializes XML HTTP content based on the data key/value mapping object for an item. * <p> * Sample usage: * * <pre> * <code> * static void setContent(HttpRequest request, * XmlNamespaceDictionary namespaceDictionary, String elementName, * Object data) { * XmlHttpContent content = new XmlHttpContent(); * content.namespaceDictionary = namespaceDictionary; * content.elementName = elementName; * content.data = data; * request.content = content; * } * </code> * </pre> * * @since 1.0 * @author Yaniv Inbar */ public class XmlHttpContent extends AbstractXmlHttpContent { /** * XML element local name, optionally prefixed by its namespace alias, for example {@code * "atom:entry"}. */ public String elementName; /** Key/value pair data. */ public Object data; @Override public final void writeTo(XmlSerializer serializer) throws IOException { namespaceDictionary.serialize(serializer, elementName, data); } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/XmlHttpContent.java
Java
asf20
1,674
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml; import com.google.api.client.http.HttpContent; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.io.OutputStream; /** * Abstract serializer for XML HTTP content based on the data key/value mapping object for an item. * * @since 1.0 * @author Yaniv Inbar */ public abstract class AbstractXmlHttpContent implements HttpContent { /** * Content type. Default value is {@link XmlHttpParser#CONTENT_TYPE}, though subclasses may define * a different default value. */ public String contentType = XmlHttpParser.CONTENT_TYPE; /** XML namespace dictionary. */ public XmlNamespaceDictionary namespaceDictionary; /** Default implementation returns {@code null}, but subclasses may override. */ public String getEncoding() { return null; } /** Default implementation returns {@code -1}, but subclasses may override. */ public long getLength() { return -1; } public final String getType() { return contentType; } public final void writeTo(OutputStream out) throws IOException { XmlSerializer serializer = Xml.createSerializer(); serializer.setOutput(out, "UTF-8"); writeTo(serializer); } protected abstract void writeTo(XmlSerializer serializer) throws IOException; }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/AbstractXmlHttpContent.java
Java
asf20
1,885
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml; import com.google.api.client.http.HttpParser; import com.google.api.client.http.HttpResponse; import com.google.api.client.util.ClassInfo; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * XML HTTP parser into an data class of key/value pairs. * <p> * Sample usage: * * <pre> * <code> * static void setParser(HttpTransport transport) { * XmlHttpParser parser = new XmlHttpParser(); * parser.namespaceDictionary = NAMESPACE_DICTIONARY; * transport.addParser(parser); * } * </code> * </pre> * * @since 1.0 * @author Yaniv Inbar */ public class XmlHttpParser implements HttpParser { /** {@code "application/xml"} content type. */ public static final String CONTENT_TYPE = "application/xml"; /** Content type. Default value is {@link #CONTENT_TYPE}. */ public String contentType = CONTENT_TYPE; /** XML namespace dictionary. */ public XmlNamespaceDictionary namespaceDictionary; public final String getContentType() { return contentType; } /** * Default implementation parses the content of the response into the data class of key/value * pairs, but subclasses may override. */ public <T> T parse(HttpResponse response, Class<T> dataClass) throws IOException { InputStream content = response.getContent(); try { T result = ClassInfo.newInstance(dataClass); XmlPullParser parser = Xml.createParser(); parser.setInput(content, null); Xml.parseElement(parser, result, namespaceDictionary, null); return result; } catch (XmlPullParserException e) { IOException exception = new IOException(); exception.initCause(e); throw exception; } finally { content.close(); } } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/XmlHttpParser.java
Java
asf20
2,421
package com.google.api.client.xml; import com.google.api.client.util.ClassInfo; import com.google.api.client.util.FieldInfo; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Map; /** * XML utilities. * * @since 1.0 * @author Yaniv Inbar */ public class Xml { /** XML Parser factory. */ public static XmlParserFactory parserFactory; /** Returns the parser factory. */ private static XmlParserFactory getParserFactory() throws XmlPullParserException { XmlParserFactory parserFactory = Xml.parserFactory; if (parserFactory == null) { parserFactory = Xml.parserFactory = DefaultXmlParserFactory.getInstance(); } return parserFactory; } /** * Returns a new XML serializer. * * @throws IllegalArgumentException if encountered an {@link XmlPullParserException} */ public static XmlSerializer createSerializer() { try { return getParserFactory().createSerializer(); } catch (XmlPullParserException e) { throw new IllegalArgumentException(e); } } /** Returns a new XML pull parser. */ public static XmlPullParser createParser() throws XmlPullParserException { XmlPullParser result = getParserFactory().createParser(); if (!result.getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES)) { throw new IllegalStateException("XML pull parser must have " + "namespace-aware feature"); } // TODO: make the XML pull parser secure return result; } /** * Shows a debug string representation of an element data object of key/value pairs. * <p> * It will make up something for the element name and XML namespaces. If those are known, it is * better to use {@link XmlNamespaceDictionary#toStringOf(String, Object)}. * * @param element element data object of key/value pairs ({@link GenericXml}, {@link Map}, or any * object with public fields) */ public static String toStringOf(Object element) { return new XmlNamespaceDictionary().toStringOf(null, element); } private static void parseValue(String stringValue, Field field, Object destination, GenericXml genericXml, Map<String, Object> destinationMap, String name) { if (field == null) { if (genericXml != null) { genericXml.set(name, parseValue(stringValue, null)); } else if (destinationMap != null) { destinationMap.put(name, parseValue(stringValue, null)); } } else { Class<?> fieldClass = field.getType(); if (Modifier.isFinal(field.getModifiers()) && !FieldInfo.isPrimitive(fieldClass)) { throw new IllegalArgumentException("final sub-element fields are not supported"); } Object fieldValue = parseValue(stringValue, fieldClass); FieldInfo.setFieldValue(field, destination, fieldValue); } } /** * Customizes the behavior of XML parsing. Subclasses may override any methods they need to * customize behavior. */ public static class CustomizeParser { /** * Returns whether to stop parsing when reaching the start tag of an XML element before it has * been processed. Only called if the element is actually being processed. By default, returns * {@code false}, but subclasses may override. * * @param namespace XML element's namespace URI * @param localName XML element's local name */ public boolean stopBeforeStartTag(String namespace, String localName) { return false; } /** * Returns whether to stop parsing when reaching the end tag of an XML element after it has been * processed. Only called if the element is actually being processed. By default, returns {@code * false}, but subclasses may override. * * @param namespace XML element's namespace URI * @param localName XML element's local name */ public boolean stopAfterEndTag(String namespace, String localName) { return false; } } /** * Parses an XML elment using the given XML pull parser into the given destination object. * <p> * Requires the the current event be {@link XmlPullParser#START_TAG} (skipping any initial * {@link XmlPullParser#START_DOCUMENT}) of the element being parsed. At normal parsing * completion, the current event will either be {@link XmlPullParser#END_TAG} of the element being * parsed, or the {@link XmlPullParser#START_TAG} of the requested {@code atom:entry}. * * @param parser XML pull parser * @param destination optional destination object to parser into or {@code null} to ignore XML * content * @param namespaceDictionary XML namespace dictionary to store unknown namespaces * @param customizeParser optional parser customizer or {@code null} for none */ public static void parseElement(XmlPullParser parser, Object destination, XmlNamespaceDictionary namespaceDictionary, CustomizeParser customizeParser) throws IOException, XmlPullParserException { parseElementInternal(parser, destination, namespaceDictionary, customizeParser); } /** * Returns whether the customize parser has requested to stop or reached end of document. * Otherwise, identical to * {@link #parseElement(XmlPullParser, Object, XmlNamespaceDictionary, CustomizeParser)} . */ private static boolean parseElementInternal(XmlPullParser parser, Object destination, XmlNamespaceDictionary namespaceDictionary, CustomizeParser customizeParser) throws IOException, XmlPullParserException { Class<?> destinationClass = destination == null ? null : destination.getClass(); GenericXml genericXml = destination instanceof GenericXml ? (GenericXml) destination : null; boolean isMap = genericXml == null && destination instanceof Map<?, ?>; @SuppressWarnings("unchecked") Map<String, Object> destinationMap = isMap ? (Map<String, Object>) destination : null; ClassInfo classInfo = isMap || destination == null ? null : ClassInfo.of(destinationClass); int eventType = parser.getEventType(); if (parser.getEventType() == XmlPullParser.START_DOCUMENT) { eventType = parser.next(); } if (eventType != XmlPullParser.START_TAG) { throw new IllegalArgumentException( "expected start of XML element, but got something else (event type " + eventType + ")"); } // generic XML String prefix = parser.getPrefix(); String alias = prefix == null ? "" : prefix; namespaceDictionary.addNamespace(alias, parser.getNamespace()); // TODO: can instead just look at the xmlns attributes? if (genericXml != null) { genericXml.namespaceDictionary = namespaceDictionary; String name = parser.getName(); genericXml.name = prefix == null ? name : prefix + ":" + name; } // attributes if (destination != null) { int attributeCount = parser.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { String attributeName = parser.getAttributeName(i); String attributePrefix = parser.getAttributePrefix(i); String attributeNamespace = parser.getAttributeNamespace(i); if (attributePrefix != null) { namespaceDictionary.addNamespace(attributePrefix, attributeNamespace); } String fieldName = getFieldName(true, attributePrefix, attributeNamespace, attributeName); Field field = isMap ? null : classInfo.getField(fieldName); parseValue(parser.getAttributeValue(i), field, destination, genericXml, destinationMap, fieldName); } } Field field; while (true) { int event = parser.next(); switch (event) { case XmlPullParser.END_DOCUMENT: return true; case XmlPullParser.END_TAG: return customizeParser != null && customizeParser.stopAfterEndTag(parser.getNamespace(), parser.getName()); case XmlPullParser.TEXT: // parse text content if (destination != null) { String textFieldName = "text()"; field = isMap ? null : classInfo.getField(textFieldName); parseValue(parser.getText(), field, destination, genericXml, destinationMap, textFieldName); } break; case XmlPullParser.START_TAG: if (customizeParser != null && customizeParser.stopBeforeStartTag(parser.getNamespace(), parser.getName())) { return true; } if (destination == null) { int level = 1; while (level != 0) { switch (parser.next()) { case XmlPullParser.END_DOCUMENT: return true; case XmlPullParser.START_TAG: level++; break; case XmlPullParser.END_TAG: level--; break; } } continue; } // element String fieldName = getFieldName(false, parser.getPrefix(), parser.getNamespace(), parser.getName()); field = isMap ? null : classInfo.getField(fieldName); Class<?> fieldClass = field == null ? null : field.getType(); boolean isStopped = false; if (field == null && !isMap && genericXml == null || field != null && FieldInfo.isPrimitive(fieldClass)) { int level = 1; while (level != 0) { switch (parser.next()) { case XmlPullParser.END_DOCUMENT: return true; case XmlPullParser.START_TAG: level++; break; case XmlPullParser.END_TAG: level--; break; case XmlPullParser.TEXT: if (level == 1) { parseValue(parser.getText(), field, destination, genericXml, destinationMap, fieldName); } break; } } } else if (field == null || Map.class.isAssignableFrom(fieldClass)) { // TODO: handle sub-field type Map<String, Object> mapValue = ClassInfo.newMapInstance(fieldClass); isStopped = parseElementInternal(parser, mapValue, namespaceDictionary, customizeParser); if (isMap) { @SuppressWarnings("unchecked") Collection<Object> list = (Collection<Object>) destinationMap.get(fieldName); if (list == null) { list = new ArrayList<Object>(1); destinationMap.put(fieldName, list); } list.add(mapValue); } else if (field != null) { FieldInfo.setFieldValue(field, destination, mapValue); } else { GenericXml atom = (GenericXml) destination; @SuppressWarnings("unchecked") Collection<Object> list = (Collection<Object>) atom.get(fieldName); if (list == null) { list = new ArrayList<Object>(1); atom.set(fieldName, list); } list.add(mapValue); } } else if (Collection.class.isAssignableFrom(fieldClass)) { @SuppressWarnings("unchecked") Collection<Object> collectionValue = (Collection<Object>) FieldInfo.getFieldValue(field, destination); if (collectionValue == null) { collectionValue = ClassInfo.newCollectionInstance(fieldClass); FieldInfo.setFieldValue(field, destination, collectionValue); } Object elementValue = null; // TODO: what about Collection<Object> or Collection<?> or // Collection<? extends X>? Class<?> subFieldClass = ClassInfo.getCollectionParameter(field); if (subFieldClass == null || FieldInfo.isPrimitive(subFieldClass)) { int level = 1; while (level != 0) { switch (parser.next()) { case XmlPullParser.END_DOCUMENT: return true; case XmlPullParser.START_TAG: level++; break; case XmlPullParser.END_TAG: level--; break; case XmlPullParser.TEXT: if (level == 1 && subFieldClass != null) { elementValue = parseValue(parser.getText(), subFieldClass); } break; } } } else { elementValue = ClassInfo.newInstance(subFieldClass); isStopped = parseElementInternal(parser, elementValue, namespaceDictionary, customizeParser); } collectionValue.add(elementValue); } else { Object value = ClassInfo.newInstance(fieldClass); isStopped = parseElementInternal(parser, value, namespaceDictionary, customizeParser); FieldInfo.setFieldValue(field, destination, value); } if (isStopped) { return true; } break; } } } private static String getFieldName( boolean isAttribute, String alias, String namespace, String name) { alias = alias == null ? "" : alias; StringBuilder buf = new StringBuilder(2 + alias.length() + name.length()); if (isAttribute) { buf.append('@'); } if (alias != "") { buf.append(alias).append(':'); } return buf.append(name).toString(); } private static Object parseValue(String stringValue, Class<?> fieldClass) { if (fieldClass == Double.class || fieldClass == double.class) { if (stringValue.equals("INF")) { return new Double(Double.POSITIVE_INFINITY); } if (stringValue.equals("-INF")) { return new Double(Double.NEGATIVE_INFINITY); } } if (fieldClass == Float.class || fieldClass == float.class) { if (stringValue.equals("INF")) { return Float.POSITIVE_INFINITY; } if (stringValue.equals("-INF")) { return Float.NEGATIVE_INFINITY; } } return FieldInfo.parsePrimitiveValue(fieldClass, stringValue); } private Xml() { } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/Xml.java
Java
asf20
14,777
<body> Atom XML. <p>This package depends on theses packages:</p> <ul> <li>{@link com.google.api.client.http}</li> <li>{@link com.google.api.client.util}</li> <li>{@link com.google.api.client.xml}</li> <li>{@link org.xmlpull.v1}</li> </ul> <p><b>Warning: this package is experimental, and its content may be changed in incompatible ways or possibly entirely removed in a future version of the library</b></p> @since 1.0 </body>
11durong-mytest1
google-api-client/src/com/google/api/client/xml/atom/package.html
HTML
asf20
437
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml.atom; import com.google.api.client.util.ClassInfo; import com.google.api.client.xml.Xml; import com.google.api.client.xml.XmlNamespaceDictionary; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * Abstract base class for an Atom feed parser when the feed type is known in advance. * * @since 1.0 * @author Yaniv Inbar */ public abstract class AbstractAtomFeedParser<T> { private boolean feedParsed; public XmlPullParser parser; public InputStream inputStream; public Class<T> feedClass; public XmlNamespaceDictionary namespaceDictionary; /** * Parse the feed and return a new parsed instance of the feed type. This method can be skipped if * all you want are the items. * * @throws XmlPullParserException */ public T parseFeed() throws IOException, XmlPullParserException { boolean close = true; try { this.feedParsed = true; T result = ClassInfo.newInstance(this.feedClass); Xml.parseElement( this.parser, result, this.namespaceDictionary, Atom.StopAtAtomEntry.INSTANCE); close = false; return result; } finally { if (close) { close(); } } } /** * Parse the next item in the feed and return a new parsed instanceof of the item type. If there * is no item to parse, it will return {@code null} and automatically close the parser (in which * case there is no need to call {@link #close()}. * * @throws XmlPullParserException */ public Object parseNextEntry() throws IOException, XmlPullParserException { XmlPullParser parser = this.parser; if (!this.feedParsed) { this.feedParsed = true; Xml.parseElement(parser, null, this.namespaceDictionary, Atom.StopAtAtomEntry.INSTANCE); } boolean close = true; try { if (parser.getEventType() == XmlPullParser.START_TAG) { Object result = parseEntryInternal(); parser.next(); close = false; return result; } } finally { if (close) { close(); } } return null; } /** Closes the underlying parser. */ public void close() throws IOException { this.inputStream.close(); } protected abstract Object parseEntryInternal() throws IOException, XmlPullParserException; }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/atom/AbstractAtomFeedParser.java
Java
asf20
2,982
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml.atom; import com.google.api.client.xml.AbstractXmlHttpContent; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; /** * Serializes Atom XML HTTP content based on the data key/value mapping object for an Atom feed. * <p> * Default value for {@link #contentType} is {@link Atom#CONTENT_TYPE}. * <p> * Sample usage: * * <pre> * <code> * static void setContent(HttpRequest request, * XmlNamespaceDictionary namespaceDictionary, Object feed) { * AtomFeedContent content = new AtomFeedContent(); * content.namespaceDictionary = namespaceDictionary; * content.feed = feed; * request.content = content; * } * </code> * </pre> * * @since 1.1 * @author Yaniv Inbar */ public class AtomFeedContent extends AbstractXmlHttpContent { /** Key/value pair data for the Atom feed. */ public Object feed; public AtomFeedContent() { contentType = Atom.CONTENT_TYPE; } @Override public final void writeTo(XmlSerializer serializer) throws IOException { namespaceDictionary.serialize(serializer, Atom.ATOM_NAMESPACE, "feed", feed); } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/atom/AtomFeedContent.java
Java
asf20
1,713
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml.atom; import com.google.api.client.http.HttpResponse; import com.google.api.client.util.ClassInfo; import com.google.api.client.xml.Xml; import com.google.api.client.xml.XmlNamespaceDictionary; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * Atom feed parser when the item class is known in advance. * * @since 1.0 * @author Yaniv Inbar */ public final class AtomFeedParser<T, I> extends AbstractAtomFeedParser<T> { public Class<I> entryClass; @SuppressWarnings("unchecked") @Override public I parseNextEntry() throws IOException, XmlPullParserException { return (I) super.parseNextEntry(); } @Override protected Object parseEntryInternal() throws IOException, XmlPullParserException { I result = ClassInfo.newInstance(this.entryClass); Xml.parseElement(parser, result, namespaceDictionary, null); return result; } public static <T, I> AtomFeedParser<T, I> create(HttpResponse response, XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<I> entryClass) throws XmlPullParserException, IOException { InputStream content = response.getContent(); try { Atom.checkContentType(response.contentType); XmlPullParser parser = Xml.createParser(); parser.setInput(content, null); AtomFeedParser<T, I> result = new AtomFeedParser<T, I>(); result.parser = parser; result.inputStream = content; result.feedClass = feedClass; result.entryClass = entryClass; result.namespaceDictionary = namespaceDictionary; content = null; return result; } finally { if (content != null) { content.close(); } } } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/atom/AtomFeedParser.java
Java
asf20
2,387
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml.atom; import com.google.api.client.xml.XmlHttpParser; /** * Atom XML HTTP parser into an data class of key/value pairs. * <p> * It overrides the {@link #contentType} to {@link Atom#CONTENT_TYPE}. * <p> * Sample usage: * * <pre> * <code> * static void setParser(HttpTransport transport) { * AtomParser parser = new AtomParser(); * parser.namespaceDictionary = NAMESPACE_DICTIONARY; * transport.addParser(parser); * } * </code> * </pre> * * @since 1.0 * @author Yaniv Inbar */ public final class AtomParser extends XmlHttpParser { public AtomParser() { contentType = Atom.CONTENT_TYPE; } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/atom/AtomParser.java
Java
asf20
1,248
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml.atom; import com.google.api.client.xml.Xml; /** * @since 1.0 * @author Yaniv Inbar */ public final class Atom { public static final String ATOM_NAMESPACE = "http://www.w3.org/2005/Atom"; public static final String CONTENT_TYPE = "application/atom+xml"; static final class StopAtAtomEntry extends Xml.CustomizeParser { static final StopAtAtomEntry INSTANCE = new StopAtAtomEntry(); @Override public boolean stopBeforeStartTag(String namespace, String localName) { return "entry".equals(localName) && ATOM_NAMESPACE.equals(namespace); } } private Atom() { } public static void checkContentType(String contentType) { if (contentType == null || !contentType.startsWith(CONTENT_TYPE)) { throw new IllegalArgumentException( "Wrong content type: expected <" + CONTENT_TYPE + "> but got <" + contentType + ">"); } } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/atom/Atom.java
Java
asf20
1,507
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.xml.atom; import com.google.api.client.xml.AbstractXmlHttpContent; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; /** * Serializes Atom XML HTTP content based on the data key/value mapping object for an Atom entry. * <p> * Default value for {@link #contentType} is {@link Atom#CONTENT_TYPE}. * <p> * Sample usage: * * <pre> * <code> * static void setContent(HttpRequest request, * XmlNamespaceDictionary namespaceDictionary, Object entry) { * AtomContent content = new AtomContent(); * content.namespaceDictionary = namespaceDictionary; * content.entry = entry; * request.content = content; * } * </code> * </pre> * * @since 1.0 * @author Yaniv Inbar */ public class AtomContent extends AbstractXmlHttpContent { /** Key/value pair data for the Atom entry. */ public Object entry; public AtomContent() { contentType = Atom.CONTENT_TYPE; } @Override public final void writeTo(XmlSerializer serializer) throws IOException { namespaceDictionary.serialize(serializer, Atom.ATOM_NAMESPACE, "entry", entry); } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/atom/AtomContent.java
Java
asf20
1,705
package com.google.api.client.xml; import com.google.api.client.util.GenericData; import com.google.api.client.util.Key; /** * Generic XML data that stores all unknown key name/value pairs. * <p> * Each data key name maps into the name of the XPath expression value for the XML element, * attribute, or text content (using {@code "text()"}). Subclasses can declare fields for known XML * content using the {@link Key} annotation. Each field can be of any visibility (private, package * private, protected, or public) and must not be static. {@code null} unknown data key names are * not allowed, but {@code null} data values are allowed. * * @since 1.0 * @author Yaniv Inbar */ public class GenericXml extends GenericData implements Cloneable { /** * Optional XML element local name prefixed by its namespace alias -- for example {@code * "atom:entry"} -- or {@code null} if not set. */ public String name; /** Optional namespace dictionary or {@code null} if not set. */ public XmlNamespaceDictionary namespaceDictionary; @Override public GenericXml clone() { return (GenericXml) super.clone(); } @Override public String toString() { XmlNamespaceDictionary namespaceDictionary = this.namespaceDictionary; if (namespaceDictionary == null) { namespaceDictionary = new XmlNamespaceDictionary(); } return namespaceDictionary.toStringOf(name, this); } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/GenericXml.java
Java
asf20
1,422
package com.google.api.client.xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; /** * Default XML parser factory that uses the default specified in {@link XmlPullParserFactory}. * * @since 1.0 * @author Yaniv Inbar */ public final class DefaultXmlParserFactory implements XmlParserFactory { /** * Only instance or {@code null} if {@link #getInstance()} has not been called. */ private static DefaultXmlParserFactory INSTANCE; /** Returns the only instance of the default XML parser factory. */ public static DefaultXmlParserFactory getInstance() throws XmlPullParserException { if (INSTANCE == null) { INSTANCE = new DefaultXmlParserFactory(); } return INSTANCE; } /** XML pull parser factory. */ private final XmlPullParserFactory factory; private DefaultXmlParserFactory() throws XmlPullParserException { factory = XmlPullParserFactory.newInstance( System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null); factory.setNamespaceAware(true); } public XmlPullParser createParser() throws XmlPullParserException { return factory.newPullParser(); } public XmlSerializer createSerializer() throws XmlPullParserException { return factory.newSerializer(); } }
11durong-mytest1
google-api-client/src/com/google/api/client/xml/DefaultXmlParserFactory.java
Java
asf20
1,365
<body> Character escaping utilities. <p><b>Warning: this package is experimental, and its content may be changed in incompatible ways or possibly entirely removed in a future version of the library</b></p> @since 1.0 </body>
11durong-mytest1
google-api-client/src/com/google/api/client/escape/package.html
HTML
asf20
226
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.escape; /** * An object that converts literal text into a format safe for inclusion in a particular context * (such as an XML document). Typically (but not always), the inverse process of "unescaping" the * text is performed automatically by the relevant parser. * * <p> * For example, an XML escaper would convert the literal string {@code "Foo<Bar>"} into {@code * "Foo&lt;Bar&gt;"} to prevent {@code "<Bar>"} from being confused with an XML tag. When the * resulting XML document is parsed, the parser API will return this text as the original literal * string {@code "Foo<Bar>"}. * * <p> * An {@code Escaper} instance is required to be stateless, and safe when used concurrently by * multiple threads. * * <p> * Several popular escapers are defined as constants in the class {@link CharEscapers}. * * @since 1.0 */ public abstract class Escaper { /** * Returns the escaped form of a given literal string. * * <p> * Note that this method may treat input characters differently depending on the specific escaper * implementation. * <ul> * <li>{@link UnicodeEscaper} handles <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> * correctly, including surrogate character pairs. If the input is badly formed the escaper should * throw {@link IllegalArgumentException}. * </ul> * * @param string the literal string to be escaped * @return the escaped form of {@code string} * @throws NullPointerException if {@code string} is null * @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be * escaped for any other reason */ public abstract String escape(String string); }
11durong-mytest1
google-api-client/src/com/google/api/client/escape/Escaper.java
Java
asf20
2,315