code
stringlengths
1
2.06M
language
stringclasses
1 value
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "scriptable.h" static NPObject* AllocateScriptable(NPP npp, NPClass *aClass) { return new Scriptable(); } static void DeallocateScriptable(NPObject *obj) { if (!obj) { return; } Scriptable *s = (Scriptable *)obj; delete s; } static void InvalidateScriptable(NPObject *obj) { if (!obj) { return; } ((Scriptable *)obj)->Invalidate(); } NPClass ScriptableNPClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateScriptable, /* deallocate */ DeallocateScriptable, /* invalidate */ InvalidateScriptable, /* hasMethod */ Scriptable::_HasMethod, /* invoke */ Scriptable::_Invoke, /* invokeDefault */ NULL, /* hasProperty */ Scriptable::_HasProperty, /* getProperty */ Scriptable::_GetProperty, /* setProperty */ Scriptable::_SetProperty, /* removeProperty */ NULL, /* enumerate */ NULL, /* construct */ NULL };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #pragma once #include <map> #include <vector> #include <atlbase.h> #include <comdef.h> #include <npapi.h> #include <npfunctions.h> #include <npruntime.h> #include "variants.h" extern NPNetscapeFuncs NPNFuncs; extern NPClass GenericNPObjectClass; typedef bool (*DefaultInvoker)(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); struct ltnum { bool operator()(long n1, long n2) const { return n1 < n2; } }; struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result); class GenericNPObject: public NPObject { private: GenericNPObject(const GenericNPObject &); bool invalid; DefaultInvoker defInvoker; void *defInvokerObject; std::vector<NPVariant> numeric_mapper; // the members of alpha mapper can be reassigned to anything the user wishes std::map<const char *, NPVariant, ltstr> alpha_mapper; // these cannot accept other types than they are initially defined with std::map<const char *, NPVariant, ltstr> immutables; public: friend bool toString(void *, const NPVariant *, uint32_t, NPVariant *); GenericNPObject(NPP instance); GenericNPObject(NPP instance, bool isMethodObj); ~GenericNPObject(); void Invalidate() {invalid = true;} void SetDefaultInvoker(DefaultInvoker di, void *context) { defInvoker = di; defInvokerObject = context; } static bool _HasMethod(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasMethod(name); } static bool _Invoke(NPObject *npobj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((GenericNPObject *)npobj)->Invoke(methodName, args, argCount, result); } static bool _InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (((GenericNPObject *)npobj)->defInvoker) { return (((GenericNPObject *)npobj)->InvokeDefault)(args, argCount, result); } else { return false; } } static bool _HasProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->HasProperty(name); } static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((GenericNPObject *)npobj)->GetProperty(name, result); } static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((GenericNPObject *)npobj)->SetProperty(name, value); } static bool _RemoveProperty(NPObject *npobj, NPIdentifier name) { return ((GenericNPObject *)npobj)->RemoveProperty(name); } static bool _Enumerate(NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) { return ((GenericNPObject *)npobj)->Enumerate(identifiers, identifierCount); } bool HasMethod(NPIdentifier name); bool Invoke(NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result); bool InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result); bool HasProperty(NPIdentifier name); bool GetProperty(NPIdentifier name, NPVariant *result); bool SetProperty(NPIdentifier name, const NPVariant *value); bool RemoveProperty(NPIdentifier name); bool Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount); };
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <windows.h> #include <winreg.h> #include "ffactivex.h" #include "common/stdafx.h" #include "axhost.h" #include "atlutil.h" #include "authorize.h" // ---------------------------------------------------------------------------- #define SUB_KEY L"SOFTWARE\\MozillaPlugins\\@itstructures.com/ffactivex\\MimeTypes\\application/x-itst-activex" // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId); BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId); BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value); HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType); // --------------------------------------------------------------------------- HKEY BaseKeys[] = { HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }; // ---------------------------------------------------------------------------- BOOL TestAuthorization (NPP Instance, int16 ArgC, char *ArgN[], char *ArgV[], const char *MimeType) { BOOL ret = FALSE; NPObject *globalObj = NULL; NPIdentifier identifier; NPVariant varLocation; NPVariant varHref; bool rc = false; int16 i; char *wrkHref; #ifdef NDEF _asm{int 3}; #endif if (Instance == NULL) { return (FALSE); } // Determine owning document // Get the window object. NPNFuncs.getvalue(Instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(Instance, globalObj, identifier, &varLocation); NPNFuncs.releaseobject(globalObj); if (!rc){ log(Instance, 0, "AxHost.TestAuthorization: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(Instance, locationObj, identifier, &varHref); NPNFuncs.releasevariantvalue(&varLocation); if (!rc) { log(Instance, 0, "AxHost.TestAuthorization: could not get the href from the location property"); return false; } ret = TRUE; wrkHref = (char *) alloca(varHref.value.stringValue.UTF8Length + 1); memcpy(wrkHref, varHref.value.stringValue.UTF8Characters, varHref.value.stringValue.UTF8Length); wrkHref[varHref.value.stringValue.UTF8Length] = 0x00; NPNFuncs.releasevariantvalue(&varHref); for (i = 0; i < ArgC; ++i) { // search for any needed information: clsid, event handling directives, etc. if (0 == strnicmp(ArgN[i], PARAM_CLSID, strlen(PARAM_CLSID))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CLSID, wrkHref, ArgV[i]); } else if (0 == strnicmp(ArgN[i], PARAM_PROGID, strlen(PARAM_PROGID))) { // The class id of the control we are asked to load ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_PROGID, wrkHref, ArgV[i]); } else if( 0 == strnicmp(ArgN[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) { ret &= TestExplicitAuthorizationUTF8(MimeType, PARAM_CODEBASEURL, wrkHref, ArgV[i]); } } log(Instance, 1, "AxHost.TestAuthorization: returning %s", ret ? "True" : "False"); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorizationUTF8 (const char *MimeType, const char *AuthorizationType, const char *DocumentUrl, const char *ProgramId) { USES_CONVERSION; BOOL ret; ret = TestExplicitAuthorization(A2W(MimeType), A2W(AuthorizationType), A2W(DocumentUrl), A2W(ProgramId)); return (ret); } // ---------------------------------------------------------------------------- BOOL TestExplicitAuthorization (const wchar_t *MimeType, const wchar_t *AuthorizationType, const wchar_t *DocumentUrl, const wchar_t *ProgramId) { BOOL ret = FALSE; #ifndef NO_REGISTRY_AUTHORIZE HKEY hKey; HKEY hSubKey; ULONG i; ULONG j; ULONG keyNameLen; ULONG valueNameLen; wchar_t keyName[_MAX_PATH]; wchar_t valueName[_MAX_PATH]; if (DocumentUrl == NULL) { return (FALSE); } if (ProgramId == NULL) { return (FALSE); } #ifdef NDEF MessageBox(NULL, DocumentUrl, ProgramId, MB_OK); #endif if ((hKey = FindKey(MimeType, AuthorizationType)) != NULL) { for (i = 0; !ret; i++) { keyNameLen = sizeof(keyName); if (RegEnumKey(hKey, i, keyName, keyNameLen) == ERROR_SUCCESS) { if (WildcardMatch(keyName, DocumentUrl)) { if (RegOpenKeyEx(hKey, keyName, 0, KEY_QUERY_VALUE, &hSubKey) == ERROR_SUCCESS) { for (j = 0; ; j++) { valueNameLen = sizeof(valueName); if (RegEnumValue(hSubKey, j, valueName, &valueNameLen, NULL, NULL, NULL, NULL) != ERROR_SUCCESS) { break; } if (WildcardMatch(valueName, ProgramId)) { ret = TRUE; break; } } RegCloseKey(hSubKey); } if (ret) { break; } } } else { break; } } RegCloseKey(hKey); } #endif return (ret); } // ---------------------------------------------------------------------------- BOOL WildcardMatch (const wchar_t *Mask, const wchar_t *Value) { size_t i; size_t j = 0; size_t maskLen; size_t valueLen; maskLen = wcslen(Mask); valueLen = wcslen(Value); for (i = 0; i < maskLen + 1; i++) { if (Mask[i] == '?') { j++; continue; } if (Mask[i] == '*') { for (; j < valueLen + 1; j++) { if (WildcardMatch(Mask + i + 1, Value + j)) { return (TRUE); } } return (FALSE); } if ((j <= valueLen) && (Mask[i] == tolower(Value[j]))) { j++; continue; } return (FALSE); } return (TRUE); } // ---------------------------------------------------------------------------- HKEY FindKey (const wchar_t *MimeType, const wchar_t *AuthorizationType) { HKEY ret = NULL; HKEY plugins; wchar_t searchKey[_MAX_PATH]; wchar_t pluginName[_MAX_PATH]; DWORD j; size_t i; for (i = 0; i < ARRAYSIZE(BaseKeys); i++) { if (RegOpenKeyEx(BaseKeys[i], L"SOFTWARE\\MozillaPlugins", 0, KEY_ENUMERATE_SUB_KEYS, &plugins) == ERROR_SUCCESS) { for (j = 0; ret == NULL; j++) { if (RegEnumKey(plugins, j, pluginName, sizeof(pluginName)) != ERROR_SUCCESS) { break; } wsprintf(searchKey, L"%s\\MimeTypes\\%s\\%s", pluginName, MimeType, AuthorizationType); if (RegOpenKeyEx(plugins, searchKey, 0, KEY_ENUMERATE_SUB_KEYS, &ret) == ERROR_SUCCESS) { break; } ret = NULL; } RegCloseKey(plugins); if (ret != NULL) { break; } } } return (ret); }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <atlbase.h> #include <atlsafe.h> #include <npapi.h> #include <npfunctions.h> #include <prtypes.h> #include <npruntime.h> #include "scriptable.h" #include "GenericNPObject.h" #include "variants.h" extern NPNetscapeFuncs NPNFuncs; BSTR Utf8StringToBstr(LPCSTR szStr, int iSize) { BSTR bstrVal; // Chars required for string int iReq = 0; if (iSize > 0) { if ((iReq = MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, 0, 0)) == 0) { return (0); } } // Account for terminating 0. if (iReq != -1) { ++iReq; } if ((bstrVal = ::SysAllocStringLen(0, iReq)) == 0) { return (0); } memset(bstrVal, 0, iReq * sizeof(wchar_t)); if (iSize > 0) { // Convert into the buffer. if (MultiByteToWideChar(CP_UTF8, 0, szStr, iSize, bstrVal, iReq) == 0) { ::SysFreeString(bstrVal); return 0; } } return (bstrVal); } void BSTR2NPVar(BSTR bstr, NPVariant *npvar, NPP instance) { USES_CONVERSION; char *npStr = NULL; size_t sourceLen; size_t bytesNeeded; sourceLen = lstrlenW(bstr); bytesNeeded = WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, NULL, 0, NULL, NULL); bytesNeeded += 1; // complete lack of documentation on Mozilla's part here, I have no // idea how this string is supposed to be freed npStr = (char *)NPNFuncs.memalloc(bytesNeeded); if (npStr) { memset(npStr, 0, bytesNeeded); WideCharToMultiByte(CP_UTF8, 0, bstr, sourceLen, npStr, bytesNeeded - 1, NULL, NULL); STRINGZ_TO_NPVARIANT(npStr, (*npvar)); } else { STRINGZ_TO_NPVARIANT(NULL, (*npvar)); } } void Dispatch2NPVar(IDispatch *disp, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &ScriptableNPClass); ((Scriptable *)obj)->setControl(disp); ((Scriptable *)obj)->setInstance(instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } void Unknown2NPVar(IUnknown *unk, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &ScriptableNPClass); ((Scriptable *)obj)->setControl(unk); ((Scriptable *)obj)->setInstance(instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } NPObject * SafeArray2NPObject(SAFEARRAY *parray, unsigned short dim, unsigned long *pindices, NPP instance) { unsigned long *indices = pindices; NPObject *obj = NULL; bool rc = true; if (!parray || !instance) { return NULL; } obj = NPNFuncs.createobject(instance, &GenericNPObjectClass); if (NULL == obj) { return NULL; } do { if (NULL == indices) { // just getting started SafeArrayLock(parray); indices = (unsigned long *)calloc(1, parray->cDims * sizeof(unsigned long)); if (NULL == indices) { rc = false; break; } } NPIdentifier id = NULL; NPVariant val; VOID_TO_NPVARIANT(val); for(indices[dim] = 0; indices[dim] < parray->rgsabound[dim].cElements; indices[dim]++) { if (dim == (parray->cDims - 1)) { // single dimension (or the bottom of the recursion) if (parray->fFeatures & FADF_VARIANT) { VARIANT variant; VariantInit(&variant); if(FAILED(SafeArrayGetElement(parray, (long *)indices, &variant))) { rc = false; break; } Variant2NPVar(&variant, &val, instance); VariantClear(&variant); } else if (parray->fFeatures & FADF_BSTR) { BSTR bstr; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &bstr))) { rc = false; break; } BSTR2NPVar(bstr, &val, instance); } else if (parray->fFeatures & FADF_DISPATCH) { IDispatch *disp; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &disp))) { rc = false; break; } Dispatch2NPVar(disp, &val, instance); } else if (parray->fFeatures & FADF_UNKNOWN) { IUnknown *unk; if(FAILED(SafeArrayGetElement(parray, (long *)indices, &unk))) { rc = false; break; } Unknown2NPVar(unk, &val, instance); } } else { // recurse NPObject *o = SafeArray2NPObject(parray, dim + 1, indices, instance); if (NULL == o) { rc = false; break; } OBJECT_TO_NPVARIANT(o, val); } id = NPNFuncs.getintidentifier(parray->rgsabound[dim].lLbound + indices[dim]); // setproperty will call retainobject or copy the internal string, we should // release variant NPNFuncs.setproperty(instance, obj, id, &val); NPNFuncs.releasevariantvalue(&val); VOID_TO_NPVARIANT(val); } } while (0); if (false == rc) { if (!pindices && indices) { free(indices); indices = NULL; SafeArrayUnlock(parray); } if (obj) { NPNFuncs.releaseobject(obj); obj = NULL; } } return obj; } #define GETVALUE(var, val) (((var->vt) & VT_BYREF) ? *(var->p##val) : (var->val)) void Variant2NPVar(const VARIANT *var, NPVariant *npvar, NPP instance) { NPObject *obj = NULL; SAFEARRAY *parray = NULL; if (!var || !npvar) { return; } VOID_TO_NPVARIANT(*npvar); switch (var->vt & ~VT_BYREF) { case VT_EMPTY: VOID_TO_NPVARIANT((*npvar)); break; case VT_NULL: NULL_TO_NPVARIANT((*npvar)); break; case VT_LPSTR: // not sure it can even appear in a VARIANT, but... STRINGZ_TO_NPVARIANT(var->pcVal, (*npvar)); break; case VT_BSTR: BSTR2NPVar(GETVALUE(var, bstrVal), npvar, instance); break; case VT_I1: INT32_TO_NPVARIANT((int32)GETVALUE(var, cVal), (*npvar)); break; case VT_I2: INT32_TO_NPVARIANT((int32)GETVALUE(var, iVal), (*npvar)); break; case VT_I4: INT32_TO_NPVARIANT((int32)GETVALUE(var, lVal), (*npvar)); break; case VT_UI1: INT32_TO_NPVARIANT((int32)GETVALUE(var, bVal), (*npvar)); break; case VT_UI2: INT32_TO_NPVARIANT((int32)GETVALUE(var, uiVal), (*npvar)); break; case VT_UI4: INT32_TO_NPVARIANT((int32)GETVALUE(var, ulVal), (*npvar)); break; case VT_BOOL: BOOLEAN_TO_NPVARIANT((GETVALUE(var, boolVal) == VARIANT_TRUE) ? true : false, (*npvar)); break; case VT_R4: DOUBLE_TO_NPVARIANT((double)GETVALUE(var, fltVal), (*npvar)); break; case VT_R8: DOUBLE_TO_NPVARIANT(GETVALUE(var, dblVal), (*npvar)); break; case VT_DISPATCH: Dispatch2NPVar(GETVALUE(var, pdispVal), npvar, instance); break; case VT_UNKNOWN: Unknown2NPVar(GETVALUE(var, punkVal), npvar, instance); break; case VT_CY: DOUBLE_TO_NPVARIANT((double)GETVALUE(var, cyVal).int64 / 10000, (*npvar)); break; case VT_DATE: BSTR bstrVal; VarBstrFromDate(GETVALUE(var, date), 0, 0, &bstrVal); BSTR2NPVar(bstrVal, npvar, instance); break; default: if (var->vt & VT_ARRAY) { obj = SafeArray2NPObject(GETVALUE(var, parray), 0, NULL, instance); OBJECT_TO_NPVARIANT(obj, (*npvar)); } break; } } #undef GETVALUE void NPVar2Variant(const NPVariant *npvar, VARIANT *var, NPP instance) { USES_CONVERSION; if (!var || !npvar) { return; } switch (npvar->type) { case NPVariantType_Void: var->vt = VT_VOID; var->ulVal = 0; break; case NPVariantType_Null: var->vt = VT_PTR; var->byref = NULL; break; case NPVariantType_Bool: var->vt = VT_BOOL; var->ulVal = npvar->value.boolValue; break; case NPVariantType_Int32: var->vt = VT_UI4; var->ulVal = npvar->value.intValue; break; case NPVariantType_Double: var->vt = VT_R8; var->dblVal = npvar->value.doubleValue; break; case NPVariantType_String: var->vt = VT_BSTR; var->bstrVal = Utf8StringToBstr(npvar->value.stringValue.UTF8Characters, npvar->value.stringValue.UTF8Length); break; case NPVariantType_Object: NPIdentifier *identifiers = NULL; uint32_t identifierCount = 0; NPObject *object = NPVARIANT_TO_OBJECT(*npvar); if (NPNFuncs.enumerate(instance, object, &identifiers, &identifierCount)) { CComSafeArray<VARIANT> variants; for (uint32_t index = 0; index < identifierCount; ++index) { NPVariant npVariant; if (NPNFuncs.getproperty(instance, object, identifiers[index], &npVariant)) { if (npVariant.type != NPVariantType_Object) { CComVariant variant; NPVar2Variant(&npVariant, &variant, instance); variants.Add(variant); } NPNFuncs.releasevariantvalue(&npVariant); } } NPNFuncs.memfree(identifiers); *reinterpret_cast<CComVariant*>(var) = variants; } else { var->vt = VT_VOID; var->ulVal = 0; } break; } }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <algorithm> #include <string> #include "GenericNPObject.h" static NPObject* AllocateGenericNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, false); } static NPObject* AllocateMethodNPObject(NPP npp, NPClass *aClass) { return new GenericNPObject(npp, true); } static void DeallocateGenericNPObject(NPObject *obj) { if (!obj) { return; } GenericNPObject *m = (GenericNPObject *)obj; delete m; } static void InvalidateGenericNPObject(NPObject *obj) { if (!obj) { return; } ((GenericNPObject *)obj)->Invalidate(); } NPClass GenericNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateGenericNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; NPClass MethodNPObjectClass = { /* version */ NP_CLASS_STRUCT_VERSION, /* allocate */ AllocateMethodNPObject, /* deallocate */ DeallocateGenericNPObject, /* invalidate */ InvalidateGenericNPObject, /* hasMethod */ GenericNPObject::_HasMethod, /* invoke */ GenericNPObject::_Invoke, /* invokeDefault */ GenericNPObject::_InvokeDefault, /* hasProperty */ GenericNPObject::_HasProperty, /* getProperty */ GenericNPObject::_GetProperty, /* setProperty */ GenericNPObject::_SetProperty, /* removeProperty */ GenericNPObject::_RemoveProperty, /* enumerate */ GenericNPObject::_Enumerate, /* construct */ NULL }; // Some standard JavaScript methods bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) { GenericNPObject *map = (GenericNPObject *)object; if (!map || map->invalid) return false; // no args expected or cared for... std::string out; std::vector<NPVariant>::iterator it; for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) { if (NPVARIANT_IS_VOID(*it)) { out += ","; } else if (NPVARIANT_IS_NULL(*it)) { out += ","; } else if (NPVARIANT_IS_BOOLEAN(*it)) { if ((*it).value.boolValue) { out += "true,"; } else { out += "false,"; } } else if (NPVARIANT_IS_INT32(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%d,", (*it).value.intValue); out += tmp; } else if (NPVARIANT_IS_DOUBLE(*it)) { char tmp[50]; memset(tmp, 0, sizeof(tmp)); _snprintf(tmp, 49, "%f,", (*it).value.doubleValue); out += tmp; } else if (NPVARIANT_IS_STRING(*it)) { out += (*it).value.stringValue.UTF8Characters; out += ","; } else if (NPVARIANT_IS_OBJECT(*it)) { out += "[object],"; } } // calculate how much space we need std::string::size_type size = out.length(); char *s = (char *)NPNFuncs.memalloc(size * sizeof(char)); if (NULL == s) { return false; } memcpy(s, out.c_str(), size); s[size - 1] = 0; // overwrite the last "," STRINGZ_TO_NPVARIANT(s, (*result)); return true; } // Some helpers static void free_numeric_element(NPVariant elem) { NPNFuncs.releasevariantvalue(&elem); } static void free_alpha_element(std::pair<const char *, NPVariant> elem) { NPNFuncs.releasevariantvalue(&(elem.second)); } // And now the GenericNPObject implementation GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj): invalid(false), defInvoker(NULL), defInvokerObject(NULL) { NPVariant val; INT32_TO_NPVARIANT(0, val); immutables["length"] = val; if (!isMethodObj) { NPObject *obj = NULL; obj = NPNFuncs.createobject(instance, &MethodNPObjectClass); if (NULL == obj) { throw NULL; } ((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this); OBJECT_TO_NPVARIANT(obj, val); immutables["toString"] = val; } } GenericNPObject::~GenericNPObject() { for_each(immutables.begin(), immutables.end(), free_alpha_element); for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element); for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element); } bool GenericNPObject::HasMethod(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL != immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault); } } } return false; } bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(immutables[key]) && immutables[key].value.objectValue->_class->invokeDefault) { return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result); } } else if (alpha_mapper.count(key) > 0) { if ( NPVARIANT_IS_OBJECT(alpha_mapper[key]) && alpha_mapper[key].value.objectValue->_class->invokeDefault) { return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result); } } } return true; } bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) { if (invalid) return false; if (defInvoker) { defInvoker(defInvokerObject, args, argCount, result); } return true; } // This method is also called before the JS engine attempts to add a new // property, most likely it's trying to check that the key is supported. // It only returns false if the string name was not found, or does not // hold a callable object bool GenericNPObject::HasProperty(NPIdentifier name) { if (invalid) return false; if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (NPVARIANT_IS_OBJECT(immutables[key])) { return (NULL == immutables[key].value.objectValue->_class->invokeDefault); } } else if (alpha_mapper.count(key) > 0) { if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) { return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault); } } return false; } return true; } static bool CopyNPVariant(NPVariant *dst, const NPVariant *src) { dst->type = src->type; if (NPVARIANT_IS_STRING(*src)) { NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8)); if (NULL == str) { return false; } dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length; memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length); str[dst->value.stringValue.UTF8Length] = 0; dst->value.stringValue.UTF8Characters = str; } else if (NPVARIANT_IS_OBJECT(*src)) { NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src)); dst->value.objectValue = src->value.objectValue; } else { dst->value = src->value; } return true; } #define MIN(x, y) ((x) < (y)) ? (x) : (y) bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { if (!CopyNPVariant(result, &(immutables[key]))) { return false; } } else if (alpha_mapper.count(key) > 0) { if (!CopyNPVariant(result, &(alpha_mapper[key]))) { return false; } } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { if (!CopyNPVariant(result, &(numeric_mapper[key]))) { return false; } } } } catch (...) { } return true; } bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (immutables.count(key) > 0) { // the key is already defined as immutable, check the new value type if (value->type != immutables[key].type) { return false; } // Seems ok, copy the new value if (!CopyNPVariant(&(immutables[key]), value)) { return false; } } else if (!CopyNPVariant(&(alpha_mapper[key]), value)) { return false; } } else { // assume int... NPVariant var; if (!CopyNPVariant(&var, value)) { return false; } unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (key >= numeric_mapper.size()) { // there's a gap we need to fill NPVariant pad; VOID_TO_NPVARIANT(pad); numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad); } numeric_mapper.at(key) = var; NPVARIANT_TO_INT32(immutables["length"])++; } } catch (...) { } return true; } bool GenericNPObject::RemoveProperty(NPIdentifier name) { if (invalid) return false; try { if (NPNFuncs.identifierisstring(name)) { char *key = NPNFuncs.utf8fromidentifier(name); if (alpha_mapper.count(key) > 0) { NPNFuncs.releasevariantvalue(&(alpha_mapper[key])); alpha_mapper.erase(key); } } else { // assume int... unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name); if (numeric_mapper.size() > key) { NPNFuncs.releasevariantvalue(&(numeric_mapper[key])); numeric_mapper.erase(numeric_mapper.begin() + key); } NPVARIANT_TO_INT32(immutables["length"])--; } } catch (...) { } return true; } bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) { if (invalid) return false; try { *identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size()); if (NULL == *identifiers) { return false; } *identifierCount = 0; std::vector<NPVariant>::iterator it; unsigned int i = 0; char str[10] = ""; for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) { // skip empty (padding) elements if (NPVARIANT_IS_VOID(*it)) continue; _snprintf(str, sizeof(str), "%u", i); (*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str); } } catch (...) { } return true; }
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ class CAxHost { private: CAxHost(const CAxHost &); NPP instance; bool isValidClsID; bool isKnown; protected: // The window handle to our plugin area in the browser HWND Window; WNDPROC OldProc; // The class/prog id of the control CLSID ClsID; LPCWSTR CodeBaseUrl; CControlEventSinkInstance *Sink; public: CAxHost(NPP inst); ~CAxHost(); CControlSiteInstance *Site; PropertyList Props; void setWindow(HWND win); HWND getWinfow(); void UpdateRect(RECT rcPos); bool verifyClsID(LPOLESTR oleClsID); bool setClsID(const char *clsid); bool setClsIDFromProgID(const char *progid); void setCodeBaseUrl(LPCWSTR clsid); bool hasValidClsID(); bool CreateControl(bool subscribeToEvents); bool AddEventHandler(wchar_t *name, wchar_t *handler); int16 HandleEvent(void *event); NPObject *GetScriptableObject(); };
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is itstructures.com code. * * The Initial Developer of the Original Code is IT Structures. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // ffactivex.cpp : Defines the exported functions for the DLL application. // #include "ffactivex.h" #include "common/stdafx.h" #include "axhost.h" #include "atlutil.h" #include "authorize.h" // A list of trusted domains // Each domain name may start with a '*' to specify that sub domains are // trusted as well // Note that a '.' is not enforced after the '*' static const char *TrustedLocations[] = {NULL}; static const unsigned int numTrustedLocations = 0; static const char *LocalhostName = "localhost"; static const bool TrustLocalhost = true; void * ffax_calloc(unsigned int size) { void *ptr = NULL; ptr = NPNFuncs.memalloc(size); if (ptr) { memset(ptr, 0, size); } return ptr; } void ffax_free(void *ptr) { if (ptr) NPNFuncs.memfree(ptr); } // // Gecko API // static unsigned int log_level = 0; static char *logger = NULL; void log(NPP instance, unsigned int level, char *message, ...) { NPVariant result; NPVariant args; NPObject *globalObj = NULL; bool rc = false; char *formatted = NULL; char *new_formatted = NULL; int buff_len = 0; int size = 0; va_list list; if (!logger || (level > log_level)) { return; } buff_len = strlen(message); buff_len += buff_len / 10; formatted = (char *)calloc(1, buff_len); while (true) { va_start(list, message); size = vsnprintf_s(formatted, buff_len, _TRUNCATE, message, list); va_end(list); if (size > -1 && size < buff_len) break; buff_len *= 2; new_formatted = (char *)realloc(formatted, buff_len); if (NULL == new_formatted) { free(formatted); return; } formatted = new_formatted; new_formatted = NULL; } NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); NPIdentifier handler = NPNFuncs.getstringidentifier(logger); STRINGZ_TO_NPVARIANT(formatted, args); bool success = NPNFuncs.invoke(instance, globalObj, handler, &args, 1, &result); NPNFuncs.releasevariantvalue(&result); NPNFuncs.releaseobject(globalObj); free(formatted); } static bool MatchURL2TrustedLocations(NPP instance, LPCTSTR matchUrl) { USES_CONVERSION; bool rc = false; CUrl url; if (!numTrustedLocations) { return true; } rc = url.CrackUrl(matchUrl, ATL_URL_DECODE); if (!rc) { log(instance, 0, "AxHost.MatchURL2TrustedLocations: failed to parse the current location URL"); return false; } if ( (url.GetScheme() == ATL_URL_SCHEME_FILE) || (!strncmp(LocalhostName, W2A(url.GetHostName()), strlen(LocalhostName)))){ return TrustLocalhost; } for (unsigned int i = 0; i < numTrustedLocations; ++i) { if (TrustedLocations[i][0] == '*') { // sub domains are trusted unsigned int len = strlen(TrustedLocations[i]); bool match = 0; if (url.GetHostNameLength() < len) { // can't be a match continue; } --len; // skip the '*' match = strncmp(W2A(url.GetHostName()) + (url.GetHostNameLength() - len), // anchor the comparison to the end of the domain name TrustedLocations[i] + 1, // skip the '*' len) == 0 ? true : false; if (match) { return true; } } else if (!strncmp(W2A(url.GetHostName()), TrustedLocations[i], url.GetHostNameLength())) { return true; } } return false; } static bool VerifySiteLock(NPP instance) { USES_CONVERSION; NPObject *globalObj = NULL; NPIdentifier identifier; NPVariant varLocation; NPVariant varHref; bool rc = false; // Get the window object. NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); // Create a "location" identifier. identifier = NPNFuncs.getstringidentifier("location"); // Get the location property from the window object (which is another object). rc = NPNFuncs.getproperty(instance, globalObj, identifier, &varLocation); NPNFuncs.releaseobject(globalObj); if (!rc){ log(instance, 0, "AxHost.VerifySiteLock: could not get the location from the global object"); return false; } // Get a pointer to the "location" object. NPObject *locationObj = varLocation.value.objectValue; // Create a "href" identifier. identifier = NPNFuncs.getstringidentifier("href"); // Get the location property from the location object. rc = NPNFuncs.getproperty(instance, locationObj, identifier, &varHref); NPNFuncs.releasevariantvalue(&varLocation); if (!rc) { log(instance, 0, "AxHost.VerifySiteLock: could not get the href from the location property"); return false; } rc = MatchURL2TrustedLocations(instance, A2W(varHref.value.stringValue.UTF8Characters)); NPNFuncs.releasevariantvalue(&varHref); if (false == rc) { log(instance, 0, "AxHost.VerifySiteLock: current location is not trusted"); } return rc; } /* * Create a new plugin instance, most probably through an embed/object HTML * element. * * Any private data we want to keep for this instance can be saved into * [instance->pdata]. * [saved] might hold information a previous instance that was invoked from the * same URL has saved for us. */ NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { NPError rc = NPERR_NO_ERROR; NPObject *browser = NULL; CAxHost *host = NULL; PropertyList events; int16 i = 0; USES_CONVERSION; //_asm {int 3}; if (!instance || (0 == NPNFuncs.size)) { return NPERR_INVALID_PARAM; } #ifdef NO_REGISTRY_AUTHORIZE // Verify that we're running from a trusted location if (!VerifySiteLock(instance)) { return NPERR_GENERIC_ERROR; } #endif instance->pdata = NULL; #ifndef NO_REGISTRY_AUTHORIZE if (!TestAuthorization (instance, argc, argn, argv, pluginType)) { return NPERR_GENERIC_ERROR; } #endif // TODO: Check the pluginType to make sure we're being called with the rigth MIME Type do { // Create a plugin instance, the actual control will be created once we // are given a window handle host = new CAxHost(instance); if (!host) { rc = NPERR_OUT_OF_MEMORY_ERROR; log(instance, 0, "AxHost.NPP_New: failed to allocate memory for a new host"); break; } // Iterate over the arguments we've been passed for (i = 0; (i < argc) && (NPERR_NO_ERROR == rc); ++i) { // search for any needed information: clsid, event handling directives, etc. if (0 == strnicmp(argn[i], PARAM_CLSID, strlen(PARAM_CLSID))) { // The class id of the control we are asked to load host->setClsID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_PROGID, strlen(PARAM_PROGID))) { // The class id of the control we are asked to load host->setClsIDFromProgID(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_DEBUG, strlen(PARAM_DEBUG))) { // Logging verbosity log_level = atoi(argv[i]); log(instance, 0, "AxHost.NPP_New: debug level set to %d", log_level); } else if (0 == strnicmp(argn[i], PARAM_LOGGER, strlen(PARAM_LOGGER))) { // Logger function logger = strdup(argv[i]); } else if (0 == strnicmp(argn[i], PARAM_ONEVENT, strlen(PARAM_ONEVENT))) { // A request to handle one of the activex's events in JS events.AddOrReplaceNamedProperty(A2W(argn[i] + strlen(PARAM_ONEVENT)), CComVariant(A2W(argv[i]))); } else if (0 == strnicmp(argn[i], PARAM_PARAM, strlen(PARAM_PARAM))) { CComBSTR paramName = argn[i] + strlen(PARAM_PARAM); CComBSTR paramValue(Utf8StringToBstr(argv[i], strlen(argv[i]))); // Check for existing params with the same name BOOL bFound = FALSE; for (unsigned long j = 0; j < host->Props.GetSize(); j++) { if (wcscmp(host->Props.GetNameOf(j), (BSTR) paramName) == 0) { bFound = TRUE; break; } } // If the parameter already exists, don't add it to the // list again. if (bFound) { continue; } // Add named parameter to list CComVariant v(paramValue); host->Props.AddNamedProperty(paramName, v); } else if(0 == strnicmp(argn[i], PARAM_CODEBASEURL, strlen(PARAM_CODEBASEURL))) { if (MatchURL2TrustedLocations(instance, A2W(argv[i]))) { host->setCodeBaseUrl(A2W(argv[i])); } else { log(instance, 0, "AxHost.NPP_New: codeBaseUrl contains an untrusted location"); } } } if (NPERR_NO_ERROR != rc) break; // Make sure we have all the information we need to initialize a new instance if (!host->hasValidClsID()) { rc = NPERR_INVALID_PARAM; log(instance, 0, "AxHost.NPP_New: no valid CLSID or PROGID"); break; } instance->pdata = host; // if no events were requested, don't fail if subscribing fails if (!host->CreateControl(events.GetSize() ? true : false)) { rc = NPERR_GENERIC_ERROR; log(instance, 0, "AxHost.NPP_New: failed to create the control"); break; } for (unsigned int j = 0; j < events.GetSize(); j++) { if (!host->AddEventHandler(events.GetNameOf(j), events.GetValueOf(j)->bstrVal)) { //rc = NPERR_GENERIC_ERROR; //break; } } if (NPERR_NO_ERROR != rc) break; } while (0); if (NPERR_NO_ERROR != rc) { delete host; } return rc; } /* * Destroy an existing plugin instance. * * [save] can be used to save information for a future instance of our plugin * that'll be invoked by the same URL. */ NPError NPP_Destroy(NPP instance, NPSavedData **save) { // _asm {int 3}; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } log(instance, 0, "NPP_Destroy: destroying the control..."); CAxHost *host = (CAxHost *)instance->pdata; delete host; instance->pdata = NULL; return NPERR_NO_ERROR; } /* * Sets an instance's window parameters. */ NPError NPP_SetWindow(NPP instance, NPWindow *window) { CAxHost *host = NULL; RECT rcPos; if (!instance || !instance->pdata) { return NPERR_INVALID_PARAM; } host = (CAxHost *)instance->pdata; host->setWindow((HWND)window->window); rcPos.left = 0; rcPos.top = 0; rcPos.right = window->width; rcPos.bottom = window->height; host->UpdateRect(rcPos); return NPERR_NO_ERROR; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "PropertyBag.h" CPropertyBag::CPropertyBag() { } CPropertyBag::~CPropertyBag() { } /////////////////////////////////////////////////////////////////////////////// // IPropertyBag implementation HRESULT STDMETHODCALLTYPE CPropertyBag::Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } VARTYPE vt = pVar->vt; VariantInit(pVar); for (unsigned long i = 0; i < m_PropertyList.GetSize(); i++) { if (wcsicmp(m_PropertyList.GetNameOf(i), pszPropName) == 0) { const VARIANT *pvSrc = m_PropertyList.GetValueOf(i); if (!pvSrc) { return E_FAIL; } CComVariant vNew; HRESULT hr = (vt == VT_EMPTY) ? vNew.Copy(pvSrc) : vNew.ChangeType(vt, pvSrc); if (FAILED(hr)) { return E_FAIL; } // Copy the new value vNew.Detach(pVar); return S_OK; } } // Property does not exist in the bag return E_FAIL; } HRESULT STDMETHODCALLTYPE CPropertyBag::Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar) { if (pszPropName == NULL) { return E_INVALIDARG; } if (pVar == NULL) { return E_INVALIDARG; } CComBSTR bstrName(pszPropName); m_PropertyList.AddOrReplaceNamedProperty(bstrName, *pVar); return S_OK; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYBAG_H #define PROPERTYBAG_H #include "PropertyList.h" // Object wrapper for property list. This class can be set up with a // list of properties and used to initialise a control with them class CPropertyBag : public CComObjectRootEx<CComSingleThreadModel>, public IPropertyBag { // List of properties in the bag PropertyList m_PropertyList; public: // Constructor CPropertyBag(); // Destructor virtual ~CPropertyBag(); BEGIN_COM_MAP(CPropertyBag) COM_INTERFACE_ENTRY(IPropertyBag) END_COM_MAP() // IPropertyBag methods virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(/* [in] */ LPCOLESTR pszPropName, /* [out][in] */ VARIANT __RPC_FAR *pVar, /* [in] */ IErrorLog __RPC_FAR *pErrorLog); virtual HRESULT STDMETHODCALLTYPE Write(/* [in] */ LPCOLESTR pszPropName, /* [in] */ VARIANT __RPC_FAR *pVar); }; typedef CComObject<CPropertyBag> CPropertyBagInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITE_H #define CONTROLSITE_H #include "IOleCommandTargetImpl.h" #include "PropertyList.h" // If you created a class derived from CControlSite, use the following macro // in the interface map of the derived class to include all the necessary // interfaces. #define CCONTROLSITE_INTERFACES() \ COM_INTERFACE_ENTRY(IOleWindow) \ COM_INTERFACE_ENTRY(IOleClientSite) \ COM_INTERFACE_ENTRY(IOleInPlaceSite) \ COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSite, IOleInPlaceSiteWindowless) \ COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteEx, IOleInPlaceSiteWindowless) \ COM_INTERFACE_ENTRY(IOleControlSite) \ COM_INTERFACE_ENTRY(IDispatch) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSink, IAdviseSinkEx) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSink2, IAdviseSinkEx) \ COM_INTERFACE_ENTRY_IID(IID_IAdviseSinkEx, IAdviseSinkEx) \ COM_INTERFACE_ENTRY(IOleCommandTarget) \ COM_INTERFACE_ENTRY(IServiceProvider) \ COM_INTERFACE_ENTRY(IBindStatusCallback) \ COM_INTERFACE_ENTRY(IWindowForBindingUI) // Temoporarily removed by bug 200680. Stops controls misbehaving and calling // windowless methods when they shouldn't. // COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceSiteWindowless, IOleInPlaceSiteWindowless) \ // Class that defines the control's security policy with regards to // what controls it hosts etc. class CControlSiteSecurityPolicy { public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid) = 0; // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) = 0; // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) = 0; }; // // Class for hosting an ActiveX control // // This class supports both windowed and windowless classes. The normal // steps to hosting a control are this: // // CControlSiteInstance *pSite = NULL; // CControlSiteInstance::CreateInstance(&pSite); // pSite->AddRef(); // pSite->Create(clsidControlToCreate); // pSite->Attach(hwndParentWindow, rcPosition); // // Where propertyList is a named list of values to initialise the new object // with, hwndParentWindow is the window in which the control is being created, // and rcPosition is the position in window coordinates where the control will // be rendered. // // Destruction is this: // // pSite->Detach(); // pSite->Release(); // pSite = NULL; class CControlSite : public CComObjectRootEx<CComSingleThreadModel>, public CControlSiteSecurityPolicy, public IOleClientSite, public IOleInPlaceSiteWindowless, public IOleControlSite, public IAdviseSinkEx, public IDispatch, public IServiceProvider, public IOleCommandTargetImpl<CControlSite>, public IBindStatusCallback, public IWindowForBindingUI { public: // Site management values // Handle to parent window HWND m_hWndParent; // Position of the site and the contained object RECT m_rcObjectPos; // Flag indicating if client site should be set early or late unsigned m_bSetClientSiteFirst:1; // Flag indicating whether control is visible or not unsigned m_bVisibleAtRuntime:1; // Flag indicating if control is in-place active unsigned m_bInPlaceActive:1; // Flag indicating if control is UI active unsigned m_bUIActive:1; // Flag indicating if control is in-place locked and cannot be deactivated unsigned m_bInPlaceLocked:1; // Flag indicating if the site allows windowless controls unsigned m_bSupportWindowlessActivation:1; // Flag indicating if control is windowless (after being created) unsigned m_bWindowless:1; // Flag indicating if only safely scriptable controls are allowed unsigned m_bSafeForScriptingObjectsOnly:1; // Pointer to an externally registered service provider CComPtr<IServiceProvider> m_spServiceProvider; // Pointer to the OLE container CComPtr<IOleContainer> m_spContainer; // Return the default security policy object static CControlSiteSecurityPolicy *GetDefaultControlSecurityPolicy(); protected: // Pointers to object interfaces // Raw pointer to the object CComPtr<IUnknown> m_spObject; // Pointer to objects IViewObject interface CComQIPtr<IViewObject, &IID_IViewObject> m_spIViewObject; // Pointer to object's IOleObject interface CComQIPtr<IOleObject, &IID_IOleObject> m_spIOleObject; // Pointer to object's IOleInPlaceObject interface CComQIPtr<IOleInPlaceObject, &IID_IOleInPlaceObject> m_spIOleInPlaceObject; // Pointer to object's IOleInPlaceObjectWindowless interface CComQIPtr<IOleInPlaceObjectWindowless, &IID_IOleInPlaceObjectWindowless> m_spIOleInPlaceObjectWindowless; // CLSID of the control CLSID m_CLSID; // Parameter list PropertyList m_ParameterList; // Pointer to the security policy CControlSiteSecurityPolicy *m_pSecurityPolicy; // Binding variables // Flag indicating whether binding is in progress unsigned m_bBindingInProgress; // Result from the binding operation HRESULT m_hrBindResult; // Double buffer drawing variables used for windowless controls // Area of buffer RECT m_rcBuffer; // Bitmap to buffer HBITMAP m_hBMBuffer; // Bitmap to buffer HBITMAP m_hBMBufferOld; // Device context HDC m_hDCBuffer; // Clipping area of site HRGN m_hRgnBuffer; // Flags indicating how the buffer was painted DWORD m_dwBufferFlags; // Ambient properties // Locale ID LCID m_nAmbientLocale; // Foreground colour COLORREF m_clrAmbientForeColor; // Background colour COLORREF m_clrAmbientBackColor; // Flag indicating if control should hatch itself bool m_bAmbientShowHatching:1; // Flag indicating if control should have grab handles bool m_bAmbientShowGrabHandles:1; // Flag indicating if control is in edit/user mode bool m_bAmbientUserMode:1; // Flag indicating if control has a 3d border or not bool m_bAmbientAppearance:1; protected: // Notifies the attached control of a change to an ambient property virtual void FireAmbientPropertyChange(DISPID id); public: // Construction and destruction // Constructor CControlSite(); // Destructor virtual ~CControlSite(); BEGIN_COM_MAP(CControlSite) CCONTROLSITE_INTERFACES() END_COM_MAP() BEGIN_OLECOMMAND_TABLE() END_OLECOMMAND_TABLE() // Returns the window used when processing ole commands HWND GetCommandTargetWindow() { return NULL; // TODO } // Object creation and management functions // Creates and initialises an object virtual HRESULT Create(REFCLSID clsid, PropertyList &pl = PropertyList(), LPCWSTR szCodebase = NULL, IBindCtx *pBindContext = NULL); // Attaches the object to the site virtual HRESULT Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream = NULL); // Detaches the object from the site virtual HRESULT Detach(); // Returns the IUnknown pointer for the object virtual HRESULT GetControlUnknown(IUnknown **ppObject); // Sets the bounding rectangle for the object virtual HRESULT SetPosition(const RECT &rcPos); // Draws the object using the provided DC virtual HRESULT Draw(HDC hdc); // Performs the specified action on the object virtual HRESULT DoVerb(LONG nVerb, LPMSG lpMsg = NULL); // Sets an advise sink up for changes to the object virtual HRESULT Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie); // Removes an advise sink virtual HRESULT Unadvise(const IID &iid, DWORD dwCookie); // Register an external service provider object virtual void SetServiceProvider(IServiceProvider *pSP) { m_spServiceProvider = pSP; } virtual void SetContainer(IOleContainer *pContainer) { m_spContainer = pContainer; } // Set the security policy object. Ownership of this object remains with the caller and the security // policy object is meant to exist for as long as it is set here. virtual void SetSecurityPolicy(CControlSiteSecurityPolicy *pSecurityPolicy) { m_pSecurityPolicy = pSecurityPolicy; } virtual CControlSiteSecurityPolicy *GetSecurityPolicy() const { return m_pSecurityPolicy; } // Methods to set ambient properties virtual void SetAmbientUserMode(BOOL bUser); // Inline helper methods // Returns the object's CLSID virtual const CLSID &GetObjectCLSID() const { return m_CLSID; } // Tests if the object is valid or not virtual BOOL IsObjectValid() const { return (m_spObject) ? TRUE : FALSE; } // Returns the parent window to this one virtual HWND GetParentWindow() const { return m_hWndParent; } // Returns the inplace active state of the object virtual BOOL IsInPlaceActive() const { return m_bInPlaceActive; } // CControlSiteSecurityPolicy // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid); // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(const IID &iid); // IServiceProvider virtual HRESULT STDMETHODCALLTYPE QueryService(REFGUID guidService, REFIID riid, void** ppv); // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); // IAdviseSink implementation virtual /* [local] */ void STDMETHODCALLTYPE OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed); virtual /* [local] */ void STDMETHODCALLTYPE OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex); virtual /* [local] */ void STDMETHODCALLTYPE OnRename(/* [in] */ IMoniker __RPC_FAR *pmk); virtual /* [local] */ void STDMETHODCALLTYPE OnSave(void); virtual /* [local] */ void STDMETHODCALLTYPE OnClose(void); // IAdviseSink2 virtual /* [local] */ void STDMETHODCALLTYPE OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk); // IAdviseSinkEx implementation virtual /* [local] */ void STDMETHODCALLTYPE OnViewStatusChange(/* [in] */ DWORD dwViewStatus); // IOleWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleClientSite implementation virtual HRESULT STDMETHODCALLTYPE SaveObject(void); virtual HRESULT STDMETHODCALLTYPE GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk); virtual HRESULT STDMETHODCALLTYPE GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer); virtual HRESULT STDMETHODCALLTYPE ShowObject(void); virtual HRESULT STDMETHODCALLTYPE OnShowWindow(/* [in] */ BOOL fShow); virtual HRESULT STDMETHODCALLTYPE RequestNewObjectLayout(void); // IOleInPlaceSite implementation virtual HRESULT STDMETHODCALLTYPE CanInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivate(void); virtual HRESULT STDMETHODCALLTYPE OnUIActivate(void); virtual HRESULT STDMETHODCALLTYPE GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo); virtual HRESULT STDMETHODCALLTYPE Scroll(/* [in] */ SIZE scrollExtant); virtual HRESULT STDMETHODCALLTYPE OnUIDeactivate(/* [in] */ BOOL fUndoable); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivate(void); virtual HRESULT STDMETHODCALLTYPE DiscardUndoState(void); virtual HRESULT STDMETHODCALLTYPE DeactivateAndUndo(void); virtual HRESULT STDMETHODCALLTYPE OnPosRectChange(/* [in] */ LPCRECT lprcPosRect); // IOleInPlaceSiteEx implementation virtual HRESULT STDMETHODCALLTYPE OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw); virtual HRESULT STDMETHODCALLTYPE RequestUIActivate(void); // IOleInPlaceSiteWindowless implementation virtual HRESULT STDMETHODCALLTYPE CanWindowlessActivate(void); virtual HRESULT STDMETHODCALLTYPE GetCapture(void); virtual HRESULT STDMETHODCALLTYPE SetCapture(/* [in] */ BOOL fCapture); virtual HRESULT STDMETHODCALLTYPE GetFocus(void); virtual HRESULT STDMETHODCALLTYPE SetFocus(/* [in] */ BOOL fFocus); virtual HRESULT STDMETHODCALLTYPE GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC); virtual HRESULT STDMETHODCALLTYPE ReleaseDC(/* [in] */ HDC hDC); virtual HRESULT STDMETHODCALLTYPE InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase); virtual HRESULT STDMETHODCALLTYPE ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip); virtual HRESULT STDMETHODCALLTYPE AdjustRect(/* [out][in] */ LPRECT prc); virtual HRESULT STDMETHODCALLTYPE OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult); // IOleControlSite implementation virtual HRESULT STDMETHODCALLTYPE OnControlInfoChanged(void); virtual HRESULT STDMETHODCALLTYPE LockInPlaceActive(/* [in] */ BOOL fLock); virtual HRESULT STDMETHODCALLTYPE GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp); virtual HRESULT STDMETHODCALLTYPE TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers); virtual HRESULT STDMETHODCALLTYPE OnFocus(/* [in] */ BOOL fGotFocus); virtual HRESULT STDMETHODCALLTYPE ShowPropertyFrame( void); // IBindStatusCallback virtual HRESULT STDMETHODCALLTYPE OnStartBinding(/* [in] */ DWORD dwReserved, /* [in] */ IBinding __RPC_FAR *pib); virtual HRESULT STDMETHODCALLTYPE GetPriority(/* [out] */ LONG __RPC_FAR *pnPriority); virtual HRESULT STDMETHODCALLTYPE OnLowResource(/* [in] */ DWORD reserved); virtual HRESULT STDMETHODCALLTYPE OnProgress(/* [in] */ ULONG ulProgress, /* [in] */ ULONG ulProgressMax, /* [in] */ ULONG ulStatusCode, /* [in] */ LPCWSTR szStatusText); virtual HRESULT STDMETHODCALLTYPE OnStopBinding(/* [in] */ HRESULT hresult, /* [unique][in] */ LPCWSTR szError); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindInfo( /* [out] */ DWORD __RPC_FAR *grfBINDF, /* [unique][out][in] */ BINDINFO __RPC_FAR *pbindinfo); virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnDataAvailable(/* [in] */ DWORD grfBSCF, /* [in] */ DWORD dwSize, /* [in] */ FORMATETC __RPC_FAR *pformatetc, /* [in] */ STGMEDIUM __RPC_FAR *pstgmed); virtual HRESULT STDMETHODCALLTYPE OnObjectAvailable(/* [in] */ REFIID riid, /* [iid_is][in] */ IUnknown __RPC_FAR *punk); // IWindowForBindingUI virtual HRESULT STDMETHODCALLTYPE GetWindow(/* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd); }; typedef CComObject<CControlSite> CControlSiteInstance; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "ItemContainer.h" CItemContainer::CItemContainer() { } CItemContainer::~CItemContainer() { } /////////////////////////////////////////////////////////////////////////////// // IParseDisplayName implementation HRESULT STDMETHODCALLTYPE CItemContainer::ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut) { // TODO return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum) { HRESULT hr = E_NOTIMPL; /* if (ppenum == NULL) { return E_POINTER; } *ppenum = NULL; typedef CComObject<CComEnumOnSTL<IEnumUnknown, &IID_IEnumUnknown, IUnknown*, _CopyInterface<IUnknown>, CNamedObjectList > > enumunk; enumunk* p = NULL; p = new enumunk; if(p == NULL) { return E_OUTOFMEMORY; } hr = p->Init(); if (SUCCEEDED(hr)) { hr = p->QueryInterface(IID_IEnumUnknown, (void**) ppenum); } if (FAILED(hRes)) { delete p; } */ return hr; } HRESULT STDMETHODCALLTYPE CItemContainer::LockContainer(/* [in] */ BOOL fLock) { // TODO return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleItemContainer implementation HRESULT STDMETHODCALLTYPE CItemContainer::GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject) { if (pszItem == NULL) { return E_INVALIDARG; } if (ppvObject == NULL) { return E_INVALIDARG; } *ppvObject = NULL; return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage) { // TODO return MK_E_NOOBJECT; } HRESULT STDMETHODCALLTYPE CItemContainer::IsRunning(/* [in] */ LPOLESTR pszItem) { // TODO return MK_E_NOOBJECT; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLEVENTSINK_H #define CONTROLEVENTSINK_H #include <map> // This class listens for events from the specified control class CControlEventSink : public CComObjectRootEx<CComSingleThreadModel>, public IDispatch { public: CControlEventSink(); // Current event connection point CComPtr<IConnectionPoint> m_spEventCP; CComPtr<ITypeInfo> m_spEventSinkTypeInfo; DWORD m_dwEventCookie; IID m_EventIID; typedef std::map<DISPID, wchar_t *> EventMap; EventMap events; NPP instance; protected: virtual ~CControlEventSink(); bool m_bSubscribed; static HRESULT WINAPI SinkQI(void* pv, REFIID riid, LPVOID* ppv, DWORD dw) { CControlEventSink *pThis = (CControlEventSink *) pv; if (!IsEqualIID(pThis->m_EventIID, GUID_NULL) && IsEqualIID(pThis->m_EventIID, riid)) { return pThis->QueryInterface(__uuidof(IDispatch), ppv); } return E_NOINTERFACE; } public: BEGIN_COM_MAP(CControlEventSink) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY_FUNC_BLIND(0, SinkQI) END_COM_MAP() virtual HRESULT SubscribeToEvents(IUnknown *pControl); virtual void UnsubscribeFromEvents(); virtual BOOL GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo); virtual HRESULT InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr); // IDispatch virtual HRESULT STDMETHODCALLTYPE GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo); virtual HRESULT STDMETHODCALLTYPE GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo); virtual HRESULT STDMETHODCALLTYPE GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId); virtual /* [local] */ HRESULT STDMETHODCALLTYPE Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr); }; typedef CComObject<CControlEventSink> CControlEventSinkInstance; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "stdafx.h" #include "ControlSiteIPFrame.h" CControlSiteIPFrame::CControlSiteIPFrame() { m_hwndFrame = NULL; } CControlSiteIPFrame::~CControlSiteIPFrame() { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { if (phwnd == NULL) { return E_INVALIDARG; } *phwnd = m_hwndFrame; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceUIWindow implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::GetBorder(/* [out] */ LPRECT lprectBorder) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return INPLACE_E_NOTOOLSPACE; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceFrame implementation HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::RemoveMenus(/* [in] */ HMENU hmenuShared) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::SetStatusText(/* [in] */ LPCOLESTR pszStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::EnableModeless(/* [in] */ BOOL fEnable) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSiteIPFrame::TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID) { return E_NOTIMPL; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, // but are changed infrequently #if !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_) #define AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // under MSVC shut off copious warnings about debug symbol too long #ifdef _MSC_VER #pragma warning( disable: 4786 ) #endif //#include "jstypes.h" //#include "prtypes.h" // Mozilla headers //#include "jscompat.h" //#include "prthread.h" //#include "prprf.h" //#include "nsID.h" //#include "nsIComponentManager.h" //#include "nsIServiceManager.h" //#include "nsStringAPI.h" //#include "nsCOMPtr.h" //#include "nsComponentManagerUtils.h" //#include "nsServiceManagerUtils.h" //#include "nsIDocument.h" //#include "nsIDocumentObserver.h" //#include "nsVoidArray.h" //#include "nsIDOMNode.h" //#include "nsIDOMNodeList.h" //#include "nsIDOMDocument.h" //#include "nsIDOMDocumentType.h" //#include "nsIDOMElement.h" #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include <windows.h> #define _ATL_APARTMENT_THREADED //#define _ATL_STATIC_REGISTRY // #define _ATL_DEBUG_INTERFACES // ATL headers // The ATL headers that come with the platform SDK have bad for scoping #if _MSC_VER >= 1400 #pragma conform(forScope, push, atlhack, off) #endif #include <atlbase.h> //You may derive a class from CComModule and use it if you want to override //something, but do not change the name of _Module extern CComModule _Module; #include <atlcom.h> #include <atlctl.h> #if _MSC_VER >= 1400 #pragma conform(forScope, pop, atlhack) #endif #include <mshtml.h> #include <mshtmhst.h> #include <docobj.h> //#include <winsock2.h> #include <comdef.h> #include <vector> #include <list> #include <string> // New winsock2.h doesn't define this anymore typedef long int32; #define NS_SCRIPTABLE #include "nscore.h" #include "npapi.h" //#include "npupp.h" #include "npfunctions.h" #include "nsID.h" #include <npruntime.h> #include "../variants.h" #include "PropertyList.h" #include "PropertyBag.h" #include "ItemContainer.h" #include "ControlSite.h" #include "ControlSiteIPFrame.h" #include "ControlEventSink.h" extern NPNetscapeFuncs NPNFuncs; // Turn off warnings about debug symbols for templates being too long #pragma warning(disable : 4786) #define TRACE_METHOD(fn) \ { \ ATLTRACE(_T("0x%04x %s()\n"), (int) GetCurrentThreadId(), _T(#fn)); \ } #define TRACE_METHOD_ARGS(fn, pattern, args) \ { \ ATLTRACE(_T("0x%04x %s(") _T(pattern) _T(")\n"), (int) GetCurrentThreadId(), _T(#fn), args); \ } //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #define NS_ASSERTION(x, y) #endif // !defined(AFX_STDAFX_H__1339B542_3453_11D2_93B9_000000000000__INCLUDED)
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include "ControlEventSink.h" CControlEventSink::CControlEventSink() : m_dwEventCookie(0), m_bSubscribed(false), m_EventIID(GUID_NULL), events() { } CControlEventSink::~CControlEventSink() { UnsubscribeFromEvents(); } BOOL CControlEventSink::GetEventSinkIID(IUnknown *pControl, IID &iid, ITypeInfo **typeInfo) { iid = GUID_NULL; if (!pControl) { return E_INVALIDARG; } // IProvideClassInfo2 way is easiest // CComQIPtr<IProvideClassInfo2> classInfo2 = pControl; // if (classInfo2) // { // classInfo2->GetGUID(GUIDKIND_DEFAULT_SOURCE_DISP_IID, &iid); // if (!::IsEqualIID(iid, GUID_NULL)) // { // return TRUE; // } // } // Yuck, the hard way CComQIPtr<IProvideClassInfo> classInfo = pControl; if (!classInfo) { return FALSE; } // Search the class type information for the default source interface // which is the outgoing event sink. CComPtr<ITypeInfo> classTypeInfo; classInfo->GetClassInfo(&classTypeInfo); if (!classTypeInfo) { return FALSE; } TYPEATTR *classAttr = NULL; if (FAILED(classTypeInfo->GetTypeAttr(&classAttr))) { return FALSE; } INT implFlags = 0; for (UINT i = 0; i < classAttr->cImplTypes; i++) { // Search for the interface with the [default, source] attr if (SUCCEEDED(classTypeInfo->GetImplTypeFlags(i, &implFlags)) && implFlags == (IMPLTYPEFLAG_FDEFAULT | IMPLTYPEFLAG_FSOURCE)) { CComPtr<ITypeInfo> eventSinkTypeInfo; HREFTYPE hRefType; if (SUCCEEDED(classTypeInfo->GetRefTypeOfImplType(i, &hRefType)) && SUCCEEDED(classTypeInfo->GetRefTypeInfo(hRefType, &eventSinkTypeInfo))) { TYPEATTR *eventSinkAttr = NULL; if (SUCCEEDED(eventSinkTypeInfo->GetTypeAttr(&eventSinkAttr))) { iid = eventSinkAttr->guid; if (typeInfo) { *typeInfo = eventSinkTypeInfo.p; (*typeInfo)->AddRef(); } eventSinkTypeInfo->ReleaseTypeAttr(eventSinkAttr); } } break; } } classTypeInfo->ReleaseTypeAttr(classAttr); return (!::IsEqualIID(iid, GUID_NULL)); } void CControlEventSink::UnsubscribeFromEvents() { if (m_bSubscribed) { DWORD tmpCookie = m_dwEventCookie; m_dwEventCookie = 0; m_bSubscribed = false; // Unsubscribe and reset - This seems to complete release and destroy us... m_spEventCP->Unadvise(tmpCookie); // Unadvise handles the Release //m_spEventCP.Release(); } } HRESULT CControlEventSink::SubscribeToEvents(IUnknown *pControl) { if (!pControl) { return E_INVALIDARG; } // Throw away any existing connections UnsubscribeFromEvents(); // Grab the outgoing event sink IID which will be used to subscribe // to events via the connection point container. IID iidEventSink; CComPtr<ITypeInfo> typeInfo; if (!GetEventSinkIID(pControl, iidEventSink, &typeInfo)) { return E_FAIL; } // Get the connection point CComQIPtr<IConnectionPointContainer> ccp = pControl; CComPtr<IConnectionPoint> cp; if (!ccp) { return E_FAIL; } // Custom IID m_EventIID = iidEventSink; DWORD dwCookie = 0; if (!ccp || FAILED(ccp->FindConnectionPoint(m_EventIID, &cp)) || FAILED(cp->Advise(this, &dwCookie))) { return E_FAIL; } m_bSubscribed = true; m_spEventCP = cp; m_dwEventCookie = dwCookie; m_spEventSinkTypeInfo = typeInfo; return S_OK; } HRESULT CControlEventSink::InternalInvoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr) { USES_CONVERSION; if (DISPATCH_METHOD != wFlags) { // any other reason to call us?! return S_FALSE; } EventMap::iterator cur = events.find(dispIdMember); if (events.end() != cur) { // invoke this event handler NPVariant result; NPVariant *args = NULL; if (pDispParams->cArgs > 0) { args = (NPVariant *)calloc(pDispParams->cArgs, sizeof(NPVariant)); if (!args) { return S_FALSE; } for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments in reverse order Variant2NPVar(&pDispParams->rgvarg[i], &args[pDispParams->cArgs - i - 1], instance); } } NPObject *globalObj = NULL; NPNFuncs.getvalue(instance, NPNVWindowNPObject, &globalObj); NPIdentifier handler = NPNFuncs.getstringidentifier(W2A((*cur).second)); bool success = NPNFuncs.invoke(instance, globalObj, handler, args, pDispParams->cArgs, &result); NPNFuncs.releaseobject(globalObj); for (unsigned int i = 0; i < pDispParams->cArgs; ++i) { // convert the arguments if (args[i].type == NPVariantType_String) { // was allocated earlier by Variant2NPVar NPNFuncs.memfree((void *)args[i].value.stringValue.UTF8Characters); } } if (!success) { return S_FALSE; } if (pVarResult) { // set the result NPVar2Variant(&result, pVarResult, instance); } NPNFuncs.releasevariantvalue(&result); } return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlEventSink::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { return InternalInvoke(dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr); }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * Brent Booker * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "StdAfx.h" #include <Objsafe.h> #include "ControlSite.h" #include "PropertyBag.h" #include "ControlSiteIPFrame.h" class CDefaultControlSiteSecurityPolicy : public CControlSiteSecurityPolicy { // Test if the specified class id implements the specified category BOOL ClassImplementsCategory(const CLSID & clsid, const CATID &catid, BOOL &bClassExists); public: // Test if the class is safe to host virtual BOOL IsClassSafeToHost(const CLSID & clsid); // Test if the specified class is marked safe for scripting virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists); // Test if the instantiated object is safe for scripting on the specified interface virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid); }; BOOL CDefaultControlSiteSecurityPolicy::ClassImplementsCategory(const CLSID &clsid, const CATID &catid, BOOL &bClassExists) { bClassExists = FALSE; // Test if there is a CLSID entry. If there isn't then obviously // the object doesn't exist and therefore doesn't implement any category. // In this situation, the function returns REGDB_E_CLASSNOTREG. CRegKey key; if (key.Open(HKEY_CLASSES_ROOT, _T("CLSID"), KEY_READ) != ERROR_SUCCESS) { // Must fail if we can't even open this! return FALSE; } LPOLESTR szCLSID = NULL; if (FAILED(StringFromCLSID(clsid, &szCLSID))) { return FALSE; } USES_CONVERSION; CRegKey keyCLSID; LONG lResult = keyCLSID.Open(key, W2CT(szCLSID), KEY_READ); CoTaskMemFree(szCLSID); if (lResult != ERROR_SUCCESS) { // Class doesn't exist return FALSE; } keyCLSID.Close(); // CLSID exists, so try checking what categories it implements bClassExists = TRUE; CComQIPtr<ICatInformation> spCatInfo; HRESULT hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (LPVOID*) &spCatInfo); if (spCatInfo == NULL) { // Must fail if we can't open the category manager return FALSE; } // See what categories the class implements CComQIPtr<IEnumCATID> spEnumCATID; if (FAILED(spCatInfo->EnumImplCategoriesOfClass(clsid, &spEnumCATID))) { // Can't enumerate classes in category so fail return FALSE; } // Search for matching categories BOOL bFound = FALSE; CATID catidNext = GUID_NULL; while (spEnumCATID->Next(1, &catidNext, NULL) == S_OK) { if (::IsEqualCATID(catid, catidNext)) { return TRUE; } } return FALSE; } // Test if the class is safe to host BOOL CDefaultControlSiteSecurityPolicy::IsClassSafeToHost(const CLSID & clsid) { return TRUE; } // Test if the specified class is marked safe for scripting BOOL CDefaultControlSiteSecurityPolicy::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) { // Test the category the object belongs to return ClassImplementsCategory(clsid, CATID_SafeForScripting, bClassExists); } // Test if the instantiated object is safe for scripting on the specified interface BOOL CDefaultControlSiteSecurityPolicy::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) { if (!pObject) { return FALSE; } // Ask the control if its safe for scripting CComQIPtr<IObjectSafety> spObjectSafety = pObject; if (!spObjectSafety) { return FALSE; } DWORD dwSupported = 0; // Supported options (mask) DWORD dwEnabled = 0; // Enabled options // Assume scripting via IDispatch if (FAILED(spObjectSafety->GetInterfaceSafetyOptions( iid, &dwSupported, &dwEnabled))) { // Interface is not safe or failure. return FALSE; } // Test if safe for scripting if (!(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER) { // Object says it is not set to be safe, but supports unsafe calling, // try enabling it and asking again. if(!(dwSupported & INTERFACESAFE_FOR_UNTRUSTED_CALLER) || FAILED(spObjectSafety->SetInterfaceSafetyOptions( iid, INTERFACESAFE_FOR_UNTRUSTED_CALLER, INTERFACESAFE_FOR_UNTRUSTED_CALLER)) || FAILED(spObjectSafety->GetInterfaceSafetyOptions( iid, &dwSupported, &dwEnabled)) || !(dwEnabled & dwSupported) & INTERFACESAFE_FOR_UNTRUSTED_CALLER) { return FALSE; } } return TRUE; } /////////////////////////////////////////////////////////////////////////////// // Constructor CControlSite::CControlSite() { TRACE_METHOD(CControlSite::CControlSite); m_hWndParent = NULL; m_CLSID = CLSID_NULL; m_bSetClientSiteFirst = FALSE; m_bVisibleAtRuntime = TRUE; memset(&m_rcObjectPos, 0, sizeof(m_rcObjectPos)); m_bInPlaceActive = FALSE; m_bUIActive = FALSE; m_bInPlaceLocked = FALSE; m_bWindowless = FALSE; m_bSupportWindowlessActivation = TRUE; m_bSafeForScriptingObjectsOnly = FALSE; m_pSecurityPolicy = GetDefaultControlSecurityPolicy(); // Initialise ambient properties m_nAmbientLocale = 0; m_clrAmbientForeColor = ::GetSysColor(COLOR_WINDOWTEXT); m_clrAmbientBackColor = ::GetSysColor(COLOR_WINDOW); m_bAmbientUserMode = true; m_bAmbientShowHatching = true; m_bAmbientShowGrabHandles = true; m_bAmbientAppearance = true; // 3d // Windowless variables m_hDCBuffer = NULL; m_hRgnBuffer = NULL; m_hBMBufferOld = NULL; m_hBMBuffer = NULL; } // Destructor CControlSite::~CControlSite() { TRACE_METHOD(CControlSite::~CControlSite); Detach(); } // Create the specified control, optionally providing properties to initialise // it with and a name. HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl, LPCWSTR szCodebase, IBindCtx *pBindContext) { TRACE_METHOD(CControlSite::Create); m_CLSID = clsid; m_ParameterList = pl; // See if security policy will allow the control to be hosted if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid)) { return E_FAIL; } // See if object is script safe BOOL checkForObjectSafety = FALSE; if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly) { BOOL bClassExists = FALSE; BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists); if (!bClassExists && szCodebase) { // Class doesn't exist, so allow code below to fetch it } else if (!bIsSafe) { // The class is not flagged as safe for scripting, so // we'll have to create it to ask it if its safe. checkForObjectSafety = TRUE; } } //Now Check if the control version needs to be updated. BOOL bUpdateControlVersion = FALSE; wchar_t *szURL = NULL; DWORD dwFileVersionMS = 0xffffffff; DWORD dwFileVersionLS = 0xffffffff; if(szCodebase) { HKEY hk = NULL; wchar_t wszKey[60] = L""; wchar_t wszData[MAX_PATH]; LPWSTR pwszClsid = NULL; DWORD dwSize = 255; DWORD dwHandle, dwLength, dwRegReturn; DWORD dwExistingFileVerMS = 0xffffffff; DWORD dwExistingFileVerLS = 0xffffffff; BOOL bFoundLocalVerInfo = FALSE; StringFromCLSID(clsid, (LPOLESTR*)&pwszClsid); swprintf(wszKey, L"%s%s%s\0", L"CLSID\\", pwszClsid, L"\\InprocServer32"); if ( RegOpenKeyExW( HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hk ) == ERROR_SUCCESS ) { dwRegReturn = RegQueryValueExW( hk, L"", NULL, NULL, (LPBYTE)wszData, &dwSize ); RegCloseKey( hk ); } if(dwRegReturn == ERROR_SUCCESS) { VS_FIXEDFILEINFO *pFileInfo; UINT uLen; dwLength = GetFileVersionInfoSizeW( wszData , &dwHandle ); LPBYTE lpData = new BYTE[dwLength]; GetFileVersionInfoW(wszData, 0, dwLength, lpData ); bFoundLocalVerInfo = VerQueryValueW( lpData, L"\\", (LPVOID*)&pFileInfo, &uLen ); if(bFoundLocalVerInfo) { dwExistingFileVerMS = pFileInfo->dwFileVersionMS; dwExistingFileVerLS = pFileInfo->dwFileVersionLS; } delete [] lpData; } // Test if the code base ends in #version=a,b,c,d const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#')); if (szHash) { if (wcsnicmp(szHash, L"#version=", 9) == 0) { int a, b, c, d; if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4) { dwFileVersionMS = MAKELONG(b,a); dwFileVersionLS = MAKELONG(d,c); //If local version info was found compare it if(bFoundLocalVerInfo) { if(dwFileVersionMS > dwExistingFileVerMS) bUpdateControlVersion = TRUE; if((dwFileVersionMS == dwExistingFileVerMS) && (dwFileVersionLS > dwExistingFileVerLS)) bUpdateControlVersion = TRUE; } } } szURL = _wcsdup(szCodebase); // Terminate at the hash mark if (szURL) szURL[szHash - szCodebase] = wchar_t('\0'); } else { szURL = _wcsdup(szCodebase); } } CComPtr<IUnknown> spObject; HRESULT hr; //If the control needs to be updated do not call CoCreateInstance otherwise you will lock files //and force a reboot on CoGetClassObjectFromURL if(!bUpdateControlVersion) { // Create the object hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject); if (SUCCEEDED(hr) && checkForObjectSafety) { // Assume scripting via IDispatch if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch))) { return E_FAIL; } // Drop through, success! } } // Do we need to download the control? if ((FAILED(hr) && szCodebase) || (bUpdateControlVersion)) { if (!szURL) return E_OUTOFMEMORY; CComPtr<IBindCtx> spBindContext; CComPtr<IBindStatusCallback> spBindStatusCallback; CComPtr<IBindStatusCallback> spOldBSC; // Create our own bind context or use the one provided? BOOL useInternalBSC = FALSE; if (!pBindContext) { useInternalBSC = TRUE; hr = CreateBindCtx(0, &spBindContext); if (FAILED(hr)) { free(szURL); return hr; } spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this); hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0); if (FAILED(hr)) { free(szURL); return hr; } } else { spBindContext = pBindContext; } //If the version from the CODEBASE value is greater than the installed control //Call CoGetClassObjectFromURL with CLSID_NULL to prevent system change reboot prompt if(bUpdateControlVersion) { hr = CoGetClassObjectFromURL(CLSID_NULL, szCodebase, dwFileVersionMS, dwFileVersionLS, NULL, spBindContext, CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_SERVER, 0, IID_IClassFactory, NULL); } else { hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS, NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown, NULL); } free(szURL); // Handle the internal binding synchronously so the object exists // or an error code is available when the method returns. if (useInternalBSC) { if (MK_S_ASYNCHRONOUS == hr) { m_bBindingInProgress = TRUE; m_hrBindResult = E_FAIL; // Spin around waiting for binding to complete HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); while (m_bBindingInProgress) { MSG msg; // Process pending messages while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (!::GetMessage(&msg, NULL, 0, 0)) { m_bBindingInProgress = FALSE; break; } ::TranslateMessage(&msg); ::DispatchMessage(&msg); } if (!m_bBindingInProgress) break; // Sleep for a bit or the next msg to appear ::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS); } ::CloseHandle(hFakeEvent); // Set the result hr = m_hrBindResult; } // Destroy the bind status callback & context if (spBindStatusCallback) { RevokeBindStatusCallback(spBindContext, spBindStatusCallback); spBindStatusCallback.Release(); spBindContext.Release(); } } //added to create control if (SUCCEEDED(hr)) { // Create the object hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject); if (SUCCEEDED(hr) && checkForObjectSafety) { // Assume scripting via IDispatch if (!m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch))) { hr = E_FAIL; } } } //EOF test code } if (spObject) { m_spObject = spObject; } return hr; } // Attach the created control to a window and activate it HRESULT CControlSite::Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream) { TRACE_METHOD(CControlSite::Attach); if (hwndParent == NULL) { NS_ASSERTION(0, "No parent hwnd"); return E_INVALIDARG; } m_hWndParent = hwndParent; m_rcObjectPos = rcPos; // Object must have been created if (m_spObject == NULL) { return E_UNEXPECTED; } m_spIViewObject = m_spObject; m_spIOleObject = m_spObject; if (m_spIOleObject == NULL) { return E_FAIL; } DWORD dwMiscStatus; m_spIOleObject->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus); if (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST) { m_bSetClientSiteFirst = TRUE; } if (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME) { m_bVisibleAtRuntime = FALSE; } // Some objects like to have the client site as the first thing // to be initialised (for ambient properties and so forth) if (m_bSetClientSiteFirst) { m_spIOleObject->SetClientSite(this); } // If there is a parameter list for the object and no init stream then // create one here. CPropertyBagInstance *pPropertyBag = NULL; if (pInitStream == NULL && m_ParameterList.GetSize() > 0) { CPropertyBagInstance::CreateInstance(&pPropertyBag); pPropertyBag->AddRef(); for (unsigned long i = 0; i < m_ParameterList.GetSize(); i++) { pPropertyBag->Write(m_ParameterList.GetNameOf(i), const_cast<VARIANT *>(m_ParameterList.GetValueOf(i))); } pInitStream = (IPersistPropertyBag *) pPropertyBag; } // Initialise the control from store if one is provided if (pInitStream) { CComQIPtr<IPropertyBag, &IID_IPropertyBag> spPropertyBag = pInitStream; CComQIPtr<IStream, &IID_IStream> spStream = pInitStream; CComQIPtr<IPersistStream, &IID_IPersistStream> spIPersistStream = m_spIOleObject; CComQIPtr<IPersistPropertyBag, &IID_IPersistPropertyBag> spIPersistPropertyBag = m_spIOleObject; if (spIPersistPropertyBag && spPropertyBag) { spIPersistPropertyBag->Load(spPropertyBag, NULL); } else if (spIPersistStream && spStream) { spIPersistStream->Load(spStream); } } else { // Initialise the object if possible CComQIPtr<IPersistStreamInit, &IID_IPersistStreamInit> spIPersistStreamInit = m_spIOleObject; if (spIPersistStreamInit) { spIPersistStreamInit->InitNew(); } } m_spIOleInPlaceObject = m_spObject; m_spIOleInPlaceObjectWindowless = m_spObject; if (m_spIOleInPlaceObject) { SetPosition(m_rcObjectPos); } // In-place activate the object if (m_bVisibleAtRuntime) { DoVerb(OLEIVERB_INPLACEACTIVATE); } // For those objects which haven't had their client site set yet, // it's done here. if (!m_bSetClientSiteFirst) { m_spIOleObject->SetClientSite(this); } return S_OK; } // Unhook the control from the window and throw it all away HRESULT CControlSite::Detach() { TRACE_METHOD(CControlSite::Detach); if (m_spIOleInPlaceObjectWindowless) { m_spIOleInPlaceObjectWindowless.Release(); } if (m_spIOleInPlaceObject) { m_spIOleInPlaceObject->InPlaceDeactivate(); m_spIOleInPlaceObject.Release(); } if (m_spIOleObject) { m_spIOleObject->Close(OLECLOSE_NOSAVE); m_spIOleObject->SetClientSite(NULL); m_spIOleObject.Release(); } m_spIViewObject.Release(); m_spObject.Release(); return S_OK; } // Return the IUnknown of the contained control HRESULT CControlSite::GetControlUnknown(IUnknown **ppObject) { *ppObject = NULL; if (m_spObject) { m_spObject->QueryInterface(IID_IUnknown, (void **) ppObject); } return S_OK; } // Subscribe to an event sink on the control HRESULT CControlSite::Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie) { if (m_spObject == NULL) { return E_UNEXPECTED; } if (pIUnkSink == NULL || pdwCookie == NULL) { return E_INVALIDARG; } return AtlAdvise(m_spObject, pIUnkSink, iid, pdwCookie); } // Unsubscribe event sink from the control HRESULT CControlSite::Unadvise(const IID &iid, DWORD dwCookie) { if (m_spObject == NULL) { return E_UNEXPECTED; } return AtlUnadvise(m_spObject, iid, dwCookie); } // Draw the control HRESULT CControlSite::Draw(HDC hdc) { TRACE_METHOD(CControlSite::Draw); // Draw only when control is windowless or deactivated if (m_spIViewObject) { if (m_bWindowless || !m_bInPlaceActive) { RECTL *prcBounds = (m_bWindowless) ? NULL : (RECTL *) &m_rcObjectPos; m_spIViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdc, prcBounds, NULL, NULL, 0); } } else { // Draw something to indicate no control is there HBRUSH hbr = CreateSolidBrush(RGB(200,200,200)); FillRect(hdc, &m_rcObjectPos, hbr); DeleteObject(hbr); } return S_OK; } // Execute the specified verb HRESULT CControlSite::DoVerb(LONG nVerb, LPMSG lpMsg) { TRACE_METHOD(CControlSite::DoVerb); if (m_spIOleObject == NULL) { return E_FAIL; } return m_spIOleObject->DoVerb(nVerb, lpMsg, this, 0, m_hWndParent, &m_rcObjectPos); } // Set the position on the control HRESULT CControlSite::SetPosition(const RECT &rcPos) { HWND hwnd; TRACE_METHOD(CControlSite::SetPosition); m_rcObjectPos = rcPos; if (m_spIOleInPlaceObject && SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&hwnd))) { m_spIOleInPlaceObject->SetObjectRects(&m_rcObjectPos, &m_rcObjectPos); } return S_OK; } void CControlSite::FireAmbientPropertyChange(DISPID id) { if (m_spObject) { CComQIPtr<IOleControl> spControl = m_spObject; if (spControl) { spControl->OnAmbientPropertyChange(id); } } } void CControlSite::SetAmbientUserMode(BOOL bUserMode) { bool bNewMode = bUserMode ? true : false; if (m_bAmbientUserMode != bNewMode) { m_bAmbientUserMode = bNewMode; FireAmbientPropertyChange(DISPID_AMBIENT_USERMODE); } } /////////////////////////////////////////////////////////////////////////////// // CControlSiteSecurityPolicy implementation CControlSiteSecurityPolicy *CControlSite::GetDefaultControlSecurityPolicy() { static CDefaultControlSiteSecurityPolicy defaultControlSecurityPolicy; return &defaultControlSecurityPolicy; } // Test if the class is safe to host BOOL CControlSite::IsClassSafeToHost(const CLSID & clsid) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsClassSafeToHost(clsid); return TRUE; } // Test if the specified class is marked safe for scripting BOOL CControlSite::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists); return TRUE; } // Test if the instantiated object is safe for scripting on the specified interface BOOL CControlSite::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid) { if (m_pSecurityPolicy) return m_pSecurityPolicy->IsObjectSafeForScripting(pObject, iid); return TRUE; } BOOL CControlSite::IsObjectSafeForScripting(const IID &iid) { return IsObjectSafeForScripting(m_spObject, iid); } /////////////////////////////////////////////////////////////////////////////// // IServiceProvider implementation HRESULT STDMETHODCALLTYPE CControlSite::QueryService(REFGUID guidService, REFIID riid, void** ppv) { if (m_spServiceProvider) return m_spServiceProvider->QueryService(guidService, riid, ppv); return E_NOINTERFACE; } /////////////////////////////////////////////////////////////////////////////// // IDispatch implementation HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr) { if (wFlags & DISPATCH_PROPERTYGET) { CComVariant vResult; switch (dispIdMember) { case DISPID_AMBIENT_APPEARANCE: vResult = CComVariant(m_bAmbientAppearance); break; case DISPID_AMBIENT_FORECOLOR: vResult = CComVariant((long) m_clrAmbientForeColor); break; case DISPID_AMBIENT_BACKCOLOR: vResult = CComVariant((long) m_clrAmbientBackColor); break; case DISPID_AMBIENT_LOCALEID: vResult = CComVariant((long) m_nAmbientLocale); break; case DISPID_AMBIENT_USERMODE: vResult = CComVariant(m_bAmbientUserMode); break; case DISPID_AMBIENT_SHOWGRABHANDLES: vResult = CComVariant(m_bAmbientShowGrabHandles); break; case DISPID_AMBIENT_SHOWHATCHING: vResult = CComVariant(m_bAmbientShowHatching); break; default: return DISP_E_MEMBERNOTFOUND; } VariantCopy(pVarResult, &vResult); return S_OK; } return E_FAIL; } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink implementation void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed) { } void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex) { // Redraw the control InvalidateRect(NULL, FALSE); } void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk) { } void STDMETHODCALLTYPE CControlSite::OnSave(void) { } void STDMETHODCALLTYPE CControlSite::OnClose(void) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSink2 implementation void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk) { } /////////////////////////////////////////////////////////////////////////////// // IAdviseSinkEx implementation void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus) { } /////////////////////////////////////////////////////////////////////////////// // IOleWindow implementation HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd) { *phwnd = m_hWndParent; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode) { return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleClientSite implementation HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer) { if (!ppContainer) return E_INVALIDARG; *ppContainer = m_spContainer; if (*ppContainer) { (*ppContainer)->AddRef(); } return (*ppContainer) ? S_OK : E_NOINTERFACE; } HRESULT STDMETHODCALLTYPE CControlSite::ShowObject(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnShowWindow(/* [in] */ BOOL fShow) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestNewObjectLayout(void) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSite implementation HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void) { m_bInPlaceActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void) { m_bUIActive = TRUE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo) { *lprcPosRect = m_rcObjectPos; *lprcClipRect = m_rcObjectPos; CControlSiteIPFrameInstance *pIPFrame = NULL; CControlSiteIPFrameInstance::CreateInstance(&pIPFrame); pIPFrame->AddRef(); *ppFrame = (IOleInPlaceFrame *) pIPFrame; *ppDoc = NULL; lpFrameInfo->fMDIApp = FALSE; lpFrameInfo->hwndFrame = NULL; lpFrameInfo->haccel = NULL; lpFrameInfo->cAccelEntries = 0; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable) { m_bUIActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect) { if (lprcPosRect == NULL) { return E_INVALIDARG; } SetPosition(m_rcObjectPos); return S_OK; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteEx implementation HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags) { m_bInPlaceActive = TRUE; if (pfNoRedraw) { *pfNoRedraw = FALSE; } if (dwFlags & ACTIVATE_WINDOWLESS) { if (!m_bSupportWindowlessActivation) { return E_INVALIDARG; } m_bWindowless = TRUE; } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw) { m_bInPlaceActive = FALSE; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void) { return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleInPlaceSiteWindowless implementation HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void) { // Allow windowless activation? return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture) { // TODO capture the mouse for the object return S_FALSE; } HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC) { if (phDC == NULL) { return E_INVALIDARG; } // Can't do nested painting if (m_hDCBuffer != NULL) { return E_UNEXPECTED; } m_rcBuffer = m_rcObjectPos; if (pRect != NULL) { m_rcBuffer = *pRect; } m_hBMBuffer = NULL; m_dwBufferFlags = grfFlags; // See if the control wants a DC that is onscreen or offscreen if (m_dwBufferFlags & OLEDC_OFFSCREEN) { m_hDCBuffer = CreateCompatibleDC(NULL); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy); m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer); SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL); // TODO When OLEDC_PAINTBKGND we must draw every site behind this one } else { // TODO When OLEDC_PAINTBKGND we must draw every site behind this one // Get the window DC m_hDCBuffer = GetWindowDC(m_hWndParent); if (m_hDCBuffer == NULL) { // Error return E_OUTOFMEMORY; } // Clip the control so it can't trash anywhere it isn't allowed to draw if (!(m_dwBufferFlags & OLEDC_NODRAW)) { m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer); // TODO Clip out opaque areas of sites behind this one SelectClipRgn(m_hDCBuffer, m_hRgnBuffer); } } *phDC = m_hDCBuffer; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC) { // Release the DC if (hDC == NULL || hDC != m_hDCBuffer) { return E_INVALIDARG; } // Test if the DC was offscreen or onscreen if ((m_dwBufferFlags & OLEDC_OFFSCREEN) && !(m_dwBufferFlags & OLEDC_NODRAW)) { // BitBlt the buffer into the control's object SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL); HDC hdc = GetWindowDC(m_hWndParent); long cx = m_rcBuffer.right - m_rcBuffer.left; long cy = m_rcBuffer.bottom - m_rcBuffer.top; BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY); ::ReleaseDC(m_hWndParent, hdc); } else { // TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one } // Clean up settings ready for next drawing if (m_hRgnBuffer) { SelectClipRgn(m_hDCBuffer, NULL); DeleteObject(m_hRgnBuffer); m_hRgnBuffer = NULL; } SelectObject(m_hDCBuffer, m_hBMBufferOld); if (m_hBMBuffer) { DeleteObject(m_hBMBuffer); m_hBMBuffer = NULL; } // Delete the DC if (m_dwBufferFlags & OLEDC_OFFSCREEN) { ::DeleteDC(m_hDCBuffer); } else { ::ReleaseDC(m_hWndParent, m_hDCBuffer); } m_hDCBuffer = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase) { // Clip the rectangle against the object's size and invalidate it RECT rcI = { 0, 0, 0, 0 }; if (pRect == NULL) { rcI = m_rcObjectPos; } else { IntersectRect(&rcI, &m_rcObjectPos, pRect); } ::InvalidateRect(m_hWndParent, &rcI, fErase); return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase) { if (hRGN == NULL) { ::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase); } else { // Clip the region with the object's bounding area HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos); if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR) { ::InvalidateRgn(m_hWndParent, hrgnClip, fErase); } DeleteObject(hrgnClip); } return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc) { if (prc == NULL) { return E_INVALIDARG; } // Clip the rectangle against the object position RECT rcI = { 0, 0, 0, 0 }; IntersectRect(&rcI, &m_rcObjectPos, prc); *prc = rcI; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult) { if (plResult == NULL) { return E_INVALIDARG; } // Pass the message to the windowless control if (m_bWindowless && m_spIOleInPlaceObjectWindowless) { return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult); } else if (m_spIOleInPlaceObject) { HWND wnd; if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd))) SendMessage(wnd, msg, wParam, lParam); } return S_FALSE; } /////////////////////////////////////////////////////////////////////////////// // IOleControlSite implementation HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock) { m_bInPlaceLocked = fLock; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags) { HRESULT hr = S_OK; if (pPtlHimetric == NULL) { return E_INVALIDARG; } if (pPtfContainer == NULL) { return E_INVALIDARG; } HDC hdc = ::GetDC(m_hWndParent); ::SetMapMode(hdc, MM_HIMETRIC); POINT rgptConvert[2]; rgptConvert[0].x = 0; rgptConvert[0].y = 0; if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER) { rgptConvert[1].x = pPtlHimetric->x; rgptConvert[1].y = pPtlHimetric->y; ::LPtoDP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x); pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y); } else if (dwFlags & XFORMCOORDS_POSITION) { pPtfContainer->x = (float)rgptConvert[1].x; pPtfContainer->y = (float)rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC) { rgptConvert[1].x = (int)(pPtfContainer->x); rgptConvert[1].y = (int)(pPtfContainer->y); ::DPtoLP(hdc, rgptConvert, 2); if (dwFlags & XFORMCOORDS_SIZE) { pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x; pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y; } else if (dwFlags & XFORMCOORDS_POSITION) { pPtlHimetric->x = rgptConvert[1].x; pPtlHimetric->y = rgptConvert[1].y; } else { hr = E_INVALIDARG; } } else { hr = E_INVALIDARG; } ::ReleaseDC(m_hWndParent, hdc); return hr; } HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void) { return E_NOTIMPL; } /////////////////////////////////////////////////////////////////////////////// // IBindStatusCallback implementation HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved, IBinding __RPC_FAR *pib) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress, ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText) { return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError) { m_bBindingInProgress = FALSE; m_hrBindResult = hresult; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF, BINDINFO __RPC_FAR *pbindInfo) { *pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE | BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE; pbindInfo->cbSize = sizeof(BINDINFO); pbindInfo->szExtraInfo = NULL; memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM)); pbindInfo->grfBindInfoF = 0; pbindInfo->dwBindVerb = 0; pbindInfo->szCustomVerb = NULL; return S_OK; } HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF, DWORD dwSize, FORMATETC __RPC_FAR *pformatetc, STGMEDIUM __RPC_FAR *pstgmed) { return E_NOTIMPL; } HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid, IUnknown __RPC_FAR *punk) { return S_OK; } // IWindowForBindingUI HRESULT STDMETHODCALLTYPE CControlSite::GetWindow( /* [in] */ REFGUID rguidReason, /* [out] */ HWND *phwnd) { *phwnd = NULL; return S_OK; }
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@netscape.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef CONTROLSITEIPFRAME_H #define CONTROLSITEIPFRAME_H class CControlSiteIPFrame : public CComObjectRootEx<CComSingleThreadModel>, public IOleInPlaceFrame { public: CControlSiteIPFrame(); virtual ~CControlSiteIPFrame(); HWND m_hwndFrame; BEGIN_COM_MAP(CControlSiteIPFrame) COM_INTERFACE_ENTRY_IID(IID_IOleWindow, IOleInPlaceFrame) COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceUIWindow, IOleInPlaceFrame) COM_INTERFACE_ENTRY(IOleInPlaceFrame) END_COM_MAP() // IOleWindow virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd); virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode); // IOleInPlaceUIWindow implementation virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetBorder(/* [out] */ LPRECT lprectBorder); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths); virtual HRESULT STDMETHODCALLTYPE SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName); // IOleInPlaceFrame implementation virtual HRESULT STDMETHODCALLTYPE InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject); virtual HRESULT STDMETHODCALLTYPE RemoveMenus(/* [in] */ HMENU hmenuShared); virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetStatusText(/* [in] */ LPCOLESTR pszStatusText); virtual HRESULT STDMETHODCALLTYPE EnableModeless(/* [in] */ BOOL fEnable); virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID); }; typedef CComObject<CControlSiteIPFrame> CControlSiteIPFrameInstance; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef IOLECOMMANDIMPL_H #define IOLECOMMANDIMPL_H // Implementation of the IOleCommandTarget interface. The template is // reasonably generic and reusable which is a good thing given how needlessly // complicated this interface is. Blame Microsoft for that and not me. // // To use this class, derive your class from it like this: // // class CComMyClass : public IOleCommandTargetImpl<CComMyClass> // { // ... Ensure IOleCommandTarget is listed in the interface map ... // BEGIN_COM_MAP(CComMyClass) // COM_INTERFACE_ENTRY(IOleCommandTarget) // // etc. // END_COM_MAP() // ... And then later on define the command target table ... // BEGIN_OLECOMMAND_TABLE() // OLECOMMAND_MESSAGE(OLECMDID_PRINT, NULL, ID_PRINT, L"Print", L"Print the page") // OLECOMMAND_MESSAGE(OLECMDID_SAVEAS, NULL, 0, L"SaveAs", L"Save the page") // OLECOMMAND_HANDLER(IDM_EDITMODE, &CGID_MSHTML, EditModeHandler, L"EditMode", L"Switch to edit mode") // END_OLECOMMAND_TABLE() // ... Now the window that OLECOMMAND_MESSAGE sends WM_COMMANDs to ... // HWND GetCommandTargetWindow() const // { // return m_hWnd; // } // ... Now procedures that OLECOMMAND_HANDLER calls ... // static HRESULT _stdcall EditModeHandler(CMozillaBrowser *pThis, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut); // } // // The command table defines which commands the object supports. Commands are // defined by a command id and a command group plus a WM_COMMAND id or procedure, // and a verb and short description. // // Notice that there are two macros for handling Ole Commands. The first, // OLECOMMAND_MESSAGE sends a WM_COMMAND message to the window returned from // GetCommandTargetWindow() (that the derived class must implement if it uses // this macro). // // The second, OLECOMMAND_HANDLER calls a static handler procedure that // conforms to the OleCommandProc typedef. The first parameter, pThis means // the static handler has access to the methods and variables in the class // instance. // // The OLECOMMAND_HANDLER macro is generally more useful when a command // takes parameters or needs to return a result to the caller. // template< class T > class IOleCommandTargetImpl : public IOleCommandTarget { struct OleExecData { const GUID *pguidCmdGroup; DWORD nCmdID; DWORD nCmdexecopt; VARIANT *pvaIn; VARIANT *pvaOut; }; public: typedef HRESULT (_stdcall *OleCommandProc)(T *pT, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut); struct OleCommandInfo { ULONG nCmdID; const GUID *pCmdGUID; ULONG nWindowsCmdID; OleCommandProc pfnCommandProc; wchar_t *szVerbText; wchar_t *szStatusText; }; // Query the status of the specified commands (test if is it supported etc.) virtual HRESULT STDMETHODCALLTYPE QueryStatus(const GUID __RPC_FAR *pguidCmdGroup, ULONG cCmds, OLECMD __RPC_FAR prgCmds[], OLECMDTEXT __RPC_FAR *pCmdText) { T* pT = static_cast<T*>(this); if (prgCmds == NULL) { return E_INVALIDARG; } OleCommandInfo *pCommands = pT->GetCommandTable(); ATLASSERT(pCommands); BOOL bCmdGroupFound = FALSE; BOOL bTextSet = FALSE; // Iterate through list of commands and flag them as supported/unsupported for (ULONG nCmd = 0; nCmd < cCmds; nCmd++) { // Unsupported by default prgCmds[nCmd].cmdf = 0; // Search the support command list for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++) { OleCommandInfo *pCI = &pCommands[nSupported]; if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0) { continue; } bCmdGroupFound = TRUE; if (pCI->nCmdID != prgCmds[nCmd].cmdID) { continue; } // Command is supported so flag it and possibly enable it prgCmds[nCmd].cmdf = OLECMDF_SUPPORTED; if (pCI->nWindowsCmdID != 0) { prgCmds[nCmd].cmdf |= OLECMDF_ENABLED; } // Copy the status/verb text for the first supported command only if (!bTextSet && pCmdText) { // See what text the caller wants wchar_t *pszTextToCopy = NULL; if (pCmdText->cmdtextf & OLECMDTEXTF_NAME) { pszTextToCopy = pCI->szVerbText; } else if (pCmdText->cmdtextf & OLECMDTEXTF_STATUS) { pszTextToCopy = pCI->szStatusText; } // Copy the text pCmdText->cwActual = 0; memset(pCmdText->rgwz, 0, pCmdText->cwBuf * sizeof(wchar_t)); if (pszTextToCopy) { // Don't exceed the provided buffer size size_t nTextLen = wcslen(pszTextToCopy); if (nTextLen > pCmdText->cwBuf) { nTextLen = pCmdText->cwBuf; } wcsncpy(pCmdText->rgwz, pszTextToCopy, nTextLen); pCmdText->cwActual = nTextLen; } bTextSet = TRUE; } break; } } // Was the command group found? if (!bCmdGroupFound) { OLECMDERR_E_UNKNOWNGROUP; } return S_OK; } // Execute the specified command virtual HRESULT STDMETHODCALLTYPE Exec(const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT __RPC_FAR *pvaIn, VARIANT __RPC_FAR *pvaOut) { T* pT = static_cast<T*>(this); BOOL bCmdGroupFound = FALSE; OleCommandInfo *pCommands = pT->GetCommandTable(); ATLASSERT(pCommands); // Search the support command list for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++) { OleCommandInfo *pCI = &pCommands[nSupported]; if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0) { continue; } bCmdGroupFound = TRUE; if (pCI->nCmdID != nCmdID) { continue; } // Send ourselves a WM_COMMAND windows message with the associated // identifier and exec data OleExecData cData; cData.pguidCmdGroup = pguidCmdGroup; cData.nCmdID = nCmdID; cData.nCmdexecopt = nCmdexecopt; cData.pvaIn = pvaIn; cData.pvaOut = pvaOut; if (pCI->pfnCommandProc) { pCI->pfnCommandProc(pT, pCI->pCmdGUID, pCI->nCmdID, nCmdexecopt, pvaIn, pvaOut); } else if (pCI->nWindowsCmdID != 0 && nCmdexecopt != OLECMDEXECOPT_SHOWHELP) { HWND hwndTarget = pT->GetCommandTargetWindow(); if (hwndTarget) { ::SendMessage(hwndTarget, WM_COMMAND, LOWORD(pCI->nWindowsCmdID), (LPARAM) &cData); } } else { // Command supported but not implemented continue; } return S_OK; } // Was the command group found? if (!bCmdGroupFound) { OLECMDERR_E_UNKNOWNGROUP; } return OLECMDERR_E_NOTSUPPORTED; } }; // Macros to be placed in any class derived from the IOleCommandTargetImpl // class. These define what commands are exposed from the object. #define BEGIN_OLECOMMAND_TABLE() \ OleCommandInfo *GetCommandTable() \ { \ static OleCommandInfo s_aSupportedCommands[] = \ { #define OLECOMMAND_MESSAGE(id, group, cmd, verb, desc) \ { id, group, cmd, NULL, verb, desc }, #define OLECOMMAND_HANDLER(id, group, handler, verb, desc) \ { id, group, 0, handler, verb, desc }, #define END_OLECOMMAND_TABLE() \ { 0, &GUID_NULL, 0, NULL, NULL, NULL } \ }; \ return s_aSupportedCommands; \ }; #endif
C++
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef PROPERTYLIST_H #define PROPERTYLIST_H // A simple array class for managing name/value pairs typically fed to controls // during initialization by IPersistPropertyBag class PropertyList { struct Property { BSTR bstrName; VARIANT vValue; } *mProperties; unsigned long mListSize; unsigned long mMaxListSize; bool EnsureMoreSpace() { // Ensure enough space exists to accomodate a new item const unsigned long kGrowBy = 10; if (!mProperties) { mProperties = (Property *) malloc(sizeof(Property) * kGrowBy); if (!mProperties) return false; mMaxListSize = kGrowBy; } else if (mListSize == mMaxListSize) { Property *pNewProperties; pNewProperties = (Property *) realloc(mProperties, sizeof(Property) * (mMaxListSize + kGrowBy)); if (!pNewProperties) return false; mProperties = pNewProperties; mMaxListSize += kGrowBy; } return true; } public: PropertyList() : mProperties(NULL), mListSize(0), mMaxListSize(0) { } ~PropertyList() { } void Clear() { if (mProperties) { for (unsigned long i = 0; i < mListSize; i++) { SysFreeString(mProperties[i].bstrName); // Safe even if NULL VariantClear(&mProperties[i].vValue); } free(mProperties); mProperties = NULL; } mListSize = 0; mMaxListSize = 0; } unsigned long GetSize() const { return mListSize; } const BSTR GetNameOf(unsigned long nIndex) const { if (nIndex > mListSize) { return NULL; } return mProperties[nIndex].bstrName; } const VARIANT *GetValueOf(unsigned long nIndex) const { if (nIndex > mListSize) { return NULL; } return &mProperties[nIndex].vValue; } bool AddOrReplaceNamedProperty(const BSTR bstrName, const VARIANT &vValue) { if (!bstrName) return false; for (unsigned long i = 0; i < GetSize(); i++) { // Case insensitive if (wcsicmp(mProperties[i].bstrName, bstrName) == 0) { return SUCCEEDED( VariantCopy(&mProperties[i].vValue, const_cast<VARIANT *>(&vValue))); } } return AddNamedProperty(bstrName, vValue); } bool AddNamedProperty(const BSTR bstrName, const VARIANT &vValue) { if (!bstrName || !EnsureMoreSpace()) return false; Property *pProp = &mProperties[mListSize]; pProp->bstrName = ::SysAllocString(bstrName); if (!pProp->bstrName) { return false; } VariantInit(&pProp->vValue); if (FAILED(VariantCopy(&pProp->vValue, const_cast<VARIANT *>(&vValue)))) { SysFreeString(pProp->bstrName); return false; } mListSize++; return true; } }; #endif
C++
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adam Lock <adamlock@eircom.net> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #ifndef ITEMCONTAINER_H #define ITEMCONTAINER_H // typedef std::map<tstring, CIUnkPtr> CNamedObjectList; // Class for managing a list of named objects. class CItemContainer : public CComObjectRootEx<CComSingleThreadModel>, public IOleItemContainer { // CNamedObjectList m_cNamedObjectList; public: CItemContainer(); virtual ~CItemContainer(); BEGIN_COM_MAP(CItemContainer) COM_INTERFACE_ENTRY_IID(IID_IParseDisplayName, IOleItemContainer) COM_INTERFACE_ENTRY_IID(IID_IOleContainer, IOleItemContainer) COM_INTERFACE_ENTRY_IID(IID_IOleItemContainer, IOleItemContainer) END_COM_MAP() // IParseDisplayName implementation virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut); // IOleContainer implementation virtual HRESULT STDMETHODCALLTYPE EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum); virtual HRESULT STDMETHODCALLTYPE LockContainer(/* [in] */ BOOL fLock); // IOleItemContainer implementation virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject); virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage); virtual HRESULT STDMETHODCALLTYPE IsRunning(/* [in] */ LPOLESTR pszItem); }; typedef CComObject<CItemContainer> CItemContainerInstance; #endif
C++
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is RSJ Software GmbH code. * * The Initial Developer of the Original Code is * RSJ Software GmbH. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributors: * Ruediger Jungbeck <ruediger.jungbeck@rsj.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <windows.h> #include <winbase.h> // ---------------------------------------------------------------------------- int main (int ArgC, char *ArgV[]) { const char *sourceName; const char *targetName; HANDLE targetHandle; void *versionPtr; DWORD versionLen; int lastError; int ret = 0; if (ArgC < 3) { fprintf(stderr, "Usage: %s <source> <target>\n", ArgV[0]); exit (1); } sourceName = ArgV[1]; targetName = ArgV[2]; if ((versionLen = GetFileVersionInfoSize(sourceName, NULL)) == 0) { fprintf(stderr, "Could not retrieve version len from %s\n", sourceName); exit (2); } if ((versionPtr = calloc(1, versionLen)) == NULL) { fprintf(stderr, "Error allocating temp memory\n"); exit (3); } if (!GetFileVersionInfo(sourceName, NULL, versionLen, versionPtr)) { fprintf(stderr, "Could not retrieve version info from %s\n", sourceName); exit (4); } if ((targetHandle = BeginUpdateResource(targetName, FALSE)) == INVALID_HANDLE_VALUE) { fprintf(stderr, "Could not begin update of %s\n", targetName); free(versionPtr); exit (5); } if (!UpdateResource(targetHandle, RT_VERSION, MAKEINTRESOURCE(VS_VERSION_INFO), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), versionPtr, versionLen)) { lastError = GetLastError(); fprintf(stderr, "Error %d updating resource\n", lastError); ret = 6; } if (!EndUpdateResource(targetHandle, FALSE)) { fprintf(stderr, "Error finishing update\n"); ret = 7; } free(versionPtr); return (ret); }
C++
[Files] Source: {#xbasepath}\Release\npffax.dll; DestDir: {app}; DestName: npffax.dll; Flags: overwritereadonly restartreplace uninsrestartdelete [Registry] Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; Flags: uninsdeletekey Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Description; ValueData: {#MyAppName} {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: ProductName; ValueData: {#MyAppName} {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Path; ValueData: {app}\npffax.dll Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex; ValueType: string; ValueName: Version; ValueData: {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes; ValueType: string; ValueName: Dummy; ValueData: {#xversion} Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex Root: HKLM32; Subkey: SOFTWARE\MozillaPlugins\@itstructures.com/ffactivex\MimeTypes\application/x-itst-activex; ValueType: string; ValueName: "Dummy"; ValueData: "{#xversion}"
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "xdcc.h" #include "xdcc_version.h" #include "irchandler.h" #include "channelhandler.h" #include "xmlstructs.h" #include "dcapifetcher.h" #include "qgproxy.h" #include "updateform.h" #include "loginform.h" #include "settingsform.h" #include <QClipboard> #include <QSharedPointer> #include <QImage> #include <QSettings> #include <QFile> #include <QEvent> #include <QProcess> XDCC::XDCC(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) { ui.setupUi(this); m_Settings = new QSettings("DotaCash", "DCClient X", this); m_Timer = new QTimer(this); connect(m_Timer, SIGNAL(timeout()), this, SLOT(tick())); m_CGProxy = new CGProxy(this); m_LocalServer = new QLocalServer(this); m_LocalServer->listen("DCClientIPC"); connect(m_LocalServer, SIGNAL(newConnection()), this, SLOT(newConnection())); connect(ui.txtChatInput, SIGNAL(returnPressed()), this, SLOT(handleChat())); connect(ui.tabGames, SIGNAL(currentChanged(int)), this, SLOT(tick())); ui.tblPubGames->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive); ui.tblPubGames->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed); ui.tblPubGames->horizontalHeader()->hideSection(2); ui.tblPubGames->horizontalHeader()->hideSection(3); ui.tblPrivGames->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive); ui.tblPrivGames->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed); ui.tblPrivGames->horizontalHeader()->hideSection(2); ui.tblPrivGames->horizontalHeader()->hideSection(3); ui.tblHLGames->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive); ui.tblHLGames->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed); ui.tblHLGames->horizontalHeader()->hideSection(2); ui.tblHLGames->horizontalHeader()->hideSection(3); ui.tblCustomGames->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive); ui.tblCustomGames->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed); ui.tblCustomGames->horizontalHeader()->hideSection(2); ui.tblCustomGames->horizontalHeader()->hideSection(3); ui.tblPlayers->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); ui.tblPlayers->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents); ui.tblPlayers->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents); ui.tblPlayers->horizontalHeader()->setResizeMode(3, QHeaderView::ResizeToContents); ui.tblPlayers->horizontalHeader()->setResizeMode(4, QHeaderView::ResizeToContents); ui.tblPlayers->horizontalHeader()->setResizeMode(5, QHeaderView::ResizeToContents); connect(ui.tblPubGames, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(gameDoubleClicked(int, int))); connect(ui.tblPrivGames, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(gameDoubleClicked(int, int))); connect(ui.tblHLGames, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(gameDoubleClicked(int, int))); connect(ui.tblCustomGames, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(gameDoubleClicked(int, int))); connect(ui.tblPubGames, SIGNAL(cellClicked(int, int)), this, SLOT(gameClicked(int, int))); connect(ui.tblPrivGames, SIGNAL(cellClicked(int, int)), this, SLOT(gameClicked(int, int))); connect(ui.tblHLGames, SIGNAL(cellClicked(int, int)), this, SLOT(gameClicked(int, int))); connect(ui.tblCustomGames, SIGNAL(cellClicked(int, int)), this, SLOT(gameClicked(int, int))); connect(ui.actionCheck_for_updates, SIGNAL(triggered()), this, SLOT(checkForUpdates())); connect(ui.action_About, SIGNAL(triggered()), this, SLOT(showAbout())); connect(ui.action_Options, SIGNAL(triggered()), this, SLOT(showSettings())); m_UpdateForm = new UpdateForm(this); m_LoginForm = new LoginForm(this); m_SettingsForm = new SettingsForm(this); connect(m_UpdateForm, SIGNAL(updateFromURL(QString&)), this, SLOT(updateFromURL(QString&))); connect(m_CGProxy, SIGNAL(joinedGame(QString, QString)), ui.tabChannels, SLOT(joinedGame(QString, QString))); m_Skin = m_Settings->value("Skin", "default").toString(); QFile styleSheet(QString("./skins/%1/style.css").arg(m_Skin)); QString style; if(styleSheet.open(QFile::ReadOnly)) { QTextStream styleIn(&styleSheet); style = styleIn.readAll(); styleSheet.close(); this->setStyleSheet(style); } m_Active = true; qApp->installEventFilter( this ); m_UpdateForm->checkForUpdates(APPCAST_URL, false); m_LoginForm->show(); } XDCC::~XDCC() { while(!m_GameInfos.empty()) { delete m_GameInfos.front(); m_GameInfos.pop_front(); } while(!m_QueueInfos.empty()) { delete m_QueueInfos.front(); m_QueueInfos.pop_front(); } while(!m_PlayerInfos.empty()) { delete m_PlayerInfos.front(); m_PlayerInfos.pop_front(); } delete m_Settings; m_Settings = NULL; delete m_Timer; delete m_CGProxy; delete m_LocalServer; delete m_LoginForm; delete m_SettingsForm; } void XDCC::updateFromURL(QString& url) { QMessageBox::warning(this, "DCClient X Update", tr("DCClient will now restart in order to apply updates.")); m_LoginForm->hide(); QStringList params; params << "--install-dir" << "."; params << "--package-dir" << "updates"; params << "--script" << "updates/file_list.xml"; if(QProcess::startDetached("updater.exe", params)) QApplication::quit(); else QMessageBox::warning(this, tr("Problem"),tr("Unable to start updater, try updating manually by downloading the file: <a href=\"%1\">%2</a>").arg(url).arg(url)); } bool XDCC::eventFilter(QObject *obj, QEvent *event) { bool inactiveRefresh = false; if(m_Settings) inactiveRefresh = m_Settings->value("InactiveRefresh", false).toBool(); static bool inActivationEvent = false; if(!inactiveRefresh) { if (obj == qApp && !inActivationEvent) { if (event->type() == QEvent::ApplicationActivate && !m_Active) { inActivationEvent = true; m_Active = true; this->tick(); m_Timer->start(3000); inActivationEvent = false; } else if (event->type() == QEvent::ApplicationDeactivate && m_Active) { inActivationEvent = true; m_Active = false; m_Timer->stop(); inActivationEvent = false; } } } return QMainWindow::eventFilter(obj, event); } void XDCC::checkForUpdates() { m_UpdateForm->checkForUpdates(APPCAST_URL, true); } void XDCC::showAbout() { QMessageBox::information(this, "DotaCash Client X", tr("DotaCash Client X v%1 by Zephyrix").arg(XDCC_VERSION)); } void XDCC::showSettings() { m_SettingsForm->show(); } void XDCC::gameDoubleClicked(int row, int column) { Q_UNUSED(column); QTableWidget* table; switch(ui.tabGames->currentIndex()) { case 0: table = ui.tblPubGames; break; case 1: table = ui.tblPrivGames; break; case 2: table = ui.tblHLGames; break; case 3: table = ui.tblCustomGames; break; default: return; } if(row < table->rowCount()) { QString txt = table->item(row, 0)->text(); QString id = table->item(row, 2)->text(); QString ip = table->item(row, 3)->text(); QClipboard *cb = QApplication::clipboard(); cb->setText(txt); requestGame(ip); ui.statusBar->showMessage(tr("%1 copied to clipboard and is now visible in LAN screen.").arg(txt), 3000); } } void XDCC::gameClicked(int row, int column) { Q_UNUSED(column); QTableWidget* table; switch(ui.tabGames->currentIndex()) { case 0: table = ui.tblPubGames; break; case 1: table = ui.tblPrivGames; break; case 2: table = ui.tblHLGames; break; case 3: table = ui.tblCustomGames; break; default: return; } if(row < table->rowCount()) { QTableWidgetItem* tblItem = table->item(row, 2); if(tblItem) m_CurrentID = tblItem->text(); tick(); } } void XDCC::newConnection() { m_ClientConnection = m_LocalServer->nextPendingConnection(); connect(m_ClientConnection, SIGNAL(disconnected()), m_ClientConnection, SLOT(deleteLater())); connect(m_ClientConnection, SIGNAL(readyRead()), this, SLOT(readData())); } void XDCC::readData() { QDataStream in(m_ClientConnection); QString arg; in >> arg; activateWindow(); } void XDCC::tick() { if(!m_Active) return; if(!m_CurrentID.isEmpty()) { ApiFetcher* playersFetcher = new ApiFetcher(this); connect(playersFetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parsePlayersXml(QString&))); QString playersUrl = "http://" + API_SERVER + QString("/api/gp.php?u=%1&l=%2").arg(m_SessionID).arg(m_CurrentID); playersFetcher->fetch(playersUrl); } ApiFetcher* gamesFetcher = new ApiFetcher(this); connect(gamesFetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parseGamesXml(QString&))); m_CurrentType = ui.tabGames->currentIndex(); QString gamesUrl = "http://" + API_SERVER + QString("/api/gg.php?u=%1&t=%2").arg(m_SessionID).arg(m_CurrentType+1); gamesFetcher->fetch(gamesUrl); ApiFetcher* queueFetcher = new ApiFetcher(this); connect(queueFetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parseQueueXml(QString&))); QString queueUrl ="http://" + API_SERVER + QString("/api/cq.php?u=%1").arg(m_SessionID); queueFetcher->fetch(queueUrl); } void XDCC::activate() { ui.tabChannels->connectToIrc(this->GetUsername()); connect(ui.tabChannels, SIGNAL(showMessage(QString, int)), this, SLOT(showMessage(QString, int))); connect(m_SettingsForm, SIGNAL(reloadSkin()), ui.tabChannels, SLOT(reloadSkin())); connect(ui.tabChannels, SIGNAL(requestGame(QString)), this , SLOT(requestGame(QString))); this->tick(); m_Timer->start(3000); this->show(); } void XDCC::showMessage(QString message, int timeout=3000) { ui.statusBar->showMessage(message, timeout); } void XDCC::handleChat() { QString curTab = ui.tabChannels->tabText(ui.tabChannels->currentIndex()); QString Message = ui.txtChatInput->text(); ui.txtChatInput->clear(); ui.tabChannels->handleChat(curTab, Message); } void XDCC::parseGamesXml(QString& data) { QXmlStreamReader xml(data); for(int i = 0; i < m_GameInfos.size(); ++i) delete m_GameInfos.at(i); m_GameInfos.clear(); QMap<QString, QString> resultMap; QString currentTag; while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); } else if (xml.isEndElement()) { if(xml.qualifiedName() == "game") { GameInfo* gameInfo = new GameInfo; gameInfo->name = resultMap["name"]; gameInfo->ip = resultMap["ip"]; gameInfo->players = resultMap["players"]; gameInfo->id = resultMap["idLobby"]; m_GameInfos.push_back(gameInfo); resultMap.clear(); } currentTag.clear(); } else if (xml.isCharacters() && !xml.isWhitespace()) { resultMap[currentTag] = xml.text().toString(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } else { QTableWidget* table; switch(m_CurrentType) { case 0: table = ui.tblPubGames; break; case 1: table = ui.tblPrivGames; break; case 2: table = ui.tblHLGames; break; case 3: table = ui.tblCustomGames; break; default: return; } table->setRowCount(m_GameInfos.size()); for(int i = 0; i < m_GameInfos.size(); ++i) { GameInfo* gameInfo = m_GameInfos.at(i); QTableWidgetItem *itemName = new QTableWidgetItem( gameInfo->name ); QTableWidgetItem *itemPlrCount = new QTableWidgetItem( gameInfo->players ); QTableWidgetItem *idx = new QTableWidgetItem( gameInfo->id ); QTableWidgetItem *ip = new QTableWidgetItem( gameInfo->ip ); itemName->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemPlrCount->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemPlrCount->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); table->setItem(i, 0, itemName); table->setItem(i, 1, itemPlrCount); table->setItem(i, 2, idx); table->setItem(i, 3, ip); } } } void XDCC::parseQueueXml(QString& data) { QXmlStreamReader xml(data); QMap<QString, QString> resultMap; QString currentTag; for(int i = 0; i < m_QueueInfos.size(); ++i) delete m_QueueInfos.at(i); m_QueueInfos.clear(); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); } else if (xml.isEndElement()) { if(xml.qualifiedName() == "game") { QueueInfo* queueInfo = new QueueInfo; queueInfo->position = resultMap["Position"]; queueInfo->name = resultMap["GameName"]; m_QueueInfos.push_back(queueInfo); resultMap.clear(); } currentTag.clear(); } else if (xml.isCharacters() && !xml.isWhitespace()) { resultMap[currentTag] = xml.text().toString(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } else { for(int i = 0; i < ui.tblQueue->rowCount(); ++i) delete ui.tblQueue->itemAt(i, 0); ui.tblQueue->setRowCount(m_QueueInfos.size()); for(int i = 0; i < m_QueueInfos.size(); ++i) { QueueInfo* queueInfo = m_QueueInfos.at(i); QTableWidgetItem *itemName = new QTableWidgetItem( queueInfo->name ); itemName->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemName->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui.tblQueue->setItem(i, 0, itemName); } } } void XDCC::parsePlayersXml(QString& data) { QXmlStreamReader xml(data); QMap<QString, QString> resultMap; QString currentTag; for(int i = 0; i < m_PlayerInfos.size(); ++i) delete m_PlayerInfos.at(i); m_PlayerInfos.clear(); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); } else if (xml.isEndElement()) { if(xml.qualifiedName() == "player") { PlayerInfo* playerInfo = new PlayerInfo; playerInfo->name = resultMap["playername"]; playerInfo->slot = resultMap["playerslot"]; playerInfo->realm = resultMap["playerrealm"]; playerInfo->elo = resultMap["playerelo"]; playerInfo->games = resultMap["playergames"]; playerInfo->kdr = resultMap["playerkdr"]; playerInfo->wins = resultMap["playerwins"]; m_PlayerInfos.push_back(playerInfo); resultMap.clear(); } currentTag.clear(); } else if (xml.isCharacters() && !xml.isWhitespace()) { resultMap[currentTag] = xml.text().toString(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } else { for(int i = 0; i < ui.tblPlayers->rowCount(); ++i) { delete ui.tblPlayers->itemAt(i, 0); delete ui.tblPlayers->itemAt(i, 1); delete ui.tblPlayers->itemAt(i, 2); delete ui.tblPlayers->itemAt(i, 3); delete ui.tblPlayers->itemAt(i, 4); delete ui.tblPlayers->itemAt(i, 5); } ui.tblPlayers->setRowCount(m_PlayerInfos.size()); for(int i = 0; i < m_PlayerInfos.size(); ++i) { PlayerInfo* playerInfo = m_PlayerInfos.at(i); QTableWidgetItem *itemName = new QTableWidgetItem( playerInfo->name ); QTableWidgetItem *itemRealm = new QTableWidgetItem( playerInfo->realm ); QTableWidgetItem *itemELO = new QTableWidgetItem( playerInfo->elo ); QTableWidgetItem *itemGames = new QTableWidgetItem( playerInfo->games ); QTableWidgetItem *itemKDR = new QTableWidgetItem( playerInfo->kdr ); QTableWidgetItem *itemWins = new QTableWidgetItem( playerInfo->wins ); itemName->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); //itemName->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemRealm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemRealm->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemELO->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemELO->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemGames->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemGames->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemKDR->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemKDR->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemWins->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemWins->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); QColor color; if(i < 5) // sentinel { if(i % 2) color = QColor(0xFF, 0xEE, 0xEE); else color = QColor(0xFF, 0xF5, 0xF5); } else if(i < 10) // scourge { if(i % 2) color = QColor(0xEE, 0xFF, 0xEE); else color = QColor(0xF5, 0xFF, 0xF5); } else // other cells color = QColor(0xFF, 0xFF, 0xFF); itemName->setBackgroundColor(color); itemRealm->setBackgroundColor(color); itemELO->setBackgroundColor(color); itemGames->setBackgroundColor(color); itemKDR->setBackgroundColor(color); itemWins->setBackgroundColor(color); ui.tblPlayers->setItem(i, 0, itemName); ui.tblPlayers->setItem(i, 1, itemRealm); ui.tblPlayers->setItem(i, 2, itemELO); ui.tblPlayers->setItem(i, 3, itemGames); ui.tblPlayers->setItem(i, 4, itemKDR); ui.tblPlayers->setItem(i, 5, itemWins); } } } void XDCC::requestGame(QString IP) { ApiFetcher* safelistFetcher = new ApiFetcher(this); QString safelistUrl = "http://" + API_SERVER + QString("/api/dccslip.php?u=%1&botip=%2").arg(m_SessionID).arg(IP); safelistFetcher->fetch(safelistUrl); m_CGProxy->requestGame(IP); }
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef FRIENDSHANDLER_H #define FRIENDSHANDLER_H #include "xdcc.h" #include <QObject> #include <QTextBrowser> #include <QListWidget> #define COMMUNI_STATIC #include <Irc> #include <IrcMessage> class FriendsHandler : public QObject { Q_OBJECT public: FriendsHandler(QString nFriendName, QWidget *parent=0); bool GetStatus() { return m_Status; } void SetStatus(bool nStatus) { m_Status = nStatus; } public slots: void joined(const QString); void parted(const QString, const QString); void nickChanged(const QString, const QString); void messageReceived(const QString &origin, const QString &message); void noticeReceived(const QString &origin, const QString &message); signals: void showMessage(QString, MessageType msgType = Normal); void requestGame(QString); private: QString m_FriendName; bool m_Status; }; #endif
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_H #define XDCC_H #ifdef WIN32 #include <Windows.h> #ifdef _DEBUG #include <vld.h> #endif #endif #include "ui_xdcc_main.h" #include <QtGui/QMainWindow> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QXmlStreamReader> #include <QDebug> #include <QMessageBox> #include <QTimer> #include <qlocalserver.h> #include <qlocalsocket.h> #include <QSettings> #include <QStringList> class GameRequester; class CGProxy; class UpdateForm; class LoginForm; class SettingsForm; class ApiFetcher; struct GameInfo; struct QueueInfo; struct PlayerInfo; class XDCC : public QMainWindow { Q_OBJECT public: XDCC(QWidget *parent = 0, Qt::WFlags flags = 0); ~XDCC(); void SetUsername(QString nUsername) { m_Username = nUsername; ui.lbl_Account->setText(m_Username); } void SetScore(quint32 nScore) { m_Score = nScore; ui.lbl_Rating->setText(QString::number(m_Score)); } void SetRank(quint32 nRank) { m_Rank = nRank; ui.lbl_Rank->setText(QString::number(m_Rank)); } void SetSessionID(QString nSessionID) { m_SessionID = nSessionID; } QString GetUsername() { return m_Username; } quint32 GetScore() { return m_Score; } quint32 GetRank() { return m_Rank; } QString GetSessionID() { return m_SessionID; } void activate(); public slots: void tick(); void newConnection(); void readData(); void handleChat(); void gameDoubleClicked(int, int); void gameClicked(int, int); void parseGamesXml(QString&); void parseQueueXml(QString&); void parsePlayersXml(QString&); void showMessage(QString, int); void checkForUpdates(); void showAbout(); void showSettings(); void requestGame(QString); void updateFromURL(QString&); private: Ui::xDCCClass ui; UpdateForm* m_UpdateForm; LoginForm* m_LoginForm; SettingsForm* m_SettingsForm; QSettings* m_Settings; QString m_Username; quint32 m_Score; quint32 m_Rank; QString m_SessionID; QTimer* m_Timer; QLocalServer* m_LocalServer; QLocalSocket* m_ClientConnection; CGProxy* m_CGProxy; QVector<GameInfo*> m_GameInfos; QVector<QueueInfo*> m_QueueInfos; QVector<PlayerInfo*> m_PlayerInfos; int m_CurrentType; QString m_CurrentID; QString m_Skin; bool m_Active; bool eventFilter(QObject *obj, QEvent *event); ApiFetcher* m_PlayersFetcher; ApiFetcher* m_GamesFetcher; ApiFetcher* m_QueueFetcher; }; #endif // XDCC_H
C++
/* Copyright 2010 Trevor Hogan 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. */ #ifndef COMMANDPACKET_H #define COMMANDPACKET_H #include <QByteArray> // // CCommandPacket // class CCommandPacket { private: unsigned char m_PacketType; int m_ID; QByteArray m_Data; public: CCommandPacket( unsigned char nPacketType, int nID, QByteArray nData ); ~CCommandPacket( ); unsigned char GetPacketType( ) { return m_PacketType; } int GetID( ) { return m_ID; } QByteArray GetData( ) { return m_Data; } }; #endif
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_LOGIN_H #define XDCC_LOGIN_H #include <QtGui/QMainWindow> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QXmlStreamReader> #include <QSettings> #include "xdcc.h" #include "ui_xdcc_login.h" class LoginForm : public QDialog { Q_OBJECT public: LoginForm(XDCC* nXDCC, QWidget *parent = 0, Qt::WFlags flags = 0); ~LoginForm(); public slots: void login(); void parseLogin(QString& data); private: Ui::LoginDialog ui; QXmlStreamReader xml; QString Username; QSettings* settings; ApiFetcher* fetcher; XDCC* m_xDCC; }; #endif // XDCC_H
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "loginform.h" #include "xdcc.h" #include "dcapifetcher.h" #include "xdcc_version.h" #include <QDebug> #include <QMap> #include <QMessageBox> LoginForm::LoginForm(XDCC* nxDCC, QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags), m_xDCC(nxDCC) { ui.setupUi(this); connect(ui.btnLogin, SIGNAL(clicked()), this, SLOT(login())); settings = new QSettings("DotaCash", "DCClient X"); QString oldUsername = settings->value("Username").toString(); if(!oldUsername.isEmpty()) { ui.txtUsername->setText(oldUsername); ui.txtPassword->setFocus(); } ui.webNews->setUrl(QUrl("http://" + API_SERVER + "/api/news.php")); } LoginForm::~LoginForm() { delete settings; //delete fetcher; } void LoginForm::login() { QString Password; Username = ui.txtUsername->text(); Password = ui.txtPassword->text(); if(Username.isEmpty() || Password.isEmpty()) return; ui.txtUsername->setReadOnly(true); ui.txtPassword->setReadOnly(true); ui.btnLogin->setDisabled(true); fetcher = new ApiFetcher(); connect(fetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parseLogin(QString&))); QString url = "http://" + API_SERVER + QString("/api/login.php?u=%1&p=%2").arg(Username).arg(Password); fetcher->fetch(url); } void LoginForm::parseLogin(QString& data) { ui.txtUsername->setReadOnly(false); ui.txtPassword->setReadOnly(false); ui.btnLogin->setDisabled(false); xml.clear(); xml.addData(data); QString currentTag; QMap<QString, QString> resultMap; while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); } else if (xml.isEndElement()) { if(xml.name() == "user") break; } else if (xml.isCharacters() && !xml.isWhitespace()) { resultMap[currentTag] = xml.text().toString(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } if(resultMap["result"] == "1") { QString AccountName = resultMap["accountname"]; quint32 Score = resultMap["score"].toUInt(); quint32 Rank = resultMap["rank"].toUInt(); QString SessionID = resultMap["session"]; settings->setValue("Username", Username); m_xDCC->SetUsername(AccountName); m_xDCC->SetScore(Score); m_xDCC->SetRank(Rank); m_xDCC->SetSessionID(SessionID); m_xDCC->activate(); this->hide(); } else { QMessageBox::information(this, "", QString("%1").arg(resultMap["reason"])); } }
C++
/* Copyright 2011 Trevor Hogan 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. Modified by Gene Chen for Qt compatibility */ #include "gameprotocol.h" #include <QtEndian> #include <QDataStream> #include <QDebug> QByteArray CGameProtocol :: ExtractString( QDataStream& ds ) { QByteArray data; // will hold your data when done quint8 byte; do { // ds is your QDataStream already pointing into your file ds >> byte; data.append(byte); } while (byte != 0); return data; } bool CGameProtocol::AssignLength( QByteArray &content ) { // insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3) if( content.size( ) >= 4 && content.size( ) <= 65535 ) { QByteArray LengthBytes; uchar dest[2]; qToLittleEndian<quint16>(content.size(), dest); LengthBytes = QByteArray((char*)dest, 2); content[2] = LengthBytes[0]; content[3] = LengthBytes[1]; return true; } return false; } bool CGameProtocol::ValidateLength( QByteArray &content ) { // verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length quint16 Length; QByteArray LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes.push_back( content[2] ); LengthBytes.push_back( content[3] ); Length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data()); if( Length == content.size( ) ) return true; } return false; } QByteArray CGameProtocol::DecodeStatString( QByteArray &data ) { quint8 Mask; QByteArray Result; for( int i = 0; i < data.size( ); i++ ) { if( ( i % 8 ) == 0 ) Mask = data[i]; else { if( ( Mask & ( 1 << ( i % 8 ) ) ) == 0 ) Result.push_back( data[i] - 1 ); else Result.push_back( data[i] ); } } return Result; } CGameInfo* CGameProtocol :: RECEIVE_W3GS_GAMEINFO ( QByteArray data ) { if( ValidateLength( data ) && data.size( ) >= 16 ) { QDataStream stream(data); quint32 ProductID; quint32 Version; quint32 HostCounter; quint32 EntryKey; QString GameName; QString GamePassword; QByteArray StatString; quint32 SlotsTotal; quint32 MapGameType; quint32 Unknown2; quint32 SlotsOpen; quint32 UpTime; quint16 Port; stream.skipRawData(4); stream.setByteOrder(QDataStream::LittleEndian); stream >> ProductID; stream >> Version; stream >> HostCounter; stream >> EntryKey; GameName = ExtractString(stream); GamePassword = ExtractString(stream); StatString = ExtractString(stream); stream >> SlotsTotal; stream >> MapGameType; stream >> Unknown2; stream >> SlotsOpen; stream >> UpTime; stream >> Port; QByteArray DecStatString = CGameProtocol::DecodeStatString( StatString ); QDataStream ds(DecStatString); ds.setByteOrder(QDataStream::LittleEndian); ds.skipRawData(5); quint16 MapWidth; quint16 MapHeight; ds >> MapWidth; ds >> MapHeight; bool Reliable = true;//((MapWidth == 1984) && (MapHeight == 1984)); return new CGameInfo(ProductID, Version, HostCounter, EntryKey, GameName, GamePassword, StatString, SlotsTotal, MapGameType, Unknown2, SlotsOpen, UpTime, Port, Reliable); } return false; } QByteArray CGameProtocol :: SEND_W3GS_DECREATEGAME( quint32 entrykey ) { QByteArray packet; QDataStream ds(&packet, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)W3GS_DECREATEGAME; ds << (quint16)0; ds << entrykey; AssignLength( packet ); return packet; } QByteArray CGameProtocol :: SEND_W3GS_CHAT_FROM_HOST( quint8 fromPID, QByteArray toPIDs, quint8 flag, quint32 flagExtra, QString message ) { QByteArray packet; QDataStream ds(&packet, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); if( !toPIDs.isEmpty( ) && !message.isEmpty( ) && message.size( ) < 255 ) { ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)W3GS_CHAT_FROM_HOST; ds << (quint16)0; ds << (quint8)toPIDs.size(); // number of receivers ds.writeRawData(toPIDs.data(), toPIDs.length()); ds << fromPID; ds << flag; if(flagExtra != -1) ds << flagExtra; ds.writeRawData(message.toAscii(), message.length()); ds << (quint8)0; AssignLength( packet ); } // DEBUG_Print( "SENT W3GS_CHAT_FROM_HOST" ); // DEBUG_Print( packet ); return packet; } quint32 CGameInfo::NextUniqueGameID = 1; CGameInfo::CGameInfo(quint32 nProductID, quint32 nVersion, quint32 nHostCounter, quint32 nEntryKey, QString nGameName, QString nGamePassword, QByteArray nStatString, quint32 nSlotsTotal, quint32 nMapGameType, quint32 nUnknown2, quint32 nSlotsOpen, quint32 nUpTime, quint16 nPort, bool nReliable) : ProductID(nProductID), Version(nVersion), HostCounter(nHostCounter), EntryKey(nEntryKey), GameName(nGameName), GamePassword(nGamePassword), StatString(nStatString), SlotsTotal(nSlotsTotal), MapGameType(nMapGameType), Unknown2(nUnknown2), SlotsOpen(nSlotsOpen), UpTime(nUpTime), Port(nPort), Reliable(nReliable) { UniqueGameID = NextUniqueGameID++; } QByteArray CGameInfo::GetPacket(quint16 port) { QByteArray packet; QDataStream ds(&packet, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol :: W3GS_GAMEINFO; ds << (quint16)0; ds << ProductID; ds << Version; ds << UniqueGameID; ds << UniqueGameID; ds.writeRawData(GameName.toUtf8(), GameName.length()); ds << (quint8)0; ds.writeRawData(GamePassword.toUtf8(), GamePassword.length()); ds << (quint8)0; ds.writeRawData(StatString.data(), StatString.length()); ds << SlotsTotal; ds << MapGameType; ds << Unknown2; ds << SlotsOpen; ds << UpTime; ds << port; QByteArray LengthBytes; uchar dest[2]; qToLittleEndian<quint16>(packet.size(), dest); LengthBytes = QByteArray((char*)dest, 2); packet[2] = LengthBytes[0]; packet[3] = LengthBytes[1]; return packet; }
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_UPDATE_H #define XDCC_UPDATE_H #include <QtGui/QMainWindow> #include <QSettings> #include "xdcc.h" #include "ui_xdcc_update.h" class DownloaderForm; class UpdateForm : public QDialog { Q_OBJECT public: UpdateForm(QWidget *parent = 0, Qt::WFlags flags = 0); void checkForUpdates(QString appCastURL, bool alwaysShow); public slots: void parseUpdateData(QString& data); void updateNow(); void beginUpdate(); signals: void updateFromURL(QString&); private: Ui_UpdateDialog ui; DownloaderForm* m_Downloader; QMap<QString,QString> m_Latest; ApiFetcher* m_Fetcher; QString m_Version; bool m_AlwaysShow; QMap<QString, QString> UpdateForm::parseUpdateItem(QXmlStreamReader& xml); void addElementDataToMap(QXmlStreamReader& xml, QMap<QString, QString>& map); bool isUpdateRequired(QString& latestVer); }; #endif // XDCC_UPDATEFORM_H
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ui_xdcc_main.h" #include "channelhandler.h" #include "friendshandler.h" #include <qstringlist.h> #include <IrcUtil> IrcHandler::IrcHandler(QWidget* parent) : QTabWidget(parent), irc(0) { connect(this, SIGNAL(tabCloseRequested(int)), this, SLOT(myCloseTab(int))); QString friendsList = QSettings("DotaCash", "DCClient X", this).value("Friends").toString(); if(!friendsList.isEmpty()) m_Friends = friendsList.toLower().split(";"); } void IrcHandler::connectToIrc(QString name) { m_Username = name; irc = new IrcSession(this); connect(irc, SIGNAL(connected()), this, SLOT(connected())); connect(irc, SIGNAL(disconnected()), this, SLOT(disconnected())); connect(irc, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(messageReceived(IrcMessage*))); irc->setHost("irc.dotacash.com"); irc->setPort(6667); irc->setNickName(m_Username); irc->setUserName("dcclient"); irc->setRealName(m_Username); irc->open(); } void IrcHandler::myCloseTab(int idx) { QString channel = this->tabText(idx); if(channel.startsWith("##") || channel == "#dcchat" || channel == "#dotacash") return; else { if(channel.at(0) == '#') irc->sendCommand(IrcCommand::createPart(channel)); removeTabName(channel); } } void IrcHandler::connected() { emit showMessage(tr("Connected to %1").arg("irc.dotacash.com"), 3000); irc->sendCommand(IrcCommand::createJoin("#dcchat")); irc->sendCommand(IrcCommand::createJoin("#dotacash")); irc->sendCommand(IrcCommand::createJoin(QString("##%1").arg(m_Username))); for(int i = 0; i < m_Friends.size(); ++i) irc->sendCommand(IrcCommand::createJoin(QString("##%1").arg(m_Friends.at(i).toLower()))); } void IrcHandler::disconnected() { for(int i = 0; i < m_ChannelMap.size(); ++i) delete m_ChannelMap.values().at(i); m_ChannelMap.clear(); emit showMessage(tr("Disconnected from %1, reconnecting...").arg("irc.dotacash.com"), 3000); } void IrcHandler::handleChat(QString& origin, QString& Message) { if(!irc) return; if(Message.isEmpty()) return; ChannelHandler* channel = m_ChannelMap[origin.toLower()]; if(Message.startsWith('/')) { QStringList Payload = Message.split(' '); QString Command; Command = Payload.at(0); Payload.pop_front(); if((Command == "/join" || Command == "/j") && !Payload.isEmpty()) { QString JoinChan = Payload.at(0); if(JoinChan.startsWith("##")) return; irc->sendCommand(IrcCommand::createJoin(JoinChan)); } else if(Command == "/part" || Command == "/p") { if(Payload.isEmpty()) { if(origin.startsWith("##") || origin == "#dcchat" || origin == "#dotacash") return; irc->sendCommand(IrcCommand::createPart(origin)); removeTabName(origin.toLower()); } else { if(Payload.at(0).startsWith("##") || Payload.at(0) == "#dcchat" || Payload.at(0) == "#dotacash") return; irc->sendCommand(IrcCommand::createPart(Payload.at(0))); } } else if(Command == "/nick" && !Payload.empty()) { irc->sendCommand(IrcCommand::createNick(Payload.at(0))); irc->setNickName(Payload.at(0)); } else if((Command == "/whisper" || Command == "/w") && Payload.size() >= 2) { QString to = Payload.at(0); Payload.pop_front(); QString& txt = Payload.join(" "); ChannelHandler* handler = m_ChannelMap[to.toLower()]; if(!handler) { handler = new ChannelHandler(false, this); m_ChannelMap[to.toLower()] = handler; this->addTab(handler->GetTab(), to); this->setCurrentIndex(this->count() - 1); } handler->showText(QString("&lt;%1&gt; %2").arg(irc->nickName()).arg(txt)); irc->sendCommand(IrcCommand::createMessage(to, txt)); } else if((Command == "/f" || Command == "/friends") && !Payload.isEmpty()) { if(Payload.at(0) == "l" || Payload.at(0) == "list") { int count = m_FriendsMap.size(); if(!count) showTextCurrentTab(tr("You currently have no friends :("), Err); else { showTextCurrentTab(tr("Your friends are:"), Sys); for(int i = 0; i < count; ++i) { QString friendName = m_FriendsMap.keys().at(i); FriendsHandler* myFriend = m_FriendsMap.values().at(i); if(myFriend) { QString status = myFriend->GetStatus() ? tr("online") : tr("offline"); showTextCurrentTab(QString("%1: %2 - %3").arg(i+1).arg(friendName).arg(status), Sys); } } } } else if(Payload.at(0) == "a") { if(Payload.length() == 1) showTextCurrentTab(tr("You need to supply the name of the friend you wish to add to your list."), Err); else { QString friendName = Payload.at(1).toLower(); if(m_Friends.contains(friendName, Qt::CaseInsensitive)) showTextCurrentTab(tr("%1 is already in your friends list.").arg(friendName), Err); else if(friendName.toLower() == m_Username.toLower()) showTextCurrentTab(tr("You cannot add yourself your friends list."), Err); else { m_Friends << friendName; irc->sendCommand(IrcCommand::createJoin(QString("##%1").arg(friendName))); QSettings("DotaCash", "DCClient X", this).setValue("Friends", m_Friends.join(";")); showTextCurrentTab(tr("Added %1 to your friends list.").arg(friendName), Sys); } } } else if(Payload.at(0) == "r") { if(Payload.length() == 1) showTextCurrentTab(tr("You need to supply the name of the friend you wish to remove from your list."), Err); else { QString friendName = Payload.at(1).toLower(); if(!m_Friends.contains(friendName, Qt::CaseInsensitive)) showTextCurrentTab(tr("%1 is not in your friends list.").arg(friendName), Err); else { int idx = m_Friends.indexOf(friendName); m_Friends.removeAt(idx); irc->sendCommand(IrcCommand::createPart(QString("##%1").arg(friendName))); delete m_FriendsMap[friendName.toLower()]; m_FriendsMap.remove(friendName.toLower()); QSettings("DotaCash", "DCClient X", this).setValue("Friends", m_Friends.join(";")); showTextCurrentTab(tr("Removed %1 from your friends list.").arg(friendName), Sys); } } } else if(Payload.at(0) == "m" || Payload.at(0) == "msg") { if(Payload.length() == 1) showTextCurrentTab(tr("What do you want to say?"), Err); else { Payload.pop_front(); QString msg = Payload.join(" "); irc->sendCommand(IrcCommand::createMessage(QString("##%1").arg(m_Username.toLower()), msg)); showTextCurrentTab(tr("You whisper to your friends: %1").arg(msg), Sys); } } } else { showTextCurrentTab(tr("Invalid command."), Err); } } else { irc->sendCommand(IrcCommand::createMessage(origin.toLower(), Message)); showTextCurrentTab(QString("&lt;%1&gt; %2").arg(irc->nickName()).arg(Message)); } } void IrcHandler::joinedChannel(IrcPrefix origin, IrcJoinMessage* joinMsg) { if(!origin.isValid()) return; QString& user = origin.name(); QString& channel = joinMsg->channel(); QString nameLower = channel.toLower(); if(user.toLower() == irc->nickName().toLower()) { if(channel.startsWith("##")) { if(nameLower != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[nameLower.mid(2)]; if(!handler) { handler = new FriendsHandler(channel.mid(2), this); m_FriendsMap[nameLower.mid(2)] = handler; } } } else { ChannelHandler* handler = m_ChannelMap[nameLower]; if(!handler) { handler = new ChannelHandler(channel.startsWith('#'), this); m_ChannelMap[nameLower] = handler; this->addTab(handler->GetTab(), channel); int idx = this->count() - 1; if(nameLower == "#dotacash" || nameLower == "#dcchat") this->tabBar()->setTabButton(idx, QTabBar::RightSide, 0); this->setCurrentIndex(idx); } } } else { if(channel.startsWith("##")) { if(nameLower != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[nameLower.mid(2)]; if(handler) handler->joined(user); } } else { ChannelHandler* handler = m_ChannelMap[nameLower]; if(handler) handler->joined(user); } } } void IrcHandler::partedChannel(IrcPrefix origin, IrcPartMessage* partMsg) { if(!origin.isValid()) return; QString& user = origin.name(); QString& channel = partMsg->channel(); if(user.toLower() == irc->nickName().toLower()) removeTabName(channel.toLower()); else { if(channel.startsWith("##")) { if(channel.toLower() != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[channel.toLower().mid(2)]; if(handler) handler->parted(user, partMsg->reason()); } } else { ChannelHandler* handler = m_ChannelMap[channel.toLower()]; if(handler) handler->parted(user, partMsg->reason()); } } } void IrcHandler::quitMessage(IrcPrefix origin, IrcQuitMessage* quitMsg) { if(!origin.isValid()) return; QString& user = origin.name(); for(QMap<QString, ChannelHandler*>::iterator i = m_ChannelMap.constBegin(); i != m_ChannelMap.constEnd(); ++i) { if(!i.key().isEmpty() && (i.value() != NULL)) i.value()->parted(user, quitMsg->reason()); } for(QMap<QString, FriendsHandler*>::iterator i = m_FriendsMap.constBegin(); i != m_FriendsMap.constEnd(); ++i) { if(!i.key().isEmpty() && (i.value() != NULL)) i.value()->parted(user, quitMsg->reason()); } } void IrcHandler::privateMessage(IrcPrefix origin, IrcPrivateMessage* privMsg) { if(!origin.isValid()) return; QString& user = origin.name(); QString& target = privMsg->target(); QString& message = privMsg->message(); QString txt = QString("<%1> %2").arg(user).arg(message); if(target.startsWith("##")) { if(target.toLower() != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[target.toLower().mid(2)]; if(handler) handler->messageReceived(user, message); } } else { if(target.toLower() != irc->nickName().toLower()) { ChannelHandler* handler = m_ChannelMap[target.toLower()]; if(!handler) { handler = new ChannelHandler(true, this); m_ChannelMap[target.toLower()] = handler; this->addTab(handler->GetTab(), target); this->setCurrentIndex(this->count() - 1); } handler->showText(txt); } else { ChannelHandler* handler = m_ChannelMap[user.toLower()]; if(!handler) { handler = new ChannelHandler(false, this); m_ChannelMap[user.toLower()] = handler; this->addTab(handler->GetTab(), user); this->setCurrentIndex(this->count() - 1); } handler->showText(txt); } } } void IrcHandler::noticeMessage(IrcPrefix origin, IrcNoticeMessage* noticeMsg) { if(!origin.isValid()) return; QString& user = origin.name(); QString& target = noticeMsg->target(); QString& message = noticeMsg->message(); if(target.startsWith("##")) { if(target.toLower() != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[target.toLower().mid(2)]; if(handler) handler->noticeReceived(user, message); } } else if(target.toLower() != irc->nickName().toLower()) { ChannelHandler* handler = m_ChannelMap[target.toLower()]; if(!handler) { handler = new ChannelHandler(target.startsWith('#'), this); m_ChannelMap[target.toLower()] = handler; this->addTab(handler->GetTab(), target); this->setCurrentIndex(this->count() - 1); } handler->noticeReceived(user, message); } else { QString txt = QString("<span class = \"notice\">-%1- %2</span>").arg(user).arg(IrcUtil::messageToHtml(message)); showTextCurrentTab(txt); } } void IrcHandler::nickMessage(IrcPrefix origin, IrcNickMessage* nickMsg) { if(!origin.isValid()) return; QString& user = origin.name(); if(user == irc->nickName()) irc->setNickName(nickMsg->nick()); for(QMap<QString, ChannelHandler*>::iterator i = m_ChannelMap.constBegin(); i != m_ChannelMap.constEnd(); ++i) { if(!i.key().isEmpty() && (i.value() != NULL)) i.value()->nickChanged(user, nickMsg->nick()); } for(QMap<QString, FriendsHandler*>::iterator i = m_FriendsMap.constBegin(); i != m_FriendsMap.constEnd(); ++i) { if(!i.key().isEmpty() && (i.value() != NULL)) i.value()->nickChanged(user, nickMsg->nick()); } } void IrcHandler::numericMessage(IrcNumericMessage* numMsg) { int code = numMsg->code(); IrcMessage* msg = numMsg; switch(code) { case Irc::RPL_NAMREPLY: QString& channel = msg->parameters().at(2).toLower(); QStringList names = msg->parameters().at(3).split(' '); if(channel.startsWith("##")) { if(channel.mid(2) != m_Username.toLower()) { FriendsHandler* target = m_FriendsMap[channel.mid(2)]; if(target) { if(names.contains(channel.mid(2), Qt::CaseInsensitive)) target->SetStatus(true); } } } else { ChannelHandler* target = m_ChannelMap[channel]; if(target) target->UpdateNames(names); } break; } } void IrcHandler::messageReceived(IrcMessage *msg) { switch(msg->type()) { case IrcMessage::Join: joinedChannel(msg->prefix(), dynamic_cast<IrcJoinMessage*>(msg)); break; case IrcMessage::Part: partedChannel(msg->prefix(), dynamic_cast<IrcPartMessage*>(msg)); break; case IrcMessage::Quit: quitMessage(msg->prefix(), dynamic_cast<IrcQuitMessage*>(msg)); break; case IrcMessage::Private: privateMessage(msg->prefix(), dynamic_cast<IrcPrivateMessage*>(msg)); break; case IrcMessage::Notice: noticeMessage(msg->prefix(), dynamic_cast<IrcNoticeMessage*>(msg)); break; case IrcMessage::Nick: nickMessage(msg->prefix(), dynamic_cast<IrcNickMessage*>(msg)); break; case IrcMessage::Numeric: numericMessage(dynamic_cast<IrcNumericMessage*>(msg)); break; } } void IrcHandler::removeTabName(QString name) { ChannelHandler* chan = m_ChannelMap[name.toLower()]; if(chan) { for(int i = 0; i < this->count(); i++) { if(this->tabText(i).toLower() == name.toLower()) { this->removeTab(i); break; } } delete chan; m_ChannelMap.remove(name.toLower()); } } void IrcHandler::showTextCurrentTab(QString message, MessageType msgType) { QString channel = this->tabText(this->currentIndex()); ChannelHandler* handler = m_ChannelMap[channel.toLower()]; QString spanClass; switch(msgType) { case Err: spanClass = "err"; break; case Friends: spanClass = "fmsg"; break; case Sys: spanClass = "sysmsg"; break; case Normal: default: spanClass = "msg"; break; } if(handler) handler->showText(QString("<span class=\"%1\">%2</span>").arg(spanClass).arg(message)); } void IrcHandler::reloadSkin() { for(int i = 0; i < m_ChannelMap.count(); ++i) { ChannelHandler* handler = m_ChannelMap.values().at(i); if(handler) handler->reloadSkin(); } } void IrcHandler::joinedGame(QString ip, QString gameName) { irc->sendCommand(IrcCommand::createNotice(QString("##%1").arg(m_Username.toLower()), QString("xdcc://%1;%2").arg(ip).arg(gameName))); } void IrcHandler::handleUrl(QUrl url) { QString data = url.toString(); if(data.startsWith("xdcc://")) { emit requestGame(data.mid(7)); } }
C++
/* Copyright 2011 Trevor Hogan 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. Modified by Gene Chen for Qt compatibility */ #ifndef GAMEPROTOCOL_H #define GAMEPROTOCOL_H #include <QByteArray> #include <QString> // // CGameProtocol // #define W3GS_HEADER_CONSTANT 247 #define GAME_NONE 0 // this case isn't part of the protocol, it's for internal use only #define GAME_FULL 2 #define GAME_PUBLIC 16 #define GAME_PRIVATE 17 #define GAMETYPE_CUSTOM 1 #define GAMETYPE_BLIZZARD 9 #define PLAYERLEAVE_DISCONNECT 1 #define PLAYERLEAVE_LOST 7 #define PLAYERLEAVE_LOSTBUILDINGS 8 #define PLAYERLEAVE_WON 9 #define PLAYERLEAVE_DRAW 10 #define PLAYERLEAVE_OBSERVER 11 #define PLAYERLEAVE_LOBBY 13 #define PLAYERLEAVE_GPROXY 100 #define REJECTJOIN_FULL 9 #define REJECTJOIN_STARTED 10 #define REJECTJOIN_WRONGPASSWORD 27 class CGameInfo; class CGameProtocol { public: enum Protocol { W3GS_PING_FROM_HOST = 1, // 0x01 W3GS_SLOTINFOJOIN = 4, // 0x04 W3GS_REJECTJOIN = 5, // 0x05 W3GS_PLAYERINFO = 6, // 0x06 W3GS_PLAYERLEAVE_OTHERS = 7, // 0x07 W3GS_GAMELOADED_OTHERS = 8, // 0x08 W3GS_SLOTINFO = 9, // 0x09 W3GS_COUNTDOWN_START = 10, // 0x0A W3GS_COUNTDOWN_END = 11, // 0x0B W3GS_INCOMING_ACTION = 12, // 0x0C W3GS_CHAT_FROM_HOST = 15, // 0x0F W3GS_START_LAG = 16, // 0x10 W3GS_STOP_LAG = 17, // 0x11 W3GS_HOST_KICK_PLAYER = 28, // 0x1C W3GS_REQJOIN = 30, // 0x1E W3GS_LEAVEGAME = 33, // 0x21 W3GS_GAMELOADED_SELF = 35, // 0x23 W3GS_OUTGOING_ACTION = 38, // 0x26 W3GS_OUTGOING_KEEPALIVE = 39, // 0x27 W3GS_CHAT_TO_HOST = 40, // 0x28 W3GS_DROPREQ = 41, // 0x29 W3GS_SEARCHGAME = 47, // 0x2F (UDP/LAN) W3GS_GAMEINFO = 48, // 0x30 (UDP/LAN) W3GS_CREATEGAME = 49, // 0x31 (UDP/LAN) W3GS_REFRESHGAME = 50, // 0x32 (UDP/LAN) W3GS_DECREATEGAME = 51, // 0x33 (UDP/LAN) W3GS_CHAT_OTHERS = 52, // 0x34 W3GS_PING_FROM_OTHERS = 53, // 0x35 W3GS_PONG_TO_OTHERS = 54, // 0x36 W3GS_MAPCHECK = 61, // 0x3D W3GS_STARTDOWNLOAD = 63, // 0x3F W3GS_MAPSIZE = 66, // 0x42 W3GS_MAPPART = 67, // 0x43 W3GS_MAPPARTOK = 68, // 0x44 W3GS_MAPPARTNOTOK = 69, // 0x45 - just a guess, received this packet after forgetting to send a crc in W3GS_MAPPART (f7 45 0a 00 01 02 01 00 00 00) W3GS_PONG_TO_HOST = 70, // 0x46 W3GS_INCOMING_ACTION2 = 72 // 0x48 - received this packet when there are too many actions to fit in W3GS_INCOMING_ACTION }; static bool AssignLength( QByteArray &content ); static bool ValidateLength( QByteArray &content ); static QByteArray ExtractString( QDataStream& ds ); static QByteArray DecodeStatString(QByteArray& ); CGameInfo* RECEIVE_W3GS_GAMEINFO( QByteArray data ); QByteArray SEND_W3GS_CHAT_FROM_HOST( quint8 fromPID, QByteArray toPIDs, quint8 flag, quint32 flagExtra, QString message ); QByteArray SEND_W3GS_DECREATEGAME( quint32 ); }; class CGameInfo { public: static quint32 NextUniqueGameID; public: CGameInfo(quint32 nProductID, quint32 nVersion, quint32 nHostCounter, quint32 nEntryKey, QString nGameName, QString nGamePassword, QByteArray nStatString, quint32 nSlotsTotal, quint32 nMapGameType, quint32 nUnknown2, quint32 nSlotsOpen, quint32 nUpTime, quint16 nPort, bool Reliable); quint32 GetProductID() { return ProductID; } quint32 GetVersion() { return Version; } quint32 GetHostCounter() { return HostCounter; } quint32 GetEntryKey() { return EntryKey; } QString GetGameName() { return GameName; } QString GetGamePassword() { return GamePassword; } QByteArray GetStatString() { return StatString; } quint32 GetSlotsTotal() { return SlotsTotal; } quint32 GetMapGameType() { return MapGameType; } quint32 GetSlotsOpen() { return SlotsOpen; } quint32 GetUpTime() { return UpTime; } quint16 GetPort() { return Port; } QString GetIP() { return IP; } quint32 GetUniqueGameID() { return UniqueGameID; } bool GetReliable() { return Reliable; } void SetProductID( quint32 nProductID ) { ProductID = nProductID; } void SetVersion( quint32 nVersion ) { Version = nVersion; } void SetHostCounter( quint32 nHostCounter ) { HostCounter = nHostCounter; } void SetGameName( QString nGameName ) { GameName = nGameName; } void SetGamePassword( QString nGamePassword ) { GamePassword = nGamePassword; } void SetStatString( QByteArray nStatString ) { StatString = nStatString; } void SetSlotsTotal( quint32 nSlotsTotal ) { SlotsTotal = nSlotsTotal; } void SetMapGameType( quint32 nMapGameType ) { MapGameType = nMapGameType; } void SetSlotsOpen( quint32 nSlotsOpen ) { SlotsOpen = nSlotsOpen; } void SetUpTime( quint32 nUpTime ) { UpTime = nUpTime; } void SetPort( quint16 nPort ) { Port = nPort; } void SetIP( QString nIP ) { IP = nIP; } QByteArray GetPacket(quint16); private: quint32 ProductID; quint32 Version; quint32 HostCounter; quint32 EntryKey; QString GameName; QString GamePassword; QByteArray StatString; quint32 SlotsTotal; quint32 MapGameType; quint32 Unknown2; quint32 SlotsOpen; quint32 UpTime; quint16 Port; QString IP; quint32 UniqueGameID; bool Reliable; }; #endif
C++
/* Copyright 2011 Gene Chen 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. With code derived from gproxy: http://code.google.com/p/gproxyplusplus/ */ #ifndef QGPROXY_H #define QGPROXY_H #include "xdcc.h" #include <QQueue> #include <QTcpSocket> #include <QTcpServer> #include <QUdpSocket> class CGameInfo; class CGameProtocol; class CCommandPacket; class CGPSProtocol; class CGProxy : public QObject { Q_OBJECT public: CGProxy(QWidget* parent=0); ~CGProxy(); void requestGame(QString ip); const QVector<CGameInfo*> getGames() { return games; } public slots: void update(); void readPendingDatagrams(); void newConnection(); void readLocalPackets(); void readServerPackets(); void localDisconnected(); void remoteDisconnected(); signals: void joinedGame(QString, QString); private: QUdpSocket* m_RequesterSocket; QTcpServer* m_LocalServer; QTcpSocket* m_RemoteSocket; QTcpSocket* m_LocalSocket; CGameProtocol* m_GameProtocol; QVector<CGameInfo*> games; CGPSProtocol *m_GPSProtocol; QTimer* timer; QString m_RemoteServerIP; QByteArray m_RemoteBytes; QByteArray m_LocalBytes; QQueue<CCommandPacket *> m_LocalPackets; QQueue<CCommandPacket *> m_RemotePackets; QQueue<CCommandPacket *> m_PacketBuffer; QVector<quint8> m_Laggers; quint32 m_TotalPacketsReceivedFromLocal; quint32 m_TotalPacketsReceivedFromRemote; quint32 m_LastAckTime; quint32 m_LastActionTime; quint32 m_LastConnectionAttemptTime; quint32 m_ReconnectKey; quint32 m_LastBroadcastTime; quint16 m_ListenPort; quint16 m_ReconnectPort; quint8 m_PID; quint8 m_ChatPID; quint8 m_NumEmptyActions; quint8 m_NumEmptyActionsUsed; bool m_ActionReceived; bool m_GameIsReliable; bool m_GameStarted; bool m_Synchronized; bool m_LeaveGameSent; void parsePacket(QString, QByteArray); void processLocalPackets(); void processServerPackets(); void SendLocalChat( QString message ); void SendEmptyAction( ); }; #endif
C++
/* Copyright 2011 Gene Chen 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. With code derived from gproxy: http://code.google.com/p/gproxyplusplus/ */ #include "qgproxy.h" #include "gpsprotocol.h" #include "gameprotocol.h" #include "commandpacket.h" #include <QSettings> #include <QSound> #include <QtEndian> #include <time.h> #ifdef WIN32 #include <windows.h> #endif #ifndef WIN32 #include <sys/time.h> #endif #ifdef __APPLE__ #include <mach/mach_time.h> #endif quint32 GetTicks( ) { #ifdef WIN32 return timeGetTime( ); #elif __APPLE__ uint64_t current = mach_absolute_time( ); static mach_timebase_info_data_t info = { 0, 0 }; // get timebase info if( info.denom == 0 ) mach_timebase_info( &info ); uint64_t elapsednano = current * ( info.numer / info.denom ); // convert ns to ms return elapsednano / 1e6; #else uint32_t ticks; struct timespec t; clock_gettime( 1, &t ); ticks = t.tv_sec * 1000; ticks += t.tv_nsec / 1000000; return ticks; #endif } quint32 GetTime( ) { return GetTicks( ) / 1000; } CGProxy::CGProxy(QWidget* parent) : QObject(parent), m_LocalSocket(0) { m_LocalServer = new QTcpServer(this); m_ListenPort = 6125; while(!m_LocalServer->listen(QHostAddress::LocalHost, m_ListenPort)) m_ListenPort++; connect(m_LocalServer, SIGNAL(newConnection()), this, SLOT(newConnection())); m_RequesterSocket = new QUdpSocket(this); m_RequesterSocket->bind(m_ListenPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint); connect(m_RequesterSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); m_GameProtocol = new CGameProtocol(); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(update())); timer->start(30); m_TotalPacketsReceivedFromLocal = 0; m_TotalPacketsReceivedFromRemote = 0; m_LastConnectionAttemptTime = 0; m_GameIsReliable = false; m_GameStarted = false; m_LeaveGameSent = false; m_ActionReceived = false; m_Synchronized = true; m_ReconnectPort = 0; m_PID = 255; m_ChatPID = 255; m_ReconnectKey = 0; m_NumEmptyActions = 0; m_NumEmptyActionsUsed = 0; m_LastAckTime = 0; m_LastActionTime = 0; m_LastBroadcastTime = 0; m_RemoteSocket = new QTcpSocket(this); connect(m_RemoteSocket, SIGNAL(disconnected()), this, SLOT(remoteDisconnected())); connect(m_RemoteSocket, SIGNAL(readyRead()), this, SLOT(readServerPackets())); } CGProxy::~CGProxy() { m_LocalServer->close(); for( QVector<CGameInfo*>::iterator i = games.begin( ); i != games.end( ); ++i ) m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetUniqueGameID()), QHostAddress::Broadcast, 6112); while( !games.empty( ) ) { delete games.front( ); games.pop_front( ); } while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } while( !m_PacketBuffer.empty( ) ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); } delete m_RemoteSocket; delete m_GameProtocol; } void CGProxy::update() { processLocalPackets(); processServerPackets(); if( !m_RemoteServerIP.isEmpty( ) && m_LocalSocket != NULL && m_LocalSocket->state() == QTcpSocket::ConnectedState ) { if( m_GameIsReliable && m_ActionReceived && GetTime( ) - m_LastActionTime >= 60 ) { if( m_NumEmptyActionsUsed < m_NumEmptyActions ) { SendEmptyAction( ); m_NumEmptyActionsUsed++; } else { SendLocalChat( "GProxy++ ran out of time to reconnect, Warcraft III will disconnect soon." ); qDebug() << ( "[GPROXY] ran out of time to reconnect" ); m_LocalSocket->disconnectFromHost( ); m_RemoteServerIP.clear( ); } m_LastActionTime = GetTime( ); } if( m_RemoteSocket->state() == QTcpSocket::ConnectedState ) { if( m_GameIsReliable && m_ActionReceived && m_ReconnectPort > 0 && GetTime( ) - m_LastAckTime >= 10 ) { m_RemoteSocket->write( m_GPSProtocol->SEND_GPSC_ACK( m_TotalPacketsReceivedFromRemote ) ); m_LastAckTime = GetTime( ); } } if( m_RemoteSocket->state() != QTcpSocket::ConnectingState && m_RemoteSocket->state() != QTcpSocket::ConnectedState ) { if( m_GameIsReliable && m_ActionReceived && m_ReconnectPort > 0 ) { if(GetTime( ) - m_LastConnectionAttemptTime >= 10) { SendLocalChat( "You have been disconnected from the server." ); quint32 TimeRemaining = ( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 - ( GetTime( ) - m_LastActionTime ); if( GetTime( ) - m_LastActionTime > quint32( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 ) TimeRemaining = 0; SendLocalChat( tr("GProxy++ is attempting to reconnect... (%1 seconds remain)").arg(TimeRemaining) ); qDebug() << ( "[GPROXY] attempting to reconnect" ); m_RemoteSocket->reset(); m_RemoteSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_RemoteSocket->connectToHost( m_RemoteServerIP, m_ReconnectPort ); m_LastConnectionAttemptTime = GetTime( ); } } else { m_LocalSocket->disconnectFromHost( ); m_RemoteServerIP.clear( ); } } if( m_RemoteSocket->state() == QTcpSocket::ConnectingState ) { // we are currently attempting to connect if( m_RemoteSocket->waitForConnected(10000) ) { // the connection attempt completed if( m_GameIsReliable && m_ActionReceived ) { // this is a reconnection, not a new connection // if the server accepts the reconnect request it will send a GPS_RECONNECT back requesting a certain number of packets SendLocalChat( "GProxy++ reconnected to the server!" ); SendLocalChat( "==================================================" ); qDebug() << ( "[GPROXY] reconnected to remote server" ); // note: even though we reset the socket when we were disconnected, we haven't been careful to ensure we never queued any data in the meantime // therefore it's possible the socket could have data in the send buffer // this is bad because the server will expect us to send a GPS_RECONNECT message first // so we must clear the send buffer before we continue // note: we aren't losing data here, any important messages that need to be sent have been put in the packet buffer // they will be requested by the server if required //m_RemoteSocket->; m_RemoteSocket->write( m_GPSProtocol->SEND_GPSC_RECONNECT( m_PID, m_ReconnectKey, m_TotalPacketsReceivedFromRemote ) ); // we cannot permit any forwarding of local packets until the game is synchronized again // this will disable forwarding and will be reset when the synchronization is complete m_Synchronized = false; } else qDebug() << ( "[GPROXY] connected to remote server" ); } else if( GetTime( ) - m_LastConnectionAttemptTime >= 10 ) { // the connection attempt timed out (10 seconds) qDebug() << ( "[GPROXY] connect to remote server timed out" ); if( m_GameIsReliable && m_ActionReceived && m_ReconnectPort > 0 ) { quint32 TimeRemaining = ( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 - ( GetTime( ) - m_LastActionTime ); if( GetTime( ) - m_LastActionTime > quint32( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 ) TimeRemaining = 0; SendLocalChat( tr("GProxy++ is attempting to reconnect... (%1 seconds remain)").arg(TimeRemaining) ); qDebug() << ( "[GPROXY] attempting to reconnect" ); m_RemoteSocket->connectToHost( m_RemoteServerIP, m_ReconnectPort ); m_LastConnectionAttemptTime = GetTime( ); } else { m_LocalSocket->disconnectFromHost( ); m_RemoteServerIP.clear( ); } } } } if(!m_LocalSocket || m_LocalSocket->state() != QTcpSocket::ConnectedState || m_RemoteSocket->state() != QTcpSocket::ConnectedState) { if( GetTime( ) - m_LastBroadcastTime >= 3 ) { for(QVector<CGameInfo*>::const_iterator i = games.constBegin(); i != games.constEnd(); ++i) m_RequesterSocket->writeDatagram((*i)->GetPacket(m_ListenPort), QHostAddress::LocalHost, 6112); m_LastBroadcastTime = GetTime( ); } } } void CGProxy::newConnection() { QTcpSocket* newClient = m_LocalServer->nextPendingConnection(); if(m_LocalSocket) { newClient->disconnectFromHost(); return; } while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } while( !m_PacketBuffer.empty( ) ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); } newClient->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_TotalPacketsReceivedFromLocal = 0; m_TotalPacketsReceivedFromRemote = 0; m_LastConnectionAttemptTime = 0; m_GameIsReliable = false; m_GameStarted = false; m_LeaveGameSent = false; m_ActionReceived = false; m_Synchronized = true; m_ReconnectPort = 0; m_PID = 255; m_ChatPID = 255; m_ReconnectKey = 0; m_NumEmptyActions = 0; m_NumEmptyActionsUsed = 0; m_LastAckTime = 0; m_LastActionTime = 0; m_LocalSocket = newClient; connect(m_LocalSocket, SIGNAL(disconnected()), this, SLOT(localDisconnected())); connect(m_LocalSocket, SIGNAL(disconnected()), m_LocalSocket, SLOT(deleteLater())); connect(m_LocalSocket, SIGNAL(readyRead()), this, SLOT(readLocalPackets())); } void CGProxy::localDisconnected() { if( m_GameIsReliable && !m_LeaveGameSent && m_RemoteSocket->state() == QTcpSocket::ConnectedState) { // note: we're not actually 100% ensuring the leavegame message is sent, we'd need to check that DoSend worked, etc... QByteArray LeaveGame; QDataStream ds(&LeaveGame, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol::W3GS_LEAVEGAME; ds << (quint16)0x08; ds << (quint32)PLAYERLEAVE_GPROXY; m_RemoteSocket->write( LeaveGame ); m_RemoteSocket->waitForBytesWritten(); m_LeaveGameSent = true; } m_RemoteSocket->disconnectFromHost(); m_LocalSocket = NULL; m_RemoteBytes.clear(); m_LocalBytes.clear(); while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } while( !m_PacketBuffer.empty( ) ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); } } void CGProxy::remoteDisconnected() { while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } if(m_LeaveGameSent) return; if(m_LocalSocket == NULL || m_LocalSocket->state() != QTcpSocket::ConnectedState) { return; } qDebug() << ( "[GPROXY] disconnected from remote server due to socket error" ); if( m_GameIsReliable && m_ActionReceived && m_ReconnectPort > 0 ) { SendLocalChat( "You have been disconnected from the server due to a socket error." ); quint32 TimeRemaining = ( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 - ( GetTime( ) - m_LastActionTime ); if( GetTime( ) - m_LastActionTime > quint32( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 ) TimeRemaining = 0; SendLocalChat( tr("GProxy++ is attempting to reconnect... (%1 seconds remain)").arg(TimeRemaining) ); qDebug() << ( "[GPROXY] attempting to reconnect" ); m_RemoteSocket->reset(); m_RemoteSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_RemoteSocket->connectToHost( m_RemoteServerIP, m_ReconnectPort ); m_LastConnectionAttemptTime = GetTime( ); } else { m_LocalSocket->disconnectFromHost( ); m_RemoteServerIP.clear( ); } } void CGProxy::readLocalPackets() { QByteArray bytes = m_LocalSocket->readAll(); m_LocalBytes += bytes; while( m_LocalBytes.size( ) >= 4 ) { if( m_LocalBytes.at(0) == W3GS_HEADER_CONSTANT ) { QByteArray LengthBytes; LengthBytes.push_back( m_LocalBytes[2] ); LengthBytes.push_back( m_LocalBytes[3] ); quint16 length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data()); if(length >= 4) { if( m_LocalBytes.size( ) >= length ) { QByteArray data = QByteArray(m_LocalBytes, length); QDataStream ds(data); bool forward = true; if( m_LocalBytes.at(1) == CGameProtocol :: W3GS_CHAT_TO_HOST ) { if( data.size( ) >= 5 ) { int i = 5; char Total = data[4]; if( Total > 0 && data.size( ) >= i + Total ) { i += Total; unsigned char Flag = data[i + 1]; i += 2; QString MessageString; if( Flag == 16 && data.size( ) >= i + 1 ) { ds.skipRawData(i); MessageString = CGameProtocol :: ExtractString(ds); } else if( Flag == 32 && data.size( ) >= i + 5 ) { ds.skipRawData(i+4); MessageString = CGameProtocol :: ExtractString(ds); } QString Command = MessageString.toLower(); if( Command.size( ) >= 1 && Command.at(0) == '/' ) { forward = false; if( Command.size( ) >= 5 && Command.mid( 0, 4 ) == "/re " ) { // if( m_BNET->GetLoggedIn( ) ) // { // //if( !m_BNET->GetReplyTarget( ).empty( ) ) // { // //m_BNET->QueueChatCommand( MessageString.substr( 4 ), m_BNET->GetReplyTarget( ), true ); // SendLocalChat( "Whispered to " + m_BNET->GetReplyTarget( ) + ": " + MessageString.substr( 4 ) ); // } // else // SendLocalChat( "Nobody has whispered you yet." ); // } // else // SendLocalChat( "You are not connected to battle.net." ); } else if( Command == "/status" ) { if( m_LocalSocket ) { if( m_GameIsReliable && m_ReconnectPort > 0 ) SendLocalChat( "GProxy++ disconnect protection: enabled" ); else SendLocalChat( "GProxy++ disconnect protection: disabled" ); } } } } } } if( forward ) { m_LocalPackets.push_back( new CCommandPacket( W3GS_HEADER_CONSTANT, m_LocalBytes[1], data ) ); m_PacketBuffer.push_back( new CCommandPacket( W3GS_HEADER_CONSTANT, m_LocalBytes[1], data ) ); m_TotalPacketsReceivedFromLocal++; } m_LocalBytes = QByteArray(m_LocalBytes.begin( ) + length, m_LocalBytes.size() - length); } else return; } else { qDebug() << "[GPROXY] received invalid packet from local player (bad length)"; m_LeaveGameSent = true; m_LocalSocket->disconnectFromHost( ); return; } } else { qDebug() << ( "[GPROXY] received invalid packet from local player (bad header constant)" ); m_LeaveGameSent = true; m_LocalSocket->disconnectFromHost( ); return; } } processLocalPackets(); } void CGProxy::processLocalPackets() { if(!m_LocalSocket || m_LocalSocket->state() != QTcpSocket::ConnectedState) return; while( !m_LocalPackets.empty( ) ) { CCommandPacket *Packet = m_LocalPackets.front( ); m_LocalPackets.pop_front( ); QByteArray Data = Packet->GetData( ); QDataStream ds(Data); ds.setByteOrder(QDataStream::LittleEndian); if( Packet->GetPacketType( ) == W3GS_HEADER_CONSTANT ) { if( Packet->GetID( ) == CGameProtocol :: W3GS_REQJOIN ) { if( Data.size( ) >= 20 ) { quint32 HostCounter; quint32 EntryKey; quint8 Unknown; quint16 ListenPort; quint32 PeerKey; QString Name; QByteArray Remainder; ds.skipRawData(4); ds >> HostCounter; ds >> EntryKey; ds >> Unknown; ds >> ListenPort; ds >> PeerKey; Name = CGameProtocol::ExtractString(ds); Remainder = QByteArray(Data.begin() + Name.size() + 20, Data.size() - (Name.size() + 20)); if(Remainder.size( ) == 18) { bool GameFound = false; for(QVector<CGameInfo*>::iterator i = games.begin( ); i != games.end( ); ++i) { if((*i)->GetUniqueGameID() == EntryKey) { m_RemoteSocket->reset(); m_RemoteSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_RemoteSocket->connectToHost((*i)->GetIP(), (*i)->GetPort()); if(!m_RemoteSocket->waitForConnected(3000)) { qDebug() << "[GPROXY] player requested to join an expired game. removing from list."; m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetUniqueGameID()), QHostAddress::Broadcast, 6112); delete (*i); games.erase(i); break; } m_LastConnectionAttemptTime = GetTime(); m_RemoteServerIP = (*i)->GetIP(); m_GameIsReliable = (*i)->GetReliable(); m_GameStarted = false; QByteArray DataRewritten; QDataStream ds(&DataRewritten, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)Packet->GetID(); ds << (quint16)0; ds << (*i)->GetHostCounter(); ds << (*i)->GetEntryKey(); ds << (quint8)Unknown; ds << (quint16)ListenPort; ds << (quint32)PeerKey; ds.writeRawData(Name.toUtf8(), Name.length()); ds << (quint8)0; ds.writeRawData(Remainder.data(), Remainder.length()); CGameProtocol::AssignLength(DataRewritten); Data = DataRewritten; GameFound = true; emit joinedGame((*i)->GetIP(), (*i)->GetGameName()); break; } } if(!GameFound) { qDebug() << "[GPROXY] local player requested unknown game (expired?) sending decreate."; m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME(EntryKey), QHostAddress::Broadcast, 6112); m_LocalSocket->disconnectFromHost(); } } else qDebug() << "[GPROXY] received invalid join request from local player (invalid remainder)"; } else qDebug() << "[GPROXY] received invalid join request from local player (too short)"; } else if(Packet->GetID( ) == CGameProtocol :: W3GS_LEAVEGAME) { QByteArray LeaveGame; QDataStream ds(&LeaveGame, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol::W3GS_LEAVEGAME; ds << (quint16)0x08; ds << (quint32)0x00; m_RemoteSocket->write( LeaveGame ); m_RemoteSocket->waitForBytesWritten(); m_LeaveGameSent = true; m_LocalSocket->disconnectFromHost(); } } if( m_RemoteSocket && m_Synchronized ) m_RemoteSocket->write(Data); delete Packet; } } void CGProxy::readServerPackets() { QByteArray bytes = m_RemoteSocket->readAll(); m_RemoteBytes += bytes; while( m_RemoteBytes.size( ) >= 4 ) { if( m_RemoteBytes.at(0) == W3GS_HEADER_CONSTANT || m_RemoteBytes.at(0) == GPS_HEADER_CONSTANT ) { QByteArray LengthBytes; LengthBytes.push_back( m_RemoteBytes[2] ); LengthBytes.push_back( m_RemoteBytes[3] ); quint16 length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data()); if( length >= 4 ) { if( m_RemoteBytes.size( ) >= length ) { QByteArray data = QByteArray(m_RemoteBytes.begin(), length); m_RemotePackets.push_back(new CCommandPacket( m_RemoteBytes.at(0), m_RemoteBytes.at(1), data )); if( m_RemoteBytes.at(0) == W3GS_HEADER_CONSTANT ) m_TotalPacketsReceivedFromRemote++; m_RemoteBytes = QByteArray(m_RemoteBytes.begin( ) + length, m_RemoteBytes.size() - length); } else return; } else { qDebug() << "[GPROXY] received invalid packet from remote server (bad length)"; m_RemoteSocket->disconnectFromHost(); return; } } else { qDebug() << "[GPROXY] received invalid packet from remote server (bad header constant)"; m_RemoteSocket->disconnectFromHost(); return; } } processServerPackets(); } void CGProxy::processServerPackets() { if(!m_LocalSocket || m_LocalSocket->state() != QTcpSocket::ConnectedState || m_RemoteSocket->state() != QTcpSocket::ConnectedState) return; while( !m_RemotePackets.empty( ) ) { CCommandPacket *Packet = m_RemotePackets.front( ); m_RemotePackets.pop_front( ); QByteArray Data = Packet->GetData( ); QDataStream ds(Data); ds.setByteOrder(QDataStream::LittleEndian); ds.skipRawData(4); if( Packet->GetPacketType( ) == W3GS_HEADER_CONSTANT ) { if( Packet->GetID( ) == CGameProtocol :: W3GS_SLOTINFOJOIN ) { if( Data.size( ) >= 6 ) { quint16 SlotInfoSize; ds >> SlotInfoSize; if( Data.size( ) >= 7 + SlotInfoSize ) m_ChatPID = Data[6 + SlotInfoSize]; } // send a GPS_INIT packet // if the server doesn't recognize it (e.g. it isn't GHost++) we should be kicked qDebug() << ( "[GPROXY] join request accepted by remote server" ); if( m_GameIsReliable ) { qDebug() << ( "[GPROXY] detected reliable game, starting GPS handshake" ); m_RemoteSocket->write( m_GPSProtocol->SEND_GPSC_INIT( 1 ) ); } else qDebug() << ( "[GPROXY] detected standard game, disconnect protection disabled" ); } else if( Packet->GetID( ) == CGameProtocol :: W3GS_COUNTDOWN_END ) { if( m_GameIsReliable && m_ReconnectPort > 0 ) qDebug() << ( "[GPROXY] game started, disconnect protection enabled" ); else { if( m_GameIsReliable ) qDebug() << ( "[GPROXY] game started but GPS handshake not complete, disconnect protection disabled" ); else qDebug() << ( "[GPROXY] game started" ); } for( QVector<CGameInfo*>::iterator i = games.begin( ); i != games.end( ); ++i ) m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetUniqueGameID()), QHostAddress::Broadcast, 6112); while( !games.empty( ) ) { delete games.front( ); games.pop_front( ); } QSettings settings("DotaCash", "DCClient X"); if(settings.value("GameStartedSound", true).toBool()) QSound::play("./sounds/GameStarted.wav"); m_GameStarted = true; } else if( Packet->GetID( ) == CGameProtocol :: W3GS_INCOMING_ACTION ) { if( m_GameIsReliable ) { // we received a game update which means we can reset the number of empty actions we have to work with // we also must send any remaining empty actions now // note: the lag screen can't be up right now otherwise the server made a big mistake, so we don't need to check for it QByteArray EmptyAction; EmptyAction.append( (char)0xF7 ); EmptyAction.append( (char)0x0C ); EmptyAction.append( (char)0x06 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); for( unsigned char i = m_NumEmptyActionsUsed; i < m_NumEmptyActions; i++ ) m_LocalSocket->write( EmptyAction ); m_NumEmptyActionsUsed = 0; } m_ActionReceived = true; m_LastActionTime = GetTime( ); } else if( Packet->GetID( ) == CGameProtocol :: W3GS_START_LAG ) { if( m_GameIsReliable ) { QByteArray Data = Packet->GetData( ); if( Data.size( ) >= 5 ) { quint8 NumLaggers = Data[4]; if( Data.size( ) == 5 + NumLaggers * 5 ) { for( quint8 i = 0; i < NumLaggers; i++ ) { bool LaggerFound = false; for( QVector<quint8>::iterator j = m_Laggers.begin( ); j != m_Laggers.end( ); j++ ) { if( *j == Data[5 + i * 5] ) LaggerFound = true; } if( LaggerFound ) qDebug() << ( "[GPROXY] warning - received start_lag on known lagger" ); else m_Laggers.push_back( Data[5 + i * 5] ); } } else qDebug() << ( "[GPROXY] warning - unhandled start_lag (2)" ); } else qDebug() << ( "[GPROXY] warning - unhandled start_lag (1)" ); } } else if( Packet->GetID( ) == CGameProtocol :: W3GS_STOP_LAG ) { if( m_GameIsReliable ) { QByteArray Data = Packet->GetData( ); if( Data.size( ) == 9 ) { bool LaggerFound = false; for( QVector<quint8>::iterator i = m_Laggers.begin( ); i != m_Laggers.end( ); ) { if( *i == Data[4] ) { i = m_Laggers.erase( i ); LaggerFound = true; } else i++; } if( !LaggerFound ) qDebug() << ( "[GPROXY] warning - received stop_lag on unknown lagger" ); } else qDebug() << ( "[GPROXY] warning - unhandled stop_lag" ); } } else if( Packet->GetID( ) == CGameProtocol :: W3GS_INCOMING_ACTION2 ) { if( m_GameIsReliable ) { // we received a fractured game update which means we cannot use any empty actions until we receive the subsequent game update // we also must send any remaining empty actions now // note: this means if we get disconnected right now we can't use any of our buffer time, which would be very unlucky // it still gives us 60 seconds total to reconnect though // note: the lag screen can't be up right now otherwise the server made a big mistake, so we don't need to check for it QByteArray EmptyAction; EmptyAction.append( (char)0xF7 ); EmptyAction.append( (char)0x0C ); EmptyAction.append( (char)0x06 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); for( unsigned char i = m_NumEmptyActionsUsed; i < m_NumEmptyActions; i++ ) m_LocalSocket->write( EmptyAction ); m_NumEmptyActionsUsed = m_NumEmptyActions; } } // forward the data m_LocalSocket->write( Packet->GetData( ) ); // we have to wait until now to send the status message since otherwise the slotinfojoin itself wouldn't have been forwarded if( Packet->GetID( ) == CGameProtocol :: W3GS_SLOTINFOJOIN ) { if( m_GameIsReliable ) SendLocalChat( tr("This is a reliable game. Requesting GProxy++ disconnect protection from server...") ); else SendLocalChat( tr("This is an unreliable game. GProxy++ disconnect protection is disabled.") ); } } else if( Packet->GetPacketType( ) == GPS_HEADER_CONSTANT ) { if( m_GameIsReliable ) { QByteArray Data = Packet->GetData( ); if( Packet->GetID( ) == CGPSProtocol :: GPS_INIT && Data.size( ) == 12 ) { ds >> m_ReconnectPort; ds >> m_PID; ds >> m_ReconnectKey; ds >> m_NumEmptyActions; SendLocalChat( tr("GProxy++ disconnect protection is ready (%1 second buffer).").arg( ( m_NumEmptyActions + 1 ) * 60 ) ); } else if( Packet->GetID( ) == CGPSProtocol :: GPS_RECONNECT && Data.size( ) == 8 ) { quint32 LastPacket; ds >> LastPacket; quint32 PacketsAlreadyUnqueued = m_TotalPacketsReceivedFromLocal - m_PacketBuffer.size( ); if( LastPacket > PacketsAlreadyUnqueued ) { int PacketsToUnqueue = LastPacket - PacketsAlreadyUnqueued; if( PacketsToUnqueue > m_PacketBuffer.size( ) ) { qDebug() << ( "[GPROXY] received GPS_RECONNECT with last packet > total packets sent" ); PacketsToUnqueue = m_PacketBuffer.size( ); } while( PacketsToUnqueue > 0 ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); PacketsToUnqueue--; } } // send remaining packets from buffer, preserve buffer // note: any packets in m_LocalPackets are still sitting at the end of this buffer because they haven't been processed yet // therefore we must check for duplicates otherwise we might (will) cause a desync QQueue<CCommandPacket *> TempBuffer; while( !m_PacketBuffer.empty( ) ) { if( m_PacketBuffer.size( ) > m_LocalPackets.size( ) ) m_RemoteSocket->write( m_PacketBuffer.front( )->GetData( ) ); TempBuffer.push_back( m_PacketBuffer.front( ) ); m_PacketBuffer.pop_front( ); } m_PacketBuffer = TempBuffer; // we can resume forwarding local packets again // doing so prior to this point could result in an out-of-order stream which would probably cause a desync m_Synchronized = true; } else if( Packet->GetID( ) == CGPSProtocol :: GPS_ACK && Data.size( ) == 8 ) { quint32 LastPacket; ds >> LastPacket; quint32 PacketsAlreadyUnqueued = m_TotalPacketsReceivedFromLocal - m_PacketBuffer.size( ); if( LastPacket > PacketsAlreadyUnqueued ) { int PacketsToUnqueue = LastPacket - PacketsAlreadyUnqueued; if( PacketsToUnqueue > m_PacketBuffer.size( ) ) { qDebug() << ( "[GPROXY] received GPS_ACK with last packet > total packets sent" ); PacketsToUnqueue = m_PacketBuffer.size( ); } while( PacketsToUnqueue > 0 ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); PacketsToUnqueue--; } } } else if( Packet->GetID( ) == CGPSProtocol :: GPS_REJECT && Data.size( ) == 8 ) { quint32 Reason; ds >> Reason; if( Reason == REJECTGPS_INVALID ) qDebug() << ( "[GPROXY] rejected by remote server: invalid data" ); else if( Reason == REJECTGPS_NOTFOUND ) qDebug() << ( "[GPROXY] rejected by remote server: player not found in any running games" ); m_LocalSocket->disconnectFromHost( ); } } } delete Packet; } } void CGProxy::requestGame(QString host) { m_RequesterSocket->writeDatagram(QByteArray("rcon_broadcast"), QHostAddress(host), 6969); } void CGProxy::readPendingDatagrams() { while (m_RequesterSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(m_RequesterSocket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; m_RequesterSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); parsePacket(sender.toString(), datagram); } } void CGProxy::parsePacket(QString IP, QByteArray datagram) { if( datagram.at(0) == W3GS_HEADER_CONSTANT ) { if( datagram.at(1) == CGameProtocol :: W3GS_GAMEINFO ) { CGameInfo* gameInfo = m_GameProtocol->RECEIVE_W3GS_GAMEINFO(datagram); gameInfo->SetIP(IP); bool DuplicateFound = false; for(QVector<CGameInfo*>::iterator i = games.begin(); i != games.end(); ++i) { if((*i)->GetIP() == IP && (*i)->GetPort() == gameInfo->GetPort()) { m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetUniqueGameID()), QHostAddress::Broadcast, 6112); delete *i; *i = gameInfo; DuplicateFound = true; break; } } if(!DuplicateFound) games.push_back(gameInfo); for(QVector<CGameInfo*>::const_iterator i = games.constBegin(); i != games.constEnd(); ++i) m_RequesterSocket->writeDatagram((*i)->GetPacket(m_ListenPort), QHostAddress::LocalHost, 6112); m_LastBroadcastTime = GetTime( ); } } } void CGProxy::SendLocalChat( QString message ) { QByteArray toPIDs; toPIDs.append(m_ChatPID); if( m_LocalSocket ) { if( m_GameStarted ) { if( message.size( ) > 127 ) message = message.left(127); m_LocalSocket->write( m_GameProtocol->SEND_W3GS_CHAT_FROM_HOST( m_ChatPID, toPIDs, 32, 0, message ) ); } else { if( message.size( ) > 254 ) message = message.left(254); m_LocalSocket->write( m_GameProtocol->SEND_W3GS_CHAT_FROM_HOST( m_ChatPID, toPIDs, 16, -1, message ) ); } } } void CGProxy::SendEmptyAction( ) { // we can't send any empty actions while the lag screen is up // so we keep track of who the lag screen is currently showing (if anyone) and we tear it down, send the empty action, and put it back up for( QVector<quint8>::iterator i = m_Laggers.begin( ); i != m_Laggers.end( ); i++ ) { QByteArray StopLag; QDataStream ds(&StopLag, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol::W3GS_STOP_LAG; ds << (quint16)9; ds << (quint8)0; ds << (quint8)*i; ds << (quint32)60000; m_LocalSocket->write( StopLag ); } QByteArray EmptyAction; EmptyAction.append( (char)0xF7 ); EmptyAction.append( (char)0x0C ); EmptyAction.append( (char)0x06 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); m_LocalSocket->write( EmptyAction ); if( !m_Laggers.empty( ) ) { QByteArray StartLag; QDataStream ds(&StartLag, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol::W3GS_START_LAG; ds << (quint16)0; ds << (quint8)m_Laggers.size(); for( QVector<quint8>::iterator i = m_Laggers.begin( ); i != m_Laggers.end( ); i++ ) { // using a lag time of 60000 ms means the counter will start at zero // hopefully warcraft 3 doesn't care about wild variations in the lag time in subsequent packets ds << (quint8)*i; ds << (quint32)60000; } CGameProtocol::AssignLength(StartLag); m_LocalSocket->write( StartLag ); } }
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "dcapifetcher.h" ApiFetcher::ApiFetcher(QWidget* parent) : QObject(parent), currentReply(0) { connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*))); connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(deleteLater())); } ApiFetcher::~ApiFetcher() { } void ApiFetcher::fetch(QString url) { QUrl nUrl(url); get(nUrl); } void ApiFetcher::get(const QUrl &url) { QNetworkRequest request(url); if (currentReply) { currentReply->disconnect(this); currentReply->deleteLater(); } currentReply = manager.get(request); connect(currentReply, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(currentReply, SIGNAL(metaDataChanged()), this, SLOT(metaDataChanged())); connect(currentReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); } void ApiFetcher::metaDataChanged() { QUrl redirectionTarget = currentReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (redirectionTarget.isValid()) { get(redirectionTarget); } } void ApiFetcher::readyRead() { int statusCode = currentReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode >= 200 && statusCode < 300) { QByteArray data = currentReply->readAll(); QString str(data); result += str; } } void ApiFetcher::error(QNetworkReply::NetworkError) { qWarning("apifetcher network error"); currentReply->disconnect(this); currentReply->deleteLater(); currentReply = 0; } void ApiFetcher::finished(QNetworkReply *reply) { Q_UNUSED(reply); emit fetchComplete(result); }
C++
/* Copyright 2010 Trevor Hogan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "gpsprotocol.h" #include <QtEndian> // // CGPSProtocol // CGPSProtocol :: CGPSProtocol( ) { } CGPSProtocol :: ~CGPSProtocol( ) { } /////////////////////// // RECEIVE FUNCTIONS // /////////////////////// //////////////////// // SEND FUNCTIONS // //////////////////// QByteArray CGPSProtocol :: SEND_GPSC_INIT( quint32 version ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_INIT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&version, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSC_RECONNECT( quint8 PID, quint32 reconnectKey, quint32 lastPacket ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_RECONNECT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char)PID ); packet.append( (char*)&reconnectKey, 4 ); packet.append( (char*)&lastPacket, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSC_ACK( quint32 lastPacket ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_ACK ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&lastPacket, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSS_INIT( quint16 reconnectPort, quint8 PID, quint32 reconnectKey, quint8 numEmptyActions ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_INIT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&reconnectPort, 2 ); packet.append( (char)PID ); packet.append( (char*)&reconnectKey, 4 ); packet.push_back( numEmptyActions ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSS_RECONNECT( quint32 lastPacket ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_RECONNECT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&lastPacket, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSS_ACK( quint32 lastPacket ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_ACK ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&lastPacket, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSS_REJECT( quint32 reason ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_REJECT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&reason, 4 ); AssignLength( packet ); return packet; } ///////////////////// // OTHER FUNCTIONS // ///////////////////// bool CGPSProtocol :: AssignLength( QByteArray &content ) { // insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3) if( content.size( ) >= 4 && content.size( ) <= 65535 ) { QByteArray LengthBytes; uchar dest[2]; qToLittleEndian<quint16>(content.size(), dest); LengthBytes = QByteArray((char*)dest, 2); content[2] = LengthBytes[0]; content[3] = LengthBytes[1]; return true; } return false; } bool CGPSProtocol :: ValidateLength( QByteArray &content ) { // verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length quint16 Length; QByteArray LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes.push_back( content[2] ); LengthBytes.push_back( content[3] ); Length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data()); if( Length == content.size( ) ) return true; } return false; }
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef IRCHANDLER_H #define IRCHANDLER_H #include <QTabWidget> #include <QMap> #include <QStringList> #include <QUrl> #define COMMUNI_STATIC #include <Irc> #include <IrcMessage> #include <IrcSession> #include <IrcCommand> #include <ircprefix.h> class ChannelHandler; class FriendsHandler; enum MessageType { Normal, Sys, Err, Friends }; class IrcHandler : public QTabWidget { Q_OBJECT public: IrcHandler(QWidget* parent); void connectToIrc(QString name); void part(QString channel) { if(irc) irc->sendCommand(IrcCommand::createPart(channel)); } public slots: void connected(); void disconnected(); void messageReceived(IrcMessage *message); void handleChat(QString&, QString&); void myCloseTab(int); void showTextCurrentTab(QString, MessageType=Normal); void reloadSkin(); void joinedGame(QString, QString); void handleUrl(QUrl); signals: void showMessage(QString, int timeout=3000); void requestGame(QString); private: IrcSession *irc; QMap<QString, ChannelHandler*> m_ChannelMap; QMap<QString, FriendsHandler*> m_FriendsMap; QString m_Username; QStringList m_Friends; void removeTabName(QString name); void joinedChannel(IrcPrefix origin, IrcJoinMessage* joinMsg); void partedChannel(IrcPrefix origin, IrcPartMessage* partMsg); void quitMessage(IrcPrefix origin, IrcQuitMessage* quitMsg); void privateMessage(IrcPrefix origin, IrcPrivateMessage* privMsg); void noticeMessage(IrcPrefix origin, IrcNoticeMessage* noticeMsg); void nickMessage(IrcPrefix origin, IrcNickMessage* nickMsg); void numericMessage(IrcNumericMessage* numMsg); }; #endif
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "updateform.h" #include "downloaderform.h" #include "dcapifetcher.h" #include "xdcc_version.h" #include <QDir> UpdateForm::UpdateForm(QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags) { ui.setupUi(this); connect(ui.okButton, SIGNAL(clicked()), this, SLOT(updateNow())); m_Version = QSettings("DotaCash", "DCClient X").value("version", XDCC_VERSION).toString(); m_Downloader = new DownloaderForm(this); connect(m_Downloader, SIGNAL(downloadsComplete()), this, SLOT(beginUpdate())); } void UpdateForm::updateNow() { QDir updateFolder("./updates/"); QStringList list = updateFolder.entryList(QDir::Files); for (int i = 0; i < list.size(); ++i) updateFolder.remove(list.at(i)); m_Downloader->addFile("http://www.dotacash.com/xdcc/file_list.xml"); m_Downloader->addFile(m_Latest["url"]); m_Downloader->beginDownloads(); } void UpdateForm::beginUpdate() { emit updateFromURL(m_Latest["url"]); } void UpdateForm::checkForUpdates(QString appCastURL, bool alwaysShow) { m_AlwaysShow = alwaysShow; ApiFetcher* updateFetcher = new ApiFetcher(this); connect(updateFetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parseUpdateData(QString&))); updateFetcher->fetch(appCastURL); } void UpdateForm::parseUpdateData(QString& data) { QXmlStreamReader xml(data); while(!xml.atEnd() && !xml.hasError()) { xml.readNext(); if(xml.isStartDocument()) continue; if(xml.isStartElement()) { if(xml.name() == "channel") continue; if(xml.name() == "item") { m_Latest = parseUpdateItem(xml); break; } } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } bool isNewer = isUpdateRequired(m_Latest["version"]); if(isNewer) { ui.label->setText("<span style=\" font-size:14pt; color:#17069c;\">" + m_Latest["title"] + "</span>"); ui.lblChangelog->setText(m_Latest["description"].replace("</br>", "<br>")); ui.cancelButton->setText(tr("Later")); ui.okButton->show(); } else { ui.label->setText("<span style=\" font-size:14pt; color:#17069c;\">" + tr("You're up to date!") + "</span>"); ui.lblChangelog->setText(tr("DCClient v%1 is the newest version currently available.").arg(m_Version)); ui.cancelButton->setText(tr("OK")); ui.okButton->hide(); } if(isNewer || m_AlwaysShow) this->show(); } bool UpdateForm::isUpdateRequired(QString& latestVer) { QStringList vals1 = m_Version.split('.'); QStringList vals2 = latestVer.split('.'); int i=0; while(i < vals1.length() && i < vals2.length() && vals1[i] == vals2[i]) { i++; } if (i < vals1.length() && i < vals2.length()) { if(vals1[i].toInt() < vals2[i].toInt()) return true; } return false; } QMap<QString, QString> UpdateForm::parseUpdateItem(QXmlStreamReader& xml) { QMap<QString, QString> mapData; if(!xml.isStartElement() || xml.name() != "item") return mapData; xml.readNext(); while(!(xml.isEndElement() && xml.name() == "item")) { if(xml.isStartElement()) { if(xml.name() == "channel") continue; if(xml.name() == "title") addElementDataToMap(xml, mapData); else if(xml.name() == "description") addElementDataToMap(xml, mapData); else if(xml.name() == "enclosure") { QXmlStreamAttributes attrs = xml.attributes(); mapData["url"] = attrs.value("url").toString(); mapData["version"] = attrs.value("sparkle:version").toString(); mapData["os"] = attrs.value("sparkle:os").toString(); mapData["type"] = attrs.value("type").toString(); mapData["size"] = attrs.value("size").toString(); } } xml.readNext(); } return mapData; } void UpdateForm::addElementDataToMap(QXmlStreamReader& xml, QMap<QString, QString>& map) { if(!xml.isStartElement()) return; QString elementName = xml.name().toString(); xml.readNext(); if(!xml.isCharacters() || xml.isWhitespace()) return; map.insert(elementName, xml.text().toString()); }
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_SETTINGS_H #define XDCC_SETTINGS_H #include <QtGui/QMainWindow> #include <QSettings> #include "xdcc.h" #include "ui_xdcc_options.h" class SettingsForm : public QDialog { Q_OBJECT public: SettingsForm(QWidget *parent = 0, Qt::WFlags flags = 0); ~SettingsForm(); public slots: void saveSettings(); signals: void reloadSkin(); private: Ui_SettingsForm ui; QSettings* settings; bool m_SoundOnGameStart; bool m_FriendFollow; bool m_Refresh; QString m_Skin; }; #endif // XDCC_SETTINGS_H
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_DOWNLOADERFORM_H #define XDCC_DOWNLOADERFORM_H #include <QtGui/QMainWindow> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QQueue> #include <QFile> #include <QTime> #include "xdcc.h" #include "ui_xdcc_downloader.h" class DownloaderForm : public QDialog { Q_OBJECT public: DownloaderForm(QWidget *parent = 0, Qt::WFlags flags = 0); void addFile(QString url); void beginDownloads(); public slots: void startNextDownload(); void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); void downloadFinished(); void downloadReadyRead(); signals: void downloadsComplete(); private: Ui_DownloaderForm ui; QNetworkAccessManager manager; QQueue<QUrl> downloadQueue; QNetworkReply* currentDownload; QFile output; QTime downloadTime; int downloadedCount; int totalCount; QString DownloaderForm::saveFileName(const QUrl &url); }; #endif // XDCC_DOWNLOADERFORM_H
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "friendshandler.h" FriendsHandler::FriendsHandler(QString nFriendName, QWidget *parent) : m_FriendName(nFriendName), QObject(parent) { m_Status = false; if(parent) { connect(this, SIGNAL(showMessage(QString, MessageType)), parent, SLOT(showTextCurrentTab(QString, MessageType))); connect(this, SIGNAL(requestGame(QString)), parent, SIGNAL(requestGame(QString))); } /* if(m_Buffer) { connect(m_Buffer, SIGNAL(joined(const QString)), this, SLOT(joined(const QString))); connect(m_Buffer, SIGNAL(parted(const QString, const QString)), this, SLOT(parted(const QString, const QString))); connect(m_Buffer, SIGNAL(quit(const QString, const QString)), this, SLOT(parted(const QString, const QString))); connect(m_Buffer, SIGNAL(nickChanged(const QString, const QString)), this, SLOT(nickChanged(const QString, const QString))); connect(m_Buffer, SIGNAL(messageReceived(const QString, const QString, Irc::Buffer::MessageFlags)), this, SLOT(messageReceived(const QString, const QString, Irc::Buffer::MessageFlags))); connect(m_Buffer, SIGNAL(noticeReceived(const QString, const QString, Irc::Buffer::MessageFlags)), this, SLOT(noticeReceived(const QString, const QString, Irc::Buffer::MessageFlags))); } */ } void FriendsHandler::nickChanged(const QString user, const QString nick) { if(user.toLower() == m_FriendName.toLower()) m_FriendName = nick; } void FriendsHandler::joined(const QString user) { if(user.toLower() == m_FriendName.toLower()) { m_Status = true; emit showMessage(tr("Your friend %1 is now online.").arg(user), Friends); } } void FriendsHandler::parted(const QString user, const QString reason) { if(user.toLower() == m_FriendName.toLower()) { m_Status = false; emit showMessage(tr("Your friend %1 is now offline.").arg(user), Friends); } } void FriendsHandler::messageReceived(const QString &origin, const QString &message) { if(origin.toLower() == m_FriendName.toLower()) { emit showMessage(QString("&lt;%1&gt; %2").arg(origin).arg(message), Friends); } } void FriendsHandler::noticeReceived(const QString &origin, const QString &message) { if(origin.toLower() == m_FriendName.toLower()) { if(message.startsWith("xdcc://")) { int idx = message.indexOf(";"); QString IP = message.mid(7).left(idx-7); QString gameName = message.mid(idx+1); emit showMessage(tr("Your friend %1 has joined the game <a href=xdcc://%2>%3</a>").arg(origin).arg(IP).arg(gameName), Friends); QSettings settings("DotaCash", "DCClient X"); if(settings.value("FriendFollow", true).toBool()) emit requestGame(IP); } } }
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "xdcc.h" #include "loginform.h" #include <QtGui/QMainWindow> #include <QSharedMemory> #include <QTranslator> #include <QLibraryInfo> #include <QFile> #include <qlocalserver.h> #include <qlocalsocket.h> QSharedMemory* _singular; QtMsgHandler oldHandler = NULL; void msgHandler(QtMsgType type, const char *msg) { oldHandler(type, msg); QFile logfile("dcclog.txt"); if(logfile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { QTextStream out(&logfile); out << msg << "\n"; logfile.close(); } } #define _CRTDBG_MAP_ALLOC int main(int argc, char *argv[]) { //_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF ); //oldHandler = qInstallMsgHandler(msgHandler); QApplication a(argc, argv); QTranslator qtTranslator; qtTranslator.load(":/lang/qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); a.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load(":/lang/xdcc_" + QLocale::system().name()); a.installTranslator(&myappTranslator); _singular = new QSharedMemory("DCClient"); if(_singular->attach(QSharedMemory::ReadWrite)) { _singular->detach(); if(argc >= 2) { QLocalSocket socket; socket.connectToServer("DCClientIPC"); if(socket.waitForConnected()) { QDataStream out(&socket); out << QString(argv[1]); socket.waitForBytesWritten(); } } return 0; } _singular->create(1); XDCC xdcc; int ret = a.exec(); delete _singular; return ret; }
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "downloaderform.h" #include <QMessageBox> #include <QFileInfo> DownloaderForm::DownloaderForm(QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags) { ui.setupUi(this); ui.progressBar->setValue(0); downloadedCount = 1; totalCount = 0; } void DownloaderForm::addFile(QString url) { downloadQueue.enqueue(url); totalCount++; } void DownloaderForm::beginDownloads() { this->show(); QTimer::singleShot(0, this, SLOT(startNextDownload())); } void DownloaderForm::startNextDownload() { if (downloadQueue.isEmpty()) { emit downloadsComplete(); return; } QUrl url = downloadQueue.dequeue(); QString filename = saveFileName(url); output.setFileName("updates/" + filename); if (!output.open(QIODevice::WriteOnly)) { QMessageBox::warning(this, tr("Update Error"), tr("Problem opening save file '%1' for download '%2': %3") .arg(qPrintable(filename)) .arg(url.toEncoded().constData()) .arg(qPrintable(output.errorString()))); downloadedCount++; startNextDownload(); return; // skip this download } QNetworkRequest request(url); currentDownload = manager.get(request); connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)), SLOT(downloadProgress(qint64,qint64))); connect(currentDownload, SIGNAL(finished()), SLOT(downloadFinished())); connect(currentDownload, SIGNAL(readyRead()), SLOT(downloadReadyRead())); downloadTime.start(); } QString DownloaderForm::saveFileName(const QUrl &url) { QString path = url.path(); QString basename = QFileInfo(path).fileName(); if (basename.isEmpty()) basename = "download"; if (QFile::exists(basename)) { // already exists, don't overwrite int i = 0; basename += '.'; while (QFile::exists(basename + QString::number(i))) ++i; basename += QString::number(i); } return basename; } void DownloaderForm::downloadFinished() { downloadedCount++; output.close(); if (currentDownload->error()) { QFile::remove(output.fileName()); QMessageBox::warning(this, tr("Update Error"), tr("Failed: %1").arg(qPrintable(currentDownload->errorString()))); } currentDownload->deleteLater(); startNextDownload(); } void DownloaderForm::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { ui.progressBar->setMaximum(bytesTotal); ui.progressBar->setValue(bytesReceived); // calculate the download speed double speed = bytesReceived * 1000.0 / downloadTime.elapsed(); QString unit; if (speed < 1024) { unit = "bytes/sec"; } else if (speed < 1024*1024) { speed /= 1024; unit = "kB/s"; } else { speed /= 1024*1024; unit = "MB/s"; } ui.lblStatus->setText(tr("Downloading file %1 at %2 %3").arg(currentDownload->url().toString()).arg(speed, 3, 'f', 1).arg(unit)); ui.progressBar->update(); ui.label->setText(tr("Downloading Updates (%1 of %2)").arg(downloadedCount).arg(totalCount)); } void DownloaderForm::downloadReadyRead() { output.write(currentDownload->readAll()); }
C++
/* Copyright 2010 Trevor Hogan 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. */ #ifndef GPSPROTOCOL_H #define GPSPROTOCOL_H #include <QByteArray> // // CGameProtocol // #define GPS_HEADER_CONSTANT 248 #define REJECTGPS_INVALID 1 #define REJECTGPS_NOTFOUND 2 class CGPSProtocol { public: enum Protocol { GPS_INIT = 1, GPS_RECONNECT = 2, GPS_ACK = 3, GPS_REJECT = 4 }; CGPSProtocol( ); ~CGPSProtocol( ); // receive functions // send functions QByteArray SEND_GPSC_INIT( quint32 version ); QByteArray SEND_GPSC_RECONNECT( quint8 PID, quint32 reconnectKey, quint32 lastPacket ); QByteArray SEND_GPSC_ACK( quint32 lastPacket ); QByteArray SEND_GPSS_INIT( quint16 reconnectPort, quint8 PID, quint32 reconnectKey, quint8 numEmptyActions ); QByteArray SEND_GPSS_RECONNECT( quint32 lastPacket ); QByteArray SEND_GPSS_ACK( quint32 lastPacket ); QByteArray SEND_GPSS_REJECT( quint32 reason ); // other functions private: bool AssignLength( QByteArray &content ); bool ValidateLength( QByteArray &content ); }; #endif
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "settingsform.h" #include <QMessageBox> #include <QDir> SettingsForm::SettingsForm(QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags) { ui.setupUi(this); connect(ui.btnSave, SIGNAL(clicked()), this, SLOT(saveSettings())); settings = new QSettings("DotaCash", "DCClient X"); m_SoundOnGameStart = settings->value("GameStartedSound", true).toBool(); ui.optionSoundGameStart->setCheckState(m_SoundOnGameStart ? Qt::Checked : Qt::Unchecked); m_FriendFollow = settings->value("FriendFollow", true).toBool(); ui.optionFriendFollow->setCheckState(m_FriendFollow ? Qt::Checked : Qt::Unchecked); m_Refresh = settings->value("InactiveRefresh", false).toBool(); ui.optionFriendFollow->setCheckState(m_Refresh ? Qt::Checked : Qt::Unchecked); m_Skin = settings->value("Skin", "default").toString(); QDir skinsDir("./skins/"); QStringList skinsList = skinsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); ui.cmbSkin->addItems(skinsList); int idx = ui.cmbSkin->findText(m_Skin); if(idx != -1) ui.cmbSkin->setCurrentIndex(idx); } SettingsForm::~SettingsForm() { delete settings; } void SettingsForm::saveSettings() { m_SoundOnGameStart = ui.optionSoundGameStart->isChecked(); settings->setValue("GameStartedSound", m_SoundOnGameStart); m_FriendFollow = ui.optionFriendFollow->isChecked(); settings->setValue("FriendFollow", m_FriendFollow); m_Refresh = ui.optionRefresh->isChecked(); settings->setValue("InactiveRefresh", m_Refresh); m_Skin = ui.cmbSkin->currentText(); settings->setValue("Skin", m_Skin); QFile styleSheet(QString("./skins/%1/style.css").arg(m_Skin)); QString style; if(styleSheet.open(QFile::ReadOnly)) { QTextStream styleIn(&styleSheet); style = styleIn.readAll(); styleSheet.close(); QMainWindow* parent = (QMainWindow*)this->parent(); parent->setStyleSheet(style); emit reloadSkin(); } this->close(); }
C++
/* Copyright 2011 Gene Chen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QObject> #include <QFile> #define COMMUNI_STATIC #include <ircutil.h> #include "channelhandler.h" ChannelHandler::ChannelHandler(bool showUserlist, QWidget* parent) : QObject(parent), lstUsers(0) { m_Tab = new QWidget(parent); QHBoxLayout* horizontalLayout = new QHBoxLayout(m_Tab); horizontalLayout->setSpacing(10); txtChat = new QTextBrowser(m_Tab); txtChat->setMinimumWidth(560); txtChat->setOpenLinks(false); horizontalLayout->addWidget(txtChat); if(showUserlist) { lstUsers = new QListWidget(m_Tab); lstUsers->setSortingEnabled(true); lstUsers->setMaximumWidth(180); lstUsers->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); lstUsers->setAlternatingRowColors(true); horizontalLayout->addWidget(lstUsers); } connect(txtChat, SIGNAL(anchorClicked(QUrl)), parent, SLOT(handleUrl(QUrl))); reloadSkin(); } void ChannelHandler::reloadSkin() { QString skin = QSettings("DotaCash", "DCClient X", this).value("Skin", "default").toString(); QFile styleSheet(QString("./skins/%1/style.css").arg(skin)); QString style; if(styleSheet.open(QFile::ReadOnly)) { QTextStream styleIn(&styleSheet); style = styleIn.readAll(); styleSheet.close(); txtChat->document()->setDefaultStyleSheet(style); } } void ChannelHandler::UpdateNames(QStringList& names) { if(!lstUsers) return; lstUsers->addItems(names); } void ChannelHandler::nickChanged(const QString user, const QString nick) { if(!lstUsers) return; QList<QListWidgetItem*> list = lstUsers->findItems(user, Qt::MatchFixedString); for(int i = 0; i < list.size(); i++) { list.at(i)->setText(nick); } txtChat->append(tr("<span class = \"sysmsg\">%1 is now known as %2</span>").arg(user).arg(nick)); } void ChannelHandler::joined(const QString user) { if(!lstUsers) return; QList<QListWidgetItem*> list = lstUsers->findItems(user, Qt::MatchFixedString); if(list.isEmpty()) { lstUsers->addItem(user); } } void ChannelHandler::parted(const QString user, const QString reason) { if(!lstUsers) return; QList<QListWidgetItem*> list = lstUsers->findItems(user, Qt::MatchFixedString); for(int i = 0; i < list.size(); i++) { lstUsers->removeItemWidget(list.at(i)); delete list.at(i); } } void ChannelHandler::messageReceived(const QString &origin, const QString &message) { QString txt = QString("<span class = \"msg\">&lt;%1&gt; %2</span>").arg(origin).arg(IrcUtil::messageToHtml(message)); txtChat->append(txt); } void ChannelHandler::noticeReceived(const QString &origin, const QString &message) { QString txt = QString("<span class = \"notice\">-%1- %2</span>").arg(origin).arg(IrcUtil::messageToHtml(message)); txtChat->append(txt); }
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef DCAPIFETCHER_H #define DCAPIFETCHER_H #include "xdcc.h" #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> class ApiFetcher : public QObject { Q_OBJECT public: ApiFetcher(QWidget* parent=0); ~ApiFetcher(); void fetch(QString url); signals: void fetchComplete(QString& data); public slots: void finished(QNetworkReply *reply); void readyRead(); void metaDataChanged(); void error(QNetworkReply::NetworkError); private: QNetworkAccessManager manager; QNetworkReply *currentReply; QString result; void get(const QUrl &url); }; #endif
C++
/* Copyright 2011 Gene Chen 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. */ #ifndef CHANNELHANDLER_H #define CHANNELHANDLER_H #include "xdcc.h" #include <QObject> #include <QTextBrowser> #include <QListWidget> #define COMMUNI_STATIC #include <Irc> #include <IrcMessage> #include <ircutil.h> class ChannelHandler : public QObject { Q_OBJECT public: ChannelHandler(bool showUserlist=true, QWidget *parent=0); QWidget* GetTab() { return m_Tab; } void showText(QString msg) { txtChat->append(msg); } void UpdateNames(QStringList& names); void reloadSkin(); void joined(const QString); void parted(const QString, const QString); void nickChanged(const QString, const QString); void messageReceived(const QString &origin, const QString &message); void noticeReceived(const QString &origin, const QString &message); private: QWidget* m_Tab; QTextBrowser* txtChat; QListWidget* lstUsers; }; #endif
C++
/* Copyright 2010 Trevor Hogan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "commandpacket.h" // // CCommandPacket // CCommandPacket :: CCommandPacket( unsigned char nPacketType, int nID, QByteArray nData ) { m_PacketType = nPacketType; m_ID = nID; m_Data = nData; } CCommandPacket :: ~CCommandPacket( ) { }
C++
#include "gamerequester.h" #include "gameprotocol.h" #include "commandpacket.h" GameRequester::GameRequester(QWidget* parent) : QObject(parent) { socket = new QUdpSocket(this); socket->bind(6969, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint); connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); gameProtocol = new CGameProtocol(); } GameRequester::~GameRequester() { for(auto i = games.begin(); i != games.end(); ++i) { socket->writeDatagram(gameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetEntryKey()), QHostAddress::Broadcast, 6112); delete *i; } }
C++
#include <vector> #include <stdio.h> #include "json.h" void populate_sources(const char *filter, std::vector<std::vector<char> > &sources) { char filename[256]; for (int i = 1; i < 64; ++i) { sprintf(filename, filter, i); FILE *fp = fopen(filename, "rb"); if (fp) { fseek(fp, 0, SEEK_END); int size = ftell(fp); fseek(fp, 0, SEEK_SET); std::vector<char> buffer(size + 1); fread (&buffer[0], 1, size, fp); fclose(fp); sources.push_back(buffer); } else { break; } } printf("Loaded %d json files\n", sources.size()); } #define IDENT(n) for (int i = 0; i < n; ++i) printf(" ") void print(json_value *value, int ident = 0) { IDENT(ident); if (value->name) printf("\"%s\" = ", value->name); switch(value->type) { case JSON_NULL: printf("null\n"); break; case JSON_OBJECT: case JSON_ARRAY: printf(value->type == JSON_OBJECT ? "{\n" : "[\n"); for (json_value *it = value->first_child; it; it = it->next_sibling) { print(it, ident + 1); } IDENT(ident); printf(value->type == JSON_OBJECT ? "}\n" : "]\n"); break; case JSON_STRING: printf("\"%s\"\n", value->string_value); break; case JSON_INT: printf("%d\n", value->int_value); break; case JSON_FLOAT: printf("%f\n", value->float_value); break; case JSON_BOOL: printf(value->int_value ? "true\n" : "false\n"); break; } } bool parse(char *source) { char *errorPos = 0; char *errorDesc = 0; int errorLine = 0; block_allocator allocator(1 << 10); json_value *root = json_parse(source, &errorPos, &errorDesc, &errorLine, &allocator); if (root) { print(root); return true; } printf("Error at line %d: %s\n%s\n\n", errorLine, errorDesc, errorPos); return false; } int main(int argc, char **argv) { // Fail printf("===FAIL===\n\n"); std::vector<std::vector<char> > sources; populate_sources("test/fail%d.json", sources); int passed = 0; for (size_t i = 0; i < sources.size(); ++i) { printf("Parsing %d\n", i + 1); if (parse(&sources[i][0])) { ++passed; } } printf("Passed %d from %d tests\n", passed, sources.size()); // Pass sources.clear(); printf("\n===PASS===\n\n"); populate_sources("test/pass%d.json", sources); passed = 0; for (size_t i = 0; i < sources.size(); ++i) { printf("Parsing %d\n", i + 1); if (parse(&sources[i][0])) { ++passed; } } printf("Passed %d from %d tests\n", passed, sources.size()); return 0; }
C++
#include <memory.h> #include "json.h" // true if character represent a digit #define IS_DIGIT(c) (c >= '0' && c <= '9') // convert string to integer char *atoi(char *first, char *last, int *out) { int sign = 1; if (first != last) { if (*first == '-') { sign = -1; ++first; } else if (*first == '+') { ++first; } } int result = 0; for (; first != last && IS_DIGIT(*first); ++first) { result = 10 * result + (*first - '0'); } *out = result * sign; return first; } // convert hexadecimal string to unsigned integer char *hatoui(char *first, char *last, unsigned int *out) { unsigned int result = 0; for (; first != last; ++first) { int digit; if (IS_DIGIT(*first)) { digit = *first - '0'; } else if (*first >= 'a' && *first <= 'f') { digit = *first - 'a' + 10; } else if (*first >= 'A' && *first <= 'F') { digit = *first - 'A' + 10; } else { break; } result = 16 * result + digit; } *out = result; return first; } // convert string to floating point char *atof(char *first, char *last, float *out) { // sign float sign = 1; if (first != last) { if (*first == '-') { sign = -1; ++first; } else if (*first == '+') { ++first; } } // integer part float result = 0; for (; first != last && IS_DIGIT(*first); ++first) { result = 10 * result + (*first - '0'); } // fraction part if (first != last && *first == '.') { ++first; float inv_base = 0.1f; for (; first != last && IS_DIGIT(*first); ++first) { result += (*first - '0') * inv_base; inv_base *= 0.1f; } } // result w\o exponent result *= sign; // exponent bool exponent_negative = false; int exponent = 0; if (first != last && (*first == 'e' || *first == 'E')) { ++first; if (*first == '-') { exponent_negative = true; ++first; } else if (*first == '+') { ++first; } for (; first != last && IS_DIGIT(*first); ++first) { exponent = 10 * exponent + (*first - '0'); } } if (exponent) { float power_of_ten = 10; for (; exponent > 1; exponent--) { power_of_ten *= 10; } if (exponent_negative) { result /= power_of_ten; } else { result *= power_of_ten; } } *out = result; return first; } json_value *json_alloc(block_allocator *allocator) { json_value *value = (json_value *)allocator->malloc(sizeof(json_value)); memset(value, 0, sizeof(json_value)); return value; } void json_append(json_value *lhs, json_value *rhs) { rhs->parent = lhs; if (lhs->last_child) { lhs->last_child = lhs->last_child->next_sibling = rhs; } else { lhs->first_child = lhs->last_child = rhs; } } #define ERROR(it, desc)\ *error_pos = it;\ *error_desc = (char *)desc;\ *error_line = 1 - escaped_newlines;\ for (char *c = it; c != source; --c)\ if (*c == '\n') ++*error_line;\ return 0 #define CHECK_TOP() if (!top) {ERROR(it, "Unexpected character");} json_value *json_parse(char *source, char **error_pos, char **error_desc, int *error_line, block_allocator *allocator) { json_value *root = 0; json_value *top = 0; char *name = 0; char *it = source; int escaped_newlines = 0; while (*it) { switch (*it) { case '{': case '[': { // create new value json_value *object = json_alloc(allocator); // name object->name = name; name = 0; // type object->type = (*it == '{') ? JSON_OBJECT : JSON_ARRAY; // skip open character ++it; // set top and root if (top) { json_append(top, object); } else if (!root) { root = object; } else { ERROR(it, "Second root. Only one root allowed"); } top = object; } break; case '}': case ']': { if (!top || top->type != ((*it == '}') ? JSON_OBJECT : JSON_ARRAY)) { ERROR(it, "Mismatch closing brace/bracket"); } // skip close character ++it; // set top top = top->parent; } break; case ':': if (!top || top->type != JSON_OBJECT) { ERROR(it, "Unexpected character"); } ++it; break; case ',': CHECK_TOP(); ++it; break; case '"': { CHECK_TOP(); // skip '"' character ++it; char *first = it; char *last = it; while (*it) { if ((unsigned char)*it < '\x20') { ERROR(first, "Control characters not allowed in strings"); } else if (*it == '\\') { switch (it[1]) { case '"': *last = '"'; break; case '\\': *last = '\\'; break; case '/': *last = '/'; break; case 'b': *last = '\b'; break; case 'f': *last = '\f'; break; case 'n': *last = '\n'; ++escaped_newlines; break; case 'r': *last = '\r'; break; case 't': *last = '\t'; break; case 'u': { unsigned int codepoint; if (hatoui(it + 2, it + 6, &codepoint) != it + 6) { ERROR(it, "Bad unicode codepoint"); } if (codepoint <= 0x7F) { *last = (char)codepoint; } else if (codepoint <= 0x7FF) { *last++ = (char)(0xC0 | (codepoint >> 6)); *last = (char)(0x80 | (codepoint & 0x3F)); } else if (codepoint <= 0xFFFF) { *last++ = (char)(0xE0 | (codepoint >> 12)); *last++ = (char)(0x80 | ((codepoint >> 6) & 0x3F)); *last = (char)(0x80 | (codepoint & 0x3F)); } } it += 4; break; default: ERROR(first, "Unrecognized escape sequence"); } ++last; it += 2; } else if (*it == '"') { *last = 0; ++it; break; } else { *last++ = *it++; } } if (!name && top->type == JSON_OBJECT) { // field name in object name = first; } else { // new string value json_value *object = json_alloc(allocator); object->name = name; name = 0; object->type = JSON_STRING; object->string_value = first; json_append(top, object); } } break; case 'n': case 't': case 'f': { CHECK_TOP(); // new null/bool value json_value *object = json_alloc(allocator); object->name = name; name = 0; // null if (it[0] == 'n' && it[1] == 'u' && it[2] == 'l' && it[3] == 'l') { object->type = JSON_NULL; it += 4; } // true else if (it[0] == 't' && it[1] == 'r' && it[2] == 'u' && it[3] == 'e') { object->type = JSON_BOOL; object->int_value = 1; it += 4; } // false else if (it[0] == 'f' && it[1] == 'a' && it[2] == 'l' && it[3] == 's' && it[4] == 'e') { object->type = JSON_BOOL; object->int_value = 0; it += 5; } else { ERROR(it, "Unknown identifier"); } json_append(top, object); } break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { CHECK_TOP(); // new number value json_value *object = json_alloc(allocator); object->name = name; name = 0; object->type = JSON_INT; char *first = it; while (*it != '\x20' && *it != '\x9' && *it != '\xD' && *it != '\xA' && *it != ',' && *it != ']' && *it != '}') { if (*it == '.' || *it == 'e' || *it == 'E') { object->type = JSON_FLOAT; } ++it; } if (object->type == JSON_INT && atoi(first, it, &object->int_value) != it) { ERROR(first, "Bad integer number"); } if (object->type == JSON_FLOAT && atof(first, it, &object->float_value) != it) { ERROR(first, "Bad float number"); } json_append(top, object); } break; default: ERROR(it, "Unexpected character"); } // skip white space while (*it == '\x20' || *it == '\x9' || *it == '\xD' || *it == '\xA') { ++it; } } if (top) { ERROR(it, "Not all objects/arrays have been properly closed"); } return root; }
C++
#ifndef BLOCK_ALLOCATOR_H #define BLOCK_ALLOCATOR_H class block_allocator { private: struct block { size_t size; size_t used; char *buffer; block *next; }; block *m_head; size_t m_blocksize; block_allocator(const block_allocator &); block_allocator &operator=(block_allocator &); public: block_allocator(size_t blocksize); ~block_allocator(); // exchange contents with rhs void swap(block_allocator &rhs); // allocate memory void *malloc(size_t size); // free all allocated blocks void free(); }; #endif
C++
#include <memory.h> #include <algorithm> #include "block_allocator.h" block_allocator::block_allocator(size_t blocksize): m_head(0), m_blocksize(blocksize) { } block_allocator::~block_allocator() { while (m_head) { block *temp = m_head->next; ::free(m_head); m_head = temp; } } void block_allocator::swap(block_allocator &rhs) { std::swap(m_blocksize, rhs.m_blocksize); std::swap(m_head, rhs.m_head); } void *block_allocator::malloc(size_t size) { if ((m_head && m_head->used + size > m_head->size) || !m_head) { // calc needed size for allocation size_t alloc_size = std::max(sizeof(block) + size, m_blocksize); // create new block char *buffer = (char *)::malloc(alloc_size); block *b = reinterpret_cast<block *>(buffer); b->size = alloc_size; b->used = sizeof(block); b->buffer = buffer; b->next = m_head; m_head = b; } void *ptr = m_head->buffer + m_head->used; m_head->used += size; return ptr; } void block_allocator::free() { block_allocator(0).swap(*this); }
C++
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <assert.h> #include <jni.h> #include <android/log.h> #include <stdio.h> #include <stdint.h> #include <math.h> #include <GLES/gl.h> static const char* LogTitle = "HeightMapProfiler"; #ifdef DEBUG #define ASSERT(x) if (!(x)) { __assert(__FILE__, __LINE__, #x); } #else #define ASSERT(X) #endif #ifdef REPORTING #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LogTitle, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LogTitle, __VA_ARGS__) #else #define LOGE(...) #define LOGI(...) #endif void __assert(const char* pFileName, const int line, const char* pMessage) { __android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", "Assert Failed! %s (%s:%d)", pMessage, pFileName, line); assert(false); } struct Mesh { int vertexBuffer; int textureBuffer; int colorBuffer; int indexBuffer; int indexCount; bool useFixedPoint; }; struct Tile { // Store a texture value for each texture LOD (Level of Detail) int textures[4]; float x; float y; float z; float centerX; float centerY; float centerZ; int maxLodCount; int lodCount; Mesh lods[4]; float maxLodDistance2; }; static const int MAX_TILES = 17; //4x4 tiles + 1 skybox. This really shouldn't be hard coded this way though. static int sTileCount = 0; static Tile sTiles[MAX_TILES]; static int sSkybox = -1; static void nativeReset(JNIEnv* env, jobject thiz) { sTileCount = 0; sSkybox = -1; } // static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ); static jint nativeAddTile( JNIEnv* env, jobject thiz, jint texture, jint lodCount, jfloat maxLodDistance, jfloat x, jfloat y, jfloat z, jfloat centerX, jfloat centerY, jfloat centerZ) { LOGI("nativeAddTile"); int index = -1; if (sTileCount < MAX_TILES) { index = sTileCount; Tile* currentTile = &sTiles[index]; currentTile->x = x; currentTile->y = y; currentTile->z = z; currentTile->centerX = centerX; currentTile->centerY = centerY; currentTile->centerZ = centerZ; currentTile->lodCount = 0; currentTile->maxLodCount = lodCount; currentTile->maxLodDistance2 = maxLodDistance * maxLodDistance; // Texture array size hard coded for now currentTile->textures[0] = texture; // first element takes default LOD texture currentTile->textures[1] = -1; // rest are set by nativeAddTextureLod() call currentTile->textures[2] = -1; currentTile->textures[3] = -1; sTileCount++; LOGI("Tile %d: (%g, %g, %g). Max lod: %d", index, x, y, z, lodCount); } return index; } static void nativeSetSkybox( JNIEnv* env, jobject thiz, jint index) { if (index < sTileCount && index >= 0) { sSkybox = index; } } // static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint); static void nativeAddLod( JNIEnv* env, jobject thiz, jint index, jint vertexBuffer, jint textureBuffer, jint indexBuffer, jint colorBuffer, jint indexCount, jboolean useFixedPoint) { LOGI("nativeAddLod (%d)", index); if (index < sTileCount && index >= 0) { Tile* currentTile = &sTiles[index]; LOGI("Adding lod for tile %d (%d of %d) - %s", index, currentTile->lodCount, currentTile->maxLodCount, useFixedPoint ? "fixed" : "float"); if (currentTile->lodCount < currentTile->maxLodCount) { const int meshIndex = currentTile->lodCount; LOGI("Mesh %d: Index Count: %d", meshIndex, indexCount); Mesh* lod = &currentTile->lods[meshIndex]; lod->vertexBuffer = vertexBuffer; lod->textureBuffer = textureBuffer; lod->colorBuffer = colorBuffer; lod->indexBuffer = indexBuffer; lod->indexCount = indexCount; lod->useFixedPoint = useFixedPoint; currentTile->lodCount++; } } } // static native void nativeAddTextureLod(int index, int lod, int textureName); static void nativeAddTextureLod( JNIEnv* env, jobject thiz, jint tileIndex, jint lod, jint textureName) { if (tileIndex < sTileCount && tileIndex >= 0) { Tile* currentTile = &sTiles[tileIndex]; LOGI("Adding texture lod for tile %d lod %d texture name %d", tileIndex, lod, textureName); if( lod >= sizeof(currentTile->textures)/sizeof(currentTile->textures[0]) ) { LOGI("Error adding texture lod for tile %d lod %d is out of range ", tileIndex, lod ); } currentTile->textures[lod] = textureName; } } static void drawTile(int index, float cameraX, float cameraY, float cameraZ, bool useTexture, bool useColor) { //LOGI("draw tile: %d", index); if (index < sTileCount) { Tile* currentTile = &sTiles[index]; const float dx = currentTile->centerX - cameraX; const float dz = currentTile->centerZ - cameraZ; const float distanceFromCamera2 = (dx * dx) + (dz * dz); int lod = currentTile->lodCount - 1; if (distanceFromCamera2 < currentTile->maxLodDistance2) { const int bucket = (int)((distanceFromCamera2 / currentTile->maxLodDistance2) * currentTile->lodCount); lod = bucket < (currentTile->lodCount - 1) ? bucket : currentTile->lodCount - 1; } ASSERT(lod < currentTile->lodCount); Mesh* lodMesh = &currentTile->lods[lod]; //LOGI("mesh %d: count: %d", index, lodMesh->indexCount); const GLint coordinateType = lodMesh->useFixedPoint ? GL_FIXED : GL_FLOAT; glPushMatrix(); glTranslatef(currentTile->x, currentTile->y, currentTile->z); glBindBuffer(GL_ARRAY_BUFFER, lodMesh->vertexBuffer); glVertexPointer(3, coordinateType, 0, 0); if (useTexture) { int texture = currentTile->textures[0]; if( currentTile->textures[lod] != -1 ) { texture = currentTile->textures[lod]; } glBindTexture(GL_TEXTURE_2D, texture); glBindBuffer(GL_ARRAY_BUFFER, lodMesh->textureBuffer); glTexCoordPointer(2, coordinateType, 0, 0); } if (useColor) { glBindBuffer(GL_ARRAY_BUFFER, lodMesh->colorBuffer); glColorPointer(4, coordinateType, 0, 0); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lodMesh->indexBuffer); glDrawElements(GL_TRIANGLES, lodMesh->indexCount, GL_UNSIGNED_SHORT, 0); glPopMatrix(); } } // Blatantly copied from the GLU ES project: // http://code.google.com/p/glues/ static void __gluMakeIdentityf(GLfloat m[16]) { m[0+4*0] = 1; m[0+4*1] = 0; m[0+4*2] = 0; m[0+4*3] = 0; m[1+4*0] = 0; m[1+4*1] = 1; m[1+4*2] = 0; m[1+4*3] = 0; m[2+4*0] = 0; m[2+4*1] = 0; m[2+4*2] = 1; m[2+4*3] = 0; m[3+4*0] = 0; m[3+4*1] = 0; m[3+4*2] = 0; m[3+4*3] = 1; } static void normalize(GLfloat v[3]) { GLfloat r; r=(GLfloat)sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); if (r==0.0f) { return; } v[0]/=r; v[1]/=r; v[2]/=r; } static void cross(GLfloat v1[3], GLfloat v2[3], GLfloat result[3]) { result[0] = v1[1]*v2[2] - v1[2]*v2[1]; result[1] = v1[2]*v2[0] - v1[0]*v2[2]; result[2] = v1[0]*v2[1] - v1[1]*v2[0]; } static void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez, GLfloat centerx, GLfloat centery, GLfloat centerz, GLfloat upx, GLfloat upy, GLfloat upz) { GLfloat forward[3], side[3], up[3]; GLfloat m[4][4]; forward[0] = centerx - eyex; forward[1] = centery - eyey; forward[2] = centerz - eyez; up[0] = upx; up[1] = upy; up[2] = upz; normalize(forward); /* Side = forward x up */ cross(forward, up, side); normalize(side); /* Recompute up as: up = side x forward */ cross(side, forward, up); __gluMakeIdentityf(&m[0][0]); m[0][0] = side[0]; m[1][0] = side[1]; m[2][0] = side[2]; m[0][1] = up[0]; m[1][1] = up[1]; m[2][1] = up[2]; m[0][2] = -forward[0]; m[1][2] = -forward[1]; m[2][2] = -forward[2]; glMultMatrixf(&m[0][0]); glTranslatef(-eyex, -eyey, -eyez); } /* Call to render the next GL frame */ static void nativeRender( JNIEnv* env, jobject thiz, jfloat cameraX, jfloat cameraY, jfloat cameraZ, jfloat lookAtX, jfloat lookAtY, jfloat lookAtZ, jboolean useTexture, jboolean useColor, jboolean cameraDirty) { //LOGI("render"); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (cameraDirty) { glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(cameraX, cameraY, cameraZ, lookAtX, lookAtY, lookAtZ, 0.0f, 1.0f, 0.0f); } glEnableClientState(GL_VERTEX_ARRAY); if (useTexture) { glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnable(GL_TEXTURE_2D); } else { glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_TEXTURE_2D); } if (useColor) { glEnableClientState(GL_COLOR_ARRAY); } else { glDisableClientState(GL_COLOR_ARRAY); } if (sSkybox != -1) { glDepthMask(false); glDisable(GL_DEPTH_TEST); drawTile(sSkybox, cameraX, cameraY, cameraZ, useTexture, useColor); glDepthMask(true); glEnable(GL_DEPTH_TEST); } for (int x = 0; x < sTileCount; x++) { if (x != sSkybox) { drawTile(x, cameraX, cameraY, cameraZ, useTexture, useColor); } } glDisableClientState(GL_VERTEX_ARRAY); //LOGI("render complete"); } static const char* classPathName = "com/android/heightmapprofiler/NativeRenderer"; static JNINativeMethod methods[] = { {"nativeReset", "()V", (void*)nativeReset }, {"nativeRender", "(FFFFFFZZZ)V", (void*)nativeRender }, {"nativeAddTile", "(IIFFFFFFF)I", (void*)nativeAddTile }, {"nativeAddLod", "(IIIIIIZ)V", (void*)nativeAddLod }, {"nativeSetSkybox", "(I)V", (void*)nativeSetSkybox }, {"nativeAddTextureLod", "(III)V", (void*)nativeAddTextureLod}, }; /* * Register several native methods for one class. */ static int registerNativeMethods(JNIEnv* env, const char* className, JNINativeMethod* gMethods, int numMethods) { jclass clazz; clazz = env->FindClass(className); if (clazz == NULL) { char error[255]; sprintf(error, "Native registration unable to find class '%s'\n", className); __android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", error); return JNI_FALSE; } if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { char error[255]; sprintf(error, "RegisterNatives failed for '%s'\n", className); __android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", error); return JNI_FALSE; } return JNI_TRUE; } /* * Register native methods for all classes we know about. */ static int registerNatives(JNIEnv* env) { if (!registerNativeMethods(env, classPathName, methods, sizeof(methods) / sizeof(methods[0]))) { return JNI_FALSE; } return JNI_TRUE; } /* * Set some test stuff up. * * Returns the JNI version on success, -1 on failure. */ JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env = NULL; jint result = -1; if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) { LOGE("ERROR: GetEnv failed"); goto bail; } assert(env != NULL); if (!registerNatives(env)) { LOGE("ERROR: HeightMapProfiler native registration failed"); goto bail; } /* success -- return valid version number */ result = JNI_VERSION_1_4; bail: return result; }
C++
char sample[] = { "=== ALL USERS PLEASE NOTE ========================\n" "\n" "CAR and CDR now return extra values.\n" "\n" "The function CAR now returns two values. Since it has to go to the\n" "trouble to figure out if the object is carcdr-able anyway, we figured\n" "you might as well get both halves at once. For example, the following\n" "code shows how to destructure a cons (SOME-CONS) into its two slots\n" "(THE-CAR and THE-CDR):\n" "\n" " (MULTIPLE-VALUE-BIND (THE-CAR THE-CDR) (CAR SOME-CONS) ...)\n" "\n" "For symmetry with CAR, CDR returns a second value which is the CAR of\n" "the object. In a related change, the functions MAKE-ARRAY and CONS\n" "have been fixed so they don't allocate any storage except on the\n" "stack. This should hopefully help people who don't like using the\n" "garbage collector because it cold boots the machine so often.\n" };
C++
#pragma once #include "Graphics_Lib.h" #include "HelpfulData.h" class Line { private: Texture * m_tex; V2DF m_start; V2DF m_end; float m_length; float m_angle; int m_numSprites; RECT m_lastSprite; int m_spriteHeight; int m_spriteWidth; void calculate(); public: Line(); ~Line(); void release(); void initialize(Texture * a_tex, V2DF start, V2DF end); void render(); void update(float dT); void setStart(V2DF start); void setEnd(V2DF end); V2DF getStart() { return m_start; } V2DF getEnd() { return m_end; } Texture* getTextureReference() { return m_tex; } };
C++
#include "Enemy.h" Enemy::Enemy() { State = Wander; } void Enemy::update() { switch(State) { case Wander: break; case Chase: break; case Attack: break; case Advanced_Attack: break; case Flank: break; default: break; } }
C++
#pragma once #include "HelpfulData.h" #include "Animation.h" class Skills { private: ClDwn cldwn; int lvlReq; int str; Animation playerAnimation; public: void use(); };
C++
#include "Floor.h" // default constructor Floor::Floor() {} // default deconstructor, make sure release is called Floor::~Floor() { release(); } // release all data safetly void Floor::release() { } // setup floor void Floor::intialize(char * fileName) { // setup a default test room for(int y = 0; y < FLOORSIZE; y++) { for(int x = 0; x < FLOORSIZE; x++) { // used later for graph int id = x + y * FLOORSIZE; // set all tiles to floor except edges if(x == 0 || x == FLOORSIZE-1 || y == 0 || y == FLOORSIZE-1) m_layout[y][x].initialize(V2DF(x*32,y*32),0); else m_layout[y][x].initialize(V2DF(x*32,y*32),1); } } // set flags to defaults m_visited = m_cleared = false; } // update all tiles void Floor::update(float dT) {} // render this floor void Floor::render() { // render each tile for(int y = 0; y < FLOORSIZE; y++) { for(int x = 0; x < FLOORSIZE; x++) { m_layout[y][x].render(); } } } // check if this entity is colliding with any walls bool Floor::WallCollision(Entity * entity) { return false; } // get graphnode based on position GraphNode * Floor::getNode(V2DF position) { return 0; } // get graphnode based on id GraphNode * Floor::getNode(int id) { return 0; }
C++
#pragma once #include "Graphics_Lib.h" #include "HelpfulData.h" class Tile { private: SpriteSheet m_tex; FRect m_bounds; int m_tileType; public: V2DF m_position; Tile(); ~Tile(); void initialize(V2DF pos, int tileType); void release(); void render(); void update(float dT); FRect getBounds(); };
C++
#include "Input.h" // Return a reference to the input device Input::Input() { // set devices to null m_pDInput = 0; m_pKeyboard = 0; m_pMouse = 0; } Input* Input::getInstance() { static Input instance; return &instance; } Input::~Input() { release(); } void Input::initialize(HINSTANCE hInst, HWND hWnd) { m_hWnd = hWnd; // Create dInput Object DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDInput, 0); // Create Mouse and Keyboard Objects m_pDInput->CreateDevice(GUID_SysKeyboard, &m_pKeyboard, 0); m_pDInput->CreateDevice(GUID_SysMouse, &m_pMouse, 0); // Set Mouse and Keyboard Data Formats m_pKeyboard->SetDataFormat( &c_dfDIKeyboard); m_pMouse->SetDataFormat(&c_dfDIMouse2); // Set the Cooperative Level of both the Mouse and Keyboard m_pKeyboard->SetCooperativeLevel( hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); m_pMouse->SetCooperativeLevel( hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); // Aquire both the Mouse and Keyboard m_pKeyboard->Acquire(); m_pMouse->Acquire(); } void Input::pollDevices() { /////////////////////////////////////////// // Poll Keyboard & Mouse for Input /////////////////////////////////////////// // Create Temp structures to hold Keyboard & Mouse states // Keyboard for(int i = 0; i < 256; i++) mKeyboardState[i] = 0; // refresh key input // Mouse mMouseState.lX = 0; // refresh mouse state mMouseState.lY = 0; mMouseState.lZ = 0; mMouseState.rgbButtons[0] = 0; mMouseState.rgbButtons[1] = 0; mMouseState.rgbButtons[2] = 0; // Poll the Keyboard HRESULT hr = m_pKeyboard->GetDeviceState(sizeof(mKeyboardState), (void**)mKeyboardState); // refesh pressed buttons for(int i = 0; i < 256; ++i) { if( (!(mKeyboardState[i] & 0x80)) && keysLastUpdate[i] ) keysLastUpdate[i] = false; } // make sure this call was successful if( FAILED(hr) ) { // keyboard lost, zero out keyboard data structure ZeroMemory(mKeyboardState, sizeof(mKeyboardState)); // Try to re-acquire for next time we poll m_pKeyboard->Acquire(); } // Poll the mouse hr = m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE2), (void**)&mMouseState); // make sure this call was successful if( FAILED(hr) ) { // keyboard lost, zero out keyboard data structure ZeroMemory(&mMouseState, sizeof(mMouseState)); // Try to re-acquire for next time we poll m_pMouse->Acquire(); } } bool Input::keyDown(int key) { return (mKeyboardState[key] & 0x80); } // only valid input is 0,1, or 2 bool Input::mouseButtonDown(int button) { return (mMouseState.rgbButtons[button] & 0x80); } bool Input::keyPressed(int key) { if( mKeyboardState[key] & 0x80 && !keysLastUpdate[key] ) { keysLastUpdate[key] = true; return true; } return false; } V2DF Input::getMousePos() { POINT p; V2DF v; GetCursorPos(&p); ScreenToClient(m_hWnd, &p); v.x = p.x; v.y = p.y; return v; } void Input::release() { // Keyboard & Mouse // safe release all created direct input objects m_pKeyboard->Unacquire(); m_pMouse->Unacquire(); if (!m_pKeyboard) m_pKeyboard->Release(); if (!m_pMouse) m_pMouse->Release(); if (!m_pDInput) m_pDInput->Release(); }
C++
#include "World.h" // default constructor World::World() {} // default destructor, make sure release is called World::~World() { release(); } // safetly release all data void World::release() { } // setup the world void World::initialize() { m_currentFloor = 0; // setup every floor for(int i = 0; i < NUM_FLOORS; i++) m_floors[i].intialize(0); } // update the current floor void World::update(float dT) { m_floors[m_currentFloor].update(dT); } // render the current floor void World::render() { m_floors[m_currentFloor].render(); } // set the current floor if the new floor exists void World::setCurrentFloor(int nFloor) { // make sure the floor exists if(nFloor < 0 || nFloor >= NUM_FLOORS) return; // set the current floor m_currentFloor = nFloor; } // make sure the floor exists then check bool World::FloorVisited(int floor) { // make sure the floor exists if(floor < 0 || floor >= NUM_FLOORS) return false; return m_floors[floor].FloorVisited(); } // make sure the floor exists then check bool World::FloorCleared(int floor) { // make sure the floor exists if(floor < 0 || floor >= NUM_FLOORS) return false; return m_floors[floor].FloorCleared(); } // check current floors walls for collision with the given entity bool World::WallCollision(Entity * entity) { return m_floors[m_currentFloor].WallCollision(entity); }
C++
#pragma once #include "Entity.h" #include "v2d.h" #include "templatevector.h" extern class Player; enum ENEMY_TYPE {BASIC_ENEMY, RANGED_ENEMY, STRONG_ENEMY}; class Enemy : public Entity { Player * target; int Attack_force; TemplateVector<GraphNode*> Math; GraphNode * node; bool See_Player; bool PlayerInRange; bool Player_Lost; enum EnemyState { Wander,Chase,Attack,Advanced_Attack,Flank }; EnemyState State; public: Enemy(); ~Enemy(); void initialize(ENEMY_TYPE,V2DF); void update(); };
C++
#pragma once #include "HelpfulData.h" #include "Input.h" #include "Entity.h" class Player : public Entity { private: //TemplateVector<Item> inventory; ClDwn invincible; int level; int experience; //Item* activeItem; float speed; int score; /* Input */ Input* pInput; public: Player(void); ~Player(void); void Update(float dT); };
C++
#pragma once #include "HelpfulData.h" class GraphNode; // used to easily store connections struct Connection { GraphNode* neighbor; float cost; }; class GraphNode { public: // all connections this node has TemplateVector<Connection> m_neighbors; // position in world space V2DF m_position; public: int totalNeighbors; GraphNode(); ~GraphNode(); void release(); void initialize(V2DF a_pos); void addNeighbor(GraphNode* a_neighbor, float a_cost); int getNeighborCount(); TemplateVector<Connection>* getNeighbors(); float Hueristic(GraphNode* other); V2DF getPosition(); };
C++
#include "Sound.h" void Sound::initialize() { //////////////////////////////////////////////////////////////////////////// // Set up FMOD and sounds /////////////////////////////////////////////////////////////////////////// // create system FMOD::System_Create(&system); // get version system->getVersion(&version); // get number of drivers system->getNumDrivers(&numdrivers); // get driver caps system->getDriverCaps(0, &caps, 0, &speakermode); // get driver info system->getDriverInfo(0, name, 256, 0); // initialize system system->init(100, FMOD_INIT_NORMAL, 0); // create sounds system->createSound("audio/hit.wav", FMOD_DEFAULT, 0, &m_soundEffects[HIT]); system->createSound("audio/press.wav", FMOD_DEFAULT, 0, &m_soundEffects[PRESS]); system->createSound("audio/fire.wav", FMOD_DEFAULT, 0, &m_soundEffects[FIRE]); } Sound::Sound() { } Sound* Sound::getInstance() { static Sound instance; return &instance; } Sound::~Sound() { release(); } void Sound::update() { system->update(); } void Sound::playSound(int sound) { system->playSound(FMOD_CHANNEL_FREE, m_soundEffects[sound], false, 0); } void Sound::release() { for(int i = 0; i < 5; ++i) { if(m_soundEffects[i]) m_soundEffects[i]->release(); } if(system) system->release(); }
C++
#include "HelpfulData.h" void seedRand() { srand(time(NULL)); } bool colliding(FRect r1, FRect r2) { // check veritcal first if( (r1.top > r2.top && r1.top < r2.bottom) || (r1.bottom > r2.top && r1.bottom < r2.bottom) ) { // check horizantally if( (r1.left > r2.left && r1.left < r2.right) || (r1.right > r2.left && r1.right < r2.right) ) { return true; } } return false; } float randomFloat(float min, float max) { // multiply by 1000 to increase accuracy since % only works with integers float temp = ( rand() % (int)(((max + 1) - min) * 1000.0f) ) + (min * 1000.0f); temp /= 1000.0f; return temp; } int randomInt(int min, int max) { return ( rand() % ((max + 1) - min) ) + min; } RECT fRectToRECT(FRect a_rect) { RECT temp; temp.top = a_rect.top; temp.bottom = a_rect.bottom; temp.left = a_rect.left; temp.right = a_rect.right; return temp; } FRect RECTtoFRect(RECT a_rect) { FRect temp; temp.top = a_rect.top; temp.bottom = a_rect.bottom; temp.left = a_rect.left; temp.right = a_rect.right; return temp; } bool colliding(V2DF point, FRect rect) { if( point.x <= rect.right && point.x >= rect.left && point.y <= rect.bottom && point.y >= rect.top ) return true; return false; } // ************************************************************* // ClDwn Class definitions // ************************************************************* // basic constructor ClDwn::ClDwn() { // set basic values m_newDuration = -1; m_duration = m_timePassed = 0.0f; m_active = false; } // skeleton destructor ClDwn::~ClDwn() {} // setup cool down for the given duration void ClDwn::initialize(float duration) { // make sure timer is reset m_newDuration = -1; m_active = false; m_timePassed = 0.0f; m_duration = duration; } // if not already active activate void ClDwn::activate() { m_active = true; } // de-activate and reset time passed void ClDwn::deActivate() { m_active = false; m_timePassed = 0.0f; } // if not active set duration to given duration... // ... if active save duration and change when done // if ignore active is true then set duration no matter what void ClDwn::changeDuration(float duration, bool ignoreActive) { if( ignoreActive || !m_active ) { m_newDuration = -1; m_duration = duration; } else { m_newDuration = duration; } } // if cool down is active then update time passed // if cool down is not active and a newDuration is waiting change duration void ClDwn::update(float dT) { // check whether on cooldown or not if (m_timePassed < m_duration && m_active) { // increment cooldown timer m_timePassed += dT; } // check if cooldown is done and needs reseting else if (m_timePassed >= m_duration) { m_timePassed = 0.0f; m_active = false; } // check if duration needs to be augmented if( m_newDuration != -1 && !m_active) { m_duration = m_newDuration; // set new duration back to non-active m_newDuration = -1; } } // *************************************************************
C++
#include "DX2DEngine.h" #include "Texture.h" #include <string.h> #include <stdlib.h> // make all pointers zero DX2DEngine::DX2DEngine() { m_pD3DObject = 0; m_pD3DDevice = 0; m_pSprite = 0; m_bVsync = false; fps = 0; frameCount = 0; elapsedTime = 0.0; } // make sure the release is called DX2DEngine::~DX2DEngine() { release(); } // set up direct x and other class components void DX2DEngine::initialize(HWND& hWnd, HINSTANCE& hInst, bool bWindowed) { m_hWnd = hWnd; // initialize fps, frameCount, and elapsed time to 0 elapsedTime = 0.0f; fps = frameCount = 0; // Calculate RECT structure for text drawing placement, using whole screen RECT rect; GetClientRect(m_hWnd, &rect); // Create the D3D Object m_pD3DObject = Direct3DCreate9(D3D_SDK_VERSION); // calculate width/height of window int width = rect.right - rect.left; int height = rect.bottom - rect.top; // Set D3D Device presentation parameters before creating the device D3DPRESENT_PARAMETERS D3Dpp; ZeroMemory(&D3Dpp, sizeof(D3Dpp)); // NULL the structure's memory D3Dpp.hDeviceWindow = hWnd; // Handle to the focus window D3Dpp.Windowed = bWindowed; // Windowed or Full-screen boolean D3Dpp.AutoDepthStencilFormat = D3DFMT_D24S8; // Format of depth/stencil buffer, 24 bit depth, 8 bit stencil D3Dpp.EnableAutoDepthStencil = TRUE; // Enables Z-Buffer (Depth Buffer) D3Dpp.BackBufferCount = 1; // Change if need of > 1 is required at a later date D3Dpp.BackBufferFormat = D3DFMT_X8R8G8B8; // Back-buffer format, 8 bits for each pixel D3Dpp.BackBufferHeight = height; // Make sure resolution is supported, use adapter modes D3Dpp.BackBufferWidth = width; // (Same as above) D3Dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // Discard back-buffer, must stay discard to support multi-sample D3Dpp.PresentationInterval = m_bVsync ? D3DPRESENT_INTERVAL_DEFAULT : D3DPRESENT_INTERVAL_IMMEDIATE; // Present back-buffer immediately, unless V-Sync is on D3Dpp.Flags = D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL; // This flag should improve performance, if not set to NULL. D3Dpp.FullScreen_RefreshRateInHz = bWindowed ? 0 : D3DPRESENT_RATE_DEFAULT; // Full-screen refresh rate, use adapter modes or default D3Dpp.MultiSampleQuality = 0; // MSAA currently off, check documentation for support. D3Dpp.MultiSampleType = D3DMULTISAMPLE_NONE; // MSAA currently off, check documentation for support. // Check device capabilities DWORD deviceBehaviorFlags = 0; m_pD3DObject->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &m_D3DCaps); // Determine vertex processing mode if(m_D3DCaps.DevCaps & D3DCREATE_HARDWARE_VERTEXPROCESSING) { // Hardware vertex processing supported? (Video Card) deviceBehaviorFlags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; } else { // If not, use software (CPU) deviceBehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } // If hardware vertex processing is on, check pure device support if(m_D3DCaps.DevCaps & D3DDEVCAPS_PUREDEVICE && deviceBehaviorFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING) { deviceBehaviorFlags |= D3DCREATE_PUREDEVICE; } // Create the D3D Device with the present parameters and device flags above m_pD3DObject->CreateDevice( D3DADAPTER_DEFAULT, // which adapter to use, set to primary D3DDEVTYPE_HAL, // device type to use, set to hardware rasterization hWnd, // handle to the focus window deviceBehaviorFlags, // behavior flags &D3Dpp, // presentation parameters &m_pD3DDevice); // returned device pointer // Create a sprite object, note you will only need one for all 2D sprites D3DXCreateSprite( m_pD3DDevice, &m_pSprite ); ////////////////////////////////////////////////////////////////////////// // Create a Font Object ////////////////////////////////////////////////////////////////////////// // Load D3DXFont, each font style you want to support will need an ID3DXFont D3DXCreateFont( m_pD3DDevice, 20, 0, FW_BOLD, 0, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, TEXT("Courier New"), &m_pFont ); // Set up camera RECT screen; GetClientRect(m_hWnd,&screen); // start camera looking at 0,0 screen_center = camera = V2DF(screen.right/2.0f,screen.bottom/2.0f); // start zoom at standard 1.0 (no scale) zoom = 1.0f; } DX2DEngine* DX2DEngine::getInstance() { static DX2DEngine instance; return &instance; } // calculate frames per second void DX2DEngine::update(float dT) { // increment frame count frameCount++; // update elapsed time elapsedTime += dT; // check if more than 1s has elapsed if (elapsedTime >= 1.0f) { // calculate fps since we are using 1 sec no division required... // ...simple use current frame count fps = frameCount; // now reset frameCount and elapsed time frameCount = 0; elapsedTime = 0.0f; } } // get fps float DX2DEngine::getFPS() { return fps; } // Clear the screen and begin the scene void DX2DEngine::start2DRender() { // Make sure the device is working if(!m_pD3DDevice) return; // Clear the back buffer, call BeginScene() m_pD3DDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DXCOLOR(0.0f, 0.4f, 0.8f, 1.0f), 1.0f, 0); m_pD3DDevice->BeginScene(); } // end the entire scene void DX2DEngine::end2DRender() { m_pD3DDevice->EndScene(); m_pD3DDevice->Present(NULL, NULL, NULL, NULL); } // start the sprite object during render void DX2DEngine::startSprite() { m_pSprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_DEPTH_FRONTTOBACK); } // stop the sprite object during render void DX2DEngine::endSprite() { m_pSprite->End(); } // return a reference to the d3d device IDirect3DDevice9* DX2DEngine::deviceRef() { return m_pD3DDevice; } // return a reference to the d3d device ID3DXSprite* DX2DEngine::spriteRef() { return m_pSprite; } ID3DXFont* DX2DEngine::fontRef() { return m_pFont; } // safetly release all data used void DX2DEngine::release() { // release the sprite object if(m_pSprite) m_pSprite->Release(); m_pSprite = 0; // release the d3d device if(m_pD3DDevice) m_pD3DDevice->Release(); m_pD3DDevice = 0; // now release the textures for(int i = 0; i < m_textures.size(); i++) { if(m_textures.get(i) && m_textures.get(i)->m_pTexture) { m_textures.get(i)->m_pTexture->Release(); m_textures.get(i)->m_pTexture = 0; delete m_textures.get(i)->name; delete m_textures.get(i); m_textures.get(i) = 0; } } // release the vector itself m_textures.release(); // release the d3d object if(m_pD3DObject) m_pD3DObject->Release(); m_pD3DObject = 0; } void DX2DEngine::writeText(char * text, RECT bounds, D3DCOLOR color) { m_pFont->DrawTextA(0, text, -1, &bounds, DT_TOP | DT_LEFT | DT_NOCLIP, color ); } void DX2DEngine::writeText(char * text, V2DF pos, float width, float height, D3DCOLOR color) { RECT bounds; bounds.left = pos.x - width/2; bounds.right = pos.x + width/2; bounds.top = pos.y - height/2; bounds.bottom = pos.y + height/2; m_pFont->DrawTextA(0, text, -1, &bounds, DT_TOP | DT_LEFT | DT_NOCLIP, color ); } void DX2DEngine::writeCenterText(char * text, RECT bounds, D3DCOLOR color) { m_pFont->DrawTextA(0, text, -1, &bounds, DT_CENTER | DT_VCENTER | DT_NOCLIP, color ); } // write text within given rect using the given formating and color void DX2DEngine::writeText(char * text, RECT bounds, D3DCOLOR color, DWORD format) { m_pFont->DrawTextA(0, text, -1, &bounds, format, color); } // Load the given texture from a file if it is not already loaded // also takes in the length of the string // if the texture already exists simply return its id // return its ID int DX2DEngine::createTexture(LPCWSTR file, int length) { bool alreadyExists = false; int index = -1; // make sure this file has not been added prior for(int i = 0; i < m_textures.size() && !alreadyExists ; ++i) { // firs make sure they are even the same length if(length = m_textures.get(i)->length) { // now compare the names for(int j = 0; j < length; ++j) { if( !(file[j] == m_textures.get(i)->name[j]) ) break; // if the final char has been checked and is the same this texture already exists if(j == length-1) { index = i; alreadyExists = true; } } } } // now only load the texture if it doesn't already exist // if it does return the index of the one already created if(alreadyExists) { return index; } // first load up the texture from the given file TextureInfo * temp = 0; temp = new (std::nothrow) TextureInfo; // used for error catching HRESULT hr; hr = D3DXCreateTextureFromFileEx(m_pD3DDevice, file, 0, 0, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, D3DCOLOR_XRGB(255, 0, 255), &temp->m_imageInfo, 0, &temp->m_pTexture); // make sure the texture is created correctly // if an error occurs return an error value if(hr != S_OK) { // delete the texture delete temp; return -1; } // add its name and length temp->length = length; // make sure this is initialized to 0 temp->name = new (std::nothrow) char[length]; for(int i = 0; i < length; ++i) temp->name[i] = 0; for(int i = 0; i < length ; ++i) { temp->name[i] = file[i]; } // now attempt to add this file to the vector m_textures.add(temp); return m_textures.size()-1; } // draw the given texture with the given attributes if it exists // if drawing from a sprite sheet pass in the correct rect // pass in NULL for a_sheetRect if not drawing from a sheet void DX2DEngine::renderTexture(int index, V2DF pos, float layer, float scale, float angle, RECT *a_sheetRect, int r, int g, int b, bool relativeToCamera) { // make sure the texture exists if(index < m_textures.size() && index >= 0) { // make sure the texture pointer itself isn't null if(m_textures.get(index)->m_pTexture) { // move relative to camera if(relativeToCamera) { // apply zoom level pos.multiply(zoom); // move to camera space pos.subtract(camera.difference(screen_center)); // scale based on zoom level scale *= zoom; } // perform culling RECT screen; GetClientRect(m_hWnd,&screen); FRect Fscreen; Fscreen.top = screen.top-100; Fscreen.bottom = screen.bottom+100; Fscreen.left = screen.left-100; Fscreen.right = screen.right+100; if(!colliding(pos, Fscreen)) return; // Scaling D3DXMATRIX scaleMat; D3DXMatrixScaling( &scaleMat, scale, scale, 1.0f ); // objects don't scale in the z layer // Rotation on Z axis, value in radians, converting from degrees D3DXMATRIX rotMat; D3DXMatrixRotationZ( &rotMat, D3DXToRadian(angle) ); // Translation D3DXMATRIX transMat; D3DXMatrixTranslation( &transMat, pos.x, pos.y, layer ); // World matrix used to set transform D3DXMATRIX worldMat; // Multiply scale and rotation, store in scale // Multiply scale and translation, store in world worldMat = scaleMat * rotMat * transMat; // Set Transform m_pSprite->SetTransform( &worldMat ); // check if a rect has been given if(a_sheetRect) { // calculate the rects center rather than the whole images float width = a_sheetRect->right - a_sheetRect->left; float height = a_sheetRect->bottom - a_sheetRect->top; // draw the texture at the rects center HRESULT hr = m_pSprite->Draw( m_textures.get(index)->m_pTexture, a_sheetRect, &D3DXVECTOR3(width * 0.5f, height * 0.5f, 0.0f), NULL, D3DCOLOR_ARGB(255, r, g, b) ); } else { // draw the texture at its center HRESULT hr = m_pSprite->Draw( m_textures.get(index)->m_pTexture, 0, &D3DXVECTOR3(m_textures.get(index)->m_imageInfo.Width * 0.5f, m_textures.get(index)->m_imageInfo.Height * 0.5f, 0.0f), NULL, D3DCOLOR_ARGB(255, r, g, b) ); } } } } void DX2DEngine::setCamera(V2DF pos) { camera = pos; } void DX2DEngine::moveCamera(V2DF dist) { camera.add(dist); } V2DF DX2DEngine::getCamera() { return camera; } void DX2DEngine::setZoom(float a_zoom) { zoom = a_zoom; } void DX2DEngine::zoomInOut(float aug) { float oldZOOM = zoom; // augment zoom zoom += aug; // make sure zoom doesn't reach or fall bellow zero and cap zoom to 10x if(zoom <= 0.1f || zoom > 3.0f) zoom = oldZOOM; } float DX2DEngine::getZoom() { return zoom; } V2DF DX2DEngine::screenCenter() { RECT temp; GetClientRect(m_hWnd,&temp); return V2DF((float)temp.right/2.0f,(float)temp.bottom/2.0f); }; D3DXIMAGE_INFO DX2DEngine::imageInfo(int index) { return m_textures.get(index)->m_imageInfo; }
C++
#include "Item.h" #include "Player.h"
C++
#include "Entity.h" Entity::Entity() { stats.health = 0; stats.str = 0; stats.tough = 0; stats.agil = 0; stats. weight = 0; rotation = 0.0f; dead = false; } Entity::~Entity() {} void Entity::takeDamage(int amount) { stats.health -= amount/(amount+stats.tough); if(stats.health <= 0) dead = true; } void Entity::setFacing(Facing a_orientation) { switch(a_orientation) { case NORTH: rotation = 0; break; case EAST: rotation = 90; break; case SOUTH: rotation = 180; break; case WEST: rotation = 270; break; } }
C++
#pragma once #include "DX2DEngine.h" #include "v2d.h" #include "HelpfulData.h" enum Texture_Type {BASIC, SHEET, ANIMATION}; // Basic 2D Sprite object // contains the necessary information to store for a single d3d texture // ...and draw it to the screen class Texture { protected: // graphics engine reference DX2DEngine* engine; // Texture reference int textureID; // tint of the texture int m_R; // Red level int m_G; // Green level int m_B; // blue level // controls wether the image is drawn in respect to the camera bool m_relativeToCamera; // used to only show a portion of a texture RECT m_viewRect; // used to discern what inherited class of texture is being used // mostly for abstraction purposes in the case of Texture pointers Texture_Type m_type; public: Texture(); ~Texture(); virtual void release(); void initialize(LPCWSTR fileName, bool relativeToCamera); void setRelativeToCamera(bool relativeToCamera) { m_relativeToCamera = relativeToCamera; } bool relativeToCamera() { return m_relativeToCamera; } void setTint(int R, int G, int B); virtual void setViewRect(RECT rect); void resetViewRect(); virtual void draw(V2DF pos, float rotAngle, float scale); int imageHeight(); int imageWidth(); Texture_Type getType() { return m_type; } };
C++
#include "GameEngine.h" #include "HelpfulData.h" GameEngine::GameEngine() { } // Make sure release is called GameEngine::~GameEngine() { release(); } // set up all game components void GameEngine::initialize() { // get sound engine reference pSound = Sound::getInstance(); // set camera move speed m_cameraSpeed = 50.0f; // get input reference pInput = Input::getInstance(); // get 2D graphics engine reference p2DEngine = DX2DEngine::getInstance(); m_state = GAME; running = true; // **************************** // put game stuff here // **************************** // **************************** FRect rect; rect.top = rect.left = 0; rect.bottom = rect.right = 32.0f; test.initialize(V2DF(300.0f,300.0f), L"images/test.png", rect, 1.0f); player.initialize(V2DF(300.0f,300.0f), L"images/test.png", rect, 1.0f); tWorld.initialize(); } // update all game components void GameEngine::update(float dT) { // backup escape key if(pInput->keyDown(DIK_DELETE)) running = false; // update based on given game state switch(m_state) { case MENU: break; case CLASS: break; case GAME: test.setPosition(pInput->getMousePos()); player.Update(dT); tWorld.update(dT); break; case VICTORY: break; case DEAD: break; } } // render all game components void GameEngine::render() { // render the given objects for each state switch(m_state) { case MENU: break; case CLASS: break; case GAME: tWorld.render(); test.render(); player.render(); break; case VICTORY: case DEAD: break; } } void GameEngine::drawText() { switch(m_state) { case MENU: break; case CLASS: break; case GAME: break; case VICTORY: case DEAD: break; } } // safetly release all game components void GameEngine::release() { tWorld.release(); } bool GameEngine::isRunning() { return running; } void GameEngine::setRunning(bool a_run) { running = a_run; } void GameEngine::setState(G_State state) { m_state = state; }
C++
#pragma once #include "templatearray.h" /** * simple templated vector. Ideal for dynamic lists of primitive types and single pointers. * @WARNING template with virtual types, or types that will be pointed to at your own risk! * in those situations, templates of pointers to those types are a much better idea. * @author mvaganov@hotmail.com December 2009 */ template<typename DATA_TYPE> class TemplateVector : public TemplateArray<DATA_TYPE> { protected: /** the default size to allocate new vectors to */ static const int DEFAULT_ALLOCATION_SIZE = 10; /** number of valid elements that the caller thinks we have.. */ int m_size; public: /** sets all fields to an initial data state. WARNING: can cause memory leaks if used without care */ inline void init() { TemplateArray<DATA_TYPE>::init(); m_size = 0; } /** cleans up memory */ inline void release() { TemplateArray<DATA_TYPE>::release(); m_size = 0; } /** @return true of the copy finished correctly */ inline bool copy(const TemplateVector<DATA_TYPE> & a_vector) { if(ensureCapacity(a_vector.m_size)) { for(int i = 0; i < a_vector.m_size; ++i) { set(i, a_vector.get(i)); } m_size = a_vector.m_size; return true; } return false; } /** copy constructor */ inline TemplateVector( const TemplateVector<DATA_TYPE> & a_vector) { init(); copy(a_vector); } /** default constructor allocates no list (zero size) */ inline TemplateVector(){init();} /** format constructor */ inline TemplateVector(const int & a_size, const DATA_TYPE & a_defaultValue) { init(); ensureCapacity(a_size); for(int i = 0; i < a_size; ++i) add(a_defaultValue); } /** @return the last value in the list */ inline DATA_TYPE & getLast() { return m_data[m_size-1]; } /** @return the last added value in the list, and lose that value */ inline DATA_TYPE & pop() { return m_data[--m_size]; } /** * @param value to add to the list * @note adding a value may cause memory allocation */ void add(const DATA_TYPE & a_value) { // where am i storing these values? // if i don't have a place to store them, i better make one. if(m_data == 0) { // make a new list to store numbers in allocateToSize(DEFAULT_ALLOCATION_SIZE); } // if we don't have enough memory allocated for this list if(m_size >= m_allocated) { // make a bigger list allocateToSize(m_allocated*2); } set(m_size, a_value); m_size++; } /** * @param a_value to add to the list if it isnt in the list already * @return true the index where the element exists */ int addNoDuplicates(const DATA_TYPE & a_value) { int index = indexOf(a_value); if(index < 0) { index = m_size; add(a_value); } return index; } /** @param a_vector a vector to add all the elements from */ inline void addVector(const TemplateVector<DATA_TYPE> & a_vector) { for(int i = 0; i < a_vector.size(); ++i) { add(a_vector.get(i)); } } /** @return the size of the list */ inline const int & size() const { return m_size; } /** * @param size the user wants the vector to be (chopping off elements) * @return false if could not allocate memory * @note may cause memory allocation if size is bigger than current */ inline bool setSize(const int & a_size) { if(!ensureCapacity(a_size)) return false; m_size = a_size; return true; } /** sets size to zero, but does not deallocate any memory */ inline void clear() { setSize(0); } /** * @param a_index is overwritten by the next element, which is * overwritten by the next element, and so on, till the last element */ void remove(const int & a_index) { moveDown(a_index, -1, m_size); setSize(m_size-1); } /** * @param a_index where to insert a_value. shifts elements in the vector. */ void insert(const int & a_index, const DATA_TYPE & a_value) { setSize(m_size+1); moveUp(a_index, 1, m_size); set(a_index, a_value); } /** * @return first element from the list and moves the rest up * @note removes the first element from the list */ inline const DATA_TYPE pull() { DATA_TYPE value = get(0); remove(0); return value; } /** @param a_index is replaced by the last element, then size is reduced. */ inline void removeFast(const int & a_index) { swap(a_index, m_size-1); setSize(m_size-1); } /** @return the index of the first appearance of a_value in this vector. uses == */ inline int indexOf(const DATA_TYPE & a_value) const { for(int i = 0; i < m_size; ++i) { if(get(i) == a_value) return i; } return -1; } /** @return index of 1st a_value at or after a_startingIndex. uses == */ inline int indexOf(const DATA_TYPE & a_value, const int & a_startingIndex) const { return TemplateArray::indexOf(a_value, a_startingIndex, m_size); } /** @return index of 1st a_value at or after a_startingIndex. uses == */ inline int indexOf(const DATA_TYPE & a_value, const int & a_startingIndex, int const & a_size) const { return TemplateArray::indexOf(a_value, a_startingIndex, a_size); } /** * will only work correctly if the TemplateVector is sorted. * @return the index of the given value, -1 if the value is not in the list */ int indexOfWithBinarySearch(const DATA_TYPE & a_value) { if(m_size) { return TemplateArray::indexOfWithBinarySearch(a_value, 0, m_size); } return -1; // failed to find key } /** * uses binary sort to put values in the correct index. safe if soring is always used * @param a_value value to insert in order * @param a_allowDuplicates will not insert duplicates if set to false * @return the index where a_value was inserted */ int insertSorted(const DATA_TYPE & a_value, const bool & a_allowDuplicates) { int index; if(!m_size || a_value < get(0)) { index = 0; } else if(!(a_value < get(m_size-1))) { index = m_size; } else { int first = 0, last = m_size; while (first <= last) { index = (first + last) / 2; if (!(a_value < m_data[index])) first = index + 1; else if (a_value < m_data[index]) last = index - 1; } if(!(a_value < m_data[index])) index++; } if(!m_size || a_allowDuplicates || a_value != m_data[index]) insert(index, a_value); return index; } /** * @param a_value first appearance replaced by last element. breaks if not in list */ inline void removeDataFast(const DATA_TYPE & a_value) { removeFast(indexOf(a_value)); } /** * @param a_listToExclude removes these elements from *this list * @return true if at least one element was removed */ inline bool removeListFast(const TemplateVector<DATA_TYPE> & a_listToExclude) { bool aTermWasRemoved = false; for(int e = 0; e < a_listToExclude.size(); ++e) { for(int i = 0; i < size(); ++i) { if(a_listToExclude.get(e) == get(i)) { removeFast(i); --i; aTermWasRemoved = true; } } } return aTermWasRemoved; } /** @param a_value first appearance is removed. breaks if not in list */ inline void removeData(const DATA_TYPE & a_value) { remove(indexOf(a_value)); } /** destructor */ inline ~TemplateVector() { release(); } };
C++
#include "Animation.h" // basic constructor Animation::Animation() { m_index = 0; m_playing = false; } // make sure safer release is called Animation::~Animation() {} // setup the animation based on the appopriate spritesheet values void Animation::initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, float fps, bool a_loop, bool relativeToCamera) { // setup sprite sheet of animation SpriteSheet::initialize(fileName,count,numRows,numColumns,spriteWidth,spriteHeight, relativeToCamera); // set type to animation m_type = ANIMATION; m_playing = false; m_loop = a_loop; // calculate frames per second m_frameSwitch.initialize( (float)m_rects.size() / fps ); } // update the animation timer void Animation::update(float dT) { // if the animation is running update the frames if( m_playing ) { // update timer m_frameSwitch.update(dT); // if the timer has finished then switch frames if( !m_frameSwitch.isActive() ) { // if the end has been reached either loop or end animation if( m_index >= m_rects.size() - 1) { // loop the animation if( m_loop ) { m_index = 0; m_frameSwitch.activate(); } // end the animation else { m_frameSwitch.deActivate(); m_playing = false; } } // animation has not reached the end else { m_index++; m_frameSwitch.activate(); } } } } // set current frame and reset the timer void Animation::setCurrentFrame(int index) { // make sure the sprite exists if( setCurrentSprite(index) ) { // reset frameswitch if it is currently running if(m_frameSwitch.isActive()) { m_frameSwitch.deActivate(); m_frameSwitch.activate(); } } } // pause the animation at its current frame void Animation::pause() { m_playing = false; } // start the animation from its current frame void Animation::play() { m_playing = true; // start the timer m_frameSwitch.activate(); } // reset to the first frame // pause afterwards if true void Animation::reset(bool pause) { // first reset to first frame m_index = 0; // reset the timer m_frameSwitch.deActivate(); if(pause) { // stop the animation m_playing = false; } else // otherwise re-activate the timer m_frameSwitch.activate(); }
C++
#pragma once #include "HelpfulData.h" #include "Texture.h" extern class Item; // used as return type for collision function // NONE = no collision occured // MAIN = only the main rect was collided with or only the main rect was checked // RIGHT, LEFT, TOP, BOT = corresponding side was collided enum SIDE {NONE,RIGHT,LEFT,TOP,BOT,MAIN}; enum Facing { NORTH, SOUTH, EAST, WEST }; enum EntityType { PLAYER, ENEMY, BOSS, OTHER }; struct Stats { int health; int str; int tough; int agil; int weight; }; // used to save collisions that have occured struct Collision { FRect m_rect; SIDE m_side; float m_pen; }; class Entity { protected: V2DF position; bool dead; float scale; int rotation; Texture tex; Facing orientation; Stats stats; FRect m_boundRect; FRect m_right; FRect m_left; FRect m_top; FRect m_bottom; TemplateVector<Collision> m_collisions; public: Entity(); ~Entity(); virtual void initialize(V2DF pos, const wchar_t* a_tex, FRect a_rect, float a_scale) { position = pos; tex.initialize(a_tex, true); scale = a_scale; } virtual void render() { tex.draw(position, rotation, scale); } virtual void update() {}; virtual void onDeath() {} void setPosition(V2DF nPos) { position = nPos; } V2DF getPosition() { return position; } void takeDamage(int amount); void setFacing(Facing orientation); void heal() { stats.health++; } // Detects if the given entity is colliding with this entity // If the checkSides flag is true it will detect which side the collision occurded on and ... // ...calculate interpentration as well as move the entities apart. // All collisions that occured this frame are stored in the m_collisions vector and are resovled by the... // ...resolveCollisions() function // returns a SIDE to based on what occured NONE = no collision, MAIN = only the main // RIGHT, LEFT, TOP, BOT = the appropriate side was collided with // checkSides true = check sub rects, false = ignore // NOTE:: the entity making the function call is the one that will be moved, other will be left were it is... // ...this also means that only the calling entities sub rects will be taken into account SIDE collisionCheck(Entity * other, bool checkSides) { // first determine if the entites main rects are colliding // get the rects relative to positions FRect rectA = getRelativeBoundRect(); // get the relative rect of the other entity FRect rectB = other->getRelativeBoundRect(); Collision col; // check if they are colliding if( colliding(rectA, rectB) ) { // used to store return value SIDE temp = MAIN; // now determine if sides need to be checked if(checkSides) { // check each subRect in the order RIGHT, LEFT, TOP, BOTTOM // RIGHT rectA = getSubRect(RIGHT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.right - rectB.left); col.m_side = RIGHT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = RIGHT; } // LEFT rectA = getSubRect(LEFT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.left - rectB.right); col.m_side = LEFT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = LEFT; } // TOP rectA = getSubRect(TOP); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.top - rectB.bottom); col.m_side = TOP; col.m_rect = rectB; m_collisions.add(col); // set return value temp = TOP; } // BOTTOM rectA = getSubRect(BOT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.bottom - rectB.top); col.m_side = BOT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = BOT; } } return temp; } // no collision occurd return none return NONE; } // overload of the previous function // functions exactly the same although it takes in a rect rather than another entity SIDE collisionCheck(FRect rectB, bool checkSides) { // first determine if the entites main rects are colliding // get the rects relative to positions FRect rectA = getRelativeBoundRect(); Collision col; // check if they are colliding if( colliding(rectA, rectB) ) { // used to store return value SIDE temp = MAIN; // now determine if sides need to be checked if(checkSides) { // check each subRect in the order RIGHT, LEFT, TOP, BOTTOM // RIGHT rectA = getSubRect(RIGHT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.right - rectB.left); col.m_side = RIGHT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = RIGHT; } // LEFT rectA = getSubRect(LEFT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.left - rectB.right); col.m_side = LEFT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = LEFT; } // TOP rectA = getSubRect(TOP); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.top - rectB.bottom); col.m_side = TOP; col.m_rect = rectB; m_collisions.add(col); // set return value temp = TOP; } // BOTTOM rectA = getSubRect(BOT); if( colliding(rectA, rectB) ) { // calculate interpenetration distance col.m_pen = (rectA.bottom - rectB.top); col.m_side = BOT; col.m_rect = rectB; m_collisions.add(col); // set return value temp = BOT; } } return temp; } // no collision occurd return none return NONE; } // resovle all collisions saved in the m_collisions vector and then clears the vector void resolveCollisions() { // get a copy of this entity's bound rect FRect rectA = getRelativeBoundRect(); // used to hold the current collisions being resloved Collision bestVert; bestVert.m_pen = 0.0f; bestVert.m_rect = rectA; bestVert.m_side = MAIN; Collision bestHoriz; bestHoriz.m_pen = 0.0f; bestHoriz.m_rect = rectA; bestHoriz.m_side = MAIN; // only search through the list if there was more than 1 collision if(m_collisions.size() > 0) { //assume the first collision is the best if( m_collisions.get(0).m_side == RIGHT || m_collisions.get(0).m_side == LEFT ) bestHoriz = m_collisions.get(0); else bestVert = m_collisions.get(0); // go through the list of collisions and find the closest horizantel and vertical components to the entity for(int i = 1; i < m_collisions.size(); ++i) { // first determine if this was a horizantal or vertical collision if ( m_collisions.get(i).m_side == RIGHT || m_collisions.get(i).m_side == LEFT ) { // check against the best horizantal if( m_collisions.get(i).m_pen < bestHoriz.m_pen || bestHoriz.m_pen == 0) bestHoriz = m_collisions.get(i); } else { // check against the best vertical if( m_collisions.get(i).m_pen < bestVert.m_pen || bestVert.m_pen == 0) bestVert = m_collisions.get(i); } } // now augment the position based on these values position.x -= bestHoriz.m_pen; position.y -= bestVert.m_pen; // remember to clear the list of collisions m_collisions.clear(); } } // return a bound rect relative to position FRect getRelativeBoundRect() { FRect temp; temp.top = position.y + m_boundRect.top; temp.left = position.x + m_boundRect.left; temp.right = position.x + m_boundRect.right; temp.bottom = position.y + m_boundRect.bottom; return temp; } // return a copy of the bound rect FRect getBoundRect() { return m_boundRect; } // return a sub bound rect of the given side relative to position FRect getSubRect(SIDE side) { FRect temp; switch(side) { case RIGHT: temp.top = position.y + m_right.top; temp.left = position.x + m_right.left; temp.right = position.x + m_right.right; temp.bottom = position.y + m_right.bottom; break; case LEFT: temp.top = position.y + m_left.top; temp.left = position.x + m_left.left; temp.right = position.x + m_left.right; temp.bottom = position.y + m_left.bottom; break; case TOP: temp.top = position.y + m_top.top; temp.left = position.x + m_top.left; temp.right = position.x + m_top.right; temp.bottom = position.y + m_top.bottom; break; case BOT: temp.top = position.y + m_bottom.top; temp.left = position.x + m_bottom.left; temp.right = position.x + m_bottom.right; temp.bottom = position.y + m_bottom.bottom; break; } return temp; } };
C++
#pragma once /** * a simple HashMap data structure, using TemplateVectors of KeyValuePairs as * buckets. The hash size is DEFAULT_BUCKET_SIZE, or 32. The hashFunction * values between 0 and 31 by bitshifting and masking */ template <class KEY, class VALUE> class TemplateHashMap { struct KeyValuePair { KEY k; VALUE v; KeyValuePair(){} KeyValuePair(KEY k):k(k){} KeyValuePair(KEY k, VALUE v):k(k),v(v){} // operators overloaded for TemplateVector bool operator<(KeyValuePair const & kvp){return k < kvp.k;} bool operator>(KeyValuePair const & kvp){return k > kvp.k;} bool operator==(KeyValuePair const& kvp){return k ==kvp.k;} }; TemplateVector<TemplateVector<KeyValuePair>> hash; static const int DEFAULT_BUCKET_SIZE = 32; public: void clear(){ for(int i = 0; i < hash.size(); ++i) hash.get(i).clear(); } TemplateHashMap() { hash.setSize(DEFAULT_BUCKET_SIZE); } int hashFunction(KEY k) { // the KEY could very likely be pointer. This hash will turn memory // addresses that are int-aligned into possibly consecutive keys, and // essentially modulo 32, accomplished here by bitwise-and-ing 32-1 return (((int)k) >> (sizeof(int) >> 1)) & 31; } /** @return the value associated with the given KEY */ VALUE * getByKey(KEY k) { int index = hashFunction(k); TemplateVector<KeyValuePair> * bucket = &hash.get(index); KeyValuePair kvp(k); int bucketIndex = bucket->indexOf(kvp); if(bucketIndex < 0) return 0; return &bucket->get(bucketIndex).v; } /** sets up a key/value pair association */ void set(KEY k, VALUE v) { int index = hashFunction(k); TemplateVector<KeyValuePair> * bucket = &hash.get(index); bucket->add(KeyValuePair(k,v)); } };
C++
#pragma once #include <math.h> // drawing and math methods that require the libraries above #define V2D_SIN sin #define V2D_COS cos // modify this if changing V2D's data types #define V2D_GLVERTEX_METHOD glVertex2fv // PI defined to reduce dependency on other math libraries #define V2D_PI (3.14159265358979323846) #define V2D_2PI (V2D_PI*2) #define V2D_HALFPI (V2D_PI/2) #define V2D_QUARTERPI (V2D_PI/4) // standard for V2D floats #define __VTYPE float // standard V2D using floats #define V2DF V2D<__VTYPE> #define V2DI V2D<int> /** * a two dimensional vector class, which includes methods to handle 2D * geometric calculation, including rotation in various circumstances. * @author mvaganov@hotmail.com April 2010 */ template<typename VTYPE> class V2D { protected: public: /** position in 2 Dimensional space */ VTYPE x, y; /** how many dimensions a V2D<VTYPE> keeps track of (sizeof(V2D)/sizeof(VTYPE)) */ static const int NUM_DIMENSIONS = 2; /** to access this class's type later */ typedef VTYPE type; /** the first (initial) dimension */ static const int _X = 0; /** the second dimension */ static const int _Y = 1; /** access X */ inline const VTYPE & getX()const{return x;} /** access Y */ inline const VTYPE & getY()const{return y;} /** mutate X */ inline void setX(const VTYPE & a_value){x=a_value;} /** mutate Y */ inline void setY(const VTYPE & a_value){y=a_value;} /** mutate X */ inline void addX(const VTYPE & a_value){x+=a_value;} /** mutate Y */ inline void addY(const VTYPE & a_value){y+=a_value;} /** @return array containing points of this vector ([V2D::X], [V2D::Y]) */ inline const VTYPE * getDimensions()const{return &x;} /** @return getDimensions()[a_dimensionField] */ inline VTYPE getField(const int & a_dimensionField)const{return getDimensions()[a_dimensionField];} /** getDimensions()[a_dimensionField]=a_value; */ inline void setField(const int & a_dimensionField, const VTYPE & a_value){(&x)[a_dimensionField]=a_value;} /** @param a_axis {X, Y} */ inline void flipAxis(const int & a_axis){(&x)[a_axis]*=-1;} /** resets the value of this vector */ inline void set(const VTYPE & a_x, const VTYPE & a_y){x = a_x; y = a_y;} /** copy another vector */ inline void set(const V2D<VTYPE> & a_v2d){set(a_v2d.x, a_v2d.y);} /** default constructor */ V2D():x(0.0),y(0.0){} /** complete constructor */ V2D(VTYPE a_x, VTYPE a_y):x(a_x),y(a_y){} /** turns a pi-radians angle into a vector */ V2D(VTYPE a_piRadians):x(V2D_COS(a_piRadians)), y(V2D_SIN(a_piRadians)){} /** copy constructor */ V2D(const V2D<VTYPE> & v):x(v.x),y(v.y){} /** sets x and y to zero */ inline void zero(){x=y=0;} /** * declares a "global" variable in a function, which is OK in a template! * (can't declare globals in headers otherwise) */ inline static const V2D<VTYPE> & ZERO() {static V2D<VTYPE> ZERO(0,0); return ZERO;} inline static const V2D<VTYPE> & ZERO_DEGREES() {static V2D<VTYPE> ZERODEGREES(1,0); return ZERODEGREES;} /** * @return true if both x and y are zero * @note function is not allowed to modify members in V2D */ inline bool isZero() const {return x == 0 && y == 0;} /** @return if both x and y are less than the given x and y */ inline bool isLessThan(const V2D<VTYPE> & p)const{return x<p.x&&y<p.y;} /** @return if both x and y are greaterthan or equl to the given x and y */ inline bool isGreaterThanOrEqualTo(const V2D<VTYPE> & p)const{return x>=p.x&&y>=p.y;} /** @return the squared length of the vector (avoids sqrt) "quadrance" */ inline VTYPE lengthSq() const{return (VTYPE)(x*x+y*y);} /** @return the length of the vector (uses sqrt) */ inline VTYPE length() const{return sqrt((VTYPE)lengthSq());} /** @return dot product of this and v2 */ inline VTYPE dot(const V2D<VTYPE> & v2) const { return (VTYPE)(x * v2.x + y * v2.y); } /** * @return positive if v2 is clockwise of this vector * (assume Y points down, X to right) */ inline VTYPE sign(const V2D<VTYPE> & v2) const{return (x*v2.y)-(y*v2.x);} /** @return the vector perpendicular to this one */ inline V2D<VTYPE> perp() const{return V2D(-y, x);} /** @param a_length what to set this vector's magnitude to */ inline void setLength(const VTYPE & a_length) { VTYPE l = length(ll); // "x = (x * a_maxLength) / l" is more precise than "x *= (a_maxLength/l)" x = (x * a_maxLength) / l; y = (y * a_maxLength) / l; } /** * @param a_maxLength x and y adjusts so that the length does not exceed this */ inline void truncate(const VTYPE & a_maxLength) { VTYPE max2 = a_maxLength*a_maxLength; VTYPE ll = lengthSq(); if(ll > max2) { VTYPE l = sqrt(ll); // "x = (x * a_maxLength) / l" is more precise than "x *= (a_maxLength/l)" x = (x * a_maxLength) / l; y = (y * a_maxLength) / l; } } /** @return the distance square between this vector and v2 (avoids sqrt) */ inline VTYPE distanceSq(const V2D<VTYPE> & v) const { VTYPE dx = x-v.x, dy = y-v.y; return dx*dx+dy*dy; } /** @return the distance between this vector and v2 */ inline VTYPE distance(const V2D<VTYPE> & v) const{return sqrt(distanceSq(v));} /** @return the vector that is the reverse of this vector */ inline V2D<VTYPE> getReverse() const { return V2D<VTYPE>(-x, -y); } /** @return a new V2D<VTYPE> that is the sum of this V2D<VTYPE> and v */ inline V2D<VTYPE> sum(const V2D<VTYPE> & v) const { return V2D<VTYPE>(x+v.x, y+v.y); } /** @return a new V2D<VTYPE> that is the difference of this V2D<VTYPE> and v */ inline V2D<VTYPE> difference(const V2D<VTYPE> & v) const { return V2D<VTYPE>(x-v.x, y-v.y); } /** @return a new V2D<VTYPE> that is the product of this V2D<VTYPE> and v */ inline V2D<VTYPE> product(const V2D<VTYPE> & v) const { return V2D<VTYPE>(x*v.x, y*v.y); } /** @return a new V2D<VTYPE> that is the product of this V2D<VTYPE> and v */ inline V2D<VTYPE> product(const VTYPE & a_value) const { return V2D<VTYPE>(x*a_value, y*a_value); } /** @return a new V2D<VTYPE> that is the quotient of this V2D<VTYPE> and the given V2D*/ inline V2D<VTYPE> quotient(const VTYPE & a_value) const { return V2D<VTYPE>(x/a_value, y/a_value); } /** @return a new V2D<VTYPE> that is the quotient of this V2D<VTYPE> and the given V2D<VTYPE> */ inline V2D<VTYPE> quotient(const V2D<VTYPE> & v) const { return V2D<VTYPE>(x/v.x, y/v.y); } /** @return this V2D<VTYPE> after adding v */ inline const V2D<VTYPE> & add(const V2D<VTYPE> & v) { x += v.x; y += v.y; return *this; } /** @return this V2D<VTYPE> after subtracting v */ inline const V2D<VTYPE> & subtract(const V2D<VTYPE> & v) { x -= v.x; y -= v.y; return *this; } /** @return this V2D<VTYPE> after multiplying v */ inline V2D<VTYPE> & multiply(const VTYPE & a_value) { x *= a_value; y *= a_value; return *this; } /** @return this V2D<VTYPE> after multiplying v */ inline V2D<VTYPE> & multiply(const V2D<VTYPE> & v) { x *= v.x; y *= v.y; return *this; } /** @return this V2D<VTYPE> after dividing v */ inline V2D<VTYPE> & divide(const VTYPE & a_value) { x /= a_value; y /= a_value; return *this; } /** @return this V2D<VTYPE> after dividing v */ inline V2D<VTYPE> & divide(const V2D<VTYPE> & v) { x /= v.x; y /= v.y; return *this; } /** @return if this V2D<VTYPE> is euqal to v */ inline bool isEqual(const V2D<VTYPE> & v) const { return (x == v.x && y == v.y); } /** @return true if this point is within a_radius from a_point */ inline bool isWithin(const VTYPE & a_radius, const V2D<VTYPE> & a_point) const { VTYPE rr = a_radius*a_radius; return this->distanceSq(a_point) <= rr; } /** @return if this point is between the rectangle inscribed by the given corners */ inline bool isBetweenRect(const V2D<VTYPE> & a, const V2D<VTYPE> & b) { return((a.x <= b.x)?(x>=a.x&&x<=b.x):(x>=b.x&&x<=a.x)) &&((a.y <= b.y)?(y>=a.y&&y<=b.y):(y>=b.y&&y<=a.y)); } /** @return true if the given vector is equivalant to this one */ inline bool equals(const V2D<VTYPE> & v)const {return x == v.x && y == v.y;} /** forces vector to have a length of 1 */ inline V2D<VTYPE> & normalize() { divide(length()); return *this; } /** a normalized verson of this vector */ inline V2D<VTYPE> normal() const { V2D<VTYPE> norm(*this); return norm.normalize(); } /** @return radians between these normalized vector is */ inline VTYPE piRadians(const V2D<VTYPE> & v) const { return V2D_COS(dot(v)); } /** @return radians that this normalized vector is */ inline VTYPE piRadians() const { return (y<0?-1:1)*piRadians(ZERO_DEGREES()); } /** @return how many degrees (standard 360 degree scale) this is */ inline VTYPE degrees() const { // altered by ME // Math. is not needed here return ((y > 0)?-1:1) * acos(x) * 180/V2D_PI; } /** @param a_normal cos(theta),sin(theta) as x,y values */ inline void rotate(const V2D<VTYPE> & a_normal) { VTYPE len = length(); // remember length data // normalize() // turn vector into simple angle, lose length data divide(len); // same as normalize, but one less function call // calculate turn in-place within a new data structure V2D<VTYPE> turned( // x_ = x*cos(theta) - y*sin(theta) x*a_normal.x - y*a_normal.y, // y_ = x*sin(theta) + y*cos(theta) x*a_normal.y + y*a_normal.x); // memory copy of structure *this = turned; // put length data back into normalized vector multiply(len); } /** @param a_degreePiRadians in piRadians */ inline void rotate(const VTYPE & a_degreePiRadians) { rotate(V2D<VTYPE>(V2D_COS(a_degreePiRadians), V2D_SIN(a_degreePiRadians))); } /** * @param a_fwd rotate this point's x axis to match this vector * @param a_side rotate this point's y axis to match this vector */ inline V2D<VTYPE> toWorldSpace(const V2D<VTYPE> & a_fwd, const V2D<VTYPE> & a_side, const V2D<VTYPE> & a_pos) const { return V2D<VTYPE>( (a_fwd.x*x) + (a_side.x*y) + (a_pos.x), (a_fwd.y*x) + (a_side.y*y) + (a_pos.y)); } /** * @param a_fwd rotate this point's x axis to match this vector * @param a_side rotate this point's y axis to match this vector */ inline V2D<VTYPE> toWorldSpace(const V2D<VTYPE> & a_fwd, const V2D<VTYPE> & a_side, const V2D<VTYPE> & a_pos, const V2D<VTYPE> & a_scale) const { return V2D<VTYPE>( (a_scale.x*a_fwd.x*x) + (a_scale.y*a_side.x*y) + (a_pos.x), (a_scale.x*a_fwd.y*x) + (a_scale.y*a_side.y*y) + (a_pos.y)); } /** * @param a_fwd rotate this point's x axis to match this vector * @param a_side rotate this point's y axis to match this vector */ inline V2D<VTYPE> toWorldSpace(const V2D<VTYPE> & a_fwd, const V2D<VTYPE> & a_side) const { return V2D<VTYPE>((a_fwd.x*x) + (a_side.x*y), (a_fwd.y*x) + (a_side.y*y)); } /** * @param a_fwd vector of translated x dimension * @param a_side vector of translated y dimension * @param a_origin origin to translate this point in relation to */ inline V2D<VTYPE> toLocalSpace(const V2D<VTYPE> & a_fwd, const V2D<VTYPE> & a_side, const V2D<VTYPE> & a_origin) const { VTYPE tx = -a_origin.dot(a_fwd); VTYPE ty = -a_origin.dot(a_side); return V2D<VTYPE>( (a_fwd.x*x) + (a_fwd.y*y) + (tx), (a_side.x*x) + (a_side.y*y) + (ty)); } /** * organizes a list of 2D vectors into a circular curve (arc) * @param a_startVector what to start at (normalized vector) * @param a_angle the angle to increment the arc by V2D(piRadians) * @param a_list the list of 2D vectors to map along the arc * @param a_arcs the number of elements in a_list */ static void arc(const V2D<VTYPE> & a_startVector, const V2D<VTYPE> & a_angle, V2D<VTYPE> * a_list, const int & a_arcs) { VTYPE len = a_startVector.length(); // remember length data a_list[0] = a_startVector; // copy starting point for calculations a_list[0].divide(len); // normalize starting point V2D<VTYPE> * lastPoint = &a_list[0]; // faster memory reference than a_list[i-1] // calculate all points in the arc as normals (faster: no division) for(int i = 1; i < a_arcs; ++i) { // calculate rotation in next point (lastPoint+1)->set( // x_ = x*cos(theta) - y*sin(theta) lastPoint->x*a_angle.x - lastPoint->y*a_angle.y, // y_ = x*sin(theta) + y*cos(theta) lastPoint->x*a_angle.y + lastPoint->y*a_angle.x); ++lastPoint; } if(len != 1) { // put length data back into normalized vector for(int i = 0; i < a_arcs; ++i) { // embarassingly parallel a_list[i].multiply(len); } } } /** * ensures wraps this V2D's x/y values around the given rectangular range * @param a_min the minimum x/y * @param a_max the maximum x/y */ inline void wrapAround(const V2D<VTYPE> & a_min, const V2D<VTYPE> & a_max) { VTYPE width = a_max.x - a_min.x; VTYPE height= a_max.y - a_min.y; while(x < a_min.x){ x += width; } while(x > a_max.x){ x -= width; } while(y < a_min.y){ y +=height; } while(y > a_max.y){ y -=height; } } /** @return the position half-way between line a->b */ inline static V2D<VTYPE> between(const V2D<VTYPE> & a, const V2D<VTYPE> & b) { V2D<VTYPE> average = b.sum(a); average.divide(2.0); return average; } /** * @param A,B line 1 * @param C,D line 2 * @param point __OUT to the intersection of line AB and CD * @param dist __OUT the distance along line AB to the intersection * @return true if intersection occurs between the lines */ static inline bool lineIntersection(const V2D<VTYPE> & A, const V2D<VTYPE> & B, const V2D<VTYPE> & C, const V2D<VTYPE> & D, VTYPE & dist, V2D<VTYPE> & point) { VTYPE rTop = (A.y-C.y)*(D.x-C.x)-(A.x-C.x)*(D.y-C.y); VTYPE rBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x); VTYPE sTop = (A.y-C.y)*(B.x-A.x)-(A.x-C.x)*(B.y-A.y); VTYPE sBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x); if ( (rBot == 0) || (sBot == 0)) { //lines are parallel return false; } VTYPE r = rTop/rBot; VTYPE s = sTop/sBot; dist = A.distance(B) * r; point = A.sum(B.difference(A).product(r)); return ( (r > 0) && (r < 1) && (s > 0) && (s < 1) ); } /** * @param a_out_closestPoint will be closest point to a_point on line AB * @return true if a_out_closestPoint is actually on line AB */ static bool closestPointOnLine(const V2D<VTYPE> & A, const V2D<VTYPE> & B, const V2D<VTYPE> & a_point, V2D<VTYPE> & a_out_closestPoint) { V2D<VTYPE> r = B.difference(A).perp(); V2D<VTYPE> d = r.product(2).sum(a_point); V2D<VTYPE> c = a_point.difference(r); VTYPE dist; bool intersected = lineIntersection(A, B, c, d, dist, a_out_closestPoint); return intersected; } /** @return if circle (a_point,a_radius) crosses line (A,B) */ static bool lineCrossesCircle(const V2D<VTYPE> & A, const V2D<VTYPE> & B, const V2D<VTYPE> & a_point, const VTYPE & a_radius, V2D<VTYPE> & a_out_closePoint) { bool connectionOnLine = closestPointOnLine(A, B, a_point, a_out_closePoint); return(connectionOnLine && a_out_closePoint.distance(a_point) <= a_radius) || a_point.distance(A) < a_radius || a_point.distance(B) < a_radius; } // overloaded operators... used sparingly to avoid confusion const V2D<VTYPE> & operator+=(const V2D<VTYPE> & rhs){return add(rhs);} const V2D<VTYPE> & operator-=(const V2D<VTYPE> & rhs){return subtract(rhs);} const V2D<VTYPE> & operator*=(const VTYPE & rhs){return multiply(rhs);} const V2D<VTYPE> & operator/=(const VTYPE & rhs){return divide(rhs);} bool operator==(const V2D<VTYPE> & rhs) const{return isEqual(rhs);} bool operator!=(const V2D<VTYPE> & rhs) const{return !isEqual(rhs);} };
C++
#include "Graph.h" // default constructor Graph::Graph() {} // default destructor // :make sure safer release is called Graph::~Graph() { release(); } // safetly release all data void Graph::release() { // release the adjacency matrix for(int i = 0; i < m_size; ++i) { delete [] m_AdjacencyMatrix[i]; } delete [] m_AdjacencyMatrix; // release the graphNodes for(int i = 0; i < m_nodes.size(); ++i) { m_nodes.get(i)->release(); } // now release the list of nodes itself m_nodes.release(); // release the debug texture m_nodeTex.release(); m_neighborTex.release(); } // set up the graph to be the given size void Graph::initialize(int a_size) { // setup debug texture m_nodeTex.initialize(L"images/graph.png",true); m_neighborTex.initialize(L"images/neighbor.png",true); // setup graph to be the given size m_size = a_size; // create the adjaceny matrix m_AdjacencyMatrix = new bool*[m_size]; for(int i = 0; i < m_size; i++) m_AdjacencyMatrix[i] = new bool[m_size]; // initialize the entire matrix to false for(int y = 0; y < m_size; y++) for(int x = 0; x < m_size; x++) m_AdjacencyMatrix[y][x] = false; } // create a new node with the given world position // the node's id is returned // if -1 is returned an error occured // most likely cause is the graph is full int Graph::createNode(V2DF a_pos) { // first check if the graph is to big if( m_nodes.size() >= m_size ) return -1; // if the graph has room add the node GraphNode* temp = new GraphNode(); temp->initialize(a_pos); m_nodes.add(temp); // return this new nodes id return m_nodes.size() - 1; } // return a reference to the given graph node // return NULL if the node doesn't exist GraphNode* Graph::getNode(int a_node) { // make sure node exists if(a_node >= 0 && a_node < m_nodes.size()) { // return a reference to the node return m_nodes.get(a_node); } // node doesn't exist return NULL return 0; } // creates a one way connection between the two nodes going from start node to end node with the given cost void Graph::setOneWayConnection(int a_start, int a_end, int a_cost) { // make sure the nodes exist if( a_start <= -1 || a_start >= m_size || a_end <= -1 || a_end >= m_size || a_start >= m_nodes.size() || a_end >= m_nodes.size() ) return; // the nodes exist so create the connection // first update the adjacency matrix m_AdjacencyMatrix[a_start][a_end] = true; // second update the start node m_nodes.get(a_start)->addNeighbor( m_nodes.get(a_end), a_cost ); } // create a two way connection between nodes start and end each with their own cost // costA = start -> end // costB = end -> start void Graph::setTwoWayConnection(int a_start, int a_end, int costA, int costB) { // set first connection setOneWayConnection(a_start, a_end, costA); // set second connection setOneWayConnection(a_end, a_start, costB); } // create a two way connection between nodes start and end with the same cost void Graph::setTwoWayConnection(int a_start, int a_end, int a_cost) { // set first connection setOneWayConnection(a_start, a_end, a_cost); // set second connection setOneWayConnection(a_end, a_start, a_cost); } // Used for debugging void Graph::render() { for(int i = 0; i < m_nodes.size(); ++i) { V2DF parent = m_nodes.get(i)->getPosition(); V2DF dif(0.0f,0.0f); V2DF child(0.0f,0.0f); m_nodeTex.draw( parent, 0.0f, 1.0f ); // draw its neighbors float angle = 0.0f; TemplateVector<Connection>* m_neighbors = m_nodes.get(i)->getNeighbors(); for(int j = 0; j < m_neighbors->size(); ++j) { child = m_neighbors->get(j).neighbor->getPosition(); dif = child.difference(parent); angle = atan2f(dif.y,dif.x)*(180.0f/V2D_PI) + 90.0f; m_neighborTex.draw( parent, angle, 1.0f ); } } }
C++
#pragma once #include "Texture.h" #include "Animation.h" #include "HelpfulData.h" #include "Entity.h" enum WeaponType { FISTS, MANUAL, BAT, AIRPLANE, STAPLEGUN, SPRAY, NAILGUN } ; class Item { private: enum Type {CURRENCY, WEAPON, MISC, AMMO}; Type itemType ; int amount ; public: Item( ) {} //copy constructor Item( int type ) { itemType = (Type)type ; } ~Item( ) {} virtual void use() { --amount ; } void pickup() { ++amount ; } int GetItemType( ) { return itemType ; } }; class Weapon : Item { private: int str; int force; float range; Texture held; Animation animation; Entity bullets ; ClDwn atkDelay; WeaponType weapon ; public: }; class Misc : Item { private: //type of misc items available enum MiscType { KIT, KEY, SUPERGLUE, MEAT, REPELLENT, THROWING } ; Entity miscItem ; Entity* player ; //stores texture type and animation Texture held ; Animation animation ; //holds the type of this item MiscType type ; //used items that have an effect on the map for a time has a duration float duration ; //throwing weapons cause a fixed amount of damage int damage ; public: }; class Ammo : Item { private: enum AmmoType {NONE, TOY, PAPER, STAPLES, HOLYWATER, NAILS}; AmmoType type ; int amount ; public: int GetAmmoType( int w ) ; } ;
C++
#include "Tile.h" // default constructor Tile::Tile() {} // default destructor make sure release is called Tile::~Tile() { release(); } // safetly release all data void Tile::release() { m_tex.release(); } // setup tile of given type void Tile::initialize(V2DF pos, int tileType) { // load texture m_tex.initialize(L"images/tileset.png",2,1,2,32,32,true); // setup bounds m_bounds.top = m_tex.SpriteHeight()/-2.0f; m_bounds.bottom = m_tex.SpriteHeight()/2.0f; m_bounds.left = m_tex.SpriteWidth()/-2.0f; m_bounds.right = m_tex.SpriteWidth()/2.0f; // set tileType m_tileType = tileType; m_tex.setCurrentSprite(m_tileType); // set position m_position = pos; } void Tile::render() { m_tex.draw(m_position,0.0f,1.0f); } void Tile::update(float dT) {} // returns collision boundry relative to position FRect Tile::getBounds() { FRect temp = m_bounds; temp.right += m_position.x; temp.left += m_position.x; temp.top += m_position.y; temp.bottom += m_position.y; return temp; }
C++
#pragma once /** ideal when the size is known at creation time */ template<typename DATA_TYPE> class TemplateArray { protected: /** pointer to the allocated data for the vector */ DATA_TYPE * m_data; /** actual number of allocated elements that we can use */ int m_allocated; public: /** @return value from the list at given index */ inline DATA_TYPE & get(const int & a_index) const { return m_data[a_index]; } /** simple mutator sets a value in the list */ inline void set(const int & a_index, const DATA_TYPE & a_value) { // complex types must overload DATA_TYPE & operator=(const DATA_TYPE &) m_data[a_index] = a_value; } inline void moveDown(const int & a_from, const int & a_offset, int a_size) { for(int i = a_from-a_offset; i < a_size; ++i) { set(i+a_offset, get(i)); } } inline void moveUp(const int & a_from, const int & a_offset, int a_last) { for(int i = a_last-a_offset-1; i >= a_from; --i) { set(i+a_offset, get(i)); } } public: /** @param a_size reallocate the vector to this size */ const bool allocateToSize(const int & a_size) { // reallocate a new list with the given size DATA_TYPE * newList = new DATA_TYPE[a_size]; // if the list could not allocate, fail... if(!newList) return false; // the temp list is the one we will keep, while the old list will be dropped. DATA_TYPE * oldList = m_data; // swap done here so set(index, value) can be called instead of the equals operator m_data = newList; // if there is old data if(oldList) { // when copying old data, make sure no over-writes happen. int smallestSize = m_allocated<a_size?m_allocated:a_size; // fill the new list with the old data for(int i = 0; i < smallestSize; ++i) { set(i, oldList[i]); } // get rid of the old list (so we can maybe use the memory later) delete [] oldList; } // mark the new allocated size (held size of oldList) m_allocated = a_size; return true; } /** note: this method is memory intesive, and should not be in any inner loops... */ void add(const DATA_TYPE & a_value) { allocateToSize(size()+1); set(size()-1, a_value); } /** note: this method is memory intesive, and should not be in any inner loops... */ DATA_TYPE * add() { allocateToSize(size()+1); return &get(size()-1); } /** sets all fields to an initial data state. WARNING: can cause memory leaks if used without care */ inline void init() { m_data = 0; m_allocated = 0; } /** cleans up memory */ inline void release() { if(m_data) { delete [] m_data; m_data = 0; m_allocated = 0; } } ~TemplateArray(){release();} /** @return true if vector allocated this size */ inline bool ensureCapacity(const int & a_size) { if(a_size && m_allocated < a_size) { return allocateToSize(a_size); } return true; } /** @return true of the copy finished correctly */ inline bool copy(const TemplateArray<DATA_TYPE> & a_array) { if(m_allocated != a_array.m_allocated) { release(); allocateToSize(a_array.m_allocated); } for(int i = 0; i < a_array.m_allocated; ++i) { set(i, a_array.get(i)); } return false; } /** copy constructor */ inline TemplateArray( const TemplateArray<DATA_TYPE> & a_array) { init(); copy(a_array); } /** default constructor allocates no list (zero size) */ inline TemplateArray(){init();} /** size constructor */ inline TemplateArray(const int & a_size) { init(); ensureCapacity(a_size); } /** format constructor */ inline TemplateArray(const int & a_size, const DATA_TYPE & a_defaultValue) { init(); ensureCapacity(a_size); for(int i = 0; i < a_size; ++i) set(i, a_defaultValue); } /** @return the size of the list */ inline const int & size() const { return m_allocated; } /** @return the last value in the list */ inline DATA_TYPE & getLast() { return get(size()-1); } /** * @return the raw pointer to the data... * @note dangerous accessor. use it only if you know what you're doing. */ inline DATA_TYPE * getRawList() { return m_data; } /** * @param a_index is overwritten by the next element, which is * overwritten by the next element, and so on, till the last element * @note this operation is memory intensive! */ void remove(const int & a_index) { moveDown(a_index, -1, size()); allocateToSize(m_allocated-1); } /** * @param a_index where to insert a_value. shifts elements in the vector. * @note this operation is memory intensive! */ void insert(const int & a_index, const DATA_TYPE & a_value) { setSize(m_size+1); moveUp(m_data, a_index, 1, size()); set(a_index, a_value); } /** swaps to elements in the vector */ inline void swap(const int & a_index0, const int & a_index1) { DATA_TYPE temp = get(a_index0); set(a_index0, get(a_index1)); set(a_index1, temp); } /** @return index of 1st a_value at or after a_startingIndex. uses == */ inline int indexOf(const DATA_TYPE & a_value, const int & a_startingIndex, const int & a_endingIndex) const { for(int i = a_startingIndex; i < a_endingIndex; ++i) { if(get(i) == a_value) return i; } return -1; } /** @return index of 1st a_value at or after a_startingIndex. uses == */ inline int indexOf(const DATA_TYPE & a_value) const { return indexOf(a_value, 0, size()); } /** * will only work correctly if the TemplateVector is sorted. * @return the index of the given value, -1 if the value is not in the list */ int indexOfWithBinarySearch(const DATA_TYPE & a_value, const int & a_first, const int & a_limit) { if(m_allocated) { int first = a_first, last = a_limit; while (first <= last) { int mid = (first + last) / 2; // compute mid point. if (a_value > m_data[mid]) first = mid + 1; // repeat search in top half. else if (a_value < m_data[mid]) last = mid - 1; // repeat search in bottom half. else return mid; // found it. return position } } return -1; // failed to find key } void setAll(const DATA_TYPE & a_value) { for(int i = 0; i < size(); ++i) { set(i, a_value); } } bool isSorted() { bool sorted = true; for(int i = 1; sorted && i < size(); ++i) { sorted = get(i) >= get(i-1); } return sorted; } };
C++
#pragma once #include "Sound.h" #include "Input.h" #include "Graphics_Lib.h" #include "Entity.h" #include "Player.h" #include "World.h" enum G_State {MENU, CLASS, GAME, DEAD, VICTORY}; // contains all game components class GameEngine { private: bool running; G_State m_state; // audio Sound* pSound; // Input Input* pInput; // Graphics DX2DEngine* p2DEngine; float m_cameraSpeed; /** entity test */ Entity test; Player player; World tWorld; public: GameEngine(); ~GameEngine(); void initialize(); void update(float dT); void render(); void drawText(); void release(); bool isRunning(); void setRunning(bool a_run); void setState(G_State state); };
C++
// // This header file is full of usual unversal functions, structs, classes and other includes // #pragma once #include <math.h> #include <time.h> #include <stdlib.h> #include <Windows.h> #include "templatearray.h" #include "templatevector.h" #include "v2d.h" #include <stdio.h> //#include <vld.h> #include <new.h> #define GRID_SIZE 32.0f #define HALF_GRID 16.0f #define BORDER 32.0f struct FRect { float top; float bottom; float right; float left; }; // used to control cool downs of actions // cooldowns/timers are based on the active bool // if active is false then the ability/action is useble // otherwise it is not // make sure to set active to true when the ability is used... // ... to start the timer class ClDwn { private: // cool down control variables float m_duration; float m_newDuration; float m_timePassed; bool m_active; public: ClDwn(); ~ClDwn(); void initialize(float duration); void update(float dT); void activate(); void deActivate(); bool isActive() { return m_active; } void changeDuration(float duration, bool ignoreAcitve); float getTimePassed() { return m_timePassed; } float getDuration() { return m_duration; } }; // seed the random number generator // WARNING: ONLY CALL ONCE AT INITIALIZATION OF GAME void seedRand(); // returns true if the two rects are colliding bool colliding(FRect r1, FRect r2); // returns true if the points lies within the rect bool colliding(V2DF point, FRect rect); // returns a random float between the two given numbers float randomFloat(float min, float max); // returns a random int between the two given numbers int randomInt(int min, int max); // takes in an float rect and converts it to an equivelent windows rect RECT fRectToRECT(FRect a_rect); // takes in a rect and converts it to an equivelent float rect FRect RECTtoFRect(RECT a_rect);
C++
#pragma once #include "SpriteSheet.h" #include "HelpfulData.h" class Animation : public SpriteSheet { private: ClDwn m_frameSwitch; bool m_playing; bool m_loop; public: Animation(); ~Animation(); void initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, float fps, bool a_loop, bool relativeToCamera); void update(float dT); void setCurrentFrame(int index); void loop(bool a_loop) { m_loop = a_loop; } void pause(); void reset(bool pause); void play(); };
C++
#include "Texture.h" // default constructor setting initial values to 0 Texture::Texture() { // set view rect to default m_viewRect.right = m_viewRect.left = m_viewRect.bottom = m_viewRect.top = -1; // set pointers to null engine = 0; } // make sure that safe release is called Texture::~Texture() { release(); } void Texture::setTint(int R, int G, int B) { m_R = R; m_G = G; m_B = B; } // setup texture object and load the given file void Texture::initialize(LPCWSTR fileName, bool relativeToCamera) { // set type to base texture m_type = BASIC; // save relativity to camera m_relativeToCamera = relativeToCamera; // set view rect to default m_viewRect.right = m_viewRect.left = m_viewRect.bottom = m_viewRect.top = -1; // first get an instance of the graphics engine if(!engine) engine = DX2DEngine::getInstance(); // set color to white by default m_R = m_G = m_B = 255; // get the length of fileName int i = 0; while(fileName[i] != 0) { i++; } // increment one more time for the null terminator i++; // also load from graphics engine textureID = engine->createTexture(fileName, i); } // safetly release all data void Texture::release() { //m_rects.release(); } // draw the texture with the given coordinates // layer is the Z layer the texture will be drawn at void Texture::draw(V2DF pos, float rotAngle, float scale) { int layer = 0; // make sure layer is less than 1 and greater than -1 if(layer >= 0.1) layer = .9; if(layer < 0) layer = 0; // check if a view rect has been set if(m_viewRect.top == -1) { // pass in view rect engine->renderTexture(textureID, pos, layer, scale, rotAngle, 0, m_R, m_G, m_B, m_relativeToCamera); } else { // pass in 0 for sprite sheet rect engine->renderTexture(textureID, pos, layer, scale, rotAngle, &m_viewRect, m_R, m_G, m_B, m_relativeToCamera); } } int Texture::imageHeight() { return engine->imageInfo(textureID).Height; } int Texture::imageWidth() { return engine->imageInfo(textureID).Width; } void Texture::resetViewRect() { m_viewRect.right = m_viewRect.left = m_viewRect.bottom = m_viewRect.top = -1; } // if the view rect is larger than the image it will be set to image limits void Texture::setViewRect(RECT a_viewRect) { // make sure that the rect is limited to the size of the image m_viewRect = a_viewRect; // restrict left if(m_viewRect.left < 0) m_viewRect.left = 0; if(m_viewRect.left > imageWidth()) m_viewRect.left = imageWidth(); // restrict right if(m_viewRect.right < 0) m_viewRect.right = 0; if(m_viewRect.right > imageWidth()) m_viewRect.right = imageWidth(); // restrict top if(m_viewRect.top < 0) m_viewRect.top = 0; if(m_viewRect.top > imageHeight()) m_viewRect.top = imageHeight(); // restrict bottom if(m_viewRect.bottom < 0) m_viewRect.bottom = 0; if(m_viewRect.bottom > imageHeight()) m_viewRect.bottom = imageHeight(); }
C++
#pragma once ////////////////////////////////////////////////////////////////////////// // FMOD ////////////////////////////////////////////////////////////////////////// #include <fmod.h> #include <fmod.hpp> #pragma comment(lib, "Fmodex_vc.lib") #define HIT 0 #define PRESS 1 #define FIRE 2 class Sound { private: FMOD::System *system; FMOD_RESULT result; unsigned int version; int numdrivers; FMOD_SPEAKERMODE speakermode; FMOD_CAPS caps; char name[256]; FMOD::Sound *m_soundEffects[3]; FMOD::Channel *m_BGMChannel; Sound(); public: static Sound* getInstance(); ~Sound(); void update(); void initialize(); void release(); void playSound(int sound); };
C++
#include "SpriteSheet.h" SpriteSheet::SpriteSheet() {} // make sure safer release is called SpriteSheet::~SpriteSheet() { release(); } // safetly release all data void SpriteSheet::release() { m_rects.release(); } // setup the texture and rects for the sprite sheet // numColumns : number of columns in sheet // numRows : number of rows in sheet // count : total number of sprites in sheet ( can be less than rows * columns ) // spriteHeight : height in pixels of each sprites // spriteWidth : width in pixels of each sprites void SpriteSheet::initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, bool relativeToCamera) { // setup basic sprite Texture::initialize(fileName,relativeToCamera); // set type to sprite sheet m_type = SHEET; // save rows and columns m_rows = numRows; m_columns = numColumns; // default draw sprite to 0 m_index = 0; // generate rects for the sheet // temp rect used to hold the data RECT temp; temp.top = 0; temp.left = 0; temp.right = spriteWidth; temp.bottom = spriteHeight; // control variable to stop generating rects when all are done bool done = false; // generate the individual rects for each sprite for(int y = 0; y < m_rows && !done; ++y) { for(int x = 0; x < m_columns && !done; ++x) { // first make sure count hasn't been succeed if( (x+(m_columns*y)) >= count ) { // all of the rects are finished exit the loops done = true; break; } // set up the rect temp.top = (y * spriteHeight); temp.bottom = (y + 1) * spriteHeight; temp.left = (x * spriteWidth); temp.right = (x + 1) * spriteWidth; // store in the rects list m_rects.add(temp); } } } // the rhe sprite to be drawn during render // returns true if the sprite existed and was set successfully // returns false otherwise bool SpriteSheet::setCurrentSprite(int index) { if( index >= 0 && index < m_rects.size() ) { m_index = index; return true; } return false; } // draw the current sprite at the given position with the given scale and angle void SpriteSheet::draw(V2DF pos, float rotAngle, float scale) { int layer = 0; // make sure layer is less than 1 and greater than -1 if(layer > 1) layer = 1; if(layer < 0) layer = 0; // get the sprite's rect RECT temp = m_rects.get(m_index); if(m_viewRect.top != -1) { // augment this rect by the view rect // only augment them if they are not equal if(temp.top != m_viewRect.top) temp.top -= m_viewRect.top; if(temp.left != m_viewRect.left) temp.left -= m_viewRect.left; if(temp.right != m_viewRect.right) temp.right -= m_viewRect.right; if(temp.bottom != m_viewRect.bottom) temp.bottom -= m_viewRect.bottom; } // draw the texture engine->renderTexture(textureID, pos, layer, scale, rotAngle, &temp, m_R, m_G, m_B, m_relativeToCamera); } // will be restricted to size of individual sprite void SpriteSheet::setViewRect(RECT a_viewRect) { // make sure that the rect is limited to the size of the image m_viewRect = a_viewRect; // restrict left if(m_viewRect.left < 0) m_viewRect.left = 0; if(m_viewRect.left > SpriteWidth()) m_viewRect.left = SpriteWidth(); // restrict right if(m_viewRect.right < 0) m_viewRect.right = 0; if(m_viewRect.right > SpriteWidth()) m_viewRect.right = SpriteWidth(); // restrict top if(m_viewRect.top < 0) m_viewRect.top = 0; if(m_viewRect.top > SpriteHeight()) m_viewRect.top = SpriteHeight(); // restrict bottom if(m_viewRect.bottom < 0) m_viewRect.bottom = 0; if(m_viewRect.bottom > SpriteHeight()) m_viewRect.bottom = SpriteHeight(); // now it will be re-made so that it represents the difference between a sprite-rect m_viewRect.top = m_rects.get(0).top - m_viewRect.top; m_viewRect.bottom = m_rects.get(0).bottom - m_viewRect.bottom; m_viewRect.left = m_rects.get(0).left - m_viewRect.left; m_viewRect.right = m_rects.get(0).right - m_viewRect.right; }
C++
#pragma once #include "Player.h" Player::Player() { tex.initialize(L"\images\test.png",true); stats.str = 0; stats.health = 0; stats.tough = 0; stats.agil = 0; stats.weight = 0; orientation = NORTH; speed = 300.0f; pInput = Input::getInstance(); } Player::~Player() { pInput->release(); } void Player::Update(float dT) { // Movement if(pInput->keyDown(DIK_W)) { position.y -= speed * dT; } if(pInput->keyDown(DIK_S)) { position.y += speed * dT; } if(pInput->keyDown(DIK_A)) { position.x -= speed * dT; } if(pInput->keyDown(DIK_D)) { position.x += speed * dT; } // Facing if(pInput->keyPressed(DIK_UP)) { orientation = NORTH; } if(pInput->keyPressed(DIK_DOWN)) { orientation = SOUTH; } if(pInput->keyPressed(DIK_LEFT)) { orientation = WEST; } if(pInput->keyPressed(DIK_RIGHT)) { orientation = EAST; } setFacing(orientation); DX2DEngine::getInstance()->setCamera(position); }
C++
#pragma once #include "Graphics_Lib.h" #include "HelpfulData.h" #include "Floor.h" extern class Entity; extern class GraphNode; #define NUM_FLOORS 10 class World { private: Floor m_floors[NUM_FLOORS]; int m_currentFloor; public: World(); ~World(); void release(); void initialize(); void setCurrentFloor(int nFloor); inline int getCurrentFloor() { return m_currentFloor; } bool FloorVisited(int floor); inline bool FloorVisited() { return m_floors[m_currentFloor].FloorVisited(); } bool FloorCleared(int floor); inline bool FloorCleared() { return m_floors[m_currentFloor].FloorCleared(); } bool WallCollision(Entity * entity); void update(float dT); void render(); //void renderMiniMap(); //void renderWorldMap(); inline GraphNode * getNode(V2DF position) { return m_floors[m_currentFloor].getNode(position); } inline GraphNode * getNode(int id) { return m_floors[m_currentFloor].getNode(id); } };
C++
#pragma once // Direct Input includes #include <dinput.h> #pragma comment(lib, "dinput8.lib") #pragma comment(lib, "dxguid.lib") #include "v2d.h" // This class handles input for the entire game and is a singleton for ease of use class Input { private: HWND m_hWnd; IDirectInput8 * m_pDInput; // Direct Input Object IDirectInputDevice8 * m_pKeyboard; // Keyboard Object IDirectInputDevice8 * m_pMouse; // Mouse Object // keyboard states bool keysLastUpdate[256]; // used to detect whether a given key was pressed last frame char mKeyboardState[256]; // mouse states DIMOUSESTATE2 mMouseState; Input(); public: ~Input(); void initialize(HINSTANCE hInst, HWND hWnd); void pollDevices(); void release(); bool keyDown(int key); bool keyPressed(int key); bool mouseButtonDown(int button); V2DF getMousePos(); static Input* getInstance(); };
C++
#pragma once #include "HelpfulData.h" #include "GraphNode.h" #include "Texture.h" class Graph { private: // the number of nodes in the graph int m_size; // relation ship of nodes in the graph bool **m_AdjacencyMatrix; // all nodes in the graph TemplateVector<GraphNode*> m_nodes; // texture used for debugging Texture m_nodeTex; Texture m_neighborTex; public: Graph(); ~Graph(); void release(); void initialize(int a_size); int createNode(V2DF a_pos); void setOneWayConnection(int a_start, int a_end, int cost); void setTwoWayConnection(int a_start, int a_end, int costA, int costB); void setTwoWayConnection(int a_start, int a_end, int costA); void render(); GraphNode* getNode(int a_node); };
C++
#pragma once #include "DX2DEngine.h" #include "HelpfulData.h" enum Orientation {TOP_LEFT,TOP_RIGHT,CENTER,BOT_RIGHT,BOT_LEFT,TOP_CENTER,BOT_CENTER}; class Message_Box { private: char * m_message; int m_length; V2DF m_pos; int m_width; int m_height; Orientation m_drawPoint; Orientation m_textPoint; int m_A; int m_R; int m_G; int m_B; public: Message_Box(); ~Message_Box(); void release(); void initialize(char * message, int length, V2DF pos, int width, int height, Orientation drawPoint, Orientation textPoint, int A, int R, int G, int B); void drawText(); void changeDrawPoint(Orientation drawPoint) { m_drawPoint = drawPoint; } void changeTextPoint(Orientation textPoint) { m_textPoint = textPoint; } V2DF getPosition() { return m_pos; } void changeMessage(char * message, int length); void changePosition(V2DF pos) { m_pos = pos; } float getWidth() { return m_width; } float getHeight() { return m_height; } void changeBounds(int width, int height) { m_width = width; m_height = height; } };
C++
#include "GraphNode.h" GraphNode::GraphNode() {} // make sure the safer release is called GraphNode::~GraphNode() {release();} void GraphNode::release() { m_neighbors.release(); } // setup node at given position void GraphNode::initialize(V2DF a_pos) { totalNeighbors = 0; m_position = a_pos; } // create a connection with the given neighbor and add it to the list void GraphNode::addNeighbor(GraphNode* a_neighbor, float a_cost) { totalNeighbors++; Connection temp; temp.neighbor = a_neighbor; temp.cost = a_cost; m_neighbors.add(temp); } int GraphNode::getNeighborCount() { return totalNeighbors; } TemplateVector<Connection>* GraphNode::getNeighbors() { return &m_neighbors; } V2DF GraphNode::getPosition() { return m_position; } // returns the hueristic value between the given node and this node float GraphNode::Hueristic(GraphNode* other) { // make sure other exists if(!other) return 0.0f; // calculate hueristic return other->getPosition().difference( m_position ).length(); }
C++
#include "MessageBox.h" // set data to defaults Message_Box::Message_Box() { m_message = 0; m_length = 0; } // make sure safer release is called Message_Box::~Message_Box() { release(); } // safetly release all data void Message_Box::release() { if(m_message) { delete [] m_message; m_message = 0; m_length = 0; } } // setup message box void Message_Box::initialize(char * message, int length, V2DF pos, int width, int height, Orientation drawPoint, Orientation textPoint, int A, int R, int G, int B) { // if a message already exists release it first if(m_message) release(); // setup message m_length = length; m_message = new char[m_length+1]; for(int i = 0; i < m_length; i++) { m_message[i] = message[i]; } m_message[m_length] = 0; // save position and bounds m_pos = pos; m_height = height; m_width = width; // save orientations m_drawPoint = drawPoint; m_textPoint = textPoint; // set color m_A = A; m_R = R; m_G = G; m_B = B; } // draw the message void Message_Box::drawText() { // get engine reference DX2DEngine * p2dEngine = DX2DEngine::getInstance(); // build rect from position and orientation RECT bounds; switch (m_drawPoint) { case TOP_LEFT: bounds.top = -m_height; bounds.left = -m_width; bounds.right = 0; bounds.bottom = 0; break; case TOP_RIGHT: bounds.top = -m_height; bounds.left = 0; bounds.right = m_width; bounds.bottom = 0; break; case CENTER: bounds.top = -m_height/2; bounds.left = -m_width/2; bounds.right = m_width/2; bounds.bottom = m_height/2; break; case BOT_RIGHT: bounds.top = 0; bounds.left = 0; bounds.right = m_width; bounds.bottom = m_height; break; case BOT_LEFT: bounds.top = 0; bounds.left = -m_width; bounds.right = 0; bounds.bottom = m_height; break; case TOP_CENTER: bounds.top = -m_height; bounds.left = -m_width/2; bounds.right = m_width/2; bounds.bottom = 0; break; case BOT_CENTER: bounds.top = 0; bounds.left = -m_width/2; bounds.right = m_width/2; bounds.bottom = m_height; break; default: break; } // add position bounds.right += m_pos.x; bounds.left += m_pos.x; bounds.top += m_pos.y; bounds.bottom += m_pos.y; DWORD formating; // determine orientation switch (m_textPoint) { case TOP_LEFT: formating = DT_TOP | DT_LEFT | DT_NOCLIP; break; case TOP_RIGHT: formating = DT_TOP | DT_RIGHT | DT_NOCLIP; break; case CENTER: formating = DT_CENTER | DT_VCENTER | DT_NOCLIP; break; case BOT_RIGHT: formating = DT_BOTTOM | DT_RIGHT | DT_NOCLIP; break; case BOT_LEFT: formating = DT_BOTTOM | DT_LEFT | DT_NOCLIP; break; case TOP_CENTER: formating = DT_TOP | DT_CENTER | DT_NOCLIP; break; case BOT_CENTER: formating = DT_BOTTOM | DT_CENTER | DT_NOCLIP; break; default: break; } // write text to the screen p2dEngine->writeText(m_message,bounds,D3DCOLOR_ARGB(255,m_R,m_G,m_B),formating); }
C++
#pragma once #include "Texture.h" class SpriteSheet : public Texture { protected: TemplateVector<RECT> m_rects; int m_index; int m_rows; int m_columns; public: SpriteSheet(); ~SpriteSheet(); void release(); void initialize(LPCWSTR fileName, int count, int numRows, int numColumns, int spriteWidth, int spriteHeight, bool relativeToCamera); bool setCurrentSprite(int index); virtual void draw(V2DF pos, float rotAngle, float scale); int getCurrentSprite() { return m_index; } int getImageCount() { return m_rects.size(); } int SpriteHeight() { return m_rects.get(0).bottom; } int SpriteWidth() { return m_rects.get(0).right; } int rows() { return m_rows; } int columns() { return m_columns; } void setViewRect(RECT a_viewRect); };
C++
#pragma once /////////////////////////////////////////////////////////////////////////// // General Windows includes /////////////////////////////////////////////////////////////////////////// #include <stdio.h> #pragma comment(lib, "winmm.lib") ////////////////////////////////////////////////////////////////////////// // Direct3D 9 headers and libraries required ////////////////////////////////////////////////////////////////////////// #include <d3d9.h> #include <d3dx9.h> #pragma comment(lib, "d3d9.lib") #pragma comment(lib, "d3dx9.lib") // used for windows error text box #include <WinUser.h> #include "v2d.h" #include "templatearray.h" #include "templatevector.h" #include "HelpfulData.h" // texture struct // saves the need for two lists of image info and images themselves struct TextureInfo { int length; // file name length char* name; // File name IDirect3DTexture9* m_pTexture; // Texture Object for a sprite D3DXIMAGE_INFO m_imageInfo; // File details of a texture }; // Singleton for basic graphics use // Simply an in-between making drawing 2d sprites in direct x easier class DX2DEngine { private: // Application variables HWND m_hWnd; bool m_bVsync; // Direct X objects/devices IDirect3D9* m_pD3DObject; // Direct3D 9 Object IDirect3DDevice9* m_pD3DDevice; // Direct3D 9 Device D3DCAPS9 m_D3DCaps; // Device Capabilities // Direct X sprites variable ID3DXSprite* m_pSprite; // Sprite Object // Direct X font variable ID3DXFont* m_pFont; // Font Object // Vector of currently loaded textures TemplateVector<TextureInfo*> m_textures; // frames per second int fps; // current number of frames rendered int frameCount; // elapsed time // used to calculate fps float elapsedTime; // camera controllers V2DF camera; V2DF screen_center; float zoom; DX2DEngine(); public: // basic functions ~DX2DEngine(); static DX2DEngine* getInstance(); void initialize(HWND& hWnd, HINSTANCE& hInst, bool bWindowed); void release(); // update to calculate fps void update(float dT); float getFPS(); // render controlers void start2DRender(); void end2DRender(); void startSprite(); void endSprite(); // accessors ID3DXSprite* spriteRef(); ID3DXFont* fontRef(); IDirect3DDevice9* deviceRef(); // Text drawing/writing functions void writeText(char *text, V2DF pos, float width, float height, D3DCOLOR color); void writeText(char *text, RECT bounds, D3DCOLOR color); void writeText(char *text, RECT bounds, D3DCOLOR color, DWORD format); void writeCenterText(char *text, RECT bounds, D3DCOLOR color); // Texture creation functions int createTexture(LPCWSTR file, int length); // Texture rendering functions void renderTexture(int index, // index of the texture V2DF pos, float layer, float scale, float angle, // position data RECT *m_sheetRect, // culling rect : used for sprite sheets int r, int g, int b, // color tint bool relativeToCamera); // true:draw relative to the camera false:don't void moveCamera(V2DF dist); void setCamera(V2DF pos); V2DF getCamera(); V2DF screenCenter(); void setZoom(float a_zoom); void zoomInOut(float aug); float getZoom(); D3DXIMAGE_INFO imageInfo(int textureID); };
C++
#include "Line.h" // make sure pointer is 0 Line::Line() { m_tex = 0; } // make sure safe release is called Line::~Line() { release(); } // safetly release all stored data void Line::release() { } // setup texture and start and end points void Line::initialize(Texture * a_tex, V2DF start, V2DF end) { // save texture reference m_tex = a_tex; // set start and end points m_start = start; m_end = end; calculate(); } // set start point and recalculate length/angle void Line::setStart(V2DF start) { // set start m_start = start; calculate(); } // set end point and recalculate length/angle void Line::setEnd(V2DF end) { // end points m_end = end; calculate(); } // determine how many times the texture must be drawn and if .... // a portion of the texture must be drawn void Line::calculate() { // save sprite height and width // if the texture is a sprite sheet or animation get the individual height and widht if(m_tex->getType() == SHEET || m_tex->getType() == ANIMATION) { // a sprite sheet pointer will work fine for either SpriteSheet * temp = (SpriteSheet*)m_tex; m_spriteHeight = temp->SpriteHeight(); m_spriteWidth = temp->SpriteWidth(); } // otherwise get the image height and width else { m_spriteHeight = m_tex->imageHeight(); m_spriteWidth = m_tex->imageWidth(); } // calculate length V2DF difference = m_end.difference(m_start); m_length = difference.length(); // calculate angle m_angle = atan2f(difference.y,difference.x)*(180.0f/V2D_PI); // determine the number of times the image must be drawn m_numSprites = (int)m_length / m_spriteHeight; // now check if a portion of a sprite must be drawn if( (int)m_length % m_spriteHeight != 0 ) { float remainder = m_spriteHeight - ( m_length - (m_spriteHeight * m_numSprites) ) ; RECT temp; // cut off the top of the texture temp.top = (int)remainder; // leave the rest the same temp.left = 0; temp.right = m_spriteWidth; temp.bottom = m_spriteHeight; m_lastSprite = temp; } } // render the line from start point to end point void Line::render() { // float angleRad = (V2D_PI / 180.0f) * wanderAngle; // steeringForce = V2DF( cos(angleRad), sin(angleRad) ).product( 10 ); // calculate half of the image length float halfImage = (float)m_spriteHeight / 2.0f; // convert angle to radians float angleRad = (V2D_PI / 180.0f) * m_angle; // create vector based on half image length and angle in radians V2DF halfImageLength( cos(angleRad), sin(angleRad) ); // get vector of full image length V2DF imageLength = halfImageLength.product( m_spriteHeight ); halfImageLength.multiply( halfImage ); // set up draw position V2DF drawPos; if(m_numSprites > 0) drawPos = m_start.sum( halfImageLength ); else drawPos = m_end; // reset textures view rect m_tex->resetViewRect(); // draw each sprite for(int i = 0; i < m_numSprites; i++) { // add image length if(i > 0) drawPos.add(imageLength); m_tex->draw(drawPos, m_angle+90.0f,1.0f); } // now check if a portion of a sprite must be drawn if( (int)m_length % m_spriteHeight != 0 ) { m_tex->setViewRect(m_lastSprite); if(m_numSprites > 0) { // determine mid point between end of the last full texture drawn and the end of the line drawPos.add(halfImageLength); drawPos = drawPos.difference(m_end).product(0.5f).sum(m_end); } else { // the length of the line is less than // determine the mid point between the start and end points of the line drawPos = m_start.difference(m_end).product(0.5f).sum(m_end); } // draw the final partial sprite m_tex->draw(drawPos,m_angle+90.0f,1.0f); } } // used if the texture is an animation void Line::update(float dT) { if( m_tex->getType() == ANIMATION ) { // update the texture Animation * temp = (Animation*)m_tex; temp->update(dT); } }
C++
#pragma once #include "Tile.h" #include "Entity.h" #include "Graph.h" #define FLOORSIZE 30 class Floor { private: Tile m_layout[FLOORSIZE][FLOORSIZE]; bool m_cleared; bool m_visited; public: Floor(); ~Floor(); void release(); void intialize(char * fileName); void update(float dT); void render(); bool WallCollision(Entity * entity); inline bool FloorCleared() { return m_cleared; } inline bool FloorVisited() { return m_visited; } GraphNode * getNode(V2DF position); GraphNode * getNode(int id); };
C++
/* * Copyright 2011, 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. */ #include <stdio.h> #include <malloc.h> #include "android/bitmap.h" #include "common.h" #include "baseapi.h" #include "allheaders.h" static jfieldID field_mNativeData; struct native_data_t { tesseract::TessBaseAPI api; PIX *pix; void *data; bool debug; native_data_t() { pix = NULL; data = NULL; debug = false; } }; static inline native_data_t * get_native_data(JNIEnv *env, jobject object) { return (native_data_t *) (env->GetIntField(object, field_mNativeData)); } #ifdef __cplusplus extern "C" { #endif jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("Failed to get the environment using GetEnv()"); return -1; } return JNI_VERSION_1_6; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClassInit(JNIEnv* env, jclass clazz) { field_mNativeData = env->GetFieldID(clazz, "mNativeData", "I"); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeConstruct(JNIEnv* env, jobject object) { native_data_t *nat = new native_data_t; if (nat == NULL) { LOGE("%s: out of memory!", __FUNCTION__); return; } env->SetIntField(object, field_mNativeData, (jint) nat); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeFinalize(JNIEnv* env, jobject object) { native_data_t *nat = get_native_data(env, object); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; if (nat != NULL) delete nat; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeInit(JNIEnv *env, jobject thiz, jstring dir, jstring lang) { native_data_t *nat = get_native_data(env, thiz); const char *c_dir = env->GetStringUTFChars(dir, NULL); const char *c_lang = env->GetStringUTFChars(lang, NULL); jboolean res = JNI_TRUE; if (nat->api.Init(c_dir, c_lang)) { LOGE("Could not initialize Tesseract API with language=%s!", c_lang); res = JNI_FALSE; } else { LOGI("Initialized Tesseract API with language=%s", c_lang); } env->ReleaseStringUTFChars(dir, c_dir); env->ReleaseStringUTFChars(lang, c_lang); return res; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImageBytes(JNIEnv *env, jobject thiz, jbyteArray data, jint width, jint height, jint bpp, jint bpl) { jbyte *data_array = env->GetByteArrayElements(data, NULL); int count = env->GetArrayLength(data); unsigned char* imagedata = (unsigned char *) malloc(count * sizeof(unsigned char)); // This is painfully slow, but necessary because we don't know // how many bits the JVM might be using to represent a byte for (int i = 0; i < count; i++) { imagedata[i] = (unsigned char) data_array[i]; } env->ReleaseByteArrayElements(data, data_array, JNI_ABORT); native_data_t *nat = get_native_data(env, thiz); nat->api.SetImage(imagedata, (int) width, (int) height, (int) bpp, (int) bpl); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = imagedata; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImagePix(JNIEnv *env, jobject thiz, jint nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixClone(pixs); native_data_t *nat = get_native_data(env, thiz); nat->api.SetImage(pixd); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = pixd; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetRectangle(JNIEnv *env, jobject thiz, jint left, jint top, jint width, jint height) { native_data_t *nat = get_native_data(env, thiz); nat->api.SetRectangle(left, top, width, height); } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetUTF8Text(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); char *text = nat->api.GetUTF8Text(); jstring result = env->NewStringUTF(text); free(text); return result; } jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetRegions(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); Pixa *pixa; Boxa *boxa = nat->api.GetRegions(&pixa); if (boxa != NULL) { boxaDestroy(&boxa); } return (int) pixa; } jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetWords(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); Pixa *pixa; Boxa *boxa = nat->api.GetWords(&pixa); if (boxa != NULL) { boxaDestroy(&boxa); } return (int) pixa; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeStop(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); // TODO How do we stop without a monitor?! } jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeMeanConfidence(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); return (jint) nat->api.MeanTextConf(); } jintArray Java_com_googlecode_tesseract_android_TessBaseAPI_nativeWordConfidences(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); int *confs = nat->api.AllWordConfidences(); if (confs == NULL) { return NULL; } int len, *trav; for (len = 0, trav = confs; *trav != -1; trav++, len++) ; LOG_ASSERT((confs != NULL), "Confidence array has %d elements", len); jintArray ret = env->NewIntArray(len); LOG_ASSERT((ret != NULL), "Could not create Java confidence array!"); env->SetIntArrayRegion(ret, 0, len, confs); delete[] confs; return ret; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetVariable(JNIEnv *env, jobject thiz, jstring var, jstring value) { native_data_t *nat = get_native_data(env, thiz); const char *c_var = env->GetStringUTFChars(var, NULL); const char *c_value = env->GetStringUTFChars(value, NULL); jboolean set = nat->api.SetVariable(c_var, c_value) ? JNI_TRUE : JNI_FALSE; env->ReleaseStringUTFChars(var, c_var); env->ReleaseStringUTFChars(value, c_value); return set; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClear(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); nat->api.Clear(); // Call between pages or documents etc to free up memory and forget adaptive data. nat->api.ClearAdaptiveClassifier(); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeEnd(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); nat->api.End(); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetDebug(JNIEnv *env, jobject thiz, jboolean debug) { native_data_t *nat = get_native_data(env, thiz); nat->debug = (debug == JNI_TRUE) ? TRUE : FALSE; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetPageSegMode(JNIEnv *env, jobject thiz, jint mode) { native_data_t *nat = get_native_data(env, thiz); nat->api.SetPageSegMode((tesseract::PageSegMode) mode); } jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetResultIterator(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); return (jint) nat->api.GetIterator(); } #ifdef __cplusplus } #endif
C++