code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
* Brent Booker
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "StdAfx.h"
#include <Objsafe.h>
#include "ControlSite.h"
#include "PropertyBag.h"
#include "ControlSiteIPFrame.h"
class CDefaultControlSiteSecurityPolicy : public CControlSiteSecurityPolicy
{
// Test if the specified class id implements the specified category
BOOL ClassImplementsCategory(const CLSID & clsid, const CATID &catid, BOOL &bClassExists);
public:
// Test if the class is safe to host
virtual BOOL IsClassSafeToHost(const CLSID & clsid);
// Test if the specified class is marked safe for scripting
virtual BOOL IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists);
// Test if the instantiated object is safe for scripting on the specified interface
virtual BOOL IsObjectSafeForScripting(IUnknown *pObject, const IID &iid);
};
BOOL
CDefaultControlSiteSecurityPolicy::ClassImplementsCategory(const CLSID &clsid, const CATID &catid, BOOL &bClassExists)
{
bClassExists = FALSE;
// Test if there is a CLSID entry. If there isn't then obviously
// the object doesn't exist and therefore doesn't implement any category.
// In this situation, the function returns REGDB_E_CLASSNOTREG.
CRegKey key;
if (key.Open(HKEY_CLASSES_ROOT, _T("CLSID"), KEY_READ) != ERROR_SUCCESS)
{
// Must fail if we can't even open this!
return FALSE;
}
LPOLESTR szCLSID = NULL;
if (FAILED(StringFromCLSID(clsid, &szCLSID)))
{
return FALSE;
}
USES_CONVERSION;
CRegKey keyCLSID;
LONG lResult = keyCLSID.Open(key, W2CT(szCLSID), KEY_READ);
CoTaskMemFree(szCLSID);
if (lResult != ERROR_SUCCESS)
{
// Class doesn't exist
return FALSE;
}
keyCLSID.Close();
// CLSID exists, so try checking what categories it implements
bClassExists = TRUE;
CComQIPtr<ICatInformation> spCatInfo;
HRESULT hr = CoCreateInstance(CLSID_StdComponentCategoriesMgr, NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (LPVOID*) &spCatInfo);
if (spCatInfo == NULL)
{
// Must fail if we can't open the category manager
return FALSE;
}
// See what categories the class implements
CComQIPtr<IEnumCATID> spEnumCATID;
if (FAILED(spCatInfo->EnumImplCategoriesOfClass(clsid, &spEnumCATID)))
{
// Can't enumerate classes in category so fail
return FALSE;
}
// Search for matching categories
BOOL bFound = FALSE;
CATID catidNext = GUID_NULL;
while (spEnumCATID->Next(1, &catidNext, NULL) == S_OK)
{
if (::IsEqualCATID(catid, catidNext))
{
return TRUE;
}
}
return FALSE;
}
// Test if the class is safe to host
BOOL CDefaultControlSiteSecurityPolicy::IsClassSafeToHost(const CLSID & clsid)
{
return TRUE;
}
// Test if the specified class is marked safe for scripting
BOOL CDefaultControlSiteSecurityPolicy::IsClassMarkedSafeForScripting(const CLSID & clsid, BOOL &bClassExists)
{
// Test the category the object belongs to
return ClassImplementsCategory(clsid, CATID_SafeForScripting, bClassExists);
}
// Test if the instantiated object is safe for scripting on the specified interface
BOOL CDefaultControlSiteSecurityPolicy::IsObjectSafeForScripting(IUnknown *pObject, const IID &iid)
{
if (!pObject) {
return FALSE;
}
// Ask the control if its safe for scripting
CComQIPtr<IObjectSafety> spObjectSafety = pObject;
if (!spObjectSafety)
{
return FALSE;
}
DWORD dwSupported = 0; // Supported options (mask)
DWORD dwEnabled = 0; // Enabled options
// Assume scripting via IDispatch, now we doesn't support IDispatchEx
if (SUCCEEDED(spObjectSafety->GetInterfaceSafetyOptions(
iid, &dwSupported, &dwEnabled)))
{
if (dwEnabled & dwSupported & INTERFACESAFE_FOR_UNTRUSTED_CALLER)
{
// Object is safe
return TRUE;
}
}
// Set it to support untrusted caller.
if(FAILED(spObjectSafety->SetInterfaceSafetyOptions(
iid, INTERFACESAFE_FOR_UNTRUSTED_CALLER, INTERFACESAFE_FOR_UNTRUSTED_CALLER)))
{
return FALSE;
}
return TRUE;
}
///////////////////////////////////////////////////////////////////////////////
// Constructor
CControlSite::CControlSite()
{
TRACE_METHOD(CControlSite::CControlSite);
m_hWndParent = NULL;
m_CLSID = CLSID_NULL;
m_bSetClientSiteFirst = FALSE;
m_bVisibleAtRuntime = TRUE;
memset(&m_rcObjectPos, 0, sizeof(m_rcObjectPos));
m_bInPlaceActive = FALSE;
m_bUIActive = FALSE;
m_bInPlaceLocked = FALSE;
m_bWindowless = FALSE;
m_bSupportWindowlessActivation = TRUE;
m_bSafeForScriptingObjectsOnly = FALSE;
m_pSecurityPolicy = GetDefaultControlSecurityPolicy();
// Initialise ambient properties
m_nAmbientLocale = 0;
m_clrAmbientForeColor = ::GetSysColor(COLOR_WINDOWTEXT);
m_clrAmbientBackColor = ::GetSysColor(COLOR_WINDOW);
m_bAmbientUserMode = true;
m_bAmbientShowHatching = true;
m_bAmbientShowGrabHandles = true;
m_bAmbientAppearance = true; // 3d
// Windowless variables
m_hDCBuffer = NULL;
m_hRgnBuffer = NULL;
m_hBMBufferOld = NULL;
m_hBMBuffer = NULL;
m_spInner = NULL;
m_needUpdateContainerSize = false;
m_currentSize.cx = m_currentSize.cy = -1;
}
// Destructor
CControlSite::~CControlSite()
{
TRACE_METHOD(CControlSite::~CControlSite);
Detach();
if (m_spInner && m_spInnerDeallocater) {
m_spInnerDeallocater(m_spInner);
}
}
// Create the specified control, optionally providing properties to initialise
// it with and a name.
HRESULT CControlSite::Create(REFCLSID clsid, PropertyList &pl,
LPCWSTR szCodebase, IBindCtx *pBindContext)
{
TRACE_METHOD(CControlSite::Create);
m_CLSID = clsid;
m_ParameterList = pl;
// See if security policy will allow the control to be hosted
if (m_pSecurityPolicy && !m_pSecurityPolicy->IsClassSafeToHost(clsid))
{
return E_FAIL;
}
// See if object is script safe
BOOL checkForObjectSafety = FALSE;
if (m_pSecurityPolicy && m_bSafeForScriptingObjectsOnly)
{
BOOL bClassExists = FALSE;
BOOL bIsSafe = m_pSecurityPolicy->IsClassMarkedSafeForScripting(clsid, bClassExists);
if (!bClassExists && szCodebase)
{
// Class doesn't exist, so allow code below to fetch it
}
else if (!bIsSafe)
{
// The class is not flagged as safe for scripting, so
// we'll have to create it to ask it if its safe.
checkForObjectSafety = TRUE;
}
}
//Now Check if the control version needs to be updated.
BOOL bUpdateControlVersion = FALSE;
wchar_t *szURL = NULL;
DWORD dwFileVersionMS = 0xffffffff;
DWORD dwFileVersionLS = 0xffffffff;
if(szCodebase)
{
HKEY hk = NULL;
wchar_t wszKey[60] = L"";
wchar_t wszData[MAX_PATH];
LPWSTR pwszClsid = NULL;
DWORD dwSize = 255;
DWORD dwHandle, dwLength, dwRegReturn;
DWORD dwExistingFileVerMS = 0xffffffff;
DWORD dwExistingFileVerLS = 0xffffffff;
BOOL bFoundLocalVerInfo = FALSE;
StringFromCLSID(clsid, (LPOLESTR*)&pwszClsid);
swprintf(wszKey, L"%s%s%s\0", L"CLSID\\", pwszClsid, L"\\InprocServer32");
if ( RegOpenKeyExW( HKEY_CLASSES_ROOT, wszKey, 0, KEY_READ, &hk ) == ERROR_SUCCESS )
{
dwRegReturn = RegQueryValueExW( hk, L"", NULL, NULL, (LPBYTE)wszData, &dwSize );
RegCloseKey( hk );
}
if(dwRegReturn == ERROR_SUCCESS)
{
VS_FIXEDFILEINFO *pFileInfo;
UINT uLen;
dwLength = GetFileVersionInfoSizeW( wszData , &dwHandle );
LPBYTE lpData = new BYTE[dwLength];
GetFileVersionInfoW(wszData, 0, dwLength, lpData );
bFoundLocalVerInfo = VerQueryValueW( lpData, L"\\", (LPVOID*)&pFileInfo, &uLen );
if(bFoundLocalVerInfo)
{
dwExistingFileVerMS = pFileInfo->dwFileVersionMS;
dwExistingFileVerLS = pFileInfo->dwFileVersionLS;
}
delete [] lpData;
}
// Test if the code base ends in #version=a,b,c,d
const wchar_t *szHash = wcsrchr(szCodebase, wchar_t('#'));
if (szHash)
{
if (wcsnicmp(szHash, L"#version=", 9) == 0)
{
int a, b, c, d;
if (swscanf(szHash + 9, L"%d,%d,%d,%d", &a, &b, &c, &d) == 4)
{
dwFileVersionMS = MAKELONG(b,a);
dwFileVersionLS = MAKELONG(d,c);
//If local version info was found compare it
if(bFoundLocalVerInfo)
{
if(dwFileVersionMS > dwExistingFileVerMS)
bUpdateControlVersion = TRUE;
if((dwFileVersionMS == dwExistingFileVerMS) && (dwFileVersionLS > dwExistingFileVerLS))
bUpdateControlVersion = TRUE;
}
}
}
szURL = _wcsdup(szCodebase);
// Terminate at the hash mark
if (szURL)
szURL[szHash - szCodebase] = wchar_t('\0');
}
else
{
szURL = _wcsdup(szCodebase);
}
}
CComPtr<IUnknown> spObject;
HRESULT hr;
//If the control needs to be updated do not call CoCreateInstance otherwise you will lock files
//and force a reboot on CoGetClassObjectFromURL
if(!bUpdateControlVersion)
{
// Create the object
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
if (SUCCEEDED(hr) && checkForObjectSafety)
{
m_bSafeForScriptingObjectsOnly = m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch));
// Drop through, success!
}
}
// Do we need to download the control?
if ((FAILED(hr) && szCodebase) || (bUpdateControlVersion))
{
if (!szURL)
return E_OUTOFMEMORY;
CComPtr<IBindCtx> spBindContext;
CComPtr<IBindStatusCallback> spBindStatusCallback;
CComPtr<IBindStatusCallback> spOldBSC;
// Create our own bind context or use the one provided?
BOOL useInternalBSC = FALSE;
if (!pBindContext)
{
useInternalBSC = TRUE;
hr = CreateBindCtx(0, &spBindContext);
if (FAILED(hr))
{
free(szURL);
return hr;
}
spBindStatusCallback = dynamic_cast<IBindStatusCallback *>(this);
hr = RegisterBindStatusCallback(spBindContext, spBindStatusCallback, &spOldBSC, 0);
if (FAILED(hr))
{
free(szURL);
return hr;
}
}
else
{
spBindContext = pBindContext;
}
//If the version from the CODEBASE value is greater than the installed control
//Call CoGetClassObjectFromURL with CLSID_NULL to prevent system change reboot prompt
if(bUpdateControlVersion)
{
hr = CoGetClassObjectFromURL(clsid, szURL, dwFileVersionMS, dwFileVersionLS,
NULL, spBindContext,
CLSCTX_INPROC_HANDLER | CLSCTX_INPROC_SERVER,
0, IID_IClassFactory, NULL);
}
else
{
hr = CoGetClassObjectFromURL(CLSID_NULL, szURL, dwFileVersionMS, dwFileVersionLS,
NULL, spBindContext, CLSCTX_ALL, NULL, IID_IUnknown,
NULL);
}
free(szURL);
// Handle the internal binding synchronously so the object exists
// or an error code is available when the method returns.
if (useInternalBSC)
{
if (MK_S_ASYNCHRONOUS == hr)
{
m_bBindingInProgress = TRUE;
m_hrBindResult = E_FAIL;
// Spin around waiting for binding to complete
HANDLE hFakeEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL);
while (m_bBindingInProgress)
{
MSG msg;
// Process pending messages
while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!::GetMessage(&msg, NULL, 0, 0))
{
m_bBindingInProgress = FALSE;
break;
}
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
if (!m_bBindingInProgress)
break;
// Sleep for a bit or the next msg to appear
::MsgWaitForMultipleObjects(1, &hFakeEvent, FALSE, 500, QS_ALLEVENTS);
}
::CloseHandle(hFakeEvent);
// Set the result
hr = m_hrBindResult;
}
// Destroy the bind status callback & context
if (spBindStatusCallback)
{
RevokeBindStatusCallback(spBindContext, spBindStatusCallback);
spBindStatusCallback.Release();
spBindContext.Release();
}
}
//added to create control
if (SUCCEEDED(hr))
{
// Create the object
hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void **) &spObject);
if (SUCCEEDED(hr) && checkForObjectSafety)
{
// Assume scripting via IDispatch
m_bSafeForScriptingObjectsOnly = m_pSecurityPolicy->IsObjectSafeForScripting(spObject, __uuidof(IDispatch));
}
}
//EOF test code
}
if (spObject)
{
m_spObject = spObject;
CComQIPtr<IObjectWithSite> site = m_spObject;
if (site) {
site->SetSite(GetUnknown());
}
}
return hr;
}
// Attach the created control to a window and activate it
HRESULT CControlSite::Attach(HWND hwndParent, const RECT &rcPos, IUnknown *pInitStream)
{
TRACE_METHOD(CControlSite::Attach);
if (hwndParent == NULL)
{
NS_ASSERTION(0, "No parent hwnd");
return E_INVALIDARG;
}
m_hWndParent = hwndParent;
m_rcObjectPos = rcPos;
// Object must have been created
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
m_spIOleControl = m_spObject;
m_spIViewObject = m_spObject;
m_spIOleObject = m_spObject;
if (m_spIOleObject == NULL)
{
return E_FAIL;
}
if (m_spIOleControl) {
m_spIOleControl->FreezeEvents(true);
}
DWORD dwMiscStatus;
m_spIOleObject->GetMiscStatus(DVASPECT_CONTENT, &dwMiscStatus);
if (dwMiscStatus & OLEMISC_SETCLIENTSITEFIRST)
{
m_bSetClientSiteFirst = TRUE;
}
if (dwMiscStatus & OLEMISC_INVISIBLEATRUNTIME)
{
m_bVisibleAtRuntime = FALSE;
}
// Some objects like to have the client site as the first thing
// to be initialised (for ambient properties and so forth)
if (m_bSetClientSiteFirst)
{
m_spIOleObject->SetClientSite(this);
}
// If there is a parameter list for the object and no init stream then
// create one here.
CPropertyBagInstance *pPropertyBag = NULL;
if (pInitStream == NULL && m_ParameterList.GetSize() > 0)
{
CPropertyBagInstance::CreateInstance(&pPropertyBag);
pPropertyBag->AddRef();
for (unsigned long i = 0; i < m_ParameterList.GetSize(); i++)
{
pPropertyBag->Write(m_ParameterList.GetNameOf(i),
const_cast<VARIANT *>(m_ParameterList.GetValueOf(i)));
}
pInitStream = (IPersistPropertyBag *) pPropertyBag;
}
// Initialise the control from store if one is provided
if (pInitStream)
{
CComQIPtr<IPropertyBag, &IID_IPropertyBag> spPropertyBag = pInitStream;
CComQIPtr<IStream, &IID_IStream> spStream = pInitStream;
CComQIPtr<IPersistStream, &IID_IPersistStream> spIPersistStream = m_spIOleObject;
CComQIPtr<IPersistPropertyBag, &IID_IPersistPropertyBag> spIPersistPropertyBag = m_spIOleObject;
if (spIPersistPropertyBag && spPropertyBag)
{
spIPersistPropertyBag->Load(spPropertyBag, NULL);
}
else if (spIPersistStream && spStream)
{
spIPersistStream->Load(spStream);
}
}
else
{
// Initialise the object if possible
CComQIPtr<IPersistStreamInit, &IID_IPersistStreamInit> spIPersistStreamInit = m_spIOleObject;
if (spIPersistStreamInit)
{
spIPersistStreamInit->InitNew();
}
}
SIZEL size, sizein;
sizein.cx = m_rcObjectPos.right - m_rcObjectPos.left;
sizein.cy = m_rcObjectPos.bottom - m_rcObjectPos.top;
SetControlSize(&sizein, &size);
m_rcObjectPos.right = m_rcObjectPos.left + size.cx;
m_rcObjectPos.bottom = m_rcObjectPos.top + size.cy;
m_spIOleInPlaceObject = m_spObject;
if (m_spIOleControl) {
m_spIOleControl->FreezeEvents(false);
}
// In-place activate the object
if (m_bVisibleAtRuntime)
{
DoVerb(OLEIVERB_INPLACEACTIVATE);
}
m_spIOleInPlaceObjectWindowless = m_spObject;
// For those objects which haven't had their client site set yet,
// it's done here.
if (!m_bSetClientSiteFirst)
{
m_spIOleObject->SetClientSite(this);
}
return S_OK;
}
// Set the control size, in pixels.
HRESULT CControlSite::SetControlSize(const LPSIZEL size, LPSIZEL out)
{
if (!size || !out) {
return E_POINTER;
}
if (!m_spIOleObject) {
return E_FAIL;
}
SIZEL szInitialHiMetric, szCustomHiMetric, szFinalHiMetric;
SIZEL szCustomPixel, szFinalPixel;
szFinalPixel = *size;
szCustomPixel = *size;
if (m_currentSize.cx == size->cx && m_currentSize.cy == size->cy) {
// Don't need to change.
return S_OK;
}
if (SUCCEEDED(m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szInitialHiMetric))) {
if (m_currentSize.cx == -1 && szCustomPixel.cx == 300 && szCustomPixel.cy == 150) {
szFinalHiMetric = szInitialHiMetric;
} else {
AtlPixelToHiMetric(&szCustomPixel, &szCustomHiMetric);
szFinalHiMetric = szCustomHiMetric;
}
}
if (SUCCEEDED(m_spIOleObject->SetExtent(DVASPECT_CONTENT, &szFinalHiMetric))) {
if (SUCCEEDED(m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szFinalHiMetric))) {
AtlHiMetricToPixel(&szFinalHiMetric, &szFinalPixel);
}
}
m_currentSize = szFinalPixel;
if (szCustomPixel.cx != szFinalPixel.cx && szCustomPixel.cy != szFinalPixel.cy) {
m_needUpdateContainerSize = true;
}
*out = szFinalPixel;
return S_OK;
}
// Unhook the control from the window and throw it all away
HRESULT CControlSite::Detach()
{
TRACE_METHOD(CControlSite::Detach);
if (m_spIOleInPlaceObjectWindowless)
{
m_spIOleInPlaceObjectWindowless.Release();
}
CComQIPtr<IObjectWithSite> site = m_spObject;
if (site) {
site->SetSite(NULL);
}
if (m_spIOleInPlaceObject)
{
m_spIOleInPlaceObject->InPlaceDeactivate();
m_spIOleInPlaceObject.Release();
}
if (m_spIOleObject)
{
m_spIOleObject->Close(OLECLOSE_NOSAVE);
m_spIOleObject->SetClientSite(NULL);
m_spIOleObject.Release();
}
m_spIViewObject.Release();
m_spObject.Release();
return S_OK;
}
// Return the IUnknown of the contained control
HRESULT CControlSite::GetControlUnknown(IUnknown **ppObject)
{
*ppObject = NULL;
if (m_spObject)
{
m_spObject->QueryInterface(IID_IUnknown, (void **) ppObject);
return S_OK;
} else {
return E_FAIL;
}
}
// Subscribe to an event sink on the control
HRESULT CControlSite::Advise(IUnknown *pIUnkSink, const IID &iid, DWORD *pdwCookie)
{
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
if (pIUnkSink == NULL || pdwCookie == NULL)
{
return E_INVALIDARG;
}
return AtlAdvise(m_spObject, pIUnkSink, iid, pdwCookie);
}
// Unsubscribe event sink from the control
HRESULT CControlSite::Unadvise(const IID &iid, DWORD dwCookie)
{
if (m_spObject == NULL)
{
return E_UNEXPECTED;
}
return AtlUnadvise(m_spObject, iid, dwCookie);
}
// Draw the control
HRESULT CControlSite::Draw(HDC hdc)
{
TRACE_METHOD(CControlSite::Draw);
// Draw only when control is windowless or deactivated
if (m_spIViewObject)
{
if (m_bWindowless || !m_bInPlaceActive)
{
RECTL *prcBounds = (m_bWindowless) ? NULL : (RECTL *) &m_rcObjectPos;
m_spIViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL, NULL, hdc, prcBounds, NULL, NULL, 0);
}
}
else
{
// Draw something to indicate no control is there
HBRUSH hbr = CreateSolidBrush(RGB(200,200,200));
FillRect(hdc, &m_rcObjectPos, hbr);
DeleteObject(hbr);
}
return S_OK;
}
// Execute the specified verb
HRESULT CControlSite::DoVerb(LONG nVerb, LPMSG lpMsg)
{
TRACE_METHOD(CControlSite::DoVerb);
if (m_spIOleObject == NULL)
{
return E_FAIL;
}
// InstallAtlThunk();
return m_spIOleObject->DoVerb(nVerb, lpMsg, this, 0, m_hWndParent, &m_rcObjectPos);
}
// Set the position on the control
HRESULT CControlSite::SetPosition(const RECT &rcPos)
{
HWND hwnd;
TRACE_METHOD(CControlSite::SetPosition);
m_rcObjectPos = rcPos;
if (m_spIOleInPlaceObject && SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&hwnd)))
{
m_spIOleInPlaceObject->SetObjectRects(&m_rcObjectPos, &m_rcObjectPos);
}
return S_OK;
}
HRESULT CControlSite::GetControlSize(LPSIZEL size){
if (m_spIOleObject) {
SIZEL szHiMetric;
HRESULT hr = m_spIOleObject->GetExtent(DVASPECT_CONTENT, &szHiMetric);
AtlHiMetricToPixel(&szHiMetric, size);
return hr;
}
return E_FAIL;
}
void CControlSite::FireAmbientPropertyChange(DISPID id)
{
if (m_spObject)
{
CComQIPtr<IOleControl> spControl = m_spObject;
if (spControl)
{
spControl->OnAmbientPropertyChange(id);
}
}
}
void CControlSite::SetAmbientUserMode(BOOL bUserMode)
{
bool bNewMode = bUserMode ? true : false;
if (m_bAmbientUserMode != bNewMode)
{
m_bAmbientUserMode = bNewMode;
FireAmbientPropertyChange(DISPID_AMBIENT_USERMODE);
}
}
///////////////////////////////////////////////////////////////////////////////
// CControlSiteSecurityPolicy implementation
CControlSiteSecurityPolicy *CControlSite::GetDefaultControlSecurityPolicy()
{
static CDefaultControlSiteSecurityPolicy defaultControlSecurityPolicy;
return &defaultControlSecurityPolicy;
}
///////////////////////////////////////////////////////////////////////////////
// IDispatch implementation
HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfoCount(/* [out] */ UINT __RPC_FAR *pctinfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetTypeInfo(/* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo __RPC_FAR *__RPC_FAR *ppTInfo)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetIDsOfNames(/* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR __RPC_FAR *rgszNames, /* [in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID __RPC_FAR *rgDispId)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::Invoke(/* [in] */ DISPID dispIdMember, /* [in] */ REFIID riid, /* [in] */ LCID lcid, /* [in] */ WORD wFlags, /* [out][in] */ DISPPARAMS __RPC_FAR *pDispParams, /* [out] */ VARIANT __RPC_FAR *pVarResult, /* [out] */ EXCEPINFO __RPC_FAR *pExcepInfo, /* [out] */ UINT __RPC_FAR *puArgErr)
{
if (wFlags & DISPATCH_PROPERTYGET)
{
CComVariant vResult;
switch (dispIdMember)
{
case DISPID_AMBIENT_APPEARANCE:
vResult = CComVariant(m_bAmbientAppearance);
break;
case DISPID_AMBIENT_FORECOLOR:
vResult = CComVariant((long) m_clrAmbientForeColor);
break;
case DISPID_AMBIENT_BACKCOLOR:
vResult = CComVariant((long) m_clrAmbientBackColor);
break;
case DISPID_AMBIENT_LOCALEID:
vResult = CComVariant((long) m_nAmbientLocale);
break;
case DISPID_AMBIENT_USERMODE:
vResult = CComVariant(m_bAmbientUserMode);
break;
case DISPID_AMBIENT_SHOWGRABHANDLES:
vResult = CComVariant(m_bAmbientShowGrabHandles);
break;
case DISPID_AMBIENT_SHOWHATCHING:
vResult = CComVariant(m_bAmbientShowHatching);
break;
default:
return DISP_E_MEMBERNOTFOUND;
}
VariantCopy(pVarResult, &vResult);
return S_OK;
}
return E_FAIL;
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSink implementation
void STDMETHODCALLTYPE CControlSite::OnDataChange(/* [unique][in] */ FORMATETC __RPC_FAR *pFormatetc, /* [unique][in] */ STGMEDIUM __RPC_FAR *pStgmed)
{
}
void STDMETHODCALLTYPE CControlSite::OnViewChange(/* [in] */ DWORD dwAspect, /* [in] */ LONG lindex)
{
// Redraw the control
InvalidateRect(NULL, FALSE);
}
void STDMETHODCALLTYPE CControlSite::OnRename(/* [in] */ IMoniker __RPC_FAR *pmk)
{
}
void STDMETHODCALLTYPE CControlSite::OnSave(void)
{
}
void STDMETHODCALLTYPE CControlSite::OnClose(void)
{
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSink2 implementation
void STDMETHODCALLTYPE CControlSite::OnLinkSrcChange(/* [unique][in] */ IMoniker __RPC_FAR *pmk)
{
}
///////////////////////////////////////////////////////////////////////////////
// IAdviseSinkEx implementation
void STDMETHODCALLTYPE CControlSite::OnViewStatusChange(/* [in] */ DWORD dwViewStatus)
{
}
///////////////////////////////////////////////////////////////////////////////
// IOleWindow implementation
HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(/* [out] */ HWND __RPC_FAR *phwnd)
{
*phwnd = m_hWndParent;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ContextSensitiveHelp(/* [in] */ BOOL fEnterMode)
{
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleClientSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::SaveObject(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetMoniker(/* [in] */ DWORD dwAssign, /* [in] */ DWORD dwWhichMoniker, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmk)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetContainer(/* [out] */ IOleContainer __RPC_FAR *__RPC_FAR *ppContainer)
{
if (!ppContainer) return E_INVALIDARG;
CComQIPtr<IOleContainer> container(this->GetUnknown());
*ppContainer = container;
if (*ppContainer)
{
(*ppContainer)->AddRef();
}
return (*ppContainer) ? S_OK : E_NOINTERFACE;
}
HRESULT STDMETHODCALLTYPE CControlSite::ShowObject(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnShowWindow(/* [in] */ BOOL fShow)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::RequestNewObjectLayout(void)
{
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::CanInPlaceActivate(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivate(void)
{
m_bInPlaceActive = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnUIActivate(void)
{
m_bUIActive = TRUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetWindowContext(/* [out] */ IOleInPlaceFrame __RPC_FAR *__RPC_FAR *ppFrame, /* [out] */ IOleInPlaceUIWindow __RPC_FAR *__RPC_FAR *ppDoc, /* [out] */ LPRECT lprcPosRect, /* [out] */ LPRECT lprcClipRect, /* [out][in] */ LPOLEINPLACEFRAMEINFO lpFrameInfo)
{
*lprcPosRect = m_rcObjectPos;
*lprcClipRect = m_rcObjectPos;
CControlSiteIPFrameInstance *pIPFrame = NULL;
CControlSiteIPFrameInstance::CreateInstance(&pIPFrame);
pIPFrame->AddRef();
*ppFrame = (IOleInPlaceFrame *) pIPFrame;
*ppDoc = NULL;
lpFrameInfo->fMDIApp = FALSE;
lpFrameInfo->hwndFrame = NULL;
lpFrameInfo->haccel = NULL;
lpFrameInfo->cAccelEntries = 0;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::Scroll(/* [in] */ SIZE scrollExtant)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnUIDeactivate(/* [in] */ BOOL fUndoable)
{
m_bUIActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivate(void)
{
m_bInPlaceActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::DiscardUndoState(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::DeactivateAndUndo(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnPosRectChange(/* [in] */ LPCRECT lprcPosRect)
{
if (lprcPosRect == NULL)
{
return E_INVALIDARG;
}
SetPosition(m_rcObjectPos);
return S_OK;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSiteEx implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceActivateEx(/* [out] */ BOOL __RPC_FAR *pfNoRedraw, /* [in] */ DWORD dwFlags)
{
m_bInPlaceActive = TRUE;
if (pfNoRedraw)
{
*pfNoRedraw = FALSE;
}
if (dwFlags & ACTIVATE_WINDOWLESS)
{
if (!m_bSupportWindowlessActivation)
{
return E_INVALIDARG;
}
m_bWindowless = TRUE;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnInPlaceDeactivateEx(/* [in] */ BOOL fNoRedraw)
{
m_bInPlaceActive = FALSE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::RequestUIActivate(void)
{
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// IOleInPlaceSiteWindowless implementation
HRESULT STDMETHODCALLTYPE CControlSite::CanWindowlessActivate(void)
{
// Allow windowless activation?
return (m_bSupportWindowlessActivation) ? S_OK : S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetCapture(void)
{
// TODO capture the mouse for the object
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::SetCapture(/* [in] */ BOOL fCapture)
{
// TODO capture the mouse for the object
return S_FALSE;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetFocus(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::SetFocus(/* [in] */ BOOL fFocus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetDC(/* [in] */ LPCRECT pRect, /* [in] */ DWORD grfFlags, /* [out] */ HDC __RPC_FAR *phDC)
{
if (phDC == NULL)
{
return E_INVALIDARG;
}
// Can't do nested painting
if (m_hDCBuffer != NULL)
{
return E_UNEXPECTED;
}
m_rcBuffer = m_rcObjectPos;
if (pRect != NULL)
{
m_rcBuffer = *pRect;
}
m_hBMBuffer = NULL;
m_dwBufferFlags = grfFlags;
// See if the control wants a DC that is onscreen or offscreen
if (m_dwBufferFlags & OLEDC_OFFSCREEN)
{
m_hDCBuffer = CreateCompatibleDC(NULL);
if (m_hDCBuffer == NULL)
{
// Error
return E_OUTOFMEMORY;
}
long cx = m_rcBuffer.right - m_rcBuffer.left;
long cy = m_rcBuffer.bottom - m_rcBuffer.top;
m_hBMBuffer = CreateCompatibleBitmap(m_hDCBuffer, cx, cy);
m_hBMBufferOld = (HBITMAP) SelectObject(m_hDCBuffer, m_hBMBuffer);
SetViewportOrgEx(m_hDCBuffer, m_rcBuffer.left, m_rcBuffer.top, NULL);
// TODO When OLEDC_PAINTBKGND we must draw every site behind this one
}
else
{
// TODO When OLEDC_PAINTBKGND we must draw every site behind this one
// Get the window DC
m_hDCBuffer = GetWindowDC(m_hWndParent);
if (m_hDCBuffer == NULL)
{
// Error
return E_OUTOFMEMORY;
}
// Clip the control so it can't trash anywhere it isn't allowed to draw
if (!(m_dwBufferFlags & OLEDC_NODRAW))
{
m_hRgnBuffer = CreateRectRgnIndirect(&m_rcBuffer);
// TODO Clip out opaque areas of sites behind this one
SelectClipRgn(m_hDCBuffer, m_hRgnBuffer);
}
}
*phDC = m_hDCBuffer;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ReleaseDC(/* [in] */ HDC hDC)
{
// Release the DC
if (hDC == NULL || hDC != m_hDCBuffer)
{
return E_INVALIDARG;
}
// Test if the DC was offscreen or onscreen
if ((m_dwBufferFlags & OLEDC_OFFSCREEN) &&
!(m_dwBufferFlags & OLEDC_NODRAW))
{
// BitBlt the buffer into the control's object
SetViewportOrgEx(m_hDCBuffer, 0, 0, NULL);
HDC hdc = GetWindowDC(m_hWndParent);
long cx = m_rcBuffer.right - m_rcBuffer.left;
long cy = m_rcBuffer.bottom - m_rcBuffer.top;
BitBlt(hdc, m_rcBuffer.left, m_rcBuffer.top, cx, cy, m_hDCBuffer, 0, 0, SRCCOPY);
::ReleaseDC(m_hWndParent, hdc);
}
else
{
// TODO If OLEDC_PAINTBKGND is set draw the DVASPECT_CONTENT of every object above this one
}
// Clean up settings ready for next drawing
if (m_hRgnBuffer)
{
SelectClipRgn(m_hDCBuffer, NULL);
DeleteObject(m_hRgnBuffer);
m_hRgnBuffer = NULL;
}
SelectObject(m_hDCBuffer, m_hBMBufferOld);
if (m_hBMBuffer)
{
DeleteObject(m_hBMBuffer);
m_hBMBuffer = NULL;
}
// Delete the DC
if (m_dwBufferFlags & OLEDC_OFFSCREEN)
{
::DeleteDC(m_hDCBuffer);
}
else
{
::ReleaseDC(m_hWndParent, m_hDCBuffer);
}
m_hDCBuffer = NULL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRect(/* [in] */ LPCRECT pRect, /* [in] */ BOOL fErase)
{
// Clip the rectangle against the object's size and invalidate it
RECT rcI = { 0, 0, 0, 0 };
if (pRect == NULL)
{
rcI = m_rcObjectPos;
}
else
{
IntersectRect(&rcI, &m_rcObjectPos, pRect);
}
::InvalidateRect(m_hWndParent, &rcI, fErase);
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::InvalidateRgn(/* [in] */ HRGN hRGN, /* [in] */ BOOL fErase)
{
if (hRGN == NULL)
{
::InvalidateRect(m_hWndParent, &m_rcObjectPos, fErase);
}
else
{
// Clip the region with the object's bounding area
HRGN hrgnClip = CreateRectRgnIndirect(&m_rcObjectPos);
if (CombineRgn(hrgnClip, hrgnClip, hRGN, RGN_AND) != ERROR)
{
::InvalidateRgn(m_hWndParent, hrgnClip, fErase);
}
DeleteObject(hrgnClip);
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ScrollRect(/* [in] */ INT dx, /* [in] */ INT dy, /* [in] */ LPCRECT pRectScroll, /* [in] */ LPCRECT pRectClip)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::AdjustRect(/* [out][in] */ LPRECT prc)
{
if (prc == NULL)
{
return E_INVALIDARG;
}
// Clip the rectangle against the object position
RECT rcI = { 0, 0, 0, 0 };
IntersectRect(&rcI, &m_rcObjectPos, prc);
*prc = rcI;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnDefWindowMessage(/* [in] */ UINT msg, /* [in] */ WPARAM wParam, /* [in] */ LPARAM lParam, /* [out] */ LRESULT __RPC_FAR *plResult)
{
if (plResult == NULL)
{
return E_INVALIDARG;
}
// Pass the message to the windowless control
if (m_bWindowless && m_spIOleInPlaceObjectWindowless)
{
return m_spIOleInPlaceObjectWindowless->OnWindowMessage(msg, wParam, lParam, plResult);
}
else if (m_spIOleInPlaceObject) {
HWND wnd;
if (SUCCEEDED(m_spIOleInPlaceObject->GetWindow(&wnd)))
SendMessage(wnd, msg, wParam, lParam);
}
return S_FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// IOleControlSite implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnControlInfoChanged(void)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::LockInPlaceActive(/* [in] */ BOOL fLock)
{
m_bInPlaceLocked = fLock;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetExtendedControl(/* [out] */ IDispatch __RPC_FAR *__RPC_FAR *ppDisp)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::TransformCoords(/* [out][in] */ POINTL __RPC_FAR *pPtlHimetric, /* [out][in] */ POINTF __RPC_FAR *pPtfContainer, /* [in] */ DWORD dwFlags)
{
HRESULT hr = S_OK;
if (pPtlHimetric == NULL)
{
return E_INVALIDARG;
}
if (pPtfContainer == NULL)
{
return E_INVALIDARG;
}
HDC hdc = ::GetDC(m_hWndParent);
::SetMapMode(hdc, MM_HIMETRIC);
POINT rgptConvert[2];
rgptConvert[0].x = 0;
rgptConvert[0].y = 0;
if (dwFlags & XFORMCOORDS_HIMETRICTOCONTAINER)
{
rgptConvert[1].x = pPtlHimetric->x;
rgptConvert[1].y = pPtlHimetric->y;
::LPtoDP(hdc, rgptConvert, 2);
if (dwFlags & XFORMCOORDS_SIZE)
{
pPtfContainer->x = (float)(rgptConvert[1].x - rgptConvert[0].x);
pPtfContainer->y = (float)(rgptConvert[0].y - rgptConvert[1].y);
}
else if (dwFlags & XFORMCOORDS_POSITION)
{
pPtfContainer->x = (float)rgptConvert[1].x;
pPtfContainer->y = (float)rgptConvert[1].y;
}
else
{
hr = E_INVALIDARG;
}
}
else if (dwFlags & XFORMCOORDS_CONTAINERTOHIMETRIC)
{
rgptConvert[1].x = (int)(pPtfContainer->x);
rgptConvert[1].y = (int)(pPtfContainer->y);
::DPtoLP(hdc, rgptConvert, 2);
if (dwFlags & XFORMCOORDS_SIZE)
{
pPtlHimetric->x = rgptConvert[1].x - rgptConvert[0].x;
pPtlHimetric->y = rgptConvert[0].y - rgptConvert[1].y;
}
else if (dwFlags & XFORMCOORDS_POSITION)
{
pPtlHimetric->x = rgptConvert[1].x;
pPtlHimetric->y = rgptConvert[1].y;
}
else
{
hr = E_INVALIDARG;
}
}
else
{
hr = E_INVALIDARG;
}
::ReleaseDC(m_hWndParent, hdc);
return hr;
}
HRESULT STDMETHODCALLTYPE CControlSite::TranslateAccelerator(/* [in] */ MSG __RPC_FAR *pMsg, /* [in] */ DWORD grfModifiers)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnFocus(/* [in] */ BOOL fGotFocus)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::ShowPropertyFrame(void)
{
return E_NOTIMPL;
}
///////////////////////////////////////////////////////////////////////////////
// IBindStatusCallback implementation
HRESULT STDMETHODCALLTYPE CControlSite::OnStartBinding(DWORD dwReserved,
IBinding __RPC_FAR *pib)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetPriority(LONG __RPC_FAR *pnPriority)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnLowResource(DWORD reserved)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnProgress(ULONG ulProgress,
ULONG ulProgressMax,
ULONG ulStatusCode,
LPCWSTR szStatusText)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnStopBinding(HRESULT hresult, LPCWSTR szError)
{
m_bBindingInProgress = FALSE;
m_hrBindResult = hresult;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::GetBindInfo(DWORD __RPC_FAR *pgrfBINDF,
BINDINFO __RPC_FAR *pbindInfo)
{
*pgrfBINDF = BINDF_ASYNCHRONOUS | BINDF_ASYNCSTORAGE |
BINDF_GETNEWESTVERSION | BINDF_NOWRITECACHE;
pbindInfo->cbSize = sizeof(BINDINFO);
pbindInfo->szExtraInfo = NULL;
memset(&pbindInfo->stgmedData, 0, sizeof(STGMEDIUM));
pbindInfo->grfBindInfoF = 0;
pbindInfo->dwBindVerb = 0;
pbindInfo->szCustomVerb = NULL;
return S_OK;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnDataAvailable(DWORD grfBSCF,
DWORD dwSize,
FORMATETC __RPC_FAR *pformatetc,
STGMEDIUM __RPC_FAR *pstgmed)
{
return E_NOTIMPL;
}
HRESULT STDMETHODCALLTYPE CControlSite::OnObjectAvailable(REFIID riid,
IUnknown __RPC_FAR *punk)
{
return S_OK;
}
// IWindowForBindingUI
HRESULT STDMETHODCALLTYPE CControlSite::GetWindow(
/* [in] */ REFGUID rguidReason,
/* [out] */ HWND *phwnd)
{
*phwnd = NULL;
return S_OK;
}
| C++ |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@netscape.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef CONTROLSITEIPFRAME_H
#define CONTROLSITEIPFRAME_H
class CControlSiteIPFrame : public CComObjectRootEx<CComSingleThreadModel>,
public IOleInPlaceFrame
{
public:
CControlSiteIPFrame();
virtual ~CControlSiteIPFrame();
HWND m_hwndFrame;
BEGIN_COM_MAP(CControlSiteIPFrame)
COM_INTERFACE_ENTRY_IID(IID_IOleWindow, IOleInPlaceFrame)
COM_INTERFACE_ENTRY_IID(IID_IOleInPlaceUIWindow, IOleInPlaceFrame)
COM_INTERFACE_ENTRY(IOleInPlaceFrame)
END_COM_MAP()
// IOleWindow
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetWindow(/* [out] */ HWND __RPC_FAR *phwnd);
virtual HRESULT STDMETHODCALLTYPE ContextSensitiveHelp(/* [in] */ BOOL fEnterMode);
// IOleInPlaceUIWindow implementation
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE GetBorder(/* [out] */ LPRECT lprectBorder);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE RequestBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetBorderSpace(/* [unique][in] */ LPCBORDERWIDTHS pborderwidths);
virtual HRESULT STDMETHODCALLTYPE SetActiveObject(/* [unique][in] */ IOleInPlaceActiveObject __RPC_FAR *pActiveObject, /* [unique][string][in] */ LPCOLESTR pszObjName);
// IOleInPlaceFrame implementation
virtual HRESULT STDMETHODCALLTYPE InsertMenus(/* [in] */ HMENU hmenuShared, /* [out][in] */ LPOLEMENUGROUPWIDTHS lpMenuWidths);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetMenu(/* [in] */ HMENU hmenuShared, /* [in] */ HOLEMENU holemenu, /* [in] */ HWND hwndActiveObject);
virtual HRESULT STDMETHODCALLTYPE RemoveMenus(/* [in] */ HMENU hmenuShared);
virtual /* [input_sync] */ HRESULT STDMETHODCALLTYPE SetStatusText(/* [in] */ LPCOLESTR pszStatusText);
virtual HRESULT STDMETHODCALLTYPE EnableModeless(/* [in] */ BOOL fEnable);
virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator(/* [in] */ LPMSG lpmsg, /* [in] */ WORD wID);
};
typedef CComObject<CControlSiteIPFrame> CControlSiteIPFrameInstance;
#endif | C++ |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef IOLECOMMANDIMPL_H
#define IOLECOMMANDIMPL_H
// Implementation of the IOleCommandTarget interface. The template is
// reasonably generic and reusable which is a good thing given how needlessly
// complicated this interface is. Blame Microsoft for that and not me.
//
// To use this class, derive your class from it like this:
//
// class CComMyClass : public IOleCommandTargetImpl<CComMyClass>
// {
// ... Ensure IOleCommandTarget is listed in the interface map ...
// BEGIN_COM_MAP(CComMyClass)
// COM_INTERFACE_ENTRY(IOleCommandTarget)
// // etc.
// END_COM_MAP()
// ... And then later on define the command target table ...
// BEGIN_OLECOMMAND_TABLE()
// OLECOMMAND_MESSAGE(OLECMDID_PRINT, NULL, ID_PRINT, L"Print", L"Print the page")
// OLECOMMAND_MESSAGE(OLECMDID_SAVEAS, NULL, 0, L"SaveAs", L"Save the page")
// OLECOMMAND_HANDLER(IDM_EDITMODE, &CGID_MSHTML, EditModeHandler, L"EditMode", L"Switch to edit mode")
// END_OLECOMMAND_TABLE()
// ... Now the window that OLECOMMAND_MESSAGE sends WM_COMMANDs to ...
// HWND GetCommandTargetWindow() const
// {
// return m_hWnd;
// }
// ... Now procedures that OLECOMMAND_HANDLER calls ...
// static HRESULT _stdcall EditModeHandler(CMozillaBrowser *pThis, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut);
// }
//
// The command table defines which commands the object supports. Commands are
// defined by a command id and a command group plus a WM_COMMAND id or procedure,
// and a verb and short description.
//
// Notice that there are two macros for handling Ole Commands. The first,
// OLECOMMAND_MESSAGE sends a WM_COMMAND message to the window returned from
// GetCommandTargetWindow() (that the derived class must implement if it uses
// this macro).
//
// The second, OLECOMMAND_HANDLER calls a static handler procedure that
// conforms to the OleCommandProc typedef. The first parameter, pThis means
// the static handler has access to the methods and variables in the class
// instance.
//
// The OLECOMMAND_HANDLER macro is generally more useful when a command
// takes parameters or needs to return a result to the caller.
//
template< class T >
class IOleCommandTargetImpl : public IOleCommandTarget
{
struct OleExecData
{
const GUID *pguidCmdGroup;
DWORD nCmdID;
DWORD nCmdexecopt;
VARIANT *pvaIn;
VARIANT *pvaOut;
};
public:
typedef HRESULT (_stdcall *OleCommandProc)(T *pT, const GUID *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT *pvaIn, VARIANT *pvaOut);
struct OleCommandInfo
{
ULONG nCmdID;
const GUID *pCmdGUID;
ULONG nWindowsCmdID;
OleCommandProc pfnCommandProc;
wchar_t *szVerbText;
wchar_t *szStatusText;
};
// Query the status of the specified commands (test if is it supported etc.)
virtual HRESULT STDMETHODCALLTYPE QueryStatus(const GUID __RPC_FAR *pguidCmdGroup, ULONG cCmds, OLECMD __RPC_FAR prgCmds[], OLECMDTEXT __RPC_FAR *pCmdText)
{
T* pT = static_cast<T*>(this);
if (prgCmds == NULL)
{
return E_INVALIDARG;
}
OleCommandInfo *pCommands = pT->GetCommandTable();
ATLASSERT(pCommands);
BOOL bCmdGroupFound = FALSE;
BOOL bTextSet = FALSE;
// Iterate through list of commands and flag them as supported/unsupported
for (ULONG nCmd = 0; nCmd < cCmds; nCmd++)
{
// Unsupported by default
prgCmds[nCmd].cmdf = 0;
// Search the support command list
for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++)
{
OleCommandInfo *pCI = &pCommands[nSupported];
if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0)
{
continue;
}
bCmdGroupFound = TRUE;
if (pCI->nCmdID != prgCmds[nCmd].cmdID)
{
continue;
}
// Command is supported so flag it and possibly enable it
prgCmds[nCmd].cmdf = OLECMDF_SUPPORTED;
if (pCI->nWindowsCmdID != 0)
{
prgCmds[nCmd].cmdf |= OLECMDF_ENABLED;
}
// Copy the status/verb text for the first supported command only
if (!bTextSet && pCmdText)
{
// See what text the caller wants
wchar_t *pszTextToCopy = NULL;
if (pCmdText->cmdtextf & OLECMDTEXTF_NAME)
{
pszTextToCopy = pCI->szVerbText;
}
else if (pCmdText->cmdtextf & OLECMDTEXTF_STATUS)
{
pszTextToCopy = pCI->szStatusText;
}
// Copy the text
pCmdText->cwActual = 0;
memset(pCmdText->rgwz, 0, pCmdText->cwBuf * sizeof(wchar_t));
if (pszTextToCopy)
{
// Don't exceed the provided buffer size
size_t nTextLen = wcslen(pszTextToCopy);
if (nTextLen > pCmdText->cwBuf)
{
nTextLen = pCmdText->cwBuf;
}
wcsncpy(pCmdText->rgwz, pszTextToCopy, nTextLen);
pCmdText->cwActual = nTextLen;
}
bTextSet = TRUE;
}
break;
}
}
// Was the command group found?
if (!bCmdGroupFound)
{
OLECMDERR_E_UNKNOWNGROUP;
}
return S_OK;
}
// Execute the specified command
virtual HRESULT STDMETHODCALLTYPE Exec(const GUID __RPC_FAR *pguidCmdGroup, DWORD nCmdID, DWORD nCmdexecopt, VARIANT __RPC_FAR *pvaIn, VARIANT __RPC_FAR *pvaOut)
{
T* pT = static_cast<T*>(this);
BOOL bCmdGroupFound = FALSE;
OleCommandInfo *pCommands = pT->GetCommandTable();
ATLASSERT(pCommands);
// Search the support command list
for (int nSupported = 0; pCommands[nSupported].pCmdGUID != &GUID_NULL; nSupported++)
{
OleCommandInfo *pCI = &pCommands[nSupported];
if (pguidCmdGroup && pCI->pCmdGUID && memcmp(pguidCmdGroup, pCI->pCmdGUID, sizeof(GUID)) == 0)
{
continue;
}
bCmdGroupFound = TRUE;
if (pCI->nCmdID != nCmdID)
{
continue;
}
// Send ourselves a WM_COMMAND windows message with the associated
// identifier and exec data
OleExecData cData;
cData.pguidCmdGroup = pguidCmdGroup;
cData.nCmdID = nCmdID;
cData.nCmdexecopt = nCmdexecopt;
cData.pvaIn = pvaIn;
cData.pvaOut = pvaOut;
if (pCI->pfnCommandProc)
{
pCI->pfnCommandProc(pT, pCI->pCmdGUID, pCI->nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
else if (pCI->nWindowsCmdID != 0 && nCmdexecopt != OLECMDEXECOPT_SHOWHELP)
{
HWND hwndTarget = pT->GetCommandTargetWindow();
if (hwndTarget)
{
::SendMessage(hwndTarget, WM_COMMAND, LOWORD(pCI->nWindowsCmdID), (LPARAM) &cData);
}
}
else
{
// Command supported but not implemented
continue;
}
return S_OK;
}
// Was the command group found?
if (!bCmdGroupFound)
{
OLECMDERR_E_UNKNOWNGROUP;
}
return OLECMDERR_E_NOTSUPPORTED;
}
};
// Macros to be placed in any class derived from the IOleCommandTargetImpl
// class. These define what commands are exposed from the object.
#define BEGIN_OLECOMMAND_TABLE() \
OleCommandInfo *GetCommandTable() \
{ \
static OleCommandInfo s_aSupportedCommands[] = \
{
#define OLECOMMAND_MESSAGE(id, group, cmd, verb, desc) \
{ id, group, cmd, NULL, verb, desc },
#define OLECOMMAND_HANDLER(id, group, handler, verb, desc) \
{ id, group, 0, handler, verb, desc },
#define END_OLECOMMAND_TABLE() \
{ 0, &GUID_NULL, 0, NULL, NULL, NULL } \
}; \
return s_aSupportedCommands; \
};
#endif | C++ |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef PROPERTYLIST_H
#define PROPERTYLIST_H
// A simple array class for managing name/value pairs typically fed to controls
// during initialization by IPersistPropertyBag
class PropertyList
{
struct Property {
BSTR bstrName;
VARIANT vValue;
} *mProperties;
unsigned long mListSize;
unsigned long mMaxListSize;
bool EnsureMoreSpace()
{
// Ensure enough space exists to accomodate a new item
const unsigned long kGrowBy = 10;
if (!mProperties)
{
mProperties = (Property *) malloc(sizeof(Property) * kGrowBy);
if (!mProperties)
return false;
mMaxListSize = kGrowBy;
}
else if (mListSize == mMaxListSize)
{
Property *pNewProperties;
pNewProperties = (Property *) realloc(mProperties, sizeof(Property) * (mMaxListSize + kGrowBy));
if (!pNewProperties)
return false;
mProperties = pNewProperties;
mMaxListSize += kGrowBy;
}
return true;
}
public:
PropertyList() :
mProperties(NULL),
mListSize(0),
mMaxListSize(0)
{
}
~PropertyList()
{
}
void Clear()
{
if (mProperties)
{
for (unsigned long i = 0; i < mListSize; i++)
{
SysFreeString(mProperties[i].bstrName); // Safe even if NULL
VariantClear(&mProperties[i].vValue);
}
free(mProperties);
mProperties = NULL;
}
mListSize = 0;
mMaxListSize = 0;
}
unsigned long GetSize() const
{
return mListSize;
}
const BSTR GetNameOf(unsigned long nIndex) const
{
if (nIndex > mListSize)
{
return NULL;
}
return mProperties[nIndex].bstrName;
}
const VARIANT *GetValueOf(unsigned long nIndex) const
{
if (nIndex > mListSize)
{
return NULL;
}
return &mProperties[nIndex].vValue;
}
bool AddOrReplaceNamedProperty(const BSTR bstrName, const VARIANT &vValue)
{
if (!bstrName)
return false;
for (unsigned long i = 0; i < GetSize(); i++)
{
// Case insensitive
if (wcsicmp(mProperties[i].bstrName, bstrName) == 0)
{
return SUCCEEDED(
VariantCopy(&mProperties[i].vValue, const_cast<VARIANT *>(&vValue)));
}
}
return AddNamedProperty(bstrName, vValue);
}
bool AddNamedProperty(const BSTR bstrName, const VARIANT &vValue)
{
if (!bstrName || !EnsureMoreSpace())
return false;
Property *pProp = &mProperties[mListSize];
pProp->bstrName = ::SysAllocString(bstrName);
if (!pProp->bstrName)
{
return false;
}
VariantInit(&pProp->vValue);
if (FAILED(VariantCopy(&pProp->vValue, const_cast<VARIANT *>(&vValue))))
{
SysFreeString(pProp->bstrName);
return false;
}
mListSize++;
return true;
}
};
#endif | C++ |
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adam Lock <adamlock@eircom.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef ITEMCONTAINER_H
#define ITEMCONTAINER_H
// typedef std::map<tstring, CIUnkPtr> CNamedObjectList;
// Class for managing a list of named objects.
class CItemContainer : public CComObjectRootEx<CComSingleThreadModel>,
public IOleItemContainer
{
// CNamedObjectList m_cNamedObjectList;
public:
CItemContainer();
virtual ~CItemContainer();
BEGIN_COM_MAP(CItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IParseDisplayName, IOleItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IOleContainer, IOleItemContainer)
COM_INTERFACE_ENTRY_IID(IID_IOleItemContainer, IOleItemContainer)
END_COM_MAP()
// IParseDisplayName implementation
virtual HRESULT STDMETHODCALLTYPE ParseDisplayName(/* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ LPOLESTR pszDisplayName, /* [out] */ ULONG __RPC_FAR *pchEaten, /* [out] */ IMoniker __RPC_FAR *__RPC_FAR *ppmkOut);
// IOleContainer implementation
virtual HRESULT STDMETHODCALLTYPE EnumObjects(/* [in] */ DWORD grfFlags, /* [out] */ IEnumUnknown __RPC_FAR *__RPC_FAR *ppenum);
virtual HRESULT STDMETHODCALLTYPE LockContainer(/* [in] */ BOOL fLock);
// IOleItemContainer implementation
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObject(/* [in] */ LPOLESTR pszItem, /* [in] */ DWORD dwSpeedNeeded, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetObjectStorage(/* [in] */ LPOLESTR pszItem, /* [unique][in] */ IBindCtx __RPC_FAR *pbc, /* [in] */ REFIID riid, /* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvStorage);
virtual HRESULT STDMETHODCALLTYPE IsRunning(/* [in] */ LPOLESTR pszItem);
};
typedef CComObject<CItemContainer> CItemContainerInstance;
#endif | C++ |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "Host.h"
#include <atlsafe.h>
#include "objectProxy.h"
class NPSafeArray: public ScriptBase
{
public:
NPSafeArray(NPP npp);
~NPSafeArray(void);
static NPSafeArray* CreateFromArray(NPP instance, SAFEARRAY* array);
static void RegisterVBArray(NPP npp);
static NPClass npClass;
SAFEARRAY* NPSafeArray::GetArrayPtr();
private:
static NPInvokeDefaultFunctionPtr GetFuncPtr(NPIdentifier name);
CComSafeArray<VARIANT> arr_;
NPObjectProxy window;
// Some wrappers to adapt NPAPI's interface.
static NPObject* Allocate(NPP npp, NPClass *aClass);
static void Deallocate(NPObject *obj);
static void Invalidate(NPObject *obj);
static bool HasMethod(NPObject *npobj, NPIdentifier name);
static bool Invoke(NPObject *npobj, NPIdentifier name,
const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool GetItem(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool ToArray(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool UBound(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool LBound(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool Dimensions(NPObject *npobj, const NPVariant *args, uint32_t argCount,
NPVariant *result);
static bool HasProperty(NPObject *npobj, NPIdentifier name);
static bool GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result);
static bool SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value);
};
| C++ |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <npapi.h>
#include <npruntime.h>
struct ScriptBase;
class CHost
{
public:
void AddRef();
void Release();
CHost(NPP npp);
virtual ~CHost(void);
NPObject *GetScriptableObject();
NPP GetInstance() {
return instance;
}
static ScriptBase *GetInternalObject(NPP npp, NPObject *embed_element);
NPObject *RegisterObject();
void UnRegisterObject();
virtual NPP ResetNPP(NPP newNpp);
protected:
NPP instance;
ScriptBase *lastObj;
ScriptBase *GetMyScriptObject();
virtual ScriptBase *CreateScriptableObject() = 0;
private:
int ref_cnt_;
};
struct ScriptBase: NPObject {
NPP instance;
CHost* host;
ScriptBase(NPP instance_) : instance(instance_) {
}
}; | 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++ |
/*
* Copyright (C) 2010 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 <stdlib.h>
namespace latinime {
struct LatinCapitalSmallPair {
unsigned short capital;
unsigned short small;
};
// Generated from http://unicode.org/Public/UNIDATA/UnicodeData.txt
//
// 1. Run the following code. Bascially taken from
// Dictionary::toLowerCase(unsigned short c) in dictionary.cpp.
// Then, get the list of chars where cc != ccc.
//
// unsigned short c, cc, ccc, ccc2;
// for (c = 0; c < 0xFFFF ; c++) {
// if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
// cc = BASE_CHARS[c];
// } else {
// cc = c;
// }
//
// // tolower
// int isBase = 0;
// if (cc >='A' && cc <= 'Z') {
// ccc = (cc | 0x20);
// ccc2 = ccc;
// isBase = 1;
// } else if (cc > 0x7F) {
// ccc = u_tolower(cc);
// ccc2 = latin_tolower(cc);
// } else {
// ccc = cc;
// ccc2 = ccc;
// }
// if (!isBase && cc != ccc) {
// wprintf(L" 0x%04X => 0x%04X => 0x%04X %lc => %lc => %lc \n",
// c, cc, ccc, c, cc, ccc);
// //assert(ccc == ccc2);
// }
// }
//
// Initially, started with an empty latin_tolower() as below.
//
// unsigned short latin_tolower(unsigned short c) {
// return c;
// }
//
//
// 2. Process the list obtained by 1 by the following perl script and apply
// 'sort -u' as well. Get the SORTED_CHAR_MAP[].
// Note that '$1' in the perl script is 'cc' in the above C code.
//
// while(<>) {
// / 0x\w* => 0x(\w*) =/;
// open(HDL, "grep -iw ^" . $1 . " UnicodeData.txt | ");
// $line = <HDL>;
// chomp $line;
// @cols = split(/;/, $line);
// print " { 0x$1, 0x$cols[13] }, // $cols[1]\n";
// }
//
//
// 3. Update the latin_tolower() function above with SORTED_CHAR_MAP. Enable
// the assert(ccc == ccc2) above and confirm the function exits successfully.
//
static const struct LatinCapitalSmallPair SORTED_CHAR_MAP[] = {
{ 0x00C4, 0x00E4 }, // LATIN CAPITAL LETTER A WITH DIAERESIS
{ 0x00C5, 0x00E5 }, // LATIN CAPITAL LETTER A WITH RING ABOVE
{ 0x00C6, 0x00E6 }, // LATIN CAPITAL LETTER AE
{ 0x00D0, 0x00F0 }, // LATIN CAPITAL LETTER ETH
{ 0x00D5, 0x00F5 }, // LATIN CAPITAL LETTER O WITH TILDE
{ 0x00D6, 0x00F6 }, // LATIN CAPITAL LETTER O WITH DIAERESIS
{ 0x00D8, 0x00F8 }, // LATIN CAPITAL LETTER O WITH STROKE
{ 0x00DC, 0x00FC }, // LATIN CAPITAL LETTER U WITH DIAERESIS
{ 0x00DE, 0x00FE }, // LATIN CAPITAL LETTER THORN
{ 0x0110, 0x0111 }, // LATIN CAPITAL LETTER D WITH STROKE
{ 0x0126, 0x0127 }, // LATIN CAPITAL LETTER H WITH STROKE
{ 0x0141, 0x0142 }, // LATIN CAPITAL LETTER L WITH STROKE
{ 0x014A, 0x014B }, // LATIN CAPITAL LETTER ENG
{ 0x0152, 0x0153 }, // LATIN CAPITAL LIGATURE OE
{ 0x0166, 0x0167 }, // LATIN CAPITAL LETTER T WITH STROKE
{ 0x0181, 0x0253 }, // LATIN CAPITAL LETTER B WITH HOOK
{ 0x0182, 0x0183 }, // LATIN CAPITAL LETTER B WITH TOPBAR
{ 0x0184, 0x0185 }, // LATIN CAPITAL LETTER TONE SIX
{ 0x0186, 0x0254 }, // LATIN CAPITAL LETTER OPEN O
{ 0x0187, 0x0188 }, // LATIN CAPITAL LETTER C WITH HOOK
{ 0x0189, 0x0256 }, // LATIN CAPITAL LETTER AFRICAN D
{ 0x018A, 0x0257 }, // LATIN CAPITAL LETTER D WITH HOOK
{ 0x018B, 0x018C }, // LATIN CAPITAL LETTER D WITH TOPBAR
{ 0x018E, 0x01DD }, // LATIN CAPITAL LETTER REVERSED E
{ 0x018F, 0x0259 }, // LATIN CAPITAL LETTER SCHWA
{ 0x0190, 0x025B }, // LATIN CAPITAL LETTER OPEN E
{ 0x0191, 0x0192 }, // LATIN CAPITAL LETTER F WITH HOOK
{ 0x0193, 0x0260 }, // LATIN CAPITAL LETTER G WITH HOOK
{ 0x0194, 0x0263 }, // LATIN CAPITAL LETTER GAMMA
{ 0x0196, 0x0269 }, // LATIN CAPITAL LETTER IOTA
{ 0x0197, 0x0268 }, // LATIN CAPITAL LETTER I WITH STROKE
{ 0x0198, 0x0199 }, // LATIN CAPITAL LETTER K WITH HOOK
{ 0x019C, 0x026F }, // LATIN CAPITAL LETTER TURNED M
{ 0x019D, 0x0272 }, // LATIN CAPITAL LETTER N WITH LEFT HOOK
{ 0x019F, 0x0275 }, // LATIN CAPITAL LETTER O WITH MIDDLE TILDE
{ 0x01A2, 0x01A3 }, // LATIN CAPITAL LETTER OI
{ 0x01A4, 0x01A5 }, // LATIN CAPITAL LETTER P WITH HOOK
{ 0x01A6, 0x0280 }, // LATIN LETTER YR
{ 0x01A7, 0x01A8 }, // LATIN CAPITAL LETTER TONE TWO
{ 0x01A9, 0x0283 }, // LATIN CAPITAL LETTER ESH
{ 0x01AC, 0x01AD }, // LATIN CAPITAL LETTER T WITH HOOK
{ 0x01AE, 0x0288 }, // LATIN CAPITAL LETTER T WITH RETROFLEX HOOK
{ 0x01B1, 0x028A }, // LATIN CAPITAL LETTER UPSILON
{ 0x01B2, 0x028B }, // LATIN CAPITAL LETTER V WITH HOOK
{ 0x01B3, 0x01B4 }, // LATIN CAPITAL LETTER Y WITH HOOK
{ 0x01B5, 0x01B6 }, // LATIN CAPITAL LETTER Z WITH STROKE
{ 0x01B7, 0x0292 }, // LATIN CAPITAL LETTER EZH
{ 0x01B8, 0x01B9 }, // LATIN CAPITAL LETTER EZH REVERSED
{ 0x01BC, 0x01BD }, // LATIN CAPITAL LETTER TONE FIVE
{ 0x01E4, 0x01E5 }, // LATIN CAPITAL LETTER G WITH STROKE
{ 0x01EA, 0x01EB }, // LATIN CAPITAL LETTER O WITH OGONEK
{ 0x01F6, 0x0195 }, // LATIN CAPITAL LETTER HWAIR
{ 0x01F7, 0x01BF }, // LATIN CAPITAL LETTER WYNN
{ 0x021C, 0x021D }, // LATIN CAPITAL LETTER YOGH
{ 0x0220, 0x019E }, // LATIN CAPITAL LETTER N WITH LONG RIGHT LEG
{ 0x0222, 0x0223 }, // LATIN CAPITAL LETTER OU
{ 0x0224, 0x0225 }, // LATIN CAPITAL LETTER Z WITH HOOK
{ 0x0226, 0x0227 }, // LATIN CAPITAL LETTER A WITH DOT ABOVE
{ 0x022E, 0x022F }, // LATIN CAPITAL LETTER O WITH DOT ABOVE
{ 0x023A, 0x2C65 }, // LATIN CAPITAL LETTER A WITH STROKE
{ 0x023B, 0x023C }, // LATIN CAPITAL LETTER C WITH STROKE
{ 0x023D, 0x019A }, // LATIN CAPITAL LETTER L WITH BAR
{ 0x023E, 0x2C66 }, // LATIN CAPITAL LETTER T WITH DIAGONAL STROKE
{ 0x0241, 0x0242 }, // LATIN CAPITAL LETTER GLOTTAL STOP
{ 0x0243, 0x0180 }, // LATIN CAPITAL LETTER B WITH STROKE
{ 0x0244, 0x0289 }, // LATIN CAPITAL LETTER U BAR
{ 0x0245, 0x028C }, // LATIN CAPITAL LETTER TURNED V
{ 0x0246, 0x0247 }, // LATIN CAPITAL LETTER E WITH STROKE
{ 0x0248, 0x0249 }, // LATIN CAPITAL LETTER J WITH STROKE
{ 0x024A, 0x024B }, // LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL
{ 0x024C, 0x024D }, // LATIN CAPITAL LETTER R WITH STROKE
{ 0x024E, 0x024F }, // LATIN CAPITAL LETTER Y WITH STROKE
{ 0x0370, 0x0371 }, // GREEK CAPITAL LETTER HETA
{ 0x0372, 0x0373 }, // GREEK CAPITAL LETTER ARCHAIC SAMPI
{ 0x0376, 0x0377 }, // GREEK CAPITAL LETTER PAMPHYLIAN DIGAMMA
{ 0x0391, 0x03B1 }, // GREEK CAPITAL LETTER ALPHA
{ 0x0392, 0x03B2 }, // GREEK CAPITAL LETTER BETA
{ 0x0393, 0x03B3 }, // GREEK CAPITAL LETTER GAMMA
{ 0x0394, 0x03B4 }, // GREEK CAPITAL LETTER DELTA
{ 0x0395, 0x03B5 }, // GREEK CAPITAL LETTER EPSILON
{ 0x0396, 0x03B6 }, // GREEK CAPITAL LETTER ZETA
{ 0x0397, 0x03B7 }, // GREEK CAPITAL LETTER ETA
{ 0x0398, 0x03B8 }, // GREEK CAPITAL LETTER THETA
{ 0x0399, 0x03B9 }, // GREEK CAPITAL LETTER IOTA
{ 0x039A, 0x03BA }, // GREEK CAPITAL LETTER KAPPA
{ 0x039B, 0x03BB }, // GREEK CAPITAL LETTER LAMDA
{ 0x039C, 0x03BC }, // GREEK CAPITAL LETTER MU
{ 0x039D, 0x03BD }, // GREEK CAPITAL LETTER NU
{ 0x039E, 0x03BE }, // GREEK CAPITAL LETTER XI
{ 0x039F, 0x03BF }, // GREEK CAPITAL LETTER OMICRON
{ 0x03A0, 0x03C0 }, // GREEK CAPITAL LETTER PI
{ 0x03A1, 0x03C1 }, // GREEK CAPITAL LETTER RHO
{ 0x03A3, 0x03C3 }, // GREEK CAPITAL LETTER SIGMA
{ 0x03A4, 0x03C4 }, // GREEK CAPITAL LETTER TAU
{ 0x03A5, 0x03C5 }, // GREEK CAPITAL LETTER UPSILON
{ 0x03A6, 0x03C6 }, // GREEK CAPITAL LETTER PHI
{ 0x03A7, 0x03C7 }, // GREEK CAPITAL LETTER CHI
{ 0x03A8, 0x03C8 }, // GREEK CAPITAL LETTER PSI
{ 0x03A9, 0x03C9 }, // GREEK CAPITAL LETTER OMEGA
{ 0x03CF, 0x03D7 }, // GREEK CAPITAL KAI SYMBOL
{ 0x03D8, 0x03D9 }, // GREEK LETTER ARCHAIC KOPPA
{ 0x03DA, 0x03DB }, // GREEK LETTER STIGMA
{ 0x03DC, 0x03DD }, // GREEK LETTER DIGAMMA
{ 0x03DE, 0x03DF }, // GREEK LETTER KOPPA
{ 0x03E0, 0x03E1 }, // GREEK LETTER SAMPI
{ 0x03E2, 0x03E3 }, // COPTIC CAPITAL LETTER SHEI
{ 0x03E4, 0x03E5 }, // COPTIC CAPITAL LETTER FEI
{ 0x03E6, 0x03E7 }, // COPTIC CAPITAL LETTER KHEI
{ 0x03E8, 0x03E9 }, // COPTIC CAPITAL LETTER HORI
{ 0x03EA, 0x03EB }, // COPTIC CAPITAL LETTER GANGIA
{ 0x03EC, 0x03ED }, // COPTIC CAPITAL LETTER SHIMA
{ 0x03EE, 0x03EF }, // COPTIC CAPITAL LETTER DEI
{ 0x03F7, 0x03F8 }, // GREEK CAPITAL LETTER SHO
{ 0x03FA, 0x03FB }, // GREEK CAPITAL LETTER SAN
{ 0x03FD, 0x037B }, // GREEK CAPITAL REVERSED LUNATE SIGMA SYMBOL
{ 0x03FE, 0x037C }, // GREEK CAPITAL DOTTED LUNATE SIGMA SYMBOL
{ 0x03FF, 0x037D }, // GREEK CAPITAL REVERSED DOTTED LUNATE SIGMA SYMBOL
{ 0x0402, 0x0452 }, // CYRILLIC CAPITAL LETTER DJE
{ 0x0404, 0x0454 }, // CYRILLIC CAPITAL LETTER UKRAINIAN IE
{ 0x0405, 0x0455 }, // CYRILLIC CAPITAL LETTER DZE
{ 0x0406, 0x0456 }, // CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I
{ 0x0408, 0x0458 }, // CYRILLIC CAPITAL LETTER JE
{ 0x0409, 0x0459 }, // CYRILLIC CAPITAL LETTER LJE
{ 0x040A, 0x045A }, // CYRILLIC CAPITAL LETTER NJE
{ 0x040B, 0x045B }, // CYRILLIC CAPITAL LETTER TSHE
{ 0x040F, 0x045F }, // CYRILLIC CAPITAL LETTER DZHE
{ 0x0410, 0x0430 }, // CYRILLIC CAPITAL LETTER A
{ 0x0411, 0x0431 }, // CYRILLIC CAPITAL LETTER BE
{ 0x0412, 0x0432 }, // CYRILLIC CAPITAL LETTER VE
{ 0x0413, 0x0433 }, // CYRILLIC CAPITAL LETTER GHE
{ 0x0414, 0x0434 }, // CYRILLIC CAPITAL LETTER DE
{ 0x0415, 0x0435 }, // CYRILLIC CAPITAL LETTER IE
{ 0x0416, 0x0436 }, // CYRILLIC CAPITAL LETTER ZHE
{ 0x0417, 0x0437 }, // CYRILLIC CAPITAL LETTER ZE
{ 0x0418, 0x0438 }, // CYRILLIC CAPITAL LETTER I
{ 0x041A, 0x043A }, // CYRILLIC CAPITAL LETTER KA
{ 0x041B, 0x043B }, // CYRILLIC CAPITAL LETTER EL
{ 0x041C, 0x043C }, // CYRILLIC CAPITAL LETTER EM
{ 0x041D, 0x043D }, // CYRILLIC CAPITAL LETTER EN
{ 0x041E, 0x043E }, // CYRILLIC CAPITAL LETTER O
{ 0x041F, 0x043F }, // CYRILLIC CAPITAL LETTER PE
{ 0x0420, 0x0440 }, // CYRILLIC CAPITAL LETTER ER
{ 0x0421, 0x0441 }, // CYRILLIC CAPITAL LETTER ES
{ 0x0422, 0x0442 }, // CYRILLIC CAPITAL LETTER TE
{ 0x0423, 0x0443 }, // CYRILLIC CAPITAL LETTER U
{ 0x0424, 0x0444 }, // CYRILLIC CAPITAL LETTER EF
{ 0x0425, 0x0445 }, // CYRILLIC CAPITAL LETTER HA
{ 0x0426, 0x0446 }, // CYRILLIC CAPITAL LETTER TSE
{ 0x0427, 0x0447 }, // CYRILLIC CAPITAL LETTER CHE
{ 0x0428, 0x0448 }, // CYRILLIC CAPITAL LETTER SHA
{ 0x0429, 0x0449 }, // CYRILLIC CAPITAL LETTER SHCHA
{ 0x042A, 0x044A }, // CYRILLIC CAPITAL LETTER HARD SIGN
{ 0x042B, 0x044B }, // CYRILLIC CAPITAL LETTER YERU
{ 0x042C, 0x044C }, // CYRILLIC CAPITAL LETTER SOFT SIGN
{ 0x042D, 0x044D }, // CYRILLIC CAPITAL LETTER E
{ 0x042E, 0x044E }, // CYRILLIC CAPITAL LETTER YU
{ 0x042F, 0x044F }, // CYRILLIC CAPITAL LETTER YA
{ 0x0460, 0x0461 }, // CYRILLIC CAPITAL LETTER OMEGA
{ 0x0462, 0x0463 }, // CYRILLIC CAPITAL LETTER YAT
{ 0x0464, 0x0465 }, // CYRILLIC CAPITAL LETTER IOTIFIED E
{ 0x0466, 0x0467 }, // CYRILLIC CAPITAL LETTER LITTLE YUS
{ 0x0468, 0x0469 }, // CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS
{ 0x046A, 0x046B }, // CYRILLIC CAPITAL LETTER BIG YUS
{ 0x046C, 0x046D }, // CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS
{ 0x046E, 0x046F }, // CYRILLIC CAPITAL LETTER KSI
{ 0x0470, 0x0471 }, // CYRILLIC CAPITAL LETTER PSI
{ 0x0472, 0x0473 }, // CYRILLIC CAPITAL LETTER FITA
{ 0x0474, 0x0475 }, // CYRILLIC CAPITAL LETTER IZHITSA
{ 0x0478, 0x0479 }, // CYRILLIC CAPITAL LETTER UK
{ 0x047A, 0x047B }, // CYRILLIC CAPITAL LETTER ROUND OMEGA
{ 0x047C, 0x047D }, // CYRILLIC CAPITAL LETTER OMEGA WITH TITLO
{ 0x047E, 0x047F }, // CYRILLIC CAPITAL LETTER OT
{ 0x0480, 0x0481 }, // CYRILLIC CAPITAL LETTER KOPPA
{ 0x048A, 0x048B }, // CYRILLIC CAPITAL LETTER SHORT I WITH TAIL
{ 0x048C, 0x048D }, // CYRILLIC CAPITAL LETTER SEMISOFT SIGN
{ 0x048E, 0x048F }, // CYRILLIC CAPITAL LETTER ER WITH TICK
{ 0x0490, 0x0491 }, // CYRILLIC CAPITAL LETTER GHE WITH UPTURN
{ 0x0492, 0x0493 }, // CYRILLIC CAPITAL LETTER GHE WITH STROKE
{ 0x0494, 0x0495 }, // CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK
{ 0x0496, 0x0497 }, // CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER
{ 0x0498, 0x0499 }, // CYRILLIC CAPITAL LETTER ZE WITH DESCENDER
{ 0x049A, 0x049B }, // CYRILLIC CAPITAL LETTER KA WITH DESCENDER
{ 0x049C, 0x049D }, // CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE
{ 0x049E, 0x049F }, // CYRILLIC CAPITAL LETTER KA WITH STROKE
{ 0x04A0, 0x04A1 }, // CYRILLIC CAPITAL LETTER BASHKIR KA
{ 0x04A2, 0x04A3 }, // CYRILLIC CAPITAL LETTER EN WITH DESCENDER
{ 0x04A4, 0x04A5 }, // CYRILLIC CAPITAL LIGATURE EN GHE
{ 0x04A6, 0x04A7 }, // CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK
{ 0x04A8, 0x04A9 }, // CYRILLIC CAPITAL LETTER ABKHASIAN HA
{ 0x04AA, 0x04AB }, // CYRILLIC CAPITAL LETTER ES WITH DESCENDER
{ 0x04AC, 0x04AD }, // CYRILLIC CAPITAL LETTER TE WITH DESCENDER
{ 0x04AE, 0x04AF }, // CYRILLIC CAPITAL LETTER STRAIGHT U
{ 0x04B0, 0x04B1 }, // CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE
{ 0x04B2, 0x04B3 }, // CYRILLIC CAPITAL LETTER HA WITH DESCENDER
{ 0x04B4, 0x04B5 }, // CYRILLIC CAPITAL LIGATURE TE TSE
{ 0x04B6, 0x04B7 }, // CYRILLIC CAPITAL LETTER CHE WITH DESCENDER
{ 0x04B8, 0x04B9 }, // CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE
{ 0x04BA, 0x04BB }, // CYRILLIC CAPITAL LETTER SHHA
{ 0x04BC, 0x04BD }, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE
{ 0x04BE, 0x04BF }, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH DESCENDER
{ 0x04C0, 0x04CF }, // CYRILLIC LETTER PALOCHKA
{ 0x04C3, 0x04C4 }, // CYRILLIC CAPITAL LETTER KA WITH HOOK
{ 0x04C5, 0x04C6 }, // CYRILLIC CAPITAL LETTER EL WITH TAIL
{ 0x04C7, 0x04C8 }, // CYRILLIC CAPITAL LETTER EN WITH HOOK
{ 0x04C9, 0x04CA }, // CYRILLIC CAPITAL LETTER EN WITH TAIL
{ 0x04CB, 0x04CC }, // CYRILLIC CAPITAL LETTER KHAKASSIAN CHE
{ 0x04CD, 0x04CE }, // CYRILLIC CAPITAL LETTER EM WITH TAIL
{ 0x04D4, 0x04D5 }, // CYRILLIC CAPITAL LIGATURE A IE
{ 0x04D8, 0x04D9 }, // CYRILLIC CAPITAL LETTER SCHWA
{ 0x04E0, 0x04E1 }, // CYRILLIC CAPITAL LETTER ABKHASIAN DZE
{ 0x04E8, 0x04E9 }, // CYRILLIC CAPITAL LETTER BARRED O
{ 0x04F6, 0x04F7 }, // CYRILLIC CAPITAL LETTER GHE WITH DESCENDER
{ 0x04FA, 0x04FB }, // CYRILLIC CAPITAL LETTER GHE WITH STROKE AND HOOK
{ 0x04FC, 0x04FD }, // CYRILLIC CAPITAL LETTER HA WITH HOOK
{ 0x04FE, 0x04FF }, // CYRILLIC CAPITAL LETTER HA WITH STROKE
{ 0x0500, 0x0501 }, // CYRILLIC CAPITAL LETTER KOMI DE
{ 0x0502, 0x0503 }, // CYRILLIC CAPITAL LETTER KOMI DJE
{ 0x0504, 0x0505 }, // CYRILLIC CAPITAL LETTER KOMI ZJE
{ 0x0506, 0x0507 }, // CYRILLIC CAPITAL LETTER KOMI DZJE
{ 0x0508, 0x0509 }, // CYRILLIC CAPITAL LETTER KOMI LJE
{ 0x050A, 0x050B }, // CYRILLIC CAPITAL LETTER KOMI NJE
{ 0x050C, 0x050D }, // CYRILLIC CAPITAL LETTER KOMI SJE
{ 0x050E, 0x050F }, // CYRILLIC CAPITAL LETTER KOMI TJE
{ 0x0510, 0x0511 }, // CYRILLIC CAPITAL LETTER REVERSED ZE
{ 0x0512, 0x0513 }, // CYRILLIC CAPITAL LETTER EL WITH HOOK
{ 0x0514, 0x0515 }, // CYRILLIC CAPITAL LETTER LHA
{ 0x0516, 0x0517 }, // CYRILLIC CAPITAL LETTER RHA
{ 0x0518, 0x0519 }, // CYRILLIC CAPITAL LETTER YAE
{ 0x051A, 0x051B }, // CYRILLIC CAPITAL LETTER QA
{ 0x051C, 0x051D }, // CYRILLIC CAPITAL LETTER WE
{ 0x051E, 0x051F }, // CYRILLIC CAPITAL LETTER ALEUT KA
{ 0x0520, 0x0521 }, // CYRILLIC CAPITAL LETTER EL WITH MIDDLE HOOK
{ 0x0522, 0x0523 }, // CYRILLIC CAPITAL LETTER EN WITH MIDDLE HOOK
{ 0x0524, 0x0525 }, // CYRILLIC CAPITAL LETTER PE WITH DESCENDER
{ 0x0531, 0x0561 }, // ARMENIAN CAPITAL LETTER AYB
{ 0x0532, 0x0562 }, // ARMENIAN CAPITAL LETTER BEN
{ 0x0533, 0x0563 }, // ARMENIAN CAPITAL LETTER GIM
{ 0x0534, 0x0564 }, // ARMENIAN CAPITAL LETTER DA
{ 0x0535, 0x0565 }, // ARMENIAN CAPITAL LETTER ECH
{ 0x0536, 0x0566 }, // ARMENIAN CAPITAL LETTER ZA
{ 0x0537, 0x0567 }, // ARMENIAN CAPITAL LETTER EH
{ 0x0538, 0x0568 }, // ARMENIAN CAPITAL LETTER ET
{ 0x0539, 0x0569 }, // ARMENIAN CAPITAL LETTER TO
{ 0x053A, 0x056A }, // ARMENIAN CAPITAL LETTER ZHE
{ 0x053B, 0x056B }, // ARMENIAN CAPITAL LETTER INI
{ 0x053C, 0x056C }, // ARMENIAN CAPITAL LETTER LIWN
{ 0x053D, 0x056D }, // ARMENIAN CAPITAL LETTER XEH
{ 0x053E, 0x056E }, // ARMENIAN CAPITAL LETTER CA
{ 0x053F, 0x056F }, // ARMENIAN CAPITAL LETTER KEN
{ 0x0540, 0x0570 }, // ARMENIAN CAPITAL LETTER HO
{ 0x0541, 0x0571 }, // ARMENIAN CAPITAL LETTER JA
{ 0x0542, 0x0572 }, // ARMENIAN CAPITAL LETTER GHAD
{ 0x0543, 0x0573 }, // ARMENIAN CAPITAL LETTER CHEH
{ 0x0544, 0x0574 }, // ARMENIAN CAPITAL LETTER MEN
{ 0x0545, 0x0575 }, // ARMENIAN CAPITAL LETTER YI
{ 0x0546, 0x0576 }, // ARMENIAN CAPITAL LETTER NOW
{ 0x0547, 0x0577 }, // ARMENIAN CAPITAL LETTER SHA
{ 0x0548, 0x0578 }, // ARMENIAN CAPITAL LETTER VO
{ 0x0549, 0x0579 }, // ARMENIAN CAPITAL LETTER CHA
{ 0x054A, 0x057A }, // ARMENIAN CAPITAL LETTER PEH
{ 0x054B, 0x057B }, // ARMENIAN CAPITAL LETTER JHEH
{ 0x054C, 0x057C }, // ARMENIAN CAPITAL LETTER RA
{ 0x054D, 0x057D }, // ARMENIAN CAPITAL LETTER SEH
{ 0x054E, 0x057E }, // ARMENIAN CAPITAL LETTER VEW
{ 0x054F, 0x057F }, // ARMENIAN CAPITAL LETTER TIWN
{ 0x0550, 0x0580 }, // ARMENIAN CAPITAL LETTER REH
{ 0x0551, 0x0581 }, // ARMENIAN CAPITAL LETTER CO
{ 0x0552, 0x0582 }, // ARMENIAN CAPITAL LETTER YIWN
{ 0x0553, 0x0583 }, // ARMENIAN CAPITAL LETTER PIWR
{ 0x0554, 0x0584 }, // ARMENIAN CAPITAL LETTER KEH
{ 0x0555, 0x0585 }, // ARMENIAN CAPITAL LETTER OH
{ 0x0556, 0x0586 }, // ARMENIAN CAPITAL LETTER FEH
{ 0x10A0, 0x2D00 }, // GEORGIAN CAPITAL LETTER AN
{ 0x10A1, 0x2D01 }, // GEORGIAN CAPITAL LETTER BAN
{ 0x10A2, 0x2D02 }, // GEORGIAN CAPITAL LETTER GAN
{ 0x10A3, 0x2D03 }, // GEORGIAN CAPITAL LETTER DON
{ 0x10A4, 0x2D04 }, // GEORGIAN CAPITAL LETTER EN
{ 0x10A5, 0x2D05 }, // GEORGIAN CAPITAL LETTER VIN
{ 0x10A6, 0x2D06 }, // GEORGIAN CAPITAL LETTER ZEN
{ 0x10A7, 0x2D07 }, // GEORGIAN CAPITAL LETTER TAN
{ 0x10A8, 0x2D08 }, // GEORGIAN CAPITAL LETTER IN
{ 0x10A9, 0x2D09 }, // GEORGIAN CAPITAL LETTER KAN
{ 0x10AA, 0x2D0A }, // GEORGIAN CAPITAL LETTER LAS
{ 0x10AB, 0x2D0B }, // GEORGIAN CAPITAL LETTER MAN
{ 0x10AC, 0x2D0C }, // GEORGIAN CAPITAL LETTER NAR
{ 0x10AD, 0x2D0D }, // GEORGIAN CAPITAL LETTER ON
{ 0x10AE, 0x2D0E }, // GEORGIAN CAPITAL LETTER PAR
{ 0x10AF, 0x2D0F }, // GEORGIAN CAPITAL LETTER ZHAR
{ 0x10B0, 0x2D10 }, // GEORGIAN CAPITAL LETTER RAE
{ 0x10B1, 0x2D11 }, // GEORGIAN CAPITAL LETTER SAN
{ 0x10B2, 0x2D12 }, // GEORGIAN CAPITAL LETTER TAR
{ 0x10B3, 0x2D13 }, // GEORGIAN CAPITAL LETTER UN
{ 0x10B4, 0x2D14 }, // GEORGIAN CAPITAL LETTER PHAR
{ 0x10B5, 0x2D15 }, // GEORGIAN CAPITAL LETTER KHAR
{ 0x10B6, 0x2D16 }, // GEORGIAN CAPITAL LETTER GHAN
{ 0x10B7, 0x2D17 }, // GEORGIAN CAPITAL LETTER QAR
{ 0x10B8, 0x2D18 }, // GEORGIAN CAPITAL LETTER SHIN
{ 0x10B9, 0x2D19 }, // GEORGIAN CAPITAL LETTER CHIN
{ 0x10BA, 0x2D1A }, // GEORGIAN CAPITAL LETTER CAN
{ 0x10BB, 0x2D1B }, // GEORGIAN CAPITAL LETTER JIL
{ 0x10BC, 0x2D1C }, // GEORGIAN CAPITAL LETTER CIL
{ 0x10BD, 0x2D1D }, // GEORGIAN CAPITAL LETTER CHAR
{ 0x10BE, 0x2D1E }, // GEORGIAN CAPITAL LETTER XAN
{ 0x10BF, 0x2D1F }, // GEORGIAN CAPITAL LETTER JHAN
{ 0x10C0, 0x2D20 }, // GEORGIAN CAPITAL LETTER HAE
{ 0x10C1, 0x2D21 }, // GEORGIAN CAPITAL LETTER HE
{ 0x10C2, 0x2D22 }, // GEORGIAN CAPITAL LETTER HIE
{ 0x10C3, 0x2D23 }, // GEORGIAN CAPITAL LETTER WE
{ 0x10C4, 0x2D24 }, // GEORGIAN CAPITAL LETTER HAR
{ 0x10C5, 0x2D25 }, // GEORGIAN CAPITAL LETTER HOE
{ 0x1E00, 0x1E01 }, // LATIN CAPITAL LETTER A WITH RING BELOW
{ 0x1E02, 0x1E03 }, // LATIN CAPITAL LETTER B WITH DOT ABOVE
{ 0x1E04, 0x1E05 }, // LATIN CAPITAL LETTER B WITH DOT BELOW
{ 0x1E06, 0x1E07 }, // LATIN CAPITAL LETTER B WITH LINE BELOW
{ 0x1E08, 0x1E09 }, // LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE
{ 0x1E0A, 0x1E0B }, // LATIN CAPITAL LETTER D WITH DOT ABOVE
{ 0x1E0C, 0x1E0D }, // LATIN CAPITAL LETTER D WITH DOT BELOW
{ 0x1E0E, 0x1E0F }, // LATIN CAPITAL LETTER D WITH LINE BELOW
{ 0x1E10, 0x1E11 }, // LATIN CAPITAL LETTER D WITH CEDILLA
{ 0x1E12, 0x1E13 }, // LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW
{ 0x1E14, 0x1E15 }, // LATIN CAPITAL LETTER E WITH MACRON AND GRAVE
{ 0x1E16, 0x1E17 }, // LATIN CAPITAL LETTER E WITH MACRON AND ACUTE
{ 0x1E18, 0x1E19 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW
{ 0x1E1A, 0x1E1B }, // LATIN CAPITAL LETTER E WITH TILDE BELOW
{ 0x1E1C, 0x1E1D }, // LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE
{ 0x1E1E, 0x1E1F }, // LATIN CAPITAL LETTER F WITH DOT ABOVE
{ 0x1E20, 0x1E21 }, // LATIN CAPITAL LETTER G WITH MACRON
{ 0x1E22, 0x1E23 }, // LATIN CAPITAL LETTER H WITH DOT ABOVE
{ 0x1E24, 0x1E25 }, // LATIN CAPITAL LETTER H WITH DOT BELOW
{ 0x1E26, 0x1E27 }, // LATIN CAPITAL LETTER H WITH DIAERESIS
{ 0x1E28, 0x1E29 }, // LATIN CAPITAL LETTER H WITH CEDILLA
{ 0x1E2A, 0x1E2B }, // LATIN CAPITAL LETTER H WITH BREVE BELOW
{ 0x1E2C, 0x1E2D }, // LATIN CAPITAL LETTER I WITH TILDE BELOW
{ 0x1E2E, 0x1E2F }, // LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE
{ 0x1E30, 0x1E31 }, // LATIN CAPITAL LETTER K WITH ACUTE
{ 0x1E32, 0x1E33 }, // LATIN CAPITAL LETTER K WITH DOT BELOW
{ 0x1E34, 0x1E35 }, // LATIN CAPITAL LETTER K WITH LINE BELOW
{ 0x1E36, 0x1E37 }, // LATIN CAPITAL LETTER L WITH DOT BELOW
{ 0x1E38, 0x1E39 }, // LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON
{ 0x1E3A, 0x1E3B }, // LATIN CAPITAL LETTER L WITH LINE BELOW
{ 0x1E3C, 0x1E3D }, // LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW
{ 0x1E3E, 0x1E3F }, // LATIN CAPITAL LETTER M WITH ACUTE
{ 0x1E40, 0x1E41 }, // LATIN CAPITAL LETTER M WITH DOT ABOVE
{ 0x1E42, 0x1E43 }, // LATIN CAPITAL LETTER M WITH DOT BELOW
{ 0x1E44, 0x1E45 }, // LATIN CAPITAL LETTER N WITH DOT ABOVE
{ 0x1E46, 0x1E47 }, // LATIN CAPITAL LETTER N WITH DOT BELOW
{ 0x1E48, 0x1E49 }, // LATIN CAPITAL LETTER N WITH LINE BELOW
{ 0x1E4A, 0x1E4B }, // LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW
{ 0x1E4C, 0x1E4D }, // LATIN CAPITAL LETTER O WITH TILDE AND ACUTE
{ 0x1E4E, 0x1E4F }, // LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS
{ 0x1E50, 0x1E51 }, // LATIN CAPITAL LETTER O WITH MACRON AND GRAVE
{ 0x1E52, 0x1E53 }, // LATIN CAPITAL LETTER O WITH MACRON AND ACUTE
{ 0x1E54, 0x1E55 }, // LATIN CAPITAL LETTER P WITH ACUTE
{ 0x1E56, 0x1E57 }, // LATIN CAPITAL LETTER P WITH DOT ABOVE
{ 0x1E58, 0x1E59 }, // LATIN CAPITAL LETTER R WITH DOT ABOVE
{ 0x1E5A, 0x1E5B }, // LATIN CAPITAL LETTER R WITH DOT BELOW
{ 0x1E5C, 0x1E5D }, // LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON
{ 0x1E5E, 0x1E5F }, // LATIN CAPITAL LETTER R WITH LINE BELOW
{ 0x1E60, 0x1E61 }, // LATIN CAPITAL LETTER S WITH DOT ABOVE
{ 0x1E62, 0x1E63 }, // LATIN CAPITAL LETTER S WITH DOT BELOW
{ 0x1E64, 0x1E65 }, // LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE
{ 0x1E66, 0x1E67 }, // LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE
{ 0x1E68, 0x1E69 }, // LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE
{ 0x1E6A, 0x1E6B }, // LATIN CAPITAL LETTER T WITH DOT ABOVE
{ 0x1E6C, 0x1E6D }, // LATIN CAPITAL LETTER T WITH DOT BELOW
{ 0x1E6E, 0x1E6F }, // LATIN CAPITAL LETTER T WITH LINE BELOW
{ 0x1E70, 0x1E71 }, // LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW
{ 0x1E72, 0x1E73 }, // LATIN CAPITAL LETTER U WITH DIAERESIS BELOW
{ 0x1E74, 0x1E75 }, // LATIN CAPITAL LETTER U WITH TILDE BELOW
{ 0x1E76, 0x1E77 }, // LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW
{ 0x1E78, 0x1E79 }, // LATIN CAPITAL LETTER U WITH TILDE AND ACUTE
{ 0x1E7A, 0x1E7B }, // LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS
{ 0x1E7C, 0x1E7D }, // LATIN CAPITAL LETTER V WITH TILDE
{ 0x1E7E, 0x1E7F }, // LATIN CAPITAL LETTER V WITH DOT BELOW
{ 0x1E80, 0x1E81 }, // LATIN CAPITAL LETTER W WITH GRAVE
{ 0x1E82, 0x1E83 }, // LATIN CAPITAL LETTER W WITH ACUTE
{ 0x1E84, 0x1E85 }, // LATIN CAPITAL LETTER W WITH DIAERESIS
{ 0x1E86, 0x1E87 }, // LATIN CAPITAL LETTER W WITH DOT ABOVE
{ 0x1E88, 0x1E89 }, // LATIN CAPITAL LETTER W WITH DOT BELOW
{ 0x1E8A, 0x1E8B }, // LATIN CAPITAL LETTER X WITH DOT ABOVE
{ 0x1E8C, 0x1E8D }, // LATIN CAPITAL LETTER X WITH DIAERESIS
{ 0x1E8E, 0x1E8F }, // LATIN CAPITAL LETTER Y WITH DOT ABOVE
{ 0x1E90, 0x1E91 }, // LATIN CAPITAL LETTER Z WITH CIRCUMFLEX
{ 0x1E92, 0x1E93 }, // LATIN CAPITAL LETTER Z WITH DOT BELOW
{ 0x1E94, 0x1E95 }, // LATIN CAPITAL LETTER Z WITH LINE BELOW
{ 0x1E9E, 0x00DF }, // LATIN CAPITAL LETTER SHARP S
{ 0x1EA0, 0x1EA1 }, // LATIN CAPITAL LETTER A WITH DOT BELOW
{ 0x1EA2, 0x1EA3 }, // LATIN CAPITAL LETTER A WITH HOOK ABOVE
{ 0x1EA4, 0x1EA5 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE
{ 0x1EA6, 0x1EA7 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE
{ 0x1EA8, 0x1EA9 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1EAA, 0x1EAB }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE
{ 0x1EAC, 0x1EAD }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EAE, 0x1EAF }, // LATIN CAPITAL LETTER A WITH BREVE AND ACUTE
{ 0x1EB0, 0x1EB1 }, // LATIN CAPITAL LETTER A WITH BREVE AND GRAVE
{ 0x1EB2, 0x1EB3 }, // LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE
{ 0x1EB4, 0x1EB5 }, // LATIN CAPITAL LETTER A WITH BREVE AND TILDE
{ 0x1EB6, 0x1EB7 }, // LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW
{ 0x1EB8, 0x1EB9 }, // LATIN CAPITAL LETTER E WITH DOT BELOW
{ 0x1EBA, 0x1EBB }, // LATIN CAPITAL LETTER E WITH HOOK ABOVE
{ 0x1EBC, 0x1EBD }, // LATIN CAPITAL LETTER E WITH TILDE
{ 0x1EBE, 0x1EBF }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE
{ 0x1EC0, 0x1EC1 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE
{ 0x1EC2, 0x1EC3 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1EC4, 0x1EC5 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE
{ 0x1EC6, 0x1EC7 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EC8, 0x1EC9 }, // LATIN CAPITAL LETTER I WITH HOOK ABOVE
{ 0x1ECA, 0x1ECB }, // LATIN CAPITAL LETTER I WITH DOT BELOW
{ 0x1ECC, 0x1ECD }, // LATIN CAPITAL LETTER O WITH DOT BELOW
{ 0x1ECE, 0x1ECF }, // LATIN CAPITAL LETTER O WITH HOOK ABOVE
{ 0x1ED0, 0x1ED1 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE
{ 0x1ED2, 0x1ED3 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE
{ 0x1ED4, 0x1ED5 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1ED6, 0x1ED7 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE
{ 0x1ED8, 0x1ED9 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EDA, 0x1EDB }, // LATIN CAPITAL LETTER O WITH HORN AND ACUTE
{ 0x1EDC, 0x1EDD }, // LATIN CAPITAL LETTER O WITH HORN AND GRAVE
{ 0x1EDE, 0x1EDF }, // LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE
{ 0x1EE0, 0x1EE1 }, // LATIN CAPITAL LETTER O WITH HORN AND TILDE
{ 0x1EE2, 0x1EE3 }, // LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW
{ 0x1EE4, 0x1EE5 }, // LATIN CAPITAL LETTER U WITH DOT BELOW
{ 0x1EE6, 0x1EE7 }, // LATIN CAPITAL LETTER U WITH HOOK ABOVE
{ 0x1EE8, 0x1EE9 }, // LATIN CAPITAL LETTER U WITH HORN AND ACUTE
{ 0x1EEA, 0x1EEB }, // LATIN CAPITAL LETTER U WITH HORN AND GRAVE
{ 0x1EEC, 0x1EED }, // LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE
{ 0x1EEE, 0x1EEF }, // LATIN CAPITAL LETTER U WITH HORN AND TILDE
{ 0x1EF0, 0x1EF1 }, // LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW
{ 0x1EF2, 0x1EF3 }, // LATIN CAPITAL LETTER Y WITH GRAVE
{ 0x1EF4, 0x1EF5 }, // LATIN CAPITAL LETTER Y WITH DOT BELOW
{ 0x1EF6, 0x1EF7 }, // LATIN CAPITAL LETTER Y WITH HOOK ABOVE
{ 0x1EF8, 0x1EF9 }, // LATIN CAPITAL LETTER Y WITH TILDE
{ 0x1EFA, 0x1EFB }, // LATIN CAPITAL LETTER MIDDLE-WELSH LL
{ 0x1EFC, 0x1EFD }, // LATIN CAPITAL LETTER MIDDLE-WELSH V
{ 0x1EFE, 0x1EFF }, // LATIN CAPITAL LETTER Y WITH LOOP
{ 0x1F08, 0x1F00 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI
{ 0x1F09, 0x1F01 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA
{ 0x1F0A, 0x1F02 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA
{ 0x1F0B, 0x1F03 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA
{ 0x1F0C, 0x1F04 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA
{ 0x1F0D, 0x1F05 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA
{ 0x1F0E, 0x1F06 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI
{ 0x1F0F, 0x1F07 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI
{ 0x1F18, 0x1F10 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI
{ 0x1F19, 0x1F11 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA
{ 0x1F1A, 0x1F12 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA
{ 0x1F1B, 0x1F13 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA
{ 0x1F1C, 0x1F14 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA
{ 0x1F1D, 0x1F15 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
{ 0x1F28, 0x1F20 }, // GREEK CAPITAL LETTER ETA WITH PSILI
{ 0x1F29, 0x1F21 }, // GREEK CAPITAL LETTER ETA WITH DASIA
{ 0x1F2A, 0x1F22 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA
{ 0x1F2B, 0x1F23 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA
{ 0x1F2C, 0x1F24 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA
{ 0x1F2D, 0x1F25 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA
{ 0x1F2E, 0x1F26 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI
{ 0x1F2F, 0x1F27 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI
{ 0x1F38, 0x1F30 }, // GREEK CAPITAL LETTER IOTA WITH PSILI
{ 0x1F39, 0x1F31 }, // GREEK CAPITAL LETTER IOTA WITH DASIA
{ 0x1F3A, 0x1F32 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA
{ 0x1F3B, 0x1F33 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA
{ 0x1F3C, 0x1F34 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA
{ 0x1F3D, 0x1F35 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA
{ 0x1F3E, 0x1F36 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI
{ 0x1F3F, 0x1F37 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI
{ 0x1F48, 0x1F40 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI
{ 0x1F49, 0x1F41 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA
{ 0x1F4A, 0x1F42 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA
{ 0x1F4B, 0x1F43 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA
{ 0x1F4C, 0x1F44 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA
{ 0x1F4D, 0x1F45 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
{ 0x1F59, 0x1F51 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA
{ 0x1F5B, 0x1F53 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
{ 0x1F5D, 0x1F55 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
{ 0x1F5F, 0x1F57 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI
{ 0x1F68, 0x1F60 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI
{ 0x1F69, 0x1F61 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA
{ 0x1F6A, 0x1F62 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA
{ 0x1F6B, 0x1F63 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA
{ 0x1F6C, 0x1F64 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA
{ 0x1F6D, 0x1F65 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA
{ 0x1F6E, 0x1F66 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI
{ 0x1F6F, 0x1F67 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI
{ 0x1F88, 0x1F80 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI
{ 0x1F89, 0x1F81 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI
{ 0x1F8A, 0x1F82 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1F8B, 0x1F83 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1F8C, 0x1F84 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1F8D, 0x1F85 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1F8E, 0x1F86 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F8F, 0x1F87 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F98, 0x1F90 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI
{ 0x1F99, 0x1F91 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI
{ 0x1F9A, 0x1F92 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1F9B, 0x1F93 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1F9C, 0x1F94 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1F9D, 0x1F95 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1F9E, 0x1F96 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F9F, 0x1F97 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FA8, 0x1FA0 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI
{ 0x1FA9, 0x1FA1 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI
{ 0x1FAA, 0x1FA2 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1FAB, 0x1FA3 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1FAC, 0x1FA4 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1FAD, 0x1FA5 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1FAE, 0x1FA6 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FAF, 0x1FA7 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FB8, 0x1FB0 }, // GREEK CAPITAL LETTER ALPHA WITH VRACHY
{ 0x1FB9, 0x1FB1 }, // GREEK CAPITAL LETTER ALPHA WITH MACRON
{ 0x1FBA, 0x1F70 }, // GREEK CAPITAL LETTER ALPHA WITH VARIA
{ 0x1FBB, 0x1F71 }, // GREEK CAPITAL LETTER ALPHA WITH OXIA
{ 0x1FBC, 0x1FB3 }, // GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
{ 0x1FC8, 0x1F72 }, // GREEK CAPITAL LETTER EPSILON WITH VARIA
{ 0x1FC9, 0x1F73 }, // GREEK CAPITAL LETTER EPSILON WITH OXIA
{ 0x1FCA, 0x1F74 }, // GREEK CAPITAL LETTER ETA WITH VARIA
{ 0x1FCB, 0x1F75 }, // GREEK CAPITAL LETTER ETA WITH OXIA
{ 0x1FCC, 0x1FC3 }, // GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
{ 0x1FD8, 0x1FD0 }, // GREEK CAPITAL LETTER IOTA WITH VRACHY
{ 0x1FD9, 0x1FD1 }, // GREEK CAPITAL LETTER IOTA WITH MACRON
{ 0x1FDA, 0x1F76 }, // GREEK CAPITAL LETTER IOTA WITH VARIA
{ 0x1FDB, 0x1F77 }, // GREEK CAPITAL LETTER IOTA WITH OXIA
{ 0x1FE8, 0x1FE0 }, // GREEK CAPITAL LETTER UPSILON WITH VRACHY
{ 0x1FE9, 0x1FE1 }, // GREEK CAPITAL LETTER UPSILON WITH MACRON
{ 0x1FEA, 0x1F7A }, // GREEK CAPITAL LETTER UPSILON WITH VARIA
{ 0x1FEB, 0x1F7B }, // GREEK CAPITAL LETTER UPSILON WITH OXIA
{ 0x1FEC, 0x1FE5 }, // GREEK CAPITAL LETTER RHO WITH DASIA
{ 0x1FF8, 0x1F78 }, // GREEK CAPITAL LETTER OMICRON WITH VARIA
{ 0x1FF9, 0x1F79 }, // GREEK CAPITAL LETTER OMICRON WITH OXIA
{ 0x1FFA, 0x1F7C }, // GREEK CAPITAL LETTER OMEGA WITH VARIA
{ 0x1FFB, 0x1F7D }, // GREEK CAPITAL LETTER OMEGA WITH OXIA
{ 0x1FFC, 0x1FF3 }, // GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
{ 0x2126, 0x03C9 }, // OHM SIGN
{ 0x212A, 0x006B }, // KELVIN SIGN
{ 0x212B, 0x00E5 }, // ANGSTROM SIGN
{ 0x2132, 0x214E }, // TURNED CAPITAL F
{ 0x2160, 0x2170 }, // ROMAN NUMERAL ONE
{ 0x2161, 0x2171 }, // ROMAN NUMERAL TWO
{ 0x2162, 0x2172 }, // ROMAN NUMERAL THREE
{ 0x2163, 0x2173 }, // ROMAN NUMERAL FOUR
{ 0x2164, 0x2174 }, // ROMAN NUMERAL FIVE
{ 0x2165, 0x2175 }, // ROMAN NUMERAL SIX
{ 0x2166, 0x2176 }, // ROMAN NUMERAL SEVEN
{ 0x2167, 0x2177 }, // ROMAN NUMERAL EIGHT
{ 0x2168, 0x2178 }, // ROMAN NUMERAL NINE
{ 0x2169, 0x2179 }, // ROMAN NUMERAL TEN
{ 0x216A, 0x217A }, // ROMAN NUMERAL ELEVEN
{ 0x216B, 0x217B }, // ROMAN NUMERAL TWELVE
{ 0x216C, 0x217C }, // ROMAN NUMERAL FIFTY
{ 0x216D, 0x217D }, // ROMAN NUMERAL ONE HUNDRED
{ 0x216E, 0x217E }, // ROMAN NUMERAL FIVE HUNDRED
{ 0x216F, 0x217F }, // ROMAN NUMERAL ONE THOUSAND
{ 0x2183, 0x2184 }, // ROMAN NUMERAL REVERSED ONE HUNDRED
{ 0x24B6, 0x24D0 }, // CIRCLED LATIN CAPITAL LETTER A
{ 0x24B7, 0x24D1 }, // CIRCLED LATIN CAPITAL LETTER B
{ 0x24B8, 0x24D2 }, // CIRCLED LATIN CAPITAL LETTER C
{ 0x24B9, 0x24D3 }, // CIRCLED LATIN CAPITAL LETTER D
{ 0x24BA, 0x24D4 }, // CIRCLED LATIN CAPITAL LETTER E
{ 0x24BB, 0x24D5 }, // CIRCLED LATIN CAPITAL LETTER F
{ 0x24BC, 0x24D6 }, // CIRCLED LATIN CAPITAL LETTER G
{ 0x24BD, 0x24D7 }, // CIRCLED LATIN CAPITAL LETTER H
{ 0x24BE, 0x24D8 }, // CIRCLED LATIN CAPITAL LETTER I
{ 0x24BF, 0x24D9 }, // CIRCLED LATIN CAPITAL LETTER J
{ 0x24C0, 0x24DA }, // CIRCLED LATIN CAPITAL LETTER K
{ 0x24C1, 0x24DB }, // CIRCLED LATIN CAPITAL LETTER L
{ 0x24C2, 0x24DC }, // CIRCLED LATIN CAPITAL LETTER M
{ 0x24C3, 0x24DD }, // CIRCLED LATIN CAPITAL LETTER N
{ 0x24C4, 0x24DE }, // CIRCLED LATIN CAPITAL LETTER O
{ 0x24C5, 0x24DF }, // CIRCLED LATIN CAPITAL LETTER P
{ 0x24C6, 0x24E0 }, // CIRCLED LATIN CAPITAL LETTER Q
{ 0x24C7, 0x24E1 }, // CIRCLED LATIN CAPITAL LETTER R
{ 0x24C8, 0x24E2 }, // CIRCLED LATIN CAPITAL LETTER S
{ 0x24C9, 0x24E3 }, // CIRCLED LATIN CAPITAL LETTER T
{ 0x24CA, 0x24E4 }, // CIRCLED LATIN CAPITAL LETTER U
{ 0x24CB, 0x24E5 }, // CIRCLED LATIN CAPITAL LETTER V
{ 0x24CC, 0x24E6 }, // CIRCLED LATIN CAPITAL LETTER W
{ 0x24CD, 0x24E7 }, // CIRCLED LATIN CAPITAL LETTER X
{ 0x24CE, 0x24E8 }, // CIRCLED LATIN CAPITAL LETTER Y
{ 0x24CF, 0x24E9 }, // CIRCLED LATIN CAPITAL LETTER Z
{ 0x2C00, 0x2C30 }, // GLAGOLITIC CAPITAL LETTER AZU
{ 0x2C01, 0x2C31 }, // GLAGOLITIC CAPITAL LETTER BUKY
{ 0x2C02, 0x2C32 }, // GLAGOLITIC CAPITAL LETTER VEDE
{ 0x2C03, 0x2C33 }, // GLAGOLITIC CAPITAL LETTER GLAGOLI
{ 0x2C04, 0x2C34 }, // GLAGOLITIC CAPITAL LETTER DOBRO
{ 0x2C05, 0x2C35 }, // GLAGOLITIC CAPITAL LETTER YESTU
{ 0x2C06, 0x2C36 }, // GLAGOLITIC CAPITAL LETTER ZHIVETE
{ 0x2C07, 0x2C37 }, // GLAGOLITIC CAPITAL LETTER DZELO
{ 0x2C08, 0x2C38 }, // GLAGOLITIC CAPITAL LETTER ZEMLJA
{ 0x2C09, 0x2C39 }, // GLAGOLITIC CAPITAL LETTER IZHE
{ 0x2C0A, 0x2C3A }, // GLAGOLITIC CAPITAL LETTER INITIAL IZHE
{ 0x2C0B, 0x2C3B }, // GLAGOLITIC CAPITAL LETTER I
{ 0x2C0C, 0x2C3C }, // GLAGOLITIC CAPITAL LETTER DJERVI
{ 0x2C0D, 0x2C3D }, // GLAGOLITIC CAPITAL LETTER KAKO
{ 0x2C0E, 0x2C3E }, // GLAGOLITIC CAPITAL LETTER LJUDIJE
{ 0x2C0F, 0x2C3F }, // GLAGOLITIC CAPITAL LETTER MYSLITE
{ 0x2C10, 0x2C40 }, // GLAGOLITIC CAPITAL LETTER NASHI
{ 0x2C11, 0x2C41 }, // GLAGOLITIC CAPITAL LETTER ONU
{ 0x2C12, 0x2C42 }, // GLAGOLITIC CAPITAL LETTER POKOJI
{ 0x2C13, 0x2C43 }, // GLAGOLITIC CAPITAL LETTER RITSI
{ 0x2C14, 0x2C44 }, // GLAGOLITIC CAPITAL LETTER SLOVO
{ 0x2C15, 0x2C45 }, // GLAGOLITIC CAPITAL LETTER TVRIDO
{ 0x2C16, 0x2C46 }, // GLAGOLITIC CAPITAL LETTER UKU
{ 0x2C17, 0x2C47 }, // GLAGOLITIC CAPITAL LETTER FRITU
{ 0x2C18, 0x2C48 }, // GLAGOLITIC CAPITAL LETTER HERU
{ 0x2C19, 0x2C49 }, // GLAGOLITIC CAPITAL LETTER OTU
{ 0x2C1A, 0x2C4A }, // GLAGOLITIC CAPITAL LETTER PE
{ 0x2C1B, 0x2C4B }, // GLAGOLITIC CAPITAL LETTER SHTA
{ 0x2C1C, 0x2C4C }, // GLAGOLITIC CAPITAL LETTER TSI
{ 0x2C1D, 0x2C4D }, // GLAGOLITIC CAPITAL LETTER CHRIVI
{ 0x2C1E, 0x2C4E }, // GLAGOLITIC CAPITAL LETTER SHA
{ 0x2C1F, 0x2C4F }, // GLAGOLITIC CAPITAL LETTER YERU
{ 0x2C20, 0x2C50 }, // GLAGOLITIC CAPITAL LETTER YERI
{ 0x2C21, 0x2C51 }, // GLAGOLITIC CAPITAL LETTER YATI
{ 0x2C22, 0x2C52 }, // GLAGOLITIC CAPITAL LETTER SPIDERY HA
{ 0x2C23, 0x2C53 }, // GLAGOLITIC CAPITAL LETTER YU
{ 0x2C24, 0x2C54 }, // GLAGOLITIC CAPITAL LETTER SMALL YUS
{ 0x2C25, 0x2C55 }, // GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL
{ 0x2C26, 0x2C56 }, // GLAGOLITIC CAPITAL LETTER YO
{ 0x2C27, 0x2C57 }, // GLAGOLITIC CAPITAL LETTER IOTATED SMALL YUS
{ 0x2C28, 0x2C58 }, // GLAGOLITIC CAPITAL LETTER BIG YUS
{ 0x2C29, 0x2C59 }, // GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS
{ 0x2C2A, 0x2C5A }, // GLAGOLITIC CAPITAL LETTER FITA
{ 0x2C2B, 0x2C5B }, // GLAGOLITIC CAPITAL LETTER IZHITSA
{ 0x2C2C, 0x2C5C }, // GLAGOLITIC CAPITAL LETTER SHTAPIC
{ 0x2C2D, 0x2C5D }, // GLAGOLITIC CAPITAL LETTER TROKUTASTI A
{ 0x2C2E, 0x2C5E }, // GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE
{ 0x2C60, 0x2C61 }, // LATIN CAPITAL LETTER L WITH DOUBLE BAR
{ 0x2C62, 0x026B }, // LATIN CAPITAL LETTER L WITH MIDDLE TILDE
{ 0x2C63, 0x1D7D }, // LATIN CAPITAL LETTER P WITH STROKE
{ 0x2C64, 0x027D }, // LATIN CAPITAL LETTER R WITH TAIL
{ 0x2C67, 0x2C68 }, // LATIN CAPITAL LETTER H WITH DESCENDER
{ 0x2C69, 0x2C6A }, // LATIN CAPITAL LETTER K WITH DESCENDER
{ 0x2C6B, 0x2C6C }, // LATIN CAPITAL LETTER Z WITH DESCENDER
{ 0x2C6D, 0x0251 }, // LATIN CAPITAL LETTER ALPHA
{ 0x2C6E, 0x0271 }, // LATIN CAPITAL LETTER M WITH HOOK
{ 0x2C6F, 0x0250 }, // LATIN CAPITAL LETTER TURNED A
{ 0x2C70, 0x0252 }, // LATIN CAPITAL LETTER TURNED ALPHA
{ 0x2C72, 0x2C73 }, // LATIN CAPITAL LETTER W WITH HOOK
{ 0x2C75, 0x2C76 }, // LATIN CAPITAL LETTER HALF H
{ 0x2C7E, 0x023F }, // LATIN CAPITAL LETTER S WITH SWASH TAIL
{ 0x2C7F, 0x0240 }, // LATIN CAPITAL LETTER Z WITH SWASH TAIL
{ 0x2C80, 0x2C81 }, // COPTIC CAPITAL LETTER ALFA
{ 0x2C82, 0x2C83 }, // COPTIC CAPITAL LETTER VIDA
{ 0x2C84, 0x2C85 }, // COPTIC CAPITAL LETTER GAMMA
{ 0x2C86, 0x2C87 }, // COPTIC CAPITAL LETTER DALDA
{ 0x2C88, 0x2C89 }, // COPTIC CAPITAL LETTER EIE
{ 0x2C8A, 0x2C8B }, // COPTIC CAPITAL LETTER SOU
{ 0x2C8C, 0x2C8D }, // COPTIC CAPITAL LETTER ZATA
{ 0x2C8E, 0x2C8F }, // COPTIC CAPITAL LETTER HATE
{ 0x2C90, 0x2C91 }, // COPTIC CAPITAL LETTER THETHE
{ 0x2C92, 0x2C93 }, // COPTIC CAPITAL LETTER IAUDA
{ 0x2C94, 0x2C95 }, // COPTIC CAPITAL LETTER KAPA
{ 0x2C96, 0x2C97 }, // COPTIC CAPITAL LETTER LAULA
{ 0x2C98, 0x2C99 }, // COPTIC CAPITAL LETTER MI
{ 0x2C9A, 0x2C9B }, // COPTIC CAPITAL LETTER NI
{ 0x2C9C, 0x2C9D }, // COPTIC CAPITAL LETTER KSI
{ 0x2C9E, 0x2C9F }, // COPTIC CAPITAL LETTER O
{ 0x2CA0, 0x2CA1 }, // COPTIC CAPITAL LETTER PI
{ 0x2CA2, 0x2CA3 }, // COPTIC CAPITAL LETTER RO
{ 0x2CA4, 0x2CA5 }, // COPTIC CAPITAL LETTER SIMA
{ 0x2CA6, 0x2CA7 }, // COPTIC CAPITAL LETTER TAU
{ 0x2CA8, 0x2CA9 }, // COPTIC CAPITAL LETTER UA
{ 0x2CAA, 0x2CAB }, // COPTIC CAPITAL LETTER FI
{ 0x2CAC, 0x2CAD }, // COPTIC CAPITAL LETTER KHI
{ 0x2CAE, 0x2CAF }, // COPTIC CAPITAL LETTER PSI
{ 0x2CB0, 0x2CB1 }, // COPTIC CAPITAL LETTER OOU
{ 0x2CB2, 0x2CB3 }, // COPTIC CAPITAL LETTER DIALECT-P ALEF
{ 0x2CB4, 0x2CB5 }, // COPTIC CAPITAL LETTER OLD COPTIC AIN
{ 0x2CB6, 0x2CB7 }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC EIE
{ 0x2CB8, 0x2CB9 }, // COPTIC CAPITAL LETTER DIALECT-P KAPA
{ 0x2CBA, 0x2CBB }, // COPTIC CAPITAL LETTER DIALECT-P NI
{ 0x2CBC, 0x2CBD }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC NI
{ 0x2CBE, 0x2CBF }, // COPTIC CAPITAL LETTER OLD COPTIC OOU
{ 0x2CC0, 0x2CC1 }, // COPTIC CAPITAL LETTER SAMPI
{ 0x2CC2, 0x2CC3 }, // COPTIC CAPITAL LETTER CROSSED SHEI
{ 0x2CC4, 0x2CC5 }, // COPTIC CAPITAL LETTER OLD COPTIC SHEI
{ 0x2CC6, 0x2CC7 }, // COPTIC CAPITAL LETTER OLD COPTIC ESH
{ 0x2CC8, 0x2CC9 }, // COPTIC CAPITAL LETTER AKHMIMIC KHEI
{ 0x2CCA, 0x2CCB }, // COPTIC CAPITAL LETTER DIALECT-P HORI
{ 0x2CCC, 0x2CCD }, // COPTIC CAPITAL LETTER OLD COPTIC HORI
{ 0x2CCE, 0x2CCF }, // COPTIC CAPITAL LETTER OLD COPTIC HA
{ 0x2CD0, 0x2CD1 }, // COPTIC CAPITAL LETTER L-SHAPED HA
{ 0x2CD2, 0x2CD3 }, // COPTIC CAPITAL LETTER OLD COPTIC HEI
{ 0x2CD4, 0x2CD5 }, // COPTIC CAPITAL LETTER OLD COPTIC HAT
{ 0x2CD6, 0x2CD7 }, // COPTIC CAPITAL LETTER OLD COPTIC GANGIA
{ 0x2CD8, 0x2CD9 }, // COPTIC CAPITAL LETTER OLD COPTIC DJA
{ 0x2CDA, 0x2CDB }, // COPTIC CAPITAL LETTER OLD COPTIC SHIMA
{ 0x2CDC, 0x2CDD }, // COPTIC CAPITAL LETTER OLD NUBIAN SHIMA
{ 0x2CDE, 0x2CDF }, // COPTIC CAPITAL LETTER OLD NUBIAN NGI
{ 0x2CE0, 0x2CE1 }, // COPTIC CAPITAL LETTER OLD NUBIAN NYI
{ 0x2CE2, 0x2CE3 }, // COPTIC CAPITAL LETTER OLD NUBIAN WAU
{ 0x2CEB, 0x2CEC }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC SHEI
{ 0x2CED, 0x2CEE }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC GANGIA
{ 0xA640, 0xA641 }, // CYRILLIC CAPITAL LETTER ZEMLYA
{ 0xA642, 0xA643 }, // CYRILLIC CAPITAL LETTER DZELO
{ 0xA644, 0xA645 }, // CYRILLIC CAPITAL LETTER REVERSED DZE
{ 0xA646, 0xA647 }, // CYRILLIC CAPITAL LETTER IOTA
{ 0xA648, 0xA649 }, // CYRILLIC CAPITAL LETTER DJERV
{ 0xA64A, 0xA64B }, // CYRILLIC CAPITAL LETTER MONOGRAPH UK
{ 0xA64C, 0xA64D }, // CYRILLIC CAPITAL LETTER BROAD OMEGA
{ 0xA64E, 0xA64F }, // CYRILLIC CAPITAL LETTER NEUTRAL YER
{ 0xA650, 0xA651 }, // CYRILLIC CAPITAL LETTER YERU WITH BACK YER
{ 0xA652, 0xA653 }, // CYRILLIC CAPITAL LETTER IOTIFIED YAT
{ 0xA654, 0xA655 }, // CYRILLIC CAPITAL LETTER REVERSED YU
{ 0xA656, 0xA657 }, // CYRILLIC CAPITAL LETTER IOTIFIED A
{ 0xA658, 0xA659 }, // CYRILLIC CAPITAL LETTER CLOSED LITTLE YUS
{ 0xA65A, 0xA65B }, // CYRILLIC CAPITAL LETTER BLENDED YUS
{ 0xA65C, 0xA65D }, // CYRILLIC CAPITAL LETTER IOTIFIED CLOSED LITTLE YUS
{ 0xA65E, 0xA65F }, // CYRILLIC CAPITAL LETTER YN
{ 0xA662, 0xA663 }, // CYRILLIC CAPITAL LETTER SOFT DE
{ 0xA664, 0xA665 }, // CYRILLIC CAPITAL LETTER SOFT EL
{ 0xA666, 0xA667 }, // CYRILLIC CAPITAL LETTER SOFT EM
{ 0xA668, 0xA669 }, // CYRILLIC CAPITAL LETTER MONOCULAR O
{ 0xA66A, 0xA66B }, // CYRILLIC CAPITAL LETTER BINOCULAR O
{ 0xA66C, 0xA66D }, // CYRILLIC CAPITAL LETTER DOUBLE MONOCULAR O
{ 0xA680, 0xA681 }, // CYRILLIC CAPITAL LETTER DWE
{ 0xA682, 0xA683 }, // CYRILLIC CAPITAL LETTER DZWE
{ 0xA684, 0xA685 }, // CYRILLIC CAPITAL LETTER ZHWE
{ 0xA686, 0xA687 }, // CYRILLIC CAPITAL LETTER CCHE
{ 0xA688, 0xA689 }, // CYRILLIC CAPITAL LETTER DZZE
{ 0xA68A, 0xA68B }, // CYRILLIC CAPITAL LETTER TE WITH MIDDLE HOOK
{ 0xA68C, 0xA68D }, // CYRILLIC CAPITAL LETTER TWE
{ 0xA68E, 0xA68F }, // CYRILLIC CAPITAL LETTER TSWE
{ 0xA690, 0xA691 }, // CYRILLIC CAPITAL LETTER TSSE
{ 0xA692, 0xA693 }, // CYRILLIC CAPITAL LETTER TCHE
{ 0xA694, 0xA695 }, // CYRILLIC CAPITAL LETTER HWE
{ 0xA696, 0xA697 }, // CYRILLIC CAPITAL LETTER SHWE
{ 0xA722, 0xA723 }, // LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF
{ 0xA724, 0xA725 }, // LATIN CAPITAL LETTER EGYPTOLOGICAL AIN
{ 0xA726, 0xA727 }, // LATIN CAPITAL LETTER HENG
{ 0xA728, 0xA729 }, // LATIN CAPITAL LETTER TZ
{ 0xA72A, 0xA72B }, // LATIN CAPITAL LETTER TRESILLO
{ 0xA72C, 0xA72D }, // LATIN CAPITAL LETTER CUATRILLO
{ 0xA72E, 0xA72F }, // LATIN CAPITAL LETTER CUATRILLO WITH COMMA
{ 0xA732, 0xA733 }, // LATIN CAPITAL LETTER AA
{ 0xA734, 0xA735 }, // LATIN CAPITAL LETTER AO
{ 0xA736, 0xA737 }, // LATIN CAPITAL LETTER AU
{ 0xA738, 0xA739 }, // LATIN CAPITAL LETTER AV
{ 0xA73A, 0xA73B }, // LATIN CAPITAL LETTER AV WITH HORIZONTAL BAR
{ 0xA73C, 0xA73D }, // LATIN CAPITAL LETTER AY
{ 0xA73E, 0xA73F }, // LATIN CAPITAL LETTER REVERSED C WITH DOT
{ 0xA740, 0xA741 }, // LATIN CAPITAL LETTER K WITH STROKE
{ 0xA742, 0xA743 }, // LATIN CAPITAL LETTER K WITH DIAGONAL STROKE
{ 0xA744, 0xA745 }, // LATIN CAPITAL LETTER K WITH STROKE AND DIAGONAL STROKE
{ 0xA746, 0xA747 }, // LATIN CAPITAL LETTER BROKEN L
{ 0xA748, 0xA749 }, // LATIN CAPITAL LETTER L WITH HIGH STROKE
{ 0xA74A, 0xA74B }, // LATIN CAPITAL LETTER O WITH LONG STROKE OVERLAY
{ 0xA74C, 0xA74D }, // LATIN CAPITAL LETTER O WITH LOOP
{ 0xA74E, 0xA74F }, // LATIN CAPITAL LETTER OO
{ 0xA750, 0xA751 }, // LATIN CAPITAL LETTER P WITH STROKE THROUGH DESCENDER
{ 0xA752, 0xA753 }, // LATIN CAPITAL LETTER P WITH FLOURISH
{ 0xA754, 0xA755 }, // LATIN CAPITAL LETTER P WITH SQUIRREL TAIL
{ 0xA756, 0xA757 }, // LATIN CAPITAL LETTER Q WITH STROKE THROUGH DESCENDER
{ 0xA758, 0xA759 }, // LATIN CAPITAL LETTER Q WITH DIAGONAL STROKE
{ 0xA75A, 0xA75B }, // LATIN CAPITAL LETTER R ROTUNDA
{ 0xA75C, 0xA75D }, // LATIN CAPITAL LETTER RUM ROTUNDA
{ 0xA75E, 0xA75F }, // LATIN CAPITAL LETTER V WITH DIAGONAL STROKE
{ 0xA760, 0xA761 }, // LATIN CAPITAL LETTER VY
{ 0xA762, 0xA763 }, // LATIN CAPITAL LETTER VISIGOTHIC Z
{ 0xA764, 0xA765 }, // LATIN CAPITAL LETTER THORN WITH STROKE
{ 0xA766, 0xA767 }, // LATIN CAPITAL LETTER THORN WITH STROKE THROUGH DESCENDER
{ 0xA768, 0xA769 }, // LATIN CAPITAL LETTER VEND
{ 0xA76A, 0xA76B }, // LATIN CAPITAL LETTER ET
{ 0xA76C, 0xA76D }, // LATIN CAPITAL LETTER IS
{ 0xA76E, 0xA76F }, // LATIN CAPITAL LETTER CON
{ 0xA779, 0xA77A }, // LATIN CAPITAL LETTER INSULAR D
{ 0xA77B, 0xA77C }, // LATIN CAPITAL LETTER INSULAR F
{ 0xA77D, 0x1D79 }, // LATIN CAPITAL LETTER INSULAR G
{ 0xA77E, 0xA77F }, // LATIN CAPITAL LETTER TURNED INSULAR G
{ 0xA780, 0xA781 }, // LATIN CAPITAL LETTER TURNED L
{ 0xA782, 0xA783 }, // LATIN CAPITAL LETTER INSULAR R
{ 0xA784, 0xA785 }, // LATIN CAPITAL LETTER INSULAR S
{ 0xA786, 0xA787 }, // LATIN CAPITAL LETTER INSULAR T
{ 0xA78B, 0xA78C }, // LATIN CAPITAL LETTER SALTILLO
{ 0xFF21, 0xFF41 }, // FULLWIDTH LATIN CAPITAL LETTER A
{ 0xFF22, 0xFF42 }, // FULLWIDTH LATIN CAPITAL LETTER B
{ 0xFF23, 0xFF43 }, // FULLWIDTH LATIN CAPITAL LETTER C
{ 0xFF24, 0xFF44 }, // FULLWIDTH LATIN CAPITAL LETTER D
{ 0xFF25, 0xFF45 }, // FULLWIDTH LATIN CAPITAL LETTER E
{ 0xFF26, 0xFF46 }, // FULLWIDTH LATIN CAPITAL LETTER F
{ 0xFF27, 0xFF47 }, // FULLWIDTH LATIN CAPITAL LETTER G
{ 0xFF28, 0xFF48 }, // FULLWIDTH LATIN CAPITAL LETTER H
{ 0xFF29, 0xFF49 }, // FULLWIDTH LATIN CAPITAL LETTER I
{ 0xFF2A, 0xFF4A }, // FULLWIDTH LATIN CAPITAL LETTER J
{ 0xFF2B, 0xFF4B }, // FULLWIDTH LATIN CAPITAL LETTER K
{ 0xFF2C, 0xFF4C }, // FULLWIDTH LATIN CAPITAL LETTER L
{ 0xFF2D, 0xFF4D }, // FULLWIDTH LATIN CAPITAL LETTER M
{ 0xFF2E, 0xFF4E }, // FULLWIDTH LATIN CAPITAL LETTER N
{ 0xFF2F, 0xFF4F }, // FULLWIDTH LATIN CAPITAL LETTER O
{ 0xFF30, 0xFF50 }, // FULLWIDTH LATIN CAPITAL LETTER P
{ 0xFF31, 0xFF51 }, // FULLWIDTH LATIN CAPITAL LETTER Q
{ 0xFF32, 0xFF52 }, // FULLWIDTH LATIN CAPITAL LETTER R
{ 0xFF33, 0xFF53 }, // FULLWIDTH LATIN CAPITAL LETTER S
{ 0xFF34, 0xFF54 }, // FULLWIDTH LATIN CAPITAL LETTER T
{ 0xFF35, 0xFF55 }, // FULLWIDTH LATIN CAPITAL LETTER U
{ 0xFF36, 0xFF56 }, // FULLWIDTH LATIN CAPITAL LETTER V
{ 0xFF37, 0xFF57 }, // FULLWIDTH LATIN CAPITAL LETTER W
{ 0xFF38, 0xFF58 }, // FULLWIDTH LATIN CAPITAL LETTER X
{ 0xFF39, 0xFF59 }, // FULLWIDTH LATIN CAPITAL LETTER Y
{ 0xFF3A, 0xFF5A } // FULLWIDTH LATIN CAPITAL LETTER Z
};
static int compare_pair_capital(const void *a, const void *b) {
return (int)(*(unsigned short *)a)
- (int)((struct LatinCapitalSmallPair*)b)->capital;
}
unsigned short latin_tolower(unsigned short c) {
struct LatinCapitalSmallPair *p =
(struct LatinCapitalSmallPair *)bsearch(&c, SORTED_CHAR_MAP,
sizeof(SORTED_CHAR_MAP) / sizeof(SORTED_CHAR_MAP[0]),
sizeof(SORTED_CHAR_MAP[0]),
compare_pair_capital);
return p ? p->small : c;
}
} // namespace latinime
| 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.
*/
#ifndef LATINIME_DICTIONARY_H
#define LATINIME_DICTIONARY_H
namespace latinime {
// 22-bit address = ~4MB dictionary size limit, which on average would be about 200k-300k words
#define ADDRESS_MASK 0x3FFFFF
// The bit that decides if an address follows in the next 22 bits
#define FLAG_ADDRESS_MASK 0x40
// The bit that decides if this is a terminal node for a word. The node could still have children,
// if the word has other endings.
#define FLAG_TERMINAL_MASK 0x80
#define FLAG_BIGRAM_READ 0x80
#define FLAG_BIGRAM_CHILDEXIST 0x40
#define FLAG_BIGRAM_CONTINUED 0x80
#define FLAG_BIGRAM_FREQ 0x7F
class Dictionary {
public:
Dictionary(void *dict, int typedLetterMultipler, int fullWordMultiplier, int dictSize);
int getSuggestions(int *codes, int codesSize, unsigned short *outWords, int *frequencies,
int maxWordLength, int maxWords, int maxAlternatives, int skipPos,
int *nextLetters, int nextLettersSize);
int getBigrams(unsigned short *word, int length, int *codes, int codesSize,
unsigned short *outWords, int *frequencies, int maxWordLength, int maxBigrams,
int maxAlternatives);
bool isValidWord(unsigned short *word, int length);
void setAsset(void *asset) { mAsset = asset; }
void *getAsset() { return mAsset; }
~Dictionary();
private:
void getVersionNumber();
bool checkIfDictVersionIsLatest();
int getAddress(int *pos);
int getBigramAddress(int *pos, bool advance);
int getFreq(int *pos);
int getBigramFreq(int *pos);
void searchForTerminalNode(int address, int frequency);
bool getFirstBitOfByte(int *pos) { return (mDict[*pos] & 0x80) > 0; }
bool getSecondBitOfByte(int *pos) { return (mDict[*pos] & 0x40) > 0; }
bool getTerminal(int *pos) { return (mDict[*pos] & FLAG_TERMINAL_MASK) > 0; }
int getCount(int *pos) { return mDict[(*pos)++] & 0xFF; }
unsigned short getChar(int *pos);
int wideStrLen(unsigned short *str);
bool sameAsTyped(unsigned short *word, int length);
bool checkFirstCharacter(unsigned short *word);
bool addWord(unsigned short *word, int length, int frequency);
bool addWordBigram(unsigned short *word, int length, int frequency);
unsigned short toLowerCase(unsigned short c);
void getWordsRec(int pos, int depth, int maxDepth, bool completion, int frequency,
int inputIndex, int diffs);
int isValidWordRec(int pos, unsigned short *word, int offset, int length);
void registerNextLetter(unsigned short c);
unsigned char *mDict;
void *mAsset;
int *mFrequencies;
int *mBigramFreq;
int mMaxWords;
int mMaxBigrams;
int mMaxWordLength;
unsigned short *mOutputChars;
unsigned short *mBigramChars;
int *mInputCodes;
int mInputLength;
int mMaxAlternatives;
unsigned short mWord[128];
int mSkipPos;
int mMaxEditDistance;
int mFullWordMultiplier;
int mTypedLetterMultiplier;
int mDictSize;
int *mNextLettersFrequencies;
int mNextLettersSize;
int mVersion;
int mBigram;
};
// ----------------------------------------------------------------------------
}; // namespace latinime
#endif // LATINIME_DICTIONARY_H
| C++ |
/*
* Copyright (C) 2010 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.
*/
#ifndef LATINIME_CHAR_UTILS_H
#define LATINIME_CHAR_UTILS_H
namespace latinime {
unsigned short latin_tolower(unsigned short c);
}; // namespace latinime
#endif // LATINIME_CHAR_UTILS_H
| C++ |
/*
**
** Copyright 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 <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
//#define LOG_TAG "dictionary.cpp"
//#include <cutils/log.h>
#define LOGI
#include "dictionary.h"
#include "basechars.h"
#include "char_utils.h"
#define DEBUG_DICT 0
#define DICTIONARY_VERSION_MIN 200
#define DICTIONARY_HEADER_SIZE 2
#define NOT_VALID_WORD -99
namespace latinime {
Dictionary::Dictionary(void *dict, int typedLetterMultiplier, int fullWordMultiplier, int size)
{
mDict = (unsigned char*) dict;
mTypedLetterMultiplier = typedLetterMultiplier;
mFullWordMultiplier = fullWordMultiplier;
mDictSize = size;
getVersionNumber();
}
Dictionary::~Dictionary()
{
}
int Dictionary::getSuggestions(int *codes, int codesSize, unsigned short *outWords, int *frequencies,
int maxWordLength, int maxWords, int maxAlternatives, int skipPos,
int *nextLetters, int nextLettersSize)
{
int suggWords;
mFrequencies = frequencies;
mOutputChars = outWords;
mInputCodes = codes;
mInputLength = codesSize;
mMaxAlternatives = maxAlternatives;
mMaxWordLength = maxWordLength;
mMaxWords = maxWords;
mSkipPos = skipPos;
mMaxEditDistance = mInputLength < 5 ? 2 : mInputLength / 2;
mNextLettersFrequencies = nextLetters;
mNextLettersSize = nextLettersSize;
if (checkIfDictVersionIsLatest()) {
getWordsRec(DICTIONARY_HEADER_SIZE, 0, mInputLength * 3, false, 1, 0, 0);
} else {
getWordsRec(0, 0, mInputLength * 3, false, 1, 0, 0);
}
// Get the word count
suggWords = 0;
while (suggWords < mMaxWords && mFrequencies[suggWords] > 0) suggWords++;
if (DEBUG_DICT) LOGI("Returning %d words", suggWords);
if (DEBUG_DICT) {
LOGI("Next letters: ");
for (int k = 0; k < nextLettersSize; k++) {
if (mNextLettersFrequencies[k] > 0) {
LOGI("%c = %d,", k, mNextLettersFrequencies[k]);
}
}
LOGI("\n");
}
return suggWords;
}
void
Dictionary::registerNextLetter(unsigned short c)
{
if (c < mNextLettersSize) {
mNextLettersFrequencies[c]++;
}
}
void
Dictionary::getVersionNumber()
{
mVersion = (mDict[0] & 0xFF);
mBigram = (mDict[1] & 0xFF);
LOGI("IN NATIVE SUGGEST Version: %d Bigram : %d \n", mVersion, mBigram);
}
// Checks whether it has the latest dictionary or the old dictionary
bool
Dictionary::checkIfDictVersionIsLatest()
{
return (mVersion >= DICTIONARY_VERSION_MIN) && (mBigram == 1 || mBigram == 0);
}
unsigned short
Dictionary::getChar(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
unsigned short ch = (unsigned short) (mDict[(*pos)++] & 0xFF);
// If the code is 255, then actual 16 bit code follows (in big endian)
if (ch == 0xFF) {
ch = ((mDict[*pos] & 0xFF) << 8) | (mDict[*pos + 1] & 0xFF);
(*pos) += 2;
}
return ch;
}
int
Dictionary::getAddress(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int address = 0;
if ((mDict[*pos] & FLAG_ADDRESS_MASK) == 0) {
*pos += 1;
} else {
address += (mDict[*pos] & (ADDRESS_MASK >> 16)) << 16;
address += (mDict[*pos + 1] & 0xFF) << 8;
address += (mDict[*pos + 2] & 0xFF);
*pos += 3;
}
if (address < 0 || address >= mDictSize) return 0;
return address;
}
int
Dictionary::getFreq(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int freq = mDict[(*pos)++] & 0xFF;
if (checkIfDictVersionIsLatest()) {
// skipping bigram
int bigramExist = (mDict[*pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0) {
(*pos) += 3;
nextBigramExist = (mDict[(*pos)++] & FLAG_BIGRAM_CONTINUED);
}
} else {
(*pos)++;
}
}
return freq;
}
int
Dictionary::wideStrLen(unsigned short *str)
{
if (!str) return 0;
unsigned short *end = str;
while (*end)
end++;
return end - str;
}
bool
Dictionary::addWord(unsigned short *word, int length, int frequency)
{
word[length] = 0;
if (DEBUG_DICT) {
char s[length + 1];
for (int i = 0; i <= length; i++) s[i] = word[i];
LOGI("Found word = %s, freq = %d : \n", s, frequency);
}
// Find the right insertion point
int insertAt = 0;
while (insertAt < mMaxWords) {
if (frequency > mFrequencies[insertAt]
|| (mFrequencies[insertAt] == frequency
&& length < wideStrLen(mOutputChars + insertAt * mMaxWordLength))) {
break;
}
insertAt++;
}
if (insertAt < mMaxWords) {
memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
(char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
(mMaxWords - insertAt - 1) * sizeof(mFrequencies[0]));
mFrequencies[insertAt] = frequency;
memmove((char*) mOutputChars + (insertAt + 1) * mMaxWordLength * sizeof(short),
(char*) mOutputChars + (insertAt ) * mMaxWordLength * sizeof(short),
(mMaxWords - insertAt - 1) * sizeof(short) * mMaxWordLength);
unsigned short *dest = mOutputChars + (insertAt ) * mMaxWordLength;
while (length--) {
*dest++ = *word++;
}
*dest = 0; // NULL terminate
if (DEBUG_DICT) LOGI("Added word at %d\n", insertAt);
return true;
}
return false;
}
bool
Dictionary::addWordBigram(unsigned short *word, int length, int frequency)
{
word[length] = 0;
if (DEBUG_DICT) {
char s[length + 1];
for (int i = 0; i <= length; i++) s[i] = word[i];
LOGI("Bigram: Found word = %s, freq = %d : \n", s, frequency);
}
// Find the right insertion point
int insertAt = 0;
while (insertAt < mMaxBigrams) {
if (frequency > mBigramFreq[insertAt]
|| (mBigramFreq[insertAt] == frequency
&& length < wideStrLen(mBigramChars + insertAt * mMaxWordLength))) {
break;
}
insertAt++;
}
LOGI("Bigram: InsertAt -> %d maxBigrams: %d\n", insertAt, mMaxBigrams);
if (insertAt < mMaxBigrams) {
memmove((char*) mBigramFreq + (insertAt + 1) * sizeof(mBigramFreq[0]),
(char*) mBigramFreq + insertAt * sizeof(mBigramFreq[0]),
(mMaxBigrams - insertAt - 1) * sizeof(mBigramFreq[0]));
mBigramFreq[insertAt] = frequency;
memmove((char*) mBigramChars + (insertAt + 1) * mMaxWordLength * sizeof(short),
(char*) mBigramChars + (insertAt ) * mMaxWordLength * sizeof(short),
(mMaxBigrams - insertAt - 1) * sizeof(short) * mMaxWordLength);
unsigned short *dest = mBigramChars + (insertAt ) * mMaxWordLength;
while (length--) {
*dest++ = *word++;
}
*dest = 0; // NULL terminate
if (DEBUG_DICT) LOGI("Bigram: Added word at %d\n", insertAt);
return true;
}
return false;
}
unsigned short
Dictionary::toLowerCase(unsigned short c) {
if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
c = BASE_CHARS[c];
}
if (c >='A' && c <= 'Z') {
c |= 32;
} else if (c > 127) {
c = latin_tolower(c);
}
return c;
}
bool
Dictionary::sameAsTyped(unsigned short *word, int length)
{
if (length != mInputLength) {
return false;
}
int *inputCodes = mInputCodes;
while (length--) {
if ((unsigned int) *inputCodes != (unsigned int) *word) {
return false;
}
inputCodes += mMaxAlternatives;
word++;
}
return true;
}
static char QUOTE = '\'';
void
Dictionary::getWordsRec(int pos, int depth, int maxDepth, bool completion, int snr, int inputIndex,
int diffs)
{
// Optimization: Prune out words that are too long compared to how much was typed.
if (depth > maxDepth) {
return;
}
if (diffs > mMaxEditDistance) {
return;
}
int count = getCount(&pos);
int *currentChars = NULL;
if (mInputLength <= inputIndex) {
completion = true;
} else {
currentChars = mInputCodes + (inputIndex * mMaxAlternatives);
}
for (int i = 0; i < count; i++) {
// -- at char
unsigned short c = getChar(&pos);
// -- at flag/add
unsigned short lowerC = toLowerCase(c);
bool terminal = getTerminal(&pos);
int childrenAddress = getAddress(&pos);
// -- after address or flag
int freq = 1;
if (terminal) freq = getFreq(&pos);
// -- after add or freq
// If we are only doing completions, no need to look at the typed characters.
if (completion) {
mWord[depth] = c;
if (terminal) {
addWord(mWord, depth + 1, freq * snr);
if (depth >= mInputLength && mSkipPos < 0) {
registerNextLetter(mWord[mInputLength]);
}
}
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth,
completion, snr, inputIndex, diffs);
}
} else if ((c == QUOTE && currentChars[0] != QUOTE) || mSkipPos == depth) {
// Skip the ' or other letter and continue deeper
mWord[depth] = c;
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth, false, snr, inputIndex, diffs);
}
} else {
int j = 0;
while (currentChars[j] > 0) {
if (currentChars[j] == lowerC || currentChars[j] == c) {
int addedWeight = j == 0 ? mTypedLetterMultiplier : 1;
mWord[depth] = c;
if (mInputLength == inputIndex + 1) {
if (terminal) {
if (//INCLUDE_TYPED_WORD_IF_VALID ||
!sameAsTyped(mWord, depth + 1)) {
int finalFreq = freq * snr * addedWeight;
if (mSkipPos < 0) finalFreq *= mFullWordMultiplier;
addWord(mWord, depth + 1, finalFreq);
}
}
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1,
maxDepth, true, snr * addedWeight, inputIndex + 1,
diffs + (j > 0));
}
} else if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth,
false, snr * addedWeight, inputIndex + 1, diffs + (j > 0));
}
}
j++;
if (mSkipPos >= 0) break;
}
}
}
}
int
Dictionary::getBigramAddress(int *pos, bool advance)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int address = 0;
address += (mDict[*pos] & 0x3F) << 16;
address += (mDict[*pos + 1] & 0xFF) << 8;
address += (mDict[*pos + 2] & 0xFF);
if (advance) {
*pos += 3;
}
if (address < 0 || address >= mDictSize) return 0;
return address;
}
int
Dictionary::getBigramFreq(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int freq = mDict[(*pos)++] & FLAG_BIGRAM_FREQ;
return freq;
}
int
Dictionary::getBigrams(unsigned short *prevWord, int prevWordLength, int *codes, int codesSize,
unsigned short *bigramChars, int *bigramFreq, int maxWordLength, int maxBigrams,
int maxAlternatives)
{
mBigramFreq = bigramFreq;
mBigramChars = bigramChars;
mInputCodes = codes;
mInputLength = codesSize;
mMaxWordLength = maxWordLength;
mMaxBigrams = maxBigrams;
mMaxAlternatives = maxAlternatives;
if (mBigram == 1 && checkIfDictVersionIsLatest()) {
int pos = isValidWordRec(DICTIONARY_HEADER_SIZE, prevWord, 0, prevWordLength);
LOGI("Pos -> %d\n", pos);
if (pos < 0) {
return 0;
}
int bigramCount = 0;
int bigramExist = (mDict[pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0 && bigramCount < maxBigrams) {
int bigramAddress = getBigramAddress(&pos, true);
int frequency = (FLAG_BIGRAM_FREQ & mDict[pos]);
// search for all bigrams and store them
searchForTerminalNode(bigramAddress, frequency);
nextBigramExist = (mDict[pos++] & FLAG_BIGRAM_CONTINUED);
bigramCount++;
}
}
return bigramCount;
}
return 0;
}
void
Dictionary::searchForTerminalNode(int addressLookingFor, int frequency)
{
// track word with such address and store it in an array
unsigned short word[mMaxWordLength];
int pos;
int followDownBranchAddress = DICTIONARY_HEADER_SIZE;
bool found = false;
char followingChar = ' ';
int depth = -1;
while(!found) {
bool followDownAddressSearchStop = false;
bool firstAddress = true;
bool haveToSearchAll = true;
if (depth >= 0) {
word[depth] = (unsigned short) followingChar;
}
pos = followDownBranchAddress; // pos start at count
int count = mDict[pos] & 0xFF;
LOGI("count - %d\n",count);
pos++;
for (int i = 0; i < count; i++) {
// pos at data
pos++;
// pos now at flag
if (!getFirstBitOfByte(&pos)) { // non-terminal
if (!followDownAddressSearchStop) {
int addr = getBigramAddress(&pos, false);
if (addr > addressLookingFor) {
followDownAddressSearchStop = true;
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
} else if (!haveToSearchAll) {
break;
}
} else {
followDownBranchAddress = addr;
followingChar = (char)(0xFF & mDict[pos-1]);
if (firstAddress) {
firstAddress = false;
haveToSearchAll = false;
}
}
}
pos += 3;
} else if (getFirstBitOfByte(&pos)) { // terminal
if (addressLookingFor == (pos-1)) { // found !!
depth++;
word[depth] = (0xFF & mDict[pos-1]);
found = true;
break;
}
if (getSecondBitOfByte(&pos)) { // address + freq (4 byte)
if (!followDownAddressSearchStop) {
int addr = getBigramAddress(&pos, false);
if (addr > addressLookingFor) {
followDownAddressSearchStop = true;
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
} else if (!haveToSearchAll) {
break;
}
} else {
followDownBranchAddress = addr;
followingChar = (char)(0xFF & mDict[pos-1]);
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
}
}
}
pos += 4;
} else { // freq only (2 byte)
pos += 2;
}
// skipping bigram
int bigramExist = (mDict[pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0) {
pos += 3;
nextBigramExist = (mDict[pos++] & FLAG_BIGRAM_CONTINUED);
}
} else {
pos++;
}
}
}
depth++;
if (followDownBranchAddress == 0) {
LOGI("ERROR!!! Cannot find bigram!!");
break;
}
}
if (checkFirstCharacter(word)) {
addWordBigram(word, depth, frequency);
}
}
bool
Dictionary::checkFirstCharacter(unsigned short *word)
{
// Checks whether this word starts with same character or neighboring characters of
// what user typed.
int *inputCodes = mInputCodes;
int maxAlt = mMaxAlternatives;
while (maxAlt > 0) {
if ((unsigned int) *inputCodes == (unsigned int) *word) {
return true;
}
inputCodes++;
maxAlt--;
}
return false;
}
bool
Dictionary::isValidWord(unsigned short *word, int length)
{
if (checkIfDictVersionIsLatest()) {
return (isValidWordRec(DICTIONARY_HEADER_SIZE, word, 0, length) != NOT_VALID_WORD);
} else {
return (isValidWordRec(0, word, 0, length) != NOT_VALID_WORD);
}
}
int
Dictionary::isValidWordRec(int pos, unsigned short *word, int offset, int length) {
// returns address of bigram data of that word
// return -99 if not found
int count = getCount(&pos);
unsigned short currentChar = (unsigned short) word[offset];
for (int j = 0; j < count; j++) {
unsigned short c = getChar(&pos);
int terminal = getTerminal(&pos);
int childPos = getAddress(&pos);
if (c == currentChar) {
if (offset == length - 1) {
if (terminal) {
return (pos+1);
}
} else {
if (childPos != 0) {
int t = isValidWordRec(childPos, word, offset + 1, length);
if (t > 0) {
return t;
}
}
}
}
if (terminal) {
getFreq(&pos);
}
// There could be two instances of each alphabet - upper and lower case. So continue
// looking ...
}
return NOT_VALID_WORD;
}
} // namespace latinime
| C++ |
/*
**
** Copyright 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 <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <jni.h>
#include "dictionary.h"
// ----------------------------------------------------------------------------
using namespace latinime;
//
// helper function to throw an exception
//
static void throwException(JNIEnv *env, const char* ex, const char* fmt, int data)
{
if (jclass cls = env->FindClass(ex)) {
char msg[1000];
sprintf(msg, fmt, data);
env->ThrowNew(cls, msg);
env->DeleteLocalRef(cls);
}
}
static jint latinime_BinaryDictionary_open
(JNIEnv *env, jobject object, jobject dictDirectBuffer,
jint typedLetterMultiplier, jint fullWordMultiplier, jint size)
{
void *dict = env->GetDirectBufferAddress(dictDirectBuffer);
if (dict == NULL) {
fprintf(stderr, "DICT: Dictionary buffer is null\n");
return 0;
}
Dictionary *dictionary = new Dictionary(dict, typedLetterMultiplier, fullWordMultiplier, size);
return (jint) dictionary;
}
static int latinime_BinaryDictionary_getSuggestions(
JNIEnv *env, jobject object, jint dict, jintArray inputArray, jint arraySize,
jcharArray outputArray, jintArray frequencyArray, jint maxWordLength, jint maxWords,
jint maxAlternatives, jint skipPos, jintArray nextLettersArray, jint nextLettersSize)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return 0;
int *frequencies = env->GetIntArrayElements(frequencyArray, NULL);
int *inputCodes = env->GetIntArrayElements(inputArray, NULL);
jchar *outputChars = env->GetCharArrayElements(outputArray, NULL);
int *nextLetters = nextLettersArray != NULL ? env->GetIntArrayElements(nextLettersArray, NULL)
: NULL;
int count = dictionary->getSuggestions(inputCodes, arraySize, (unsigned short*) outputChars,
frequencies, maxWordLength, maxWords, maxAlternatives, skipPos, nextLetters,
nextLettersSize);
env->ReleaseIntArrayElements(frequencyArray, frequencies, 0);
env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT);
env->ReleaseCharArrayElements(outputArray, outputChars, 0);
if (nextLetters) {
env->ReleaseIntArrayElements(nextLettersArray, nextLetters, 0);
}
return count;
}
static int latinime_BinaryDictionary_getBigrams
(JNIEnv *env, jobject object, jint dict, jcharArray prevWordArray, jint prevWordLength,
jintArray inputArray, jint inputArraySize, jcharArray outputArray,
jintArray frequencyArray, jint maxWordLength, jint maxBigrams, jint maxAlternatives)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return 0;
jchar *prevWord = env->GetCharArrayElements(prevWordArray, NULL);
int *inputCodes = env->GetIntArrayElements(inputArray, NULL);
jchar *outputChars = env->GetCharArrayElements(outputArray, NULL);
int *frequencies = env->GetIntArrayElements(frequencyArray, NULL);
int count = dictionary->getBigrams((unsigned short*) prevWord, prevWordLength, inputCodes,
inputArraySize, (unsigned short*) outputChars, frequencies, maxWordLength, maxBigrams,
maxAlternatives);
env->ReleaseCharArrayElements(prevWordArray, prevWord, JNI_ABORT);
env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT);
env->ReleaseCharArrayElements(outputArray, outputChars, 0);
env->ReleaseIntArrayElements(frequencyArray, frequencies, 0);
return count;
}
static jboolean latinime_BinaryDictionary_isValidWord
(JNIEnv *env, jobject object, jint dict, jcharArray wordArray, jint wordLength)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return (jboolean) false;
jchar *word = env->GetCharArrayElements(wordArray, NULL);
jboolean result = dictionary->isValidWord((unsigned short*) word, wordLength);
env->ReleaseCharArrayElements(wordArray, word, JNI_ABORT);
return result;
}
static void latinime_BinaryDictionary_close
(JNIEnv *env, jobject object, jint dict)
{
Dictionary *dictionary = (Dictionary*) dict;
delete (Dictionary*) dict;
}
// ----------------------------------------------------------------------------
static JNINativeMethod gMethods[] = {
{"openNative", "(Ljava/nio/ByteBuffer;III)I",
(void*)latinime_BinaryDictionary_open},
{"closeNative", "(I)V", (void*)latinime_BinaryDictionary_close},
{"getSuggestionsNative", "(I[II[C[IIIII[II)I", (void*)latinime_BinaryDictionary_getSuggestions},
{"isValidWordNative", "(I[CI)Z", (void*)latinime_BinaryDictionary_isValidWord},
{"getBigramsNative", "(I[CI[II[C[IIII)I", (void*)latinime_BinaryDictionary_getBigrams}
};
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
fprintf(stderr,
"Native registration unable to find class '%s'\n", className);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
fprintf(stderr, "RegisterNatives failed for '%s'\n", className);
return JNI_FALSE;
}
return JNI_TRUE;
}
static int registerNatives(JNIEnv *env)
{
const char* const kClassPathName = "org/pocketworkstation/pckeyboard/BinaryDictionary";
return registerNativeMethods(env,
kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0]));
}
/*
* Returns the JNI version on success, -1 on failure.
*/
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
fprintf(stderr, "ERROR: GetEnv failed\n");
goto bail;
}
assert(env != NULL);
if (!registerNatives(env)) {
fprintf(stderr, "ERROR: BinaryDictionary native registration failed\n");
goto bail;
}
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MEMORY_H__
#define __MEMORY_H__
#include <fstream>
#include "Cartridge.h"
#include "Sound.h"
#include "Pad.h"
#define SIZE_MEM 65536
class Memory
{
protected:
Cartridge *c;
Sound * s;
private:
void DmaTransfer(BYTE direction);
public:
BYTE memory[SIZE_MEM];
public:
Memory(Sound * s);
~Memory();
Memory *GetPtrMemory();
void ResetMem();
void LoadCartridge(Cartridge *c);
void MemW(WORD direction, BYTE value);
inline void MemWNoCheck(WORD direction, BYTE value){ memory[direction] = value; };
inline BYTE MemR(WORD direction)
{
if ((direction < 0x8000) || ((direction >=0xA000) && (direction < 0xC000)))
{
return c->Read(direction);
}
else if ((direction >= 0xFF10) && (direction <= 0xFF3F))
{
if(s)
return s->ReadRegister(direction);
}
return memory[direction];
}
void SaveMemory(std::ofstream * file);
void LoadMemory(std::ifstream * file);
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MBC_H__
#define __MBC_H__
#include <string>
#include "Def.h"
void InitMBCNone(std::string nameROM, BYTE * memCartridge, int romSize);
void InitMBC1(std::string, BYTE * memCartridge, int romSize, int ramHeaderSize);
void InitMBC2(std::string, BYTE * memCartridge, int romSize);
void InitMBC3(std::string, BYTE * memCartridge, int romSize, int ramHeaderSize);
void InitMBC5(std::string, BYTE * memCartridge, int romSize, int ramHeaderSize);
void DestroyMBC();
BYTE NoneRead(WORD direction);
void NoneWrite(WORD direction, BYTE value);
BYTE MBC1Read(WORD direction);
void MBC1Write(WORD direction, BYTE value);
BYTE MBC2Read(WORD direction);
void MBC2Write(WORD direction, BYTE value);
BYTE MBC3Read(WORD direction);
void MBC3Write(WORD direction, BYTE value);
BYTE MBC5Read(WORD direction);
void MBC5Write(WORD direction, BYTE value);
void MBCPathBatteries(std::string path);
void MBCSaveState(std::ofstream * file);
void MBCLoadState(std::ifstream * file);
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "Sound.h"
using namespace std;
enum SoundError { ERROR, NO_ERROR };
int Sound::HandleError( const char* str )
{
if ( str )
{
cerr << "Error: " << str << endl;
return ERROR;
}
else
return NO_ERROR;
}
Sound::Sound()
{
enabled = false;
initialized = true;
sampleRate = 44100;//22050;
if ( SDL_Init( SDL_INIT_AUDIO ) < 0 )
{
initialized = false;
return;
}
atexit( SDL_Quit );
if (ChangeSampleRate(sampleRate) == ERROR)
{
initialized = false;
return;
}
if (Start() == ERROR)
{
initialized = false;
return;
}
}
Sound::~Sound()
{
}
int Sound::ChangeSampleRate(long newSampleRate)
{
if (!initialized)
return NO_ERROR;
sampleRate = newSampleRate;
bool wasEnabled = enabled;
if (wasEnabled)
Stop();
// Set sample rate and check for out of memory error
if (HandleError( apu.set_sample_rate(sampleRate) ) == ERROR)
return ERROR;
if (wasEnabled)
{
if (Start() == ERROR)
return ERROR;
}
return NO_ERROR;
}
int Sound::Start()
{
if (!initialized)
return NO_ERROR;
if (!enabled)
{
// Generate a few seconds of sound and play using SDL
if (HandleError( sound.start(sampleRate, 2) ) == ERROR)
return ERROR;
}
enabled = true;
return NO_ERROR;
}
int Sound::Stop()
{
if (!initialized)
return NO_ERROR;
if (enabled)
sound.stop();
enabled = false;
return NO_ERROR;
}
bool Sound::GetEnabled()
{
return enabled;
}
void Sound::SetEnabled(bool enabled)
{
if (enabled)
Start();
else
Stop();
}
void Sound::EndFrame()
{
if ((!initialized) || (!enabled))
return;
apu.end_frame();
int const buf_size = 2048;
static blip_sample_t buf [buf_size];
if ( apu.samples_avail() >= buf_size )
{
// Play whatever samples are available
long count = apu.read_samples( buf, buf_size );
sound.write( buf, count );
}
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include <fstream>
#include <iomanip>
#include "Registers.h"
#include "GBException.h"
using namespace std;
Registers::Registers() {ResetRegs();}
Registers::~Registers()
{
}
Registers *Registers::GetPtrRegisters() {return this;}
WORD Registers::Get_Reg(e_registers reg)
{
switch (reg){
case A: return this->Get_A(); break;
case B: return this->Get_B(); break;
case C: return this->Get_C(); break;
case D: return this->Get_D(); break;
case E: return this->Get_E(); break;
case F: return this->Get_F(); break;
case H: return this->Get_H(); break;
case L: return this->Get_L(); break;
case AF: return this->Get_AF(); break;
case BC: return this->Get_BC(); break;
case DE: return this->Get_DE(); break;
case HL: return this->Get_HL(); break;
case PC: return this->Get_PC(); break;
case SP: return this->Get_SP(); break;
default:
stringstream out;
out << "Get_Reg - Error, incorrect register: " << reg << endl;
throw GBException(out.str().data());
}
}
void Registers::Set_Reg(e_registers reg, WORD value)
{
switch (reg){
case A: this->Set_A((BYTE)value); break;
case B: this->Set_B((BYTE)value); break;
case C: this->Set_C((BYTE)value); break;
case D: this->Set_D((BYTE)value); break;
case E: this->Set_E((BYTE)value); break;
case F: this->Set_F((BYTE)value); break;
case H: this->Set_H((BYTE)value); break;
case L: this->Set_L((BYTE)value); break;
case AF: this->Set_AF(value); break;
case BC: this->Set_BC(value); break;
case DE: this->Set_DE(value); break;
case HL: this->Set_HL(value); break;
case PC: this->Set_PC(value); break;
case SP: this->Set_SP(value); break;
default:
stringstream out;
out << "Set_Reg - Error, incorrect register: " << reg << endl;
throw GBException(out.str().data());
}
}
BYTE Registers::Get_Flag(e_registers flag)
{
switch (flag){
case f_C: return this->Get_flagC();
case f_H: return this->Get_flagH();
case f_N: return this->Get_flagN();
case f_Z: return this->Get_flagZ();
default:
stringstream out;
out << "Error, incorrect flag (Get): " << flag << endl;
throw GBException(out.str().data());
}
}
void Registers::Set_Flag(e_registers flag, BYTE value)
{
switch (flag){
case f_C: this->Set_flagC(value);
case f_H: this->Set_flagH(value);
case f_N: this->Set_flagN(value);
case f_Z: this->Set_flagZ(value);
default:
stringstream out;
out << "Error, incorrect flag (Set): " << flag << endl;
throw GBException(out.str().data());
}
}
void Registers::ResetRegs()
{
this->Set_AF(0x01B0);
this->Set_BC(0x0013);
this->Set_DE(0x00D8);
this->Set_HL(0x014D);
this->Set_PC(0x0100);
this->Set_SP(0xFFFE);
this->Set_Halt(false);
this->Set_Stop(false);
this->Set_IME(false);
}
string Registers::ToString()
{
stringstream out;
/*out << "PC: " << setfill('0') << setw(4) << uppercase << hex << (int)Get_PC()
<< ", AF: " << setfill('0') << setw(4) << uppercase << hex << (int)Get_AF()
<< ", BC: " << setfill('0') << setw(4) << uppercase << hex << (int)Get_BC()
<< ", DE: " << setfill('0') << setw(4) << uppercase << hex << (int)Get_DE()
<< ", HL: " << setfill('0') << setw(4) << uppercase << hex << (int)Get_HL()
<< ", SP: " << setfill('0') << setw(4) << uppercase << hex << (int) Get_SP()
<< ", H: " << Get_Halt() << ", S: " << Get_Stop() << ", I: " << Get_IME();*/
out << "PC = " << hex << (int)Get_PC()
<< " SP = " << hex << (int)Get_SP()
<< " AF = " << hex << (int)Get_AF()
<< " BC = " << hex << (int)Get_BC()
<< " DE = " << hex << (int)Get_DE()
<< " HL = " << hex << (int)Get_HL()
<< " Interrupts = " << Get_IME();
return out.str();
}
void Registers::SaveRegs(ofstream * file)
{
//file->write((char *)this, sizeof(Registers));
file->write((char *)&this->af.doble, sizeof(WORD));
file->write((char *)&this->bc.doble, sizeof(WORD));
file->write((char *)&this->de.doble, sizeof(WORD));
file->write((char *)&this->hl.doble, sizeof(WORD));
file->write((char *)&this->pc, sizeof(WORD));
file->write((char *)&this->sp, sizeof(WORD));
file->write((char *)&this->IME, sizeof(bool));
file->write((char *)&this->pendingIME, sizeof(bool));
file->write((char *)&this->pendingIMEvalue, sizeof(bool));
file->write((char *)&this->halt, sizeof(bool));
file->write((char *)&this->stop, sizeof(bool));
}
void Registers::LoadRegs(ifstream * file)
{
file->read((char *)&this->af.doble, sizeof(WORD));
file->read((char *)&this->bc.doble, sizeof(WORD));
file->read((char *)&this->de.doble, sizeof(WORD));
file->read((char *)&this->hl.doble, sizeof(WORD));
file->read((char *)&this->pc, sizeof(WORD));
file->read((char *)&this->sp, sizeof(WORD));
file->read((char *)&this->IME, sizeof(bool));
file->read((char *)&this->pendingIME, sizeof(bool));
file->read((char *)&this->pendingIMEvalue, sizeof(bool));
file->read((char *)&this->halt, sizeof(bool));
file->read((char *)&this->stop, sizeof(bool));
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CPU.h"
#include "Instructions.h"
#include <iomanip>
#include <fstream>
#include <sstream>
#include "Registers.h"
#include "GBException.h"
#include "Log.h"
using namespace std;
CPU::CPU(Video *v, Sound * s): Memory(s)
{
Init(v);
}
CPU::CPU(Video *v, Cartridge *c, Sound * s): Memory(s)
{
Init(v);
LoadCartridge(c);
}
void CPU::Init(Video *v)
{
numInstructions = 0;
cyclesLCD = 0;
bitSerial = -1;
this->v = v;
v->SetMem(this->GetPtrMemory());
FillInstructionCycles();
FillInstructionCyclesCB();
//this->log = new QueueLog(1000000);
}
CPU::~CPU()
{
}
void CPU::Reset()
{
ResetRegs();
ResetMem();
v->ClearScreen();
if (s && (s->GetEnabled()))
{
s->Stop();
s->Start();
}
}
void CPU::ExecuteOneFrame()
{
if (!this->c)
return;
actualCycles = 0;
BYTE OpCode = 0, NextOpcode = 0, lastOpCode = 0;
Instructions inst(this->GetPtrRegisters(), this->GetPtrMemory());
frameCompleted = false;
UpdatePad();
//log->Enqueue("\n\nStartFrame", NULL, "");
while (!frameCompleted)
{
numInstructions++;
lastOpCode = OpCode;
OpCode = MemR(Get_PC());
NextOpcode = MemR(Get_PC() + 1);
/*
stringstream ssOpCode;
ssOpCode << numInstructions << " - ";
ssOpCode << "OpCode: " << setfill('0') << setw(2) << uppercase << hex << (int)OpCode;
if (OpCode == 0xCB)
ssOpCode << setfill('0') << setw(2) << uppercase << hex << (int)NextOpcode;
ssOpCode << ", ";
log->Enqueue(ssOpCode.str(), this->GetPtrRegisters(), "");
*/
lastCycles = 4;
if (!Get_Halt() && !Get_Stop())
{
/*ssOpCode << " FF41 = " << hex << (int)memory[0xFF41];
ssOpCode << " FFFF = " << hex << (int)memory[0xFFFF];
log->Enqueue("", this->GetPtrRegisters(), ssOpCode.str());*/
switch(OpCode)
{
case (0x00): inst.NOP(); break;
case (0x01): inst.LD_n_nn(BC); break;
case (0x02): inst.LD_n_A(c_BC); break;
case (0x03): inst.INC_nn(BC); break;
case (0x04): inst.INC_n(B); break;
case (0x05): inst.DEC_n(B); break;
case (0x06): inst.LD_nn_n(B); break;
case (0x07): inst.RLCA(); break;
case (0x08): inst.LD_nn_SP(); break;
case (0x09): inst.ADD_HL_n(BC); break;
case (0x0A): inst.LD_A_n(c_BC); break;
case (0x0B): inst.DEC_nn(BC); break;
case (0x0C): inst.INC_n(C); break;
case (0x0D): inst.DEC_n(C); break;
case (0x0E): inst.LD_nn_n(C); break;
case (0x0F): inst.RRC_n(A); break;
case (0x10): inst.STOP(); break;
case (0x11): inst.LD_n_nn(DE); break;
case (0x12): inst.LD_n_A(c_DE); break;
case (0x13): inst.INC_nn(DE); break;
case (0x14): inst.INC_n(D); break;
case (0x15): inst.DEC_n(D); break;
case (0x16): inst.LD_nn_n(D); break;
case (0x17): inst.RL_n(A); break;
case (0x18): inst.JR(); break;
case (0x19): inst.ADD_HL_n(DE); break;
case (0x1A): inst.LD_A_n(c_DE); break;
case (0x1B): inst.DEC_nn(DE); break;
case (0x1C): inst.INC_n(E); break;
case (0x1D): inst.DEC_n(E); break;
case (0x1E): inst.LD_nn_n(E); break;
case (0x1F): inst.RR_n(A); break;
case (0x20): inst.JR_CC_n(f_Z, 0); break;
case (0x21): inst.LD_n_nn(HL); break;
case (0x22): inst.LDI_cHL_A(); break;
case (0x23): inst.INC_nn(HL); break;
case (0x24): inst.INC_n(H); break;
case (0x25): inst.DEC_n(H); break;
case (0x26): inst.LD_nn_n(H); break;
case (0x27): inst.DAA(); break;
case (0x28): inst.JR_CC_n(f_Z, 1); break;
case (0x29): inst.ADD_HL_n(HL); break;
case (0x2A): inst.LDI_A_cHL(); break;
case (0x2B): inst.DEC_nn(HL); break;
case (0x2C): inst.INC_n(L); break;
case (0x2D): inst.DEC_n(L); break;
case (0x2E): inst.LD_nn_n(L); break;
case (0x2F): inst.CPL(); break;
case (0x30): inst.JR_CC_n(f_C, 0); break;
case (0x31): inst.LD_n_nn(SP); break;
case (0x32): inst.LDD_cHL_A(); break;
case (0x33): inst.INC_nn(SP); break;
case (0x34): inst.INC_n(c_HL); break;
case (0x35): inst.DEC_n(c_HL); break;
case (0x36): inst.LD_r1_r2(c_HL, $); break;
case (0x37): inst.SCF(); break;
case (0x38): inst.JR_CC_n(f_C, 1); break;
case (0x39): inst.ADD_HL_n(SP); break;
case (0x3A): inst.LDD_A_cHL(); break;
case (0x3B): inst.DEC_nn(SP); break;
case (0x3C): inst.INC_n(A); break;
case (0x3D): inst.DEC_n(A); break;
case (0x3E): inst.LD_A_n($); break;
case (0x3F): inst.CCF(); break;
case (0x40): inst.LD_r1_r2(B, B); break;
case (0x41): inst.LD_r1_r2(B, C); break;
case (0x42): inst.LD_r1_r2(B, D); break;
case (0x43): inst.LD_r1_r2(B, E); break;
case (0x44): inst.LD_r1_r2(B, H); break;
case (0x45): inst.LD_r1_r2(B, L); break;
case (0x46): inst.LD_r1_r2(B, c_HL); break;
case (0x47): inst.LD_n_A(B); break;
case (0x48): inst.LD_r1_r2(C, B); break;
case (0x49): inst.LD_r1_r2(C, C); break;
case (0x4A): inst.LD_r1_r2(C, D); break;
case (0x4B): inst.LD_r1_r2(C, E); break;
case (0x4C): inst.LD_r1_r2(C, H); break;
case (0x4D): inst.LD_r1_r2(C, L); break;
case (0x4E): inst.LD_r1_r2(C, c_HL); break;
case (0x4F): inst.LD_n_A(C); break;
case (0x50): inst.LD_r1_r2(D, B); break;
case (0x51): inst.LD_r1_r2(D, C); break;
case (0x52): inst.LD_r1_r2(D, D); break;
case (0x53): inst.LD_r1_r2(D, E); break;
case (0x54): inst.LD_r1_r2(D, H); break;
case (0x55): inst.LD_r1_r2(D, L); break;
case (0x56): inst.LD_r1_r2(D, c_HL); break;
case (0x57): inst.LD_n_A(D); break;
case (0x58): inst.LD_r1_r2(E, B); break;
case (0x59): inst.LD_r1_r2(E, C); break;
case (0x5A): inst.LD_r1_r2(E, D); break;
case (0x5B): inst.LD_r1_r2(E, E); break;
case (0x5C): inst.LD_r1_r2(E, H); break;
case (0x5D): inst.LD_r1_r2(E, L); break;
case (0x5E): inst.LD_r1_r2(E, c_HL); break;
case (0x5F): inst.LD_n_A(E); break;
case (0x60): inst.LD_r1_r2(H, B); break;
case (0x61): inst.LD_r1_r2(H, C); break;
case (0x62): inst.LD_r1_r2(H, D); break;
case (0x63): inst.LD_r1_r2(H, E); break;
case (0x64): inst.LD_r1_r2(H, H); break;
case (0x65): inst.LD_r1_r2(H, L); break;
case (0x66): inst.LD_r1_r2(H, c_HL); break;
case (0x67): inst.LD_n_A(H); break;
case (0x68): inst.LD_r1_r2(L, B); break;
case (0x69): inst.LD_r1_r2(L, C); break;
case (0x6A): inst.LD_r1_r2(L, D); break;
case (0x6B): inst.LD_r1_r2(L, E); break;
case (0x6C): inst.LD_r1_r2(L, H); break;
case (0x6D): inst.LD_r1_r2(L, L); break;
case (0x6E): inst.LD_r1_r2(L, c_HL); break;
case (0x6F): inst.LD_n_A(L); break;
case (0x70): inst.LD_r1_r2(c_HL, B); break;
case (0x71): inst.LD_r1_r2(c_HL, C); break;
case (0x72): inst.LD_r1_r2(c_HL, D); break;
case (0x73): inst.LD_r1_r2(c_HL, E); break;
case (0x74): inst.LD_r1_r2(c_HL, H); break;
case (0x75): inst.LD_r1_r2(c_HL, L); break;
case (0x76): inst.HALT(); break;
case (0x77): inst.LD_n_A(c_HL); break;
case (0x78): inst.LD_A_n(B); break;
case (0x79): inst.LD_A_n(C); break;
case (0x7A): inst.LD_A_n(D); break;
case (0x7B): inst.LD_A_n(E); break;
case (0x7C): inst.LD_A_n(H); break;
case (0x7D): inst.LD_A_n(L); break;
case (0x7E): inst.LD_A_n(c_HL); break;
case (0x7F): inst.LD_n_A(A); break;
case (0x80): inst.ADD_A_n(B); break;
case (0x81): inst.ADD_A_n(C); break;
case (0x82): inst.ADD_A_n(D); break;
case (0x83): inst.ADD_A_n(E); break;
case (0x84): inst.ADD_A_n(H); break;
case (0x85): inst.ADD_A_n(L); break;
case (0x86): inst.ADD_A_n(c_HL); break;
case (0x87): inst.ADD_A_n(A); break;
case (0x88): inst.ADC_A_n(B); break;
case (0x89): inst.ADC_A_n(C); break;
case (0x8A): inst.ADC_A_n(D); break;
case (0x8B): inst.ADC_A_n(E); break;
case (0x8C): inst.ADC_A_n(H); break;
case (0x8D): inst.ADC_A_n(L); break;
case (0x8E): inst.ADC_A_n(c_HL); break;
case (0x8F): inst.ADC_A_n(A); break;
case (0x90): inst.SUB_n(B); break;
case (0x91): inst.SUB_n(C); break;
case (0x92): inst.SUB_n(D); break;
case (0x93): inst.SUB_n(E); break;
case (0x94): inst.SUB_n(H); break;
case (0x95): inst.SUB_n(L); break;
case (0x96): inst.SUB_n(c_HL); break;
case (0x97): inst.SUB_n(A); break;
case (0x98): inst.SBC_A(B); break;
case (0x99): inst.SBC_A(C); break;
case (0x9A): inst.SBC_A(D); break;
case (0x9B): inst.SBC_A(E); break;
case (0x9C): inst.SBC_A(H); break;
case (0x9D): inst.SBC_A(L); break;
case (0x9E): inst.SBC_A(c_HL); break;
case (0x9F): inst.SBC_A(A); break;
case (0xA0): inst.AND(B); break;
case (0xA1): inst.AND(C); break;
case (0xA2): inst.AND(D); break;
case (0xA3): inst.AND(E); break;
case (0xA4): inst.AND(H); break;
case (0xA5): inst.AND(L); break;
case (0xA6): inst.AND(c_HL); break;
case (0xA7): inst.AND(A); break;
case (0xA8): inst.XOR_n(B); break;
case (0xA9): inst.XOR_n(C); break;
case (0xAA): inst.XOR_n(D); break;
case (0xAB): inst.XOR_n(E); break;
case (0xAC): inst.XOR_n(H); break;
case (0xAD): inst.XOR_n(L); break;
case (0xAE): inst.XOR_n(c_HL); break;
case (0xAF): inst.XOR_n(A); break;
case (0xB0): inst.OR_n(B); break;
case (0xB1): inst.OR_n(C); break;
case (0xB2): inst.OR_n(D); break;
case (0xB3): inst.OR_n(E); break;
case (0xB4): inst.OR_n(H); break;
case (0xB5): inst.OR_n(L); break;
case (0xB6): inst.OR_n(c_HL); break;
case (0xB7): inst.OR_n(A); break;
case (0xB8): inst.CP_n(B); break;
case (0xB9): inst.CP_n(C); break;
case (0xBA): inst.CP_n(D); break;
case (0xBB): inst.CP_n(E); break;
case (0xBC): inst.CP_n(H); break;
case (0xBD): inst.CP_n(L); break;
case (0xBE): inst.CP_n(c_HL); break;
case (0xBF): inst.CP_n(A); break;
case (0xC0): inst.RET_cc(f_Z, 0); break;
case (0xC1): inst.POP_nn(BC); break;
case (0xC2): inst.JP_cc_nn(f_Z, 0); break;
case (0xC3): inst.JP_nn(); break;
case (0xC4): inst.CALL_cc_nn(f_Z, 0); break;
case (0xC5): inst.PUSH_nn(BC); break;
case (0xC6): inst.ADD_A_n($); break;
case (0xC7): inst.RST_n(0x00); break;
case (0xC8): inst.RET_cc(f_Z, 1); break;
case (0xC9): inst.RET(); break;
case (0xCA): inst.JP_cc_nn(f_Z, 1); break;
case (0xCB): OpCodeCB(&inst); break;
case (0xCC): inst.CALL_cc_nn(f_Z, 1); break;
case (0xCD): inst.CALL_nn(); break;
case (0xCE): inst.ADC_A_n($); break;
case (0xCF): inst.RST_n(0x08); break;
case (0xD0): inst.RET_cc(f_C, 0); break;
case (0xD1): inst.POP_nn(DE); break;
case (0xD2): inst.JP_cc_nn(f_C, 0); break;
case (0xD4): inst.CALL_cc_nn(f_C, 0); break;
case (0xD5): inst.PUSH_nn(DE); break;
case (0xD6): inst.SUB_n($); break;
case (0xD7): inst.RST_n(0x10); break;
case (0xD8): inst.RET_cc(f_C, 1); break;
case (0xD9): inst.RETI(); break;
case (0xDA): inst.JP_cc_nn(f_C, 1); break;
case (0xDC): inst.CALL_cc_nn(f_C, 1); break;
case (0xDE): inst.SBC_A($); break;
case (0xDF): inst.RST_n(0x18); break;
case (0xE0): inst.LDH_c$_A(); break;
case (0xE1): inst.POP_nn(HL); break;
case (0xE2): inst.LD_cC_A(); break;
case (0xE5): inst.PUSH_nn(HL); break;
case (0xE6): inst.AND($); break;
case (0xE7): inst.RST_n(0x20); break;
case (0xE8): inst.ADD_SP_n(); break;
case (0xE9): inst.JP_HL(); break;
case (0xEA): inst.LD_n_A(c_$$); break;
case (0xEE): inst.XOR_n($); break;
case (0xEF): inst.RST_n(0x28); break;
case (0xF0): inst.LDH_A_n(); break;
case (0xF1): inst.POP_nn(AF); break;
case (0xF2): inst.LD_A_cC(); break;
case (0xF3): inst.DI(); break;
case (0xF5): inst.PUSH_nn(AF); break;
case (0xF6): inst.OR_n($); break;
case (0xF7): inst.RST_n(0x30); break;
case (0xF8): inst.LDHL_SP_n(); break;
case (0xF9): inst.LD_SP_HL(); break;
case (0xFA): inst.LD_A_n(c_$$); break;
case (0xFB): inst.EI(); break;
case (0xFE): inst.CP_n($); break;
case (0xFF): inst.RST_n(0x38); break;
default:
stringstream out;
out << "Error, instruction not implemented: 0x";
out << setfill('0') << setw(2) << uppercase << hex << (int)OpCode << endl;
throw GBException(out.str());
}
if (OpCode == 0xCB)
lastCycles = instructionCyclesCB[NextOpcode];
else
lastCycles = instructionCycles[OpCode];
}
cyclesLCD += lastCycles;
cyclesTimer += lastCycles;
cyclesDIV += lastCycles;
actualCycles += lastCycles;
cyclesSerial += lastCycles;
UpdateStateLCD();
UpdateTimer();
UpdateSerial();
Interrupts(&inst);
}//end for
}
void CPU::OpCodeCB(Instructions * inst)
{
BYTE OpCode;
OpCode = MemR(Get_PC() + 1);
switch (OpCode)
{
case (0x00): inst->RLC_n(B); break;
case (0x01): inst->RLC_n(C); break;
case (0x02): inst->RLC_n(D); break;
case (0x03): inst->RLC_n(E); break;
case (0x04): inst->RLC_n(H); break;
case (0x05): inst->RLC_n(L); break;
case (0x06): inst->RLC_n(c_HL); break;
case (0x07): inst->RLC_n(A); break;
case (0x08): inst->RRC_n(B); break;
case (0x09): inst->RRC_n(C); break;
case (0x0A): inst->RRC_n(D); break;
case (0x0B): inst->RRC_n(E); break;
case (0x0C): inst->RRC_n(H); break;
case (0x0D): inst->RRC_n(L); break;
case (0x0E): inst->RRC_n(c_HL); break;
case (0x0F): inst->RRC_n(A); break;
case (0x10): inst->RL_n(B); break;
case (0x11): inst->RL_n(C); break;
case (0x12): inst->RL_n(D); break;
case (0x13): inst->RL_n(E); break;
case (0x14): inst->RL_n(H); break;
case (0x15): inst->RL_n(L); break;
case (0x16): inst->RL_n(c_HL); break;
case (0x17): inst->RL_n(A); break;
case (0x18): inst->RR_n(B); break;
case (0x19): inst->RR_n(C); break;
case (0x1A): inst->RR_n(D); break;
case (0x1B): inst->RR_n(E); break;
case (0x1C): inst->RR_n(H); break;
case (0x1D): inst->RR_n(L); break;
case (0x1E): inst->RR_n(c_HL); break;
case (0x1F): inst->RR_n(A); break;
case (0x20): inst->SLA_n(B); break;
case (0x21): inst->SLA_n(C); break;
case (0x22): inst->SLA_n(D); break;
case (0x23): inst->SLA_n(E); break;
case (0x24): inst->SLA_n(H); break;
case (0x25): inst->SLA_n(L); break;
case (0x26): inst->SLA_n(c_HL); break;
case (0x27): inst->SLA_n(A); break;
case (0x28): inst->SRA_n(B); break;
case (0x29): inst->SRA_n(C); break;
case (0x2A): inst->SRA_n(D); break;
case (0x2B): inst->SRA_n(E); break;
case (0x2C): inst->SRA_n(H); break;
case (0x2D): inst->SRA_n(L); break;
case (0x2E): inst->SRA_n(c_HL); break;
case (0x2F): inst->SRA_n(A); break;
case (0x30): inst->SWAP(B); break;
case (0x31): inst->SWAP(C); break;
case (0x32): inst->SWAP(D); break;
case (0x33): inst->SWAP(E); break;
case (0x34): inst->SWAP(H); break;
case (0x35): inst->SWAP(L); break;
case (0x36): inst->SWAP(c_HL); break;
case (0x37): inst->SWAP(A); break;
case (0x38): inst->SRL_n(B); break;
case (0x39): inst->SRL_n(C); break;
case (0x3A): inst->SRL_n(D); break;
case (0x3B): inst->SRL_n(E); break;
case (0x3C): inst->SRL_n(H); break;
case (0x3D): inst->SRL_n(L); break;
case (0x3E): inst->SRL_n(c_HL); break;
case (0x3F): inst->SRL_n(A); break;
case (0x40): inst->BIT_b_r(0, B); break;
case (0x41): inst->BIT_b_r(0, C); break;
case (0x42): inst->BIT_b_r(0, D); break;
case (0x43): inst->BIT_b_r(0, E); break;
case (0x44): inst->BIT_b_r(0, H); break;
case (0x45): inst->BIT_b_r(0, L); break;
case (0x46): inst->BIT_b_r(0, c_HL); break;
case (0x47): inst->BIT_b_r(0, A); break;
case (0x48): inst->BIT_b_r(1, B); break;
case (0x49): inst->BIT_b_r(1, C); break;
case (0x4A): inst->BIT_b_r(1, D); break;
case (0x4B): inst->BIT_b_r(1, E); break;
case (0x4C): inst->BIT_b_r(1, H); break;
case (0x4D): inst->BIT_b_r(1, L); break;
case (0x4E): inst->BIT_b_r(1, c_HL); break;
case (0x4F): inst->BIT_b_r(1, A); break;
case (0x50): inst->BIT_b_r(2, B); break;
case (0x51): inst->BIT_b_r(2, C); break;
case (0x52): inst->BIT_b_r(2, D); break;
case (0x53): inst->BIT_b_r(2, E); break;
case (0x54): inst->BIT_b_r(2, H); break;
case (0x55): inst->BIT_b_r(2, L); break;
case (0x56): inst->BIT_b_r(2, c_HL); break;
case (0x57): inst->BIT_b_r(2, A); break;
case (0x58): inst->BIT_b_r(3, B); break;
case (0x59): inst->BIT_b_r(3, C); break;
case (0x5A): inst->BIT_b_r(3, D); break;
case (0x5B): inst->BIT_b_r(3, E); break;
case (0x5C): inst->BIT_b_r(3, H); break;
case (0x5D): inst->BIT_b_r(3, L); break;
case (0x5E): inst->BIT_b_r(3, c_HL); break;
case (0x5F): inst->BIT_b_r(3, A); break;
case (0x60): inst->BIT_b_r(4, B); break;
case (0x61): inst->BIT_b_r(4, C); break;
case (0x62): inst->BIT_b_r(4, D); break;
case (0x63): inst->BIT_b_r(4, E); break;
case (0x64): inst->BIT_b_r(4, H); break;
case (0x65): inst->BIT_b_r(4, L); break;
case (0x66): inst->BIT_b_r(4, c_HL); break;
case (0x67): inst->BIT_b_r(4, A); break;
case (0x68): inst->BIT_b_r(5, B); break;
case (0x69): inst->BIT_b_r(5, C); break;
case (0x6A): inst->BIT_b_r(5, D); break;
case (0x6B): inst->BIT_b_r(5, E); break;
case (0x6C): inst->BIT_b_r(5, H); break;
case (0x6D): inst->BIT_b_r(5, L); break;
case (0x6E): inst->BIT_b_r(5, c_HL); break;
case (0x6F): inst->BIT_b_r(5, A); break;
case (0x70): inst->BIT_b_r(6, B); break;
case (0x71): inst->BIT_b_r(6, C); break;
case (0x72): inst->BIT_b_r(6, D); break;
case (0x73): inst->BIT_b_r(6, E); break;
case (0x74): inst->BIT_b_r(6, H); break;
case (0x75): inst->BIT_b_r(6, L); break;
case (0x76): inst->BIT_b_r(6, c_HL); break;
case (0x77): inst->BIT_b_r(6, A); break;
case (0x78): inst->BIT_b_r(7, B); break;
case (0x79): inst->BIT_b_r(7, C); break;
case (0x7A): inst->BIT_b_r(7, D); break;
case (0x7B): inst->BIT_b_r(7, E); break;
case (0x7C): inst->BIT_b_r(7, H); break;
case (0x7D): inst->BIT_b_r(7, L); break;
case (0x7E): inst->BIT_b_r(7, c_HL); break;
case (0x7F): inst->BIT_b_r(7, A); break;
case (0x80): inst->RES_b_r(0, B); break;
case (0x81): inst->RES_b_r(0, C); break;
case (0x82): inst->RES_b_r(0, D); break;
case (0x83): inst->RES_b_r(0, E); break;
case (0x84): inst->RES_b_r(0, H); break;
case (0x85): inst->RES_b_r(0, L); break;
case (0x86): inst->RES_b_r(0, c_HL); break;
case (0x87): inst->RES_b_r(0, A); break;
case (0x88): inst->RES_b_r(1, B); break;
case (0x89): inst->RES_b_r(1, C); break;
case (0x8A): inst->RES_b_r(1, D); break;
case (0x8B): inst->RES_b_r(1, E); break;
case (0x8C): inst->RES_b_r(1, H); break;
case (0x8D): inst->RES_b_r(1, L); break;
case (0x8E): inst->RES_b_r(1, c_HL); break;
case (0x8F): inst->RES_b_r(1, A); break;
case (0x90): inst->RES_b_r(2, B); break;
case (0x91): inst->RES_b_r(2, C); break;
case (0x92): inst->RES_b_r(2, D); break;
case (0x93): inst->RES_b_r(2, E); break;
case (0x94): inst->RES_b_r(2, H); break;
case (0x95): inst->RES_b_r(2, L); break;
case (0x96): inst->RES_b_r(2, c_HL); break;
case (0x97): inst->RES_b_r(2, A); break;
case (0x98): inst->RES_b_r(3, B); break;
case (0x99): inst->RES_b_r(3, C); break;
case (0x9A): inst->RES_b_r(3, D); break;
case (0x9B): inst->RES_b_r(3, E); break;
case (0x9C): inst->RES_b_r(3, H); break;
case (0x9D): inst->RES_b_r(3, L); break;
case (0x9E): inst->RES_b_r(3, c_HL); break;
case (0x9F): inst->RES_b_r(3, A); break;
case (0xA0): inst->RES_b_r(4, B); break;
case (0xA1): inst->RES_b_r(4, C); break;
case (0xA2): inst->RES_b_r(4, D); break;
case (0xA3): inst->RES_b_r(4, E); break;
case (0xA4): inst->RES_b_r(4, H); break;
case (0xA5): inst->RES_b_r(4, L); break;
case (0xA6): inst->RES_b_r(4, c_HL); break;
case (0xA7): inst->RES_b_r(4, A); break;
case (0xA8): inst->RES_b_r(5, B); break;
case (0xA9): inst->RES_b_r(5, C); break;
case (0xAA): inst->RES_b_r(5, D); break;
case (0xAB): inst->RES_b_r(5, E); break;
case (0xAC): inst->RES_b_r(5, H); break;
case (0xAD): inst->RES_b_r(5, L); break;
case (0xAE): inst->RES_b_r(5, c_HL); break;
case (0xAF): inst->RES_b_r(5, A); break;
case (0xB0): inst->RES_b_r(6, B); break;
case (0xB1): inst->RES_b_r(6, C); break;
case (0xB2): inst->RES_b_r(6, D); break;
case (0xB3): inst->RES_b_r(6, E); break;
case (0xB4): inst->RES_b_r(6, H); break;
case (0xB5): inst->RES_b_r(6, L); break;
case (0xB6): inst->RES_b_r(6, c_HL); break;
case (0xB7): inst->RES_b_r(6, A); break;
case (0xB8): inst->RES_b_r(7, B); break;
case (0xB9): inst->RES_b_r(7, C); break;
case (0xBA): inst->RES_b_r(7, D); break;
case (0xBB): inst->RES_b_r(7, E); break;
case (0xBC): inst->RES_b_r(7, H); break;
case (0xBD): inst->RES_b_r(7, L); break;
case (0xBE): inst->RES_b_r(7, c_HL); break;
case (0xBF): inst->RES_b_r(7, A); break;
case (0xC0): inst->SET_b_r(0, B); break;
case (0xC1): inst->SET_b_r(0, C); break;
case (0xC2): inst->SET_b_r(0, D); break;
case (0xC3): inst->SET_b_r(0, E); break;
case (0xC4): inst->SET_b_r(0, H); break;
case (0xC5): inst->SET_b_r(0, L); break;
case (0xC6): inst->SET_b_r(0, c_HL); break;
case (0xC7): inst->SET_b_r(0, A); break;
case (0xC8): inst->SET_b_r(1, B); break;
case (0xC9): inst->SET_b_r(1, C); break;
case (0xCA): inst->SET_b_r(1, D); break;
case (0xCB): inst->SET_b_r(1, E); break;
case (0xCC): inst->SET_b_r(1, H); break;
case (0xCD): inst->SET_b_r(1, L); break;
case (0xCE): inst->SET_b_r(1, c_HL); break;
case (0xCF): inst->SET_b_r(1, A); break;
case (0xD0): inst->SET_b_r(2, B); break;
case (0xD1): inst->SET_b_r(2, C); break;
case (0xD2): inst->SET_b_r(2, D); break;
case (0xD3): inst->SET_b_r(2, E); break;
case (0xD4): inst->SET_b_r(2, H); break;
case (0xD5): inst->SET_b_r(2, L); break;
case (0xD6): inst->SET_b_r(2, c_HL); break;
case (0xD7): inst->SET_b_r(2, A); break;
case (0xD8): inst->SET_b_r(3, B); break;
case (0xD9): inst->SET_b_r(3, C); break;
case (0xDA): inst->SET_b_r(3, D); break;
case (0xDB): inst->SET_b_r(3, E); break;
case (0xDC): inst->SET_b_r(3, H); break;
case (0xDD): inst->SET_b_r(3, L); break;
case (0xDE): inst->SET_b_r(3, c_HL); break;
case (0xDF): inst->SET_b_r(3, A); break;
case (0xE0): inst->SET_b_r(4, B); break;
case (0xE1): inst->SET_b_r(4, C); break;
case (0xE2): inst->SET_b_r(4, D); break;
case (0xE3): inst->SET_b_r(4, E); break;
case (0xE4): inst->SET_b_r(4, H); break;
case (0xE5): inst->SET_b_r(4, L); break;
case (0xE6): inst->SET_b_r(4, c_HL); break;
case (0xE7): inst->SET_b_r(4, A); break;
case (0xE8): inst->SET_b_r(5, B); break;
case (0xE9): inst->SET_b_r(5, C); break;
case (0xEA): inst->SET_b_r(5, D); break;
case (0xEB): inst->SET_b_r(5, E); break;
case (0xEC): inst->SET_b_r(5, H); break;
case (0xED): inst->SET_b_r(5, L); break;
case (0xEE): inst->SET_b_r(5, c_HL); break;
case (0xEF): inst->SET_b_r(5, A); break;
case (0xF0): inst->SET_b_r(6, B); break;
case (0xF1): inst->SET_b_r(6, C); break;
case (0xF2): inst->SET_b_r(6, D); break;
case (0xF3): inst->SET_b_r(6, E); break;
case (0xF4): inst->SET_b_r(6, H); break;
case (0xF5): inst->SET_b_r(6, L); break;
case (0xF6): inst->SET_b_r(6, c_HL); break;
case (0xF7): inst->SET_b_r(6, A); break;
case (0xF8): inst->SET_b_r(7, B); break;
case (0xF9): inst->SET_b_r(7, C); break;
case (0xFA): inst->SET_b_r(7, D); break;
case (0xFB): inst->SET_b_r(7, E); break;
case (0xFC): inst->SET_b_r(7, H); break;
case (0xFD): inst->SET_b_r(7, L); break;
case (0xFE): inst->SET_b_r(7, c_HL); break;
case (0xFF): inst->SET_b_r(7, A); break;
default:
stringstream out;
out << "Error, instruction not implemented: 0xCB";
out << setfill('0') << setw(2) << uppercase << hex << (int)OpCode << "\n";
throw GBException(out.str().data());
}
}
void CPU::FillInstructionCycles()
{
for (int i=0; i<0x100; i++)
instructionCycles[i] = 4;
instructionCycles[0x01] = 12;
instructionCycles[0x02] = 8;
instructionCycles[0x03] = 8;
instructionCycles[0x06] = 8;
instructionCycles[0x08] = 20;
instructionCycles[0x09] = 8;
instructionCycles[0x0A] = 8;
instructionCycles[0x0B] = 8;
instructionCycles[0x0E] = 8;
instructionCycles[0x11] = 12;
instructionCycles[0x12] = 8;
instructionCycles[0x13] = 8;
instructionCycles[0x16] = 8;
instructionCycles[0x18] = 8;
instructionCycles[0x19] = 8;
instructionCycles[0x1A] = 8;
instructionCycles[0x1B] = 8;
instructionCycles[0x1E] = 8;
instructionCycles[0x20] = 8;
instructionCycles[0x21] = 12;
instructionCycles[0x22] = 8;
instructionCycles[0x23] = 8;
instructionCycles[0x26] = 8;
instructionCycles[0x28] = 8;
instructionCycles[0x29] = 8;
instructionCycles[0x2A] = 8;
instructionCycles[0x2B] = 8;
instructionCycles[0x2E] = 8;
instructionCycles[0x30] = 8;
instructionCycles[0x31] = 12;
instructionCycles[0x32] = 8;
instructionCycles[0x33] = 8;
instructionCycles[0x34] = 12;
instructionCycles[0x35] = 12;
instructionCycles[0x36] = 12;
instructionCycles[0x38] = 8;
instructionCycles[0x39] = 8;
instructionCycles[0x3A] = 8;
instructionCycles[0x3B] = 8;
instructionCycles[0x3E] = 8;
instructionCycles[0x46] = 8;
instructionCycles[0x4E] = 8;
instructionCycles[0x56] = 8;
instructionCycles[0x5E] = 8;
instructionCycles[0x66] = 8;
instructionCycles[0x70] = 8;
instructionCycles[0x71] = 8;
instructionCycles[0x72] = 8;
instructionCycles[0x73] = 8;
instructionCycles[0x74] = 8;
instructionCycles[0x77] = 8;
instructionCycles[0x7E] = 8;
instructionCycles[0x86] = 8;
instructionCycles[0x8E] = 8;
instructionCycles[0x96] = 8;
instructionCycles[0x9E] = 8;
instructionCycles[0xA6] = 8;
instructionCycles[0xAE] = 8;
instructionCycles[0xB6] = 8;
instructionCycles[0xDE] = 8;
instructionCycles[0xC0] = 8;
instructionCycles[0xC1] = 12;
instructionCycles[0xC2] = 12;
instructionCycles[0xC3] = 12;
instructionCycles[0xC4] = 12;
instructionCycles[0xC5] = 16;
instructionCycles[0xC6] = 8;
instructionCycles[0xC7] = 32;
instructionCycles[0xC8] = 8;
instructionCycles[0xC9] = 8;
instructionCycles[0xCA] = 12;
instructionCycles[0xCC] = 12;
instructionCycles[0xCD] = 12;
instructionCycles[0xCE] = 8;
instructionCycles[0xCF] = 32;
instructionCycles[0xD0] = 8;
instructionCycles[0xD1] = 12;
instructionCycles[0xD2] = 12;
instructionCycles[0xD4] = 12;
instructionCycles[0xD5] = 16;
instructionCycles[0xD6] = 8;
instructionCycles[0xD7] = 32;
instructionCycles[0xD8] = 8;
instructionCycles[0xD9] = 8;
instructionCycles[0xDA] = 12;
instructionCycles[0xDC] = 12;
instructionCycles[0xDF] = 32;
instructionCycles[0xE0] = 12;
instructionCycles[0xE1] = 12;
instructionCycles[0xE2] = 8;
instructionCycles[0xE5] = 16;
instructionCycles[0xE6] = 8;
instructionCycles[0xE7] = 32;
instructionCycles[0xE8] = 16;
instructionCycles[0xEA] = 16;
instructionCycles[0xEE] = 8;
instructionCycles[0xEF] = 32;
instructionCycles[0xF0] = 12;
instructionCycles[0xF1] = 12;
instructionCycles[0xF2] = 8;
instructionCycles[0xF5] = 16;
instructionCycles[0xF6] = 8;
instructionCycles[0xF7] = 32;
instructionCycles[0xF8] = 12;
instructionCycles[0xF9] = 8;
instructionCycles[0xFA] = 16;
instructionCycles[0xFE] = 8;
instructionCycles[0xFF] = 32;
}
void CPU::FillInstructionCyclesCB()
{
for (int i=0; i<0x100; i++)
instructionCyclesCB[i] = 8;
instructionCyclesCB[0x06] = 16;
instructionCyclesCB[0x0E] = 16;
instructionCyclesCB[0x16] = 16;
instructionCyclesCB[0x1E] = 16;
instructionCyclesCB[0x26] = 16;
instructionCyclesCB[0x2E] = 16;
instructionCyclesCB[0x36] = 16;
instructionCyclesCB[0x3E] = 16;
instructionCyclesCB[0x46] = 12; //16?
instructionCyclesCB[0x4E] = 12; //16?
instructionCyclesCB[0x56] = 12; //16?
instructionCyclesCB[0x5E] = 12; //16?
instructionCyclesCB[0x66] = 12; //16?
instructionCyclesCB[0x6E] = 12; //16?
instructionCyclesCB[0x76] = 12; //16?
instructionCyclesCB[0x7E] = 12; //16?
instructionCyclesCB[0x86] = 16;
instructionCyclesCB[0x8E] = 16;
instructionCyclesCB[0x96] = 16;
instructionCyclesCB[0x9E] = 16;
instructionCyclesCB[0xA6] = 16;
instructionCyclesCB[0xAE] = 16;
instructionCyclesCB[0xB6] = 16;
instructionCyclesCB[0xBE] = 16;
instructionCyclesCB[0xC6] = 16;
instructionCyclesCB[0xCE] = 16;
instructionCyclesCB[0xD6] = 16;
instructionCyclesCB[0xDE] = 16;
instructionCyclesCB[0xE6] = 16;
instructionCyclesCB[0xEE] = 16;
instructionCyclesCB[0xF6] = 16;
instructionCyclesCB[0xFE] = 16;
}
void CPU::UpdatePad()
{
int interrupt = PadCheckKeyboard(&memory[P1]);
if (interrupt)
memory[IF] |= 0x10;
}
void CPU::UpdateStateLCD()
{
BYTE screenOn = BIT7(memory[LCDC]);
BYTE mode = BITS01(memory[STAT]);
switch (mode)
{
case (0): // Durante H-Blank
if (cyclesLCD >= MAX_LCD_MODE_0)
{
if (memory[LY] == 144) // Si estamos en la linea 144, cambiamos al modo 1 (V-Blank)
{
// Poner a 01 el flag (bits 0-1) del modo 1.
memory[STAT] = (memory[STAT] & ~0x03) | 0x01;
if (screenOn)
{
// Interrupcion V-Blank
memory[IF] |= 0x01;
// Si interrupcion V-Blank habilitada, marcar peticion de interrupcion
// en 0xFF0F. Bit 1, flag de interrupcion de LCD STAT.
if (BIT4(memory[STAT]))
memory[IF] |= 0x02;
}
}
else // Sino, cambiamos al modo 2
{
// Poner a 10 el flag (bits 0-1) del modo 2.
memory[STAT] = (memory[STAT] & ~0x03) | 0x02;
// Si interrupcion OAM habilitada, marcar peticion de interrupcion
// en 0xFF0F. Bit 1, flag de interrupcion de LCD STAT
if (BIT5(memory[STAT]) && screenOn)
memory[IF] |= 0x02;
v->UpdateLine(memory[LY]);
}
memory[LY]++;
CheckLYC();
cyclesLCD -= MAX_LCD_MODE_0;
}
break;
case (1): // Durante V-Blank
if (cyclesLCD >= MAX_LCD_MODE_1)
{
// Si hemos llegado al final
if (memory[LY] == 153)
{
memory[LY] = 0;
// Poner a 10 el flag (bits 0-1) del modo 2.
memory[STAT] = (memory[STAT] & ~0x03) | 0x02;
// Si interrupcion OAM habilitada, marcar peticion de interrupcion
// en 0xFF0F. Bit 1, flag de interrupcion de LCD STAT
if (BIT5(memory[STAT]) && screenOn)
memory[IF] |= 0x02;
OnEndFrame();
}
else
memory[LY]++;
CheckLYC();
cyclesLCD -= MAX_LCD_MODE_1;
}
break;
case (2): // Cuando OAM se esta usando
if (cyclesLCD >= MAX_LCD_MODE_2)
{
// Poner a 11 el flag (bits 0-1) del modo 3.
memory[STAT] = (memory[STAT] & ~0x03) | 0x03;
cyclesLCD -= MAX_LCD_MODE_2;
}
break;
case (3): // Cuando OAM y memoria de video se estan usando (Se esta pasando informacion al LCD)
if (cyclesLCD >= MAX_LCD_MODE_3)
{
// Poner a 00 el flag (bits 0-1) del modo 0.
memory[STAT] &= ~0x03;
// Si interrupcion H-Blank habilitada, marcar peticion de interrupcion
// en 0xFF0F. Bit 1, flag de interrupcion de LCD STAT
if (BIT3(memory[STAT]) && screenOn)
memory[IF] |= 0x02;
cyclesLCD -= MAX_LCD_MODE_3;
}
break;
}
}
inline void CPU::CheckLYC()
{
if (memory[LY] == memory[LYC])
{
memory[STAT] |= 0x04;
if (BIT6(memory[STAT]))
memory[IF] |= 0x02;
}
else
memory[STAT] &= ~0x04;
}
inline void CPU::UpdateSerial()
{
if (BIT7(memory[SC]) && BIT0(memory[SC]))
{
if (bitSerial < 0)
{
bitSerial = 0;
cyclesSerial = 0;
return;
}
if (cyclesSerial >= 512)
{
if (bitSerial > 7)
{
memory[SC] &= 0x7F;
memory[IF] |= 0x08;
bitSerial = -1;
return;
}
memory[SB] = memory[SB] << 1;
memory[SB] |= 0x01;
cyclesSerial -= 512;
bitSerial++;
}
}
}
void CPU::Interrupts(Instructions * inst)
{
if (!Get_IME())
return;
BYTE interrupts = memory[IE] & memory[IF];
if (!interrupts)
return;
Set_IME(false);
Set_Halt(false);
inst->PUSH_PC();
if (BIT0(interrupts)) //V-Blank
{
Set_PC(0x40);
memory[IF] &= ~0x01;
}
else if (BIT1(interrupts)) //LCD-Stat
{
Set_PC(0x48);
memory[IF] &= ~0x02;
}
else if (BIT2(interrupts)) //Timer
{
Set_PC(0x50);
memory[IF] &= ~0x04;
}
else if(BIT3(interrupts)) //Serial
{
Set_PC(0x58);
memory[IF] &= ~0x08;
}
else if (BIT4(interrupts)) //Joypad
{
Set_PC(0x60);
memory[IF] &= ~0x10;
}
}
void CPU::UpdateTimer()
{
// Estos serian los valores en Hz que puede tomar TAC:
// 4096, 262144, 65536, 16384
// En overflowTimer se encuentran estos valores en ciclos
// maquina
WORD overflowTimer[] = {1024, 16, 64, 256};
if (BIT2(memory[TAC])) //Si esta habilitado el timer
{
if (cyclesTimer >= overflowTimer[BITS01(memory[TAC])])
{
if (memory[TIMA] == 0xFF)
{
memory[TIMA] = memory[TMA];
memory[IF] |= 0x04;
}
else
memory[TIMA]++;
cyclesTimer = 0;
}
}
else
cyclesTimer = 0;
if (cyclesDIV >= 256)
{
memory[DIV]++;
cyclesDIV = 0;
}
}
void CPU::OnEndFrame()
{
v->RefreshScreen();
if (s)
s->EndFrame();
frameCompleted = true;
}
void CPU::SaveLog()
{
log->Save("log.txt");
}
void CPU::SaveState(string saveDirectory, int numSlot)
{
if (c == NULL)
{
throw GBException("There is not rom loaded. The process can't continue.");
}
stringstream st;
st << saveDirectory << c->GetName().c_str();
st << "-" << numSlot << ".sav";
string fileName = st.str();
ofstream * file = new ofstream(fileName.c_str(), ios::out|ios::binary|ios::trunc);
if (file && file->is_open())
{
int version = SAVE_STATE_VERSION;
file->write((char *)&version, sizeof(int));
file->write(c->GetName().c_str(), 16);
SaveRegs(file);
SaveMemory(file);
c->SaveMBC(file);
file->close();
}
if (file)
delete file;
}
void CPU::LoadState(string loadDirectory, int numSlot)
{
if (c == NULL)
{
throw GBException("There is not rom loaded. The process can't continue.");
}
stringstream st;
st << loadDirectory << c->GetName().c_str();
st << "-" << numSlot << ".sav";
string fileName = st.str();
ifstream * file = new ifstream(fileName.c_str(), ios::in|ios::binary);
if (file && file->is_open())
{
int version = 0;
file->read((char *)&version, sizeof(int));
if (version != SAVE_STATE_VERSION)
{
file->close();
delete file;
throw GBException("This filesave is not compatible and can't be loaded.");
}
char * buffer = new char[16];
file->read(buffer, 16);
string cartName = string(buffer, 16);
delete[] buffer;
if (cartName != c->GetName())
{
file->close();
delete file;
throw GBException("This filesave does not correspond to this rom and can't be loaded.");
}
LoadRegs(file);
LoadMemory(file);
c->LoadMBC(file);
file->close();
delete file;
}
else
{
if (file)
delete file;
throw GBException("Unable to open the filesave.");
}
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __SETTINGS_H__
#define __SETTINGS_H__
#include <string>
class Settings
{
public:
bool greenScale;
int windowZoom;
bool soundEnabled;
int soundSampleRate;
int padKeys[8];
std::string recentRoms[10];
public:
Settings();
};
Settings SettingsGetCopy();
bool SettingsGetGreenScale();
int SettingsGetWindowZoom();
bool SettingsGetSoundEnabled();
int SettingsGetSoundSampleRate();
int* SettingsGetInput();
std::string* SettingsGetRecentRoms();
void SettingsSetNewValues(Settings newSettings);
void SettingsSetGreenScale(bool greenScale);
void SettingsSetWindowZoom(int windowZoom);
void SettingsSetSoundEnabled(bool enabled);
void SettingsSetSoundSampleRate(int sampleRate);
void SettingsSetInput(const int* padKeys);
void SettingsSetRecentRoms(const std::string* recentRoms);
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GBException.h"
using namespace std;
GBException::GBException(): exception()
{
newException("", GBUnknown);
}
GBException::GBException(string description): exception()
{
newException(description, GBUnknown);
}
GBException::GBException(string description, ExceptionType type): exception()
{
newException(description, type);
}
GBException::~GBException() throw()
{
}
ExceptionType GBException::GetType()
{
return type;
}
void GBException::newException(string description, ExceptionType type)
{
this->description = description;
this->type = type;
}
const char * GBException::what() const throw()
{
return description.c_str();
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __INSTRUCCIONES_H__
#define __INSTRUCCIONES_H__
#include "Registers.h"
#include "Memory.h"
class Instructions
{
private:
Registers *reg;
Memory *mem;
public:
Instructions(Registers *reg, Memory *mem);
~Instructions(void);
void ADC_A_n(e_registers place);
void ADD_A_n(e_registers place);
void ADD_HL_n(e_registers place);
void ADD_SP_n();
void AND(e_registers place);
void BIT_b_r(BYTE bit, e_registers place);
void CALL_nn();
void CALL_cc_nn(e_registers flag, BYTE value2check);
void CCF();
void CP_n(e_registers place);
void CPL();
void DAA();
void DEC_n(e_registers place);
void DEC_nn(e_registers place);
void DI();
void EI();
void HALT();
void INC_n(e_registers place);
void INC_nn(e_registers place);
void JP_nn();
void JP_cc_nn(e_registers flag, BYTE value2check);
void JP_HL();
void JR();
void JR_CC_n(e_registers flag, BYTE value2check);
void LDD_A_cHL();
void LDD_cHL_A();
void LDH_c$_A();
void LDH_A_n();
void LDHL_SP_n();
void LDI_A_cHL();
void LDI_cHL_A();
void LD_n_A(e_registers place);
void LD_n_nn(e_registers place);
void LD_nn_n(e_registers place);
void LD_A_n(e_registers place);
void LD_A_cC();
void LD_cC_A();
void LD_nn_SP();
void LD_r1_r2(e_registers e_reg1, e_registers e_reg2);
void LD_SP_HL();
void NOP();
void OR_n(e_registers place);
void POP_nn(e_registers place);
void PUSH_nn(e_registers place);
void PUSH_PC();
void RES_b_r(BYTE bit, e_registers place);
void RET();
void RETI();
void RET_cc(e_registers flag, BYTE value2check);
void RL_n(e_registers place);
//void RLA();
void RLCA();
void RLC_n(e_registers place);
void RR_n(e_registers place);
void RRC_n(e_registers place);
//void RRCA();
void RST_n(BYTE desp);
void SBC_A(e_registers place);
void SET_b_r(BYTE bit, e_registers place);
void SCF();
void SLA_n(e_registers place);
void SRA_n(e_registers place);
void SRL_n(e_registers place);
void STOP();
void SUB_n(e_registers place);
void SWAP(e_registers place);
void XOR_n(e_registers place);
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "Video.h"
using namespace std;
Video::Video(IGBScreenDrawable * screen)
{
this->pixel = new VideoPixel();
this->screen = screen;
}
Video::~Video(void)
{
}
void Video::SetMem(Memory *mem)
{
this->mem = mem;
}
void Video::UpdateLine(BYTE y)
{
screen->OnPreDraw();
OrderOAM(y);
UpdateBG(y);
UpdateWin(y);
UpdateOAM(y);
screen->OnPostDraw();
}
void Video::RefreshScreen()
{
screen->OnRefreshScreen();
}
void Video::ClearScreen()
{
screen->OnClear();
}
void Video::UpdateBG(int y)
{
int x, yScrolled;
BYTE valueLCDC, valueSCX;
bool display;
valueLCDC = mem->memory[LCDC];
valueSCX = mem->memory[SCX];
display = BIT7(valueLCDC) && BIT0(valueLCDC);
//Si el LCD o Background desactivado
//pintamos la linea de blanco
if (!display)
{
for (x=0; x<GB_SCREEN_W; x++)
screen->OnDrawPixel(3, x, y);
return;
}
//Seleccionar el tile map
pixel->mapIni = BIT3(valueLCDC) ? 0x9C00 : 0x9800;
GetPalette(pixel->palette, BGP);
yScrolled = (y + mem->memory[SCY]);
if (yScrolled < 0)
yScrolled += 256;
else if (yScrolled > 255)
yScrolled -= 256;
pixel->yTile = yScrolled % 8;
pixel->rowMap = (yScrolled/8 * 32);
pixel->tileDataSelect = BIT4(valueLCDC);
for (x=0; x<GB_SCREEN_W; x++)
{
pixel->x = x;
pixel->xScrolled = (x + valueSCX);
if (pixel->xScrolled > 255)
pixel->xScrolled -= 256;
GetColor(pixel);
screen->OnDrawPixel(pixel->color, x, y);
indexColorsBGWnd[x][y] = pixel->indexColor;
}
}
void Video::UpdateWin(int y)
{
int x, wndPosX, xIni, yScrolled;
WORD wndPosY;
//Si la ventana esta desactivada no hacemos nada
if (!BIT5(mem->memory[LCDC]))
return;
wndPosX = mem->memory[WX] - 7;
wndPosY = mem->memory[WY];
if (y < wndPosY)
return;
if (wndPosX < 0) xIni = 0;
else if (wndPosX > GB_SCREEN_W) xIni = GB_SCREEN_W;
else xIni = wndPosX;
GetPalette(pixel->palette, BGP);
pixel->mapIni = BIT6(mem->memory[LCDC]) ? 0x9C00 : 0x9800;
yScrolled = y - wndPosY;
pixel->yTile = yScrolled % 8;
pixel->rowMap = yScrolled/8 * 32;
pixel->tileDataSelect = BIT4(mem->memory[LCDC]);
pixel->y = y;
for (x=xIni; x<GB_SCREEN_W; x++)
{
pixel->x = x;
pixel->xScrolled = x - wndPosX;
GetColor(pixel);
screen->OnDrawPixel(pixel->color, x, y);
indexColorsBGWnd[x][y] = pixel->indexColor;
}
}
inline void Video::GetColor(VideoPixel * p)
{
BYTE xTile, line[2];
WORD idTile, dirTile;
idTile = p->mapIni + (p->rowMap + p->xScrolled/8);
if (!p->tileDataSelect) //Seleccionar el tile data
{
//0x8800 = 0x9000 - (128 * 16)
dirTile = (WORD)(0x9000 + ((char)mem->memory[idTile])*16); //Se multiplica por 16 porque cada tile ocupa 16 bytes
}
else
{
dirTile = 0x8000 + mem->memory[idTile]*16;
}
xTile = p->xScrolled % 8;
line[0] = mem->memory[dirTile + (p->yTile * 2)]; //yTile * 2 porque cada linea de 1 tile ocupa 2 bytes
line[1] = mem->memory[dirTile + (p->yTile * 2) + 1];
BYTE pixX = (BYTE)abs((int)xTile - 7);
//Un pixel lo componen 2 bits. Seleccionar la posicion del bit en los dos bytes (line[0] y line[1])
//Esto devolvera un numero de color que junto a la paleta de color nos dara el color requerido
p->indexColor = (((line[1] & (0x01 << pixX)) >> pixX) << 1) | ((line[0] & (0x01 << pixX)) >> pixX);
p->color = p->palette[p->indexColor];
}
void Video::OrderOAM(int y)
{
int ySprite, hSprite, dir;
orderedOAM.clear();
if (!BIT1(mem->memory[LCDC])) //OAM desactivado
return;
hSprite = BIT2(mem->memory[LCDC]) ? 16 : 8;
for(dir=0xFE00; dir<0xFEA0; dir+=0x04)
{
ySprite = mem->memory[dir];
ySprite -= 16; //y en pantalla
if ((ySprite > y-hSprite) && (ySprite <= y))
orderedOAM.insert(pair<int, int>(mem->memory[dir+1], dir));
}
}
void Video::UpdateOAM(int y)
{
int x, xSprite, numSpritesLine, xBeg;
int attrSprite, xTile, yTile, xFlip, yFlip, countX, countY, behind, mode16, ySprite;
WORD dirSprite, tileNumber, dirTile;
int color;
int palette0[4], palette1[4];
BYTE line[2];
if (!BIT1(mem->memory[LCDC])) //OAM desactivado
return;
mode16 = BIT2(mem->memory[LCDC]);
GetPalette(palette0, OBP0);
GetPalette(palette1, OBP1);
multimap<int, int>::iterator it;
numSpritesLine = 0;
for (it=orderedOAM.begin(); (it != orderedOAM.end()) && (numSpritesLine < 10); it++)
{
numSpritesLine++;
dirSprite = (*it).second;
ySprite = mem->memory[dirSprite] - 16; //=mem->MemR(dirSprite + 0);
xSprite = (*it).first - 8; //=mem->MemR(dirSprite + 1);
if (xSprite == -8)
continue;
tileNumber = mem->memory[dirSprite + 2];
if (mode16)
tileNumber = tileNumber & 0xFE;
//!!!!!!!!!Si toca la parte de abajo del tile de 8x16 hay que sumar uno (tileNumber | 0x01)
attrSprite = mem->memory[dirSprite + 3];
dirTile = 0x8000 + tileNumber*16;
xFlip = BIT5(attrSprite);
yFlip = BIT6(attrSprite);
behind = BIT7(attrSprite);
xTile = countX = countY = 0;
yTile = y - ySprite;
countY = yTile;
if (yFlip)
yTile = abs(yTile - (mode16 ? 15 : 7));
if (xSprite>0)
{
xBeg = xSprite;
countX = 0;
}
else
{
xBeg = 0;
countX = abs(xSprite);
}
for (x=xBeg; ((x<xSprite+8) && (x<GB_SCREEN_W)); x++)
{
xTile = xFlip ? abs(countX - 7) : countX;
line[0] = mem->memory[dirTile + (yTile * 2)]; //yTile * 2 porque cada linea de 1 tile ocupa 2 bytes
line[1] = mem->memory[dirTile + (yTile * 2) + 1];
int pixX = abs((int)xTile - 7);
//Un pixel lo componen 2 bits. Seleccionar la posicion del bit en los dos bytes (line[0] y line[1])
//Esto devolvera un numero de color que junto a la paleta de color nos dara el color requerido
BYTE index = (((line[1] & (0x01 << pixX)) >> pixX) << 1) | ((line[0] & (0x01 << pixX)) >> pixX);
//El 0 es transparente (no pintar)
if ((index) && ((!behind) || (!indexColorsBGWnd[xSprite + countX][ySprite + countY])))
{
//color = !BIT4(attrSprite) ? palette0[index] : palette1[index];
if (!BIT4(attrSprite))
color = palette0[index];
else
color = palette1[index];
screen->OnDrawPixel(color, xSprite + countX, ySprite + countY);
}
countX++;
}
}
}
void Video::GetPalette(int * palette, int dir)
{
BYTE paletteData = mem->memory[dir];
palette[0] = abs((int)(BITS01(paletteData) - 3));
palette[1] = abs((int)((BITS23(paletteData) >> 2) - 3));
palette[2] = abs((int)((BITS45(paletteData) >> 4) - 3));
palette[3] = abs((int)((BITS67(paletteData) >> 6) - 3));
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __VIDEO_H__
#define __VIDEO_H__
#include "map"
#include "Def.h"
#include "Memory.h"
#include "IGBScreenDrawable.h"
struct VideoPixel
{
int x, y;
int rowMap, tileDataSelect;
int color, indexColor, xScrolled;
int palette[4];
WORD mapIni;
BYTE yTile;
};
class Video
{
private:
Memory *mem;
std::multimap<int, int> orderedOAM; //posicion x, dir. memoria
int indexColorsBGWnd[GB_SCREEN_W][GB_SCREEN_H]; //Indice de color en pantalla pintadas por background y window
IGBScreenDrawable * screen;
VideoPixel * pixel;
public:
Video(IGBScreenDrawable * screen);
~Video(void);
void SetMem(Memory *mem);
void RefreshScreen();
void ClearScreen();
void UpdateLine(BYTE line);
private:
void UpdateBG(int line);
void UpdateWin(int line);
void OrderOAM(int line);
void UpdateOAM(int line);
inline void GetColor(VideoPixel * p);
void GetPalette(int * palette, int dir);
};
#endif
| C++ |
// Simplified Nintendo Game Boy PAPU sound chip emulator
// Gb_Snd_Emu 0.1.4. Copyright (C) 2003-2005 Shay Green. GNU LGPL license.
#ifndef BASIC_GB_APU_H
#define BASIC_GB_APU_H
#include "gb_apu/Gb_Apu.h"
#include "gb_apu/Multi_Buffer.h"
class Basic_Gb_Apu {
public:
Basic_Gb_Apu();
~Basic_Gb_Apu();
// Set output sample rate
blargg_err_t set_sample_rate( long rate );
// Pass reads and writes in the range 0xff10-0xff3f
void write_register( gb_addr_t, int data );
int read_register( gb_addr_t );
// End a 1/60 sound frame and add samples to buffer
void end_frame();
// Samples are generated in stereo, left first. Sample counts are always
// a multiple of 2.
// Number of samples in buffer
long samples_avail() const;
// Read at most 'count' samples out of buffer and return number actually read
typedef blip_sample_t sample_t;
long read_samples( sample_t* out, long count );
private:
Gb_Apu apu;
Stereo_Buffer buf;
blip_time_t time;
// faked CPU timing
blip_time_t clock() { return time += 4; }
};
#endif
| C++ |
// Gb_Snd_Emu 0.1.4. http://www.slack.net/~ant/libs/
#include "Wave_Writer.h"
#include <assert.h>
#include <stdlib.h>
/* Copyright (C) 2003-2005 by Shay Green. Permission is hereby granted, free
of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the
following conditions: The above copyright notice and this permission notice
shall be included in all copies or substantial portions of the Software. THE
SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
const int header_size = 0x2C;
static void exit_with_error( const char* str ) {
fprintf( stderr, "Error: %s\n", str );
exit( EXIT_FAILURE );
}
Wave_Writer::Wave_Writer( long sample_rate, const char* filename )
{
sample_count_ = 0;
rate = sample_rate;
buf_pos = header_size;
stereo( 0 );
buf = new unsigned char [buf_size];
if ( !buf )
exit_with_error( "Out of memory" );
file = fopen( filename, "wb" );
if ( !file )
exit_with_error( "Couldn't open WAVE file for writing" );
}
void Wave_Writer::flush()
{
if ( buf_pos && !fwrite( buf, buf_pos, 1, file ) )
exit_with_error( "Couldn't write WAVE data" );
buf_pos = 0;
}
void Wave_Writer::write( const sample_t* in, long remain, int skip )
{
sample_count_ += remain;
while ( remain )
{
if ( buf_pos >= buf_size )
flush();
long n = (unsigned long) (buf_size - buf_pos) / sizeof (sample_t);
if ( n > remain )
n = remain;
remain -= n;
// convert to lsb first format
unsigned char* p = &buf [buf_pos];
while ( n-- )
{
int s = *in;
in += skip;
*p++ = (unsigned char) s;
*p++ = (unsigned char) (s >> 8);
}
buf_pos = p - buf;
assert( buf_pos <= buf_size );
}
}
void Wave_Writer::write( const float* in, long remain, int skip )
{
sample_count_ += remain;
while ( remain )
{
if ( buf_pos >= buf_size )
flush();
long n = (unsigned long) (buf_size - buf_pos) / sizeof (sample_t);
if ( n > remain )
n = remain;
remain -= n;
// convert to lsb first format
unsigned char* p = &buf [buf_pos];
while ( n-- )
{
long s = *in * 0x7fff;
in += skip;
if ( (short) s != s )
s = 0x7fff - (s >> 24); // clamp to 16 bits
*p++ = (unsigned char) s;
*p++ = (unsigned char) (s >> 8);
}
buf_pos = p - buf;
assert( buf_pos <= buf_size );
}
}
Wave_Writer::~Wave_Writer()
{
flush();
// generate header
long ds = sample_count_ * sizeof (sample_t);
long rs = header_size - 8 + ds;
int frame_size = chan_count * sizeof (sample_t);
long bps = rate * frame_size;
unsigned char header [header_size] = {
'R','I','F','F',
rs,rs>>8, // length of rest of file
rs>>16,rs>>24,
'W','A','V','E',
'f','m','t',' ',
0x10,0,0,0, // size of fmt chunk
1,0, // uncompressed format
chan_count,0, // channel count
rate,rate >> 8, // sample rate
rate>>16,rate>>24,
bps,bps>>8, // bytes per second
bps>>16,bps>>24,
frame_size,0, // bytes per sample frame
16,0, // bits per sample
'd','a','t','a',
ds,ds>>8,ds>>16,ds>>24// size of sample data
// ... // sample data
};
// write header
fseek( file, 0, SEEK_SET );
fwrite( header, sizeof header, 1, file );
fclose( file );
delete [] buf;
}
| C++ |
// Nintendo Game Boy PAPU sound chip emulator
// Gb_Snd_Emu 0.1.4. Copyright (C) 2003-2005 Shay Green. GNU LGPL license.
#ifndef GB_APU_H
#define GB_APU_H
typedef long gb_time_t; // clock cycle count
typedef unsigned gb_addr_t; // 16-bit address
#include "Gb_Oscs.h"
class Gb_Apu {
public:
Gb_Apu();
~Gb_Apu();
// Set overall volume of all oscillators, where 1.0 is full volume
void volume( double );
// Set treble equalization
void treble_eq( const blip_eq_t& );
// Reset oscillators and internal state
void reset();
// Assign all oscillator outputs to specified buffer(s). If buffer
// is NULL, silence all oscillators.
void output( Blip_Buffer* mono );
void output( Blip_Buffer* center, Blip_Buffer* left, Blip_Buffer* right );
// Assign single oscillator output to buffer(s). Valid indicies are 0 to 3,
// which refer to Square 1, Square 2, Wave, and Noise.
// If buffer is NULL, silence oscillator.
enum { osc_count = 4 };
void osc_output( int index, Blip_Buffer* mono );
void osc_output( int index, Blip_Buffer* center, Blip_Buffer* left, Blip_Buffer* right );
// Reads and writes at addr must satisfy start_addr <= addr <= end_addr
enum { start_addr = 0xff10 };
enum { end_addr = 0xff3f };
enum { register_count = end_addr - start_addr + 1 };
// Write 'data' to address at specified time
void write_register( gb_time_t, gb_addr_t, int data );
// Read from address at specified time
int read_register( gb_time_t, gb_addr_t );
// Run all oscillators up to specified time, end current time frame, then
// start a new frame at time 0. Return true if any oscillators added
// sound to one of the left/right buffers, false if they only added
// to the center buffer.
bool end_frame( gb_time_t );
private:
// noncopyable
Gb_Apu( const Gb_Apu& );
Gb_Apu& operator = ( const Gb_Apu& );
Gb_Osc* oscs [osc_count];
gb_time_t next_frame_time;
gb_time_t last_time;
int frame_count;
bool stereo_found;
Gb_Square square1;
Gb_Square square2;
Gb_Wave wave;
Gb_Noise noise;
BOOST::uint8_t regs [register_count];
Gb_Square::Synth square_synth; // shared between squares
Gb_Wave::Synth other_synth; // shared between wave and noise
void run_until( gb_time_t );
};
inline void Gb_Apu::output( Blip_Buffer* b ) { output( b, NULL, NULL ); }
inline void Gb_Apu::osc_output( int i, Blip_Buffer* b ) { osc_output( i, b, NULL, NULL ); }
#endif
| C++ |
// Blip_Buffer 0.3.4. http://www.slack.net/~ant/libs/
#include "Multi_Buffer.h"
/* Copyright (C) 2003-2005 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details. You should have received a copy of the GNU Lesser General
Public License along with this module; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include BLARGG_SOURCE_BEGIN
Multi_Buffer::Multi_Buffer( int spf ) : samples_per_frame_( spf )
{
length_ = 0;
sample_rate_ = 0;
channels_changed_count_ = 1;
}
blargg_err_t Multi_Buffer::set_channel_count( int )
{
return blargg_success;
}
Mono_Buffer::Mono_Buffer() : Multi_Buffer( 1 )
{
}
Mono_Buffer::~Mono_Buffer()
{
}
blargg_err_t Mono_Buffer::set_sample_rate( long rate, int msec )
{
BLARGG_RETURN_ERR( buf.set_sample_rate( rate, msec ) );
return Multi_Buffer::set_sample_rate( buf.sample_rate(), buf.length() );
}
// Silent_Buffer
Silent_Buffer::Silent_Buffer() : Multi_Buffer( 1 ) // 0 channels would probably confuse
{
chan.left = NULL;
chan.center = NULL;
chan.right = NULL;
}
// Mono_Buffer
Mono_Buffer::channel_t Mono_Buffer::channel( int index )
{
channel_t ch;
ch.center = &buf;
ch.left = &buf;
ch.right = &buf;
return ch;
}
void Mono_Buffer::end_frame( blip_time_t t, bool )
{
buf.end_frame( t );
}
// Stereo_Buffer
Stereo_Buffer::Stereo_Buffer() : Multi_Buffer( 2 )
{
chan.center = &bufs [0];
chan.left = &bufs [1];
chan.right = &bufs [2];
}
Stereo_Buffer::~Stereo_Buffer()
{
}
blargg_err_t Stereo_Buffer::set_sample_rate( long rate, int msec )
{
for ( int i = 0; i < buf_count; i++ )
BLARGG_RETURN_ERR( bufs [i].set_sample_rate( rate, msec ) );
return Multi_Buffer::set_sample_rate( bufs [0].sample_rate(), bufs [0].length() );
}
void Stereo_Buffer::clock_rate( long rate )
{
for ( int i = 0; i < buf_count; i++ )
bufs [i].clock_rate( rate );
}
void Stereo_Buffer::bass_freq( int bass )
{
for ( unsigned i = 0; i < buf_count; i++ )
bufs [i].bass_freq( bass );
}
void Stereo_Buffer::clear()
{
stereo_added = false;
was_stereo = false;
for ( int i = 0; i < buf_count; i++ )
bufs [i].clear();
}
void Stereo_Buffer::end_frame( blip_time_t clock_count, bool stereo )
{
for ( unsigned i = 0; i < buf_count; i++ )
bufs [i].end_frame( clock_count );
stereo_added |= stereo;
}
long Stereo_Buffer::read_samples( blip_sample_t* out, long count )
{
require( !(count & 1) ); // count must be even
count = (unsigned) count / 2;
long avail = bufs [0].samples_avail();
if ( count > avail )
count = avail;
if ( count )
{
if ( stereo_added || was_stereo )
{
mix_stereo( out, count );
bufs [0].remove_samples( count );
bufs [1].remove_samples( count );
bufs [2].remove_samples( count );
}
else
{
mix_mono( out, count );
bufs [0].remove_samples( count );
bufs [1].remove_silence( count );
bufs [2].remove_silence( count );
}
// to do: this might miss opportunities for optimization
if ( !bufs [0].samples_avail() ) {
was_stereo = stereo_added;
stereo_added = false;
}
}
return count * 2;
}
#include BLARGG_ENABLE_OPTIMIZER
void Stereo_Buffer::mix_stereo( blip_sample_t* out, long count )
{
Blip_Reader left;
Blip_Reader right;
Blip_Reader center;
left.begin( bufs [1] );
right.begin( bufs [2] );
int bass = center.begin( bufs [0] );
while ( count-- )
{
int c = center.read();
long l = c + left.read();
long r = c + right.read();
center.next( bass );
out [0] = l;
out [1] = r;
out += 2;
if ( (BOOST::int16_t) l != l )
out [-2] = 0x7FFF - (l >> 24);
left.next( bass );
right.next( bass );
if ( (BOOST::int16_t) r != r )
out [-1] = 0x7FFF - (r >> 24);
}
center.end( bufs [0] );
right.end( bufs [2] );
left.end( bufs [1] );
}
void Stereo_Buffer::mix_mono( blip_sample_t* out, long count )
{
Blip_Reader in;
int bass = in.begin( bufs [0] );
while ( count-- )
{
long s = in.read();
in.next( bass );
out [0] = s;
out [1] = s;
out += 2;
if ( (BOOST::int16_t) s != s ) {
s = 0x7FFF - (s >> 24);
out [-2] = s;
out [-1] = s;
}
}
in.end( bufs [0] );
}
| C++ |
// Multi-channel sound buffer interface, and basic mono and stereo buffers
// Blip_Buffer 0.3.4. Copyright (C) 2003-2005 Shay Green. GNU LGPL license.
#ifndef MULTI_BUFFER_H
#define MULTI_BUFFER_H
#include "Blip_Buffer.h"
// Interface to one or more Blip_Buffers mapped to one or more channels
// consisting of left, center, and right buffers.
class Multi_Buffer {
public:
Multi_Buffer( int samples_per_frame );
virtual ~Multi_Buffer() { }
// Set the number of channels available
virtual blargg_err_t set_channel_count( int );
// Get indexed channel, from 0 to channel count - 1
struct channel_t {
Blip_Buffer* center;
Blip_Buffer* left;
Blip_Buffer* right;
};
virtual channel_t channel( int index ) = 0;
// See Blip_Buffer.h
virtual blargg_err_t set_sample_rate( long rate, int msec = blip_default_length ) = 0;
virtual void clock_rate( long ) = 0;
virtual void bass_freq( int ) = 0;
virtual void clear() = 0;
long sample_rate() const;
// Length of buffer, in milliseconds
int length() const;
// See Blip_Buffer.h. For optimal operation, pass false for 'added_stereo'
// if nothing was added to the left and right buffers of any channel for
// this time frame.
virtual void end_frame( blip_time_t, bool added_stereo = true ) = 0;
// Number of samples per output frame (1 = mono, 2 = stereo)
int samples_per_frame() const;
// Count of changes to channel configuration. Incremented whenever
// a change is made to any of the Blip_Buffers for any channel.
unsigned channels_changed_count() { return channels_changed_count_; }
// See Blip_Buffer.h
virtual long read_samples( blip_sample_t*, long ) = 0;
virtual long samples_avail() const = 0;
protected:
void channels_changed() { channels_changed_count_++; }
private:
// noncopyable
Multi_Buffer( const Multi_Buffer& );
Multi_Buffer& operator = ( const Multi_Buffer& );
unsigned channels_changed_count_;
long sample_rate_;
int length_;
int const samples_per_frame_;
};
// Uses a single buffer and outputs mono samples.
class Mono_Buffer : public Multi_Buffer {
Blip_Buffer buf;
public:
Mono_Buffer();
~Mono_Buffer();
// Buffer used for all channels
Blip_Buffer* center() { return &buf; }
// See Multi_Buffer
blargg_err_t set_sample_rate( long rate, int msec = blip_default_length );
void clock_rate( long );
void bass_freq( int );
void clear();
channel_t channel( int );
void end_frame( blip_time_t, bool unused = true );
long samples_avail() const;
long read_samples( blip_sample_t*, long );
};
// Uses three buffers (one for center) and outputs stereo sample pairs.
class Stereo_Buffer : public Multi_Buffer {
public:
Stereo_Buffer();
~Stereo_Buffer();
// Buffers used for all channels
Blip_Buffer* center() { return &bufs [0]; }
Blip_Buffer* left() { return &bufs [1]; }
Blip_Buffer* right() { return &bufs [2]; }
// See Multi_Buffer
blargg_err_t set_sample_rate( long, int msec = blip_default_length );
void clock_rate( long );
void bass_freq( int );
void clear();
channel_t channel( int index );
void end_frame( blip_time_t, bool added_stereo = true );
long samples_avail() const;
long read_samples( blip_sample_t*, long );
private:
enum { buf_count = 3 };
Blip_Buffer bufs [buf_count];
channel_t chan;
bool stereo_added;
bool was_stereo;
void mix_stereo( blip_sample_t*, long );
void mix_mono( blip_sample_t*, long );
};
// Silent_Buffer generates no samples, useful where no sound is wanted
class Silent_Buffer : public Multi_Buffer {
channel_t chan;
public:
Silent_Buffer();
blargg_err_t set_sample_rate( long rate, int msec = blip_default_length );
void clock_rate( long ) { }
void bass_freq( int ) { }
void clear() { }
channel_t channel( int ) { return chan; }
void end_frame( blip_time_t, bool unused = true ) { }
long samples_avail() const { return 0; }
long read_samples( blip_sample_t*, long ) { return 0; }
};
// End of public interface
inline blargg_err_t Silent_Buffer::set_sample_rate( long rate, int msec )
{
return Multi_Buffer::set_sample_rate( rate, msec );
}
inline blargg_err_t Multi_Buffer::set_sample_rate( long rate, int msec )
{
sample_rate_ = rate;
length_ = msec;
return blargg_success;
}
inline int Multi_Buffer::samples_per_frame() const { return samples_per_frame_; }
inline long Stereo_Buffer::samples_avail() const { return bufs [0].samples_avail() * 2; }
inline Stereo_Buffer::channel_t Stereo_Buffer::channel( int index ) { return chan; }
inline long Multi_Buffer::sample_rate() const { return sample_rate_; }
inline int Multi_Buffer::length() const { return length_; }
inline void Mono_Buffer::clock_rate( long rate ) { buf.clock_rate( rate ); }
inline void Mono_Buffer::clear() { buf.clear(); }
inline void Mono_Buffer::bass_freq( int freq ) { buf.bass_freq( freq ); }
inline long Mono_Buffer::read_samples( blip_sample_t* p, long s ) { return buf.read_samples( p, s ); }
inline long Mono_Buffer::samples_avail() const { return buf.samples_avail(); }
#endif
| C++ |
// Blip_Buffer 0.3.4. http://www.slack.net/~ant/libs/
#include "Blip_Buffer.h"
#include <string.h>
#include <stddef.h>
#include <math.h>
/* Copyright (C) 2003-2005 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details. You should have received a copy of the GNU Lesser General
Public License along with this module; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include BLARGG_SOURCE_BEGIN
Blip_Buffer::Blip_Buffer()
{
samples_per_sec = 44100;
buffer_ = NULL;
// try to cause assertion failure if buffer is used before these are set
clocks_per_sec = 0;
factor_ = ~0ul;
offset_ = 0;
buffer_size_ = 0;
length_ = 0;
bass_freq_ = 16;
}
void Blip_Buffer::clear( bool entire_buffer )
{
long count = (entire_buffer ? buffer_size_ : samples_avail());
offset_ = 0;
reader_accum = 0;
if ( buffer_ )
memset( buffer_, sample_offset_ & 0xFF, (count + widest_impulse_) * sizeof (buf_t_) );
}
blargg_err_t Blip_Buffer::set_sample_rate( long new_rate, int msec )
{
unsigned new_size = (ULONG_MAX >> BLIP_BUFFER_ACCURACY) + 1 - widest_impulse_ - 64;
if ( msec != blip_default_length )
{
size_t s = (new_rate * (msec + 1) + 999) / 1000;
if ( s < new_size )
new_size = s;
else
require( false ); // requested buffer length exceeds limit
}
if ( buffer_size_ != new_size )
{
delete [] buffer_;
buffer_ = NULL; // allow for exception in allocation below
buffer_size_ = 0;
offset_ = 0;
int const count_clocks_extra = 2;
buffer_ = BLARGG_NEW buf_t_ [new_size + widest_impulse_ + count_clocks_extra];
BLARGG_CHECK_ALLOC( buffer_ );
}
buffer_size_ = new_size;
length_ = new_size * 1000 / new_rate - 1;
if ( msec )
assert( length_ == msec ); // ensure length is same as that passed in
samples_per_sec = new_rate;
if ( clocks_per_sec )
clock_rate( clocks_per_sec ); // recalculate factor
bass_freq( bass_freq_ ); // recalculate shift
clear();
return blargg_success;
}
blip_resampled_time_t Blip_Buffer::clock_rate_factor( long clock_rate ) const
{
blip_resampled_time_t factor = (unsigned long) floor(
(double) samples_per_sec / clock_rate * (1L << BLIP_BUFFER_ACCURACY) + 0.5 );
require( factor > 0 ); // clock_rate/sample_rate ratio is too large
return factor;
}
Blip_Buffer::~Blip_Buffer()
{
delete [] buffer_;
}
void Blip_Buffer::bass_freq( int freq )
{
bass_freq_ = freq;
if ( freq == 0 )
{
bass_shift = 31; // 32 or greater invokes undefined behavior elsewhere
return;
}
bass_shift = 1 + (int) floor( 1.442695041 * log( 0.124 * samples_per_sec / freq ) );
if ( bass_shift < 0 )
bass_shift = 0;
if ( bass_shift > 24 )
bass_shift = 24;
}
long Blip_Buffer::count_samples( blip_time_t t ) const
{
return (resampled_time( t ) >> BLIP_BUFFER_ACCURACY) - (offset_ >> BLIP_BUFFER_ACCURACY);
}
blip_time_t Blip_Buffer::count_clocks( long count ) const
{
if ( count > buffer_size_ )
count = buffer_size_;
return ((count << BLIP_BUFFER_ACCURACY) - offset_ + (factor_ - 1)) / factor_;
}
void Blip_Impulse_::init( blip_pair_t_* imps, int w, int r, int fb )
{
fine_bits = fb;
width = w;
impulses = (imp_t*) imps;
generate = true;
volume_unit_ = -1.0;
res = r;
buf = NULL;
impulse = &impulses [width * res * 2 * (fine_bits ? 2 : 1)];
offset = 0;
}
const int impulse_bits = 15;
const long impulse_amp = 1L << impulse_bits;
const long impulse_offset = impulse_amp / 2;
void Blip_Impulse_::scale_impulse( int unit, imp_t* imp_in ) const
{
long offset = ((long) unit << impulse_bits) - impulse_offset * unit +
(1 << (impulse_bits - 1));
imp_t* imp = imp_in;
imp_t* fimp = impulse;
for ( int n = res / 2 + 1; n--; )
{
int error = unit;
for ( int nn = width; nn--; )
{
long a = ((long) *fimp++ * unit + offset) >> impulse_bits;
error -= a - unit;
*imp++ = (imp_t) a;
}
// add error to middle
imp [-width / 2 - 1] += (imp_t) error;
}
if ( res > 2 )
{
// second half is mirror-image
const imp_t* rev = imp - width - 1;
for ( int nn = (res / 2 - 1) * width - 1; nn--; )
*imp++ = *--rev;
*imp++ = (imp_t) unit;
}
// copy to odd offset
*imp++ = (imp_t) unit;
memcpy( imp, imp_in, (res * width - 1) * sizeof *imp );
/*
for ( int i = 0; i < res; i++ )
{
for ( int j = 0; j < width; j++ )
printf( "%6d,", imp_in [i * width + j] - 0x8000 );
printf( "\n" );
}*/
}
const int max_res = 1 << blip_res_bits_;
void Blip_Impulse_::fine_volume_unit()
{
// to do: find way of merging in-place without temporary buffer
imp_t temp [max_res * 2 * Blip_Buffer::widest_impulse_];
scale_impulse( (offset & 0xffff) << fine_bits, temp );
imp_t* imp2 = impulses + res * 2 * width;
scale_impulse( offset & 0xffff, imp2 );
// merge impulses
imp_t* imp = impulses;
imp_t* src2 = temp;
for ( int n = res / 2 * 2 * width; n--; )
{
*imp++ = *imp2++;
*imp++ = *imp2++;
*imp++ = *src2++;
*imp++ = *src2++;
}
}
void Blip_Impulse_::volume_unit( double new_unit )
{
if ( new_unit == volume_unit_ )
return;
if ( generate )
treble_eq( blip_eq_t( -8.87, 8800, 44100 ) );
volume_unit_ = new_unit;
offset = 0x10001 * (unsigned long) floor( volume_unit_ * 0x10000 + 0.5 );
if ( fine_bits )
fine_volume_unit();
else
scale_impulse( offset & 0xffff, impulses );
}
static const double pi = 3.1415926535897932384626433832795029L;
void Blip_Impulse_::treble_eq( const blip_eq_t& new_eq )
{
if ( !generate && new_eq.treble == eq.treble && new_eq.cutoff == eq.cutoff &&
new_eq.sample_rate == eq.sample_rate )
return; // already calculated with same parameters
generate = false;
eq = new_eq;
double treble = pow( 10.0, 1.0 / 20 * eq.treble ); // dB (-6dB = 0.50)
if ( treble < 0.000005 )
treble = 0.000005;
const double treble_freq = 22050.0; // treble level at 22 kHz harmonic
const double sample_rate = eq.sample_rate;
const double pt = treble_freq * 2 / sample_rate;
double cutoff = eq.cutoff * 2 / sample_rate;
if ( cutoff >= pt * 0.95 || cutoff >= 0.95 )
{
cutoff = 0.5;
treble = 1.0;
}
// DSF Synthesis (See T. Stilson & J. Smith (1996),
// Alias-free digital synthesis of classic analog waveforms)
// reduce adjacent impulse interference by using small part of wide impulse
const double n_harm = 4096;
const double rolloff = pow( treble, 1.0 / (n_harm * pt - n_harm * cutoff) );
const double rescale = 1.0 / pow( rolloff, n_harm * cutoff );
const double pow_a_n = rescale * pow( rolloff, n_harm );
const double pow_a_nc = rescale * pow( rolloff, n_harm * cutoff );
double total = 0.0;
const double to_angle = pi / 2 / n_harm / max_res;
float buf [max_res * (Blip_Buffer::widest_impulse_ - 2) / 2];
const int size = max_res * (width - 2) / 2;
for ( int i = size; i--; )
{
double angle = (i * 2 + 1) * to_angle;
// equivalent
//double y = dsf( angle, n_harm * cutoff, 1.0 );
//y -= rescale * dsf( angle, n_harm * cutoff, rolloff );
//y += rescale * dsf( angle, n_harm, rolloff );
const double cos_angle = cos( angle );
const double cos_nc_angle = cos( n_harm * cutoff * angle );
const double cos_nc1_angle = cos( (n_harm * cutoff - 1.0) * angle );
double b = 2.0 - 2.0 * cos_angle;
double a = 1.0 - cos_angle - cos_nc_angle + cos_nc1_angle;
double d = 1.0 + rolloff * (rolloff - 2.0 * cos_angle);
double c = pow_a_n * rolloff * cos( (n_harm - 1.0) * angle ) -
pow_a_n * cos( n_harm * angle ) -
pow_a_nc * rolloff * cos_nc1_angle +
pow_a_nc * cos_nc_angle;
// optimization of a / b + c / d
double y = (a * d + c * b) / (b * d);
// fixed window which affects wider impulses more
if ( width > 12 )
{
double window = cos( n_harm / 1.25 / Blip_Buffer::widest_impulse_ * angle );
y *= window * window;
}
total += (float) y;
buf [i] = (float) y;
}
// integrate runs of length 'max_res'
double factor = impulse_amp * 0.5 / total; // 0.5 accounts for other mirrored half
imp_t* imp = impulse;
const int step = max_res / res;
int offset = res > 1 ? max_res : max_res / 2;
for ( int n = res / 2 + 1; n--; offset -= step )
{
for ( int w = -width / 2; w < width / 2; w++ )
{
double sum = 0;
for ( int i = max_res; i--; )
{
int index = w * max_res + offset + i;
if ( index < 0 )
index = -index - 1;
if ( index < size )
sum += buf [index];
}
*imp++ = (imp_t) floor( sum * factor + (impulse_offset + 0.5) );
}
}
// rescale
double unit = volume_unit_;
if ( unit >= 0 )
{
volume_unit_ = -1;
volume_unit( unit );
}
}
void Blip_Buffer::remove_samples( long count )
{
require( buffer_ ); // sample rate must have been set
if ( !count ) // optimization
return;
remove_silence( count );
// Allows synthesis slightly past time passed to end_frame(), as long as it's
// not more than an output sample.
// to do: kind of hacky, could add run_until() which keeps track of extra synthesis
int const copy_extra = 1;
// copy remaining samples to beginning and clear old samples
long remain = samples_avail() + widest_impulse_ + copy_extra;
if ( count >= remain )
memmove( buffer_, buffer_ + count, remain * sizeof (buf_t_) );
else
memcpy( buffer_, buffer_ + count, remain * sizeof (buf_t_) );
memset( buffer_ + remain, sample_offset_ & 0xFF, count * sizeof (buf_t_) );
}
#include BLARGG_ENABLE_OPTIMIZER
long Blip_Buffer::read_samples( blip_sample_t* out, long max_samples, bool stereo )
{
require( buffer_ ); // sample rate must have been set
long count = samples_avail();
if ( count > max_samples )
count = max_samples;
if ( !count )
return 0; // optimization
int sample_offset_ = this->sample_offset_;
int bass_shift = this->bass_shift;
buf_t_* buf = buffer_;
long accum = reader_accum;
if ( !stereo )
{
for ( long n = count; n--; )
{
long s = accum >> accum_fract;
accum -= accum >> bass_shift;
accum += (long (*buf++) - sample_offset_) << accum_fract;
*out++ = (blip_sample_t) s;
// clamp sample
if ( (BOOST::int16_t) s != s )
out [-1] = blip_sample_t (0x7FFF - (s >> 24));
}
}
else
{
for ( long n = count; n--; )
{
long s = accum >> accum_fract;
accum -= accum >> bass_shift;
accum += (long (*buf++) - sample_offset_) << accum_fract;
*out = (blip_sample_t) s;
out += 2;
// clamp sample
if ( (BOOST::int16_t) s != s )
out [-2] = blip_sample_t (0x7FFF - (s >> 24));
}
}
reader_accum = accum;
remove_samples( count );
return count;
}
void Blip_Buffer::mix_samples( const blip_sample_t* in, long count )
{
buf_t_* buf = &buffer_ [(offset_ >> BLIP_BUFFER_ACCURACY) + (widest_impulse_ / 2 - 1)];
int prev = 0;
while ( count-- )
{
int s = *in++;
*buf += s - prev;
prev = s;
++buf;
}
*buf -= *--in;
}
| C++ |
// Gb_Snd_Emu 0.1.4. http://www.slack.net/~ant/libs/
#include "Gb_Apu.h"
#include <string.h>
/* Copyright (C) 2003-2005 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details. You should have received a copy of the GNU Lesser General
Public License along with this module; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include BLARGG_SOURCE_BEGIN
const int trigger = 0x80;
// Gb_Osc
Gb_Osc::Gb_Osc()
{
output = NULL;
outputs [0] = NULL;
outputs [1] = NULL;
outputs [2] = NULL;
outputs [3] = NULL;
}
void Gb_Osc::reset()
{
delay = 0;
last_amp = 0;
period = 2048;
volume = 0;
global_volume = 7; // added
frequency = 0;
length = 0;
enabled = false;
length_enabled = false;
output_select = 3;
output = outputs [output_select];
}
void Gb_Osc::clock_length()
{
if ( length_enabled && length )
--length;
}
void Gb_Osc::write_register( int reg, int value )
{
if ( reg == 4 )
length_enabled = value & 0x40;
}
// Gb_Env
void Gb_Env::reset()
{
env_period = 0;
env_dir = 0;
env_delay = 0;
new_volume = 0;
Gb_Osc::reset();
}
Gb_Env::Gb_Env()
{
}
void Gb_Env::clock_envelope()
{
if ( env_delay && !--env_delay )
{
env_delay = env_period;
if ( env_dir )
{
if ( volume < 15 )
++volume;
}
else if ( volume > 0 )
{
--volume;
}
}
}
void Gb_Env::write_register( int reg, int value )
{
if ( reg == 2 ) {
env_period = value & 7;
env_dir = value & 8;
volume = new_volume = value >> 4;
}
else if ( reg == 4 && (value & trigger) ) {
env_delay = env_period;
volume = new_volume;
enabled = true;
}
Gb_Osc::write_register( reg, value );
}
// Gb_Square
void Gb_Square::reset()
{
phase = 1;
duty = 1;
sweep_period = 0;
sweep_delay = 0;
sweep_shift = 0;
sweep_dir = 0;
sweep_freq = 0;
new_length = 0;
Gb_Env::reset();
}
Gb_Square::Gb_Square()
{
has_sweep = false;
}
void Gb_Square::clock_sweep()
{
if ( sweep_period && sweep_delay && !--sweep_delay )
{
sweep_delay = sweep_period;
frequency = sweep_freq;
period = (2048 - frequency) * 4;
int offset = sweep_freq >> sweep_shift;
if ( sweep_dir )
offset = -offset;
sweep_freq += offset;
if ( sweep_freq < 0 )
{
sweep_freq = 0;
}
else if ( sweep_freq >= 2048 )
{
sweep_delay = 0;
sweep_freq = 2048; // stop sound output
}
}
}
void Gb_Square::write_register( int reg, int value )
{
static unsigned char const duty_table [4] = { 1, 2, 4, 6 };
switch ( reg )
{
case 0:
sweep_period = (value >> 4) & 7; // changed
sweep_shift = value & 7;
sweep_dir = value & 0x08;
break;
case 1:
new_length = length = 64 - (value & 0x3f);
duty = duty_table [value >> 6];
break;
case 3:
frequency = (frequency & ~0xFF) + value;
length = new_length;
break;
case 4:
frequency = (value & 7) * 0x100 + (frequency & 0xFF);
length = new_length;
if ( value & trigger )
{
sweep_freq = frequency;
if ( has_sweep && sweep_period && sweep_shift )
{
sweep_delay = 1;
clock_sweep();
}
}
break;
}
period = (2048 - frequency) * 4;
Gb_Env::write_register( reg, value );
}
void Gb_Square::run( gb_time_t time, gb_time_t end_time )
{
// to do: when frequency goes above 20000 Hz output should actually be 1/2 volume
// rather than 0
if ( !enabled || (!length && length_enabled) || !volume || sweep_freq == 2048 ||
!frequency || period < 27 )
{
if ( last_amp )
{
synth->offset( time, -last_amp, output );
last_amp = 0;
}
delay = 0;
}
else
{
int amp = (phase < duty) ? volume : -volume;
amp *= global_volume;
if ( amp != last_amp )
{
synth->offset( time, amp - last_amp, output );
last_amp = amp;
}
time += delay;
if ( time < end_time )
{
Blip_Buffer* const output = this->output;
const int duty = this->duty;
int phase = this->phase;
amp *= 2;
do
{
phase = (phase + 1) & 7;
if ( phase == 0 || phase == duty )
{
amp = -amp;
synth->offset_inline( time, amp, output );
}
time += period;
}
while ( time < end_time );
this->phase = phase;
last_amp = amp >> 1;
}
delay = time - end_time;
}
}
// Gb_Wave
void Gb_Wave::reset()
{
volume_shift = 0;
wave_pos = 0;
new_length = 0;
memset( wave, 0, sizeof wave );
Gb_Osc::reset();
}
Gb_Wave::Gb_Wave() {
}
void Gb_Wave::write_register( int reg, int value )
{
switch ( reg )
{
case 0:
new_enabled = value & 0x80;
enabled &= new_enabled;
break;
case 1:
new_length = length = 256 - value;
break;
case 2:
volume = ((value >> 5) & 3);
volume_shift = (volume - 1) & 7; // silence = 7
break;
case 3:
frequency = (frequency & ~0xFF) + value;
break;
case 4:
frequency = (value & 7) * 0x100 + (frequency & 0xFF);
if ( new_enabled && (value & trigger) )
{
wave_pos = 0;
length = new_length;
enabled = true;
}
break;
}
period = (2048 - frequency) * 2;
Gb_Osc::write_register( reg, value );
}
void Gb_Wave::run( gb_time_t time, gb_time_t end_time )
{
// to do: when frequency goes above 20000 Hz output should actually be 1/2 volume
// rather than 0
if ( !enabled || (!length && length_enabled) || !volume || !frequency || period < 7 )
{
if ( last_amp ) {
synth->offset( time, -last_amp, output );
last_amp = 0;
}
delay = 0;
}
else
{
int const vol_factor = global_volume * 2;
// wave data or shift may have changed
int diff = (wave [wave_pos] >> volume_shift) * vol_factor - last_amp;
if ( diff )
{
last_amp += diff;
synth->offset( time, diff, output );
}
time += delay;
if ( time < end_time )
{
int const volume_shift = this->volume_shift;
int wave_pos = this->wave_pos;
do
{
wave_pos = unsigned (wave_pos + 1) % wave_size;
int amp = (wave [wave_pos] >> volume_shift) * vol_factor;
int delta = amp - last_amp;
if ( delta )
{
last_amp = amp;
synth->offset_inline( time, delta, output );
}
time += period;
}
while ( time < end_time );
this->wave_pos = wave_pos;
}
delay = time - end_time;
}
}
// Gb_Noise
void Gb_Noise::reset()
{
bits = 1;
tap = 14;
Gb_Env::reset();
}
Gb_Noise::Gb_Noise() {
}
void Gb_Noise::write_register( int reg, int value )
{
if ( reg == 1 ) {
new_length = length = 64 - (value & 0x3f);
}
else if ( reg == 2 ) {
// based on VBA code, noise is the only exception to the envelope code
// while the volume level here is applied when the channel is enabled,
// current volume is only affected by writes to this register if volume
// is zero and direction is up... (definitely needs verification)
int temp = volume;
Gb_Env::write_register( reg, value );
if ( ( value & 0xF8 ) != 0 ) volume = temp;
return;
}
else if ( reg == 3 ) {
tap = 14 - (value & 8);
// noise formula and frequency tested against Metroid 2 and Zelda LA
int divisor = (value & 7) * 16;
if ( !divisor )
divisor = 8;
period = divisor << (value >> 4);
}
else if ( reg == 4 && value & trigger ) {
bits = ~0u;
length = new_length;
}
Gb_Env::write_register( reg, value );
}
#include BLARGG_ENABLE_OPTIMIZER
void Gb_Noise::run( gb_time_t time, gb_time_t end_time )
{
if ( !enabled || (!length && length_enabled) || !volume ) {
if ( last_amp ) {
synth->offset( time, -last_amp, output );
last_amp = 0;
}
delay = 0;
}
else
{
int amp = bits & 1 ? -volume : volume;
amp *= global_volume;
if ( amp != last_amp ) {
synth->offset( time, amp - last_amp, output );
last_amp = amp;
}
time += delay;
if ( time < end_time )
{
Blip_Buffer* const output = this->output;
// keep parallel resampled time to eliminate multiplication in the loop
const blip_resampled_time_t resampled_period =
output->resampled_duration( period );
blip_resampled_time_t resampled_time = output->resampled_time( time );
const unsigned mask = ~(1u << tap);
unsigned bits = this->bits;
amp *= 2;
do {
unsigned feedback = bits;
bits >>= 1;
feedback = 1 & (feedback ^ bits);
time += period;
bits = (feedback << tap) | (bits & mask);
// feedback just happens to be true only when the level needs to change
// (the previous and current bits are different)
if ( feedback ) {
amp = -amp;
synth->offset_resampled( resampled_time, amp, output );
}
resampled_time += resampled_period;
}
while ( time < end_time );
this->bits = bits;
last_amp = amp >> 1;
}
delay = time - end_time;
}
}
| C++ |
// Buffer of sound samples into which band-limited waveforms can be synthesized
// using Blip_Wave or Blip_Synth.
// Blip_Buffer 0.3.4. Copyright (C) 2003-2005 Shay Green. GNU LGPL license.
#ifndef BLIP_BUFFER_H
#define BLIP_BUFFER_H
#include "blargg_common.h"
class Blip_Reader;
// Source time unit.
typedef long blip_time_t;
// Type of sample produced. Signed 16-bit format.
typedef BOOST::int16_t blip_sample_t;
// Make buffer as large as possible (currently about 65000 samples)
const int blip_default_length = 0;
typedef unsigned long blip_resampled_time_t; // not documented
class Blip_Buffer {
public:
// Construct an empty buffer.
Blip_Buffer();
~Blip_Buffer();
// Set output sample rate and buffer length in milliseconds (1/1000 sec),
// then clear buffer. If length is not specified, make as large as possible.
// If there is insufficient memory for the buffer, sets the buffer length
// to 0 and returns error string (or propagates exception if compiler supports it).
blargg_err_t set_sample_rate( long samples_per_sec, int msec_length = blip_default_length );
// Length of buffer, in milliseconds
int length() const;
// Current output sample rate
long sample_rate() const;
// Number of source time units per second
void clock_rate( long );
long clock_rate() const;
// Set frequency at which high-pass filter attenuation passes -3dB
void bass_freq( int frequency );
// Remove all available samples and clear buffer to silence. If 'entire_buffer' is
// false, just clear out any samples waiting rather than the entire buffer.
void clear( bool entire_buffer = true );
// End current time frame of specified duration and make its samples available
// (along with any still-unread samples) for reading with read_samples(). Begin
// a new time frame at the end of the current frame. All transitions must have
// been added before 'time'.
void end_frame( blip_time_t time );
// Number of samples available for reading with read_samples()
long samples_avail() const;
// Read at most 'max_samples' out of buffer into 'dest', removing them from from
// the buffer. Return number of samples actually read and removed. If stereo is
// true, increment 'dest' one extra time after writing each sample, to allow
// easy interleving of two channels into a stereo output buffer.
long read_samples( blip_sample_t* dest, long max_samples, bool stereo = false );
// Remove 'count' samples from those waiting to be read
void remove_samples( long count );
// Number of samples delay from synthesis to samples read out
int output_latency() const;
// Beta features
// Number of raw samples that can be mixed within frame of specified duration
long count_samples( blip_time_t duration ) const;
// Mix 'count' samples from 'buf' into buffer.
void mix_samples( const blip_sample_t* buf, long count );
// Count number of clocks needed until 'count' samples will be available.
// If buffer can't even hold 'count' samples, returns number of clocks until
// buffer is full.
blip_time_t count_clocks( long count ) const;
// not documented yet
void remove_silence( long count );
blip_resampled_time_t resampled_time( blip_time_t t ) const
{
return t * blip_resampled_time_t (factor_) + offset_;
}
blip_resampled_time_t clock_rate_factor( long clock_rate ) const;
blip_resampled_time_t resampled_duration( int t ) const
{
return t * blip_resampled_time_t (factor_);
}
private:
// noncopyable
Blip_Buffer( const Blip_Buffer& );
Blip_Buffer& operator = ( const Blip_Buffer& );
// Don't use the following members. They are public only for technical reasons.
public:
enum { sample_offset_ = 0x7F7F }; // repeated byte allows memset to clear buffer
enum { widest_impulse_ = 24 };
typedef BOOST::uint16_t buf_t_;
unsigned long factor_;
blip_resampled_time_t offset_;
buf_t_* buffer_;
unsigned buffer_size_;
private:
long reader_accum;
int bass_shift;
long samples_per_sec;
long clocks_per_sec;
int bass_freq_;
int length_;
enum { accum_fract = 15 }; // less than 16 to give extra sample range
friend class Blip_Reader;
};
// Low-pass equalization parameters (see notes.txt)
class blip_eq_t {
public:
blip_eq_t( double treble = 0 );
blip_eq_t( double treble, long cutoff, long sample_rate );
private:
double treble;
long cutoff;
long sample_rate;
friend class Blip_Impulse_;
};
// not documented yet (see Multi_Buffer.cpp for an example of use)
class Blip_Reader {
const Blip_Buffer::buf_t_* buf;
long accum;
#ifdef __MWERKS__
void operator = ( struct foobar ); // helps optimizer
#endif
public:
// avoid anything which might cause optimizer to put object in memory
int begin( Blip_Buffer& blip_buf ) {
buf = blip_buf.buffer_;
accum = blip_buf.reader_accum;
return blip_buf.bass_shift;
}
int read() const {
return accum >> Blip_Buffer::accum_fract;
}
void next( int bass_shift = 9 ) {
accum -= accum >> bass_shift;
accum += ((long) *buf++ - Blip_Buffer::sample_offset_) << Blip_Buffer::accum_fract;
}
void end( Blip_Buffer& blip_buf ) {
blip_buf.reader_accum = accum;
}
};
// End of public interface
#ifndef BLIP_BUFFER_ACCURACY
#define BLIP_BUFFER_ACCURACY 16
#endif
const int blip_res_bits_ = 5;
typedef BOOST::uint32_t blip_pair_t_;
class Blip_Impulse_ {
typedef BOOST::uint16_t imp_t;
blip_eq_t eq;
double volume_unit_;
imp_t* impulses;
imp_t* impulse;
int width;
int fine_bits;
int res;
bool generate;
void fine_volume_unit();
void scale_impulse( int unit, imp_t* ) const;
public:
Blip_Buffer* buf;
BOOST::uint32_t offset;
void init( blip_pair_t_* impulses, int width, int res, int fine_bits = 0 );
void volume_unit( double );
void treble_eq( const blip_eq_t& );
};
inline blip_eq_t::blip_eq_t( double t ) :
treble( t ), cutoff( 0 ), sample_rate( 44100 ) {
}
inline blip_eq_t::blip_eq_t( double t, long c, long sr ) :
treble( t ), cutoff( c ), sample_rate( sr ) {
}
inline int Blip_Buffer::length() const {
return length_;
}
inline long Blip_Buffer::samples_avail() const {
return long (offset_ >> BLIP_BUFFER_ACCURACY);
}
inline long Blip_Buffer::sample_rate() const {
return samples_per_sec;
}
inline void Blip_Buffer::end_frame( blip_time_t t ) {
offset_ += t * factor_;
assert(( "Blip_Buffer::end_frame(): Frame went past end of buffer",
samples_avail() <= (long) buffer_size_ ));
}
inline void Blip_Buffer::remove_silence( long count ) {
assert(( "Blip_Buffer::remove_silence(): Tried to remove more samples than available",
count <= samples_avail() ));
offset_ -= blip_resampled_time_t (count) << BLIP_BUFFER_ACCURACY;
}
inline int Blip_Buffer::output_latency() const {
return widest_impulse_ / 2;
}
inline long Blip_Buffer::clock_rate() const {
return clocks_per_sec;
}
inline void Blip_Buffer::clock_rate( long cps )
{
clocks_per_sec = cps;
factor_ = clock_rate_factor( cps );
}
#include "Blip_Synth.h"
#endif
| C++ |
// By default, #included at beginning of library source files
// Copyright (C) 2005 Shay Green.
#ifndef BLARGG_SOURCE_H
#define BLARGG_SOURCE_H
// If debugging is enabled, abort program if expr is false. Meant for checking
// internal state and consistency. A failed assertion indicates a bug in the module.
// void assert( bool expr );
#include <assert.h>
// If debugging is enabled and expr is false, abort program. Meant for checking
// caller-supplied parameters and operations that are outside the control of the
// module. A failed requirement indicates a bug outside the module.
// void require( bool expr );
#undef require
#define require( expr ) assert(( "unmet requirement", expr ))
// Like printf() except output goes to debug log file. Might be defined to do
// nothing (not even evaluate its arguments).
// void dprintf( const char* format, ... );
#undef dprintf
#define dprintf (1) ? ((void) 0) : (void)
// If enabled, evaluate expr and if false, make debug log entry with source file
// and line. Meant for finding situations that should be examined further, but that
// don't indicate a problem. In all cases, execution continues normally.
#undef check
#define check( expr ) ((void) 0)
// If expr returns non-NULL error string, return it from current function, otherwise continue.
#define BLARGG_RETURN_ERR( expr ) do { \
blargg_err_t blargg_return_err_ = (expr); \
if ( blargg_return_err_ ) return blargg_return_err_; \
} while ( 0 )
// If ptr is NULL, return out of memory error string.
#define BLARGG_CHECK_ALLOC( ptr ) do { if ( !(ptr) ) return "Out of memory"; } while ( 0 )
// Avoid any macros which evaluate their arguments multiple times
#undef min
#undef max
// using const references generates crappy code, and I am currenly only using these
// for built-in types, so they take arguments by value
template<class T>
inline T min( T x, T y )
{
if ( x < y )
return x;
return y;
}
template<class T>
inline T max( T x, T y )
{
if ( x < y )
return y;
return x;
}
#endif
| C++ |
// Gb_Snd_Emu 0.1.4. http://www.slack.net/~ant/libs/
#include "Gb_Apu.h"
#include <string.h>
/* Copyright (C) 2003-2005 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details. You should have received a copy of the GNU Lesser General
Public License along with this module; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#include BLARGG_SOURCE_BEGIN
Gb_Apu::Gb_Apu()
{
square1.synth = &square_synth;
square2.synth = &square_synth;
square1.has_sweep = true;
wave.synth = &other_synth;
noise.synth = &other_synth;
oscs [0] = &square1;
oscs [1] = &square2;
oscs [2] = &wave;
oscs [3] = &noise;
volume( 1.0 );
reset();
}
Gb_Apu::~Gb_Apu()
{
}
void Gb_Apu::treble_eq( const blip_eq_t& eq )
{
square_synth.treble_eq( eq );
other_synth.treble_eq( eq );
}
void Gb_Apu::volume( double vol )
{
vol *= 0.60 / osc_count;
square_synth.volume( vol );
other_synth.volume( vol );
}
void Gb_Apu::output( Blip_Buffer* center, Blip_Buffer* left, Blip_Buffer* right )
{
for ( int i = 0; i < osc_count; i++ )
osc_output( i, center, left, right );
}
void Gb_Apu::reset()
{
next_frame_time = 0;
last_time = 0;
frame_count = 0;
stereo_found = false;
square1.reset();
square2.reset();
wave.reset();
noise.reset();
memset( regs, 0, sizeof regs );
}
void Gb_Apu::osc_output( int index, Blip_Buffer* center, Blip_Buffer* left, Blip_Buffer* right )
{
require( (unsigned) index < osc_count );
Gb_Osc& osc = *oscs [index];
if ( center && !left && !right )
{
// mono
left = center;
right = center;
}
else
{
// must be silenced or stereo
require( (!left && !right) || (left && right) );
}
osc.outputs [1] = right;
osc.outputs [2] = left;
osc.outputs [3] = center;
osc.output = osc.outputs [osc.output_select];
}
void Gb_Apu::run_until( gb_time_t end_time )
{
require( end_time >= last_time ); // end_time must not be before previous time
if ( end_time == last_time )
return;
while ( true )
{
gb_time_t time = next_frame_time;
if ( time > end_time )
time = end_time;
// run oscillators
for ( int i = 0; i < osc_count; ++i ) {
Gb_Osc& osc = *oscs [i];
if ( osc.output ) {
if ( osc.output != osc.outputs [3] )
stereo_found = true;
osc.run( last_time, time );
}
}
last_time = time;
if ( time == end_time )
break;
next_frame_time += 4194304 / 256; // 256 Hz
// 256 Hz actions
square1.clock_length();
square2.clock_length();
wave.clock_length();
noise.clock_length();
frame_count = (frame_count + 1) & 3;
if ( frame_count == 0 ) {
// 64 Hz actions
square1.clock_envelope();
square2.clock_envelope();
noise.clock_envelope();
}
if ( frame_count & 1 )
square1.clock_sweep(); // 128 Hz action
}
}
bool Gb_Apu::end_frame( gb_time_t end_time )
{
if ( end_time > last_time )
run_until( end_time );
assert( next_frame_time >= end_time );
next_frame_time -= end_time;
assert( last_time >= end_time );
last_time -= end_time;
bool result = stereo_found;
stereo_found = false;
return result;
}
void Gb_Apu::write_register( gb_time_t time, gb_addr_t addr, int data )
{
require( (unsigned) data < 0x100 );
int reg = addr - start_addr;
if ( (unsigned) reg >= register_count )
return;
run_until( time );
regs [reg] = data;
if ( addr < 0xff24 )
{
// oscillator
int index = reg / 5;
oscs [index]->write_register( reg - index * 5, data );
}
// added
else if ( addr == 0xff24 )
{
int global_volume = data & 7;
int old_volume = square1.global_volume;
if ( old_volume != global_volume )
{
int any_enabled = false;
for ( int i = 0; i < osc_count; i++ )
{
Gb_Osc& osc = *oscs [i];
if ( osc.enabled )
{
if ( osc.last_amp )
{
int new_amp = osc.last_amp * global_volume / osc.global_volume;
if ( osc.output )
square_synth.offset( time, new_amp - osc.last_amp, osc.output );
osc.last_amp = new_amp;
}
any_enabled |= osc.volume;
}
osc.global_volume = global_volume;
}
if ( !any_enabled && square1.outputs [3] )
square_synth.offset( time, (global_volume - old_volume) * 15 * 2, square1.outputs [3] );
}
}
else if ( addr == 0xff25 || addr == 0xff26 )
{
int mask = (regs [0xff26 - start_addr] & 0x80) ? ~0 : 0;
int flags = regs [0xff25 - start_addr] & mask;
// left/right assignments
for ( int i = 0; i < osc_count; i++ )
{
Gb_Osc& osc = *oscs [i];
osc.enabled &= mask;
int bits = flags >> i;
Blip_Buffer* old_output = osc.output;
osc.output_select = (bits >> 3 & 2) | (bits & 1);
osc.output = osc.outputs [osc.output_select];
if ( osc.output != old_output && osc.last_amp )
{
if ( old_output )
square_synth.offset( time, -osc.last_amp, old_output );
osc.last_amp = 0;
}
}
}
else if ( addr >= 0xff30 )
{
int index = (addr & 0x0f) * 2;
wave.wave [index] = data >> 4;
wave.wave [index + 1] = data & 0x0f;
}
}
int Gb_Apu::read_register( gb_time_t time, gb_addr_t addr )
{
// function now takes actual address, i.e. 0xFFXX
require( start_addr <= addr && addr <= end_addr );
run_until( time );
int data = regs [addr - start_addr];
if ( addr == 0xff26 )
{
data &= 0xf0;
for ( int i = 0; i < osc_count; i++ )
{
const Gb_Osc& osc = *oscs [i];
if ( osc.enabled && (osc.length || !osc.length_enabled) )
data |= 1 << i;
}
}
return data;
}
| C++ |
// Blip_Synth and Blip_Wave are waveform transition synthesizers for adding
// waveforms to a Blip_Buffer.
// Blip_Buffer 0.3.4. Copyright (C) 2003-2005 Shay Green. GNU LGPL license.
#ifndef BLIP_SYNTH_H
#define BLIP_SYNTH_H
#ifndef BLIP_BUFFER_H
#include "Blip_Buffer.h"
#endif
// Quality level. Higher levels are slower, and worse in a few cases.
// Use blip_good_quality as a starting point.
const int blip_low_quality = 1;
const int blip_med_quality = 2;
const int blip_good_quality = 3;
const int blip_high_quality = 4;
// Blip_Synth is a transition waveform synthesizer which adds band-limited
// offsets (transitions) into a Blip_Buffer. For a simpler interface, use
// Blip_Wave (below).
//
// Range specifies the greatest expected offset that will occur. For a
// waveform that goes between +amp and -amp, range should be amp * 2 (half
// that if it only goes between +amp and 0). When range is large, a higher
// accuracy scheme is used; to force this even when range is small, pass
// the negative of range (i.e. -range).
template<int quality,int range>
class Blip_Synth {
BOOST_STATIC_ASSERT( 1 <= quality && quality <= 5 );
BOOST_STATIC_ASSERT( -32768 <= range && range <= 32767 );
enum {
abs_range = (range < 0) ? -range : range,
fine_mode = (range > 512 || range < 0),
width = (quality < 5 ? quality * 4 : Blip_Buffer::widest_impulse_),
res = 1 << blip_res_bits_,
impulse_size = width / 2 * (fine_mode + 1),
base_impulses_size = width / 2 * (res / 2 + 1),
fine_bits = (fine_mode ? (abs_range <= 64 ? 2 : abs_range <= 128 ? 3 :
abs_range <= 256 ? 4 : abs_range <= 512 ? 5 : abs_range <= 1024 ? 6 :
abs_range <= 2048 ? 7 : 8) : 0)
};
blip_pair_t_ impulses [impulse_size * res * 2 + base_impulses_size];
Blip_Impulse_ impulse;
void init() { impulse.init( impulses, width, res, fine_bits ); }
public:
Blip_Synth() { init(); }
Blip_Synth( double volume ) { init(); this->volume( volume ); }
// Configure low-pass filter (see notes.txt). Not optimized for real-time control
void treble_eq( const blip_eq_t& eq ) { impulse.treble_eq( eq ); }
// Set volume of a transition at amplitude 'range' by setting volume_unit
// to v / range
void volume( double v ) { impulse.volume_unit( v * (1.0 / abs_range) ); }
// Set base volume unit of transitions, where 1.0 is a full swing between the
// positive and negative extremes. Not optimized for real-time control.
void volume_unit( double unit ) { impulse.volume_unit( unit ); }
// Default Blip_Buffer used for output when none is specified for a given call
Blip_Buffer* output() const { return impulse.buf; }
void output( Blip_Buffer* b ) { impulse.buf = b; }
// Add an amplitude offset (transition) with a magnitude of delta * volume_unit
// into the specified buffer (default buffer if none specified) at the
// specified source time. Delta can be positive or negative. To increase
// performance by inlining code at the call site, use offset_inline().
void offset( blip_time_t, int delta, Blip_Buffer* ) const;
void offset_resampled( blip_resampled_time_t, int delta, Blip_Buffer* ) const;
void offset_resampled( blip_resampled_time_t t, int o ) const {
offset_resampled( t, o, impulse.buf );
}
void offset( blip_time_t t, int delta ) const {
offset( t, delta, impulse.buf );
}
void offset_inline( blip_time_t time, int delta, Blip_Buffer* buf ) const {
offset_resampled( time * buf->factor_ + buf->offset_, delta, buf );
}
void offset_inline( blip_time_t time, int delta ) const {
offset_inline( time, delta, impulse.buf );
}
};
// Blip_Wave is a synthesizer for adding a *single* waveform to a Blip_Buffer.
// A wave is built from a series of delays and new amplitudes. This provides a
// simpler interface than Blip_Synth, nothing more.
template<int quality,int range>
class Blip_Wave {
Blip_Synth<quality,range> synth;
blip_time_t time_;
int last_amp;
void init() { time_ = 0; last_amp = 0; }
public:
// Start wave at time 0 and amplitude 0
Blip_Wave() { init(); }
Blip_Wave( double volume ) { init(); this->volume( volume ); }
// See Blip_Synth for description
void volume( double v ) { synth.volume( v ); }
void volume_unit( double v ) { synth.volume_unit( v ); }
void treble_eq( const blip_eq_t& eq){ synth.treble_eq( eq ); }
Blip_Buffer* output() const { return synth.output(); }
void output( Blip_Buffer* b ) { synth.output( b ); if ( !b ) time_ = last_amp = 0; }
// Current time in frame
blip_time_t time() const { return time_; }
void time( blip_time_t t ) { time_ = t; }
// Current amplitude of wave
int amplitude() const { return last_amp; }
void amplitude( int );
// Move forward by 't' time units
void delay( blip_time_t t ) { time_ += t; }
// End time frame of specified duration. Localize time to new frame.
// If wave hadn't been run to end of frame, start it at beginning of new frame.
void end_frame( blip_time_t duration )
{
time_ -= duration;
if ( time_ < 0 )
time_ = 0;
}
};
// End of public interface
template<int quality,int range>
void Blip_Wave<quality,range>::amplitude( int amp ) {
int delta = amp - last_amp;
last_amp = amp;
synth.offset_inline( time_, delta );
}
template<int quality,int range>
inline void Blip_Synth<quality,range>::offset_resampled( blip_resampled_time_t time,
int delta, Blip_Buffer* blip_buf ) const
{
typedef blip_pair_t_ pair_t;
unsigned sample_index = (time >> BLIP_BUFFER_ACCURACY) & ~1;
assert(( "Blip_Synth/Blip_wave: Went past end of buffer",
sample_index < blip_buf->buffer_size_ ));
enum { const_offset = Blip_Buffer::widest_impulse_ / 2 - width / 2 };
pair_t* buf = (pair_t*) &blip_buf->buffer_ [const_offset + sample_index];
enum { shift = BLIP_BUFFER_ACCURACY - blip_res_bits_ };
enum { mask = res * 2 - 1 };
const pair_t* imp = &impulses [((time >> shift) & mask) * impulse_size];
pair_t offset = impulse.offset * delta;
if ( !fine_bits )
{
// normal mode
for ( int n = width / 4; n; --n )
{
pair_t t0 = buf [0] - offset;
pair_t t1 = buf [1] - offset;
t0 += imp [0] * delta;
t1 += imp [1] * delta;
imp += 2;
buf [0] = t0;
buf [1] = t1;
buf += 2;
}
}
else
{
// fine mode
enum { sub_range = 1 << fine_bits };
delta += sub_range / 2;
int delta2 = (delta & (sub_range - 1)) - sub_range / 2;
delta >>= fine_bits;
for ( int n = width / 4; n; --n )
{
pair_t t0 = buf [0] - offset;
pair_t t1 = buf [1] - offset;
t0 += imp [0] * delta2;
t0 += imp [1] * delta;
t1 += imp [2] * delta2;
t1 += imp [3] * delta;
imp += 4;
buf [0] = t0;
buf [1] = t1;
buf += 2;
}
}
}
template<int quality,int range>
void Blip_Synth<quality,range>::offset( blip_time_t time, int delta, Blip_Buffer* buf ) const {
offset_resampled( time * buf->factor_ + buf->offset_, delta, buf );
}
#endif
| C++ |
// Gb_Snd_Emu 0.1.4. http://www.slack.net/~ant/libs/
#include "Basic_Gb_Apu.h"
/* Copyright (C) 2003-2005 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details. You should have received a copy of the GNU Lesser General
Public License along with this module; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
gb_time_t const frame_length = 70224;
Basic_Gb_Apu::Basic_Gb_Apu()
{
time = 0;
// Adjust frequency equalization to make it sound like a tiny speaker
apu.treble_eq( -20.0 ); // lower values muffle it more
buf.bass_freq( 461 ); // higher values simulate smaller speaker
}
Basic_Gb_Apu::~Basic_Gb_Apu()
{
}
blargg_err_t Basic_Gb_Apu::set_sample_rate( long rate )
{
apu.output( buf.center(), buf.left(), buf.right() );
buf.clock_rate( 4194304 );
return buf.set_sample_rate( rate );
}
void Basic_Gb_Apu::write_register( gb_addr_t addr, int data )
{
apu.write_register( clock(), addr, data );
}
int Basic_Gb_Apu::read_register( gb_addr_t addr )
{
return apu.read_register( clock(), addr );
}
void Basic_Gb_Apu::end_frame()
{
time = 0;
bool stereo = apu.end_frame( frame_length );
buf.end_frame( frame_length, stereo );
}
long Basic_Gb_Apu::samples_avail() const
{
return buf.samples_avail();
}
long Basic_Gb_Apu::read_samples( sample_t* out, long count )
{
return buf.read_samples( out, count );
}
| C++ |
// Use Basic_Gb_Apu to play random tones. Writes output to sound file "out.wav".
#include "Basic_Gb_Apu.h"
#include "Wave_Writer.h"
#include <stdlib.h>
static Basic_Gb_Apu apu;
// "emulate" 1/60 second of sound
static void emulate_frame()
{
static int delay;
if ( --delay <= 0 )
{
delay = 12;
// Start a new random tone
int chan = rand() & 0x11;
apu.write_register( 0xff26, 0x80 );
apu.write_register( 0xff25, chan ? chan : 0x11 );
apu.write_register( 0xff11, 0x80 );
int freq = (rand() & 0x3ff) + 0x300;
apu.write_register( 0xff13, freq & 0xff );
apu.write_register( 0xff12, 0xf1 );
apu.write_register( 0xff14, (freq >> 8) | 0x80 );
}
// Generate 1/60 second of sound into APU's sample buffer
apu.end_frame();
}
int main( int argc, char** argv )
{
long const sample_rate = 44100;
// Set sample rate and check for out of memory error
if ( apu.set_sample_rate( sample_rate ) )
return EXIT_FAILURE;
// Generate a few seconds of sound into wave file
Wave_Writer wave( sample_rate );
wave.stereo( true );
for ( int n = 60 * 4; n--; )
{
// Simulate emulation of 1/60 second frame
emulate_frame();
// Samples from the frame can now be read out of the apu, or
// allowed to accumulate and read out later. Use samples_avail()
// to find out how many samples are currently in the buffer.
int const buf_size = 2048;
static blip_sample_t buf [buf_size];
// Play whatever samples are available
long count = apu.read_samples( buf, buf_size );
wave.write( buf, count );
}
return 0;
}
| C++ |
// Gb_Snd_Emu 0.1.4. http://www.slack.net/~ant/
#include "Sound_Queue.h"
#include <assert.h>
#include <string.h>
/* Copyright (C) 2005 by Shay Green. Permission is hereby granted, free of
charge, to any person obtaining a copy of this software module and associated
documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the
following conditions: The above copyright notice and this permission notice
shall be included in all copies or substantial portions of the Software. THE
SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
// Return current SDL_GetError() string, or str if SDL didn't have a string
static const char* sdl_error( const char* str )
{
const char* sdl_str = SDL_GetError();
if ( sdl_str && *sdl_str )
str = sdl_str;
return str;
}
Sound_Queue::Sound_Queue()
{
bufs = NULL;
free_sem = NULL;
sound_open = false;
}
Sound_Queue::~Sound_Queue()
{
stop();
}
const char* Sound_Queue::start( long sample_rate, int chan_count )
{
assert( !bufs ); // can only be initialized once
write_buf = 0;
write_pos = 0;
read_buf = 0;
bufs = new sample_t [(long) buf_size * buf_count];
if ( !bufs )
return "Out of memory";
currently_playing_ = bufs;
free_sem = SDL_CreateSemaphore( buf_count - 1 );
if ( !free_sem )
return sdl_error( "Couldn't create semaphore" );
SDL_AudioSpec as;
as.freq = sample_rate;
as.format = AUDIO_S16SYS;
as.channels = chan_count;
as.silence = 0;
as.samples = buf_size / chan_count;
as.size = 0;
as.callback = fill_buffer_;
as.userdata = this;
if ( SDL_OpenAudio( &as, NULL ) < 0 )
return sdl_error( "Couldn't open SDL audio" );
SDL_PauseAudio( false );
sound_open = true;
return NULL;
}
void Sound_Queue::stop()
{
if ( sound_open )
{
sound_open = false;
SDL_PauseAudio( true );
SDL_CloseAudio();
}
if ( free_sem )
{
SDL_DestroySemaphore( free_sem );
free_sem = NULL;
}
delete [] bufs;
bufs = NULL;
}
int Sound_Queue::sample_count() const
{
int buf_free = SDL_SemValue( free_sem ) * buf_size + (buf_size - write_pos);
return buf_size * buf_count - buf_free;
}
inline Sound_Queue::sample_t* Sound_Queue::buf( int index )
{
assert( (unsigned) index < buf_count );
return bufs + (long) index * buf_size;
}
void Sound_Queue::write( const sample_t* in, int count )
{
while ( count )
{
int n = buf_size - write_pos;
if ( n > count )
n = count;
memcpy( buf( write_buf ) + write_pos, in, n * sizeof (sample_t) );
in += n;
write_pos += n;
count -= n;
if ( write_pos >= buf_size )
{
write_pos = 0;
write_buf = (write_buf + 1) % buf_count;
SDL_SemWait( free_sem );
}
}
}
void Sound_Queue::fill_buffer( Uint8* out, int count )
{
if ( SDL_SemValue( free_sem ) < buf_count - 1 )
{
currently_playing_ = buf( read_buf );
memcpy( out, buf( read_buf ), count );
read_buf = (read_buf + 1) % buf_count;
SDL_SemPost( free_sem );
}
else
{
memset( out, 0, count );
}
}
void Sound_Queue::fill_buffer_( void* user_data, Uint8* out, int count )
{
((Sound_Queue*) user_data)->fill_buffer( out, count );
}
| C++ |
// WAVE sound file writer for recording 16-bit output during program development
// Copyright (C) 2003-2004 Shay Green. MIT license.
#ifndef WAVE_WRITER_HPP
#define WAVE_WRITER_HPP
#include <stddef.h>
#include <stdio.h>
class Wave_Writer {
public:
typedef short sample_t;
// Create sound file with given sample rate (in Hz) and filename.
// Exit program if there's an error.
Wave_Writer( long sample_rate, char const* filename = "out.wav" );
// Enable stereo output
void stereo( int );
// Append 'count' samples to file. Use every 'skip'th source sample; allows
// one channel of stereo sample pairs to be written by specifying a skip of 2.
void write( const sample_t*, long count, int skip = 1 );
// Append 'count' floating-point samples to file. Use every 'skip'th source sample;
// allows one channel of stereo sample pairs to be written by specifying a skip of 2.
void write( const float*, long count, int skip = 1 );
// Number of samples written so far
long sample_count() const;
// Write sound file header and close file. If no samples were written,
// delete file.
~Wave_Writer();
// End of public interface
private:
enum { buf_size = 32768 * 2 };
unsigned char* buf;
FILE* file;
long sample_count_;
long rate;
long buf_pos;
int chan_count;
void flush();
};
inline void Wave_Writer::stereo( int s ) {
chan_count = s ? 2 : 1;
}
inline long Wave_Writer::sample_count() const {
return sample_count_;
}
#endif
| C++ |
// Simple sound queue for synchronous sound handling in SDL
// Copyright (C) 2005 Shay Green. MIT license.
#ifndef SOUND_QUEUE_H
#define SOUND_QUEUE_H
#include "SDL.h"
// Simple SDL sound wrapper that has a synchronous interface
class Sound_Queue {
public:
Sound_Queue();
~Sound_Queue();
// Initialize with specified sample rate and channel count.
// Returns NULL on success, otherwise error string.
const char* start( long sample_rate, int chan_count = 1 );
// Number of samples in buffer waiting to be played
int sample_count() const;
// Write samples to buffer and block until enough space is available
typedef short sample_t;
void write( const sample_t*, int count );
// Pointer to samples currently playing (for showing waveform display)
sample_t const* currently_playing() const { return currently_playing_; }
// Stop audio output
void stop();
private:
enum { buf_size = 4096 };
enum { buf_count = 3 };
sample_t* volatile bufs;
SDL_sem* volatile free_sem;
sample_t* volatile currently_playing_;
int volatile read_buf;
int write_buf;
int write_pos;
bool sound_open;
sample_t* buf( int index );
void fill_buffer( Uint8*, int );
static void fill_buffer_( void*, Uint8*, int );
};
#endif
| C++ |
// Use Sound_Queue to play APU sound using SDL
#include "Basic_Gb_Apu.h"
#include "Sound_Queue.h"
#include "SDL.h"
#include <stdlib.h>
static Basic_Gb_Apu apu;
// "emulate" 1/60 second of sound
static void emulate_frame()
{
static int delay;
if ( --delay <= 0 )
{
delay = 12;
// Start a new random tone
int chan = rand() & 0x11;
apu.write_register( 0xff26, 0x80 );
apu.write_register( 0xff25, chan ? chan : 0x11 );
apu.write_register( 0xff11, 0x80 );
int freq = (rand() & 0x3ff) + 0x300;
apu.write_register( 0xff13, freq & 0xff );
apu.write_register( 0xff12, 0xf1 );
apu.write_register( 0xff14, (freq >> 8) | 0x80 );
}
// Generate 1/60 second of sound into APU's sample buffer
apu.end_frame();
}
static void handle_error( const char* str )
{
if ( str )
{
fprintf( stderr, "Error: %s\n", str );
exit( EXIT_FAILURE );
}
}
int main( int argc, char** argv )
{
long const sample_rate = 44100;
if ( SDL_Init( SDL_INIT_AUDIO ) < 0 )
return EXIT_FAILURE;
atexit( SDL_Quit );
// Set sample rate and check for out of memory error
handle_error( apu.set_sample_rate( sample_rate ) );
// Generate a few seconds of sound and play using SDL
Sound_Queue sound;
handle_error( sound.start( sample_rate, 2 ) );
for ( int n = 60 * 4; n--; )
{
// Simulate emulation of 1/60 second frame
emulate_frame();
// Samples from the frame can now be read out of the apu, or
// allowed to accumulate and read out later. Use samples_avail()
// to find out how many samples are currently in the buffer.
int const buf_size = 2048;
static blip_sample_t buf [buf_size];
// Play whatever samples are available
long count = apu.read_samples( buf, buf_size );
sound.write( buf, count );
}
return 0;
}
| C++ |
// Boost substitute. For full boost library see http://boost.org
#ifndef BOOST_CSTDINT_HPP
#define BOOST_CSTDINT_HPP
#if BLARGG_USE_NAMESPACE
#include <climits>
#else
#include <limits.h>
#endif
BLARGG_BEGIN_NAMESPACE( boost )
#if UCHAR_MAX != 0xFF || SCHAR_MAX != 0x7F
# error "No suitable 8-bit type available"
#endif
typedef unsigned char uint8_t;
typedef signed char int8_t;
#if USHRT_MAX != 0xFFFF
# error "No suitable 16-bit type available"
#endif
typedef short int16_t;
typedef unsigned short uint16_t;
#if ULONG_MAX == 0xFFFFFFFF
typedef long int32_t;
typedef unsigned long uint32_t;
#elif UINT_MAX == 0xFFFFFFFF
typedef int int32_t;
typedef unsigned int uint32_t;
#else
# error "No suitable 32-bit type available"
#endif
BLARGG_END_NAMESPACE
#endif
| C++ |
// Boost substitute. For full boost library see http://boost.org
#ifndef BOOST_STATIC_ASSERT_HPP
#define BOOST_STATIC_ASSERT_HPP
#if defined (_MSC_VER) && _MSC_VER <= 1200
// MSVC6 can't handle the ##line concatenation
#define BOOST_STATIC_ASSERT( expr ) struct { int n [1 / ((expr) ? 1 : 0)]; }
#else
#define BOOST_STATIC_ASSERT3( expr, line ) \
typedef int boost_static_assert_##line [1 / ((expr) ? 1 : 0)]
#define BOOST_STATIC_ASSERT2( expr, line ) BOOST_STATIC_ASSERT3( expr, line )
#define BOOST_STATIC_ASSERT( expr ) BOOST_STATIC_ASSERT2( expr, __LINE__ )
#endif
#endif
| C++ |
// Boost substitute. For full boost library see http://boost.org
#ifndef BOOST_CONFIG_HPP
#define BOOST_CONFIG_HPP
#define BOOST_MINIMAL 1
#define BLARGG_BEGIN_NAMESPACE( name )
#define BLARGG_END_NAMESPACE
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __LOGQUEUE_H__
#define __LOGQUEUE_H__
#include "Registers.h"
struct ItemLog {
std::string prefix;
Registers * regs;
std::string suffix;
ItemLog * next;
ItemLog * prev;
};
//Esta clase se encarga de guardar los valores de los registros hasta un
//número máximo. Cuando se alcanza dicho máximo y antes de insertar uno
//nuevo, se borra el más antiguo. Es decir, tiene el funcionamiento de un cola.
//El más nuevo será el apuntado por last y el más viejo por first.
// item1 -> item2 -> item3
// ^ ^
// first last
class QueueLog
{
private:
int maxItems;
int numItems;
ItemLog * first;
ItemLog * last;
public:
QueueLog(int maxItems);
~QueueLog();
void Enqueue(std::string prefix, Registers * regs, std::string suffix);
void Save(std::string path);
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __CARTRIDGE_H__
#define __CARTRIDGE_H__
#include <string>
#include "Def.h"
#define CART_NAME 0x0134
#define CART_TYPE 0x0147
#define CART_ROM_SIZE 0x0148
#define CART_RAM_SIZE 0x0149
class Cartridge
{
private:
unsigned long _romSize;
std::string _name;
bool _isLoaded;
BYTE * _memCartridge;
BYTE (*ptrRead)(WORD);
void (*ptrWrite)(WORD, BYTE);
void CheckCartridge(std::string batteriesPath="");
int CheckRomSize(int numHeaderSize, int fileSize);
public:
Cartridge(std::string fileName, std::string batteriesPath="");
Cartridge(BYTE * cartridgeBuffer, unsigned long size, std::string batteriesPath="");
~Cartridge();
BYTE *GetData();
unsigned int GetSize();
std::string GetName();
bool IsLoaded();
inline BYTE Read(WORD direction) { return ptrRead(direction); };
inline void Write(WORD direction, BYTE value) { ptrWrite(direction, value); };
void Print(int beg, int end);
void SaveMBC(std::ofstream * file);
void LoadMBC(std::ifstream * file);
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include "Memory.h"
#include "Cartridge.h"
using namespace std;
Memory::Memory(Sound * s)
{
this->c = NULL;
this->s = s;
ResetMem();
}
Memory::~Memory()
{
}
Memory *Memory::GetPtrMemory() { return this; }
void Memory::LoadCartridge(Cartridge *c)
{
this->c = c;
}
void Memory::ResetMem()
{
/*for (WORD i=0; i<(SIZE_MEM - 1); i++ )
memory[i] = 0x00;*/
memset(&memory, 0x00, SIZE_MEM);
memory[TIMA] = 0x00; //TIMA
memory[TMA] = 0x00; //TMA
memory[TAC] = 0x00; //TAC
if (s)
{
s->WriteRegister(NR10, 0x80); //NR10
s->WriteRegister(NR11, 0xBF); //NR11
s->WriteRegister(NR12, 0xF3); //NR12
s->WriteRegister(NR14, 0xBF); //NR14
s->WriteRegister(NR21, 0x3F); //NR21
s->WriteRegister(NR22, 0x00); //NR22
s->WriteRegister(NR24, 0xBF); //NR24
s->WriteRegister(NR30, 0x7F); //NR30
s->WriteRegister(NR31, 0xFF); //NR31
s->WriteRegister(NR32, 0x9F); //NR32
s->WriteRegister(NR33, 0xBF); //NR33
s->WriteRegister(NR41, 0xFF); //NR41
s->WriteRegister(NR42, 0x00); //NR42
s->WriteRegister(NR43, 0x00); //NR43
s->WriteRegister(NR30, 0xBF); //NR30
s->WriteRegister(NR50, 0x77); //NR50
s->WriteRegister(NR51, 0xF3); //NR51
s->WriteRegister(NR52, 0xF1); //NR52
}
memory[LCDC] = 0x91; //LCDC
memory[SCY] = 0x00; //SCY
memory[SCX] = 0x00; //SCX
memory[LYC] = 0x00; //LYC
memory[BGP] = 0xFC; //BGP
memory[OBP0] = 0xFF; //OBP0
memory[OBP1] = 0xFF; //OBP1
memory[WY] = 0x00; //WY
memory[WX] = 0x00; //WX
memory[IE] = 0x00; //IE
memory[STAT] = 0x02; //LCD_STAT
}
void Memory::MemW(WORD direction, BYTE value)
{
if ((direction < 0x8000) || ((direction >= 0xA000)&&(direction < 0xC000)))
{
c->Write(direction, value);
return;
}
else if ((direction >= 0xC000) && (direction < 0xDE00))//C000-DDFF
memory[direction + 0x2000] = value;
else if ((direction >= 0xE000) && (direction < 0xFE00))//E000-FDFF
memory[direction - 0x2000] = value;
else if ((direction >= 0xFF10) && (direction <= 0xFF3F))
{
if(s)
s->WriteRegister(direction, value);
}
else
{
switch (direction)
{
case DMA:
DmaTransfer(value);
break;
case P1:
BYTE oldP1;
oldP1 = memory[P1];
value = (value & 0xF0) | (oldP1 & ~0xF0);
value = PadUpdateInput(value);
if ((value != oldP1) && ((value & 0x0F) != 0x0F))
{
//Debe producir una interrupcion
memory[IF] |= 0x10;
}
break;
case STAT: value = (value & ~0x07) | (memory[STAT] & 0x07); break;
case LY:
case DIV: value = 0; break;
}
}
memory[direction] = value;
}
void Memory::DmaTransfer(BYTE direction)
{
BYTE i;
for (i=0; i<0xA0; i++)
MemWNoCheck(0xFE00 + i, MemR((direction << 8) + i));
}
void Memory::SaveMemory(ofstream * file)
{
file->write((char *)&memory[0x8000], 0x8000);
}
void Memory::LoadMemory(ifstream * file)
{
file->read((char *)&memory[0x8000], 0x8000);
if (s)
{
for (int dir=0xFF10; dir<0xFF40; dir++)
s->WriteRegister(dir, memory[dir]);
}
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MAINAPP_H__
#define __MAINAPP_H__
#include <wx/wx.h>
#include "MainFrame.h"
#undef main
/*******************************************************************************
// MainApp Class
*******************************************************************************/
class MainApp : public wxApp {
DECLARE_CLASS(MainApp)
private:
MainFrame *frame;
public:
/**
* Called to initialize this MainApp.
*
* @return true if initialization succeeded; false otherwise.
*/
bool OnInit();
/**
* Called to run this MainApp.
*
* @return The status code (0 if good, non-0 if bad).
*/
int OnRun();
/**
* Called when this MainApp is ready to exit.
*
* @return The exit code.
*/
int OnExit();
void MacOpenFile(const wxString &fileName);
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <wx/artprov.h>
#include <wx/bookctrl.h>
#include <wx/spinctrl.h>
#include <wx/config.h>
#include <wx/fileconf.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include "SettingsDialog.h"
#include "IDControls.h"
#include "InputTextCtrl.h"
#include "../Pad.h"
#include "Xpm/preferences1.xpm"
IMPLEMENT_CLASS(SettingsDialog, wxPropertySheetDialog)
BEGIN_EVENT_TABLE(SettingsDialog, wxPropertySheetDialog)
END_EVENT_TABLE()
SettingsDialog::SettingsDialog(wxWindow* win)
{
settings = SettingsGetCopy();
m_imageList = NULL;
bool useToolBook = false;
int sheetStyle = wxPROPSHEET_SHRINKTOFIT;
if (useToolBook)
{
sheetStyle |= wxPROPSHEET_BUTTONTOOLBOOK;
//SetSheetInnerBorder(0);
//SetSheetOuterBorder(0);
wxBitmap preferences1(preferences1_xpm);
// create a dummy image list with a few icons
const wxSize imageSize(32, 32);
m_imageList = new wxImageList(imageSize.GetWidth(), imageSize.GetHeight());
m_imageList->Add(preferences1);
m_imageList->Add(wxArtProvider::GetIcon(wxART_QUESTION, wxART_OTHER, imageSize));
}
SetSheetStyle(sheetStyle);
Create(win, wxID_ANY, _("Preferences"));
wxBookCtrlBase* notebook = GetBookCtrl();
if (useToolBook)
notebook->SetImageList(m_imageList);
CreateButtons(wxOK | wxCANCEL);
wxPanel* generalSettings = CreateGeneralSettingsPage(notebook);
wxPanel* soundSettings = CreateSoundSettingsPage(notebook);
wxPanel* inputSettings = CreateInputSettingsPage(notebook);
notebook->AddPage(generalSettings, _("General"), true);
notebook->AddPage(soundSettings, _("Sound"), false);
notebook->AddPage(inputSettings, _("Input"), false);
LayoutDialog();
}
SettingsDialog::~SettingsDialog()
{
if (m_imageList)
delete m_imageList;
}
/*! * Transfer data to the window */
bool SettingsDialog::TransferDataToWindow()
{
settings = SettingsGetCopy();
wxRadioBox* greenscaleCtrl = (wxRadioBox*) FindWindow(ID_GREENSCALE);
wxChoice* winZoomCtrl = (wxChoice*) FindWindow(ID_WINZOOM);
wxCheckBox* soundEnabledCtrl = (wxCheckBox*) FindWindow(ID_SOUND_ENABLED);
wxChoice* soundSRCtrl = (wxChoice*) FindWindow(ID_SOUND_SR);
InputTextCtrl* upCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_UP);
InputTextCtrl* downCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_DOWN);
InputTextCtrl* leftCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_LEFT);
InputTextCtrl* rightCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_RIGHT);
InputTextCtrl* aCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_A);
InputTextCtrl* bCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_B);
InputTextCtrl* selectCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_SELECT);
InputTextCtrl* startCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_START);
greenscaleCtrl->SetSelection(settings.greenScale);
winZoomCtrl->SetSelection(settings.windowZoom - 1);
soundEnabledCtrl->SetValue(settings.soundEnabled);
int sampleRates[] = { 22050, 32000, 44100, 48000 };
int idSampleRate = 2;
for (int i=0; i<4; i++)
{
if (settings.soundSampleRate == sampleRates[i])
idSampleRate = i;
}
soundSRCtrl->SetSelection(idSampleRate);
upCtrl->OnChangeKey( settings.padKeys[0]);
downCtrl->OnChangeKey( settings.padKeys[1]);
leftCtrl->OnChangeKey( settings.padKeys[2]);
rightCtrl->OnChangeKey( settings.padKeys[3]);
aCtrl->OnChangeKey( settings.padKeys[4]);
bCtrl->OnChangeKey( settings.padKeys[5]);
selectCtrl->OnChangeKey(settings.padKeys[6]);
startCtrl->OnChangeKey( settings.padKeys[7]);
return true;
}
/*! * Transfer data from the window */
bool SettingsDialog::TransferDataFromWindow()
{
wxRadioBox* greenscaleCtrl = (wxRadioBox*) FindWindow(ID_GREENSCALE);
wxChoice* winZoomCtrl = (wxChoice*) FindWindow(ID_WINZOOM);
wxCheckBox* soundEnabledCtrl = (wxCheckBox*) FindWindow(ID_SOUND_ENABLED);
wxChoice* soundSRCtrl = (wxChoice*) FindWindow(ID_SOUND_SR);
InputTextCtrl* upCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_UP);
InputTextCtrl* downCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_DOWN);
InputTextCtrl* leftCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_LEFT);
InputTextCtrl* rightCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_RIGHT);
InputTextCtrl* aCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_A);
InputTextCtrl* bCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_B);
InputTextCtrl* selectCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_SELECT);
InputTextCtrl* startCtrl = (InputTextCtrl*) FindWindow(ID_TEXTCTRL_START);
settings.greenScale = greenscaleCtrl->GetSelection();
settings.windowZoom = winZoomCtrl->GetSelection()+1;
settings.soundEnabled = soundEnabledCtrl->GetValue();
int sampleRates[] = { 22050, 32000, 44100, 48000 };
int idSampleRate = soundSRCtrl->GetSelection();
settings.soundSampleRate = sampleRates[idSampleRate];
settings.padKeys[0] = upCtrl->keyCode;
settings.padKeys[1] = downCtrl->keyCode;
settings.padKeys[2] = leftCtrl->keyCode;
settings.padKeys[3] = rightCtrl->keyCode;
settings.padKeys[4] = aCtrl->keyCode;
settings.padKeys[5] = bCtrl->keyCode;
settings.padKeys[6] = selectCtrl->keyCode;
settings.padKeys[7] = startCtrl->keyCode;
SaveToFile();
return true;
}
wxPanel* SettingsDialog::CreateGeneralSettingsPage(wxWindow* parent)
{
wxPanel* panel = new wxPanel(parent, wxID_ANY);
wxStaticText * grayGreenLabel = new wxStaticText(panel, wxID_ANY, wxT("Color palette:"));
wxString grayGreenChoices[2];
grayGreenChoices[0] = wxT("Grayscale");
grayGreenChoices[1] = wxT("Greenscale");
wxRadioBox* grayGreenRadioBox = new wxRadioBox(panel, ID_GREENSCALE, wxT(""),
wxDefaultPosition, wxDefaultSize, 2, grayGreenChoices, 1, wxRA_SPECIFY_COLS);
wxStaticText * winZoomLabel = new wxStaticText(panel, wxID_ANY, wxT("Window size:"));
wxChoice* winZoomChoice = new wxChoice(panel, ID_WINZOOM);
winZoomChoice->Append(wxT("1x"));
winZoomChoice->Append(wxT("2x"));
winZoomChoice->Append(wxT("3x"));
winZoomChoice->Append(wxT("4x"));
wxFlexGridSizer *grid = new wxFlexGridSizer(2, 3, 5);
grid->Add(grayGreenLabel, 0, wxUP, 7);
grid->Add(grayGreenRadioBox);
grid->Add(winZoomLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(winZoomChoice);
wxBoxSizer *topSizer = new wxBoxSizer( wxVERTICAL );
topSizer->Add(grid, 0, wxALL, 10);
panel->SetSizerAndFit(topSizer);
return panel;
}
wxPanel* SettingsDialog::CreateSoundSettingsPage(wxWindow* parent)
{
wxPanel* panel = new wxPanel(parent, wxID_ANY);
wxStaticText * enabledLabel = new wxStaticText(panel, wxID_ANY, wxT("Enabled:"));
wxCheckBox * enabledCheckBox = new wxCheckBox(panel, ID_SOUND_ENABLED, wxT(""));
enabledCheckBox->SetValue(true);
wxStaticText * sampleRateLabel = new wxStaticText(panel, wxID_ANY, wxT("Sample Rate:"));
wxChoice* sampleRateChoice = new wxChoice(panel, ID_SOUND_SR);
sampleRateChoice->Append(wxT("22050 Hz"));
sampleRateChoice->Append(wxT("32000 Hz"));
sampleRateChoice->Append(wxT("44100 Hz"));
sampleRateChoice->Append(wxT("48000 Hz"));
sampleRateChoice->SetSelection(0);
wxFlexGridSizer *grid = new wxFlexGridSizer(2, 3, 5);
grid->Add(enabledLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(enabledCheckBox);
grid->Add(sampleRateLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(sampleRateChoice);
wxBoxSizer *topSizer = new wxBoxSizer( wxVERTICAL );
topSizer->Add(grid, 0, wxALL, 10);
panel->SetSizerAndFit(topSizer);
return panel;
}
wxPanel* SettingsDialog::CreateInputSettingsPage(wxWindow* parent)
{
wxPanel* panel = new wxPanel(parent, wxID_ANY);
wxStaticText * upLabel = new wxStaticText(panel, wxID_ANY, wxT("Up:"));
InputTextCtrl * upTextCtrl = new InputTextCtrl(panel, ID_TEXTCTRL_UP);
wxStaticText * downLabel = new wxStaticText(panel, wxID_ANY, wxT("Down:"));
InputTextCtrl * downTextCtrl = new InputTextCtrl(panel, ID_TEXTCTRL_DOWN);
wxStaticText * leftLabel = new wxStaticText(panel, wxID_ANY, wxT("Left:"));
InputTextCtrl * leftTextCtrl = new InputTextCtrl(panel, ID_TEXTCTRL_LEFT);
wxStaticText * rightLabel = new wxStaticText(panel, wxID_ANY, wxT("Right:"));
InputTextCtrl * rightTextCtrl = new InputTextCtrl(panel, ID_TEXTCTRL_RIGHT);
wxStaticText * aLabel = new wxStaticText(panel, wxID_ANY, wxT("A:"));
InputTextCtrl * aTextCtrl = new InputTextCtrl(panel, ID_TEXTCTRL_A);
wxStaticText * bLabel = new wxStaticText(panel, wxID_ANY, wxT("B:"));
InputTextCtrl * bTextCtrl = new InputTextCtrl(panel, ID_TEXTCTRL_B);
wxStaticText * selectLabel = new wxStaticText(panel, wxID_ANY, wxT("Select:"));
InputTextCtrl * selectTextCtrl = new InputTextCtrl(panel, ID_TEXTCTRL_SELECT);
wxStaticText * startLabel = new wxStaticText(panel, wxID_ANY, wxT("Start:"));
InputTextCtrl * startTextCtrl = new InputTextCtrl(panel, ID_TEXTCTRL_START);
wxFlexGridSizer *grid = new wxFlexGridSizer(2, 3, 5);
grid->Add(upLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(upTextCtrl);
grid->Add(downLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(downTextCtrl);
grid->Add(leftLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(leftTextCtrl);
grid->Add(rightLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(rightTextCtrl);
grid->Add(aLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(aTextCtrl);
grid->Add(bLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(bTextCtrl);
grid->Add(selectLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(selectTextCtrl);
grid->Add(startLabel, 0, wxALL|wxALIGN_CENTER_VERTICAL, 0);
grid->Add(startTextCtrl);
wxBoxSizer * topSizer = new wxBoxSizer(wxVERTICAL);
topSizer->Add(0, 10);
topSizer->Add(grid, 0, wxRIGHT|wxLEFT, 30);
topSizer->Add(0, 10);
panel->SetSizerAndFit(topSizer);
return panel;
}
void SettingsDialog::SaveToFile(bool reloadSettings)
{
if (reloadSettings)
settings = SettingsGetCopy();
wxString configDir = wxStandardPaths::Get().GetUserDataDir();
if (!wxFileName::DirExists(configDir))
wxFileName::Mkdir(configDir, 0777, wxPATH_MKDIR_FULL);
wxFileName configPath(configDir, wxT("config.ini"));
// Guardar a disco
wxFileConfig fileConfig(wxT("gbpablog"), wxT("pablogasco"), configPath.GetFullPath());
fileConfig.Write(wxT("General/greenScale"), settings.greenScale);
fileConfig.Write(wxT("General/windowZoom"), settings.windowZoom);
fileConfig.Write(wxT("Sound/enabled"), settings.soundEnabled);
fileConfig.Write(wxT("Sound/sampleRate"), settings.soundSampleRate);
fileConfig.Write(wxT("Input/up"), settings.padKeys[0]);
fileConfig.Write(wxT("Input/down"), settings.padKeys[1]);
fileConfig.Write(wxT("Input/left"), settings.padKeys[2]);
fileConfig.Write(wxT("Input/right"), settings.padKeys[3]);
fileConfig.Write(wxT("Input/a"), settings.padKeys[4]);
fileConfig.Write(wxT("Input/b"), settings.padKeys[5]);
fileConfig.Write(wxT("Input/select"), settings.padKeys[6]);
fileConfig.Write(wxT("Input/start"), settings.padKeys[7]);
wxString auxString[10];
for (int i=0; i<10; i++)
{
auxString[i] = wxString(settings.recentRoms[i].c_str(), wxConvUTF8);
}
fileConfig.Write(wxT("RecentRoms/01"), auxString[0]);
fileConfig.Write(wxT("RecentRoms/02"), auxString[1]);
fileConfig.Write(wxT("RecentRoms/03"), auxString[2]);
fileConfig.Write(wxT("RecentRoms/04"), auxString[3]);
fileConfig.Write(wxT("RecentRoms/05"), auxString[4]);
fileConfig.Write(wxT("RecentRoms/06"), auxString[5]);
fileConfig.Write(wxT("RecentRoms/07"), auxString[6]);
fileConfig.Write(wxT("RecentRoms/08"), auxString[7]);
fileConfig.Write(wxT("RecentRoms/09"), auxString[8]);
fileConfig.Write(wxT("RecentRoms/10"), auxString[9]);
}
void SettingsDialog::LoadFromFile()
{
wxString configDir = wxStandardPaths::Get().GetUserDataDir();
wxFileName configPath(configDir, wxT("config.ini"));
// Cargar de disco
wxFileConfig fileConfig(wxT("gbpablog"), wxT("pablogasco"), configPath.GetFullPath());
fileConfig.Read(wxT("General/greenScale"), &settings.greenScale);
fileConfig.Read(wxT("General/windowZoom"), &settings.windowZoom);
fileConfig.Read(wxT("Sound/enabled"), &settings.soundEnabled);
fileConfig.Read(wxT("Sound/sampleRate"), &settings.soundSampleRate);
fileConfig.Read(wxT("Input/up"), &settings.padKeys[0]);
fileConfig.Read(wxT("Input/down"), &settings.padKeys[1]);
fileConfig.Read(wxT("Input/left"), &settings.padKeys[2]);
fileConfig.Read(wxT("Input/right"), &settings.padKeys[3]);
fileConfig.Read(wxT("Input/a"), &settings.padKeys[4]);
fileConfig.Read(wxT("Input/b"), &settings.padKeys[5]);
fileConfig.Read(wxT("Input/select"), &settings.padKeys[6]);
fileConfig.Read(wxT("Input/start"), &settings.padKeys[7]);
wxString auxString[10];
fileConfig.Read(wxT("RecentRoms/01"), &auxString[0]);
fileConfig.Read(wxT("RecentRoms/02"), &auxString[1]);
fileConfig.Read(wxT("RecentRoms/03"), &auxString[2]);
fileConfig.Read(wxT("RecentRoms/04"), &auxString[3]);
fileConfig.Read(wxT("RecentRoms/05"), &auxString[4]);
fileConfig.Read(wxT("RecentRoms/06"), &auxString[5]);
fileConfig.Read(wxT("RecentRoms/07"), &auxString[6]);
fileConfig.Read(wxT("RecentRoms/08"), &auxString[7]);
fileConfig.Read(wxT("RecentRoms/09"), &auxString[8]);
fileConfig.Read(wxT("RecentRoms/10"), &auxString[9]);
for (int i=0; i<10; i++)
{
settings.recentRoms[i] = auxString[i].mb_str();
}
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __SETTINGSDIALOG_H__
#define __SETTINGSDIALOG_H__
#include <wx/wx.h>
#include <wx/propdlg.h>
#include <wx/generic/propdlg.h>
#include <wx/imaglist.h>
#include "../Settings.h"
class SettingsDialog: public wxPropertySheetDialog
{
DECLARE_CLASS(SettingsDialog)
DECLARE_EVENT_TABLE()
private:
bool TransferDataToWindow();
bool TransferDataFromWindow();
wxPanel* CreateGeneralSettingsPage(wxWindow* parent);
wxPanel* CreateSoundSettingsPage(wxWindow* parent);
wxPanel* CreateInputSettingsPage(wxWindow* parent);
public:
SettingsDialog(wxWindow* parent);
~SettingsDialog();
void SaveToFile(bool reloadSettings=false);
void LoadFromFile();
Settings settings;
protected:
wxImageList* m_imageList;
};
#endif | C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InputTextCtrl.h"
IMPLEMENT_CLASS(InputTextCtrl, wxTextCtrl)
BEGIN_EVENT_TABLE(InputTextCtrl, wxTextCtrl)
EVT_KEY_DOWN(InputTextCtrl::OnKeyDown)
END_EVENT_TABLE()
wxString InputTextCtrl::keyNames[NUM_KEYNAMES];
bool InputTextCtrl::keyNamesInitialized = false;
void InputTextCtrl::InitializeKeyNames()
{
if (InputTextCtrl::keyNamesInitialized)
return;
for (int i=0; i<NUM_KEYNAMES; i++)
InputTextCtrl::keyNames[i] = wxT("");
/* ASCII */
/*
InputTextCtrl::keyNames['!'] = wxT("!");
InputTextCtrl::keyNames['\"'] = wxT("\"");
InputTextCtrl::keyNames['#'] = wxT("#");
InputTextCtrl::keyNames['$'] = wxT("$");
InputTextCtrl::keyNames['%'] = wxT("%");
InputTextCtrl::keyNames['&'] = wxT("&");
InputTextCtrl::keyNames['\''] = wxT("'");
InputTextCtrl::keyNames['('] = wxT("(");
InputTextCtrl::keyNames[')'] = wxT(")");
InputTextCtrl::keyNames['*'] = wxT("*");
InputTextCtrl::keyNames['+'] = wxT("+");
InputTextCtrl::keyNames[','] = wxT(",");
InputTextCtrl::keyNames['-'] = wxT("-");
InputTextCtrl::keyNames['.'] = wxT(".");
InputTextCtrl::keyNames['/'] = wxT("/");
*/
InputTextCtrl::keyNames['0'] = wxT("0");
InputTextCtrl::keyNames['1'] = wxT("1");
InputTextCtrl::keyNames['2'] = wxT("2");
InputTextCtrl::keyNames['3'] = wxT("3");
InputTextCtrl::keyNames['4'] = wxT("4");
InputTextCtrl::keyNames['5'] = wxT("5");
InputTextCtrl::keyNames['6'] = wxT("6");
InputTextCtrl::keyNames['7'] = wxT("7");
InputTextCtrl::keyNames['8'] = wxT("8");
InputTextCtrl::keyNames['9'] = wxT("9");
/*
InputTextCtrl::keyNames[':'] = wxT(":");
InputTextCtrl::keyNames[';'] = wxT(";");
InputTextCtrl::keyNames['<'] = wxT("<");
InputTextCtrl::keyNames['='] = wxT("=");
InputTextCtrl::keyNames['>'] = wxT(">");
InputTextCtrl::keyNames['?'] = wxT("?");
InputTextCtrl::keyNames['@'] = wxT("@");
*/
InputTextCtrl::keyNames['A'] = wxT("A");
InputTextCtrl::keyNames['B'] = wxT("B");
InputTextCtrl::keyNames['C'] = wxT("C");
InputTextCtrl::keyNames['D'] = wxT("D");
InputTextCtrl::keyNames['E'] = wxT("E");
InputTextCtrl::keyNames['F'] = wxT("F");
InputTextCtrl::keyNames['G'] = wxT("G");
InputTextCtrl::keyNames['H'] = wxT("H");
InputTextCtrl::keyNames['I'] = wxT("I");
InputTextCtrl::keyNames['J'] = wxT("J");
InputTextCtrl::keyNames['K'] = wxT("K");
InputTextCtrl::keyNames['L'] = wxT("L");
InputTextCtrl::keyNames['M'] = wxT("M");
InputTextCtrl::keyNames['N'] = wxT("N");
InputTextCtrl::keyNames['O'] = wxT("O");
InputTextCtrl::keyNames['P'] = wxT("P");
InputTextCtrl::keyNames['Q'] = wxT("Q");
InputTextCtrl::keyNames['R'] = wxT("R");
InputTextCtrl::keyNames['S'] = wxT("S");
InputTextCtrl::keyNames['T'] = wxT("T");
InputTextCtrl::keyNames['U'] = wxT("U");
InputTextCtrl::keyNames['V'] = wxT("V");
InputTextCtrl::keyNames['W'] = wxT("W");
InputTextCtrl::keyNames['X'] = wxT("X");
InputTextCtrl::keyNames['Y'] = wxT("Y");
InputTextCtrl::keyNames['Z'] = wxT("Z");
/*
InputTextCtrl::keyNames['['] = wxT("[");
InputTextCtrl::keyNames['\\'] = wxT("\\");
InputTextCtrl::keyNames[']'] = wxT("]");
InputTextCtrl::keyNames['^'] = wxT("^");
InputTextCtrl::keyNames['_'] = wxT("_");
InputTextCtrl::keyNames['`'] = wxT("`");
InputTextCtrl::keyNames['{'] = wxT("{");
InputTextCtrl::keyNames['|'] = wxT("|");
InputTextCtrl::keyNames['}'] = wxT("}");
InputTextCtrl::keyNames['~'] = wxT("~");
*/
/* NO ASCII */
InputTextCtrl::keyNames[WXK_BACK] = wxT("Backspace");
InputTextCtrl::keyNames[WXK_TAB] = wxT("Tab");
InputTextCtrl::keyNames[WXK_RETURN] = wxT("Return");
InputTextCtrl::keyNames[WXK_ESCAPE] = wxT("Escape");
InputTextCtrl::keyNames[WXK_SPACE] = wxT("Space");
InputTextCtrl::keyNames[WXK_DELETE] = wxT("Delete");
InputTextCtrl::keyNames[WXK_START] = wxT("Start");
InputTextCtrl::keyNames[WXK_LBUTTON] = wxT("Left Mouse Button");
InputTextCtrl::keyNames[WXK_RBUTTON] = wxT("Right Mouse Button");
InputTextCtrl::keyNames[WXK_CANCEL] = wxT("Control-Break");
InputTextCtrl::keyNames[WXK_MBUTTON] = wxT("Middle Mouse Button");
InputTextCtrl::keyNames[WXK_CLEAR] = wxT("Clear");
InputTextCtrl::keyNames[WXK_SHIFT] = wxT("Shift");
InputTextCtrl::keyNames[WXK_ALT] = wxT("Alt");
InputTextCtrl::keyNames[WXK_CONTROL] = wxT("Control");
InputTextCtrl::keyNames[WXK_MENU] = wxT("Menu");
InputTextCtrl::keyNames[WXK_PAUSE] = wxT("Pause");
InputTextCtrl::keyNames[WXK_CAPITAL] = wxT("CapsLock");
InputTextCtrl::keyNames[WXK_END] = wxT("End");
InputTextCtrl::keyNames[WXK_HOME] = wxT("Home");
InputTextCtrl::keyNames[WXK_LEFT] = wxT("Left");
InputTextCtrl::keyNames[WXK_UP] = wxT("Up");
InputTextCtrl::keyNames[WXK_RIGHT] = wxT("Right");
InputTextCtrl::keyNames[WXK_DOWN] = wxT("Down");
InputTextCtrl::keyNames[WXK_SELECT] = wxT("Select");
InputTextCtrl::keyNames[WXK_PRINT] = wxT("Print");
InputTextCtrl::keyNames[WXK_EXECUTE] = wxT("Execute");
InputTextCtrl::keyNames[WXK_SNAPSHOT] = wxT("Print Screen");
InputTextCtrl::keyNames[WXK_INSERT] = wxT("Insert");
InputTextCtrl::keyNames[WXK_HELP] = wxT("Help");
InputTextCtrl::keyNames[WXK_NUMPAD0] = wxT("Numpad 0");
InputTextCtrl::keyNames[WXK_NUMPAD1] = wxT("Numpad 1");
InputTextCtrl::keyNames[WXK_NUMPAD2] = wxT("Numpad 2");
InputTextCtrl::keyNames[WXK_NUMPAD3] = wxT("Numpad 3");
InputTextCtrl::keyNames[WXK_NUMPAD4] = wxT("Numpad 4");
InputTextCtrl::keyNames[WXK_NUMPAD5] = wxT("Numpad 5");
InputTextCtrl::keyNames[WXK_NUMPAD6] = wxT("Numpad 6");
InputTextCtrl::keyNames[WXK_NUMPAD7] = wxT("Numpad 7");
InputTextCtrl::keyNames[WXK_NUMPAD8] = wxT("Numpad 8");
InputTextCtrl::keyNames[WXK_NUMPAD9] = wxT("Numpad 9");
InputTextCtrl::keyNames[WXK_MULTIPLY] = wxT("*");
InputTextCtrl::keyNames[WXK_ADD] = wxT("+");
InputTextCtrl::keyNames[WXK_SEPARATOR] = wxT("'");
InputTextCtrl::keyNames[WXK_SUBTRACT] = wxT("-");
InputTextCtrl::keyNames[WXK_DECIMAL] = wxT(".");
InputTextCtrl::keyNames[WXK_DIVIDE] = wxT("/");
InputTextCtrl::keyNames[WXK_F1] = wxT("F1");
InputTextCtrl::keyNames[WXK_F2] = wxT("F2");
InputTextCtrl::keyNames[WXK_F3] = wxT("F3");
InputTextCtrl::keyNames[WXK_F4] = wxT("F4");
InputTextCtrl::keyNames[WXK_F5] = wxT("F5");
InputTextCtrl::keyNames[WXK_F6] = wxT("F6");
InputTextCtrl::keyNames[WXK_F7] = wxT("F7");
InputTextCtrl::keyNames[WXK_F8] = wxT("F8");
InputTextCtrl::keyNames[WXK_F9] = wxT("F9");
InputTextCtrl::keyNames[WXK_F10] = wxT("F10");
InputTextCtrl::keyNames[WXK_F11] = wxT("F11");
InputTextCtrl::keyNames[WXK_F12] = wxT("F12");
InputTextCtrl::keyNames[WXK_F13] = wxT("F13");
InputTextCtrl::keyNames[WXK_F14] = wxT("F14");
InputTextCtrl::keyNames[WXK_F15] = wxT("F15");
InputTextCtrl::keyNames[WXK_F16] = wxT("F16");
InputTextCtrl::keyNames[WXK_F17] = wxT("F17");
InputTextCtrl::keyNames[WXK_F18] = wxT("F18");
InputTextCtrl::keyNames[WXK_F19] = wxT("F19");
InputTextCtrl::keyNames[WXK_F20] = wxT("F20");
InputTextCtrl::keyNames[WXK_F21] = wxT("F21");
InputTextCtrl::keyNames[WXK_F22] = wxT("F22");
InputTextCtrl::keyNames[WXK_F23] = wxT("F23");
InputTextCtrl::keyNames[WXK_F24] = wxT("F24");
InputTextCtrl::keyNames[WXK_NUMLOCK] = wxT("NumLock");
InputTextCtrl::keyNames[WXK_SCROLL] = wxT("ScrollLock");
InputTextCtrl::keyNames[WXK_PAGEUP] = wxT("PageUp");
InputTextCtrl::keyNames[WXK_PAGEDOWN] = wxT("PageDown");
InputTextCtrl::keyNames[WXK_PRIOR] = wxT("PageUp");
InputTextCtrl::keyNames[WXK_NEXT] = wxT("PageDown");
InputTextCtrl::keyNames[WXK_NUMPAD_SPACE] = wxT("Numpad Space");
InputTextCtrl::keyNames[WXK_NUMPAD_TAB] = wxT("Numpad Tab");
InputTextCtrl::keyNames[WXK_NUMPAD_ENTER] = wxT("Numpad Enter");
InputTextCtrl::keyNames[WXK_NUMPAD_F1] = wxT("Numpad F1");
InputTextCtrl::keyNames[WXK_NUMPAD_F2] = wxT("Numpad F2");
InputTextCtrl::keyNames[WXK_NUMPAD_F3] = wxT("Numpad F3");
InputTextCtrl::keyNames[WXK_NUMPAD_F4] = wxT("Numpad F4");
InputTextCtrl::keyNames[WXK_NUMPAD_HOME] = wxT("Numpad Home");
InputTextCtrl::keyNames[WXK_NUMPAD_LEFT] = wxT("Numpad Left");
InputTextCtrl::keyNames[WXK_NUMPAD_UP] = wxT("Numpad Up");
InputTextCtrl::keyNames[WXK_NUMPAD_RIGHT] = wxT("Numpad Right");
InputTextCtrl::keyNames[WXK_NUMPAD_DOWN] = wxT("Numpad Down");
InputTextCtrl::keyNames[WXK_NUMPAD_PAGEUP] = wxT("Numpad PageUp");
InputTextCtrl::keyNames[WXK_NUMPAD_PAGEDOWN] = wxT("Numpad PageDown");
InputTextCtrl::keyNames[WXK_NUMPAD_PRIOR] = wxT("Numpad PageUp");
InputTextCtrl::keyNames[WXK_NUMPAD_NEXT] = wxT("Numpad PageDown");
InputTextCtrl::keyNames[WXK_NUMPAD_END] = wxT("Numpad End");
InputTextCtrl::keyNames[WXK_NUMPAD_BEGIN] = wxT("Numpad Begin");
InputTextCtrl::keyNames[WXK_NUMPAD_INSERT] = wxT("Numpad Insert");
InputTextCtrl::keyNames[WXK_NUMPAD_DELETE] = wxT("Numpad Delete");
InputTextCtrl::keyNames[WXK_NUMPAD_EQUAL] = wxT("Numpad =");
InputTextCtrl::keyNames[WXK_NUMPAD_MULTIPLY] = wxT("Numpad *");
InputTextCtrl::keyNames[WXK_NUMPAD_ADD] = wxT("Numpad +");
InputTextCtrl::keyNames[WXK_NUMPAD_SEPARATOR] = wxT("Numpad Separator");
InputTextCtrl::keyNames[WXK_NUMPAD_SUBTRACT] = wxT("Numpad -");
InputTextCtrl::keyNames[WXK_NUMPAD_DECIMAL] = wxT("Numpad .");
InputTextCtrl::keyNames[WXK_NUMPAD_DIVIDE] = wxT("Numpad /");
InputTextCtrl::keyNames[WXK_WINDOWS_LEFT] = wxT("Windows Left");
InputTextCtrl::keyNames[WXK_WINDOWS_RIGHT] = wxT("Windows Right");
InputTextCtrl::keyNames[WXK_WINDOWS_MENU] = wxT("Application");
InputTextCtrl::keyNames[WXK_COMMAND] = wxT("Command");
InputTextCtrl::keyNames[WXK_SPECIAL1] = wxT("Special 1");
InputTextCtrl::keyNames[WXK_SPECIAL2] = wxT("Special 2");
InputTextCtrl::keyNames[WXK_SPECIAL3] = wxT("Special 3");
InputTextCtrl::keyNames[WXK_SPECIAL4] = wxT("Special 4");
InputTextCtrl::keyNames[WXK_SPECIAL5] = wxT("Special 5");
InputTextCtrl::keyNames[WXK_SPECIAL6] = wxT("Special 6");
InputTextCtrl::keyNames[WXK_SPECIAL7] = wxT("Special 7");
InputTextCtrl::keyNames[WXK_SPECIAL8] = wxT("Special 8");
InputTextCtrl::keyNames[WXK_SPECIAL9] = wxT("Special 9");
InputTextCtrl::keyNames[WXK_SPECIAL10] = wxT("Special 10");
InputTextCtrl::keyNames[WXK_SPECIAL11] = wxT("Special 11");
InputTextCtrl::keyNames[WXK_SPECIAL12] = wxT("Special 12");
InputTextCtrl::keyNames[WXK_SPECIAL13] = wxT("Special 13");
InputTextCtrl::keyNames[WXK_SPECIAL14] = wxT("Special 14");
InputTextCtrl::keyNames[WXK_SPECIAL15] = wxT("Special 15");
InputTextCtrl::keyNames[WXK_SPECIAL16] = wxT("Special 16");
InputTextCtrl::keyNames[WXK_SPECIAL17] = wxT("Special 17");
InputTextCtrl::keyNames[WXK_SPECIAL18] = wxT("Special 18");
InputTextCtrl::keyNames[WXK_SPECIAL19] = wxT("Special 19");
InputTextCtrl::keyNames[WXK_SPECIAL20] = wxT("Special 20");
InputTextCtrl::keyNamesInitialized = true;
}
InputTextCtrl::InputTextCtrl(wxWindow* parent, wxWindowID id)
{
keyCode = 0;
InputTextCtrl::InitializeKeyNames();
Create(parent, id, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER|wxTE_PROCESS_TAB );
}
void InputTextCtrl::OnKeyDown(wxKeyEvent& event)
{
int keyCode = event.GetKeyCode();
OnChangeKey(keyCode);
}
void InputTextCtrl::OnChangeKey(int keyCode)
{
if (InputTextCtrl::keyNames[keyCode] == wxT(""))
{
if (!keyCode)
{
this->SetBackgroundColour(*wxRED);
this->ChangeValue(wxT("Invalid key"));
}
else
{
this->SetBackgroundColour(*wxWHITE);
this->ChangeValue(wxString::Format(wxT("Key %i"),keyCode));
}
}
else
{
this->SetBackgroundColour(*wxWHITE);
this->ChangeValue(InputTextCtrl::keyNames[keyCode]);
}
this->keyCode = keyCode;
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <wx/dcbuffer.h>
#include <wx/image.h>
#include "MainPanel.h"
#include "MainFrame.h"
#include "IDControls.h"
#include "../Def.h"
#include "../Settings.h"
inline void MainPanel::OnEraseBackground(wxEraseEvent &) { /* do nothing */ }
IMPLEMENT_CLASS(MainPanel, wxPanel)
BEGIN_EVENT_TABLE(MainPanel, wxPanel)
EVT_PAINT(MainPanel::OnPaint)
EVT_ERASE_BACKGROUND(MainPanel::OnEraseBackground)
END_EVENT_TABLE()
BYTE palettes[][4][3] = {
{
{ 16, 57, 16},
{ 49, 99, 49},
{140, 173, 16},
{156, 189, 16}
},
{
{ 0, 0, 0},
{ 85, 85, 85},
{170, 170, 170},
{255, 255, 255}
}
};
MainPanel::MainPanel(wxWindow *parent) : wxPanel(parent, ID_MAINPANEL) {
imgBuf = NULL;
SetBackgroundStyle(wxBG_STYLE_CUSTOM);
windowParent = parent;
CreateScreen();
ChangeSize();
this->SetDropTarget(new DnDFile(parent));
}
MainPanel::~MainPanel() {
delete[] imgBuf;
}
void MainPanel::CreateScreen() {
imgBuf = new BYTE[GB_SCREEN_W*GB_SCREEN_H*3];
OnClear();
ChangePalette(SettingsGetGreenScale());
}
void MainPanel::ChangeSize()
{
int zoom = SettingsGetWindowZoom();
wxSize size(GB_SCREEN_W*zoom, GB_SCREEN_H*zoom);
SetMinSize(size);
SetMaxSize(size);
}
void MainPanel::OnPaint(wxPaintEvent &) {
wxImage img = wxImage(GB_SCREEN_W, GB_SCREEN_H, imgBuf, true);
int winZoom = SettingsGetWindowZoom();
if (winZoom > 1)
img.Rescale(GB_SCREEN_W*winZoom, GB_SCREEN_H*winZoom, wxIMAGE_QUALITY_NORMAL);
wxBitmap bmp(img);
// paint the screen
wxAutoBufferedPaintDC dc(this);
dc.DrawBitmap(bmp, 0, 0);
// dc.DrawText(wxString("Pokemon"), 0, 0);
}
void MainPanel::OnPreDraw()
{
}
void MainPanel::OnPostDraw()
{
}
void MainPanel::OnRefreshScreen()
{
// refresh the panel
Refresh(false);
Update();
}
void MainPanel::ChangePalette(bool original)
{
if (original)
selPalette = 0;
else
selPalette = 1;
}
void MainPanel::OnClear()
{
int size = GB_SCREEN_W*GB_SCREEN_H*3;
memset(imgBuf, 0, size);
}
void MainPanel::OnDrawPixel(int idColor, int x, int y)
{
/*
int zoom = SettingsGetWindowZoom();
void * ptrPalette = &palettes[selPalette][idColor][0];
unsigned long offsetBuf = 0;
int sizeLine = GB_SCREEN_W * 3 * zoom;
int offsetX = x * 3 * zoom;
int offsetY = 0;
int i, j;
for (i=0; i<zoom; i++)
{
offsetY = (y * zoom + i) * sizeLine;
offsetBuf = offsetY + offsetX;
for (j=0; j<zoom; j++)
{
memcpy(&imgBuf[offsetBuf], ptrPalette, 3);
offsetBuf += 3;
}
}
*/
BYTE colorR = palettes[selPalette][idColor][0];
BYTE colorG = palettes[selPalette][idColor][1];
BYTE colorB = palettes[selPalette][idColor][2];
int sizeLine = GB_SCREEN_W * 3;
int offsetX = x * 3;
int offsetY = y * sizeLine;
int offsetBuf = offsetY + offsetX;
imgBuf[offsetBuf + 0] = colorR;
imgBuf[offsetBuf + 1] = colorG;
imgBuf[offsetBuf + 2] = colorB;
}
DnDFile::DnDFile(wxWindow * parent)
{
this->parent = parent;
}
bool DnDFile::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames)
{
MainFrame * frame = (MainFrame *)parent;
frame->ChangeFile(filenames[0]);
return true;
} | C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <wx/wfstream.h>
#include <wx/zipstrm.h>
#include <wx/stdpaths.h>
#include "MainFrame.h"
#include "AboutDialog.h"
#include "IDControls.h"
#include "../Settings.h"
#include "../Pad.h"
#include "../GBException.h"
#include "Xpm/open.xpm"
#include "Xpm/play.xpm"
#include "Xpm/pause.xpm"
#include "Xpm/stop.xpm"
#include "Xpm/recent.xpm"
#include "Xpm/gb16.xpm"
#include "Xpm/gb32.xpm"
using namespace std;
IMPLEMENT_CLASS(MainFrame, wxFrame)
BEGIN_EVENT_TABLE(MainFrame, wxFrame)
EVT_MENU(wxID_EXIT, MainFrame::OnFileExit)
EVT_MENU(wxID_OPEN, MainFrame::OnFileOpen)
EVT_MENU(ID_OPEN_RECENT, MainFrame::OnRecent)
EVT_MENU_RANGE(ID_RECENT0, ID_RECENT9, MainFrame::OnRecentItem)
EVT_MENU(ID_CLEAR_RECENT, MainFrame::OnClearRecent)
EVT_MENU_RANGE(ID_LOADSTATE0, ID_LOADSTATE9, MainFrame::OnLoadState)
EVT_MENU_RANGE(ID_SAVESTATE0, ID_SAVESTATE9, MainFrame::OnSaveState)
EVT_MENU(wxID_PREFERENCES, MainFrame::OnSettings)
EVT_MENU(wxID_ABOUT, MainFrame::OnAbout)
EVT_MENU(ID_START, MainFrame::OnPlay)
EVT_MENU(ID_PAUSE, MainFrame::OnPause)
EVT_MENU(ID_STOP, MainFrame::OnStop)
EVT_UPDATE_UI( ID_START, MainFrame::OnPlayUpdateUI )
EVT_UPDATE_UI( ID_PAUSE, MainFrame::OnPauseUpdateUI )
EVT_UPDATE_UI( ID_STOP, MainFrame::OnStopUpdateUI )
EVT_UPDATE_UI_RANGE(ID_LOADSTATE0, ID_LOADSTATE9, MainFrame::OnLoadStateUpdateUI)
EVT_UPDATE_UI_RANGE(ID_SAVESTATE0, ID_SAVESTATE9, MainFrame::OnSaveStateUpdateUI)
EVT_TIMER(ID_TIMER, MainFrame::OnTimer)
END_EVENT_TABLE()
MainFrame::MainFrame(wxString fileName)
{
// Create the MainFrame
this->Create(0, ID_MAINFRAME, wxT("gbpablog"), wxDefaultPosition,
wxDefaultSize, wxCAPTION | wxSYSTEM_MENU |
wxMINIMIZE_BOX | wxCLOSE_BOX);
wxIconBundle * icons = new wxIconBundle(wxIcon(gb16_xpm));
icons->AddIcon(wxIcon(gb32_xpm));
this->SetIcons(*icons);
this->CreateMenuBar();
this->CreateToolBar();
numRecentFiles = 0;
settingsDialog = new SettingsDialog(this);
settingsDialog->CentreOnScreen();
settingsDialog->LoadFromFile();
SettingsSetNewValues(settingsDialog->settings);
PadSetKeys(SettingsGetInput());
this->CreateRecentMenu(SettingsGetRecentRoms());
// create the MainPanel
panel = new MainPanel(this);
sound = new Sound();
video = new Video(panel);
cpu = new CPU(video, sound);
cartridge = NULL;
emuState = NotStartedYet;
this->SetClientSize(GB_SCREEN_W*SettingsGetWindowZoom(), GB_SCREEN_H*SettingsGetWindowZoom());
sound->ChangeSampleRate(SettingsGetSoundSampleRate());
sound->SetEnabled(SettingsGetSoundEnabled());
if (fileName != wxT(""))
ChangeFile(fileName);
timerExecution = new wxTimer(this, ID_TIMER);
timerExecution->Start(16);
//ShowFullScreen(true, wxFULLSCREEN_ALL);
}
MainFrame::~MainFrame()
{
this->Clean();
}
void MainFrame::CreateMenuBar()
{
// create the main menubar
mb = new wxMenuBar();
// create the file menu
wxMenu *fileMenu = new wxMenu;
fileMenu->Append(wxID_OPEN, wxT("&Open\tCtrl+O"));
recentMenuFile = new wxMenu;
recentMenuFile->AppendSeparator();
recentMenuFile->Append(ID_CLEAR_RECENT, wxT("Clear recent roms"));
fileMenu->AppendSubMenu(recentMenuFile, wxT("Open Recent"));
// Se crea un wxMenu que se tratará exactamente igual que a recentMenuFile
// para poder tener uno en el menuBar y otro como popUp
recentMenuPopup = new wxMenu;
recentMenuPopup->AppendSeparator();
recentMenuPopup->Append(ID_CLEAR_RECENT, wxT("Clear recent roms"));
wxMenu * loadMenuFile = new wxMenu;
wxMenu * saveMenuFile = new wxMenu;
wxString slotMenu;
for (int i=1; i<11; i++)
{
int id = i % 10;
slotMenu = wxT("");
slotMenu << wxT("Slot ") << id << wxT("\tCtrl+Alt+") << id;
loadMenuFile->Append(ID_LOADSTATE0+id, slotMenu);
slotMenu = wxT("");
slotMenu << wxT("Slot ") << id << wxT("\tCtrl+") << id;
saveMenuFile->Append(ID_SAVESTATE0+id, slotMenu);
}
fileMenu->AppendSubMenu(loadMenuFile, wxT("Load State"));
fileMenu->AppendSubMenu(saveMenuFile, wxT("Save State"));
fileMenu->Append(wxID_EXIT, wxT("E&xit"));
// add the file menu to the menu bar
mb->Append(fileMenu, wxT("&File"));
// create the emulation menu
wxMenu *emulationMenu = new wxMenu;
emulationMenu->Append(wxID_PREFERENCES, wxT("&Settings\tCtrl+E"));
emulationMenu->Append(ID_START, wxT("&Start\tCtrl+S"));
emulationMenu->Append(ID_PAUSE, wxT("&Pause\tCtrl+P"));
emulationMenu->Append(ID_STOP, wxT("S&top\tCtrl+T"));
// add the file menu to the menu bar
mb->Append(emulationMenu, wxT("&Emulation"));
// create the help menu
wxMenu *helpMenu = new wxMenu;
helpMenu->Append(wxID_ABOUT, wxT("&About"));
// add the help menu to the menu bar
mb->Append(helpMenu, wxT("&Help"));
// add the menu bar to the MainFrame
this->SetMenuBar(mb);
}
void MainFrame::CreateToolBar()
{
toolBar = new wxToolBar(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTB_HORIZONTAL|wxNO_BORDER);
wxBitmap bmpOpen(open_xpm);
toolBar->AddTool(wxID_OPEN, bmpOpen, wxT("Open"));
wxBitmap bmpRecent(recent_xpm);
toolBar->AddTool(ID_OPEN_RECENT, bmpRecent, wxT("Recent"));
toolBar->AddSeparator();
wxBitmap bmpPlay(play_xpm);
toolBar->AddTool(ID_START, bmpPlay, wxT("Start"));
wxBitmap bmpPause(pause_xpm);
toolBar->AddTool(ID_PAUSE, bmpPause, wxT("Pause"));
wxBitmap bmpStop(stop_xpm);
toolBar->AddTool(ID_STOP, bmpStop, wxT("Stop"));
toolBar->EnableTool(ID_START, false);
toolBar->EnableTool(ID_PAUSE, false);
toolBar->EnableTool(ID_STOP, false);
toolBar->Realize();
this->SetToolBar(toolBar);
}
void MainFrame::OnRecent(wxCommandEvent &event)
{
this->PopupMenu(recentMenuPopup, 0, 0);
}
void MainFrame::OnFileOpen(wxCommandEvent &) {
wxFileDialog* openDialog = new wxFileDialog(this, wxT("Choose a gameboy rom to open"), wxEmptyString, wxEmptyString,
wxT("Gameboy roms (*.gb; *.zip)|*.gb;*.zip"),
wxFD_OPEN, wxDefaultPosition);
// Creates a "open file" dialog
if (openDialog->ShowModal() == wxID_OK) // if the user click "Open" instead of "Cancel"
this->ChangeFile(openDialog->GetPath());
// Clean up after ourselves
openDialog->Destroy();
}
void MainFrame::OnRecentItem(wxCommandEvent &event)
{
int idAux = event.GetId();
int id = idAux - ID_RECENT0;
ChangeFile(recentFiles[id].fullName);
}
void MainFrame::OnLoadState(wxCommandEvent &event)
{
int idAux = event.GetId();
int id = idAux - ID_LOADSTATE0;
wxString savesDir = wxStandardPaths::Get().GetUserDataDir() + wxFileName::GetPathSeparator()
+ wxT("SaveStates") + wxFileName::GetPathSeparator();
try
{
cpu->LoadState(string(savesDir.mb_str()), id);
}
catch(GBException e)
{
wxMessageBox(wxString(e.what(), wxConvUTF8), wxT("Error"), wxICON_WARNING);
}
}
void MainFrame::OnSaveState(wxCommandEvent &event)
{
int idAux = event.GetId();
int id = idAux - ID_SAVESTATE0;
wxString savesDir = wxStandardPaths::Get().GetUserDataDir() + wxFileName::GetPathSeparator()
+ wxT("SaveStates");
if (!wxFileName::DirExists(savesDir))
wxFileName::Mkdir(savesDir, 0777, wxPATH_MKDIR_FULL);
savesDir += wxFileName::GetPathSeparator();
try
{
cpu->SaveState(string(savesDir.mb_str()), id);
}
catch(GBException e)
{
wxMessageBox(wxString(e.what(), wxConvUTF8), wxT("Error"), wxICON_WARNING);
}
}
void MainFrame::OnClearRecent(wxCommandEvent &)
{
for (int i=0; i<numRecentFiles; i++)
{
recentMenuFile->Delete(ID_RECENT0+i);
recentMenuPopup->Delete(ID_RECENT0+i);
}
numRecentFiles = 0;
this->RecentRomsToSettings();
settingsDialog->SaveToFile(true);
}
void MainFrame::ChangeFile(const wxString fileName)
{
BYTE * buffer = NULL;
unsigned long size = 0;
bool isZip = false;
if (!wxFileExists(fileName))
{
wxMessageBox(wxT("The file:\n")+fileName+wxT("\ndoesn't exist"), wxT("Error"));
return;
}
wxString fileLower = fileName.Lower();
if (fileLower.EndsWith(wxT(".zip")))
{
isZip = true;
this->LoadZip(fileName, &buffer, &size);
if ((buffer == NULL) || (size == 0))
return;
}
else if (!fileLower.EndsWith(wxT(".gb")))
{
wxMessageBox(wxT("Only gb and zip files allowed!"), wxT("Error"));
return;
}
// Si ha llegado aquí es que es un archivo permitido
cpu->Reset();
if (cartridge)
delete cartridge;
wxString battsDir = wxStandardPaths::Get().GetUserDataDir() + wxFileName::GetPathSeparator()
+ wxT("Batts");
if (!wxFileName::DirExists(battsDir))
wxFileName::Mkdir(battsDir, 0777, wxPATH_MKDIR_FULL);
battsDir += wxFileName::GetPathSeparator();
if (isZip) {
cartridge = new Cartridge(buffer, size, string(battsDir.mb_str()));
}else {
cartridge = new Cartridge(string(fileName.mb_str()), string(battsDir.mb_str()));
}
cpu->LoadCartridge(cartridge);
emuState = Playing;
this->UpdateRecentMenu(fileName);
}
/*
* Carga un fichero comprimido con zip y busca una rom de gameboy (un fichero con extension gb).
* Si existe mas de una rom solo carga la primera. Si se ha encontrado, la rom se devuelve en un buffer
* junto con su tamaño, sino las variables se dejan intactas
*/
void MainFrame::LoadZip(const wxString zipPath, BYTE ** buffer, unsigned long * size)
{
wxString fileInZip, fileLower;
wxZipEntry* entry;
wxFFileInputStream in(zipPath);
wxZipInputStream zip(in);
while (entry = zip.GetNextEntry())
{
fileInZip = entry->GetName();
fileLower = fileInZip.Lower();
if (fileLower.EndsWith(wxT(".gb")))
{
*size = zip.GetSize();
*buffer = new BYTE[*size];
zip.Read(*buffer, *size);
delete entry;
return;
}
else
{
delete entry;
continue;
}
}
// Archivo no encontrado
wxMessageBox(wxT("GameBoy rom not found in the file:\n")+zipPath, wxT("Error"));
return;
}
void MainFrame::CreateRecentMenu(std::string * roms)
{
for (int i=0; i<MAX_RECENT_FILES; i++)
{
if (roms[i] == "")
break;
recentFiles[i].fullName = wxString(roms[i].c_str(), wxConvUTF8);
recentFiles[i].shortName = recentFiles[i].fullName.substr(recentFiles[i].fullName.rfind(wxFileName::GetPathSeparator())+1);
int id = ID_RECENT0 + numRecentFiles;
recentMenuFile->Insert(numRecentFiles, id, recentFiles[i].shortName);
recentMenuPopup->Insert(numRecentFiles, id, recentFiles[i].shortName);
numRecentFiles++;
}
}
void MainFrame::UpdateRecentMenu(wxString fileName)
{
wxString shortName = fileName.substr(fileName.rfind(wxFileName::GetPathSeparator())+1);
int previousIndex = -1;
for (int i=0; i<numRecentFiles; i++)
{
if (recentFiles[i].fullName == fileName)
{
previousIndex = i;
break;
}
}
int startFrom;
// Si ya existia de antes y es el primero
if (previousIndex == 0)
{
return;
}
// Si ya existia de antes y no es el primero
else if (previousIndex > 0)
{
startFrom = previousIndex-1;
}
// Si no existia pero no hemos llegado al limite
else if (numRecentFiles < MAX_RECENT_FILES)
{
startFrom = numRecentFiles-1;
int id = ID_RECENT0 + numRecentFiles;
recentMenuFile->Insert(numRecentFiles, id, wxT(""));
recentMenuPopup->Insert(numRecentFiles, id, wxT(""));
numRecentFiles++;
}
// Si no existia pero hemos llegado al limite
else
{
startFrom = MAX_RECENT_FILES-2;
}
for (int i=startFrom; i>=0; i--)
{
recentFiles[i+1].shortName = recentFiles[i].shortName;
recentFiles[i+1].fullName = recentFiles[i].fullName;
}
recentFiles[0].shortName = shortName;
recentFiles[0].fullName = fileName;
for (int i=0; i<numRecentFiles; i++)
{
recentMenuFile->SetLabel(ID_RECENT0+i, recentFiles[i].shortName);
recentMenuPopup->SetLabel(ID_RECENT0+i, recentFiles[i].shortName);
}
this->RecentRomsToSettings();
settingsDialog->SaveToFile(true);
}
void MainFrame::RecentRomsToSettings()
{
std::string recentRomsSettings[10];
for (int i=0; i<numRecentFiles; i++)
{
recentRomsSettings[i] = recentFiles[i].fullName.mb_str();
}
for(int i=numRecentFiles; i<MAX_RECENT_FILES; i++)
{
recentRomsSettings[i] = "";
}
SettingsSetRecentRoms(recentRomsSettings);
}
void MainFrame::OnFileExit(wxCommandEvent &)
{
this->Close();
}
void MainFrame::Clean()
{
emuState = Stopped;
timerExecution->Stop();
delete cpu;
delete video;
delete sound;
if (cartridge)
delete cartridge;
if (settingsDialog)
settingsDialog->Destroy();
}
/*
* Abre un dialogo de configuracion. Cuando se cierra se encarga de aplicar ciertos cambios a la emulacion
*/
void MainFrame::OnSettings(wxCommandEvent &)
{
enumEmuStates lastState = emuState;
if (emuState == Playing)
emuState = Paused;
if (settingsDialog->ShowModal() == wxID_OK)
{
SettingsSetNewValues(settingsDialog->settings);
panel->ChangePalette(SettingsGetGreenScale());
panel->ChangeSize();
this->SetClientSize(GB_SCREEN_W*SettingsGetWindowZoom(), GB_SCREEN_H*SettingsGetWindowZoom());
PadSetKeys(SettingsGetInput());
sound->ChangeSampleRate(SettingsGetSoundSampleRate());
sound->SetEnabled(SettingsGetSoundEnabled());
}
emuState = lastState;
}
void MainFrame::OnAbout(wxCommandEvent &)
{
AboutDialog(this);
}
void MainFrame::OnPlay(wxCommandEvent &)
{
emuState = Playing;
}
void MainFrame::OnPause(wxCommandEvent &)
{
if (emuState == Playing)
emuState = Paused;
else if (emuState == Paused)
emuState = Playing;
}
void MainFrame::OnStop(wxCommandEvent &)
{
cpu->Reset();
panel->OnRefreshScreen();
emuState = Stopped;
}
void MainFrame::OnPlayUpdateUI(wxUpdateUIEvent& event)
{
if ((emuState == NotStartedYet) || (emuState == Playing))
event.Enable(false);
else
event.Enable(true);
}
void MainFrame::OnPauseUpdateUI(wxUpdateUIEvent& event)
{
if ((emuState == NotStartedYet) || (emuState == Stopped))
event.Enable(false);
else
event.Enable(true);
}
void MainFrame::OnStopUpdateUI(wxUpdateUIEvent& event)
{
if ((emuState == Stopped)||(emuState == NotStartedYet))
event.Enable(false);
else
event.Enable(true);
}
void MainFrame::OnLoadStateUpdateUI(wxUpdateUIEvent& event)
{
if ((emuState == Stopped)||(emuState == NotStartedYet))
event.Enable(false);
else
event.Enable(true);
}
void MainFrame::OnSaveStateUpdateUI(wxUpdateUIEvent& event)
{
if ((emuState == Stopped)||(emuState == NotStartedYet))
event.Enable(false);
else
event.Enable(true);
}
void MainFrame::OnTimer(wxTimerEvent &event)
{
if (emuState == Playing)
cpu->ExecuteOneFrame();
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MAINFRAME_H__
#define __MAINFRAME_H__
#define MAX_RECENT_FILES 10
#include <wx/wx.h>
#include "SettingsDialog.h"
#include "MainPanel.h"
#include "../CPU.h"
struct RecentFile
{
wxString shortName;
wxString fullName;
};
/*******************************************************************************
// MainFrame Class
*******************************************************************************/
class MainFrame : public wxFrame {
DECLARE_CLASS(MainFrame)
DECLARE_EVENT_TABLE()
private:
wxMenuBar *mb;
wxMenu *recentMenuFile;
wxMenu *recentMenuPopup;
wxToolBar* toolBar;
wxTimer * timerExecution;
MainPanel *panel;
SettingsDialog * settingsDialog;
Video * video;
Sound * sound;
Cartridge * cartridge;
RecentFile recentFiles[MAX_RECENT_FILES];
int numRecentFiles;
enum enumEmuStates { NotStartedYet, Stopped, Paused, Playing };
enumEmuStates emuState;
/**
* Called when exit from the file menu is selected.
*/
void OnFileExit(wxCommandEvent &);
void OnFileOpen(wxCommandEvent &);
void OnRecent(wxCommandEvent &event);
void OnRecentItem(wxCommandEvent &event);
void OnClearRecent(wxCommandEvent &event);
void OnLoadState(wxCommandEvent &event);
void OnSaveState(wxCommandEvent &event);
void OnSettings(wxCommandEvent &);
void OnAbout(wxCommandEvent &);
void OnPlay(wxCommandEvent &);
void OnPause(wxCommandEvent &);
void OnStop(wxCommandEvent &);
void OnPlayUpdateUI(wxUpdateUIEvent& event);
void OnPauseUpdateUI(wxUpdateUIEvent& event);
void OnStopUpdateUI(wxUpdateUIEvent& event);
void OnLoadStateUpdateUI(wxUpdateUIEvent& event);
void OnSaveStateUpdateUI(wxUpdateUIEvent& event);
//void OnIdle(wxIdleEvent &event);
void OnTimer(wxTimerEvent &event);
void CreateMenuBar();
void CreateToolBar();
void CreateRecentMenu(std::string * roms);
void RecentRomsToSettings();
void UpdateRecentMenu(wxString fileName);
void LoadZip(const wxString zipPath, BYTE ** buffer, unsigned long * size);
void Clean();
public:
CPU * cpu;
/**
* Creates a new MainFrame.
*/
MainFrame(wxString fileName);
~MainFrame();
/**
* Gets the MainPanel within this MainFrame.
*
* @return The MainPanel.
*/
inline MainPanel &GetPanel() { return *panel; }
void ChangeFile(const wxString fileName);
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <wx/cmdline.h>
#include <wx/filename.h>
#include "MainApp.h"
#include "../Def.h"
IMPLEMENT_CLASS(MainApp, wxApp)
IMPLEMENT_APP(MainApp)
static const wxCmdLineEntryDesc g_cmdLineDesc[] =
{
{ wxCMD_LINE_SWITCH, wxT("h"), wxT("help"), wxT("displays this help"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_OPTION_HELP },
{ wxCMD_LINE_SWITCH, wxT("v"), wxT("version"), wxT("print version"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
{ wxCMD_LINE_PARAM, NULL, NULL, wxT("input file"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL },
{ wxCMD_LINE_NONE, NULL, NULL, NULL, wxCMD_LINE_VAL_NONE, wxCMD_LINE_PARAM_OPTIONAL }
};
bool MainApp::OnInit() {
wxString cmdFilename = wxT("");
wxCmdLineParser cmdParser(g_cmdLineDesc, argc, argv);
int res;
{
wxLogNull log;
// Pass false to suppress auto Usage() message
res = cmdParser.Parse(false);
}
// Check if the user asked for command-line help
if (res == -1 || res > 0 || cmdParser.Found(wxT("h")))
{
cmdParser.Usage();
return false;
}
// Check if the user asked for the version
if (cmdParser.Found(wxT("v")))
{
#ifndef __WXMSW__
wxLog::SetActiveTarget(new wxLogStderr);
#endif
wxString msg = wxT("");
msg << wxT(APP_NAME) << wxT(" ") << wxT(APP_VERSION);
wxLogMessage(wxT("%s"), msg.c_str());
return false;
}
// Check for a filename
if (cmdParser.GetParamCount() > 0)
{
cmdFilename = cmdParser.GetParam(0);
// Under Windows when invoking via a document
// in Explorer, we are passed the short form.
// So normalize and make the long form.
wxFileName fName(cmdFilename);
fName.Normalize(wxPATH_NORM_LONG|wxPATH_NORM_DOTS|wxPATH_NORM_TILDE|wxPATH_NORM_ABSOLUTE);
cmdFilename = fName.GetFullPath();
}
// create the MainFrame
frame = new MainFrame(cmdFilename);
frame->Centre();
frame->Show();
// Our MainFrame is the Top Window
SetTopWindow(frame);
// initialization should always succeed
return true;
}
int MainApp::OnRun() {
// initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cerr << "unable to init SDL: " << SDL_GetError() << '\n';
return -1;
}
// start the main loop
return wxApp::OnRun();
}
int MainApp::OnExit() {
SDL_Quit();
// return the standard exit code
return wxApp::OnExit();
}
void MainApp::MacOpenFile(const wxString &fileName)
{
frame->ChangeFile(fileName);
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <wx/wx.h>
#include <wx/hyperlink.h> // hyperlink support
#include "SDL.h"
#include "AboutDialog.h"
#include "Xpm/gb64.xpm" // app icon bitmap
#include "../Def.h"
AboutDialog::AboutDialog (wxWindow *parent)
: wxDialog (parent, -1, _("About ..."),
wxDefaultPosition, wxDefaultSize,
wxDEFAULT_DIALOG_STYLE) {
// sets the application icon
SetTitle (_("About ..."));
const SDL_version* sdlVersion = SDL_Linked_Version();
wxString stringSDLVersion;
stringSDLVersion << (int)sdlVersion->major << wxT(".") << (int)sdlVersion->minor << wxT(".") << (int)sdlVersion->patch;
// about info
wxFlexGridSizer *aboutinfo = new wxFlexGridSizer (2, 3, 3);
aboutinfo->Add (new wxStaticText(this, wxID_ANY, _("Version: ")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT(APP_VERSION)));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, _("Written by: ")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT(APP_MAINT)));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, _("Licence type: ")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT(APP_LICENCE)));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, _("wxWidgets: ")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxVERSION_STRING));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, _("SDL: ")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, stringSDLVersion));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, _("Thanks to: ")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, _("Authors of Pan Docs")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT("")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT("bcrew1375 (Miracle GB)")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT("")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT("AntonioND (GiiBii)")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT("")));
aboutinfo->Add (new wxStaticText(this, wxID_ANY, wxT("Shay Green (Gb_Snd_Emu)")));
// about icontitle//info
wxBoxSizer *aboutpane = new wxBoxSizer (wxHORIZONTAL);
aboutpane->Add (new wxStaticBitmap (this, wxID_ANY, wxBitmap (gb64_xpm)),
0, wxRIGHT, 10);
aboutpane->Add (aboutinfo, 0, wxEXPAND);
//aboutpane->Add (60, 0);
// about complete
wxBoxSizer *totalpane = new wxBoxSizer (wxVERTICAL);
totalpane->Add (0, 20);
wxStaticText *appname = new wxStaticText (this, wxID_ANY, wxT(APP_NAME));
appname->SetFont (wxFont (24, wxDEFAULT, wxNORMAL, wxBOLD));
totalpane->Add (appname, 0, wxALIGN_CENTER);
totalpane->Add (0, 10);
totalpane->Add (aboutpane, 0, wxALIGN_CENTER | wxRIGHT | wxLEFT, 20);
totalpane->Add (0, 10);
wxHyperlinkCtrl *website = new wxHyperlinkCtrl (this, wxID_ANY, wxT(APP_WEBSITE), wxT(APP_WEBSITE));
totalpane->Add (website, 0, wxALIGN_CENTER);
totalpane->Add (0, 10);
wxButton *okButton = new wxButton (this, wxID_OK, _("OK"));
okButton->SetDefault();
totalpane->Add (okButton, 0, wxALIGN_CENTER | wxALL, 10);
SetSizerAndFit (totalpane);
CentreOnParent();
ShowModal();
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __ABOUTDIALOG_H__
#define __ABOUTDIALOG_H__
class AboutDialog: public wxDialog {
public:
AboutDialog (wxWindow *parent);
};
#endif | C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MAINPANEL_H__
#define __MAINPANEL_H__
#include <wx/wx.h>
#include <wx/dnd.h>
#include "SDL.h"
#include "../IGBScreenDrawable.h"
#include "../Def.h"
/*******************************************************************************
* MainPanel Class
*******************************************************************************/
class MainPanel : public wxPanel, public IGBScreenDrawable {
DECLARE_CLASS(MainPanel)
DECLARE_EVENT_TABLE()
private:
int selPalette;
BYTE * imgBuf;
void OnPaint(wxPaintEvent &);
void OnEraseBackground(wxEraseEvent &);
/**
* Creates the SDL_Surface used by this MainPanel.
*/
void CreateScreen();
public:
wxWindow * windowParent;
MainPanel(wxWindow *parent);
~MainPanel();
void ChangeSize();
void ChangePalette(bool original);
void OnPreDraw();
void OnPostDraw();
void OnDrawPixel(int idColor, int x, int y);
void OnRefreshScreen();
void OnClear();
};
// A drop target that adds filenames to a list box
class DnDFile : public wxFileDropTarget {
public:
DnDFile(wxWindow *parent);
virtual bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames);
private:
wxWindow *parent;
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __INPUTTEXTCTRL_H__
#define __INPUTTEXTCTRL_H__
#define NUM_KEYNAMES 1024
#include <wx/wx.h>
class InputTextCtrl: public wxTextCtrl
{
DECLARE_CLASS(InputTextCtrl)
DECLARE_EVENT_TABLE()
public:
int keyCode;
InputTextCtrl(wxWindow* parent, wxWindowID id);
void OnChangeKey(int keyCode);
private:
static wxString keyNames[NUM_KEYNAMES];
static bool keyNamesInitialized;
static void InitializeKeyNames();
void OnKeyDown(wxKeyEvent& event);
};
#endif | C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __SOUND_H__
#define __SOUND_H__
#include "SDL.h"
// Definir la siguiente linea para que en Visual Studio no haya conflicto
// entre SDL y GB_Snd_Emu al definir tipos basicos
#define BLARGG_COMPILER_HAS_NAMESPACE 1
#include "Basic_Gb_Apu.h"
#include "Sound_Queue.h"
#include "Def.h"
class Sound
{
private:
Basic_Gb_Apu apu;
Sound_Queue sound;
bool initialized;
bool enabled;
long sampleRate;
int HandleError( const char* str );
public:
Sound();
~Sound();
int ChangeSampleRate(long newSampleRate);
int Start();
int Stop();
bool GetEnabled();
void SetEnabled(bool enabled);
inline void WriteRegister(WORD dir, BYTE value) { if (enabled) apu.write_register( dir, value ); }
inline BYTE ReadRegister(WORD dir) { return enabled ? apu.read_register( dir ) : 0; }
void EndFrame();
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __CPU_H__
#define __CPU_H__
#include "Registers.h"
#include "Instructions.h"
#include "Memory.h"
#include "Video.h"
#include "Sound.h"
#include "Pad.h"
#include "Cartridge.h"
#include "Log.h"
class CPU: public Registers, public Memory
{
private:
unsigned long numInstructions;
unsigned long actualCycles;
BYTE lastCycles;
WORD cyclesLCD;
WORD cyclesTimer;
WORD cyclesDIV;
WORD cyclesSerial;
int bitSerial;
Video *v;
QueueLog *log;
BYTE instructionCycles[0xFF];
BYTE instructionCyclesCB[0xFF];
bool frameCompleted;
public:
CPU(Video *v, Sound * s);
CPU(Video *v, Cartridge *c, Sound * s);
~CPU();
void ExecuteOneFrame();
void UpdatePad();
void Reset();
void SaveLog();
void SaveState(std::string saveDirectory, int numSlot);
void LoadState(std::string loadDirectory, int numSlot);
private:
void Init(Video *v);
void FillInstructionCycles();
void FillInstructionCyclesCB();
void OpCodeCB(Instructions * inst);
void UpdateStateLCD();
void UpdateTimer();
void UpdateSerial();
void Interrupts(Instructions * inst);
void CheckLYC();
void OnEndFrame();
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __GBEXCEPTION_H__
#define __GBEXCEPTION_H__
#include <string>
enum ExceptionType { GBUnknown, GBError, GBExit };
class GBException: public std::exception
{
private:
std::string description;
ExceptionType type;
void newException(std::string desc, ExceptionType type);
public:
GBException();
GBException(std::string desc);
GBException(std::string desc, ExceptionType type);
const char* what() const throw();
ExceptionType GetType();
~GBException() throw();
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __REGISTERS_H__
#define __REGISTERS_H__
#include "Def.h"
#include <iostream>
enum e_registers {
A = 0x00, B, C, D, E, F, H, L, //registros simples
AF = 0x10, BC, DE, HL, //registros dobles
f_Z = 0x20, f_N, f_H, f_C, //flags
PC = 0x30, SP, $, c_$$,
c_BC = 0x40, c_DE, c_HL, //memoria apuntada por el registro doble
};
union u_register{
WORD doble;
BYTE simple[2];
};
class Registers
{
private:
u_register af, bc, de, hl;
WORD pc; //Program Counter
WORD sp; //Stack Pointer
bool IME;
bool pendingIME;
bool pendingIMEvalue;
bool halt;
bool stop;
public:
Registers();
~Registers();
Registers *GetPtrRegisters();
inline BYTE Get_A() {return this->af.simple[1];}
inline void Set_A(BYTE value) {this->af.simple[1] = value;}
inline BYTE Get_B() {return this->bc.simple[1];}
inline void Set_B(BYTE value) {this->bc.simple[1] = value;}
inline BYTE Get_C() {return this->bc.simple[0];}
inline void Set_C(BYTE value) {this->bc.simple[0] = value;}
inline BYTE Get_D() {return this->de.simple[1];}
inline void Set_D(BYTE value) {this->de.simple[1] = value;}
inline BYTE Get_E() {return this->de.simple[0];}
inline void Set_E(BYTE value) {this->de.simple[0] = value;}
inline BYTE Get_F() {return this->af.simple[0];}
inline void Set_F(BYTE value) {this->af.simple[0] = value;}
inline BYTE Get_H() {return this->hl.simple[1];}
inline void Set_H(BYTE value) {this->hl.simple[1] = value;}
inline BYTE Get_L() {return this->hl.simple[0];}
inline void Set_L(BYTE value) {this->hl.simple[0] = value;}
inline WORD Get_AF() {return this->af.doble;}
inline void Set_AF(WORD value) {this->af.doble = value;}
inline WORD Get_BC() {return this->bc.doble;}
inline void Set_BC(WORD value) {this->bc.doble = value;}
inline WORD Get_DE() {return this->de.doble;}
inline void Set_DE(WORD value) {this->de.doble = value;}
inline WORD Get_HL() {return this->hl.doble;}
inline void Set_HL(WORD value) {this->hl.doble = value;}
inline WORD Get_PC() {return this->pc;}
inline void Set_PC(WORD value) {this->pc = value;}
inline void Add_PC(int value) {this->pc += value;};
inline WORD Get_SP() {return this->sp;}
inline void Set_SP(WORD value) {this->sp = value;}
inline void Add_SP(int value) {this->sp += value;};
inline bool Get_IME() {return this->IME;}
inline void Set_IME(bool value, bool immediately=true)
{
if (immediately)
{
this->IME = value;
this->pendingIME = false;
}
else
{
this->pendingIME = true;
this->pendingIMEvalue = value;
}
}
inline void Set_PendingIME()
{
if (this->pendingIME)
{
this->IME = this->pendingIMEvalue;
this->pendingIME = false;
}
}
inline bool Get_Halt() {return this->halt;}
inline void Set_Halt(bool value) {this->halt = value;}
inline bool Get_Stop() {return this->stop;}
inline void Set_Stop(bool value) {this->stop = value;}
WORD Get_Reg(e_registers reg);
void Set_Reg(e_registers reg, WORD value);
inline BYTE Get_flagZ() {return (this->af.simple[0] >> 7);}
inline void Set_flagZ(BYTE value) {this->af.simple[0] = (this->af.simple[0] & 0x7F) | (value << 7);}
inline BYTE Get_flagN() {return ((this->af.simple[0] & 0x40) >> 6);}
inline void Set_flagN(BYTE value) {this->af.simple[0] = (this->af.simple[0] & 0xBF) | (value << 6);}
inline BYTE Get_flagH() {return ((this->af.simple[0] & 0x20) >> 5);}
inline void Set_flagH(BYTE value) {this->af.simple[0] = (this->af.simple[0] & 0xDF) | (value << 5);}
inline BYTE Get_flagC() {return ((this->af.simple[0] & 0x10) >> 4);}
inline void Set_flagC(BYTE value) {this->af.simple[0] = (this->af.simple[0] & 0xEF) | (value << 4);}
BYTE Get_Flag(e_registers flag);
void Set_Flag(e_registers flag, BYTE value);
void ResetRegs();
void SaveRegs(std::ofstream * file);
void LoadRegs(std::ifstream * file);
std::string ToString();
};
#endif
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <fstream>
#include <iostream>
#include <string>
#include <string.h>
#include <iomanip>
#include "Cartridge.h"
#include "Def.h"
#include "GBException.h"
#include "MBC.h"
using namespace std;
/*
* Constructor que recibe un fichero, lo carga en memoria y lo procesa
*/
Cartridge::Cartridge(string fileName, string batteriesPath)
{
_memCartridge = NULL;
ifstream::pos_type size;
ifstream file (fileName.c_str(), ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
this->_romSize = (unsigned long)size;
_memCartridge = new BYTE [size];
file.seekg (0, ios::beg);
file.read ((char *)_memCartridge, size);
file.close();
cout << fileName << ":\nFile loaded in memory correctly" << endl;
CheckCartridge(batteriesPath);
_isLoaded = true;
}
else
{
cerr << fileName << ": Error trying to open the file" << endl;
_isLoaded = false;
}
}
/*
* Constructor que recibe un buffer y su tamaño y lo procesa
*/
Cartridge::Cartridge(BYTE * cartridgeBuffer, unsigned long size, string batteriesPath)
{
_romSize = size;
_memCartridge = cartridgeBuffer;
CheckCartridge(batteriesPath);
_isLoaded = true;
}
Cartridge::~Cartridge(void)
{
DestroyMBC();
if (_memCartridge)
delete [] _memCartridge;
}
/*
* Comprueba el buffer de la rom, extrae el nombre, compara el tamaño e inicializa el MBC
*/
void Cartridge::CheckCartridge(string batteriesPath)
{
MBCPathBatteries(batteriesPath);
_name = string((char *)&_memCartridge[CART_NAME], 16);
CheckRomSize((int)_memCartridge[CART_ROM_SIZE], _romSize);
switch(_memCartridge[CART_TYPE])
{
case 0x00: //ROM ONLY
case 0x08: //ROM+RAM
case 0x09: //ROM+RAM+BATTERY
ptrRead = &NoneRead;
ptrWrite = &NoneWrite;
InitMBCNone(_name, _memCartridge, _romSize);
break;
case 0x01: //ROM+MBC1
case 0x02: //ROM+MBC1+RAM
case 0x03: //ROM+MBC1+RAM+BATT
ptrRead = &MBC1Read;
ptrWrite = &MBC1Write;
InitMBC1(_name, _memCartridge, _romSize, _memCartridge[CART_RAM_SIZE]);
break;
case 0x05: //ROM+MBC2
case 0x06: //ROM+MBC2+BATTERY
ptrRead = &MBC2Read;
ptrWrite = &MBC2Write;
InitMBC2(_name, _memCartridge, _romSize);
break;
/*
case 0x0B: //ROM+MMM01
case 0x0C: //ROM+MMM01+SRAM
case 0x0D: mbc = MMM01; break; //ROM+MMM01+SRAM+BATT*/
case 0x0F: //ROM+MBC3+TIMER+BATT
case 0x10: //ROM+MBC3+TIMER+RAM+BATT
case 0x11: //ROM+MBC3
case 0x12: //ROM+MBC3+RAM
case 0x13: //ROM+MBC3+RAM+BATT
ptrRead = &MBC3Read;
ptrWrite = &MBC3Write;
InitMBC3(_name, _memCartridge, _romSize, _memCartridge[CART_RAM_SIZE]);
break;
case 0x19: //ROM+MBC5
case 0x1A: //ROM+MBC5+RAM
case 0x1B: //ROM+MBC5+RAM+BATT
case 0x1C: //ROM+MBC5+RUMBLE
case 0x1D: //ROM+MBC5+RUMBLE+SRAM
case 0x1E: //ROM+MBC5+RUMBLE+SRAM+BATT
ptrRead = &MBC5Read;
ptrWrite = &MBC5Write;
InitMBC5(_name, _memCartridge, _romSize, _memCartridge[CART_RAM_SIZE]);
break;
/*case 0x1F: //Pocket Camera
case 0xFD: //Bandai TAMA5
case 0xFE: mbc = Other; break; //Hudson HuC-3
case 0xFF: mbc = HuC1; break; //Hudson HuC-1*/
default: throw GBException("MBC not implemented yet");
}
}
/*
* Compara el tamaño de la rom con el valor de la cabecera
*/
int Cartridge::CheckRomSize(int numHeaderSize, int fileSize)
{
int headerSize = 32768 << (numHeaderSize & 0x0F);
if (numHeaderSize & 0xF0)
headerSize += (32768 << ((numHeaderSize & 0xF0) >> 0x04));
if (headerSize != fileSize)
{
cout << "The header does not match with the file size" << endl;
return 0;
}
else
return 1;
}
BYTE *Cartridge::GetData()
{
return _memCartridge;
}
unsigned int Cartridge::GetSize()
{
return _romSize;
}
string Cartridge::GetName()
{
return _name;
}
bool Cartridge::IsLoaded()
{
return _isLoaded;
}
void Cartridge::SaveMBC(ofstream * file)
{
MBCSaveState(file);
}
void Cartridge::LoadMBC(ifstream * file)
{
MBCLoadState(file);
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Settings.h"
#include <wx/wx.h>
using namespace std;
Settings settings;
Settings::Settings()
{
greenScale = false;
windowZoom = 1;
soundEnabled = true;
soundSampleRate = 44100;
padKeys[0] = WXK_UP; // Up
padKeys[1] = WXK_DOWN; // Down
padKeys[2] = WXK_LEFT; // Left
padKeys[3] = WXK_RIGHT;// Right
padKeys[4] = 'A'; // A
padKeys[5] = 'S'; // B
padKeys[6] = 'Q'; // Select
padKeys[7] = 'W'; // Start
}
Settings SettingsGetCopy()
{
return settings;
}
void SettingsSetNewValues(Settings newSettings)
{
settings = newSettings;
}
bool SettingsGetGreenScale()
{
return settings.greenScale;
}
void SettingsSetGreenScale(bool greenScale)
{
settings.greenScale = greenScale;
}
int SettingsGetWindowZoom()
{
return settings.windowZoom;
}
void SettingsSetWindowZoom(int windowZoom)
{
settings.windowZoom = windowZoom;
}
bool SettingsGetSoundEnabled()
{
return settings.soundEnabled;
}
void SettingsSetSoundEnabled(bool enabled)
{
settings.soundEnabled = enabled;
}
int SettingsGetSoundSampleRate()
{
return settings.soundSampleRate;
}
void SettingsSetSoundSampleRate(int sampleRate)
{
settings.soundSampleRate = sampleRate;
}
int* SettingsGetInput()
{
return &settings.padKeys[0];
}
void SettingsSetInput(const int* padKeys)
{
for (int i=0; i<8; i++)
{
settings.padKeys[i] = padKeys[i];
}
}
string* SettingsGetRecentRoms()
{
return &settings.recentRoms[0];
}
void SettingsSetRecentRoms(const string* recentRoms)
{
for (int i=0; i<10; i++)
{
settings.recentRoms[i] = recentRoms[i];
}
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MBC.h"
#include "GBException.h"
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
static BYTE * _memCartridge = NULL;
static BYTE * _memRamMBC = NULL;
static int _memMode = 0;
static int _romBank = 1;
static int _romSize = 0; //Bytes
static int _ramBank = 0;
static int _ramSize = 0; //Bytes
static int _ramEnabled = 0;
static string _romName = "";
static string _pathBatteries = "";
void MBCSaveRam();
void MBCLoadRam();
void InitMBC(string romName, BYTE * memCartridge, int romSize)
{
_romName = romName;
_memCartridge = memCartridge;
_memMode = 0;
_romBank = 1;
_romSize = romSize;
_ramBank = 0;
_ramEnabled = 0;
_ramSize = 0;
_memRamMBC = NULL;
}
void InitMBCNone(string romName, BYTE * memCartridge, int romSize)
{
InitMBC(romName, memCartridge, romSize);
}
void InitMBC1(string romName, BYTE * memCartridge, int romSize, int ramHeaderSize)
{
InitMBC(romName, memCartridge, romSize);
if (ramHeaderSize == 0x01)
_ramSize = 2048; //2KB
else if (ramHeaderSize == 0x02)
_ramSize = 8192; //8KB
else if (ramHeaderSize == 0x03)
_ramSize = 32768; //32KB
if (_ramSize)
_memRamMBC = new BYTE[_ramSize];
MBCLoadRam();
}
void InitMBC2(string romName, BYTE * memCartridge, int romSize)
{
InitMBC(romName, memCartridge, romSize);
_ramSize = 512;
_memRamMBC = new BYTE[_ramSize];
MBCLoadRam();
}
void InitMBC3(string romName, BYTE * memCartridge, int romSize, int ramHeaderSize)
{
InitMBC(romName, memCartridge, romSize);
if (ramHeaderSize == 0x01)
_ramSize = 8192; //8KB = 64Kb
else if (ramHeaderSize == 0x02)
_ramSize = 32768; //32KB = 256Kb
else if (ramHeaderSize == 0x03)
_ramSize = 131072; //128KB = 1Mb
if (_ramSize)
_memRamMBC = new BYTE[_ramSize];
MBCLoadRam();
}
void InitMBC5(string romName, BYTE * memCartridge, int romSize, int ramHeaderSize)
{
InitMBC1(romName, memCartridge, romSize, ramHeaderSize);
}
void DestroyMBC()
{
if (_memRamMBC)
delete [] _memRamMBC;
}
BYTE NoneRead(WORD direction)
{
return _memCartridge[direction];
}
void NoneWrite(WORD direction, BYTE value)
{
//No hacer nada
return;
}
void MBC1Write(WORD direction, BYTE value)
{
if (direction < 0x2000) //Habilitar/Deshabilitar RAM
{
_ramEnabled = ((value & 0x0F) == 0x0A);
if (!_ramEnabled)
MBCSaveRam();
}
else if (direction < 0x4000) //Cambiar romBank
{
value &= 0x1F;
if (!value)
value++;
_romBank = (_romBank & 0x60) | value;
}
else if (direction < 0x6000) //Cambiar romBank o ramBank dependiendo del modo
{
if (!_memMode) //Modo 16/8 (Seleccionar romBank)
{
_romBank = ((value & 0x03) << 5) | (_romBank & 0x1F);
}
else //Modo 4/32 (Seleccionar ramBank)
{
_ramBank = value & 0x03;
}
}
else if (direction < 0x8000) //Seleccionar modo
{
_memMode = value & 0x01;
}
else if ((direction >=0xA000) && (direction < 0xC000)) //Intenta escribir en RAM
{
if (_ramEnabled)
_memRamMBC[direction - 0xA000 + (0x2000*_ramBank)] = value;
}
}
BYTE MBC1Read(WORD direction)
{
if (direction < 0x4000)
return _memCartridge[direction];
else if (direction < 0x8000)
return _memCartridge[(direction - 0x4000) + (0x4000*_romBank)];
else if ((direction >=0xA000) && (direction < 0xC000) && _ramEnabled)
return _memRamMBC[direction - 0xA000 + (0x2000*_ramBank)];
return 0;
}
void MBC2Write(WORD direction, BYTE value)
{
if (direction < 0x2000) //Habilitar/Deshabilitar RAM
{
if (! (direction & 0x10))
_ramEnabled = !_ramEnabled;
if (!_ramEnabled)
MBCSaveRam();
}
else if (direction < 0x4000) //Cambiar romBank
{
if (!(direction & 0x100))
return;
value &= 0x0F;
if (!value)
value++;
_romBank = value;
}
else if (direction < 0x6000)
{
return;
}
else if (direction < 0x8000) //Seleccionar modo
{
return;
}
else if ((direction >=0xA000) && (direction < 0xA200)) //Intenta escribir en RAM
{
if (_ramEnabled)
_memRamMBC[direction - 0xA000] = value & 0x0F;
//throw GBException("Intenta escribir en RAM de cartucho");
}
}
BYTE MBC2Read(WORD direction)
{
if (direction < 0x4000)
return _memCartridge[direction];
else if (direction < 0x8000)
return _memCartridge[(direction - 0x4000) + (0x4000*_romBank)];
else if ((direction >=0xA000) && (direction < 0xC000) && (_ramEnabled))
return _memRamMBC[direction - 0xA000];
return 0;
}
void MBC3Write(WORD direction, BYTE value)
{
if (direction < 0x2000) //Habilitar/Deshabilitar RAM
{
_ramEnabled = ((value & 0x0F) == 0x0A);
if (!_ramEnabled)
MBCSaveRam();
}
else if (direction < 0x4000) //Cambiar romBank
{
value = value ? value : 1;
_romBank = value & 0x7F;
}
else if (direction < 0x6000) //Cambiar ramBank o RTC
{
if (value < 4) //(Seleccionar ramBank)
{
_ramBank = value;
}
else if ((value >= 0x08) && (value <=0x0C)) //Seleccionar RTC
{
//throw GBException("RTC no implementado");
}
}
else if (direction < 0x8000)
{
//throw GBException("RTC no implementado");
}
else if ((direction >=0xA000) && (direction < 0xC000)) //Intenta escribir en RAM
{
if (_ramEnabled)
_memRamMBC[direction - 0xA000 + (0x2000*_ramBank)] = value;
}
}
BYTE MBC3Read(WORD direction)
{
if (direction < 0x4000)
return _memCartridge[direction];
else if (direction < 0x8000)
return _memCartridge[(direction - 0x4000) + (0x4000*_romBank)];
else if ((direction >=0xA000) && (direction < 0xC000) && (_ramEnabled))
return _memRamMBC[direction - 0xA000 + (0x2000*_ramBank)];
return 0;
}
void MBC5Write(WORD direction, BYTE value)
{
if (direction < 0x2000) //Habilitar/Deshabilitar RAM
{
_ramEnabled = ((value & 0x0F) == 0x0A);
if (!_ramEnabled)
MBCSaveRam();
}
else if (direction < 0x3000) //Cambiar romBank
{
_romBank = (_romBank & 0x100) | value;
}
else if (direction < 0x4000) //Cambiar romBank
{
_romBank = ((value & 0x01) << 8) | (_romBank & 0xFF);
}
else if (direction < 0x6000) //Cambiar ramBank o RTC
{
_ramBank = value & 0x0F;
}
else if (direction < 0x8000)
{
//throw GBException("Zona no conocida");
}
else if ((direction >=0xA000) && (direction < 0xC000)) //Intenta escribir en RAM
{
if (_ramEnabled)
_memRamMBC[direction - 0xA000 + (0x2000*_ramBank)] = value;
}
}
BYTE MBC5Read(WORD direction)
{
if (direction < 0x4000)
return _memCartridge[direction];
else if (direction < 0x8000)
return _memCartridge[(direction - 0x4000) + (0x4000*_romBank)];
else if ((direction >=0xA000) && (direction < 0xC000) && (_ramEnabled))
return _memRamMBC[direction - 0xA000 + (0x2000*_ramBank)];
return 0;
}
void MBCLoadRam()
{
stringstream fileName;
fileName << _pathBatteries.c_str() << _romName.c_str() << ".BATT";
ifstream file(fileName.str().c_str(), ios::in|ios::binary);
if (file)
{
file.read((char *)_memRamMBC, _ramSize);
file.close();
}
}
void MBCSaveRam()
{
if (_ramSize == 0)
return;
stringstream fileName;
fileName << _pathBatteries.c_str() << _romName.c_str() << ".BATT";
ofstream file(fileName.str().c_str(), ios::out|ios::trunc|ios::binary);
if (file)
{
file.write((char *)_memRamMBC, _ramSize);
file.close();
}
}
void MBCPathBatteries(string path)
{
_pathBatteries = path;
}
void MBCSaveState(ofstream * file)
{
file->write((char *)&_memMode, sizeof(int));
file->write((char *)&_romBank, sizeof(int));
file->write((char *)&_romSize, sizeof(int));
file->write((char *)&_ramBank, sizeof(int));
file->write((char *)&_ramSize, sizeof(int));
file->write((char *)&_ramEnabled, sizeof(int));
file->write((char *)_memRamMBC, _ramSize);
}
void MBCLoadState(ifstream * file)
{
file->read((char *)&_memMode, sizeof(int));
file->read((char *)&_romBank, sizeof(int));
file->read((char *)&_romSize, sizeof(int));
file->read((char *)&_ramBank, sizeof(int));
file->read((char *)&_ramSize, sizeof(int));
file->read((char *)&_ramEnabled, sizeof(int));
file->read((char *)_memRamMBC, _ramSize);
}
/*
Game Boy MMM01 emulation
Author: byuu
Date: 2010-01-04
Games that use MMM01:
=====================
Momotarou Collection 2
Taito Variety Pack
Word of warning:
================
There are bad dumps of the above games floating around.
Verify correct dumps by examining in hex editor:
Momotarou Collection 2:
00000 = Momotarou Collection 2 [menu]
08000 = Momotarou Dengeki
88000 = Momotarou Gaiden
Taito Variety Pack:
00000 = Taito Variety Pack [menu]
08000 = Sagaia
28000 = Chase HQ
48000 = Bubble Bobble
68000 = Elevator Action
The bad dumps place the menu at the very end of the ROM.
If this is the case, header detection will fail.
Assuming you have a bad dump, you will have to fix it yourself.
Here is example code to fix Momotarou Collection 2:
#include <stdio.h>
int main() {
FILE *fp = fopen("momo.gb", "rb");
char g1[0x80000]; fread(g1, 1, 0x80000, fp);
char g2[0x78000]; fread(g2, 1, 0x78000, fp);
char g3[0x08000]; fread(g3, 1, 0x08000, fp);
fclose(fp);
fp = fopen("momo-out.gb", "wb");
fwrite(g3, 1, 0x08000, fp);
fwrite(g1, 1, 0x80000, fp);
fwrite(g2, 1, 0x78000, fp);
fclose(fp);
return 0;
}
Detecting MMM01:
================
switch(romdata[0x0147]) {
...
case 0x0b: info.mapper = Mapper::MMM01; break;
case 0x0c: info.mapper = Mapper::MMM01; info.ram = true; break;
case 0x0d: info.mapper = Mapper::MMM01; info.ram = true; info.battery = true; break;
...
}
Emulating MMM01:
================
The MMM01 is a meta-mapper, it allows one to map 0000-3fff.
Once a sub-game is mapped in, the MMM01 reverts to an ordinary
mapper, allowing mapping of 4000-7fff and a000-bfff.
Here is the source code for an MMM01 emulator.
I cannot guarantee its completeness.
struct MMM01 : MMIO {
bool rom_mode;
uint8 rom_base;
bool ram_enable;
uint8 rom_select;
uint8 ram_select;
uint8 mmio_read(uint16 addr);
void mmio_write(uint16 addr, uint8 data);
void power();
} mmm01;
uint8 Cartridge::MMM01::mmio_read(uint16 addr) {
if((addr & 0x8000) == 0x0000) {
if(rom_mode == 0) return cartridge.rom_read(addr);
}
if((addr & 0xc000) == 0x0000) {
return cartridge.rom_read(0x8000 + (rom_base << 14) + (addr & 0x3fff));
}
if((addr & 0xc000) == 0x4000) {
return cartridge.rom_read(0x8000 + (rom_base << 14) + (rom_select << 14) + (addr & 0x3fff));
}
if((addr & 0xe000) == 0xa000) {
if(ram_enable) return cartridge.ram_read((ram_select << 13) + (addr & 0x1fff));
return 0x00;
}
return 0x00;
}
void Cartridge::MMM01::mmio_write(uint16 addr, uint8 data) {
if((addr & 0xe000) == 0x0000) { //0000-1fff
if(rom_mode == 0) {
rom_mode = 1;
} else {
ram_enable = (data & 0x0f) == 0x0a;
}
}
if((addr & 0xe000) == 0x2000) { //2000-3fff
if(rom_mode == 0) {
rom_base = data & 0x3f;
} else {
rom_select = data;
}
}
if((addr & 0xe000) == 0x4000) { //4000-5fff
if(rom_mode == 1) {
ram_select = data;
}
}
if((addr & 0xe000) == 0x6000) { //6000-7fff
//unknown purpose
}
if((addr & 0xe000) == 0xa000) { //a000-bfff
if(ram_enable) cartridge.ram_write((ram_select << 13) + (addr & 0x1fff), data);
}
}
void Cartridge::MMM01::power() {
rom_mode = 0;
rom_base = 0x00;
ram_enable = false;
rom_select = 0x01;
ram_select = 0x00;
}
*/ | C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include <wx/wx.h>
#include <iostream>
#include "Pad.h"
#include "GBException.h"
using namespace std;
static wxKeyCode keysUsed[] = { WXK_UP, WXK_DOWN, WXK_LEFT, WXK_RIGHT, (wxKeyCode)'A', (wxKeyCode)'S', (wxKeyCode)'Q', (wxKeyCode)'W' };
static BYTE gbPadState[8];
void PadSetKeys(int * keys)
{
for (int i=0; i<8; i++)
keysUsed[i] = (wxKeyCode)keys[i];
}
BYTE PadUpdateInput(BYTE valueP1)
{
if(!BIT5(valueP1))
return ((valueP1 & 0x30) |
(!gbPadState[gbSTART] << 3) | (!gbPadState[gbSELECT] << 2) | (!gbPadState[gbB] << 1) | (!gbPadState[gbA]));
if(!BIT4(valueP1))
return ((valueP1 & 0x30) |
(!gbPadState[gbDOWN] << 3) | (!gbPadState[gbUP] << 2) | (!gbPadState[gbLEFT] << 1) | (!gbPadState[gbRIGHT]));
//Desactivar los botones
return 0x3F;
}
// Devuelve 1 cuando se ha pulsado una tecla
// 0 en caso contrario
int PadCheckKeyboard(BYTE * valueP1)
{
int interrupt = 0;
for (int i=0; i<8; i++)
{
if ((gbPadState[i] == 0) && (wxGetKeyState(keysUsed[i]) == true))
{
interrupt = 1;
}
gbPadState[i] = wxGetKeyState(keysUsed[i]);
}
*valueP1 = PadUpdateInput(*valueP1);
return 0;
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Log.h"
#include <fstream>
#include <string>
using namespace std;
QueueLog::QueueLog(int maxItems)
{
if (maxItems <= 0)
maxItems = 100;
this->maxItems = maxItems;
this->numItems = 0;
this->first = NULL;
this->last = NULL;
}
QueueLog::~QueueLog()
{
ItemLog * item;
ItemLog * auxItem;
item = first;
while (item) {
auxItem = item->next;
if (item->regs)
delete item->regs;
delete item;
item = auxItem;
}
}
void QueueLog::Enqueue(string prefix, Registers * regs, string suffix)
{
ItemLog * newItem = new ItemLog;
newItem->prefix = prefix;
newItem->regs = NULL;
if (regs)
{
newItem->regs = new Registers();
*newItem->regs = *regs;
}
newItem->suffix = suffix;
newItem->next = NULL;
newItem->prev = NULL;
if (numItems >= maxItems)
{
first = first->next;
//Borrar el más viejo
if (first->prev->regs)
delete first->prev->regs;
delete first->prev;
first->prev = NULL;
numItems--;
}
if (first == NULL)
{
first = newItem;
last = newItem;
}
else
{
last->next = newItem;
newItem->prev = last;
last = newItem;
}
numItems++;
}
void QueueLog::Save(string path)
{
ofstream file(path.c_str(), ios_base::out);
if (file)
{
ItemLog * item;
item = first;
while (item) {
file << item->prefix;
if (item->regs)
file << item->regs->ToString();
file << item->suffix << endl;
item = item->next;
}
file.close();
}
}
| C++ |
/*
This file is part of gbpablog.
gbpablog is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
gbpablog is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with gbpablog. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __IGBSCREENDRAWABLE_H__
#define __IGBSCREENDRAWABLE_H__
class IGBScreenDrawable
{
public:
virtual void OnPreDraw() = 0;
virtual void OnPostDraw() = 0;
virtual void OnDrawPixel(int idColor, int x, int y) = 0;
virtual void OnRefreshScreen() = 0;
virtual void OnClear() = 0;
};
#endif | C++ |
#include <iostream>
class Errors
{
private:
int liczba_bledow;
public:
int getLiczbaBledow()
{
return liczba_bledow;
}
double blad(const char* s)
{
std::cerr << "blad: " << s << '\n';
liczba_bledow++;
return 1;
}
};
| C++ |
// kalkulator
#include <iostream>
#include <strstream>
#include <ctype.h>
#include <math.h>
using namespace std;
/************* typy i zmienne globalne ***********/
enum wartosc_symbolu {
NAZWA, LICZBA, KONIEC,
PLUS='+', MINUS='-', MNOZ='*', DZIEL='/', POTEGA='^',
DRUK=';', PRZYPIS='=',LN='(', PN=')'
};
wartosc_symbolu biezacy_symbol;
double wartosc_liczby;
char napis[256];
/*************************************************/
/*************** obsuga bledow********************/
int liczba_bledow;
double blad(const char* s)
{
cerr << "blad: " << s << '\n';
liczba_bledow++;
return 1;
}
/*************************************************/
/**************** tablica symboli*****************/
#include <string.h>
struct nazwa {
char* napis;
nazwa* nast;
double wartosc;
};
int const ROZMTBL = 23;
nazwa* tablica[ROZMTBL];
nazwa* szukaj(const char* p, int wst=0)
{
int ii = 0; //mieszaj
const char* pp = p;
while (*pp) ii = ii<<1 ^ *pp++;
if (ii < 0) ii = -ii;
ii %= ROZMTBL;
for (nazwa* n=tablica[ii]; n; n=n->nast) //szukaj
if (strcmp(p,n->napis) == 0) return n;
if (wst==0) blad("nie znaleziono nazwy");
nazwa* nn = new nazwa; //wstaw
nn->napis = new char[strlen(p)+1];
strcpy(nn->napis,p);
nn->wartosc = 1;
nn->nast = tablica[ii];
tablica[ii] = nn;
return nn;
}
inline nazwa* wstaw(const char* s) {return szukaj(s,1);}
/*******************************************************/
/****************** funkcja wejsciowa ******************/
wartosc_symbolu daj_symbol()
{
char ch;
do { // pomin wszystkie biale spacje z wyjatkiem '\n'
if (!cin.get(ch)) return biezacy_symbol = KONIEC;
} while (ch!='\n' && isspace(ch));
switch(ch) {
case ';':
case '\n':
return biezacy_symbol = DRUK;
case '^':
case '*':
case '/':
case '+':
case '-':
case '(':
case ')':
case '=':
return biezacy_symbol = wartosc_symbolu(ch);
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
cin.putback(ch);
cin >> wartosc_liczby;
return biezacy_symbol=LICZBA;
default: //NAZWA, NAZWA= lub blad
if (isalpha(ch)) {
char* p = napis;
*p++ = ch;
while (cin.get(ch) && isalnum(ch)) *p++ = ch;
cin.putback(ch);
*p = 0;
return biezacy_symbol = NAZWA;
}
blad("niepoprawny symbol");
return biezacy_symbol=DRUK;
}
}
/*********************************************************/
/************************* parser ************************/
double wyrazenie();
double czynnik() // obsluz czynniki
{
switch (biezacy_symbol) {
case LICZBA:
daj_symbol(); // stala zmiennopozycyjna
return wartosc_liczby;
case NAZWA:
if (daj_symbol() == PRZYPIS) {
nazwa* n = wstaw(napis);
daj_symbol();
n->wartosc = wyrazenie();
return n->wartosc;
}
return szukaj(napis)->wartosc;
case MINUS: // minus jednoargumentowy
daj_symbol();
return -czynnik();
case LN:
{ daj_symbol();
double e = wyrazenie();
if (biezacy_symbol != PN) return blad("spodziewany )");
daj_symbol();
return e;
}
case KONIEC:
return 1;
default:
return blad("spodziewany czynnik");
}
}
double potega()
{
double lewa = czynnik();
for(;;)
switch(biezacy_symbol) {
case POTEGA:
daj_symbol(); // zjedz ^
lewa = pow(lewa, potega());
break;
default:
return lewa;
}
}
double skladnik() // pomnoz i podziel
{
double lewa = potega();
for(;;)
switch (biezacy_symbol) {
case MNOZ:
daj_symbol(); // zjedz *
lewa *= potega();
break;
case DZIEL:
{ daj_symbol(); // zjedz /
double d = potega();
if (d == 0) return blad("dzielenie przez 0");
lewa /= d;
break;
}
default:
return lewa;
}
}
double wyrazenie() // dodaj i odejmij
{
double lewa = skladnik();
for(;;) // petla nieskonczona
switch (biezacy_symbol) {
case PLUS:
daj_symbol(); // zjedz +
lewa += skladnik();
break;
case MINUS:
daj_symbol(); // zjedz -
lewa -= skladnik();
break;
default:
return lewa;
}
}
/*********************************************************/
/***************** program sterujacy *********************/
int main(int argc, char* argv[])
{
switch(argc) {
case 1: // czytaj ze standardowego pliku wejsciowego
break;
case 2: // czytaj napis argumentow
// cin = *new istrstream(argv[1], strlen(argv[1]));
break;
default:
blad("za duzo argumentow");
return 1;
}
// wstaw nazwy zdefiniowane pierwotnie
wstaw("pi")->wartosc = 3.1415926535897932385;
wstaw("e")->wartosc = 2.7182818284590452354;
while(cin) {
daj_symbol();
if (biezacy_symbol == KONIEC) break;
if (biezacy_symbol == DRUK) continue;
cout << wyrazenie() << "\n";
}
return liczba_bledow;
}
| C++ |
#include <vector>
#include <string>
#include <iostream>
#include "Errors.cpp"
using namespace std;
class nazwa {
private:
string napis;
double wartosc;
public:
nazwa(string text,double value)
{
napis=text;
wartosc=value;
}
double getWartosc()
{
return wartosc;
}
char* getNapis()
{
napis.c_str();
}
double setWartosc(double v)
{
wartosc=v;
return wartosc;
}
char* setNapis(string s)
{
napis=s;
napis.c_str();
}
};
class Lista
{
private:
vector<nazwa> Lista;
Errors e;
public:
nazwa szukaj(string p, int wst=0,double value=1)
{
for(int i=0;i<Lista.size();i++)
{
if(strcmp(Lista.at(i).getNapis(),p.c_str())==0)
{
return Lista.at(i);
}
}
if (wst==0) e.blad("nie znaleziono nazwy");
nazwa nn(p,value); //wstaw
Lista.push_back(nn);
return nn;
}
nazwa wstaw(string s,double value=1) {
return szukaj(s,1,value);
}
int getLiczbaBledow()
{
return e.getLiczbaBledow();
}
};
| C++ |
#include <iostream>
#include <strstream>
#include "Inter.cpp"
#include <ctype.h>
#include <math.h>
using namespace std;
int main(int argc, char* argv[])
{
Inter i;
Errors e;
switch(argc) {
case 1: // czytaj ze standardowego pliku wejsciowego
break;
case 2: // czytaj napis argumentow
// cin = *new istrstream(argv[1], strlen(argv[1]));
break;
default:
e.blad("za duzo argumentow");
return 1;
}
// wstaw nazwy zdefiniowane pierwotnie
i.wstaw("pi",3.1415926535897932385) ;
i.wstaw("e",2.7182818284590452354) ;
while(cin) {
i.daj_symbol();
if (i.getBierzacySymblo() == KONIEC) break;
if (i.getBierzacySymblo() == DRUK) continue;
cout << i.wyraz() << "\n";
}
return i.GetLiczbaBledow();
}
| C++ |
#include <iostream>
#include <strstream>
#include "Lista.cpp"
#include <ctype.h>
#include <math.h>
using namespace std;
enum wartosc_symbolu {
NAZWA, LICZBA, KONIEC,
PLUS='+', MINUS='-', MNOZ='*', DZIEL='/', POTEGA='^',
DRUK=';', PRZYPIS='=',LN='(', PN=')'
};
class Inter
{
private:
wartosc_symbolu biezacy_symbol;
double wartosc_liczby;
char napis[256];
Lista tablica;
Errors e;
double czynnik() // obsluz czynniki
{
switch (biezacy_symbol) {
case LICZBA:
daj_symbol(); // stala zmiennopozycyjna
return wartosc_liczby;
case NAZWA:
if (daj_symbol() == PRZYPIS) {
daj_symbol();
double temp=wyrazenie();
nazwa n = tablica.wstaw(string(napis),temp);
return n.getWartosc();
}
return tablica.szukaj(napis).getWartosc();
case MINUS: // minus jednoargumentowy
daj_symbol();
return -czynnik();
case LN:
{ daj_symbol();
double a = wyrazenie();
if (biezacy_symbol != PN) return e.blad("spodziewany )");
daj_symbol();
return a;
}
case KONIEC:
return 1;
default:
return e.blad("spodziewany czynnik");
}
}
double potega()
{
double lewa = czynnik();
for(;;)
switch(biezacy_symbol) {
case POTEGA:
daj_symbol(); // zjedz ^
lewa = pow(lewa, potega());
break;
default:
return lewa;
}
}
double skladnik() // pomnoz i podziel
{
double lewa = potega();
for(;;)
switch (biezacy_symbol) {
case MNOZ:
daj_symbol(); // zjedz *
lewa *= potega();
break;
case DZIEL:
{ daj_symbol(); // zjedz /
double d = potega();
if (d == 0) return e.blad("dzielenie przez 0");
lewa /= d;
break;
}
default:
return lewa;
}
}
double wyrazenie() // dodaj i odejmij
{
double lewa = skladnik();
for(;;) // petla nieskonczona
switch (biezacy_symbol) {
case PLUS:
daj_symbol(); // zjedz +
lewa += skladnik();
break;
case MINUS:
daj_symbol(); // zjedz -
lewa -= skladnik();
break;
default:
return lewa;
}
}
public:
nazwa wstaw(string s,double value) {
return tablica.szukaj(s,1,value);
}
double wyraz()
{
return wyrazenie();
}
wartosc_symbolu daj_symbol()
{
char ch;
do { // pomin wszystkie biale spacje z wyjatkiem '\n'
if (!cin.get(ch)) return biezacy_symbol = KONIEC;
} while (ch!='\n' && isspace(ch));
switch(ch) {
case ';':
case '\n':
return biezacy_symbol = DRUK;
case '^':
case '*':
case '/':
case '+':
case '-':
case '(':
case ')':
case '=':
return biezacy_symbol = wartosc_symbolu(ch);
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
cin.putback(ch);
cin >> wartosc_liczby;
return biezacy_symbol=LICZBA;
default: //NAZWA, NAZWA= lub blad
if (isalpha(ch)) {
char* p = napis;
*p++ = ch;
while (cin.get(ch) && isalnum(ch)) *p++ = ch;
cin.putback(ch);
*p = 0;
return biezacy_symbol = NAZWA;
}
e.blad("niepoprawny symbol");
return biezacy_symbol=DRUK;
}
}
wartosc_symbolu getBierzacySymblo()
{
return biezacy_symbol;
}
int GetLiczbaBledow(){
return e.getLiczbaBledow()+tablica.getLiczbaBledow();
}
};
| C++ |
// stdafx.cpp : source file that includes just the standard includes
// test.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| C++ |
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
Hello
return 0;
}
| C++ |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "com_google_ase_Exec.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include "android/log.h"
#define LOG_TAG "Exec"
#define LOG(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
void JNU_ThrowByName(JNIEnv* env, const char* name, const char* msg) {
jclass clazz = env->FindClass(name);
if (clazz != NULL) {
env->ThrowNew(clazz, msg);
}
env->DeleteLocalRef(clazz);
}
char* JNU_GetStringNativeChars(JNIEnv* env, jstring jstr) {
if (jstr == NULL) {
return NULL;
}
jbyteArray bytes = 0;
jthrowable exc;
char* result = 0;
if (env->EnsureLocalCapacity(2) < 0) {
return 0; /* out of memory error */
}
jclass Class_java_lang_String = env->FindClass("java/lang/String");
jmethodID MID_String_getBytes = env->GetMethodID(
Class_java_lang_String, "getBytes", "()[B");
bytes = (jbyteArray) env->CallObjectMethod(jstr, MID_String_getBytes);
exc = env->ExceptionOccurred();
if (!exc) {
jint len = env->GetArrayLength(bytes);
result = (char*) malloc(len + 1);
if (result == 0) {
JNU_ThrowByName(env, "java/lang/OutOfMemoryError", 0);
env->DeleteLocalRef(bytes);
return 0;
}
env->GetByteArrayRegion(bytes, 0, len, (jbyte*) result);
result[len] = 0; /* NULL-terminate */
} else {
env->DeleteLocalRef(exc);
}
env->DeleteLocalRef(bytes);
return result;
}
int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) {
jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor");
jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor,
"descriptor", "I");
return env->GetIntField(fileDescriptor, descriptor);
}
static int create_subprocess(
const char* cmd, const char* arg0, const char* arg1, int* pProcessId) {
char* devname;
int ptm;
pid_t pid;
ptm = open("/dev/ptmx", O_RDWR); // | O_NOCTTY);
if(ptm < 0){
LOG("[ cannot open /dev/ptmx - %s ]\n", strerror(errno));
return -1;
}
fcntl(ptm, F_SETFD, FD_CLOEXEC);
if(grantpt(ptm) || unlockpt(ptm) ||
((devname = (char*) ptsname(ptm)) == 0)){
LOG("[ trouble with /dev/ptmx - %s ]\n", strerror(errno));
return -1;
}
pid = fork();
if(pid < 0) {
LOG("- fork failed: %s -\n", strerror(errno));
return -1;
}
if(pid == 0){
int pts;
setsid();
pts = open(devname, O_RDWR);
if(pts < 0) exit(-1);
dup2(pts, 0);
dup2(pts, 1);
dup2(pts, 2);
close(ptm);
execl(cmd, cmd, arg0, arg1, NULL);
exit(-1);
} else {
*pProcessId = (int) pid;
return ptm;
}
}
JNIEXPORT jobject JNICALL Java_com_google_ase_Exec_createSubprocess(
JNIEnv* env, jclass clazz, jstring cmd, jstring arg0, jstring arg1,
jintArray processIdArray) {
char* cmd_8 = JNU_GetStringNativeChars(env, cmd);
char* arg0_8 = JNU_GetStringNativeChars(env, arg0);
char* arg1_8 = JNU_GetStringNativeChars(env, arg1);
int procId;
int ptm = create_subprocess(cmd_8, arg0_8, arg1_8, &procId);
if (processIdArray) {
int procIdLen = env->GetArrayLength(processIdArray);
if (procIdLen > 0) {
jboolean isCopy;
int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy);
if (pProcId) {
*pProcId = procId;
env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0);
}
}
}
jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor");
jmethodID init = env->GetMethodID(Class_java_io_FileDescriptor,
"<init>", "()V");
jobject result = env->NewObject(Class_java_io_FileDescriptor, init);
if (!result) {
LOG("Couldn't create a FileDescriptor.");
} else {
jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor,
"descriptor", "I");
env->SetIntField(result, descriptor, ptm);
}
return result;
}
JNIEXPORT void Java_com_google_ase_Exec_setPtyWindowSize(
JNIEnv* env, jclass clazz, jobject fileDescriptor, jint row, jint col,
jint xpixel, jint ypixel) {
int fd;
struct winsize sz;
fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
if (env->ExceptionOccurred() != NULL) {
return;
}
sz.ws_row = row;
sz.ws_col = col;
sz.ws_xpixel = xpixel;
sz.ws_ypixel = ypixel;
ioctl(fd, TIOCSWINSZ, &sz);
}
JNIEXPORT jint Java_com_google_ase_Exec_waitFor(JNIEnv* env, jclass clazz,
jint procId) {
int status;
waitpid(procId, &status, 0);
int result = 0;
if (WIFEXITED(status)) {
result = WEXITSTATUS(status);
}
return result;
}
| C++ |
/*
** MEMWATCH.H
** Nonintrusive ANSI C memory leak / overwrite detection
** Copyright (C) 1992-2002 Johan Lindh
** All rights reserved.
** Version 2.71
**
************************************************************************
**
** PURPOSE:
**
** MEMWATCH has been written to allow guys and gals that like to
** program in C a public-domain memory error control product.
** I hope you'll find it's as advanced as most commercial packages.
** The idea is that you use it during the development phase and
** then remove the MEMWATCH define to produce your final product.
** MEMWATCH is distributed in source code form in order to allow
** you to compile it for your platform with your own compiler.
** It's aim is to be 100% ANSI C, but some compilers are more stingy
** than others. If it doesn't compile without warnings, please mail
** me the configuration of operating system and compiler you are using
** along with a description of how to modify the source, and the version
** number of MEMWATCH that you are using.
**
************************************************************************
This file is part of MEMWATCH.
MEMWATCH is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
MEMWATCH is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MEMWATCH; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
************************************************************************
**
** REVISION HISTORY:
**
** 920810 JLI [1.00]
** 920830 JLI [1.10 double-free detection]
** 920912 JLI [1.15 mwPuts, mwGrab/Drop, mwLimit]
** 921022 JLI [1.20 ASSERT and VERIFY]
** 921105 JLI [1.30 C++ support and TRACE]
** 921116 JLI [1.40 mwSetOutFunc]
** 930215 JLI [1.50 modified ASSERT/VERIFY]
** 930327 JLI [1.51 better auto-init & PC-lint support]
** 930506 JLI [1.55 MemWatch class, improved C++ support]
** 930507 JLI [1.60 mwTest & CHECK()]
** 930809 JLI [1.65 Abort/Retry/Ignore]
** 930820 JLI [1.70 data dump when unfreed]
** 931016 JLI [1.72 modified C++ new/delete handling]
** 931108 JLI [1.77 mwSetAssertAction() & some small changes]
** 940110 JLI [1.80 no-mans-land alloc/checking]
** 940328 JLI [2.00 version 2.0 rewrite]
** Improved NML (no-mans-land) support.
** Improved performance (especially for free()ing!).
** Support for 'read-only' buffers (checksums)
** ^^ NOTE: I never did this... maybe I should?
** FBI (free'd block info) tagged before freed blocks
** Exporting of the mwCounter variable
** mwBreakOut() localizes debugger support
** Allocation statistics (global, per-module, per-line)
** Self-repair ability with relinking
** 950913 JLI [2.10 improved garbage handling]
** 951201 JLI [2.11 improved auto-free in emergencies]
** 960125 JLI [X.01 implemented auto-checking using mwAutoCheck()]
** 960514 JLI [2.12 undefining of existing macros]
** 960515 JLI [2.13 possibility to use default new() & delete()]
** 960516 JLI [2.20 suppression of file flushing on unfreed msgs]
** 960516 JLI [2.21 better support for using MEMWATCH with DLL's]
** 960710 JLI [X.02 multiple logs and mwFlushNow()]
** 960801 JLI [2.22 merged X.01 version with current]
** 960805 JLI [2.30 mwIsXXXXAddr() to avoid unneeded GP's]
** 960805 JLI [2.31 merged X.02 version with current]
** 961002 JLI [2.32 support for realloc() + fixed STDERR bug]
** 961222 JLI [2.40 added mwMark() & mwUnmark()]
** 970101 JLI [2.41 added over/underflow checking after failed ASSERT/VERIFY]
** 970113 JLI [2.42 added support for PC-Lint 7.00g]
** 970207 JLI [2.43 added support for strdup()]
** 970209 JLI [2.44 changed default filename to lowercase]
** 970405 JLI [2.45 fixed bug related with atexit() and some C++ compilers]
** 970723 JLI [2.46 added MW_ARI_NULLREAD flag]
** 970813 JLI [2.47 stabilized marker handling]
** 980317 JLI [2.48 ripped out C++ support; wasn't working good anyway]
** 980318 JLI [2.50 improved self-repair facilities & SIGSEGV support]
** 980417 JLI [2.51 more checks for invalid addresses]
** 980512 JLI [2.52 moved MW_ARI_NULLREAD to occur before aborting]
** 990112 JLI [2.53 added check for empty heap to mwIsOwned]
** 990217 JLI [2.55 improved the emergency repairs diagnostics and NML]
** 990224 JLI [2.56 changed ordering of members in structures]
** 990303 JLI [2.57 first maybe-fixit-for-hpux test]
** 990516 JLI [2.58 added 'static' to the definition of mwAutoInit]
** 990517 JLI [2.59 fixed some high-sensitivity warnings]
** 990610 JLI [2.60 fixed some more high-sensitivity warnings]
** 990715 JLI [2.61 changed TRACE/ASSERT/VERIFY macro names]
** 991001 JLI [2.62 added CHECK_BUFFER() and mwTestBuffer()]
** 991007 JLI [2.63 first shot at a 64-bit compatible version]
** 991009 JLI [2.64 undef's strdup() if defined, mwStrdup made const]
** 000704 JLI [2.65 added some more detection for 64-bits]
** 010502 JLI [2.66 incorporated some user fixes]
** [mwRelink() could print out garbage pointer (thanks mac@phobos.ca)]
** [added array destructor for C++ (thanks rdasilva@connecttel.com)]
** [added mutex support (thanks rdasilva@connecttel.com)]
** 010531 JLI [2.67 fix: mwMutexXXX() was declared even if MW_HAVE_MUTEX was not defined]
** 010619 JLI [2.68 fix: mwRealloc() could leave the mutex locked]
** 020918 JLI [2.69 changed to GPL, added C++ array allocation by Howard Cohen]
** 030212 JLI [2.70 mwMalloc() bug for very large allocations (4GB on 32bits)]
** 030520 JLI [2.71 added ULONG_LONG_MAX as a 64-bit detector (thanks Sami Salonen)]
**
** To use, simply include 'MEMWATCH.H' as a header file,
** and add MEMWATCH.C to your list of files, and define the macro
** 'MEMWATCH'. If this is not defined, MEMWATCH will disable itself.
**
** To call the standard C malloc / realloc / calloc / free; use mwMalloc_(),
** mwCalloc_() and mwFree_(). Note that mwFree_() will correctly
** free both malloc()'d memory as well as mwMalloc()'d.
**
** 980317: C++ support has been disabled.
** The code remains, but is not compiled.
**
** For use with C++, which allows use of inlining in header files
** and class specific new/delete, you must also define 'new' as
** 'mwNew' and 'delete' as 'mwDelete'. Do this *after* you include
** C++ header files from libraries, otherwise you can mess up their
** class definitions. If you don't define these, the C++ allocations
** will not have source file and line number information. Also note,
** most C++ class libraries implement their own C++ memory management,
** and don't allow anyone to override them. MFC belongs to this crew.
** In these cases, the only thing to do is to use MEMWATCH_NOCPP.
**
** You can capture output from MEMWATCH using mwSetOutFunc().
** Just give it the adress of a "void myOutFunc(int c)" function,
** and all characters to be output will be redirected there.
**
** A failing ASSERT() or VERIFY() will normally always abort your
** program. This can be changed using mwSetAriFunc(). Give it a
** pointer to a "int myAriFunc(const char *)" function. Your function
** must ask the user whether to Abort, Retry or Ignore the trap.
** Return 2 to Abort, 1 to Retry or 0 to Ignore. Beware retry; it
** causes the expression to be evaluated again! MEMWATCH has a
** default ARI handler. It's disabled by default, but you can enable
** it by calling 'mwDefaultAri()'. Note that this will STILL abort
** your program unless you define MEMWATCH_STDIO to allow MEMWATCH
** to use the standard C I/O streams. Also, setting the ARI function
** will cause MEMWATCH *NOT* to write the ARI error to stderr. The
** error string is passed to the ARI function instead, as the
** 'const char *' parameter.
**
** You can disable MEMWATCH's ASSERT/VERIFY and/or TRACE implementations.
** This can be useful if you're using a debug terminal or smart debugger.
** Disable them by defining MW_NOASSERT, MW_NOVERIFY or MW_NOTRACE.
**
** MEMWATCH fills all allocated memory with the byte 0xFE, so if
** you're looking at erroneous data which are all 0xFE:s, the
** data probably was not initialized by you. The exception is
** calloc(), which will fill with zero's. All freed buffers are
** zapped with 0xFD. If this is what you look at, you're using
** data that has been freed. If this is the case, be aware that
** MEMWATCH places a 'free'd block info' structure immediately
** before the freed data. This block contains info about where
** the block was freed. The information is in readable text,
** in the format "FBI<counter>filename(line)", for example:
** "FBI<267>test.c(12)". Using FBI's slows down free(), so it's
** disabled by default. Use mwFreeBufferInfo(1) to enable it.
**
** To aid in tracking down wild pointer writes, MEMWATCH can perform
** no-mans-land allocations. No-mans-land will contain the byte 0xFC.
** MEMWATCH will, when this is enabled, convert recently free'd memory
** into NML allocations.
**
** MEMWATCH protects it's own data buffers with checksums. If you
** get an internal error, it means you're overwriting wildly,
** or using an uninitialized pointer.
**
************************************************************************
**
** Note when compiling with Microsoft C:
** - MSC ignores fflush() by default. This is overridden, so that
** the disk log will always be current.
**
** This utility has been tested with:
** PC-lint 7.0k, passed as 100% ANSI C compatible
** Microsoft Visual C++ on Win16 and Win32
** Microsoft C on DOS
** SAS C on an Amiga 500
** Gnu C on a PC running Red Hat Linux
** ...and using an (to me) unknown compiler on an Atari machine.
**
************************************************************************
**
** Format of error messages in MEMWATCH.LOG:
** message: <sequence-number> filename(linenumber), information
**
** Errors caught by MemWatch, when they are detected, and any
** actions taken besides writing to the log file MEMWATCH.LOG:
**
** Double-freeing:
** A pointer that was recently freed and has not since been
** reused was freed again. The place where the previous free()
** was executed is displayed.
** Detect: delete or free() using the offending pointer.
** Action: The delete or free() is cancelled, execution continues.
** Underflow:
** You have written just ahead of the allocated memory.
** The size and place of the allocation is displayed.
** Detect: delete or free() of the damaged buffer.
** Action: The buffer is freed, but there may be secondary damage.
** Overflow:
** Like underflow, but you've written after the end of the buffer.
** Detect: see Underflow.
** Action: see Underflow.
** WILD free:
** An unrecognized pointer was passed to delete or free().
** The pointer may have been returned from a library function;
** in that case, use mwFree_() to force free() of it.
** Also, this may be a double-free, but the previous free was
** too long ago, causing MEMWATCH to 'forget' it.
** Detect: delete or free() of the offending pointer.
** Action: The delete or free() is cancelled, execution continues.
** NULL free:
** It's unclear to me whether or not freeing of NULL pointers
** is legal in ANSI C, therefore a warning is written to the log file,
** but the error counter remains the same. This is legal using C++,
** so the warning does not appear with delete.
** Detect: When you free(NULL).
** Action: The free() is cancelled.
** Failed:
** A request to allocate memory failed. If the allocation is
** small, this may be due to memory depletion, but is more likely
** to be memory fragmentation problems. The amount of memory
** allocated so far is displayed also.
** Detect: When you new, malloc(), realloc() or calloc() memory.
** Action: NULL is returned.
** Realloc:
** A request to re-allocate a memory buffer failed for reasons
** other than out-of-memory. The specific reason is shown.
** Detect: When you realloc()
** Action: realloc() is cancelled, NULL is returned
** Limit fail:
** A request to allocate memory failed since it would violate
** the limit set using mwLimit(). mwLimit() is used to stress-test
** your code under simulated low memory conditions.
** Detect: At new, malloc(), realloc() or calloc().
** Action: NULL is returned.
** Assert trap:
** An ASSERT() failed. The ASSERT() macro works like C's assert()
** macro/function, except that it's interactive. See your C manual.
** Detect: On the ASSERT().
** Action: Program ends with an advisory message to stderr, OR
** Program writes the ASSERT to the log and continues, OR
** Program asks Abort/Retry/Ignore? and takes that action.
** Verify trap:
** A VERIFY() failed. The VERIFY() macro works like ASSERT(),
** but if MEMWATCH is not defined, it still evaluates the
** expression, but it does not act upon the result.
** Detect: On the VERIFY().
** Action: Program ends with an advisory message to stderr, OR
** Program writes the VERIFY to the log and continues, OR
** Program asks Abort/Retry/Ignore? and takes that action.
** Wild pointer:
** A no-mans-land buffer has been written into. MEMWATCH can
** allocate and distribute chunks of memory solely for the
** purpose of trying to catch random writes into memory.
** Detect: Always on CHECK(), but can be detected in several places.
** Action: The error is logged, and if an ARI handler is installed,
** it is executed, otherwise, execution continues.
** Unfreed:
** A memory buffer you allocated has not been freed.
** You are informed where it was allocated, and whether any
** over or underflow has occured. MemWatch also displays up to
** 16 bytes of the data, as much as it can, in hex and text.
** Detect: When MemWatch terminates.
** Action: The buffer is freed.
** Check:
** An error was detected during a CHECK() operation.
** The associated pointer is displayed along with
** the file and line where the CHECK() was executed.
** Followed immediately by a normal error message.
** Detect: When you CHECK()
** Action: Depends on the error
** Relink:
** After a MEMWATCH internal control block has been trashed,
** MEMWATCH tries to repair the damage. If successful, program
** execution will continue instead of aborting. Some information
** about the block may be gone permanently, though.
** Detect: N/A
** Action: Relink successful: program continues.
** Relink fails: program aborts.
** Internal:
** An internal error is flagged by MEMWATCH when it's control
** structures have been damaged. You are likely using an uninitialized
** pointer somewhere in your program, or are zapping memory all over.
** The message may give you additional diagnostic information.
** If possible, MEMWATCH will recover and continue execution.
** Detect: Various actions.
** Action: Whatever is needed
** Mark:
** The program terminated without umarking all marked pointers. Marking
** can be used to track resources other than memory. mwMark(pointer,text,...)
** when the resource is allocated, and mwUnmark(pointer) when it's freed.
** The 'text' is displayed for still marked pointers when the program
** ends.
** Detect: When MemWatch terminates.
** Action: The error is logged.
**
**
************************************************************************
**
** The author may be reached by e-mail at the address below. If you
** mail me about source code changes in MEMWATCH, remember to include
** MW's version number.
**
** Johan Lindh
** johan@linkdata.se
**
** The latest version of MEMWATCH may be downloaded from
** http://www.linkdata.se/
*/
#ifndef __MEMWATCH_H
#define __MEMWATCH_H
/* Make sure that malloc(), realloc(), calloc() and free() are declared. */
/*lint -save -e537 */
#include <stdlib.h>
/*lint -restore */
#ifdef __cplusplus
extern "C" {
#endif
/*
** Constants used
** All MEMWATCH constants start with the prefix MW_, followed by
** a short mnemonic which indicates where the constant is used,
** followed by a descriptive text about it.
*/
#define MW_ARI_NULLREAD 0x10 /* Null read (to start debugger) */
#define MW_ARI_ABORT 0x04 /* ARI handler says: abort program! */
#define MW_ARI_RETRY 0x02 /* ARI handler says: retry action! */
#define MW_ARI_IGNORE 0x01 /* ARI handler says: ignore error! */
#define MW_VAL_NEW 0xFE /* value in newly allocated memory */
#define MW_VAL_DEL 0xFD /* value in newly deleted memory */
#define MW_VAL_NML 0xFC /* value in no-mans-land */
#define MW_VAL_GRB 0xFB /* value in grabbed memory */
#define MW_TEST_ALL 0xFFFF /* perform all tests */
#define MW_TEST_CHAIN 0x0001 /* walk the heap chain */
#define MW_TEST_ALLOC 0x0002 /* test allocations & NML guards */
#define MW_TEST_NML 0x0004 /* test all-NML areas for modifications */
#define MW_NML_NONE 0 /* no NML */
#define MW_NML_FREE 1 /* turn FREE'd memory into NML */
#define MW_NML_ALL 2 /* all unused memory is NML */
#define MW_NML_DEFAULT 0 /* the default NML setting */
#define MW_STAT_GLOBAL 0 /* only global statistics collected */
#define MW_STAT_MODULE 1 /* collect statistics on a module basis */
#define MW_STAT_LINE 2 /* collect statistics on a line basis */
#define MW_STAT_DEFAULT 0 /* the default statistics setting */
/*
** MemWatch internal constants
** You may change these and recompile MemWatch to change the limits
** of some parameters. Respect the recommended minimums!
*/
#define MW_TRACE_BUFFER 2048 /* (min 160) size of TRACE()'s output buffer */
#define MW_FREE_LIST 64 /* (min 4) number of free()'s to track */
/*
** Exported variables
** In case you have to remove the 'const' keyword because your compiler
** doesn't support it, be aware that changing the values may cause
** unpredictable behaviour.
** - mwCounter contains the current action count. You can use this to
** place breakpoints using a debugger, if you want.
*/
#ifndef __MEMWATCH_C
extern const unsigned long mwCounter;
#endif
/*
** System functions
** Normally, it is not nessecary to call any of these. MEMWATCH will
** automatically initialize itself on the first MEMWATCH function call,
** and set up a call to mwAbort() using atexit(). Some C++ implementations
** run the atexit() chain before the program has terminated, so you
** may have to use mwInit() or the MemWatch C++ class to get good
** behaviour.
** - mwInit() can be called to disable the atexit() usage. If mwInit()
** is called directly, you must call mwTerm() to end MemWatch, or
** mwAbort().
** - mwTerm() is usually not nessecary to call; but if called, it will
** call mwAbort() if it finds that it is cancelling the 'topmost'
** mwInit() call.
** - mwAbort() cleans up after MEMWATCH, reports unfreed buffers, etc.
*/
void mwInit( void );
void mwTerm( void );
void mwAbort( void );
/*
** Setup functions
** These functions control the operation of MEMWATCH's protective features.
** - mwFlushNow() causes MEMWATCH to flush it's buffers.
** - mwDoFlush() controls whether MEMWATCH flushes the disk buffers after
** writes. The default is smart flushing: MEMWATCH will not flush buffers
** explicitly until memory errors are detected. Then, all writes are
** flushed until program end or mwDoFlush(0) is called.
** - mwLimit() sets the allocation limit, an arbitrary limit on how much
** memory your program may allocate in bytes. Used to stress-test app.
** Also, in virtual-memory or multitasking environs, puts a limit on
** how much MW_NML_ALL can eat up.
** - mwGrab() grabs up X kilobytes of memory. Allocates actual memory,
** can be used to stress test app & OS both.
** - mwDrop() drops X kilobytes of grabbed memory.
** - mwNoMansLand() sets the behaviour of the NML logic. See the
** MW_NML_xxx for more information. The default is MW_NML_DEFAULT.
** - mwStatistics() sets the behaviour of the statistics collector. See
** the MW_STAT_xxx defines for more information. Default MW_STAT_DEFAULT.
** - mwFreeBufferInfo() enables or disables the tagging of free'd buffers
** with freeing information. This information is written in text form,
** using sprintf(), so it's pretty slow. Disabled by default.
** - mwAutoCheck() performs a CHECK() operation whenever a MemWatch function
** is used. Slows down performance, of course.
** - mwCalcCheck() calculates checksums for all data buffers. Slow!
** - mwDumpCheck() logs buffers where stored & calc'd checksums differ. Slow!!
** - mwMark() sets a generic marker. Returns the pointer given.
** - mwUnmark() removes a generic marker. If, at the end of execution, some
** markers are still in existence, these will be reported as leakage.
** returns the pointer given.
*/
void mwFlushNow( void );
void mwDoFlush( int onoff );
void mwLimit( long bytes );
unsigned mwGrab( unsigned kilobytes );
unsigned mwDrop( unsigned kilobytes );
void mwNoMansLand( int mw_nml_level );
void mwStatistics( int level );
void mwFreeBufferInfo( int onoff );
void mwAutoCheck( int onoff );
void mwCalcCheck( void );
void mwDumpCheck( void );
void * mwMark( void *p, const char *description, const char *file, unsigned line );
void * mwUnmark( void *p, const char *file, unsigned line );
/*
** Testing/verification/tracing
** All of these macros except VERIFY() evaluates to a null statement
** if MEMWATCH is not defined during compilation.
** - mwIsReadAddr() checks a memory area for read privilige.
** - mwIsSafeAddr() checks a memory area for both read & write privilige.
** This function and mwIsReadAddr() is highly system-specific and
** may not be implemented. If this is the case, they will default
** to returning nonzero for any non-NULL pointer.
** - CHECK() does a complete memory integrity test. Slow!
** - CHECK_THIS() checks only selected components.
** - CHECK_BUFFER() checks the indicated buffer for errors.
** - mwASSERT() or ASSERT() If the expression evaluates to nonzero, execution continues.
** Otherwise, the ARI handler is called, if present. If not present,
** the default ARI action is taken (set with mwSetAriAction()).
** ASSERT() can be disabled by defining MW_NOASSERT.
** - mwVERIFY() or VERIFY() works just like ASSERT(), but when compiling without
** MEMWATCH the macro evaluates to the expression.
** VERIFY() can be disabled by defining MW_NOVERIFY.
** - mwTRACE() or TRACE() writes some text and data to the log. Use like printf().
** TRACE() can be disabled by defining MW_NOTRACE.
*/
int mwIsReadAddr( const void *p, unsigned len );
int mwIsSafeAddr( void *p, unsigned len );
int mwTest( const char *file, int line, int mw_test_flags );
int mwTestBuffer( const char *file, int line, void *p );
int mwAssert( int, const char*, const char*, int );
int mwVerify( int, const char*, const char*, int );
/*
** User I/O functions
** - mwTrace() works like printf(), but dumps output either to the
** function specified with mwSetOutFunc(), or the log file.
** - mwPuts() works like puts(), dumps output like mwTrace().
** - mwSetOutFunc() allows you to give the adress of a function
** where all user output will go. (exeption: see mwSetAriFunc)
** Specifying NULL will direct output to the log file.
** - mwSetAriFunc() gives MEMWATCH the adress of a function to call
** when an 'Abort, Retry, Ignore' question is called for. The
** actual error message is NOT printed when you've set this adress,
** but instead it is passed as an argument. If you call with NULL
** for an argument, the ARI handler is disabled again. When the
** handler is disabled, MEMWATCH will automatically take the
** action specified by mwSetAriAction().
** - mwSetAriAction() sets the default ARI return value MEMWATCH should
** use if no ARI handler is specified. Defaults to MW_ARI_ABORT.
** - mwAriHandler() is an ANSI ARI handler you can use if you like. It
** dumps output to stderr, and expects input from stdin.
** - mwBreakOut() is called in certain cases when MEMWATCH feels it would
** be nice to break into a debugger. If you feel like MEMWATCH, place
** an execution breakpoint on this function.
*/
void mwTrace( const char* format_string, ... );
void mwPuts( const char* text );
void mwSetOutFunc( void (*func)(int) );
void mwSetAriFunc( int (*func)(const char*) );
void mwSetAriAction( int mw_ari_value );
int mwAriHandler( const char* cause );
void mwBreakOut( const char* cause );
/*
** Allocation/deallocation functions
** These functions are the ones actually to perform allocations
** when running MEMWATCH, for both C and C++ calls.
** - mwMalloc() debugging allocator
** - mwMalloc_() always resolves to a clean call of malloc()
** - mwRealloc() debugging re-allocator
** - mwRealloc_() always resolves to a clean call of realloc()
** - mwCalloc() debugging allocator, fills with zeros
** - mwCalloc_() always resolves to a clean call of calloc()
** - mwFree() debugging free. Can only free memory which has
** been allocated by MEMWATCH.
** - mwFree_() resolves to a) normal free() or b) debugging free.
** Can free memory allocated by MEMWATCH and malloc() both.
** Does not generate any runtime errors.
*/
void* mwMalloc( size_t, const char*, int );
void* mwMalloc_( size_t );
void* mwRealloc( void *, size_t, const char*, int );
void* mwRealloc_( void *, size_t );
void* mwCalloc( size_t, size_t, const char*, int );
void* mwCalloc_( size_t, size_t );
void mwFree( void*, const char*, int );
void mwFree_( void* );
char* mwStrdup( const char *, const char*, int );
/*
** Enable/disable precompiler block
** This block of defines and if(n)defs make sure that references
** to MEMWATCH is completely removed from the code if the MEMWATCH
** manifest constant is not defined.
*/
#ifndef __MEMWATCH_C
#ifdef MEMWATCH
#define mwASSERT(exp) while(mwAssert((int)(exp),#exp,__FILE__,__LINE__))
#ifndef MW_NOASSERT
#ifndef ASSERT
#define ASSERT mwASSERT
#endif /* !ASSERT */
#endif /* !MW_NOASSERT */
#define mwVERIFY(exp) while(mwVerify((int)(exp),#exp,__FILE__,__LINE__))
#ifndef MW_NOVERIFY
#ifndef VERIFY
#define VERIFY mwVERIFY
#endif /* !VERIFY */
#endif /* !MW_NOVERIFY */
#define mwTRACE mwTrace
#ifndef MW_NOTRACE
#ifndef TRACE
#define TRACE mwTRACE
#endif /* !TRACE */
#endif /* !MW_NOTRACE */
/* some compilers use a define and not a function */
/* for strdup(). */
#ifdef strdup
#undef strdup
#endif
#define malloc(n) mwMalloc(n,__FILE__,__LINE__)
#define strdup(p) mwStrdup(p,__FILE__,__LINE__)
#define realloc(p,n) mwRealloc(p,n,__FILE__,__LINE__)
#define calloc(n,m) mwCalloc(n,m,__FILE__,__LINE__)
#define free(p) mwFree(p,__FILE__,__LINE__)
#define CHECK() mwTest(__FILE__,__LINE__,MW_TEST_ALL)
#define CHECK_THIS(n) mwTest(__FILE__,__LINE__,n)
#define CHECK_BUFFER(b) mwTestBuffer(__FILE__,__LINE__,b)
#define MARK(p) mwMark(p,#p,__FILE__,__LINE__)
#define UNMARK(p) mwUnmark(p,__FILE__,__LINE__)
#else /* MEMWATCH */
#define mwASSERT(exp)
#ifndef MW_NOASSERT
#ifndef ASSERT
#define ASSERT mwASSERT
#endif /* !ASSERT */
#endif /* !MW_NOASSERT */
#define mwVERIFY(exp) exp
#ifndef MW_NOVERIFY
#ifndef VERIFY
#define VERIFY mwVERIFY
#endif /* !VERIFY */
#endif /* !MW_NOVERIFY */
/*lint -esym(773,mwTRACE) */
#define mwTRACE /*lint -save -e506 */ 1?(void)0:mwDummyTraceFunction /*lint -restore */
#ifndef MW_NOTRACE
#ifndef TRACE
/*lint -esym(773,TRACE) */
#define TRACE mwTRACE
#endif /* !TRACE */
#endif /* !MW_NOTRACE */
extern void mwDummyTraceFunction(const char *,...);
/*lint -save -e652 */
#define mwDoFlush(n)
#define mwPuts(s)
#define mwInit()
#define mwGrab(n)
#define mwDrop(n)
#define mwLimit(n)
#define mwTest(f,l)
#define mwSetOutFunc(f)
#define mwSetAriFunc(f)
#define mwDefaultAri()
#define mwNomansland()
#define mwStatistics(f)
#define mwMark(p,t,f,n) (p)
#define mwUnmark(p,f,n) (p)
#define mwMalloc(n,f,l) malloc(n)
#define mwStrdup(p,f,l) strdup(p)
#define mwRealloc(p,n,f,l) realloc(p,n)
#define mwCalloc(n,m,f,l) calloc(n,m)
#define mwFree(p) free(p)
#define mwMalloc_(n) malloc(n)
#define mwRealloc_(p,n) realloc(p,n)
#define mwCalloc_(n,m) calloc(n,m)
#define mwFree_(p) free(p)
#define mwAssert(e,es,f,l)
#define mwVerify(e,es,f,l) (e)
#define mwTrace mwDummyTrace
#define mwTestBuffer(f,l,b) (0)
#define CHECK()
#define CHECK_THIS(n)
#define CHECK_BUFFER(b)
#define MARK(p) (p)
#define UNMARK(p) (p)
/*lint -restore */
#endif /* MEMWATCH */
#endif /* !__MEMWATCH_C */
#ifdef __cplusplus
}
#endif
#if 0 /* 980317: disabled C++ */
/*
** C++ support section
** Implements the C++ support. Please note that in order to avoid
** messing up library classes, C++ support is disabled by default.
** You must NOT enable it until AFTER the inclusion of all header
** files belonging to code that are not compiled with MEMWATCH, and
** possibly for some that are! The reason for this is that a C++
** class may implement it's own new() function, and the preprocessor
** would substitute this crucial declaration for MEMWATCH new().
** You can forcibly deny C++ support by defining MEMWATCH_NOCPP.
** To enble C++ support, you must be compiling C++, MEMWATCH must
** be defined, MEMWATCH_NOCPP must not be defined, and finally,
** you must define 'new' to be 'mwNew', and 'delete' to be 'mwDelete'.
** Unlike C, C++ code can begin executing *way* before main(), for
** example if a global variable is created. For this reason, you can
** declare a global variable of the class 'MemWatch'. If this is
** is the first variable created, it will then check ALL C++ allocations
** and deallocations. Unfortunately, this evaluation order is not
** guaranteed by C++, though the compilers I've tried evaluates them
** in the order encountered.
*/
#ifdef __cplusplus
#ifndef __MEMWATCH_C
#ifdef MEMWATCH
#ifndef MEMWATCH_NOCPP
extern int mwNCur;
extern const char *mwNFile;
extern int mwNLine;
class MemWatch {
public:
MemWatch();
~MemWatch();
};
void * operator new(size_t);
void * operator new(size_t,const char *,int);
void * operator new[] (size_t,const char *,int); // hjc 07/16/02
void operator delete(void *);
#define mwNew new(__FILE__,__LINE__)
#define mwDelete (mwNCur=1,mwNFile=__FILE__,mwNLine=__LINE__),delete
#endif /* MEMWATCH_NOCPP */
#endif /* MEMWATCH */
#endif /* !__MEMWATCH_C */
#endif /* __cplusplus */
#endif /* 980317: disabled C++ */
#endif /* __MEMWATCH_H */
/* EOF MEMWATCH.H */
| C++ |
/* lex.cpp - implement lexing.
*
* Lex acts like a global singleton that retains in-memory copies
* of
****/
#include "lex.h"
#include <fstream>
// keep constants in private namespace
namespace
{
const size_t IO_SIZE = (1024*16); // grow by this much, as needed
const size_t FIRST_READ = (IO_SIZE * 16); // size of our (big!) first read attempt
const long MAX_FILE_SIZE = (1024*1024*8); // I doubt we could handle 8MB worth of grammar!
}
unique_ptr<char> TToken::Unquote() const
{
assert(Type == Lex::QUOTED);
unique_ptr<char> Result(new char[TextLen-1]);
strncpy(Result.get(), Text+1, TextLen-2);
return Result;
}
TToken TToken::Null = { nullptr, 0, 0 };
int TToken::IsNull()
{
return Text == nullptr && TextLen == 0 && Type == 0;
}
LexFile::LexFile(const char* Path, TFileChars Text, TToken FromInclude_)
: Filename(Path), FileText(std::move(Text)), ErrorCount(0), FromInclude(FromInclude_)
{
}
// defaults do all the work
LexFile::~LexFile()
{
}
// TRover: a reference to a pointer to const chars.
typedef char const * & TRover;
/* GetComment() - we hit a '/' followed by a '/' or '*'
*/
void GetComment(TRover Rover, TToken& Token)
{
Token.Type = Lex::COMMENT;
if(*Rover++ == '/') // if single-line comment
{
for(; *Rover; ++Rover)
if(*Rover == '\n')
break;
}
else // else it's a multi-line style comment
{
for(; *Rover; ++Rover)
if(Rover[0] == '*' && Rover[1] == '/')
break;
}
if(*Rover == '\0')
{
// TODO: use line number when context stuff is working!
ErrorExit(ERROR_EOF_IN_COMMENT, "Unexpected EOF in comment.\n");
}
}
int GetDirective(TRover Rover, TToken& Token)
{
int State = 0;
while(isalpha((unsigned char)*Rover++))
;
if(Rover - Token.Text < TToken::MAXLEN)
{
int Len = int(Rover - Token.Text);
if(Len == 5 && !strncmp("%left", Token.Text, 5))
Token.Type = Lex::LEFT, State = 1;
else if(Len == 6 && !strncmp("%right", Token.Text, 6))
Token.Type = Lex::RIGHT, State = 1;
else if(Len == 9 && !strncmp("%nonassoc", Token.Text, 9))
Token.Type = Lex::NONASSOC, State = 1;
else if(Len == 6 && !strncmp("%token", Token.Text, 6))
Token.Type = Lex::TOKEN;
else if(Len == 8 && !strncmp("%operand", Token.Text, 8))
Token.Type = Lex::OPERAND;
else if(Len == 5 && !strncmp("%test", Token.Text, 5))
Token.Type = Lex::TEST;
else if(Len == 6 && !strncmp("%start", Token.Text, 6))
Token.Type = Lex::START;
else
Token.Type = Lex::UNKDIR;
}
return State;
}
void GetWhite(TRover Rover, TToken& Token)
{
Token.Type = Lex::WHITESPACE;
while(strchr(" \t\r\v\f", *Rover))
++Rover;
}
int GetIdent(char const* &Rover, TToken& Token)
{
while(isalnum((unsigned char)*Rover) || *Rover == '_')
++Rover;
Token.Type = Lex::IDENT;
return 0;
}
typedef char* charp;
/* GetNextToken1() - handling operator precedence
*/
int GetNextToken1(char const * &Rover, TToken& Token)
{
char Char;
int State = 1;
Token.Text = Rover;
Token.Type = Lex::NOTUSED;
if((Char=*Rover++) == '\0')
{
Token.Type = Lex::TKEOF;
--Rover;
State = -1;
}
else if(isalpha((unsigned char)Char) || Char == '_')
State = GetIdent(Rover, Token);
else if(strchr(" \t\r\v\f", Char))
GetWhite(Rover, Token);
else if(Char == '/' && (*Rover == '/' || *Rover == '*'))
GetComment(Rover, Token);
else if(Char == '%')
State = GetDirective(Rover, Token);
else
{
switch(Char)
{
case '\n' : Token.Type = Lex::NEWLINE; break;
case '|' : Token.Type = Lex::ORBAR; break;
case ';' : Token.Type = Lex::SEMICOLON; break;
default :
Token.Type = Lex::ILLEGAL;
}
}
if(Rover - Token.Text > TToken::MAXLEN)
{
Token.Type = Lex::TOOLONG;
Token.TextLen = TToken::MAXLEN;
}
else
Token.TextLen = (short)(Rover - Token.Text);
if(Token.Type == Lex::NOTUSED)
fprintf(stderr, "rover=%10.10s\n", Token.Text);
assert(Token.Type != Lex::NOTUSED);
return State;
}
/* GetNextToken0() - normal state of tokenizing.
*/
int GetNextToken0(TRover Rover, TToken& Token)
{
char Char;
int State;
State = 0;
Token.Text = Rover;
Token.Type = Lex::NOTUSED;
if((Char=*Rover++) == '\0')
{
Token.Type = Lex::TKEOF;
--Rover;
State = -1;
}
else if(isalpha((unsigned char)Char) || Char == '_')
State = GetIdent(Rover, Token);
else if(strchr(" \t\r\v\f", Char))
GetWhite(Rover, Token);
else if(Char == '/' && (*Rover == '/' || *Rover == '*'))
GetComment(Rover, Token);
else if(Char == '%')
State = GetDirective(Rover, Token);
else
{
switch(Char)
{
case '\n' : Token.Type = Lex::NEWLINE; break;
case '|' : Token.Type = Lex::ORBAR; break;
case ';' : Token.Type = Lex::SEMICOLON; break;
default :
Token.Type = Lex::ILLEGAL;
}
}
if(Rover - Token.Text > TToken::MAXLEN)
{
Token.Type = Lex::TOOLONG;
Token.TextLen = TToken::MAXLEN;
}
else
Token.TextLen = (short)(Rover - Token.Text);
if(Token.Type == Lex::NOTUSED)
fprintf(stderr, "rover=%10.10s\n", Token.Text);
assert(Token.Type != Lex::NOTUSED);
return State;
}
/* Tokenize() - break input file into tokens.
*
* Returns the number of error tokens encountered. Note that we will
* tokenize successfully, no matter what. Anything bad is just viewed
* as an error token, which is still a token!
*/
typedef int (*STATEFUNC)(TRover Rover, TToken& Token);
int LexFile::Tokenize()
{
char* Rover = &(*FileText)[0]; // get raw pointer
int SectionCount = 0;
TToken Token;
int State = 0; // start state
STATEFUNC Machine[] = { GetNextToken0, GetNextToken1 };
assert(Tokens.size() == 0); // don't call us more than once!
assert(Rover != nullptr);
ErrorCount = 0;
Tokens.reserve(64);
while((State=Machine[State]((TRover)Rover, Token)) >= 0)
{
Tokens.push_back(Token);
switch(Token.Type)
{
case Lex::ILLEGAL :
case Lex::TOOLONG :
case Lex::BADQUOTE : ++ErrorCount;
break;
case Lex::SECTION : ++SectionCount;
break;
}
}
return ErrorCount;
}
/* Lex::FileLoad() - reads contents of Filename to create new LexFile.
*
* Lex is the owner of all such LexFile objects. If a particular file
* was already loaded in the past, we just return a reference to that
* LexFile.
*/
TTokenizedFile Lex::FileLoad(const char* Filename, TToken FromInclude)
{
// caller must check for already loaded file
assert(Files.count(Filename) == 0);
TFileChars FileText(::FileLoad(Filename));
// store it in our map until shutdown time
Files[Filename] = unique_ptr<LexFile>(new LexFile(Filename, std::move(FileText), FromInclude));
// return pointer to loaded file
return Files[Filename].get();
}
TTokenizedFile Lex::Loaded(const char* Filename)
{
std::map<std::string, std::unique_ptr<LexFile> >::iterator Iter;
Iter = Files.find(Filename);
if(Iter == Files.end())
return nullptr;
else
return Iter->second.get();
}
Lex::Lex()
{
}
Lex::~Lex()
{
}
#if 0
char* FileLoad(const char *filename)
{
// open in binary, don't want line ending transformations
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in)
{
in.seekg(0, std::ios::end);
auto Size = in.tellg();
char* contents = new char[(size_t)Size+1];
in.seekg(0, std::ios::beg);
in.read(&contents[0], Size);
in.close();
return(contents);
}
throw(errno);
}
#endif
/* FileLoad() - load the contents of a file into a NUL-terminated string.
*
* There is some funky stuff about standard library file seeking designed
* to permit files larger than you have an integral type for. However,
* our speed drops more than linearly with grammar size, so it's not a
* bad idea to object to being handed a too-large file (e.g., they passed
* us the name of an executable by mistake or something). So, we kill two
* birds with one stone by defining a maximum file size that still fits
* in 32 bits.
*/
static void Resize(const char* Filename, std::vector<char>& Buffer, size_t NewSize)
{
try {
Buffer.resize(NewSize);
}
catch(std::bad_alloc)
{
ErrorExit(ERROR_INPUT_FILE_TOO_BIG,
"Unable to allocate %luKB for reading file '%s' (is it huge?)\n",
(unsigned long)(NewSize / 1024), Filename);
}
}
unique_ptr<std::vector<char>> FileLoad(const char* Filename)
{
unique_ptr<std::vector<char>> Result(new std::vector<char>);
std::vector<char>& Buffer = *Result.get();
size_t LogicalSize = 0;
size_t PhysicalSize = 0;
size_t BytesRead = 0;
assert(Filename != NULL);
assert((IO_SIZE % 512) == 0); // nobody does weird sector sizes, right?
// use exception-safe pointer to hold file handle
unique_ptr<FILE, int(*)(FILE*)> FilePtr(nullptr, fclose);
FilePtr.reset(fopen(Filename, "r"));
if(FilePtr == nullptr)
ErrorExit(ERROR_CANT_OPEN_INPUT_FILE,
"Unable to open '%s' for reading.\n"
"%d: %s\n", Filename, errno, strerror(errno));
for(;;)
{
PhysicalSize = PhysicalSize ? (PhysicalSize+IO_SIZE) : FIRST_READ;
/* +1 is to allow for adding a trailing NUL byte */
Resize(Filename, Buffer, PhysicalSize+1);
BytesRead = fread((void*)(&Buffer[0]+LogicalSize), sizeof(char), IO_SIZE, FilePtr.get());
LogicalSize+= BytesRead;
if(BytesRead != IO_SIZE)
{
/* check for errors first */
if(ferror(FilePtr.get()))
ErrorExit(ERROR_UNKNOWN_FREAD_ERROR,
"Unknown fread() error while reading '%s'\n", Filename);
/* if we hit the end, then we're done */
else if(feof(FilePtr.get()))
{
Buffer[LogicalSize] = '\0';
break; // the only normal exit from the loop!
}
else
ErrorExit(ERROR_FREAD_FELL_SHORT,
"Can't happen: fread() fell short with no errors before EOF.\n");
}
}
// shrink it back down to minimum needed size.
Resize(Filename, Buffer, LogicalSize+1);
return Result;
}
| C++ |
#include "common.h"
#include <string>
#include <map>
#include <memory>
struct TToken;
class LexedFile
{
char* Load(const char* Filename);
friend class Lex;
LexedFile(const char* Filename);
private:
~LexedFile();
LexedFile(const LexedFile& Other); // disallow: private and no definition
LexedFile& operator=(const LexedFile& Other); // disallow: private and no definition
struct Deleter{void operator()(LexedFile*File) const {delete File;}};
std::string Filename; // name of file
char* Buffer; // complete text of file
TToken* Tokens; // array of tokens (result of tokenizing Buffer)
int ErrorCount; // # of error tokens in Tokens
LexedFile* ParentFile; // file that caused us to be loaded (or NULL)
};
class Lex
{
public:
Lex();
~Lex();
LexedFile& FileLoad(const char* Filename);
private:
std::map<std::string, std::unique_ptr<LexedFile, LexedFile::Deleter>> Files;
};
#if 0
LexedFile::~LexedFile()
{
}
Lex::Lex()
{
}
Lex::~Lex()
{
// Files.clear();
}
void main(void)
{
Lex ThisLex;
}
#endif
| C++ |
#ifndef COMMON_H_
#define COMMON_H_
/* common.h - header file with information most files need.
*
* This should be included first by every .h and .c file. That ensures
* an opportunity to make early tweaks, such as is needed by Microsoft C++
* for memory debugging.
*/
//#include "microsoft.h" // should be first include in this file.
#include <cassert>
#include <cstdarg>
#include <string>
#include <cstring>
#include <memory>
using std::unique_ptr;
// define some annotations
#if defined(_MSC_VER)
# define A_NORETURN __declspec(noreturn)
#elif defined(__GNUC__)
# define A_NORETURN __attribute__((noreturn))
#else
# define A_NORETURN
#endif
#ifdef _MSC_VER
// if we let him check realloc, he'll make innumerable spurious complaints...
inline _Check_return_ void* r_i_p(void* ptr, size_t NewSize)
{
void* Result = realloc(ptr, NewSize);
__analysis_assume(Result != NULL);
return Result;
}
#else
# define __analysis_assume
# define r_i_p realloc
#endif
class Global
{
private:
static struct OptionBag // options we might need two copies of
{
int ExpectCode;
int ExpectLine;
int TabStop;
bool DumpFlag;
bool VerboseFlag;
bool TokenizeFlag;
const char* ShowFirst;
const char* ShowFollow;
const char* StyleFile;
const char* InputFile;
} Options;
static int GetIntArg(int Char, const char* Arg);
public:
static void ParseArgs(int ArgCount, char** Args, Global::OptionBag* Options=NULL);
friend void A_NORETURN Exit(int Line, int Error);
static int Dump() { return Options.DumpFlag; }
static int Verbose() { return Options.VerboseFlag; }
static int Tokenize() { return Options.TokenizeFlag; }
static const char* InputFilename() { return Options.InputFile; }
};
void A_NORETURN ErrorExit(int Code, const char* Format, ...);
void ErrorPrologue(int Code);
void Usage(const char* Format, ...);
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define ARGUNUSED(x) (void)(x)
#define MAX_OPERATOR_PATTERN (32)
enum ERRORCODE
{
ERROR_NONE = 0,
ERROR_COMMANDLINE = 1, /* error on commandline */
ERROR_TERM_USED_AS_NONTERM = 2, /* */
ERROR_UNDECL_LITERAL_IN_PROD = 3,
ERROR_MISSING_NAME_IN_TOKEN_DECL = 4,
ERROR_LITERAL_ALREADY_DEFINED = 5,
ERROR_UNDEFINED_OPERATOR = 6,
ERROR_EOF_IN_PREC = 7,
ERROR_EXPECTING_OPERATOR_DECL = 8,
ERROR_PREC_WITHOUT_OPERATORS = 9,
ERROR_BAD_TOKEN_IN_DECL = 10,
ERROR_EXPECTING_NONTERM = 11,
ERROR_EXPECTING_COLON = 12,
ERROR_EXPECTING_AFTER_ACTION = 13,
ERROR_EXPECTING_OR_SEMI = 14,
ERROR_CANT_OPEN_INPUT_FILE = 15,
ERROR_INPUT_FILE_TOO_BIG = 16,
ERROR_UNKNOWN_FREAD_ERROR = 17,
ERROR_FREAD_FELL_SHORT = 18,
ERROR_UNDEFINED_NONTERM = 19,
ERROR_EOF_IN_COMMENT = 20,
ERROR_TERM_ALREADY_DEFINED = 21,
ERROR_EXPECTING_SEMICOLON = 22,
ERROR_LL_CONFLICT = 23,
ERROR_UNREACHABLE_NONTERMINAL = 24,
ERROR_UNDECL_LITERAL_IN_OP_DECL = 25,
ERROR_DUPL_OP_DECL = 26,
ERROR_OP_DECL_TOO_LONG = 27,
ERROR_DUP_SYM_IN_OPERATOR = 28,
ERROR_FAILED_OP_PREC_TABLE = 29,
ERROR_PREFIX_UNARY_DECL_LEFT = 30,
ERROR_POSTFIX_UNARY_DECL_RIGHT = 31,
ERROR_EOF_IN_TEST = 32,
ERROR_UNDEF_SYMBOL_IN_TEST = 33,
ERROR_NONTERM_IN_TEST = 34,
ERROR_BAD_TOKEN_IN_TEST = 35,
ERROR_LEFT_RECURSION = 36,
ERROR_BAD_NAME_IN_TEMPLATE = 37,
ERROR_EXPECTING_IDENT_AFTER_START = 38,
ERROR_RULES_ARE_IDENTICAL = 39,
ERROR_COMMON_PREFIX_CONTAINS_ACTION = 40,
ERROR_SYMBOL_DOES_NOT_TERMINATE = 41,
ERROR_A_NULLABLE_B_CLASH = 42,
ERROR_TWO_NULLABLE_RULES = 43,
ERROR_ILLEGAL_TOKEN = 44,
ERROR_BAD_QUOTE = 45,
ERROR_REDUCE_REDUCE_CONFLICT = 46,
ERROR_MUST_BE_NONASSOC = 47,
ERROR_NO_SYMBOL_BEFORE_SLASH = 48,
ERROR_NO_EMBEDDED_ACTION = 49,
ERROR_NOT_OPERATOR_OR_OPERAND = 50,
ERROR_NO_MATCHING_OPERATOR_PATTERN = 51,
ERROR_MISSING_OPERAND_IN_DECL = 52,
ERROR_BAD_OP_ABBREV = 53,
ERROR_CLASH_IN_OP_ABBREV = 54,
ERROR_SUFFIXES_NULLABLE = 55,
ERROR_SUFFIXES_CLASH = 56,
};
void ExitExpect(int LineNumber, int ErrorNumber);
//void A_NORETURN Exit(int LineNumber, int ErrorNumber);
void ErrorPrologue(int Error);
void A_NORETURN ErrorExit(int Error, const char* Format, ...);
void A_NORETURN Error(const char* Format, ...);
void ErrorEpilog(int Line);
void Dump(const char* Format, ...);
void DumpVerbose(const char* Format, ...);
void Usage(const char* Format, ...);
//char* StrClone(const char* Src);
//int StrEndsWith(const char* Src, const char* Suffix);
//#define NEW(T) ((T*)calloc(1, sizeof(T)))
#define ISALPHA(x) isalpha((unsigned char)(x))
#define ISDIGIT(x) isdigit((unsigned char)(x))
#endif
| C++ |
#ifdef _MSC_VER
#include "common.h"
void MicrosoftDebug()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF /*| _CRTDBG_CHECK_CRT_DF */);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
}
#endif
| C++ |
/* globals.cpp - source for Global.
*/
#include "common.h"
Global::OptionBag Global::Options =
{
-1, // ExpectCode
-1, // ExpectLine
0, // TabStop
0, // VerboseFlag
false, // TokenizeFlag
NULL, // ShowFirst
NULL, // ShowFollow
NULL, // StyleFile
};
#if 0
int Global::ExpectCode = -1;
int Global::ExpectLine = -1;
int Global::TabStop;
bool Global::DumpFlag;
bool Global::VerboseFlag;
bool Global::TokenizeFlag;
const char* Global::InputFile;
const char* Global::ShowFirst;
const char* Global::ShowFollow;
const char* Global::StyleFile;
#endif
/* ParseArgs() - parse command-line arguments.
*
*/
void Global::ParseArgs(int ArgCount, char** Args, Global::OptionBag* Temp)
{
int iArg;
const char* Arg;
if(Temp == NULL)
Temp = &Global::Options;
if(ArgCount < 2)
Usage("You must supply an input filename.\n");
for(iArg = 1; iArg < ArgCount; ++iArg)
{
Arg = Args[iArg];
if(Arg[0] == '-')
{
int Char;
++Arg;
while((Char = *Arg++) != '\0')switch(Char)
{
case 'c' :
Temp->ExpectCode = GetIntArg(Char, Arg);
Arg = Arg + strlen(Arg);
break;
case 'd' : Temp->DumpFlag = true;
break;
case 'f' :
if(Arg[-2] != '-')
Usage("'%s': -f<name> cannot be combined with other options.\n", Args[iArg]);
else
{
Temp->ShowFirst = Arg;
if(!ISALPHA(Temp->ShowFirst[0]))
Usage("Illegal character after '-f'. Use -fname to show FIRST set of non-terminal 'name'\n");
Arg += strlen(Arg);
}
break;
case 's' :
if(Arg[-2] != '-')
Usage("'%s': -s<name> cannot be combined with other options.\n", Args[iArg]);
else
{
Temp->StyleFile = Arg;
Arg += strlen(Arg);
}
break;
case 'w' :
if(Arg[-2] != '-')
Usage("'%s': -w<name> cannot be combined with other options.\n", Args[iArg]);
else
{
Temp->ShowFollow = Arg;
if(!ISALPHA(Temp->ShowFollow[0]))
Usage("Illegal character after '-w'. Use -wname to show FOLLOW set of non-terminal 'name'\n");
Arg += strlen(Arg);
}
break;
case 'k' : Temp->TokenizeFlag = true;
break;
case 'v' : ++Temp->VerboseFlag;
break;
case 'l' :
Temp->ExpectLine = GetIntArg(Char, Arg);
Arg = Arg + strlen(Arg);
break;
case 't' :
Temp->TabStop = GetIntArg(Char, Arg);
Arg = Arg + strlen(Arg);
break;
default:
Usage("'%c': Unknown option.\n", Char);
}
}
else if(Temp->InputFile == NULL)
Temp->InputFile = Arg;
else
Usage("'%s': only one input file allowed.\n", Arg);
}
if(Temp->InputFile == NULL)
Usage("Missing input file.\n");
::Dump("ParseArgs() returns\n");
}
int Global::GetIntArg(int Char, const char* Arg)
{
if(!ISDIGIT(*Arg))
ErrorExit(ERROR_COMMANDLINE, "Expecting integer after -%c.\n", Char);
return atoi(Arg);
}
| C++ |
#include "common.h"
void Dump(const char* Format, ...)
{
va_list ArgPtr;
if(Global::Dump())
{
assert(Format != NULL);
va_start(ArgPtr, Format);
vfprintf(stdout, Format, ArgPtr);
va_end(ArgPtr);
fflush(stdout);
}
}
void DumpVerbose(const char* Format, ...)
{
va_list ArgPtr;
if(Global::Dump() && Global::Verbose())
{
assert(Format != NULL);
va_start(ArgPtr, Format);
vfprintf(stdout, Format, ArgPtr);
va_end(ArgPtr);
fflush(stdout);
}
}
static int ErrorCode; // connects ErrorPrologue to ErrorEpilog
/* Exit() - end-of-the-line on the way out the door.
*
* This is the final function called to exit blacc with an error.
* It handles any user option indicating that a particular error code
* and/or error on a particular line was expected, setting the exit
* status accordingly (mainly for regression tests of blacc itself).
*
* Our exit status is the (non-zero) number of the error, unless
* the user specified an expected error code/line#. In the latter
* case, the exit status is EXIT_SUCCESS if the code/line# was
* expected and EXIT_FAILURE otherwise.
**********************************************************************/
void A_NORETURN Exit(int Line, int Error)
{
int Status = -1;
/* if command-line did not request error expectations */
if(Global::Options.ExpectLine == -1 && Global::Options.ExpectCode == -1)
Status = Error;
/* else, our status is binary: were the expectations met? */
else
{
Status = EXIT_SUCCESS;
if(Global::Options.ExpectLine != -1 && Global::Options.ExpectLine != Line)
Status = EXIT_FAILURE;
else if(Global::Options.ExpectCode != -1 && Global::Options.ExpectCode != Error)
Status = EXIT_FAILURE;
}
assert(Status != -1);
fflush(stderr);
fflush(stdout);
exit(Status);
}
/* ErrorExit() - print formatted error message and exit.
*/
void A_NORETURN ErrorExit(int Code, const char* Format, ...)
{
va_list ArgPtr;
ErrorPrologue(Code);
assert(Format != NULL);
va_start(ArgPtr, Format);
vfprintf(stderr, Format, ArgPtr);
va_end(ArgPtr);
fflush(stderr);
Exit(-1, Code);
}
void ErrorPrologue(int Code)
{
fprintf(stderr, "blacc error %d:\n", Code);
fflush(stderr);
ErrorCode = Code;
}
void ErrorEpilog(int Line)
{
Exit(Line, ErrorCode);
}
/* Usage() - print formatted error, plus usage info, then exit.
*/
void Usage(const char* Format, ...)
{
va_list ArgPtr;
assert(Format != NULL);
va_start(ArgPtr, Format);
vfprintf(stderr, Format, ArgPtr);
va_end(ArgPtr);
fprintf(stderr, "Usage:\n");
fprintf(stderr, " blacc [options] file.blc\n");
fprintf(stderr, "Where:\n");
fprintf(stderr, " -c###\n");
fprintf(stderr, " causes an exit code of 1 if an error ### is not encountered.\n");
fprintf(stderr, " -d\n");
fprintf(stderr, " dumps internal information.\n");
fprintf(stderr, " -fname Display FIRST set of nonterminal 'name'.\n");
fprintf(stderr, " -k emit tokenized version of input (useless to normal users).\n");
fprintf(stderr, " -l###\n");
fprintf(stderr, " causes an exit code of 1 if an error on line ### is not found.\n");
fprintf(stderr, " -v Increase verbosity of output.\n");
fprintf(stderr, " -wname Display FOLLOW set of nonterminal 'name'.\n");
Exit(-1, ERROR_COMMANDLINE);
}
| C++ |
#include "common.h"
#include "file.h"
File::File() : Buffer(nullptr), Filename(nullptr)
{
printf("Construct file!\n");
}
File::~File()
{
printf("Destruct file!\n");
if(Buffer)
free(Buffer);
}
| C++ |
/* main.cpp - entry point for BLACC (Burk Labs' Anachronistic Compiler Compiler)
*
* BLACC is designed to be a parser generator that I can easily bend
* to whatever inconvenient need I have.
*/
#include "common.h"
#include "lex.h"
#include <stdio.h>
#include <thread>
#include <stack>
static TTokenizedFile PrepareInputTokens(Lex* ThisLex, const char* GrammarFilename,
TToken IncludeToken);
static unsigned int HardwareConcurrency(void);
int main(int ArgCount, char** Args)
{
const char* GrammarFilename;
// TToken NullToken = {nullptr, 0, 0};
// _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
// parse command-line so we can get an input file
Global::ParseArgs(ArgCount, Args);
printf("# of threads = %u\n", HardwareConcurrency());
unique_ptr<Lex> ThisLex(new Lex);
GrammarFilename = Global::InputFilename();
if(!GrammarFilename)
Usage("Missing name of input file.\n");
TTokenizedFile GrammarFile =
PrepareInputTokens(ThisLex.get(), Global::InputFilename(), TToken::Null);
}
/* PrepareInputTokens() - Get to the point we have a set of input tokens ready to parse.
*
* This function will, if it encounters no errors, completely tokenize all of the
* input of the designated input file, as well as all files it %include's.
****************************************************************************************/
static TTokenizedFile PrepareInputTokens(Lex *ThisLex, const char* GrammarFilename,
TToken IncludeToken)
{
int TokenErrors;
// read the input file
TTokenizedFile GrammarFile = ThisLex->FileLoad(GrammarFilename, IncludeToken);
TokenErrors = GrammarFile->Tokenize();
if(TokenErrors > 0)
{
if(TokenErrors > 1)
printf("%d error tokens in '%s'\n", TokenErrors, Global::InputFilename());
}
else
{
// scan token list for valid %include directives
for(auto TokenIter=GrammarFile->Begin(); TokenIter != GrammarFile->End(); ++TokenIter)
{
if(TokenIter->Type == Lex::INCLUDE && TokenIter[1].Type == Lex::QUOTED)
{
unique_ptr<char> Filename(TokenIter[1].Unquote());
if(!ThisLex->Loaded(Filename.get()))
ThisLex->FileLoad(Filename.get(), TokenIter[0]);
}
}
}
return GrammarFile;
}
/* HardwareConcurrency() - How much parallelism does the hardware have?
*
* Due to a very painful bug in Visual C++, we use a wrapper function for
* what should be a simple library call.
*/
static unsigned int HardwareConcurrency(void)
{
static unsigned int ThreadCount;
if(ThreadCount == 0)
{
#ifdef _MSC_VER // compiler believes catch unreasonable (true if there were no bug)
# pragma warning(push)
# pragma warning(disable:4702)
#endif
try {
ThreadCount = std::thread::hardware_concurrency();
}
catch (...)
{
fprintf(stderr,
"Can't happen: hardware_concurrency() threw an exception.\n"
"Are you running under Windows/AppVerifier with HighVersionLie checked?\n"
"If so, you may want to do something like:\n"
" appverif -disable HighVersionLie -for blacc.exe\n"
);
throw;
}
#ifdef _MSC_VER
# pragma warning(pop)
#endif
// note that 0 is essentially "don't know"
if(ThreadCount == 0)
ThreadCount = 1;
}
return ThreadCount;
}
| C++ |
#ifndef SYMBOL_H_
#define SYMBOL_H_
/* symbol.h - define core data type.
*
* SYMBOL is an opaque pointer representing an instance of a symbol
* (terminal, non-terminal, or action). There may be one or more
* instances for a given symbol; an instance basically refers to a
* specific textual occurrence in the source grammar.
*/
#ifndef INPUT_H_
# include "input.h"
#endif
class SYMBOL
{
public:
~SYMBOL();
private:
SYMBOL(int Terminal);
static SYMBOL NewNonTerm(TToken Token);
static SYMBOL NewTerm(TToken Token);
};
typedef struct SYMBOLS_
{
void* Dummy_;
} SYMBOLS_, *SYMBOLS;
#endif /* SYMBOL_H_ */
| C++ |
#ifndef FILE_H_
#define FILE_H_
#include <memory>
#include <string>
using namespace std;
class File
{
public:
File();
~File();
char* Load(const char* Filename);
private:
File(const File& Other); // disallow: private and no definition
File& operator=(const File& Other); // disallow: private and no definition
char* Buffer;
string Filename;
};
#endif /* FILE_H_ */
| C++ |
#ifndef LEX_H_
#define LEX_H_
#include "common.h"
#include <limits.h> // a pox on C++'s limits framework!
//#include <functional>
#include <map>
#include <memory>
#include <new>
#include <vector>
/* TToken - a token type.
*
* Tokens need to be relatively small and cheap since we will be storing
* them all in an array (per file) that stays in memory until blacc exits.
******************************************************************************/
struct TToken
{
const char* Text; // raw pointer into original file text
unsigned short TextLen; // # of bytes in this token (no NUL termination!)
short Type; // token type, as defined in Lex
enum{ MAXLEN = SHRT_MAX }; // maximum length for any token
static TToken Null;
int IsNull();
unique_ptr<char>Unquote() const;
};
typedef std::vector<TToken> TTokens;
typedef std::vector<TToken>::const_iterator TTokenIter;
typedef unique_ptr<std::vector<char>> TFileChars;
//class LexFile;
class Lex;
// FileLoad(): lowest-level function for loading a file.
unique_ptr<std::vector<char>> FileLoad(const char* Filename);
// LexFile: a file that will be loaded and tokenized.
class LexFile
{
public:
friend class Lex;
friend class Lexer;
int Tokenize();
TToken operator[](int Index) { return Tokens[Index]; }
TTokens GetTokens() { return Tokens; }
TTokenIter Begin() { return Tokens.begin(); }
TTokenIter End() { return Tokens.end(); }
~LexFile();
private:
LexFile(const char* Filename, TFileChars Text, TToken FromInclude);
// cruft for 'Tokens' unique_ptr vector
// struct Deleter{void operator()(LexFile*File) const {delete File;}};
LexFile(const LexFile& Other); // disallow: private and no definition
LexFile& operator=(const LexFile& Other); // disallow: private and no definition
std::string Filename; // name of file
TFileChars FileText; // must live as long as Tokens
TTokens Tokens; // array of tokens (result of tokenizing Buffer)
int ErrorCount; // # of error tokens in Tokens
TToken FromInclude; // parent file %include token (or NULL)
};
//typedef std::unique_ptr<LexFile> const &TTokenizedFile;
typedef LexFile *TTokenizedFile;
class Lexer
{
public:
Lexer(LexFile& RootFile);
~Lexer();
private:
};
class Lex
{
public:
Lex();
~Lex();
TTokenizedFile FileLoad(const char* Filename, TToken FromInclude);
TTokenizedFile Loaded(const char* Filename);
enum
{
TKEOF, // End-Of-File
IDENT, // [A-Za-z][A-Za-z0-9]+
ACTION, // { ... }
SECTION, // %%
QUOTED, // a quoted string
LEFT, // %left
RIGHT, // %right
NONASSOC, // %nonassoc
TOKEN, // %token
NEWLINE, // '\n'
OPERAND,
TEST, // %test
LINE,
START,
CODE,
PROGRAM,
NONTERM, // IDENT followed by ':'
MATCHANY,
NOACT,
COMMENT,
WHITESPACE,
OPERATOR,
ORBAR,
SEMICOLON,
NOTUSED, // useful for marking a token as not yet defined
// numbers > NOTUSED are all illegal tokens
TOOLONG, // token was too long
ILLEGAL, // didn't match any token type
UNKDIR, // unknown directive
BADQUOTE, // unterminated quote
INCLUDE, // %include
};
private:
std::map<std::string, std::unique_ptr<LexFile> > Files;
};
#endif
| C++ |
#ifndef DRIVE_H_
#define DRIVE_H_
#include "WPILib.h"
#include "GlobalInclude.h"
class Drive
{
public:
Drive();
virtual ~Drive();
void printLeft(void);
void jagDebug(int);
void printRight(void);
/*
CANJaguar *leftJag;// CAN attached Jag for the Left1 motor **** 2
CANJaguar *rightJag;// CAN attached Jag for the Right1 motor ** 3
CANJaguar *leftJag2;// 4
CANJaguar *rightJag2;//5
*/
Jaguar *leftJag;
Jaguar *rightJag;
Jaguar *leftJag2;
Jaguar *rightJag2;
Encoder *leftEnc;
Encoder *rightEnc;
DoubleSolenoid *shifter; // 1,2
RobotDrive *myRobot; // robot drive system
};
#endif /*DRIVE_H_*/
| C++ |
#ifndef ARM_H_
#define ARM_H_
#include "WPILib.h"
#include "DoubleSolenoid.h"
#include "GlobalInclude.h"
#include "PIDCalculator.h"
#include "OperatorInterface.h"
class Arm
{
public:
Arm(OperatorInterface *oiArmX);
//void jagDebug(int);
virtual ~Arm();
void liftInit(void);
OperatorInterface *oiArm;
Jaguar *lift1; // 6
Jaguar *lift2; // 7
Jaguar *arm; // 8
DigitalInput *bottomLiftSwitch;
DigitalInput *topLiftSwitch;
DigitalInput *bottomArmSwitch;
DigitalInput *topArmSwitch;
Encoder *liftEnc;
//Encoder *armEnc;
PIDCalculator *armCalc;
PIDCalculator *liftCalc;
PIDController *liftPID;
PIDController *armPID;
DoubleSolenoid *gripperSolenoid; // 3
DoubleSolenoid *minibotSolenoid; // 4
DoubleSolenoid *brakeSolenoid;
void liftSubroutine();
void armSubroutine();
//AnalogInput *armPot;
private:
float Kpl, Kil, Kdl, Kpa, Kia, Kda;
float liftSetpoints[8];
};
#endif /*ARM_H_*/
| C++ |
#ifndef PHOTOSWITCH_H_
#define PHOTOSWITCH_H_
#include "WPIlib.h"
#include "GlobalInclude.h"
#include "Sensor.h"
class PhotoSwitch
{
public:
PhotoSwitch(Drive *y);
~PhotoSwitch(void);
int onLight(void);
int onDark(void);
int onDark1(void);
int onDark3(void);
int allLight(void);
int allDark(void);
int dLeft(void);
int dRight(void);
int lLeft(void);
int lRight(void);
float drive(int);
float getLeftSpeed(void);
float getRightSpeed(void);
//void gyroSubroutine(int);
DigitalInput *p1;//dark 1
DigitalInput *p2;//dark 2
DigitalInput *p3;//dark 3
DigitalInput *p4;//light 1
DigitalInput *p5;//light 2
DigitalInput *p6;//light 3
//Sensor *sensor;
float leftSpeed;
float rightSpeed;
int binary;
Sensor *sensor;
private:
float steeringGain;
};
#endif /*PHOTOSWITCH_H_*/
| C++ |
#include "WPILib.h"
#include "GlobalInclude.h"
//#include "CANJaguar.h"
#include "PhotoSwitch.h"
#include "Drive.h"
#include "OperatorInterface.h"
#include "PIDCalculator.h"
#include "Arm.h"
#define waitTime 0.01//try 0.05 or 0.1
class CANRobotDemo : public IterativeRobot
{
Drive *dr;
OperatorInterface *oi;
PhotoSwitch *ps;
Arm *arm;
Compressor *comp;
public:
CANRobotDemo(void){
//SmartDashboard::init();
GetWatchdog().SetExpiration(100);
}//end of constructor
void RobotInit()
{
printf("RobotInit");
/*****moved from constructor*****/
wpi_stackTraceEnable(true);
dr = new Drive();
oi = new OperatorInterface();
ps = new PhotoSwitch(dr);
arm = new Arm(oi);
comp = new Compressor(10,1);
/*****end moved*****/
//oi->lcd->Printf(DriverStationLCD::kMain_Line6, 1, "Bus Voltage: %f",dr->leftJag->GetBusVoltage());
}//end of RobotInit
void AutonomousInit(void)
{
printf("AutonomousInit\n");
GetWatchdog().SetEnabled(false);
oi->updateButtons();
arm->liftInit();
}//end of AutonomousInit
void AutonomousPeriodic(void)
{
ps->drive(oi->ds->GetDigitalIn(1));
dr->myRobot->TankDrive(ps->leftSpeed,ps->rightSpeed);
if((ps->allLight()) || (ps->allDark()))
{
//run lift and arm
}
//SmartDashboard::Log
/*
printf("onDark: %i\n", ps->onDark());
printf("onDark1: %i\n", ps->onDark1());
printf("onDark3: %i\n", ps->onDark3());
printf("dleft: %i\n", ps->dLeft());
printf("dRight: %i\n", ps->dRight());
printf("allDark: %i\n", ps->allDark());
*/
}//end of AutonomousPeriodic
void TeleopInit(void)
{
printf("TeleOpInit\n");
GetWatchdog().SetEnabled(false);
arm->liftInit();
oi->updateButtons();
comp->Start();
}//end of TeleopInit
void TeleopPeriodic(void)
{
//printf("my teleopPeriodic\n");
}//end of TeleOpPeriodic
void TeleopContinuous(void)
{
//printf("my teleopContinuous\n");
//printf("killSw true\n");
dr->myRobot->TankDrive(oi->rightStick,oi->leftStick); // drive with tank style
arm->liftSubroutine();
arm->armSubroutine();
if(oi->rightStick->GetTrigger())
{
dr->shifter->Set(DoubleSolenoid::kForward);//high gear
}else if(oi->leftStick->GetTrigger())
{
dr->shifter->Set(DoubleSolenoid::kReverse);//low gear
}else
{
//do nothing
}
//printf("its working");
if(oi->killSw == true)
{
}else if (oi->killSw == false){
//comp->Stop();
}//end of else
}
//void TeleOpContinuous(){} not currently used
void DisabledInit(void)
{
printf("DisabledInit\n");
}//end of DisabledInit
void DisabledPeriodic(void)
{
//printf("Disabled\n");
//pid->Disable();
//gyro->Reset();
//delete ps;
//ps = NULL;
//dr->leftJag->Set(0.0);
//dr->rightJag->Set(0.0);
//comp->Stop();
}//end of DisabledPeriodic
//void DisabledContinuous(void){} not currently used
};//end of CANRobotDemo Class
START_ROBOT_CLASS(CANRobotDemo);
| C++ |
#ifndef SENSOR_H_
#define SENSOR_H_
#include "WPILib.h"
#include "GlobalInclude.h"
#include "PIDCalculator.h"
#include "Drive.h"
class Sensor
{
public:
Sensor(Drive *z);
virtual ~Sensor();
Drive *sensorDrive;
Gyro *gyro;
PIDCalculator *calc;
PIDController *pid;
void gyroSubroutine(int);
float leftOutput;
float rightOutput;
};
#endif /*SENSOR_H_*/
| C++ |
#include "Sensor.h"
Sensor::Sensor(Drive *z)
{
sensorDrive = z;
gyro = new Gyro(1);
calc = new PIDCalculator();
pid = new PIDController(0.0625,0.003,0,gyro,calc);
pid->SetInputRange(-360,360);//-360 degrees to 360 degrees
pid->SetTolerance(0.15);//tolerance is 0.15% of total range
pid->SetOutputRange(-1.0,1.0);
}
void Sensor::gyroSubroutine(int direction)//0 for left, 1 for right
{
int flag = 0; //outside tolerance zone
printf("gyroSubroutine() function called");
if(direction == 0)
{
pid->SetSetpoint(-12); //take left fork
printf("Setpoint = -10");
}else if (direction == 1 ){
pid->SetSetpoint(12); //take right fork
printf("Setpoint = 10");
}else{
pid->SetSetpoint(12);//default to right fork
printf("Setpoint = default");
}//end of else
gyro->Reset();
pid->Enable();
printf("OnTarget: %i", pid->OnTarget());
while(flag == 0)
{
leftOutput = calc->getOutput()*-1.0;
rightOutput = leftOutput * -1.0;
sensorDrive->myRobot->TankDrive(leftOutput,rightOutput);
printf("Gyro: %f PID Output: %f\n" , gyro->GetAngle(), calc->getOutput());
if((gyro->GetAngle()<13) && (gyro->GetAngle()>11))
{
flag = 1;
}else if((gyro->GetAngle()>-13) && (gyro->GetAngle()<-11)){
flag = 1;
}
Wait(0.02);
}
pid->Disable();
}//end of gyroSubroutine
Sensor::~Sensor()
{
printf("*****Sensor Deconstructor Called*****");
delete pid;
delete gyro;
delete sensorDrive;
delete calc;
pid = NULL;
gyro = NULL;
sensorDrive = NULL;
calc = NULL;
}
| C++ |
#include "Arm.h"
#define manual 1
#define armGain 0.4
#define liftGain 0.5
Arm::Arm(OperatorInterface *oiArmX)
{
oiArm = oiArmX;
lift1 = new Jaguar(5);
lift2 = new Jaguar(6);
arm = new Jaguar(7);
liftEnc = new Encoder(7,8);
liftEnc->SetDistancePerPulse(1);
liftEnc->Start();
//armEnc = new Encoder(12);//ToDo check the port
gripperSolenoid = new DoubleSolenoid(1,2);//shifter is 2 and 3
minibotSolenoid = new DoubleSolenoid(7,8);
brakeSolenoid = new DoubleSolenoid(3,4);
Kpl = 0.00001; //todo tune PID loop
Kil = Kdl = Kia = Kda = 0.0;
Kpa = 1.0;
//liftSetpoints [8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
//max is -4959
liftSetpoints[0] = 4959;//top right 113.5"
liftSetpoints[1] = 4036.5;//middle right 76.5" -4036.5
liftSetpoints[2] = 1943.25;//bottom right 39.5" -1943.25
liftSetpoints[3] = 4959;//top left 105" 10" past max
liftSetpoints[4] = 3594.75;//middle left 68" -3594.75
liftSetpoints[5] = 1526.75;//bottom left 31" -1526.75
liftSetpoints[6] = 2067.25;//feeding 42" -2067.25
liftSetpoints[7] = 0.0;//ground
liftCalc = new PIDCalculator();
liftPID = new PIDController(Kpl,Kil,Kdl,liftEnc,liftCalc);
armCalc = new PIDCalculator();
armPID = new PIDController(Kpa,Kia,Kda,liftEnc,armCalc);//CHANGE INPUT
//set input range, ouput range, and tolerance for each
liftPID->SetSetpoint(0);
liftPID->SetTolerance(15);
liftPID->SetOutputRange(1,-1);
liftPID->SetInputRange(0,-4959);
armPID->SetTolerance(.5);
armPID->SetOutputRange(-0.5,0.5);
topLiftSwitch = new DigitalInput(11);
}//end of constructor
void Arm::liftInit()
{
liftPID->Enable();
liftEnc->Reset();
liftPID->SetSetpoint(liftSetpoints[7]);
#if liftDebug == 1
SmartDashboard::init();
#endif
}//end of liftInit()
void Arm::liftSubroutine()
{
oiArm->updateButtons();
/*********Start Manual Lift Control*********/
#if manual == 1
if(oiArm->ds->GetDigitalIn(4)==0)
{
lift1->Set(liftGain);
lift2->Set(liftGain));
}else if(oiArm->ds->GetDigitalIn(2)==0)
{
lift1->Set(-liftGain);
lift2->Set(-liftGain);
}else{
lift1->Set(0.0);
lift2->Set(0.0);
}
brakeSolenoid->Set(DoubleSolenoid::kReverse);//or kForward
#endif
/*********End Manual Lift Control*********/
/*********Start Setpoint Lift Control*********/
#if manual == 0
if(oiArm->bottomLeft)
{
liftPID->SetSetpoint(liftSetpoints[5]);
printf("bottomLeft");
}
else if(oiArm->middleLeft)
{
liftPID->SetSetpoint(liftSetpoints[4]);
printf("middleLeft");
}
else if(oiArm->topLeft)
{
liftPID->SetSetpoint(liftSetpoints[3]);
printf("topLeft");
}
else if(oiArm->bottomRight)
{
liftPID->SetSetpoint(liftSetpoints[2]);
printf("bottomRight");
}
else if(oiArm->middleRight)
{
liftPID->SetSetpoint(liftSetpoints[1]);
printf("middleRight");
}
else if(oiArm->topRight)
{
liftPID->SetSetpoint(liftSetpoints[0]);
printf("topRight");
}else if(oiArm->ground)
{
liftPID->SetSetpoint(liftSetpoints[7]);
printf("ground");
}else if(oiArm->feeding)
{
liftPID->SetSetpoint(liftSetpoints[6]);
printf("feeding");
}
lift1->Set((-1)*(liftCalc->getOutput()));
lift2->Set((-1)*(liftCalc->getOutput()));
brakeSolenoid->Set(DoubleSolenoid::kForward);//or backward
#endif //end of manual == 0
//printf("LiftEnc: %f\n",liftEnc->GetDistance());
#if liftDebug == 1
SmartDashboard::Log(liftEnc->GetDistance(),"Encoder Value");
SmartDashboard::Log(liftPID->GetSetpoint(),"PID Setpoint");
SmartDashboard::Log(liftPID->GetError(),"PID Error");
SmartDashboard::Log(liftPID->OnTarget(),"OnTarget");
SmartDashboard::Log(liftCalc->getOutput(),"PID Output");
printf("PID Setpoint: %f\n",liftPID->GetSetpoint());
#endif
}//end of liftSubroutine
void Arm::armSubroutine()
{
oiArm->updateButtons();
#if manual == 0
if(oiArm->ds->GetDigitalIn(4)==0)
{
arm->Set(-0.4);
}else if(oiArm->ds->GetDigitalIn(2)==0)
{
arm->Set(0.4);
}else{
arm->Set(0.0);
}
#endif
#if manual == 1
if(oiArm->middleRight)
{
arm->Set(-armGain);
//printf("arm down\n");
}else if(oiArm->topRight)
{
arm->Set(armGain);
//printf("arm up\n");
}else{
arm->Set(0.0);
}
#endif
/*****Gripper pneumatics*****/
if(oiArm->gripper)
{
gripperSolenoid->Set(DoubleSolenoid::kReverse);
}else if(oiArm->gripper == false)
{
gripperSolenoid->Set(DoubleSolenoid::kForward);
}
/*****Minibot pneumatics*****/
if(oiArm->mbUp==false)
{
minibotSolenoid->Set(DoubleSolenoid::kReverse);
}else if(oiArm->mbDown==false)
{
minibotSolenoid->Set(DoubleSolenoid::kForward);
}
// negative values raise the arm
}//end of armSubroutine
Arm::~Arm()
{
delete lift1;
delete lift2;
delete arm;
delete oiArm;
delete bottomLiftSwitch;
delete topLiftSwitch;
delete bottomArmSwitch;
delete topArmSwitch;
delete liftCalc;
delete liftPID;
delete armCalc;
delete armPID;
delete liftEnc;
delete gripperSolenoid;
delete minibotSolenoid;
delete brakeSolenoid;
oiArm = NULL;
lift1 = NULL;
lift2 = NULL;
arm = NULL;
bottomLiftSwitch = NULL;
topLiftSwitch = NULL;
bottomArmSwitch = NULL;
topArmSwitch = NULL;
liftCalc = NULL;
liftPID = NULL;
armCalc = NULL;
armPID = NULL;
liftEnc = NULL;
gripperSolenoid = NULL;
minibotSolenoid = NULL;
brakeSolenoid = NULL;
}
| C++ |
#include "OperatorInterface.h"
OperatorInterface::OperatorInterface()
{
leftStick = new Joystick(1);
rightStick = new Joystick(2);
ds = DriverStation::GetInstance();
lcd = DriverStationLCD::GetInstance();
estop = new Joystick(3);
}
void OperatorInterface::updateButtons()
{
#if oiExperimental == 1
killSw = ds->GetDigitalIn(3); //true is enable, false is disabled
liftUp = ds->GetDigitalIn(2); //false for up
liftDown = ds->GetDigitalIn(4); //false for down
mbUp = ds->GetDigitalIn(5);
mbDown = ds->GetDigitalIn(7);
topRight = estop->GetRawButton(1);
middleRight = estop->GetRawButton(2);
bottomRight = estop->GetRawButton(3);
topLeft = estop->GetRawButton(4);
middleLeft = estop->GetRawButton(5);
bottomLeft = estop->GetRawButton(6);
feeding = estop->GetRawButton(7);
ground = estop->GetRawButton(8);
gripper = estop->GetRawButton(9);
lineTrack = estop->GetRawButton(10); //true is up
forkDirection = estop->GetRawButton(11); //0 for left, 1 for right
#endif
}
OperatorInterface::~OperatorInterface()
{
delete leftStick;
delete rightStick;
delete estop;
delete ds;
leftStick = NULL;
rightStick = NULL;
estop = NULL;
ds = NULL;
}
| C++ |
#include "PIDCalculator.h"
PIDCalculator::PIDCalculator()
{
printf("PIDCalculator Initialized");
pidOutput = 0;
}
PIDCalculator::~PIDCalculator()
{
printf("PIDCalculator Deconstructor Called");
//delete instance;
//instance = NULL;
}
float PIDCalculator::getOutput()
{
return pidOutput;
}
void PIDCalculator::PIDWrite(float output)
{
//printf("PIDWrite Called\n");
pidOutput = output;
}
/*
PIDCalculator* PIDCalculator::Clone()
{
if(instance == NULL)
{
instance = new PIDCalculator();
}//end of if
return instance;
}
*/
| C++ |
#include "WPILib.h"
#include "Drive.h"
Drive::Drive()
{
/*
leftJag = new CANJaguar(5); // These must be initialized in the same order
rightJag = new CANJaguar(3); // as they are declared above.
leftJag2 = new CANJaguar(4);
rightJag2 = new CANJaguar(2);
*/
leftJag = new Jaguar(4); // These must be initialized in the same order
leftJag2 = new Jaguar(3);
rightJag = new Jaguar(2); // as they are declared above.
rightJag2 = new Jaguar(1);
//myRobot = new RobotDrive(leftJag, rightJag);
myRobot = new RobotDrive(leftJag, leftJag2, rightJag, rightJag2);
//myRobot->SetSafetyEnabled(false);
shifter = new DoubleSolenoid(5,6);
//myRobot->SetInvertedMotor(RobotDrive::kFrontRightMotor, true);
//myRobot->SetInvertedMotor(RobotDrive::kFrontLeftMotor, true);
//myRobot->SetInvertedMotor(RobotDrive::kRearRightMotor, true);
//myRobot->SetInvertedMotor(RobotDrive::kRearLeftMotor, true);
}//end of constructor
Drive::~Drive()
{
delete leftJag;
delete leftJag2;
delete rightJag;
delete rightJag2;
delete myRobot;
delete shifter;
leftJag = NULL;
leftJag2 = NULL;
rightJag = NULL;
rightJag2 = NULL;
myRobot = NULL;
shifter = NULL;
}
| C++ |
#ifndef PIDCALCULATOR_H_
#define PIDCALCULATOR_H_
#include "WPILib.h"
#include "GlobalInclude.h"
class PIDCalculator : public PIDOutput
{
public:
//static PIDCalculator* PIDCalculator::instance;
PIDCalculator();
virtual ~PIDCalculator();
virtual void PIDWrite(float output);
virtual float getOutput(void);
//static PIDCalculator *Clone(void);
protected:
private:
float pidOutput;
};
#endif /*PIDCALCULATOR_H_*/
| C++ |
#ifndef OPERATORINTERFACE_H_
#define OPERATORINTERFACE_H_
#include "WPILib.h"
#include "GlobalInclude.h"
class OperatorInterface
{
public:
OperatorInterface();
virtual ~OperatorInterface();
void updateButtons(void);
Joystick *leftStick; // left joystick
Joystick *rightStick;
DriverStation *ds;
DriverStationLCD *lcd;
#if oiExperimental == 1
Joystick *estop;
bool killSw;
bool liftUp;//false is up
bool liftDown;//false is down
bool lineTrack;
bool topRight, middleRight, bottomRight;
bool topLeft, middleLeft, bottomLeft;
bool feeding, ground;
bool gripper;
bool forkDirection;
bool mbUp;
bool mbDown;
//true on the two above is center
#endif
};
#endif /*OPERATORINTERFACE_H_*/
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.