text
stringlengths
54
60.6k
<commit_before>// RegAccess.cpp: implementation of the neTKVMRegAccess class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "RegAccess.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// neTKVMRegAccess::neTKVMRegAccess() : m_lpsRegPath(NULL), m_hkPrimaryHKey(0) { } neTKVMRegAccess::neTKVMRegAccess(HKEY hNewPrKey, LPCTSTR lpzNewRegPath) : m_lpsRegPath(NULL), m_hkPrimaryHKey(0) { SetPrimaryKey(hNewPrKey); if (SetRegPath(lpzNewRegPath) == FALSE) { throw neTKVMRegAccessConstructorFailedException(); } } neTKVMRegAccess::~neTKVMRegAccess() { delete m_lpsRegPath; } VOID neTKVMRegAccess::SetPrimaryKey(HKEY hNewPrKey) { m_hkPrimaryHKey = hNewPrKey; } BOOL neTKVMRegAccess::SetRegPath(LPCTSTR lpzNewRegPath) { delete m_lpsRegPath; if (!lpzNewRegPath) { m_lpsRegPath = NULL; return TRUE; } m_lpsRegPath = _tcsdup(lpzNewRegPath); return (m_lpsRegPath != NULL)?TRUE:FALSE; } HKEY neTKVMRegAccess::GetPrimaryKey(VOID) { return m_hkPrimaryHKey; } BOOL neTKVMRegAccess::GetRegPath(LPTSTR lpsBuffer, DWORD dwNumberOfElements) { if (!dwNumberOfElements) { return FALSE; } if (!m_lpsRegPath) { *lpsBuffer = 0; return TRUE; } return (_tcscpy_s(lpsBuffer, dwNumberOfElements, m_lpsRegPath) == 0)?TRUE:FALSE; } DWORD neTKVMRegAccess::ReadDWord(LPCTSTR lpzValueName, DWORD dwDefault, LPCTSTR lpzSubKey) { DWORD dwRes = 0; return (ReadDWord(lpzValueName, &dwRes, lpzSubKey) == TRUE)?dwRes:dwDefault; } BOOL neTKVMRegAccess::ReadDWord(LPCTSTR lpzValueName, LPDWORD lpdwValue, LPCTSTR lpzSubKey) { BOOL bRes = FALSE; DWORD dwValue = 0, dwSize = sizeof(dwValue), dwType = REG_DWORD; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryValueEx(hkReadKeyHandle, lpzValueName, NULL, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS) { bRes = TRUE; if (lpdwValue) { *lpdwValue = dwValue; } } RegCloseKey(hkReadKeyHandle); } return bRes; } DWORD neTKVMRegAccess::ReadString(LPCTSTR lpzValueName, LPTSTR lpzData, DWORD dwNumberOfElements, LPCTSTR lpzSubKey) { DWORD dwRes = 0; DWORD dwType = REG_SZ; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwBuffSize = dwNumberOfElements * sizeof(lpzData[0]); memset(lpzData, 0, dwBuffSize); FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryValueEx(hkReadKeyHandle, lpzValueName, NULL, &dwType, (LPBYTE)lpzData, &dwBuffSize) == ERROR_SUCCESS) dwRes = dwBuffSize / sizeof(lpzData[0]); RegCloseKey(hkReadKeyHandle); } return dwRes; } DWORD neTKVMRegAccess::ReadBinary(LPCTSTR lpzValueName, LPBYTE lpzData, DWORD dwSize, LPCTSTR lpzSubKey) { DWORD dwRes = 0; DWORD dwType = REG_BINARY; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; memset(lpzData, 0, dwSize); FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryValueEx(hkReadKeyHandle, lpzValueName, NULL, &dwType, lpzData, &dwSize) == ERROR_SUCCESS) dwRes = dwSize; RegCloseKey(hkReadKeyHandle); } return dwRes; } BOOL neTKVMRegAccess::ReadValueName(LPTSTR lpsValueName, DWORD dwNumberOfElements, DWORD dwIndex, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; BYTE baData[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDataSize = DEFAULT_REG_ENTRY_DATA_LEN, dwType = REG_BINARY; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { DWORD dwBuffSize = dwNumberOfElements * sizeof(lpsValueName[0]); if (RegEnumValue(hkReadKeyHandle, dwIndex, lpsValueName, &dwBuffSize, NULL, &dwType, baData, &dwDataSize) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkReadKeyHandle); } return bResult; } BOOL neTKVMRegAccess::ReadKeyName(LPTSTR lpsKeyName, DWORD dwNumberOfElements, DWORD dwIndex, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkReadKeyHandle = NULL; FILETIME stTimeFile; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_ENUMERATE_SUB_KEYS, &hkReadKeyHandle) == ERROR_SUCCESS) { DWORD dwBuffSize = dwNumberOfElements * sizeof(lpsKeyName[0]); if (RegEnumKeyEx(hkReadKeyHandle, dwIndex, lpsKeyName, &dwBuffSize, NULL, NULL, NULL, &stTimeFile) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkReadKeyHandle); } return bResult; } BOOL neTKVMRegAccess::WriteValue(LPCTSTR lpzValueName, DWORD dwValue, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkWriteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDisposition; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegCreateKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkWriteKeyHandle, &dwDisposition) == ERROR_SUCCESS) { if (RegSetValueEx(hkWriteKeyHandle, lpzValueName, 0, REG_DWORD, (LPCBYTE)&dwValue, sizeof(DWORD)) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkWriteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::WriteString(LPCTSTR lpzValueName, LPCTSTR lpzValue, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkWriteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDisposition; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegCreateKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkWriteKeyHandle, &dwDisposition) == ERROR_SUCCESS) { DWORD dwBuffSize = ((DWORD)_tcslen(lpzValue) + 1) * sizeof(lpzValue[0]); if (RegSetValueEx(hkWriteKeyHandle, lpzValueName, 0, REG_SZ, (LPCBYTE)lpzValue, dwBuffSize) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkWriteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::WriteBinary(LPCTSTR lpzValueName, LPCBYTE lpData, DWORD dwDataSize, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkWriteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDisposition; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegCreateKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkWriteKeyHandle, &dwDisposition) == ERROR_SUCCESS) { if (RegSetValueEx(hkWriteKeyHandle, lpzValueName, 0, REG_BINARY, lpData, dwDataSize) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkWriteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::AddKey(LPCTSTR lpzKeyName) { BOOL bResult = FALSE; HKEY hkWriteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDisposition; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzKeyName); if (RegCreateKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkWriteKeyHandle, &dwDisposition) == ERROR_SUCCESS) { RegCloseKey(hkWriteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::DeleteKey(LPCTSTR lpzKeyName, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkDeleteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_WRITE, &hkDeleteKeyHandle) == ERROR_SUCCESS) { if (RegDeleteKey(hkDeleteKeyHandle, lpzKeyName) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkDeleteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::DeleteValue(LPCTSTR lpzValueName, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkDeleteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_WRITE, &hkDeleteKeyHandle) == ERROR_SUCCESS) { if (RegDeleteValue(hkDeleteKeyHandle, lpzValueName) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkDeleteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::GetValueInfo(LPCTSTR lpzValueName, DWORD* lpDataType, DWORD* lpDataSize, LPCTSTR lpzSubKey) { BOOL bRet = FALSE; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryValueEx(hkReadKeyHandle, lpzValueName, NULL, lpDataType, NULL, lpDataSize) == ERROR_SUCCESS) bRet = TRUE; RegCloseKey(hkReadKeyHandle); } return bRet; } BOOL neTKVMRegAccess::GetKeyInfo(LPDWORD lpdwNofSubKeys, LPDWORD lpdwMaxSubKeyLen, LPDWORD lpdwNofValues, LPDWORD lpdwMaxValueNameLen, LPDWORD lpdwMaxValueLen, LPCTSTR lpzSubKey) { BOOL bRet = FALSE; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryInfoKey(hkReadKeyHandle, NULL, NULL, NULL, lpdwNofSubKeys, lpdwMaxSubKeyLen, NULL, lpdwNofValues, lpdwMaxValueNameLen, lpdwMaxValueLen, NULL, NULL) == ERROR_SUCCESS) bRet = TRUE; RegCloseKey(hkReadKeyHandle); } return bRet; } VOID neTKVMRegAccess::FormatFullRegPath(LPTSTR lpzFullPathBuff, DWORD_PTR dwNumberOfElements, LPCTSTR lpzSubKey) { DWORD_PTR dwReqNumberOfElements = (m_lpsRegPath?_tcslen(m_lpsRegPath):0) + (lpzSubKey?_tcslen(lpzSubKey):0) + ((m_lpsRegPath && lpzSubKey)?1:0) + 1; memset(lpzFullPathBuff, 0, dwNumberOfElements); if (dwNumberOfElements >= dwReqNumberOfElements) { if (m_lpsRegPath) _tcscpy_s(lpzFullPathBuff, dwNumberOfElements, m_lpsRegPath); if (lpzSubKey) { if (m_lpsRegPath) _tcscat_s(lpzFullPathBuff, dwNumberOfElements, TEXT("\\")); _tcscat_s(lpzFullPathBuff, dwNumberOfElements, lpzSubKey); } } } <commit_msg>NetKvm: bug fix in RegAccess class<commit_after>// RegAccess.cpp: implementation of the neTKVMRegAccess class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "RegAccess.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// neTKVMRegAccess::neTKVMRegAccess() : m_lpsRegPath(NULL), m_hkPrimaryHKey(0) { } neTKVMRegAccess::neTKVMRegAccess(HKEY hNewPrKey, LPCTSTR lpzNewRegPath) : m_lpsRegPath(NULL), m_hkPrimaryHKey(0) { SetPrimaryKey(hNewPrKey); if (SetRegPath(lpzNewRegPath) == FALSE) { throw neTKVMRegAccessConstructorFailedException(); } } neTKVMRegAccess::~neTKVMRegAccess() { delete m_lpsRegPath; } VOID neTKVMRegAccess::SetPrimaryKey(HKEY hNewPrKey) { m_hkPrimaryHKey = hNewPrKey; } BOOL neTKVMRegAccess::SetRegPath(LPCTSTR lpzNewRegPath) { delete m_lpsRegPath; if (!lpzNewRegPath) { m_lpsRegPath = NULL; return TRUE; } m_lpsRegPath = _tcsdup(lpzNewRegPath); return (m_lpsRegPath != NULL)?TRUE:FALSE; } HKEY neTKVMRegAccess::GetPrimaryKey(VOID) { return m_hkPrimaryHKey; } BOOL neTKVMRegAccess::GetRegPath(LPTSTR lpsBuffer, DWORD dwNumberOfElements) { if (!dwNumberOfElements) { return FALSE; } if (!m_lpsRegPath) { *lpsBuffer = 0; return TRUE; } return (_tcscpy_s(lpsBuffer, dwNumberOfElements, m_lpsRegPath) == 0)?TRUE:FALSE; } DWORD neTKVMRegAccess::ReadDWord(LPCTSTR lpzValueName, DWORD dwDefault, LPCTSTR lpzSubKey) { DWORD dwRes = 0; return (ReadDWord(lpzValueName, &dwRes, lpzSubKey) == TRUE)?dwRes:dwDefault; } BOOL neTKVMRegAccess::ReadDWord(LPCTSTR lpzValueName, LPDWORD lpdwValue, LPCTSTR lpzSubKey) { BOOL bRes = FALSE; DWORD dwValue = 0, dwSize = sizeof(dwValue), dwType = REG_DWORD; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryValueEx(hkReadKeyHandle, lpzValueName, NULL, &dwType, (LPBYTE)&dwValue, &dwSize) == ERROR_SUCCESS) { bRes = TRUE; if (lpdwValue) { *lpdwValue = dwValue; } } RegCloseKey(hkReadKeyHandle); } return bRes; } DWORD neTKVMRegAccess::ReadString(LPCTSTR lpzValueName, LPTSTR lpzData, DWORD dwNumberOfElements, LPCTSTR lpzSubKey) { DWORD dwRes = 0; DWORD dwType = REG_SZ; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwBuffSize = dwNumberOfElements * sizeof(lpzData[0]); memset(lpzData, 0, dwBuffSize); FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryValueEx(hkReadKeyHandle, lpzValueName, NULL, &dwType, (LPBYTE)lpzData, &dwBuffSize) == ERROR_SUCCESS) dwRes = dwBuffSize / sizeof(lpzData[0]); RegCloseKey(hkReadKeyHandle); } return dwRes; } DWORD neTKVMRegAccess::ReadBinary(LPCTSTR lpzValueName, LPBYTE lpzData, DWORD dwSize, LPCTSTR lpzSubKey) { DWORD dwRes = 0; DWORD dwType = REG_BINARY; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; memset(lpzData, 0, dwSize); FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryValueEx(hkReadKeyHandle, lpzValueName, NULL, &dwType, lpzData, &dwSize) == ERROR_SUCCESS) dwRes = dwSize; RegCloseKey(hkReadKeyHandle); } return dwRes; } BOOL neTKVMRegAccess::ReadValueName(LPTSTR lpsValueName, DWORD dwNumberOfElements, DWORD dwIndex, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; BYTE baData[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDataSize = DEFAULT_REG_ENTRY_DATA_LEN, dwType = REG_BINARY; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { DWORD dwBuffSize = dwNumberOfElements * sizeof(lpsValueName[0]); if (RegEnumValue(hkReadKeyHandle, dwIndex, lpsValueName, &dwBuffSize, NULL, &dwType, baData, &dwDataSize) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkReadKeyHandle); } return bResult; } BOOL neTKVMRegAccess::ReadKeyName(LPTSTR lpsKeyName, DWORD dwNumberOfElements, DWORD dwIndex, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkReadKeyHandle = NULL; FILETIME stTimeFile; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_ENUMERATE_SUB_KEYS, &hkReadKeyHandle) == ERROR_SUCCESS) { DWORD dwBuffSize = dwNumberOfElements * sizeof(lpsKeyName[0]); if (RegEnumKeyEx(hkReadKeyHandle, dwIndex, lpsKeyName, &dwBuffSize, NULL, NULL, NULL, &stTimeFile) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkReadKeyHandle); } return bResult; } BOOL neTKVMRegAccess::WriteValue(LPCTSTR lpzValueName, DWORD dwValue, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkWriteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDisposition; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegCreateKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkWriteKeyHandle, &dwDisposition) == ERROR_SUCCESS) { if (RegSetValueEx(hkWriteKeyHandle, lpzValueName, 0, REG_DWORD, (LPCBYTE)&dwValue, sizeof(DWORD)) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkWriteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::WriteString(LPCTSTR lpzValueName, LPCTSTR lpzValue, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkWriteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDisposition; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegCreateKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkWriteKeyHandle, &dwDisposition) == ERROR_SUCCESS) { DWORD dwBuffSize = ((DWORD)_tcslen(lpzValue) + 1) * sizeof(lpzValue[0]); if (RegSetValueEx(hkWriteKeyHandle, lpzValueName, 0, REG_SZ, (LPCBYTE)lpzValue, dwBuffSize) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkWriteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::WriteBinary(LPCTSTR lpzValueName, LPCBYTE lpData, DWORD dwDataSize, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkWriteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDisposition; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegCreateKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkWriteKeyHandle, &dwDisposition) == ERROR_SUCCESS) { if (RegSetValueEx(hkWriteKeyHandle, lpzValueName, 0, REG_BINARY, lpData, dwDataSize) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkWriteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::AddKey(LPCTSTR lpzKeyName) { BOOL bResult = FALSE; HKEY hkWriteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; DWORD dwDisposition; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzKeyName); if (RegCreateKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, TEXT(""), REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hkWriteKeyHandle, &dwDisposition) == ERROR_SUCCESS) { bResult = TRUE; RegCloseKey(hkWriteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::DeleteKey(LPCTSTR lpzKeyName, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkDeleteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_WRITE, &hkDeleteKeyHandle) == ERROR_SUCCESS) { if (RegDeleteKey(hkDeleteKeyHandle, lpzKeyName) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkDeleteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::DeleteValue(LPCTSTR lpzValueName, LPCTSTR lpzSubKey) { BOOL bResult = FALSE; HKEY hkDeleteKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_WRITE, &hkDeleteKeyHandle) == ERROR_SUCCESS) { if (RegDeleteValue(hkDeleteKeyHandle, lpzValueName) == ERROR_SUCCESS) bResult = TRUE; RegCloseKey(hkDeleteKeyHandle); } return bResult; } BOOL neTKVMRegAccess::GetValueInfo(LPCTSTR lpzValueName, DWORD* lpDataType, DWORD* lpDataSize, LPCTSTR lpzSubKey) { BOOL bRet = FALSE; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryValueEx(hkReadKeyHandle, lpzValueName, NULL, lpDataType, NULL, lpDataSize) == ERROR_SUCCESS) bRet = TRUE; RegCloseKey(hkReadKeyHandle); } return bRet; } BOOL neTKVMRegAccess::GetKeyInfo(LPDWORD lpdwNofSubKeys, LPDWORD lpdwMaxSubKeyLen, LPDWORD lpdwNofValues, LPDWORD lpdwMaxValueNameLen, LPDWORD lpdwMaxValueLen, LPCTSTR lpzSubKey) { BOOL bRet = FALSE; HKEY hkReadKeyHandle = NULL; TCHAR tcaFullRegPath[DEFAULT_REG_ENTRY_DATA_LEN]; FormatFullRegPath(tcaFullRegPath, TBUF_SIZEOF(tcaFullRegPath), lpzSubKey); if (RegOpenKeyEx(m_hkPrimaryHKey, tcaFullRegPath, 0, KEY_QUERY_VALUE, &hkReadKeyHandle) == ERROR_SUCCESS) { if (RegQueryInfoKey(hkReadKeyHandle, NULL, NULL, NULL, lpdwNofSubKeys, lpdwMaxSubKeyLen, NULL, lpdwNofValues, lpdwMaxValueNameLen, lpdwMaxValueLen, NULL, NULL) == ERROR_SUCCESS) bRet = TRUE; RegCloseKey(hkReadKeyHandle); } return bRet; } VOID neTKVMRegAccess::FormatFullRegPath(LPTSTR lpzFullPathBuff, DWORD_PTR dwNumberOfElements, LPCTSTR lpzSubKey) { DWORD_PTR dwReqNumberOfElements = (m_lpsRegPath?_tcslen(m_lpsRegPath):0) + (lpzSubKey?_tcslen(lpzSubKey):0) + ((m_lpsRegPath && lpzSubKey)?1:0) + 1; memset(lpzFullPathBuff, 0, dwNumberOfElements); if (dwNumberOfElements >= dwReqNumberOfElements) { if (m_lpsRegPath) _tcscpy_s(lpzFullPathBuff, dwNumberOfElements, m_lpsRegPath); if (lpzSubKey) { if (m_lpsRegPath) _tcscat_s(lpzFullPathBuff, dwNumberOfElements, TEXT("\\")); _tcscat_s(lpzFullPathBuff, dwNumberOfElements, lpzSubKey); } } } <|endoftext|>
<commit_before>/******************************************************************************\ * File: support.cpp * Purpose: Implementation of DecoratedFrame class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/stockitem.h> // for wxGetStockLabel #include <wx/extension/filedlg.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> #include <wx/extension/report/listviewfile.h> #include <wx/extension/report/stc.h> #ifndef __WXMSW__ #include "app.xpm" #endif #include "support.h" #include "defs.h" DecoratedFrame::DecoratedFrame() : wxExFrameWithHistory( NULL, wxID_ANY, wxTheApp->GetAppDisplayName(), // title 25, // maxFiles 4) // maxProjects , m_MenuVCS(new wxExMenu) { SetIcon(wxICON(app)); #if wxUSE_STATUSBAR std::vector<wxExStatusBarPane> panes; panes.push_back(wxExStatusBarPane()); panes.push_back(wxExStatusBarPane("PaneFileType", 50, _("File type"))); panes.push_back(wxExStatusBarPane("PaneLines", 100, _("Lines"))); if (wxExLexers::Get()->Count() > 0) { #ifdef __WXMSW__ const int lexer_size = 60; #else const int lexer_size = 75; #endif panes.push_back(wxExStatusBarPane("PaneLexer", lexer_size, _("Lexer"))); panes.push_back(wxExStatusBarPane("PaneTheme", 100, _("Theme"))); } panes.push_back(wxExStatusBarPane("PaneItems", 65, _("Items"))); SetupStatusBar(panes); #endif wxExMenu *menuFile = new wxExMenu(); menuFile->Append(wxID_NEW); menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENT_FILE_MENU, menuFile); wxMenu* menuOpen = new wxMenu(); menuOpen->Append(ID_OPEN_LEXERS, _("&Lexers File")); menuOpen->Append(ID_OPEN_LOGFILE, _("&Log File")); menuOpen->Append(ID_OPEN_VCS, _("&VCS File")); menuFile->AppendSeparator(); menuFile->AppendSubMenu(menuOpen, _("Open")); menuFile->AppendSeparator(); menuFile->Append(wxID_CLOSE); menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll")); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE); menuFile->AppendSeparator(); menuFile->AppendPrint(); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu *menuEdit = new wxExMenu(); menuEdit->Append(wxID_UNDO); menuEdit->Append(wxID_REDO); menuEdit->AppendSeparator(); menuEdit->Append(wxID_CUT); menuEdit->Append(wxID_COPY); menuEdit->Append(wxID_PASTE); menuEdit->AppendSeparator(); menuEdit->Append(wxID_JUMP_TO); menuEdit->AppendSeparator(); wxExMenu* menuFind = new wxExMenu(); menuFind->Append(wxID_FIND); menuFind->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3")); menuFind->Append(wxID_REPLACE); menuFind->Append(ID_FIND_IN_FILES, wxExEllipsed(_("Find &In Files"))); menuFind->Append(ID_REPLACE_IN_FILES, wxExEllipsed(_("Replace In File&s"))); menuEdit->AppendSubMenu(menuFind, _("&Find And Replace")); menuEdit->AppendSeparator(); wxExMenu* menuMore = new wxExMenu(); if (menuMore->AppendTools(ID_MENU_TOOLS)) { menuMore->AppendSeparator(); } menuMore->Append(ID_EDIT_ADD_HEADER, wxExEllipsed(_("&Add Header"))); menuMore->Append(ID_EDIT_INSERT_SEQUENCE, wxExEllipsed(_("Insert Sequence"))); menuMore->AppendSeparator(); menuMore->Append( ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl+H")); menuEdit->AppendSubMenu(menuMore, _("More")); menuEdit->AppendSeparator(); m_MenuVCS->BuildVCS(); menuEdit->AppendSubMenu(m_MenuVCS, "&VCS", wxEmptyString, ID_MENU_VCS); menuEdit->AppendSeparator(); wxExMenu* menuMacro = new wxExMenu(); menuMacro->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record")); menuMacro->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record")); menuMacro->AppendSeparator(); menuMacro->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M")); menuEdit->AppendSubMenu(menuMacro, _("&Macro")); wxExMenu *menuView = new wxExMenu; menuView->AppendBars(); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files")); menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects")); menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer")); menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History")); menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table")); wxMenu *menuProcess = new wxMenu(); menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select"))); menuProcess->AppendSeparator(); menuProcess->Append(wxID_EXECUTE); menuProcess->Append(wxID_STOP); wxExMenu *menuProject = new wxExMenu(); menuProject->Append( ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW); menuProject->Append( ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN); UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject); menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text")); menuProject->Append( ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE), wxEmptyString, wxART_CLOSE); menuProject->AppendSeparator(); menuProject->Append( ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE); menuProject->Append( ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS); menuProject->AppendSeparator(); menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort")); wxMenu *menuWindow = new wxMenu(); menuWindow->Append(ID_SPLIT, _("Split")); wxMenu* menuOptions = new wxMenu(); if (wxExLexers::Get()->Count() > 0) { menuOptions->Append(ID_OPTION_VCS, wxExEllipsed(_("Set &VCS"))); } else { menuOptions->Append( ID_OPTION_LIST_COMPARATOR, wxExEllipsed(_("Set List &Comparator"))); } menuOptions->AppendSeparator(); menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font"))); // text also used as caption menuOptions->Append( ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set List &Read Only Colour"))); wxMenu *menuListSort = new wxMenu; menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending")); menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending")); menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle")); menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method")); menuOptions->AppendSeparator(); menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options"))); wxMenu *menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar* menubar = new wxMenuBar(); menubar->Append(menuFile, wxGetStockLabel(wxID_FILE)); menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT)); menubar->Append(menuView, _("&View")); menubar->Append(menuProcess, _("&Process")); menubar->Append(menuProject, _("&Project")); menubar->Append(menuWindow, _("&Window")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP)); SetMenuBar(menubar); } bool DecoratedFrame::AllowClose(wxWindowID id, wxWindow* page) { if (ProcessIsRunning()) { return false; } else if (id == NOTEBOOK_EDITORS) { wxExFileDialog dlg(this, &((wxExSTC*)page)->GetFile()); return dlg.ShowModalIfChanged() == wxID_OK; } else if (id == NOTEBOOK_PROJECTS) { wxExFileDialog dlg(this, (wxExListViewFile*)page); return dlg.ShowModalIfChanged() == wxID_OK; } else { return wxExFrameWithHistory::AllowClose(id, page); } } void DecoratedFrame::OnNotebook(wxWindowID id, wxWindow* page) { if (id == NOTEBOOK_EDITORS) { ((wxExSTC*)page)->PropertiesMessage(); } else if (id == NOTEBOOK_PROJECTS) { #if wxUSE_STATUSBAR ((wxExListViewFile*)page)->GetFileName().StatusText(); ((wxExListViewFile*)page)->UpdateStatusBar(); #endif } else if (id == NOTEBOOK_LISTS) { // Do nothing special. } else { wxFAIL; } } <commit_msg>use same size for theme as for lexer<commit_after>/******************************************************************************\ * File: support.cpp * Purpose: Implementation of DecoratedFrame class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/stockitem.h> // for wxGetStockLabel #include <wx/extension/filedlg.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> #include <wx/extension/report/listviewfile.h> #include <wx/extension/report/stc.h> #ifndef __WXMSW__ #include "app.xpm" #endif #include "support.h" #include "defs.h" DecoratedFrame::DecoratedFrame() : wxExFrameWithHistory( NULL, wxID_ANY, wxTheApp->GetAppDisplayName(), // title 25, // maxFiles 4) // maxProjects , m_MenuVCS(new wxExMenu) { SetIcon(wxICON(app)); #if wxUSE_STATUSBAR std::vector<wxExStatusBarPane> panes; panes.push_back(wxExStatusBarPane()); panes.push_back(wxExStatusBarPane("PaneFileType", 50, _("File type"))); panes.push_back(wxExStatusBarPane("PaneLines", 100, _("Lines"))); if (wxExLexers::Get()->Count() > 0) { #ifdef __WXMSW__ const int lexer_size = 60; #else const int lexer_size = 75; #endif panes.push_back(wxExStatusBarPane("PaneLexer", lexer_size, _("Lexer"))); panes.push_back(wxExStatusBarPane("PaneTheme", lexer_size, _("Theme"))); } panes.push_back(wxExStatusBarPane("PaneItems", 65, _("Items"))); SetupStatusBar(panes); #endif wxExMenu *menuFile = new wxExMenu(); menuFile->Append(wxID_NEW); menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENT_FILE_MENU, menuFile); wxMenu* menuOpen = new wxMenu(); menuOpen->Append(ID_OPEN_LEXERS, _("&Lexers File")); menuOpen->Append(ID_OPEN_LOGFILE, _("&Log File")); menuOpen->Append(ID_OPEN_VCS, _("&VCS File")); menuFile->AppendSeparator(); menuFile->AppendSubMenu(menuOpen, _("Open")); menuFile->AppendSeparator(); menuFile->Append(wxID_CLOSE); menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll")); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE); menuFile->AppendSeparator(); menuFile->AppendPrint(); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu *menuEdit = new wxExMenu(); menuEdit->Append(wxID_UNDO); menuEdit->Append(wxID_REDO); menuEdit->AppendSeparator(); menuEdit->Append(wxID_CUT); menuEdit->Append(wxID_COPY); menuEdit->Append(wxID_PASTE); menuEdit->AppendSeparator(); menuEdit->Append(wxID_JUMP_TO); menuEdit->AppendSeparator(); wxExMenu* menuFind = new wxExMenu(); menuFind->Append(wxID_FIND); menuFind->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3")); menuFind->Append(wxID_REPLACE); menuFind->Append(ID_FIND_IN_FILES, wxExEllipsed(_("Find &In Files"))); menuFind->Append(ID_REPLACE_IN_FILES, wxExEllipsed(_("Replace In File&s"))); menuEdit->AppendSubMenu(menuFind, _("&Find And Replace")); menuEdit->AppendSeparator(); wxExMenu* menuMore = new wxExMenu(); if (menuMore->AppendTools(ID_MENU_TOOLS)) { menuMore->AppendSeparator(); } menuMore->Append(ID_EDIT_ADD_HEADER, wxExEllipsed(_("&Add Header"))); menuMore->Append(ID_EDIT_INSERT_SEQUENCE, wxExEllipsed(_("Insert Sequence"))); menuMore->AppendSeparator(); menuMore->Append( ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl+H")); menuEdit->AppendSubMenu(menuMore, _("More")); menuEdit->AppendSeparator(); m_MenuVCS->BuildVCS(); menuEdit->AppendSubMenu(m_MenuVCS, "&VCS", wxEmptyString, ID_MENU_VCS); menuEdit->AppendSeparator(); wxExMenu* menuMacro = new wxExMenu(); menuMacro->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record")); menuMacro->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record")); menuMacro->AppendSeparator(); menuMacro->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M")); menuEdit->AppendSubMenu(menuMacro, _("&Macro")); wxExMenu *menuView = new wxExMenu; menuView->AppendBars(); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files")); menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects")); menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer")); menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History")); menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table")); wxMenu *menuProcess = new wxMenu(); menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select"))); menuProcess->AppendSeparator(); menuProcess->Append(wxID_EXECUTE); menuProcess->Append(wxID_STOP); wxExMenu *menuProject = new wxExMenu(); menuProject->Append( ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW); menuProject->Append( ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN); UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject); menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text")); menuProject->Append( ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE), wxEmptyString, wxART_CLOSE); menuProject->AppendSeparator(); menuProject->Append( ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE); menuProject->Append( ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS); menuProject->AppendSeparator(); menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort")); wxMenu *menuWindow = new wxMenu(); menuWindow->Append(ID_SPLIT, _("Split")); wxMenu* menuOptions = new wxMenu(); if (wxExLexers::Get()->Count() > 0) { menuOptions->Append(ID_OPTION_VCS, wxExEllipsed(_("Set &VCS"))); } else { menuOptions->Append( ID_OPTION_LIST_COMPARATOR, wxExEllipsed(_("Set List &Comparator"))); } menuOptions->AppendSeparator(); menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font"))); // text also used as caption menuOptions->Append( ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set List &Read Only Colour"))); wxMenu *menuListSort = new wxMenu; menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending")); menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending")); menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle")); menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method")); menuOptions->AppendSeparator(); menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options"))); wxMenu *menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar* menubar = new wxMenuBar(); menubar->Append(menuFile, wxGetStockLabel(wxID_FILE)); menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT)); menubar->Append(menuView, _("&View")); menubar->Append(menuProcess, _("&Process")); menubar->Append(menuProject, _("&Project")); menubar->Append(menuWindow, _("&Window")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP)); SetMenuBar(menubar); } bool DecoratedFrame::AllowClose(wxWindowID id, wxWindow* page) { if (ProcessIsRunning()) { return false; } else if (id == NOTEBOOK_EDITORS) { wxExFileDialog dlg(this, &((wxExSTC*)page)->GetFile()); return dlg.ShowModalIfChanged() == wxID_OK; } else if (id == NOTEBOOK_PROJECTS) { wxExFileDialog dlg(this, (wxExListViewFile*)page); return dlg.ShowModalIfChanged() == wxID_OK; } else { return wxExFrameWithHistory::AllowClose(id, page); } } void DecoratedFrame::OnNotebook(wxWindowID id, wxWindow* page) { if (id == NOTEBOOK_EDITORS) { ((wxExSTC*)page)->PropertiesMessage(); } else if (id == NOTEBOOK_PROJECTS) { #if wxUSE_STATUSBAR ((wxExListViewFile*)page)->GetFileName().StatusText(); ((wxExListViewFile*)page)->UpdateStatusBar(); #endif } else if (id == NOTEBOOK_LISTS) { // Do nothing special. } else { wxFAIL; } } <|endoftext|>
<commit_before>#define LOG_TAG "silk-h264-enc" #include "SimpleH264Encoder.h" #include <queue> #include <media/stagefright/MediaBuffer.h> #include <media/stagefright/MetaData.h> // This is an ugly hack. We forked this from libstagefright // so we can trigger key frames and adjust bitrate #include "MediaCodecSource.h" #include <media/openmax/OMX_IVCommon.h> #include <media/stagefright/OMXCodec.h> #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/foundation/AMessage.h> #include <utils/Thread.h> #include <utils/SystemClock.h> #include <utils/Log.h> using namespace android; static const char* kMimeTypeAvc = "video/avc"; static const uint32_t kColorFormat = OMX_COLOR_FormatYUV420SemiPlanar; static const int32_t kIFrameInterval = 60; class SingleBufferMediaSource: public MediaSource { public: SingleBufferMediaSource(int width, int height) : mBuffer(0), mHaveNextBuffer(false) { mMetaData = new MetaData(); mMetaData->setInt32(kKeyWidth, width); mMetaData->setInt32(kKeyHeight, height); mMetaData->setInt32(kKeyStride, width); mMetaData->setInt32(kKeySliceHeight, height); mMetaData->setInt32(kKeyColorFormat, kColorFormat); mMetaData->setCString(kKeyMIMEType, "video/raw"); } status_t start(MetaData *params = NULL) override { (void) params; return 0; } status_t stop() override { nextFrame(nullptr); // Unclog read return 0; } sp<MetaData> getFormat() override { return mMetaData; } status_t read(MediaBuffer **buffer, const ReadOptions *options = NULL) override { Mutex::Autolock autolock(mBufferLock); if (options != NULL) { ALOGW("ReadOptions not supported"); return ERROR_END_OF_STREAM; } while (!mHaveNextBuffer) { mBufferCondition.wait(mBufferLock); } mHaveNextBuffer = false; if (!mBuffer) { ALOGI("End of stream"); return ERROR_END_OF_STREAM; } *buffer = mBuffer; mBuffer = nullptr; return OK; } void nextFrame(android::MediaBuffer *yuv420SemiPlanarFrame) { Mutex::Autolock autolock(mBufferLock); if (mBuffer) { mBuffer->release(); } mBuffer = yuv420SemiPlanarFrame; mHaveNextBuffer = true; mBufferCondition.signal(); } private: MediaBuffer *mBuffer; bool mHaveNextBuffer; Mutex mBufferLock; Condition mBufferCondition; sp<MetaData> mMetaData; }; class SimpleH264EncoderImpl: public SimpleH264Encoder { public: static SimpleH264Encoder *Create(int width, int height, int maxBitrateK, int targetFps, FrameOutCallback frameOutCallback, void *frameOutUserData); virtual ~SimpleH264EncoderImpl() { stop(); } virtual void setBitRate(int bitrateK); virtual void requestKeyFrame(); virtual void nextFrame(void *yuv420SemiPlanarFrame, void (*deallocator)(void *), InputFrameInfo& inputFrameInfo); virtual void stop(); private: class FramePuller: public android::Thread { public: FramePuller(SimpleH264EncoderImpl *encoder): encoder(encoder) {}; private: bool threadLoop() override { return encoder->threadLoop(); } SimpleH264EncoderImpl *encoder; }; friend class FramePuller; SimpleH264EncoderImpl(int width, int height, int maxBitrateK, FrameOutCallback frameOutCallback, void *frameOutUserData); bool init(int targetFps); bool threadLoop(); int width; int height; int maxBitrateK; FrameOutCallback frameOutCallback; void *frameOutUserData; uint8_t *codecConfig; int codecConfigLength; uint8_t *encodedFrame; int encodedFrameMaxLength; int64_t lastCaptureTimeMs; android::sp<android::ALooper> looper; android::sp<android::MediaCodecSource> mediaCodecSource; android::sp<SingleBufferMediaSource> frameQueue; android::sp<android::Thread> framePuller; std::queue<InputFrameInfo> frameInfo; android::Mutex mutex; }; SimpleH264Encoder *SimpleH264EncoderImpl::Create(int width, int height, int maxBitrateK, int targetFps, FrameOutCallback frameOutCallback, void *frameOutUserData) { SimpleH264EncoderImpl *enc = new SimpleH264EncoderImpl( width, height, maxBitrateK, frameOutCallback, frameOutUserData ); if (!enc->init(targetFps)) { delete enc; enc = nullptr; }; return enc; bail: delete enc; return nullptr; } SimpleH264EncoderImpl::SimpleH264EncoderImpl(int width, int height, int maxBitrateK, FrameOutCallback frameOutCallback, void *frameOutUserData) : width(width), height(height), maxBitrateK(maxBitrateK), frameOutCallback(frameOutCallback), frameOutUserData(frameOutUserData), codecConfig(nullptr), codecConfigLength(0), encodedFrame(nullptr), encodedFrameMaxLength(0), lastCaptureTimeMs(-1) { frameQueue = new SingleBufferMediaSource(width, height); looper = new ALooper; looper->setName("SimpleH264Encoder"); framePuller = new SimpleH264EncoderImpl::FramePuller(this); }; bool SimpleH264EncoderImpl::init(int targetFps) { sp<MetaData> meta = frameQueue->getFormat(); int32_t width, height, stride, sliceHeight, colorFormat; CHECK(meta->findInt32(kKeyWidth, &width)); CHECK(meta->findInt32(kKeyHeight, &height)); CHECK(meta->findInt32(kKeyStride, &stride)); CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight)); CHECK(meta->findInt32(kKeyColorFormat, &colorFormat)); sp<AMessage> format = new AMessage(); format->setInt32("width", width); format->setInt32("height", height); format->setInt32("stride", stride); format->setInt32("slice-height", sliceHeight); format->setInt32("color-format", colorFormat); format->setString("mime", kMimeTypeAvc); format->setInt32("bitrate", maxBitrateK * 1024); format->setInt32("bitrate-mode", OMX_Video_ControlRateConstant); format->setFloat("frame-rate", targetFps); format->setInt32("i-frame-interval", kIFrameInterval); looper->start(); mediaCodecSource = MediaCodecSource::Create( looper, format, frameQueue, #ifdef TARGET_GE_MARSHMALLOW NULL, #endif 0 ); if (mediaCodecSource == nullptr) { ALOGE("Unable to create encoder"); return false; } status_t err; err = mediaCodecSource->start(); if (err != 0) { ALOGE("Unable to start encoder"); return false; } err = framePuller->run(); if (err != 0) { ALOGE("Unable to start puller thread"); return false; } return true; } void SimpleH264EncoderImpl::setBitRate(int bitrateK) { Mutex::Autolock autolock(mutex); if (mediaCodecSource != nullptr) { mediaCodecSource->videoBitRate( (bitrateK < maxBitrateK ? bitrateK : maxBitrateK) * 1024 ); } } void SimpleH264EncoderImpl::requestKeyFrame() { Mutex::Autolock autolock(mutex); if (mediaCodecSource != nullptr) { mediaCodecSource->requestIDRFrame(); } } class UserMediaBuffer: public android::MediaBuffer { public: UserMediaBuffer(void *data, size_t size, void (*deallocator)(void *)) : MediaBuffer(data, size), deallocator(deallocator) {} protected: ~UserMediaBuffer() { deallocator(data()); } private: void (*deallocator)(void *); }; void SimpleH264EncoderImpl::nextFrame(void *yuv420SemiPlanarFrame, void (*deallocator)(void *), InputFrameInfo& inputFrameInfo) { Mutex::Autolock autolock(mutex); if (frameQueue == nullptr) { ALOGI("Stopped, ignoring frame"); return; } auto buffer = new UserMediaBuffer( yuv420SemiPlanarFrame, height * width * 3 / 2, deallocator ); buffer->meta_data()->setInt64(kKeyTime, inputFrameInfo.captureTimeMs * 1000); frameInfo.push(inputFrameInfo); frameQueue->nextFrame(buffer); } void SimpleH264EncoderImpl::stop() { Mutex::Autolock autolock(mutex); framePuller->requestExit(); if (mediaCodecSource != nullptr) { mediaCodecSource->stop(); } if (frameQueue != nullptr) { frameQueue->stop(); } if (looper != nullptr) { looper->stop(); } if (framePuller->isRunning()) { framePuller->join(); CHECK(!framePuller->isRunning()); } frameQueue = nullptr; mediaCodecSource = nullptr; looper = nullptr; delete [] codecConfig; codecConfig = nullptr; codecConfigLength = 0; delete [] encodedFrame; encodedFrame = nullptr; encodedFrameMaxLength = 0; } bool SimpleH264EncoderImpl::threadLoop() { MediaBuffer *buffer; status_t err = mediaCodecSource->read(&buffer); if (err != OK) { ALOGE("Error reading from source: %d", err); return false; } if (buffer == NULL) { ALOGE("Failed to get buffer from source"); return false; } int32_t isCodecConfig = 0; int32_t isIFrame = 0; int64_t timestamp = 0; if (buffer->meta_data() == NULL) { ALOGE("Failed to get buffer meta_data()"); return false; } buffer->meta_data()->findInt32(kKeyIsCodecConfig, &isCodecConfig); buffer->meta_data()->findInt32(kKeyIsSyncFrame, &isIFrame); if (isCodecConfig) { if (codecConfig) { delete [] codecConfig; } codecConfigLength = buffer->range_length(); codecConfig = new uint8_t[codecConfigLength]; memcpy(codecConfig, static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(), codecConfigLength ); } else { EncodedFrameInfo info; bool drop = false; info.userData = frameOutUserData; info.keyFrame = isIFrame; int64_t timeMicro = 0; buffer->meta_data()->findInt64(kKeyTime, &timeMicro); info.input.captureTimeMs = timeMicro / 1000; if (lastCaptureTimeMs > -1) { auto timeSinceLastFrameMs = static_cast<int>(info.input.captureTimeMs - lastCaptureTimeMs); ALOGE("Frame. iframe=%d timeSinceLastFrameMs=%dms captureTimeMs=%lldms", isIFrame, timeSinceLastFrameMs, info.input.captureTimeMs); } lastCaptureTimeMs = info.input.captureTimeMs; { Mutex::Autolock autolock(mutex); for (;;) { if (frameInfo.empty()) { ALOGE("frameInfo exhausted. Encoder broken?"); drop = true; break; } InputFrameInfo& ifi = frameInfo.front(); if (ifi.captureTimeMs != info.input.captureTimeMs) { ALOGE("Unknown frame. Encoder broken?"); frameInfo.pop(); continue; } info.input = ifi; frameInfo.pop(); break; } } if (!drop) { if (isIFrame) { int encodedFrameLength = codecConfigLength + buffer->range_length(); if (encodedFrame == nullptr || encodedFrameMaxLength < encodedFrameLength) { encodedFrameMaxLength = encodedFrameLength + encodedFrameLength / 2; delete [] encodedFrame; encodedFrame = new uint8_t[encodedFrameMaxLength]; } // Always send codecConfig with an i-frame to make the stream more // resilient if (codecConfig) { memcpy(encodedFrame, codecConfig, codecConfigLength); } memcpy( encodedFrame + codecConfigLength, static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(), buffer->range_length() ); info.encodedFrame = encodedFrame; info.encodedFrameLength = encodedFrameLength; } else { info.encodedFrame = static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(); info.encodedFrameLength = buffer->range_length(); } frameOutCallback(info); } } buffer->release(); return true; } SimpleH264Encoder *SimpleH264Encoder::Create(int width, int height, int maxBitrateK, int targetFps, FrameOutCallback frameOutCallback, void *frameOutUserData) { return SimpleH264EncoderImpl::Create( width, height, maxBitrateK, targetFps, frameOutCallback, frameOutUserData ); } <commit_msg>broken_heart:<commit_after>#define LOG_TAG "silk-h264-enc" #include "SimpleH264Encoder.h" #include <queue> #include <media/stagefright/MediaBuffer.h> #include <media/stagefright/MetaData.h> // This is an ugly hack. We forked this from libstagefright // so we can trigger key frames and adjust bitrate #include "MediaCodecSource.h" #include <media/openmax/OMX_IVCommon.h> #include <media/stagefright/OMXCodec.h> #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/foundation/AMessage.h> #include <utils/Thread.h> #include <utils/SystemClock.h> #include <utils/Log.h> using namespace android; static const char* kMimeTypeAvc = "video/avc"; static const uint32_t kColorFormat = OMX_COLOR_FormatYUV420SemiPlanar; static const int32_t kIFrameInterval = 60; class SingleBufferMediaSource: public MediaSource { public: SingleBufferMediaSource(int width, int height) : mBuffer(0), mHaveNextBuffer(false) { mMetaData = new MetaData(); mMetaData->setInt32(kKeyWidth, width); mMetaData->setInt32(kKeyHeight, height); mMetaData->setInt32(kKeyStride, width); mMetaData->setInt32(kKeySliceHeight, height); mMetaData->setInt32(kKeyColorFormat, kColorFormat); mMetaData->setCString(kKeyMIMEType, "video/raw"); } status_t start(MetaData *params = NULL) override { (void) params; return 0; } status_t stop() override { nextFrame(nullptr); // Unclog read return 0; } sp<MetaData> getFormat() override { return mMetaData; } status_t read(MediaBuffer **buffer, const ReadOptions *options = NULL) override { Mutex::Autolock autolock(mBufferLock); if (options != NULL) { ALOGW("ReadOptions not supported"); return ERROR_END_OF_STREAM; } while (!mHaveNextBuffer) { mBufferCondition.wait(mBufferLock); } mHaveNextBuffer = false; if (!mBuffer) { ALOGI("End of stream"); return ERROR_END_OF_STREAM; } *buffer = mBuffer; mBuffer = nullptr; return OK; } void nextFrame(android::MediaBuffer *yuv420SemiPlanarFrame) { Mutex::Autolock autolock(mBufferLock); if (mBuffer) { mBuffer->release(); } mBuffer = yuv420SemiPlanarFrame; mHaveNextBuffer = true; mBufferCondition.signal(); } private: MediaBuffer *mBuffer; bool mHaveNextBuffer; Mutex mBufferLock; Condition mBufferCondition; sp<MetaData> mMetaData; }; class SimpleH264EncoderImpl: public SimpleH264Encoder { public: static SimpleH264Encoder *Create(int width, int height, int maxBitrateK, int targetFps, FrameOutCallback frameOutCallback, void *frameOutUserData); virtual ~SimpleH264EncoderImpl() { stop(); } virtual void setBitRate(int bitrateK); virtual void requestKeyFrame(); virtual void nextFrame(void *yuv420SemiPlanarFrame, void (*deallocator)(void *), InputFrameInfo& inputFrameInfo); virtual void stop(); private: class FramePuller: public android::Thread { public: FramePuller(SimpleH264EncoderImpl *encoder): encoder(encoder) {}; private: bool threadLoop() override { return encoder->threadLoop(); } SimpleH264EncoderImpl *encoder; }; friend class FramePuller; SimpleH264EncoderImpl(int width, int height, int maxBitrateK, FrameOutCallback frameOutCallback, void *frameOutUserData); bool init(int targetFps); bool threadLoop(); int width; int height; int maxBitrateK; FrameOutCallback frameOutCallback; void *frameOutUserData; uint8_t *codecConfig; int codecConfigLength; uint8_t *encodedFrame; int encodedFrameMaxLength; int64_t lastCaptureTimeMs; android::sp<android::ALooper> looper; android::sp<android::MediaCodecSource> mediaCodecSource; android::sp<SingleBufferMediaSource> frameQueue; android::sp<android::Thread> framePuller; std::queue<InputFrameInfo> frameInfo; android::Mutex mutex; }; SimpleH264Encoder *SimpleH264EncoderImpl::Create(int width, int height, int maxBitrateK, int targetFps, FrameOutCallback frameOutCallback, void *frameOutUserData) { SimpleH264EncoderImpl *enc = new SimpleH264EncoderImpl( width, height, maxBitrateK, frameOutCallback, frameOutUserData ); if (!enc->init(targetFps)) { delete enc; enc = nullptr; }; return enc; bail: delete enc; return nullptr; } SimpleH264EncoderImpl::SimpleH264EncoderImpl(int width, int height, int maxBitrateK, FrameOutCallback frameOutCallback, void *frameOutUserData) : width(width), height(height), maxBitrateK(maxBitrateK), frameOutCallback(frameOutCallback), frameOutUserData(frameOutUserData), codecConfig(nullptr), codecConfigLength(0), encodedFrame(nullptr), encodedFrameMaxLength(0), lastCaptureTimeMs(-1) { frameQueue = new SingleBufferMediaSource(width, height); looper = new ALooper; looper->setName("SimpleH264Encoder"); framePuller = new SimpleH264EncoderImpl::FramePuller(this); }; bool SimpleH264EncoderImpl::init(int targetFps) { sp<MetaData> meta = frameQueue->getFormat(); int32_t width, height, stride, sliceHeight, colorFormat; CHECK(meta->findInt32(kKeyWidth, &width)); CHECK(meta->findInt32(kKeyHeight, &height)); CHECK(meta->findInt32(kKeyStride, &stride)); CHECK(meta->findInt32(kKeySliceHeight, &sliceHeight)); CHECK(meta->findInt32(kKeyColorFormat, &colorFormat)); sp<AMessage> format = new AMessage(); format->setInt32("width", width); format->setInt32("height", height); format->setInt32("stride", stride); format->setInt32("slice-height", sliceHeight); format->setInt32("color-format", colorFormat); format->setString("mime", kMimeTypeAvc); format->setInt32("bitrate", maxBitrateK * 1024); format->setInt32("bitrate-mode", OMX_Video_ControlRateConstant); format->setFloat("frame-rate", targetFps); format->setInt32("i-frame-interval", kIFrameInterval); looper->start(); mediaCodecSource = MediaCodecSource::Create( looper, format, frameQueue, #ifdef TARGET_GE_MARSHMALLOW NULL, #endif 0 ); if (mediaCodecSource == nullptr) { ALOGE("Unable to create encoder"); return false; } status_t err; err = mediaCodecSource->start(); if (err != 0) { ALOGE("Unable to start encoder"); return false; } err = framePuller->run(); if (err != 0) { ALOGE("Unable to start puller thread"); return false; } return true; } void SimpleH264EncoderImpl::setBitRate(int bitrateK) { Mutex::Autolock autolock(mutex); if (mediaCodecSource != nullptr) { mediaCodecSource->videoBitRate( (bitrateK < maxBitrateK ? bitrateK : maxBitrateK) * 1024 ); } } void SimpleH264EncoderImpl::requestKeyFrame() { Mutex::Autolock autolock(mutex); if (mediaCodecSource != nullptr) { mediaCodecSource->requestIDRFrame(); } } class UserMediaBuffer: public android::MediaBuffer { public: UserMediaBuffer(void *data, size_t size, void (*deallocator)(void *)) : MediaBuffer(data, size), deallocator(deallocator) {} protected: ~UserMediaBuffer() { deallocator(data()); } private: void (*deallocator)(void *); }; void SimpleH264EncoderImpl::nextFrame(void *yuv420SemiPlanarFrame, void (*deallocator)(void *), InputFrameInfo& inputFrameInfo) { Mutex::Autolock autolock(mutex); if (frameQueue == nullptr) { ALOGI("Stopped, ignoring frame"); return; } auto buffer = new UserMediaBuffer( yuv420SemiPlanarFrame, height * width * 3 / 2, deallocator ); buffer->meta_data()->setInt64(kKeyTime, inputFrameInfo.captureTimeMs * 1000); frameInfo.push(inputFrameInfo); frameQueue->nextFrame(buffer); } void SimpleH264EncoderImpl::stop() { Mutex::Autolock autolock(mutex); framePuller->requestExit(); if (mediaCodecSource != nullptr) { mediaCodecSource->stop(); } if (frameQueue != nullptr) { frameQueue->stop(); } if (looper != nullptr) { looper->stop(); } if (framePuller->isRunning()) { framePuller->join(); CHECK(!framePuller->isRunning()); } frameQueue = nullptr; mediaCodecSource = nullptr; looper = nullptr; delete [] codecConfig; codecConfig = nullptr; codecConfigLength = 0; delete [] encodedFrame; encodedFrame = nullptr; encodedFrameMaxLength = 0; } bool SimpleH264EncoderImpl::threadLoop() { MediaBuffer *buffer; status_t err = mediaCodecSource->read(&buffer); if (err != OK) { ALOGE("Error reading from source: %d", err); return false; } if (buffer == NULL) { ALOGE("Failed to get buffer from source"); return false; } int32_t isCodecConfig = 0; int32_t isIFrame = 0; int64_t timestamp = 0; if (buffer->meta_data() == NULL) { ALOGE("Failed to get buffer meta_data()"); return false; } buffer->meta_data()->findInt32(kKeyIsCodecConfig, &isCodecConfig); buffer->meta_data()->findInt32(kKeyIsSyncFrame, &isIFrame); if (isCodecConfig) { if (codecConfig) { delete [] codecConfig; } codecConfigLength = buffer->range_length(); codecConfig = new uint8_t[codecConfigLength]; memcpy(codecConfig, static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(), codecConfigLength ); } else { EncodedFrameInfo info; bool drop = false; info.userData = frameOutUserData; info.keyFrame = isIFrame; int64_t timeMicro = 0; buffer->meta_data()->findInt64(kKeyTime, &timeMicro); info.input.captureTimeMs = timeMicro / 1000; if (lastCaptureTimeMs > -1) { auto timeSinceLastFrameMs = static_cast<int>(info.input.captureTimeMs - lastCaptureTimeMs); ALOGE("Frame. iframe=%d timeSinceLastFrameMs=%dms captureTimeMs=%lldms", isIFrame, timeSinceLastFrameMs, static_cast<long long>(info.input.captureTimeMs)); } lastCaptureTimeMs = info.input.captureTimeMs; { Mutex::Autolock autolock(mutex); for (;;) { if (frameInfo.empty()) { ALOGE("frameInfo exhausted. Encoder broken?"); drop = true; break; } InputFrameInfo& ifi = frameInfo.front(); if (ifi.captureTimeMs != info.input.captureTimeMs) { ALOGE("Unknown frame. Encoder broken?"); frameInfo.pop(); continue; } info.input = ifi; frameInfo.pop(); break; } } if (!drop) { if (isIFrame) { int encodedFrameLength = codecConfigLength + buffer->range_length(); if (encodedFrame == nullptr || encodedFrameMaxLength < encodedFrameLength) { encodedFrameMaxLength = encodedFrameLength + encodedFrameLength / 2; delete [] encodedFrame; encodedFrame = new uint8_t[encodedFrameMaxLength]; } // Always send codecConfig with an i-frame to make the stream more // resilient if (codecConfig) { memcpy(encodedFrame, codecConfig, codecConfigLength); } memcpy( encodedFrame + codecConfigLength, static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(), buffer->range_length() ); info.encodedFrame = encodedFrame; info.encodedFrameLength = encodedFrameLength; } else { info.encodedFrame = static_cast<uint8_t*>(buffer->data()) + buffer->range_offset(); info.encodedFrameLength = buffer->range_length(); } frameOutCallback(info); } } buffer->release(); return true; } SimpleH264Encoder *SimpleH264Encoder::Create(int width, int height, int maxBitrateK, int targetFps, FrameOutCallback frameOutCallback, void *frameOutUserData) { return SimpleH264EncoderImpl::Create( width, height, maxBitrateK, targetFps, frameOutCallback, frameOutUserData ); } <|endoftext|>
<commit_before>/* * File: AizuJudger.cpp * Author: 51isoft * * Created on 2014年8月13日, 下午2:53 */ #include "AizuJudger.h" AizuJudger::AizuJudger(JudgerInfo * _info) : VirtualJudger(_info) { language_table["1"] = "C++"; language_table["2"] = "C"; language_table["3"] = "JAVA"; language_table["6"] = "C#"; language_table["5"] = "Python"; language_table["9"] = "Ruby"; } AizuJudger::~AizuJudger() { } void AizuJudger::initHandShake(){ socket->sendMessage(CONFIG->GetJudge_connect_string() + "\nAizu"); } /** * Login to Aizu */ void AizuJudger::login() { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, "http://judge.u-aizu.ac.jp/onlinejudge/index.jsp"); string post = (string) "loginUserID=" + info->GetUsername() + "&loginPassword=" + escapeURL(info->GetPassword()) + "&submit=Sign+in"; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str()); performCurl(); string html = loadAllFromFile(tmpfilename); //cout<<ts; if (html.find("<span class=\"line\">Login</span>") != string::npos) { throw Exception("Login failed!"); } } /** * Submit a run * @param bott Bott file for Run info * @return Submit status */ int AizuJudger::submit(Bott * bott) { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, "http://judge.u-aizu.ac.jp/onlinejudge/servlet/Submit"); string post = (string) "userID=" + escapeURL(info->GetUsername()) + "&password=" + escapeURL(info->GetPassword()) + "&problemNO=" + bott->Getvid() + "&language=" + escapeURL(bott->Getlanguage()) + "&sourceCode=" + escapeURL(bott->Getsrc()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str()); try { performCurl(); } catch (Exception & e) { return SUBMIT_OTHER_ERROR; } string html = loadAllFromFile(tmpfilename); if (html.find("UserID or Password is Wrong.") != string::npos || html.find("<span class=\"line\">Login</span>") != string::npos) return SUBMIT_OTHER_ERROR; return SUBMIT_NORMAL; } /** * Get result and related info * @param bott Original Bott info * @return Result Bott file */ Bott * AizuJudger::getStatus(Bott * bott) { time_t begin_time = time(NULL); Bott * result_bott; while (true) { // check wait time if (time(NULL) - begin_time > info->GetMax_wait_time()) { throw Exception("Failed to get current result, judge time out."); } prepareCurl(); curl_easy_setopt( curl, CURLOPT_URL, ((string) "http://judge.u-aizu.ac.jp/onlinejudge/status.jsp").c_str()); performCurl(); string html = loadAllFromFile(tmpfilename); string status; string runid, result, time_used, memory_used; // get first row of current user if (!RE2::PartialMatch( html, "(?s)(<tr class=\"dat\".*?id=" + info->GetUsername() + ".*?</tr>)", &status)) { throw Exception("Failed to get status row."); } // get result if (!RE2::PartialMatch( status, "(?s)rid=([0-9]*).*status.*?<a href=\"review.*?>(.*?)</a>", &runid, &result)) { throw Exception("Failed to get current result."); } result = convertResult(trim(result)); if (isFinalResult(result)) { // result is the final one, get details if (result != "Runtime Error" && result != "Compile Error") { if (!RE2::PartialMatch( status, "(?s)<td class=\"text-center\">([0-9\\.]*) s.*?<td.*?>([0-9]*) KB", &time_used, &memory_used)) { throw Exception("Failed to parse details from status row."); } } else { memory_used = time_used = "0"; } result_bott = new Bott; result_bott->Settype(RESULT_REPORT); result_bott->Setresult(convertResult(result)); result_bott->Settime_used( intToString(stringToDouble(time_used) * 100 + 0.1)); result_bott->Setmemory_used(trim(memory_used)); result_bott->Setremote_runid(trim(runid)); break; } } return result_bott; } /** * Convert result text to local ones, keep consistency * @param result Original result * @return Converted local result */ string AizuJudger::convertResult(string result) { if (result.find("Time Limit Exceeded") != string::npos) return "Time Limit Exceed"; if (result.find("Memory Limit Exceeded") != string::npos) return "Memory Limit Exceed"; if (result.find("Output Limit Exceeded") != string::npos) return "Output Limit Exceed"; return trim(result); } /** * Get compile error info * @param bott Result bott file * @return Compile error info */ string AizuJudger::getCEinfo(Bott * bott) { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, ((string) "http://judge.u-aizu.ac.jp/onlinejudge/compile_log.jsp?runID=" + bott->Getremote_runid()).c_str()); performCurl(); string info = loadAllFromFile(tmpfilename); string result; char * ce_info = new char[info.length() + 1]; strcpy(ce_info, info.c_str()); char * buffer = new char[info.length() * 2]; // SCU is in GBK charset charset_convert("SHIFT_JIS", "UTF-8//TRANSLIT", ce_info, info.length() + 1, buffer, info.length() * 2); if (!RE2::PartialMatch(buffer, "(?s)<p style=\"font-size:11pt;\">(.*)</p>", &result)) { return ""; } strcpy(buffer, result.c_str()); decode_html_entities_utf8(buffer, NULL); result = buffer; delete [] ce_info; delete [] buffer; return trim(result); } <commit_msg>Aizu: double space after <tr....<commit_after>/* * File: AizuJudger.cpp * Author: 51isoft * * Created on 2014年8月13日, 下午2:53 */ #include "AizuJudger.h" AizuJudger::AizuJudger(JudgerInfo * _info) : VirtualJudger(_info) { language_table["1"] = "C++"; language_table["2"] = "C"; language_table["3"] = "JAVA"; language_table["6"] = "C#"; language_table["5"] = "Python"; language_table["9"] = "Ruby"; } AizuJudger::~AizuJudger() { } void AizuJudger::initHandShake(){ socket->sendMessage(CONFIG->GetJudge_connect_string() + "\nAizu"); } /** * Login to Aizu */ void AizuJudger::login() { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, "http://judge.u-aizu.ac.jp/onlinejudge/index.jsp"); string post = (string) "loginUserID=" + info->GetUsername() + "&loginPassword=" + escapeURL(info->GetPassword()) + "&submit=Sign+in"; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str()); performCurl(); string html = loadAllFromFile(tmpfilename); //cout<<ts; if (html.find("<span class=\"line\">Login</span>") != string::npos) { throw Exception("Login failed!"); } } /** * Submit a run * @param bott Bott file for Run info * @return Submit status */ int AizuJudger::submit(Bott * bott) { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, "http://judge.u-aizu.ac.jp/onlinejudge/servlet/Submit"); string post = (string) "userID=" + escapeURL(info->GetUsername()) + "&password=" + escapeURL(info->GetPassword()) + "&problemNO=" + bott->Getvid() + "&language=" + escapeURL(bott->Getlanguage()) + "&sourceCode=" + escapeURL(bott->Getsrc()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post.c_str()); try { performCurl(); } catch (Exception & e) { return SUBMIT_OTHER_ERROR; } string html = loadAllFromFile(tmpfilename); if (html.find("UserID or Password is Wrong.") != string::npos || html.find("<span class=\"line\">Login</span>") != string::npos) return SUBMIT_OTHER_ERROR; return SUBMIT_NORMAL; } /** * Get result and related info * @param bott Original Bott info * @return Result Bott file */ Bott * AizuJudger::getStatus(Bott * bott) { time_t begin_time = time(NULL); Bott * result_bott; while (true) { // check wait time if (time(NULL) - begin_time > info->GetMax_wait_time()) { throw Exception("Failed to get current result, judge time out."); } prepareCurl(); curl_easy_setopt( curl, CURLOPT_URL, ((string) "http://judge.u-aizu.ac.jp/onlinejudge/status.jsp").c_str()); performCurl(); string html = loadAllFromFile(tmpfilename); string status; string runid, result, time_used, memory_used; // get first row of current user if (!RE2::PartialMatch( html, "(?s)(<tr *class=\"dat\".*?id=" + info->GetUsername() + ".*?</tr>)", &status)) { throw Exception("Failed to get status row."); } // get result if (!RE2::PartialMatch( status, "(?s)rid=([0-9]*).*status.*?<a href=\"review.*?>(.*?)</a>", &runid, &result)) { throw Exception("Failed to get current result."); } result = convertResult(trim(result)); if (isFinalResult(result)) { // result is the final one, get details if (result != "Runtime Error" && result != "Compile Error") { if (!RE2::PartialMatch( status, "(?s)<td class=\"text-center\">([0-9\\.]*) s.*?<td.*?>([0-9]*) KB", &time_used, &memory_used)) { throw Exception("Failed to parse details from status row."); } } else { memory_used = time_used = "0"; } result_bott = new Bott; result_bott->Settype(RESULT_REPORT); result_bott->Setresult(convertResult(result)); result_bott->Settime_used( intToString(stringToDouble(time_used) * 100 + 0.1)); result_bott->Setmemory_used(trim(memory_used)); result_bott->Setremote_runid(trim(runid)); break; } } return result_bott; } /** * Convert result text to local ones, keep consistency * @param result Original result * @return Converted local result */ string AizuJudger::convertResult(string result) { if (result.find("Time Limit Exceeded") != string::npos) return "Time Limit Exceed"; if (result.find("Memory Limit Exceeded") != string::npos) return "Memory Limit Exceed"; if (result.find("Output Limit Exceeded") != string::npos) return "Output Limit Exceed"; return trim(result); } /** * Get compile error info * @param bott Result bott file * @return Compile error info */ string AizuJudger::getCEinfo(Bott * bott) { prepareCurl(); curl_easy_setopt(curl, CURLOPT_URL, ((string) "http://judge.u-aizu.ac.jp/onlinejudge/compile_log.jsp?runID=" + bott->Getremote_runid()).c_str()); performCurl(); string info = loadAllFromFile(tmpfilename); string result; char * ce_info = new char[info.length() + 1]; strcpy(ce_info, info.c_str()); char * buffer = new char[info.length() * 2]; // SCU is in GBK charset charset_convert("SHIFT_JIS", "UTF-8//TRANSLIT", ce_info, info.length() + 1, buffer, info.length() * 2); if (!RE2::PartialMatch(buffer, "(?s)<p style=\"font-size:11pt;\">(.*)</p>", &result)) { return ""; } strcpy(buffer, result.c_str()); decode_html_entities_utf8(buffer, NULL); result = buffer; delete [] ce_info; delete [] buffer; return trim(result); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: pcd_viewer.cpp 35932 2011-02-10 03:55:03Z rusu $ * */ // PCL #include <boost/thread/thread.hpp> #include <Eigen/Geometry> #include <pcl/common/common.h> #include <pcl/io/pcd_io.h> #include <pcl/io/kinect_grabber.h> #include <cfloat> #include <pcl/visualization/point_cloud_handlers.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/visualization/histogram_visualizer.h> #include <pcl/terminal_tools/print.h> #include <pcl/terminal_tools/parse.h> #include <pcl/terminal_tools/time.h> using terminal_tools::print_color; using terminal_tools::print_error; using terminal_tools::print_error; using terminal_tools::print_warn; using terminal_tools::print_info; using terminal_tools::print_debug; using terminal_tools::print_value; using terminal_tools::print_highlight; using terminal_tools::TT_BRIGHT; using terminal_tools::TT_RED; using terminal_tools::TT_GREEN; using terminal_tools::TT_BLUE; typedef pcl_visualization::PointCloudColorHandler<pcl::PointCloud<pcl::PointXYZ> > ColorHandler; typedef ColorHandler::Ptr ColorHandlerPtr; typedef ColorHandler::ConstPtr ColorHandlerConstPtr; typedef pcl_visualization::PointCloudGeometryHandler<pcl::PointCloud<pcl::PointXYZ> > GeometryHandler; typedef GeometryHandler::Ptr GeometryHandlerPtr; typedef GeometryHandler::ConstPtr GeometryHandlerConstPtr; boost::mutex mutex_; #define NORMALS_SCALE 0.01 #define PC_SCALE 0.001 void printHelp (int argc, char **argv) { //print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]); print_error ("Syntax is: %s <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -dev device_id = device to be used\n"); print_info (" maybe \"#n\", with n being the number of the device in device list.\n"); print_info (" maybe \"bus@addr\", with bus and addr being the usb bus and address where device is connected.\n"); print_info (" maybe \"serial\", with serial being the serial number of the device.\n"); print_info (" -bc r,g,b = background color\n"); print_info (" -fc r,g,b = foreground color\n"); print_info (" -ps X = point size ("); print_value ("1..64"); print_info (") \n"); print_info (" -opaque X = rendered point cloud opacity ("); print_value ("0..1"); print_info (")\n"); print_info (" -ax "); print_value ("n"); print_info (" = enable on-screen display of "); print_color (stdout, TT_BRIGHT, TT_RED, "X"); print_color (stdout, TT_BRIGHT, TT_GREEN, "Y"); print_color (stdout, TT_BRIGHT, TT_BLUE, "Z"); print_info (" axes and scale them to "); print_value ("n\n"); print_info (" -ax_pos X,Y,Z = if axes are enabled, set their X,Y,Z position in space (default "); print_value ("0,0,0"); print_info (")\n"); print_info ("\n"); print_info (" -cam (*) = use given camera settings as initial view\n"); print_info (stderr, " (*) [Clipping Range / Focal Point / Position / ViewUp / Distance / Window Size / Window Pos] or use a <filename.cam> that contains the same information.\n"); print_info ("\n"); print_info (" -multiview 0/1 = enable/disable auto-multi viewport rendering (default "); print_value ("disabled"); print_info (")\n"); print_info ("\n"); print_info ("\n"); print_info (" -normals 0/X = disable/enable the display of every Xth point's surface normal as lines (default "); print_value ("disabled"); print_info (")\n"); print_info (" -normals_scale X = resize the normal unit vector size to X (default "); print_value ("0.02"); print_info (")\n"); print_info ("\n"); print_info (" -pc 0/X = disable/enable the display of every Xth point's principal curvatures as lines (default "); print_value ("disabled"); print_info (")\n"); print_info (" -pc_scale X = resize the principal curvatures vectors size to X (default "); print_value ("0.02"); print_info (")\n"); print_info ("\n"); print_info ("\n(Note: for multiple .pcd files, provide multiple -{fc,ps,opaque} parameters; they will be automatically assigned to the right file)\n"); } // Create the PCLVisualizer object boost::shared_ptr<pcl_visualization::PCLVisualizer> p; ColorHandlerPtr color_handler; GeometryHandlerPtr geometry_handler; std::vector<double> fcolor_r, fcolor_b, fcolor_g; bool fcolorparam = false; struct EventHelper { void cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud) { //std::cout << __PRETTY_FUNCTION__ << " " << cloud->width << std::endl; // Add the dataset with a XYZ and a random handler // geometry_handler.reset (new pcl_visualization::PointCloudGeometryHandlerXYZ<pcl::PointCloud<pcl::PointXYZRGB> > (*cloud)); //// If color was given, ues that //if (fcolorparam) // color_handler.reset (new pcl_visualization::PointCloudColorHandlerCustom<pcl::PointCloud<pcl::PointXYZRGB> > (cloud, fcolor_r, fcolor_g, fcolor_b)); //else // color_handler.reset (new pcl_visualization::PointCloudColorHandlerRandom<pcl::PointCloud<pcl::PointXYZRGB> > (cloud)); // Add the cloud to the renderer boost::mutex::scoped_lock lock(mutex_); if (!cloud) return; p->removePointCloud ("KinectCloud"); p->addPointCloud (*cloud, "KinectCloud"); } }; /* ---[ */ int main (int argc, char** argv) { srand (time (0)); if (argc > 1) { for (int i = 1; i < argc; i++) { if (std::string(argv[i]) == "-h") { printHelp (argc, argv); return (-1); } } } // Command line parsing double bcolor[3] = {0, 0, 0}; terminal_tools::parse_3x_arguments (argc, argv, "-bc", bcolor[0], bcolor[1], bcolor[2]); fcolorparam = terminal_tools::parse_multiple_3x_arguments (argc, argv, "-fc", fcolor_r, fcolor_g, fcolor_b); int psize = 0; terminal_tools::parse_argument (argc, argv, "-ps", psize); double opaque; terminal_tools::parse_argument (argc, argv, "-opaque", opaque); p.reset (new pcl_visualization::PCLVisualizer (argc, argv, "PCD viewer")); // // Change the cloud rendered point size // if (psize > 0) // p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_POINT_SIZE, psize, "KinectCloud"); // // // Change the cloud rendered opacity // if (opaque >= 0) // p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_OPACITY, opaque, "KinectCloud"); p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]); //boost::signals2::connection c = interface->registerCallback (boost::bind (&bla::blatestpointcloudrgb, *this, _1)); //boost::function<void (boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> f = boost::bind (&bla::blatestpointcloudrgb, this, _1); //boost::signals2::connection c = // interface->registerCallback <void(boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> (boost::bind (&bla::blatestpointcloudrgb, *this, _1).); // Read axes settings double axes = 0.0; terminal_tools::parse_argument (argc, argv, "-ax", axes); if (axes != 0.0 && p) { double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0; terminal_tools::parse_3x_arguments (argc, argv, "-ax_pos", ax_x, ax_y, ax_z, false); // Draw XYZ axes if command-line enabled p->addCoordinateSystem (axes, ax_x, ax_y, ax_z); } std::string device_id = ""; terminal_tools::parse_argument (argc, argv, "-dev", device_id); pcl::Grabber* interface = new pcl::OpenNIGrabber(device_id); EventHelper h; boost::function<void(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&)> f = boost::bind(&EventHelper::cloud_cb, &h, _1); boost::signals2::connection c1 = interface->registerCallback (f); interface->start (); while (true) { boost::this_thread::sleep(boost::posix_time::microseconds(10000)); { boost::mutex::scoped_lock lock(mutex_); p->spinOnce (); if (p->wasStopped ()) break; } } interface->stop (); } /* ]--- */ <commit_msg>non-blocking version of the viewer -> 30Hz reading, but less framerate displaying.<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: pcd_viewer.cpp 35932 2011-02-10 03:55:03Z rusu $ * */ // PCL #include <boost/thread/thread.hpp> #include <Eigen/Geometry> #include <pcl/common/common.h> #include <pcl/io/pcd_io.h> #include <pcl/io/kinect_grabber.h> #include <cfloat> #include <pcl/visualization/point_cloud_handlers.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/visualization/histogram_visualizer.h> #include <pcl/terminal_tools/print.h> #include <pcl/terminal_tools/parse.h> #include <pcl/terminal_tools/time.h> using terminal_tools::print_color; using terminal_tools::print_error; using terminal_tools::print_error; using terminal_tools::print_warn; using terminal_tools::print_info; using terminal_tools::print_debug; using terminal_tools::print_value; using terminal_tools::print_highlight; using terminal_tools::TT_BRIGHT; using terminal_tools::TT_RED; using terminal_tools::TT_GREEN; using terminal_tools::TT_BLUE; typedef pcl_visualization::PointCloudColorHandler<pcl::PointCloud<pcl::PointXYZ> > ColorHandler; typedef ColorHandler::Ptr ColorHandlerPtr; typedef ColorHandler::ConstPtr ColorHandlerConstPtr; typedef pcl_visualization::PointCloudGeometryHandler<pcl::PointCloud<pcl::PointXYZ> > GeometryHandler; typedef GeometryHandler::Ptr GeometryHandlerPtr; typedef GeometryHandler::ConstPtr GeometryHandlerConstPtr; boost::mutex mutex_; pcl::PointCloud<pcl::PointXYZ>::ConstPtr g_cloud; bool new_cloud = false; #define NORMALS_SCALE 0.01 #define PC_SCALE 0.001 void printHelp (int argc, char **argv) { //print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]); print_error ("Syntax is: %s <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -dev device_id = device to be used\n"); print_info (" maybe \"#n\", with n being the number of the device in device list.\n"); print_info (" maybe \"bus@addr\", with bus and addr being the usb bus and address where device is connected.\n"); print_info (" maybe \"serial\", with serial being the serial number of the device.\n"); print_info (" -bc r,g,b = background color\n"); print_info (" -fc r,g,b = foreground color\n"); print_info (" -ps X = point size ("); print_value ("1..64"); print_info (") \n"); print_info (" -opaque X = rendered point cloud opacity ("); print_value ("0..1"); print_info (")\n"); print_info (" -ax "); print_value ("n"); print_info (" = enable on-screen display of "); print_color (stdout, TT_BRIGHT, TT_RED, "X"); print_color (stdout, TT_BRIGHT, TT_GREEN, "Y"); print_color (stdout, TT_BRIGHT, TT_BLUE, "Z"); print_info (" axes and scale them to "); print_value ("n\n"); print_info (" -ax_pos X,Y,Z = if axes are enabled, set their X,Y,Z position in space (default "); print_value ("0,0,0"); print_info (")\n"); print_info ("\n"); print_info (" -cam (*) = use given camera settings as initial view\n"); print_info (stderr, " (*) [Clipping Range / Focal Point / Position / ViewUp / Distance / Window Size / Window Pos] or use a <filename.cam> that contains the same information.\n"); print_info ("\n"); print_info (" -multiview 0/1 = enable/disable auto-multi viewport rendering (default "); print_value ("disabled"); print_info (")\n"); print_info ("\n"); print_info ("\n"); print_info (" -normals 0/X = disable/enable the display of every Xth point's surface normal as lines (default "); print_value ("disabled"); print_info (")\n"); print_info (" -normals_scale X = resize the normal unit vector size to X (default "); print_value ("0.02"); print_info (")\n"); print_info ("\n"); print_info (" -pc 0/X = disable/enable the display of every Xth point's principal curvatures as lines (default "); print_value ("disabled"); print_info (")\n"); print_info (" -pc_scale X = resize the principal curvatures vectors size to X (default "); print_value ("0.02"); print_info (")\n"); print_info ("\n"); print_info ("\n(Note: for multiple .pcd files, provide multiple -{fc,ps,opaque} parameters; they will be automatically assigned to the right file)\n"); } // Create the PCLVisualizer object boost::shared_ptr<pcl_visualization::PCLVisualizer> p; ColorHandlerPtr color_handler; GeometryHandlerPtr geometry_handler; std::vector<double> fcolor_r, fcolor_b, fcolor_g; bool fcolorparam = false; struct EventHelper { void cloud_cb (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud) { if (mutex_.try_lock ()) { g_cloud = cloud; new_cloud = true; mutex_.unlock (); } } }; /* ---[ */ int main (int argc, char** argv) { srand (time (0)); if (argc > 1) { for (int i = 1; i < argc; i++) { if (std::string (argv[i]) == "-h") { printHelp (argc, argv); return (-1); } } } // Command line parsing double bcolor[3] = {0, 0, 0}; terminal_tools::parse_3x_arguments (argc, argv, "-bc", bcolor[0], bcolor[1], bcolor[2]); fcolorparam = terminal_tools::parse_multiple_3x_arguments (argc, argv, "-fc", fcolor_r, fcolor_g, fcolor_b); int psize = 0; terminal_tools::parse_argument (argc, argv, "-ps", psize); double opaque; terminal_tools::parse_argument (argc, argv, "-opaque", opaque); p.reset (new pcl_visualization::PCLVisualizer (argc, argv, "PCD viewer")); // // Change the cloud rendered point size // if (psize > 0) // p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_POINT_SIZE, psize, "KinectCloud"); // // // Change the cloud rendered opacity // if (opaque >= 0) // p->setPointCloudRenderingProperties (pcl_visualization::PCL_VISUALIZER_OPACITY, opaque, "KinectCloud"); p->setBackgroundColor (bcolor[0], bcolor[1], bcolor[2]); //boost::signals2::connection c = interface->registerCallback (boost::bind (&bla::blatestpointcloudrgb, *this, _1)); //boost::function<void (boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> f = boost::bind (&bla::blatestpointcloudrgb, this, _1); //boost::signals2::connection c = // interface->registerCallback <void(boost::shared_ptr<pcl::PointCloud<pcl::PointXYZRGB> >)> (boost::bind (&bla::blatestpointcloudrgb, *this, _1).); // Read axes settings double axes = 0.0; terminal_tools::parse_argument (argc, argv, "-ax", axes); if (axes != 0.0 && p) { double ax_x = 0.0, ax_y = 0.0, ax_z = 0.0; terminal_tools::parse_3x_arguments (argc, argv, "-ax_pos", ax_x, ax_y, ax_z, false); // Draw XYZ axes if command-line enabled p->addCoordinateSystem (axes, ax_x, ax_y, ax_z); } std::string device_id = ""; terminal_tools::parse_argument (argc, argv, "-dev", device_id); pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id); EventHelper h; boost::function<void(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1); boost::signals2::connection c1 = interface->registerCallback (f); interface->start (); while (!p->wasStopped ()) { p->spinOnce (); if (new_cloud && mutex_.try_lock ()) { new_cloud = false; if (g_cloud) { p->removePointCloud ("KinectCloud"); p->addPointCloud (*g_cloud, "KinectCloud"); } mutex_.unlock (); } else usleep (1000); } interface->stop (); } /* ]--- */ <|endoftext|>
<commit_before> #include "boost/asio.hpp" #include "vtrc-common/vtrc-mutex-typedefs.h" #include "vtrc-bind.h" #include "vtrc-function.h" #include "vtrc-protocol-layer-s.h" #include "vtrc-monotonic-timer.h" #include "vtrc-data-queue.h" #include "vtrc-hash-iface.h" #include "vtrc-transformer-iface.h" #include "vtrc-transport-iface.h" #include "vtrc-common/vtrc-rpc-service-wrapper.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-common/vtrc-rpc-controller.h" #include "vtrc-common/vtrc-call-context.h" #include "vtrc-application.h" #include "protocol/vtrc-errors.pb.h" #include "protocol/vtrc-auth.pb.h" #include "protocol/vtrc-rpc-lowlevel.pb.h" #include "vtrc-chrono.h" #include "vtrc-atomic.h" #include "vtrc-common/vtrc-random-device.h" #include "vtrc-common/vtrc-delayed-call.h" namespace vtrc { namespace server { namespace gpb = google::protobuf; namespace bsys = boost::system; namespace basio = boost::asio; namespace { enum init_stage_enum { stage_begin = 1 ,stage_client_select = 2 ,stage_client_ready = 3 }; typedef std::map < std::string, common::rpc_service_wrapper_sptr > service_map; typedef vtrc_rpc::lowlevel_unit lowlevel_unit_type; typedef vtrc::shared_ptr<lowlevel_unit_type> lowlevel_unit_sptr; } namespace data_queue = common::data_queue; struct protocol_layer_s::impl { typedef impl this_type; typedef protocol_layer_s parent_type; application &app_; common::transport_iface *connection_; protocol_layer_s *parent_; bool ready_; service_map services_; shared_mutex services_lock_; std::string client_id_; common::delayed_call keepalive_calls_; typedef vtrc::function<void (void)> stage_function_type; stage_function_type stage_function_; vtrc::atomic<unsigned> current_calls_; const unsigned maximum_calls_; impl( application &a, common::transport_iface *c, unsigned maximum_calls) :app_(a) ,connection_(c) ,ready_(false) ,current_calls_(0) ,maximum_calls_(maximum_calls) ,keepalive_calls_(a.get_io_service( )) { stage_function_ = vtrc::bind( &this_type::on_client_selection, this ); /// client has only 10 seconds for init connection /// todo: think about setting for this timeout value keepalive_calls_.call_from_now( vtrc::bind( &this_type::on_init_timeout, this, _1 ), boost::posix_time::seconds( 10 )); } common::rpc_service_wrapper_sptr get_service( const std::string &name ) { upgradable_lock lk( services_lock_ ); common::rpc_service_wrapper_sptr result; service_map::iterator f( services_.find( name ) ); if( f != services_.end( ) ) { result = f->second; } else { result = app_.get_service_by_name( connection_, name ); if( result ) { upgrade_to_unique ulk( lk ); services_.insert( std::make_pair( name, result ) ); } } return result; } const std::string &client_id( ) const { return client_id_; } void on_init_timeout( const boost::system::error_code &error ) { if( !error ) { /// timeout for client init vtrc_auth::init_capsule cap; cap.mutable_error( )->set_code( vtrc_errors::ERR_TIMEOUT ); cap.set_ready( false ); send_and_close( cap ); } } void send_proto_message( const gpb::MessageLite &mess ) { std::string s(mess.SerializeAsString( )); connection_->write( s.c_str( ), s.size( ) ); } void send_proto_message( const gpb::MessageLite &mess, common::system_closure_type closure, bool on_send) { std::string s(mess.SerializeAsString( )); connection_->write( s.c_str( ), s.size( ), closure, on_send ); } void send_and_close( const gpb::MessageLite &mess ) { send_proto_message( mess, vtrc::bind( &this_type::close_client, this, _1, connection_->shared_from_this( )), true ); } void set_client_ready( ) { keepalive_calls_.cancel( ); stage_function_ = vtrc::bind( &this_type::on_rcp_call_ready, this ); parent_->set_ready( true ); } void close_client( const bsys::error_code & /*err*/, common::connection_iface_sptr /*inst*/) { connection_->close( ); } void on_client_transformer( ) { using namespace common::transformers; vtrc_auth::init_capsule capsule; bool check = get_pop_message( capsule ); if( !check ) { capsule.Clear( ); capsule.mutable_error( )->set_code( vtrc_errors::ERR_INTERNAL ); send_and_close( capsule ); return; } if( !capsule.ready( ) ) { connection_->close( ); return; } vtrc_auth::transformer_setup tsetup; tsetup.ParseFromString( capsule.body( ) ); std::string key(app_.get_session_key( connection_, client_id_ )); create_key( key, // input tsetup.salt1( ), // input tsetup.salt2( ), // input key ); // output common::transformer_iface *new_transformer = erseefor::create( key.c_str( ), key.size( ) ); // client revertor is my transformer parent_->change_transformer( new_transformer ); capsule.Clear( ); capsule.set_ready( true ); capsule.set_text( "Kiva nahda sinut!" ); set_client_ready( ); send_proto_message( capsule ); } void setup_transformer( unsigned id ) { using namespace common::transformers; vtrc_auth::transformer_setup ts; vtrc_auth::init_capsule capsule; if( id == vtrc_auth::TRANSFORM_NONE ) { capsule.set_ready( true ); capsule.set_text( "Kiva nahda sinut!" ); set_client_ready( ); send_proto_message( capsule ); } else if( id == vtrc_auth::TRANSFORM_ERSEEFOR ) { std::string key(app_.get_session_key(connection_, client_id_)); generate_key_infos( key, // input *ts.mutable_salt1( ), // output *ts.mutable_salt2( ), // output key ); // output common::transformer_iface *new_reverter = erseefor::create( key.c_str( ), key.size( ) ); // client transformer is my revertor parent_->change_revertor( new_reverter ); capsule.set_ready( true ); capsule.set_body( ts.SerializeAsString( ) ); stage_function_ = vtrc::bind( &this_type::on_client_transformer, this ); send_proto_message( capsule ); } else { capsule.set_ready( false ); vtrc_errors::container *er(capsule.mutable_error( )); er->set_code( vtrc_errors::ERR_INVALID_VALUE ); er->set_category(vtrc_errors::CATEGORY_INTERNAL); er->set_additional( "Invalid transformer" ); send_and_close( capsule ); return; } } void on_client_selection( ) { vtrc_auth::init_capsule capsule; bool check = get_pop_message( capsule ); if( !check ) { connection_->close( ); return; } if( !capsule.ready( ) ) { connection_->close( ); return; } vtrc_auth::client_selection cs; cs.ParseFromString( capsule.body( ) ); common::hash_iface *new_checker( common::hash::create_by_index( cs.hash( ) ) ); common::hash_iface *new_maker( common::hash::create_by_index( cs.hash( ) ) ); if( !new_maker ) { delete new_checker; } if( !new_maker || !new_checker ) { connection_->close( ); return; } client_id_.assign( cs.id( ) ); parent_->change_hash_checker( new_checker ); parent_->change_hash_maker( new_maker ); setup_transformer( cs.transform( ) ); } bool get_pop_message( gpb::MessageLite &capsule ) { bool check = parent_->parse_and_pop( capsule ); if( !check ) { connection_->close( ); } return check; } void call_done( const vtrc_errors::container & /*err*/ ) { --current_calls_; } void push_call( lowlevel_unit_sptr llu, common::connection_iface_sptr /*conn*/ ) { parent_->make_local_call( llu, vtrc::bind(&this_type::call_done, this, _1 )); } void send_busy( lowlevel_unit_type &llu ) { if( llu.opt( ).wait( ) ) { llu.clear_call( ); llu.clear_request( ); llu.clear_response( ); llu.mutable_error( )->set_code( vtrc_errors::ERR_BUSY ); parent_->call_rpc_method( llu ); } } void process_call( lowlevel_unit_sptr &llu ) { if( ++current_calls_ <= maximum_calls_ ) { app_.get_rpc_service( ).post( vtrc::bind( &this_type::push_call, this, llu, connection_->shared_from_this( ))); } else { --current_calls_; send_busy( *llu ); } } void push_event_answer( lowlevel_unit_sptr llu, common::connection_iface_sptr /*conn*/ ) { parent_->push_rpc_message( llu->id( ), llu ); } void process_event_cb( lowlevel_unit_sptr &llu ) { parent_->push_rpc_message( llu->id( ), llu ); } void on_rcp_call_ready( ) { typedef vtrc_rpc::message_info message_info; while( !parent_->message_queue_empty( ) ) { lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>()); if(!get_pop_message( *llu )) { return; } if( llu->has_info( ) ) { switch (llu->info( ).message_type( )) { case message_info::MESSAGE_CALL: process_call( llu ); break; case message_info::MESSAGE_EVENT: case message_info::MESSAGE_CALLBACK: case message_info::MESSAGE_INSERTION_CALL: process_event_cb( llu ); break; default: break; } } } } std::string first_message( ) { vtrc_auth::init_capsule cap; vtrc_auth::init_protocol hello_mess; cap.set_text( "Tervetuloa!" ); cap.set_ready( true ); hello_mess.add_hash_supported( vtrc_auth::HASH_NONE ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_16 ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_32 ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_64 ); hello_mess.add_hash_supported( vtrc_auth::HASH_SHA2_256 ); hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_NONE ); hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_ERSEEFOR ); cap.set_body( hello_mess.SerializeAsString( ) ); return cap.SerializeAsString( ); } void init( ) { static const std::string data(first_message( )); connection_->write(data.c_str( ), data.size( )); } void data_ready( ) { stage_function_( ); } }; protocol_layer_s::protocol_layer_s( application &a, common::transport_iface *connection, unsigned maximym_calls, size_t mess_len) :common::protocol_layer(connection, false, mess_len) ,impl_(new impl(a, connection, maximym_calls)) { impl_->parent_ = this; } protocol_layer_s::~protocol_layer_s( ) { delete impl_; } void protocol_layer_s::init( ) { impl_->init( ); } void protocol_layer_s::close( ) { } const std::string &protocol_layer_s::client_id( ) const { return impl_->client_id( ); } void protocol_layer_s::on_data_ready( ) { impl_->data_ready( ); } common::rpc_service_wrapper_sptr protocol_layer_s::get_service_by_name( const std::string &name) { return impl_->get_service(name); } }} <commit_msg>proto<commit_after> #include "boost/asio.hpp" #include "vtrc-common/vtrc-mutex-typedefs.h" #include "vtrc-bind.h" #include "vtrc-function.h" #include "vtrc-protocol-layer-s.h" #include "vtrc-monotonic-timer.h" #include "vtrc-data-queue.h" #include "vtrc-hash-iface.h" #include "vtrc-transformer-iface.h" #include "vtrc-transport-iface.h" #include "vtrc-common/vtrc-rpc-service-wrapper.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-common/vtrc-rpc-controller.h" #include "vtrc-common/vtrc-call-context.h" #include "vtrc-application.h" #include "protocol/vtrc-errors.pb.h" #include "protocol/vtrc-auth.pb.h" #include "protocol/vtrc-rpc-lowlevel.pb.h" #include "vtrc-chrono.h" #include "vtrc-atomic.h" #include "vtrc-common/vtrc-random-device.h" #include "vtrc-common/vtrc-delayed-call.h" namespace vtrc { namespace server { namespace gpb = google::protobuf; namespace bsys = boost::system; namespace basio = boost::asio; namespace { enum init_stage_enum { stage_begin = 1 ,stage_client_select = 2 ,stage_client_ready = 3 }; typedef std::map < std::string, common::rpc_service_wrapper_sptr > service_map; typedef vtrc_rpc::lowlevel_unit lowlevel_unit_type; typedef vtrc::shared_ptr<lowlevel_unit_type> lowlevel_unit_sptr; } namespace data_queue = common::data_queue; struct protocol_layer_s::impl { typedef impl this_type; typedef protocol_layer_s parent_type; application &app_; common::transport_iface *connection_; protocol_layer_s *parent_; bool ready_; service_map services_; shared_mutex services_lock_; std::string client_id_; common::delayed_call keepalive_calls_; typedef vtrc::function<void (void)> stage_function_type; stage_function_type stage_function_; vtrc::atomic<unsigned> current_calls_; const unsigned maximum_calls_; impl( application &a, common::transport_iface *c, unsigned maximum_calls) :app_(a) ,connection_(c) ,ready_(false) ,current_calls_(0) ,maximum_calls_(maximum_calls) ,keepalive_calls_(a.get_io_service( )) { stage_function_ = vtrc::bind( &this_type::on_client_selection, this ); /// client has only 10 seconds for init connection /// todo: think about setting for this timeout value keepalive_calls_.call_from_now( vtrc::bind( &this_type::on_init_timeout, this, _1 ), boost::posix_time::seconds( 10 )); } common::rpc_service_wrapper_sptr get_service( const std::string &name ) { upgradable_lock lk( services_lock_ ); common::rpc_service_wrapper_sptr result; service_map::iterator f( services_.find( name ) ); if( f != services_.end( ) ) { result = f->second; } else { result = app_.get_service_by_name( connection_, name ); if( result ) { upgrade_to_unique ulk( lk ); services_.insert( std::make_pair( name, result ) ); } } return result; } const std::string &client_id( ) const { return client_id_; } void on_init_timeout( const boost::system::error_code &error ) { if( !error ) { /// timeout for client init vtrc_auth::init_capsule cap; cap.mutable_error( )->set_code( vtrc_errors::ERR_TIMEOUT ); cap.set_ready( false ); send_and_close( cap ); } } void send_proto_message( const gpb::MessageLite &mess ) { std::string s(mess.SerializeAsString( )); connection_->write( s.c_str( ), s.size( ) ); } void send_proto_message( const gpb::MessageLite &mess, common::system_closure_type closure, bool on_send) { std::string s(mess.SerializeAsString( )); connection_->write( s.c_str( ), s.size( ), closure, on_send ); } void send_and_close( const gpb::MessageLite &mess ) { send_proto_message( mess, vtrc::bind( &this_type::close_client, this, _1, connection_->shared_from_this( )), true ); } void set_client_ready( ) { keepalive_calls_.cancel( ); stage_function_ = vtrc::bind( &this_type::on_rcp_call_ready, this ); parent_->set_ready( true ); } void close_client( const bsys::error_code & /*err*/, common::connection_iface_sptr /*inst*/) { connection_->close( ); } void on_client_transformer( ) { using namespace common::transformers; vtrc_auth::init_capsule capsule; bool check = get_pop_message( capsule ); if( !check ) { capsule.Clear( ); capsule.mutable_error( )->set_code( vtrc_errors::ERR_INTERNAL ); send_and_close( capsule ); return; } if( !capsule.ready( ) ) { connection_->close( ); return; } vtrc_auth::transformer_setup tsetup; tsetup.ParseFromString( capsule.body( ) ); std::string key(app_.get_session_key( connection_, client_id_ )); create_key( key, // input tsetup.salt1( ), // input tsetup.salt2( ), // input key ); // output common::transformer_iface *new_transformer = erseefor::create( key.c_str( ), key.size( ) ); // client revertor is my transformer parent_->change_transformer( new_transformer ); capsule.Clear( ); capsule.set_ready( true ); capsule.set_text( "Kiva nahda sinut!" ); set_client_ready( ); send_proto_message( capsule ); } void setup_transformer( unsigned id ) { using namespace common::transformers; vtrc_auth::transformer_setup ts; vtrc_auth::init_capsule capsule; if( id == vtrc_auth::TRANSFORM_NONE ) { capsule.set_ready( true ); capsule.set_text( "Kiva nahda sinut!" ); set_client_ready( ); send_proto_message( capsule ); } else if( id == vtrc_auth::TRANSFORM_ERSEEFOR ) { std::string key(app_.get_session_key(connection_, client_id_)); generate_key_infos( key, // input *ts.mutable_salt1( ), // output *ts.mutable_salt2( ), // output key ); // output common::transformer_iface *new_reverter = erseefor::create( key.c_str( ), key.size( ) ); // client transformer is my revertor parent_->change_revertor( new_reverter ); capsule.set_ready( true ); capsule.set_body( ts.SerializeAsString( ) ); stage_function_ = vtrc::bind( &this_type::on_client_transformer, this ); send_proto_message( capsule ); } else { capsule.set_ready( false ); vtrc_errors::container *er(capsule.mutable_error( )); er->set_code( vtrc_errors::ERR_INVALID_VALUE ); er->set_category(vtrc_errors::CATEGORY_INTERNAL); er->set_additional( "Invalid transformer" ); send_and_close( capsule ); return; } } void on_client_selection( ) { vtrc_auth::init_capsule capsule; bool check = get_pop_message( capsule ); if( !check ) { connection_->close( ); return; } if( !capsule.ready( ) ) { connection_->close( ); return; } vtrc_auth::client_selection cs; cs.ParseFromString( capsule.body( ) ); common::hash_iface *new_checker( common::hash::create_by_index( cs.hash( ) ) ); common::hash_iface *new_maker( common::hash::create_by_index( cs.hash( ) ) ); if( !new_maker ) { delete new_checker; } if( !new_maker || !new_checker ) { connection_->close( ); return; } client_id_.assign( cs.id( ) ); parent_->change_hash_checker( new_checker ); parent_->change_hash_maker( new_maker ); setup_transformer( cs.transform( ) ); } bool get_pop_message( gpb::MessageLite &capsule ) { bool check = parent_->parse_and_pop( capsule ); if( !check ) { connection_->close( ); } return check; } void call_done( const vtrc_errors::container & /*err*/ ) { --current_calls_; } void push_call( lowlevel_unit_sptr llu, common::connection_iface_sptr /*conn*/ ) { parent_->make_local_call( llu, vtrc::bind(&this_type::call_done, this, _1 )); } void send_busy( lowlevel_unit_type &llu ) { if( llu.opt( ).wait( ) ) { llu.clear_call( ); llu.clear_request( ); llu.clear_response( ); llu.mutable_error( )->set_code( vtrc_errors::ERR_BUSY ); parent_->call_rpc_method( llu ); } } void process_call( lowlevel_unit_sptr &llu ) { if( ++current_calls_ <= maximum_calls_ ) { app_.get_rpc_service( ).post( vtrc::bind( &this_type::push_call, this, llu, connection_->shared_from_this( ))); } else { send_busy( *llu ); --current_calls_; } } void push_event_answer( lowlevel_unit_sptr llu, common::connection_iface_sptr /*conn*/ ) { parent_->push_rpc_message( llu->id( ), llu ); } void process_event_cb( lowlevel_unit_sptr &llu ) { parent_->push_rpc_message( llu->id( ), llu ); } void on_rcp_call_ready( ) { typedef vtrc_rpc::message_info message_info; while( !parent_->message_queue_empty( ) ) { lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>()); if(!get_pop_message( *llu )) { return; } if( llu->has_info( ) ) { switch (llu->info( ).message_type( )) { case message_info::MESSAGE_CALL: process_call( llu ); break; case message_info::MESSAGE_EVENT: case message_info::MESSAGE_CALLBACK: case message_info::MESSAGE_INSERTION_CALL: process_event_cb( llu ); break; default: break; } } } } std::string first_message( ) { vtrc_auth::init_capsule cap; vtrc_auth::init_protocol hello_mess; cap.set_text( "Tervetuloa!" ); cap.set_ready( true ); hello_mess.add_hash_supported( vtrc_auth::HASH_NONE ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_16 ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_32 ); hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_64 ); hello_mess.add_hash_supported( vtrc_auth::HASH_SHA2_256 ); hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_NONE ); hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_ERSEEFOR ); cap.set_body( hello_mess.SerializeAsString( ) ); return cap.SerializeAsString( ); } void init( ) { static const std::string data(first_message( )); connection_->write(data.c_str( ), data.size( )); } void data_ready( ) { stage_function_( ); } }; protocol_layer_s::protocol_layer_s( application &a, common::transport_iface *connection, unsigned maximym_calls, size_t mess_len) :common::protocol_layer(connection, false, mess_len) ,impl_(new impl(a, connection, maximym_calls)) { impl_->parent_ = this; } protocol_layer_s::~protocol_layer_s( ) { delete impl_; } void protocol_layer_s::init( ) { impl_->init( ); } void protocol_layer_s::close( ) { } const std::string &protocol_layer_s::client_id( ) const { return impl_->client_id( ); } void protocol_layer_s::on_data_ready( ) { impl_->data_ready( ); } common::rpc_service_wrapper_sptr protocol_layer_s::get_service_by_name( const std::string &name) { return impl_->get_service(name); } }} <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #define N 3 #define MAX 0x200 struct TAlumno { char nombre_completo[MAX]; double programacion; double bases_de_datos; }; int main(int argc, char *argv[]){ struct TAlumno clase[N]; /* Pedir los datos */ for (int i=0; i<N; i++){ printf("Nombre completo: "); gets( clase[i].nombre_completo ); printf("Nota de Programación: "); scanf(" %lf", &clase[i].programacion ); printf("Nota de Bases de Datos: "); scanf(" %lf", &clase[i].bases_de_datos ); } /* Imprimir los datos */ for (int i=0; i<N; i++){ printf("Nombre completo: %s\n", clase[i].nombre_completo ); printf("Nota de Programación: %.2lf\n", clase[i].programacion ); printf("Nota de Bases de Datos: %.2lf\n", clase[i].bases_de_datos ); } return EXIT_SUCCESS; } <commit_msg>title with structs<commit_after>#include <stdio.h> #include <stdlib.h> #define N 3 #define MAX 0x200 struct TContenidos { double programacion; double bases_de_datos; } struct TAlumno { char nombre_completo[MAX]; struct TContenidos asignaturas; }; int main(int argc, char *argv[]){ struct TAlumno clase[N]; /* Pedir los datos */ for (int i=0; i<N; i++){ printf("Nombre completo: "); gets( clase[i].nombre_completo ); printf("Nota de Programación: "); scanf(" %lf", &clase[i].asignaturas.programacion ); printf("Nota de Bases de Datos: "); scanf(" %lf", &clase[i].asignaturas.bases_de_datos ); } /* Imprimir los datos */ for (int i=0; i<N; i++){ printf("Nombre completo: %s\n", clase[i].nombre_completo ); printf("Nota de Programación: %.2lf\n", clase[i].asignaturas.programacion ); printf("Nota de Bases de Datos: %.2lf\n", clase[i].asignaturas.bases_de_datos ); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Add ICU platform to aerial_v4.<commit_after><|endoftext|>
<commit_before><commit_msg>Create 1180 - Lowest Number and Position.cpp<commit_after><|endoftext|>
<commit_before><commit_msg>DBG: added corner traj info<commit_after><|endoftext|>
<commit_before>#include "Capture.h" #include "Compute.h" #include "ImageLogger.h" #include "Timer.h" #include "Motor.h" #include "Radio.h" #include "Navio/Util.h" #include <iostream> #include <limits.h> #include <signal.h> #include <stdlib.h> #include <time.h> static volatile bool quit = false; static void Quit(int) { quit = true; } static const int refreshRate = 30; int main(int /*argc*/, char** /*argv*/) { if (! check_apm()) { system("sudo modprobe bcm2835-v4l2"); Capture cap(0); ImageLogger log; Compute compute(&cap, &log); cap.Start(); log.Start(); compute.Start(); Motor motor; Radio rc; Timer timer; float steer = 0; signal(SIGHUP, Quit); signal(SIGINT, Quit); timer.Start(); while (! quit) { OutputData data; compute.SwapOutputData(data); float throttle = rc.ReadThrottle(); float leftMotor, rightMotor; if (data.direction == GoBack) { if (steer > 0.) { leftMotor = -throttle; rightMotor = throttle; } else { rightMotor = -throttle; leftMotor = throttle; } } else { if (data.direction == GoStraight) { leftMotor = throttle; rightMotor = throttle; } else { steer = (M_PI_2 - atan2(data.hiY - data.loY, data.hiX - data.loX)) / 10.; std::cerr << "steer = " << steer << std::endl; leftMotor = steer > 0. ? (1. - steer) * throttle : throttle; rightMotor = steer < 0. ? (1. + steer) * throttle : throttle; } } motor.SetLeftMotor (leftMotor); motor.SetRightMotor(rightMotor); struct timespec sleep = {0, 1000 * timer.NextSleep(refreshRate, INT_MAX)}; nanosleep(&sleep, NULL); } motor.SetLeftMotor (0.); motor.SetRightMotor(0.); cap.Stop(); compute.Stop(); log.Stop(); } return 0; } <commit_msg>steering gain<commit_after>#include "Capture.h" #include "Compute.h" #include "ImageLogger.h" #include "Timer.h" #include "Motor.h" #include "Radio.h" #include "Navio/Util.h" #include <iostream> #include <limits.h> #include <signal.h> #include <stdlib.h> #include <time.h> static volatile bool quit = false; static void Quit(int) { quit = true; } static const int refreshRate = 30; int main(int /*argc*/, char** /*argv*/) { if (! check_apm()) { system("sudo modprobe bcm2835-v4l2"); Capture cap(0); ImageLogger log; Compute compute(&cap, &log); cap.Start(); log.Start(); compute.Start(); Motor motor; Radio rc; Timer timer; float steer = 0; signal(SIGHUP, Quit); signal(SIGINT, Quit); timer.Start(); while (! quit) { OutputData data; compute.SwapOutputData(data); float throttle = rc.ReadThrottle(); float leftMotor, rightMotor; if (data.direction == GoBack) { if (steer > 0.) { leftMotor = -throttle; rightMotor = throttle; } else { rightMotor = -throttle; leftMotor = throttle; } } else { if (data.direction == GoStraight) { leftMotor = throttle; rightMotor = throttle; } else { steer = 18. * (M_PI_2 - atan2(data.hiY - data.loY, data.hiX - data.loX)); //std::cerr << "steer = " << steer << std::endl; leftMotor = steer > 0. ? (1. - std::min( 1.F,steer)) * throttle : throttle; rightMotor = steer < 0. ? (1. + std::max(-1.F,steer)) * throttle : throttle; } } motor.SetLeftMotor (leftMotor); motor.SetRightMotor(rightMotor); struct timespec sleep = {0, 1000 * timer.NextSleep(refreshRate, INT_MAX)}; nanosleep(&sleep, NULL); } motor.SetLeftMotor (0.); motor.SetRightMotor(0.); cap.Stop(); compute.Stop(); log.Stop(); } return 0; } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef APPLY_HH_ #define APPLY_HH_ #include <tuple> #include <utility> template <typename Func, typename Args, typename IndexList> struct apply_helper; template <typename Func, typename Tuple, size_t... I> struct apply_helper<Func, Tuple, std::index_sequence<I...>> { static auto apply(Func func, Tuple args) { return func(std::get<I>(std::forward<Tuple>(args))...); } }; template <typename Func, typename... T> inline auto apply(Func func, std::tuple<T...>&& args) { using helper = apply_helper<Func, std::tuple<T...>&&, std::index_sequence_for<T...>>; return helper::apply(std::move(func), std::move(args)); } template <typename Func, typename... T> inline auto apply(Func func, std::tuple<T...>& args) { using helper = apply_helper<Func, std::tuple<T...>&, std::index_sequence_for<T...>>; return helper::apply(std::move(func), args); } template <typename Func, typename... T> inline auto apply(Func func, const std::tuple<T...>& args) { using helper = apply_helper<Func, const std::tuple<T...>&, std::index_sequence_for<T...>>; return helper::apply(std::move(func), args); } #endif /* APPLY_HH_ */ <commit_msg>core: use perfect forwarding for function object in apply()<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef APPLY_HH_ #define APPLY_HH_ #include <tuple> #include <utility> template <typename Func, typename Args, typename IndexList> struct apply_helper; template <typename Func, typename Tuple, size_t... I> struct apply_helper<Func, Tuple, std::index_sequence<I...>> { static auto apply(Func&& func, Tuple args) { return func(std::get<I>(std::forward<Tuple>(args))...); } }; template <typename Func, typename... T> inline auto apply(Func&& func, std::tuple<T...>&& args) { using helper = apply_helper<Func, std::tuple<T...>&&, std::index_sequence_for<T...>>; return helper::apply(std::forward<Func>(func), std::move(args)); } template <typename Func, typename... T> inline auto apply(Func&& func, std::tuple<T...>& args) { using helper = apply_helper<Func, std::tuple<T...>&, std::index_sequence_for<T...>>; return helper::apply(std::forward<Func>(func), args); } template <typename Func, typename... T> inline auto apply(Func&& func, const std::tuple<T...>& args) { using helper = apply_helper<Func, const std::tuple<T...>&, std::index_sequence_for<T...>>; return helper::apply(std::forward<Func>(func), args); } #endif /* APPLY_HH_ */ <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef APPLY_HH_ #define APPLY_HH_ #include <tuple> template <size_t... I> struct index_list { }; template <size_t Cur, size_t N, typename Result> struct index_list_helper; template <size_t N, size_t... I> struct index_list_helper<N, N, index_list<I...>> { using type = index_list<I...>; }; template <size_t Cur, size_t N, size_t... I> struct index_list_helper<Cur, N, index_list<I...>> { using type = typename index_list_helper<Cur + 1, N, index_list<I..., Cur>>::type; }; template <size_t N> using make_index_list = typename index_list_helper<0, N, index_list<>>::type; template <typename Func, typename Args, typename IndexList> struct apply_helper; template <typename Func, typename... T, size_t... I> struct apply_helper<Func, std::tuple<T...>, index_list<I...>> { static auto apply(Func func, std::tuple<T...> args) { return func(std::get<I>(std::move(args))...); } }; template <typename Func, typename... T> auto apply(Func func, std::tuple<T...>&& args) { using helper = apply_helper<Func, std::tuple<T...>, make_index_list<sizeof...(T)>>; return helper::apply(std::move(func), std::move(args)); } #endif /* APPLY_HH_ */ <commit_msg>replace ad-hoc index list generator with standard one<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef APPLY_HH_ #define APPLY_HH_ #include <tuple> #include <utility> template <typename Func, typename Args, typename IndexList> struct apply_helper; template <typename Func, typename... T, size_t... I> struct apply_helper<Func, std::tuple<T...>, std::index_sequence<I...>> { static auto apply(Func func, std::tuple<T...> args) { return func(std::get<I>(std::move(args))...); } }; template <typename Func, typename... T> auto apply(Func func, std::tuple<T...>&& args) { using helper = apply_helper<Func, std::tuple<T...>, std::index_sequence_for<T...>>; return helper::apply(std::move(func), std::move(args)); } #endif /* APPLY_HH_ */ <|endoftext|>
<commit_before>#include "util.h" #include <iostream> #include <iomanip> #include <stdlib.h> using namespace std; const char* kpcSampleDatabase = "mysql_cpp_data"; void print_stock_table(mysqlpp::Query& query) { // You must reset the query object when re-using it. query.reset(); // You can write to the query object like you would any ostream. query << "select * from stock"; // Show the query string. If you do this, you have to do it before // you execute() or store() or use() it. cout << "Query: " << query.preview() << endl; // Execute the query and save the results. mysqlpp::Result res = query.store(); cout << "Records Found: " << res.size() << endl << endl; // Display a header for the stock table cout.setf(ios::left); cout << setw(21) << "Item" << setw(10) << "Num" << setw(10) << "Weight" << setw(10) << "Price" << "Date" << endl << endl; // Use the Result class's read-only random access iterator to walk // through the query results. mysqlpp::Row row; mysqlpp::Result::iterator i; for (i = res.begin(); i != res.end(); ++i) { row = *i; // Note that you can use either the column index or name to // retrieve the data. cout << setw(20) << row[0].c_str() << ' ' << setw(9) << row[1].c_str() << ' ' << setw(9) << row.lookup_by_name("weight").c_str() << ' ' << setw(9) << row[3].c_str() << ' ' << row[4] << endl; } } bool connect_to_db(int argc, char *argv[], mysqlpp::Connection& con, const char *kdb) { if (argc < 1) { cerr << "Bad argument count: " << argc << '!' << endl; return false; } if ((argc > 1) && (argv[1][0] == '-')) { cout << "usage: " << argv[0] << " [host] [user] [password] [port]" << endl; cout << endl << "\tConnects to database "; if (kdb) { cout << '"' << kdb << '"'; } else { cout << "server"; } cout << " on localhost using your user" << endl; cout << "\tname and no password by default." << endl << endl; return false; } if (!kdb) { kdb = kpcSampleDatabase; } bool success = false; if (argc == 1) { success = con.connect(kdb); } else if (argc == 2) { success = con.connect(kdb, argv[1]); } else if (argc == 3) { success = con.connect(kdb, argv[1], argv[2]); } else if (argc == 4) { success = con.connect(kdb, argv[1], argv[2], argv[3]); } else if (argc >= 5) { success = con.real_connect(kdb, argv[1], argv[2], argv[3], atoi(argv[4])); } if (!success) { cerr << "Database connection failed." << endl << endl; } return success; } <commit_msg>Added optional iconv() support, for Win32 UTF-8 to UCS-2LE conversion.<commit_after>#include "util.h" #include <iostream> #include <iomanip> #include <stdlib.h> using namespace std; // Uncomment this macro if you want the 'item' strings to be converted // from UTF-8 to UCS-2LE (i.e. Win32's native Unicode encoding) using // the iconv library. This is not necessary on modern Unices, because // they handle UTF-8 directly. //#define USE_ICONV_UCS2 #ifdef USE_ICONV_UCS2 # include <iconv.h> #endif const char* kpcSampleDatabase = "mysql_cpp_data"; void print_stock_table(mysqlpp::Query& query) { // You must reset the query object when re-using it. query.reset(); // You can write to the query object like you would any ostream. query << "select * from stock"; // Show the query string. If you do this, you have to do it before // you execute() or store() or use() it. cout << "Query: " << query.preview() << endl; // Execute the query and save the results. mysqlpp::Result res = query.store(); cout << "Records Found: " << res.size() << endl << endl; // Display a header for the stock table cout.setf(ios::left); cout << setw(21) << "Item" << setw(10) << "Num" << setw(10) << "Weight" << setw(10) << "Price" << "Date" << endl << endl; #ifdef USE_ICONV_UCS2 iconv_t ich = iconv_open("UCS-2LE", "UTF-8"); if (int(ich) == -1) { cerr << "iconv doesn't support the necessary character sets!" << endl; return; } #endif // Use the Result class's read-only random access iterator to walk // through the query results. mysqlpp::Row row; mysqlpp::Result::iterator i; for (i = res.begin(); i != res.end(); ++i) { row = *i; // Output first column, the item string. The ICONV option // shows just one way to convert the UTF-8 data returned by // MySQL to little-endian UCS-2 characters. One might be able // to convince the Win32 API function MultiByteToWideChar to do // this, but I couldn't make it work. #ifdef USE_ICONV_UCS2 wchar_t wideItem[100]; char* wideItemPtr = (char*)wideItem; size_t in_bytes = row[0].length() + 1; size_t out_bytes = sizeof(wideItem); const char* narrowItem = row[0].c_str(); iconv(ich, &narrowItem, &in_bytes, &wideItemPtr, &out_bytes); wcout.setf(ios::left); wcout << setw(20) << wstring(wideItem) << ' '; #else cout << setw(20) << row[0].c_str() << ' '; #endif // Note that you can use either the column index or name to // retrieve the data. cout << setw(9) << row[1].c_str() << ' ' << setw(9) << row.lookup_by_name("weight").c_str() << ' ' << setw(9) << row[3].c_str() << ' ' << row[4] << endl; } #ifdef USE_ICONV_UCS2 iconv_close(ich); #endif } bool connect_to_db(int argc, char *argv[], mysqlpp::Connection& con, const char *kdb) { if (argc < 1) { cerr << "Bad argument count: " << argc << '!' << endl; return false; } if ((argc > 1) && (argv[1][0] == '-')) { cout << "usage: " << argv[0] << " [host] [user] [password] [port]" << endl; cout << endl << "\tConnects to database "; if (kdb) { cout << '"' << kdb << '"'; } else { cout << "server"; } cout << " on localhost using your user" << endl; cout << "\tname and no password by default." << endl << endl; return false; } if (!kdb) { kdb = kpcSampleDatabase; } bool success = false; if (argc == 1) { success = con.connect(kdb); } else if (argc == 2) { success = con.connect(kdb, argv[1]); } else if (argc == 3) { success = con.connect(kdb, argv[1], argv[2]); } else if (argc == 4) { success = con.connect(kdb, argv[1], argv[2], argv[3]); } else if (argc >= 5) { success = con.real_connect(kdb, argv[1], argv[2], argv[3], atoi(argv[4])); } if (!success) { cerr << "Database connection failed." << endl << endl; } return success; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: Object.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: rt $ $Date: 2003-04-24 13:21:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source 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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_LANG_OBJJECT_HXX_ #include "java/lang/Class.hxx" #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_JAVA_XJAVAVM_HPP_ #include <com/sun/star/java/XJavaVM.hpp> #endif #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_ #include "java/sql/SQLException.hxx" #endif #ifndef _VOS_PROCESS_HXX_ #include <vos/process.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _RTL_PROCESS_H_ #include <rtl/process.h> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif using namespace connectivity; namespace starjava = com::sun::star::java; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; ::rtl::Reference< jvmaccess::VirtualMachine > InitJava(const Reference<XMultiServiceFactory >& _rxFactory) { ::rtl::Reference< jvmaccess::VirtualMachine > aRet; OSL_ENSURE(_rxFactory.is(),"No XMultiServiceFactory a.v.!"); if(!_rxFactory.is()) return aRet; try { Reference< ::starjava::XJavaVM > xVM(_rxFactory->createInstance( rtl::OUString::createFromAscii("com.sun.star.java.JavaVirtualMachine")), UNO_QUERY); OSL_ENSURE(_rxFactory.is(),"InitJava: I have no factory!"); if (!xVM.is() || !_rxFactory.is()) throw Exception(); // -2; Sequence<sal_Int8> processID(16); rtl_getGlobalProcessId( (sal_uInt8*) processID.getArray() ); processID.realloc(17); processID[16] = 0; Any uaJVM = xVM->getJavaVM( processID ); if (!uaJVM.hasValue()) throw Exception(); // -5 else { sal_Int32 nValue; jvmaccess::VirtualMachine* pJVM = NULL; if ( uaJVM >>= nValue ) pJVM = reinterpret_cast< jvmaccess::VirtualMachine* > (nValue); else { sal_Int64 nTemp; uaJVM >>= nTemp; pJVM = reinterpret_cast< jvmaccess::VirtualMachine* > (nTemp); } aRet = pJVM; } } catch (Exception& e) { } return aRet; } // ----------------------------------------------------------------------------- ::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM(const ::rtl::Reference< jvmaccess::VirtualMachine >& _rVM = ::rtl::Reference< jvmaccess::VirtualMachine >(), sal_Bool _bSet = sal_False) { static ::rtl::Reference< jvmaccess::VirtualMachine > s_VM; if ( _rVM.is() || _bSet ) s_VM = _rVM; return s_VM; } // ----------------------------------------------------------------------------- ::rtl::Reference< jvmaccess::VirtualMachine > java_lang_Object::getVM(const Reference<XMultiServiceFactory >& _rxFactory) { ::rtl::Reference< jvmaccess::VirtualMachine > xVM = getJavaVM(); if ( !xVM.is() && _rxFactory.is() ) getJavaVM(InitJava(_rxFactory)); return xVM; } // ----------------------------------------------------------------------------- SDBThreadAttach::SDBThreadAttach() : m_aGuard(java_lang_Object::getVM()) { pEnv = m_aGuard.getEnvironment(); } // ----------------------------------------------------------------------------- SDBThreadAttach::~SDBThreadAttach() { } // ----------------------------------------------------------------------------- sal_Int32& getJavaVMRefCount() { static sal_Int32 s_nRefCount = 0; return s_nRefCount; } // ----------------------------------------------------------------------------- void SDBThreadAttach::addRef() { getJavaVMRefCount()++; } // ----------------------------------------------------------------------------- void SDBThreadAttach::releaseRef() { getJavaVMRefCount()--; if ( getJavaVMRefCount() == 0 ) getJavaVM(::rtl::Reference< jvmaccess::VirtualMachine >(),sal_True); } // ----------------------------------------------------------------------------- // statische Variablen der Klasse: jclass java_lang_Object::theClass = 0; sal_uInt32 java_lang_Object::nObjCount = 0; jclass java_lang_Object::getMyClass() { if( !theClass ) { SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/lang/Object" ); theClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); } return theClass; } // der eigentliche Konstruktor java_lang_Object::java_lang_Object(const Reference<XMultiServiceFactory >& _rxFactory) : object( 0 ),m_xFactory(_rxFactory) { } // der protected-Konstruktor fuer abgeleitete Klassen java_lang_Object::java_lang_Object( JNIEnv * pXEnv, jobject myObj ) : object( NULL ) { SDBThreadAttach t; if( t.pEnv && myObj ) object = t.pEnv->NewGlobalRef( myObj ); } java_lang_Object::~java_lang_Object() { if( object ) { SDBThreadAttach t; if( t.pEnv ) t.pEnv->DeleteGlobalRef( object ); } } // der protected-Konstruktor fuer abgeleitete Klassen void java_lang_Object::saveRef( JNIEnv * pXEnv, jobject myObj ) { OSL_ENSURE( myObj, "object in c++ -> Java Wrapper" ); SDBThreadAttach t; if( t.pEnv && myObj ) object = t.pEnv->NewGlobalRef( myObj ); } java_lang_Class * java_lang_Object::getClass() { jobject out; SDBThreadAttach t; if( t.pEnv ) { // temporaere Variable initialisieren char * cSignature = "()Ljava/lang/Class;"; char * cMethodName = "getClass"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallObjectMethodA( object, mID, NULL ); ThrowSQLException(t.pEnv,NULL); return new java_lang_Class( t.pEnv, out ); } //mID } //pEnv return NULL; } ::rtl::OUString java_lang_Object::toString() { SDBThreadAttach t; ::rtl::OUString aStr; if( t.pEnv ) { // temporaere Variable initialisieren char * cSignature = "()Ljava/lang/String;"; char * cMethodName = "toString"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { jstring out(0); out = (jstring)t.pEnv->CallObjectMethod( object, mID); ThrowSQLException(t.pEnv,NULL); if(out) aStr = JavaString2String(t.pEnv,out); } //mID } //pEnv return aStr; } // -------------------------------------------------------------------------------- void java_lang_Object::ThrowSQLException(JNIEnv * pEnv,const Reference< XInterface> & _rContext) throw(SQLException, RuntimeException) { jthrowable jThrow = NULL; if(pEnv && (jThrow = pEnv->ExceptionOccurred())) { pEnv->ExceptionClear();// we have to clear the exception here because we want to handle it itself if(pEnv->IsInstanceOf(jThrow,java_sql_SQLException_BASE::getMyClass())) { java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,jThrow); SQLException e( pException->getMessage(), _rContext, pException->getSQLState(), pException->getErrorCode(), Any() ); delete pException; throw e; } else if(pEnv->IsInstanceOf(jThrow,java_lang_Throwable::getMyClass())) { java_lang_Throwable *pThrow = new java_lang_Throwable(pEnv,jThrow); ::rtl::OUString aMsg = pThrow->getMessage(); if(!aMsg.getLength()) aMsg = pThrow->getLocalizedMessage(); if(!aMsg.getLength()) aMsg = pThrow->toString(); delete pThrow; throw SQLException(aMsg,_rContext,::rtl::OUString(),-1,Any()); } } } <commit_msg>INTEGRATION: CWS dba08 (1.14.18); FILE MERGED 2003/06/17 06:10:59 oj 1.14.18.1: #110233# assign java vm to variable<commit_after>/************************************************************************* * * $RCSfile: Object.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: vg $ $Date: 2003-06-25 11:06:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source 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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_JAVA_LANG_OBJJECT_HXX_ #include "java/lang/Class.hxx" #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_ #include <com/sun/star/uno/Exception.hpp> #endif #ifndef _COM_SUN_STAR_JAVA_XJAVAVM_HPP_ #include <com/sun/star/java/XJavaVM.hpp> #endif #ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_ #include "java/tools.hxx" #endif #ifndef _CONNECTIVITY_JAVA_SQL_SQLEXCEPTION_HXX_ #include "java/sql/SQLException.hxx" #endif #ifndef _VOS_PROCESS_HXX_ #include <vos/process.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _RTL_PROCESS_H_ #include <rtl/process.h> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif using namespace connectivity; namespace starjava = com::sun::star::java; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; ::rtl::Reference< jvmaccess::VirtualMachine > InitJava(const Reference<XMultiServiceFactory >& _rxFactory) { ::rtl::Reference< jvmaccess::VirtualMachine > aRet; OSL_ENSURE(_rxFactory.is(),"No XMultiServiceFactory a.v.!"); if(!_rxFactory.is()) return aRet; try { Reference< ::starjava::XJavaVM > xVM(_rxFactory->createInstance( rtl::OUString::createFromAscii("com.sun.star.java.JavaVirtualMachine")), UNO_QUERY); OSL_ENSURE(_rxFactory.is(),"InitJava: I have no factory!"); if (!xVM.is() || !_rxFactory.is()) throw Exception(); // -2; Sequence<sal_Int8> processID(16); rtl_getGlobalProcessId( (sal_uInt8*) processID.getArray() ); processID.realloc(17); processID[16] = 0; Any uaJVM = xVM->getJavaVM( processID ); if (!uaJVM.hasValue()) throw Exception(); // -5 else { sal_Int32 nValue; jvmaccess::VirtualMachine* pJVM = NULL; if ( uaJVM >>= nValue ) pJVM = reinterpret_cast< jvmaccess::VirtualMachine* > (nValue); else { sal_Int64 nTemp; uaJVM >>= nTemp; pJVM = reinterpret_cast< jvmaccess::VirtualMachine* > (nTemp); } aRet = pJVM; } } catch (Exception& e) { } return aRet; } // ----------------------------------------------------------------------------- ::rtl::Reference< jvmaccess::VirtualMachine > getJavaVM(const ::rtl::Reference< jvmaccess::VirtualMachine >& _rVM = ::rtl::Reference< jvmaccess::VirtualMachine >(), sal_Bool _bSet = sal_False) { static ::rtl::Reference< jvmaccess::VirtualMachine > s_VM; if ( _rVM.is() || _bSet ) s_VM = _rVM; return s_VM; } // ----------------------------------------------------------------------------- ::rtl::Reference< jvmaccess::VirtualMachine > java_lang_Object::getVM(const Reference<XMultiServiceFactory >& _rxFactory) { ::rtl::Reference< jvmaccess::VirtualMachine > xVM = getJavaVM(); if ( !xVM.is() && _rxFactory.is() ) xVM = getJavaVM(InitJava(_rxFactory)); return xVM; } // ----------------------------------------------------------------------------- SDBThreadAttach::SDBThreadAttach() : m_aGuard(java_lang_Object::getVM()) { pEnv = m_aGuard.getEnvironment(); } // ----------------------------------------------------------------------------- SDBThreadAttach::~SDBThreadAttach() { } // ----------------------------------------------------------------------------- sal_Int32& getJavaVMRefCount() { static sal_Int32 s_nRefCount = 0; return s_nRefCount; } // ----------------------------------------------------------------------------- void SDBThreadAttach::addRef() { getJavaVMRefCount()++; } // ----------------------------------------------------------------------------- void SDBThreadAttach::releaseRef() { getJavaVMRefCount()--; if ( getJavaVMRefCount() == 0 ) getJavaVM(::rtl::Reference< jvmaccess::VirtualMachine >(),sal_True); } // ----------------------------------------------------------------------------- // statische Variablen der Klasse: jclass java_lang_Object::theClass = 0; sal_uInt32 java_lang_Object::nObjCount = 0; jclass java_lang_Object::getMyClass() { if( !theClass ) { SDBThreadAttach t; if( !t.pEnv ) return (jclass)NULL; jclass tempClass = t.pEnv->FindClass( "java/lang/Object" ); theClass = (jclass)t.pEnv->NewGlobalRef( tempClass ); t.pEnv->DeleteLocalRef( tempClass ); } return theClass; } // der eigentliche Konstruktor java_lang_Object::java_lang_Object(const Reference<XMultiServiceFactory >& _rxFactory) : object( 0 ),m_xFactory(_rxFactory) { } // der protected-Konstruktor fuer abgeleitete Klassen java_lang_Object::java_lang_Object( JNIEnv * pXEnv, jobject myObj ) : object( NULL ) { SDBThreadAttach t; if( t.pEnv && myObj ) object = t.pEnv->NewGlobalRef( myObj ); } java_lang_Object::~java_lang_Object() { if( object ) { SDBThreadAttach t; if( t.pEnv ) t.pEnv->DeleteGlobalRef( object ); } } // der protected-Konstruktor fuer abgeleitete Klassen void java_lang_Object::saveRef( JNIEnv * pXEnv, jobject myObj ) { OSL_ENSURE( myObj, "object in c++ -> Java Wrapper" ); SDBThreadAttach t; if( t.pEnv && myObj ) object = t.pEnv->NewGlobalRef( myObj ); } java_lang_Class * java_lang_Object::getClass() { jobject out; SDBThreadAttach t; if( t.pEnv ) { // temporaere Variable initialisieren char * cSignature = "()Ljava/lang/Class;"; char * cMethodName = "getClass"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { out = t.pEnv->CallObjectMethodA( object, mID, NULL ); ThrowSQLException(t.pEnv,NULL); return new java_lang_Class( t.pEnv, out ); } //mID } //pEnv return NULL; } ::rtl::OUString java_lang_Object::toString() { SDBThreadAttach t; ::rtl::OUString aStr; if( t.pEnv ) { // temporaere Variable initialisieren char * cSignature = "()Ljava/lang/String;"; char * cMethodName = "toString"; // Java-Call absetzen jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!"); if( mID ) { jstring out(0); out = (jstring)t.pEnv->CallObjectMethod( object, mID); ThrowSQLException(t.pEnv,NULL); if(out) aStr = JavaString2String(t.pEnv,out); } //mID } //pEnv return aStr; } // -------------------------------------------------------------------------------- void java_lang_Object::ThrowSQLException(JNIEnv * pEnv,const Reference< XInterface> & _rContext) throw(SQLException, RuntimeException) { jthrowable jThrow = NULL; if(pEnv && (jThrow = pEnv->ExceptionOccurred())) { pEnv->ExceptionClear();// we have to clear the exception here because we want to handle it itself if(pEnv->IsInstanceOf(jThrow,java_sql_SQLException_BASE::getMyClass())) { java_sql_SQLException_BASE* pException = new java_sql_SQLException_BASE(pEnv,jThrow); SQLException e( pException->getMessage(), _rContext, pException->getSQLState(), pException->getErrorCode(), Any() ); delete pException; throw e; } else if(pEnv->IsInstanceOf(jThrow,java_lang_Throwable::getMyClass())) { java_lang_Throwable *pThrow = new java_lang_Throwable(pEnv,jThrow); ::rtl::OUString aMsg = pThrow->getMessage(); if(!aMsg.getLength()) aMsg = pThrow->getLocalizedMessage(); if(!aMsg.getLength()) aMsg = pThrow->toString(); delete pThrow; throw SQLException(aMsg,_rContext,::rtl::OUString(),-1,Any()); } } } <|endoftext|>
<commit_before>/* * util.hpp * * Created on: Feb 28, 2015 * Author: hugo */ #ifndef MFLASH_CPP_CORE_UTIL_HPP_ #define MFLASH_CPP_CORE_UTIL_HPP_ #include <fstream> #include <iostream> #include <sstream> #include <string> #include <unistd.h> #include "../core/type.hpp" using namespace std; namespace mflash { const int MFLASH_MATRIX_THREADS = 1; const int MFLASH_VECTOR_THREADS = 1; const double MAPPING_PERCENTAGE = 0.1; const string FILE_SEPARATOR = "/"; const string DIRECTORY = ".G-FLASH"; const string GRAPH = "graph"; const string STREAM_FILE = "edge_stream"; const int64 DEFAULT_BYTES_BLOCK = sizeof(int64) * 5; // 40 BYTES int64 MEMORY_SIZE_BYTES = 1 * 1073741824L; //2GB int64 get_mapping_limit(int64 block_size_bytes) { return 1048576; //MAPPING_PERCENTAGE * block_size_bytes; } string get_parent_directory(string graph) { int64 pos = graph.find_last_of(FILE_SEPARATOR); return graph.substr(0, pos) + FILE_SEPARATOR; } string get_mflash_directory(string graph) { string path = get_parent_directory(graph) + DIRECTORY; /* boost::filesystem::path dir(path); if( !boost::filesystem::exists(path) ){ boost::filesystem::create_directories(path); }*/ return path; } string get_stream_file(string graph) { return get_parent_directory(graph) + DIRECTORY + FILE_SEPARATOR + STREAM_FILE; } string get_block_file(string graph, int64 i, int64 j) { std::stringstream file; file << get_mflash_directory(graph) << FILE_SEPARATOR << i << "_" << j << ".block"; return file.str(); } bool exist_file(string file) { ifstream f(file.c_str()); if (f.good()) { f.close(); return true; } else { f.close(); return false; } } int64 file_size(string file) { if (exist_file(file)) { ifstream in(file, std::ifstream::ate | std::ifstream::binary); int64 size = in.tellg(); in.close(); return size; } return 0; } ios::openmode get_file_properties(string file, bool write) { if (!write) { return ios::in | ios::binary | ios::ate; } ios::openmode properties = ios::out | ios::binary | ios::ate; if (exist_file(file)) { properties |= ios::in; } return properties; } /*string get_mflash_directory(string graph) { string path = get_parent_directory(graph); boost::filesystem::path dir(path); if( !boost::filesystem::exists(path) ){ boost::filesystem::create_directories(path); } return path; } string get_block_file(string graph, int64 i, int64 j){ std::stringstream file; file << get_mflash_directory(graph) << FILE_SEPARATOR << i << "_" << j << ".block"; return file.str(); } bool exist_file(string file){ return boost::filesystem::exists(boost::filesystem::path(file)); } int64 file_size(string file){ return boost::filesystem::file_size(boost::filesystem::path(file)); }*/ void quicksort(double values[], int64 indexes[], int64 left, int64 right, bool asc) { double pivot = values[left + (right - left) / 2]; int i = left; int j = right; int operator_ = asc ? 1 : -1; while (i <= j) { while (operator_ * values[i] < operator_ * pivot) { i++; } while (operator_ * values[j] > operator_ * pivot) { j--; } if (i <= j) { int64 idxTmp = indexes[i]; double valueTmp = values[i]; values[i] = values[j]; values[j] = valueTmp; indexes[i] = indexes[j]; indexes[j] = idxTmp; i++; j--; } } if (left < j) quicksort(values, indexes, left, j, asc); if (i < right) quicksort(values, indexes, i, right, asc); } int64* sort_and_get_indexes(int64 n, double values[], bool asc) { int64 *indexes = new int64[n]; for (int64 i = 0; i < n; i++) { indexes[i] = i; } quicksort(values, indexes, 0, n - 1, asc); return indexes; } /* int stick_this_thread_to_core(int core_id) { int num_cores = sysconf(_SC_NPROCESSORS_ONLN); if (core_id < 0 || core_id >= num_cores) return EINVAL; cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core_id, &cpuset); pthread_t current_thread = pthread_self(); return pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset); } */ } #endif /* MFLASH_CPP_CORE_UTIL_HPP_ */ <commit_msg>Method to get partition filename<commit_after>/* * util.hpp * * Created on: Feb 28, 2015 * Author: hugo */ #ifndef MFLASH_CPP_CORE_UTIL_HPP_ #define MFLASH_CPP_CORE_UTIL_HPP_ #include <fstream> #include <iostream> #include <sstream> #include <string> #include <unistd.h> #include "../core/type.hpp" using namespace std; namespace mflash { const int MFLASH_MATRIX_THREADS = 1; const int MFLASH_VECTOR_THREADS = 1; const double MAPPING_PERCENTAGE = 0.1; const string FILE_SEPARATOR = "/"; const string DIRECTORY = ".G-FLASH"; const string GRAPH = "graph"; const string STREAM_FILE = "edge_stream"; const int64 DEFAULT_BYTES_BLOCK = sizeof(int64) * 5; // 40 BYTES int64 MEMORY_SIZE_BYTES = 1 * 1073741824L; //2GB int64 get_mapping_limit(int64 block_size_bytes) { return 1048576; //MAPPING_PERCENTAGE * block_size_bytes; } string get_parent_directory(string graph) { int64 pos = graph.find_last_of(FILE_SEPARATOR); return graph.substr(0, pos) + FILE_SEPARATOR; } string get_mflash_directory(string graph) { string path = get_parent_directory(graph) + DIRECTORY; /* boost::filesystem::path dir(path); if( !boost::filesystem::exists(path) ){ boost::filesystem::create_directories(path); }*/ return path; } string get_stream_file(string graph) { return get_parent_directory(graph) + DIRECTORY + FILE_SEPARATOR + STREAM_FILE; } string get_block_file(string graph, int64 i, int64 j) { std::stringstream file; file << get_mflash_directory(graph) << FILE_SEPARATOR << i << "_" << j << ".block"; return file.str(); } string get_partition_file(string graph, int64 partition_id) { std::stringstream file; file << get_mflash_directory(graph) << FILE_SEPARATOR << partition_id << ".partition"; return file.str(); } bool exist_file(string file) { ifstream f(file.c_str()); if (f.good()) { f.close(); return true; } else { f.close(); return false; } } int64 file_size(string file) { if (exist_file(file)) { ifstream in(file, std::ifstream::ate | std::ifstream::binary); int64 size = in.tellg(); in.close(); return size; } return 0; } ios::openmode get_file_properties(string file, bool write) { if (!write) { return ios::in | ios::binary | ios::ate; } ios::openmode properties = ios::out | ios::binary | ios::ate; if (exist_file(file)) { properties |= ios::in; } return properties; } /*string get_mflash_directory(string graph) { string path = get_parent_directory(graph); boost::filesystem::path dir(path); if( !boost::filesystem::exists(path) ){ boost::filesystem::create_directories(path); } return path; } string get_block_file(string graph, int64 i, int64 j){ std::stringstream file; file << get_mflash_directory(graph) << FILE_SEPARATOR << i << "_" << j << ".block"; return file.str(); } bool exist_file(string file){ return boost::filesystem::exists(boost::filesystem::path(file)); } int64 file_size(string file){ return boost::filesystem::file_size(boost::filesystem::path(file)); }*/ void quicksort(double values[], int64 indexes[], int64 left, int64 right, bool asc) { double pivot = values[left + (right - left) / 2]; int i = left; int j = right; int operator_ = asc ? 1 : -1; while (i <= j) { while (operator_ * values[i] < operator_ * pivot) { i++; } while (operator_ * values[j] > operator_ * pivot) { j--; } if (i <= j) { int64 idxTmp = indexes[i]; double valueTmp = values[i]; values[i] = values[j]; values[j] = valueTmp; indexes[i] = indexes[j]; indexes[j] = idxTmp; i++; j--; } } if (left < j) quicksort(values, indexes, left, j, asc); if (i < right) quicksort(values, indexes, i, right, asc); } int64* sort_and_get_indexes(int64 n, double values[], bool asc) { int64 *indexes = new int64[n]; for (int64 i = 0; i < n; i++) { indexes[i] = i; } quicksort(values, indexes, 0, n - 1, asc); return indexes; } /* int stick_this_thread_to_core(int core_id) { int num_cores = sysconf(_SC_NPROCESSORS_ONLN); if (core_id < 0 || core_id >= num_cores) return EINVAL; cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core_id, &cpuset); pthread_t current_thread = pthread_self(); return pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset); } */ } #endif /* MFLASH_CPP_CORE_UTIL_HPP_ */ <|endoftext|>
<commit_before>#ifndef GNR_COROUTINE_HPP # define GNR_COROUTINE_HPP # pragma once #include <cassert> #include <cstdint> #include <functional> #include <memory> #include "savestate.hpp" namespace gnr { namespace { // half a megabyte stack default enum : std::size_t { anon_default_stack_size = 512 * 1024 }; } template < std::size_t N = anon_default_stack_size, template <typename> class Function = std::function > class coroutine { public: enum : std::size_t { default_stack_size = anon_default_stack_size }; enum : std::size_t { stack_size = N }; enum status : std::uint8_t { INITIALIZED, RUNNING, TERMINATED }; private: statebuf env_in_; statebuf env_out_; enum status status_{TERMINATED}; std::unique_ptr<char[]> stack_; Function<void()> f_; public: explicit coroutine() : stack_(new char[stack_size]) { } template <typename F> explicit coroutine(F&& f) : coroutine() { assign(std::forward<F>(f)); } coroutine(coroutine&&) = default; coroutine& operator=(coroutine&&) = default; template <typename F> coroutine& operator=(F&& f) { assign(std::forward<F>(f)); return *this; } auto status() const noexcept { return status_; } auto is_terminated() const noexcept { return TERMINATED == status_; } template <typename F> void assign(F&& f) { f_ = [this, f = std::forward<F>(f)]() { status_ = RUNNING; f(*this); status_ = TERMINATED; yield(); }; status_ = INITIALIZED; } #if defined(__GNUC__) void yield() noexcept __attribute__ ((noinline)) #elif defined(_MSC_VER) __declspec(noinline) void yield() noexcept #else # error "unsupported compiler" #endif { #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi"); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #elif defined(__arm__) && !defined(__ARM_ARCH_7__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7, ""r8", "r9", "r10", "lr"); #elif defined(__arm__) && defined(__ARM_ARCH_7__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r8", "r9", "r10", "lr"); #endif #endif if (!savestate(env_out_)) { restorestate(env_in_); } // else do nothing } #if defined(__GNUC__) void resume() noexcept __attribute__ ((noinline)) #elif defined(_MSC_VER) __declspec(noinline) void resume() noexcept #else # error "unsupported compiler" #endif { #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi"); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #elif defined(__arm__) && !defined(__ARM_ARCH_7__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr"); #elif defined(__arm__) && defined(__ARM_ARCH_7__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r8", "r9", "r10", "lr"); #endif #endif assert(TERMINATED != status()); if (savestate(env_in_)) { return; } else if (RUNNING == status()) { restorestate(env_out_); } else { #if defined(__GNUC__) // stack switch #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile( "movl %0, %%esp" : : "r" (stack_.get() + stack_size) ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile( "movq %0, %%rsp" : : "r" (stack_.get() + stack_size) ); #elif defined(__arm__) asm volatile( "mov sp, %0" : : "r" (stack_.get() + stack_size) ); #else #error "can't switch stack frame" #endif #elif defined(_MSC_VER) auto const p(stack_.get() + stack_size); _asm mov esp, p #else #error "can't switch stack frame" #endif f_(); } } }; } #endif // GNR_COROUTINE_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_COROUTINE_HPP # define GNR_COROUTINE_HPP # pragma once #include <cassert> #include <cstdint> #include <functional> #include <memory> #include "savestate.hpp" namespace gnr { namespace { // half a megabyte stack default enum : std::size_t { anon_default_stack_size = 512 * 1024 }; } template < std::size_t N = anon_default_stack_size, template <typename> class Function = std::function > class coroutine { public: enum : std::size_t { default_stack_size = anon_default_stack_size }; enum : std::size_t { stack_size = N }; enum status : std::uint8_t { INITIALIZED, RUNNING, TERMINATED }; private: statebuf env_in_; statebuf env_out_; enum status status_{TERMINATED}; std::unique_ptr<char[]> stack_; Function<void()> f_; public: explicit coroutine() : stack_(new char[stack_size]) { } template <typename F> explicit coroutine(F&& f) : coroutine() { assign(std::forward<F>(f)); } coroutine(coroutine&&) = default; coroutine& operator=(coroutine&&) = default; template <typename F> coroutine& operator=(F&& f) { assign(std::forward<F>(f)); return *this; } auto status() const noexcept { return status_; } auto is_terminated() const noexcept { return TERMINATED == status_; } template <typename F> void assign(F&& f) { f_ = [this, f = std::forward<F>(f)]() { status_ = RUNNING; f(*this); status_ = TERMINATED; yield(); }; status_ = INITIALIZED; } #if defined(__GNUC__) void yield() noexcept __attribute__ ((noinline)) #elif defined(_MSC_VER) __declspec(noinline) void yield() noexcept #else # error "unsupported compiler" #endif { #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi"); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #elif defined(__arm__) && !defined(__ARM_ARCH_7__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr"); #elif defined(__arm__) && defined(__ARM_ARCH_7__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r8", "r9", "r10", "lr"); #endif #endif if (!savestate(env_out_)) { restorestate(env_in_); } // else do nothing } #if defined(__GNUC__) void resume() noexcept __attribute__ ((noinline)) #elif defined(_MSC_VER) __declspec(noinline) void resume() noexcept #else # error "unsupported compiler" #endif { #if defined(__GNUC__) #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ("":::"eax", "ebx", "ecx", "edx", "esi", "edi"); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ("":::"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"); #elif defined(__arm__) && !defined(__ARM_ARCH_7__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "lr"); #elif defined(__arm__) && defined(__ARM_ARCH_7__) asm volatile ("":::"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r8", "r9", "r10", "lr"); #endif #endif assert(TERMINATED != status()); if (savestate(env_in_)) { return; } else if (RUNNING == status()) { restorestate(env_out_); } else { #if defined(__GNUC__) // stack switch #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile( "movl %0, %%esp" : : "r" (stack_.get() + stack_size) ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile( "movq %0, %%rsp" : : "r" (stack_.get() + stack_size) ); #elif defined(__arm__) asm volatile( "mov sp, %0" : : "r" (stack_.get() + stack_size) ); #else #error "can't switch stack frame" #endif #elif defined(_MSC_VER) auto const p(stack_.get() + stack_size); _asm mov esp, p #else #error "can't switch stack frame" #endif f_(); } } }; } #endif // GNR_COROUTINE_HPP <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <cstdlib> #include <cstring> #include <cerrno> #include <fcntl.h> #include <unistd.h> using std::cout; using std::endl; using std::string; void nope_out(const string & prefix); int main(const int argc, const char * argv []) { if (argc != 2) { cout << "Usage: " << argv[0] << " FILE" << endl; exit(EXIT_FAILURE); } // if const char * filename = argv[1]; int ofd, cfd; if ((ofd = open(filename, O_RDONLY)) == -1) { nope_out("open"); } // if // DO STUFF HERE if ((cfd = close(ofd)) == -1) { nope_out("close"); } // if return EXIT_SUCCESS; } // main void nope_out(const string & prefix) { perror(prefix.c_str()); exit(EXIT_FAILURE); } // nope_out <commit_msg>updated lseek example<commit_after>#include <iostream> #include <string> #include <cstdlib> #include <cstring> #include <cerrno> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> using std::cout; using std::endl; using std::string; void nope_out(const string & prefix); int main(const int argc, const char * argv []) { if (argc != 2) { cout << "Usage: " << argv[0] << " FILE" << endl; exit(EXIT_FAILURE); } // if const char * filename = argv[1]; int ofd, cfd; if ((ofd = open(filename, O_RDONLY)) == -1) { nope_out("open"); } // if // DO STUFF HERE off_t size; if ((size = lseek(ofd, 0, SEEK_END)) == -1) { nope_out("lseek"); } // if cout << size << endl; if ((cfd = close(ofd)) == -1) { nope_out("close"); } // if return EXIT_SUCCESS; } // main void nope_out(const string & prefix) { perror(prefix.c_str()); // exit(EXIT_FAILURE); } // nope_out <|endoftext|>
<commit_before>#ifndef GENERIC_COROUTINE_HPP # define GENERIC_COROUTINE_HPP # pragma once #include <cassert> #include <csetjmp> #include <functional> #include "forwarder.hpp" #include "lightptr.hpp" namespace generic { class coroutine { jmp_buf env_in_; jmp_buf env_out_; ::std::function<void()> f_; bool running_; bool terminated_; ::generic::light_ptr<char[]> stack_; char* const stack_top_; public: explicit coroutine(::std::size_t const N = 128 * 1024) : running_{false}, terminated_{true}, stack_(new char[N]), stack_top_(stack_.get() + N) { } template <typename F> explicit coroutine(::std::size_t const N, F&& f) : coroutine(N) { assign(::std::forward<F>(f)); } auto terminated() const noexcept { return terminated_; } template <typename F> void assign(F&& f) { running_ = terminated_ = false; f_ = [this, f = ::std::forward<F>(f)]() mutable { f(*this); running_ = false; terminated_ = true; yield(); }; } void yield() noexcept { if (setjmp(env_out_)) { return; } else { longjmp(env_in_, 1); } } void resume() noexcept { if (setjmp(env_in_)) { return; } else if (running_) { longjmp(env_out_, 1); } else { running_ = true; // stack switch #if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile( "movq %%rsp, %0" : : "rm" (stack_top_) ); #elif defined(i386) || defined(__i386) || defined(__i386__) asm volatile( "movl %%esp, %0" : : "rm" (stack_top_) ); #else #error "can't switch stack frame" #endif f_(); } } }; } #endif // GENERIC_COROUTINE_HPP <commit_msg>some fixes<commit_after>#ifndef GENERIC_COROUTINE_HPP # define GENERIC_COROUTINE_HPP # pragma once #include <cassert> #include <csetjmp> #include <functional> #include <memory> #include "forwarder.hpp" namespace generic { class coroutine { jmp_buf env_in_; jmp_buf env_out_; ::std::function<void()> f_; bool running_; bool terminated_; ::std::unique_ptr<char[]> stack_; char* const stack_top_; public: explicit coroutine(::std::size_t const N = 128 * 1024) : running_{false}, terminated_{true}, stack_(new char[N]), stack_top_(stack_.get() + N) { } template <typename F> explicit coroutine(::std::size_t const N, F&& f) : coroutine(N) { assign(::std::forward<F>(f)); } auto terminated() const noexcept { return terminated_; } template <typename F> void assign(F&& f) { running_ = terminated_ = false; f_ = [this, f = ::std::forward<F>(f)]() mutable { f(*this); running_ = false; terminated_ = true; yield(); }; } void yield() noexcept { if (setjmp(env_out_)) { return; } else { longjmp(env_in_, 1); } } void resume() noexcept { if (setjmp(env_in_)) { return; } else if (running_) { longjmp(env_out_, 1); } else { running_ = true; // stack switch #if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile( "movq %0, %%rsp" : : "rm" (stack_top_) ); #elif defined(i386) || defined(__i386) || defined(__i386__) asm volatile( "movl %0, %%esp" : : "rm" (stack_top_) ); #else #error "can't switch stack frame" #endif f_(); } } }; } #endif // GENERIC_COROUTINE_HPP <|endoftext|>
<commit_before>/* * qi_roivolumes.cpp * * Copyright (c) 2016 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <fstream> #include <string> #include "QI/Types.h" #include "QI/IO.h" #include "QI/Args.h" #include "itkLabelGeometryImageFilter.h" typedef itk::LabelGeometryImageFilter<QI::VolumeI, QI::VolumeF> TLblGeoFilter; // Declare arguments here so they are available in helper functions args::ArgumentParser parser("Calculates average values or volumes of ROI labels.\n" "If the --volumes flag is specified, only give the label images.\n" "If --volumes is not specified, give label and value image pairs (all labels first, then all values).\n" "Output goes to stdout\n" "http://github.com/spinicist/QUIT"); args::PositionalList<std::string> in_paths(parser, "INPUT", "Input file paths."); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information (will mess up output, for test runs only)", {'v', "verbose"}); args::Flag volumes(parser, "VOLUMES", "Output ROI volumes, not average values (does not require value images)", {'V', "volumes"}); args::ValueFlag<std::string> label_list_path(parser, "LABELS", "Specify labels and names to use in text file 'label number, label name' one per line", {'l', "labels"}); args::Flag print_names(parser, "PRINT_NAMES", "Print label names in first column/row (LABEL_NUMBERS must be specified)", {'n', "print_names"}); args::Flag transpose(parser, "TRANSPOSE", "Transpose output table (values go in rows instead of columns", {'t', "transpose"}); args::Flag ignore_zero(parser, "IGNORE_ZERO", "Ignore 0 label (background)", {'z', "ignore_zero"}); args::ValueFlag<std::string> delim(parser, "DELIMITER", "Specify delimiter to use between entries (default ,)", {'d',"delim"}, ","); args::ValueFlagList<std::string> header_paths(parser, "HEADER", "Add a header (can be specified multiple times)", {'H', "header"}); /* * Helper function to calculate the volume of a voxel in an image */ double VoxelVolume(QI::VolumeI::Pointer img) { double vox_volume = img->GetSpacing()[0]; for (int v = 1; v < 3; v++) vox_volume *= img->GetSpacing()[v]; return vox_volume; } /* * Helper function to work out the label list */ void GetLabelList(TLblGeoFilter::LabelsType &label_numbers, std::vector<std::string> &label_names) { if (label_list_path) { if (verbose) std::cout << "Opening label list file: " << label_list_path.Get() << std::endl; std::ifstream file(label_list_path.Get()); std::string temp; while (std::getline(file, temp, ',')) { label_numbers.push_back(stoi(temp)); std::getline(file, temp); label_names.push_back(temp); } } else { if (verbose) std::cout << "Reading first label file to determine labels: " << QI::CheckList(in_paths).at(0) << std::endl; TLblGeoFilter::Pointer label_filter = TLblGeoFilter::New(); label_filter->CalculatePixelIndicesOff(); label_filter->CalculateOrientedBoundingBoxOff(); label_filter->CalculateOrientedLabelRegionsOff(); QI::VolumeI::Pointer img = QI::ReadImage<QI::VolumeI>(QI::CheckList(in_paths).at(0)); label_filter->SetInput(img); label_filter->Update(); label_numbers = label_filter->GetLabels(); std::sort(label_numbers.begin(), label_numbers.end()); } if (ignore_zero) { if (verbose) std::cout << "Removing zero from label list." << std::endl; label_numbers.erase(std::remove(label_numbers.begin(), label_numbers.end(), 0), label_numbers.end()); } } /* * Helper function to read in all the header lines */ std::vector<std::vector<std::string>> GetHeaders(int n_files) { std::vector<std::vector<std::string>> headers(header_paths.Get().size(), std::vector<std::string>()); for (int h = 0; h < headers.size(); h++) { const std::string header_path = header_paths.Get().at(h); if (verbose) std::cout << "Reading header file: " << header_path << std::endl; std::ifstream header_file(header_path); std::string element; while (std::getline(header_file, element)) { headers.at(h).push_back(element); } if (headers.at(h).size() != n_files) { QI_EXCEPTION("Number of input files (" << n_files << ") does not match number of entries (" << headers.at(h).size() << ") in header: " << header_path) } } return headers; } /* * Helper function to actually work out all the values */ std::vector<std::vector<double>> GetValues(const int n_files, const TLblGeoFilter::LabelsType &labels) { std::vector<std::vector<double>> values(in_paths.Get().size(), std::vector<double>(labels.size())); TLblGeoFilter::Pointer label_filter = TLblGeoFilter::New(); QI::VolumeI::Pointer label_img = ITK_NULLPTR; QI::VolumeF::Pointer value_img = ITK_NULLPTR; for (int f = 0; f < n_files; f++) { if (volumes) { if (verbose) std::cout << "Reading label file: " << in_paths.Get().at(f) << std::endl; label_img = QI::ReadImage<QI::VolumeI>(in_paths.Get().at(f)); } else { if (verbose) std::cout << "Reading label file: " << in_paths.Get().at(f) << std::endl; label_img = QI::ReadImage<QI::VolumeI>(in_paths.Get().at(f)); if (verbose) std::cout << "Reading value file: " << in_paths.Get().at(f + n_files) << std::endl; value_img = QI::ReadImage(in_paths.Get().at(f + n_files)); label_filter->SetIntensityInput(value_img); } double vox_volume = VoxelVolume(label_img); label_filter->SetInput(label_img); label_filter->Update(); for (int i = 0; i < labels.size(); i++) { const double n_voxels = label_filter->GetVolume(labels.at(i)); // This is the count of pixels if (volumes) { values.at(f).at(i) = vox_volume * n_voxels; } else { const double integrated = label_filter->GetIntegratedIntensity(labels.at(i)); values.at(f).at(i) = integrated / n_voxels; } } } return values; } /* * MAIN */ int main(int argc, char **argv) { QI::ParseArgs(parser, argc, argv); int n_files = QI::CheckList(in_paths).size(); if (volumes) { if (verbose) std::cout << "There are " << n_files << " input images, finding ROI volumes" << std::endl; } else { // For ROI values, we have label and value image pairs if (n_files % 2 != 0) { std::cerr << "Require an even number of input images when finding ROI values" << std::endl; return EXIT_FAILURE; } n_files = n_files / 2; if (verbose) std::cout << "There are " << n_files << " input image pairs, finding mean ROI values" << std::endl; } // Setup label number list typename TLblGeoFilter::LabelsType labels; std::vector<std::string> label_names; GetLabelList(labels, label_names); // Setup headers (if any) auto headers = GetHeaders(n_files); // Now get the values/volumes auto values_table = GetValues(n_files, labels); if (verbose) std::cout << "Writing CSV: " << std::endl; if (transpose) { if (print_names) { for (int i = 0; i < headers.size(); ++i) { std::cout << delim.Get(); } auto it = label_names.begin(); std::cout << *it; for (++it; it != label_names.end(); ++it) { std::cout << delim.Get() << *it; } std::cout << std::endl; } for (int row = 0; row < values_table.size(); ++row){ for (auto h = headers.begin(); h != headers.end(); h++) { std::cout << h->at(row) << delim.Get(); } auto values_row_it = values_table.at(row).begin(); std::cout << *values_row_it; for (++values_row_it; values_row_it != values_table.at(row).end(); ++values_row_it) { std::cout << delim.Get() << *values_row_it; } std::cout << std::endl; } } else { for (auto hdr = headers.begin(); hdr != headers.end(); ++hdr) { if (print_names) std::cout << delim.Get(); auto h_el = hdr->begin(); std::cout << *h_el; for (++h_el; h_el != hdr->end(); ++h_el) { std::cout << delim.Get() << *h_el; } std::cout << std::endl; } for (int l = 0; l < labels.size(); ++l) { if (print_names) std::cout << label_names.at(l) << delim.Get(); auto values_col_it = values_table.begin(); std::cout << values_col_it->at(l); for (++values_col_it; values_col_it != values_table.end(); ++values_col_it) { std::cout << delim.Get() << values_col_it->at(l); } std::cout << std::endl; } } return EXIT_SUCCESS; } <commit_msg>BUG: Values table had wrong number of initial entries<commit_after>/* * qi_roivolumes.cpp * * Copyright (c) 2016 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <fstream> #include <string> #include "QI/Types.h" #include "QI/IO.h" #include "QI/Args.h" #include "itkLabelGeometryImageFilter.h" typedef itk::LabelGeometryImageFilter<QI::VolumeI, QI::VolumeF> TLblGeoFilter; // Declare arguments here so they are available in helper functions args::ArgumentParser parser("Calculates average values or volumes of ROI labels.\n" "If the --volumes flag is specified, only give the label images.\n" "If --volumes is not specified, give label and value image pairs (all labels first, then all values).\n" "Output goes to stdout\n" "http://github.com/spinicist/QUIT"); args::PositionalList<std::string> in_paths(parser, "INPUT", "Input file paths."); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information (will mess up output, for test runs only)", {'v', "verbose"}); args::Flag volumes(parser, "VOLUMES", "Output ROI volumes, not average values (does not require value images)", {'V', "volumes"}); args::ValueFlag<std::string> label_list_path(parser, "LABELS", "Specify labels and names to use in text file 'label number, label name' one per line", {'l', "labels"}); args::Flag print_names(parser, "PRINT_NAMES", "Print label names in first column/row (LABEL_NUMBERS must be specified)", {'n', "print_names"}); args::Flag transpose(parser, "TRANSPOSE", "Transpose output table (values go in rows instead of columns", {'t', "transpose"}); args::Flag ignore_zero(parser, "IGNORE_ZERO", "Ignore 0 label (background)", {'z', "ignore_zero"}); args::ValueFlag<std::string> delim(parser, "DELIMITER", "Specify delimiter to use between entries (default ,)", {'d',"delim"}, ","); args::ValueFlagList<std::string> header_paths(parser, "HEADER", "Add a header (can be specified multiple times)", {'H', "header"}); /* * Helper function to calculate the volume of a voxel in an image */ double VoxelVolume(QI::VolumeI::Pointer img) { double vox_volume = img->GetSpacing()[0]; for (int v = 1; v < 3; v++) vox_volume *= img->GetSpacing()[v]; return vox_volume; } /* * Helper function to work out the label list */ void GetLabelList(TLblGeoFilter::LabelsType &label_numbers, std::vector<std::string> &label_names) { if (label_list_path) { if (verbose) std::cout << "Opening label list file: " << label_list_path.Get() << std::endl; std::ifstream file(label_list_path.Get()); std::string temp; while (std::getline(file, temp, ',')) { label_numbers.push_back(stoi(temp)); std::getline(file, temp); label_names.push_back(temp); } } else { if (verbose) std::cout << "Reading first label file to determine labels: " << QI::CheckList(in_paths).at(0) << std::endl; TLblGeoFilter::Pointer label_filter = TLblGeoFilter::New(); label_filter->CalculatePixelIndicesOff(); label_filter->CalculateOrientedBoundingBoxOff(); label_filter->CalculateOrientedLabelRegionsOff(); QI::VolumeI::Pointer img = QI::ReadImage<QI::VolumeI>(QI::CheckList(in_paths).at(0)); label_filter->SetInput(img); label_filter->Update(); label_numbers = label_filter->GetLabels(); std::sort(label_numbers.begin(), label_numbers.end()); } if (ignore_zero) { if (verbose) std::cout << "Removing zero from label list." << std::endl; label_numbers.erase(std::remove(label_numbers.begin(), label_numbers.end(), 0), label_numbers.end()); } } /* * Helper function to read in all the header lines */ std::vector<std::vector<std::string>> GetHeaders(int n_files) { std::vector<std::vector<std::string>> headers(header_paths.Get().size(), std::vector<std::string>()); for (int h = 0; h < headers.size(); h++) { const std::string header_path = header_paths.Get().at(h); if (verbose) std::cout << "Reading header file: " << header_path << std::endl; std::ifstream header_file(header_path); std::string element; while (std::getline(header_file, element)) { headers.at(h).push_back(element); } if (headers.at(h).size() != n_files) { QI_EXCEPTION("Number of input files (" << n_files << ") does not match number of entries (" << headers.at(h).size() << ") in header: " << header_path) } } return headers; } /* * Helper function to actually work out all the values */ std::vector<std::vector<double>> GetValues(const int n_files, const TLblGeoFilter::LabelsType &labels) { std::vector<std::vector<double>> values(n_files, std::vector<double>(labels.size())); TLblGeoFilter::Pointer label_filter = TLblGeoFilter::New(); QI::VolumeI::Pointer label_img = ITK_NULLPTR; QI::VolumeF::Pointer value_img = ITK_NULLPTR; for (int f = 0; f < n_files; f++) { if (volumes) { if (verbose) std::cout << "Reading label file: " << in_paths.Get().at(f) << std::endl; label_img = QI::ReadImage<QI::VolumeI>(in_paths.Get().at(f)); } else { if (verbose) std::cout << "Reading label file: " << in_paths.Get().at(f) << std::endl; label_img = QI::ReadImage<QI::VolumeI>(in_paths.Get().at(f)); if (verbose) std::cout << "Reading value file: " << in_paths.Get().at(f + n_files) << std::endl; value_img = QI::ReadImage(in_paths.Get().at(f + n_files)); label_filter->SetIntensityInput(value_img); } double vox_volume = VoxelVolume(label_img); label_filter->SetInput(label_img); label_filter->Update(); for (int i = 0; i < labels.size(); i++) { const double n_voxels = label_filter->GetVolume(labels.at(i)); // This is the count of pixels if (volumes) { values.at(f).at(i) = vox_volume * n_voxels; } else { const double integrated = label_filter->GetIntegratedIntensity(labels.at(i)); values.at(f).at(i) = integrated / n_voxels; } } } return values; } /* * MAIN */ int main(int argc, char **argv) { QI::ParseArgs(parser, argc, argv); int n_files = QI::CheckList(in_paths).size(); if (volumes) { if (verbose) std::cout << "There are " << n_files << " input images, finding ROI volumes" << std::endl; } else { // For ROI values, we have label and value image pairs if (n_files % 2 != 0) { std::cerr << "Require an even number of input images when finding ROI values" << std::endl; return EXIT_FAILURE; } n_files = n_files / 2; if (verbose) std::cout << "There are " << n_files << " input image pairs, finding mean ROI values" << std::endl; } // Setup label number list typename TLblGeoFilter::LabelsType labels; std::vector<std::string> label_names; GetLabelList(labels, label_names); // Setup headers (if any) auto headers = GetHeaders(n_files); // Now get the values/volumes auto values_table = GetValues(n_files, labels); if (verbose) std::cout << "Writing CSV: " << std::endl; if (transpose) { if (print_names) { for (int i = 0; i < headers.size(); ++i) { std::cout << delim.Get(); } auto it = label_names.begin(); std::cout << *it; for (++it; it != label_names.end(); ++it) { std::cout << delim.Get() << *it; } std::cout << std::endl; } for (int row = 0; row < values_table.size(); ++row){ for (auto h = headers.begin(); h != headers.end(); h++) { std::cout << h->at(row) << delim.Get(); } auto values_row_it = values_table.at(row).begin(); std::cout << *values_row_it; for (++values_row_it; values_row_it != values_table.at(row).end(); ++values_row_it) { std::cout << delim.Get() << *values_row_it; } std::cout << std::endl; } } else { for (auto hdr = headers.begin(); hdr != headers.end(); ++hdr) { if (print_names) std::cout << delim.Get(); auto h_el = hdr->begin(); std::cout << *h_el; for (++h_el; h_el != hdr->end(); ++h_el) { std::cout << delim.Get() << *h_el; } std::cout << std::endl; } for (int l = 0; l < labels.size(); ++l) { if (print_names) std::cout << label_names.at(l) << delim.Get(); auto values_col_it = values_table.begin(); std::cout << values_col_it->at(l); for (++values_col_it; values_col_it != values_table.end(); ++values_col_it) { std::cout << delim.Get() << values_col_it->at(l); } std::cout << std::endl; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include "drake/solvers/NloptSolver.h" #include <stdexcept> #include <list> #include <vector> #include <nlopt.hpp> #include "drake/core/Gradient.h" #include "drake/solvers/Optimization.h" using drake::solvers::SolutionResult; namespace Drake { namespace { Eigen::VectorXd MakeEigenVector(const std::vector<double>& x) { Eigen::VectorXd xvec(x.size()); for (size_t i = 0; i < x.size(); i++) { xvec[i] = x[i]; } return xvec; } TaylorVecXd MakeInputTaylorVec(const Eigen::VectorXd& xvec, const VariableList& variable_list) { size_t var_count = 0; for (const DecisionVariableView& v : variable_list) { var_count += v.size(); } auto tx = initializeAutoDiff(xvec); TaylorVecXd this_x(var_count); size_t index = 0; for (const DecisionVariableView& v : variable_list) { this_x.segment(index, v.size()) = tx.segment(v.index(), v.size()); index += v.size(); } return this_x; } // This function meets the signature requirements for nlopt::vfunc as // described in // http://ab-initio.mit.edu/wiki/index.php/NLopt_C-plus-plus_Reference#Objective_function double EvaluateCosts(const std::vector<double>& x, std::vector<double>& grad, void* f_data) { const OptimizationProblem* prog = reinterpret_cast<const OptimizationProblem*>(f_data); double cost = 0; Eigen::VectorXd xvec = MakeEigenVector(x); auto tx = initializeAutoDiff(xvec); TaylorVecXd ty(1); TaylorVecXd this_x; if (!grad.empty()) { grad.assign(grad.size(), 0); } for (auto const& binding : prog->generic_objectives()) { size_t index = 0; for (const DecisionVariableView& v : binding.variable_list()) { this_x.conservativeResize(index + v.size()); this_x.segment(index, v.size()) = tx.segment(v.index(), v.size()); index += v.size(); } binding.constraint()->eval(this_x, ty); cost += ty(0).value(); if (!grad.empty()) { for (const DecisionVariableView& v : binding.variable_list()) { for (size_t j = v.index(); j < v.index() + v.size(); j++) { grad[j] += ty(0).derivatives()(j); } } } } return cost; } /// Structure to marshall data into the NLopt callback functions, /// which take only a single pointer argument. struct WrappedConstraint { WrappedConstraint(const Constraint* constraint_in, const VariableList* variable_list_in) : constraint(constraint_in), variable_list(variable_list_in), force_bounds(false), force_upper(false) {} const Constraint* constraint; const VariableList* variable_list; bool force_bounds; ///< force usage of only upper or lower bounds bool force_upper; ///< Only used if force_bounds is set. Selects ///< which bounds are being tested (lower bound ///< vs. upper bound). // TODO(sam.creasey) It might be desirable to have a cache for the // result of evaluating the constraints if NLopt were being used in // a situation where constraints were frequently being wrapped in // such a way as to result in multiple evaluations. As this is a // speculative case, and since NLopt's roundoff issues with // duplicate constraints preclude it from being used in some // scenarios, I'm not implementing such a cache at this time. std::set<size_t> active_constraints; }; double ApplyConstraintBounds(double result, double lb, double ub) { // Our (Drake's) constraints are expressed in the form lb <= f(x) <= // ub. NLopt always wants the value of a constraint expressed as // f(x) <= 0. // // For upper bounds rewrite as: f(x) - ub <= 0 // For lower bounds rewrite as: -f(x) + lb <= 0 // // If both upper and lower bounds are set, default to evaluating the // upper bound, and switch to the lower bound only if it's being // exceeded. // // See // http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Nonlinear_constraints // for more detail on how NLopt interprets return values. if ((ub != std::numeric_limits<double>::infinity()) && ((result >= lb) || (lb == ub))) { result -= ub; } else { if (lb == -std::numeric_limits<double>::infinity()) { throw std::runtime_error( "Unable to handle constraint with no bounds."); } result *= -1; result += lb; } return result; } // This function meets the signature of nlopt_mfunc as described in // http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Vector-valued_constraints void EvaluateVectorConstraint(unsigned m, double* result, unsigned n, const double* x, double* grad, void* f_data) { const WrappedConstraint* wrapped = reinterpret_cast<WrappedConstraint*>(f_data); Eigen::VectorXd xvec(n); for (size_t i = 0; i < n; i++) { xvec[i] = x[i]; } // http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Vector-valued_constraints // explicity tells us that it's allocated m * n array elements // before invoking this function. It does not seem to have been // zeroed, and not all constraints will store gradients for all // decision variables (so don't leave junk in the other array // elements). if (grad) { memset(grad, 0, sizeof(double) * m * n); } const Constraint* c = wrapped->constraint; const size_t num_constraints = c->num_constraints(); assert(num_constraints >= m); assert(wrapped->active_constraints.size() == m); TaylorVecXd ty(num_constraints); TaylorVecXd this_x = MakeInputTaylorVec(xvec, *(wrapped->variable_list)); c->eval(this_x, ty); const Eigen::VectorXd& lower_bound = c->lower_bound(); const Eigen::VectorXd& upper_bound = c->upper_bound(); size_t result_idx = 0; for (size_t i = 0; i < num_constraints; i++) { if (!wrapped->active_constraints.count(i)) { continue; } if (wrapped->force_bounds && wrapped->force_upper && (upper_bound(i) != std::numeric_limits<double>::infinity())) { result[result_idx] = ApplyConstraintBounds( ty(i).value(), -std::numeric_limits<double>::infinity(), upper_bound(i)); } else if (wrapped->force_bounds && !wrapped->force_upper && (lower_bound(i) != -std::numeric_limits<double>::infinity())) { result[result_idx] = ApplyConstraintBounds( ty(i).value(), lower_bound(i), std::numeric_limits<double>::infinity()); } else { result[result_idx] = ApplyConstraintBounds( ty(i).value(), lower_bound(i), upper_bound(i)); } result_idx++; assert(result_idx <= m); } if (grad) { for (const DecisionVariableView& v : *(wrapped->variable_list)) { result_idx = 0; for (size_t i = 0; i < num_constraints; i++) { if (!wrapped->active_constraints.count(i)) { continue; } double grad_sign = 1; if (c->upper_bound()(i) == std::numeric_limits<double>::infinity()) { grad_sign = -1; } else if (wrapped->force_bounds && !wrapped->force_upper) { grad_sign = -1; } for (size_t j = v.index(); j < v.index() + v.size(); j++) { grad[(result_idx * n) + j] = ty(i).derivatives()(j) * grad_sign; } result_idx++; assert(result_idx <= m); } assert(result_idx == m); } } } template <typename C> void WrapConstraint(const OptimizationProblem::Binding<C>& binding, double constraint_tol, nlopt::opt* opt, std::list<WrappedConstraint>* wrapped_list) { // Version of the wrapped constraint which refers only to equality // constraints (if any), and will be used with // add_equality_mconstraint. WrappedConstraint wrapped_eq(binding.constraint().get(), &binding.variable_list()); // Version of the wrapped constraint which refers only to inequality // constraints (if any), and will be used with // add_equality_mconstraint. WrappedConstraint wrapped_in(binding.constraint().get(), &binding.variable_list()); bool is_pure_inequality = true; const Eigen::VectorXd& lower_bound = binding.constraint()->lower_bound(); const Eigen::VectorXd& upper_bound = binding.constraint()->upper_bound(); assert(lower_bound.size() == upper_bound.size()); for (size_t i = 0; i < lower_bound.size(); i++) { if (lower_bound(i) == upper_bound(i)) { wrapped_eq.active_constraints.insert(i); } else { if ((lower_bound(i) != -std::numeric_limits<double>::infinity()) && (upper_bound(i) != std::numeric_limits<double>::infinity())) { is_pure_inequality = false; } wrapped_in.active_constraints.insert(i); } } if (wrapped_eq.active_constraints.size()) { wrapped_list->push_back(wrapped_eq); std::vector<double> tol(wrapped_eq.active_constraints.size(), constraint_tol); opt->add_equality_mconstraint( EvaluateVectorConstraint, &wrapped_list->back(), tol); } if (wrapped_in.active_constraints.size()) { std::vector<double> tol(wrapped_in.active_constraints.size(), constraint_tol); wrapped_list->push_back(wrapped_in); if (is_pure_inequality) { opt->add_inequality_mconstraint( EvaluateVectorConstraint, &wrapped_list->back(), tol); } else { wrapped_list->back().force_bounds = true; wrapped_list->back().force_upper = true; opt->add_inequality_mconstraint( EvaluateVectorConstraint, &wrapped_list->back(), tol); wrapped_list->push_back(wrapped_in); wrapped_list->back().force_bounds = true; wrapped_list->back().force_upper = false; opt->add_inequality_mconstraint( EvaluateVectorConstraint, &wrapped_list->back(), tol); } } } } // anonymous namespace bool NloptSolver::available() const { return true; } SolutionResult NloptSolver::Solve(OptimizationProblem &prog) const { int nx = prog.num_vars(); // Load the algo to use and the size. nlopt::opt opt(nlopt::LD_SLSQP, nx); const Eigen::VectorXd& initial_guess = prog.initial_guess(); std::vector<double> x(initial_guess.size()); for (size_t i = 0; i < x.size(); i++) { x[i] = initial_guess[i]; } std::vector<double> xlow(nx, -std::numeric_limits<double>::infinity()); std::vector<double> xupp(nx, std::numeric_limits<double>::infinity()); for (auto const& binding : prog.bounding_box_constraints()) { auto const& c = binding.constraint(); const Eigen::VectorXd& lower_bound = c->lower_bound(); const Eigen::VectorXd& upper_bound = c->upper_bound(); for (const DecisionVariableView& v : binding.variable_list()) { for (int k = 0; k < v.size(); k++) { const int idx = v.index() + k; xlow[idx] = std::max(lower_bound(k), xlow[idx]); xupp[idx] = std::min(upper_bound(k), xupp[idx]); if (x[idx] < xlow[idx]) { x[idx] = xlow[idx]; } if (x[idx] > xupp[idx]) { x[idx] = xupp[idx]; } } } } opt.set_lower_bounds(xlow); opt.set_upper_bounds(xupp); opt.set_min_objective(EvaluateCosts, &prog); // TODO(sam.creasey): All hardcoded tolerances in this function // should be made configurable when #1879 is fixed. const double constraint_tol = 1e-6; const double xtol_rel = 1e-6; const double xtol_abs = 1e-6; std::list<WrappedConstraint> wrapped_list; // TODO(sam.creasey): Missing test coverage for generic constraints // with >1 output. for (const auto& c : prog.generic_constraints()) { WrapConstraint(c, constraint_tol, &opt, &wrapped_list); } for (const auto& c : prog.linear_equality_constraints()) { WrapConstraint(c, constraint_tol, &opt, &wrapped_list); } // TODO(sam.creasey): Missing test coverage for linear constraints // with >1 output. for (const auto& c : prog.linear_constraints()) { WrapConstraint(c, constraint_tol, &opt, &wrapped_list); } opt.set_xtol_rel(xtol_rel); opt.set_xtol_abs(xtol_abs); SolutionResult result = SolutionResult::kSolutionFound; nlopt::result nlopt_result = nlopt::FAILURE; try { double minf = 0; nlopt_result = opt.optimize(x, minf); } catch (std::invalid_argument&) { result = SolutionResult::kInvalidInput; } catch (std::bad_alloc&) { result = SolutionResult::kUnknownError; } catch (nlopt::roundoff_limited) { result = SolutionResult::kUnknownError; } catch (nlopt::forced_stop) { result = SolutionResult::kUnknownError; } catch (std::runtime_error&) { result = SolutionResult::kUnknownError; } Eigen::VectorXd sol(x.size()); for (int i = 0; i < nx; i++) { sol(i) = x[i]; } prog.SetDecisionVariableValues(sol); prog.SetSolverResult("NLopt", nlopt_result); return result; } } <commit_msg>Change template spelling in an attempt to make clang happy.<commit_after> #include "drake/solvers/NloptSolver.h" #include <stdexcept> #include <list> #include <vector> #include <nlopt.hpp> #include "drake/core/Gradient.h" #include "drake/solvers/Optimization.h" using drake::solvers::SolutionResult; namespace Drake { namespace { Eigen::VectorXd MakeEigenVector(const std::vector<double>& x) { Eigen::VectorXd xvec(x.size()); for (size_t i = 0; i < x.size(); i++) { xvec[i] = x[i]; } return xvec; } TaylorVecXd MakeInputTaylorVec(const Eigen::VectorXd& xvec, const VariableList& variable_list) { size_t var_count = 0; for (const DecisionVariableView& v : variable_list) { var_count += v.size(); } auto tx = initializeAutoDiff(xvec); TaylorVecXd this_x(var_count); size_t index = 0; for (const DecisionVariableView& v : variable_list) { this_x.segment(index, v.size()) = tx.segment(v.index(), v.size()); index += v.size(); } return this_x; } // This function meets the signature requirements for nlopt::vfunc as // described in // http://ab-initio.mit.edu/wiki/index.php/NLopt_C-plus-plus_Reference#Objective_function double EvaluateCosts(const std::vector<double>& x, std::vector<double>& grad, void* f_data) { const OptimizationProblem* prog = reinterpret_cast<const OptimizationProblem*>(f_data); double cost = 0; Eigen::VectorXd xvec = MakeEigenVector(x); auto tx = initializeAutoDiff(xvec); TaylorVecXd ty(1); TaylorVecXd this_x; if (!grad.empty()) { grad.assign(grad.size(), 0); } for (auto const& binding : prog->generic_objectives()) { size_t index = 0; for (const DecisionVariableView& v : binding.variable_list()) { this_x.conservativeResize(index + v.size()); this_x.segment(index, v.size()) = tx.segment(v.index(), v.size()); index += v.size(); } binding.constraint()->eval(this_x, ty); cost += ty(0).value(); if (!grad.empty()) { for (const DecisionVariableView& v : binding.variable_list()) { for (size_t j = v.index(); j < v.index() + v.size(); j++) { grad[j] += ty(0).derivatives()(j); } } } } return cost; } /// Structure to marshall data into the NLopt callback functions, /// which take only a single pointer argument. struct WrappedConstraint { WrappedConstraint(const Constraint* constraint_in, const VariableList* variable_list_in) : constraint(constraint_in), variable_list(variable_list_in), force_bounds(false), force_upper(false) {} const Constraint* constraint; const VariableList* variable_list; bool force_bounds; ///< force usage of only upper or lower bounds bool force_upper; ///< Only used if force_bounds is set. Selects ///< which bounds are being tested (lower bound ///< vs. upper bound). // TODO(sam.creasey) It might be desirable to have a cache for the // result of evaluating the constraints if NLopt were being used in // a situation where constraints were frequently being wrapped in // such a way as to result in multiple evaluations. As this is a // speculative case, and since NLopt's roundoff issues with // duplicate constraints preclude it from being used in some // scenarios, I'm not implementing such a cache at this time. std::set<size_t> active_constraints; }; double ApplyConstraintBounds(double result, double lb, double ub) { // Our (Drake's) constraints are expressed in the form lb <= f(x) <= // ub. NLopt always wants the value of a constraint expressed as // f(x) <= 0. // // For upper bounds rewrite as: f(x) - ub <= 0 // For lower bounds rewrite as: -f(x) + lb <= 0 // // If both upper and lower bounds are set, default to evaluating the // upper bound, and switch to the lower bound only if it's being // exceeded. // // See // http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Nonlinear_constraints // for more detail on how NLopt interprets return values. if ((ub != std::numeric_limits<double>::infinity()) && ((result >= lb) || (lb == ub))) { result -= ub; } else { if (lb == -std::numeric_limits<double>::infinity()) { throw std::runtime_error( "Unable to handle constraint with no bounds."); } result *= -1; result += lb; } return result; } // This function meets the signature of nlopt_mfunc as described in // http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Vector-valued_constraints void EvaluateVectorConstraint(unsigned m, double* result, unsigned n, const double* x, double* grad, void* f_data) { const WrappedConstraint* wrapped = reinterpret_cast<WrappedConstraint*>(f_data); Eigen::VectorXd xvec(n); for (size_t i = 0; i < n; i++) { xvec[i] = x[i]; } // http://ab-initio.mit.edu/wiki/index.php/NLopt_Reference#Vector-valued_constraints // explicity tells us that it's allocated m * n array elements // before invoking this function. It does not seem to have been // zeroed, and not all constraints will store gradients for all // decision variables (so don't leave junk in the other array // elements). if (grad) { memset(grad, 0, sizeof(double) * m * n); } const Constraint* c = wrapped->constraint; const size_t num_constraints = c->num_constraints(); assert(num_constraints >= m); assert(wrapped->active_constraints.size() == m); TaylorVecXd ty(num_constraints); TaylorVecXd this_x = MakeInputTaylorVec(xvec, *(wrapped->variable_list)); c->eval(this_x, ty); const Eigen::VectorXd& lower_bound = c->lower_bound(); const Eigen::VectorXd& upper_bound = c->upper_bound(); size_t result_idx = 0; for (size_t i = 0; i < num_constraints; i++) { if (!wrapped->active_constraints.count(i)) { continue; } if (wrapped->force_bounds && wrapped->force_upper && (upper_bound(i) != std::numeric_limits<double>::infinity())) { result[result_idx] = ApplyConstraintBounds( ty(i).value(), -std::numeric_limits<double>::infinity(), upper_bound(i)); } else if (wrapped->force_bounds && !wrapped->force_upper && (lower_bound(i) != -std::numeric_limits<double>::infinity())) { result[result_idx] = ApplyConstraintBounds( ty(i).value(), lower_bound(i), std::numeric_limits<double>::infinity()); } else { result[result_idx] = ApplyConstraintBounds( ty(i).value(), lower_bound(i), upper_bound(i)); } result_idx++; assert(result_idx <= m); } if (grad) { for (const DecisionVariableView& v : *(wrapped->variable_list)) { result_idx = 0; for (size_t i = 0; i < num_constraints; i++) { if (!wrapped->active_constraints.count(i)) { continue; } double grad_sign = 1; if (c->upper_bound()(i) == std::numeric_limits<double>::infinity()) { grad_sign = -1; } else if (wrapped->force_bounds && !wrapped->force_upper) { grad_sign = -1; } for (size_t j = v.index(); j < v.index() + v.size(); j++) { grad[(result_idx * n) + j] = ty(i).derivatives()(j) * grad_sign; } result_idx++; assert(result_idx <= m); } assert(result_idx == m); } } } // We can't declare a variable of type OptimizationProblem::Binding, // since that's private and clang gets annoyed. template <typename _Binding> void WrapConstraint(const _Binding& binding, double constraint_tol, nlopt::opt* opt, std::list<WrappedConstraint>* wrapped_list) { // Version of the wrapped constraint which refers only to equality // constraints (if any), and will be used with // add_equality_mconstraint. WrappedConstraint wrapped_eq(binding.constraint().get(), &binding.variable_list()); // Version of the wrapped constraint which refers only to inequality // constraints (if any), and will be used with // add_equality_mconstraint. WrappedConstraint wrapped_in(binding.constraint().get(), &binding.variable_list()); bool is_pure_inequality = true; const Eigen::VectorXd& lower_bound = binding.constraint()->lower_bound(); const Eigen::VectorXd& upper_bound = binding.constraint()->upper_bound(); assert(lower_bound.size() == upper_bound.size()); for (size_t i = 0; i < lower_bound.size(); i++) { if (lower_bound(i) == upper_bound(i)) { wrapped_eq.active_constraints.insert(i); } else { if ((lower_bound(i) != -std::numeric_limits<double>::infinity()) && (upper_bound(i) != std::numeric_limits<double>::infinity())) { is_pure_inequality = false; } wrapped_in.active_constraints.insert(i); } } if (wrapped_eq.active_constraints.size()) { wrapped_list->push_back(wrapped_eq); std::vector<double> tol(wrapped_eq.active_constraints.size(), constraint_tol); opt->add_equality_mconstraint( EvaluateVectorConstraint, &wrapped_list->back(), tol); } if (wrapped_in.active_constraints.size()) { std::vector<double> tol(wrapped_in.active_constraints.size(), constraint_tol); wrapped_list->push_back(wrapped_in); if (is_pure_inequality) { opt->add_inequality_mconstraint( EvaluateVectorConstraint, &wrapped_list->back(), tol); } else { wrapped_list->back().force_bounds = true; wrapped_list->back().force_upper = true; opt->add_inequality_mconstraint( EvaluateVectorConstraint, &wrapped_list->back(), tol); wrapped_list->push_back(wrapped_in); wrapped_list->back().force_bounds = true; wrapped_list->back().force_upper = false; opt->add_inequality_mconstraint( EvaluateVectorConstraint, &wrapped_list->back(), tol); } } } } // anonymous namespace bool NloptSolver::available() const { return true; } SolutionResult NloptSolver::Solve(OptimizationProblem &prog) const { int nx = prog.num_vars(); // Load the algo to use and the size. nlopt::opt opt(nlopt::LD_SLSQP, nx); const Eigen::VectorXd& initial_guess = prog.initial_guess(); std::vector<double> x(initial_guess.size()); for (size_t i = 0; i < x.size(); i++) { x[i] = initial_guess[i]; } std::vector<double> xlow(nx, -std::numeric_limits<double>::infinity()); std::vector<double> xupp(nx, std::numeric_limits<double>::infinity()); for (auto const& binding : prog.bounding_box_constraints()) { auto const& c = binding.constraint(); const Eigen::VectorXd& lower_bound = c->lower_bound(); const Eigen::VectorXd& upper_bound = c->upper_bound(); for (const DecisionVariableView& v : binding.variable_list()) { for (int k = 0; k < v.size(); k++) { const int idx = v.index() + k; xlow[idx] = std::max(lower_bound(k), xlow[idx]); xupp[idx] = std::min(upper_bound(k), xupp[idx]); if (x[idx] < xlow[idx]) { x[idx] = xlow[idx]; } if (x[idx] > xupp[idx]) { x[idx] = xupp[idx]; } } } } opt.set_lower_bounds(xlow); opt.set_upper_bounds(xupp); opt.set_min_objective(EvaluateCosts, &prog); // TODO(sam.creasey): All hardcoded tolerances in this function // should be made configurable when #1879 is fixed. const double constraint_tol = 1e-6; const double xtol_rel = 1e-6; const double xtol_abs = 1e-6; std::list<WrappedConstraint> wrapped_list; // TODO(sam.creasey): Missing test coverage for generic constraints // with >1 output. for (const auto& c : prog.generic_constraints()) { WrapConstraint(c, constraint_tol, &opt, &wrapped_list); } for (const auto& c : prog.linear_equality_constraints()) { WrapConstraint(c, constraint_tol, &opt, &wrapped_list); } // TODO(sam.creasey): Missing test coverage for linear constraints // with >1 output. for (const auto& c : prog.linear_constraints()) { WrapConstraint(c, constraint_tol, &opt, &wrapped_list); } opt.set_xtol_rel(xtol_rel); opt.set_xtol_abs(xtol_abs); SolutionResult result = SolutionResult::kSolutionFound; nlopt::result nlopt_result = nlopt::FAILURE; try { double minf = 0; nlopt_result = opt.optimize(x, minf); } catch (std::invalid_argument&) { result = SolutionResult::kInvalidInput; } catch (std::bad_alloc&) { result = SolutionResult::kUnknownError; } catch (nlopt::roundoff_limited) { result = SolutionResult::kUnknownError; } catch (nlopt::forced_stop) { result = SolutionResult::kUnknownError; } catch (std::runtime_error&) { result = SolutionResult::kUnknownError; } Eigen::VectorXd sol(x.size()); for (int i = 0; i < nx; i++) { sol(i) = x[i]; } prog.SetDecisionVariableValues(sol); prog.SetSolverResult("NLopt", nlopt_result); return result; } } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <rapidcheck/gtest.h> #include <algorithm> #include <iterator> #include <vector> #include SPECIFIC_HEADER // Running tests TEST(TEST_NAME, NoValue) { std::vector<unsigned> expected = { }; ASSERT_EQ(expected, build_grays(0)); } TEST(TEST_NAME, SpecificNumberOfValues) { std::vector<unsigned> expected = { 0b000, 0b001, 0b011, 0b010, 0b110, 0b111, 0b101 }; ASSERT_EQ(expected, build_grays(7)); } RC_GTEST_PROP(TEST_NAME, RightNumberOfValues, (unsigned short N)) { RC_ASSERT(build_grays(N).size() == N); } RC_GTEST_PROP(TEST_NAME, AllEntriesAreUnique, (unsigned short N)) { auto&& out = build_grays(N); std::sort(std::begin(out), std::end(out)); RC_ASSERT(std::adjacent_find(std::begin(out), std::end(out)) == std::end(out)); } RC_GTEST_PROP(TEST_NAME, OneBitDifferBetweenTwoSuccessives, (unsigned short N)) { RC_PRE(N != unsigned short()); auto&& out = build_grays(N); std::vector<std::pair<unsigned, unsigned>> successives; std::transform(std::begin(out), std::prev(std::end(out)) , std::next(std::begin(out)) , std::back_inserter(successives) , [](auto&& elt, auto&& next_elt) { return std::make_pair(elt, next_elt); }); RC_ASSERT(std::find_if(std::begin(successives), std::end(successives) , [](auto&& entries) { auto n = entries.first ^ entries.second; // most be even return n & (n-1); }) == std::end(successives)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); int ret { RUN_ALL_TESTS() }; return ret; } <commit_msg>[gray-code][g++] Fix compile<commit_after>#include "gtest/gtest.h" #include <rapidcheck/gtest.h> #include <algorithm> #include <iterator> #include <vector> #include SPECIFIC_HEADER // Running tests TEST(TEST_NAME, NoValue) { std::vector<unsigned> expected = { }; ASSERT_EQ(expected, build_grays(0)); } TEST(TEST_NAME, SpecificNumberOfValues) { std::vector<unsigned> expected = { 0b000, 0b001, 0b011, 0b010, 0b110, 0b111, 0b101 }; ASSERT_EQ(expected, build_grays(7)); } RC_GTEST_PROP(TEST_NAME, RightNumberOfValues, (unsigned short N)) { RC_ASSERT(build_grays(N).size() == N); } RC_GTEST_PROP(TEST_NAME, AllEntriesAreUnique, (unsigned short N)) { auto&& out = build_grays(N); std::sort(std::begin(out), std::end(out)); RC_ASSERT(std::adjacent_find(std::begin(out), std::end(out)) == std::end(out)); } RC_GTEST_PROP(TEST_NAME, OneBitDifferBetweenTwoSuccessives, (unsigned short N)) { RC_PRE(N != (unsigned short())); auto&& out = build_grays(N); std::vector<std::pair<unsigned, unsigned>> successives; std::transform(std::begin(out), std::prev(std::end(out)) , std::next(std::begin(out)) , std::back_inserter(successives) , [](auto&& elt, auto&& next_elt) { return std::make_pair(elt, next_elt); }); RC_ASSERT(std::find_if(std::begin(successives), std::end(successives) , [](auto&& entries) { auto n = entries.first ^ entries.second; // most be even return n & (n-1); }) == std::end(successives)); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); int ret { RUN_ALL_TESTS() }; return ret; } <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2018 Satya Das 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. */ #include "cppparser.h" #include "cppdom.h" #include "cppobjfactory.h" #include "string-utils.h" #include <algorithm> #include <fstream> #include <vector> std::set<std::string> gMacroNames = {"DECLARE_MESSAGE_MAP", "DECLARE_DYNAMIC", "ACPL_DECLARE_MEMBERS", "DBSYMUTL_MAKE_GETSYMBOLID_FUNCTION", "DBSYMUTL_MAKE_HASSYMBOLID_FUNCTION", "DBSYMUTL_MAKE_HASSYMBOLNAME_FUNCTION"}; std::set<std::string> gKnownApiDecorNames = {"ODRX_ABSTRACT", "FIRSTDLL_EXPORT", "GE_DLLEXPIMPORT", "ADESK_NO_VTABLE", "ACDBCORE2D_PORT", "ACBASE_PORT"}; extern CppCompound* parseStream(char* stm, size_t stmSize); CppObjFactory* gObjFactory = nullptr; CppParser::CppParser(CppObjFactory* objFactory) : objFactory_(objFactory) { if (objFactory_ == nullptr) objFactory_ = new CppObjFactory; } void CppParser::addKnownMacro(std::string knownMacro) { gMacroNames.insert(std::move(knownMacro)); } void CppParser::addKnownMacros(const std::vector<std::string>& knownMacros) { for (auto& macro : knownMacros) gMacroNames.insert(macro); } void CppParser::addKnownApiDecor(std::string knownApiDecor) { gKnownApiDecorNames.insert(std::move(knownApiDecor)); } void CppParser::addKnownApiDecors(const std::vector<std::string>& knownApiDecor) { for (auto& apiDecor : knownApiDecor) gKnownApiDecorNames.insert(apiDecor); } CppCompound* CppParser::parseFile(const char* filename) { auto stm = readFile(filename); CppCompound* cppCompound = parseStream(stm.data(), stm.size()); if (cppCompound == NULL) return cppCompound; cppCompound->name_ = filename; return cppCompound; } CppCompound* CppParser::parseStream(char* stm, size_t stmSize) { if (stm == nullptr || stmSize == 0) return nullptr; gObjFactory = objFactory_; return ::parseStream(stm, stmSize); } CppProgram* CppParser::loadProgram(const char* szInputPath) { auto program = new CppProgram; loadProgram(szInputPath, *program); return program; } static void collectFiles(const bfs::path& path, std::vector<std::string>& files) { if (bfs::is_regular_file(path)) { files.push_back(path.string()); } else if (bfs::is_directory(path)) { for (bfs::directory_iterator dirItr(path); dirItr != bfs::directory_iterator(); ++dirItr) { collectFiles(*dirItr, files); } } } static std::vector<std::string> collectFiles(const bfs::path& path) { std::vector<std::string> files; collectFiles(path, files); if (!files.empty()) std::sort(files.begin(), files.end()); return files; } void CppParser::loadProgram(const bfs::path& path, CppProgram& program) { auto files = collectFiles(path); for (const auto& f : files) { auto cppDom = parseFile(f.c_str()); if (cppDom) program.addCppDom(cppDom); } } CppParser::ByteArray CppParser::readFile(const char* filename) { ByteArray contents; std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); size_t size = in.tellg(); contents.resize(size + 3); // For adding last 2 nulls and a new line. in.seekg(0, std::ios::beg); in.read(&contents[0], size); in.close(); auto len = stripChar(contents.data(), size, '\r'); assert(len <= size); contents.resize(len + 3); contents[len] = '\n'; contents[len + 1] = '\0'; contents[len + 2] = '\0'; } return (contents); } <commit_msg>Added some known macros for parsing ObjectArx code.<commit_after>/* The MIT License (MIT) Copyright (c) 2018 Satya Das 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. */ #include "cppparser.h" #include "cppdom.h" #include "cppobjfactory.h" #include "string-utils.h" #include <algorithm> #include <fstream> #include <iostream> #include <vector> std::set<std::string> gMacroNames = {"DECLARE_MESSAGE_MAP", "DECLARE_DYNAMIC", "ACPL_DECLARE_MEMBERS", "DBSYMUTL_MAKE_GETSYMBOLID_FUNCTION", "DBSYMUTL_MAKE_HASSYMBOLID_FUNCTION", "DBSYMUTL_MAKE_HASSYMBOLNAME_FUNCTION", "ACRX_DECLARE_MEMBERS_EXPIMP", "ACRX_DECLARE_MEMBERS_ACBASE_PORT_EXPIMP" }; std::set<std::string> gKnownApiDecorNames = {"ODRX_ABSTRACT", "FIRSTDLL_EXPORT", "GE_DLLEXPIMPORT", "ADESK_NO_VTABLE", "ACDBCORE2D_PORT", "ACBASE_PORT", "ACCORE_PORT", "ACDB_PORT", "ACPAL_PORT"}; extern CppCompound* parseStream(char* stm, size_t stmSize); CppObjFactory* gObjFactory = nullptr; CppParser::CppParser(CppObjFactory* objFactory) : objFactory_(objFactory) { if (objFactory_ == nullptr) objFactory_ = new CppObjFactory; } void CppParser::addKnownMacro(std::string knownMacro) { gMacroNames.insert(std::move(knownMacro)); } void CppParser::addKnownMacros(const std::vector<std::string>& knownMacros) { for (auto& macro : knownMacros) gMacroNames.insert(macro); } void CppParser::addKnownApiDecor(std::string knownApiDecor) { gKnownApiDecorNames.insert(std::move(knownApiDecor)); } void CppParser::addKnownApiDecors(const std::vector<std::string>& knownApiDecor) { for (auto& apiDecor : knownApiDecor) gKnownApiDecorNames.insert(apiDecor); } CppCompound* CppParser::parseFile(const char* filename) { auto stm = readFile(filename); CppCompound* cppCompound = parseStream(stm.data(), stm.size()); if (cppCompound == NULL) return cppCompound; cppCompound->name_ = filename; return cppCompound; } CppCompound* CppParser::parseStream(char* stm, size_t stmSize) { if (stm == nullptr || stmSize == 0) return nullptr; gObjFactory = objFactory_; return ::parseStream(stm, stmSize); } CppProgram* CppParser::loadProgram(const char* szInputPath) { auto program = new CppProgram; loadProgram(szInputPath, *program); return program; } static void collectFiles(const bfs::path& path, std::vector<std::string>& files) { if (bfs::is_regular_file(path)) { files.push_back(path.string()); } else if (bfs::is_directory(path)) { for (bfs::directory_iterator dirItr(path); dirItr != bfs::directory_iterator(); ++dirItr) { collectFiles(*dirItr, files); } } } static std::vector<std::string> collectFiles(const bfs::path& path) { std::vector<std::string> files; collectFiles(path, files); if (!files.empty()) std::sort(files.begin(), files.end()); return files; } void CppParser::loadProgram(const bfs::path& path, CppProgram& program) { auto files = collectFiles(path); for (const auto& f : files) { std::cout << "Parsing file: '" << f << "'\n"; auto cppDom = parseFile(f.c_str()); if (cppDom) program.addCppDom(cppDom); } } CppParser::ByteArray CppParser::readFile(const char* filename) { ByteArray contents; std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); size_t size = in.tellg(); contents.resize(size + 3); // For adding last 2 nulls and a new line. in.seekg(0, std::ios::beg); in.read(&contents[0], size); in.close(); auto len = stripChar(contents.data(), size, '\r'); assert(len <= size); contents.resize(len + 3); contents[len] = '\n'; contents[len + 1] = '\0'; contents[len + 2] = '\0'; } return (contents); } <|endoftext|>
<commit_before>#include "error.h" #include <curl/curl.h> namespace cpr { ErrorCode getErrorCodeForCurlError(int curlCode) { switch (curlCode) { case CURLE_OK: return ErrorCode::OK; case CURLE_UNSUPPORTED_PROTOCOL: return ErrorCode::UNSUPPORTED_PROTOCOL; case CURLE_URL_MALFORMAT: return ErrorCode::INVALID_URL_FORMAT; case CURLE_COULDNT_RESOLVE_PROXY: return ErrorCode::PROXY_RESOLUTION_FAILURE; case CURLE_COULDNT_RESOLVE_HOST: return ErrorCode::HOST_RESOLUTION_FAILURE; case CURLE_COULDNT_CONNECT: return ErrorCode::CONNECTION_FAILURE; case CURLE_OPERATION_TIMEDOUT: return ErrorCode::OPERATION_TIMEDOUT; case CURLE_SSL_CONNECT_ERROR: return ErrorCode::SSL_CONNECT_ERROR; case CURLE_PEER_FAILED_VERIFICATION: return ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR; case CURLE_GOT_NOTHING: return ErrorCode::EMPTY_RESPONSE; case CURLE_SSL_ENGINE_NOTFOUND: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_ENGINE_SETFAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SEND_ERROR: return ErrorCode::NETWORK_SEND_FAILURE; case CURLE_RECV_ERROR: return ErrorCode::NETWORK_RECEIVE_ERROR; case CURLE_SSL_CERTPROBLEM: return ErrorCode::SSL_LOCAL_CERTIFICATE_ERROR; case CURLE_SSL_CIPHER: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_CACERT: return ErrorCode::SSL_CACERT_ERROR; case CURLE_USE_SSL_FAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_ENGINE_INITFAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_CACERT_BADFILE: return ErrorCode::SSL_CACERT_ERROR; case CURLE_SSL_SHUTDOWN_FAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_CRL_BADFILE: return ErrorCode::SSL_CACERT_ERROR; case CURLE_SSL_ISSUER_ERROR: return ErrorCode::SSL_CACERT_ERROR; case CURLE_TOO_MANY_REDIRECTS: return ErrorCode::OK; default: return ErrorCode::INTERNAL_ERROR; } } } // namespace cpr <commit_msg>Use lowercase underscore for variable name<commit_after>#include "error.h" #include <curl/curl.h> namespace cpr { ErrorCode getErrorCodeForCurlError(int curl_code) { switch (curl_code) { case CURLE_OK: return ErrorCode::OK; case CURLE_UNSUPPORTED_PROTOCOL: return ErrorCode::UNSUPPORTED_PROTOCOL; case CURLE_URL_MALFORMAT: return ErrorCode::INVALID_URL_FORMAT; case CURLE_COULDNT_RESOLVE_PROXY: return ErrorCode::PROXY_RESOLUTION_FAILURE; case CURLE_COULDNT_RESOLVE_HOST: return ErrorCode::HOST_RESOLUTION_FAILURE; case CURLE_COULDNT_CONNECT: return ErrorCode::CONNECTION_FAILURE; case CURLE_OPERATION_TIMEDOUT: return ErrorCode::OPERATION_TIMEDOUT; case CURLE_SSL_CONNECT_ERROR: return ErrorCode::SSL_CONNECT_ERROR; case CURLE_PEER_FAILED_VERIFICATION: return ErrorCode::SSL_REMOTE_CERTIFICATE_ERROR; case CURLE_GOT_NOTHING: return ErrorCode::EMPTY_RESPONSE; case CURLE_SSL_ENGINE_NOTFOUND: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_ENGINE_SETFAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SEND_ERROR: return ErrorCode::NETWORK_SEND_FAILURE; case CURLE_RECV_ERROR: return ErrorCode::NETWORK_RECEIVE_ERROR; case CURLE_SSL_CERTPROBLEM: return ErrorCode::SSL_LOCAL_CERTIFICATE_ERROR; case CURLE_SSL_CIPHER: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_CACERT: return ErrorCode::SSL_CACERT_ERROR; case CURLE_USE_SSL_FAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_ENGINE_INITFAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_CACERT_BADFILE: return ErrorCode::SSL_CACERT_ERROR; case CURLE_SSL_SHUTDOWN_FAILED: return ErrorCode::GENERIC_SSL_ERROR; case CURLE_SSL_CRL_BADFILE: return ErrorCode::SSL_CACERT_ERROR; case CURLE_SSL_ISSUER_ERROR: return ErrorCode::SSL_CACERT_ERROR; case CURLE_TOO_MANY_REDIRECTS: return ErrorCode::OK; default: return ErrorCode::INTERNAL_ERROR; } } } // namespace cpr <|endoftext|>
<commit_before>// Copyright (c) 2017 Pierre Fourgeaud // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "drivers/xml/serializablecodec_xml.h" #include "core/enginecontext.h" #include "core/fileaccess.h" #include "core/resourceloader.h" #include "core/serializable.h" #include "core/type_traits/attributeaccessor.h" #include "core/type_traits/objectdefinition.h" #include "core/utils.h" #include <cstring> #include <logger.h> namespace CodeHero { // Standard parsing bool ParseBool(const std::string& iInput) { bool res = false; if (iInput == "true") { res = true; } else if (iInput == "false") { res = false; } else { LOGE << "[SerializableCodecXML]: Faile to parse bool argument: '" << iInput << "' is not valid." << std::endl; } return res; } float ParseFloat(const std::string& iInput) { float res = 0.0f; try { res = std::stof(iInput); } catch (const std::exception& e) { LOGE << "XML: Fail to parse float argument, got: " << e.what() << std::endl; } return res; } Vector2 ParseVector2(const std::string& iInput) { Vector2 res; auto nums = Split(iInput, ' '); if (nums.size() != 2) { LOGE << "[SerializableCodexXML]: Fail to parse Vector2 argument. Got " << nums.size() << " members, expected 2." << std::endl; return res; } try { res.SetX(ParseFloat(nums[0])); res.SetY(ParseFloat(nums[1])); } catch (const std::exception& e) { LOGE << "[SerializableCodexXML]: Fail to parse Vector2 argument, got: " << e.what() << std::endl; } return res; } Vector3 ParseVector3(const std::string& iInput) { Vector3 res; auto nums = Split(iInput, ' '); if (nums.size() != 3) { LOGE << "XML: Fail to parse Vector3 argument. Got " << nums.size() << " members, expected 3." << std::endl; return res; } try { res.SetX(ParseFloat(nums[0])); res.SetY(ParseFloat(nums[1])); res.SetZ(ParseFloat(nums[2])); } catch (const std::exception& e) { LOGE << "XML: Fail to parse Vector3 argument, got: " << e.what() << std::endl; } return res; } Quaternion ParseQuaternion(const std::string& iInput) { Quaternion res; auto nums = Split(iInput, ' '); if (nums.size() == 3) { try { res.FromEulerAngles(ParseFloat(nums[0]), ParseFloat(nums[1]), ParseFloat(nums[2])); } catch (const std::exception& e) { LOGE << "[SerializableCodexXML]: Fail to parse Quaternion argument, got: " << e.what() << std::endl; } } else { LOGE << "[SerializableCodexXML]: Fail to parse Quaternion argument. Got " << nums.size() << " members." << std::endl; } return res; } VariantArray ParseArray(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren) { VariantArray res; for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) { if (std::strcmp(it->name(), "subattribute") == 0) { std::string attrVal = it->attribute("value").as_string(); res.push_back(attrVal); } else { LOGE << "[SerializableCodeXML]: Failed to parse array attribute with name '" << it->name() << "'" << std::endl; } } return std::move(res); } VariantHashMap ParseHashMap(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren) { VariantHashMap res; for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) { if (std::strcmp(it->name(), "subattribute") == 0) { std::string attr = it->attribute("name").as_string(); std::string attrVal = it->attribute("value").as_string(); res[attr] = attrVal; } else { LOGE << "[SerializableCodeXML]: Failed to parse hashmap attribute with name '" << it->name() << "'" << std::endl; } } return std::move(res); } SerializableCodecXML::SerializableCodecXML(const std::shared_ptr<EngineContext>& iContext) : ResourceCodec<Serializable>(iContext) { std::vector<std::string> ext{"xml", "XML"}; for (auto& e : ext) { _AddExtension(e); } } SerializableCodecXML::~SerializableCodecXML() {} Error SerializableCodecXML::Load(FileAccess& iF, Serializable& oObject) { const int32_t size = iF.GetSize(); std::string content = iF.ReadAll(); pugi::xml_document doc; pugi::xml_parse_result result = doc.load_string(content.c_str()); if (!result) { LOGE << "XML [" << content << "] parsed with errors, attr value: [" << doc.child("node").attribute("attr").value() << "]" << std::endl; LOGE << "Error description: " << result.description() << std::endl; LOGE << "Error offset: " << result.offset << " (error at [..." << (&content[result.offset]) << "]" << std::endl; return ERR_PARSING_FAILED; } const std::string rootTypeName = oObject.GetTypeName(); pugi::xml_node root = doc.child(rootTypeName.c_str()); if (!root) { LOGE << "Failed to find node " << rootTypeName << ". Object not imported." << std::endl; return ERR_PARSING_FAILED; } auto rootDef = Object::GetDefinition(rootTypeName); if (!rootDef) { LOGE << "No definition was declared for object '" << rootTypeName << "'. Object not imported." << std::endl; return ERR_INVALID_PARAMETER; } Error loadResult = _Load(rootDef, root, oObject); return loadResult; } Error SerializableCodecXML::_Load(const std::shared_ptr<ObjectDefinition>& iDefinition, const pugi::xml_node& iNode, Serializable& oObject) const { oObject.BeginLoad(); for (pugi::xml_node_iterator it = iNode.begin(); it != iNode.end(); ++it) { // If the current node is attribute, then it is an attribute for the current object if (std::strcmp(it->name(), "attribute") == 0) { // No need to check for neither if name or value exists, the GetAttribe and then the parsers will fail // if no value where passed std::string attr = it->attribute("name").as_string(); std::string attrVal = it->attribute("value").as_string(); auto attrInfo = iDefinition->GetAttribute(attr); if (attrInfo.IsNull()) { LOGE << "Attribute '" << attr << "' not registered for object '" << iDefinition->GetName() << "', ignored." << std::endl; } else { switch (attrInfo.GetType()) { case Variant::Value::VVT_Bool: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseBool(attrVal))); break; case Variant::Value::VVT_Float: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseFloat(attrVal))); break; case Variant::Value::VVT_String: attrInfo.GetAccessor()->Set(&oObject, Variant(std::string(attrVal))); break; case Variant::Value::VVT_Vector2: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseVector2(attrVal))); break; case Variant::Value::VVT_Vector3: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseVector3(attrVal))); break; case Variant::Value::VVT_Quaternion: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseQuaternion(attrVal))); break; case Variant::Value::VVT_Array: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseArray(it->children()))); break; case Variant::Value::VVT_HashMap: // HashMap in variant for now does support only <string, string> // When the type will evolve in a more complicated/complete version // we will need to revise this parsing attrInfo.GetAccessor()->Set(&oObject, Variant(ParseHashMap(it->children()))); break; case Variant::Value::VVT_SerializablePtr: // If the tag is attribute and the type is shared_ptr<Serializable> // we consider that we expect a collection of SerializablePtr object // the attribute tag being a way to group those elements together if (_ParseCollection(it->children(), attrInfo, oObject) != Error::OK) { LOGE << "[SerializableCodeXML]: Failed to parse collection '" << attr << "'." << std::endl; } break; default: // Should not be here... CH_ASSERT(false); break; } } } else { auto attrInfo = iDefinition->GetAttribute(it->name()); if (attrInfo.IsNull()) { LOGE << "Attribute '" << it->name() << "' not registered for object '" << iDefinition->GetName() << "', ignored." << std::endl; continue; } _LoadObject(it, attrInfo, oObject); } } oObject.EndLoad(); return OK; } Error SerializableCodecXML::_ParseCollection(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren, const AttributeInfo& iAttrInfo, Serializable& oObject) const { Error ret = Error::OK; for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) { ret = _LoadObject(it, iAttrInfo, oObject); if (ret != Error::OK) { LOGE << "[SerializableCodecXML]: Failed to load object '" << it->name() << "'." << std::endl; break; } } return ret; } Error SerializableCodecXML::_LoadObject(const pugi::xml_node_iterator& iNode, const AttributeInfo& iAttrInfo, Serializable& oObject) const { auto def = Object::GetDefinition(iNode->name()); if (!def) { LOGE << "[SerializableCodecXML]: No definition was declared for object '" << iNode->name() << "'. Object not imported." << std::endl; return Error::ERR_PARSING_FAILED; } auto attr = iNode->attribute("path"); // Whatever path we take next, we will need this object std::shared_ptr<Serializable> obj = std::static_pointer_cast<Serializable>(def->Create()); // If it has a path to file, we use the resource loader if (attr) { m_pContext->GetSubsystem<ResourceLoader<Serializable>>()->Load(attr.as_string(), *obj.get()); } else { // Or we load it here // TODO(pierre) All object here can be serializable // but we should add a test. We can at least do a IsA (to be added soon) Error res = _Load(def, *iNode, *obj.get()); if (res != Error::OK) { LOGE << "[SerializableCodecXML]: Failed to import " << iNode->name() << " object. Continuing..." << std::endl; return res; } } iAttrInfo.GetAccessor()->Set(&oObject, Variant(obj)); return Error::OK; } } // namespace CodeHero <commit_msg>Remove unused size variable in serializable xml codec<commit_after>// Copyright (c) 2017 Pierre Fourgeaud // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "drivers/xml/serializablecodec_xml.h" #include "core/enginecontext.h" #include "core/fileaccess.h" #include "core/resourceloader.h" #include "core/serializable.h" #include "core/type_traits/attributeaccessor.h" #include "core/type_traits/objectdefinition.h" #include "core/utils.h" #include <cstring> #include <logger.h> namespace CodeHero { // Standard parsing bool ParseBool(const std::string& iInput) { bool res = false; if (iInput == "true") { res = true; } else if (iInput == "false") { res = false; } else { LOGE << "[SerializableCodecXML]: Faile to parse bool argument: '" << iInput << "' is not valid." << std::endl; } return res; } float ParseFloat(const std::string& iInput) { float res = 0.0f; try { res = std::stof(iInput); } catch (const std::exception& e) { LOGE << "XML: Fail to parse float argument, got: " << e.what() << std::endl; } return res; } Vector2 ParseVector2(const std::string& iInput) { Vector2 res; auto nums = Split(iInput, ' '); if (nums.size() != 2) { LOGE << "[SerializableCodexXML]: Fail to parse Vector2 argument. Got " << nums.size() << " members, expected 2." << std::endl; return res; } try { res.SetX(ParseFloat(nums[0])); res.SetY(ParseFloat(nums[1])); } catch (const std::exception& e) { LOGE << "[SerializableCodexXML]: Fail to parse Vector2 argument, got: " << e.what() << std::endl; } return res; } Vector3 ParseVector3(const std::string& iInput) { Vector3 res; auto nums = Split(iInput, ' '); if (nums.size() != 3) { LOGE << "XML: Fail to parse Vector3 argument. Got " << nums.size() << " members, expected 3." << std::endl; return res; } try { res.SetX(ParseFloat(nums[0])); res.SetY(ParseFloat(nums[1])); res.SetZ(ParseFloat(nums[2])); } catch (const std::exception& e) { LOGE << "XML: Fail to parse Vector3 argument, got: " << e.what() << std::endl; } return res; } Quaternion ParseQuaternion(const std::string& iInput) { Quaternion res; auto nums = Split(iInput, ' '); if (nums.size() == 3) { try { res.FromEulerAngles(ParseFloat(nums[0]), ParseFloat(nums[1]), ParseFloat(nums[2])); } catch (const std::exception& e) { LOGE << "[SerializableCodexXML]: Fail to parse Quaternion argument, got: " << e.what() << std::endl; } } else { LOGE << "[SerializableCodexXML]: Fail to parse Quaternion argument. Got " << nums.size() << " members." << std::endl; } return res; } VariantArray ParseArray(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren) { VariantArray res; for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) { if (std::strcmp(it->name(), "subattribute") == 0) { std::string attrVal = it->attribute("value").as_string(); res.push_back(attrVal); } else { LOGE << "[SerializableCodeXML]: Failed to parse array attribute with name '" << it->name() << "'" << std::endl; } } return std::move(res); } VariantHashMap ParseHashMap(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren) { VariantHashMap res; for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) { if (std::strcmp(it->name(), "subattribute") == 0) { std::string attr = it->attribute("name").as_string(); std::string attrVal = it->attribute("value").as_string(); res[attr] = attrVal; } else { LOGE << "[SerializableCodeXML]: Failed to parse hashmap attribute with name '" << it->name() << "'" << std::endl; } } return std::move(res); } SerializableCodecXML::SerializableCodecXML(const std::shared_ptr<EngineContext>& iContext) : ResourceCodec<Serializable>(iContext) { std::vector<std::string> ext{"xml", "XML"}; for (auto& e : ext) { _AddExtension(e); } } SerializableCodecXML::~SerializableCodecXML() {} Error SerializableCodecXML::Load(FileAccess& iF, Serializable& oObject) { std::string content = iF.ReadAll(); pugi::xml_document doc; pugi::xml_parse_result result = doc.load_string(content.c_str()); if (!result) { LOGE << "XML [" << content << "] parsed with errors, attr value: [" << doc.child("node").attribute("attr").value() << "]" << std::endl; LOGE << "Error description: " << result.description() << std::endl; LOGE << "Error offset: " << result.offset << " (error at [..." << (&content[result.offset]) << "]" << std::endl; return ERR_PARSING_FAILED; } const std::string rootTypeName = oObject.GetTypeName(); pugi::xml_node root = doc.child(rootTypeName.c_str()); if (!root) { LOGE << "Failed to find node " << rootTypeName << ". Object not imported." << std::endl; return ERR_PARSING_FAILED; } auto rootDef = Object::GetDefinition(rootTypeName); if (!rootDef) { LOGE << "No definition was declared for object '" << rootTypeName << "'. Object not imported." << std::endl; return ERR_INVALID_PARAMETER; } Error loadResult = _Load(rootDef, root, oObject); return loadResult; } Error SerializableCodecXML::_Load(const std::shared_ptr<ObjectDefinition>& iDefinition, const pugi::xml_node& iNode, Serializable& oObject) const { oObject.BeginLoad(); for (pugi::xml_node_iterator it = iNode.begin(); it != iNode.end(); ++it) { // If the current node is attribute, then it is an attribute for the current object if (std::strcmp(it->name(), "attribute") == 0) { // No need to check for neither if name or value exists, the GetAttribe and then the parsers will fail // if no value where passed std::string attr = it->attribute("name").as_string(); std::string attrVal = it->attribute("value").as_string(); auto attrInfo = iDefinition->GetAttribute(attr); if (attrInfo.IsNull()) { LOGE << "Attribute '" << attr << "' not registered for object '" << iDefinition->GetName() << "', ignored." << std::endl; } else { switch (attrInfo.GetType()) { case Variant::Value::VVT_Bool: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseBool(attrVal))); break; case Variant::Value::VVT_Float: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseFloat(attrVal))); break; case Variant::Value::VVT_String: attrInfo.GetAccessor()->Set(&oObject, Variant(std::string(attrVal))); break; case Variant::Value::VVT_Vector2: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseVector2(attrVal))); break; case Variant::Value::VVT_Vector3: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseVector3(attrVal))); break; case Variant::Value::VVT_Quaternion: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseQuaternion(attrVal))); break; case Variant::Value::VVT_Array: attrInfo.GetAccessor()->Set(&oObject, Variant(ParseArray(it->children()))); break; case Variant::Value::VVT_HashMap: // HashMap in variant for now does support only <string, string> // When the type will evolve in a more complicated/complete version // we will need to revise this parsing attrInfo.GetAccessor()->Set(&oObject, Variant(ParseHashMap(it->children()))); break; case Variant::Value::VVT_SerializablePtr: // If the tag is attribute and the type is shared_ptr<Serializable> // we consider that we expect a collection of SerializablePtr object // the attribute tag being a way to group those elements together if (_ParseCollection(it->children(), attrInfo, oObject) != Error::OK) { LOGE << "[SerializableCodeXML]: Failed to parse collection '" << attr << "'." << std::endl; } break; default: // Should not be here... CH_ASSERT(false); break; } } } else { auto attrInfo = iDefinition->GetAttribute(it->name()); if (attrInfo.IsNull()) { LOGE << "Attribute '" << it->name() << "' not registered for object '" << iDefinition->GetName() << "', ignored." << std::endl; continue; } _LoadObject(it, attrInfo, oObject); } } oObject.EndLoad(); return OK; } Error SerializableCodecXML::_ParseCollection(const pugi::xml_object_range<pugi::xml_node_iterator>& iChildren, const AttributeInfo& iAttrInfo, Serializable& oObject) const { Error ret = Error::OK; for (pugi::xml_node_iterator it = iChildren.begin(); it != iChildren.end(); ++it) { ret = _LoadObject(it, iAttrInfo, oObject); if (ret != Error::OK) { LOGE << "[SerializableCodecXML]: Failed to load object '" << it->name() << "'." << std::endl; break; } } return ret; } Error SerializableCodecXML::_LoadObject(const pugi::xml_node_iterator& iNode, const AttributeInfo& iAttrInfo, Serializable& oObject) const { auto def = Object::GetDefinition(iNode->name()); if (!def) { LOGE << "[SerializableCodecXML]: No definition was declared for object '" << iNode->name() << "'. Object not imported." << std::endl; return Error::ERR_PARSING_FAILED; } auto attr = iNode->attribute("path"); // Whatever path we take next, we will need this object std::shared_ptr<Serializable> obj = std::static_pointer_cast<Serializable>(def->Create()); // If it has a path to file, we use the resource loader if (attr) { m_pContext->GetSubsystem<ResourceLoader<Serializable>>()->Load(attr.as_string(), *obj.get()); } else { // Or we load it here // TODO(pierre) All object here can be serializable // but we should add a test. We can at least do a IsA (to be added soon) Error res = _Load(def, *iNode, *obj.get()); if (res != Error::OK) { LOGE << "[SerializableCodecXML]: Failed to import " << iNode->name() << " object. Continuing..." << std::endl; return res; } } iAttrInfo.GetAccessor()->Set(&oObject, Variant(obj)); return Error::OK; } } // namespace CodeHero <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: salogl.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2005-01-18 15:17:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source 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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALOGL_H #include <salogl.h> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> using namespace rtl; // ------------ // - Lib-Name - // ------------ #ifdef MACOSX #define OGL_LIBNAME "libGL.dylib" #else #define OGL_LIBNAME "libGL.so.1" #endif // ---------- // - Macros - // ---------- // ----------------- // - Statics init. - // ----------------- // Members GLXContext X11SalOpenGL::maGLXContext = 0; Display* X11SalOpenGL::mpDisplay = 0; XVisualInfo* X11SalOpenGL::mpVisualInfo = 0; BOOL X11SalOpenGL::mbHaveGLVisual = FALSE; oslModule X11SalOpenGL::mpGLLib = 0; #ifdef SOLARIS oslModule aMotifLib; #endif ULONG X11SalOpenGL::mnOGLState = OGL_STATE_UNLOADED; GLXContext (*X11SalOpenGL::pCreateContext)( Display *, XVisualInfo *, GLXContext, Bool ) = 0; void (*X11SalOpenGL::pDestroyContext)( Display *, GLXContext ) = 0; GLXContext (*X11SalOpenGL::pGetCurrentContext)( ) = 0; Bool (*X11SalOpenGL::pMakeCurrent)( Display *, GLXDrawable, GLXContext ) = 0; void (*X11SalOpenGL::pSwapBuffers)( Display*, GLXDrawable ) = 0; int (*X11SalOpenGL::pGetConfig)( Display*, XVisualInfo*, int, int* ) = 0; void (*X11SalOpenGL::pFlush)() = 0; // ------------- // - X11SalOpenGL - // ------------- X11SalOpenGL::X11SalOpenGL( SalGraphics* pSGraphics ) { X11SalGraphics* pGraphics = static_cast<X11SalGraphics*>(pSGraphics); mpDisplay = pGraphics->GetXDisplay(); mpVisualInfo = pGraphics->GetDisplay()->GetVisual(); maDrawable = pGraphics->GetDrawable(); } // ------------------------------------------------------------------------ X11SalOpenGL::~X11SalOpenGL() { } // ------------------------------------------------------------------------ bool X11SalOpenGL::IsValid() { if( OGL_STATE_UNLOADED == mnOGLState ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions; if( *DisplayString( mpDisplay ) == ':' || ! strncmp( DisplayString( mpDisplay ), "localhost:", 10 ) ) { // GLX only on local displays due to strange problems // with remote GLX ppExtensions = XListExtensions( mpDisplay, &nExtensions ); for( int i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); #if OSL_DEBUG_LEVEL > 1 if( ! bHasGLX ) fprintf( stderr, "XServer does not support GLX extension\n" ); #endif if( bHasGLX ) { /* * #82406# the XFree4.0 GLX module does not seem * to work that great, at least not the one that comes * with the default installation and Matrox cards. * Since these are common we disable usage of * OpenGL per default. */ static const char* pOverrideGLX = getenv( "SAL_ENABLE_GLX_XFREE4" ); if( ! strncmp( ServerVendor( mpDisplay ), "The XFree86 Project, Inc", 24 ) && VendorRelease( mpDisplay ) >= 4000 && ! pOverrideGLX ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "disabling GLX usage on XFree >= 4.0\n" ); #endif bHasGLX = FALSE; } } } if( bHasGLX && mpVisualInfo->c_class == TrueColor && ImplInit() ) { int nDoubleBuffer = 0; int nHaveGL = 0; pGetConfig( mpDisplay, mpVisualInfo, GLX_USE_GL, &nHaveGL ); pGetConfig( mpDisplay, mpVisualInfo, GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { SalDisplay* pSalDisplay = GetSalData()->GetDisplay(); BOOL bPreviousState = pSalDisplay->GetXLib()->GetIgnoreXErrors(); pSalDisplay->GetXLib()->SetIgnoreXErrors( TRUE ); mbHaveGLVisual = TRUE; maGLXContext = pCreateContext( mpDisplay, mpVisualInfo, 0, True ); if( pSalDisplay->GetXLib()->WasXError() ) mbHaveGLVisual = FALSE; else pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); if( pSalDisplay->GetXLib()->WasXError() ) mbHaveGLVisual = FALSE; pSalDisplay->GetXLib()->SetIgnoreXErrors( bPreviousState ); if( mbHaveGLVisual ) mnOGLState = OGL_STATE_VALID; else maGLXContext = None; } } if( mnOGLState != OGL_STATE_VALID ) mnOGLState = OGL_STATE_INVALID; #if OSL_DEBUG_LEVEL > 1 if( mnOGLState == OGL_STATE_VALID ) fprintf( stderr, "Using GLX on visual id %x.\n", mpVisualInfo->visualid ); else fprintf( stderr, "Not using GLX.\n" ); #endif } return mnOGLState == OGL_STATE_VALID ? TRUE : FALSE; } void X11SalOpenGL::Release() { if( maGLXContext && pDestroyContext ) pDestroyContext( mpDisplay, maGLXContext ); } // ------------------------------------------------------------------------ void X11SalOpenGL::ReleaseLib() { if( mpGLLib ) { osl_unloadModule( mpGLLib ); #ifdef SOLARIS if( aMotifLib ) osl_unloadModule( aMotifLib ); #endif mpGLLib = 0; pCreateContext = 0; pDestroyContext = 0; pGetCurrentContext = 0; pMakeCurrent = 0; pSwapBuffers = 0; pGetConfig = 0; mnOGLState = OGL_STATE_UNLOADED; } } // ------------------------------------------------------------------------ void* X11SalOpenGL::GetOGLFnc( const char *pFncName ) { return resolveSymbol( pFncName ); } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLEntry( SalGraphics* pGraphics ) { GLXDrawable aDrawable = static_cast<X11SalGraphics*>(pGraphics)->GetDrawable(); if( aDrawable != maDrawable ) { maDrawable = aDrawable; pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); } } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLExit( SalGraphics* pGraphics ) { } // ------------------------------------------------------------------------ void* X11SalOpenGL::resolveSymbol( const char* pSymbol ) { void* pSym = NULL; if( mpGLLib ) { OUString aSym = OUString::createFromAscii( pSymbol ); pSym = osl_getSymbol( mpGLLib, aSym.pData ); } return pSym; } BOOL X11SalOpenGL::ImplInit() { if( ! mpGLLib ) { ByteString sNoGL( getenv( "SAL_NOOPENGL" ) ); if( sNoGL.ToLowerAscii() == "true" ) return FALSE; sal_Int32 nRtldMode = SAL_LOADMODULE_NOW; #ifdef SOLARIS /* #i36866# an obscure interaction with jvm can let java crash * if we do not use SAL_LOADMODULE_GLOBAL here */ nRtldMode |= SAL_LOADMODULE_GLOBAL; /* #i36899# and we need Xm, too, else jvm will not work properly. */ OUString aMotifName( RTL_CONSTASCII_USTRINGPARAM( "libXm.so" ) ); aMotifLib = osl_loadModule( aMotifName.pData, nRtldMode ); #endif OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( OGL_LIBNAME ) ); mpGLLib = osl_loadModule( aLibName.pData, nRtldMode ); } if( ! mpGLLib ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, OGL_LIBNAME "could not be opened\n" ); #endif return FALSE; } // Internal use pCreateContext = (GLXContext(*)(Display*,XVisualInfo*,GLXContext,Bool )) resolveSymbol( "glXCreateContext" ); pDestroyContext = (void(*)(Display*,GLXContext)) resolveSymbol( "glXDestroyContext" ); pGetCurrentContext = (GLXContext(*)()) resolveSymbol( "glXGetCurrentContext" ); pMakeCurrent = (Bool(*)(Display*,GLXDrawable,GLXContext)) resolveSymbol( "glXMakeCurrent" ); pSwapBuffers=(void(*)(Display*, GLXDrawable)) resolveSymbol( "glXSwapBuffers" ); pGetConfig = (int(*)(Display*, XVisualInfo*, int, int* )) resolveSymbol( "glXGetConfig" ); pFlush = (void(*)()) resolveSymbol( "glFlush" ); BOOL bRet = pCreateContext && pDestroyContext && pGetCurrentContext && pMakeCurrent && pSwapBuffers && pGetConfig ? TRUE : FALSE; #if OSL_DEBUG_LEVEL > 1 if( ! bRet ) fprintf( stderr, "could not find all needed symbols in " OGL_LIBNAME "\n" ); #endif return bRet; } void X11SalOpenGL::StartScene( SalGraphics* pGraphics ) { // flush pending operations which otherwise might be drawn // at the wrong time XSync( mpDisplay, False ); } void X11SalOpenGL::StopScene() { if( maDrawable ) { pSwapBuffers( mpDisplay, maDrawable ); pFlush(); } } void X11SalOpenGL::MakeVisualWeights( Display* pDisplay, XVisualInfo* pInfos, int *pWeights, int nVisuals ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions,i ; // GLX only on local displays due to strange problems // with remote GLX if( ! ( *DisplayString( pDisplay ) == ':' || !strncmp( DisplayString( pDisplay ), "localhost:", 10 ) ) ) return; ppExtensions = XListExtensions( pDisplay, &nExtensions ); for( i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); if( ! bHasGLX ) return; if( ! ImplInit() ) return; for( i = 0; i < nVisuals; i++ ) { int nDoubleBuffer = 0; int nHaveGL = 0; // a weight lesser than zero indicates an invalid visual (wrong screen) if( pInfos[i].c_class == TrueColor && pWeights[i] >= 0) { pGetConfig( pDisplay, &pInfos[ i ], GLX_USE_GL, &nHaveGL ); pGetConfig( pDisplay, &pInfos[ i ], GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { mbHaveGLVisual = TRUE; pWeights[ i ] += 65536; } } } } <commit_msg>INTEGRATION: CWS vcl38 (1.13.64); FILE MERGED 2005/03/10 11:27:37 pl 1.13.64.1: #i44630# avoid 8 bit truecolor visuals<commit_after>/************************************************************************* * * $RCSfile: salogl.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: rt $ $Date: 2005-03-30 09:09:42 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source 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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALOGL_H #include <salogl.h> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> using namespace rtl; // ------------ // - Lib-Name - // ------------ #ifdef MACOSX #define OGL_LIBNAME "libGL.dylib" #else #define OGL_LIBNAME "libGL.so.1" #endif // ---------- // - Macros - // ---------- // ----------------- // - Statics init. - // ----------------- // Members GLXContext X11SalOpenGL::maGLXContext = 0; Display* X11SalOpenGL::mpDisplay = 0; XVisualInfo* X11SalOpenGL::mpVisualInfo = 0; BOOL X11SalOpenGL::mbHaveGLVisual = FALSE; oslModule X11SalOpenGL::mpGLLib = 0; #ifdef SOLARIS oslModule aMotifLib; #endif ULONG X11SalOpenGL::mnOGLState = OGL_STATE_UNLOADED; GLXContext (*X11SalOpenGL::pCreateContext)( Display *, XVisualInfo *, GLXContext, Bool ) = 0; void (*X11SalOpenGL::pDestroyContext)( Display *, GLXContext ) = 0; GLXContext (*X11SalOpenGL::pGetCurrentContext)( ) = 0; Bool (*X11SalOpenGL::pMakeCurrent)( Display *, GLXDrawable, GLXContext ) = 0; void (*X11SalOpenGL::pSwapBuffers)( Display*, GLXDrawable ) = 0; int (*X11SalOpenGL::pGetConfig)( Display*, XVisualInfo*, int, int* ) = 0; void (*X11SalOpenGL::pFlush)() = 0; // ------------- // - X11SalOpenGL - // ------------- X11SalOpenGL::X11SalOpenGL( SalGraphics* pSGraphics ) { X11SalGraphics* pGraphics = static_cast<X11SalGraphics*>(pSGraphics); mpDisplay = pGraphics->GetXDisplay(); mpVisualInfo = pGraphics->GetDisplay()->GetVisual(); maDrawable = pGraphics->GetDrawable(); } // ------------------------------------------------------------------------ X11SalOpenGL::~X11SalOpenGL() { } // ------------------------------------------------------------------------ bool X11SalOpenGL::IsValid() { if( OGL_STATE_UNLOADED == mnOGLState ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions; if( *DisplayString( mpDisplay ) == ':' || ! strncmp( DisplayString( mpDisplay ), "localhost:", 10 ) ) { // GLX only on local displays due to strange problems // with remote GLX ppExtensions = XListExtensions( mpDisplay, &nExtensions ); for( int i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); #if OSL_DEBUG_LEVEL > 1 if( ! bHasGLX ) fprintf( stderr, "XServer does not support GLX extension\n" ); #endif if( bHasGLX ) { /* * #82406# the XFree4.0 GLX module does not seem * to work that great, at least not the one that comes * with the default installation and Matrox cards. * Since these are common we disable usage of * OpenGL per default. */ static const char* pOverrideGLX = getenv( "SAL_ENABLE_GLX_XFREE4" ); if( ! strncmp( ServerVendor( mpDisplay ), "The XFree86 Project, Inc", 24 ) && VendorRelease( mpDisplay ) >= 4000 && ! pOverrideGLX ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "disabling GLX usage on XFree >= 4.0\n" ); #endif bHasGLX = FALSE; } } } if( bHasGLX && mpVisualInfo->c_class == TrueColor && ImplInit() ) { int nDoubleBuffer = 0; int nHaveGL = 0; pGetConfig( mpDisplay, mpVisualInfo, GLX_USE_GL, &nHaveGL ); pGetConfig( mpDisplay, mpVisualInfo, GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { SalDisplay* pSalDisplay = GetSalData()->GetDisplay(); BOOL bPreviousState = pSalDisplay->GetXLib()->GetIgnoreXErrors(); pSalDisplay->GetXLib()->SetIgnoreXErrors( TRUE ); mbHaveGLVisual = TRUE; maGLXContext = pCreateContext( mpDisplay, mpVisualInfo, 0, True ); if( pSalDisplay->GetXLib()->WasXError() ) mbHaveGLVisual = FALSE; else pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); if( pSalDisplay->GetXLib()->WasXError() ) mbHaveGLVisual = FALSE; pSalDisplay->GetXLib()->SetIgnoreXErrors( bPreviousState ); if( mbHaveGLVisual ) mnOGLState = OGL_STATE_VALID; else maGLXContext = None; } } if( mnOGLState != OGL_STATE_VALID ) mnOGLState = OGL_STATE_INVALID; #if OSL_DEBUG_LEVEL > 1 if( mnOGLState == OGL_STATE_VALID ) fprintf( stderr, "Using GLX on visual id %x.\n", mpVisualInfo->visualid ); else fprintf( stderr, "Not using GLX.\n" ); #endif } return mnOGLState == OGL_STATE_VALID ? TRUE : FALSE; } void X11SalOpenGL::Release() { if( maGLXContext && pDestroyContext ) pDestroyContext( mpDisplay, maGLXContext ); } // ------------------------------------------------------------------------ void X11SalOpenGL::ReleaseLib() { if( mpGLLib ) { osl_unloadModule( mpGLLib ); #ifdef SOLARIS if( aMotifLib ) osl_unloadModule( aMotifLib ); #endif mpGLLib = 0; pCreateContext = 0; pDestroyContext = 0; pGetCurrentContext = 0; pMakeCurrent = 0; pSwapBuffers = 0; pGetConfig = 0; mnOGLState = OGL_STATE_UNLOADED; } } // ------------------------------------------------------------------------ void* X11SalOpenGL::GetOGLFnc( const char *pFncName ) { return resolveSymbol( pFncName ); } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLEntry( SalGraphics* pGraphics ) { GLXDrawable aDrawable = static_cast<X11SalGraphics*>(pGraphics)->GetDrawable(); if( aDrawable != maDrawable ) { maDrawable = aDrawable; pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); } } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLExit( SalGraphics* pGraphics ) { } // ------------------------------------------------------------------------ void* X11SalOpenGL::resolveSymbol( const char* pSymbol ) { void* pSym = NULL; if( mpGLLib ) { OUString aSym = OUString::createFromAscii( pSymbol ); pSym = osl_getSymbol( mpGLLib, aSym.pData ); } return pSym; } BOOL X11SalOpenGL::ImplInit() { if( ! mpGLLib ) { ByteString sNoGL( getenv( "SAL_NOOPENGL" ) ); if( sNoGL.ToLowerAscii() == "true" ) return FALSE; sal_Int32 nRtldMode = SAL_LOADMODULE_NOW; #ifdef SOLARIS /* #i36866# an obscure interaction with jvm can let java crash * if we do not use SAL_LOADMODULE_GLOBAL here */ nRtldMode |= SAL_LOADMODULE_GLOBAL; /* #i36899# and we need Xm, too, else jvm will not work properly. */ OUString aMotifName( RTL_CONSTASCII_USTRINGPARAM( "libXm.so" ) ); aMotifLib = osl_loadModule( aMotifName.pData, nRtldMode ); #endif OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( OGL_LIBNAME ) ); mpGLLib = osl_loadModule( aLibName.pData, nRtldMode ); } if( ! mpGLLib ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, OGL_LIBNAME "could not be opened\n" ); #endif return FALSE; } // Internal use pCreateContext = (GLXContext(*)(Display*,XVisualInfo*,GLXContext,Bool )) resolveSymbol( "glXCreateContext" ); pDestroyContext = (void(*)(Display*,GLXContext)) resolveSymbol( "glXDestroyContext" ); pGetCurrentContext = (GLXContext(*)()) resolveSymbol( "glXGetCurrentContext" ); pMakeCurrent = (Bool(*)(Display*,GLXDrawable,GLXContext)) resolveSymbol( "glXMakeCurrent" ); pSwapBuffers=(void(*)(Display*, GLXDrawable)) resolveSymbol( "glXSwapBuffers" ); pGetConfig = (int(*)(Display*, XVisualInfo*, int, int* )) resolveSymbol( "glXGetConfig" ); pFlush = (void(*)()) resolveSymbol( "glFlush" ); BOOL bRet = pCreateContext && pDestroyContext && pGetCurrentContext && pMakeCurrent && pSwapBuffers && pGetConfig ? TRUE : FALSE; #if OSL_DEBUG_LEVEL > 1 if( ! bRet ) fprintf( stderr, "could not find all needed symbols in " OGL_LIBNAME "\n" ); #endif return bRet; } void X11SalOpenGL::StartScene( SalGraphics* pGraphics ) { // flush pending operations which otherwise might be drawn // at the wrong time XSync( mpDisplay, False ); } void X11SalOpenGL::StopScene() { if( maDrawable ) { pSwapBuffers( mpDisplay, maDrawable ); pFlush(); } } void X11SalOpenGL::MakeVisualWeights( Display* pDisplay, XVisualInfo* pInfos, int *pWeights, int nVisuals ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions,i ; // GLX only on local displays due to strange problems // with remote GLX if( ! ( *DisplayString( pDisplay ) == ':' || !strncmp( DisplayString( pDisplay ), "localhost:", 10 ) ) ) return; ppExtensions = XListExtensions( pDisplay, &nExtensions ); for( i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); if( ! bHasGLX ) return; if( ! ImplInit() ) return; for( i = 0; i < nVisuals; i++ ) { int nDoubleBuffer = 0; int nHaveGL = 0; // a weight lesser than zero indicates an invalid visual (wrong screen) if( pInfos[i].c_class == TrueColor && pInfos[i].depth > 14 && pWeights[i] >= 0) { pGetConfig( pDisplay, &pInfos[ i ], GLX_USE_GL, &nHaveGL ); pGetConfig( pDisplay, &pInfos[ i ], GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { mbHaveGLVisual = TRUE; pWeights[ i ] += 65536; } } } } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2016 Haggi Krey, The appleseedhq Organization // // 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. // // Interface header. #include "shadingnode.h" // appleseed-maya headers. #include "utilities/logging.h" #include "utilities/tools.h" #include "utilities/pystring.h" // Maya headers. #include <maya/MPlugArray.h> ShadingNode::ShadingNode() { } ShadingNode::ShadingNode(const MObject& mobj) { setMObject(mobj); } ShadingNode::ShadingNode(const ShadingNode& other) : inputAttributes(other.inputAttributes) , outputAttributes(other.outputAttributes) { setMObject(other.mobject); } void ShadingNode::setMObject(const MObject& mobj) { mobject = mobj; if (mobject != MObject::kNullObj) { typeName = getDepNodeTypeName(mobject); fullName = getObjectName(mobject); } } bool ShadingNode::isInPlugValid(const MPlug& plug) const { MPlug tmpPlug = plug; if (!tmpPlug.isDestination()) return false; while (tmpPlug.isChild()) tmpPlug = tmpPlug.parent(); // if we have an array, check the main plug if (tmpPlug.isElement()) tmpPlug = tmpPlug.array(); const MString& plugName = getAttributeNameFromPlug(tmpPlug); for (size_t inattrId = 0; inattrId < inputAttributes.size(); inattrId++) { if (plugName == inputAttributes[inattrId].name.c_str()) return true; } return false; } bool ShadingNode::isOutPlugValid(const MPlug& plug) const { MPlug tmpPlug = plug; if (!tmpPlug.isSource()) return false; while (tmpPlug.isChild()) tmpPlug = tmpPlug.parent(); // if we have an array, check the main plug if (tmpPlug.isElement()) tmpPlug = tmpPlug.array(); MString plugName = getAttributeNameFromPlug(tmpPlug); for (size_t attrId = 0; attrId < outputAttributes.size(); attrId++) { if (plugName == outputAttributes[attrId].name.c_str()) return true; } return false; } bool ShadingNode::isAttributeValid(const MString& attributeName) const { MFnDependencyNode depFn(mobject); MPlugArray pa; depFn.getConnections(pa); for (uint pId = 0; pId < pa.length(); pId++) { if (pa[pId].isDestination()) { MPlug parentPlug = pa[pId]; while (parentPlug.isChild()) parentPlug = parentPlug.parent(); MString plugName = getAttributeNameFromPlug(parentPlug); if (plugName == attributeName) { for (size_t inattrId = 0; inattrId < inputAttributes.size(); inattrId++) { if (attributeName == inputAttributes[inattrId].name.c_str()) return true; } } } } return false; } void ShadingNode::getConnectedInputObjects(MObjectArray& objectArray) const { MStatus stat; MFnDependencyNode depFn(mobject); MStringArray aliasArray; depFn.getAliasList(aliasArray); MObjectArray objectList; MPlugArray connections; depFn.getConnections(connections); for (uint connId = 0; connId < connections.length(); connId++) { MPlug p = connections[connId]; if (!p.isDestination()) continue; // a connection can be a direct connection or a child connection e.g. colorR, colorG... // but in a shader description file only the main attribute is listed so we go up until we have the main plug MPlug mainPlug = p; while (mainPlug.isChild()) mainPlug = mainPlug.parent(); if (mainPlug.isElement()) mainPlug = mainPlug.array(); MStringArray stringArray; // name contains node.attributeName, so we have to get rid of the nodeName mainPlug.name().split('.', stringArray); MString plugName = stringArray[stringArray.length() - 1]; if (!isAttributeValid(plugName)) continue; getConnectedInNodes(p, objectList); makeUniqueArray(objectList); } objectArray = objectList; } <commit_msg>Fix the copy constructor<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2016 Haggi Krey, The appleseedhq Organization // // 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. // // Interface header. #include "shadingnode.h" // appleseed-maya headers. #include "utilities/logging.h" #include "utilities/tools.h" #include "utilities/pystring.h" // Maya headers. #include <maya/MPlugArray.h> ShadingNode::ShadingNode() { } ShadingNode::ShadingNode(const MObject& mobj) { setMObject(mobj); } ShadingNode::ShadingNode(const ShadingNode& other) : inputAttributes(other.inputAttributes) , outputAttributes(other.outputAttributes) { typeName = other.typeName; fullName = other.fullName; setMObject(other.mobject); } void ShadingNode::setMObject(const MObject& mobj) { mobject = mobj; if (mobject != MObject::kNullObj) { typeName = getDepNodeTypeName(mobject); fullName = getObjectName(mobject); } } bool ShadingNode::isInPlugValid(const MPlug& plug) const { MPlug tmpPlug = plug; if (!tmpPlug.isDestination()) return false; while (tmpPlug.isChild()) tmpPlug = tmpPlug.parent(); // if we have an array, check the main plug if (tmpPlug.isElement()) tmpPlug = tmpPlug.array(); const MString& plugName = getAttributeNameFromPlug(tmpPlug); for (size_t inattrId = 0; inattrId < inputAttributes.size(); inattrId++) { if (plugName == inputAttributes[inattrId].name.c_str()) return true; } return false; } bool ShadingNode::isOutPlugValid(const MPlug& plug) const { MPlug tmpPlug = plug; if (!tmpPlug.isSource()) return false; while (tmpPlug.isChild()) tmpPlug = tmpPlug.parent(); // if we have an array, check the main plug if (tmpPlug.isElement()) tmpPlug = tmpPlug.array(); MString plugName = getAttributeNameFromPlug(tmpPlug); for (size_t attrId = 0; attrId < outputAttributes.size(); attrId++) { if (plugName == outputAttributes[attrId].name.c_str()) return true; } return false; } bool ShadingNode::isAttributeValid(const MString& attributeName) const { MFnDependencyNode depFn(mobject); MPlugArray pa; depFn.getConnections(pa); for (uint pId = 0; pId < pa.length(); pId++) { if (pa[pId].isDestination()) { MPlug parentPlug = pa[pId]; while (parentPlug.isChild()) parentPlug = parentPlug.parent(); MString plugName = getAttributeNameFromPlug(parentPlug); if (plugName == attributeName) { for (size_t inattrId = 0; inattrId < inputAttributes.size(); inattrId++) { if (attributeName == inputAttributes[inattrId].name.c_str()) return true; } } } } return false; } void ShadingNode::getConnectedInputObjects(MObjectArray& objectArray) const { MStatus stat; MFnDependencyNode depFn(mobject); MStringArray aliasArray; depFn.getAliasList(aliasArray); MObjectArray objectList; MPlugArray connections; depFn.getConnections(connections); for (uint connId = 0; connId < connections.length(); connId++) { MPlug p = connections[connId]; if (!p.isDestination()) continue; // a connection can be a direct connection or a child connection e.g. colorR, colorG... // but in a shader description file only the main attribute is listed so we go up until we have the main plug MPlug mainPlug = p; while (mainPlug.isChild()) mainPlug = mainPlug.parent(); if (mainPlug.isElement()) mainPlug = mainPlug.array(); MStringArray stringArray; // name contains node.attributeName, so we have to get rid of the nodeName mainPlug.name().split('.', stringArray); MString plugName = stringArray[stringArray.length() - 1]; if (!isAttributeValid(plugName)) continue; getConnectedInNodes(p, objectList); makeUniqueArray(objectList); } objectArray = objectList; } <|endoftext|>
<commit_before>#include "sipclienttransaction.h" #include "siptransactionuser.h" #include <QDebug> // 2 seconds for a SIP reply const unsigned int TIMEOUT = 2000; // 1 minute for the user to react const unsigned int INVITE_TIMEOUT = 60000; SIPClientTransaction::SIPClientTransaction(): ongoingTransactionType_(SIP_UNKNOWN_REQUEST), connected_(false), sessionID_(0), state_(INACTIVE), pendingRequest_(SIP_UNKNOWN_REQUEST), transactionUser_(NULL) {} void SIPClientTransaction::init(SIPTransactionUser* tu, uint32_t sessionID) { Q_ASSERT(sessionID != 0); Q_ASSERT(tu); transactionUser_ = tu; sessionID_ = sessionID; requestTimer_.setSingleShot(true); connect(&requestTimer_, SIGNAL(timeout()), this, SLOT(requestTimeOut())); } //processes incoming response bool SIPClientTransaction::processResponse(SIPResponse &response) { Q_ASSERT(sessionID_ != 0); Q_ASSERT(transactionUser_ != NULL); if(!sessionID_ || transactionUser_ == NULL) { qWarning() << "WARNING: SIP Client Transaction not initialized."; return true; } int responseCode = response.type; if(responseCode >= 300 && responseCode <= 399) { // TODO: 8.1.3.4 Processing 3xx Responses in RFC 3261 qDebug() << "Got a redirection response Code. Not implemented!"; return false; } if(responseCode >= 400 && responseCode <= 499) { // TODO: 8.1.3.5 Processing 4xx Responses in RFC 3261 qDebug() << "Got a Client Failure Response Code. Not implemented!"; // TODO: if the response is 481 or 408, terminate dialog return false; } if(responseCode >= 500 && responseCode <= 599) { qDebug() << "Got a Server Failure Response Code. Not implemented!"; return false; } if(ongoingTransactionType_ == INVITE) { if(responseCode >= 600 && responseCode <= 699) { qDebug() << "Got a Global Failure Response Code for INVITE"; transactionUser_->callRejected(sessionID_); return false; } else { switch (response.type) { case SIP_RINGING: transactionUser_->callRinging(sessionID_); break; case SIP_OK: break; // TODO: check that SDP is alright with us and negotiate transactionUser_->callNegotiated(sessionID_); requestSender(ACK); default: break; } } } if(responseCode >= 200) { ongoingTransactionType_ = SIP_UNKNOWN_REQUEST; } return true; } bool SIPClientTransaction::startCall() { qDebug() << "Starting a call and sending an INVITE in session"; Q_ASSERT(sessionID_ != 0); if(!sessionID_) { qWarning() << "WARNING: SIP Client Transaction not initialized"; return false; } if(state_ == INACTIVE) { requestSender(INVITE); } else { qWarning() << "WARNING: Trying to start a call, when it is already running or negotiating:" << state_; return false; } return true; } void SIPClientTransaction::endCall() { if(state_ != RUNNNING) { qDebug() << "WARNING: Trying to end a non-active call!"; return; } requestSender(BYE); } void SIPClientTransaction::registerToServer() { requestSender(REGISTER); } void SIPClientTransaction::connectionReady(bool ready) { connected_ = ready; if(pendingRequest_ != SIP_UNKNOWN_REQUEST) { requestSender(pendingRequest_); pendingRequest_ = SIP_UNKNOWN_REQUEST; } } void SIPClientTransaction::getRequestMessageInfo(RequestType type, std::shared_ptr<SIPMessageInfo>& outMessage) { outMessage = std::shared_ptr<SIPMessageInfo> (new SIPMessageInfo); if(type == ACK) { outMessage->transactionRequest = INVITE; } else if(type == CANCEL) { outMessage->transactionRequest = ongoingTransactionType_; } else { outMessage->transactionRequest = type; } outMessage->dialog = NULL; outMessage->maxForwards = 71; outMessage->version = "2.0"; outMessage->cSeq = 0; // INVALID, should be set in dialog } void SIPClientTransaction::requestSender(RequestType type) { if(!connected_) { pendingRequest_ = type; } else { ongoingTransactionType_ = type; emit sendRequest(sessionID_, type); if(type != INVITE) { qDebug() << "Request timeout set to: " << TIMEOUT; requestTimer_.start(TIMEOUT); } else { qDebug() << "INVITE timeout set to: " << INVITE_TIMEOUT; requestTimer_.start(INVITE_TIMEOUT); } } } void SIPClientTransaction::requestTimeOut() { qDebug() << "No response. Request timed out"; if(ongoingTransactionType_ == INVITE) { sendRequest(sessionID_, BYE); // TODO tell user we have failed } requestSender(CANCEL); transactionUser_->callRejected(sessionID_); ongoingTransactionType_ = SIP_UNKNOWN_REQUEST; } <commit_msg>Send ACK before starting call.<commit_after>#include "sipclienttransaction.h" #include "siptransactionuser.h" #include <QDebug> // 2 seconds for a SIP reply const unsigned int TIMEOUT = 2000; // 1 minute for the user to react const unsigned int INVITE_TIMEOUT = 60000; SIPClientTransaction::SIPClientTransaction(): ongoingTransactionType_(SIP_UNKNOWN_REQUEST), connected_(false), sessionID_(0), state_(INACTIVE), pendingRequest_(SIP_UNKNOWN_REQUEST), transactionUser_(NULL) {} void SIPClientTransaction::init(SIPTransactionUser* tu, uint32_t sessionID) { Q_ASSERT(sessionID != 0); Q_ASSERT(tu); transactionUser_ = tu; sessionID_ = sessionID; requestTimer_.setSingleShot(true); connect(&requestTimer_, SIGNAL(timeout()), this, SLOT(requestTimeOut())); } //processes incoming response bool SIPClientTransaction::processResponse(SIPResponse &response) { Q_ASSERT(sessionID_ != 0); Q_ASSERT(transactionUser_ != NULL); qDebug() << "Client starts processing response"; if(!sessionID_ || transactionUser_ == NULL) { qWarning() << "WARNING: SIP Client Transaction not initialized."; return true; } int responseCode = response.type; if(responseCode >= 300 && responseCode <= 399) { // TODO: 8.1.3.4 Processing 3xx Responses in RFC 3261 qDebug() << "Got a redirection response Code. Not implemented!"; return false; } if(responseCode >= 400 && responseCode <= 499) { // TODO: 8.1.3.5 Processing 4xx Responses in RFC 3261 qDebug() << "Got a Client Failure Response Code. Not implemented!"; // TODO: if the response is 481 or 408, terminate dialog return false; } if(responseCode >= 500 && responseCode <= 599) { qDebug() << "Got a Server Failure Response Code. Not implemented!"; return false; } if(ongoingTransactionType_ == INVITE) { if(responseCode >= 600 && responseCode <= 699) { qDebug() << "Got a Global Failure Response Code for INVITE"; transactionUser_->callRejected(sessionID_); return false; } else { switch (response.type) { case SIP_RINGING: transactionUser_->callRinging(sessionID_); break; case SIP_OK: // the sdp has been check by transaction layer before this. requestSender(ACK); transactionUser_->callNegotiated(sessionID_); break; default: break; } } } if(responseCode >= 200) { ongoingTransactionType_ = SIP_UNKNOWN_REQUEST; } return true; } bool SIPClientTransaction::startCall() { qDebug() << "Starting a call and sending an INVITE in session"; Q_ASSERT(sessionID_ != 0); if(!sessionID_) { qWarning() << "WARNING: SIP Client Transaction not initialized"; return false; } if(state_ == INACTIVE) { requestSender(INVITE); } else { qWarning() << "WARNING: Trying to start a call, when it is already running or negotiating:" << state_; return false; } return true; } void SIPClientTransaction::endCall() { if(state_ != RUNNNING) { qDebug() << "WARNING: Trying to end a non-active call!"; return; } requestSender(BYE); } void SIPClientTransaction::registerToServer() { requestSender(REGISTER); } void SIPClientTransaction::connectionReady(bool ready) { connected_ = ready; if(pendingRequest_ != SIP_UNKNOWN_REQUEST) { requestSender(pendingRequest_); pendingRequest_ = SIP_UNKNOWN_REQUEST; } } void SIPClientTransaction::getRequestMessageInfo(RequestType type, std::shared_ptr<SIPMessageInfo>& outMessage) { outMessage = std::shared_ptr<SIPMessageInfo> (new SIPMessageInfo); if(type == ACK) { outMessage->transactionRequest = INVITE; } else if(type == CANCEL) { outMessage->transactionRequest = ongoingTransactionType_; } else { outMessage->transactionRequest = type; } outMessage->dialog = NULL; outMessage->maxForwards = 71; outMessage->version = "2.0"; outMessage->cSeq = 0; // invalid, should be set in dialog } void SIPClientTransaction::requestSender(RequestType type) { if(!connected_) { qDebug() << "Added a pending request:" << type; pendingRequest_ = type; } else { qDebug() << "Client starts sending a request:" << type; ongoingTransactionType_ = type; emit sendRequest(sessionID_, type); if(type != INVITE) { qDebug() << "Request timeout set to: " << TIMEOUT; requestTimer_.start(TIMEOUT); } else { qDebug() << "INVITE timeout set to: " << INVITE_TIMEOUT; requestTimer_.start(INVITE_TIMEOUT); } } } void SIPClientTransaction::requestTimeOut() { qDebug() << "No response. Request timed out"; if(ongoingTransactionType_ == INVITE) { sendRequest(sessionID_, BYE); // TODO tell user we have failed } requestSender(CANCEL); transactionUser_->callRejected(sessionID_); ongoingTransactionType_ = SIP_UNKNOWN_REQUEST; } <|endoftext|>
<commit_before>// Copyright 2010-2021 Google LLC // 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. // [START program] // [START import] #include <vector> #include "ortools/base/logging.h" #include "ortools/linear_solver/linear_solver.h" // [END import] namespace operations_research { void AssignmentMip() { // Data // [START data_model] const std::vector<std::vector<double>> costs{ {90, 80, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 95}, {45, 110, 95, 115}, {50, 100, 90, 100}, }; const int num_workers = costs.size(); const int num_tasks = costs[0].size(); // [END data_model] // Solver // [START solver] // Create the mip solver with the SCIP backend. std::unique_ptr<MPSolver> solver(MPSolver::CreateSolver("SCIP")); if (!solver) { LOG(WARNING) << "SCIP solver unavailable."; return; } // [END solver] // Variables // [START variables] // x[i][j] is an array of 0-1 variables, which will be 1 // if worker i is assigned to task j. std::vector<std::vector<const MPVariable*>> x( num_workers, std::vector<const MPVariable*>(num_tasks)); for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { x[i][j] = solver->MakeIntVar(0, 1, ""); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int i = 0; i < num_workers; ++i) { LinearExpr worker_sum; for (int j = 0; j < num_tasks; ++j) { worker_sum += x[i][j]; } solver->MakeRowConstraint(worker_sum <= 1.0); } // Each task is assigned to exactly one worker. for (int j = 0; j < num_tasks; ++j) { LinearExpr task_sum; for (int i = 0; i < num_workers; ++i) { task_sum += x[i][j]; } solver->MakeRowConstraint(task_sum == 1.0); } // [END constraints] // Objective. // [START objective] MPObjective* const objective = solver->MutableObjective(); for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { objective->SetCoefficient(x[i][j], costs[i][j]); } } objective->SetMinimization(); // [END objective] // Solve // [START solve] const MPSolver::ResultStatus result_status = solver->Solve(); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (result_status != MPSolver::OPTIMAL & result_status != MPSolver::FEASIBLE) { LOG(FATAL) << "No solution found."; } LOG(INFO) << "Total cost = " << objective->Value() << "\n\n"; for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point // arithmetic). if (x[i][j]->solution_value() > 0.5) { LOG(INFO) << "Worker " << i << " assigned to task " << j << ". Cost = " << costs[i][j]; } } } // [END print_solution] } } // namespace operations_research int main(int argc, char** argv) { operations_research::AssignmentMip(); return EXIT_SUCCESS; } // [END program] <commit_msg>linear_solver: Fix cond in sample<commit_after>// Copyright 2010-2021 Google LLC // 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. // [START program] // [START import] #include <vector> #include "ortools/base/logging.h" #include "ortools/linear_solver/linear_solver.h" // [END import] namespace operations_research { void AssignmentMip() { // Data // [START data_model] const std::vector<std::vector<double>> costs{ {90, 80, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 95}, {45, 110, 95, 115}, {50, 100, 90, 100}, }; const int num_workers = costs.size(); const int num_tasks = costs[0].size(); // [END data_model] // Solver // [START solver] // Create the mip solver with the SCIP backend. std::unique_ptr<MPSolver> solver(MPSolver::CreateSolver("SCIP")); if (!solver) { LOG(WARNING) << "SCIP solver unavailable."; return; } // [END solver] // Variables // [START variables] // x[i][j] is an array of 0-1 variables, which will be 1 // if worker i is assigned to task j. std::vector<std::vector<const MPVariable*>> x( num_workers, std::vector<const MPVariable*>(num_tasks)); for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { x[i][j] = solver->MakeIntVar(0, 1, ""); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int i = 0; i < num_workers; ++i) { LinearExpr worker_sum; for (int j = 0; j < num_tasks; ++j) { worker_sum += x[i][j]; } solver->MakeRowConstraint(worker_sum <= 1.0); } // Each task is assigned to exactly one worker. for (int j = 0; j < num_tasks; ++j) { LinearExpr task_sum; for (int i = 0; i < num_workers; ++i) { task_sum += x[i][j]; } solver->MakeRowConstraint(task_sum == 1.0); } // [END constraints] // Objective. // [START objective] MPObjective* const objective = solver->MutableObjective(); for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { objective->SetCoefficient(x[i][j], costs[i][j]); } } objective->SetMinimization(); // [END objective] // Solve // [START solve] const MPSolver::ResultStatus result_status = solver->Solve(); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (result_status != MPSolver::OPTIMAL && result_status != MPSolver::FEASIBLE) { LOG(FATAL) << "No solution found."; } LOG(INFO) << "Total cost = " << objective->Value() << "\n\n"; for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point // arithmetic). if (x[i][j]->solution_value() > 0.5) { LOG(INFO) << "Worker " << i << " assigned to task " << j << ". Cost = " << costs[i][j]; } } } // [END print_solution] } } // namespace operations_research int main(int argc, char** argv) { operations_research::AssignmentMip(); return EXIT_SUCCESS; } // [END program] <|endoftext|>
<commit_before>// // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ScenicWindow.cpp: // Implements methods from ScenicWindow // #include "util/fuchsia/ScenicWindow.h" #include <fuchsia/images/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fdio/directory.h> #include <lib/fidl/cpp/interface_ptr.h> #include <lib/fidl/cpp/interface_request.h> #include <lib/ui/scenic/cpp/view_token_pair.h> #include <lib/zx/channel.h> #include <zircon/status.h> #include "common/debug.h" namespace { async::Loop *GetDefaultLoop() { static async::Loop *defaultLoop = new async::Loop(&kAsyncLoopConfigAttachToCurrentThread); return defaultLoop; } zx::channel ConnectToServiceRoot() { zx::channel clientChannel; zx::channel serverChannel; zx_status_t result = zx::channel::create(0, &clientChannel, &serverChannel); ASSERT(result == ZX_OK); result = fdio_service_connect("/svc/.", serverChannel.release()); ASSERT(result == ZX_OK); return clientChannel; } template <typename Interface> zx_status_t ConnectToService(zx_handle_t serviceRoot, fidl::InterfaceRequest<Interface> request) { ASSERT(request.is_valid()); return fdio_service_connect_at(serviceRoot, Interface::Name_, request.TakeChannel().release()); } template <typename Interface> fidl::InterfacePtr<Interface> ConnectToService(zx_handle_t serviceRoot) { fidl::InterfacePtr<Interface> result; ConnectToService(serviceRoot, result.NewRequest()); return result; } } // namespace ScenicWindow::ScenicWindow() : mLoop(GetDefaultLoop()), mServiceRoot(ConnectToServiceRoot()), mScenic(ConnectToService<fuchsia::ui::scenic::Scenic>(mServiceRoot.get())), mPresenter(ConnectToService<fuchsia::ui::policy::Presenter>(mServiceRoot.get())), mScenicSession(mScenic.get()), mShape(&mScenicSession), mMaterial(&mScenicSession) {} ScenicWindow::~ScenicWindow() { destroy(); } bool ScenicWindow::initialize(const std::string &name, int width, int height) { // Set up scenic resources. mShape.SetShape(scenic::Rectangle(&mScenicSession, width, height)); mShape.SetMaterial(mMaterial); fuchsia::ui::views::ViewToken viewToken; fuchsia::ui::views::ViewHolderToken viewHolderToken; std::tie(viewToken, viewHolderToken) = scenic::NewViewTokenPair(); // Create view. mView = std::make_unique<scenic::View>(&mScenicSession, std::move(viewToken), name); mView->AddChild(mShape); mScenicSession.Present(0, [](fuchsia::images::PresentationInfo info) {}); // Present view. mPresenter->PresentView(std::move(viewHolderToken), nullptr); mWidth = width; mHeight = height; resetNativeWindow(); return true; } void ScenicWindow::destroy() { mFuchsiaEGLWindow.reset(); } void ScenicWindow::resetNativeWindow() { fuchsia::images::ImagePipe2Ptr imagePipe; uint32_t imagePipeId = mScenicSession.AllocResourceId(); mScenicSession.Enqueue(scenic::NewCreateImagePipe2Cmd(imagePipeId, imagePipe.NewRequest())); zx_handle_t imagePipeHandle = imagePipe.Unbind().TakeChannel().release(); mMaterial.SetTexture(imagePipeId); mScenicSession.ReleaseResource(imagePipeId); mScenicSession.Present(0, [](fuchsia::images::PresentationInfo info) {}); mFuchsiaEGLWindow.reset(fuchsia_egl_window_create(imagePipeHandle, mWidth, mHeight)); } EGLNativeWindowType ScenicWindow::getNativeWindow() const { return reinterpret_cast<EGLNativeWindowType>(mFuchsiaEGLWindow.get()); } EGLNativeDisplayType ScenicWindow::getNativeDisplay() const { return EGL_DEFAULT_DISPLAY; } void ScenicWindow::messageLoop() { mLoop->Run(zx::deadline_after({}), true /* once */); } void ScenicWindow::setMousePosition(int x, int y) { UNIMPLEMENTED(); } bool ScenicWindow::setPosition(int x, int y) { UNIMPLEMENTED(); return false; } bool ScenicWindow::resize(int width, int height) { mWidth = width; mHeight = height; fuchsia_egl_window_resize(mFuchsiaEGLWindow.get(), width, height); return true; } void ScenicWindow::setVisible(bool isVisible) {} void ScenicWindow::signalTestEvent() {} void ScenicWindow::OnScenicEvents(std::vector<fuchsia::ui::scenic::Event> events) { UNIMPLEMENTED(); } void ScenicWindow::OnScenicError(zx_status_t status) { WARN() << "OnScenicError: " << zx_status_get_string(status); } // static OSWindow *OSWindow::New() { return new ScenicWindow; } <commit_msg>[fuchsia] Change all Angle Presents to Present2s<commit_after>// // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ScenicWindow.cpp: // Implements methods from ScenicWindow // #include "util/fuchsia/ScenicWindow.h" #include <fuchsia/images/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/fdio/directory.h> #include <lib/fidl/cpp/interface_ptr.h> #include <lib/fidl/cpp/interface_request.h> #include <lib/ui/scenic/cpp/view_token_pair.h> #include <lib/zx/channel.h> #include <zircon/status.h> #include "common/debug.h" namespace { async::Loop *GetDefaultLoop() { static async::Loop *defaultLoop = new async::Loop(&kAsyncLoopConfigAttachToCurrentThread); return defaultLoop; } zx::channel ConnectToServiceRoot() { zx::channel clientChannel; zx::channel serverChannel; zx_status_t result = zx::channel::create(0, &clientChannel, &serverChannel); ASSERT(result == ZX_OK); result = fdio_service_connect("/svc/.", serverChannel.release()); ASSERT(result == ZX_OK); return clientChannel; } template <typename Interface> zx_status_t ConnectToService(zx_handle_t serviceRoot, fidl::InterfaceRequest<Interface> request) { ASSERT(request.is_valid()); return fdio_service_connect_at(serviceRoot, Interface::Name_, request.TakeChannel().release()); } template <typename Interface> fidl::InterfacePtr<Interface> ConnectToService(zx_handle_t serviceRoot) { fidl::InterfacePtr<Interface> result; ConnectToService(serviceRoot, result.NewRequest()); return result; } } // namespace ScenicWindow::ScenicWindow() : mLoop(GetDefaultLoop()), mServiceRoot(ConnectToServiceRoot()), mScenic(ConnectToService<fuchsia::ui::scenic::Scenic>(mServiceRoot.get())), mPresenter(ConnectToService<fuchsia::ui::policy::Presenter>(mServiceRoot.get())), mScenicSession(mScenic.get()), mShape(&mScenicSession), mMaterial(&mScenicSession) {} ScenicWindow::~ScenicWindow() { destroy(); } bool ScenicWindow::initialize(const std::string &name, int width, int height) { // Set up scenic resources. mShape.SetShape(scenic::Rectangle(&mScenicSession, width, height)); mShape.SetMaterial(mMaterial); fuchsia::ui::views::ViewToken viewToken; fuchsia::ui::views::ViewHolderToken viewHolderToken; std::tie(viewToken, viewHolderToken) = scenic::NewViewTokenPair(); // Create view. mView = std::make_unique<scenic::View>(&mScenicSession, std::move(viewToken), name); mView->AddChild(mShape); mScenicSession.Present2(0, 0, [](fuchsia::scenic::scheduling::FuturePresentationTimes info) {}); // Present view. mPresenter->PresentView(std::move(viewHolderToken), nullptr); mWidth = width; mHeight = height; resetNativeWindow(); return true; } void ScenicWindow::destroy() { mFuchsiaEGLWindow.reset(); } void ScenicWindow::resetNativeWindow() { fuchsia::images::ImagePipe2Ptr imagePipe; uint32_t imagePipeId = mScenicSession.AllocResourceId(); mScenicSession.Enqueue(scenic::NewCreateImagePipe2Cmd(imagePipeId, imagePipe.NewRequest())); zx_handle_t imagePipeHandle = imagePipe.Unbind().TakeChannel().release(); mMaterial.SetTexture(imagePipeId); mScenicSession.ReleaseResource(imagePipeId); mScenicSession.Present2(0, 0, [](fuchsia::scenic::scheduling::FuturePresentationTimes info) {}); mFuchsiaEGLWindow.reset(fuchsia_egl_window_create(imagePipeHandle, mWidth, mHeight)); } EGLNativeWindowType ScenicWindow::getNativeWindow() const { return reinterpret_cast<EGLNativeWindowType>(mFuchsiaEGLWindow.get()); } EGLNativeDisplayType ScenicWindow::getNativeDisplay() const { return EGL_DEFAULT_DISPLAY; } void ScenicWindow::messageLoop() { mLoop->Run(zx::deadline_after({}), true /* once */); } void ScenicWindow::setMousePosition(int x, int y) { UNIMPLEMENTED(); } bool ScenicWindow::setPosition(int x, int y) { UNIMPLEMENTED(); return false; } bool ScenicWindow::resize(int width, int height) { mWidth = width; mHeight = height; fuchsia_egl_window_resize(mFuchsiaEGLWindow.get(), width, height); return true; } void ScenicWindow::setVisible(bool isVisible) {} void ScenicWindow::signalTestEvent() {} void ScenicWindow::OnScenicEvents(std::vector<fuchsia::ui::scenic::Event> events) { UNIMPLEMENTED(); } void ScenicWindow::OnScenicError(zx_status_t status) { WARN() << "OnScenicError: " << zx_status_get_string(status); } // static OSWindow *OSWindow::New() { return new ScenicWindow; } <|endoftext|>
<commit_before>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, jschulze@ucsd.edu // // This file is part of Virvo. // // Virvo is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <limits> #include "vvglew.h" #include "vvimageclient.h" #include "vvgltools.h" #include "vvtexrend.h" #include "float.h" #include "vvrayrend.h" #include "vvshaderfactory.h" #include "vvshaderprogram.h" #include "vvtoolshed.h" #include "vvsocketio.h" #include "vvdebugmsg.h" #include "vvimage.h" using std::cerr; using std::endl; vvImageClient::vvImageClient(vvVolDesc *vd, vvRenderState renderState, const char* slaveName, int port, const char* slaveFileName) : vvRemoteClient(vd, renderState, vvRenderer::REMOTE_IMAGE, slaveName, port, slaveFileName) , _image(NULL) { vvDebugMsg::msg(1, "vvImageClient::vvImageClient()"); rendererType = REMOTE_IMAGE; glewInit(); glGenTextures(1, &_rgbaTex); _image = new vvImage; } vvImageClient::~vvImageClient() { vvDebugMsg::msg(1, "vvImageClient::~vvImageClient()"); glDeleteTextures(1, &_rgbaTex); } vvRemoteClient::ErrorType vvImageClient::render() { vvDebugMsg::msg(1, "vvImageClient::render()"); vvRemoteClient::ErrorType err = requestFrame(); if(err != vvRemoteClient::VV_OK) return err; if(!_socketIO) return vvRemoteClient::VV_SOCKET_ERROR; vvSocket::ErrorType sockerr = _socketIO->getImage(_image); if(sockerr != vvSocket::VV_OK) { std::cerr << "vvImageClient::render: socket error (" << sockerr << ") - exiting..." << std::endl; return vvRemoteClient::VV_SOCKET_ERROR; } _image->decode(); const int h = _image->getHeight(); const int w = _image->getWidth(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_TRANSFORM_BIT); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); // get pixel and depth-data glBindTexture(GL_TEXTURE_2D, _rgbaTex); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, _image->getImagePtr()); vvGLTools::drawViewAlignedQuad(); glPopAttrib(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); return VV_OK; } // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <commit_msg>Image client doesn't need glew<commit_after>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, jschulze@ucsd.edu // // This file is part of Virvo. // // Virvo is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include <limits> #include "vvimageclient.h" #include "vvgltools.h" #include "vvtexrend.h" #include "float.h" #include "vvrayrend.h" #include "vvshaderfactory.h" #include "vvshaderprogram.h" #include "vvtoolshed.h" #include "vvsocketio.h" #include "vvdebugmsg.h" #include "vvimage.h" using std::cerr; using std::endl; vvImageClient::vvImageClient(vvVolDesc *vd, vvRenderState renderState, const char* slaveName, int port, const char* slaveFileName) : vvRemoteClient(vd, renderState, vvRenderer::REMOTE_IMAGE, slaveName, port, slaveFileName) , _image(NULL) { vvDebugMsg::msg(1, "vvImageClient::vvImageClient()"); rendererType = REMOTE_IMAGE; glGenTextures(1, &_rgbaTex); _image = new vvImage; } vvImageClient::~vvImageClient() { vvDebugMsg::msg(1, "vvImageClient::~vvImageClient()"); glDeleteTextures(1, &_rgbaTex); } vvRemoteClient::ErrorType vvImageClient::render() { vvDebugMsg::msg(1, "vvImageClient::render()"); vvRemoteClient::ErrorType err = requestFrame(); if(err != vvRemoteClient::VV_OK) return err; if(!_socketIO) return vvRemoteClient::VV_SOCKET_ERROR; vvSocket::ErrorType sockerr = _socketIO->getImage(_image); if(sockerr != vvSocket::VV_OK) { std::cerr << "vvImageClient::render: socket error (" << sockerr << ") - exiting..." << std::endl; return vvRemoteClient::VV_SOCKET_ERROR; } _image->decode(); const int h = _image->getHeight(); const int w = _image->getWidth(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glPushAttrib(GL_COLOR_BUFFER_BIT | GL_CURRENT_BIT | GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_TEXTURE_BIT | GL_TRANSFORM_BIT); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); // get pixel and depth-data glBindTexture(GL_TEXTURE_2D, _rgbaTex); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, _image->getImagePtr()); vvGLTools::drawViewAlignedQuad(); glPopAttrib(); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); return VV_OK; } // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <|endoftext|>
<commit_before>// -*- coding: us-ascii-unix -*- // Copyright 2015 Lukas Kemmer // // 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 <string> // std::stod #include "bitmap/bitmap.hh" #include "geo/geo-func.hh" // floated #include "geo/int-point.hh" #include "geo/int-size.hh" #include "gui/accelerator-entry.hh" #include "gui/grid-dialog.hh" #include "gui/paint-dialog.hh" #include "gui/static-bitmap.hh" #include "gui/ui-constants.hh" #include "util/color-bitmap-util.hh" #include "util-wx/fwd-wx.hh" #include "util-wx/fwd-bind.hh" #include "util-wx/layout-wx.hh" #include "util-wx/key-codes.hh" namespace faint{ static coord to_coord(const utf8_string& s, coord defaultValue){ try{ return std::stod(s.c_str()); } catch (const std::exception&){ return defaultValue; } } Optional<Grid> show_grid_dialog(wxWindow* parent, const Grid& oldGrid, DialogContext& c) { Grid grid = oldGrid; auto dlg = fixed_size_dialog(parent, "Grid"); auto make_edit = [&](coord value){ auto edit = create_text_control(dlg.get(), ""); fit_size_to(edit, "10000"); set_number_text(edit, value, 2_dec, Signal::NO); return edit; }; // Spacing edit field auto labelSpacing = create_label(dlg.get(), "&Spacing", TextAlign::RIGHT); auto editSpacing = make_edit(grid.Spacing()); // Anchor edit fields Point anchor = grid.Anchor(); auto labelX = create_label(dlg, "&X", TextAlign::RIGHT); make_uniformly_sized({labelSpacing, labelX}); auto editX = make_edit(anchor.x); auto labelY = create_label(dlg.get(), "&Y"); auto editY = make_edit(anchor.y); // Dashes-checkbox auto dashed = create_checkbox(dlg, "&dashed lines", grid.Dashed()); using namespace layout; auto spacingRow = create_row(OuterSpacing(0), ui::item_spacing, {labelSpacing, raw(editSpacing)}); auto anchorRow = create_row(OuterSpacing(0), ui::item_spacing, {labelX, raw(editX), labelY, raw(editY)}); auto make_color_bitmap = [&](){ return color_bitmap(grid.GetColor(), IntSize(20, 20)); }; auto colorLabel = create_label(dlg, "&color"); auto colorButton = new StaticBitmap(raw(dlg.get()), make_color_bitmap()); set_size(colorButton, get_size(dashed)); set_stock_cursor(colorButton, wxCURSOR_HAND); set_stock_cursor(colorLabel, wxCURSOR_HAND); auto pick_grid_color = [&](){ show_color_only_dialog(raw(dlg), "Grid color", grid.GetColor(), c).Visit( [&](const Color& c){ grid.SetColor(c); colorButton->SetBitmap(make_color_bitmap()); }); }; set_accelerators(raw(dlg), { {key::C, Alt+key::C, pick_grid_color}}); events::on_mouse_left_down(colorButton, [&](const IntPoint&){ pick_grid_color(); }); events::on_mouse_left_down(colorLabel, [&](const IntPoint&){ pick_grid_color(); }); set_sizer(dlg.get(), create_column({ spacingRow, anchorRow, create_row({raw(dashed)}), create_row({raw(colorButton), colorLabel}), center(create_row({create_ok_cancel_buttons(dlg.get())}))})); auto get_grid = [&](){ return Grid(true, // Enabled to_coord(get_text(editSpacing), grid.Spacing()), grid.GetColor(), Point(to_coord(get_text(editX), anchor.x), to_coord(get_text(editY), anchor.y)), get(dashed)); }; center_over_parent(dlg); return c.ShowModal(*dlg) == DialogChoice::OK ? option(get_grid()) : no_option(); } } // namespace <commit_msg>Added enabled checkbox to grid dialog.<commit_after>// -*- coding: us-ascii-unix -*- // Copyright 2015 Lukas Kemmer // // 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 <string> // std::stod #include "bitmap/bitmap.hh" #include "geo/geo-func.hh" // floated #include "geo/int-point.hh" #include "geo/int-size.hh" #include "gui/accelerator-entry.hh" #include "gui/grid-dialog.hh" #include "gui/paint-dialog.hh" #include "gui/static-bitmap.hh" #include "gui/ui-constants.hh" #include "util/color-bitmap-util.hh" #include "util-wx/fwd-wx.hh" #include "util-wx/fwd-bind.hh" #include "util-wx/layout-wx.hh" #include "util-wx/key-codes.hh" namespace faint{ static coord to_coord(const utf8_string& s, coord defaultValue){ try{ return std::stod(s.c_str()); } catch (const std::exception&){ return defaultValue; } } Optional<Grid> show_grid_dialog(wxWindow* parent, const Grid& oldGrid, DialogContext& c) { Grid grid = oldGrid; auto dlg = fixed_size_dialog(parent, "Grid"); auto make_edit = [&](coord value){ auto edit = create_text_control(dlg.get(), ""); fit_size_to(edit, "10000"); set_number_text(edit, value, 2_dec, Signal::NO); return edit; }; // Spacing edit field auto labelSpacing = create_label(dlg.get(), "&Spacing", TextAlign::RIGHT); auto editSpacing = make_edit(grid.Spacing()); // Anchor edit fields Point anchor = grid.Anchor(); auto labelX = create_label(dlg, "&X", TextAlign::RIGHT); make_uniformly_sized({labelSpacing, labelX}); auto editX = make_edit(anchor.x); auto labelY = create_label(dlg.get(), "&Y"); auto editY = make_edit(anchor.y); // Enabled-checkbox auto enabled = create_checkbox(dlg, "&enabled", grid.Enabled()); // Dashes-checkbox auto dashed = create_checkbox(dlg, "&dashes", grid.Dashed()); using namespace layout; auto spacingRow = create_row(OuterSpacing(0), ui::item_spacing, {labelSpacing, raw(editSpacing)}); auto anchorRow = create_row(OuterSpacing(0), ui::item_spacing, {labelX, raw(editX), labelY, raw(editY)}); auto make_color_bitmap = [&](){ return color_bitmap(grid.GetColor(), IntSize(20, 20)); }; auto colorLabel = create_label(dlg, "&color"); auto colorButton = new StaticBitmap(raw(dlg.get()), make_color_bitmap()); set_size(colorButton, get_size(dashed)); set_stock_cursor(colorButton, wxCURSOR_HAND); set_stock_cursor(colorLabel, wxCURSOR_HAND); auto pick_grid_color = [&](){ show_color_only_dialog(raw(dlg), "Grid color", grid.GetColor(), c).Visit( [&](const Color& c){ grid.SetColor(c); colorButton->SetBitmap(make_color_bitmap()); }); }; set_accelerators(raw(dlg), { {key::C, Alt+key::C, pick_grid_color}}); events::on_mouse_left_down(colorButton, [&](const IntPoint&){ pick_grid_color(); }); events::on_mouse_left_down(colorLabel, [&](const IntPoint&){ pick_grid_color(); }); set_sizer(dlg.get(), create_column({ create_row({raw(enabled)}), spacingRow, anchorRow, create_row({raw(dashed)}), create_row({raw(colorButton), colorLabel}), center(create_row({create_ok_cancel_buttons(dlg.get())}))})); auto get_grid = [&](){ return Grid(get(enabled), to_coord(get_text(editSpacing), grid.Spacing()), grid.GetColor(), Point(to_coord(get_text(editX), anchor.x), to_coord(get_text(editY), anchor.y)), get(dashed)); }; center_over_parent(dlg); return c.ShowModal(*dlg) == DialogChoice::OK ? option(get_grid()) : no_option(); } } // namespace <|endoftext|>
<commit_before>#include "SboxByte.h" #include "SboxByte64Tab.h" using namespace std; using namespace magma; // @todo #89:15min SboxByte should use source sbox as is, without creating tab SboxByte::SboxByte(const std::vector<uint8_t> &uz) : SboxByte( make_unique<SboxByte64Tab>(uz, 0), make_unique<SboxByte64Tab>(uz, 1), make_unique<SboxByte64Tab>(uz, 2), make_unique<SboxByte64Tab>(uz, 3) ) { } SboxByte::SboxByte( unique_ptr<const Tab> tab1, unique_ptr<const Tab> tab2, unique_ptr<const Tab> tab3, unique_ptr<const Tab> tab4 ) : tab1(move(tab1)), tab2(move(tab2)), tab3(move(tab3)), tab4(move(tab4)) { } uint32_t SboxByte::transform(uint32_t v) const { return tab1->translate(v) | (tab2->translate(v >> 8) << 8) | (tab3->translate(v >> 16) << 16) | (tab4->translate(v >> 24) << 24); } <commit_msg>#91: SboxByte64Tab is not optimizations, dedup only<commit_after>#include "SboxByte.h" #include "SboxByte64Tab.h" using namespace std; using namespace magma; SboxByte::SboxByte(const std::vector<uint8_t> &uz) : SboxByte( make_unique<SboxByte64Tab>(uz, 0), make_unique<SboxByte64Tab>(uz, 1), make_unique<SboxByte64Tab>(uz, 2), make_unique<SboxByte64Tab>(uz, 3) ) { } SboxByte::SboxByte( unique_ptr<const Tab> tab1, unique_ptr<const Tab> tab2, unique_ptr<const Tab> tab3, unique_ptr<const Tab> tab4 ) : tab1(move(tab1)), tab2(move(tab2)), tab3(move(tab3)), tab4(move(tab4)) { } uint32_t SboxByte::transform(uint32_t v) const { return tab1->translate(v) | (tab2->translate(v >> 8) << 8) | (tab3->translate(v >> 16) << 16) | (tab4->translate(v >> 24) << 24); } <|endoftext|>
<commit_before>#include "sl_generator.h" #include <vector> #include <algorithm> #include <random> #include "sl_problem.h" #include "sl_field.h" #include "sl_clue_placement.h" #include "sl_generator_option.h" #include "../common/grid_loop_helper.h" #include "../common/union_find.h" namespace penciloid { namespace slitherlink { namespace { bool HasUndecidedEdgeNearby(Field &field, Y y_base, X x_base) { y_base = y_base * 2 + 1; x_base = x_base * 2 + 1; for (Y dy(-7); dy <= 7; ++dy) { for (X dx(-7); dx <= 7; ++dx) { Y y = y_base + dy; X x = x_base + dx; if (0 <= y && y <= 2 * field.height() && 0 <= x && x <= 2 * field.width()) { if (static_cast<int>(y) % 2 != static_cast<int>(x) % 2 && field.GetEdge(LoopPosition(y, x)) == Field::EDGE_UNDECIDED) { return true; } } } } return false; } bool HasZeroNearby(Field &field, CellPosition pos) { for (Y dy(-1); dy <= 1; ++dy) { for (X dx(-1); dx <= 1; ++dx) { Y y = pos.y + dy; X x = pos.x + dx; if (0 <= y && y < field.height() && 0 <= x && x < field.width() && field.GetClue(CellPosition(y, x)) == Clue(0)) { return true; } } } return false; } } bool GenerateByLocalSearch(const CluePlacement &placement, const GeneratorOption &constraint, std::mt19937 *rnd, Problem *ret) { std::uniform_real_distribution<float> real_rnd(0.0, 1.0); Y height = placement.height(); X width = placement.width(); Problem current_problem(height, width); int max_step = static_cast<int>(height) * static_cast<int>(width) * 10; int number_unplaced_clues = 0; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { Clue clue = placement.GetClue(CellPosition(y, x)); if (clue == kSomeClue) ++number_unplaced_clues; else if (clue != kNoClue) current_problem.SetClue(CellPosition(y, x), clue); } } Field latest_field(current_problem, constraint.field_database); for (int step = 0; step < max_step; ++step) { Field::EdgeCount previous_decided_edges = latest_field.GetNumberOfDecidedEdges(); bool is_progress = false; double temperature = 5.0; std::vector<CellPosition> position_candidates; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) if (placement.GetClue(CellPosition(y, x)) == kSomeClue) { if (HasUndecidedEdgeNearby(latest_field, y, x)) { position_candidates.push_back(CellPosition(y, x)); } } } std::shuffle(position_candidates.begin(), position_candidates.end(), *rnd); for (CellPosition &pos : position_candidates) { Clue previous_clue = current_problem.GetClue(pos); bool is_zero_ok = !HasZeroNearby(latest_field, pos); std::vector<Clue> new_clue_candidates; for (Clue c(is_zero_ok ? 0 : 1); c <= 3; ++c) { if (c != previous_clue) new_clue_candidates.push_back(c); } std::shuffle(new_clue_candidates.begin(), new_clue_candidates.end(), *rnd); Field common; if (previous_clue == kNoClue) common = latest_field; else { current_problem.SetClue(pos, kNoClue); common = Field(current_problem, constraint.field_database); } for (Clue new_clue : new_clue_candidates) { current_problem.SetClue(pos, new_clue); Field next_field_candidate(common); next_field_candidate.AddClue(pos, new_clue); if (next_field_candidate.IsInconsistent()) continue; bool transition = false; Field::EdgeCount next_decided_edges = next_field_candidate.GetNumberOfDecidedEdges(); if (previous_decided_edges < next_decided_edges) { transition = true; } else { double transition_probability = exp(static_cast<double>(static_cast<int>(next_decided_edges) - static_cast<int>(previous_decided_edges)) / temperature); if (real_rnd(*rnd) < transition_probability) transition = true; } if (!transition) continue; Field in_out_test_field = next_field_candidate; ApplyInOutRule(&in_out_test_field); CheckConnectability(&in_out_test_field); if (in_out_test_field.IsInconsistent()) { continue; } // update field & problem if (previous_clue == kNoClue) --number_unplaced_clues; previous_decided_edges = next_decided_edges; is_progress = true; latest_field = next_field_candidate; break; } if (is_progress) break; else current_problem.SetClue(pos, previous_clue); } if (latest_field.IsFullySolved() && !latest_field.IsInconsistent() && number_unplaced_clues == 0) { *ret = current_problem; return true; } } return false; } CluePlacement GenerateCluePlacement(Y height, X width, int number_clues, Symmetry symmetry, std::mt19937 *rnd) { UnionFind cell_groups(static_cast<int>(height) * static_cast<int>(width)); CluePlacement ret(height, width); auto cell_id = [height, width](Y y, X x) { return static_cast<int>(y) * static_cast<int>(width) + static_cast<int>(x); }; if ((symmetry & kSymmetryTetrad) == kSymmetryTetrad && static_cast<int>(height) == static_cast<int>(width)) { for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); int id_rotated = cell_id(Y(x), X(height - y - 1)); cell_groups.Join(id, id_rotated); } } } if (symmetry & kSymmetryDyad) { for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); int id_rotated = cell_id(height - y - 1, width - x - 1); cell_groups.Join(id, id_rotated); } } } if (symmetry & kSymmetryHorizontalLine) { for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); int id_flipped = cell_id(height - y - 1, x); cell_groups.Join(id, id_flipped); } } } if (symmetry & kSymmetryVerticalLine) { for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); int id_flipped = cell_id(y, width - x - 1); cell_groups.Join(id, id_flipped); } } } std::vector<std::pair<CellPosition, int> > possible_clues; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); if (cell_groups.Root(id) == id) { possible_clues.push_back({ CellPosition(y, x), cell_groups.UnionSize(id) }); } } } while (number_clues > 0 && possible_clues.size() > 0) { std::vector<double> scores; double score_total = 0.0; for (auto p : possible_clues) { CellPosition pos = p.first; int score_base = 0; for (Y dy(-2); dy <= 2; ++dy) { for (X dx(-2); dx <= 2; ++dx) { CellPosition pos2 = pos + Direction(dy, dx); if (0 <= pos2.y && pos2.y < height && 0 <= pos2.x && pos2.x < width) { if (ret.GetClue(pos2) == kSomeClue) { int dist = 0; dist += (dy > 0 ? dy : -dy); dist += (dx > 0 ? dx : -dx); score_base += 5 - dist; if (dist == 1) score_base += 2; } } } } double cell_score = 64.0 * pow(2.0, (16.0 - score_base) / 2.0) + 4.0; scores.push_back(cell_score); score_total += cell_score; } double r = std::uniform_real_distribution<float>(0.0, static_cast<float>(score_total))(*rnd); int next_idx = possible_clues.size() - 1; for (int i = 0; i < scores.size(); ++i) { if (r < scores[i]) { next_idx = i; break; } else r -= scores[i]; } CellPosition representative_pos = possible_clues[next_idx].first; int representative_id = cell_id(representative_pos.y, representative_pos.x); for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); if (cell_groups.Root(id) == cell_groups.Root(representative_id)) { --number_clues; ret.SetClue(CellPosition(y, x), kSomeClue); } } } possible_clues[next_idx] = possible_clues[possible_clues.size() - 1]; possible_clues.pop_back(); } return ret; } } } <commit_msg>Slitherlink: stop immediately if there was no change many times and use tabu list in Generator<commit_after>#include "sl_generator.h" #include <vector> #include <algorithm> #include <random> #include "sl_problem.h" #include "sl_field.h" #include "sl_clue_placement.h" #include "sl_generator_option.h" #include "../common/grid_loop_helper.h" #include "../common/union_find.h" namespace penciloid { namespace slitherlink { namespace { bool HasUndecidedEdgeNearby(Field &field, Y y_base, X x_base) { y_base = y_base * 2 + 1; x_base = x_base * 2 + 1; for (Y dy(-7); dy <= 7; ++dy) { for (X dx(-7); dx <= 7; ++dx) { Y y = y_base + dy; X x = x_base + dx; if (0 <= y && y <= 2 * field.height() && 0 <= x && x <= 2 * field.width()) { if (static_cast<int>(y) % 2 != static_cast<int>(x) % 2 && field.GetEdge(LoopPosition(y, x)) == Field::EDGE_UNDECIDED) { return true; } } } } return false; } bool HasZeroNearby(Field &field, CellPosition pos) { for (Y dy(-1); dy <= 1; ++dy) { for (X dx(-1); dx <= 1; ++dx) { Y y = pos.y + dy; X x = pos.x + dx; if (0 <= y && y < field.height() && 0 <= x && x < field.width() && field.GetClue(CellPosition(y, x)) == Clue(0)) { return true; } } } return false; } long long FieldHash(Field &field, long long hash_size) { long long ret = 0; for (Y y(0); y < field.height(); ++y) { for (X x(0); x < field.width(); ++x) { Clue c = field.GetClue(CellPosition(y, x)); if (c == kNoClue) ret = (ret * 7) % hash_size; else ret = (ret * 7 + c + 1) % hash_size; } } return ret; } } bool GenerateByLocalSearch(const CluePlacement &placement, const GeneratorOption &constraint, std::mt19937 *rnd, Problem *ret) { std::uniform_real_distribution<float> real_rnd(0.0, 1.0); Y height = placement.height(); X width = placement.width(); Problem current_problem(height, width); int max_step = static_cast<int>(height) * static_cast<int>(width) * 10; const int kTabuSize = 8; const long long kTabuHashSize = 1e9 + 7; long long tabu_list[kTabuSize]; for (int i = 0; i < kTabuSize; ++i) tabu_list[i] = -1; int number_unplaced_clues = 0; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { Clue clue = placement.GetClue(CellPosition(y, x)); if (clue == kSomeClue) ++number_unplaced_clues; else if (clue != kNoClue) current_problem.SetClue(CellPosition(y, x), clue); } } Field latest_field(current_problem, constraint.field_database); int no_progress = 0; int step = 0; for (; step < max_step; ++step) { Field::EdgeCount previous_decided_edges = latest_field.GetNumberOfDecidedEdges(); bool is_progress = false; double temperature = 5.0; std::vector<CellPosition> position_candidates; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) if (placement.GetClue(CellPosition(y, x)) == kSomeClue) { if (HasUndecidedEdgeNearby(latest_field, y, x)) { position_candidates.push_back(CellPosition(y, x)); } } } std::shuffle(position_candidates.begin(), position_candidates.end(), *rnd); for (CellPosition &pos : position_candidates) { Clue previous_clue = current_problem.GetClue(pos); bool is_zero_ok = !HasZeroNearby(latest_field, pos); std::vector<Clue> new_clue_candidates; for (Clue c(is_zero_ok ? 0 : 1); c <= 3; ++c) { if (c != previous_clue) new_clue_candidates.push_back(c); } std::shuffle(new_clue_candidates.begin(), new_clue_candidates.end(), *rnd); Field common; if (previous_clue == kNoClue) common = latest_field; else { current_problem.SetClue(pos, kNoClue); common = Field(current_problem, constraint.field_database); } for (Clue new_clue : new_clue_candidates) { current_problem.SetClue(pos, new_clue); Field next_field_candidate(common); next_field_candidate.AddClue(pos, new_clue); if (next_field_candidate.IsInconsistent()) continue; long long next_hash = FieldHash(next_field_candidate, kTabuHashSize); bool tabu_collision = false; for (int i = 0; i < kTabuSize; ++i) { if (tabu_list[i] == next_hash) { tabu_collision = true; } } if (tabu_collision) continue; bool transition = false; Field::EdgeCount next_decided_edges = next_field_candidate.GetNumberOfDecidedEdges(); if (previous_decided_edges < next_decided_edges) { transition = true; } else { double transition_probability = exp(static_cast<double>(static_cast<int>(next_decided_edges) - static_cast<int>(previous_decided_edges)) / temperature); if (real_rnd(*rnd) < transition_probability) transition = true; } if (!transition) continue; Field in_out_test_field = next_field_candidate; ApplyInOutRule(&in_out_test_field); CheckConnectability(&in_out_test_field); if (in_out_test_field.IsInconsistent()) { continue; } // update field & problem if (previous_clue == kNoClue) --number_unplaced_clues; previous_decided_edges = next_decided_edges; is_progress = true; latest_field = next_field_candidate; for (int i = 1; i < kTabuSize; ++i) tabu_list[i - 1] = tabu_list[i]; tabu_list[kTabuSize - 1] = next_hash; break; } if (is_progress) break; else current_problem.SetClue(pos, previous_clue); } if (!is_progress) { ++no_progress; if (no_progress >= 10) break; } if (latest_field.IsFullySolved() && !latest_field.IsInconsistent() && number_unplaced_clues == 0) { *ret = current_problem; return true; } } return false; } CluePlacement GenerateCluePlacement(Y height, X width, int number_clues, Symmetry symmetry, std::mt19937 *rnd) { UnionFind cell_groups(static_cast<int>(height) * static_cast<int>(width)); CluePlacement ret(height, width); auto cell_id = [height, width](Y y, X x) { return static_cast<int>(y) * static_cast<int>(width) + static_cast<int>(x); }; if ((symmetry & kSymmetryTetrad) == kSymmetryTetrad && static_cast<int>(height) == static_cast<int>(width)) { for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); int id_rotated = cell_id(Y(x), X(height - y - 1)); cell_groups.Join(id, id_rotated); } } } if (symmetry & kSymmetryDyad) { for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); int id_rotated = cell_id(height - y - 1, width - x - 1); cell_groups.Join(id, id_rotated); } } } if (symmetry & kSymmetryHorizontalLine) { for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); int id_flipped = cell_id(height - y - 1, x); cell_groups.Join(id, id_flipped); } } } if (symmetry & kSymmetryVerticalLine) { for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); int id_flipped = cell_id(y, width - x - 1); cell_groups.Join(id, id_flipped); } } } std::vector<std::pair<CellPosition, int> > possible_clues; for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); if (cell_groups.Root(id) == id) { possible_clues.push_back({ CellPosition(y, x), cell_groups.UnionSize(id) }); } } } while (number_clues > 0 && possible_clues.size() > 0) { std::vector<double> scores; double score_total = 0.0; for (auto p : possible_clues) { CellPosition pos = p.first; int score_base = 0; for (Y dy(-2); dy <= 2; ++dy) { for (X dx(-2); dx <= 2; ++dx) { CellPosition pos2 = pos + Direction(dy, dx); if (0 <= pos2.y && pos2.y < height && 0 <= pos2.x && pos2.x < width) { if (ret.GetClue(pos2) == kSomeClue) { int dist = 0; dist += (dy > 0 ? dy : -dy); dist += (dx > 0 ? dx : -dx); score_base += 5 - dist; if (dist == 1) score_base += 2; } } } } double cell_score = 64.0 * pow(2.0, (16.0 - score_base) / 2.0) + 4.0; scores.push_back(cell_score); score_total += cell_score; } double r = std::uniform_real_distribution<float>(0.0, static_cast<float>(score_total))(*rnd); int next_idx = possible_clues.size() - 1; for (int i = 0; i < scores.size(); ++i) { if (r < scores[i]) { next_idx = i; break; } else r -= scores[i]; } CellPosition representative_pos = possible_clues[next_idx].first; int representative_id = cell_id(representative_pos.y, representative_pos.x); for (Y y(0); y < height; ++y) { for (X x(0); x < width; ++x) { int id = cell_id(y, x); if (cell_groups.Root(id) == cell_groups.Root(representative_id)) { --number_clues; ret.SetClue(CellPosition(y, x), kSomeClue); } } } possible_clues[next_idx] = possible_clues[possible_clues.size() - 1]; possible_clues.pop_back(); } return ret; } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <unistd.h> #include <osquery/core.h> #include <osquery/logger.h> #include <osquery/tables.h> #include <osquery/sql.h> extern "C" { #include <libcryptsetup.h> } namespace osquery { namespace tables { void genFDEStatusForBlockDevice(const std::string& name, const std::string& uuid, const std::string& parent_name, std::map<std::string, Row>& encrypted_rows, QueryData& results) { Row r; r["name"] = name; r["uuid"] = uuid; struct crypt_device* cd = nullptr; struct crypt_active_device cad; crypt_status_info ci; std::string type; std::string cipher; std::string cipher_mode; ci = crypt_status(cd, name.c_str()); switch (ci) { case CRYPT_ACTIVE: case CRYPT_BUSY: { r["encrypted"] = "1"; int crypt_init; #if defined(CENTOS_CENTOS6) || defined(RHEL_RHEL6) || \ defined(SCIENTIFIC_SCIENTIFIC6) crypt_init = crypt_init_by_name(&cd, name.c_str()); #else crypt_init = crypt_init_by_name_and_header(&cd, name.c_str(), nullptr); #endif if (crypt_init < 0) { VLOG(1) << "Unable to initialize crypt device for " << name; break; } type = crypt_get_type(cd); if (crypt_get_active_device(cd, name.c_str(), &cad) < 0) { VLOG(1) << "Unable to get active device for " << name; break; } cipher = crypt_get_cipher(cd); cipher_mode = crypt_get_cipher_mode(cd); r["type"] = type + "-" + cipher + "-" + cipher_mode; encrypted_rows[name] = r; break; } default: if (encrypted_rows.count(parent_name)) { auto parent_row = encrypted_rows[parent_name]; r["encrypted"] = "1"; r["type"] = parent_row["type"]; } else { r["encrypted"] = "0"; } } if (cd != nullptr) { crypt_free(cd); } results.push_back(r); } QueryData genFDEStatus(QueryContext &context) { QueryData results; if (getuid() || geteuid()) { VLOG(1) << "Not running as root, disk encryption status not available"; return results; } std::map<std::string, Row> encrypted_rows; auto block_devices = SQL::selectAllFrom("block_devices"); for (const auto &row : block_devices) { const auto name = (row.count("name") > 0) ? row.at("name") : ""; const auto uuid = (row.count("uuid") > 0) ? row.at("uuid") : ""; const auto parent_name = (row.count("parent") > 0 ? row.at("parent") : ""); genFDEStatusForBlockDevice( name, uuid, parent_name, encrypted_rows, results); } return results; } } } <commit_msg>[Fix #3717] Check crypt API values before constructing strings (#3746)<commit_after>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <unistd.h> #include <vector> #include <osquery/core.h> #include <osquery/logger.h> #include <osquery/sql.h> #include <osquery/tables.h> extern "C" { #include <libcryptsetup.h> } #include "osquery/core/conversions.h" namespace osquery { namespace tables { void genFDEStatusForBlockDevice(const std::string& name, const std::string& uuid, const std::string& parent_name, std::map<std::string, Row>& encrypted_rows, QueryData& results) { Row r; r["name"] = name; r["uuid"] = uuid; struct crypt_device* cd = nullptr; auto ci = crypt_status(cd, name.c_str()); switch (ci) { case CRYPT_ACTIVE: case CRYPT_BUSY: { r["encrypted"] = "1"; auto crypt_init = crypt_init_by_name_and_header(&cd, name.c_str(), nullptr); if (crypt_init < 0) { VLOG(1) << "Unable to initialize crypt device for " << name; break; } struct crypt_active_device cad; if (crypt_get_active_device(cd, name.c_str(), &cad) < 0) { VLOG(1) << "Unable to get active device for " << name; break; } // Construct the "type" with the cipher and mode too. std::vector<std::string> items; auto ctype = crypt_get_type(cd); if (ctype != nullptr) { items.push_back(ctype); } auto ccipher = crypt_get_cipher(cd); if (ccipher != nullptr) { items.push_back(ccipher); } auto ccipher_mode = crypt_get_cipher_mode(cd); if (ccipher_mode != nullptr) { items.push_back(ccipher_mode); } r["type"] = osquery::join(items, "-"); encrypted_rows[name] = r; break; } default: if (encrypted_rows.count(parent_name)) { auto parent_row = encrypted_rows[parent_name]; r["encrypted"] = "1"; r["type"] = parent_row["type"]; } else { r["encrypted"] = "0"; } } if (cd != nullptr) { crypt_free(cd); } results.push_back(r); } QueryData genFDEStatus(QueryContext& context) { QueryData results; if (getuid() || geteuid()) { VLOG(1) << "Not running as root, disk encryption status not available"; return results; } std::map<std::string, Row> encrypted_rows; auto block_devices = SQL::selectAllFrom("block_devices"); for (const auto& row : block_devices) { const auto name = (row.count("name") > 0) ? row.at("name") : ""; const auto uuid = (row.count("uuid") > 0) ? row.at("uuid") : ""; const auto parent_name = (row.count("parent") > 0 ? row.at("parent") : ""); genFDEStatusForBlockDevice( name, uuid, parent_name, encrypted_rows, results); } return results; } } } <|endoftext|>
<commit_before>#include "Memory.h" #include "Memory/MBC1.h" #include "Memory/MBC2.h" #include "Memory/MBC3.h" #include "Memory/RomOnly.h" MemoryChip* Memory::createMemoryChipForCartridge(Memory* memory, Cartridge* cartridge) { MemoryChip* chip; switch (cartridge->getCartridgeType()) { case Cartridge::CartridgeType::MBC3: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC3_RAM: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC3_RAM_BATTERY: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC3_TIMER_BATTERY: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC3_TIMER_RAM_BATTERY: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC2_BATTERY: chip = new MBC2(memory, cartridge); break; case Cartridge::CartridgeType::MBC2: chip = new MBC2(memory, cartridge); break; case Cartridge::CartridgeType::MBC1: chip = new MBC1(memory, cartridge); break; case Cartridge::CartridgeType::MBC1_RAM: chip = new MBC1(memory, cartridge); break; case Cartridge::CartridgeType::MBC1_RAM_BATTERY: chip = new MBC1(memory, cartridge); break; case Cartridge::CartridgeType::ROM_RAM: chip = new RomOnly(memory, cartridge); break; case Cartridge::CartridgeType::ROM_RAM_BATTERY: chip = new RomOnly(memory, cartridge); break; case Cartridge::CartridgeType::ROM_ONLY: chip = new RomOnly(memory, cartridge); break; default: std::cout << "Memory chip not supported yet" << std::endl; exit(-1); break; } return chip; } Memory::Memory(Cartridge *cartridge, Audio *audio, Joypad *joypad) { this->map = new byte[0x10000]; memset(map, 0, 0x10000); this->audio = audio; this->joypad = joypad; this->cartridge = cartridge; loadCartridge(); this->chip = Memory::createMemoryChipForCartridge(this, cartridge); if (cartridge->getRamSize() != Cartridge::RamSize::NONE_RAM) { chip->load(cartridge->getTitle()); } } void Memory::init(CPU * cpu) { this->cpu = cpu; } byte Memory::read(const word address) const { if (address <= 0xBFFF) { return chip->read(address); } else if (address == 0xFF00) { return joypad->getState(); } else { return readDirectly(address); } } void Memory::write(const word address, const byte data) { if (address <= 0xBFFF) { chip->write(address, data); } else if ( (address >= 0xC000) && (address <= 0xDFFF) ){ map[address] = data; } else if ( (address > 0xE000) && (address <= 0xFDFF) ) { map[address] = data; map[address -0x2000] = data; } else if ((address >= 0xFEA0) && (address <= 0xFEFF)) { // Not allowed } else if (address == 0xFF04) { map[address] = 0x0; cpu->resetDivRegister(); }else if (address == 0xFF07) { map[address] = data ; switch(data & 0x03) { case 0: cpu->setCurrentClockSpeed(1024); break; case 1: cpu->setCurrentClockSpeed(16); break; case 2: cpu->setCurrentClockSpeed(64); break; case 3: cpu->setCurrentClockSpeed(256); break; default: assert(false); break; } } else if (address == 0xFF41) { // Not allowed } else if (address == 0xFF46){ map[0xFF46] = data; DMA(data); } else if ((address >= 0xFF4C) && (address <= 0xFF7F)) { // Not allowed } else if ( address >= 0xFF10 && address <= 0xFF3F ) { audio->writeAudioRegister(address, data); address[map] = data; } else { writeDirectly(address, data); } } void Memory::DMA(byte data) { for ( int i = 0; i < 0xA0; i++ ) { writeDirectly(0xFE00+i, read((cpu->getAF().hi << 8) + i)); } } void Memory::loadCartridge() const { byte *rom = cartridge->getRom(); for ( int i = 0; i < 0x8000; i++ ) { map[i] = rom[i]; } } void Memory::reset() { map[0xFF05] = 0x00; map[0xFF06] = 0x00; map[0xFF07] = 0x00; map[0xFF0F] = 0xE1; map[0xFF10] = 0x80; map[0xFF11] = 0xBF; map[0xFF12] = 0xF3; map[0xFF14] = 0xBF; map[0xFF16] = 0x3F; map[0xFF17] = 0x00; map[0xFF19] = 0xBF; map[0xFF1A] = 0x7F; map[0xFF1B] = 0xFF; map[0xFF1C] = 0x9F; map[0xFF1E] = 0xBF; map[0xFF20] = 0xFF; map[0xFF21] = 0x00; map[0xFF22] = 0x00; map[0xFF23] = 0xBF; map[0xFF24] = 0x77; map[0xFF25] = 0xF3; map[0xFF26] = 0xF1; map[0xFF40] = 0x91; map[0xFF42] = 0x00; map[0xFF43] = 0x00; map[0xFF45] = 0x00; map[0xFF47] = 0xFC; map[0xFF48] = 0xFF; map[0xFF49] = 0xFF; map[0xFF4A] = 0x00; map[0xFF4B] = 0x00; map[0xFFFF] = 0x00; } Memory::~Memory() { if (cartridge->getRamSize() != Cartridge::RamSize::NONE_RAM) { chip->save(cartridge->getTitle()); } delete []map; } <commit_msg>Cloning the memory also when writting on the ECHOed memory.<commit_after>#include "Memory.h" #include "Memory/MBC1.h" #include "Memory/MBC2.h" #include "Memory/MBC3.h" #include "Memory/RomOnly.h" MemoryChip* Memory::createMemoryChipForCartridge(Memory* memory, Cartridge* cartridge) { MemoryChip* chip; switch (cartridge->getCartridgeType()) { case Cartridge::CartridgeType::MBC3: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC3_RAM: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC3_RAM_BATTERY: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC3_TIMER_BATTERY: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC3_TIMER_RAM_BATTERY: chip = new MBC3(memory, cartridge); break; case Cartridge::CartridgeType::MBC2_BATTERY: chip = new MBC2(memory, cartridge); break; case Cartridge::CartridgeType::MBC2: chip = new MBC2(memory, cartridge); break; case Cartridge::CartridgeType::MBC1: chip = new MBC1(memory, cartridge); break; case Cartridge::CartridgeType::MBC1_RAM: chip = new MBC1(memory, cartridge); break; case Cartridge::CartridgeType::MBC1_RAM_BATTERY: chip = new MBC1(memory, cartridge); break; case Cartridge::CartridgeType::ROM_RAM: chip = new RomOnly(memory, cartridge); break; case Cartridge::CartridgeType::ROM_RAM_BATTERY: chip = new RomOnly(memory, cartridge); break; case Cartridge::CartridgeType::ROM_ONLY: chip = new RomOnly(memory, cartridge); break; default: std::cout << "Memory chip not supported yet" << std::endl; exit(-1); break; } return chip; } Memory::Memory(Cartridge *cartridge, Audio *audio, Joypad *joypad) { this->map = new byte[0x10000]; memset(map, 0, 0x10000); this->audio = audio; this->joypad = joypad; this->cartridge = cartridge; loadCartridge(); this->chip = Memory::createMemoryChipForCartridge(this, cartridge); if (cartridge->getRamSize() != Cartridge::RamSize::NONE_RAM) { chip->load(cartridge->getTitle()); } } void Memory::init(CPU * cpu) { this->cpu = cpu; } byte Memory::read(const word address) const { if (address <= 0xBFFF) { return chip->read(address); } else if (address == 0xFF00) { return joypad->getState(); } else { return readDirectly(address); } } void Memory::write(const word address, const byte data) { if (address <= 0xBFFF) { chip->write(address, data); } else if ( (address >= 0xC000) && (address <= 0xDFFF) ){ map[address] = data; if (address <= 0xDDFF) { map[address + 0x2000] = data; } } else if ( (address > 0xE000) && (address <= 0xFDFF) ) { map[address] = data; map[address - 0x2000] = data; } else if ((address >= 0xFEA0) && (address <= 0xFEFF)) { // Not allowed } else if (address == 0xFF04) { map[address] = 0x0; cpu->resetDivRegister(); }else if (address == 0xFF07) { map[address] = data ; switch(data & 0x03) { case 0: cpu->setCurrentClockSpeed(1024); break; case 1: cpu->setCurrentClockSpeed(16); break; case 2: cpu->setCurrentClockSpeed(64); break; case 3: cpu->setCurrentClockSpeed(256); break; default: assert(false); break; } } else if (address == 0xFF41) { // Not allowed } else if (address == 0xFF46){ map[0xFF46] = data; DMA(data); } else if ((address >= 0xFF4C) && (address <= 0xFF7F)) { // Not allowed } else if ( address >= 0xFF10 && address <= 0xFF3F ) { audio->writeAudioRegister(address, data); address[map] = data; } else { writeDirectly(address, data); } } void Memory::DMA(byte data) { for ( int i = 0; i < 0xA0; i++ ) { writeDirectly(0xFE00+i, read((cpu->getAF().hi << 8) + i)); } } void Memory::loadCartridge() const { byte *rom = cartridge->getRom(); for ( int i = 0; i < 0x8000; i++ ) { map[i] = rom[i]; } } void Memory::reset() { map[0xFF05] = 0x00; map[0xFF06] = 0x00; map[0xFF07] = 0x00; map[0xFF0F] = 0xE1; map[0xFF10] = 0x80; map[0xFF11] = 0xBF; map[0xFF12] = 0xF3; map[0xFF14] = 0xBF; map[0xFF16] = 0x3F; map[0xFF17] = 0x00; map[0xFF19] = 0xBF; map[0xFF1A] = 0x7F; map[0xFF1B] = 0xFF; map[0xFF1C] = 0x9F; map[0xFF1E] = 0xBF; map[0xFF20] = 0xFF; map[0xFF21] = 0x00; map[0xFF22] = 0x00; map[0xFF23] = 0xBF; map[0xFF24] = 0x77; map[0xFF25] = 0xF3; map[0xFF26] = 0xF1; map[0xFF40] = 0x91; map[0xFF42] = 0x00; map[0xFF43] = 0x00; map[0xFF45] = 0x00; map[0xFF47] = 0xFC; map[0xFF48] = 0xFF; map[0xFF49] = 0xFF; map[0xFF4A] = 0x00; map[0xFF4B] = 0x00; map[0xFFFF] = 0x00; } Memory::~Memory() { if (cartridge->getRamSize() != Cartridge::RamSize::NONE_RAM) { chip->save(cartridge->getTitle()); } delete []map; } <|endoftext|>
<commit_before>#ifndef __RULE_GENERATOR_HPP__ #define __RULE_GENERATOR_HPP__ #include <string> #include <tuple> #include <type_traits> #include <boost/function_types/result_type.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/function_arity.hpp> #include "boost/mpl/at.hpp" template <typename T, T *ptr> struct FunctionPointer; template <typename Ret, typename... Args, Ret (*f)(Args...)> struct FunctionPointer<Ret(Args...), f> { Ret operator()(Args... args) { return f(args...); } }; #define FUNCTION(x) \ std::tuple<decltype(x), FunctionPointer<decltype(x), &x>, MetaString<_S(#x)> > #define FUNCTOR(x) std::tuple<decltype(&x::operator()), x, MetaString<_S(#x)> > enum ComposeResult { RuleNotApplicable, Composable, NotComposable, OutOfArityBounds }; template <typename F, typename G, int Par> struct ComposabilityHelper { typedef typename boost::function_types::result_type<G>::type RetType; typedef typename boost::mpl::at_c<boost::function_types::parameter_types<F>, Par>::type ArgType; static const bool value = std::is_convertible<RetType, ArgType>::value; }; template <typename T, typename U> struct ComposabilityRule; // Determines if two functions are composable, where // both are represented by their decltypes (F, G) // and their names (FName, GName). template <typename F, typename FOType, typename FName, typename G, typename GOType, typename GName> struct ComposabilityRule<std::tuple<F, FOType, FName>, std::tuple<G, GOType, GName> > { typedef ComposabilityRule<std::tuple<F, FOType, FName>, std::tuple<G, GOType, GName> > type; typedef F Function; typedef FName FunctionName; typedef FOType ObjectType; static const int arity = boost::function_types::function_arity<F>::value; // Checks if this rule is applicable to determining the // composability of the functions f and g // (i.e. whether f refers to FName and g to GName), // and if so, decides whether they are composable or not. static ComposeResult TryCompose(const std::string &f, const std::string &g, int parameter = 0) { // TODO: support arbitary number of arity const bool composable[5] = { ComposabilityHelper<F, G, 0>::value, ComposabilityHelper<F, G, 1>::value, ComposabilityHelper<F, G, 2>::value, ComposabilityHelper<F, G, 3>::value, ComposabilityHelper<F, G, 4>::value }; if (parameter > arity) return OutOfArityBounds; if (!FName::Equals(f) || !GName::Equals(g)) { return RuleNotApplicable; } else { return composable[parameter] ? Composable : NotComposable; } } // Gets the runtime name of the inner function G if // F and G are composable (and f is the name of F). static std::string GetInnerFunction(const std::string &f, int parameter = 0) { const bool composable[5] = { ComposabilityHelper<F, G, 0>::value, ComposabilityHelper<F, G, 1>::value, ComposabilityHelper<F, G, 2>::value, ComposabilityHelper<F, G, 3>::value, ComposabilityHelper<F, G, 4>::value }; if (!FName::Equals(f)) { return ""; } else { return composable[parameter] ? GName::GetRuntimeString() : ""; } } }; #endif <commit_msg>Minor runtime optimalization of rule_generator.<commit_after>#ifndef __RULE_GENERATOR_HPP__ #define __RULE_GENERATOR_HPP__ #include <string> #include <tuple> #include <type_traits> #include <boost/function_types/result_type.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/function_arity.hpp> #include "boost/mpl/at.hpp" template <typename T, T *ptr> struct FunctionPointer; template <typename Ret, typename... Args, Ret (*f)(Args...)> struct FunctionPointer<Ret(Args...), f> { Ret operator()(Args... args) { return f(args...); } }; #define FUNCTION(x) \ std::tuple<decltype(x), FunctionPointer<decltype(x), &x>, MetaString<_S(#x)> > #define FUNCTOR(x) std::tuple<decltype(&x::operator()), x, MetaString<_S(#x)> > enum ComposeResult { RuleNotApplicable, Composable, NotComposable, OutOfArityBounds }; template <typename F, typename G, int Par> struct ComposabilityHelper { typedef typename boost::function_types::result_type<G>::type RetType; typedef typename boost::mpl::at_c<boost::function_types::parameter_types<F>, Par>::type ArgType; static const bool value = std::is_convertible<RetType, ArgType>::value; }; template <typename T, typename U> struct ComposabilityRule; // Determines if two functions are composable, where // both are represented by their decltypes (F, G) // and their names (FName, GName). template <typename F, typename FOType, typename FName, typename G, typename GOType, typename GName> struct ComposabilityRule<std::tuple<F, FOType, FName>, std::tuple<G, GOType, GName> > { typedef ComposabilityRule<std::tuple<F, FOType, FName>, std::tuple<G, GOType, GName> > type; typedef F Function; typedef FName FunctionName; typedef FOType ObjectType; static const int arity = boost::function_types::function_arity<F>::value; // Checks if this rule is applicable to determining the // composability of the functions f and g // (i.e. whether f refers to FName and g to GName), // and if so, decides whether they are composable or not. static ComposeResult TryCompose(const std::string &f, const std::string &g, int parameter = 0) { // TODO: support arbitary number of arity static constexpr bool composable[5] = { ComposabilityHelper<F, G, 0>::value, ComposabilityHelper<F, G, 1>::value, ComposabilityHelper<F, G, 2>::value, ComposabilityHelper<F, G, 3>::value, ComposabilityHelper<F, G, 4>::value }; if (parameter > arity) return OutOfArityBounds; if (!FName::Equals(f) || !GName::Equals(g)) { return RuleNotApplicable; } else { return composable[parameter] ? Composable : NotComposable; } } // Gets the runtime name of the inner function G if // F and G are composable (and f is the name of F). static std::string GetInnerFunction(const std::string &f, int parameter = 0) { static constexpr bool composable[5] = { ComposabilityHelper<F, G, 0>::value, ComposabilityHelper<F, G, 1>::value, ComposabilityHelper<F, G, 2>::value, ComposabilityHelper<F, G, 3>::value, ComposabilityHelper<F, G, 4>::value }; if (!FName::Equals(f)) { return ""; } else { return composable[parameter] ? GName::GetRuntimeString() : ""; } } }; #endif <|endoftext|>
<commit_before>//===- PDBSymbolFunc.cpp - --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDBSymbol.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" #include "llvm/Support/Format.h" #include <utility> using namespace llvm; PDBSymbolFunc::PDBSymbolFunc(const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol) : PDBSymbol(PDBSession, std::move(Symbol)) {} std::unique_ptr<PDBSymbolTypeFunctionSig> PDBSymbolFunc::getSignature() const { return Session.getConcreteSymbolById<PDBSymbolTypeFunctionSig>(getTypeId()); } void PDBSymbolFunc::dump(raw_ostream &OS, int Indent, PDB_DumpLevel Level) const { OS << stream_indent(Indent); if (Level >= PDB_DumpLevel::Normal) { uint32_t FuncStart = getRelativeVirtualAddress(); uint32_t FuncEnd = FuncStart + getLength(); if (FuncStart == 0 && FuncEnd == 0) { OS << "func [???] "; } else { OS << "func "; OS << "[" << format_hex(FuncStart, 8); if (auto DebugStart = findOneChild<PDBSymbolFuncDebugStart>()) OS << "+" << DebugStart->getRelativeVirtualAddress() - FuncStart; OS << " - " << format_hex(FuncEnd, 8); if (auto DebugEnd = findOneChild<PDBSymbolFuncDebugEnd>()) OS << "-" << FuncEnd - DebugEnd->getRelativeVirtualAddress(); OS << "] "; } PDB_RegisterId Reg = getLocalBasePointerRegisterId(); if (Reg == PDB_RegisterId::VFrame) OS << "(VFrame)"; else if (hasFramePointer()) OS << "(" << Reg << ")"; else OS << "(FPO)"; OS << " "; uint32_t FuncSigId = getTypeId(); if (auto FuncSig = getSignature()) { // If we have a signature, dump the name with the signature. if (auto ReturnType = FuncSig->getReturnType()) { ReturnType->dump(OS, 0, PDB_DumpLevel::Compact); OS << " "; } OS << FuncSig->getCallingConvention() << " "; if (auto ClassParent = FuncSig->getClassParent()) { ClassParent->dump(OS, 0, PDB_DumpLevel::Compact); OS << "::"; } OS << getName(); FuncSig->dumpArgList(OS); } else { uint32_t ClassId = getClassParentId(); if (ClassId != 0) { if (auto Class = Session.getSymbolById(ClassId)) { if (auto UDT = dyn_cast<PDBSymbolTypeUDT>(Class.get())) OS << UDT->getName() << "::"; else OS << "{class " << Class->getSymTag() << "}::"; } } OS << getName(); } } else { OS << getName(); } } <commit_msg>Fix -Wunused-variable warning.<commit_after>//===- PDBSymbolFunc.cpp - --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h" #include "llvm/DebugInfo/PDB/IPDBSession.h" #include "llvm/DebugInfo/PDB/PDBSymbol.h" #include "llvm/DebugInfo/PDB/PDBSymbolFunc.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h" #include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h" #include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h" #include "llvm/Support/Format.h" #include <utility> using namespace llvm; PDBSymbolFunc::PDBSymbolFunc(const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol) : PDBSymbol(PDBSession, std::move(Symbol)) {} std::unique_ptr<PDBSymbolTypeFunctionSig> PDBSymbolFunc::getSignature() const { return Session.getConcreteSymbolById<PDBSymbolTypeFunctionSig>(getTypeId()); } void PDBSymbolFunc::dump(raw_ostream &OS, int Indent, PDB_DumpLevel Level) const { OS << stream_indent(Indent); if (Level >= PDB_DumpLevel::Normal) { uint32_t FuncStart = getRelativeVirtualAddress(); uint32_t FuncEnd = FuncStart + getLength(); if (FuncStart == 0 && FuncEnd == 0) { OS << "func [???] "; } else { OS << "func "; OS << "[" << format_hex(FuncStart, 8); if (auto DebugStart = findOneChild<PDBSymbolFuncDebugStart>()) OS << "+" << DebugStart->getRelativeVirtualAddress() - FuncStart; OS << " - " << format_hex(FuncEnd, 8); if (auto DebugEnd = findOneChild<PDBSymbolFuncDebugEnd>()) OS << "-" << FuncEnd - DebugEnd->getRelativeVirtualAddress(); OS << "] "; } PDB_RegisterId Reg = getLocalBasePointerRegisterId(); if (Reg == PDB_RegisterId::VFrame) OS << "(VFrame)"; else if (hasFramePointer()) OS << "(" << Reg << ")"; else OS << "(FPO)"; OS << " "; if (auto FuncSig = getSignature()) { // If we have a signature, dump the name with the signature. if (auto ReturnType = FuncSig->getReturnType()) { ReturnType->dump(OS, 0, PDB_DumpLevel::Compact); OS << " "; } OS << FuncSig->getCallingConvention() << " "; if (auto ClassParent = FuncSig->getClassParent()) { ClassParent->dump(OS, 0, PDB_DumpLevel::Compact); OS << "::"; } OS << getName(); FuncSig->dumpArgList(OS); } else { uint32_t ClassId = getClassParentId(); if (ClassId != 0) { if (auto Class = Session.getSymbolById(ClassId)) { if (auto UDT = dyn_cast<PDBSymbolTypeUDT>(Class.get())) OS << UDT->getName() << "::"; else OS << "{class " << Class->getSymTag() << "}::"; } } OS << getName(); } } else { OS << getName(); } } <|endoftext|>
<commit_before>//===--- BaremMetal.cpp - Bare Metal ToolChain ------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BareMetal.h" #include "CommonArgs.h" #include "InputInfo.h" #include "Gnu.h" #include "clang/Basic/VirtualFileSystem.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" using namespace llvm::opt; using namespace clang; using namespace clang::driver; using namespace clang::driver::tools; using namespace clang::driver::toolchains; BareMetal::BareMetal(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) : ToolChain(D, Triple, Args) { getProgramPaths().push_back(getDriver().getInstalledDir()); if (getDriver().getInstalledDir() != getDriver().Dir) getProgramPaths().push_back(getDriver().Dir); } BareMetal::~BareMetal() {} /// Is the triple {arm,thumb}-none-none-{eabi,eabihf} ? static bool isARMBareMetal(const llvm::Triple &Triple) { if (Triple.getArch() != llvm::Triple::arm && Triple.getArch() != llvm::Triple::thumb) return false; if (Triple.getVendor() != llvm::Triple::UnknownVendor) return false; if (Triple.getOS() != llvm::Triple::UnknownOS) return false; if (Triple.getEnvironment() != llvm::Triple::EABI && Triple.getEnvironment() != llvm::Triple::EABIHF) return false; return true; } bool BareMetal::handlesTarget(const llvm::Triple &Triple) { return isARMBareMetal(Triple); } Tool *BareMetal::buildLinker() const { return new tools::baremetal::Linker(*this); } std::string BareMetal::getThreadModel() const { return "single"; } bool BareMetal::isThreadModelSupported(const StringRef Model) const { return Model == "single"; } std::string BareMetal::getRuntimesDir() const { SmallString<128> Dir(getDriver().ResourceDir); llvm::sys::path::append(Dir, "lib", "baremetal"); return Dir.str(); } void BareMetal::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc)) return; if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { SmallString<128> Dir(getDriver().ResourceDir); llvm::sys::path::append(Dir, "include"); addSystemInclude(DriverArgs, CC1Args, Dir.str()); } if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) { SmallString<128> Dir(getDriver().SysRoot); llvm::sys::path::append(Dir, "include"); addSystemInclude(DriverArgs, CC1Args, Dir.str()); } } void BareMetal::addClangTargetOptions(const ArgList &DriverArgs, ArgStringList &CC1Args) const { CC1Args.push_back("-nostdsysteminc"); } std::string BareMetal::findLibCxxIncludePath(CXXStdlibType LibType) const { StringRef SysRoot = getDriver().SysRoot; if (SysRoot.empty()) return ""; switch (LibType) { case ToolChain::CST_Libcxx: { SmallString<128> Dir(SysRoot); llvm::sys::path::append(Dir, "include", "c++", "v1"); return Dir.str(); } case ToolChain::CST_Libstdcxx: { SmallString<128> Dir(SysRoot); llvm::sys::path::append(Dir, "include", "c++"); std::error_code EC; Generic_GCC::GCCVersion Version = {"", -1, -1, -1, "", "", ""}; // Walk the subdirs, and find the one with the newest gcc version: for (vfs::directory_iterator LI = getDriver().getVFS().dir_begin(Dir.str(), EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef VersionText = llvm::sys::path::filename(LI->getName()); auto CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText); if (CandidateVersion.Major == -1) continue; if (CandidateVersion <= Version) continue; Version = CandidateVersion; } if (Version.Major == -1) return ""; llvm::sys::path::append(Dir, Version.Text); return Dir.str(); } } } void BareMetal::AddClangCXXStdlibIncludeArgs( const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc) || DriverArgs.hasArg(options::OPT_nostdlibinc) || DriverArgs.hasArg(options::OPT_nostdincxx)) return; std::string Path = findLibCxxIncludePath(GetCXXStdlibType(DriverArgs)); if (!Path.empty()) addSystemInclude(DriverArgs, CC1Args, Path); } void BareMetal::AddCXXStdlibLibArgs(const ArgList &Args, ArgStringList &CmdArgs) const { switch (GetCXXStdlibType(Args)) { case ToolChain::CST_Libcxx: CmdArgs.push_back("-lc++"); CmdArgs.push_back("-lc++abi"); break; case ToolChain::CST_Libstdcxx: CmdArgs.push_back("-lstdc++"); CmdArgs.push_back("-lsupc++"); break; } CmdArgs.push_back("-lunwind"); } void BareMetal::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs) const { CmdArgs.push_back(Args.MakeArgString("-lclang_rt.builtins-" + getTriple().getArchName() + ".a")); } void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { ArgStringList CmdArgs; auto &TC = static_cast<const toolchains::BareMetal&>(getToolChain()); AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA); CmdArgs.push_back("-Bstatic"); CmdArgs.push_back(Args.MakeArgString("-L" + TC.getRuntimesDir())); Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group, options::OPT_e, options::OPT_s, options::OPT_t, options::OPT_Z_Flag, options::OPT_r}); if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { if (C.getDriver().CCCIsCXX()) TC.AddCXXStdlibLibArgs(Args, CmdArgs); CmdArgs.push_back("-lc"); CmdArgs.push_back("-lm"); TC.AddLinkRuntimeLib(Args, CmdArgs); } CmdArgs.push_back("-o"); CmdArgs.push_back(Output.getFilename()); C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(TC.GetLinkerPath()), CmdArgs, Inputs)); } <commit_msg>Appease more buildbots about r303873<commit_after>//===--- BaremMetal.cpp - Bare Metal ToolChain ------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "BareMetal.h" #include "CommonArgs.h" #include "InputInfo.h" #include "Gnu.h" #include "clang/Basic/VirtualFileSystem.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/DriverDiagnostic.h" #include "clang/Driver/Options.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" using namespace llvm::opt; using namespace clang; using namespace clang::driver; using namespace clang::driver::tools; using namespace clang::driver::toolchains; BareMetal::BareMetal(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) : ToolChain(D, Triple, Args) { getProgramPaths().push_back(getDriver().getInstalledDir()); if (getDriver().getInstalledDir() != getDriver().Dir) getProgramPaths().push_back(getDriver().Dir); } BareMetal::~BareMetal() {} /// Is the triple {arm,thumb}-none-none-{eabi,eabihf} ? static bool isARMBareMetal(const llvm::Triple &Triple) { if (Triple.getArch() != llvm::Triple::arm && Triple.getArch() != llvm::Triple::thumb) return false; if (Triple.getVendor() != llvm::Triple::UnknownVendor) return false; if (Triple.getOS() != llvm::Triple::UnknownOS) return false; if (Triple.getEnvironment() != llvm::Triple::EABI && Triple.getEnvironment() != llvm::Triple::EABIHF) return false; return true; } bool BareMetal::handlesTarget(const llvm::Triple &Triple) { return isARMBareMetal(Triple); } Tool *BareMetal::buildLinker() const { return new tools::baremetal::Linker(*this); } std::string BareMetal::getThreadModel() const { return "single"; } bool BareMetal::isThreadModelSupported(const StringRef Model) const { return Model == "single"; } std::string BareMetal::getRuntimesDir() const { SmallString<128> Dir(getDriver().ResourceDir); llvm::sys::path::append(Dir, "lib", "baremetal"); return Dir.str(); } void BareMetal::AddClangSystemIncludeArgs(const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc)) return; if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { SmallString<128> Dir(getDriver().ResourceDir); llvm::sys::path::append(Dir, "include"); addSystemInclude(DriverArgs, CC1Args, Dir.str()); } if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) { SmallString<128> Dir(getDriver().SysRoot); llvm::sys::path::append(Dir, "include"); addSystemInclude(DriverArgs, CC1Args, Dir.str()); } } void BareMetal::addClangTargetOptions(const ArgList &DriverArgs, ArgStringList &CC1Args) const { CC1Args.push_back("-nostdsysteminc"); } std::string BareMetal::findLibCxxIncludePath(CXXStdlibType LibType) const { StringRef SysRoot = getDriver().SysRoot; if (SysRoot.empty()) return ""; switch (LibType) { case ToolChain::CST_Libcxx: { SmallString<128> Dir(SysRoot); llvm::sys::path::append(Dir, "include", "c++", "v1"); return Dir.str(); } case ToolChain::CST_Libstdcxx: { SmallString<128> Dir(SysRoot); llvm::sys::path::append(Dir, "include", "c++"); std::error_code EC; Generic_GCC::GCCVersion Version = {"", -1, -1, -1, "", "", ""}; // Walk the subdirs, and find the one with the newest gcc version: for (vfs::directory_iterator LI = getDriver().getVFS().dir_begin(Dir.str(), EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef VersionText = llvm::sys::path::filename(LI->getName()); auto CandidateVersion = Generic_GCC::GCCVersion::Parse(VersionText); if (CandidateVersion.Major == -1) continue; if (CandidateVersion <= Version) continue; Version = CandidateVersion; } if (Version.Major == -1) return ""; llvm::sys::path::append(Dir, Version.Text); return Dir.str(); } } llvm_unreachable("unhandled LibType"); } void BareMetal::AddClangCXXStdlibIncludeArgs( const ArgList &DriverArgs, ArgStringList &CC1Args) const { if (DriverArgs.hasArg(options::OPT_nostdinc) || DriverArgs.hasArg(options::OPT_nostdlibinc) || DriverArgs.hasArg(options::OPT_nostdincxx)) return; std::string Path = findLibCxxIncludePath(GetCXXStdlibType(DriverArgs)); if (!Path.empty()) addSystemInclude(DriverArgs, CC1Args, Path); } void BareMetal::AddCXXStdlibLibArgs(const ArgList &Args, ArgStringList &CmdArgs) const { switch (GetCXXStdlibType(Args)) { case ToolChain::CST_Libcxx: CmdArgs.push_back("-lc++"); CmdArgs.push_back("-lc++abi"); break; case ToolChain::CST_Libstdcxx: CmdArgs.push_back("-lstdc++"); CmdArgs.push_back("-lsupc++"); break; } CmdArgs.push_back("-lunwind"); } void BareMetal::AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs) const { CmdArgs.push_back(Args.MakeArgString("-lclang_rt.builtins-" + getTriple().getArchName() + ".a")); } void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const ArgList &Args, const char *LinkingOutput) const { ArgStringList CmdArgs; auto &TC = static_cast<const toolchains::BareMetal&>(getToolChain()); AddLinkerInputs(TC, Inputs, Args, CmdArgs, JA); CmdArgs.push_back("-Bstatic"); CmdArgs.push_back(Args.MakeArgString("-L" + TC.getRuntimesDir())); Args.AddAllArgs(CmdArgs, {options::OPT_L, options::OPT_T_Group, options::OPT_e, options::OPT_s, options::OPT_t, options::OPT_Z_Flag, options::OPT_r}); if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { if (C.getDriver().CCCIsCXX()) TC.AddCXXStdlibLibArgs(Args, CmdArgs); CmdArgs.push_back("-lc"); CmdArgs.push_back("-lm"); TC.AddLinkRuntimeLib(Args, CmdArgs); } CmdArgs.push_back("-o"); CmdArgs.push_back(Output.getFilename()); C.addCommand(llvm::make_unique<Command>(JA, *this, Args.MakeArgString(TC.GetLinkerPath()), CmdArgs, Inputs)); } <|endoftext|>
<commit_before>#pragma once #include <pip/syntax.hpp> #include <functional> #include <unordered_set> namespace pip { // Kinds of declarations. enum decl_kind : int { dk_program, dk_table, dk_meter, }; // Kinds of matching strategies. enum rule_kind : int { rk_exact, rk_prefix, rk_wildcard, rk_range, rk_expr, }; /// The base class of all declarations. A declaration introduces a named /// entity. struct decl : cc::node { decl(decl_kind k, symbol* id) : cc::node(k, {}), id(id) { } void dump(); symbol* id; virtual ~decl() {} }; /// A dataplane program. A dataplane program is defined (primarily) by a /// list of match table and their associated actions. /// /// \todo How do we (or should we?) incorporate other kinds of declarations. /// For example, should we declare ports? Should we declare meters? Group /// actions? Do we need to process the list of declarations to find e.g., /// the entry table? struct program_decl : decl { program_decl(const decl_seq& ds) : decl(dk_program, nullptr), decls(ds) { } program_decl(decl_seq&& ds) : decl(dk_program, nullptr), decls(std::move(ds)) { } ~program_decl() { for(auto d : decls) delete d; } /// A list of declarations. decl_seq decls; }; /// Represents a match in a table. This is a key/value pair where the key /// is a literal expression, and the value is an action list expression. /// The rule kind of this object must match that of the table it /// appears in. struct rule : cc::node { rule(rule_kind k, expr* key, const action_seq& val) : cc::node(0, {}), kind(k), key(key), acts(val) { } rule(rule_kind k, expr* key, action_seq&& val) : cc::node(0, {}), kind(k), key(key), acts(std::move(val)) { } /// The kind of matching operation. rule_kind kind; /// The matched key -- a literal. expr* key; /// The list of actions to be executed. action_seq acts; }; /// A lookup table. Match tables are determined by a matching kind, which /// prescribes the how keys are found in the table. /// /// \todo Support general purpose tables, that can include arbitrary forms /// of matching (e.g., wildcard and exact). Note an exact match in a wildcard /// table is simply one with no don't-care bits. Maybe we don't need to /// generalize this so much. struct table_decl : decl { table_decl(symbol* id, rule_kind k, const action_seq& as, const rule_seq& ms) : decl(dk_table, id), rule(k), prep(as), rules(ms) { } table_decl(symbol* id, rule_kind k, action_seq&& as, rule_seq&& ms) : decl(dk_table, id), rule(k), prep(std::move(as)), rules(std::move(ms)) { } ~table_decl() { for(auto r : rules) delete r; } /// The kind of table. rule_kind rule; /// The sequence of actions used to form the key for lookup. action_seq prep; /// The content of the action table. rule_seq rules; /// A hash table to match keys for exact-match tables std::unordered_set<std::uint64_t, std::hash<std::uint64_t>> key_table; }; /// A flow metering device. /// /// \todo Implement this? struct meter_decl : decl { meter_decl(symbol* id) : decl(dk_meter, id) { } }; // -------------------------------------------------------------------------- // // Operations /// Returns the kind of a declaration. inline decl_kind get_kind(const decl* d) { return static_cast<decl_kind>(d->kind); } } // namespace pip // -------------------------------------------------------------------------- // // Casting namespace cc { template<> struct node_info<pip::program_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_program; } }; template<> struct node_info<pip::table_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_table; } }; template<> struct node_info<pip::meter_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_meter; } }; } // namespace cc <commit_msg>add check for double deletion<commit_after>#pragma once #include <pip/syntax.hpp> #include <functional> #include <unordered_set> namespace pip { // Kinds of declarations. enum decl_kind : int { dk_program, dk_table, dk_meter, }; // Kinds of matching strategies. enum rule_kind : int { rk_exact, rk_prefix, rk_wildcard, rk_range, rk_expr, }; /// The base class of all declarations. A declaration introduces a named /// entity. struct decl : cc::node { decl(decl_kind k, symbol* id) : cc::node(k, {}), id(id) { } void dump(); symbol* id; virtual ~decl() {} }; /// A dataplane program. A dataplane program is defined (primarily) by a /// list of match table and their associated actions. /// /// \todo How do we (or should we?) incorporate other kinds of declarations. /// For example, should we declare ports? Should we declare meters? Group /// actions? Do we need to process the list of declarations to find e.g., /// the entry table? struct program_decl : decl { program_decl(const decl_seq& ds) : decl(dk_program, nullptr), decls(ds) { } program_decl(decl_seq&& ds) : decl(dk_program, nullptr), decls(std::move(ds)) { } ~program_decl() { for(auto d : decls) if(d) delete d; } /// A list of declarations. decl_seq decls; }; /// Represents a match in a table. This is a key/value pair where the key /// is a literal expression, and the value is an action list expression. /// The rule kind of this object must match that of the table it /// appears in. struct rule : cc::node { rule(rule_kind k, expr* key, const action_seq& val) : cc::node(0, {}), kind(k), key(key), acts(val) { } rule(rule_kind k, expr* key, action_seq&& val) : cc::node(0, {}), kind(k), key(key), acts(std::move(val)) { } /// The kind of matching operation. rule_kind kind; /// The matched key -- a literal. expr* key; /// The list of actions to be executed. action_seq acts; }; /// A lookup table. Match tables are determined by a matching kind, which /// prescribes the how keys are found in the table. /// /// \todo Support general purpose tables, that can include arbitrary forms /// of matching (e.g., wildcard and exact). Note an exact match in a wildcard /// table is simply one with no don't-care bits. Maybe we don't need to /// generalize this so much. struct table_decl : decl { table_decl(symbol* id, rule_kind k, const action_seq& as, const rule_seq& ms) : decl(dk_table, id), rule(k), prep(as), rules(ms) { } table_decl(symbol* id, rule_kind k, action_seq&& as, rule_seq&& ms) : decl(dk_table, id), rule(k), prep(std::move(as)), rules(std::move(ms)) { } ~table_decl() { for(auto r : rules) if(r) delete r; } /// The kind of table. rule_kind rule; /// The sequence of actions used to form the key for lookup. action_seq prep; /// The content of the action table. rule_seq rules; /// A hash table to match keys for exact-match tables std::unordered_set<std::uint64_t, std::hash<std::uint64_t>> key_table; }; /// A flow metering device. /// /// \todo Implement this? struct meter_decl : decl { meter_decl(symbol* id) : decl(dk_meter, id) { } }; // -------------------------------------------------------------------------- // // Operations /// Returns the kind of a declaration. inline decl_kind get_kind(const decl* d) { return static_cast<decl_kind>(d->kind); } } // namespace pip // -------------------------------------------------------------------------- // // Casting namespace cc { template<> struct node_info<pip::program_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_program; } }; template<> struct node_info<pip::table_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_table; } }; template<> struct node_info<pip::meter_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_meter; } }; } // namespace cc <|endoftext|>
<commit_before>/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * 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. */ /*! \file refactoring.hpp \brief Refactoring \author Mathias Soeken \author Eleonora Testa */ #pragma once #include <iostream> #include "../networks/mig.hpp" #include "../traits.hpp" #include "../utils/progress_bar.hpp" #include "../utils/stopwatch.hpp" #include "../views/cut_view.hpp" #include "../views/mffc_view.hpp" #include "../views/topo_view.hpp" #include "cleanup.hpp" #include "cut_rewriting.hpp" #include "detail/mffc_utils.hpp" #include "dont_cares.hpp" #include "simulation.hpp" #include <fmt/format.h> #include <kitty/dynamic_truth_table.hpp> namespace mockturtle { /*! \brief Parameters for refactoring. * * The data structure `refactoring_params` holds configurable parameters with * default arguments for `refactoring`. */ struct refactoring_params { /*! \brief Maximum number of PIs in MFFCs. */ uint32_t max_pis{6}; /*! \brief Allow zero-gain substitutions */ bool allow_zero_gain{false}; /*! \brief Use don't cares for optimization. */ bool use_dont_cares{false}; /*! \brief Show progress. */ bool progress{false}; /*! \brief Be verbose. */ bool verbose{false}; }; /*! \brief Statistics for refactoring. * * The data structure `refactoring_stats` provides data collected by running * `refactoring`. */ struct refactoring_stats { /*! \brief Total runtime. */ stopwatch<>::duration time_total{0}; /*! \brief Accumulated runtime for computing MFFCs. */ stopwatch<>::duration time_mffc{0}; /*! \brief Accumulated runtime for rewriting. */ stopwatch<>::duration time_refactoring{0}; /*! \brief Accumulated runtime for simulating MFFCs. */ stopwatch<>::duration time_simulation{0}; void report() const { std::cout << fmt::format( "[i] total time = {:>5.2f} secs\n", to_seconds( time_total ) ); std::cout << fmt::format( "[i] MFFC time = {:>5.2f} secs\n", to_seconds( time_mffc ) ); std::cout << fmt::format( "[i] refactoring time = {:>5.2f} secs\n", to_seconds( time_refactoring ) ); std::cout << fmt::format( "[i] simulation time = {:>5.2f} secs\n", to_seconds( time_simulation ) ); } }; namespace detail { template<class Ntk, class RefactoringFn, class Iterator, class = void> struct has_refactoring_with_dont_cares : std::false_type { }; template<class Ntk, class RefactoringFn, class Iterator> struct has_refactoring_with_dont_cares<Ntk, RefactoringFn, Iterator, std::void_t<decltype( std::declval<RefactoringFn>()( std::declval<Ntk&>(), std::declval<kitty::dynamic_truth_table>(), std::declval<kitty::dynamic_truth_table>(), std::declval<Iterator const&>(), std::declval<Iterator const&>(), std::declval<void( signal<Ntk> )>() ) )>> : std::true_type { }; template<class Ntk, class RefactoringFn, class Iterator> inline constexpr bool has_refactoring_with_dont_cares_v = has_refactoring_with_dont_cares<Ntk, RefactoringFn, Iterator>::value; template<class Ntk, class RefactoringFn, class NodeCostFn> class refactoring_impl { public: refactoring_impl( Ntk& ntk, RefactoringFn&& refactoring_fn, refactoring_params const& ps, refactoring_stats& st, NodeCostFn const& cost_fn ) : ntk( ntk ), refactoring_fn( refactoring_fn ), ps( ps ), st( st ), cost_fn( cost_fn ) {} void run() { const auto size = ntk.size(); progress_bar pbar{ntk.size(), "refactoring |{0}| node = {1:>4} cand = {2:>4} est. reduction = {3:>5}", ps.progress}; stopwatch t( st.time_total ); ntk.clear_visited(); ntk.clear_values(); ntk.foreach_node( [&]( auto const& n ) { ntk.set_value( n, ntk.fanout_size( n ) ); } ); ntk.foreach_gate( [&]( auto const& n, auto i ) { if ( i >= size ) { return false; } if ( ntk.fanout_size( n ) == 0u ) { return true; } const auto mffc = make_with_stopwatch<mffc_view<Ntk>>( st.time_mffc, ntk, n ); pbar( i, i, _candidates, _estimated_gain ); if ( mffc.num_pos() == 0 || mffc.num_pis() > ps.max_pis || mffc.size() < 4 ) { return true; } std::vector<signal<Ntk>> leaves( mffc.num_pis() ); mffc.foreach_pi( [&]( auto const& n, auto j ) { leaves[j] = ntk.make_signal( n ); } ); default_simulator<kitty::dynamic_truth_table> sim( mffc.num_pis() ); const auto tt = call_with_stopwatch( st.time_simulation, [&]() { return simulate<kitty::dynamic_truth_table>( mffc, sim )[0]; } ); signal<Ntk> new_f; { if ( ps.use_dont_cares ) { if constexpr ( has_refactoring_with_dont_cares_v<Ntk, RefactoringFn, decltype( leaves.begin() )> ) { std::vector<node<Ntk>> pivots; for ( auto const& c : leaves ) { pivots.push_back( ntk.get_node( c ) ); } stopwatch t( st.time_refactoring ); refactoring_fn( ntk, tt, satisfiability_dont_cares( ntk, pivots, 16u ), leaves.begin(), leaves.end(), [&]( auto const& f ) { new_f = f; return false; } ); } else { stopwatch t( st.time_refactoring ); refactoring_fn( ntk, tt, leaves.begin(), leaves.end(), [&]( auto const& f ) { new_f = f; return false; } ); } } else { stopwatch t( st.time_refactoring ); refactoring_fn( ntk, tt, leaves.begin(), leaves.end(), [&]( auto const& f ) { new_f = f; return false; } ); } } if ( n == ntk.get_node( new_f ) ) { return true; } int32_t gain = recursive_deref( n ); gain -= recursive_ref( ntk.get_node( new_f ) ); if ( gain > 0 || ( ps.allow_zero_gain && gain == 0 ) ) { ++_candidates; _estimated_gain += gain; ntk.substitute_node( n, new_f ); ntk.set_value( n, 0 ); ntk.set_value( ntk.get_node( new_f ), ntk.fanout_size( ntk.get_node( new_f ) ) ); for ( auto i = 0u; i < leaves.size(); i++ ) { ntk.set_value( ntk.get_node( leaves[i] ), ntk.fanout_size( ntk.get_node( leaves[i] ) ) ); } } else { recursive_deref( ntk.get_node( new_f ) ); recursive_ref( n ); } return true; } ); } private: uint32_t recursive_deref( node<Ntk> const& n ) { /* terminate? */ if ( ntk.is_constant( n ) || ntk.is_pi( n ) ) return 0; /* recursively collect nodes */ uint32_t value{cost_fn( ntk, n )}; ntk.foreach_fanin( n, [&]( auto const& s ) { if ( ntk.decr_value( ntk.get_node( s ) ) == 0 ) { value += recursive_deref( ntk.get_node( s ) ); } } ); return value; } uint32_t recursive_ref( node<Ntk> const& n ) { /* terminate? */ if ( ntk.is_constant( n ) || ntk.is_pi( n ) ) return 0; /* recursively collect nodes */ uint32_t value{cost_fn( ntk, n )}; ntk.foreach_fanin( n, [&]( auto const& s ) { if ( ntk.incr_value( ntk.get_node( s ) ) == 0 ) { value += recursive_ref( ntk.get_node( s ) ); } } ); return value; } private: Ntk& ntk; RefactoringFn&& refactoring_fn; refactoring_params const& ps; refactoring_stats& st; NodeCostFn cost_fn; uint32_t _candidates{0}; uint32_t _estimated_gain{0}; }; } /* namespace detail */ /*! \brief Boolean refactoring. * * This algorithm performs refactoring by collapsing maximal fanout-free cones * (MFFCs) into truth tables and recreate a new network structure from it. * The algorithm performs changes directly in the input network and keeps the * substituted structures dangling in the network. They can be cleaned up using * the `cleanup_dangling` algorithm. * * The refactoring function must be of type `NtkDest::signal(NtkDest&, * kitty::dynamic_truth_table const&, LeavesIterator, LeavesIterator)` where * `LeavesIterator` can be dereferenced to a `NtkDest::signal`. The last two * parameters compose an iterator pair where the distance matches the number of * variables of the truth table that is passed as second parameter. There are * some refactoring algorithms in the folder * `mockturtle/algorithms/node_resyntesis`, since the resynthesis functions * have the same signature. * * **Required network functions:** * - `get_node` * - `size` * - `make_signal` * - `foreach_gate` * - `substitute_node` * - `clear_visited` * - `clear_values` * - `fanout_size` * - `set_value` * - `foreach_node` * * \param ntk Input network (will be changed in-place) * \param refactoring_fn Refactoring function * \param ps Refactoring params * \param pst Refactoring statistics * \param cost_fn Node cost function (a functor with signature `uint32_t(Ntk const&, node<Ntk> const&)`) */ template<class Ntk, class RefactoringFn, class NodeCostFn = detail::unit_cost<Ntk>> void refactoring( Ntk& ntk, RefactoringFn&& refactoring_fn, refactoring_params const& ps = {}, refactoring_stats* pst = nullptr, NodeCostFn const& cost_fn = {} ) { static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" ); static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" ); static_assert( has_size_v<Ntk>, "Ntk does not implement the size method" ); static_assert( has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" ); static_assert( has_foreach_gate_v<Ntk>, "Ntk does not implement the foreach_gate method" ); static_assert( has_substitute_node_v<Ntk>, "Ntk does not implement the substitute_node method" ); static_assert( has_clear_visited_v<Ntk>, "Ntk does not implement the clear_visited method" ); static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the clear_values method" ); static_assert( has_fanout_size_v<Ntk>, "Ntk does not implement the fanout_size method" ); static_assert( has_set_value_v<Ntk>, "Ntk does not implement the set_value method" ); static_assert( has_foreach_node_v<Ntk>, "Ntk does not implement the foreach_node method" ); refactoring_stats st; detail::refactoring_impl<Ntk, RefactoringFn, NodeCostFn> p( ntk, refactoring_fn, ps, st, cost_fn ); p.run(); if ( ps.verbose ) { st.report(); } if ( pst ) { *pst = st; } } } /* namespace mockturtle */ <commit_msg>refactoring: some fixes. (#233)<commit_after>/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * 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. */ /*! \file refactoring.hpp \brief Refactoring \author Mathias Soeken \author Eleonora Testa */ #pragma once #include "../networks/mig.hpp" #include "../traits.hpp" #include "../utils/progress_bar.hpp" #include "../utils/stopwatch.hpp" #include "../views/cut_view.hpp" #include "../views/mffc_view.hpp" #include "../views/topo_view.hpp" #include "cleanup.hpp" #include "cut_rewriting.hpp" #include "detail/mffc_utils.hpp" #include "dont_cares.hpp" #include "simulation.hpp" #include <fmt/format.h> #include <kitty/dynamic_truth_table.hpp> namespace mockturtle { /*! \brief Parameters for refactoring. * * The data structure `refactoring_params` holds configurable parameters with * default arguments for `refactoring`. */ struct refactoring_params { /*! \brief Maximum number of PIs in MFFCs. */ uint32_t max_pis{6}; /*! \brief Allow zero-gain substitutions */ bool allow_zero_gain{false}; /*! \brief Use don't cares for optimization. */ bool use_dont_cares{false}; /*! \brief Show progress. */ bool progress{false}; /*! \brief Be verbose. */ bool verbose{false}; }; /*! \brief Statistics for refactoring. * * The data structure `refactoring_stats` provides data collected by running * `refactoring`. */ struct refactoring_stats { /*! \brief Total runtime. */ stopwatch<>::duration time_total{0}; /*! \brief Accumulated runtime for computing MFFCs. */ stopwatch<>::duration time_mffc{0}; /*! \brief Accumulated runtime for rewriting. */ stopwatch<>::duration time_refactoring{0}; /*! \brief Accumulated runtime for simulating MFFCs. */ stopwatch<>::duration time_simulation{0}; void report() const { std::cout << fmt::format( "[i] total time = {:>5.2f} secs\n", to_seconds( time_total ) ); std::cout << fmt::format( "[i] MFFC time = {:>5.2f} secs\n", to_seconds( time_mffc ) ); std::cout << fmt::format( "[i] refactoring time = {:>5.2f} secs\n", to_seconds( time_refactoring ) ); std::cout << fmt::format( "[i] simulation time = {:>5.2f} secs\n", to_seconds( time_simulation ) ); } }; namespace detail { template<class Ntk, class RefactoringFn, class Iterator, class = void> struct has_refactoring_with_dont_cares : std::false_type { }; template<class Ntk, class RefactoringFn, class Iterator> struct has_refactoring_with_dont_cares<Ntk, RefactoringFn, Iterator, std::void_t<decltype( std::declval<RefactoringFn>()( std::declval<Ntk&>(), std::declval<kitty::dynamic_truth_table>(), std::declval<kitty::dynamic_truth_table>(), std::declval<Iterator const&>(), std::declval<Iterator const&>(), std::declval<void( signal<Ntk> )>() ) )>> : std::true_type { }; template<class Ntk, class RefactoringFn, class Iterator> inline constexpr bool has_refactoring_with_dont_cares_v = has_refactoring_with_dont_cares<Ntk, RefactoringFn, Iterator>::value; template<class Ntk, class RefactoringFn, class NodeCostFn> class refactoring_impl { public: refactoring_impl( Ntk& ntk, RefactoringFn&& refactoring_fn, refactoring_params const& ps, refactoring_stats& st, NodeCostFn const& cost_fn ) : ntk( ntk ), refactoring_fn( refactoring_fn ), ps( ps ), st( st ), cost_fn( cost_fn ) {} void run() { progress_bar pbar{ntk.size(), "refactoring |{0}| node = {1:>4} cand = {2:>4} est. reduction = {3:>5}", ps.progress}; stopwatch t( st.time_total ); ntk.clear_visited(); ntk.clear_values(); ntk.foreach_node( [&]( auto const& n ) { ntk.set_value( n, ntk.fanout_size( n ) ); } ); const auto size = ntk.num_gates(); ntk.foreach_gate( [&]( auto const& n, auto i ) { if ( i >= size ) { return false; } if ( ntk.fanout_size( n ) == 0u ) { return true; } const auto mffc = make_with_stopwatch<mffc_view<Ntk>>( st.time_mffc, ntk, n ); pbar( i, i, _candidates, _estimated_gain ); if ( mffc.num_pos() == 0 || mffc.num_pis() > ps.max_pis || mffc.size() < 4 ) { return true; } std::vector<signal<Ntk>> leaves( mffc.num_pis() ); mffc.foreach_pi( [&]( auto const& n, auto j ) { leaves[j] = ntk.make_signal( n ); } ); default_simulator<kitty::dynamic_truth_table> sim( mffc.num_pis() ); const auto tt = call_with_stopwatch( st.time_simulation, [&]() { return simulate<kitty::dynamic_truth_table>( mffc, sim )[0]; } ); signal<Ntk> new_f; { if ( ps.use_dont_cares ) { if constexpr ( has_refactoring_with_dont_cares_v<Ntk, RefactoringFn, decltype( leaves.begin() )> ) { std::vector<node<Ntk>> pivots; for ( auto const& c : leaves ) { pivots.push_back( ntk.get_node( c ) ); } stopwatch t( st.time_refactoring ); refactoring_fn( ntk, tt, satisfiability_dont_cares( ntk, pivots, 16u ), leaves.begin(), leaves.end(), [&]( auto const& f ) { new_f = f; return false; } ); } else { stopwatch t( st.time_refactoring ); refactoring_fn( ntk, tt, leaves.begin(), leaves.end(), [&]( auto const& f ) { new_f = f; return false; } ); } } else { stopwatch t( st.time_refactoring ); refactoring_fn( ntk, tt, leaves.begin(), leaves.end(), [&]( auto const& f ) { new_f = f; return false; } ); } } if ( n == ntk.get_node( new_f ) ) { return true; } int32_t gain = recursive_deref( n ); gain -= recursive_ref( ntk.get_node( new_f ) ); if ( gain > 0 || ( ps.allow_zero_gain && gain == 0 ) ) { ++_candidates; _estimated_gain += gain; ntk.substitute_node( n, new_f ); ntk.set_value( n, 0 ); ntk.set_value( ntk.get_node( new_f ), ntk.fanout_size( ntk.get_node( new_f ) ) ); for ( auto i = 0u; i < leaves.size(); i++ ) { ntk.set_value( ntk.get_node( leaves[i] ), ntk.fanout_size( ntk.get_node( leaves[i] ) ) ); } } else { recursive_deref( ntk.get_node( new_f ) ); recursive_ref( n ); } return true; } ); } private: uint32_t recursive_deref( node<Ntk> const& n ) { /* terminate? */ if ( ntk.is_constant( n ) || ntk.is_pi( n ) ) return 0; /* recursively collect nodes */ uint32_t value{cost_fn( ntk, n )}; ntk.foreach_fanin( n, [&]( auto const& s ) { if ( ntk.decr_value( ntk.get_node( s ) ) == 0 ) { value += recursive_deref( ntk.get_node( s ) ); } } ); return value; } uint32_t recursive_ref( node<Ntk> const& n ) { /* terminate? */ if ( ntk.is_constant( n ) || ntk.is_pi( n ) ) return 0; /* recursively collect nodes */ uint32_t value{cost_fn( ntk, n )}; ntk.foreach_fanin( n, [&]( auto const& s ) { if ( ntk.incr_value( ntk.get_node( s ) ) == 0 ) { value += recursive_ref( ntk.get_node( s ) ); } } ); return value; } private: Ntk& ntk; RefactoringFn&& refactoring_fn; refactoring_params const& ps; refactoring_stats& st; NodeCostFn cost_fn; uint32_t _candidates{0}; uint32_t _estimated_gain{0}; }; } /* namespace detail */ /*! \brief Boolean refactoring. * * This algorithm performs refactoring by collapsing maximal fanout-free cones * (MFFCs) into truth tables and recreating a new network structure from it. * The algorithm performs changes directly in the input network and keeps the * substituted structures dangling in the network. They can be cleaned up using * the `cleanup_dangling` algorithm. * * The refactoring function must be of type `NtkDest::signal(NtkDest&, * kitty::dynamic_truth_table const&, LeavesIterator, LeavesIterator)` where * `LeavesIterator` can be dereferenced to a `NtkDest::signal`. The last two * parameters compose an iterator pair where the distance matches the number of * variables of the truth table that is passed as second parameter. There are * some refactoring algorithms in the folder * `mockturtle/algorithms/node_resyntesis`, since the resynthesis functions * have the same signature. * * **Required network functions:** * - `get_node` * - `size` * - `make_signal` * - `foreach_gate` * - `substitute_node` * - `clear_visited` * - `clear_values` * - `fanout_size` * - `set_value` * - `foreach_node` * * \param ntk Input network (will be changed in-place) * \param refactoring_fn Refactoring function * \param ps Refactoring params * \param pst Refactoring statistics * \param cost_fn Node cost function (a functor with signature `uint32_t(Ntk const&, node<Ntk> const&)`) */ template<class Ntk, class RefactoringFn, class NodeCostFn = detail::unit_cost<Ntk>> void refactoring( Ntk& ntk, RefactoringFn&& refactoring_fn, refactoring_params const& ps = {}, refactoring_stats* pst = nullptr, NodeCostFn const& cost_fn = {} ) { static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" ); static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" ); static_assert( has_size_v<Ntk>, "Ntk does not implement the size method" ); static_assert( has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" ); static_assert( has_foreach_gate_v<Ntk>, "Ntk does not implement the foreach_gate method" ); static_assert( has_substitute_node_v<Ntk>, "Ntk does not implement the substitute_node method" ); static_assert( has_clear_visited_v<Ntk>, "Ntk does not implement the clear_visited method" ); static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the clear_values method" ); static_assert( has_fanout_size_v<Ntk>, "Ntk does not implement the fanout_size method" ); static_assert( has_set_value_v<Ntk>, "Ntk does not implement the set_value method" ); static_assert( has_foreach_node_v<Ntk>, "Ntk does not implement the foreach_node method" ); refactoring_stats st; detail::refactoring_impl<Ntk, RefactoringFn, NodeCostFn> p( ntk, refactoring_fn, ps, st, cost_fn ); p.run(); if ( ps.verbose ) { st.report(); } if ( pst ) { *pst = st; } } } /* namespace mockturtle */ <|endoftext|>
<commit_before>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the X86 specific subclass of TargetMachine. // //===----------------------------------------------------------------------===// #include "X86TargetAsmInfo.h" #include "X86TargetMachine.h" #include "X86.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; /// X86TargetMachineModule - Note that this is used on hosts that cannot link /// in a library unless there are references into the library. In particular, /// it seems that it is not possible to get things to work on Win32 without /// this. Though it is unused, do not remove it. extern "C" int X86TargetMachineModule; int X86TargetMachineModule = 0; namespace { // Register the target. RegisterTarget<X86_32TargetMachine> X("x86", " 32-bit X86: Pentium-Pro and above"); RegisterTarget<X86_64TargetMachine> Y("x86-64", " 64-bit X86: EM64T and AMD64"); } const TargetAsmInfo *X86TargetMachine::createTargetAsmInfo() const { return new X86TargetAsmInfo(*this); } unsigned X86_32TargetMachine::getJITMatchQuality() { #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) return 10; #endif return 0; } unsigned X86_64TargetMachine::getJITMatchQuality() { #if defined(__x86_64__) return 10; #endif return 0; } unsigned X86_32TargetMachine::getModuleMatchQuality(const Module &M) { // We strongly match "i[3-9]86-*". std::string TT = M.getTargetTriple(); if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' && TT[4] == '-' && TT[1] - '3' < 6) return 20; if (M.getEndianness() == Module::LittleEndian && M.getPointerSize() == Module::Pointer32) return 10; // Weak match else if (M.getEndianness() != Module::AnyEndianness || M.getPointerSize() != Module::AnyPointerSize) return 0; // Match for some other target return getJITMatchQuality()/2; } unsigned X86_64TargetMachine::getModuleMatchQuality(const Module &M) { // We strongly match "x86_64-*". std::string TT = M.getTargetTriple(); if (TT.size() >= 7 && TT[0] == 'x' && TT[1] == '8' && TT[2] == '6' && TT[3] == '_' && TT[4] == '6' && TT[5] == '4' && TT[6] == '-') return 20; // We strongly match "amd64-*". if (TT.size() >= 6 && TT[0] == 'a' && TT[1] == 'm' && TT[2] == 'd' && TT[3] == '6' && TT[4] == '4' && TT[5] == '-') return 20; if (M.getEndianness() == Module::LittleEndian && M.getPointerSize() == Module::Pointer64) return 10; // Weak match else if (M.getEndianness() != Module::AnyEndianness || M.getPointerSize() != Module::AnyPointerSize) return 0; // Match for some other target return getJITMatchQuality()/2; } X86_32TargetMachine::X86_32TargetMachine(const Module &M, const std::string &FS) : X86TargetMachine(M, FS, false) { } X86_64TargetMachine::X86_64TargetMachine(const Module &M, const std::string &FS) : X86TargetMachine(M, FS, true) { } /// X86TargetMachine ctor - Create an ILP32 architecture model /// X86TargetMachine::X86TargetMachine(const Module &M, const std::string &FS, bool is64Bit) : Subtarget(M, FS, is64Bit), DataLayout(Subtarget.is64Bit() ? std::string("e-p:64:64-f64:32:64-i64:32:64") : std::string("e-p:32:32-f64:32:64-i64:32:64")), FrameInfo(TargetFrameInfo::StackGrowsDown, Subtarget.getStackAlignment(), Subtarget.is64Bit() ? -8 : -4), InstrInfo(*this), JITInfo(*this), TLInfo(*this) { if (getRelocationModel() == Reloc::Default) if (Subtarget.isTargetDarwin() || Subtarget.isTargetCygMing()) setRelocationModel(Reloc::DynamicNoPIC); else setRelocationModel(Reloc::Static); if (Subtarget.is64Bit()) { // No DynamicNoPIC support under X86-64. if (getRelocationModel() == Reloc::DynamicNoPIC) setRelocationModel(Reloc::PIC_); // Default X86-64 code model is small. if (getCodeModel() == CodeModel::Default) setCodeModel(CodeModel::Small); } if (Subtarget.isTargetCygMing()) Subtarget.setPICStyle(PICStyle::WinPIC); else if (Subtarget.isTargetDarwin()) if (Subtarget.is64Bit()) Subtarget.setPICStyle(PICStyle::RIPRel); else Subtarget.setPICStyle(PICStyle::Stub); else if (Subtarget.isTargetELF()) if (Subtarget.is64Bit()) Subtarget.setPICStyle(PICStyle::RIPRel); else Subtarget.setPICStyle(PICStyle::GOT); } //===----------------------------------------------------------------------===// // Pass Pipeline Configuration //===----------------------------------------------------------------------===// bool X86TargetMachine::addInstSelector(FunctionPassManager &PM, bool Fast) { // Install an instruction selector. PM.add(createX86ISelDag(*this, Fast)); return false; } bool X86TargetMachine::addPostRegAlloc(FunctionPassManager &PM, bool Fast) { PM.add(createX86FloatingPointStackifierPass()); return true; // -print-machineinstr should print after this. } bool X86TargetMachine::addAssemblyEmitter(FunctionPassManager &PM, bool Fast, std::ostream &Out) { PM.add(createX86CodePrinterPass(Out, *this)); return false; } bool X86TargetMachine::addCodeEmitter(FunctionPassManager &PM, bool Fast, MachineCodeEmitter &MCE) { // FIXME: Move this to TargetJITInfo! setRelocationModel(Reloc::Static); Subtarget.setPICStyle(PICStyle::None); // JIT cannot ensure globals are placed in the lower 4G of address. if (Subtarget.is64Bit()) setCodeModel(CodeModel::Large); PM.add(createX86CodeEmitterPass(*this, MCE)); return false; } bool X86TargetMachine::addSimpleCodeEmitter(FunctionPassManager &PM, bool Fast, MachineCodeEmitter &MCE) { PM.add(createX86CodeEmitterPass(*this, MCE)); return false; } <commit_msg>80 col. violation.<commit_after>//===-- X86TargetMachine.cpp - Define TargetMachine for the X86 -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the X86 specific subclass of TargetMachine. // //===----------------------------------------------------------------------===// #include "X86TargetAsmInfo.h" #include "X86TargetMachine.h" #include "X86.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/Passes.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetMachineRegistry.h" #include "llvm/Transforms/Scalar.h" using namespace llvm; /// X86TargetMachineModule - Note that this is used on hosts that cannot link /// in a library unless there are references into the library. In particular, /// it seems that it is not possible to get things to work on Win32 without /// this. Though it is unused, do not remove it. extern "C" int X86TargetMachineModule; int X86TargetMachineModule = 0; namespace { // Register the target. RegisterTarget<X86_32TargetMachine> X("x86", " 32-bit X86: Pentium-Pro and above"); RegisterTarget<X86_64TargetMachine> Y("x86-64", " 64-bit X86: EM64T and AMD64"); } const TargetAsmInfo *X86TargetMachine::createTargetAsmInfo() const { return new X86TargetAsmInfo(*this); } unsigned X86_32TargetMachine::getJITMatchQuality() { #if defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) return 10; #endif return 0; } unsigned X86_64TargetMachine::getJITMatchQuality() { #if defined(__x86_64__) return 10; #endif return 0; } unsigned X86_32TargetMachine::getModuleMatchQuality(const Module &M) { // We strongly match "i[3-9]86-*". std::string TT = M.getTargetTriple(); if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' && TT[4] == '-' && TT[1] - '3' < 6) return 20; if (M.getEndianness() == Module::LittleEndian && M.getPointerSize() == Module::Pointer32) return 10; // Weak match else if (M.getEndianness() != Module::AnyEndianness || M.getPointerSize() != Module::AnyPointerSize) return 0; // Match for some other target return getJITMatchQuality()/2; } unsigned X86_64TargetMachine::getModuleMatchQuality(const Module &M) { // We strongly match "x86_64-*". std::string TT = M.getTargetTriple(); if (TT.size() >= 7 && TT[0] == 'x' && TT[1] == '8' && TT[2] == '6' && TT[3] == '_' && TT[4] == '6' && TT[5] == '4' && TT[6] == '-') return 20; // We strongly match "amd64-*". if (TT.size() >= 6 && TT[0] == 'a' && TT[1] == 'm' && TT[2] == 'd' && TT[3] == '6' && TT[4] == '4' && TT[5] == '-') return 20; if (M.getEndianness() == Module::LittleEndian && M.getPointerSize() == Module::Pointer64) return 10; // Weak match else if (M.getEndianness() != Module::AnyEndianness || M.getPointerSize() != Module::AnyPointerSize) return 0; // Match for some other target return getJITMatchQuality()/2; } X86_32TargetMachine::X86_32TargetMachine(const Module &M, const std::string &FS) : X86TargetMachine(M, FS, false) { } X86_64TargetMachine::X86_64TargetMachine(const Module &M, const std::string &FS) : X86TargetMachine(M, FS, true) { } /// X86TargetMachine ctor - Create an ILP32 architecture model /// X86TargetMachine::X86TargetMachine(const Module &M, const std::string &FS, bool is64Bit) : Subtarget(M, FS, is64Bit), DataLayout(Subtarget.is64Bit() ? std::string("e-p:64:64-f64:32:64-i64:32:64") : std::string("e-p:32:32-f64:32:64-i64:32:64")), FrameInfo(TargetFrameInfo::StackGrowsDown, Subtarget.getStackAlignment(), Subtarget.is64Bit() ? -8 : -4), InstrInfo(*this), JITInfo(*this), TLInfo(*this) { if (getRelocationModel() == Reloc::Default) if (Subtarget.isTargetDarwin() || Subtarget.isTargetCygMing()) setRelocationModel(Reloc::DynamicNoPIC); else setRelocationModel(Reloc::Static); if (Subtarget.is64Bit()) { // No DynamicNoPIC support under X86-64. if (getRelocationModel() == Reloc::DynamicNoPIC) setRelocationModel(Reloc::PIC_); // Default X86-64 code model is small. if (getCodeModel() == CodeModel::Default) setCodeModel(CodeModel::Small); } if (Subtarget.isTargetCygMing()) Subtarget.setPICStyle(PICStyle::WinPIC); else if (Subtarget.isTargetDarwin()) if (Subtarget.is64Bit()) Subtarget.setPICStyle(PICStyle::RIPRel); else Subtarget.setPICStyle(PICStyle::Stub); else if (Subtarget.isTargetELF()) if (Subtarget.is64Bit()) Subtarget.setPICStyle(PICStyle::RIPRel); else Subtarget.setPICStyle(PICStyle::GOT); } //===----------------------------------------------------------------------===// // Pass Pipeline Configuration //===----------------------------------------------------------------------===// bool X86TargetMachine::addInstSelector(FunctionPassManager &PM, bool Fast) { // Install an instruction selector. PM.add(createX86ISelDag(*this, Fast)); return false; } bool X86TargetMachine::addPostRegAlloc(FunctionPassManager &PM, bool Fast) { PM.add(createX86FloatingPointStackifierPass()); return true; // -print-machineinstr should print after this. } bool X86TargetMachine::addAssemblyEmitter(FunctionPassManager &PM, bool Fast, std::ostream &Out) { PM.add(createX86CodePrinterPass(Out, *this)); return false; } bool X86TargetMachine::addCodeEmitter(FunctionPassManager &PM, bool Fast, MachineCodeEmitter &MCE) { // FIXME: Move this to TargetJITInfo! setRelocationModel(Reloc::Static); Subtarget.setPICStyle(PICStyle::None); // JIT cannot ensure globals are placed in the lower 4G of address. if (Subtarget.is64Bit()) setCodeModel(CodeModel::Large); PM.add(createX86CodeEmitterPass(*this, MCE)); return false; } bool X86TargetMachine::addSimpleCodeEmitter(FunctionPassManager &PM, bool Fast, MachineCodeEmitter &MCE) { PM.add(createX86CodeEmitterPass(*this, MCE)); return false; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "cling/UserInterface/UserInterface.h" #include "cling/MetaProcessor/MetaProcessor.h" #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/PathV1.h" // Fragment copied from LLVM's raw_ostream.cpp #if defined(_MSC_VER) #ifndef STDIN_FILENO # define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO # define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO # define STDERR_FILENO 2 #endif #else //#if defined(HAVE_UNISTD_H) # include <unistd.h> //#endif #endif namespace cling { UserInterface::UserInterface(Interpreter& interp) { // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false); m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts)); } UserInterface::~UserInterface() {} void UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { PrintLogo(); } // History file is $HOME/.cling_history static const char* histfile = ".cling_history"; llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory(); histfilePath.appendComponent(histfile); using namespace textinput; StreamReader* R = StreamReader::Create(); TerminalDisplay* D = TerminalDisplay::Create(); TextInput TI(*R, *D, histfilePath.c_str()); TI.SetPrompt("[cling]$ "); std::string line; while (true) { m_MetaProcessor->getOuts().flush(); TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { break; } int indent = m_MetaProcessor->process(line.c_str()); // Quit requested if (indent < 0) break; std::string Prompt = "[cling]"; if (m_MetaProcessor->getInterpreter().isRawInputEnabled()) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } } void UserInterface::PrintLogo() { llvm::raw_ostream& outs = m_MetaProcessor->getOuts(); outs << "\n"; outs << "****************** CLING ******************" << "\n"; outs << "* Type C++ code and press enter to run it *" << "\n"; outs << "* Type .q to exit *" << "\n"; outs << "*******************************************" << "\n"; } } // end namespace cling <commit_msg>We have HAVE_UNISTD_H through LLVM buildsystem.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Axel Naumann <axel@cern.ch> //------------------------------------------------------------------------------ #include "cling/UserInterface/UserInterface.h" #include "cling/MetaProcessor/MetaProcessor.h" #include "textinput/TextInput.h" #include "textinput/StreamReader.h" #include "textinput/TerminalDisplay.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/PathV1.h" // Fragment copied from LLVM's raw_ostream.cpp #if defined(HAVE_UNISTD_H) # include <unistd.h> #endif #if defined(_MSC_VER) #ifndef STDIN_FILENO # define STDIN_FILENO 0 #endif #ifndef STDOUT_FILENO # define STDOUT_FILENO 1 #endif #ifndef STDERR_FILENO # define STDERR_FILENO 2 #endif #endif namespace cling { UserInterface::UserInterface(Interpreter& interp) { // We need stream that doesn't close its file descriptor, thus we are not // using llvm::outs. Keeping file descriptor open we will be able to use // the results in pipes (Savannah #99234). static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false); m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts)); } UserInterface::~UserInterface() {} void UserInterface::runInteractively(bool nologo /* = false */) { if (!nologo) { PrintLogo(); } // History file is $HOME/.cling_history static const char* histfile = ".cling_history"; llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory(); histfilePath.appendComponent(histfile); using namespace textinput; StreamReader* R = StreamReader::Create(); TerminalDisplay* D = TerminalDisplay::Create(); TextInput TI(*R, *D, histfilePath.c_str()); TI.SetPrompt("[cling]$ "); std::string line; while (true) { m_MetaProcessor->getOuts().flush(); TextInput::EReadResult RR = TI.ReadInput(); TI.TakeInput(line); if (RR == TextInput::kRREOF) { break; } int indent = m_MetaProcessor->process(line.c_str()); // Quit requested if (indent < 0) break; std::string Prompt = "[cling]"; if (m_MetaProcessor->getInterpreter().isRawInputEnabled()) Prompt.append("! "); else Prompt.append("$ "); if (indent > 0) // Continuation requested. Prompt.append('?' + std::string(indent * 3, ' ')); TI.SetPrompt(Prompt.c_str()); } } void UserInterface::PrintLogo() { llvm::raw_ostream& outs = m_MetaProcessor->getOuts(); outs << "\n"; outs << "****************** CLING ******************" << "\n"; outs << "* Type C++ code and press enter to run it *" << "\n"; outs << "* Type .q to exit *" << "\n"; outs << "*******************************************" << "\n"; } } // end namespace cling <|endoftext|>
<commit_before>#include <QCloseEvent> #include <QDateTime> #include <QMessageBox> #include <qwt_symbol.h> #include <stdexcept> #include <vector> #include "mainwindow.h" #include "ui_mainwindow.h" const double sampleIUnit = 1000.; const double sampleThicknessUnit = 1000000.; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), config(), configUI(), experiment(this), experimentFatalError(false), dataB(), dataHallU(), dataResistivity(), qwtPlotCurveHallU("Hall U"), qwtPlotCurveResistivity("Resistivity"), ui(new Ui::MainWindow) { experiment.setObjectName("experiment"); ui->setupUi(this); QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show())); QObject::connect(&experiment, SIGNAL(coilBMeasured(double)), ui->coilBDoubleSpinBox, SLOT(setValue(double))); QObject::connect(&experiment, SIGNAL(coilIMeasured(double)), ui->coilCurrMeasDoubleSpinBox, SLOT(setValue(double))); QObject::connect(&experiment, SIGNAL(coilUMeasured(double)), ui->coilVoltMeasDoubleSpinBox, SLOT(setValue(double))); dataB.reserve(1024); dataHallU.reserve(1024); dataResistivity.reserve(1024); ui->qwtPlot->enableAxis(QwtPlot::yRight, true); ui->qwtPlot->setAxisTitle(QwtPlot::yRight, tr("(*) Resistivity [Ω]")); ui->qwtPlot->setAxisTitle(QwtPlot::yLeft, "(×) hall U [V]"); ui->qwtPlot->setAxisTitle(QwtPlot::xBottom, "B [T]"); qwtPlotCurveHallU.attach(ui->qwtPlot); qwtPlotCurveHallU.setStyle(QwtPlotCurve::NoCurve); QwtSymbol *qwtPlotHallUSymbol = new QwtSymbol(QwtSymbol::XCross); qwtPlotHallUSymbol->setColor(QColor(255, 0, 0)); qwtPlotHallUSymbol->setSize(QSize(8, 8)); qwtPlotCurveHallU.setSymbol(qwtPlotHallUSymbol); qwtPlotCurveResistivity.setYAxis(QwtPlot::yRight); qwtPlotCurveResistivity.attach(ui->qwtPlot); qwtPlotCurveResistivity.setStyle(QwtPlotCurve::NoCurve); QwtSymbol *qwtPlotResistivitySymbol = new QwtSymbol(QwtSymbol::Star1); qwtPlotResistivitySymbol->setColor(QColor(0, 255, 0)); qwtPlotResistivitySymbol->setSize(QSize(8, 8)); qwtPlotCurveResistivity.setSymbol(qwtPlotResistivitySymbol); ui->hallProbeNameComboBox->addItems(config.hallProbes()); ui->sampleSizeDoubleSpinBox->setValue(config.sampleSize()); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { if (configUI.isHidden() && configUI.result() == QDialog::Accepted) { event->ignore(); if (!experimentFatalError && experiment.coilI() != 0) { if (QMessageBox::warning( this, "Power is still on!", "Power is still on and should be turned (slowly!) " "off before end of experiment.\n\n" "Exit experiment withought shutdown?", QMessageBox::Yes, QMessageBox::No) != QMessageBox::Yes) { // TODO: Offer shut down. return; } } experiment.close(); config.setCoilIRangeMax(ui->coilCurrMaxDoubleSpinBox->value()); config.setCoilIRangeMin(ui->coilCurrMinDoubleSpinBox->value()); config.setCoilIRangeStep(ui->coilCurrStepDoubleSpinBox->value()); config.setSampleI(ui->sampleCurrDoubleSpinBox->value()); config.setSampleThickness(ui->sampleThicknessDoubleSpinBox->value()/sampleThicknessUnit); hide(); configUI.show(); return; } QMainWindow::closeEvent(event); } void MainWindow::measure(bool single) { experiment.measure(single); ui->coilGroupBox->setEnabled(false); ui->measurePushButton->setEnabled(false); ui->sampleGroupBox->setEnabled(false); ui->startPushButton->setText("Abort"); } void MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double value) { if (ui->coilPowerCheckBox->isChecked()) { ui->measurePushButton->setEnabled(false); ui->startPushButton->setEnabled(false); ui->sweepingProgressBar->setMaximum(0); ui->sweepingWidget->setEnabled(true); experiment.setCoilI(value); } } void MainWindow::on_coilCurrMaxDoubleSpinBox_valueChanged(double val1) { double val2(ui->coilCurrMinDoubleSpinBox->value()); experiment.setCoilIRange(val1, val2); } void MainWindow::on_coilCurrMinDoubleSpinBox_valueChanged(double val1) { double val2(ui->coilCurrMaxDoubleSpinBox->value()); experiment.setCoilIRange(val1, val2); } void MainWindow::on_coilCurrStepDoubleSpinBox_valueChanged(double val) { experiment.setCoilIStep(val); } void MainWindow::on_coilPowerCheckBox_toggled(bool checked) { ui->measurePushButton->setEnabled(false); ui->startPushButton->setEnabled(false); ui->sweepingProgressBar->setMaximum(0); ui->sweepingWidget->setEnabled(true); if (checked) { experiment.setCoilI(ui->coilCurrDoubleSpinBox->value()); } else { experiment.setCoilI(0); } } void MainWindow::on_experiment_fatalError(const QString &errorShort, const QString &errorLong) { QString title("Fatal error in experiment: "); QString text("%1:\n\n%2"); experimentFatalError = true; text = text.arg(errorShort).arg(errorLong); title.append(errorShort); QMessageBox::critical(this, title, text); close(); } void MainWindow::on_experiment_measured(const QString &time, double B, double resistivity, double hallU) { ui->dataTableWidget->insertRow(0); ui->dataTableWidget->setItem( 0, 0, new QTableWidgetItem(QVariant(B).toString())); ui->dataTableWidget->setItem( 0, 1, new QTableWidgetItem(QVariant(resistivity).toString())); ui->dataTableWidget->setItem( 0, 2, new QTableWidgetItem(QVariant(hallU).toString())); ui->dataTableWidget->setItem( 0, 3, new QTableWidgetItem(time)); bool nanInData(false); if (!isnan(B)) { ui->coilBDoubleSpinBox->setValue(B); if (dataB.size() == dataB.capacity()) { int reserve(dataB.capacity() * 2); dataB.resize(reserve); dataHallU.resize(reserve); dataResistivity.resize(reserve); } // TODO: skip NAN data from ploting nanInData |= isnan(hallU); nanInData |= isnan(resistivity); dataB.append(B); dataHallU.append(hallU); dataResistivity.append(resistivity); const double *dataX = dataB.constData(); const int dataSize = dataB.size(); qwtPlotCurveResistivity.setRawSamples( dataX, dataResistivity.constData(), dataSize); qwtPlotCurveHallU.setRawSamples(dataX, dataHallU.constData(), dataSize); ui->qwtPlot->replot(); } else nanInData = true; if(nanInData) ui->statusBar->showMessage("Warning: NAN in data found! ", 5000); } void MainWindow::on_experiment_measurementCompleted() { ui->coilGroupBox->setEnabled(true); ui->sampleGroupBox->setEnabled(true); ui->measurePushButton->setEnabled(true); ui->startPushButton->setText("Start"); } void MainWindow::on_experiment_sweepingCompleted() { ui->measurePushButton->setEnabled(true); ui->startPushButton->setEnabled(true); ui->sweepingProgressBar->setMaximum(100); ui->sweepingWidget->setEnabled(false); } void MainWindow::on_measurePushButton_clicked() { measure(true); } void MainWindow::on_hallProbeDeleteToolButton_clicked() { QString name(ui->hallProbeNameComboBox->currentText()); int idx(ui->hallProbeNameComboBox->findText(name)); if (idx != -1) { ui->hallProbeNameComboBox->removeItem(idx); } config.deleteHallProbeEquationB(name); config.deleteHallProbeSampleSize(name); } void MainWindow::on_hallProbeSaveToolButton_clicked() { QString equation(ui->hallProbeEquationBLineEdit->text()); double size(ui->hallProbeSampleSizeDoubleSpinBox->value()); QString name(ui->hallProbeNameComboBox->currentText()); if (ui->hallProbeNameComboBox->findText(name) == -1) { ui->hallProbeNameComboBox->addItem(name); } config.setHallProbeEquationB(name, equation); config.setHallProbeSampleSize(name, size); experiment.setEquationB(equation); } void MainWindow::on_hallProbeNameComboBox_currentIndexChanged(const QString &currentText) { QString equation(config.hallProbeEquationB(currentText)); double size(config.hallProbeSampleSize(currentText)); ui->hallProbeEquationBLineEdit->setText(equation); ui->hallProbeSampleSizeDoubleSpinBox->setValue(size); experiment.setEquationB(equation); experiment.setSampleSize(size); ui->sampleSizeDoubleSpinBox->setValue(size); } void MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double value) { experiment.setSampleI(value/sampleIUnit); } void MainWindow::on_sampleNameLineEdit_editingFinished() { experiment.setSampleName(ui->sampleNameLineEdit->text()); } void MainWindow::on_sampleSizeDoubleSpinBox_valueChanged(double size) { config.setSampleSize(size); experiment.setSampleSize(size); } void MainWindow::on_sampleThicknessDoubleSpinBox_valueChanged(double value) { experiment.setSampleThickness(value/sampleThicknessUnit); } void MainWindow::on_startPushButton_clicked() { if (experiment.isMeasuring()) { experiment.measurementAbort(); } else { // TODO //experiment.measurementStartIntervall(); measure(false); } } void MainWindow::show() { if (!experiment.open()) return; double val; val = experiment.coilI(); ui->coilCurrDoubleSpinBox->setValue(val); ui->coilPowerCheckBox->setChecked(val != 0); val = experiment.sampleI(); ui->sampleCurrDoubleSpinBox->setValue(val*sampleIUnit); val = experiment.coilMaxI(); ui->coilCurrDoubleSpinBox->setMaximum(val); ui->coilCurrDoubleSpinBox->setMinimum(-val); ui->coilCurrMaxDoubleSpinBox->setMaximum(val); ui->coilCurrMaxDoubleSpinBox->setMinimum(-val); ui->coilCurrMinDoubleSpinBox->setMaximum(val); ui->coilCurrMinDoubleSpinBox->setMinimum(-val); ui->coilCurrStepDoubleSpinBox->setMaximum(val); ui->coilCurrMaxDoubleSpinBox->setValue(config.coilIRangeMax()); ui->coilCurrMinDoubleSpinBox->setValue(config.coilIRangeMin()); ui->coilCurrStepDoubleSpinBox->setValue(config.coilIRangeStep()); ui->sampleCurrDoubleSpinBox->setValue(config.sampleI()); ui->sampleThicknessDoubleSpinBox->setValue(config.sampleThickness()*sampleThicknessUnit); experiment.setCoilIStep(ui->coilCurrStepDoubleSpinBox->value()); QWidget::show(); } void MainWindow::startApp() { configUI.show(); } <commit_msg>fix: reset fatal error indicator<commit_after>#include <QCloseEvent> #include <QDateTime> #include <QMessageBox> #include <qwt_symbol.h> #include <stdexcept> #include <vector> #include "mainwindow.h" #include "ui_mainwindow.h" const double sampleIUnit = 1000.; const double sampleThicknessUnit = 1000000.; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), config(), configUI(), experiment(this), experimentFatalError(false), dataB(), dataHallU(), dataResistivity(), qwtPlotCurveHallU("Hall U"), qwtPlotCurveResistivity("Resistivity"), ui(new Ui::MainWindow) { experiment.setObjectName("experiment"); ui->setupUi(this); QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show())); QObject::connect(&experiment, SIGNAL(coilBMeasured(double)), ui->coilBDoubleSpinBox, SLOT(setValue(double))); QObject::connect(&experiment, SIGNAL(coilIMeasured(double)), ui->coilCurrMeasDoubleSpinBox, SLOT(setValue(double))); QObject::connect(&experiment, SIGNAL(coilUMeasured(double)), ui->coilVoltMeasDoubleSpinBox, SLOT(setValue(double))); dataB.reserve(1024); dataHallU.reserve(1024); dataResistivity.reserve(1024); ui->qwtPlot->enableAxis(QwtPlot::yRight, true); ui->qwtPlot->setAxisTitle(QwtPlot::yRight, tr("(*) Resistivity [Ω]")); ui->qwtPlot->setAxisTitle(QwtPlot::yLeft, "(×) hall U [V]"); ui->qwtPlot->setAxisTitle(QwtPlot::xBottom, "B [T]"); qwtPlotCurveHallU.attach(ui->qwtPlot); qwtPlotCurveHallU.setStyle(QwtPlotCurve::NoCurve); QwtSymbol *qwtPlotHallUSymbol = new QwtSymbol(QwtSymbol::XCross); qwtPlotHallUSymbol->setColor(QColor(255, 0, 0)); qwtPlotHallUSymbol->setSize(QSize(8, 8)); qwtPlotCurveHallU.setSymbol(qwtPlotHallUSymbol); qwtPlotCurveResistivity.setYAxis(QwtPlot::yRight); qwtPlotCurveResistivity.attach(ui->qwtPlot); qwtPlotCurveResistivity.setStyle(QwtPlotCurve::NoCurve); QwtSymbol *qwtPlotResistivitySymbol = new QwtSymbol(QwtSymbol::Star1); qwtPlotResistivitySymbol->setColor(QColor(0, 255, 0)); qwtPlotResistivitySymbol->setSize(QSize(8, 8)); qwtPlotCurveResistivity.setSymbol(qwtPlotResistivitySymbol); ui->hallProbeNameComboBox->addItems(config.hallProbes()); ui->sampleSizeDoubleSpinBox->setValue(config.sampleSize()); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { if (configUI.isHidden() && configUI.result() == QDialog::Accepted) { event->ignore(); if (!experimentFatalError && experiment.coilI() != 0) { if (QMessageBox::warning( this, "Power is still on!", "Power is still on and should be turned (slowly!) " "off before end of experiment.\n\n" "Exit experiment withought shutdown?", QMessageBox::Yes, QMessageBox::No) != QMessageBox::Yes) { // TODO: Offer shut down. return; } } experiment.close(); config.setCoilIRangeMax(ui->coilCurrMaxDoubleSpinBox->value()); config.setCoilIRangeMin(ui->coilCurrMinDoubleSpinBox->value()); config.setCoilIRangeStep(ui->coilCurrStepDoubleSpinBox->value()); config.setSampleI(ui->sampleCurrDoubleSpinBox->value()); config.setSampleThickness(ui->sampleThicknessDoubleSpinBox->value()/sampleThicknessUnit); hide(); configUI.show(); return; } QMainWindow::closeEvent(event); } void MainWindow::measure(bool single) { experiment.measure(single); ui->coilGroupBox->setEnabled(false); ui->measurePushButton->setEnabled(false); ui->sampleGroupBox->setEnabled(false); ui->startPushButton->setText("Abort"); } void MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double value) { if (ui->coilPowerCheckBox->isChecked()) { ui->measurePushButton->setEnabled(false); ui->startPushButton->setEnabled(false); ui->sweepingProgressBar->setMaximum(0); ui->sweepingWidget->setEnabled(true); experiment.setCoilI(value); } } void MainWindow::on_coilCurrMaxDoubleSpinBox_valueChanged(double val1) { double val2(ui->coilCurrMinDoubleSpinBox->value()); experiment.setCoilIRange(val1, val2); } void MainWindow::on_coilCurrMinDoubleSpinBox_valueChanged(double val1) { double val2(ui->coilCurrMaxDoubleSpinBox->value()); experiment.setCoilIRange(val1, val2); } void MainWindow::on_coilCurrStepDoubleSpinBox_valueChanged(double val) { experiment.setCoilIStep(val); } void MainWindow::on_coilPowerCheckBox_toggled(bool checked) { ui->measurePushButton->setEnabled(false); ui->startPushButton->setEnabled(false); ui->sweepingProgressBar->setMaximum(0); ui->sweepingWidget->setEnabled(true); if (checked) { experiment.setCoilI(ui->coilCurrDoubleSpinBox->value()); } else { experiment.setCoilI(0); } } void MainWindow::on_experiment_fatalError(const QString &errorShort, const QString &errorLong) { QString title("Fatal error in experiment: "); QString text("%1:\n\n%2"); experimentFatalError = true; text = text.arg(errorShort).arg(errorLong); title.append(errorShort); QMessageBox::critical(this, title, text); close(); } void MainWindow::on_experiment_measured(const QString &time, double B, double resistivity, double hallU) { ui->dataTableWidget->insertRow(0); ui->dataTableWidget->setItem( 0, 0, new QTableWidgetItem(QVariant(B).toString())); ui->dataTableWidget->setItem( 0, 1, new QTableWidgetItem(QVariant(resistivity).toString())); ui->dataTableWidget->setItem( 0, 2, new QTableWidgetItem(QVariant(hallU).toString())); ui->dataTableWidget->setItem( 0, 3, new QTableWidgetItem(time)); bool nanInData(false); if (!isnan(B)) { ui->coilBDoubleSpinBox->setValue(B); if (dataB.size() == dataB.capacity()) { int reserve(dataB.capacity() * 2); dataB.resize(reserve); dataHallU.resize(reserve); dataResistivity.resize(reserve); } // TODO: skip NAN data from ploting nanInData |= isnan(hallU); nanInData |= isnan(resistivity); dataB.append(B); dataHallU.append(hallU); dataResistivity.append(resistivity); const double *dataX = dataB.constData(); const int dataSize = dataB.size(); qwtPlotCurveResistivity.setRawSamples( dataX, dataResistivity.constData(), dataSize); qwtPlotCurveHallU.setRawSamples(dataX, dataHallU.constData(), dataSize); ui->qwtPlot->replot(); } else nanInData = true; if(nanInData) ui->statusBar->showMessage("Warning: NAN in data found! ", 5000); } void MainWindow::on_experiment_measurementCompleted() { ui->coilGroupBox->setEnabled(true); ui->sampleGroupBox->setEnabled(true); ui->measurePushButton->setEnabled(true); ui->startPushButton->setText("Start"); } void MainWindow::on_experiment_sweepingCompleted() { ui->measurePushButton->setEnabled(true); ui->startPushButton->setEnabled(true); ui->sweepingProgressBar->setMaximum(100); ui->sweepingWidget->setEnabled(false); } void MainWindow::on_measurePushButton_clicked() { measure(true); } void MainWindow::on_hallProbeDeleteToolButton_clicked() { QString name(ui->hallProbeNameComboBox->currentText()); int idx(ui->hallProbeNameComboBox->findText(name)); if (idx != -1) { ui->hallProbeNameComboBox->removeItem(idx); } config.deleteHallProbeEquationB(name); config.deleteHallProbeSampleSize(name); } void MainWindow::on_hallProbeSaveToolButton_clicked() { QString equation(ui->hallProbeEquationBLineEdit->text()); double size(ui->hallProbeSampleSizeDoubleSpinBox->value()); QString name(ui->hallProbeNameComboBox->currentText()); if (ui->hallProbeNameComboBox->findText(name) == -1) { ui->hallProbeNameComboBox->addItem(name); } config.setHallProbeEquationB(name, equation); config.setHallProbeSampleSize(name, size); experiment.setEquationB(equation); } void MainWindow::on_hallProbeNameComboBox_currentIndexChanged(const QString &currentText) { QString equation(config.hallProbeEquationB(currentText)); double size(config.hallProbeSampleSize(currentText)); ui->hallProbeEquationBLineEdit->setText(equation); ui->hallProbeSampleSizeDoubleSpinBox->setValue(size); experiment.setEquationB(equation); experiment.setSampleSize(size); ui->sampleSizeDoubleSpinBox->setValue(size); } void MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double value) { experiment.setSampleI(value/sampleIUnit); } void MainWindow::on_sampleNameLineEdit_editingFinished() { experiment.setSampleName(ui->sampleNameLineEdit->text()); } void MainWindow::on_sampleSizeDoubleSpinBox_valueChanged(double size) { config.setSampleSize(size); experiment.setSampleSize(size); } void MainWindow::on_sampleThicknessDoubleSpinBox_valueChanged(double value) { experiment.setSampleThickness(value/sampleThicknessUnit); } void MainWindow::on_startPushButton_clicked() { if (experiment.isMeasuring()) { experiment.measurementAbort(); } else { // TODO //experiment.measurementStartIntervall(); measure(false); } } void MainWindow::show() { experimentFatalError = false; if (!experiment.open()) return; double val; val = experiment.coilI(); ui->coilCurrDoubleSpinBox->setValue(val); ui->coilPowerCheckBox->setChecked(val != 0); val = experiment.sampleI(); ui->sampleCurrDoubleSpinBox->setValue(val*sampleIUnit); val = experiment.coilMaxI(); ui->coilCurrDoubleSpinBox->setMaximum(val); ui->coilCurrDoubleSpinBox->setMinimum(-val); ui->coilCurrMaxDoubleSpinBox->setMaximum(val); ui->coilCurrMaxDoubleSpinBox->setMinimum(-val); ui->coilCurrMinDoubleSpinBox->setMaximum(val); ui->coilCurrMinDoubleSpinBox->setMinimum(-val); ui->coilCurrStepDoubleSpinBox->setMaximum(val); ui->coilCurrMaxDoubleSpinBox->setValue(config.coilIRangeMax()); ui->coilCurrMinDoubleSpinBox->setValue(config.coilIRangeMin()); ui->coilCurrStepDoubleSpinBox->setValue(config.coilIRangeStep()); ui->sampleCurrDoubleSpinBox->setValue(config.sampleI()); ui->sampleThicknessDoubleSpinBox->setValue(config.sampleThickness()*sampleThicknessUnit); experiment.setCoilIStep(ui->coilCurrStepDoubleSpinBox->value()); QWidget::show(); } void MainWindow::startApp() { configUI.show(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <libport/sys/stat.h> #include <libport/cassert> #include <libport/cstring> #include <libport/cstdlib> #include <libport/cstdio> #include <iostream> #include <libport/config.h> #include <libport/foreach.hh> #include <libport/sysexits.hh> #include <urbi/urbi-root.hh> #include <libport/config.h> #if defined WIN32 # define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Windows #elif defined __APPLE__ # define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Apple #else # define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Linux #endif /*--------. | Helpers | `--------*/ static std::string mygetenv(const std::string& var, const std::string& val = "") { const char* res = getenv(var.c_str()); return res ? std::string(res) : val; } // static void // xsetenv(const std::string& var, const std::string& val, int force) // { // #ifdef WIN32 // if (force || mygetenv(var).empty()) // _putenv(strdup((var + "=" + val).c_str())); // #else // setenv(var.c_str(), val.c_str(), force); // #endif // } /*------------. | Reporting. | `------------*/ static bool debug() { static bool res = mygetenv("GD_LEVEL") == "DUMP"; return res; } # define URBI_ROOT_ECHO(S) \ std::cerr << S << std::endl \ # define URBI_ROOT_DEBUG(Self, S) \ do { \ if (debug()) \ URBI_ROOT_ECHO(Self << ": " << S); \ } while (0) \ # define URBI_ROOT_FATAL(Self, N, S) \ do { \ URBI_ROOT_ECHO(Self << ": " << S); \ exit(N); \ } while (0) /*-----------------. | File constants. | `-----------------*/ static const std::string libext = APPLE_LINUX_WINDOWS(".dylib", ".so", ".dll"); static const std::string separator = APPLE_LINUX_WINDOWS("/", "/", "\\"); static const std::string libdir = APPLE_LINUX_WINDOWS("lib", "lib", "bin"); /// Join path components. static std::string operator/(const std::string& lhs, const std::string& rhs) { return (lhs.empty() ? rhs : rhs.empty() ? lhs : lhs + separator + rhs); } /*-------------------------------------. | Crapy dynamic portability routines. | `-------------------------------------*/ #ifdef WIN32 #define RTLD_LAZY 0 #define RTLD_NOW 0 #define RTLD_GLOBAL 0 static RTLD_HANDLE dlopen(const char* name, int) { RTLD_HANDLE res = LoadLibrary(name); if (res) { char buf[BUFSIZ]; GetModuleFileName(res, buf, sizeof buf - 1); buf[sizeof buf - 1] = 0; } return res; } static void* dlsym(RTLD_HANDLE module, const char* name) { return GetProcAddress(module, name); } static const char* dlerror(DWORD err = GetLastError()) { static char buf[1024]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, 0, (LPTSTR)buf, sizeof buf, 0); return buf; } #else # include <dlfcn.h> #endif typedef std::vector<std::string> strings_type; static strings_type split(std::string lib) { strings_type res; size_t pos; while ((pos = lib.find(':')) != lib.npos) { std::string s = lib.substr(0, pos); lib = lib.substr(pos + 1, lib.npos); #ifdef WIN32 // In case we split "c:\foo" into "c" and "\foo", glue them // together again. if (s[0] == '\\' && !res.empty() && res.back().length() == 1) res.back() += ':' + s; else #endif res.push_back(s); } if (!lib.empty()) res.push_back(lib); return res; } /// \a path does not include the extension. static RTLD_HANDLE xdlopen(const std::string& program, const std::string& msg, std::string path, sysexit status = EX_FAIL, int flags = RTLD_LAZY | RTLD_GLOBAL) { path += LIBPORT_LIBSFX; path += libext; URBI_ROOT_DEBUG(program, "loading library: " << path << " (" << msg << ")"); if (RTLD_HANDLE res = dlopen(path.c_str(), flags)) return res; else URBI_ROOT_FATAL(program, status, "cannot open library: " << path << ": " << dlerror()); } template <typename Res> static Res xdlsym(const std::string& program, const char* modname, RTLD_HANDLE module, const char* name) { URBI_ROOT_DEBUG(program, "loading symbol " << name << " from " << modname); // Reinterpret-cast fails with gcc3 arm. if (Res res = (Res)(dlsym(module, name))) return res; else URBI_ROOT_FATAL(program, 2, "cannot locate " << name << " symbol: " << dlerror()); } static std::string resolve_symlinks(const std::string& logname, const std::string& s) { #if defined WIN32 return s; #else char path[BUFSIZ]; strncpy(path, s.c_str(), BUFSIZ); path[BUFSIZ - 1] = 0; while (readlink(path, path, BUFSIZ) != -1) URBI_ROOT_DEBUG(logname, "unrolling symbolic link: " << path); return path; #endif } /*-----------. | UrbiRoot. | `-----------*/ UrbiRoot::UrbiRoot(const std::string& program, bool static_build) : program_(program) , root_() , handle_libjpeg_(0) , handle_libport_(0) , handle_libsched_(0) , handle_liburbi_(0) , handle_libuobject_(0) { // Find our directory. std::string uroot = mygetenv("URBI_ROOT"); if (!uroot.empty()) { URBI_ROOT_DEBUG(program_, "URBI_ROOT is set, forcing root directory: " << root_); root_ = uroot; } else { URBI_ROOT_DEBUG(program_, "guessing Urbi root: invoked as: " << program_); // Handle the chained symlinks case. std::string argv0 = resolve_symlinks(program_, program); #ifdef WIN32 size_t pos = argv0.find_last_of("/\\"); #else size_t pos = argv0.rfind('/'); #endif if (pos == std::string::npos) { URBI_ROOT_DEBUG(program_, "invoked from the path, looking for ourselves in PATH"); strings_type path = split(mygetenv("PATH")); foreach (const std::string& dir, path) { struct stat stats; std::string file = dir / argv0; if (stat(file.c_str(), &stats) == 0) { URBI_ROOT_DEBUG(program_, "found: " << file); root_ = dir / ".."; URBI_ROOT_DEBUG(program_, "root directory is: " << root_); break; } URBI_ROOT_DEBUG(program_, "not found: " << file); } } else { root_ = argv0.substr(0, pos) / ".."; URBI_ROOT_DEBUG(program_, "invoked with a path, setting root to parent directory: " << root_); } } if (root_.empty()) URBI_ROOT_FATAL(program_, 3, "Unable to find Urbi SDK installation location. " "Please set URBI_ROOT."); // const std::string urbi_path = root_ / "share" / "gostai"; // xsetenv("URBI_PATH", mygetenv("URBI_PATH") + ":" + urbi_path, true); // URBI_ROOT_DEBUG("append to URBI_PATH: " << urbi_path); if (!static_build) { handle_libjpeg_ = library_load("jpeg"); handle_libport_ = library_load("port"); handle_libsched_ = library_load("sched"); handle_libserialize_ = library_load("serialize"); handle_liburbi_ = library_load("urbi"); } } RTLD_HANDLE UrbiRoot::library_load(const std::string& base) { std::string envvar = "URBI_ROOT_LIB" + base; foreach (char& s, envvar) s = toupper(s); return xdlopen(program_, base, mygetenv(envvar, root(libdir / "lib" + base))); } std::string UrbiRoot::root(const std::string& path) const { return root_ / path; } std::string UrbiRoot::core_path(const std::string& path) const { return root_ / "gostai" / "core" / LIBPORT_URBI_HOST / path; } std::string UrbiRoot::uobjects_path(const std::string& path) const { return core_path("uobjects" / path); } std::string UrbiRoot::share_path(const std::string& path) const { return root_ / "share" / "gostai" / path; } void UrbiRoot::load_plugin() { handle_libuobject_ = xdlopen(program_, "plugin UObject implementation", mygetenv("URBI_ROOT_LIBPLUGIN", core_path() / "engine" / "libuobject"), // This exit status is understood by the test suite. It // helps it skipping SDK Remote tests that cannot run // without Urbi SDK. EX_OSFILE); } /// Location of Urbi remote libuobject void UrbiRoot::load_remote() { handle_libuobject_ = xdlopen(program_, "remote UObject implementation", mygetenv("URBI_ROOT_LIBREMOTE", core_path() / "remote" / "libuobject"), EX_OSFILE); } void UrbiRoot::load_custom(const std::string& path_) { handle_libuobject_ = xdlopen(program_, "custom UObject implementation", path_ / "libuobject", EX_OSFILE); } typedef int(*urbi_launch_type)(int, const char*[], UrbiRoot&); int UrbiRoot::urbi_launch(int argc, const char** argv) { urbi_launch_type f = xdlsym<urbi_launch_type>(program_, "liburbi-launch", handle_liburbi_, "urbi_launch"); return f(argc, argv, *this); } int UrbiRoot::urbi_launch(int argc, char** argv) { return urbi_launch(argc, const_cast<const char**>(argv)); } typedef int(*urbi_main_type)(const std::vector<std::string>& args, UrbiRoot& root, bool block, bool errors); int UrbiRoot::urbi_main(const std::vector<std::string>& args, bool block, bool errors) { urbi_main_type f = xdlsym<urbi_main_type>(program_, "libuobject", handle_libuobject_, "urbi_main_args"); URBI_ROOT_DEBUG(program_, "command line: "); foreach (const std::string& arg, args) URBI_ROOT_DEBUG(program_, " " << arg); return f(args, *this, block, errors); } <commit_msg>Permit override of LIBSFX (partial revert of 8782377).<commit_after>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #include <libport/sys/stat.h> #include <libport/cassert> #include <libport/cstring> #include <libport/cstdlib> #include <libport/cstdio> #include <iostream> #include <libport/config.h> #include <libport/foreach.hh> #include <libport/sysexits.hh> #include <urbi/urbi-root.hh> #include <libport/config.h> #if defined WIN32 # define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Windows #elif defined __APPLE__ # define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Apple #else # define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Linux #endif /*--------. | Helpers | `--------*/ static std::string mygetenv(const std::string& var, const std::string& val = "") { const char* res = getenv(var.c_str()); return res ? std::string(res) : val; } // static void // xsetenv(const std::string& var, const std::string& val, int force) // { // #ifdef WIN32 // if (force || mygetenv(var).empty()) // _putenv(strdup((var + "=" + val).c_str())); // #else // setenv(var.c_str(), val.c_str(), force); // #endif // } /*------------. | Reporting. | `------------*/ static bool debug() { static bool res = mygetenv("GD_LEVEL") == "DUMP"; return res; } # define URBI_ROOT_ECHO(S) \ std::cerr << S << std::endl \ # define URBI_ROOT_DEBUG(Self, S) \ do { \ if (debug()) \ URBI_ROOT_ECHO(Self << ": " << S); \ } while (0) \ # define URBI_ROOT_FATAL(Self, N, S) \ do { \ URBI_ROOT_ECHO(Self << ": " << S); \ exit(N); \ } while (0) /*-----------------. | File constants. | `-----------------*/ static const std::string libext = APPLE_LINUX_WINDOWS(".dylib", ".so", ".dll"); static const std::string separator = APPLE_LINUX_WINDOWS("/", "/", "\\"); static const std::string libdir = APPLE_LINUX_WINDOWS("lib", "lib", "bin"); /// Join path components. static std::string operator/(const std::string& lhs, const std::string& rhs) { return (lhs.empty() ? rhs : rhs.empty() ? lhs : lhs + separator + rhs); } /*-------------------------------------. | Crapy dynamic portability routines. | `-------------------------------------*/ #ifdef WIN32 #define RTLD_LAZY 0 #define RTLD_NOW 0 #define RTLD_GLOBAL 0 static RTLD_HANDLE dlopen(const char* name, int) { RTLD_HANDLE res = LoadLibrary(name); if (res) { char buf[BUFSIZ]; GetModuleFileName(res, buf, sizeof buf - 1); buf[sizeof buf - 1] = 0; } return res; } static void* dlsym(RTLD_HANDLE module, const char* name) { return GetProcAddress(module, name); } static const char* dlerror(DWORD err = GetLastError()) { static char buf[1024]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 0, err, 0, (LPTSTR)buf, sizeof buf, 0); return buf; } #else # include <dlfcn.h> #endif typedef std::vector<std::string> strings_type; static strings_type split(std::string lib) { strings_type res; size_t pos; while ((pos = lib.find(':')) != lib.npos) { std::string s = lib.substr(0, pos); lib = lib.substr(pos + 1, lib.npos); #ifdef WIN32 // In case we split "c:\foo" into "c" and "\foo", glue them // together again. if (s[0] == '\\' && !res.empty() && res.back().length() == 1) res.back() += ':' + s; else #endif res.push_back(s); } if (!lib.empty()) res.push_back(lib); return res; } /// \a path does not include the extension. static RTLD_HANDLE xdlopen(const std::string& program, const std::string& msg, std::string path, sysexit status = EX_FAIL, int flags = RTLD_LAZY | RTLD_GLOBAL) { path += libext; URBI_ROOT_DEBUG(program, "loading library: " << path << " (" << msg << ")"); if (RTLD_HANDLE res = dlopen(path.c_str(), flags)) return res; else URBI_ROOT_FATAL(program, status, "cannot open library: " << path << ": " << dlerror()); } template <typename Res> static Res xdlsym(const std::string& program, const char* modname, RTLD_HANDLE module, const char* name) { URBI_ROOT_DEBUG(program, "loading symbol " << name << " from " << modname); // Reinterpret-cast fails with gcc3 arm. if (Res res = (Res)(dlsym(module, name))) return res; else URBI_ROOT_FATAL(program, 2, "cannot locate " << name << " symbol: " << dlerror()); } static std::string resolve_symlinks(const std::string& logname, const std::string& s) { #if defined WIN32 return s; #else char path[BUFSIZ]; strncpy(path, s.c_str(), BUFSIZ); path[BUFSIZ - 1] = 0; while (readlink(path, path, BUFSIZ) != -1) URBI_ROOT_DEBUG(logname, "unrolling symbolic link: " << path); return path; #endif } /*-----------. | UrbiRoot. | `-----------*/ UrbiRoot::UrbiRoot(const std::string& program, bool static_build) : program_(program) , root_() , handle_libjpeg_(0) , handle_libport_(0) , handle_libsched_(0) , handle_liburbi_(0) , handle_libuobject_(0) { // Find our directory. std::string uroot = mygetenv("URBI_ROOT"); if (!uroot.empty()) { URBI_ROOT_DEBUG(program_, "URBI_ROOT is set, forcing root directory: " << root_); root_ = uroot; } else { URBI_ROOT_DEBUG(program_, "guessing Urbi root: invoked as: " << program_); // Handle the chained symlinks case. std::string argv0 = resolve_symlinks(program_, program); #ifdef WIN32 size_t pos = argv0.find_last_of("/\\"); #else size_t pos = argv0.rfind('/'); #endif if (pos == std::string::npos) { URBI_ROOT_DEBUG(program_, "invoked from the path, looking for ourselves in PATH"); strings_type path = split(mygetenv("PATH")); foreach (const std::string& dir, path) { struct stat stats; std::string file = dir / argv0; if (stat(file.c_str(), &stats) == 0) { URBI_ROOT_DEBUG(program_, "found: " << file); root_ = dir / ".."; URBI_ROOT_DEBUG(program_, "root directory is: " << root_); break; } URBI_ROOT_DEBUG(program_, "not found: " << file); } } else { root_ = argv0.substr(0, pos) / ".."; URBI_ROOT_DEBUG(program_, "invoked with a path, setting root to parent directory: " << root_); } } if (root_.empty()) URBI_ROOT_FATAL(program_, 3, "Unable to find Urbi SDK installation location. " "Please set URBI_ROOT."); // const std::string urbi_path = root_ / "share" / "gostai"; // xsetenv("URBI_PATH", mygetenv("URBI_PATH") + ":" + urbi_path, true); // URBI_ROOT_DEBUG("append to URBI_PATH: " << urbi_path); if (!static_build) { handle_libjpeg_ = library_load("jpeg"); handle_libport_ = library_load("port"); handle_libsched_ = library_load("sched"); handle_libserialize_ = library_load("serialize"); handle_liburbi_ = library_load("urbi"); } } RTLD_HANDLE UrbiRoot::library_load(const std::string& base) { std::string envvar = "URBI_ROOT_LIB" + base; foreach (char& s, envvar) s = toupper(s); return xdlopen(program_, base, mygetenv(envvar, root(libdir / "lib" + base + LIBPORT_LIBSFX))); } std::string UrbiRoot::root(const std::string& path) const { return root_ / path; } std::string UrbiRoot::core_path(const std::string& path) const { return root_ / "gostai" / "core" / LIBPORT_URBI_HOST / path; } std::string UrbiRoot::uobjects_path(const std::string& path) const { return core_path("uobjects" / path); } std::string UrbiRoot::share_path(const std::string& path) const { return root_ / "share" / "gostai" / path; } void UrbiRoot::load_plugin() { handle_libuobject_ = xdlopen(program_, "plugin UObject implementation", mygetenv("URBI_ROOT_LIBPLUGIN", core_path() / "engine" / "libuobject"), // This exit status is understood by the test suite. It // helps it skipping SDK Remote tests that cannot run // without Urbi SDK. EX_OSFILE); } /// Location of Urbi remote libuobject void UrbiRoot::load_remote() { handle_libuobject_ = xdlopen(program_, "remote UObject implementation", mygetenv("URBI_ROOT_LIBREMOTE", core_path() / "remote" / "libuobject"), EX_OSFILE); } void UrbiRoot::load_custom(const std::string& path_) { handle_libuobject_ = xdlopen(program_, "custom UObject implementation", path_ / "libuobject", EX_OSFILE); } typedef int(*urbi_launch_type)(int, const char*[], UrbiRoot&); int UrbiRoot::urbi_launch(int argc, const char** argv) { urbi_launch_type f = xdlsym<urbi_launch_type>(program_, "liburbi-launch", handle_liburbi_, "urbi_launch"); return f(argc, argv, *this); } int UrbiRoot::urbi_launch(int argc, char** argv) { return urbi_launch(argc, const_cast<const char**>(argv)); } typedef int(*urbi_main_type)(const std::vector<std::string>& args, UrbiRoot& root, bool block, bool errors); int UrbiRoot::urbi_main(const std::vector<std::string>& args, bool block, bool errors) { urbi_main_type f = xdlsym<urbi_main_type>(program_, "libuobject", handle_libuobject_, "urbi_main_args"); URBI_ROOT_DEBUG(program_, "command line: "); foreach (const std::string& arg, args) URBI_ROOT_DEBUG(program_, " " << arg); return f(args, *this, block, errors); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <functional> #include <sstream> class Parser { public: using Constraint = std::function<bool(std::vector<std::string>)>; Parser(int argc, char **argv); void add_arg(std::string longhand, std::vector<Constraint> constraints={}, std::string shorthand="", bool required = false, std::string description=""); bool check_validity(std::string *const err_msg = nullptr); template <typename T> T get(std::string hand) const; template <typename T> T get_shorthand(std::string shorthand) const; template <typename T> T get_longhand(std::string longhand) const; std::string get_raw() const; private: struct Arg { std::vector<Constraint> constraints; std::string shorthand; std::string longhand; std::string description; bool required; std::vector<std::string> arguments; //arguments to the argument to the program }; std::vector<std::string> _raw_args; std::vector<Arg> _args; }; <commit_msg>rewhitespaced Parser.cpp<commit_after>#include <iostream> #include <string> #include <vector> #include <functional> #include <sstream> class Parser { public: using Constraint = std::function<bool(std::vector<std::string>)>; Parser(int argc, char **argv); void add_arg(std::string longhand, std::vector<Constraint> constraints={}, std::string shorthand="", bool required = false, std::string description=""); bool check_validity(std::string *const err_msg = nullptr); template <typename T> T get(std::string hand) const; template <typename T> T get_shorthand(std::string shorthand) const; template <typename T> T get_longhand(std::string longhand) const; std::string get_raw() const; private: struct Arg { std::vector<Constraint> constraints; std::string shorthand; std::string longhand; std::string description; bool required; std::vector<std::string> arguments; //arguments to the argument to the program }; std::vector<std::string> _raw_args; std::vector<Arg> _args; }; <|endoftext|>
<commit_before>/// \file PwFont.cpp //----------------------------------------------------------------------------- #include "stdafx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif void SetPasswordFont(CWnd* pDlgItem) { // Initialize a CFont object with the characteristics given // in a LOGFONT structure. LOGFONT lf; memset(&lf, 0, sizeof(LOGFONT)); // clear out structure lf.lfHeight = 14; // request a 14-pixel-height font strcpy(lf.lfFaceName, "Courier"); // request a face name "Courier" HFONT hfont = ::CreateFontIndirect(&lf); // create the font if (hfont != NULL) { // Convert the HFONT to CFont*. CFont* pfont = CFont::FromHandle(hfont); if (pfont != NULL) pDlgItem->SetFont(pfont); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- <commit_msg>reduced resource leak when calling CreateFontIndirect to just one leaked item<commit_after>/// \file PwFont.cpp //----------------------------------------------------------------------------- #include "stdafx.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif void SetPasswordFont(CWnd* pDlgItem) { // for now, this keeps the leak down to just one static HFONT hfont = NULL; if ( hfont == NULL ) { // Initialize a CFont object with the characteristics given // in a LOGFONT structure. LOGFONT lf; memset(&lf, 0, sizeof(LOGFONT)); // clear out structure lf.lfHeight = 14; // request a 14-pixel-height font strcpy(lf.lfFaceName, "Courier"); // request a face name "Courier" hfont = ::CreateFontIndirect(&lf); // create the font (must be deleted with ::DeleteObject() } if (hfont != NULL) { // Convert the HFONT to CFont*. CFont* pfont = CFont::FromHandle(hfont); if (pfont != NULL) pDlgItem->SetFont(pfont); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "QNETag.h" #include <QString> #include <QFile> #include <QByteArray> #include <QCryptographicHash> #include <QFileInfo> #include <QDataStream> QNETag::QNETag() { } QNETag::~QNETag() { } QString QNETag::UrlSafeBase64Encode(QByteArray data) { QByteArray encodedData = data.toBase64(); QString encodedStr = QString(encodedData); encodedStr = encodedStr.replace("+","-").replace("/","_"); return encodedStr; } QByteArray QNETag::Sha1(QByteArray data) { QCryptographicHash sha1Hash(QCryptographicHash::Sha1); sha1Hash.addData(data); return sha1Hash.result(); } /* This method will return an non-empty string if the file exists and readable */ QString QNETag::CalcETag(QString fileName) { QString etag = ""; QFileInfo fi(fileName); if(fi.exists() && fi.permission(QFile::ReadUser)) { QFile fh(fileName); bool opened = fh.open(QIODevice::ReadOnly); if (opened){ qint64 fileLen = fh.size(); if(fileLen <= CHUNK_SIZE) { QByteArray fileData = fh.readAll(); QByteArray sha1Data = Sha1(fileData); QByteArray hashData = sha1Data; hashData.insert(0,0x16); etag = UrlSafeBase64Encode(hashData); } else { int chunkCount = fileLen / CHUNK_SIZE; if(fileLen % CHUNK_SIZE != 0) { chunkCount += 1; } QByteArray sha1AllData; for(int i=0; i<chunkCount; i++) { qint64 chunkSize = CHUNK_SIZE; if(i == chunkCount-1) { chunkSize = fileLen-(chunkCount-1)*CHUNK_SIZE; } QByteArray buf = QByteArray(chunkSize,' '); fh.read(buf.data(),chunkSize); QByteArray sha1Data = Sha1(buf); sha1AllData.append(sha1Data); } QByteArray hashData = Sha1(sha1AllData); hashData.insert(0,0x96); etag = UrlSafeBase64Encode(hashData); } fh.close(); } } return etag; } <commit_msg>Fix the error when reading big files.<commit_after>#include "QNETag.h" #include <QString> #include <QFile> #include <QByteArray> #include <QCryptographicHash> #include <QFileInfo> #include <QDataStream> QNETag::QNETag() { } QNETag::~QNETag() { } QString QNETag::UrlSafeBase64Encode(QByteArray data) { QByteArray encodedData = data.toBase64(QByteArray::Base64UrlEncoding); QString encodedStr = QString(encodedData); return encodedStr; } QByteArray QNETag::Sha1(QByteArray data) { QCryptographicHash sha1Hash(QCryptographicHash::Sha1); sha1Hash.addData(data); return sha1Hash.result(); } /* This method will return an non-empty string if the file exists and readable */ QString QNETag::CalcETag(QString fileName) { QString etag = ""; QFileInfo fi(fileName); if(fi.exists() && fi.permission(QFile::ReadUser)) { QFile fh(fileName); bool opened = fh.open(QIODevice::ReadOnly); if (opened){ qint64 fileLen = fh.size(); if(fileLen <= CHUNK_SIZE) { QByteArray fileData = fh.readAll(); QByteArray sha1Data = Sha1(fileData); QByteArray hashData = sha1Data; hashData.prepend(0x16); etag = UrlSafeBase64Encode(hashData); } else { int chunkCount = fileLen / CHUNK_SIZE; if(fileLen % CHUNK_SIZE != 0) { chunkCount += 1; } QByteArray sha1AllData; for(int i=0; i<chunkCount; i++) { qint64 chunkSize = CHUNK_SIZE; if(i == chunkCount-1) { chunkSize = fileLen-(chunkCount-1)*CHUNK_SIZE; } QByteArray buf=fh.read(chunkSize); QByteArray sha1Data = Sha1(buf); sha1AllData.append(sha1Data); } QByteArray hashData = Sha1(sha1AllData); hashData.prepend(0x96); etag = UrlSafeBase64Encode(hashData); } fh.close(); } } return etag; } <|endoftext|>
<commit_before>#include <sstream> #include "helper_functions.h" using namespace std; bool compareArr(const int* array1, const int* array2){ while (*array1 != 0 || *array2 != 0){ if (*array1 != *array2){ return false; } *array1++; *array2++; } return true; } // See interface (header file). unsigned int countNumOfArgTypes(int *argTypes) { unsigned int count = 1; while (argTypes[(count - 1)] != 0) { count += 1; } return count; } int *copyArgTypes(int *argTypes) { unsigned int argTypesLength = 0; while (argTypes[argTypesLength]){ argTypesLength++; } int *memArgTypes = new int[argTypesLength]; unsigned int i = 0; while (argTypes[i] != 0) { memArgTypes[i] = argTypes[i]; i++; } memArgTypes[i] = 0; return memArgTypes; } // See interface (header file). string toString(unsigned int number) { stringstream ss; ss << number; return ss.str(); } // See interface (header file). unsigned int toUnsignedInteger(string text) { stringstream ss; ss << text; unsigned int number = 0; ss >> number; return number; } <commit_msg>add helper functions<commit_after>#include <sstream> #include "helper_functions.h" using namespace std; bool compareArr(const int* array1, const int* array2){ while (*array1 != 0 || *array2 != 0){ if (*array1 != *array2){ return false; } *array1++; *array2++; } return true; } // See interface (header file). unsigned int countNumOfArgTypes(int *argTypes) { unsigned int count = 1; while (argTypes[(count - 1)] != 0) { count += 1; } return count; } int *copyArgTypes(int *argTypes) { unsigned int argTypesLength = 0; while (argTypes[argTypesLength]){ argTypesLength++; } int *memArgTypes = new int[argTypesLength]; unsigned int i = 0; while (argTypes[i] != 0) { memArgTypes[i] = argTypes[i]; i++; } memArgTypes[i] = 0; return memArgTypes; } // See interface (header file). string toString(unsigned int number) { stringstream ss; ss << number; return ss.str(); } // See interface (header file). unsigned int toUnsignedInteger(string text) { stringstream ss; ss << text; unsigned int number = 0; ss >> number; return number; } // See interface (header file). short toShort(char *array) { return *(static_cast<short *>(array)); } // See interface (header file). int toInt(char *array) { return *(static_cast<int *>(array)); } // See interface (header file). long toLong(char *array) { return *(static_cast<long *>(array)); } // See interface (header file). double toDouble(char *array) { return *(static_cast<double *>(array)); } // See interface (header file). float toFloat(char *array) { return *(static_cast<float *>(array)); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: querystatus.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 18:06:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFXQUERYSTATUS_HXX #include <querystatus.hxx> #endif #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #include <svtools/intitem.hxx> #include <svtools/itemset.hxx> #include <svtools/itemdel.hxx> #include <svtools/visitem.hxx> #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #include <comphelper/processfactory.hxx> #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_ #include <com/sun/star/frame/status/ItemStatus.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_ #include <com/sun/star/frame/status/ItemState.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_ #include <com/sun/star/frame/status/Visibility.hpp> #endif using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::frame::status; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; class SfxQueryStatus_Impl : public ::com::sun::star::frame::XStatusListener , public ::com::sun::star::lang::XTypeProvider , public ::cppu::OWeakObject { public: SFX_DECL_XINTERFACE_XTYPEPROVIDER SfxQueryStatus_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider, USHORT nSlotId, const rtl::OUString& aCommand ); virtual ~SfxQueryStatus_Impl(); // Query method SfxItemState QueryState( SfxPoolItem*& pPoolItem ); // XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException ); // XStatusListener virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); private: SfxQueryStatus_Impl( const SfxQueryStatus& ); SfxQueryStatus_Impl(); SfxQueryStatus_Impl& operator=( const SfxQueryStatus& ); sal_Bool m_bQueryInProgress; SfxItemState m_eState; SfxPoolItem* m_pItem; USHORT m_nSlotID; osl::Condition m_aCondition; ::com::sun::star::util::URL m_aCommand; com::sun::star::uno::Reference< com::sun::star::frame::XDispatch > m_xDispatch; }; SFX_IMPL_XINTERFACE_2( SfxQueryStatus_Impl, OWeakObject, ::com::sun::star::frame::XStatusListener, ::com::sun::star::lang::XEventListener ) SFX_IMPL_XTYPEPROVIDER_2( SfxQueryStatus_Impl, ::com::sun::star::frame::XStatusListener, ::com::sun::star::lang::XEventListener ) SfxQueryStatus_Impl::SfxQueryStatus_Impl( const Reference< XDispatchProvider >& rDispatchProvider, USHORT nSlotId, const OUString& rCommand ) : cppu::OWeakObject(), m_eState( SFX_ITEM_DISABLED ), m_pItem( 0 ), m_bQueryInProgress( sal_False ), m_nSlotID( nSlotId ) { m_aCommand.Complete = rCommand; Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); xTrans->parseStrict( m_aCommand ); if ( rDispatchProvider.is() ) m_xDispatch = rDispatchProvider->queryDispatch( m_aCommand, rtl::OUString(), 0 ); m_aCondition.reset(); } SfxQueryStatus_Impl::~SfxQueryStatus_Impl() { } void SAL_CALL SfxQueryStatus_Impl::disposing( const EventObject& Source ) throw( RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); m_xDispatch.clear(); } void SAL_CALL SfxQueryStatus_Impl::statusChanged( const FeatureStateEvent& rEvent) throw( RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); m_pItem = NULL; m_eState = SFX_ITEM_DISABLED; if ( rEvent.IsEnabled ) { m_eState = SFX_ITEM_AVAILABLE; ::com::sun::star::uno::Type pType = rEvent.State.getValueType(); if ( pType == ::getBooleanCppuType() ) { sal_Bool bTemp ; rEvent.State >>= bTemp ; m_pItem = new SfxBoolItem( m_nSlotID, bTemp ); } else if ( pType == ::getCppuType((const sal_uInt16*)0) ) { sal_uInt16 nTemp ; rEvent.State >>= nTemp ; m_pItem = new SfxUInt16Item( m_nSlotID, nTemp ); } else if ( pType == ::getCppuType((const sal_uInt32*)0) ) { sal_uInt32 nTemp ; rEvent.State >>= nTemp ; m_pItem = new SfxUInt32Item( m_nSlotID, nTemp ); } else if ( pType == ::getCppuType((const ::rtl::OUString*)0) ) { ::rtl::OUString sTemp ; rEvent.State >>= sTemp ; m_pItem = new SfxStringItem( m_nSlotID, sTemp ); } else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::ItemStatus*)0) ) { ItemStatus aItemStatus; rEvent.State >>= aItemStatus; m_eState = aItemStatus.State; m_pItem = new SfxVoidItem( m_nSlotID ); } else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::Visibility*)0) ) { Visibility aVisibilityStatus; rEvent.State >>= aVisibilityStatus; m_pItem = new SfxVisibilityItem( m_nSlotID, aVisibilityStatus.bVisible ); } else { m_eState = SFX_ITEM_UNKNOWN; m_pItem = new SfxVoidItem( m_nSlotID ); } } if ( m_pItem ) DeleteItemOnIdle( m_pItem ); try { m_aCondition.set(); m_xDispatch->removeStatusListener( Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( this ), UNO_QUERY ), m_aCommand ); } catch ( Exception& ) { } } // Query method SfxItemState SfxQueryStatus_Impl::QueryState( SfxPoolItem*& rpPoolItem ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); if ( !m_bQueryInProgress ) { m_pItem = NULL; m_eState = SFX_ITEM_DISABLED; if ( m_xDispatch.is() ) { try { m_aCondition.reset(); m_bQueryInProgress = sal_True; m_xDispatch->addStatusListener( Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( this ), UNO_QUERY ), m_aCommand ); } catch ( Exception& ) { m_aCondition.set(); } } else m_aCondition.set(); } m_aCondition.wait(); m_bQueryInProgress = sal_False; rpPoolItem = m_pItem; return m_eState; } //************************************************************************* SfxQueryStatus::SfxQueryStatus( const Reference< XDispatchProvider >& rDispatchProvider, USHORT nSlotId, const OUString& rCommand ) { m_pSfxQueryStatusImpl = new SfxQueryStatus_Impl( rDispatchProvider, nSlotId, rCommand ); m_xStatusListener = Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( m_pSfxQueryStatusImpl ), UNO_QUERY ); } SfxQueryStatus::~SfxQueryStatus() { } SfxItemState SfxQueryStatus::QueryState( SfxPoolItem*& rpPoolItem ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); return m_pSfxQueryStatusImpl->QueryState( rpPoolItem ); } <commit_msg>INTEGRATION: CWS warnings01 (1.4.66); FILE MERGED 2005/11/28 16:14:11 cd 1.4.66.2: #i55991# Remove warnings 2005/11/09 12:03:24 cd 1.4.66.1: #i55991# Make code warning free for gcc<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: querystatus.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 22:17:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFXQUERYSTATUS_HXX #include <querystatus.hxx> #endif #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _SFXENUMITEM_HXX //autogen #include <svtools/eitem.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #include <svtools/intitem.hxx> #include <svtools/itemset.hxx> #include <svtools/itemdel.hxx> #include <svtools/visitem.hxx> #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #include <comphelper/processfactory.hxx> #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_ #include <com/sun/star/frame/status/ItemStatus.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_ #include <com/sun/star/frame/status/ItemState.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_ #include <com/sun/star/frame/status/Visibility.hpp> #endif using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::frame::status; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; class SfxQueryStatus_Impl : public ::com::sun::star::frame::XStatusListener , public ::com::sun::star::lang::XTypeProvider , public ::cppu::OWeakObject { public: SFX_DECL_XINTERFACE_XTYPEPROVIDER SfxQueryStatus_Impl( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& rDispatchProvider, USHORT nSlotId, const rtl::OUString& aCommand ); virtual ~SfxQueryStatus_Impl(); // Query method SfxItemState QueryState( SfxPoolItem*& pPoolItem ); // XEventListener virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException ); // XStatusListener virtual void SAL_CALL statusChanged(const ::com::sun::star::frame::FeatureStateEvent& Event) throw( ::com::sun::star::uno::RuntimeException ); private: SfxQueryStatus_Impl( const SfxQueryStatus& ); SfxQueryStatus_Impl(); SfxQueryStatus_Impl& operator=( const SfxQueryStatus& ); sal_Bool m_bQueryInProgress; SfxItemState m_eState; SfxPoolItem* m_pItem; USHORT m_nSlotID; osl::Condition m_aCondition; ::com::sun::star::util::URL m_aCommand; com::sun::star::uno::Reference< com::sun::star::frame::XDispatch > m_xDispatch; }; SFX_IMPL_XINTERFACE_2( SfxQueryStatus_Impl, OWeakObject, ::com::sun::star::frame::XStatusListener, ::com::sun::star::lang::XEventListener ) SFX_IMPL_XTYPEPROVIDER_2( SfxQueryStatus_Impl, ::com::sun::star::frame::XStatusListener, ::com::sun::star::lang::XEventListener ) SfxQueryStatus_Impl::SfxQueryStatus_Impl( const Reference< XDispatchProvider >& rDispatchProvider, USHORT nSlotId, const OUString& rCommand ) : cppu::OWeakObject(), m_bQueryInProgress( sal_False ), m_eState( SFX_ITEM_DISABLED ), m_pItem( 0 ), m_nSlotID( nSlotId ) { m_aCommand.Complete = rCommand; Reference < XURLTransformer > xTrans( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); xTrans->parseStrict( m_aCommand ); if ( rDispatchProvider.is() ) m_xDispatch = rDispatchProvider->queryDispatch( m_aCommand, rtl::OUString(), 0 ); m_aCondition.reset(); } SfxQueryStatus_Impl::~SfxQueryStatus_Impl() { } void SAL_CALL SfxQueryStatus_Impl::disposing( const EventObject& ) throw( RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); m_xDispatch.clear(); } void SAL_CALL SfxQueryStatus_Impl::statusChanged( const FeatureStateEvent& rEvent) throw( RuntimeException ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); m_pItem = NULL; m_eState = SFX_ITEM_DISABLED; if ( rEvent.IsEnabled ) { m_eState = SFX_ITEM_AVAILABLE; ::com::sun::star::uno::Type pType = rEvent.State.getValueType(); if ( pType == ::getBooleanCppuType() ) { sal_Bool bTemp ; rEvent.State >>= bTemp ; m_pItem = new SfxBoolItem( m_nSlotID, bTemp ); } else if ( pType == ::getCppuType((const sal_uInt16*)0) ) { sal_uInt16 nTemp ; rEvent.State >>= nTemp ; m_pItem = new SfxUInt16Item( m_nSlotID, nTemp ); } else if ( pType == ::getCppuType((const sal_uInt32*)0) ) { sal_uInt32 nTemp ; rEvent.State >>= nTemp ; m_pItem = new SfxUInt32Item( m_nSlotID, nTemp ); } else if ( pType == ::getCppuType((const ::rtl::OUString*)0) ) { ::rtl::OUString sTemp ; rEvent.State >>= sTemp ; m_pItem = new SfxStringItem( m_nSlotID, sTemp ); } else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::ItemStatus*)0) ) { ItemStatus aItemStatus; rEvent.State >>= aItemStatus; m_eState = aItemStatus.State; m_pItem = new SfxVoidItem( m_nSlotID ); } else if ( pType == ::getCppuType((const ::com::sun::star::frame::status::Visibility*)0) ) { Visibility aVisibilityStatus; rEvent.State >>= aVisibilityStatus; m_pItem = new SfxVisibilityItem( m_nSlotID, aVisibilityStatus.bVisible ); } else { m_eState = SFX_ITEM_UNKNOWN; m_pItem = new SfxVoidItem( m_nSlotID ); } } if ( m_pItem ) DeleteItemOnIdle( m_pItem ); try { m_aCondition.set(); m_xDispatch->removeStatusListener( Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( this ), UNO_QUERY ), m_aCommand ); } catch ( Exception& ) { } } // Query method SfxItemState SfxQueryStatus_Impl::QueryState( SfxPoolItem*& rpPoolItem ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); if ( !m_bQueryInProgress ) { m_pItem = NULL; m_eState = SFX_ITEM_DISABLED; if ( m_xDispatch.is() ) { try { m_aCondition.reset(); m_bQueryInProgress = sal_True; m_xDispatch->addStatusListener( Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( this ), UNO_QUERY ), m_aCommand ); } catch ( Exception& ) { m_aCondition.set(); } } else m_aCondition.set(); } m_aCondition.wait(); m_bQueryInProgress = sal_False; rpPoolItem = m_pItem; return m_eState; } //************************************************************************* SfxQueryStatus::SfxQueryStatus( const Reference< XDispatchProvider >& rDispatchProvider, USHORT nSlotId, const OUString& rCommand ) { m_pSfxQueryStatusImpl = new SfxQueryStatus_Impl( rDispatchProvider, nSlotId, rCommand ); m_xStatusListener = Reference< XStatusListener >( static_cast< cppu::OWeakObject* >( m_pSfxQueryStatusImpl ), UNO_QUERY ); } SfxQueryStatus::~SfxQueryStatus() { } SfxItemState SfxQueryStatus::QueryState( SfxPoolItem*& rpPoolItem ) { ::vos::OGuard aGuard( Application::GetSolarMutex() ); return m_pSfxQueryStatusImpl->QueryState( rpPoolItem ); } <|endoftext|>
<commit_before>#include "AConfig.h" #if(HAS_CAMERASERVO) // Includes #include <Arduino.h> #include <avr/io.h> #include <avr/interrupt.h> #include "CCameraServo.h" #include "CServo.h" #include "CPin.h" #include "NConfigManager.h" #include "NDataManager.h" #include "NModuleManager.h" #include "NCommManager.h" #include "CTimer.h" #include "CControllerBoard.h" #include <math.h> // Defines #ifndef F_CPU #define F_CPU 16000000UL #endif // File local variables and methods namespace { constexpr float kZeroPosMicrosecs = 1487.0f; constexpr float kMicrosecPerDegree = 9.523809f; constexpr float kDegPerMicrosec = ( 1 / kMicrosecPerDegree ); // Helper functions specifically for the HITEC servo constexpr uint32_t DegreesToMicroseconds( float degreesIn, bool isInverted = false ) { return static_cast<uint32_t>( ( kMicrosecPerDegree * ( isInverted ? -degreesIn : degreesIn ) ) + kZeroPosMicrosecs ); } constexpr float MicrosecondsToDegrees( uint32_t microsecondsIn, bool isInverted = false ) { return ( isInverted ? -( ( static_cast<float>( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec ) :( ( static_cast<float>( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec ) ); } constexpr float kNeutralPosition_deg = 0.0f; constexpr uint32_t kNeutralPosition_us = DegreesToMicroseconds( 0.0f ); constexpr float kDefaultSpeed = 50.0f; // Degrees per sec // Attributes CTimer m_controlTimer; CTimer m_telemetryTimer; float m_targetPos_deg = kNeutralPosition_deg; float m_currentPos_deg = kNeutralPosition_deg; uint32_t m_targetPos_us = kNeutralPosition_us; uint32_t m_currentPos_us = kNeutralPosition_us; float m_fCurrentPos_us = kZeroPosMicrosecs; uint32_t m_tDelta = 0; uint32_t m_tLast = 0; // Settings float m_speed_deg_per_s = kDefaultSpeed; int m_isInverted = 0; // 0 - Not inverted, 1 - Inverted // Derived from settings float m_speed_us_per_ms = ( kDefaultSpeed * 0.001f ) * kMicrosecPerDegree; // Float<->Int conversion helpers constexpr int32_t Encode( float valueIn ) { return static_cast<int32_t>( valueIn * 1000.0f ); } constexpr float Decode( int32_t valueIn ) { return ( static_cast<float>( valueIn ) * 0.001f ); } void SetServoPosition( uint32_t microsecondsIn ) { // Set to 90° --> pulsewdith = 1.5ms OCR1A = microsecondsIn * 2; } } void CCameraServo::Initialize() { // Set up the pin for the camera servo pinMode( CAMERAMOUNT_PIN, OUTPUT ); // Set up the timers driving the PWM for the servo (AVR specific) TCCR1A = 0; TCCR1B = 0; TCCR1A |= ( 1 << COM1A1 ) | ( 1 << WGM11 ); // non-inverting mode for OC1A TCCR1B |= ( 1 << WGM13 ) | ( 1 << WGM12 ) | ( 1 << CS11 ); // Mode 14, Prescaler 8 ICR1 = 40000; // 320000 / 8 = 40000 // Set initial position SetServoPosition( kNeutralPosition_us ); // Mark camera servo as enabled NConfigManager::m_capabilityBitmask |= ( 1 << CAMERA_MOUNT_1_AXIS_CAPABLE ); // Reset timers m_controlTimer.Reset(); m_telemetryTimer.Reset(); } void CCameraServo::Update( CCommand& command ) { // Check for messages if( NCommManager::m_isCommandAvailable ) { // Handle messages if( command.Equals( "camServ_tpos" ) ) { // TODO: Ideally this unit would have the ability to autonomously set its own target and ack receipt with a separate mechanism // Acknowledge target position Serial.print( F( "camServ_tpos:" ) ); Serial.print( static_cast<int32_t>( command.m_arguments[1] ) ); Serial.println( ';' ); // Update the target position m_targetPos_deg = Decode( static_cast<int32_t>( command.m_arguments[1] ) ); // Update the target microseconds m_targetPos_us = DegreesToMicroseconds( m_targetPos_deg, m_isInverted ); } else if( command.Equals( "camServ_spd" ) ) { // Acknowledge receipt of command Serial.print( F( "camServ_spd:" ) ); Serial.print( static_cast<int32_t>( command.m_arguments[1] ) ); Serial.println( ';' ); // Decode the requested speed and update the setting m_speed_deg_per_s = Decode( static_cast<int32_t>( command.m_arguments[1] ) ); m_speed_us_per_ms = ( m_speed_deg_per_s * 0.001f ) * kMicrosecPerDegree; } else if( command.Equals( "camServ_inv" ) ) { if( command.m_arguments[1] == 1 ) { // Set inverted m_isInverted = 1; // Report back Serial.print( F( "camServ_inv:1;" ) ); } else if( command.m_arguments[1] == 0 ) { // Set uninverted m_isInverted = 0; // Report back Serial.print( F( "camServ_inv:0;" ) ); } } } // Run servo adjustment at 200Hz if( m_controlTimer.HasElapsed( 5 ) ) { // Get time elapsed since last position update m_tDelta = millis() - m_tLast; // Update position if not at desired location if( m_currentPos_us != m_targetPos_us ) { float error = static_cast<float>( m_targetPos_us ) - m_fCurrentPos_us; // Check to see if the error/dT is smaller than the speed limit if( abs( error / static_cast<float>( m_tDelta ) ) < m_speed_us_per_ms ) { // Move directly to the target // NOTE: Cannot use the cast method like below, since the floating point // representation of the target pos might be comparatively less than the integer value. // I.e. target = 32, static_cast<float>( 32 ) -> 31.99999, static_cast<uint32_t>( 31.99999 ) -> 31 // This could lead to the current position never reaching the target m_currentPos_us = m_targetPos_us; // Update the floating point representation as well, for use in future target updates m_fCurrentPos_us = static_cast<float>( m_targetPos_us ); } else { // Move by the delta towards the target m_fCurrentPos_us += ( m_speed_us_per_ms * static_cast<float>( m_tDelta ) ); // Cast the floating point servo command to an integer m_currentPos_us = static_cast<uint32_t>( m_fCurrentPos_us ); } // Set the servo to this target SetServoPosition( m_currentPos_us ); // Update the position value in degrees m_currentPos_deg = MicrosecondsToDegrees( m_currentPos_us ); } m_tLast = millis(); } // Emit position telemetry at 10Hz if( m_telemetryTimer.HasElapsed( 100 ) ) { Serial.print( F( "camServ_pos:" ) ); Serial.print( Encode( m_currentPos_deg ) ); Serial.println( ';' ); } } #endif <commit_msg>Fixed sign error<commit_after>#include "AConfig.h" #if(HAS_CAMERASERVO) // Includes #include <Arduino.h> #include <avr/io.h> #include <avr/interrupt.h> #include "CCameraServo.h" #include "CServo.h" #include "CPin.h" #include "NConfigManager.h" #include "NDataManager.h" #include "NModuleManager.h" #include "NCommManager.h" #include "CTimer.h" #include "CControllerBoard.h" #include <math.h> // Defines #ifndef F_CPU #define F_CPU 16000000UL #endif // File local variables and methods namespace { constexpr float kZeroPosMicrosecs = 1487.0f; constexpr float kMicrosecPerDegree = 9.523809f; constexpr float kDegPerMicrosec = ( 1 / kMicrosecPerDegree ); // Helper functions specifically for the HITEC servo constexpr uint32_t DegreesToMicroseconds( float degreesIn, bool isInverted = false ) { return static_cast<uint32_t>( ( kMicrosecPerDegree * ( isInverted ? -degreesIn : degreesIn ) ) + kZeroPosMicrosecs ); } constexpr float MicrosecondsToDegrees( uint32_t microsecondsIn, bool isInverted = false ) { return ( isInverted ? -( ( static_cast<float>( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec ) :( ( static_cast<float>( microsecondsIn ) - kZeroPosMicrosecs ) * kDegPerMicrosec ) ); } constexpr float kNeutralPosition_deg = 0.0f; constexpr uint32_t kNeutralPosition_us = DegreesToMicroseconds( 0.0f ); constexpr float kDefaultSpeed = 50.0f; // Degrees per sec // Attributes CTimer m_controlTimer; CTimer m_telemetryTimer; float m_targetPos_deg = kNeutralPosition_deg; float m_currentPos_deg = kNeutralPosition_deg; uint32_t m_targetPos_us = kNeutralPosition_us; uint32_t m_currentPos_us = kNeutralPosition_us; float m_fCurrentPos_us = kZeroPosMicrosecs; uint32_t m_tDelta = 0; uint32_t m_tLast = 0; // Settings float m_speed_deg_per_s = kDefaultSpeed; int m_isInverted = 0; // 0 - Not inverted, 1 - Inverted // Derived from settings float m_speed_us_per_ms = ( kDefaultSpeed * 0.001f ) * kMicrosecPerDegree; // Float<->Int conversion helpers constexpr int32_t Encode( float valueIn ) { return static_cast<int32_t>( valueIn * 1000.0f ); } constexpr float Decode( int32_t valueIn ) { return ( static_cast<float>( valueIn ) * 0.001f ); } void SetServoPosition( uint32_t microsecondsIn ) { // Set to 90° --> pulsewdith = 1.5ms OCR1A = microsecondsIn * 2; } } void CCameraServo::Initialize() { // Set up the pin for the camera servo pinMode( CAMERAMOUNT_PIN, OUTPUT ); // Set up the timers driving the PWM for the servo (AVR specific) TCCR1A = 0; TCCR1B = 0; TCCR1A |= ( 1 << COM1A1 ) | ( 1 << WGM11 ); // non-inverting mode for OC1A TCCR1B |= ( 1 << WGM13 ) | ( 1 << WGM12 ) | ( 1 << CS11 ); // Mode 14, Prescaler 8 ICR1 = 40000; // 320000 / 8 = 40000 // Set initial position SetServoPosition( kNeutralPosition_us ); // Mark camera servo as enabled NConfigManager::m_capabilityBitmask |= ( 1 << CAMERA_MOUNT_1_AXIS_CAPABLE ); // Reset timers m_controlTimer.Reset(); m_telemetryTimer.Reset(); } void CCameraServo::Update( CCommand& command ) { // Check for messages if( NCommManager::m_isCommandAvailable ) { // Handle messages if( command.Equals( "camServ_tpos" ) ) { // TODO: Ideally this unit would have the ability to autonomously set its own target and ack receipt with a separate mechanism // Acknowledge target position Serial.print( F( "camServ_tpos:" ) ); Serial.print( static_cast<int32_t>( command.m_arguments[1] ) ); Serial.println( ';' ); // Update the target position m_targetPos_deg = Decode( static_cast<int32_t>( command.m_arguments[1] ) ); // Update the target microseconds m_targetPos_us = DegreesToMicroseconds( m_targetPos_deg, m_isInverted ); } else if( command.Equals( "camServ_spd" ) ) { // Acknowledge receipt of command Serial.print( F( "camServ_spd:" ) ); Serial.print( static_cast<int32_t>( command.m_arguments[1] ) ); Serial.println( ';' ); // Decode the requested speed and update the setting m_speed_deg_per_s = Decode( static_cast<int32_t>( command.m_arguments[1] ) ); m_speed_us_per_ms = ( m_speed_deg_per_s * 0.001f ) * kMicrosecPerDegree; } else if( command.Equals( "camServ_inv" ) ) { if( command.m_arguments[1] == 1 ) { // Set inverted m_isInverted = 1; // Report back Serial.print( F( "camServ_inv:1;" ) ); } else if( command.m_arguments[1] == 0 ) { // Set uninverted m_isInverted = 0; // Report back Serial.print( F( "camServ_inv:0;" ) ); } } } // Run servo adjustment at 200Hz if( m_controlTimer.HasElapsed( 5 ) ) { // Get time elapsed since last position update m_tDelta = millis() - m_tLast; // Update position if not at desired location if( m_currentPos_us != m_targetPos_us ) { float error = static_cast<float>( m_targetPos_us ) - m_fCurrentPos_us; // Check to see if the error/dT is smaller than the speed limit if( abs( error / static_cast<float>( m_tDelta ) ) < m_speed_us_per_ms ) { // Move directly to the target // NOTE: Cannot use the cast method like below, since the floating point // representation of the target pos might be comparatively less than the integer value. // I.e. target = 32, static_cast<float>( 32 ) -> 31.99999, static_cast<uint32_t>( 31.99999 ) -> 31 // This could lead to the current position never reaching the target m_currentPos_us = m_targetPos_us; // Update the floating point representation as well, for use in future target updates m_fCurrentPos_us = static_cast<float>( m_targetPos_us ); } else { // Move by the delta towards the target m_fCurrentPos_us += ( ( ( error < 0 ) ? -m_speed_us_per_ms : m_speed_us_per_ms ) * static_cast<float>( m_tDelta ) ); // Cast the floating point servo command to an integer m_currentPos_us = static_cast<uint32_t>( m_fCurrentPos_us ); } // Set the servo to this target SetServoPosition( m_currentPos_us ); // Update the position value in degrees m_currentPos_deg = MicrosecondsToDegrees( m_currentPos_us ); } m_tLast = millis(); } // Emit position telemetry at 10Hz if( m_telemetryTimer.HasElapsed( 100 ) ) { Serial.print( F( "camServ_pos:" ) ); Serial.print( Encode( m_currentPos_deg ) ); Serial.println( ';' ); } } #endif <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015 Dennis Wandschura 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. */ #include "ActionPlaySound.h" #include <vxEngineLib/MessageManager.h> #include <vxEngineLib/Message.h> #include <vxEngineLib/AudioMessage.h> #include <vxEngineLib/MessageTypes.h> ActionPlaySound::ActionPlaySound(const vx::StringID &sid, vx::MessageManager* msgManager, f32 time) :m_sid(sid), m_msgManager(msgManager), m_timer(), m_time(time) { } ActionPlaySound::~ActionPlaySound() { } void ActionPlaySound::run() { auto elapsedTime = m_timer.getTimeSeconds(); if (elapsedTime >= m_time) { vx::Message msg; msg.arg1.u64 = m_sid.value; msg.code = (u32)vx::AudioMessage::PlaySound; msg.type = vx::MessageType::Audio; m_msgManager->addMessage(msg); m_timer.reset(); } }<commit_msg>action to play a sound file<commit_after>/* The MIT License (MIT) Copyright (c) 2015 Dennis Wandschura 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. */ #include "ActionPlaySound.h" #include <vxEngineLib/MessageManager.h> #include <vxEngineLib/Message.h> #include <vxEngineLib/AudioMessage.h> #include <vxEngineLib/MessageTypes.h> ActionPlaySound::ActionPlaySound(const vx::StringID &sid, vx::MessageManager* msgManager, f32 time) :m_sid(sid), m_msgManager(msgManager), m_timer(), m_time(time) { } ActionPlaySound::~ActionPlaySound() { } void ActionPlaySound::run() { /*auto elapsedTime = m_timer.getTimeSeconds(); if (elapsedTime >= m_time) { vx::Message msg; msg.arg1.u64 = m_sid.value; msg.code = (u32)vx::AudioMessage::PlaySound; msg.type = vx::MessageType::Audio; m_msgManager->addMessage(msg); m_timer.reset(); }*/ }<|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> using namespace std; //Function to count the lines of the script to be converted int linecounter(string dir){ int counter = 0; string line; //Create new file stream to file to be converted ifstream file(dir); while (getline(file, line)){ counter++;} return counter; } //Accepts a string and returns the value of the key(s) in digispark language //Some of the keys are encoded using their usage IDs. Refer to http://www.usb.org/developers/hidpage/Hut1_12v2.pdf (Page 53-59) string stringprocessor(string key){ if((key == "A") || (key == "a")){ key = "KEY_A"; return key; } else if((key == "B") || (key == "b")){ key = "KEY_B"; return key; } else if((key == "C") || (key == "c")){ key = "KEY_C"; return key; } else if((key == "D") || (key == "d")){ key = "KEY_D"; return key; } else if((key == "E") || (key == "e")){ key = "KEY_E"; return key; } else if((key == "F") || (key == "f")){ key = "KEY_F"; return key; } else if((key == "G") || (key == "g")){ key = "KEY_G"; return key; } else if((key == "H") || (key == "h")){ key = "KEY_H"; return key; } else if((key == "I") || (key == "i")){ key = "KEY_I"; return key; } else if((key == "J") || (key == "j")){ key = "KEY_J"; return key; } else if((key == "K") || (key == "k")){ key = "KEY_K"; return key; } else if((key == "L") || (key == "l")){ key = "KEY_L"; return key; } else if((key == "M") || (key == "m")){ key = "KEY_M"; return key; } else if((key == "N") || (key == "n")){ key = "KEY_N"; return key; } else if((key == "O") || (key == "o")){ key = "KEY_O"; return key; } else if((key == "P") || (key == "p")){ key = "KEY_P"; return key; } else if((key == "Q") || (key == "q")){ key = "KEY_Q"; return key; } else if((key == "R") || (key == "r")){ key = "KEY_R"; return key; } else if((key == "S") || (key == "s")){ key = "KEY_S"; return key; } else if((key == "T") || (key == "t")){ key = "KEY_T"; return key; } else if((key == "U") || (key == "u")){ key = "KEY_U"; return key; } else if((key == "V") || (key == "v")){ key = "KEY_V"; return key; } else if((key == "W") || (key == "w")){ key = "KEY_W"; return key; } else if((key == "X") || (key == "x")){ key = "KEY_X"; return key; } else if((key == "Y") || (key == "y")){ key = "KEY_Y"; return key; } else if((key == "Z") || (key == "z")){ key = "KEY_Z"; return key; } else if(key=="1"){ key = "KEY_1"; return key; } else if(key=="2"){ key = "KEY_2"; return key; } else if(key=="3"){ key = "KEY_3"; return key; } else if(key=="4"){ key = "KEY_4"; return key; } else if(key=="5"){ key = "KEY_5"; return key; } else if(key=="6"){ key = "KEY_6"; return key; } else if(key=="7"){ key = "KEY_7"; return key; } else if(key=="8"){ key = "KEY_8"; return key; } else if(key=="9"){ key = "KEY_9"; return key; } else if(key=="0"){ key = "KEY_0"; return key; } else if(key=="ENTER"){ key = "KEY_ENTER"; return key; } else if(key=="F1"){ key = "KEY_F1"; return key; } else if(key=="F2"){ key = "KEY_F2"; return key; } else if(key=="F3"){ key = "KEY_F3"; return key; } else if(key=="F4"){ key = "KEY_F4"; return key; } else if(key=="F5"){ key = "KEY_F5"; return key; } else if(key=="F6"){ key = "KEY_F6"; return key; } else if(key=="F7"){ key = "KEY_F7"; return key; } else if(key=="F8"){ key = "KEY_F8"; return key; } else if(key=="F9"){ key = "KEY_F9"; return key; } else if(key=="F10"){ key = "KEY_F10"; return key; } else if(key=="F11"){ key = "KEY_F11"; return key; } else if(key=="F12"){ key = "KEY_F12"; return key; } else if((key=="GUI") || (key=="WINDOWS")){ key = "0, MOD_GUI_LEFT"; //Doesn't work without the 0, for some reason return key; } else if((key=="APP") || (key=="MENU")){ key = "101"; //Doesn't work without the 0, for some reason return key; } else if(key=="SHIFT"){ key = "MOD_SHIFT_LEFT"; return key; } else if(key=="ALT"){ key = "MOD_ALT_LEFT"; return key; } else if((key=="CONTROL") || (key=="CTRL")){ key = "MOD_CONTROL_LEFT"; //Doesn't work without the 0, for some reason return key; } else if((key=="DOWNARROW") || (key=="DOWN")){ key = "84"; //Doesn't work without the 0, for some reason return key; } else if((key=="UPARROW") || (key=="UP")){ key = "83"; //Doesn't work without the 0, for some reason return key; } else if((key=="LEFTARROW") || (key=="LEFT")){ key = "79"; //Doesn't work without the 0, for some reason return key; } else if((key=="RIGHTARROW") || (key=="RIGHT")){ key = "89"; //Doesn't work without the 0, for some reason return key; } else if((key=="BREAK") || (key=="PAUSE")){ key = "126"; //Doesn't work without the 0, for some reason return key; } else if(key=="CAPSLOCK"){ key = "30"; return key; } else if((key=="ESC") || (key=="ESCAPE")){ key = "110"; return key; } else if(key=="DELETE"){ key = "15"; return key; } else if(key=="END"){ key = "81"; return key; } else if(key=="HOME"){ key = "80"; return key; } else if(key=="NUMLOCK"){ key = "90"; return key; } else if(key=="PAGEUP"){ key = "85"; return key; } else if(key=="PAGEDOWN"){ key = "86"; return key; } else if(key=="PRINTSCREEN"){ key = "124"; return key; } else if(key=="SCROLLLOCK"){ key = "125"; return key; } else if(key=="SPACE"){ key = "61"; return key; } else if(key=="TAB"){ key = "16"; return key; } } int main(){ //Eye-candy cout<<" _ _ _"<<endl; cout<<">(.)__ <(.)__ =(.)__"<<endl; cout<<" (___/ (___/ (___/"<<endl; cout<<endl; cout<<endl; cout<<"Welcome to digiQuack, the easy DuckyScript to Digispark payload converter!"<<endl; //Ask user to enter path to file to be converted string dir; cout<<"Enter the path of the file to be converted:"<<endl; cin>>dir; //Open input file stream ifstream filein(dir); //Check if file stream opened - if file exists and is a valid input if(!filein){ cout<<"File not found or invalid input."<<endl; return -1; } //Check if the input file is empty if ( filein.peek() == std::ifstream::traits_type::eof() ) { cout<<"File supplied is empty"<<endl; return -1; } //Create a counter as big as the number of lines in the input file int counter = linecounter(dir); //Open converted file fstream and create text file ofstream fileout; fileout.open ("converted.txt"); //Create a string variable to store each individual ducky command/line to process in the for loop string command; //Create a trigger for the default delay command - if default delay command is encountered, inject converted script with delay lines int delay = 0; //Insert this line in the beginning of the converted script to make sure that (on older systems) the first keystroke after a delay isn't missed fileout << "DigiKeyboard.sendKeyStroke(0);\n"; //Create temporary string variables to use for string manipulation in the following for-loop string tmpstring; string tmpstring2; string fincom; //Use this variable to keep track of the last converted command to use in the repeat function string key; //Variable to be used in the keystroke conversion if clause underneath int replays = 0; //Replays counter for the REPLAY feature if clause underneath //Open a for loop to process each line/command of the input script for(int i=0; i<counter; i++){ //Set command string equal to current line getline(filein, command); //Check for DEFAULT_DELAY or DEFAULTDELAY, set the delay variable and re-examine for-loop (Note: writing the delay commands happens at the end of the for-loop). tmpstring = tmpstring.assign(command,0,13); if((tmpstring.compare("DEFAULTDELAY ")==0) || (tmpstring.compare("DEFAULT_DELAY")==0)){ command.erase(0,13); delay = stoi(command); continue; } //Convert duckyscript comments to Arduino IDE comments: Extract 3 first characters, if == REM, replace them with //, write to output and re-examine for-loop - this helps avoid placing unnecessary delay commands tmpstring = tmpstring.assign(command,0,3); if(tmpstring.compare("REM") == 0){ command.replace(0,4,"//"); fileout << command << "\n"; continue; } //Convert duckyscript STRING commands to digispark print commands (Note, used F to store large strings to flash since the digispark has few RAM) tmpstring = tmpstring.assign(command,0,6); if(tmpstring.compare("STRING") == 0){ command.replace(0,7,"DigiKeyboard.print(F(\""); command += "\"));"; fincom = command; //See use of fincom above fileout << command << "\n"; command = ""; //Empty the string so it won't trigger the keystroke processor } //Convert DELAY command (Not DEFAULTDELAY) tmpstring = tmpstring.assign(command,0,5); if(tmpstring.compare("DELAY") == 0){ command.erase(0,6); fincom = "DigiKeyboard.delay(" + command + ");"; fileout << fincom << "\n"; command = ""; //command variable is set to null to bypass keystroke processor but still access default delay } //REPLAY feature (Note: at the end, command variable is set to null to bypass keystroke processor but still access default delay) tmpstring = tmpstring.assign(command,0,5); if(tmpstring.compare("REPLAY") == 0){ command.erase(0,6); replays = stoi(command); for(int j=0; j < replays; j++){ fileout << fincom << "\n"; } command = ""; } //Convert keystroke commands by calling the string processor function if(!command.empty()){ key = command.substr(0, command.find(' ')); tmpstring = "DigiKeyboard.sendKeyStroke(" + stringprocessor(key); command.erase(0, command.find(' ')+1); if(!command.empty()){ tmpstring = tmpstring + ","; tmpstring = tmpstring + stringprocessor(command); } tmpstring = tmpstring + ");"; fincom = tmpstring; fileout << fincom << "\n"; } //If default delay trigger is activated, inject output file with a delay command if(delay!=0){ fileout << "DigiKeyboard.delay(" << delay << ");\n"; } } //Ask if user wants to execute the script just once - Use the counter variable instead of initialising a new one since counter won't be used anymore. cout << "Script has been converted successfully. Do you want the DigiSpark to execute the script once or loop infinitely? Select 0 for infinity and 1 for a single execution." << endl; cout << "[0/1]:"; cin >> counter; if(counter){ fileout << "exit();"; } //Close converted script txt fstream fileout.close(); return 0; } <commit_msg>Bugfixes<commit_after>#include <iostream> #include <fstream> #include <string> using namespace std; //Function to count the lines of the script to be converted int linecounter(string dir){ int counter = 0; string line; //Create new file stream to file to be converted ifstream file(dir); while (getline(file, line)){ counter++;} return counter; } //Accepts a string and returns the value of the key(s) in digispark language //Some of the keys are encoded using their usage IDs. Refer to http://www.usb.org/developers/hidpage/Hut1_12v2.pdf (Page 53-59) string stringprocessor(string key){ if((key == "A") || (key == "a")){ key = "KEY_A"; return key; } else if((key == "B") || (key == "b")){ key = "KEY_B"; return key; } else if((key == "C") || (key == "c")){ key = "KEY_C"; return key; } else if((key == "D") || (key == "d")){ key = "KEY_D"; return key; } else if((key == "E") || (key == "e")){ key = "KEY_E"; return key; } else if((key == "F") || (key == "f")){ key = "KEY_F"; return key; } else if((key == "G") || (key == "g")){ key = "KEY_G"; return key; } else if((key == "H") || (key == "h")){ key = "KEY_H"; return key; } else if((key == "I") || (key == "i")){ key = "KEY_I"; return key; } else if((key == "J") || (key == "j")){ key = "KEY_J"; return key; } else if((key == "K") || (key == "k")){ key = "KEY_K"; return key; } else if((key == "L") || (key == "l")){ key = "KEY_L"; return key; } else if((key == "M") || (key == "m")){ key = "KEY_M"; return key; } else if((key == "N") || (key == "n")){ key = "KEY_N"; return key; } else if((key == "O") || (key == "o")){ key = "KEY_O"; return key; } else if((key == "P") || (key == "p")){ key = "KEY_P"; return key; } else if((key == "Q") || (key == "q")){ key = "KEY_Q"; return key; } else if((key == "R") || (key == "r")){ key = "KEY_R"; return key; } else if((key == "S") || (key == "s")){ key = "KEY_S"; return key; } else if((key == "T") || (key == "t")){ key = "KEY_T"; return key; } else if((key == "U") || (key == "u")){ key = "KEY_U"; return key; } else if((key == "V") || (key == "v")){ key = "KEY_V"; return key; } else if((key == "W") || (key == "w")){ key = "KEY_W"; return key; } else if((key == "X") || (key == "x")){ key = "KEY_X"; return key; } else if((key == "Y") || (key == "y")){ key = "KEY_Y"; return key; } else if((key == "Z") || (key == "z")){ key = "KEY_Z"; return key; } else if(key=="1"){ key = "KEY_1"; return key; } else if(key=="2"){ key = "KEY_2"; return key; } else if(key=="3"){ key = "KEY_3"; return key; } else if(key=="4"){ key = "KEY_4"; return key; } else if(key=="5"){ key = "KEY_5"; return key; } else if(key=="6"){ key = "KEY_6"; return key; } else if(key=="7"){ key = "KEY_7"; return key; } else if(key=="8"){ key = "KEY_8"; return key; } else if(key=="9"){ key = "KEY_9"; return key; } else if(key=="0"){ key = "KEY_0"; return key; } else if(key=="ENTER"){ key = "KEY_ENTER"; return key; } else if(key=="F1"){ key = "KEY_F1"; return key; } else if(key=="F2"){ key = "KEY_F2"; return key; } else if(key=="F3"){ key = "KEY_F3"; return key; } else if(key=="F4"){ key = "KEY_F4"; return key; } else if(key=="F5"){ key = "KEY_F5"; return key; } else if(key=="F6"){ key = "KEY_F6"; return key; } else if(key=="F7"){ key = "KEY_F7"; return key; } else if(key=="F8"){ key = "KEY_F8"; return key; } else if(key=="F9"){ key = "KEY_F9"; return key; } else if(key=="F10"){ key = "KEY_F10"; return key; } else if(key=="F11"){ key = "KEY_F11"; return key; } else if(key=="F12"){ key = "KEY_F12"; return key; } else if((key=="GUI") || (key=="WINDOWS")){ key = "0, MOD_GUI_LEFT"; //Doesn't work without the 0, for some reason return key; } else if((key=="APP") || (key=="MENU")){ key = "101"; return key; } else if(key=="SHIFT"){ key = "MOD_SHIFT_LEFT"; return key; } else if(key=="ALT"){ key = "MOD_ALT_LEFT"; return key; } else if((key=="CONTROL") || (key=="CTRL")){ key = "MOD_CONTROL_LEFT"; return key; } else if((key=="DOWNARROW") || (key=="DOWN")){ key = "81"; return key; } else if((key=="UPARROW") || (key=="UP")){ key = "82"; return key; } else if((key=="LEFTARROW") || (key=="LEFT")){ key = "80"; return key; } else if((key=="RIGHTARROW") || (key=="RIGHT")){ key = "79"; return key; } else if((key=="BREAK") || (key=="PAUSE")){ key = "72"; return key; } else if(key=="CAPSLOCK"){ key = "57"; return key; } else if((key=="ESC") || (key=="ESCAPE")){ key = "41"; return key; } else if(key=="DELETE"){ key = "42"; return key; } else if(key=="END"){ key = "77"; return key; } else if(key=="HOME"){ key = "74"; return key; } else if(key=="NUMLOCK"){ key = "83"; return key; } else if(key=="PAGEUP"){ key = "75"; return key; } else if(key=="PAGEDOWN"){ key = "78"; return key; } else if(key=="PRINTSCREEN"){ key = "70"; return key; } else if(key=="SCROLLLOCK"){ key = "71"; return key; } else if(key=="SPACE"){ key = "44"; return key; } else if(key=="TAB"){ key = "43"; return key; } } int main(){ //Eye-candy cout<<" _ _ _"<<endl; cout<<">(.)__ <(.)__ =(.)__"<<endl; cout<<" (___/ (___/ (___/"<<endl; cout<<endl; cout<<endl; cout<<"Welcome to digiQuack, the easy DuckyScript to Digispark payload converter!"<<endl; //Ask user to enter path to file to be converted string dir; cout<<"Enter the path of the file to be converted:"<<endl; cin>>dir; //Open input file stream ifstream filein(dir); //Check if file stream opened - if file exists and is a valid input if(!filein){ cout<<"File not found or invalid input."<<endl; return -1; } //Check if the input file is empty if ( filein.peek() == std::ifstream::traits_type::eof() ) { cout<<"File supplied is empty"<<endl; return -1; } //Create a counter as big as the number of lines in the input file int counter = linecounter(dir); //Open converted file fstream and create text file ofstream fileout; fileout.open ("converted.txt"); //Create a string variable to store each individual ducky command/line to process in the for loop string command; //Create a trigger for the default delay command - if default delay command is encountered, inject converted script with delay lines int delay = 0; //Insert this line in the beginning of the converted script to make sure that (on older systems) the first keystroke after a delay isn't missed fileout << "DigiKeyboard.sendKeyStroke(0);\n"; //Create temporary string variables to use for string manipulation in the following for-loop string tmpstring; string tmpstring2; string fincom; //Use this variable to keep track of the last converted command to use in the repeat function string key; //Variable to be used in the keystroke conversion if clause underneath int replays = 0; //Replays counter for the REPLAY feature if clause underneath //Open a for loop to process each line/command of the input script for(int i=0; i<counter; i++){ //Set command string equal to current line getline(filein, command); //Check for DEFAULT_DELAY or DEFAULTDELAY, set the delay variable and re-examine for-loop (Note: writing the delay commands happens at the end of the for-loop). tmpstring = tmpstring.assign(command,0,13); if((tmpstring.compare("DEFAULTDELAY ")==0) || (tmpstring.compare("DEFAULT_DELAY")==0)){ command.erase(0,13); delay = stoi(command); continue; } //Convert duckyscript comments to Arduino IDE comments: Extract 3 first characters, if == REM, replace them with //, write to output and re-examine for-loop - this helps avoid placing unnecessary delay commands tmpstring = tmpstring.assign(command,0,3); if(tmpstring.compare("REM") == 0){ command.replace(0,4,"//"); fileout << command << "\n"; continue; } //Convert duckyscript STRING commands to digispark print commands (Note, used F to store large strings to flash since the digispark has few RAM) tmpstring = tmpstring.assign(command,0,6); if(tmpstring.compare("STRING") == 0){ command.replace(0,7,"DigiKeyboard.print(F(\""); command += "\"));"; fincom = command; //See use of fincom above fileout << command << "\n"; command = ""; //Empty the string so it won't trigger the keystroke processor } //Convert DELAY command (Not DEFAULTDELAY) tmpstring = tmpstring.assign(command,0,5); if(tmpstring.compare("DELAY") == 0){ command.erase(0,6); fincom = "DigiKeyboard.delay(" + command + ");"; fileout << fincom << "\n"; command = ""; //command variable is set to null to bypass keystroke processor but still access default delay } //REPLAY feature (Note: at the end, command variable is set to null to bypass keystroke processor but still access default delay) tmpstring = tmpstring.assign(command,0,5); if(tmpstring.compare("REPLAY") == 0){ command.erase(0,6); replays = stoi(command); for(int j=0; j < replays; j++){ fileout << fincom << "\n"; } command = ""; } //Convert keystroke commands by calling the string processor function if(!command.empty()){ key = command.substr(0, command.find(' ')); tmpstring = "DigiKeyboard.sendKeyStroke(" + stringprocessor(key); command.erase(0, command.find(' ')+1); if(!command.empty()){ tmpstring = tmpstring + ","; tmpstring = tmpstring + stringprocessor(command); } tmpstring = tmpstring + ");"; fincom = tmpstring; fileout << fincom << "\n"; } //If default delay trigger is activated, inject output file with a delay command if(delay!=0){ fileout << "DigiKeyboard.delay(" << delay << ");\n"; } } //Ask if user wants to execute the script just once - Use the counter variable instead of initialising a new one since counter won't be used anymore. cout << "Script has been converted successfully. Do you want the DigiSpark to execute the script once or loop infinitely? Select 0 for infinity and 1 for a single execution." << endl; cout << "[0/1]:"; cin >> counter; if(counter){ fileout << "exit();"; } //Close converted script txt fstream fileout.close(); return 0; } <|endoftext|>
<commit_before>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <QDateTime> #include <QString> #include <QVariantMap> #include <TelepathyQt4/Account> #include <TelepathyQt4/ChannelFactory> #include <TelepathyQt4/ConnectionFactory> #include <TelepathyQt4/Debug> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/Types> #include <telepathy-glib/debug.h> #include <glib-object.h> #include <dbus/dbus-glib.h> #include <tests/lib/glib/contacts-conn.h> #include <tests/lib/test.h> using namespace Tp; using namespace Tp::Client; // A really minimal Account implementation, totally not spec compliant outside the parts stressed by // this test class AccountAdaptor : public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Telepathy.Account") Q_CLASSINFO("D-Bus Introspection", "" " <interface name=\"org.freedesktop.Telepathy.Account\" >\n" " <property name=\"Interfaces\" type=\"as\" access=\"read\" />\n" " <property name=\"Connection\" type=\"o\" access=\"read\" />\n" " <signal name=\"AccountPropertyChanged\" >\n" " <arg name=\"Properties\" type=\"a{sv}\" />\n" " </signal>\n" " </interface>\n" "") Q_PROPERTY(QDBusObjectPath Connection READ Connection) Q_PROPERTY(QStringList Interfaces READ Interfaces) public: AccountAdaptor(QObject *parent) : QDBusAbstractAdaptor(parent), mConnection(QLatin1String("/")) { } virtual ~AccountAdaptor() { } void setConnection(QString conn) { if (conn.isEmpty()) { conn = QLatin1String("/"); } mConnection = QDBusObjectPath(conn); QVariantMap props; props.insert(QLatin1String("Connection"), QVariant::fromValue(mConnection)); Q_EMIT AccountPropertyChanged(props); } public: // Properties inline QDBusObjectPath Connection() const { return mConnection; } inline QStringList Interfaces() const { return QStringList(); } Q_SIGNALS: // Signals void AccountPropertyChanged(const QVariantMap &properties); private: QDBusObjectPath mConnection; }; class TestAccountConnectionFactory : public Test { Q_OBJECT public: TestAccountConnectionFactory(QObject *parent = 0) : Test(parent), mDispatcher(0), mConnService1(0), mConnService2(0), mAccountAdaptor(0), mReceivedHaveConnection(0), mReceivedConn(0) { } protected Q_SLOTS: void onConnectionChanged(const Tp::ConnectionPtr &conn); void expectPropertyChange(const QString &property); private Q_SLOTS: void initTestCase(); void init(); void testCreateAndIntrospect(); void testDefaultFactoryInitialConn(); void testReadifyingFactoryInitialConn(); void testSwitch(); void testQueuedSwitch(); void cleanup(); void cleanupTestCase(); private: QObject *mDispatcher; QString mAccountBusName, mAccountPath; TpTestsContactsConnection *mConnService1, *mConnService2; QString mConnPath1, mConnPath2; QString mConnName1, mConnName2; AccountAdaptor *mAccountAdaptor; AccountPtr mAccount; bool *mReceivedHaveConnection; QString *mReceivedConn; QStringList mReceivedConns; }; void TestAccountConnectionFactory::onConnectionChanged(const Tp::ConnectionPtr &conn) { qDebug() << "have connection:" << !conn.isNull(); mReceivedHaveConnection = new bool(!conn.isNull()); } void TestAccountConnectionFactory::expectPropertyChange(const QString &property) { if (property != QLatin1String("connection")) { // Not interesting return; } ConnectionPtr conn = mAccount->connection(); qDebug() << "connection changed:" << (conn ? conn->objectPath() : QLatin1String("none")); if (conn) { QCOMPARE(conn->objectPath(), conn->objectPath()); } if (mReceivedConn) { delete mReceivedConn; } mReceivedConn = new QString(conn ? conn->objectPath() : QLatin1String("")); mReceivedConns.push_back(conn ? conn->objectPath() : QLatin1String("")); } void TestAccountConnectionFactory::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("account-connection-factory"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); gchar *name; gchar *connPath; GError *error = 0; mConnService1 = TP_TESTS_CONTACTS_CONNECTION(g_object_new( TP_TESTS_TYPE_CONTACTS_CONNECTION, "account", "me1@example.com", "protocol", "simple", NULL)); QVERIFY(mConnService1 != 0); QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService1), "contacts", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName1 = QLatin1String(name); mConnPath1 = QLatin1String(connPath); g_free(name); g_free(connPath); mConnService2 = TP_TESTS_CONTACTS_CONNECTION(g_object_new( TP_TESTS_TYPE_CONTACTS_CONNECTION, "account", "me2@example.com", "protocol", "simple", NULL)); QVERIFY(mConnService2 != 0); QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService2), "contacts", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName2 = QLatin1String(name); mConnPath2 = QLatin1String(connPath); g_free(name); g_free(connPath); mAccountBusName = QLatin1String(TELEPATHY_INTERFACE_ACCOUNT_MANAGER); mAccountPath = QLatin1String("/org/freedesktop/Telepathy/Account/simple/simple/account"); } void TestAccountConnectionFactory::init() { initImpl(); mDispatcher = new QObject(this); mAccountAdaptor = new AccountAdaptor(mDispatcher); QDBusConnection bus = QDBusConnection::sessionBus(); QVERIFY(bus.registerService(mAccountBusName)); QVERIFY(bus.registerObject(mAccountPath, mDispatcher)); } // If this test fails, probably the mini-Account implements too little for the Account proxy to work // OR the Account proxy is completely broken :) void TestAccountConnectionFactory::testCreateAndIntrospect() { mAccount = Account::create(mAccountBusName, mAccountPath); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); } void TestAccountConnectionFactory::testDefaultFactoryInitialConn() { mAccountAdaptor->setConnection(mConnPath1); mAccount = Account::create(mAccountBusName, mAccountPath); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAccount->connection()->objectPath(), mConnPath1); QVERIFY(!mAccount->connection().isNull()); QCOMPARE(mAccount->connectionFactory()->features(), Features()); } void TestAccountConnectionFactory::testReadifyingFactoryInitialConn() { mAccountAdaptor->setConnection(mConnPath1); mAccount = Account::create(mAccountBusName, mAccountPath, ConnectionFactory::create(QDBusConnection::sessionBus(), Connection::FeatureCore), ChannelFactory::create(QDBusConnection::sessionBus())); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAccount->connection()->objectPath(), mConnPath1); ConnectionPtr conn = mAccount->connection(); QVERIFY(!conn.isNull()); QVERIFY(conn->isReady(Connection::FeatureCore)); QCOMPARE(mAccount->connectionFactory()->features(), Features(Connection::FeatureCore)); } void TestAccountConnectionFactory::testSwitch() { mAccount = Account::create(mAccountBusName, mAccountPath, ConnectionFactory::create(QDBusConnection::sessionBus(), Connection::FeatureCore), ChannelFactory::create(QDBusConnection::sessionBus())); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(mAccount->connection().isNull()); QVERIFY(connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr &)), SLOT(onConnectionChanged(const Tp::ConnectionPtr &)))); QVERIFY(connect(mAccount.data(), SIGNAL(propertyChanged(QString)), SLOT(expectPropertyChange(QString)))); // Switch from none to conn 1 mAccountAdaptor->setConnection(mConnPath1); while (!mReceivedHaveConnection || !mReceivedConn) { mLoop->processEvents(); } QCOMPARE(*mReceivedHaveConnection, true); QCOMPARE(*mReceivedConn, mConnPath1); delete mReceivedHaveConnection; mReceivedHaveConnection = 0; delete mReceivedConn; mReceivedConn = 0; QCOMPARE(mAccount->connection()->objectPath(), mConnPath1); QVERIFY(!mAccount->connection().isNull()); ConnectionPtr conn = mAccount->connection(); QVERIFY(!conn.isNull()); QCOMPARE(conn->objectPath(), mConnPath1); QVERIFY(conn->isReady(Connection::FeatureCore)); // Switch from conn 1 to conn 2 mAccountAdaptor->setConnection(mConnPath2); while (!mReceivedConn) { mLoop->processEvents(); } QCOMPARE(*mReceivedConn, mConnPath2); delete mReceivedConn; mReceivedConn = 0; // connectionChanged() should have been emitted as it is a new connection QVERIFY(mReceivedHaveConnection); QVERIFY(!mAccount->connection().isNull()); QCOMPARE(mAccount->connection()->objectPath(), mConnPath2); conn = mAccount->connection(); QVERIFY(!conn.isNull()); QCOMPARE(conn->objectPath(), mConnPath2); QVERIFY(conn->isReady(Connection::FeatureCore)); // Switch from conn 2 to none mAccountAdaptor->setConnection(QString()); while (!mReceivedHaveConnection || !mReceivedConn) { mLoop->processEvents(); } QCOMPARE(*mReceivedConn, QString()); QCOMPARE(*mReceivedHaveConnection, false); QVERIFY(mAccount->connection().isNull()); } void TestAccountConnectionFactory::testQueuedSwitch() { mAccount = Account::create(mAccountBusName, mAccountPath, ConnectionFactory::create(QDBusConnection::sessionBus(), Connection::FeatureCore), ChannelFactory::create(QDBusConnection::sessionBus())); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(mAccount->connection().isNull()); QVERIFY(connect(mAccount.data(), SIGNAL(propertyChanged(QString)), SLOT(expectPropertyChange(QString)))); // Switch a few times but don't give the proxy update machinery time to run mAccountAdaptor->setConnection(mConnPath1); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(mConnPath2); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(mConnPath2); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(mConnPath2); mAccountAdaptor->setConnection(mConnPath2); mAccountAdaptor->setConnection(mConnPath1); // We should get a total of 8 changes because some of them aren't actually any different while (mReceivedConns.size() < 8) { mLoop->processEvents(); } // To ensure it didn't go over, which might be possible if it handled two events in one iter QCOMPARE(mReceivedConns.size(), 8); // Ensure we got them in the correct order QCOMPARE(mReceivedConns, QStringList() << mConnPath1 << QString() << mConnPath2 << QString() << mConnPath2 << QString() << mConnPath2 << mConnPath1); // Check that the final state is correct QCOMPARE(mAccount->connection()->objectPath(), mConnPath1); QVERIFY(!mAccount->connection().isNull()); } void TestAccountConnectionFactory::cleanup() { mAccount.reset(); if (mReceivedHaveConnection) { delete mReceivedHaveConnection; mReceivedHaveConnection = 0; } if (mReceivedConn) { delete mReceivedConn; mReceivedConn = 0; } if (mAccountAdaptor) { delete mAccountAdaptor; mAccountAdaptor = 0; } if (mDispatcher) { delete mDispatcher; mDispatcher = 0; } mReceivedConns.clear(); cleanupImpl(); } void TestAccountConnectionFactory::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestAccountConnectionFactory) #include "_gen/account-connection-factory.cpp.moc.hpp" <commit_msg>Don't leak successive haveConnections (from connectionChanged) in TestAccountConnFact<commit_after>#include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtDBus/QtDBus> #include <QtTest/QtTest> #include <QDateTime> #include <QString> #include <QVariantMap> #include <TelepathyQt4/Account> #include <TelepathyQt4/ChannelFactory> #include <TelepathyQt4/ConnectionFactory> #include <TelepathyQt4/Debug> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4/Types> #include <telepathy-glib/debug.h> #include <glib-object.h> #include <dbus/dbus-glib.h> #include <tests/lib/glib/contacts-conn.h> #include <tests/lib/test.h> using namespace Tp; using namespace Tp::Client; // A really minimal Account implementation, totally not spec compliant outside the parts stressed by // this test class AccountAdaptor : public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Telepathy.Account") Q_CLASSINFO("D-Bus Introspection", "" " <interface name=\"org.freedesktop.Telepathy.Account\" >\n" " <property name=\"Interfaces\" type=\"as\" access=\"read\" />\n" " <property name=\"Connection\" type=\"o\" access=\"read\" />\n" " <signal name=\"AccountPropertyChanged\" >\n" " <arg name=\"Properties\" type=\"a{sv}\" />\n" " </signal>\n" " </interface>\n" "") Q_PROPERTY(QDBusObjectPath Connection READ Connection) Q_PROPERTY(QStringList Interfaces READ Interfaces) public: AccountAdaptor(QObject *parent) : QDBusAbstractAdaptor(parent), mConnection(QLatin1String("/")) { } virtual ~AccountAdaptor() { } void setConnection(QString conn) { if (conn.isEmpty()) { conn = QLatin1String("/"); } mConnection = QDBusObjectPath(conn); QVariantMap props; props.insert(QLatin1String("Connection"), QVariant::fromValue(mConnection)); Q_EMIT AccountPropertyChanged(props); } public: // Properties inline QDBusObjectPath Connection() const { return mConnection; } inline QStringList Interfaces() const { return QStringList(); } Q_SIGNALS: // Signals void AccountPropertyChanged(const QVariantMap &properties); private: QDBusObjectPath mConnection; }; class TestAccountConnectionFactory : public Test { Q_OBJECT public: TestAccountConnectionFactory(QObject *parent = 0) : Test(parent), mDispatcher(0), mConnService1(0), mConnService2(0), mAccountAdaptor(0), mReceivedHaveConnection(0), mReceivedConn(0) { } protected Q_SLOTS: void onConnectionChanged(const Tp::ConnectionPtr &conn); void expectPropertyChange(const QString &property); private Q_SLOTS: void initTestCase(); void init(); void testCreateAndIntrospect(); void testDefaultFactoryInitialConn(); void testReadifyingFactoryInitialConn(); void testSwitch(); void testQueuedSwitch(); void cleanup(); void cleanupTestCase(); private: QObject *mDispatcher; QString mAccountBusName, mAccountPath; TpTestsContactsConnection *mConnService1, *mConnService2; QString mConnPath1, mConnPath2; QString mConnName1, mConnName2; AccountAdaptor *mAccountAdaptor; AccountPtr mAccount; bool *mReceivedHaveConnection; QString *mReceivedConn; QStringList mReceivedConns; }; void TestAccountConnectionFactory::onConnectionChanged(const Tp::ConnectionPtr &conn) { qDebug() << "have connection:" << !conn.isNull(); if (mReceivedHaveConnection) { delete mReceivedHaveConnection; } mReceivedHaveConnection = new bool(!conn.isNull()); } void TestAccountConnectionFactory::expectPropertyChange(const QString &property) { if (property != QLatin1String("connection")) { // Not interesting return; } ConnectionPtr conn = mAccount->connection(); qDebug() << "connection changed:" << (conn ? conn->objectPath() : QLatin1String("none")); if (conn) { QCOMPARE(conn->objectPath(), conn->objectPath()); } if (mReceivedConn) { delete mReceivedConn; } mReceivedConn = new QString(conn ? conn->objectPath() : QLatin1String("")); mReceivedConns.push_back(conn ? conn->objectPath() : QLatin1String("")); } void TestAccountConnectionFactory::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("account-connection-factory"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); gchar *name; gchar *connPath; GError *error = 0; mConnService1 = TP_TESTS_CONTACTS_CONNECTION(g_object_new( TP_TESTS_TYPE_CONTACTS_CONNECTION, "account", "me1@example.com", "protocol", "simple", NULL)); QVERIFY(mConnService1 != 0); QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService1), "contacts", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName1 = QLatin1String(name); mConnPath1 = QLatin1String(connPath); g_free(name); g_free(connPath); mConnService2 = TP_TESTS_CONTACTS_CONNECTION(g_object_new( TP_TESTS_TYPE_CONTACTS_CONNECTION, "account", "me2@example.com", "protocol", "simple", NULL)); QVERIFY(mConnService2 != 0); QVERIFY(tp_base_connection_register(TP_BASE_CONNECTION(mConnService2), "contacts", &name, &connPath, &error)); QVERIFY(error == 0); QVERIFY(name != 0); QVERIFY(connPath != 0); mConnName2 = QLatin1String(name); mConnPath2 = QLatin1String(connPath); g_free(name); g_free(connPath); mAccountBusName = QLatin1String(TELEPATHY_INTERFACE_ACCOUNT_MANAGER); mAccountPath = QLatin1String("/org/freedesktop/Telepathy/Account/simple/simple/account"); } void TestAccountConnectionFactory::init() { initImpl(); mDispatcher = new QObject(this); mAccountAdaptor = new AccountAdaptor(mDispatcher); QDBusConnection bus = QDBusConnection::sessionBus(); QVERIFY(bus.registerService(mAccountBusName)); QVERIFY(bus.registerObject(mAccountPath, mDispatcher)); } // If this test fails, probably the mini-Account implements too little for the Account proxy to work // OR the Account proxy is completely broken :) void TestAccountConnectionFactory::testCreateAndIntrospect() { mAccount = Account::create(mAccountBusName, mAccountPath); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); } void TestAccountConnectionFactory::testDefaultFactoryInitialConn() { mAccountAdaptor->setConnection(mConnPath1); mAccount = Account::create(mAccountBusName, mAccountPath); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAccount->connection()->objectPath(), mConnPath1); QVERIFY(!mAccount->connection().isNull()); QCOMPARE(mAccount->connectionFactory()->features(), Features()); } void TestAccountConnectionFactory::testReadifyingFactoryInitialConn() { mAccountAdaptor->setConnection(mConnPath1); mAccount = Account::create(mAccountBusName, mAccountPath, ConnectionFactory::create(QDBusConnection::sessionBus(), Connection::FeatureCore), ChannelFactory::create(QDBusConnection::sessionBus())); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QCOMPARE(mAccount->connection()->objectPath(), mConnPath1); ConnectionPtr conn = mAccount->connection(); QVERIFY(!conn.isNull()); QVERIFY(conn->isReady(Connection::FeatureCore)); QCOMPARE(mAccount->connectionFactory()->features(), Features(Connection::FeatureCore)); } void TestAccountConnectionFactory::testSwitch() { mAccount = Account::create(mAccountBusName, mAccountPath, ConnectionFactory::create(QDBusConnection::sessionBus(), Connection::FeatureCore), ChannelFactory::create(QDBusConnection::sessionBus())); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(mAccount->connection().isNull()); QVERIFY(connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr &)), SLOT(onConnectionChanged(const Tp::ConnectionPtr &)))); QVERIFY(connect(mAccount.data(), SIGNAL(propertyChanged(QString)), SLOT(expectPropertyChange(QString)))); // Switch from none to conn 1 mAccountAdaptor->setConnection(mConnPath1); while (!mReceivedHaveConnection || !mReceivedConn) { mLoop->processEvents(); } QCOMPARE(*mReceivedHaveConnection, true); QCOMPARE(*mReceivedConn, mConnPath1); delete mReceivedHaveConnection; mReceivedHaveConnection = 0; delete mReceivedConn; mReceivedConn = 0; QCOMPARE(mAccount->connection()->objectPath(), mConnPath1); QVERIFY(!mAccount->connection().isNull()); ConnectionPtr conn = mAccount->connection(); QVERIFY(!conn.isNull()); QCOMPARE(conn->objectPath(), mConnPath1); QVERIFY(conn->isReady(Connection::FeatureCore)); // Switch from conn 1 to conn 2 mAccountAdaptor->setConnection(mConnPath2); while (!mReceivedConn) { mLoop->processEvents(); } QCOMPARE(*mReceivedConn, mConnPath2); delete mReceivedConn; mReceivedConn = 0; // connectionChanged() should have been emitted as it is a new connection QVERIFY(mReceivedHaveConnection); QVERIFY(!mAccount->connection().isNull()); QCOMPARE(mAccount->connection()->objectPath(), mConnPath2); conn = mAccount->connection(); QVERIFY(!conn.isNull()); QCOMPARE(conn->objectPath(), mConnPath2); QVERIFY(conn->isReady(Connection::FeatureCore)); // Switch from conn 2 to none mAccountAdaptor->setConnection(QString()); while (!mReceivedHaveConnection || !mReceivedConn) { mLoop->processEvents(); } QCOMPARE(*mReceivedConn, QString()); QCOMPARE(*mReceivedHaveConnection, false); QVERIFY(mAccount->connection().isNull()); } void TestAccountConnectionFactory::testQueuedSwitch() { mAccount = Account::create(mAccountBusName, mAccountPath, ConnectionFactory::create(QDBusConnection::sessionBus(), Connection::FeatureCore), ChannelFactory::create(QDBusConnection::sessionBus())); QVERIFY(connect(mAccount->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); QVERIFY(mAccount->connection().isNull()); QVERIFY(connect(mAccount.data(), SIGNAL(propertyChanged(QString)), SLOT(expectPropertyChange(QString)))); // Switch a few times but don't give the proxy update machinery time to run mAccountAdaptor->setConnection(mConnPath1); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(mConnPath2); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(mConnPath2); mAccountAdaptor->setConnection(QString()); mAccountAdaptor->setConnection(mConnPath2); mAccountAdaptor->setConnection(mConnPath2); mAccountAdaptor->setConnection(mConnPath1); // We should get a total of 8 changes because some of them aren't actually any different while (mReceivedConns.size() < 8) { mLoop->processEvents(); } // To ensure it didn't go over, which might be possible if it handled two events in one iter QCOMPARE(mReceivedConns.size(), 8); // Ensure we got them in the correct order QCOMPARE(mReceivedConns, QStringList() << mConnPath1 << QString() << mConnPath2 << QString() << mConnPath2 << QString() << mConnPath2 << mConnPath1); // Check that the final state is correct QCOMPARE(mAccount->connection()->objectPath(), mConnPath1); QVERIFY(!mAccount->connection().isNull()); } void TestAccountConnectionFactory::cleanup() { mAccount.reset(); if (mReceivedHaveConnection) { delete mReceivedHaveConnection; mReceivedHaveConnection = 0; } if (mReceivedConn) { delete mReceivedConn; mReceivedConn = 0; } if (mAccountAdaptor) { delete mAccountAdaptor; mAccountAdaptor = 0; } if (mDispatcher) { delete mDispatcher; mDispatcher = 0; } mReceivedConns.clear(); cleanupImpl(); } void TestAccountConnectionFactory::cleanupTestCase() { cleanupTestCaseImpl(); } QTEST_MAIN(TestAccountConnectionFactory) #include "_gen/account-connection-factory.cpp.moc.hpp" <|endoftext|>
<commit_before>#include "appinfo.h" const Version AppInfo::version = Version(0, 7, 1, 259); const std::string AppInfo::name = "JASP"; std::string AppInfo::getShortDesc() { return AppInfo::name + " " + AppInfo::version.asString(); } <commit_msg>Version bump: 0.7.1.5<commit_after>#include "appinfo.h" const Version AppInfo::version = Version(0, 7, 1, 260); const std::string AppInfo::name = "JASP"; std::string AppInfo::getShortDesc() { return AppInfo::name + " " + AppInfo::version.asString(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/basictypes.h" #include "base/file_path.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autofill/autofill_common_test.h" #include "chrome/browser/autofill/autofill_type.h" #include "chrome/browser/autofill/data_driven_test.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/autofill/personal_data_manager.h" #include "googleurl/src/gurl.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebInputElement.h" #include "webkit/glue/form_data.h" namespace { const FilePath::CharType kTestName[] = FILE_PATH_LITERAL("merge"); const FilePath::CharType kFileNamePattern[] = FILE_PATH_LITERAL("*.in"); const char kFieldSeparator[] = ": "; const char kProfileSeparator[] = "---"; const size_t kFieldOffset = arraysize(kFieldSeparator) - 1; const AutofillFieldType kProfileFieldTypes[] = { NAME_FIRST, NAME_MIDDLE, NAME_LAST, EMAIL_ADDRESS, COMPANY_NAME, ADDRESS_HOME_LINE1, ADDRESS_HOME_LINE2, ADDRESS_HOME_CITY, ADDRESS_HOME_STATE, ADDRESS_HOME_ZIP, ADDRESS_HOME_COUNTRY, PHONE_HOME_WHOLE_NUMBER }; // Serializes the |profiles| into a string. std::string SerializeProfiles(const std::vector<AutofillProfile*>& profiles) { std::string result; for (size_t i = 0; i < profiles.size(); ++i) { result += kProfileSeparator; result += "\n"; for (size_t j = 0; j < arraysize(kProfileFieldTypes); ++j) { AutofillFieldType type = kProfileFieldTypes[j]; std::vector<string16> values; profiles[i]->GetMultiInfo(type, &values); for (size_t k = 0; k < values.size(); ++k) { result += AutofillType::FieldTypeToString(type); result += kFieldSeparator; result += UTF16ToUTF8(values[k]); result += "\n"; } } } return result; } class PersonalDataManagerMock : public PersonalDataManager { public: PersonalDataManagerMock(); virtual ~PersonalDataManagerMock(); // Reset the saved profiles. void Reset(); // PersonalDataManager: virtual void SaveImportedProfile(const AutofillProfile& profile) OVERRIDE; virtual const std::vector<AutofillProfile*>& web_profiles() const OVERRIDE; private: ScopedVector<AutofillProfile> profiles_; DISALLOW_COPY_AND_ASSIGN(PersonalDataManagerMock); }; PersonalDataManagerMock::PersonalDataManagerMock() : PersonalDataManager() { } PersonalDataManagerMock::~PersonalDataManagerMock() { } void PersonalDataManagerMock::Reset() { profiles_.reset(); } void PersonalDataManagerMock::SaveImportedProfile( const AutofillProfile& profile) { std::vector<AutofillProfile> profiles; if (!MergeProfile(profile, profiles_.get(), &profiles)) profiles_.push_back(new AutofillProfile(profile)); } const std::vector<AutofillProfile*>& PersonalDataManagerMock::web_profiles() const { return profiles_.get(); } } // namespace // A data-driven test for verifying merging of Autofill profiles. Each input is // a structured dump of a set of implicitly detected autofill profiles. The // corresponding output file is a dump of the saved profiles that result from // importing the input profiles. The output file format is identical to the // input format. class AutofillMergeTest : public testing::Test, public DataDrivenTest { protected: AutofillMergeTest(); virtual ~AutofillMergeTest(); // testing::Test: virtual void SetUp(); // DataDrivenTest: virtual void GenerateResults(const std::string& input, std::string* output) OVERRIDE; // Deserializes a set of Autofill profiles from |profiles|, imports each // sequentially, and fills |merged_profiles| with the serialized result. void MergeProfiles(const std::string& profiles, std::string* merged_profiles); scoped_ptr<PersonalDataManagerMock> personal_data_; private: DISALLOW_COPY_AND_ASSIGN(AutofillMergeTest); }; AutofillMergeTest::AutofillMergeTest() : DataDrivenTest() { } AutofillMergeTest::~AutofillMergeTest() { } void AutofillMergeTest::SetUp() { autofill_test::DisableSystemServices(NULL); personal_data_.reset(new PersonalDataManagerMock); } void AutofillMergeTest::GenerateResults(const std::string& input, std::string* output) { MergeProfiles(input, output); } void AutofillMergeTest::MergeProfiles(const std::string& profiles, std::string* merged_profiles) { // Start with no saved profiles. personal_data_->Reset(); // Create a test form. webkit_glue::FormData form; form.name = ASCIIToUTF16("MyTestForm"); form.method = ASCIIToUTF16("POST"); form.origin = GURL("https://www.example.com/origin.html"); form.action = GURL("https://www.example.com/action.html"); form.user_submitted = true; // Parse the input line by line. std::vector<std::string> lines; Tokenize(profiles, "\n", &lines); for (size_t i = 0; i < lines.size(); ++i) { std::string line = lines[i]; if (line != kProfileSeparator) { // Add a field to the current profile. size_t separator_pos = line.find(kFieldSeparator); ASSERT_NE(std::string::npos, separator_pos); string16 field_type = UTF8ToUTF16(line.substr(0, separator_pos)); string16 value = UTF8ToUTF16(line.substr(separator_pos + kFieldOffset)); webkit_glue::FormField field; field.label = field_type; field.name = field_type; field.value = value; field.form_control_type = ASCIIToUTF16("text"); form.fields.push_back(field); } // The first line is always a profile separator, and the last profile is not // followed by an explicit separator. if ((i > 0 && line == kProfileSeparator) || i == lines.size() - 1) { // Reached the end of a profile. Try to import it. FormStructure form_structure(form); for (size_t i = 0; i < form_structure.field_count(); ++i) { // Set the heuristic type for each field, which is currently serialized // into the field's name. AutofillField* field = const_cast<AutofillField*>(form_structure.field(i)); AutofillFieldType type = AutofillType::StringToFieldType(UTF16ToUTF8(field->name)); field->set_heuristic_type(type); } // Import the profile. const CreditCard* imported_credit_card; personal_data_->ImportFormData(form_structure, &imported_credit_card); EXPECT_FALSE(imported_credit_card); // Clear the |form| to start a new profile. form.fields.clear(); } } *merged_profiles = SerializeProfiles(personal_data_->web_profiles()); } TEST_F(AutofillMergeTest, DataDrivenMergeProfiles) { RunDataDrivenTest(GetInputDirectory(kTestName), GetOutputDirectory(kTestName), kFileNamePattern); } <commit_msg>AutofillMergeTest doesn't need scoped_ptr for PersonalDataManager mock<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/basictypes.h" #include "base/file_path.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autofill/autofill_common_test.h" #include "chrome/browser/autofill/autofill_type.h" #include "chrome/browser/autofill/data_driven_test.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/autofill/personal_data_manager.h" #include "googleurl/src/gurl.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebInputElement.h" #include "webkit/glue/form_data.h" namespace { const FilePath::CharType kTestName[] = FILE_PATH_LITERAL("merge"); const FilePath::CharType kFileNamePattern[] = FILE_PATH_LITERAL("*.in"); const char kFieldSeparator[] = ": "; const char kProfileSeparator[] = "---"; const size_t kFieldOffset = arraysize(kFieldSeparator) - 1; const AutofillFieldType kProfileFieldTypes[] = { NAME_FIRST, NAME_MIDDLE, NAME_LAST, EMAIL_ADDRESS, COMPANY_NAME, ADDRESS_HOME_LINE1, ADDRESS_HOME_LINE2, ADDRESS_HOME_CITY, ADDRESS_HOME_STATE, ADDRESS_HOME_ZIP, ADDRESS_HOME_COUNTRY, PHONE_HOME_WHOLE_NUMBER }; // Serializes the |profiles| into a string. std::string SerializeProfiles(const std::vector<AutofillProfile*>& profiles) { std::string result; for (size_t i = 0; i < profiles.size(); ++i) { result += kProfileSeparator; result += "\n"; for (size_t j = 0; j < arraysize(kProfileFieldTypes); ++j) { AutofillFieldType type = kProfileFieldTypes[j]; std::vector<string16> values; profiles[i]->GetMultiInfo(type, &values); for (size_t k = 0; k < values.size(); ++k) { result += AutofillType::FieldTypeToString(type); result += kFieldSeparator; result += UTF16ToUTF8(values[k]); result += "\n"; } } } return result; } class PersonalDataManagerMock : public PersonalDataManager { public: PersonalDataManagerMock(); virtual ~PersonalDataManagerMock(); // Reset the saved profiles. void Reset(); // PersonalDataManager: virtual void SaveImportedProfile(const AutofillProfile& profile) OVERRIDE; virtual const std::vector<AutofillProfile*>& web_profiles() const OVERRIDE; private: ScopedVector<AutofillProfile> profiles_; DISALLOW_COPY_AND_ASSIGN(PersonalDataManagerMock); }; PersonalDataManagerMock::PersonalDataManagerMock() : PersonalDataManager() { } PersonalDataManagerMock::~PersonalDataManagerMock() { } void PersonalDataManagerMock::Reset() { profiles_.reset(); } void PersonalDataManagerMock::SaveImportedProfile( const AutofillProfile& profile) { std::vector<AutofillProfile> profiles; if (!MergeProfile(profile, profiles_.get(), &profiles)) profiles_.push_back(new AutofillProfile(profile)); } const std::vector<AutofillProfile*>& PersonalDataManagerMock::web_profiles() const { return profiles_.get(); } } // namespace // A data-driven test for verifying merging of Autofill profiles. Each input is // a structured dump of a set of implicitly detected autofill profiles. The // corresponding output file is a dump of the saved profiles that result from // importing the input profiles. The output file format is identical to the // input format. class AutofillMergeTest : public testing::Test, public DataDrivenTest { protected: AutofillMergeTest(); virtual ~AutofillMergeTest(); // testing::Test: virtual void SetUp(); // DataDrivenTest: virtual void GenerateResults(const std::string& input, std::string* output) OVERRIDE; // Deserializes a set of Autofill profiles from |profiles|, imports each // sequentially, and fills |merged_profiles| with the serialized result. void MergeProfiles(const std::string& profiles, std::string* merged_profiles); PersonalDataManagerMock personal_data_; private: DISALLOW_COPY_AND_ASSIGN(AutofillMergeTest); }; AutofillMergeTest::AutofillMergeTest() : DataDrivenTest() { } AutofillMergeTest::~AutofillMergeTest() { } void AutofillMergeTest::SetUp() { autofill_test::DisableSystemServices(NULL); } void AutofillMergeTest::GenerateResults(const std::string& input, std::string* output) { MergeProfiles(input, output); } void AutofillMergeTest::MergeProfiles(const std::string& profiles, std::string* merged_profiles) { // Start with no saved profiles. personal_data_.Reset(); // Create a test form. webkit_glue::FormData form; form.name = ASCIIToUTF16("MyTestForm"); form.method = ASCIIToUTF16("POST"); form.origin = GURL("https://www.example.com/origin.html"); form.action = GURL("https://www.example.com/action.html"); form.user_submitted = true; // Parse the input line by line. std::vector<std::string> lines; Tokenize(profiles, "\n", &lines); for (size_t i = 0; i < lines.size(); ++i) { std::string line = lines[i]; if (line != kProfileSeparator) { // Add a field to the current profile. size_t separator_pos = line.find(kFieldSeparator); ASSERT_NE(std::string::npos, separator_pos); string16 field_type = UTF8ToUTF16(line.substr(0, separator_pos)); string16 value = UTF8ToUTF16(line.substr(separator_pos + kFieldOffset)); webkit_glue::FormField field; field.label = field_type; field.name = field_type; field.value = value; field.form_control_type = ASCIIToUTF16("text"); form.fields.push_back(field); } // The first line is always a profile separator, and the last profile is not // followed by an explicit separator. if ((i > 0 && line == kProfileSeparator) || i == lines.size() - 1) { // Reached the end of a profile. Try to import it. FormStructure form_structure(form); for (size_t i = 0; i < form_structure.field_count(); ++i) { // Set the heuristic type for each field, which is currently serialized // into the field's name. AutofillField* field = const_cast<AutofillField*>(form_structure.field(i)); AutofillFieldType type = AutofillType::StringToFieldType(UTF16ToUTF8(field->name)); field->set_heuristic_type(type); } // Import the profile. const CreditCard* imported_credit_card; personal_data_.ImportFormData(form_structure, &imported_credit_card); EXPECT_EQ(static_cast<const CreditCard*>(NULL), imported_credit_card); // Clear the |form| to start a new profile. form.fields.clear(); } } *merged_profiles = SerializeProfiles(personal_data_.web_profiles()); } TEST_F(AutofillMergeTest, DataDrivenMergeProfiles) { RunDataDrivenTest(GetInputDirectory(kTestName), GetOutputDirectory(kTestName), kFileNamePattern); } <|endoftext|>
<commit_before>//-------------------------------------------------------------------------------------- // File: SpriteFont.cpp // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248929 //-------------------------------------------------------------------------------------- #include "pch.h" #define NOMINMAX #include <algorithm> #include <vector> #include "SpriteFont.h" #include "DirectXHelpers.h" #include "BinaryReader.h" using namespace DirectX; using namespace Microsoft::WRL; // Internal SpriteFont implementation class. class SpriteFont::Impl { public: Impl(_In_ ID3D11Device* device, _In_ BinaryReader* reader); Impl(_In_ ID3D11ShaderResourceView* texture, _In_reads_(glyphCount) Glyph const* glyphs, _In_ size_t glyphCount, _In_ float lineSpacing); Glyph const* FindGlyph(wchar_t character) const; void SetDefaultCharacter(wchar_t character); template<typename TAction> void ForEachGlyph(_In_z_ wchar_t const* text, TAction action); // Fields. ComPtr<ID3D11ShaderResourceView> texture; std::vector<Glyph> glyphs; Glyph const* defaultGlyph; float lineSpacing; }; // Constants. const XMFLOAT2 SpriteFont::Float2Zero(0, 0); static const char spriteFontMagic[] = "DXTKfont"; // Comparison operators make our sorted glyph vector work with std::binary_search and lower_bound. namespace DirectX { static inline bool operator< (SpriteFont::Glyph const& left, SpriteFont::Glyph const& right) { return left.Character < right.Character; } static inline bool operator< (wchar_t left, SpriteFont::Glyph const& right) { return left < right.Character; } static inline bool operator< (SpriteFont::Glyph const& left, wchar_t right) { return left.Character < right; } } // Reads a SpriteFont from the binary format created by the MakeSpriteFont utility. SpriteFont::Impl::Impl(_In_ ID3D11Device* device, _In_ BinaryReader* reader) { // Validate the header. for (char const* magic = spriteFontMagic; *magic; magic++) { if (reader->Read<uint8_t>() != *magic) { DebugTrace( "SpriteFont provided with an invalid .spritefont file\n" ); throw std::exception("Not a MakeSpriteFont output binary"); } } // Read the glyph data. auto glyphCount = reader->Read<uint32_t>(); auto glyphData = reader->ReadArray<Glyph>(glyphCount); glyphs.assign(glyphData, glyphData + glyphCount); // Read font properties. lineSpacing = reader->Read<float>(); SetDefaultCharacter((wchar_t)reader->Read<uint32_t>()); // Read the texture data. auto textureWidth = reader->Read<uint32_t>(); auto textureHeight = reader->Read<uint32_t>(); auto textureFormat = reader->Read<DXGI_FORMAT>(); auto textureStride = reader->Read<uint32_t>(); auto textureRows = reader->Read<uint32_t>(); auto textureData = reader->ReadArray<uint8_t>(textureStride * textureRows); // Create the D3D texture. CD3D11_TEXTURE2D_DESC textureDesc(textureFormat, textureWidth, textureHeight, 1, 1, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_IMMUTABLE); CD3D11_SHADER_RESOURCE_VIEW_DESC viewDesc(D3D11_SRV_DIMENSION_TEXTURE2D, textureFormat); D3D11_SUBRESOURCE_DATA initData = { textureData, textureStride }; ComPtr<ID3D11Texture2D> texture2D; ThrowIfFailed( device->CreateTexture2D(&textureDesc, &initData, &texture2D) ); ThrowIfFailed( device->CreateShaderResourceView(texture2D.Get(), &viewDesc, &texture) ); SetDebugObjectName(texture.Get(), "DirectXTK:SpriteFont"); SetDebugObjectName(texture2D.Get(), "DirectXTK:SpriteFont"); } // Constructs a SpriteFont from arbitrary user specified glyph data. SpriteFont::Impl::Impl(_In_ ID3D11ShaderResourceView* texture, _In_reads_(glyphCount) Glyph const* glyphs, _In_ size_t glyphCount, _In_ float lineSpacing) : texture(texture), glyphs(glyphs, glyphs + glyphCount), lineSpacing(lineSpacing), defaultGlyph(nullptr) { if (!std::is_sorted(glyphs, glyphs + glyphCount)) { throw std::exception("Glyphs must be in ascending codepoint order"); } } // Looks up the requested glyph, falling back to the default character if it is not in the font. SpriteFont::Glyph const* SpriteFont::Impl::FindGlyph(wchar_t character) const { auto glyph = std::lower_bound(glyphs.begin(), glyphs.end(), character); if (glyph != glyphs.end() && glyph->Character == character) { return &*glyph; } if (defaultGlyph) { return defaultGlyph; } DebugTrace( "SpriteFont encountered a character not in the font (%u, %C), and no default glyph was provided\n", character, character ); throw std::exception("Character not in font"); } // Sets the missing-character fallback glyph. void SpriteFont::Impl::SetDefaultCharacter(wchar_t character) { defaultGlyph = nullptr; if (character) { defaultGlyph = FindGlyph(character); } } // The core glyph layout algorithm, shared between DrawString and MeasureString. template<typename TAction> void SpriteFont::Impl::ForEachGlyph(_In_z_ wchar_t const* text, TAction action) { float x = 0; float y = 0; for (; *text; text++) { wchar_t character = *text; switch (character) { case '\r': // Skip carriage returns. continue; case '\n': // New line. x = 0; y += lineSpacing; break; default: // Output this character. auto glyph = FindGlyph(character); x += glyph->XOffset; if (x < 0) x = 0; if (!iswspace(character)) { action(glyph, x, y); } x += glyph->Subrect.right - glyph->Subrect.left + glyph->XAdvance; break; } } } // Construct from a binary file created by the MakeSpriteFont utility. SpriteFont::SpriteFont(_In_ ID3D11Device* device, _In_z_ wchar_t const* fileName) { BinaryReader reader(fileName); pImpl.reset(new Impl(device, &reader)); } // Construct from a binary blob created by the MakeSpriteFont utility and already loaded into memory. SpriteFont::SpriteFont(_In_ ID3D11Device* device, _In_reads_bytes_(dataSize) uint8_t const* dataBlob, _In_ size_t dataSize) { BinaryReader reader(dataBlob, dataSize); pImpl.reset(new Impl(device, &reader)); } // Construct from arbitrary user specified glyph data (for those not using the MakeSpriteFont utility). SpriteFont::SpriteFont(_In_ ID3D11ShaderResourceView* texture, _In_reads_(glyphCount) Glyph const* glyphs, _In_ size_t glyphCount, _In_ float lineSpacing) : pImpl(new Impl(texture, glyphs, glyphCount, lineSpacing)) { } // Move constructor. SpriteFont::SpriteFont(SpriteFont&& moveFrom) : pImpl(std::move(moveFrom.pImpl)) { } // Move assignment. SpriteFont& SpriteFont::operator= (SpriteFont&& moveFrom) { pImpl = std::move(moveFrom.pImpl); return *this; } // Public destructor. SpriteFont::~SpriteFont() { } void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, float scale, SpriteEffects effects, float layerDepth) { DrawString(spriteBatch, text, XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMVectorReplicate(scale), effects, layerDepth); } void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects, float layerDepth) { DrawString(spriteBatch, text, XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMLoadFloat2(&scale), effects, layerDepth); } void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, float scale, SpriteEffects effects, float layerDepth) { DrawString(spriteBatch, text, position, color, rotation, origin, XMVectorReplicate(scale), effects, layerDepth); } void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects, float layerDepth) { static_assert(SpriteEffects_FlipHorizontally == 1 && SpriteEffects_FlipVertically == 2, "If you change these enum values, the following tables must be updated to match"); // Lookup table indicates which way to move along each axis per SpriteEffects enum value. static XMVECTORF32 axisDirectionTable[4] = { { -1, -1 }, { 1, -1 }, { -1, 1 }, { 1, 1 }, }; // Lookup table indicates which axes are mirrored for each SpriteEffects enum value. static XMVECTORF32 axisIsMirroredTable[4] = { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 }, }; XMVECTOR baseOffset = origin; // If the text is mirrored, offset the start position accordingly. if (effects) { baseOffset -= MeasureString(text) * axisIsMirroredTable[effects & 3]; } // Draw each character in turn. pImpl->ForEachGlyph(text, [&](Glyph const* glyph, float x, float y) { XMVECTOR offset = XMVectorMultiplyAdd(XMVectorSet(x, y + glyph->YOffset, 0, 0), axisDirectionTable[effects & 3], baseOffset); if (effects) { // For mirrored characters, specify bottom and/or right instead of top left. XMVECTOR glyphRect = XMConvertVectorIntToFloat(XMLoadInt4(reinterpret_cast<uint32_t const*>(&glyph->Subrect)), 0); // xy = glyph width/height. glyphRect = XMVectorSwizzle<2, 3, 0, 1>(glyphRect) - glyphRect; offset = XMVectorMultiplyAdd(glyphRect, axisIsMirroredTable[effects & 3], offset); } spriteBatch->Draw(pImpl->texture.Get(), position, &glyph->Subrect, color, rotation, offset, scale, effects, layerDepth); }); } XMVECTOR SpriteFont::MeasureString(_In_z_ wchar_t const* text) const { XMVECTOR result = XMVectorZero(); pImpl->ForEachGlyph(text, [&](Glyph const* glyph, float x, float y) { float w = (float)(glyph->Subrect.right - glyph->Subrect.left); float h = (float)(glyph->Subrect.bottom - glyph->Subrect.top) + glyph->YOffset; h = std::max(h, pImpl->lineSpacing); result = XMVectorMax(result, XMVectorSet(x + w, y + h, 0, 0)); }); return result; } float SpriteFont::GetLineSpacing() const { return pImpl->lineSpacing; } void SpriteFont::SetLineSpacing(float spacing) { pImpl->lineSpacing = spacing; } wchar_t SpriteFont::GetDefaultCharacter() const { return pImpl->defaultGlyph ? (wchar_t)pImpl->defaultGlyph->Character : 0; } void SpriteFont::SetDefaultCharacter(wchar_t character) { pImpl->SetDefaultCharacter(character); } bool SpriteFont::ContainsCharacter(wchar_t character) const { return std::binary_search(pImpl->glyphs.begin(), pImpl->glyphs.end(), character); } <commit_msg>SpriteFont: fix problem with skipping render of white-space characters that are not blank<commit_after>//-------------------------------------------------------------------------------------- // File: SpriteFont.cpp // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=248929 //-------------------------------------------------------------------------------------- #include "pch.h" #define NOMINMAX #include <algorithm> #include <vector> #include "SpriteFont.h" #include "DirectXHelpers.h" #include "BinaryReader.h" using namespace DirectX; using namespace Microsoft::WRL; // Internal SpriteFont implementation class. class SpriteFont::Impl { public: Impl(_In_ ID3D11Device* device, _In_ BinaryReader* reader); Impl(_In_ ID3D11ShaderResourceView* texture, _In_reads_(glyphCount) Glyph const* glyphs, _In_ size_t glyphCount, _In_ float lineSpacing); Glyph const* FindGlyph(wchar_t character) const; void SetDefaultCharacter(wchar_t character); template<typename TAction> void ForEachGlyph(_In_z_ wchar_t const* text, TAction action); // Fields. ComPtr<ID3D11ShaderResourceView> texture; std::vector<Glyph> glyphs; Glyph const* defaultGlyph; float lineSpacing; }; // Constants. const XMFLOAT2 SpriteFont::Float2Zero(0, 0); static const char spriteFontMagic[] = "DXTKfont"; // Comparison operators make our sorted glyph vector work with std::binary_search and lower_bound. namespace DirectX { static inline bool operator< (SpriteFont::Glyph const& left, SpriteFont::Glyph const& right) { return left.Character < right.Character; } static inline bool operator< (wchar_t left, SpriteFont::Glyph const& right) { return left < right.Character; } static inline bool operator< (SpriteFont::Glyph const& left, wchar_t right) { return left.Character < right; } } // Reads a SpriteFont from the binary format created by the MakeSpriteFont utility. SpriteFont::Impl::Impl(_In_ ID3D11Device* device, _In_ BinaryReader* reader) { // Validate the header. for (char const* magic = spriteFontMagic; *magic; magic++) { if (reader->Read<uint8_t>() != *magic) { DebugTrace( "SpriteFont provided with an invalid .spritefont file\n" ); throw std::exception("Not a MakeSpriteFont output binary"); } } // Read the glyph data. auto glyphCount = reader->Read<uint32_t>(); auto glyphData = reader->ReadArray<Glyph>(glyphCount); glyphs.assign(glyphData, glyphData + glyphCount); // Read font properties. lineSpacing = reader->Read<float>(); SetDefaultCharacter((wchar_t)reader->Read<uint32_t>()); // Read the texture data. auto textureWidth = reader->Read<uint32_t>(); auto textureHeight = reader->Read<uint32_t>(); auto textureFormat = reader->Read<DXGI_FORMAT>(); auto textureStride = reader->Read<uint32_t>(); auto textureRows = reader->Read<uint32_t>(); auto textureData = reader->ReadArray<uint8_t>(textureStride * textureRows); // Create the D3D texture. CD3D11_TEXTURE2D_DESC textureDesc(textureFormat, textureWidth, textureHeight, 1, 1, D3D11_BIND_SHADER_RESOURCE, D3D11_USAGE_IMMUTABLE); CD3D11_SHADER_RESOURCE_VIEW_DESC viewDesc(D3D11_SRV_DIMENSION_TEXTURE2D, textureFormat); D3D11_SUBRESOURCE_DATA initData = { textureData, textureStride }; ComPtr<ID3D11Texture2D> texture2D; ThrowIfFailed( device->CreateTexture2D(&textureDesc, &initData, &texture2D) ); ThrowIfFailed( device->CreateShaderResourceView(texture2D.Get(), &viewDesc, &texture) ); SetDebugObjectName(texture.Get(), "DirectXTK:SpriteFont"); SetDebugObjectName(texture2D.Get(), "DirectXTK:SpriteFont"); } // Constructs a SpriteFont from arbitrary user specified glyph data. SpriteFont::Impl::Impl(_In_ ID3D11ShaderResourceView* texture, _In_reads_(glyphCount) Glyph const* glyphs, _In_ size_t glyphCount, _In_ float lineSpacing) : texture(texture), glyphs(glyphs, glyphs + glyphCount), lineSpacing(lineSpacing), defaultGlyph(nullptr) { if (!std::is_sorted(glyphs, glyphs + glyphCount)) { throw std::exception("Glyphs must be in ascending codepoint order"); } } // Looks up the requested glyph, falling back to the default character if it is not in the font. SpriteFont::Glyph const* SpriteFont::Impl::FindGlyph(wchar_t character) const { auto glyph = std::lower_bound(glyphs.begin(), glyphs.end(), character); if (glyph != glyphs.end() && glyph->Character == character) { return &*glyph; } if (defaultGlyph) { return defaultGlyph; } DebugTrace( "SpriteFont encountered a character not in the font (%u, %C), and no default glyph was provided\n", character, character ); throw std::exception("Character not in font"); } // Sets the missing-character fallback glyph. void SpriteFont::Impl::SetDefaultCharacter(wchar_t character) { defaultGlyph = nullptr; if (character) { defaultGlyph = FindGlyph(character); } } // The core glyph layout algorithm, shared between DrawString and MeasureString. template<typename TAction> void SpriteFont::Impl::ForEachGlyph(_In_z_ wchar_t const* text, TAction action) { float x = 0; float y = 0; for (; *text; text++) { wchar_t character = *text; switch (character) { case '\r': // Skip carriage returns. continue; case '\n': // New line. x = 0; y += lineSpacing; break; default: // Output this character. auto glyph = FindGlyph(character); x += glyph->XOffset; if (x < 0) x = 0; if ( !iswspace(character) || ( ( glyph->Subrect.right - glyph->Subrect.left ) > 1 ) || ( ( glyph->Subrect.bottom - glyph->Subrect.top ) > 1 ) ) { action(glyph, x, y); } x += glyph->Subrect.right - glyph->Subrect.left + glyph->XAdvance; break; } } } // Construct from a binary file created by the MakeSpriteFont utility. SpriteFont::SpriteFont(_In_ ID3D11Device* device, _In_z_ wchar_t const* fileName) { BinaryReader reader(fileName); pImpl.reset(new Impl(device, &reader)); } // Construct from a binary blob created by the MakeSpriteFont utility and already loaded into memory. SpriteFont::SpriteFont(_In_ ID3D11Device* device, _In_reads_bytes_(dataSize) uint8_t const* dataBlob, _In_ size_t dataSize) { BinaryReader reader(dataBlob, dataSize); pImpl.reset(new Impl(device, &reader)); } // Construct from arbitrary user specified glyph data (for those not using the MakeSpriteFont utility). SpriteFont::SpriteFont(_In_ ID3D11ShaderResourceView* texture, _In_reads_(glyphCount) Glyph const* glyphs, _In_ size_t glyphCount, _In_ float lineSpacing) : pImpl(new Impl(texture, glyphs, glyphCount, lineSpacing)) { } // Move constructor. SpriteFont::SpriteFont(SpriteFont&& moveFrom) : pImpl(std::move(moveFrom.pImpl)) { } // Move assignment. SpriteFont& SpriteFont::operator= (SpriteFont&& moveFrom) { pImpl = std::move(moveFrom.pImpl); return *this; } // Public destructor. SpriteFont::~SpriteFont() { } void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, float scale, SpriteEffects effects, float layerDepth) { DrawString(spriteBatch, text, XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMVectorReplicate(scale), effects, layerDepth); } void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, XMFLOAT2 const& position, FXMVECTOR color, float rotation, XMFLOAT2 const& origin, XMFLOAT2 const& scale, SpriteEffects effects, float layerDepth) { DrawString(spriteBatch, text, XMLoadFloat2(&position), color, rotation, XMLoadFloat2(&origin), XMLoadFloat2(&scale), effects, layerDepth); } void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, float scale, SpriteEffects effects, float layerDepth) { DrawString(spriteBatch, text, position, color, rotation, origin, XMVectorReplicate(scale), effects, layerDepth); } void XM_CALLCONV SpriteFont::DrawString(_In_ SpriteBatch* spriteBatch, _In_z_ wchar_t const* text, FXMVECTOR position, FXMVECTOR color, float rotation, FXMVECTOR origin, GXMVECTOR scale, SpriteEffects effects, float layerDepth) { static_assert(SpriteEffects_FlipHorizontally == 1 && SpriteEffects_FlipVertically == 2, "If you change these enum values, the following tables must be updated to match"); // Lookup table indicates which way to move along each axis per SpriteEffects enum value. static XMVECTORF32 axisDirectionTable[4] = { { -1, -1 }, { 1, -1 }, { -1, 1 }, { 1, 1 }, }; // Lookup table indicates which axes are mirrored for each SpriteEffects enum value. static XMVECTORF32 axisIsMirroredTable[4] = { { 0, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 }, }; XMVECTOR baseOffset = origin; // If the text is mirrored, offset the start position accordingly. if (effects) { baseOffset -= MeasureString(text) * axisIsMirroredTable[effects & 3]; } // Draw each character in turn. pImpl->ForEachGlyph(text, [&](Glyph const* glyph, float x, float y) { XMVECTOR offset = XMVectorMultiplyAdd(XMVectorSet(x, y + glyph->YOffset, 0, 0), axisDirectionTable[effects & 3], baseOffset); if (effects) { // For mirrored characters, specify bottom and/or right instead of top left. XMVECTOR glyphRect = XMConvertVectorIntToFloat(XMLoadInt4(reinterpret_cast<uint32_t const*>(&glyph->Subrect)), 0); // xy = glyph width/height. glyphRect = XMVectorSwizzle<2, 3, 0, 1>(glyphRect) - glyphRect; offset = XMVectorMultiplyAdd(glyphRect, axisIsMirroredTable[effects & 3], offset); } spriteBatch->Draw(pImpl->texture.Get(), position, &glyph->Subrect, color, rotation, offset, scale, effects, layerDepth); }); } XMVECTOR SpriteFont::MeasureString(_In_z_ wchar_t const* text) const { XMVECTOR result = XMVectorZero(); pImpl->ForEachGlyph(text, [&](Glyph const* glyph, float x, float y) { float w = (float)(glyph->Subrect.right - glyph->Subrect.left); float h = (float)(glyph->Subrect.bottom - glyph->Subrect.top) + glyph->YOffset; h = std::max(h, pImpl->lineSpacing); result = XMVectorMax(result, XMVectorSet(x + w, y + h, 0, 0)); }); return result; } float SpriteFont::GetLineSpacing() const { return pImpl->lineSpacing; } void SpriteFont::SetLineSpacing(float spacing) { pImpl->lineSpacing = spacing; } wchar_t SpriteFont::GetDefaultCharacter() const { return pImpl->defaultGlyph ? (wchar_t)pImpl->defaultGlyph->Character : 0; } void SpriteFont::SetDefaultCharacter(wchar_t character) { pImpl->SetDefaultCharacter(character); } bool SpriteFont::ContainsCharacter(wchar_t character) const { return std::binary_search(pImpl->glyphs.begin(), pImpl->glyphs.end(), character); } <|endoftext|>
<commit_before><commit_msg>Fix a typo that crashes oobe.<commit_after><|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "geojson_datasource.hpp" #include "geojson_featureset.hpp" #include <fstream> #include <algorithm> // boost #include <boost/variant.hpp> #include <boost/make_shared.hpp> #include <boost/algorithm/string.hpp> #include <boost/spirit/include/support_multi_pass.hpp> #include <boost/foreach.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry.hpp> #include <boost/geometry/extensions/index/rtree/rtree.hpp> // mapnik #include <mapnik/unicode.hpp> #include <mapnik/utils.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_kv_iterator.hpp> #include <mapnik/box2d.hpp> #include <mapnik/debug.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/projection.hpp> #include <mapnik/util/geometry_to_ds_type.hpp> #include <mapnik/json/feature_collection_parser.hpp> using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(geojson_datasource) struct attr_value_converter : public boost::static_visitor<mapnik::eAttributeType> { mapnik::eAttributeType operator() (mapnik::value_integer /*val*/) const { return mapnik::Integer; } mapnik::eAttributeType operator() (double /*val*/) const { return mapnik::Double; } mapnik::eAttributeType operator() (float /*val*/) const { return mapnik::Double; } mapnik::eAttributeType operator() (bool /*val*/) const { return mapnik::Boolean; } mapnik::eAttributeType operator() (std::string const& /*val*/) const { return mapnik::String; } mapnik::eAttributeType operator() (UnicodeString const& /*val*/) const { return mapnik::String; } mapnik::eAttributeType operator() (mapnik::value_null const& /*val*/) const { return mapnik::String; } }; geojson_datasource::geojson_datasource(parameters const& params) : datasource(params), type_(datasource::Vector), desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")), file_(*params.get<std::string>("file","")), extent_(), tr_(new mapnik::transcoder(*params.get<std::string>("encoding","utf-8"))), features_(), tree_(16,1) { if (file_.empty()) throw mapnik::datasource_exception("GeoJSON Plugin: missing <file> parameter"); typedef std::istreambuf_iterator<char> base_iterator_type; #if defined (_WINDOWS) std::ifstream is(mapnik::utf8_to_utf16(file_),std::ios_base::in | std::ios_base::binary); #else std::ifstream is(file_.c_str(),std::ios_base::in | std::ios_base::binary); #endif boost::spirit::multi_pass<base_iterator_type> begin = boost::spirit::make_default_multi_pass(base_iterator_type(is)); boost::spirit::multi_pass<base_iterator_type> end = boost::spirit::make_default_multi_pass(base_iterator_type()); mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>(); mapnik::json::feature_collection_parser<boost::spirit::multi_pass<base_iterator_type> > p(ctx,*tr_); bool result = p.parse(begin,end, features_); if (!result) { throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file '" + file_ + "'"); } bool first = true; std::size_t count=0; BOOST_FOREACH (mapnik::feature_ptr f, features_) { mapnik::box2d<double> const& box = f->envelope(); if (first) { extent_ = box; first = false; mapnik::feature_kv_iterator f_itr = f->begin(); mapnik::feature_kv_iterator f_end = f->end(); for ( ;f_itr!=f_end; ++f_itr) { desc_.add_descriptor(mapnik::attribute_descriptor(boost::get<0>(*f_itr), boost::apply_visitor(attr_value_converter(),boost::get<1>(*f_itr).base()))); } } else { extent_.expand_to_include(box); } tree_.insert(box_type(point_type(box.minx(),box.miny()),point_type(box.maxx(),box.maxy())), count++); } } geojson_datasource::~geojson_datasource() { } const char * geojson_datasource::name() { return "geojson"; } boost::optional<mapnik::datasource::geometry_t> geojson_datasource::get_geometry_type() const { boost::optional<mapnik::datasource::geometry_t> result; int multi_type = 0; unsigned num_features = features_.size(); for (unsigned i = 0; i < num_features && i < 5; ++i) { mapnik::util::to_ds_type(features_[i]->paths(),result); if (result) { int type = static_cast<int>(*result); if (multi_type > 0 && multi_type != type) { result.reset(mapnik::datasource::Collection); return result; } multi_type = type; } } return result; } mapnik::datasource::datasource_t geojson_datasource::type() const { return type_; } mapnik::box2d<double> geojson_datasource::envelope() const { return extent_; } mapnik::layer_descriptor geojson_datasource::get_descriptor() const { return desc_; } mapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const { // if the query box intersects our world extent then query for features mapnik::box2d<double> const& b = q.get_bbox(); if (extent_.intersects(b)) { box_type box(point_type(b.minx(),b.miny()),point_type(b.maxx(),b.maxy())); index_array_ = tree_.find(box); return boost::make_shared<geojson_featureset>(features_, index_array_.begin(), index_array_.end()); } // otherwise return an empty featureset pointer return mapnik::featureset_ptr(); } // FIXME mapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const { throw mapnik::datasource_exception("GeoJSON Plugin: features_at_point is not supported yet"); return mapnik::featureset_ptr(); } <commit_msg>+ implement features_at_point in term of existing features(query)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "geojson_datasource.hpp" #include "geojson_featureset.hpp" #include <fstream> #include <algorithm> // boost #include <boost/variant.hpp> #include <boost/make_shared.hpp> #include <boost/algorithm/string.hpp> #include <boost/spirit/include/support_multi_pass.hpp> #include <boost/foreach.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry.hpp> #include <boost/geometry/extensions/index/rtree/rtree.hpp> // mapnik #include <mapnik/unicode.hpp> #include <mapnik/utils.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_kv_iterator.hpp> #include <mapnik/box2d.hpp> #include <mapnik/debug.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/projection.hpp> #include <mapnik/util/geometry_to_ds_type.hpp> #include <mapnik/json/feature_collection_parser.hpp> using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(geojson_datasource) struct attr_value_converter : public boost::static_visitor<mapnik::eAttributeType> { mapnik::eAttributeType operator() (mapnik::value_integer /*val*/) const { return mapnik::Integer; } mapnik::eAttributeType operator() (double /*val*/) const { return mapnik::Double; } mapnik::eAttributeType operator() (float /*val*/) const { return mapnik::Double; } mapnik::eAttributeType operator() (bool /*val*/) const { return mapnik::Boolean; } mapnik::eAttributeType operator() (std::string const& /*val*/) const { return mapnik::String; } mapnik::eAttributeType operator() (UnicodeString const& /*val*/) const { return mapnik::String; } mapnik::eAttributeType operator() (mapnik::value_null const& /*val*/) const { return mapnik::String; } }; geojson_datasource::geojson_datasource(parameters const& params) : datasource(params), type_(datasource::Vector), desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8")), file_(*params.get<std::string>("file","")), extent_(), tr_(new mapnik::transcoder(*params.get<std::string>("encoding","utf-8"))), features_(), tree_(16,1) { if (file_.empty()) throw mapnik::datasource_exception("GeoJSON Plugin: missing <file> parameter"); typedef std::istreambuf_iterator<char> base_iterator_type; #if defined (_WINDOWS) std::ifstream is(mapnik::utf8_to_utf16(file_),std::ios_base::in | std::ios_base::binary); #else std::ifstream is(file_.c_str(),std::ios_base::in | std::ios_base::binary); #endif boost::spirit::multi_pass<base_iterator_type> begin = boost::spirit::make_default_multi_pass(base_iterator_type(is)); boost::spirit::multi_pass<base_iterator_type> end = boost::spirit::make_default_multi_pass(base_iterator_type()); mapnik::context_ptr ctx = boost::make_shared<mapnik::context_type>(); mapnik::json::feature_collection_parser<boost::spirit::multi_pass<base_iterator_type> > p(ctx,*tr_); bool result = p.parse(begin,end, features_); if (!result) { throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file '" + file_ + "'"); } bool first = true; std::size_t count=0; BOOST_FOREACH (mapnik::feature_ptr f, features_) { mapnik::box2d<double> const& box = f->envelope(); if (first) { extent_ = box; first = false; mapnik::feature_kv_iterator f_itr = f->begin(); mapnik::feature_kv_iterator f_end = f->end(); for ( ;f_itr!=f_end; ++f_itr) { desc_.add_descriptor(mapnik::attribute_descriptor(boost::get<0>(*f_itr), boost::apply_visitor(attr_value_converter(),boost::get<1>(*f_itr).base()))); } } else { extent_.expand_to_include(box); } tree_.insert(box_type(point_type(box.minx(),box.miny()),point_type(box.maxx(),box.maxy())), count++); } } geojson_datasource::~geojson_datasource() { } const char * geojson_datasource::name() { return "geojson"; } boost::optional<mapnik::datasource::geometry_t> geojson_datasource::get_geometry_type() const { boost::optional<mapnik::datasource::geometry_t> result; int multi_type = 0; unsigned num_features = features_.size(); for (unsigned i = 0; i < num_features && i < 5; ++i) { mapnik::util::to_ds_type(features_[i]->paths(),result); if (result) { int type = static_cast<int>(*result); if (multi_type > 0 && multi_type != type) { result.reset(mapnik::datasource::Collection); return result; } multi_type = type; } } return result; } mapnik::datasource::datasource_t geojson_datasource::type() const { return type_; } mapnik::box2d<double> geojson_datasource::envelope() const { return extent_; } mapnik::layer_descriptor geojson_datasource::get_descriptor() const { return desc_; } mapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const { // if the query box intersects our world extent then query for features mapnik::box2d<double> const& b = q.get_bbox(); if (extent_.intersects(b)) { box_type box(point_type(b.minx(),b.miny()),point_type(b.maxx(),b.maxy())); index_array_ = tree_.find(box); return boost::make_shared<geojson_featureset>(features_, index_array_.begin(), index_array_.end()); } // otherwise return an empty featureset pointer return mapnik::featureset_ptr(); } mapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const { mapnik::box2d<double> query_bbox(pt, pt); query_bbox.pad(tol); mapnik::query q(query_bbox); std::vector<mapnik::attribute_descriptor> const& desc = desc_.get_descriptors(); std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin(); std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end(); for ( ;itr!=end;++itr) { q.add_property_name(itr->get_name()); } return features(q); } <|endoftext|>
<commit_before><commit_msg>Update screen view is reset while language is switched.<commit_after><|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "geojson_datasource.hpp" #include "geojson_featureset.hpp" #include "large_geojson_featureset.hpp" #include <fstream> #include <algorithm> // boost #include <boost/algorithm/string.hpp> #include <boost/spirit/include/qi.hpp> // mapnik #include <mapnik/boolean.hpp> #include <mapnik/unicode.hpp> #include <mapnik/utils.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_factory.hpp> #include <mapnik/feature_kv_iterator.hpp> #include <mapnik/value_types.hpp> #include <mapnik/box2d.hpp> #include <mapnik/debug.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/projection.hpp> #include <mapnik/util/variant.hpp> #include <mapnik/util/file_io.hpp> #include <mapnik/util/geometry_to_ds_type.hpp> #include <mapnik/make_unique.hpp> #include <mapnik/geometry_adapters.hpp> #include <mapnik/json/feature_collection_grammar.hpp> #include <mapnik/json/extract_bounding_box_grammar_impl.hpp> #if defined(SHAPE_MEMORY_MAPPED_FILE) #include <boost/interprocess/mapped_region.hpp> #include <mapnik/mapped_memory_cache.hpp> #endif using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(geojson_datasource) struct attr_value_converter { mapnik::eAttributeType operator() (mapnik::value_integer) const { return mapnik::Integer; } mapnik::eAttributeType operator() (double) const { return mapnik::Double; } mapnik::eAttributeType operator() (float) const { return mapnik::Double; } mapnik::eAttributeType operator() (bool) const { return mapnik::Boolean; } mapnik::eAttributeType operator() (std::string const& ) const { return mapnik::String; } mapnik::eAttributeType operator() (mapnik::value_unicode_string const&) const { return mapnik::String; } mapnik::eAttributeType operator() (mapnik::value_null const& ) const { return mapnik::String; } }; geojson_datasource::geojson_datasource(parameters const& params) : datasource(params), type_(datasource::Vector), desc_(geojson_datasource::name(), *params.get<std::string>("encoding","utf-8")), filename_(), inline_string_(), extent_(), features_(), tree_(nullptr) { boost::optional<std::string> inline_string = params.get<std::string>("inline"); if (inline_string) { inline_string_ = *inline_string; } else { boost::optional<std::string> file = params.get<std::string>("file"); if (!file) throw mapnik::datasource_exception("GeoJSON Plugin: missing <file> parameter"); boost::optional<std::string> base = params.get<std::string>("base"); if (base) filename_ = *base + "/" + *file; else filename_ = *file; } if (!inline_string_.empty()) { char const* start = inline_string_.c_str(); char const* end = start + inline_string_.size(); parse_geojson(start, end); } else { cache_features_ = *params.get<mapnik::boolean_type>("cache_features", true); #if !defined(SHAPE_MEMORY_MAPPED_FILE) mapnik::util::file file(filename_); if (!file.open()) { throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'"); } std::string file_buffer; file_buffer.resize(file.size()); std::fread(&file_buffer[0], file.size(), 1, file.get()); char const* start = file_buffer.c_str(); char const* end = start + file_buffer.length(); if (cache_features_) { parse_geojson(start, end); } else { initialise_index(start, end); } #else boost::optional<mapnik::mapped_region_ptr> mapped_region = mapnik::mapped_memory_cache::instance().find(filename_, false); if (!mapped_region) { throw std::runtime_error("could not get file mapping for "+ filename_); } char const* start = reinterpret_cast<char const*>((*mapped_region)->get_address()); char const* end = start + (*mapped_region)->get_size(); if (cache_features_) { parse_geojson(start, end); } else { initialise_index(start, end); } #endif } } namespace { using base_iterator_type = char const*; const mapnik::transcoder geojson_datasource_static_tr("utf8"); const mapnik::json::feature_collection_grammar<base_iterator_type,mapnik::feature_impl> geojson_datasource_static_fc_grammar(geojson_datasource_static_tr); const mapnik::json::feature_grammar<base_iterator_type, mapnik::feature_impl> geojson_datasource_static_feature_grammar(geojson_datasource_static_tr); const mapnik::json::extract_bounding_box_grammar<base_iterator_type> geojson_datasource_static_bbox_grammar; } template <typename Iterator> void geojson_datasource::initialise_index(Iterator start, Iterator end) { mapnik::json::boxes boxes; boost::spirit::ascii::space_type space; Iterator itr = start; if (!boost::spirit::qi::phrase_parse(itr, end, (geojson_datasource_static_bbox_grammar)(boost::phoenix::ref(boxes)) , space)) { throw mapnik::datasource_exception("GeoJSON Plugin: could not parse: '" + filename_ + "'"); } // bulk insert initialise r-tree tree_ = std::make_unique<spatial_index_type>(boxes); // calculate total extent for (auto const& item : boxes) { auto const& box = std::get<0>(item); auto const& geometry_index = std::get<1>(item); if (!extent_.valid()) { extent_ = box; // parse first feature to extract attributes schema. // NOTE: this doesn't yield correct answer for geoJSON in general, just an indication Iterator itr = start + geometry_index.first; Iterator end = itr + geometry_index.second; mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1)); boost::spirit::ascii::space_type space; if (!boost::spirit::qi::phrase_parse(itr, end, (geojson_datasource_static_feature_grammar)(boost::phoenix::ref(*feature)), space)) { throw std::runtime_error("Failed to parse geojson feature"); } for ( auto const& kv : *feature) { desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv), mapnik::util::apply_visitor(attr_value_converter(), std::get<1>(kv)))); } } else { extent_.expand_to_include(box); } } } template <typename Iterator> void geojson_datasource::parse_geojson(Iterator start, Iterator end) { boost::spirit::ascii::space_type space; mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); std::size_t start_id = 1; mapnik::json::default_feature_callback callback(features_); bool result = boost::spirit::qi::phrase_parse(start, end, (geojson_datasource_static_fc_grammar) (boost::phoenix::ref(ctx),boost::phoenix::ref(start_id), boost::phoenix::ref(callback)), space); if (!result) { if (!inline_string_.empty()) throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file from in-memory string"); else throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file '" + filename_ + "'"); } using values_container = std::vector< std::pair<box_type, std::pair<std::size_t, std::size_t>>>; values_container values; values.reserve(features_.size()); std::size_t geometry_index = 0; for (mapnik::feature_ptr const& f : features_) { mapnik::box2d<double> box = f->envelope(); if (box.valid()) { if (geometry_index == 0) { extent_ = box; for ( auto const& kv : *f) { desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv), mapnik::util::apply_visitor(attr_value_converter(), std::get<1>(kv)))); } } else { extent_.expand_to_include(box); } } values.emplace_back(box, std::make_pair(geometry_index,0)); ++geometry_index; } // packing algorithm tree_ = std::make_unique<spatial_index_type>(values); } geojson_datasource::~geojson_datasource() { } const char * geojson_datasource::name() { return "geojson"; } mapnik::datasource::datasource_t geojson_datasource::type() const { return type_; } mapnik::box2d<double> geojson_datasource::envelope() const { return extent_; } mapnik::layer_descriptor geojson_datasource::get_descriptor() const { return desc_; } boost::optional<mapnik::datasource_geometry_t> geojson_datasource::get_geometry_type() const { boost::optional<mapnik::datasource_geometry_t> result; int multi_type = 0; if (cache_features_) { unsigned num_features = features_.size(); for (unsigned i = 0; i < num_features && i < 5; ++i) { result = mapnik::util::to_ds_type(features_[i]->get_geometry()); if (result) { int type = static_cast<int>(*result); if (multi_type > 0 && multi_type != type) { result.reset(mapnik::datasource_geometry_t::Collection); return result; } multi_type = type; } } } else { mapnik::util::file file(filename_); if (!file.open()) { throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'"); } auto itr = tree_->qbegin(boost::geometry::index::intersects(extent_)); auto end = tree_->qend(); mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); for (std::size_t count = 0; itr !=end && count < 5; ++itr,++count) { geojson_datasource::item_type const& item = *itr; std::size_t file_offset = item.second.first; std::size_t size = item.second.second; std::fseek(file.get(), file_offset, SEEK_SET); std::vector<char> json; json.resize(size); std::fread(json.data(), size, 1, file.get()); using chr_iterator_type = char const*; chr_iterator_type start = json.data(); chr_iterator_type end = start + json.size(); using namespace boost::spirit; ascii::space_type space; mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1)); if (!qi::phrase_parse(start, end, (geojson_datasource_static_feature_grammar)(boost::phoenix::ref(*feature)), space)) { throw std::runtime_error("Failed to parse geojson feature"); } result = mapnik::util::to_ds_type(feature->get_geometry()); if (result) { int type = static_cast<int>(*result); if (multi_type > 0 && multi_type != type) { result.reset(mapnik::datasource_geometry_t::Collection); return result; } multi_type = type; } } } return result; } mapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const { // if the query box intersects our world extent then query for features mapnik::box2d<double> const& box = q.get_bbox(); if (extent_.intersects(box)) { geojson_featureset::array_type index_array; if (tree_) { tree_->query(boost::geometry::index::intersects(box),std::back_inserter(index_array)); if (cache_features_) { return std::make_shared<geojson_featureset>(features_, std::move(index_array)); } else { std::sort(index_array.begin(),index_array.end(), [] (item_type const& item0, item_type const& item1) { return item0.second.first < item1.second.first; }); return std::make_shared<large_geojson_featureset>(filename_, std::move(index_array)); } } } // otherwise return an empty featureset pointer return mapnik::featureset_ptr(); } mapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const { mapnik::box2d<double> query_bbox(pt, pt); query_bbox.pad(tol); mapnik::query q(query_bbox); std::vector<mapnik::attribute_descriptor> const& desc = desc_.get_descriptors(); std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin(); std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end(); for ( ;itr!=end;++itr) { q.add_property_name(itr->get_name()); } return features(q); } <commit_msg>silence boost warning in geojson_datasource<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include "geojson_datasource.hpp" #include "geojson_featureset.hpp" #include "large_geojson_featureset.hpp" #include <fstream> #include <algorithm> // boost #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wunused-local-typedef" #include <boost/algorithm/string.hpp> #include <boost/spirit/include/qi.hpp> #pragma GCC diagnostic pop // mapnik #include <mapnik/boolean.hpp> #include <mapnik/unicode.hpp> #include <mapnik/utils.hpp> #include <mapnik/feature.hpp> #include <mapnik/feature_factory.hpp> #include <mapnik/feature_kv_iterator.hpp> #include <mapnik/value_types.hpp> #include <mapnik/box2d.hpp> #include <mapnik/debug.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/projection.hpp> #include <mapnik/util/variant.hpp> #include <mapnik/util/file_io.hpp> #include <mapnik/util/geometry_to_ds_type.hpp> #include <mapnik/make_unique.hpp> #include <mapnik/geometry_adapters.hpp> #include <mapnik/json/feature_collection_grammar.hpp> #include <mapnik/json/extract_bounding_box_grammar_impl.hpp> #if defined(SHAPE_MEMORY_MAPPED_FILE) #include <boost/interprocess/mapped_region.hpp> #include <mapnik/mapped_memory_cache.hpp> #endif using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(geojson_datasource) struct attr_value_converter { mapnik::eAttributeType operator() (mapnik::value_integer) const { return mapnik::Integer; } mapnik::eAttributeType operator() (double) const { return mapnik::Double; } mapnik::eAttributeType operator() (float) const { return mapnik::Double; } mapnik::eAttributeType operator() (bool) const { return mapnik::Boolean; } mapnik::eAttributeType operator() (std::string const& ) const { return mapnik::String; } mapnik::eAttributeType operator() (mapnik::value_unicode_string const&) const { return mapnik::String; } mapnik::eAttributeType operator() (mapnik::value_null const& ) const { return mapnik::String; } }; geojson_datasource::geojson_datasource(parameters const& params) : datasource(params), type_(datasource::Vector), desc_(geojson_datasource::name(), *params.get<std::string>("encoding","utf-8")), filename_(), inline_string_(), extent_(), features_(), tree_(nullptr) { boost::optional<std::string> inline_string = params.get<std::string>("inline"); if (inline_string) { inline_string_ = *inline_string; } else { boost::optional<std::string> file = params.get<std::string>("file"); if (!file) throw mapnik::datasource_exception("GeoJSON Plugin: missing <file> parameter"); boost::optional<std::string> base = params.get<std::string>("base"); if (base) filename_ = *base + "/" + *file; else filename_ = *file; } if (!inline_string_.empty()) { char const* start = inline_string_.c_str(); char const* end = start + inline_string_.size(); parse_geojson(start, end); } else { cache_features_ = *params.get<mapnik::boolean_type>("cache_features", true); #if !defined(SHAPE_MEMORY_MAPPED_FILE) mapnik::util::file file(filename_); if (!file.open()) { throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'"); } std::string file_buffer; file_buffer.resize(file.size()); std::fread(&file_buffer[0], file.size(), 1, file.get()); char const* start = file_buffer.c_str(); char const* end = start + file_buffer.length(); if (cache_features_) { parse_geojson(start, end); } else { initialise_index(start, end); } #else boost::optional<mapnik::mapped_region_ptr> mapped_region = mapnik::mapped_memory_cache::instance().find(filename_, false); if (!mapped_region) { throw std::runtime_error("could not get file mapping for "+ filename_); } char const* start = reinterpret_cast<char const*>((*mapped_region)->get_address()); char const* end = start + (*mapped_region)->get_size(); if (cache_features_) { parse_geojson(start, end); } else { initialise_index(start, end); } #endif } } namespace { using base_iterator_type = char const*; const mapnik::transcoder geojson_datasource_static_tr("utf8"); const mapnik::json::feature_collection_grammar<base_iterator_type,mapnik::feature_impl> geojson_datasource_static_fc_grammar(geojson_datasource_static_tr); const mapnik::json::feature_grammar<base_iterator_type, mapnik::feature_impl> geojson_datasource_static_feature_grammar(geojson_datasource_static_tr); const mapnik::json::extract_bounding_box_grammar<base_iterator_type> geojson_datasource_static_bbox_grammar; } template <typename Iterator> void geojson_datasource::initialise_index(Iterator start, Iterator end) { mapnik::json::boxes boxes; boost::spirit::ascii::space_type space; Iterator itr = start; if (!boost::spirit::qi::phrase_parse(itr, end, (geojson_datasource_static_bbox_grammar)(boost::phoenix::ref(boxes)) , space)) { throw mapnik::datasource_exception("GeoJSON Plugin: could not parse: '" + filename_ + "'"); } // bulk insert initialise r-tree tree_ = std::make_unique<spatial_index_type>(boxes); // calculate total extent for (auto const& item : boxes) { auto const& box = std::get<0>(item); auto const& geometry_index = std::get<1>(item); if (!extent_.valid()) { extent_ = box; // parse first feature to extract attributes schema. // NOTE: this doesn't yield correct answer for geoJSON in general, just an indication Iterator itr = start + geometry_index.first; Iterator end = itr + geometry_index.second; mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1)); boost::spirit::ascii::space_type space; if (!boost::spirit::qi::phrase_parse(itr, end, (geojson_datasource_static_feature_grammar)(boost::phoenix::ref(*feature)), space)) { throw std::runtime_error("Failed to parse geojson feature"); } for ( auto const& kv : *feature) { desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv), mapnik::util::apply_visitor(attr_value_converter(), std::get<1>(kv)))); } } else { extent_.expand_to_include(box); } } } template <typename Iterator> void geojson_datasource::parse_geojson(Iterator start, Iterator end) { boost::spirit::ascii::space_type space; mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); std::size_t start_id = 1; mapnik::json::default_feature_callback callback(features_); bool result = boost::spirit::qi::phrase_parse(start, end, (geojson_datasource_static_fc_grammar) (boost::phoenix::ref(ctx),boost::phoenix::ref(start_id), boost::phoenix::ref(callback)), space); if (!result) { if (!inline_string_.empty()) throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file from in-memory string"); else throw mapnik::datasource_exception("geojson_datasource: Failed parse GeoJSON file '" + filename_ + "'"); } using values_container = std::vector< std::pair<box_type, std::pair<std::size_t, std::size_t>>>; values_container values; values.reserve(features_.size()); std::size_t geometry_index = 0; for (mapnik::feature_ptr const& f : features_) { mapnik::box2d<double> box = f->envelope(); if (box.valid()) { if (geometry_index == 0) { extent_ = box; for ( auto const& kv : *f) { desc_.add_descriptor(mapnik::attribute_descriptor(std::get<0>(kv), mapnik::util::apply_visitor(attr_value_converter(), std::get<1>(kv)))); } } else { extent_.expand_to_include(box); } } values.emplace_back(box, std::make_pair(geometry_index,0)); ++geometry_index; } // packing algorithm tree_ = std::make_unique<spatial_index_type>(values); } geojson_datasource::~geojson_datasource() { } const char * geojson_datasource::name() { return "geojson"; } mapnik::datasource::datasource_t geojson_datasource::type() const { return type_; } mapnik::box2d<double> geojson_datasource::envelope() const { return extent_; } mapnik::layer_descriptor geojson_datasource::get_descriptor() const { return desc_; } boost::optional<mapnik::datasource_geometry_t> geojson_datasource::get_geometry_type() const { boost::optional<mapnik::datasource_geometry_t> result; int multi_type = 0; if (cache_features_) { unsigned num_features = features_.size(); for (unsigned i = 0; i < num_features && i < 5; ++i) { result = mapnik::util::to_ds_type(features_[i]->get_geometry()); if (result) { int type = static_cast<int>(*result); if (multi_type > 0 && multi_type != type) { result.reset(mapnik::datasource_geometry_t::Collection); return result; } multi_type = type; } } } else { mapnik::util::file file(filename_); if (!file.open()) { throw mapnik::datasource_exception("GeoJSON Plugin: could not open: '" + filename_ + "'"); } auto itr = tree_->qbegin(boost::geometry::index::intersects(extent_)); auto end = tree_->qend(); mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); for (std::size_t count = 0; itr !=end && count < 5; ++itr,++count) { geojson_datasource::item_type const& item = *itr; std::size_t file_offset = item.second.first; std::size_t size = item.second.second; std::fseek(file.get(), file_offset, SEEK_SET); std::vector<char> json; json.resize(size); std::fread(json.data(), size, 1, file.get()); using chr_iterator_type = char const*; chr_iterator_type start = json.data(); chr_iterator_type end = start + json.size(); using namespace boost::spirit; ascii::space_type space; mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1)); if (!qi::phrase_parse(start, end, (geojson_datasource_static_feature_grammar)(boost::phoenix::ref(*feature)), space)) { throw std::runtime_error("Failed to parse geojson feature"); } result = mapnik::util::to_ds_type(feature->get_geometry()); if (result) { int type = static_cast<int>(*result); if (multi_type > 0 && multi_type != type) { result.reset(mapnik::datasource_geometry_t::Collection); return result; } multi_type = type; } } } return result; } mapnik::featureset_ptr geojson_datasource::features(mapnik::query const& q) const { // if the query box intersects our world extent then query for features mapnik::box2d<double> const& box = q.get_bbox(); if (extent_.intersects(box)) { geojson_featureset::array_type index_array; if (tree_) { tree_->query(boost::geometry::index::intersects(box),std::back_inserter(index_array)); if (cache_features_) { return std::make_shared<geojson_featureset>(features_, std::move(index_array)); } else { std::sort(index_array.begin(),index_array.end(), [] (item_type const& item0, item_type const& item1) { return item0.second.first < item1.second.first; }); return std::make_shared<large_geojson_featureset>(filename_, std::move(index_array)); } } } // otherwise return an empty featureset pointer return mapnik::featureset_ptr(); } mapnik::featureset_ptr geojson_datasource::features_at_point(mapnik::coord2d const& pt, double tol) const { mapnik::box2d<double> query_bbox(pt, pt); query_bbox.pad(tol); mapnik::query q(query_bbox); std::vector<mapnik::attribute_descriptor> const& desc = desc_.get_descriptors(); std::vector<mapnik::attribute_descriptor>::const_iterator itr = desc.begin(); std::vector<mapnik::attribute_descriptor>::const_iterator end = desc.end(); for ( ;itr!=end;++itr) { q.add_property_name(itr->get_name()); } return features(q); } <|endoftext|>
<commit_before>#include "nxtFlashTool.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtWidgets/QMessageBox> using namespace qReal; using namespace qReal::robots::generators; NxtFlashTool::NxtFlashTool(qReal::ErrorReporterInterface *errorReporter) : mErrorReporter(errorReporter) , mUploadState(done) { QProcessEnvironment environment(QProcessEnvironment::systemEnvironment()); environment.insert("QREALDIR", qApp->applicationDirPath()); environment.insert("QREALDIRPOSIX", qApp->applicationDirPath().remove(1,1).prepend("/cygdrive/")); environment.insert("DISPLAY", ":0.0"); mFlashProcess.setProcessEnvironment(environment); mUploadProcess.setProcessEnvironment(environment); mRunProcess.setProcessEnvironment(environment); connect(&mFlashProcess, SIGNAL(readyRead()), this, SLOT(readNxtFlashData())); connect(&mFlashProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError))); connect(&mFlashProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(nxtFlashingFinished(int, QProcess::ExitStatus))); connect(&mUploadProcess, SIGNAL(readyRead()), this, SLOT(readNxtUploadData())); connect(&mUploadProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError))); connect(&mUploadProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(nxtUploadingFinished(int, QProcess::ExitStatus))); connect(&mRunProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError))); } void NxtFlashTool::flashRobot() { #ifdef Q_OS_WIN mFlashProcess.setEnvironment(QProcess::systemEnvironment()); mFlashProcess.setWorkingDirectory(qApp->applicationDirPath() + "/nxt-tools/nexttool/"); mFlashProcess.start("cmd", QStringList() << "/c" << qApp->applicationDirPath() + "/nxt-tools/flash.bat"); #else mFlashProcess.start("sh", QStringList() << qApp->applicationDirPath() + "/nxt-tools/flash.sh"); #endif mErrorReporter->addInformation(tr("Firmware flash started. Please don't disconnect robot during the process")); } void NxtFlashTool::runProgram(QFileInfo const &fileInfo) { mSource = fileInfo; mRunProcess.setEnvironment(QProcess::systemEnvironment()); mRunProcess.setWorkingDirectory(qApp->applicationDirPath() + "/nxt-tools/"); mRunProcess.start("cmd", QStringList() << "/c" << qApp->applicationDirPath() + "/nxt-tools/nexttool/NexTTool.exe /COM=usb -run=" + QString("%1/%2_OSEK.rxe").arg(mSource.absolutePath(),mSource.baseName())); } void NxtFlashTool::error(QProcess::ProcessError error) { Q_UNUSED(error) mErrorReporter->addInformation(tr("Some error occured. Make sure you are running QReal with superuser privileges")); } void NxtFlashTool::nxtFlashingFinished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED(exitStatus) if (exitCode == 0) { mErrorReporter->addInformation(tr("Flashing process completed.")); } else if (exitCode == 127) { mErrorReporter->addError(tr("flash.sh not found. Make sure it is present in QReal installation directory")); } else if (exitCode == 139) { mErrorReporter->addError(tr("QReal requires superuser privileges to flash NXT robot")); } else if (exitCode == 0) { askToRun(); } } void NxtFlashTool::askToRun() { if (QMessageBox::question(0, tr("Do you want to run it?"), tr("The program has been uploaded.")) == QMessageBox::Ok) { runProgram(mSource); } } void NxtFlashTool::readNxtFlashData() { QStringList const output = QString(mFlashProcess.readAll()).split("\n", QString::SkipEmptyParts); qDebug() << "exit code:" << mFlashProcess.exitCode(); qDebug() << output; foreach (QString const &error, output) { if (error == "NXT not found. Is it properly plugged in via USB?") { mErrorReporter->addError(tr("NXT not found. Check USB connection and make sure the robot is ON")); } else if (error == "NXT found, but not running in reset mode.") { mErrorReporter->addError(tr("NXT is not in reset mode. Please reset your NXT manually and try again")); } else if (error == "Firmware flash complete.") { mErrorReporter->addInformation(tr("Firmware flash complete!")); } } } void NxtFlashTool::uploadProgram(QFileInfo const &fileInfo) { #ifdef Q_OS_WIN mUploadProcess.setWorkingDirectory(qApp->applicationDirPath() + "/nxt-tools/"); mUploadProcess.start("cmd", QStringList() << "/c" << qApp->applicationDirPath() + "/nxt-tools/upload.bat " + fileInfo.baseName() + " " + fileInfo.absolutePath()); #else mUploadProcess.start("sh", QStringList() << qApp->applicationDirPath() + "/nxt-tools/upload.sh"); #endif mErrorReporter->addInformation(tr("Uploading program started. Please don't disconnect robot during the process")); } void NxtFlashTool::nxtUploadingFinished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED(exitStatus) if (exitCode == 127) { // most likely wineconsole didn't start and generate files needed to proceed compilation mErrorReporter->addError(tr("Uploading failed. Make sure that X-server allows root to run GUI applications")); } else if (exitCode == 139) { mErrorReporter->addError(tr("QReal requires superuser privileges to flash NXT robot")); } } void NxtFlashTool::readNxtUploadData() { QStringList const output = QString(mUploadProcess.readAll()).split("\n", QString::SkipEmptyParts); /* each command produces its own output, so thousands of 'em. using UploadState enum to determine in which state we are (to show appropriate error if something goes wrong) */ foreach (QString const &error, output) { if (error.contains("Removing ")) { mUploadState = clean; } else if (error.contains("Compiling ")) { mUploadState = compile; } else if (error.contains("recipe for target") && error.contains("failed")) { mUploadState = compilationError; } else if (error.contains("Generating binary image file")) { mUploadState = link; } else if (error.contains("Executing NeXTTool to upload") && mUploadState != compilationError) { mUploadState = uploadStart; } else if (error.contains("_OSEK.rxe=") && mUploadState != compilationError) { mUploadState = flash; } else if (error.contains("NeXTTool is terminated")) { if (mUploadState == uploadStart) { mErrorReporter->addError(tr("Could not upload program. Make sure the robot is connected and ON")); } else if (mUploadState == flash) { mErrorReporter->addInformation(tr("Uploading completed successfully")); } else if (mUploadState == compilationError) { mErrorReporter->addError(tr("Compilation error occured. Please check your function blocks syntax. If you sure in their validness contact developers")); } mUploadState = done; } else if (error.contains("An unhandled exception occurred")) { mErrorReporter->addError(tr("QReal requires superuser privileges to upload programs on NXT robot")); break; } } } <commit_msg>little fix<commit_after>#include "nxtFlashTool.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtWidgets/QMessageBox> using namespace qReal; using namespace qReal::robots::generators; NxtFlashTool::NxtFlashTool(qReal::ErrorReporterInterface *errorReporter) : mErrorReporter(errorReporter) , mUploadState(done) { QProcessEnvironment environment(QProcessEnvironment::systemEnvironment()); environment.insert("QREALDIR", qApp->applicationDirPath()); environment.insert("QREALDIRPOSIX", qApp->applicationDirPath().remove(1,1).prepend("/cygdrive/")); environment.insert("DISPLAY", ":0.0"); mFlashProcess.setProcessEnvironment(environment); mUploadProcess.setProcessEnvironment(environment); mRunProcess.setProcessEnvironment(environment); connect(&mFlashProcess, SIGNAL(readyRead()), this, SLOT(readNxtFlashData())); connect(&mFlashProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError))); connect(&mFlashProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(nxtFlashingFinished(int, QProcess::ExitStatus))); connect(&mUploadProcess, SIGNAL(readyRead()), this, SLOT(readNxtUploadData())); connect(&mUploadProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError))); connect(&mUploadProcess, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(nxtUploadingFinished(int, QProcess::ExitStatus))); connect(&mRunProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(error(QProcess::ProcessError))); } void NxtFlashTool::flashRobot() { #ifdef Q_OS_WIN mFlashProcess.setEnvironment(QProcess::systemEnvironment()); mFlashProcess.setWorkingDirectory(qApp->applicationDirPath() + "/nxt-tools/nexttool/"); mFlashProcess.start("cmd", QStringList() << "/c" << qApp->applicationDirPath() + "/nxt-tools/flash.bat"); #else mFlashProcess.start("sh", QStringList() << qApp->applicationDirPath() + "/nxt-tools/flash.sh"); #endif mErrorReporter->addInformation(tr("Firmware flash started. Please don't disconnect robot during the process")); } void NxtFlashTool::runProgram(QFileInfo const &fileInfo) { mSource = fileInfo; mRunProcess.setEnvironment(QProcess::systemEnvironment()); mRunProcess.setWorkingDirectory(qApp->applicationDirPath() + "/nxt-tools/"); mRunProcess.start("cmd", QStringList() << "/c" << qApp->applicationDirPath() + "/nxt-tools/nexttool/NexTTool.exe /COM=usb -run=" + QString("%1_OSEK.rxe").arg(mSource.baseName())); } void NxtFlashTool::error(QProcess::ProcessError error) { Q_UNUSED(error) mErrorReporter->addInformation(tr("Some error occured. Make sure you are running QReal with superuser privileges")); } void NxtFlashTool::nxtFlashingFinished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED(exitStatus) if (exitCode == 0) { mErrorReporter->addInformation(tr("Flashing process completed.")); } else if (exitCode == 127) { mErrorReporter->addError(tr("flash.sh not found. Make sure it is present in QReal installation directory")); } else if (exitCode == 139) { mErrorReporter->addError(tr("QReal requires superuser privileges to flash NXT robot")); } else if (exitCode == 0) { askToRun(); } } void NxtFlashTool::askToRun() { if (QMessageBox::question(0, tr("Do you want to run it?"), tr("The program has been uploaded.")) == QMessageBox::Ok) { runProgram(mSource); } } void NxtFlashTool::readNxtFlashData() { QStringList const output = QString(mFlashProcess.readAll()).split("\n", QString::SkipEmptyParts); qDebug() << "exit code:" << mFlashProcess.exitCode(); qDebug() << output; foreach (QString const &error, output) { if (error == "NXT not found. Is it properly plugged in via USB?") { mErrorReporter->addError(tr("NXT not found. Check USB connection and make sure the robot is ON")); } else if (error == "NXT found, but not running in reset mode.") { mErrorReporter->addError(tr("NXT is not in reset mode. Please reset your NXT manually and try again")); } else if (error == "Firmware flash complete.") { mErrorReporter->addInformation(tr("Firmware flash complete!")); } } } void NxtFlashTool::uploadProgram(QFileInfo const &fileInfo) { #ifdef Q_OS_WIN mUploadProcess.setWorkingDirectory(qApp->applicationDirPath() + "/nxt-tools/"); mUploadProcess.start("cmd", QStringList() << "/c" << qApp->applicationDirPath() + "/nxt-tools/upload.bat " + fileInfo.baseName() + " " + fileInfo.absolutePath()); #else mUploadProcess.start("sh", QStringList() << qApp->applicationDirPath() + "/nxt-tools/upload.sh"); #endif mErrorReporter->addInformation(tr("Uploading program started. Please don't disconnect robot during the process")); } void NxtFlashTool::nxtUploadingFinished(int exitCode, QProcess::ExitStatus exitStatus) { Q_UNUSED(exitStatus) if (exitCode == 127) { // most likely wineconsole didn't start and generate files needed to proceed compilation mErrorReporter->addError(tr("Uploading failed. Make sure that X-server allows root to run GUI applications")); } else if (exitCode == 139) { mErrorReporter->addError(tr("QReal requires superuser privileges to flash NXT robot")); } } void NxtFlashTool::readNxtUploadData() { QStringList const output = QString(mUploadProcess.readAll()).split("\n", QString::SkipEmptyParts); /* each command produces its own output, so thousands of 'em. using UploadState enum to determine in which state we are (to show appropriate error if something goes wrong) */ foreach (QString const &error, output) { if (error.contains("Removing ")) { mUploadState = clean; } else if (error.contains("Compiling ")) { mUploadState = compile; } else if (error.contains("recipe for target") && error.contains("failed")) { mUploadState = compilationError; } else if (error.contains("Generating binary image file")) { mUploadState = link; } else if (error.contains("Executing NeXTTool to upload") && mUploadState != compilationError) { mUploadState = uploadStart; } else if (error.contains("_OSEK.rxe=") && mUploadState != compilationError) { mUploadState = flash; } else if (error.contains("NeXTTool is terminated")) { if (mUploadState == uploadStart) { mErrorReporter->addError(tr("Could not upload program. Make sure the robot is connected and ON")); } else if (mUploadState == flash) { mErrorReporter->addInformation(tr("Uploading completed successfully")); } else if (mUploadState == compilationError) { mErrorReporter->addError(tr("Compilation error occured. Please check your function blocks syntax. If you sure in their validness contact developers")); } mUploadState = done; } else if (error.contains("An unhandled exception occurred")) { mErrorReporter->addError(tr("QReal requires superuser privileges to upload programs on NXT robot")); break; } } } <|endoftext|>
<commit_before>#ifndef DYNAMIC_FUSION_QUATERNION_HPP #define DYNAMIC_FUSION_QUATERNION_HPP #pragma once #include <iostream> #include <kfusion/types.hpp> //Adapted from https://github.com/Poofjunior/QPose namespace kfusion{ namespace utils{ /** * \class Quaternion * \brief a templated quaternion class that also enables quick storage and * retrieval of rotations encoded as a vector3 and angle. * \details All angles are in radians. * \warning This template is intended to be instantiated with a floating point * data type. */ template <typename T> class Quaternion { public: Quaternion() : w_(1), x_(0), y_(0), z_(0) {} Quaternion(T w, T x, T y, T z) : w_(w), x_(x), y_(y), z_(z) {} /** * Encodes rotation from a normal * @param normal */ Quaternion(const Vec3f& normal) { Vec3f a(1, 0, 0); Vec3f b(0, 1, 0); Vec3f t0 = normal.cross(a); if (t0.dot(t0) < 0.001f) t0 = normal.cross(b); t0 = cv::normalize(t0); Vec3f t1 = normal.cross(t0); t1 = cv::normalize(t1); cv::Mat3f matrix; matrix.push_back(t0); matrix.push_back(t1); matrix.push_back(normal); w_ = sqrt(1.0 + matrix.at<float>(0,0) + matrix.at<float>(1,1) + matrix.at<float>(2,2)) / 2.0; // FIXME: this breaks when w_ = 0; x_ = (matrix.at<float>(2,1) - matrix.at<float>(1,2)) / (w_ * 4); y_ = (matrix.at<float>(0,2) - matrix.at<float>(2,0)) / (w_ * 4); z_ = (matrix.at<float>(1,0) - matrix.at<float>(2,1)) / (w_ * 4); normalize(); } ~Quaternion() {} /** * Quaternion Rotation Properties for straightforward usage of quaternions * to store rotations. */ /** * \fn void encodeRotation( T theta, T x, T y, T z) * \brief Store a normalized rotation in the quaternion encoded as a rotation * of theta about the vector (x,y,z). */ void encodeRotation(T theta, T x, T y, T z) { auto sin_half = sin(theta / 2); w_ = cos(theta / 2); x_ = x * sin_half; y_ = y * sin_half; z_ = z * sin_half; normalize(); } /** * \fn void encodeRotation( T theta, T x, T y, T z) * \brief Store a normalized rotation in the quaternion encoded as a rotation * of theta about the vector (x,y,z). */ void getRodrigues(T& x, T& y, T& z) { if(w_ == 1) { x = y = z = 0; return; } T half_theta = acos(w_); T k = sin(half_theta) * tan(half_theta); x = x_ / k; y = y_ / k; z = z_ / k; } /** * \fn void rotate( T& x, T& y, T& z) * \brief rotate a vector3 (x,y,z) by the angle theta about the axis * (U_x, U_y, U_z) stored in the quaternion. */ void rotate(T& x, T& y, T& z) { Quaternion<T> q = (*this); Quaternion<T> qStar = (*this).conjugate(); Quaternion<T> rotatedVal = q * Quaternion(0, x, y, z) * qStar; x = rotatedVal.x_; y = rotatedVal.y_; z = rotatedVal.z_; } /** /** * \fn void rotate( T& x, T& y, T& z) * \brief rotate a vector3 (x,y,z) by the angle theta about the axis * (U_x, U_y, U_z) stored in the quaternion. */ void rotate(Vec3f& v) const { auto rot= *this; rot.normalize(); Vec3f q_vec(rot.x_, rot.y_, rot.z_); v += (q_vec*2.f).cross( q_vec.cross(v) + v*rot.w_ ); } /** * Quaternion Mathematical Properties * implemented below **/ Quaternion operator+(const Quaternion& other) { return Quaternion( (w_ + other.w_), (x_ + other.x_), (y_ + other.y_), (z_ + other.z_)); } Quaternion operator-(const Quaternion& other) { return Quaternion((w_ - other.w_), (x_ - other.x_), (y_ - other.y_), (z_ - other.z_)); } Quaternion operator-() { return Quaternion(-w_, -x_, -y_, -z_); } bool operator==(const Quaternion& other) const { return (w_ == other.w_) && (x_ == other.x_) && (y_ == other.y_) && (z_ == other.z_); } /** * \fn template <typename U> friend Quaternion operator*(const U scalar, * const Quaternion& q) * \brief implements scalar multiplication for arbitrary scalar types. */ template <typename U> friend Quaternion operator*(const U scalar, const Quaternion& other) { return Quaternion<T>((scalar * other.w_), (scalar * other.x_), (scalar * other.y_), (scalar * other.z_)); } template <typename U> friend Quaternion operator/(const Quaternion& q, const U scalar) { return (1 / scalar) * q; } /// Quaternion Product Quaternion operator*(const Quaternion& other) { return Quaternion( ((w_*other.w_) - (x_*other.x_) - (y_*other.y_) - (z_*other.z_)), ((w_*other.x_) + (x_*other.w_) + (y_*other.z_) - (z_*other.y_)), ((w_*other.y_) - (x_*other.z_) + (y_*other.w_) + (z_*other.x_)), ((w_*other.z_) + (x_*other.y_) - (y_*other.x_) + (z_*other.w_)) ); } /** * \fn static T dotProduct(Quaternion q1, Quaternion q2) * \brief returns the dot product of two quaternions. */ T dotProduct(Quaternion other) { return 0.5 * ((conjugate() * other) + (*this) * other.conjugate()).w_; } /// Conjugate Quaternion conjugate() const { return Quaternion<T>(w_, -x_, -y_, -z_); } T norm() { return sqrt((w_ * w_) + (x_ * x_) + (y_ * y_) + (z_ * z_)); } /** * \fn void normalize() * \brief normalizes the quaternion to magnitude 1 */ void normalize() { // should never happen unless the Quaternion<T> wasn't initialized // correctly. T theNorm = norm(); assert(theNorm > 0); (*this) = (1.0/theNorm) * (*this); } /** * \fn template <typename U> friend std::ostream& operator << * (std::ostream& os, const Quaternion<U>& q); * \brief a templated friend function for printing quaternions. * \details T cannot be used as dummy parameter since it would be shared by * the class, and this function is not a member function. */ template <typename U> friend std::ostream& operator << (std::ostream& os, const Quaternion<U>& q) { os << "(" << q.w_ << ", " << q.x_ << ", " << q.y_ << ", " << q.z_ << ")"; return os; } //TODO: shouldn't have Vec3f but rather Vec3<T>. Not sure how to determine this later T w_; T x_; T y_; T z_; }; } } #endif // DYNAMIC_FUSION_QUATERNION_HPP<commit_msg>Added check to make sure no division by 0 is performed<commit_after>#ifndef DYNAMIC_FUSION_QUATERNION_HPP #define DYNAMIC_FUSION_QUATERNION_HPP #pragma once #include <iostream> #include <kfusion/types.hpp> //Adapted from https://github.com/Poofjunior/QPose namespace kfusion{ namespace utils{ /** * \class Quaternion * \brief a templated quaternion class that also enables quick storage and * retrieval of rotations encoded as a vector3 and angle. * \details All angles are in radians. * \warning This template is intended to be instantiated with a floating point * data type. */ template <typename T> class Quaternion { public: Quaternion() : w_(1), x_(0), y_(0), z_(0) {} Quaternion(T w, T x, T y, T z) : w_(w), x_(x), y_(y), z_(z) {} /** * Encodes rotation from a normal * @param normal */ Quaternion(const Vec3f& normal) { Vec3f a(1, 0, 0); Vec3f b(0, 1, 0); Vec3f t0 = normal.cross(a); if (t0.dot(t0) < 0.001f) t0 = normal.cross(b); t0 = cv::normalize(t0); Vec3f t1 = normal.cross(t0); t1 = cv::normalize(t1); cv::Mat3f matrix; matrix.push_back(t0); matrix.push_back(t1); matrix.push_back(normal); w_ = sqrt(1.0 + matrix.at<float>(0,0) + matrix.at<float>(1,1) + matrix.at<float>(2,2)) / 2.0; // FIXME: this breaks when w_ = 0; x_ = (matrix.at<float>(2,1) - matrix.at<float>(1,2)) / (w_ * 4); y_ = (matrix.at<float>(0,2) - matrix.at<float>(2,0)) / (w_ * 4); z_ = (matrix.at<float>(1,0) - matrix.at<float>(2,1)) / (w_ * 4); normalize(); } ~Quaternion() {} /** * Quaternion Rotation Properties for straightforward usage of quaternions * to store rotations. */ /** * \fn void encodeRotation( T theta, T x, T y, T z) * \brief Store a normalized rotation in the quaternion encoded as a rotation * of theta about the vector (x,y,z). */ void encodeRotation(T theta, T x, T y, T z) { auto sin_half = sin(theta / 2); w_ = cos(theta / 2); x_ = x * sin_half; y_ = y * sin_half; z_ = z * sin_half; normalize(); } /** * \fn void encodeRotation( T theta, T x, T y, T z) * \brief Store a normalized rotation in the quaternion encoded as a rotation * of theta about the vector (x,y,z). */ void getRodrigues(T& x, T& y, T& z) { if(w_ == 1) { x = y = z = 0; return; } T half_theta = acos(w_); T k = sin(half_theta) * tan(half_theta); x = x_ / k; y = y_ / k; z = z_ / k; } /** * \fn void rotate( T& x, T& y, T& z) * \brief rotate a vector3 (x,y,z) by the angle theta about the axis * (U_x, U_y, U_z) stored in the quaternion. */ void rotate(T& x, T& y, T& z) { Quaternion<T> q = (*this); Quaternion<T> qStar = (*this).conjugate(); Quaternion<T> rotatedVal = q * Quaternion(0, x, y, z) * qStar; x = rotatedVal.x_; y = rotatedVal.y_; z = rotatedVal.z_; } /** /** * \fn void rotate( T& x, T& y, T& z) * \brief rotate a vector3 (x,y,z) by the angle theta about the axis * (U_x, U_y, U_z) stored in the quaternion. */ void rotate(Vec3f& v) const { auto rot= *this; rot.normalize(); Vec3f q_vec(rot.x_, rot.y_, rot.z_); v += (q_vec*2.f).cross( q_vec.cross(v) + v*rot.w_ ); } /** * Quaternion Mathematical Properties * implemented below **/ Quaternion operator+(const Quaternion& other) { return Quaternion( (w_ + other.w_), (x_ + other.x_), (y_ + other.y_), (z_ + other.z_)); } Quaternion operator-(const Quaternion& other) { return Quaternion((w_ - other.w_), (x_ - other.x_), (y_ - other.y_), (z_ - other.z_)); } Quaternion operator-() { return Quaternion(-w_, -x_, -y_, -z_); } bool operator==(const Quaternion& other) const { return (w_ == other.w_) && (x_ == other.x_) && (y_ == other.y_) && (z_ == other.z_); } /** * \fn template <typename U> friend Quaternion operator*(const U scalar, * const Quaternion& q) * \brief implements scalar multiplication for arbitrary scalar types. */ template <typename U> friend Quaternion operator*(const U scalar, const Quaternion& other) { return Quaternion<T>((scalar * other.w_), (scalar * other.x_), (scalar * other.y_), (scalar * other.z_)); } template <typename U> friend Quaternion operator/(const Quaternion& q, const U scalar) { return (1 / scalar) * q; } /// Quaternion Product Quaternion operator*(const Quaternion& other) { return Quaternion( ((w_*other.w_) - (x_*other.x_) - (y_*other.y_) - (z_*other.z_)), ((w_*other.x_) + (x_*other.w_) + (y_*other.z_) - (z_*other.y_)), ((w_*other.y_) - (x_*other.z_) + (y_*other.w_) + (z_*other.x_)), ((w_*other.z_) + (x_*other.y_) - (y_*other.x_) + (z_*other.w_)) ); } /** * \fn static T dotProduct(Quaternion q1, Quaternion q2) * \brief returns the dot product of two quaternions. */ T dotProduct(Quaternion other) { return 0.5 * ((conjugate() * other) + (*this) * other.conjugate()).w_; } /// Conjugate Quaternion conjugate() const { return Quaternion<T>(w_, -x_, -y_, -z_); } T norm() { return sqrt((w_ * w_) + (x_ * x_) + (y_ * y_) + (z_ * z_)); } /** * \fn void normalize() * \brief normalizes the quaternion to magnitude 1 */ void normalize() { // should never happen unless the Quaternion<T> wasn't initialized // correctly. assert( !((w_ == 0) && (x_ == 0) && (y_ == 0) && (z_ == 0))); T theNorm = norm(); assert(theNorm > 0); (*this) = (1.0/theNorm) * (*this); } /** * \fn template <typename U> friend std::ostream& operator << * (std::ostream& os, const Quaternion<U>& q); * \brief a templated friend function for printing quaternions. * \details T cannot be used as dummy parameter since it would be shared by * the class, and this function is not a member function. */ template <typename U> friend std::ostream& operator << (std::ostream& os, const Quaternion<U>& q) { os << "(" << q.w_ << ", " << q.x_ << ", " << q.y_ << ", " << q.z_ << ")"; return os; } //TODO: shouldn't have Vec3f but rather Vec3<T>. Not sure how to determine this later T w_; T x_; T y_; T z_; }; } } #endif // DYNAMIC_FUSION_QUATERNION_HPP<|endoftext|>
<commit_before>/* This file is part of the kolab resource - the implementation of the Kolab storage format. See www.kolab.org for documentation on this. Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "note.h" #include <libkcal/journal.h> using namespace Kolab; KCal::Journal* Note::xmlToJournal( const QString& xml ) { Note note; note.load( xml ); KCal::Journal* journal = new KCal::Journal(); note.saveTo( journal ); return journal; } QString Note::journalToXML( KCal::Journal* journal ) { Note note( journal ); return note.saveXML(); } Note::Note( KCal::Journal* journal ) { if ( journal ) setFields( journal ); } Note::~Note() { } void Note::setSummary( const QString& summary ) { mSummary = summary; } QString Note::summary() const { return mSummary; } void Note::setBackgroundColor( const QColor& bgColor ) { mBackgroundColor = bgColor; } QColor Note::backgroundColor() const { return mBackgroundColor; } void Note::setForegroundColor( const QColor& fgColor ) { mForegroundColor = fgColor; } QColor Note::foregroundColor() const { return mForegroundColor; } bool Note::loadAttribute( QDomElement& element ) { QString tagName = element.tagName(); if ( tagName == "summary" ) setSummary( element.text() ); else if ( tagName == "foreground-color" ) setForegroundColor( stringToColor( element.text() ) ); else if ( tagName == "background-color" ) setBackgroundColor( stringToColor( element.text() ) ); else return KolabBase::loadAttribute( element ); // We handled this return true; } bool Note::saveAttributes( QDomElement& element ) const { // Save the base class elements KolabBase::saveAttributes( element ); // Save the elements #if 0 QDomComment c = element.ownerDocument().createComment( "Note specific attributes" ); element.appendChild( c ); #endif writeString( element, "summary", summary() ); writeString( element, "foreground-color", colorToString( foregroundColor() ) ); writeString( element, "background-color", colorToString( backgroundColor() ) ); return true; } bool Note::loadXML( const QDomDocument& document ) { QDomElement top = document.documentElement(); if ( top.tagName() != "note" ) { qWarning( "XML error: Top tag was %s instead of the expected Note", top.tagName().ascii() ); return false; } for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) { if ( n.isComment() ) continue; if ( n.isElement() ) { QDomElement e = n.toElement(); if ( !loadAttribute( e ) ) // TODO: Unhandled tag - save for later storage qDebug( "Warning: Unhandled tag %s", e.tagName().ascii() ); } else qDebug( "Node is not a comment or an element???" ); } return true; } QString Note::saveXML() const { QDomDocument document = domTree(); QDomElement element = document.createElement( "note" ); element.setAttribute( "version", "1.0" ); saveAttributes( element ); document.appendChild( element ); return document.toString(); } void Note::setFields( const KCal::Journal* journal ) { KolabBase::setFields( journal ); // TODO: background and foreground setSummary( journal->summary() ); } void Note::saveTo( KCal::Journal* journal ) { KolabBase::saveTo( journal ); // TODO: background and foreground journal->setSummary( summary() ); } <commit_msg>Fix error message to show the right lowercase tag<commit_after>/* This file is part of the kolab resource - the implementation of the Kolab storage format. See www.kolab.org for documentation on this. Copyright (c) 2004 Bo Thorsen <bo@klaralvdalens-datakonsult.se> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "note.h" #include <libkcal/journal.h> using namespace Kolab; KCal::Journal* Note::xmlToJournal( const QString& xml ) { Note note; note.load( xml ); KCal::Journal* journal = new KCal::Journal(); note.saveTo( journal ); return journal; } QString Note::journalToXML( KCal::Journal* journal ) { Note note( journal ); return note.saveXML(); } Note::Note( KCal::Journal* journal ) { if ( journal ) setFields( journal ); } Note::~Note() { } void Note::setSummary( const QString& summary ) { mSummary = summary; } QString Note::summary() const { return mSummary; } void Note::setBackgroundColor( const QColor& bgColor ) { mBackgroundColor = bgColor; } QColor Note::backgroundColor() const { return mBackgroundColor; } void Note::setForegroundColor( const QColor& fgColor ) { mForegroundColor = fgColor; } QColor Note::foregroundColor() const { return mForegroundColor; } bool Note::loadAttribute( QDomElement& element ) { QString tagName = element.tagName(); if ( tagName == "summary" ) setSummary( element.text() ); else if ( tagName == "foreground-color" ) setForegroundColor( stringToColor( element.text() ) ); else if ( tagName == "background-color" ) setBackgroundColor( stringToColor( element.text() ) ); else return KolabBase::loadAttribute( element ); // We handled this return true; } bool Note::saveAttributes( QDomElement& element ) const { // Save the base class elements KolabBase::saveAttributes( element ); // Save the elements #if 0 QDomComment c = element.ownerDocument().createComment( "Note specific attributes" ); element.appendChild( c ); #endif writeString( element, "summary", summary() ); writeString( element, "foreground-color", colorToString( foregroundColor() ) ); writeString( element, "background-color", colorToString( backgroundColor() ) ); return true; } bool Note::loadXML( const QDomDocument& document ) { QDomElement top = document.documentElement(); if ( top.tagName() != "note" ) { qWarning( "XML error: Top tag was %s instead of the expected note", top.tagName().ascii() ); return false; } for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) { if ( n.isComment() ) continue; if ( n.isElement() ) { QDomElement e = n.toElement(); if ( !loadAttribute( e ) ) // TODO: Unhandled tag - save for later storage qDebug( "Warning: Unhandled tag %s", e.tagName().ascii() ); } else qDebug( "Node is not a comment or an element???" ); } return true; } QString Note::saveXML() const { QDomDocument document = domTree(); QDomElement element = document.createElement( "note" ); element.setAttribute( "version", "1.0" ); saveAttributes( element ); document.appendChild( element ); return document.toString(); } void Note::setFields( const KCal::Journal* journal ) { KolabBase::setFields( journal ); // TODO: background and foreground setSummary( journal->summary() ); } void Note::saveTo( KCal::Journal* journal ) { KolabBase::saveTo( journal ); // TODO: background and foreground journal->setSummary( summary() ); } <|endoftext|>
<commit_before>/* This file is part of the kolab resource - the implementation of the Kolab storage format. See www.kolab.org for documentation on this. Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "note.h" #include <libkcal/journal.h> #include <knotes/version.h> #include <kdebug.h> using namespace Kolab; KCal::Journal* Note::xmlToJournal( const QString& xml ) { Note note; note.load( xml ); KCal::Journal* journal = new KCal::Journal(); note.saveTo( journal ); return journal; } QString Note::journalToXML( KCal::Journal* journal ) { Note note( journal ); return note.saveXML(); } Note::Note( KCal::Journal* journal ) : mRichText( false ) { if ( journal ) setFields( journal ); } Note::~Note() { } void Note::setSummary( const QString& summary ) { mSummary = summary; } QString Note::summary() const { return mSummary; } void Note::setBackgroundColor( const QColor& bgColor ) { mBackgroundColor = bgColor; } QColor Note::backgroundColor() const { return mBackgroundColor; } void Note::setForegroundColor( const QColor& fgColor ) { mForegroundColor = fgColor; } QColor Note::foregroundColor() const { return mForegroundColor; } void Note::setRichText( bool richText ) { mRichText = richText; } bool Note::richText() const { return mRichText; } bool Note::loadAttribute( QDomElement& element ) { QString tagName = element.tagName(); if ( tagName == "summary" ) setSummary( element.text() ); else if ( tagName == "foreground-color" ) setForegroundColor( stringToColor( element.text() ) ); else if ( tagName == "background-color" ) setBackgroundColor( stringToColor( element.text() ) ); else if ( tagName == "knotes-richtext" ) mRichText = ( element.text() == "true" ); else return KolabBase::loadAttribute( element ); // We handled this return true; } bool Note::saveAttributes( QDomElement& element ) const { // Save the base class elements KolabBase::saveAttributes( element ); // Save the elements #if 0 QDomComment c = element.ownerDocument().createComment( "Note specific attributes" ); element.appendChild( c ); #endif writeString( element, "summary", summary() ); writeString( element, "foreground-color", colorToString( foregroundColor() ) ); writeString( element, "background-color", colorToString( backgroundColor() ) ); writeString( element, "knotes-richtext", mRichText ? "true" : "false" ); return true; } bool Note::loadXML( const QDomDocument& document ) { QDomElement top = document.documentElement(); if ( top.tagName() != "note" ) { qWarning( "XML error: Top tag was %s instead of the expected note", top.tagName().ascii() ); return false; } for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) { if ( n.isComment() ) continue; if ( n.isElement() ) { QDomElement e = n.toElement(); if ( !loadAttribute( e ) ) // TODO: Unhandled tag - save for later storage kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl; } else kdDebug() << "Node is not a comment or an element???" << endl; } return true; } QString Note::saveXML() const { QDomDocument document = domTree(); QDomElement element = document.createElement( "note" ); element.setAttribute( "version", "1.0" ); saveAttributes( element ); document.appendChild( element ); return document.toString(); } void Note::setFields( const KCal::Journal* journal ) { KolabBase::setFields( journal ); // TODO: background and foreground setSummary( journal->summary() ); setBackgroundColor( journal->customProperty( "KNotes", "BgColor" ) ); setForegroundColor( journal->customProperty( "KNotes", "FgColor" ) ); setRichText( journal->customProperty( "KNotes", "RichText" ) == "true" ); } void Note::saveTo( KCal::Journal* journal ) { KolabBase::saveTo( journal ); // TODO: background and foreground journal->setSummary( summary() ); journal->setCustomProperty( "KNotes", "FgColor", colorToString( foregroundColor() ) ); journal->setCustomProperty( "KNotes", "BgColor", colorToString( backgroundColor() ) ); journal->setCustomProperty( "KNotes", "RichText", richText() ? "true" : "false" ); } QString Note::productID() const { return QString( "KNotes %1, Kolab resource" ).arg( KNOTES_VERSION ); } <commit_msg>I hope that it fixed kolab/issue3119 colorToString return #000000 even if color is invalid => it's alway black.<commit_after>/* This file is part of the kolab resource - the implementation of the Kolab storage format. See www.kolab.org for documentation on this. Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "note.h" #include <libkcal/journal.h> #include <knotes/version.h> #include <kdebug.h> using namespace Kolab; KCal::Journal* Note::xmlToJournal( const QString& xml ) { Note note; note.load( xml ); KCal::Journal* journal = new KCal::Journal(); note.saveTo( journal ); return journal; } QString Note::journalToXML( KCal::Journal* journal ) { Note note( journal ); return note.saveXML(); } Note::Note( KCal::Journal* journal ) : mRichText( false ) { if ( journal ) setFields( journal ); } Note::~Note() { } void Note::setSummary( const QString& summary ) { mSummary = summary; } QString Note::summary() const { return mSummary; } void Note::setBackgroundColor( const QColor& bgColor ) { mBackgroundColor = bgColor; } QColor Note::backgroundColor() const { return mBackgroundColor; } void Note::setForegroundColor( const QColor& fgColor ) { mForegroundColor = fgColor; } QColor Note::foregroundColor() const { return mForegroundColor; } void Note::setRichText( bool richText ) { mRichText = richText; } bool Note::richText() const { return mRichText; } bool Note::loadAttribute( QDomElement& element ) { QString tagName = element.tagName(); if ( tagName == "summary" ) setSummary( element.text() ); else if ( tagName == "foreground-color" ) setForegroundColor( stringToColor( element.text() ) ); else if ( tagName == "background-color" ) setBackgroundColor( stringToColor( element.text() ) ); else if ( tagName == "knotes-richtext" ) mRichText = ( element.text() == "true" ); else return KolabBase::loadAttribute( element ); // We handled this return true; } bool Note::saveAttributes( QDomElement& element ) const { // Save the base class elements KolabBase::saveAttributes( element ); // Save the elements #if 0 QDomComment c = element.ownerDocument().createComment( "Note specific attributes" ); element.appendChild( c ); #endif writeString( element, "summary", summary() ); if ( foregroundColor().isValid() ) writeString( element, "foreground-color", colorToString( foregroundColor() ) ); if ( backgroundColor().isValid() ) writeString( element, "background-color", colorToString( backgroundColor() ) ); writeString( element, "knotes-richtext", mRichText ? "true" : "false" ); return true; } bool Note::loadXML( const QDomDocument& document ) { QDomElement top = document.documentElement(); if ( top.tagName() != "note" ) { qWarning( "XML error: Top tag was %s instead of the expected note", top.tagName().ascii() ); return false; } for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) { if ( n.isComment() ) continue; if ( n.isElement() ) { QDomElement e = n.toElement(); if ( !loadAttribute( e ) ) // TODO: Unhandled tag - save for later storage kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl; } else kdDebug() << "Node is not a comment or an element???" << endl; } return true; } QString Note::saveXML() const { QDomDocument document = domTree(); QDomElement element = document.createElement( "note" ); element.setAttribute( "version", "1.0" ); saveAttributes( element ); document.appendChild( element ); return document.toString(); } void Note::setFields( const KCal::Journal* journal ) { KolabBase::setFields( journal ); // TODO: background and foreground setSummary( journal->summary() ); setBackgroundColor( journal->customProperty( "KNotes", "BgColor" ) ); setForegroundColor( journal->customProperty( "KNotes", "FgColor" ) ); setRichText( journal->customProperty( "KNotes", "RichText" ) == "true" ); } void Note::saveTo( KCal::Journal* journal ) { KolabBase::saveTo( journal ); // TODO: background and foreground journal->setSummary( summary() ); if ( foregroundColor().isValid() ) journal->setCustomProperty( "KNotes", "FgColor", colorToString( foregroundColor() ) ); if ( backgroundColor().isValid() ) journal->setCustomProperty( "KNotes", "BgColor", colorToString( backgroundColor() ) ); journal->setCustomProperty( "KNotes", "RichText", richText() ? "true" : "false" ); } QString Note::productID() const { return QString( "KNotes %1, Kolab resource" ).arg( KNOTES_VERSION ); } <|endoftext|>
<commit_before>#include "chainerx/cuda/memory_pool.h" #include <gtest/gtest.h> #include "chainerx/error.h" namespace chainerx { namespace cuda { TEST(MemoryPoolTest, Malloc) { MemoryPool memory_pool{0}; void* ptr1 = memory_pool.Malloc(1); void* ptr2 = memory_pool.Malloc(1); EXPECT_NE(ptr1, ptr2); memory_pool.Free(ptr2); void* ptr3 = memory_pool.Malloc(1); EXPECT_EQ(ptr2, ptr3); memory_pool.Free(ptr3); memory_pool.Free(ptr1); } TEST(MemoryPoolTest, AllocationUnitSize) { MemoryPool memory_pool{0}; void* ptr1 = memory_pool.Malloc(100); memory_pool.Free(ptr1); void* ptr2 = memory_pool.Malloc(100 + kAllocationUnitSize); EXPECT_NE(ptr1, ptr2); memory_pool.Free(ptr2); } TEST(MemoryPoolTest, ZeroByte) { MemoryPool memory_pool{0}; void* ptr = memory_pool.Malloc(0); EXPECT_EQ(nullptr, ptr); memory_pool.Free(ptr); // no throw } TEST(MemoryPoolTest, DoubleFree) { MemoryPool memory_pool{0}; void* ptr = memory_pool.Malloc(1); memory_pool.Free(ptr); EXPECT_THROW(memory_pool.Free(ptr), ChainerxError); } TEST(MemoryPoolTest, FreeForeignPointer) { MemoryPool memory_pool{0}; void* ptr = &memory_pool; EXPECT_THROW(memory_pool.Free(ptr), ChainerxError); } } // namespace cuda } // namespace chainerx <commit_msg>Add tests for pinned memory pool<commit_after>#include "chainerx/cuda/memory_pool.h" #include <gtest/gtest.h> #include "chainerx/error.h" namespace chainerx { namespace cuda { TEST(MemoryPoolTest, Malloc) { MemoryPool memory_pool{0}; void* ptr1 = memory_pool.Malloc(1); void* ptr2 = memory_pool.Malloc(1); EXPECT_NE(ptr1, ptr2); memory_pool.Free(ptr2); void* ptr3 = memory_pool.Malloc(1); EXPECT_EQ(ptr2, ptr3); memory_pool.Free(ptr3); memory_pool.Free(ptr1); } TEST(MemoryPoolTest, AllocationUnitSize) { MemoryPool memory_pool{0}; void* ptr1 = memory_pool.Malloc(100); memory_pool.Free(ptr1); void* ptr2 = memory_pool.Malloc(100 + kAllocationUnitSize); EXPECT_NE(ptr1, ptr2); memory_pool.Free(ptr2); } TEST(MemoryPoolTest, ZeroByte) { MemoryPool memory_pool{0}; void* ptr = memory_pool.Malloc(0); EXPECT_EQ(nullptr, ptr); memory_pool.Free(ptr); // no throw } TEST(MemoryPoolTest, DoubleFree) { MemoryPool memory_pool{0}; void* ptr = memory_pool.Malloc(1); memory_pool.Free(ptr); EXPECT_THROW(memory_pool.Free(ptr), ChainerxError); } TEST(MemoryPoolTest, FreeForeignPointer) { MemoryPool memory_pool{0}; void* ptr = &memory_pool; EXPECT_THROW(memory_pool.Free(ptr), ChainerxError); } TEST(PinnedMemoryPoolTest, Malloc) { PinnedMemoryPool pinned_memory_pool{0}; void* ptr1 = pinned_memory_pool.Malloc(1); void* ptr2 = pinned_memory_pool.Malloc(1); EXPECT_NE(ptr1, ptr2); pinned_memory_pool.Free(ptr2); void* ptr3 = pinned_memory_pool.Malloc(1); EXPECT_EQ(ptr2, ptr3); pinned_memory_pool.Free(ptr3); pinned_memory_pool.Free(ptr1); } TEST(PinnedMemoryPoolTest, AllocationUnitSize) { PinnedMemoryPool pinned_memory_pool{0}; void* ptr1 = pinned_memory_pool.Malloc(100); pinned_memory_pool.Free(ptr1); void* ptr2 = pinned_memory_pool.Malloc(100 + kAllocationUnitSize); EXPECT_NE(ptr1, ptr2); pinned_memory_pool.Free(ptr2); } TEST(PinnedMemoryPoolTest, ZeroByte) { PinnedMemoryPool pinned_memory_pool{0}; void* ptr = pinned_memory_pool.Malloc(0); EXPECT_EQ(nullptr, ptr); pinned_memory_pool.Free(ptr); // no throw } TEST(PinnedMemoryPoolTest, DoubleFree) { PinnedMemoryPool pinned_memory_pool{0}; void* ptr = pinned_memory_pool.Malloc(1); pinned_memory_pool.Free(ptr); EXPECT_THROW(pinned_memory_pool.Free(ptr), ChainerxError); } TEST(PinnedMemoryPoolTest, FreeForeignPointer) { PinnedMemoryPool pinned_memory_pool{0}; void* ptr = &pinned_memory_pool; EXPECT_THROW(pinned_memory_pool.Free(ptr), ChainerxError); } } // namespace cuda } // namespace chainerx <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: salfontutils.hxx,v $ * * $Revision: 1.3 $ * last change: $Author: bmahbod $ $Date: 2001-03-26 21:53:16 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source 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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2001 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // ======================================================================= // ======================================================================= #ifndef _SV_SALFONTUTILS_HXX #define _SV_SALFONTUTILS_HXX #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_OUTFONT_HXX #include <outfont.hxx> #endif // ======================================================================= // ======================================================================= static const char *kFontWeightThin1 = "Thin"; static const char *kFontWeightThin2 = "thin"; static const char *kFontWeightLight1 = "Light"; static const char *kFontWeightLight2 = "light"; static const char *kFontWeightBold1 = "Bold"; static const char *kFontWeightBold2 = "bold"; static const char *kFontWeightUltra1 = "Ultra"; static const char *kFontWeightUltra2 = "ultra"; static const char *kFontWeightSemi1 = "Semi"; static const char *kFontWeightSemi2 = "semi"; static const char *kFontWeightNormal1 = "Normal"; static const char *kFontWeightNormal2 = "normal"; static const char *kFontWeightMedium1 = "Medium"; static const char *kFontWeightMedium2 = "medium"; static const char *kFontWeightBlack1 = "Black"; static const char *kFontWeightBlack2 = "black"; static const char *kFontWeightRoman1 = "Roman"; static const char *kFontWeightRoman2 = "roman"; static const char *kFontWeightRegular1 = "Regular"; static const char *kFontWeightRegular2 = "regular"; // ======================================================================= // ======================================================================= DECLARE_LIST( FontList, ImplFontData* ); // ======================================================================= // ======================================================================= FontList *GetMacFontList(); // ======================================================================= // ======================================================================= #endif // _SV_SALFONTUTILS_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.984); FILE MERGED 2005/09/05 14:43:33 rt 1.3.984.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salfontutils.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 10:33:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // ======================================================================= // ======================================================================= #ifndef _SV_SALFONTUTILS_HXX #define _SV_SALFONTUTILS_HXX #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_OUTFONT_HXX #include <outfont.hxx> #endif // ======================================================================= // ======================================================================= static const char *kFontWeightThin1 = "Thin"; static const char *kFontWeightThin2 = "thin"; static const char *kFontWeightLight1 = "Light"; static const char *kFontWeightLight2 = "light"; static const char *kFontWeightBold1 = "Bold"; static const char *kFontWeightBold2 = "bold"; static const char *kFontWeightUltra1 = "Ultra"; static const char *kFontWeightUltra2 = "ultra"; static const char *kFontWeightSemi1 = "Semi"; static const char *kFontWeightSemi2 = "semi"; static const char *kFontWeightNormal1 = "Normal"; static const char *kFontWeightNormal2 = "normal"; static const char *kFontWeightMedium1 = "Medium"; static const char *kFontWeightMedium2 = "medium"; static const char *kFontWeightBlack1 = "Black"; static const char *kFontWeightBlack2 = "black"; static const char *kFontWeightRoman1 = "Roman"; static const char *kFontWeightRoman2 = "roman"; static const char *kFontWeightRegular1 = "Regular"; static const char *kFontWeightRegular2 = "regular"; // ======================================================================= // ======================================================================= DECLARE_LIST( FontList, ImplFontData* ); // ======================================================================= // ======================================================================= FontList *GetMacFontList(); // ======================================================================= // ======================================================================= #endif // _SV_SALFONTUTILS_HXX <|endoftext|>
<commit_before><commit_msg>coverity#735656 Division or modulo by zero<commit_after><|endoftext|>
<commit_before>// Recursive function that has one parameter n of type int and that returns // the nth Fibonacci number: // F0 = 1, F1 = 1, F2 = 2, F3 = 3, F4 = 5 // F(i+2) = F(i) + F(i+1) for i = 0, 1, 2, ... #include <iostream> #include <cstdlib> #include <assert.h> using std::cout; using std::cin; using std::endl; int fibonacci(int n); void checkFibonacci(); int main() { checkFibonacci(); for (int n = 0; n <= 11; n++) { cout << "The fibonacci of " << n << " is " << fibonacci(n) << endl; } return 0; } int fibonacci(int n) { if (n < 0) { cout << "Invalid parameter for the fibonacci function.\n"; exit(1); } else if (n == 0 || n == 1) { return 1; } else { return (fibonacci(n-2) + fibonacci(n-1)); } } void checkFibonacci() { // According to wikipedia: assert(fibonacci(0) == 1); assert(fibonacci(1) == 1); assert(fibonacci(2) == 2); assert(fibonacci(3) == 3); assert(fibonacci(4) == 5); assert(fibonacci(5) == 8); assert(fibonacci(6) == 13); assert(fibonacci(7) == 21); assert(fibonacci(8) == 34); assert(fibonacci(9) == 55); assert(fibonacci(10) == 89); assert(fibonacci(11) == 144); } <commit_msg>Cleaning up in the recursion folder.<commit_after>/* Recursive function that has one parameter n of type int and that returns * the nth Fibonacci number: * F0 = 1, F1 = 1, F2 = 2, F3 = 3, F4 = 5 * F(i+2) = F(i) + F(i+1) for i = 0, 1, 2, ... */ /* Timing fibonacci recursive vs. iterative (real, user): * Iterative (real, user) Recursive (real, user) * 1st Fibonacci: 0m0.011s, 0m0.001s * 3rd Fibonacci: 0m0.004s, 0m0.001s * 5th Fibonacci: 0m0.004s, 0m0.001s * 7th Fibonacci: 0m0.004s, 0m0.001s * 9th Fibonacci: 0m0.004s, 0m0.001s * 11th Fibonacci: 0m0.004s, 0m0.001s * 13th Fibonacci: 0m0.004s, 0m0.001s * 15th Fibonacci: 0m0.003s, 0m0.001s */ #include <iostream> #include <cstdlib> #include <assert.h> #include <string> using std::cout; using std::cin; using std::endl; using std::string; long long fibonacciRecursive(long long n); long long fibonacciIterative(long long n); long long fibonacciRecursiveImproved(long long n); long long calcFibonacci(long long n, long long fib[]); void checkFibonacci(); int main(int argc, char* argv[]) { if (argc != 3) { cout << "usage: fibonacci iterative|recursive|recursive_improved number\n"; exit(1); } string method = argv[1]; string number = argv[2]; int n = atoi(number.c_str()); if (method == "iterative") { cout << fibonacciIterative(n) << endl; } else if (method == "recursive") { cout << fibonacciRecursive(n) << endl; } else if (method == "recursive_improved") { cout << fibonacciRecursiveImproved(n) << endl; } else { cout << "usage: fibonacci iterative|recursive number\n"; exit(1); } return 0; } long long fibonacciRecursive(long long n) { if (n < 0) { cout << "Invalid parameter for the fibonacci function.\n"; exit(1); } else if (n == 0 || n == 1) { return 1; } else { return (fibonacciRecursive(n-2) + fibonacciRecursive(n-1)); } } long long fibonacciRecursiveImproved(long long n) { if (n < 0) { cout << "Invalid parameter for the fibonacci function.\n"; exit(1); } long long fib[n + 1]; return calcFibonacci(n, fib); } long long calcFibonacci(long long n, long long fib[]) { if (n == 0) { fib[0] = 1; return fib[n]; } else if (n == 1) { fib[0] = 1; fib[1] = 1; return fib[n]; } else { fib[n-1] = calcFibonacci(n-1, fib); fib[n] = fib[n-2] + fib[n-1]; return fib[n]; } } long long fibonacciIterative(long long n) { if (n < 0) { cout << "Invalid parameter for the fibonacci function.\n"; exit(1); } else if (n == 0 || n == 1) { return 1; } else { long long previous = 1; long long current = 1; long long next = 0; for (long long i = 2; i <= n; i++) { next = previous + current; previous = current; current = next; } return next; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salsys.cxx,v $ * * $Revision: 1.17 $ * * last change: $Author: obo $ $Date: 2007-01-25 11:25:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <salunx.h> #include <salsys.hxx> #include <dtint.hxx> #include <msgbox.hxx> #include <button.hxx> #include <svdata.hxx> #include <saldata.hxx> #include <salinst.h> #include <saldisp.hxx> #include <salsys.h> #include <rtl/ustrbuf.hxx> #include <osl/thread.h> SalSystem* X11SalInstance::CreateSalSystem() { return new X11SalSystem(); } // ----------------------------------------------------------------------- X11SalSystem::~X11SalSystem() { } // for the moment only handle xinerama case unsigned int X11SalSystem::GetDisplayScreenCount() { SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); return pSalDisp->IsXinerama() ? pSalDisp->GetXineramaScreens().size() : pSalDisp->GetScreenCount(); } bool X11SalSystem::IsMultiDisplay() { SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); unsigned int nScreenCount = pSalDisp->GetScreenCount(); return pSalDisp->IsXinerama() ? false : (nScreenCount > 1); } unsigned int X11SalSystem::GetDefaultDisplayNumber() { SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); return pSalDisp->GetDefaultScreenNumber(); } Rectangle X11SalSystem::GetDisplayScreenPosSizePixel( unsigned int nScreen ) { Rectangle aRet; SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); if( pSalDisp->IsXinerama() ) { const std::vector< Rectangle >& rScreens = pSalDisp->GetXineramaScreens(); if( nScreen < rScreens.size() ) aRet = rScreens[nScreen]; } else { const SalDisplay::ScreenData& rScreen = pSalDisp->getDataForScreen( nScreen ); aRet = Rectangle( Point( 0, 0 ), rScreen.m_aSize ); } return aRet; } Rectangle X11SalSystem::GetDisplayWorkAreaPosSizePixel( unsigned int nScreen ) { // FIXME: workareas return GetDisplayScreenPosSizePixel( nScreen ); } rtl::OUString X11SalSystem::GetScreenName( unsigned int nScreen ) { rtl::OUString aScreenName; SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); if( pSalDisp->IsXinerama() ) { const std::vector< Rectangle >& rScreens = pSalDisp->GetXineramaScreens(); if( nScreen >= rScreens.size() ) nScreen = 0; rtl::OUStringBuffer aBuf( 256 ); aBuf.append( rtl::OStringToOUString( rtl::OString( DisplayString( pSalDisp->GetDisplay() ) ), osl_getThreadTextEncoding() ) ); aBuf.appendAscii( " [" ); aBuf.append( static_cast<sal_Int32>(nScreen) ); aBuf.append( sal_Unicode(']') ); aScreenName = aBuf.makeStringAndClear(); } else { if( nScreen >= static_cast<unsigned int>(pSalDisp->GetScreenCount()) ) nScreen = 0; rtl::OUStringBuffer aBuf( 256 ); aBuf.append( rtl::OStringToOUString( rtl::OString( DisplayString( pSalDisp->GetDisplay() ) ), osl_getThreadTextEncoding() ) ); // search backwards for ':' int nPos = aBuf.getLength(); if( nPos > 0 ) nPos--; while( nPos > 0 && aBuf.charAt( nPos ) != ':' ) nPos--; // search forward to '.' while( nPos < aBuf.getLength() && aBuf.charAt( nPos ) != '.' ) nPos++; if( nPos < aBuf.getLength() ) aBuf.setLength( nPos+1 ); else aBuf.append( sal_Unicode('.') ); aBuf.append( static_cast<sal_Int32>(nScreen) ); aScreenName = aBuf.makeStringAndClear(); } return aScreenName; } int X11SalSystem::ShowNativeDialog( const String& rTitle, const String& rMessage, const std::list< String >& rButtons, int nDefButton ) { int nRet = -1; ImplSVData* pSVData = ImplGetSVData(); if( pSVData->mpIntroWindow ) pSVData->mpIntroWindow->Hide(); WarningBox aWarn( NULL, WB_STDWORK, rMessage ); aWarn.SetText( rTitle ); aWarn.Clear(); USHORT nButton = 0; for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it ) { aWarn.AddButton( *it, nButton+1, nButton == (USHORT)nDefButton ? BUTTONDIALOG_DEFBUTTON : 0 ); nButton++; } aWarn.SetFocusButton( (USHORT)nDefButton+1 ); nRet = ((int)aWarn.Execute()) - 1; // normalize behaviour, actually this should never happen if( nRet < -1 || nRet >= int(rButtons.size()) ) nRet = -1; return nRet; } int X11SalSystem::ShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton) { int nDefButton = 0; std::list< String > aButtons; int nButtonIds[5], nBut = 0; if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK || nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ) { aButtons.push_back( Button::GetStandardText( BUTTON_OK ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK; } if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL || nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO ) { aButtons.push_back( Button::GetStandardText( BUTTON_YES ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES; aButtons.push_back( Button::GetStandardText( BUTTON_NO ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO; if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO ) nDefButton = 1; } if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL || nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL || nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL ) { if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL ) { aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY; } aButtons.push_back( Button::GetStandardText( BUTTON_CANCEL ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL; if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL ) nDefButton = aButtons.size()-1; } if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE ) { aButtons.push_back( Button::GetStandardText( BUTTON_ABORT ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT; aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY; aButtons.push_back( Button::GetStandardText( BUTTON_IGNORE ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE; switch( nDefaultButton ) { case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break; case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break; } } int nResult = ShowNativeDialog( rTitle, rMessage, aButtons, nDefButton ); return nResult != -1 ? nButtonIds[ nResult ] : 0; } <commit_msg>INTEGRATION: CWS vgbugs07 (1.17.104); FILE MERGED 2007/06/04 13:29:59 vg 1.17.104.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salsys.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: hr $ $Date: 2007-06-27 20:47:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <salunx.h> #include <vcl/salsys.hxx> #include <dtint.hxx> #include <vcl/msgbox.hxx> #include <vcl/button.hxx> #include <vcl/svdata.hxx> #include <saldata.hxx> #include <salinst.h> #include <saldisp.hxx> #include <salsys.h> #include <rtl/ustrbuf.hxx> #include <osl/thread.h> SalSystem* X11SalInstance::CreateSalSystem() { return new X11SalSystem(); } // ----------------------------------------------------------------------- X11SalSystem::~X11SalSystem() { } // for the moment only handle xinerama case unsigned int X11SalSystem::GetDisplayScreenCount() { SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); return pSalDisp->IsXinerama() ? pSalDisp->GetXineramaScreens().size() : pSalDisp->GetScreenCount(); } bool X11SalSystem::IsMultiDisplay() { SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); unsigned int nScreenCount = pSalDisp->GetScreenCount(); return pSalDisp->IsXinerama() ? false : (nScreenCount > 1); } unsigned int X11SalSystem::GetDefaultDisplayNumber() { SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); return pSalDisp->GetDefaultScreenNumber(); } Rectangle X11SalSystem::GetDisplayScreenPosSizePixel( unsigned int nScreen ) { Rectangle aRet; SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); if( pSalDisp->IsXinerama() ) { const std::vector< Rectangle >& rScreens = pSalDisp->GetXineramaScreens(); if( nScreen < rScreens.size() ) aRet = rScreens[nScreen]; } else { const SalDisplay::ScreenData& rScreen = pSalDisp->getDataForScreen( nScreen ); aRet = Rectangle( Point( 0, 0 ), rScreen.m_aSize ); } return aRet; } Rectangle X11SalSystem::GetDisplayWorkAreaPosSizePixel( unsigned int nScreen ) { // FIXME: workareas return GetDisplayScreenPosSizePixel( nScreen ); } rtl::OUString X11SalSystem::GetScreenName( unsigned int nScreen ) { rtl::OUString aScreenName; SalDisplay* pSalDisp = GetX11SalData()->GetDisplay(); if( pSalDisp->IsXinerama() ) { const std::vector< Rectangle >& rScreens = pSalDisp->GetXineramaScreens(); if( nScreen >= rScreens.size() ) nScreen = 0; rtl::OUStringBuffer aBuf( 256 ); aBuf.append( rtl::OStringToOUString( rtl::OString( DisplayString( pSalDisp->GetDisplay() ) ), osl_getThreadTextEncoding() ) ); aBuf.appendAscii( " [" ); aBuf.append( static_cast<sal_Int32>(nScreen) ); aBuf.append( sal_Unicode(']') ); aScreenName = aBuf.makeStringAndClear(); } else { if( nScreen >= static_cast<unsigned int>(pSalDisp->GetScreenCount()) ) nScreen = 0; rtl::OUStringBuffer aBuf( 256 ); aBuf.append( rtl::OStringToOUString( rtl::OString( DisplayString( pSalDisp->GetDisplay() ) ), osl_getThreadTextEncoding() ) ); // search backwards for ':' int nPos = aBuf.getLength(); if( nPos > 0 ) nPos--; while( nPos > 0 && aBuf.charAt( nPos ) != ':' ) nPos--; // search forward to '.' while( nPos < aBuf.getLength() && aBuf.charAt( nPos ) != '.' ) nPos++; if( nPos < aBuf.getLength() ) aBuf.setLength( nPos+1 ); else aBuf.append( sal_Unicode('.') ); aBuf.append( static_cast<sal_Int32>(nScreen) ); aScreenName = aBuf.makeStringAndClear(); } return aScreenName; } int X11SalSystem::ShowNativeDialog( const String& rTitle, const String& rMessage, const std::list< String >& rButtons, int nDefButton ) { int nRet = -1; ImplSVData* pSVData = ImplGetSVData(); if( pSVData->mpIntroWindow ) pSVData->mpIntroWindow->Hide(); WarningBox aWarn( NULL, WB_STDWORK, rMessage ); aWarn.SetText( rTitle ); aWarn.Clear(); USHORT nButton = 0; for( std::list< String >::const_iterator it = rButtons.begin(); it != rButtons.end(); ++it ) { aWarn.AddButton( *it, nButton+1, nButton == (USHORT)nDefButton ? BUTTONDIALOG_DEFBUTTON : 0 ); nButton++; } aWarn.SetFocusButton( (USHORT)nDefButton+1 ); nRet = ((int)aWarn.Execute()) - 1; // normalize behaviour, actually this should never happen if( nRet < -1 || nRet >= int(rButtons.size()) ) nRet = -1; return nRet; } int X11SalSystem::ShowNativeMessageBox(const String& rTitle, const String& rMessage, int nButtonCombination, int nDefaultButton) { int nDefButton = 0; std::list< String > aButtons; int nButtonIds[5], nBut = 0; if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK || nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL ) { aButtons.push_back( Button::GetStandardText( BUTTON_OK ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_OK; } if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL || nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO ) { aButtons.push_back( Button::GetStandardText( BUTTON_YES ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_YES; aButtons.push_back( Button::GetStandardText( BUTTON_NO ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO; if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_NO ) nDefButton = 1; } if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_OK_CANCEL || nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_YES_NO_CANCEL || nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL ) { if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_RETRY_CANCEL ) { aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY; } aButtons.push_back( Button::GetStandardText( BUTTON_CANCEL ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL; if( nDefaultButton == SALSYSTEM_SHOWNATIVEMSGBOX_BTN_CANCEL ) nDefButton = aButtons.size()-1; } if( nButtonCombination == SALSYSTEM_SHOWNATIVEMSGBOX_BTNCOMBI_ABORT_RETRY_IGNORE ) { aButtons.push_back( Button::GetStandardText( BUTTON_ABORT ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_ABORT; aButtons.push_back( Button::GetStandardText( BUTTON_RETRY ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY; aButtons.push_back( Button::GetStandardText( BUTTON_IGNORE ) ); nButtonIds[nBut++] = SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE; switch( nDefaultButton ) { case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_RETRY: nDefButton = 1;break; case SALSYSTEM_SHOWNATIVEMSGBOX_BTN_IGNORE: nDefButton = 2;break; } } int nResult = ShowNativeDialog( rTitle, rMessage, aButtons, nDefButton ); return nResult != -1 ? nButtonIds[ nResult ] : 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salogl.cxx,v $ * * $Revision: 1.21 $ * * last change: $Author: rt $ $Date: 2007-07-03 14:08:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <salunx.h> #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALDISP_HXX #include <saldisp.hxx> #endif #ifndef _SV_SALOGL_H #include <salogl.h> #endif #ifndef _SV_SALGDI_H #include <salgdi.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> using namespace rtl; // ------------ // - Lib-Name - // ------------ #ifdef MACOSX #define OGL_LIBNAME "libGL.dylib" #else #define OGL_LIBNAME "libGL.so.1" #endif // ---------- // - Macros - // ---------- // ----------------- // - Statics init. - // ----------------- // Members GLXContext X11SalOpenGL::maGLXContext = 0; Display* X11SalOpenGL::mpDisplay = 0; const XVisualInfo* X11SalOpenGL::mpVisualInfo = 0; BOOL X11SalOpenGL::mbHaveGLVisual = FALSE; oslModule X11SalOpenGL::mpGLLib = 0; #ifdef SOLARIS oslModule aMotifLib; #endif ULONG X11SalOpenGL::mnOGLState = OGL_STATE_UNLOADED; GLXContext (*X11SalOpenGL::pCreateContext)( Display *, XVisualInfo *, GLXContext, Bool ) = 0; void (*X11SalOpenGL::pDestroyContext)( Display *, GLXContext ) = 0; GLXContext (*X11SalOpenGL::pGetCurrentContext)( ) = 0; Bool (*X11SalOpenGL::pMakeCurrent)( Display *, GLXDrawable, GLXContext ) = 0; void (*X11SalOpenGL::pSwapBuffers)( Display*, GLXDrawable ) = 0; int (*X11SalOpenGL::pGetConfig)( Display*, XVisualInfo*, int, int* ) = 0; void (*X11SalOpenGL::pFlush)() = 0; // ------------- // - X11SalOpenGL - // ------------- // FIXME: Multiscreen X11SalOpenGL::X11SalOpenGL( SalGraphics* pSGraphics ) { X11SalGraphics* pGraphics = static_cast<X11SalGraphics*>(pSGraphics); mpDisplay = pGraphics->GetXDisplay(); mpVisualInfo = &pGraphics->GetDisplay()->GetVisual(pGraphics->GetScreenNumber()); maDrawable = pGraphics->GetDrawable(); } // ------------------------------------------------------------------------ X11SalOpenGL::~X11SalOpenGL() { } // ------------------------------------------------------------------------ bool X11SalOpenGL::IsValid() { if( OGL_STATE_UNLOADED == mnOGLState ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions; if( *DisplayString( mpDisplay ) == ':' || ! strncmp( DisplayString( mpDisplay ), "localhost:", 10 ) ) { // GLX only on local displays due to strange problems // with remote GLX ppExtensions = XListExtensions( mpDisplay, &nExtensions ); for( int i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); #if OSL_DEBUG_LEVEL > 1 if( ! bHasGLX ) fprintf( stderr, "XServer does not support GLX extension\n" ); #endif if( bHasGLX ) { /* * #82406# the XFree4.0 GLX module does not seem * to work that great, at least not the one that comes * with the default installation and Matrox cards. * Since these are common we disable usage of * OpenGL per default. */ static const char* pOverrideGLX = getenv( "SAL_ENABLE_GLX_XFREE4" ); if( ! strncmp( ServerVendor( mpDisplay ), "The XFree86 Project, Inc", 24 ) && VendorRelease( mpDisplay ) >= 4000 && ! pOverrideGLX ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "disabling GLX usage on XFree >= 4.0\n" ); #endif bHasGLX = FALSE; } } } if( bHasGLX && mpVisualInfo->c_class == TrueColor && ImplInit() ) { int nDoubleBuffer = 0; int nHaveGL = 0; pGetConfig( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), GLX_USE_GL, &nHaveGL ); pGetConfig( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { SalDisplay* pSalDisplay = GetX11SalData()->GetDisplay(); pSalDisplay->GetXLib()->PushXErrorLevel( true ); mbHaveGLVisual = TRUE; maGLXContext = pCreateContext( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), 0, True ); if( ! pSalDisplay->GetXLib()->HasXErrorOccured() ) pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); if( pSalDisplay->GetXLib()->HasXErrorOccured() ) mbHaveGLVisual = FALSE; pSalDisplay->GetXLib()->PopXErrorLevel(); if( mbHaveGLVisual ) mnOGLState = OGL_STATE_VALID; else maGLXContext = None; } } if( mnOGLState != OGL_STATE_VALID ) mnOGLState = OGL_STATE_INVALID; #if OSL_DEBUG_LEVEL > 1 if( mnOGLState == OGL_STATE_VALID ) fprintf( stderr, "Using GLX on visual id %lx.\n", mpVisualInfo->visualid ); else fprintf( stderr, "Not using GLX.\n" ); #endif } return mnOGLState == OGL_STATE_VALID ? TRUE : FALSE; } void X11SalOpenGL::Release() { if( maGLXContext && pDestroyContext ) pDestroyContext( mpDisplay, maGLXContext ); } // ------------------------------------------------------------------------ void X11SalOpenGL::ReleaseLib() { if( mpGLLib ) { osl_unloadModule( mpGLLib ); #ifdef SOLARIS if( aMotifLib ) osl_unloadModule( aMotifLib ); #endif mpGLLib = 0; pCreateContext = 0; pDestroyContext = 0; pGetCurrentContext = 0; pMakeCurrent = 0; pSwapBuffers = 0; pGetConfig = 0; mnOGLState = OGL_STATE_UNLOADED; } } // ------------------------------------------------------------------------ oglFunction X11SalOpenGL::GetOGLFnc( const char *pFncName ) { return resolveSymbol( pFncName ); } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLEntry( SalGraphics* pGraphics ) { GLXDrawable aDrawable = static_cast<X11SalGraphics*>(pGraphics)->GetDrawable(); if( aDrawable != maDrawable ) { maDrawable = aDrawable; pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); } } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLExit( SalGraphics* ) { } // ------------------------------------------------------------------------ oglFunction X11SalOpenGL::resolveSymbol( const char* pSymbol ) { oglFunction pSym = NULL; if( mpGLLib ) { OUString aSym = OUString::createFromAscii( pSymbol ); pSym = osl_getFunctionSymbol( mpGLLib, aSym.pData ); } return pSym; } BOOL X11SalOpenGL::ImplInit() { if( ! mpGLLib ) { ByteString sNoGL( getenv( "SAL_NOOPENGL" ) ); if( sNoGL.ToLowerAscii() == "true" ) return FALSE; sal_Int32 nRtldMode = SAL_LOADMODULE_NOW; #ifdef SOLARIS /* #i36866# an obscure interaction with jvm can let java crash * if we do not use SAL_LOADMODULE_GLOBAL here */ nRtldMode |= SAL_LOADMODULE_GLOBAL; /* #i36899# and we need Xm, too, else jvm will not work properly. */ OUString aMotifName( RTL_CONSTASCII_USTRINGPARAM( "libXm.so" ) ); aMotifLib = osl_loadModule( aMotifName.pData, nRtldMode ); #endif OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( OGL_LIBNAME ) ); mpGLLib = osl_loadModule( aLibName.pData, nRtldMode ); } if( ! mpGLLib ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, OGL_LIBNAME "could not be opened\n" ); #endif return FALSE; } // Internal use pCreateContext = (GLXContext(*)(Display*,XVisualInfo*,GLXContext,Bool )) resolveSymbol( "glXCreateContext" ); pDestroyContext = (void(*)(Display*,GLXContext)) resolveSymbol( "glXDestroyContext" ); pGetCurrentContext = (GLXContext(*)()) resolveSymbol( "glXGetCurrentContext" ); pMakeCurrent = (Bool(*)(Display*,GLXDrawable,GLXContext)) resolveSymbol( "glXMakeCurrent" ); pSwapBuffers=(void(*)(Display*, GLXDrawable)) resolveSymbol( "glXSwapBuffers" ); pGetConfig = (int(*)(Display*, XVisualInfo*, int, int* )) resolveSymbol( "glXGetConfig" ); pFlush = (void(*)()) resolveSymbol( "glFlush" ); BOOL bRet = pCreateContext && pDestroyContext && pGetCurrentContext && pMakeCurrent && pSwapBuffers && pGetConfig ? TRUE : FALSE; #if OSL_DEBUG_LEVEL > 1 if( ! bRet ) fprintf( stderr, "could not find all needed symbols in " OGL_LIBNAME "\n" ); #endif return bRet; } void X11SalOpenGL::StartScene( SalGraphics* ) { // flush pending operations which otherwise might be drawn // at the wrong time XSync( mpDisplay, False ); } void X11SalOpenGL::StopScene() { if( maDrawable ) { pSwapBuffers( mpDisplay, maDrawable ); pFlush(); } } void X11SalOpenGL::MakeVisualWeights( Display* pDisplay, XVisualInfo* pInfos, int *pWeights, int nVisuals ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions,i ; // GLX only on local displays due to strange problems // with remote GLX if( ! ( *DisplayString( pDisplay ) == ':' || !strncmp( DisplayString( pDisplay ), "localhost:", 10 ) ) ) return; ppExtensions = XListExtensions( pDisplay, &nExtensions ); for( i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); if( ! bHasGLX ) return; if( ! ImplInit() ) return; for( i = 0; i < nVisuals; i++ ) { int nDoubleBuffer = 0; int nHaveGL = 0; // a weight lesser than zero indicates an invalid visual (wrong screen) if( pInfos[i].c_class == TrueColor && pInfos[i].depth > 14 && pWeights[i] >= 0) { pGetConfig( pDisplay, &pInfos[ i ], GLX_USE_GL, &nHaveGL ); pGetConfig( pDisplay, &pInfos[ i ], GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { mbHaveGLVisual = TRUE; pWeights[ i ] += 65536; } } } } <commit_msg>INTEGRATION: CWS changefileheader (1.21.246); FILE MERGED 2008/04/01 13:02:02 thb 1.21.246.2: #i85898# Stripping all external header guards 2008/03/28 15:45:28 rt 1.21.246.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: salogl.cxx,v $ * $Revision: 1.22 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <salunx.h> #include <saldata.hxx> #include <saldisp.hxx> #include <salogl.h> #include <salgdi.h> #include <stdlib.h> #include <stdio.h> #include <string.h> using namespace rtl; // ------------ // - Lib-Name - // ------------ #ifdef MACOSX #define OGL_LIBNAME "libGL.dylib" #else #define OGL_LIBNAME "libGL.so.1" #endif // ---------- // - Macros - // ---------- // ----------------- // - Statics init. - // ----------------- // Members GLXContext X11SalOpenGL::maGLXContext = 0; Display* X11SalOpenGL::mpDisplay = 0; const XVisualInfo* X11SalOpenGL::mpVisualInfo = 0; BOOL X11SalOpenGL::mbHaveGLVisual = FALSE; oslModule X11SalOpenGL::mpGLLib = 0; #ifdef SOLARIS oslModule aMotifLib; #endif ULONG X11SalOpenGL::mnOGLState = OGL_STATE_UNLOADED; GLXContext (*X11SalOpenGL::pCreateContext)( Display *, XVisualInfo *, GLXContext, Bool ) = 0; void (*X11SalOpenGL::pDestroyContext)( Display *, GLXContext ) = 0; GLXContext (*X11SalOpenGL::pGetCurrentContext)( ) = 0; Bool (*X11SalOpenGL::pMakeCurrent)( Display *, GLXDrawable, GLXContext ) = 0; void (*X11SalOpenGL::pSwapBuffers)( Display*, GLXDrawable ) = 0; int (*X11SalOpenGL::pGetConfig)( Display*, XVisualInfo*, int, int* ) = 0; void (*X11SalOpenGL::pFlush)() = 0; // ------------- // - X11SalOpenGL - // ------------- // FIXME: Multiscreen X11SalOpenGL::X11SalOpenGL( SalGraphics* pSGraphics ) { X11SalGraphics* pGraphics = static_cast<X11SalGraphics*>(pSGraphics); mpDisplay = pGraphics->GetXDisplay(); mpVisualInfo = &pGraphics->GetDisplay()->GetVisual(pGraphics->GetScreenNumber()); maDrawable = pGraphics->GetDrawable(); } // ------------------------------------------------------------------------ X11SalOpenGL::~X11SalOpenGL() { } // ------------------------------------------------------------------------ bool X11SalOpenGL::IsValid() { if( OGL_STATE_UNLOADED == mnOGLState ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions; if( *DisplayString( mpDisplay ) == ':' || ! strncmp( DisplayString( mpDisplay ), "localhost:", 10 ) ) { // GLX only on local displays due to strange problems // with remote GLX ppExtensions = XListExtensions( mpDisplay, &nExtensions ); for( int i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); #if OSL_DEBUG_LEVEL > 1 if( ! bHasGLX ) fprintf( stderr, "XServer does not support GLX extension\n" ); #endif if( bHasGLX ) { /* * #82406# the XFree4.0 GLX module does not seem * to work that great, at least not the one that comes * with the default installation and Matrox cards. * Since these are common we disable usage of * OpenGL per default. */ static const char* pOverrideGLX = getenv( "SAL_ENABLE_GLX_XFREE4" ); if( ! strncmp( ServerVendor( mpDisplay ), "The XFree86 Project, Inc", 24 ) && VendorRelease( mpDisplay ) >= 4000 && ! pOverrideGLX ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "disabling GLX usage on XFree >= 4.0\n" ); #endif bHasGLX = FALSE; } } } if( bHasGLX && mpVisualInfo->c_class == TrueColor && ImplInit() ) { int nDoubleBuffer = 0; int nHaveGL = 0; pGetConfig( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), GLX_USE_GL, &nHaveGL ); pGetConfig( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { SalDisplay* pSalDisplay = GetX11SalData()->GetDisplay(); pSalDisplay->GetXLib()->PushXErrorLevel( true ); mbHaveGLVisual = TRUE; maGLXContext = pCreateContext( mpDisplay, const_cast<XVisualInfo*>(mpVisualInfo), 0, True ); if( ! pSalDisplay->GetXLib()->HasXErrorOccured() ) pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); if( pSalDisplay->GetXLib()->HasXErrorOccured() ) mbHaveGLVisual = FALSE; pSalDisplay->GetXLib()->PopXErrorLevel(); if( mbHaveGLVisual ) mnOGLState = OGL_STATE_VALID; else maGLXContext = None; } } if( mnOGLState != OGL_STATE_VALID ) mnOGLState = OGL_STATE_INVALID; #if OSL_DEBUG_LEVEL > 1 if( mnOGLState == OGL_STATE_VALID ) fprintf( stderr, "Using GLX on visual id %lx.\n", mpVisualInfo->visualid ); else fprintf( stderr, "Not using GLX.\n" ); #endif } return mnOGLState == OGL_STATE_VALID ? TRUE : FALSE; } void X11SalOpenGL::Release() { if( maGLXContext && pDestroyContext ) pDestroyContext( mpDisplay, maGLXContext ); } // ------------------------------------------------------------------------ void X11SalOpenGL::ReleaseLib() { if( mpGLLib ) { osl_unloadModule( mpGLLib ); #ifdef SOLARIS if( aMotifLib ) osl_unloadModule( aMotifLib ); #endif mpGLLib = 0; pCreateContext = 0; pDestroyContext = 0; pGetCurrentContext = 0; pMakeCurrent = 0; pSwapBuffers = 0; pGetConfig = 0; mnOGLState = OGL_STATE_UNLOADED; } } // ------------------------------------------------------------------------ oglFunction X11SalOpenGL::GetOGLFnc( const char *pFncName ) { return resolveSymbol( pFncName ); } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLEntry( SalGraphics* pGraphics ) { GLXDrawable aDrawable = static_cast<X11SalGraphics*>(pGraphics)->GetDrawable(); if( aDrawable != maDrawable ) { maDrawable = aDrawable; pMakeCurrent( mpDisplay, maDrawable, maGLXContext ); } } // ------------------------------------------------------------------------ void X11SalOpenGL::OGLExit( SalGraphics* ) { } // ------------------------------------------------------------------------ oglFunction X11SalOpenGL::resolveSymbol( const char* pSymbol ) { oglFunction pSym = NULL; if( mpGLLib ) { OUString aSym = OUString::createFromAscii( pSymbol ); pSym = osl_getFunctionSymbol( mpGLLib, aSym.pData ); } return pSym; } BOOL X11SalOpenGL::ImplInit() { if( ! mpGLLib ) { ByteString sNoGL( getenv( "SAL_NOOPENGL" ) ); if( sNoGL.ToLowerAscii() == "true" ) return FALSE; sal_Int32 nRtldMode = SAL_LOADMODULE_NOW; #ifdef SOLARIS /* #i36866# an obscure interaction with jvm can let java crash * if we do not use SAL_LOADMODULE_GLOBAL here */ nRtldMode |= SAL_LOADMODULE_GLOBAL; /* #i36899# and we need Xm, too, else jvm will not work properly. */ OUString aMotifName( RTL_CONSTASCII_USTRINGPARAM( "libXm.so" ) ); aMotifLib = osl_loadModule( aMotifName.pData, nRtldMode ); #endif OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( OGL_LIBNAME ) ); mpGLLib = osl_loadModule( aLibName.pData, nRtldMode ); } if( ! mpGLLib ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, OGL_LIBNAME "could not be opened\n" ); #endif return FALSE; } // Internal use pCreateContext = (GLXContext(*)(Display*,XVisualInfo*,GLXContext,Bool )) resolveSymbol( "glXCreateContext" ); pDestroyContext = (void(*)(Display*,GLXContext)) resolveSymbol( "glXDestroyContext" ); pGetCurrentContext = (GLXContext(*)()) resolveSymbol( "glXGetCurrentContext" ); pMakeCurrent = (Bool(*)(Display*,GLXDrawable,GLXContext)) resolveSymbol( "glXMakeCurrent" ); pSwapBuffers=(void(*)(Display*, GLXDrawable)) resolveSymbol( "glXSwapBuffers" ); pGetConfig = (int(*)(Display*, XVisualInfo*, int, int* )) resolveSymbol( "glXGetConfig" ); pFlush = (void(*)()) resolveSymbol( "glFlush" ); BOOL bRet = pCreateContext && pDestroyContext && pGetCurrentContext && pMakeCurrent && pSwapBuffers && pGetConfig ? TRUE : FALSE; #if OSL_DEBUG_LEVEL > 1 if( ! bRet ) fprintf( stderr, "could not find all needed symbols in " OGL_LIBNAME "\n" ); #endif return bRet; } void X11SalOpenGL::StartScene( SalGraphics* ) { // flush pending operations which otherwise might be drawn // at the wrong time XSync( mpDisplay, False ); } void X11SalOpenGL::StopScene() { if( maDrawable ) { pSwapBuffers( mpDisplay, maDrawable ); pFlush(); } } void X11SalOpenGL::MakeVisualWeights( Display* pDisplay, XVisualInfo* pInfos, int *pWeights, int nVisuals ) { BOOL bHasGLX = FALSE; char **ppExtensions; int nExtensions,i ; // GLX only on local displays due to strange problems // with remote GLX if( ! ( *DisplayString( pDisplay ) == ':' || !strncmp( DisplayString( pDisplay ), "localhost:", 10 ) ) ) return; ppExtensions = XListExtensions( pDisplay, &nExtensions ); for( i=0; i < nExtensions; i++ ) { if( ! strncmp( "GLX", ppExtensions[ i ], 3 ) ) { bHasGLX = TRUE; break; } } XFreeExtensionList( ppExtensions ); if( ! bHasGLX ) return; if( ! ImplInit() ) return; for( i = 0; i < nVisuals; i++ ) { int nDoubleBuffer = 0; int nHaveGL = 0; // a weight lesser than zero indicates an invalid visual (wrong screen) if( pInfos[i].c_class == TrueColor && pInfos[i].depth > 14 && pWeights[i] >= 0) { pGetConfig( pDisplay, &pInfos[ i ], GLX_USE_GL, &nHaveGL ); pGetConfig( pDisplay, &pInfos[ i ], GLX_DOUBLEBUFFER, &nDoubleBuffer ); if( nHaveGL && ! nDoubleBuffer ) { mbHaveGLVisual = TRUE; pWeights[ i ] += 65536; } } } } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved." #include "test.h" // verify stats after a new row inserted into the root // verify stats after a row overwrite in the root // verify stats after a row deletion in the root // verify stats after an update callback inserts row // verify stats after an update callback overwrites row // verify ststs after an update callback deletes row #include <db.h> #include <unistd.h> #include <sys/stat.h> static int my_update_callback(DB *db UU(), const DBT *key UU(), const DBT *old_val, const DBT *extra, void (*set_val)(const DBT *new_val, void *set_extra), void *set_extra) { if (old_val != NULL && old_val->size == 42) // special code for delete set_val(NULL, set_extra); else set_val(extra, set_extra); return 0; } static void run_test (void) { int r; r = system("rm -rf " ENVDIR); CKERR(r); r = toku_os_mkdir(ENVDIR, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); DB_ENV *env = NULL; r = db_env_create(&env, 0); CKERR(r); env->set_errfile(env, stderr); r = env->set_redzone(env, 0); CKERR(r); env->set_update(env, my_update_callback); r = env->open(env, ENVDIR, DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN|DB_CREATE|DB_PRIVATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); DB *db = NULL; r = db_create(&db, env, 0); CKERR(r); DB_TXN *txn = NULL; r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); // verify that stats include a new row inserted into the root { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; char val = 1; DBT k,v; r = db->put(db, txn, dbt_init(&k, &key, sizeof key), dbt_init(&v, &val, sizeof val), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); } // verify that stats are updated by row overwrite in the root { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; int val = 2; DBT k,v; r = db->put(db, txn, dbt_init(&k, &key, sizeof key), dbt_init(&v, &val, sizeof val), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); } // verify that stats are updated by row deletion in the root { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; DBT k; r = db->del(db, txn, dbt_init(&k, &key, sizeof key), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys <= 1 && s.bt_dsize == 0); // since garbage collection may not occur, the key count may not be updated r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); // garbage collection is not happening here yet, so // the number of keys should be 1 assert(s.bt_nkeys == 1 && s.bt_dsize == 0); } // verify update of non-existing key inserts a row { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; char val = 1; DBT k = { .data = &key, .size = sizeof key }; DBT e = { .data = &val, .size = sizeof val }; r = db->update(db, txn, &k, &e, 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); } // verify update callback overwrites the row { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; int val = 2; DBT k = { .data = &key, .size = sizeof key }; DBT e = { .data = &val, .size = sizeof val }; r = db->update(db, txn, &k, &e, 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); } // verify update callback deletes the row { // insert a new row r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; char val[42]; memset(val, 0, sizeof val); DBT k = { .data = &key, .size = sizeof key }; DBT e = { .data = &val, .size = sizeof val }; r = db->update(db, txn, &k, &e, 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys <= 2 && s.bt_dsize == sizeof key + sizeof val); // update it again, this should delete the row r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->update(db, txn, &k, &e, 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys <= 2 && s.bt_dsize == 0); // since garbage collection may not occur, the key count may not be updated r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys <= 2 && s.bt_dsize == 0); } r = db->close(db, 0); CKERR(r); r = env->close(env, 0); CKERR(r); } int test_main (int argc , char * const argv[]) { parse_args(argc, argv); run_test(); return 0; } <commit_msg>closes #5744, make comment in test of bug exposed by test<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "$Id$" #ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved." #include "test.h" // verify stats after a new row inserted into the root // verify stats after a row overwrite in the root // verify stats after a row deletion in the root // verify stats after an update callback inserts row // verify stats after an update callback overwrites row // verify ststs after an update callback deletes row #include <db.h> #include <unistd.h> #include <sys/stat.h> static int my_update_callback(DB *db UU(), const DBT *key UU(), const DBT *old_val, const DBT *extra, void (*set_val)(const DBT *new_val, void *set_extra), void *set_extra) { if (old_val != NULL && old_val->size == 42) // special code for delete set_val(NULL, set_extra); else set_val(extra, set_extra); return 0; } static void run_test (void) { int r; r = system("rm -rf " ENVDIR); CKERR(r); r = toku_os_mkdir(ENVDIR, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); DB_ENV *env = NULL; r = db_env_create(&env, 0); CKERR(r); env->set_errfile(env, stderr); r = env->set_redzone(env, 0); CKERR(r); env->set_update(env, my_update_callback); r = env->open(env, ENVDIR, DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN|DB_CREATE|DB_PRIVATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); DB *db = NULL; r = db_create(&db, env, 0); CKERR(r); DB_TXN *txn = NULL; r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); // verify that stats include a new row inserted into the root { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; char val = 1; DBT k,v; r = db->put(db, txn, dbt_init(&k, &key, sizeof key), dbt_init(&v, &val, sizeof val), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); } // verify that stats are updated by row overwrite in the root { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; int val = 2; DBT k,v; r = db->put(db, txn, dbt_init(&k, &key, sizeof key), dbt_init(&v, &val, sizeof val), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); } // verify that stats are updated by row deletion in the root { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; DBT k; r = db->del(db, txn, dbt_init(&k, &key, sizeof key), 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys <= 1 && s.bt_dsize == 0); // since garbage collection may not occur, the key count may not be updated r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); // garbage collection is not happening here yet, so // the number of keys should be 1 assert(s.bt_nkeys == 1 && s.bt_dsize == 0); } // verify update of non-existing key inserts a row // // // NOTE: #5744 was caught by this test below. // // { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; char val = 1; DBT k = { .data = &key, .size = sizeof key }; DBT e = { .data = &val, .size = sizeof val }; r = db->update(db, txn, &k, &e, 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); } // verify update callback overwrites the row { r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; int val = 2; DBT k = { .data = &key, .size = sizeof key }; DBT e = { .data = &val, .size = sizeof val }; r = db->update(db, txn, &k, &e, 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys == 1 && s.bt_dsize == sizeof key + sizeof val); } // verify update callback deletes the row { // insert a new row r = env->txn_begin(env, 0, &txn, 0); CKERR(r); int key = 1; char val[42]; memset(val, 0, sizeof val); DBT k = { .data = &key, .size = sizeof key }; DBT e = { .data = &val, .size = sizeof val }; r = db->update(db, txn, &k, &e, 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); DB_BTREE_STAT64 s; r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys <= 2 && s.bt_dsize == sizeof key + sizeof val); // update it again, this should delete the row r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->update(db, txn, &k, &e, 0); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys <= 2 && s.bt_dsize == 0); // since garbage collection may not occur, the key count may not be updated r = db->close(db, 0); CKERR(r); r = db_create(&db, env, 0); CKERR(r); r = env->txn_begin(env, 0, &txn, 0); CKERR(r); r = db->open(db, txn, "foo.db", 0, DB_BTREE, DB_CREATE, S_IRWXU+S_IRWXG+S_IRWXO); CKERR(r); r = txn->commit(txn, 0); CKERR(r); r = db->stat64(db, NULL, &s); CKERR(r); assert(s.bt_nkeys <= 2 && s.bt_dsize == 0); } r = db->close(db, 0); CKERR(r); r = env->close(env, 0); CKERR(r); } int test_main (int argc , char * const argv[]) { parse_args(argc, argv); run_test(); return 0; } <|endoftext|>
<commit_before>/** @file * * @ingroup dspSoundFileLib * * @brief Provides a common interface to soundfile data * * @details This object provides a common set of attributes and methods for working with soundfiles at a specific filepath. * This allows us to access metadata and copy values in a common way without duplicating code. As with the rest of the * SoundfileLib, it relies on the third-party <a href="http://www.mega-nerd.com/libsndfile/">libsndfile library</a>.@n * Be aware that attributes and metadata are cached when the setFilePath method is called in order to provide efficiency, but this may lead to problems if the file somehow changes after the method call. * * @authors Nathan Wolek * * @copyright Copyright © 2013 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfile.h" #include "TTInterpolate.h" #define thisTTClass TTSoundfile #define thisTTClassName "soundfile" #define thisTTClassTags "soundfile" TT_AUDIO_CONSTRUCTOR, mFilePath(kTTSymEmpty), mNumChannels(0), mSampleRate(0.0), mLengthInSamples(0), mLengthInSeconds(0.0), mTitle(kTTSymEmpty), mArtist(kTTSymEmpty), mDate(kTTSymEmpty), mAnnotation(kTTSymEmpty), mSoundFile(NULL) { // add the attributes and messages here addAttributeWithSetter(FilePath, kTypeSymbol); addAttribute(NumChannels, kTypeInt16); addAttributeProperty(NumChannels, readOnly, kTTBoolYes); // need to add the rest of these here... addAttribute(SampleRate, kTypeFloat64); addAttributeProperty(SampleRate, readOnly, kTTBoolYes); addAttribute(LengthInSamples, kTypeInt64); addAttributeProperty(LengthInSamples, readOnly, kTTBoolYes); addAttribute(LengthInSeconds, kTypeFloat64); addAttributeProperty(LengthInSeconds, readOnly, kTTBoolYes); addAttribute(Title, kTypeSymbol); addAttributeProperty(Title, readOnly, kTTBoolYes); addAttribute(Artist, kTypeSymbol); addAttributeProperty(Artist, readOnly, kTTBoolYes); addAttribute(Date, kTypeSymbol); addAttributeProperty(Date, readOnly, kTTBoolYes); addAttribute(Annotation, kTypeSymbol); addAttributeProperty(Annotation, readOnly, kTTBoolYes); } TTSoundfile::~TTSoundfile() { // copied from TTSoundfilePlayer, confirm that it is needed if (mSoundFile) sf_close(mSoundFile); } TTErr TTSoundfile::setFilePath(const TTValue& newValue) { TTSymbol potentialFilePath = newValue; SNDFILE* soundfile; const char* textInfo; #ifdef TT_PLATFORM_WIN // There is a bug in libsndfile on Windows where upon return from this function a runtime check fails // because the stack is corrupted around soundfileInfo when sf_open() is called. // We work around this by allocating some extra memory to absorb the overrun. // [tap - old comment from soundfileplayer] SF_INFO soundfileInfo[2]; #else SF_INFO soundfileInfo[1]; #endif memset(&soundfileInfo, 0, sizeof(SF_INFO)); //soundfileInfo.format = 0; soundfile = sf_open(potentialFilePath.c_str(), SFM_READ, soundfileInfo); if (soundfile) { // if the filepath was valid // swap out the old for the new, but hold onto the old for a moment SNDFILE* oldSoundFile = mSoundFile; mSoundFile = soundfile; // if there was an old file, we can now close it if (oldSoundFile) sf_close(oldSoundFile); // copy the metadata to our local variable memcpy(&mSoundFileInfo, soundfileInfo, sizeof(SF_INFO)); /* copy additional data to local variables */ // filepath mFilePath = potentialFilePath; // number of channels mNumChannels = mSoundFileInfo.channels; // sample rate mSampleRate = mSoundFileInfo.samplerate; // duration in samples mLengthInSamples = mSoundFileInfo.frames; // duration in seconds mLengthInSeconds = mLengthInSamples / mSampleRate; // copy specific metadata pieces to separate TTSymbols // in transfer from player, made this little pattern into a macro #define SF_STRING_TO_TTSYMBOL(sf_info_piece, local_ttsymbol) \ textInfo = sf_get_string(soundfile, sf_info_piece); \ if (textInfo) { \ local_ttsymbol = TT(textInfo); \ } \ else local_ttsymbol = kTTSymEmpty; // title SF_STRING_TO_TTSYMBOL(SF_STR_TITLE, mTitle); // artist SF_STRING_TO_TTSYMBOL(SF_STR_ARTIST, mArtist); // date SF_STRING_TO_TTSYMBOL(SF_STR_DATE, mDate); // comment SF_STRING_TO_TTSYMBOL(SF_STR_COMMENT, mAnnotation); return kTTErrNone; } else { // if the filepath was invalid char errstr[256]; sf_error_str(soundfile, errstr, 256); TTLogMessage("cannot open soundfile %s: %s", potentialFilePath.c_str(), errstr); return kTTErrInvalidFilepath; } } TTErr TTSoundfile::peek(const TTRowID frame, const TTColumnID channel, TTSampleValue& value) { TTSampleVector temp_value; sf_count_t seekInFrames; sf_count_t numSamplesRead; seekInFrames = sf_seek(mSoundFile, frame, SEEK_SET); if (seekInFrames == -1) { return kTTErrGeneric; } temp_value.resize(mNumChannels); numSamplesRead = sf_readf_double(mSoundFile, &temp_value[0], 1); if (numSamplesRead != 1) { return kTTErrGeneric; } value = temp_value[channel]; return kTTErrNone; } TTErr TTSoundfile::peeki(const TTFloat64 frame, const TTColumnID channel, TTSampleValue& value) { // variables needed TTColumnID p_channel = channel; TTFloat64 indexIntegralPart = TTInt32(frame); TTFloat64 indexFractionalPart = frame - indexIntegralPart; // before makeInBounds to get the right value! TTRowID indexThisInteger = TTRowID(indexIntegralPart); TTRowID indexNextInteger = indexThisInteger + 1; TTSampleValue valueThisInteger, valueNextInteger; peek(indexThisInteger, p_channel, valueThisInteger); peek(indexNextInteger, p_channel, valueNextInteger); // simple linear interpolation adapted from TTDelay value = TTInterpolateLinear(valueThisInteger, valueNextInteger, indexFractionalPart); return kTTErrNone; }<commit_msg>SoundfileLib: removed 8 uses of kTTBoolYes, project still does NOT build.<commit_after>/** @file * * @ingroup dspSoundFileLib * * @brief Provides a common interface to soundfile data * * @details This object provides a common set of attributes and methods for working with soundfiles at a specific filepath. * This allows us to access metadata and copy values in a common way without duplicating code. As with the rest of the * SoundfileLib, it relies on the third-party <a href="http://www.mega-nerd.com/libsndfile/">libsndfile library</a>.@n * Be aware that attributes and metadata are cached when the setFilePath method is called in order to provide efficiency, but this may lead to problems if the file somehow changes after the method call. * * @authors Nathan Wolek * * @copyright Copyright © 2013 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfile.h" #include "TTInterpolate.h" #define thisTTClass TTSoundfile #define thisTTClassName "soundfile" #define thisTTClassTags "soundfile" TT_AUDIO_CONSTRUCTOR, mFilePath(kTTSymEmpty), mNumChannels(0), mSampleRate(0.0), mLengthInSamples(0), mLengthInSeconds(0.0), mTitle(kTTSymEmpty), mArtist(kTTSymEmpty), mDate(kTTSymEmpty), mAnnotation(kTTSymEmpty), mSoundFile(NULL) { // add the attributes and messages here addAttributeWithSetter(FilePath, kTypeSymbol); addAttribute(NumChannels, kTypeInt16); addAttributeProperty(NumChannels, readOnly, TTValue(YES)); // need to add the rest of these here... addAttribute(SampleRate, kTypeFloat64); addAttributeProperty(SampleRate, readOnly, TTValue(YES)); addAttribute(LengthInSamples, kTypeInt64); addAttributeProperty(LengthInSamples, readOnly, TTValue(YES)); addAttribute(LengthInSeconds, kTypeFloat64); addAttributeProperty(LengthInSeconds, readOnly, TTValue(YES)); addAttribute(Title, kTypeSymbol); addAttributeProperty(Title, readOnly, TTValue(YES)); addAttribute(Artist, kTypeSymbol); addAttributeProperty(Artist, readOnly, TTValue(YES)); addAttribute(Date, kTypeSymbol); addAttributeProperty(Date, readOnly, TTValue(YES)); addAttribute(Annotation, kTypeSymbol); addAttributeProperty(Annotation, readOnly, TTValue(YES)); } TTSoundfile::~TTSoundfile() { // copied from TTSoundfilePlayer, confirm that it is needed if (mSoundFile) sf_close(mSoundFile); } TTErr TTSoundfile::setFilePath(const TTValue& newValue) { TTSymbol potentialFilePath = newValue; SNDFILE* soundfile; const char* textInfo; #ifdef TT_PLATFORM_WIN // There is a bug in libsndfile on Windows where upon return from this function a runtime check fails // because the stack is corrupted around soundfileInfo when sf_open() is called. // We work around this by allocating some extra memory to absorb the overrun. // [tap - old comment from soundfileplayer] SF_INFO soundfileInfo[2]; #else SF_INFO soundfileInfo[1]; #endif memset(&soundfileInfo, 0, sizeof(SF_INFO)); //soundfileInfo.format = 0; soundfile = sf_open(potentialFilePath.c_str(), SFM_READ, soundfileInfo); if (soundfile) { // if the filepath was valid // swap out the old for the new, but hold onto the old for a moment SNDFILE* oldSoundFile = mSoundFile; mSoundFile = soundfile; // if there was an old file, we can now close it if (oldSoundFile) sf_close(oldSoundFile); // copy the metadata to our local variable memcpy(&mSoundFileInfo, soundfileInfo, sizeof(SF_INFO)); /* copy additional data to local variables */ // filepath mFilePath = potentialFilePath; // number of channels mNumChannels = mSoundFileInfo.channels; // sample rate mSampleRate = mSoundFileInfo.samplerate; // duration in samples mLengthInSamples = mSoundFileInfo.frames; // duration in seconds mLengthInSeconds = mLengthInSamples / mSampleRate; // copy specific metadata pieces to separate TTSymbols // in transfer from player, made this little pattern into a macro #define SF_STRING_TO_TTSYMBOL(sf_info_piece, local_ttsymbol) \ textInfo = sf_get_string(soundfile, sf_info_piece); \ if (textInfo) { \ local_ttsymbol = TT(textInfo); \ } \ else local_ttsymbol = kTTSymEmpty; // title SF_STRING_TO_TTSYMBOL(SF_STR_TITLE, mTitle); // artist SF_STRING_TO_TTSYMBOL(SF_STR_ARTIST, mArtist); // date SF_STRING_TO_TTSYMBOL(SF_STR_DATE, mDate); // comment SF_STRING_TO_TTSYMBOL(SF_STR_COMMENT, mAnnotation); return kTTErrNone; } else { // if the filepath was invalid char errstr[256]; sf_error_str(soundfile, errstr, 256); TTLogMessage("cannot open soundfile %s: %s", potentialFilePath.c_str(), errstr); return kTTErrInvalidFilepath; } } TTErr TTSoundfile::peek(const TTRowID frame, const TTColumnID channel, TTSampleValue& value) { TTSampleVector temp_value; sf_count_t seekInFrames; sf_count_t numSamplesRead; seekInFrames = sf_seek(mSoundFile, frame, SEEK_SET); if (seekInFrames == -1) { return kTTErrGeneric; } temp_value.resize(mNumChannels); numSamplesRead = sf_readf_double(mSoundFile, &temp_value[0], 1); if (numSamplesRead != 1) { return kTTErrGeneric; } value = temp_value[channel]; return kTTErrNone; } TTErr TTSoundfile::peeki(const TTFloat64 frame, const TTColumnID channel, TTSampleValue& value) { // variables needed TTColumnID p_channel = channel; TTFloat64 indexIntegralPart = TTInt32(frame); TTFloat64 indexFractionalPart = frame - indexIntegralPart; // before makeInBounds to get the right value! TTRowID indexThisInteger = TTRowID(indexIntegralPart); TTRowID indexNextInteger = indexThisInteger + 1; TTSampleValue valueThisInteger, valueNextInteger; peek(indexThisInteger, p_channel, valueThisInteger); peek(indexNextInteger, p_channel, valueNextInteger); // simple linear interpolation adapted from TTDelay value = TTInterpolateLinear(valueThisInteger, valueNextInteger, indexFractionalPart); return kTTErrNone; }<|endoftext|>
<commit_before>/** * @file curl.cpp * @brief Brief description of file. * */ #include <stdio.h> #include <angort/angort.h> #include <angort/hash.h> #include <curl/curl.h> using namespace angort; struct CurlWrapper : GarbageCollected { char buf[CURL_ERROR_SIZE]; CURL *c; char *data; size_t len,maxsize; CurlWrapper(){ size_t writefunc(void *buffer, size_t size, size_t nmemb, void *userp); c = curl_easy_init(); maxsize=1024; data=(char *)malloc(maxsize); *data=0; len = 0; curl_easy_setopt(c,CURLOPT_ERRORBUFFER,buf); curl_easy_setopt(c,CURLOPT_WRITEFUNCTION,writefunc); curl_easy_setopt(c,CURLOPT_WRITEDATA,this); } ~CurlWrapper(){ curl_easy_cleanup(c); free(data); } }; class CurlType : public GCType { public: CurlType(){ add("CURL","CURL"); } CurlWrapper *get(Value *v){ if(v->t != this) throw RUNT(EX_TYPE,"").set("Expected CURL, not %s",v->t->name); return (CurlWrapper*)(v->v.gc); } void set(Value *v){ v->clr(); v->t = this; v->v.gc = new CurlWrapper(); incRef(v); } }; size_t writefunc(void *buffer, size_t size, size_t nmemb, void *userp){ CurlWrapper *c = (CurlWrapper *)userp; size_t s = size*nmemb; while(c->len+s+1>c->maxsize){ c->maxsize+=1024; c->data=(char *)realloc(c->data,c->maxsize); } memcpy(c->data+c->len,buffer,s); c->len+=s; c->data[c->len]=0; return s; } static CurlType tCurl; %name curl %shared %type curl tCurl CurlWrapper inline float hgetfloatdef(Hash *h,const char *s,float def=0){ Value *v = h->getSym(s); if(v) return v->toFloat(); else return def; } inline int hgetintdef(Hash *h,const char *s,int def=0){ Value *v = h->getSym(s); if(v) return v->toInt(); else return def; } inline const char *hgetstrdef(Hash *h,const char *s,const char *def=NULL){ Value *v = h->getSym(s); if(v) return v->toString().get(); else return def; } inline float hgetfloat(Hash *h,const char *s){ Value *v = h->getSym(s); if(!v)throw RUNT(EX_NOTFOUND,"").set("required key '%s' not found in hash",s); return v->toFloat(); } inline int hgetint(Hash *h,const char *s){ Value *v = h->getSym(s); if(!v)throw RUNT(EX_NOTFOUND,"").set("required key '%s' not found in hash",s); return v->toInt(); } inline const char *hgetstr(Hash *h,const char *s){ Value *v = h->getSym(s); if(!v)throw RUNT(EX_NOTFOUND,"").set("required key '%s' not found in hash",s); return v->toString().get(); } inline Value *hgetsym(Hash *h,const char *s){ Value *v = h->getSym(s); if(!v)throw RUNT(EX_NOTFOUND,"").set("required key '%s' not found in hash",s); return v; } %init { fprintf(stderr,"Initialising CURL plugin, %s %s\n",__DATE__,__TIME__); curl_global_init(CURL_GLOBAL_ALL); } %shutdown { curl_global_cleanup(); } %word make (-- curl) make a curl object, need this to do anything. Then setopt and perform with it. { tCurl.set(a->pushval()); } %word setopt (curl hash -- curl) set opts in curl (supported: `url, `post) { Hash *p1 = Types::tHash->get(a->popval()); CurlWrapper *p0 = tCurl.get(a->stack.peekptr()); CURL *c = p0->c; if(const char *url = hgetstrdef(p1,"url",NULL)) curl_easy_setopt(c,CURLOPT_URL,url); if(const char *post = hgetstrdef(p1,"postfields",NULL)) curl_easy_setopt(c,CURLOPT_COPYPOSTFIELDS,post); } %wordargs args h (hash -- string) turn a hash into an arg string { int maxsize = 256; int curlen=0; char *buf = (char *)malloc(maxsize); *buf=0; Iterator<Value *> *iter = p0->createIterator(true); for(iter->first();!iter->isDone();iter->next()){ Value *v = iter->current(); const StringBuffer &b = v->toString(); const char *s = b.get(); int klen = strlen(s); if(p0->find(v)){ const StringBuffer &bv = p0->getval()->toString(); const char *sv = bv.get(); int vlen = strlen(sv); while(klen+vlen+curlen+4>maxsize){ maxsize+=256; buf = (char *)realloc(buf,maxsize); } sprintf(buf+curlen,"%s=%s&",s,sv); curlen+=klen+vlen+2; } } buf[strlen(buf)-1]=0; // remove last & a->pushString(buf); free(buf); delete iter; } %wordargs perform A|curl (curl -- error|none) perform the transfer, use "data" to get the data { CURLcode rv = curl_easy_perform(p0->c); if(rv == CURLE_OK) a->pushNone(); else { a->pushString(p0->buf); } } %wordargs data A|curl (curl -- data) get downloaded data (as string) { Value v; Types::tString->set(&v,p0->data); a->pushval()->copy(&v); } <commit_msg>oops - word descs don't like quotes.<commit_after>/** * @file curl.cpp * @brief Brief description of file. * */ #include <stdio.h> #include <angort/angort.h> #include <angort/hash.h> #include <curl/curl.h> using namespace angort; struct CurlWrapper : GarbageCollected { char buf[CURL_ERROR_SIZE]; CURL *c; char *data; size_t len,maxsize; CurlWrapper(){ size_t writefunc(void *buffer, size_t size, size_t nmemb, void *userp); c = curl_easy_init(); maxsize=1024; data=(char *)malloc(maxsize); *data=0; len = 0; curl_easy_setopt(c,CURLOPT_ERRORBUFFER,buf); curl_easy_setopt(c,CURLOPT_WRITEFUNCTION,writefunc); curl_easy_setopt(c,CURLOPT_WRITEDATA,this); } ~CurlWrapper(){ curl_easy_cleanup(c); free(data); } }; class CurlType : public GCType { public: CurlType(){ add("CURL","CURL"); } CurlWrapper *get(Value *v){ if(v->t != this) throw RUNT(EX_TYPE,"").set("Expected CURL, not %s",v->t->name); return (CurlWrapper*)(v->v.gc); } void set(Value *v){ v->clr(); v->t = this; v->v.gc = new CurlWrapper(); incRef(v); } }; size_t writefunc(void *buffer, size_t size, size_t nmemb, void *userp){ CurlWrapper *c = (CurlWrapper *)userp; size_t s = size*nmemb; while(c->len+s+1>c->maxsize){ c->maxsize+=1024; c->data=(char *)realloc(c->data,c->maxsize); } memcpy(c->data+c->len,buffer,s); c->len+=s; c->data[c->len]=0; return s; } static CurlType tCurl; %name curl %shared %type curl tCurl CurlWrapper inline float hgetfloatdef(Hash *h,const char *s,float def=0){ Value *v = h->getSym(s); if(v) return v->toFloat(); else return def; } inline int hgetintdef(Hash *h,const char *s,int def=0){ Value *v = h->getSym(s); if(v) return v->toInt(); else return def; } inline const char *hgetstrdef(Hash *h,const char *s,const char *def=NULL){ Value *v = h->getSym(s); if(v) return v->toString().get(); else return def; } inline float hgetfloat(Hash *h,const char *s){ Value *v = h->getSym(s); if(!v)throw RUNT(EX_NOTFOUND,"").set("required key '%s' not found in hash",s); return v->toFloat(); } inline int hgetint(Hash *h,const char *s){ Value *v = h->getSym(s); if(!v)throw RUNT(EX_NOTFOUND,"").set("required key '%s' not found in hash",s); return v->toInt(); } inline const char *hgetstr(Hash *h,const char *s){ Value *v = h->getSym(s); if(!v)throw RUNT(EX_NOTFOUND,"").set("required key '%s' not found in hash",s); return v->toString().get(); } inline Value *hgetsym(Hash *h,const char *s){ Value *v = h->getSym(s); if(!v)throw RUNT(EX_NOTFOUND,"").set("required key '%s' not found in hash",s); return v; } %init { fprintf(stderr,"Initialising CURL plugin, %s %s\n",__DATE__,__TIME__); curl_global_init(CURL_GLOBAL_ALL); } %shutdown { curl_global_cleanup(); } %word make (-- curl) make a curl object, need this to do anything. Then setopt and perform with it. { tCurl.set(a->pushval()); } %word setopt (curl hash -- curl) set opts in curl (supported: `url, `post) { Hash *p1 = Types::tHash->get(a->popval()); CurlWrapper *p0 = tCurl.get(a->stack.peekptr()); CURL *c = p0->c; if(const char *url = hgetstrdef(p1,"url",NULL)) curl_easy_setopt(c,CURLOPT_URL,url); if(const char *post = hgetstrdef(p1,"postfields",NULL)) curl_easy_setopt(c,CURLOPT_COPYPOSTFIELDS,post); } %wordargs args h (hash -- string) turn a hash into an arg string { int maxsize = 256; int curlen=0; char *buf = (char *)malloc(maxsize); *buf=0; Iterator<Value *> *iter = p0->createIterator(true); for(iter->first();!iter->isDone();iter->next()){ Value *v = iter->current(); const StringBuffer &b = v->toString(); const char *s = b.get(); int klen = strlen(s); if(p0->find(v)){ const StringBuffer &bv = p0->getval()->toString(); const char *sv = bv.get(); int vlen = strlen(sv); while(klen+vlen+curlen+4>maxsize){ maxsize+=256; buf = (char *)realloc(buf,maxsize); } sprintf(buf+curlen,"%s=%s&",s,sv); curlen+=klen+vlen+2; } } buf[strlen(buf)-1]=0; // remove last & a->pushString(buf); free(buf); delete iter; } %wordargs perform A|curl (curl -- error|none) perform the transfer, use curl$data to get the data { CURLcode rv = curl_easy_perform(p0->c); if(rv == CURLE_OK) a->pushNone(); else { a->pushString(p0->buf); } } %wordargs data A|curl (curl -- data) get downloaded data (as string) { Value v; Types::tString->set(&v,p0->data); a->pushval()->copy(&v); } <|endoftext|>
<commit_before>#include "ssdt.h" #include "undocumented.h" #include "pe.h" #include "log.h" #include "ntdll.h" //structures struct SSDTStruct { LONG* pServiceTable; PVOID pCounterTable; #ifdef _WIN64 ULONGLONG NumberOfServices; #else ULONG NumberOfServices; #endif PCHAR pArgumentTable; }; //Based on: https://code.google.com/p/volatility/issues/detail?id=189#c2 static SSDTStruct* SSDTfind() { static PVOID SSDT = 0; if (!SSDT) { UNICODE_STRING routineName; #ifndef _WIN64 //x86 code RtlInitUnicodeString(&routineName, L"KeServiceDescriptorTable"); SSDT = MmGetSystemRoutineAddress(&routineName); #else //x64 code RtlInitUnicodeString(&routineName, L"KeAddSystemServiceTable"); PVOID KeASST = MmGetSystemRoutineAddress(&routineName); if (!KeASST) return 0; unsigned char function[1024]; unsigned int function_size = 0; RtlCopyMemory(function, KeASST, sizeof(function)); for (unsigned int i = 0; i < sizeof(function); i++) { if (function[i] == 0xC3) //ret { function_size = i + 1; break; } } if (!function_size) return 0; /* 000000014050EA4A 48 C1 E0 05 shl rax, 5 000000014050EA4E 48 83 BC 18 80 3A 36 00 00 cmp qword ptr [rax+rbx+363A80h], 0 <- we are looking for this instruction 000000014050EA57 0F 85 B2 5C 0A 00 jnz loc_1405B470F 000000014050EA5D 48 8D 8B C0 3A 36 00 lea rcx, rva KeServiceDescriptorTableShadow[rbx] 000000014050EA64 48 03 C8 add rcx, rax 000000014050EA67 48 83 39 00 cmp qword ptr [rcx], 0 */ unsigned int rvaSSDT = 0; for (unsigned int i = 0; i < function_size; i++) { if (((*(unsigned int*)(function + i)) & 0x00FFFFF0) == 0xBC8340 && !*(unsigned char*)(function + i + 8)) //4?83bc?? ???????? 00 cmp qword ptr [r?+r?+????????h],0 { rvaSSDT = *(unsigned int*)(function + i + 4); break; } } if (!rvaSSDT) return 0; Log("[TITANHIDE] SSDT RVA: 0x%X\n", rvaSSDT); PVOID base = Undocumented::GetKernelBase(); if (!base) { Log("[TITANHIDE] GetKernelBase() failed!\n"); return 0; } Log("[TITANHIDE] GetKernelBase()->0x%p\n", base); SSDT = (PVOID)((unsigned char*)base + rvaSSDT); #endif } return (SSDTStruct*)SSDT; } PVOID SSDT::GetFunctionAddress(const char* apiname) { //read address from SSDT SSDTStruct* SSDT = SSDTfind(); if (!SSDT) { Log("[TITANHIDE] SSDT not found...\n"); return 0; } ULONG_PTR SSDTbase = (ULONG_PTR)SSDT->pServiceTable; if (!SSDTbase) { Log("[TITANHIDE] ServiceTable not found...\n"); return 0; } ULONG readOffset = NTDLL::GetExportSsdtIndex(apiname); if (readOffset == -1) return 0; if (readOffset >= SSDT->NumberOfServices) { Log("[TITANHIDE] Invalid read offset...\n"); return 0; } #ifdef _WIN64 return (PVOID)((SSDT->pServiceTable[readOffset] >> 4) + SSDTbase); #else return (PVOID)SSDT->pServiceTable[readOffset]; #endif } static void InterlockedSet(LONG* Destination, LONG Source) { //Change memory properties. PMDL g_pmdl = IoAllocateMdl(Destination, sizeof(LONG), 0, 0, NULL); if (!g_pmdl) return; MmBuildMdlForNonPagedPool(g_pmdl); LONG* Mapped = (LONG*)MmMapLockedPages(g_pmdl, KernelMode); if (!Mapped) { IoFreeMdl(g_pmdl); return; } InterlockedExchange(Mapped, Source); //Restore memory properties. MmUnmapLockedPages((PVOID)Mapped, g_pmdl); IoFreeMdl(g_pmdl); } #ifdef _WIN64 static PVOID FindCaveAddress(PVOID CodeStart, ULONG CodeSize, ULONG CaveSize) { unsigned char* Code = (unsigned char*)CodeStart; for (unsigned int i = 0, j = 0; i < CodeSize; i++) { if (Code[i] == 0x90 || Code[i] == 0xCC) //NOP or INT3 j++; else j = 0; if (j == CaveSize) return (PVOID)((ULONG_PTR)CodeStart + i - CaveSize + 1); } return 0; } #endif //_WIN64 HOOK SSDT::Hook(const char* apiname, void* newfunc) { SSDTStruct* SSDT = SSDTfind(); if (!SSDT) { Log("[TITANHIDE] SSDT not found...\n"); return 0; } ULONG_PTR SSDTbase = (ULONG_PTR)SSDT->pServiceTable; if (!SSDTbase) { Log("[TITANHIDE] ServiceTable not found...\n"); return 0; } ULONG FunctionIndex = NTDLL::GetExportSsdtIndex(apiname); if (FunctionIndex == -1) return 0; if (FunctionIndex >= SSDT->NumberOfServices) { Log("[TITANHIDE] Invalid API offset...\n"); return 0; } HOOK hHook = 0; ULONG oldValue = SSDT->pServiceTable[FunctionIndex]; ULONG newValue; #ifdef _WIN64 /* x64 SSDT Hook; 1) find API addr 2) get code page+size 3) find cave address 4) hook cave address (using hooklib) 5) change SSDT value */ static ULONG CodeSize = 0; static PVOID CodeStart = 0; if (!CodeStart) { ULONG_PTR Lowest = SSDTbase; ULONG_PTR Highest = Lowest + 0x0FFFFFFF; Log("[TITANHIDE] Range: 0x%p-0x%p\n", Lowest, Highest); CodeSize = 0; CodeStart = PE::GetPageBase(Undocumented::GetKernelBase(), &CodeSize, (PVOID)((oldValue >> 4) + SSDTbase)); if (!CodeStart || !CodeSize) { Log("[TITANHIDE] PeGetPageBase failed...\n"); return 0; } Log("[TITANHIDE] CodeStart: 0x%p, CodeSize: 0x%X\n", CodeStart, CodeSize); if ((ULONG_PTR)CodeStart < Lowest) //start of the page is out of range (impossible, but whatever) { CodeSize -= (ULONG)(Lowest - (ULONG_PTR)CodeStart); CodeStart = (PVOID)Lowest; Log("[TITANHIDE] CodeStart: 0x%p, CodeSize: 0x%X\n", CodeStart, CodeSize); } Log("[TITANHIDE] Range: 0x%p-0x%p\n", CodeStart, (ULONG_PTR)CodeStart + CodeSize); } PVOID CaveAddress = FindCaveAddress(CodeStart, CodeSize, sizeof(HOOKOPCODES)); if (!CaveAddress) { Log("[TITANHIDE] FindCaveAddress failed...\n"); return 0; } Log("[TITANHIDE] CaveAddress: 0x%p\n", CaveAddress); hHook = Hooklib::Hook(CaveAddress, (void*)newfunc); if (!hHook) return 0; newValue = (ULONG)((ULONG_PTR)CaveAddress - SSDTbase); newValue = (newValue << 4) | oldValue & 0xF; //update HOOK structure hHook->SSDTindex = FunctionIndex; hHook->SSDTold = oldValue; hHook->SSDTnew = newValue; hHook->SSDTaddress = (oldValue >> 4) + SSDTbase; #else /* x86 SSDT Hook: 1) change SSDT value */ newValue = (ULONG)newfunc; hHook = (HOOK)RtlAllocateMemory(true, sizeof(hookstruct)); //update HOOK structure hHook->SSDTindex = FunctionIndex; hHook->SSDTold = oldValue; hHook->SSDTnew = newValue; hHook->SSDTaddress = oldValue; #endif InterlockedSet(&SSDT->pServiceTable[FunctionIndex], newValue); Log("[TITANHIDE] SSDThook(%s:0x%p, 0x%p)\n", apiname, hHook->SSDTold, hHook->SSDTnew); return hHook; } void SSDT::Hook(HOOK hHook) { if (!hHook) return; SSDTStruct* SSDT = SSDTfind(); if (!SSDT) { Log("[TITANHIDE] SSDT not found...\n"); return; } LONG* SSDT_Table = SSDT->pServiceTable; if (!SSDT_Table) { Log("[TITANHIDE] ServiceTable not found...\n"); return; } InterlockedSet(&SSDT_Table[hHook->SSDTindex], hHook->SSDTnew); } void SSDT::Unhook(HOOK hHook, bool free) { if (!hHook) return; SSDTStruct* SSDT = SSDTfind(); if (!SSDT) { Log("[TITANHIDE] SSDT not found...\n"); return; } LONG* SSDT_Table = SSDT->pServiceTable; if (!SSDT_Table) { Log("[TITANHIDE] ServiceTable not found...\n"); return; } InterlockedSet(&SSDT_Table[hHook->SSDTindex], hHook->SSDTold); #ifdef _WIN64 if (free) Hooklib::Unhook(hHook, true); #else UNREFERENCED_PARAMETER(free); #endif }<commit_msg>fixed a compilation error on x32<commit_after>#include "ssdt.h" #include "undocumented.h" #include "pe.h" #include "log.h" #include "ntdll.h" //structures struct SSDTStruct { LONG* pServiceTable; PVOID pCounterTable; #ifdef _WIN64 ULONGLONG NumberOfServices; #else ULONG NumberOfServices; #endif PCHAR pArgumentTable; }; //Based on: https://code.google.com/p/volatility/issues/detail?id=189#c2 static SSDTStruct* SSDTfind() { static PVOID SSDT = 0; if (!SSDT) { UNICODE_STRING routineName; #ifndef _WIN64 //x86 code RtlInitUnicodeString(&routineName, L"KeServiceDescriptorTable"); SSDT = MmGetSystemRoutineAddress(&routineName); #else //x64 code RtlInitUnicodeString(&routineName, L"KeAddSystemServiceTable"); PVOID KeASST = MmGetSystemRoutineAddress(&routineName); if (!KeASST) return 0; unsigned char function[1024]; unsigned int function_size = 0; RtlCopyMemory(function, KeASST, sizeof(function)); for (unsigned int i = 0; i < sizeof(function); i++) { if (function[i] == 0xC3) //ret { function_size = i + 1; break; } } if (!function_size) return 0; /* 000000014050EA4A 48 C1 E0 05 shl rax, 5 000000014050EA4E 48 83 BC 18 80 3A 36 00 00 cmp qword ptr [rax+rbx+363A80h], 0 <- we are looking for this instruction 000000014050EA57 0F 85 B2 5C 0A 00 jnz loc_1405B470F 000000014050EA5D 48 8D 8B C0 3A 36 00 lea rcx, rva KeServiceDescriptorTableShadow[rbx] 000000014050EA64 48 03 C8 add rcx, rax 000000014050EA67 48 83 39 00 cmp qword ptr [rcx], 0 */ unsigned int rvaSSDT = 0; for (unsigned int i = 0; i < function_size; i++) { if (((*(unsigned int*)(function + i)) & 0x00FFFFF0) == 0xBC8340 && !*(unsigned char*)(function + i + 8)) //4?83bc?? ???????? 00 cmp qword ptr [r?+r?+????????h],0 { rvaSSDT = *(unsigned int*)(function + i + 4); break; } } if (!rvaSSDT) return 0; Log("[TITANHIDE] SSDT RVA: 0x%X\n", rvaSSDT); PVOID base = Undocumented::GetKernelBase(); if (!base) { Log("[TITANHIDE] GetKernelBase() failed!\n"); return 0; } Log("[TITANHIDE] GetKernelBase()->0x%p\n", base); SSDT = (PVOID)((unsigned char*)base + rvaSSDT); #endif } return (SSDTStruct*)SSDT; } PVOID SSDT::GetFunctionAddress(const char* apiname) { //read address from SSDT SSDTStruct* SSDT = SSDTfind(); if (!SSDT) { Log("[TITANHIDE] SSDT not found...\n"); return 0; } ULONG_PTR SSDTbase = (ULONG_PTR)SSDT->pServiceTable; if (!SSDTbase) { Log("[TITANHIDE] ServiceTable not found...\n"); return 0; } ULONG readOffset = NTDLL::GetExportSsdtIndex(apiname); if (readOffset == -1) return 0; if (readOffset >= SSDT->NumberOfServices) { Log("[TITANHIDE] Invalid read offset...\n"); return 0; } #ifdef _WIN64 return (PVOID)((SSDT->pServiceTable[readOffset] >> 4) + SSDTbase); #else return (PVOID)SSDT->pServiceTable[readOffset]; #endif } static void InterlockedSet(LONG* Destination, LONG Source) { //Change memory properties. PMDL g_pmdl = IoAllocateMdl(Destination, sizeof(LONG), 0, 0, NULL); if (!g_pmdl) return; MmBuildMdlForNonPagedPool(g_pmdl); LONG* Mapped = (LONG*)MmMapLockedPages(g_pmdl, KernelMode); if (!Mapped) { IoFreeMdl(g_pmdl); return; } InterlockedExchange(Mapped, Source); //Restore memory properties. MmUnmapLockedPages((PVOID)Mapped, g_pmdl); IoFreeMdl(g_pmdl); } #ifdef _WIN64 static PVOID FindCaveAddress(PVOID CodeStart, ULONG CodeSize, ULONG CaveSize) { unsigned char* Code = (unsigned char*)CodeStart; for (unsigned int i = 0, j = 0; i < CodeSize; i++) { if (Code[i] == 0x90 || Code[i] == 0xCC) //NOP or INT3 j++; else j = 0; if (j == CaveSize) return (PVOID)((ULONG_PTR)CodeStart + i - CaveSize + 1); } return 0; } #endif //_WIN64 HOOK SSDT::Hook(const char* apiname, void* newfunc) { SSDTStruct* SSDT = SSDTfind(); if (!SSDT) { Log("[TITANHIDE] SSDT not found...\n"); return 0; } ULONG_PTR SSDTbase = (ULONG_PTR)SSDT->pServiceTable; if (!SSDTbase) { Log("[TITANHIDE] ServiceTable not found...\n"); return 0; } ULONG FunctionIndex = NTDLL::GetExportSsdtIndex(apiname); if (FunctionIndex == -1) return 0; if (FunctionIndex >= SSDT->NumberOfServices) { Log("[TITANHIDE] Invalid API offset...\n"); return 0; } HOOK hHook = 0; ULONG oldValue = SSDT->pServiceTable[FunctionIndex]; ULONG newValue; #ifdef _WIN64 /* x64 SSDT Hook; 1) find API addr 2) get code page+size 3) find cave address 4) hook cave address (using hooklib) 5) change SSDT value */ static ULONG CodeSize = 0; static PVOID CodeStart = 0; if (!CodeStart) { ULONG_PTR Lowest = SSDTbase; ULONG_PTR Highest = Lowest + 0x0FFFFFFF; Log("[TITANHIDE] Range: 0x%p-0x%p\n", Lowest, Highest); CodeSize = 0; CodeStart = PE::GetPageBase(Undocumented::GetKernelBase(), &CodeSize, (PVOID)((oldValue >> 4) + SSDTbase)); if (!CodeStart || !CodeSize) { Log("[TITANHIDE] PeGetPageBase failed...\n"); return 0; } Log("[TITANHIDE] CodeStart: 0x%p, CodeSize: 0x%X\n", CodeStart, CodeSize); if ((ULONG_PTR)CodeStart < Lowest) //start of the page is out of range (impossible, but whatever) { CodeSize -= (ULONG)(Lowest - (ULONG_PTR)CodeStart); CodeStart = (PVOID)Lowest; Log("[TITANHIDE] CodeStart: 0x%p, CodeSize: 0x%X\n", CodeStart, CodeSize); } Log("[TITANHIDE] Range: 0x%p-0x%p\n", CodeStart, (ULONG_PTR)CodeStart + CodeSize); } PVOID CaveAddress = FindCaveAddress(CodeStart, CodeSize, sizeof(HOOKOPCODES)); if (!CaveAddress) { Log("[TITANHIDE] FindCaveAddress failed...\n"); return 0; } Log("[TITANHIDE] CaveAddress: 0x%p\n", CaveAddress); hHook = Hooklib::Hook(CaveAddress, (void*)newfunc); if (!hHook) return 0; newValue = (ULONG)((ULONG_PTR)CaveAddress - SSDTbase); newValue = (newValue << 4) | oldValue & 0xF; //update HOOK structure hHook->SSDTindex = FunctionIndex; hHook->SSDTold = oldValue; hHook->SSDTnew = newValue; hHook->SSDTaddress = (oldValue >> 4) + SSDTbase; #else /* x86 SSDT Hook: 1) change SSDT value */ newValue = (ULONG)newfunc; hHook = (HOOK)RtlAllocateMemory(true, sizeof(HOOKSTRUCT)); //update HOOK structure hHook->SSDTindex = FunctionIndex; hHook->SSDTold = oldValue; hHook->SSDTnew = newValue; hHook->SSDTaddress = oldValue; #endif InterlockedSet(&SSDT->pServiceTable[FunctionIndex], newValue); Log("[TITANHIDE] SSDThook(%s:0x%p, 0x%p)\n", apiname, hHook->SSDTold, hHook->SSDTnew); return hHook; } void SSDT::Hook(HOOK hHook) { if (!hHook) return; SSDTStruct* SSDT = SSDTfind(); if (!SSDT) { Log("[TITANHIDE] SSDT not found...\n"); return; } LONG* SSDT_Table = SSDT->pServiceTable; if (!SSDT_Table) { Log("[TITANHIDE] ServiceTable not found...\n"); return; } InterlockedSet(&SSDT_Table[hHook->SSDTindex], hHook->SSDTnew); } void SSDT::Unhook(HOOK hHook, bool free) { if (!hHook) return; SSDTStruct* SSDT = SSDTfind(); if (!SSDT) { Log("[TITANHIDE] SSDT not found...\n"); return; } LONG* SSDT_Table = SSDT->pServiceTable; if (!SSDT_Table) { Log("[TITANHIDE] ServiceTable not found...\n"); return; } InterlockedSet(&SSDT_Table[hHook->SSDTindex], hHook->SSDTold); #ifdef _WIN64 if (free) Hooklib::Unhook(hHook, true); #else UNREFERENCED_PARAMETER(free); #endif }<|endoftext|>
<commit_before>#include <cassert> #include <cmath> #include "BankedMemory.h" #include "functions.h" using namespace Simulator; using namespace std; BankedMemory::Bank::Bank() : func(NULL), busy(false) { } BankedMemory::Bank::~Bank() { delete func; } void BankedMemory::Request::release() { if (refcount != NULL && --*refcount == 0) { delete[] (char*)data.data; delete refcount; } } BankedMemory::Request& BankedMemory::Request::operator =(const Request& req) { release(); refcount = req.refcount; callback = req.callback; write = req.write; address = req.address; data = req.data; ++*refcount; return *this; } BankedMemory::Request::Request(const Request& req) : refcount(NULL) { *this = req; } BankedMemory::Request::Request() { refcount = new unsigned long(1); data.data = NULL; } BankedMemory::Request::~Request() { release(); } void BankedMemory::registerListener(IMemoryCallback& callback) { m_caches.insert(&callback); } void BankedMemory::unregisterListener(IMemoryCallback& callback) { m_caches.erase(&callback); } size_t BankedMemory::GetQueueIndex(IMemoryCallback* callback) { return m_portmap.insert(make_pair(callback, m_portmap.size())).first->second; } size_t BankedMemory::GetBankFromAddress(MemAddr address) const { return (address >> 6) % m_banks.size(); } void BankedMemory::AddRequest(Pipeline& queue, const Request& request, bool data) { // Get the initial delay, independent of message size CycleNo now = getKernel()->getCycleNo(); CycleNo done = now + (CycleNo)log2(m_banks.size()); Pipeline::const_reverse_iterator p = queue.rbegin(); if (p != queue.rend() && done < p->first) { // We're waiting for another message to be sent, so skip the initial delay // (pretend our data comes after the data of the previous message) done = p->first; } if (data) { // This delay is the time is takes for the message body to traverse the network done += (request.data.size + m_config.sizeOfLine - 1) / m_config.sizeOfLine; } // At least one size for the 'header' done++; queue.insert(make_pair(done, request)); } Result BankedMemory::read(IMemoryCallback& callback, MemAddr address, void* data, MemSize size, MemTag tag) { if (size > SIZE_MAX) { throw InvalidArgumentException("Size argument too big"); } Pipeline& queue = m_incoming[ GetQueueIndex(&callback) ]; if (m_config.bufferSize == INFINITE || queue.size() < m_config.bufferSize) { COMMIT { Request request; request.address = address; request.callback = &callback; request.data.data = new char[ (size_t)size ]; request.data.size = size; request.data.tag = tag; request.write = false; AddRequest(queue, request, false); } return DELAYED; } return FAILED; } Result BankedMemory::write(IMemoryCallback& callback, MemAddr address, void* data, MemSize size, MemTag tag) { if (size > SIZE_MAX) { throw InvalidArgumentException("Size argument too big"); } Pipeline& queue = m_incoming[ GetQueueIndex(&callback) ]; if (m_config.bufferSize == INFINITE || queue.size() < m_config.bufferSize) { assert(tag.fid != INVALID_LFID); Request request; request.address = address; request.callback = &callback; request.data.data = new char[ (size_t)size ]; request.data.size = size; request.data.tag = tag; request.write = true; memcpy(request.data.data, data, (size_t)size); // Broadcast the snoop data for (set<IMemoryCallback*>::iterator p = m_caches.begin(); p != m_caches.end(); p++) { if (!(*p)->onMemorySnooped(request.address, request.data)) { return FAILED; } } COMMIT { // Calculate completion time AddRequest(queue, request, true); } return DELAYED; } return FAILED; } void BankedMemory::read(MemAddr address, void* data, MemSize size) { return VirtualMemory::read(address, data, size); } void BankedMemory::write(MemAddr address, const void* data, MemSize size, int perm) { return VirtualMemory::write(address, data, size, perm); } bool BankedMemory::checkPermissions(MemAddr address, MemSize size, int access) const { return VirtualMemory::CheckPermissions(address, size, access); } Result BankedMemory::onCycleWritePhase(unsigned int stateIndex) { CycleNo now = getKernel()->getCycleNo(); if (stateIndex < m_incoming.size() + m_outgoing.size()) { // Process a queue bool incoming = (stateIndex % 2); int index = (stateIndex / 2); vector<Pipeline>& queues = (incoming) ? m_incoming : m_outgoing; Pipeline& queue = queues[index]; Pipeline::iterator p = queue.begin(); if (p == queue.end()) { // Empty queue, nothing to do return DELAYED; } if (p->first <= now) { // This request has arrived, send it to a bank/cpu Request& request = p->second; if (incoming) { // Incoming pipeline, send it to a bank Bank& bank = m_banks[ GetBankFromAddress(request.address) ]; if (bank.busy || !bank.func->invoke(index)) { return FAILED; } COMMIT { // Calculate bank read/write delay CycleNo delay = m_config.baseRequestTime + m_config.timePerLine * (request.data.size + m_config.sizeOfLine - 1) / m_config.sizeOfLine; bank.request = request; bank.busy = true; bank.done = now + delay; } } else { // Outgoing pipeline, send it to the callback if (request.write) { if (!request.callback->onMemoryWriteCompleted(request.data.tag)) { return FAILED; } } else { if (!request.callback->onMemoryReadCompleted(request.data)) { return FAILED; } } } COMMIT{ queue.erase(p); } } } else { // Process a bank Bank& bank = m_banks[stateIndex - m_incoming.size() - m_outgoing.size()]; if (!bank.busy) { // Nothing to do return DELAYED; } if (bank.done <= now) { // This bank is done serving the request if (bank.request.write) { VirtualMemory::write(bank.request.address, bank.request.data.data, bank.request.data.size); } else { VirtualMemory::read(bank.request.address, bank.request.data.data, bank.request.data.size); } // Move it to the outgoing queue COMMIT { Pipeline& queue = m_outgoing[ GetQueueIndex(bank.request.callback) ]; AddRequest(queue, bank.request, !bank.request.write); bank.busy = false; } } } return SUCCESS; } BankedMemory::BankedMemory(Object* parent, Kernel& kernel, const std::string& name, const Config& config, size_t nProcs) : IComponent(parent, kernel, name, 2 * nProcs + config.numBanks), m_config(config), m_banks(config.numBanks), m_incoming(nProcs), m_outgoing(nProcs) { for (size_t i = 0; i < m_banks.size(); i++) { m_banks[i].func = new ArbitratedWriteFunction(kernel); } } <commit_msg>Fixed iterator compilation problem on Mac<commit_after>#include <cassert> #include <cmath> #include "BankedMemory.h" #include "functions.h" using namespace Simulator; using namespace std; BankedMemory::Bank::Bank() : func(NULL), busy(false) { } BankedMemory::Bank::~Bank() { delete func; } void BankedMemory::Request::release() { if (refcount != NULL && --*refcount == 0) { delete[] (char*)data.data; delete refcount; } } BankedMemory::Request& BankedMemory::Request::operator =(const Request& req) { release(); refcount = req.refcount; callback = req.callback; write = req.write; address = req.address; data = req.data; ++*refcount; return *this; } BankedMemory::Request::Request(const Request& req) : refcount(NULL) { *this = req; } BankedMemory::Request::Request() { refcount = new unsigned long(1); data.data = NULL; } BankedMemory::Request::~Request() { release(); } void BankedMemory::registerListener(IMemoryCallback& callback) { m_caches.insert(&callback); } void BankedMemory::unregisterListener(IMemoryCallback& callback) { m_caches.erase(&callback); } size_t BankedMemory::GetQueueIndex(IMemoryCallback* callback) { return m_portmap.insert(make_pair(callback, m_portmap.size())).first->second; } size_t BankedMemory::GetBankFromAddress(MemAddr address) const { return (address >> 6) % m_banks.size(); } void BankedMemory::AddRequest(Pipeline& queue, const Request& request, bool data) { // Get the initial delay, independent of message size CycleNo now = getKernel()->getCycleNo(); CycleNo done = now + (CycleNo)log2(m_banks.size()); Pipeline::reverse_iterator p = queue.rbegin(); if (p != queue.rend() && done < p->first) { // We're waiting for another message to be sent, so skip the initial delay // (pretend our data comes after the data of the previous message) done = p->first; } if (data) { // This delay is the time is takes for the message body to traverse the network done += (request.data.size + m_config.sizeOfLine - 1) / m_config.sizeOfLine; } // At least one size for the 'header' done++; queue.insert(make_pair(done, request)); } Result BankedMemory::read(IMemoryCallback& callback, MemAddr address, void* data, MemSize size, MemTag tag) { if (size > SIZE_MAX) { throw InvalidArgumentException("Size argument too big"); } Pipeline& queue = m_incoming[ GetQueueIndex(&callback) ]; if (m_config.bufferSize == INFINITE || queue.size() < m_config.bufferSize) { COMMIT { Request request; request.address = address; request.callback = &callback; request.data.data = new char[ (size_t)size ]; request.data.size = size; request.data.tag = tag; request.write = false; AddRequest(queue, request, false); } return DELAYED; } return FAILED; } Result BankedMemory::write(IMemoryCallback& callback, MemAddr address, void* data, MemSize size, MemTag tag) { if (size > SIZE_MAX) { throw InvalidArgumentException("Size argument too big"); } Pipeline& queue = m_incoming[ GetQueueIndex(&callback) ]; if (m_config.bufferSize == INFINITE || queue.size() < m_config.bufferSize) { assert(tag.fid != INVALID_LFID); Request request; request.address = address; request.callback = &callback; request.data.data = new char[ (size_t)size ]; request.data.size = size; request.data.tag = tag; request.write = true; memcpy(request.data.data, data, (size_t)size); // Broadcast the snoop data for (set<IMemoryCallback*>::iterator p = m_caches.begin(); p != m_caches.end(); p++) { if (!(*p)->onMemorySnooped(request.address, request.data)) { return FAILED; } } COMMIT { // Calculate completion time AddRequest(queue, request, true); } return DELAYED; } return FAILED; } void BankedMemory::read(MemAddr address, void* data, MemSize size) { return VirtualMemory::read(address, data, size); } void BankedMemory::write(MemAddr address, const void* data, MemSize size, int perm) { return VirtualMemory::write(address, data, size, perm); } bool BankedMemory::checkPermissions(MemAddr address, MemSize size, int access) const { return VirtualMemory::CheckPermissions(address, size, access); } Result BankedMemory::onCycleWritePhase(unsigned int stateIndex) { CycleNo now = getKernel()->getCycleNo(); if (stateIndex < m_incoming.size() + m_outgoing.size()) { // Process a queue bool incoming = (stateIndex % 2); int index = (stateIndex / 2); vector<Pipeline>& queues = (incoming) ? m_incoming : m_outgoing; Pipeline& queue = queues[index]; Pipeline::iterator p = queue.begin(); if (p == queue.end()) { // Empty queue, nothing to do return DELAYED; } if (p->first <= now) { // This request has arrived, send it to a bank/cpu Request& request = p->second; if (incoming) { // Incoming pipeline, send it to a bank Bank& bank = m_banks[ GetBankFromAddress(request.address) ]; if (bank.busy || !bank.func->invoke(index)) { return FAILED; } COMMIT { // Calculate bank read/write delay CycleNo delay = m_config.baseRequestTime + m_config.timePerLine * (request.data.size + m_config.sizeOfLine - 1) / m_config.sizeOfLine; bank.request = request; bank.busy = true; bank.done = now + delay; } } else { // Outgoing pipeline, send it to the callback if (request.write) { if (!request.callback->onMemoryWriteCompleted(request.data.tag)) { return FAILED; } } else { if (!request.callback->onMemoryReadCompleted(request.data)) { return FAILED; } } } COMMIT{ queue.erase(p); } } } else { // Process a bank Bank& bank = m_banks[stateIndex - m_incoming.size() - m_outgoing.size()]; if (!bank.busy) { // Nothing to do return DELAYED; } if (bank.done <= now) { // This bank is done serving the request if (bank.request.write) { VirtualMemory::write(bank.request.address, bank.request.data.data, bank.request.data.size); } else { VirtualMemory::read(bank.request.address, bank.request.data.data, bank.request.data.size); } // Move it to the outgoing queue COMMIT { Pipeline& queue = m_outgoing[ GetQueueIndex(bank.request.callback) ]; AddRequest(queue, bank.request, !bank.request.write); bank.busy = false; } } } return SUCCESS; } BankedMemory::BankedMemory(Object* parent, Kernel& kernel, const std::string& name, const Config& config, size_t nProcs) : IComponent(parent, kernel, name, 2 * nProcs + config.numBanks), m_config(config), m_banks(config.numBanks), m_incoming(nProcs), m_outgoing(nProcs) { for (size_t i = 0; i < m_banks.size(); i++) { m_banks[i].func = new ArbitratedWriteFunction(kernel); } } <|endoftext|>
<commit_before>/* * SimpleGeoSphereRenderer.cpp * * Copyright (C) 2012 by CGV (TU Dresden) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "vislib/graphics/gl/IncludeAllGL.h" #include "mmcore/moldyn/SimpleGeoSphereRenderer.h" #include "mmcore/view/CallRender3D.h" #include "vislib/graphics/gl/ShaderSource.h" #include "mmcore/CoreInstance.h" #include "mmcore/view/CallGetTransferFunction.h" #include "vislib/math/Matrix.h" #include "vislib/math/ShallowMatrix.h" using namespace megamol::core; /* * moldyn::SimpleGeoSphereRenderer::SimpleGeoSphereRenderer */ moldyn::SimpleGeoSphereRenderer::SimpleGeoSphereRenderer(void) : AbstractSimpleSphereRenderer(), sphereShader() { // intentionally empty } /* * moldyn::SimpleGeoSphereRenderer::~SimpleGeoSphereRenderer */ moldyn::SimpleGeoSphereRenderer::~SimpleGeoSphereRenderer(void) { this->Release(); } /* * moldyn::SimpleGeoSphereRenderer::create */ bool moldyn::SimpleGeoSphereRenderer::create(void) { using vislib::sys::Log; ASSERT(IsAvailable()); vislib::graphics::gl::ShaderSource vert, geom, frag; if (!instance()->ShaderSourceFactory().MakeShaderSource("simplegeosphere::vertex", vert)) { return false; } if (!instance()->ShaderSourceFactory().MakeShaderSource("simplegeosphere::geometry", geom)) { return false; } if (!instance()->ShaderSourceFactory().MakeShaderSource("simplegeosphere::fragment", frag)) { return false; } const char *buildState = "compile"; try { if (!this->sphereShader.Compile(vert.Code(), vert.Count(), geom.Code(), geom.Count(), frag.Code(), frag.Count())) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to compile sphere shader: Unknown error\n"); return false; } // not needed any more because its version 1.5 GLSL //buildState = "setup"; //this->sphereShader.SetProgramParameter(GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS); //this->sphereShader.SetProgramParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP); //this->sphereShader.SetProgramParameter(GL_GEOMETRY_VERTICES_OUT_EXT, 4); buildState = "link"; if (!this->sphereShader.Link()) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to link sphere shader: Unknown error\n"); return false; } } catch(vislib::graphics::gl::AbstractOpenGLShader::CompileException ce) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to %s sphere shader (@%s): %s\n", buildState, vislib::graphics::gl::AbstractOpenGLShader::CompileException::CompileActionName( ce.FailedAction()) ,ce.GetMsgA()); return false; } catch(vislib::Exception e) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to %s sphere shader: %s\n", buildState, e.GetMsgA()); return false; } catch(...) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to %s sphere shader: Unknown exception\n", buildState); return false; } return AbstractSimpleSphereRenderer::create(); } /* * moldyn::SimpleGeoSphereRenderer::release */ void moldyn::SimpleGeoSphereRenderer::release(void) { this->sphereShader.Release(); AbstractSimpleSphereRenderer::release(); } /* * moldyn::SimpleGeoSphereRenderer::Render */ bool moldyn::SimpleGeoSphereRenderer::Render(Call& call) { view::CallRender3D *cr = dynamic_cast<view::CallRender3D*>(&call); if (cr == NULL) return false; float scaling = 1.0f; MultiParticleDataCall *c2 = this->getData(static_cast<unsigned int>(cr->Time()), scaling); if (c2 == NULL) return false; float clipDat[4]; float clipCol[4]; this->getClipData(clipDat, clipCol); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_VERTEX_PROGRAM_TWO_SIDE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE_ARB); glScalef(scaling, scaling, scaling); float viewportStuff[4]; ::glGetFloatv(GL_VIEWPORT, viewportStuff); glPointSize(vislib::math::Max(viewportStuff[2], viewportStuff[3])); if (viewportStuff[2] < 1.0f) viewportStuff[2] = 1.0f; if (viewportStuff[3] < 1.0f) viewportStuff[3] = 1.0f; viewportStuff[2] = 2.0f / viewportStuff[2]; viewportStuff[3] = 2.0f / viewportStuff[3]; // Get GL_MODELVIEW matrix GLfloat modelMatrix_column[16]; glGetFloatv(GL_MODELVIEW_MATRIX, modelMatrix_column); vislib::math::ShallowMatrix<GLfloat, 4, vislib::math::COLUMN_MAJOR> modelMatrix(&modelMatrix_column[0]); // Get GL_PROJECTION matrix GLfloat projMatrix_column[16]; glGetFloatv(GL_PROJECTION_MATRIX, projMatrix_column); vislib::math::ShallowMatrix<GLfloat, 4, vislib::math::COLUMN_MAJOR> projMatrix(&projMatrix_column[0]); // Compute modelviewprojection matrix vislib::math::Matrix<GLfloat, 4, vislib::math::ROW_MAJOR> modelProjMatrix = projMatrix * modelMatrix; // Get light position GLfloat lightPos[4]; glGetLightfv(GL_LIGHT0, GL_POSITION, lightPos); this->sphereShader.Enable(); // Set shader variables glUniform4fv(this->sphereShader.ParameterLocation("viewAttr"), 1, viewportStuff); glUniform3fv(this->sphereShader.ParameterLocation("camIn"), 1, cr->GetCameraParameters()->Front().PeekComponents()); glUniform3fv(this->sphereShader.ParameterLocation("camRight"), 1, cr->GetCameraParameters()->Right().PeekComponents()); glUniform3fv(this->sphereShader.ParameterLocation("camUp"), 1, cr->GetCameraParameters()->Up().PeekComponents()); glUniformMatrix4fv(this->sphereShader.ParameterLocation("modelview"), 1, false, modelMatrix_column); glUniformMatrix4fv(this->sphereShader.ParameterLocation("proj"), 1, false, projMatrix_column); glUniform4fv(this->sphereShader.ParameterLocation("lightPos"), 1, lightPos); glUniform4fv(this->sphereShader.ParameterLocation("clipDat"), 1, clipDat); glUniform4fv(this->sphereShader.ParameterLocation("clipCol"), 1, clipCol); // Vertex attributes GLint vertexPos = glGetAttribLocation(this->sphereShader, "vertex"); GLint vertexColor = glGetAttribLocation(this->sphereShader, "color"); for (unsigned int i = 0; i < c2->GetParticleListCount(); i++) { MultiParticleDataCall::Particles &parts = c2->AccessParticles(i); float minC = 0.0f, maxC = 0.0f; unsigned int colTabSize = 0; // colour switch (parts.GetColourDataType()) { case MultiParticleDataCall::Particles::COLDATA_NONE: { const unsigned char* gc = parts.GetGlobalColour(); ::glVertexAttrib3d(vertexColor, static_cast<double>(gc[0]) / 255.0, static_cast<double>(gc[1]) / 255.0, static_cast<double>(gc[2]) / 255.0); } break; case MultiParticleDataCall::Particles::COLDATA_UINT8_RGB: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 3, GL_UNSIGNED_BYTE, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_UINT8_RGBA: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_FLOAT_RGB: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 3, GL_FLOAT, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_FLOAT_RGBA: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 4, GL_FLOAT, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_FLOAT_I: { ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 1, GL_FLOAT, GL_FALSE, parts.GetColourDataStride(), parts.GetColourData()); glEnable(GL_TEXTURE_1D); view::CallGetTransferFunction *cgtf = this->getTFSlot.CallAs<view::CallGetTransferFunction>(); if ((cgtf != NULL) && ((*cgtf)())) { glBindTexture(GL_TEXTURE_1D, cgtf->OpenGLTexture()); colTabSize = cgtf->TextureSize(); } else { glBindTexture(GL_TEXTURE_1D, this->greyTF); colTabSize = 2; } glUniform1i(this->sphereShader.ParameterLocation("colTab"), 0); minC = parts.GetMinColourIndexValue(); maxC = parts.GetMaxColourIndexValue(); } break; default: ::glVertexAttrib3f(vertexColor, 0.5f, 0.5f, 0.5f); break; } // radius and position switch (parts.GetVertexDataType()) { case MultiParticleDataCall::Particles::VERTDATA_NONE: continue; case MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZ: ::glEnableVertexAttribArray(vertexPos); ::glVertexAttribPointer(vertexPos, 3, GL_FLOAT, GL_FALSE, parts.GetVertexDataStride(), parts.GetVertexData()); ::glUniform4f(this->sphereShader.ParameterLocation("inConsts1"), parts.GetGlobalRadius(), minC, maxC, float(colTabSize)); break; case MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR: ::glEnableVertexAttribArray(vertexPos); ::glVertexAttribPointer(vertexPos, 4, GL_FLOAT, GL_FALSE, parts.GetVertexDataStride(), parts.GetVertexData()); ::glUniform4f(this->sphereShader.ParameterLocation("inConsts1"), -1.0f, minC, maxC, float(colTabSize)); break; default: continue; } ::glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(parts.GetCount())); ::glDisableVertexAttribArray(vertexPos); ::glDisableVertexAttribArray(vertexColor); glDisable(GL_TEXTURE_1D); } c2->Unlock(); this->sphereShader.Disable(); return true; } <commit_msg>Introduced MMPLD 1.3 to SimpleGeoSphereRenderer<commit_after>/* * SimpleGeoSphereRenderer.cpp * * Copyright (C) 2012 by CGV (TU Dresden) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "vislib/graphics/gl/IncludeAllGL.h" #include "mmcore/moldyn/SimpleGeoSphereRenderer.h" #include "mmcore/view/CallRender3D.h" #include "vislib/graphics/gl/ShaderSource.h" #include "mmcore/CoreInstance.h" #include "mmcore/view/CallGetTransferFunction.h" #include "vislib/math/Matrix.h" #include "vislib/math/ShallowMatrix.h" using namespace megamol::core; /* * moldyn::SimpleGeoSphereRenderer::SimpleGeoSphereRenderer */ moldyn::SimpleGeoSphereRenderer::SimpleGeoSphereRenderer(void) : AbstractSimpleSphereRenderer(), sphereShader() { // intentionally empty } /* * moldyn::SimpleGeoSphereRenderer::~SimpleGeoSphereRenderer */ moldyn::SimpleGeoSphereRenderer::~SimpleGeoSphereRenderer(void) { this->Release(); } /* * moldyn::SimpleGeoSphereRenderer::create */ bool moldyn::SimpleGeoSphereRenderer::create(void) { using vislib::sys::Log; ASSERT(IsAvailable()); vislib::graphics::gl::ShaderSource vert, geom, frag; if (!instance()->ShaderSourceFactory().MakeShaderSource("simplegeosphere::vertex", vert)) { return false; } if (!instance()->ShaderSourceFactory().MakeShaderSource("simplegeosphere::geometry", geom)) { return false; } if (!instance()->ShaderSourceFactory().MakeShaderSource("simplegeosphere::fragment", frag)) { return false; } const char *buildState = "compile"; try { if (!this->sphereShader.Compile(vert.Code(), vert.Count(), geom.Code(), geom.Count(), frag.Code(), frag.Count())) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to compile sphere shader: Unknown error\n"); return false; } // not needed any more because its version 1.5 GLSL //buildState = "setup"; //this->sphereShader.SetProgramParameter(GL_GEOMETRY_INPUT_TYPE_EXT, GL_POINTS); //this->sphereShader.SetProgramParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_TRIANGLE_STRIP); //this->sphereShader.SetProgramParameter(GL_GEOMETRY_VERTICES_OUT_EXT, 4); buildState = "link"; if (!this->sphereShader.Link()) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to link sphere shader: Unknown error\n"); return false; } } catch(vislib::graphics::gl::AbstractOpenGLShader::CompileException ce) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to %s sphere shader (@%s): %s\n", buildState, vislib::graphics::gl::AbstractOpenGLShader::CompileException::CompileActionName( ce.FailedAction()) ,ce.GetMsgA()); return false; } catch(vislib::Exception e) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to %s sphere shader: %s\n", buildState, e.GetMsgA()); return false; } catch(...) { vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "Unable to %s sphere shader: Unknown exception\n", buildState); return false; } return AbstractSimpleSphereRenderer::create(); } /* * moldyn::SimpleGeoSphereRenderer::release */ void moldyn::SimpleGeoSphereRenderer::release(void) { this->sphereShader.Release(); AbstractSimpleSphereRenderer::release(); } /* * moldyn::SimpleGeoSphereRenderer::Render */ bool moldyn::SimpleGeoSphereRenderer::Render(Call& call) { view::CallRender3D *cr = dynamic_cast<view::CallRender3D*>(&call); if (cr == NULL) return false; float scaling = 1.0f; MultiParticleDataCall *c2 = this->getData(static_cast<unsigned int>(cr->Time()), scaling); if (c2 == NULL) return false; float clipDat[4]; float clipCol[4]; this->getClipData(clipDat, clipCol); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_VERTEX_PROGRAM_TWO_SIDE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE_ARB); glScalef(scaling, scaling, scaling); float viewportStuff[4]; ::glGetFloatv(GL_VIEWPORT, viewportStuff); glPointSize(vislib::math::Max(viewportStuff[2], viewportStuff[3])); if (viewportStuff[2] < 1.0f) viewportStuff[2] = 1.0f; if (viewportStuff[3] < 1.0f) viewportStuff[3] = 1.0f; viewportStuff[2] = 2.0f / viewportStuff[2]; viewportStuff[3] = 2.0f / viewportStuff[3]; // Get GL_MODELVIEW matrix GLfloat modelMatrix_column[16]; glGetFloatv(GL_MODELVIEW_MATRIX, modelMatrix_column); vislib::math::ShallowMatrix<GLfloat, 4, vislib::math::COLUMN_MAJOR> modelMatrix(&modelMatrix_column[0]); // Get GL_PROJECTION matrix GLfloat projMatrix_column[16]; glGetFloatv(GL_PROJECTION_MATRIX, projMatrix_column); vislib::math::ShallowMatrix<GLfloat, 4, vislib::math::COLUMN_MAJOR> projMatrix(&projMatrix_column[0]); // Compute modelviewprojection matrix vislib::math::Matrix<GLfloat, 4, vislib::math::ROW_MAJOR> modelProjMatrix = projMatrix * modelMatrix; // Get light position GLfloat lightPos[4]; glGetLightfv(GL_LIGHT0, GL_POSITION, lightPos); this->sphereShader.Enable(); // Set shader variables glUniform4fv(this->sphereShader.ParameterLocation("viewAttr"), 1, viewportStuff); glUniform3fv(this->sphereShader.ParameterLocation("camIn"), 1, cr->GetCameraParameters()->Front().PeekComponents()); glUniform3fv(this->sphereShader.ParameterLocation("camRight"), 1, cr->GetCameraParameters()->Right().PeekComponents()); glUniform3fv(this->sphereShader.ParameterLocation("camUp"), 1, cr->GetCameraParameters()->Up().PeekComponents()); glUniformMatrix4fv(this->sphereShader.ParameterLocation("modelview"), 1, false, modelMatrix_column); glUniformMatrix4fv(this->sphereShader.ParameterLocation("proj"), 1, false, projMatrix_column); glUniform4fv(this->sphereShader.ParameterLocation("lightPos"), 1, lightPos); glUniform4fv(this->sphereShader.ParameterLocation("clipDat"), 1, clipDat); glUniform4fv(this->sphereShader.ParameterLocation("clipCol"), 1, clipCol); // Vertex attributes GLint vertexPos = glGetAttribLocation(this->sphereShader, "vertex"); GLint vertexColor = glGetAttribLocation(this->sphereShader, "color"); for (unsigned int i = 0; i < c2->GetParticleListCount(); i++) { MultiParticleDataCall::Particles &parts = c2->AccessParticles(i); float minC = 0.0f, maxC = 0.0f; unsigned int colTabSize = 0; // colour switch (parts.GetColourDataType()) { case MultiParticleDataCall::Particles::COLDATA_NONE: { const unsigned char* gc = parts.GetGlobalColour(); ::glVertexAttrib3d(vertexColor, static_cast<double>(gc[0]) / 255.0, static_cast<double>(gc[1]) / 255.0, static_cast<double>(gc[2]) / 255.0); } break; case MultiParticleDataCall::Particles::COLDATA_UINT8_RGB: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 3, GL_UNSIGNED_BYTE, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_UINT8_RGBA: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_FLOAT_RGB: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 3, GL_FLOAT, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_FLOAT_RGBA: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 4, GL_FLOAT, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_SHORT_RGBA: ::glEnableVertexAttribArray(vertexColor); ::glVertexAttribPointer(vertexColor, 4, GL_SHORT, GL_TRUE, parts.GetColourDataStride(), parts.GetColourData()); break; case MultiParticleDataCall::Particles::COLDATA_FLOAT_I: case MultiParticleDataCall::Particles::COLDATA_DOUBLE_I: { ::glEnableVertexAttribArray(vertexColor); if (MultiParticleDataCall::Particles::COLDATA_FLOAT_I) { ::glVertexAttribPointer(vertexColor, 1, GL_FLOAT, GL_FALSE, parts.GetColourDataStride(), parts.GetColourData()); } else { glVertexAttribPointer(vertexColor, 1, GL_DOUBLE, GL_FALSE, parts.GetColourDataStride(), parts.GetColourData()); } glEnable(GL_TEXTURE_1D); view::CallGetTransferFunction *cgtf = this->getTFSlot.CallAs<view::CallGetTransferFunction>(); if ((cgtf != NULL) && ((*cgtf)())) { glBindTexture(GL_TEXTURE_1D, cgtf->OpenGLTexture()); colTabSize = cgtf->TextureSize(); } else { glBindTexture(GL_TEXTURE_1D, this->greyTF); colTabSize = 2; } glUniform1i(this->sphereShader.ParameterLocation("colTab"), 0); minC = parts.GetMinColourIndexValue(); maxC = parts.GetMaxColourIndexValue(); } break; default: ::glVertexAttrib3f(vertexColor, 0.5f, 0.5f, 0.5f); break; } // radius and position switch (parts.GetVertexDataType()) { case MultiParticleDataCall::Particles::VERTDATA_NONE: continue; case MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZ: ::glEnableVertexAttribArray(vertexPos); ::glVertexAttribPointer(vertexPos, 3, GL_FLOAT, GL_FALSE, parts.GetVertexDataStride(), parts.GetVertexData()); ::glUniform4f(this->sphereShader.ParameterLocation("inConsts1"), parts.GetGlobalRadius(), minC, maxC, float(colTabSize)); break; case MultiParticleDataCall::Particles::VERTDATA_DOUBLE_XYZ: ::glEnableVertexAttribArray(vertexPos); ::glVertexAttribPointer(vertexPos, 3, GL_DOUBLE, GL_FALSE, parts.GetVertexDataStride(), parts.GetVertexData()); ::glUniform4f(this->sphereShader.ParameterLocation("inConsts1"), parts.GetGlobalRadius(), minC, maxC, float(colTabSize)); break; case MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR: ::glEnableVertexAttribArray(vertexPos); ::glVertexAttribPointer(vertexPos, 4, GL_FLOAT, GL_FALSE, parts.GetVertexDataStride(), parts.GetVertexData()); ::glUniform4f(this->sphereShader.ParameterLocation("inConsts1"), -1.0f, minC, maxC, float(colTabSize)); break; default: continue; } ::glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(parts.GetCount())); ::glDisableVertexAttribArray(vertexPos); ::glDisableVertexAttribArray(vertexColor); glDisable(GL_TEXTURE_1D); } c2->Unlock(); this->sphereShader.Disable(); return true; } <|endoftext|>
<commit_before>/*========================================================================= Program: NeuroLib (DTI command line tools) Language: C++ Date: $Date: 2008-07-02 15:54:54 $ Version: $Revision: 1.5 $ Author: Casey Goodlett (gcasey@sci.utah.edu) Copyright (c) Casey Goodlett. All rights reserved. See NeuroLibCopyright.txt or http://www.ia.unc.edu/dev/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <exception> #include <cassert> #include <itkVectorImage.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkResampleImageFilter.h> #include <itkImageToVectorImageFilter.h> #include <itkNthElementImageAdaptor.h> #include "itkVectorBSplineInterpolateImageFunction.h" #include "transforms.h" int main(int argc, char* argv[]) { // This software reads a vectorized .nrrd file performs a // transformation and updates the embedded gradient strings typedef double RealType; typedef double TransformRealType; typedef itk::AffineTransform<TransformRealType,3> AffineTransformType; const unsigned int DIM = 3; typedef unsigned short DWIPixelType; typedef itk::VectorImage<DWIPixelType, DIM> VectorImageType; typedef itk::Image<DWIPixelType, DIM> ComponentImageType; if(argc != 4) { std::cerr << "Usage: " << argv[0] << " infile outfile transform" << std::endl; std::cerr << "This program transform a vector image and updates the gradient" << " directions if they are specified using the NAMIC convention for DWI data"; return EXIT_FAILURE; } const std::string infile = argv[1]; const std::string outfile = argv[2]; const std::string transformfile = argv[3]; typedef itk::ImageFileReader<VectorImageType> ImageFileReaderType; ImageFileReaderType::Pointer reader = ImageFileReaderType::New(); reader->SetFileName(infile); try { reader->Update(); } catch (itk::ExceptionObject & e) { std::cerr << e <<std::endl; return EXIT_FAILURE; } VectorImageType::Pointer dwimg = reader->GetOutput(); AffineTransformType::Pointer transform = NULL; vnl_matrix<TransformRealType> R(3,3,0); if (transformfile.rfind(".dof") != std::string::npos) { // Use RView transform file reader RViewTransform<TransformRealType> dof(readDOFFile<TransformRealType>(transformfile)); // image transform transform = createITKAffine(dof, dwimg->GetLargestPossibleRegion().GetSize(), dwimg->GetSpacing(), dwimg->GetOrigin()); // gradient transform // g' = R g R = vnl_matrix_inverse<TransformRealType>(transform->GetMatrix().GetVnlMatrix()); } else { // Assume ITK transform std::cerr << "ITK transform not implemented" << std::endl; return EXIT_FAILURE; } // Transform components of dwi image // TODO: this really isnt that awesome or memory efficient a way of // doing things. const unsigned int vectorlength = reader->GetOutput()->GetVectorLength(); assert(vectorlength > 6); typedef itk::NthElementImageAdaptor<VectorImageType, unsigned int> VectorElementAdaptorType; VectorElementAdaptorType::Pointer adaptor = VectorElementAdaptorType::New(); adaptor->SetImage(reader->GetOutput()); typedef itk::ImageToVectorImageFilter<ComponentImageType> VectorComposeFilterType; VectorComposeFilterType::Pointer vcompose = VectorComposeFilterType::New(); typedef itk::ResampleImageFilter<VectorElementAdaptorType,ComponentImageType> ResamplerType; ResamplerType::Pointer resampler = ResamplerType::New(); for(unsigned int i = 0; i < vectorlength; i++) { // Transform the ith component of the vector image adaptor->SelectNthElement(i); adaptor->Update(); resampler->SetInput(adaptor); resampler->SetTransform(transform); resampler->SetOutputSpacing(reader->GetOutput()->GetSpacing()); resampler->SetOutputOrigin(reader->GetOutput()->GetOrigin()); resampler->SetSize(reader->GetOutput()->GetLargestPossibleRegion().GetSize()); resampler->Update(); vcompose->SetNthInput(i,resampler->GetOutput()); } vcompose->Update(); // Transform gradient directions // write output typedef itk::ImageFileWriter<VectorImageType> ImageFileWriterType; ImageFileWriterType::Pointer writer = ImageFileWriterType::New(); writer->SetInput(vcompose->GetOutput()); writer->SetFileName(outfile); try { writer->Update(); } catch (itk::ExceptionObject & e) { std::cerr << e << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>COMP: Change the call of SetNthInput to SetInput as a workaround to a recent change in ITK which removed SetNthInput.<commit_after>/*========================================================================= Program: NeuroLib (DTI command line tools) Language: C++ Date: $Date: 2008-11-24 22:09:26 $ Version: $Revision: 1.6 $ Author: Casey Goodlett (gcasey@sci.utah.edu) Copyright (c) Casey Goodlett. All rights reserved. See NeuroLibCopyright.txt or http://www.ia.unc.edu/dev/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <exception> #include <cassert> #include <itkVectorImage.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkResampleImageFilter.h> #include <itkImageToVectorImageFilter.h> #include <itkNthElementImageAdaptor.h> #include "itkVectorBSplineInterpolateImageFunction.h" #include "transforms.h" int main(int argc, char* argv[]) { // This software reads a vectorized .nrrd file performs a // transformation and updates the embedded gradient strings typedef double RealType; typedef double TransformRealType; typedef itk::AffineTransform<TransformRealType,3> AffineTransformType; const unsigned int DIM = 3; typedef unsigned short DWIPixelType; typedef itk::VectorImage<DWIPixelType, DIM> VectorImageType; typedef itk::Image<DWIPixelType, DIM> ComponentImageType; if(argc != 4) { std::cerr << "Usage: " << argv[0] << " infile outfile transform" << std::endl; std::cerr << "This program transform a vector image and updates the gradient" << " directions if they are specified using the NAMIC convention for DWI data"; return EXIT_FAILURE; } const std::string infile = argv[1]; const std::string outfile = argv[2]; const std::string transformfile = argv[3]; typedef itk::ImageFileReader<VectorImageType> ImageFileReaderType; ImageFileReaderType::Pointer reader = ImageFileReaderType::New(); reader->SetFileName(infile); try { reader->Update(); } catch (itk::ExceptionObject & e) { std::cerr << e <<std::endl; return EXIT_FAILURE; } VectorImageType::Pointer dwimg = reader->GetOutput(); AffineTransformType::Pointer transform = NULL; vnl_matrix<TransformRealType> R(3,3,0); if (transformfile.rfind(".dof") != std::string::npos) { // Use RView transform file reader RViewTransform<TransformRealType> dof(readDOFFile<TransformRealType>(transformfile)); // image transform transform = createITKAffine(dof, dwimg->GetLargestPossibleRegion().GetSize(), dwimg->GetSpacing(), dwimg->GetOrigin()); // gradient transform // g' = R g R = vnl_matrix_inverse<TransformRealType>(transform->GetMatrix().GetVnlMatrix()); } else { // Assume ITK transform std::cerr << "ITK transform not implemented" << std::endl; return EXIT_FAILURE; } // Transform components of dwi image // TODO: this really isnt that awesome or memory efficient a way of // doing things. const unsigned int vectorlength = reader->GetOutput()->GetVectorLength(); assert(vectorlength > 6); typedef itk::NthElementImageAdaptor<VectorImageType, unsigned int> VectorElementAdaptorType; VectorElementAdaptorType::Pointer adaptor = VectorElementAdaptorType::New(); adaptor->SetImage(reader->GetOutput()); typedef itk::ImageToVectorImageFilter<ComponentImageType> VectorComposeFilterType; VectorComposeFilterType::Pointer vcompose = VectorComposeFilterType::New(); typedef itk::ResampleImageFilter<VectorElementAdaptorType,ComponentImageType> ResamplerType; ResamplerType::Pointer resampler = ResamplerType::New(); for(unsigned int i = 0; i < vectorlength; i++) { // Transform the ith component of the vector image adaptor->SelectNthElement(i); adaptor->Update(); resampler->SetInput(adaptor); resampler->SetTransform(transform); resampler->SetOutputSpacing(reader->GetOutput()->GetSpacing()); resampler->SetOutputOrigin(reader->GetOutput()->GetOrigin()); resampler->SetSize(reader->GetOutput()->GetLargestPossibleRegion().GetSize()); resampler->Update(); vcompose->SetInput(i,resampler->GetOutput()); } vcompose->Update(); // Transform gradient directions // write output typedef itk::ImageFileWriter<VectorImageType> ImageFileWriterType; ImageFileWriterType::Pointer writer = ImageFileWriterType::New(); writer->SetInput(vcompose->GetOutput()); writer->SetFileName(outfile); try { writer->Update(); } catch (itk::ExceptionObject & e) { std::cerr << e << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* sound.cpp: sound handling class. * By 2MB Solutions: https//2mb.solutions * Released under the MIT license. See license.txt for details. * Billy: https://stormdragon.tk/ * Michael: https://michaeltaboada.me * */ #include "sound.h" int sound::sounds=0; ALLEGRO_VOICE* sound::voice = NULL; map<string, ALLEGRO_MIXER*> sound::mixers; map<string, ALLEGRO_SAMPLE*> sound::samples; sound::sound(void) { if(!al_is_audio_installed()) { al_install_audio(); al_init_acodec_addon(); } sounds++; si = NULL; looping = false; panval=0; gainval=0; pitchval=100; paused=false; active=false; if(mixers.find("default")==mixers.end()) { ALLEGRO_MIXER* m = NULL; m = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2); if(!m) { log("Default mixer could not be created!\n"); return; } mixers.insert(pair<string, ALLEGRO_MIXER*>("default", m)); if(voice) { if(!al_attach_mixer_to_voice(mixers.find("default")->second, voice)) { log("Could not attach default mixer to default voice!\n"); } } } if(!voice) { ALLEGRO_VOICE* v = NULL; v = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2); if(!v) { log("Default voice could not be created!\n"); return; } voice=v; if(!al_attach_mixer_to_voice(mixers.find("default")->second, voice)) { log("Could not attach default mixer to default voice!\n"); return; } } } sound::~sound(void) { sounds--; stop(); if(si) { al_destroy_sample_instance(si); } if(sounds==0) { map<string, ALLEGRO_SAMPLE*>::iterator it= samples.begin(); while(it!=samples.end()) { al_destroy_sample(it->second); samples.erase(it++); } map<string, ALLEGRO_MIXER*>::iterator it2= mixers.begin(); while(it2!=mixers.end()) { al_destroy_mixer(it2->second); mixers.erase(it2++); } if(voice) { al_destroy_voice(voice); voice=NULL; } } } void sound::log(string s) { // printf(s.c_str()); } /** *Stop the sound. *@return Whether the sound was successfully stopped. **/ bool sound::stop() { if(si) { return al_stop_sample_instance(si); } else { return false; } return false; } /** *Load a file into the sound. *@return Whether the sound was successfully loaded. **/ bool sound::load(string file/**< [in] The file to load.**/, string mixer/**< [in] The mixer name to put the sound on, can be excluded, which adds it to the default mixer.**/) { if(mixers.find(mixer)==mixers.end()) { ALLEGRO_MIXER* m = NULL; m = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2); if(!m) { log("Could not create mixer "+mixer+"!\n"); return false; } mixers.insert(pair<string, ALLEGRO_MIXER*>(mixer, m)); } if(!voice) { ALLEGRO_VOICE* v = NULL; v=al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2); if(!v) { log("Could not create default voice!\n"); return false; } voice=v; if(!al_attach_mixer_to_voice(mixers.find(mixer)->second, voice)) { log("Could not attach mixer "+mixer+" to default voice!\n"); return false; } } if(samples.find(file)==samples.end()) { ALLEGRO_SAMPLE* s=NULL; s = al_load_sample(((string)(al_path_cstr(al_get_standard_path(ALLEGRO_RESOURCES_PATH), '/'))+file).c_str()); if(!s) { log("Could not load file "+file+"!\n"); return false; } samples.insert(pair<string, ALLEGRO_SAMPLE*>(file, s)); } if(si) { al_destroy_sample_instance(si); } si = al_create_sample_instance(samples.find(file)->second); if(!si) { log("could not create sample instance!\n"); return false; } if(!al_attach_sample_instance_to_mixer(si, mixers.find(mixer)->second)) { log("Could not attach the sample instance to the "+mixer+" mixer!\n"); return false; } active=true; return true; } double sound::dB2lin( double dB ) { static const double DB_2_LOG = 0.11512925464970228420089957273422; // ln( 10 ) / 20 return exp( dB * DB_2_LOG ); } double sound::pan(double doubleval) { float new_pan=doubleval; if(new_pan<-100) new_pan=-100; if(new_pan>100) new_pan=100; new_pan=0-(fabs(new_pan)); new_pan=dB2lin(new_pan); new_pan=1.0-new_pan; if(doubleval<0) new_pan=0-new_pan; else new_pan=fabs(new_pan); if(new_pan<-1) new_pan=-1; if(new_pan>1) new_pan=1; return new_pan; } /** *Gets the pan. *@return The pan in decibel. **/ double sound::get_pan() { return panval; } /** *Sets the pan in decibel. *@return Whether the pan was successfully set. **/ bool sound::set_pan(double pan_value/**< [in] The pan in decibel.**/) { if(pan_value < -100) { pan_value = -100; } else if(pan_value >100) { pan_value=100; } double linpan = pan(pan_value); if(si) { if(!al_set_sample_instance_pan(si, linpan)) { return false; } } else { return false; } panval=pan_value; return true; } /** *Check the gain of the sound. *@return The gain. **/ double sound::get_gain() { return gainval; } /** *Set the gain of the sound in decibel. *@return Whether the gain was successfully set. **/ bool sound::set_gain(double gain/**< [in] The gain in decibel.**/) { if(gain < -100) { gain = -100; } else if(gain > 0) { gain = 0; } if(si) { double new_gain = dB2lin(gain); uint32_t version = al_get_allegro_version(); int major = version >> 24; int minor = (version >> 16) & 255; int revision = (version >> 8) & 255; if(major == 5 && minor == 2 && revision == 2) { new_gain = new_gain+(sqrt(2)-1); } if(!al_set_sample_instance_gain(si, new_gain)) { return false; } } else { return false; } gainval=gain; return true; } /** *Get the pitch in decibel. *@return The pitch. **/ double sound::get_pitch() { return pitchval; } /** *Set the pitch. *@return Whether the pitch was successfully set. **/ bool sound::set_pitch(double pitch/**< [in] The pitch in decibel.**/) { if(pitch < 1) { pitch=1; } if(si) { if(!al_set_sample_instance_speed(si, pitch/100.0)) { return false; } } else { return false; } pitchval=pitch; return true; } /** *Check whether the sound loops. *@return Whether hte file loops. **/ bool sound::get_loop() { return looping; } /** *Set the file to loop or not. *@return Whether the looping value was successfully set. **/ bool sound::set_loop(bool loop/**< [in] Should the file loop?**/) { if(si) { if(loop) { if(!al_set_sample_instance_playmode(si, ALLEGRO_PLAYMODE_LOOP)) { return false; } } else { if(!al_set_sample_instance_playmode(si, ALLEGRO_PLAYMODE_ONCE)) { return false; } } } else { return false; } looping=loop; return true; } /** *Play the file. *@return Whether the file was successfully started playing. **/ bool sound::play() { if(si) { if(paused) { paused = !al_set_sample_instance_playing(si, true); return !paused; } bool p = al_play_sample_instance(si); this->set_gain(gainval); return p; } else { return false; } return false; } /** *Check whether the sound is playing. *@return Whether the sound is playing. **/ bool sound::is_playing() { if(si) { return al_get_sample_instance_playing(si); } else { return false; } return false; } /** *Pause the sound. *@return Whether the sound is paused. **/ bool sound::pause() { if(si) { if(paused) { return true; } else { paused = !al_set_sample_instance_playing(si, false); return !paused; } } else { return false; } return false; } /** *Check whether the sound is paused. *@return Whether the sound is paused. **/ bool sound::get_paused() { return paused; } /** *Check whether the sound has a file loaded into it. *@return Whether the sound is active. **/ bool sound::get_active() { return active; } <commit_msg>updated sound.cpp<commit_after>/* sound.cpp: sound handling class. * By 2MB Solutions: https//2mb.solutions * Released under the MIT license. See license.txt for details. * Billy: https://stormdragon.tk/ * Michael: https://michaeltaboada.me * */ #include "sound.h" int sound::sounds=0; ALLEGRO_VOICE* sound::voice = NULL; map<string, ALLEGRO_MIXER*> sound::mixers; map<string, ALLEGRO_SAMPLE*> sound::samples; sound::sound(void) { if(!al_is_audio_installed()) { al_install_audio(); al_init_acodec_addon(); } sounds++; si = NULL; looping = false; panval=0; gainval=0; pitchval=100; paused=false; active=false; if(mixers.find("default")==mixers.end()) { ALLEGRO_MIXER* m = NULL; m = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2); if(!m) { log("Default mixer could not be created!\n"); return; } mixers.insert(pair<string, ALLEGRO_MIXER*>("default", m)); if(voice) { if(!al_attach_mixer_to_voice(mixers.find("default")->second, voice)) { log("Could not attach default mixer to default voice!\n"); } } } if(!voice) { ALLEGRO_VOICE* v = NULL; v = al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2); if(!v) { log("Default voice could not be created!\n"); return; } voice=v; if(!al_attach_mixer_to_voice(mixers.find("default")->second, voice)) { log("Could not attach default mixer to default voice!\n"); return; } } } sound::~sound(void) { sounds--; stop(); if(si) { al_destroy_sample_instance(si); } if(sounds==0) { map<string, ALLEGRO_SAMPLE*>::iterator it= samples.begin(); while(it!=samples.end()) { al_destroy_sample(it->second); samples.erase(it++); } map<string, ALLEGRO_MIXER*>::iterator it2= mixers.begin(); while(it2!=mixers.end()) { al_destroy_mixer(it2->second); mixers.erase(it2++); } if(voice) { al_destroy_voice(voice); voice=NULL; } } } void sound::log(string s) { // printf(s.c_str()); } /** *Stop the sound. *@return Whether the sound was successfully stopped. **/ bool sound::stop() { if(si) { return al_stop_sample_instance(si); } else { return false; } return false; } /** *Load a file into the sound. *@return Whether the sound was successfully loaded. **/ bool sound::load(string file/**< [in] The file to load.**/, string mixer/**< [in] The mixer name to put the sound on, can be excluded, which adds it to the default mixer.**/) { if(mixers.find(mixer)==mixers.end()) { ALLEGRO_MIXER* m = NULL; m = al_create_mixer(44100, ALLEGRO_AUDIO_DEPTH_FLOAT32, ALLEGRO_CHANNEL_CONF_2); if(!m) { log("Could not create mixer "+mixer+"!\n"); return false; } mixers.insert(pair<string, ALLEGRO_MIXER*>(mixer, m)); } if(!voice) { ALLEGRO_VOICE* v = NULL; v=al_create_voice(44100, ALLEGRO_AUDIO_DEPTH_INT16, ALLEGRO_CHANNEL_CONF_2); if(!v) { log("Could not create default voice!\n"); return false; } voice=v; if(!al_attach_mixer_to_voice(mixers.find(mixer)->second, voice)) { log("Could not attach mixer "+mixer+" to default voice!\n"); return false; } } if(samples.find(file)==samples.end()) { ALLEGRO_SAMPLE* s=NULL; s = al_load_sample(((string)(al_path_cstr(al_get_standard_path(ALLEGRO_RESOURCES_PATH), '/'))+file).c_str()); if(!s) { log("Could not load file "+file+"!\n"); return false; } samples.insert(pair<string, ALLEGRO_SAMPLE*>(file, s)); } if(si) { al_destroy_sample_instance(si); } si = al_create_sample_instance(samples.find(file)->second); if(!si) { log("could not create sample instance!\n"); return false; } if(!al_attach_sample_instance_to_mixer(si, mixers.find(mixer)->second)) { log("Could not attach the sample instance to the "+mixer+" mixer!\n"); return false; } active=true; return true; } double sound::dB2lin( double dB ) { static const double DB_2_LOG = 0.11512925464970228420089957273422; // ln( 10 ) / 20 return exp( dB * DB_2_LOG ); } double sound::pan(double doubleval) { float new_pan=doubleval; if(new_pan<-100) new_pan=-100; if(new_pan>100) new_pan=100; new_pan=0-(fabs(new_pan)); new_pan=dB2lin(new_pan); new_pan=1.0-new_pan; if(doubleval<0) new_pan=0-new_pan; else new_pan=fabs(new_pan); if(new_pan<-1) new_pan=-1; if(new_pan>1) new_pan=1; return new_pan; } /** *Gets the pan. *@return The pan in decibel. **/ double sound::get_pan() { return panval; } /** *Sets the pan in decibel. *@return Whether the pan was successfully set. **/ bool sound::set_pan(double pan_value/**< [in] The pan in decibel.**/) { if(pan_value < -100) { pan_value = -100; } else if(pan_value >100) { pan_value=100; } double linpan = pan(pan_value); if(si) { if(!al_set_sample_instance_pan(si, linpan)) { return false; } } else { return false; } panval=pan_value; return true; } /** *Check the gain of the sound. *@return The gain. **/ double sound::get_gain() { return gainval; } /** *Set the gain of the sound in decibel. *@return Whether the gain was successfully set. **/ bool sound::set_gain(double gain/**< [in] The gain in decibel.**/) { if(gain < -100) { gain = -100; } else if(gain > 0) { gain = 0; } if(si) { double new_gain = dB2lin(gain); if(al_get_channel_count(al_get_sample_instance_channels(si)) == 1) { new_gain = new_gain+(sqrt(2)-1); } if(!al_set_sample_instance_gain(si, new_gain)) { return false; } } else { return false; } gainval=gain; return true; } /** *Get the pitch in decibel. *@return The pitch. **/ double sound::get_pitch() { return pitchval; } /** *Set the pitch. *@return Whether the pitch was successfully set. **/ bool sound::set_pitch(double pitch/**< [in] The pitch in decibel.**/) { if(pitch < 1) { pitch=1; } if(si) { if(!al_set_sample_instance_speed(si, pitch/100.0)) { return false; } } else { return false; } pitchval=pitch; return true; } /** *Check whether the sound loops. *@return Whether hte file loops. **/ bool sound::get_loop() { return looping; } /** *Set the file to loop or not. *@return Whether the looping value was successfully set. **/ bool sound::set_loop(bool loop/**< [in] Should the file loop?**/) { if(si) { if(loop) { if(!al_set_sample_instance_playmode(si, ALLEGRO_PLAYMODE_LOOP)) { return false; } } else { if(!al_set_sample_instance_playmode(si, ALLEGRO_PLAYMODE_ONCE)) { return false; } } } else { return false; } looping=loop; return true; } /** *Play the file. *@return Whether the file was successfully started playing. **/ bool sound::play() { if(si) { if(paused) { paused = !al_set_sample_instance_playing(si, true); return !paused; } bool p = al_play_sample_instance(si); this->set_gain(gainval); return p; } else { return false; } return false; } /** *Check whether the sound is playing. *@return Whether the sound is playing. **/ bool sound::is_playing() { if(si) { return al_get_sample_instance_playing(si); } else { return false; } return false; } /** *Pause the sound. *@return Whether the sound is paused. **/ bool sound::pause() { if(si) { if(paused) { return true; } else { paused = !al_set_sample_instance_playing(si, false); return !paused; } } else { return false; } return false; } /** *Check whether the sound is paused. *@return Whether the sound is paused. **/ bool sound::get_paused() { return paused; } /** *Check whether the sound has a file loaded into it. *@return Whether the sound is active. **/ bool sound::get_active() { return active; } <|endoftext|>
<commit_before><commit_msg>CID-287<commit_after><|endoftext|>
<commit_before>#include "Thread.h" using namespace std; extern "C" TVMMainEntry VMLoadModule(const char *module); extern "C" void VMUnloadModule(void); void fileCallback(void* calldata, int result); void timerISR(void*); void idle(void*); void scheduler(); TVMThreadID nextID; //increment every time a thread is created. Decrement never. vector<Thread*> *threads; Thread *tr, *mainThread, *pt, *sched; queue<Thread*> *readyQ[NUM_RQS]; sigset_t sigs; TVMStatus VMStart(int tickms, int machinetickms, int argc, char *argv[]) { nextID = 0; TVMThreadID idletid; TVMMainEntry mainFunc = VMLoadModule(argv[0]); if (!mainFunc) { return VM_STATUS_FAILURE; }//if mainFunc doesn't load, kill yourself threads = new vector<Thread*>; for (int i = 0; i < NUM_RQS; i++) { readyQ[i] = new queue<Thread*>; }//allocate memory for ready queues sched = new Thread; mainThread = new Thread; mainThread->setPriority(VM_THREAD_PRIORITY_NORMAL); mainThread->setState(VM_THREAD_STATE_READY); mainThread->setID(nextID); nextID++; readyQ[mainThread->getPriority()]->push(mainThread); threads->push_back(mainThread); tr = mainThread; VMThreadCreate(idle, NULL, 0x100000, VM_THREAD_PRIORITY_NIL, &idletid); VMThreadActivate(idletid); MachineInitialize(machinetickms); MachineRequestAlarm((tickms*1000), timerISR, NULL); MachineEnableSignals(); mainFunc(argc, argv); VMUnloadModule(); MachineTerminate(); delete threads; return VM_STATUS_SUCCESS; } //VMStart TVMStatus VMFileOpen(const char *filename, int flags, int mode, int *filedescriptor) { tr->setcd(-18); //impossible to have a negative file descriptor if (filename == NULL || filedescriptor == NULL) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//need to have a filename and a place to put the FD MachineFileOpen(filename, flags, mode, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); if(tr->getcd() < 0) { return VM_STATUS_FAILURE; }//if invalid FD *filedescriptor = tr->getcd(); return VM_STATUS_SUCCESS; } // VMFileOpen TVMStatus VMFileClose(int filedescriptor) { tr->setcd(1); // Make thread wait here. MachineFileClose(filedescriptor, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); if (tr->getcd() < 0) { return VM_STATUS_FAILURE; }//negative result is a failure return VM_STATUS_SUCCESS; }//TVMStatus VMFileClose(int filedescriptor) TVMStatus VMFileWrite(int filedescriptor, void *data, int *length) { tr->setcd(-739); if (!data || !length) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//not allowed to have NULL pointers for where we put the data MachineFileWrite(filedescriptor, data, *length, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); if(tr->getcd() < 0) { return VM_STATUS_FAILURE; }//if a non-negative number of bytes written return VM_STATUS_SUCCESS; } // VMFileWrite TVMStatus VMFileSeek(int filedescriptor, int offset, int whence, int *newoffset) { tr->setcd(-728); MachineFileSeek(filedescriptor, offset, whence, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); if (newoffset) { *newoffset = tr->getcd(); } if (tr->getcd() < 0) return VM_STATUS_FAILURE; return VM_STATUS_SUCCESS; }//TVMStatus VMFileseek(int filedescriptor, int offset, int whence, int *newoffset) TVMStatus VMFileRead(int filedescriptor, void *data, int *length) { tr->setcd(-728); if (!data || !length) return VM_STATUS_ERROR_INVALID_PARAMETER; MachineFileRead(filedescriptor, data, *length, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); *length = tr->getcd(); if (tr->getcd() < 0) return VM_STATUS_FAILURE; return VM_STATUS_SUCCESS; }//TVMStatus VMFileseek(int filedescriptor, int offset, int whence, int *newoffset) TVMStatus VMThreadSleep(TVMTick tick) { if (tick == VM_TIMEOUT_IMMEDIATE) { tr->setState(VM_THREAD_STATE_READY); readyQ[tr->getPriority()]->push(tr); scheduler(); }// the current process yields the remainder of its processing quantum to the next ready process of equal priority. else if (tick == VM_TIMEOUT_INFINITE) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//invalid param else { tr->setTicks(tick); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); } //does nothing while the number of ticks that have passed since entering this function is less than the number to sleep on return VM_STATUS_SUCCESS; }//TVMStatus VMThreadSleep(TVMTick tick) TVMStatus VMThreadID(TVMThreadIDRef threadref) { if (!threadref) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//if threadref is a null pointer threadref = tr->getIDRef(); return VM_STATUS_SUCCESS; }//TVMStatus VMThreadID(TVMThreadIDRef threadref) TVMStatus VMThreadState(TVMThreadID thread, TVMThreadStateRef state) { bool found = false; if (!state) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//if stateref is a null pointer for (vector<Thread*>::iterator itr = threads->begin(); itr != threads->end(); itr++) { if (*((*itr)->getIDRef()) == thread) { *state = (*itr)->getState(); found = true; }//found correct thread }//linear search through threads vector for the thread ID in question if (!found) return VM_STATUS_ERROR_INVALID_ID; return VM_STATUS_SUCCESS; }//TVMStatus VMThreadState(TVMThreadID thread, TVMThreadStateRef state) TVMStatus VMThreadActivate(TVMThreadID thread) { bool found = false; Thread* nt = NULL; for (vector<Thread*>::iterator itr = threads->begin(); itr != threads->end(); itr++) { if (*((*itr)->getIDRef()) == thread) { nt = *itr; found = true; }//found correct thread }//linear search through threads vector for the thread ID in question if (!found) return VM_STATUS_ERROR_INVALID_ID; if (nt->getState() != VM_THREAD_STATE_DEAD) return VM_STATUS_ERROR_INVALID_STATE; nt->setState(VM_THREAD_STATE_READY); nt->getEntry(); readyQ[nt->getPriority()]->push(nt); return VM_STATUS_SUCCESS; }//TVMStatus VMThreadActivate(TVMThreadID thread) TVMStatus VMThreadCreate(TVMThreadEntry entry, void *param, TVMMemorySize memsize, TVMThreadPriority prio, TVMThreadIDRef tid) { SMachineContext context; if (!entry || !tid) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//INVALID PARAMS, must not be NULL uint8_t *mem = new uint8_t[memsize]; Thread* t = new Thread(prio, VM_THREAD_STATE_DEAD, *tid = nextID, mem, memsize, entry, param); nextID++; threads->push_back(t); MachineContextCreate(&context, entry, param, (void*) mem, memsize); t->setContext(context); return VM_STATUS_SUCCESS; }//TVMStatus VMThreadCreate(TVMThreadEntry entry, void *param, TVMMemorySize memsize, TVMThreadPriority prio, TVMThreadIDRef tid) void fileCallback(void* calldata, int result) { Thread* cbt = (Thread*)calldata; cbt->setcd(result); while (cbt->getState() != VM_THREAD_STATE_WAITING); cbt->setState(VM_THREAD_STATE_READY); readyQ[cbt->getPriority()]->push(cbt); }//void fileCallback(void* calldata, int result) void timerISR(void*) { MachineResumeSignals(&sigs); // MachineSuspendSignals(&sigs); for (vector<Thread*>::iterator itr = threads->begin(); itr != threads->end(); itr++) { (*itr)->decrementTicks(); }//add one tick passed to every thread scheduler(); MachineResumeSignals(&sigs); }//Timer ISR: Do Everything! void scheduler() { pt = tr; if (pt->getState() == VM_THREAD_STATE_RUNNING) { pt->setState(VM_THREAD_STATE_READY); readyQ[pt->getPriority()]->push(pt); }//return non-blocked old thread to ready queues if (!readyQ[VM_THREAD_PRIORITY_HIGH]->empty()) { tr = readyQ[VM_THREAD_PRIORITY_HIGH]->front(); readyQ[VM_THREAD_PRIORITY_HIGH]->pop(); }//if there's anything in hi-pri, run it else if (!readyQ[VM_THREAD_PRIORITY_NORMAL]->empty()) { tr = readyQ[VM_THREAD_PRIORITY_NORMAL]->front(); readyQ[VM_THREAD_PRIORITY_NORMAL]->pop(); }//if there's anything in med-pri, run it else if (!readyQ[VM_THREAD_PRIORITY_LOW]->empty()) { tr = readyQ[VM_THREAD_PRIORITY_LOW]->front(); readyQ[VM_THREAD_PRIORITY_LOW]->pop(); }//if there's anything in low-pri, run it else { tr = readyQ[VM_THREAD_PRIORITY_NIL]->front(); readyQ[VM_THREAD_PRIORITY_LOW]->pop(); }//if there's nothing in any of the RQs, spin with the idle process tr->setState(VM_THREAD_STATE_RUNNING); MachineContextSwitch(pt->getContextRef(), tr->getContextRef()); }//void scheduler() void idle(void*) { while(1); }//idles forever! <commit_msg>Fixed segfault. All sections but mutex written and functional.<commit_after>#include "Thread.h" using namespace std; extern "C" TVMMainEntry VMLoadModule(const char *module); extern "C" void VMUnloadModule(void); void fileCallback(void* calldata, int result); void timerISR(void*); void idle(void*); void scheduler(); TVMThreadID nextID; //increment every time a thread is created. Decrement never. vector<Thread*> *threads; Thread *tr, *mainThread, *pt, *sched; queue<Thread*> *readyQ[NUM_RQS]; sigset_t sigs; TVMStatus VMStart(int tickms, int machinetickms, int argc, char *argv[]) { nextID = 0; TVMThreadID idletid; TVMMainEntry mainFunc = VMLoadModule(argv[0]); if (!mainFunc) { return VM_STATUS_FAILURE; }//if mainFunc doesn't load, kill yourself threads = new vector<Thread*>; for (int i = 0; i < NUM_RQS; i++) { readyQ[i] = new queue<Thread*>; }//allocate memory for ready queues sched = new Thread; mainThread = new Thread; mainThread->setPriority(VM_THREAD_PRIORITY_NORMAL); mainThread->setState(VM_THREAD_STATE_READY); mainThread->setID(nextID); nextID++; readyQ[mainThread->getPriority()]->push(mainThread); threads->push_back(mainThread); tr = mainThread; VMThreadCreate(idle, NULL, 0x100000, VM_THREAD_PRIORITY_NIL, &idletid); VMThreadActivate(idletid); MachineInitialize(machinetickms); MachineRequestAlarm((tickms*1000), timerISR, NULL); MachineEnableSignals(); mainFunc(argc, argv); VMUnloadModule(); MachineTerminate(); for (vector<Thread*>::iterator itr = threads->begin(); itr != threads->end(); itr++) { if ((*itr)) { delete *itr; }//delete contents of threads }//for all threads delete threads; return VM_STATUS_SUCCESS; } //VMStart TVMStatus VMFileOpen(const char *filename, int flags, int mode, int *filedescriptor) { tr->setcd(-18); //impossible to have a negative file descriptor if (filename == NULL || filedescriptor == NULL) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//need to have a filename and a place to put the FD MachineFileOpen(filename, flags, mode, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); if(tr->getcd() < 0) { return VM_STATUS_FAILURE; }//if invalid FD *filedescriptor = tr->getcd(); return VM_STATUS_SUCCESS; } // VMFileOpen TVMStatus VMFileClose(int filedescriptor) { tr->setcd(1); // Make thread wait here. MachineFileClose(filedescriptor, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); if (tr->getcd() < 0) { return VM_STATUS_FAILURE; }//negative result is a failure return VM_STATUS_SUCCESS; }//TVMStatus VMFileClose(int filedescriptor) TVMStatus VMFileWrite(int filedescriptor, void *data, int *length) { tr->setcd(-739); if (!data || !length) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//not allowed to have NULL pointers for where we put the data MachineFileWrite(filedescriptor, data, *length, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); if(tr->getcd() < 0) { return VM_STATUS_FAILURE; }//if a non-negative number of bytes written return VM_STATUS_SUCCESS; } // VMFileWrite TVMStatus VMFileSeek(int filedescriptor, int offset, int whence, int *newoffset) { tr->setcd(-728); MachineFileSeek(filedescriptor, offset, whence, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); if (newoffset) { *newoffset = tr->getcd(); } if (tr->getcd() < 0) return VM_STATUS_FAILURE; return VM_STATUS_SUCCESS; }//TVMStatus VMFileseek(int filedescriptor, int offset, int whence, int *newoffset) TVMStatus VMFileRead(int filedescriptor, void *data, int *length) { tr->setcd(-728); if (!data || !length) return VM_STATUS_ERROR_INVALID_PARAMETER; MachineFileRead(filedescriptor, data, *length, fileCallback, (void*)tr); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); *length = tr->getcd(); if (tr->getcd() < 0) return VM_STATUS_FAILURE; return VM_STATUS_SUCCESS; }//TVMStatus VMFileseek(int filedescriptor, int offset, int whence, int *newoffset) TVMStatus VMThreadSleep(TVMTick tick) { if (tick == VM_TIMEOUT_IMMEDIATE) { tr->setState(VM_THREAD_STATE_READY); readyQ[tr->getPriority()]->push(tr); scheduler(); }// the current process yields the remainder of its processing quantum to the next ready process of equal priority. else if (tick == VM_TIMEOUT_INFINITE) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//invalid param else { tr->setTicks(tick); tr->setState(VM_THREAD_STATE_WAITING); scheduler(); } //does nothing while the number of ticks that have passed since entering this function is less than the number to sleep on return VM_STATUS_SUCCESS; }//TVMStatus VMThreadSleep(TVMTick tick) TVMStatus VMThreadID(TVMThreadIDRef threadref) { if (!threadref) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//if threadref is a null pointer threadref = tr->getIDRef(); return VM_STATUS_SUCCESS; }//TVMStatus VMThreadID(TVMThreadIDRef threadref) TVMStatus VMThreadState(TVMThreadID thread, TVMThreadStateRef state) { bool found = false; if (!state) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//if stateref is a null pointer for (vector<Thread*>::iterator itr = threads->begin(); itr != threads->end(); itr++) { if (*((*itr)->getIDRef()) == thread) { *state = (*itr)->getState(); found = true; }//found correct thread }//linear search through threads vector for the thread ID in question if (!found) return VM_STATUS_ERROR_INVALID_ID; return VM_STATUS_SUCCESS; }//TVMStatus VMThreadState(TVMThreadID thread, TVMThreadStateRef state) TVMStatus VMThreadActivate(TVMThreadID thread) { bool found = false; Thread* nt = NULL; for (vector<Thread*>::iterator itr = threads->begin(); itr != threads->end(); itr++) { if (*((*itr)->getIDRef()) == thread) { nt = *itr; found = true; }//found correct thread }//linear search through threads vector for the thread ID in question if (!found) return VM_STATUS_ERROR_INVALID_ID; if (nt->getState() != VM_THREAD_STATE_DEAD) return VM_STATUS_ERROR_INVALID_STATE; nt->setState(VM_THREAD_STATE_READY); nt->getEntry(); readyQ[nt->getPriority()]->push(nt); return VM_STATUS_SUCCESS; }//TVMStatus VMThreadActivate(TVMThreadID thread) TVMStatus VMThreadCreate(TVMThreadEntry entry, void *param, TVMMemorySize memsize, TVMThreadPriority prio, TVMThreadIDRef tid) { SMachineContext context; if (!entry || !tid) { return VM_STATUS_ERROR_INVALID_PARAMETER; }//INVALID PARAMS, must not be NULL uint8_t *mem = new uint8_t[memsize]; Thread* t = new Thread(prio, VM_THREAD_STATE_DEAD, *tid = nextID, mem, memsize, entry, param); nextID++; threads->push_back(t); MachineContextCreate(&context, entry, param, (void*) mem, memsize); t->setContext(context); return VM_STATUS_SUCCESS; }//TVMStatus VMThreadCreate(TVMThreadEntry entry, void *param, TVMMemorySize memsize, TVMThreadPriority prio, TVMThreadIDRef tid) void fileCallback(void* calldata, int result) { Thread* cbt = (Thread*)calldata; cbt->setcd(result); while (cbt->getState() != VM_THREAD_STATE_WAITING); cbt->setState(VM_THREAD_STATE_READY); readyQ[cbt->getPriority()]->push(cbt); }//void fileCallback(void* calldata, int result) void timerISR(void*) { // MachineResumeSignals(&sigs); MachineSuspendSignals(&sigs); for (vector<Thread*>::iterator itr = threads->begin(); itr != threads->end(); itr++) { (*itr)->decrementTicks(); }//add one tick passed to every thread MachineResumeSignals(&sigs); scheduler(); }//Timer ISR: Do Everything! void scheduler() { pt = tr; if (pt->getState() == VM_THREAD_STATE_RUNNING) { pt->setState(VM_THREAD_STATE_READY); readyQ[pt->getPriority()]->push(pt); }//return non-blocked old thread to ready queues if (!readyQ[VM_THREAD_PRIORITY_HIGH]->empty()) { tr = readyQ[VM_THREAD_PRIORITY_HIGH]->front(); readyQ[VM_THREAD_PRIORITY_HIGH]->pop(); }//if there's anything in hi-pri, run it else if (!readyQ[VM_THREAD_PRIORITY_NORMAL]->empty()) { tr = readyQ[VM_THREAD_PRIORITY_NORMAL]->front(); readyQ[VM_THREAD_PRIORITY_NORMAL]->pop(); }//if there's anything in med-pri, run it else if (!readyQ[VM_THREAD_PRIORITY_LOW]->empty()) { tr = readyQ[VM_THREAD_PRIORITY_LOW]->front(); readyQ[VM_THREAD_PRIORITY_LOW]->pop(); }//if there's anything in low-pri, run it else { tr = readyQ[VM_THREAD_PRIORITY_NIL]->front(); readyQ[VM_THREAD_PRIORITY_NIL]->pop(); }//if there's nothing in any of the RQs, spin with the idle process tr->setState(VM_THREAD_STATE_RUNNING); MachineContextSwitch(pt->getContextRef(), tr->getContextRef()); }//void scheduler() void idle(void*) { while(1); }//idles forever! <|endoftext|>
<commit_before>/* * Copyright (c) 2018-2019 Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #ifdef DEVICE_WATCHDOG #include "Watchdog.h" #define MS_TO_US(x) ((x) * 1000) //macro to convert millisecond to microsecond namespace mbed { static const uint32_t elapsed_ms = MBED_CONF_TARGET_WATCHDOG_TIMEOUT / 2; Watchdog::Watchdog() : _running(false) { } bool Watchdog::start() { watchdog_status_t sts; MBED_ASSERT(MBED_CONF_TARGET_WATCHDOG_TIMEOUT < get_max_timeout()); core_util_critical_section_enter(); if (_running) { core_util_critical_section_exit(); return false; } watchdog_config_t config; config.timeout_ms = MBED_CONF_TARGET_WATCHDOG_TIMEOUT; sts = hal_watchdog_init(&config); if (sts == WATCHDOG_STATUS_OK) { _running = true; } core_util_critical_section_exit(); if (_running) { us_timestamp_t timeout = (MS_TO_US(((elapsed_ms <= 0) ? 1 : elapsed_ms))); _ticker->attach_us(callback(&Watchdog::get_instance(), &Watchdog::kick), timeout); } return _running; } bool Watchdog::stop() { watchdog_status_t sts; bool msts = true; core_util_critical_section_enter(); if (_running) { sts = hal_watchdog_stop(); if (sts != WATCHDOG_STATUS_OK) { msts = false; } else { _ticker->detach(); _running = false; } } else { msts = false; } core_util_critical_section_exit(); return msts; } void Watchdog::kick() { core_util_critical_section_enter(); hal_watchdog_kick(); core_util_critical_section_exit(); } bool Watchdog::is_running() const { return _running; } uint32_t Watchdog::get_timeout() const { return hal_watchdog_get_reload_value(); } uint32_t Watchdog::get_max_timeout() const { const watchdog_features_t features = hal_watchdog_get_platform_features(); return features.max_timeout; } } // namespace mbed #endif // DEVICE_WATCHDOG <commit_msg>Watchdog: fix dtor<commit_after>/* * Copyright (c) 2018-2019 Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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. */ #ifdef DEVICE_WATCHDOG #include "Watchdog.h" #define MS_TO_US(x) ((x) * 1000) //macro to convert millisecond to microsecond namespace mbed { static const uint32_t elapsed_ms = MBED_CONF_TARGET_WATCHDOG_TIMEOUT / 2; Watchdog::Watchdog() : _running(false) { } ~Watchdog::Watchdog() { } bool Watchdog::start() { watchdog_status_t sts; MBED_ASSERT(MBED_CONF_TARGET_WATCHDOG_TIMEOUT < get_max_timeout()); core_util_critical_section_enter(); if (_running) { core_util_critical_section_exit(); return false; } watchdog_config_t config; config.timeout_ms = MBED_CONF_TARGET_WATCHDOG_TIMEOUT; sts = hal_watchdog_init(&config); if (sts == WATCHDOG_STATUS_OK) { _running = true; } core_util_critical_section_exit(); if (_running) { us_timestamp_t timeout = (MS_TO_US(((elapsed_ms <= 0) ? 1 : elapsed_ms))); _ticker->attach_us(callback(&Watchdog::get_instance(), &Watchdog::kick), timeout); } return _running; } bool Watchdog::stop() { watchdog_status_t sts; bool msts = true; core_util_critical_section_enter(); if (_running) { sts = hal_watchdog_stop(); if (sts != WATCHDOG_STATUS_OK) { msts = false; } else { _ticker->detach(); _running = false; } } else { msts = false; } core_util_critical_section_exit(); return msts; } void Watchdog::kick() { core_util_critical_section_enter(); hal_watchdog_kick(); core_util_critical_section_exit(); } bool Watchdog::is_running() const { return _running; } uint32_t Watchdog::get_timeout() const { return hal_watchdog_get_reload_value(); } uint32_t Watchdog::get_max_timeout() const { const watchdog_features_t features = hal_watchdog_get_platform_features(); return features.max_timeout; } } // namespace mbed #endif // DEVICE_WATCHDOG <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include <assert.h> #include <windows.h> #include "webrtc/modules/desktop_capture/desktop_frame_win.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { namespace { typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled); // Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if // error occurs. std::string Utf16ToUtf8(const WCHAR* str) { int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); if (len_utf8 <= 0) return std::string(); std::string result(len_utf8, '\0'); int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1, &*(result.begin()), len_utf8, NULL, NULL); if (rv != len_utf8) assert(false); return result; } BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { WindowCapturer::WindowList* list = reinterpret_cast<WindowCapturer::WindowList*>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. int len = GetWindowTextLength(hwnd); HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW))) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; GetClassName(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; WindowCapturer::Window window; window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd); const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowText(hwnd, window_title, kTitleLength); window.title = Utf16ToUtf8(window_title); // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } class WindowCapturerWin : public WindowCapturer { public: WindowCapturerWin(); virtual ~WindowCapturerWin(); // WindowCapturer interface. virtual bool GetWindowList(WindowList* windows) OVERRIDE; virtual bool SelectWindow(WindowId id) OVERRIDE; // DesktopCapturer interface. virtual void Start(Callback* callback) OVERRIDE; virtual void Capture(const DesktopRegion& region) OVERRIDE; private: bool IsAeroEnabled(); Callback* callback_; // HWND and HDC for the currently selected window or NULL if window is not // selected. HWND window_; // dwmapi.dll is used to determine if desktop compositing is enabled. HMODULE dwmapi_library_; DwmIsCompositionEnabledFunc is_composition_enabled_func_; DesktopSize previous_size_; DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin); }; WindowCapturerWin::WindowCapturerWin() : callback_(NULL), window_(NULL) { // Try to load dwmapi.dll dynamically since it is not available on XP. dwmapi_library_ = LoadLibrary(L"dwmapi.dll"); if (dwmapi_library_) { is_composition_enabled_func_ = reinterpret_cast<DwmIsCompositionEnabledFunc>( GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled")); assert(is_composition_enabled_func_); } else { is_composition_enabled_func_ = NULL; } } WindowCapturerWin::~WindowCapturerWin() { if (dwmapi_library_) FreeLibrary(dwmapi_library_); } bool WindowCapturerWin::IsAeroEnabled() { BOOL result = FALSE; if (is_composition_enabled_func_) is_composition_enabled_func_(&result); return result != FALSE; } bool WindowCapturerWin::GetWindowList(WindowList* windows) { WindowList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; windows->swap(result); return true; } bool WindowCapturerWin::SelectWindow(WindowId id) { HWND window = reinterpret_cast<HWND>(id); if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window)) return false; window_ = window; previous_size_.set(0, 0); return true; } void WindowCapturerWin::Start(Callback* callback) { assert(!callback_); assert(callback); callback_ = callback; } void WindowCapturerWin::Capture(const DesktopRegion& region) { if (!window_) { LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } // Stop capturing if the window has been minimized or hidden. if (IsIconic(window_) || !IsWindowVisible(window_)) { callback_->OnCaptureCompleted(NULL); return; } RECT rect; if (!GetWindowRect(window_, &rect)) { LOG(LS_WARNING) << "Failed to get window size: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } HDC window_dc = GetWindowDC(window_); if (!window_dc) { LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create( DesktopSize(rect.right - rect.left, rect.bottom - rect.top), NULL, window_dc)); if (!frame.get()) { ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(NULL); return; } HDC mem_dc = CreateCompatibleDC(window_dc); HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap()); BOOL result = FALSE; // When desktop composition (Aero) is enabled each window is rendered to a // private buffer allowing BitBlt() to get the window content even if the // window is occluded. PrintWindow() is slower but lets rendering the window // contents to an off-screen device context when Aero is not available. // PrintWindow() is not supported by some applications. // // If Aero is enabled, we prefer BitBlt() because it's faster and avoids // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may // render occluding windows on top of the desired window. // // When composition is enabled the DC returned by GetWindowDC() doesn't always // have window frame rendered correctly. Windows renders it only once and then // caches the result between captures. We hack it around by calling // PrintWindow() whenever window size changes - it somehow affects what we // get from BitBlt() on the subsequent captures. if (!IsAeroEnabled() || (!previous_size_.is_empty() && !previous_size_.equals(frame->size()))) { result = PrintWindow(window_, mem_dc, 0); } // Aero is enabled or PrintWindow() failed, use BitBlt. if (!result) { result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(), window_dc, 0, 0, SRCCOPY); } SelectObject(mem_dc, previous_object); DeleteDC(mem_dc); ReleaseDC(window_, window_dc); previous_size_ = frame->size(); if (!result) { LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed."; frame.reset(); } callback_->OnCaptureCompleted(frame.release()); } } // namespace // static WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) { return new WindowCapturerWin(); } } // namespace webrtc <commit_msg>Call PrintWindow for the first time of capturing to capture the window frames correctly. This will fix artifacts on the captured window frames, especially for cmd, which sometimes leaks glimpss of other window's content.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/desktop_capture/window_capturer.h" #include <assert.h> #include <windows.h> #include "webrtc/modules/desktop_capture/desktop_frame_win.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/scoped_ptr.h" namespace webrtc { namespace { typedef HRESULT (WINAPI *DwmIsCompositionEnabledFunc)(BOOL* enabled); // Coverts a zero-terminated UTF-16 string to UTF-8. Returns an empty string if // error occurs. std::string Utf16ToUtf8(const WCHAR* str) { int len_utf8 = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL); if (len_utf8 <= 0) return std::string(); std::string result(len_utf8, '\0'); int rv = WideCharToMultiByte(CP_UTF8, 0, str, -1, &*(result.begin()), len_utf8, NULL, NULL); if (rv != len_utf8) assert(false); return result; } BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { WindowCapturer::WindowList* list = reinterpret_cast<WindowCapturer::WindowList*>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. int len = GetWindowTextLength(hwnd); HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (len == 0 || IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW))) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; GetClassName(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; WindowCapturer::Window window; window.id = reinterpret_cast<WindowCapturer::WindowId>(hwnd); const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowText(hwnd, window_title, kTitleLength); window.title = Utf16ToUtf8(window_title); // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } class WindowCapturerWin : public WindowCapturer { public: WindowCapturerWin(); virtual ~WindowCapturerWin(); // WindowCapturer interface. virtual bool GetWindowList(WindowList* windows) OVERRIDE; virtual bool SelectWindow(WindowId id) OVERRIDE; // DesktopCapturer interface. virtual void Start(Callback* callback) OVERRIDE; virtual void Capture(const DesktopRegion& region) OVERRIDE; private: bool IsAeroEnabled(); Callback* callback_; // HWND and HDC for the currently selected window or NULL if window is not // selected. HWND window_; // dwmapi.dll is used to determine if desktop compositing is enabled. HMODULE dwmapi_library_; DwmIsCompositionEnabledFunc is_composition_enabled_func_; DesktopSize previous_size_; DISALLOW_COPY_AND_ASSIGN(WindowCapturerWin); }; WindowCapturerWin::WindowCapturerWin() : callback_(NULL), window_(NULL) { // Try to load dwmapi.dll dynamically since it is not available on XP. dwmapi_library_ = LoadLibrary(L"dwmapi.dll"); if (dwmapi_library_) { is_composition_enabled_func_ = reinterpret_cast<DwmIsCompositionEnabledFunc>( GetProcAddress(dwmapi_library_, "DwmIsCompositionEnabled")); assert(is_composition_enabled_func_); } else { is_composition_enabled_func_ = NULL; } } WindowCapturerWin::~WindowCapturerWin() { if (dwmapi_library_) FreeLibrary(dwmapi_library_); } bool WindowCapturerWin::IsAeroEnabled() { BOOL result = FALSE; if (is_composition_enabled_func_) is_composition_enabled_func_(&result); return result != FALSE; } bool WindowCapturerWin::GetWindowList(WindowList* windows) { WindowList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; windows->swap(result); return true; } bool WindowCapturerWin::SelectWindow(WindowId id) { HWND window = reinterpret_cast<HWND>(id); if (!IsWindow(window) || !IsWindowVisible(window) || IsIconic(window)) return false; window_ = window; previous_size_.set(0, 0); return true; } void WindowCapturerWin::Start(Callback* callback) { assert(!callback_); assert(callback); callback_ = callback; } void WindowCapturerWin::Capture(const DesktopRegion& region) { if (!window_) { LOG(LS_ERROR) << "Window hasn't been selected: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } // Stop capturing if the window has been minimized or hidden. if (IsIconic(window_) || !IsWindowVisible(window_)) { callback_->OnCaptureCompleted(NULL); return; } RECT rect; if (!GetWindowRect(window_, &rect)) { LOG(LS_WARNING) << "Failed to get window size: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } HDC window_dc = GetWindowDC(window_); if (!window_dc) { LOG(LS_WARNING) << "Failed to get window DC: " << GetLastError(); callback_->OnCaptureCompleted(NULL); return; } scoped_ptr<DesktopFrameWin> frame(DesktopFrameWin::Create( DesktopSize(rect.right - rect.left, rect.bottom - rect.top), NULL, window_dc)); if (!frame.get()) { ReleaseDC(window_, window_dc); callback_->OnCaptureCompleted(NULL); return; } HDC mem_dc = CreateCompatibleDC(window_dc); HGDIOBJ previous_object = SelectObject(mem_dc, frame->bitmap()); BOOL result = FALSE; // When desktop composition (Aero) is enabled each window is rendered to a // private buffer allowing BitBlt() to get the window content even if the // window is occluded. PrintWindow() is slower but lets rendering the window // contents to an off-screen device context when Aero is not available. // PrintWindow() is not supported by some applications. // // If Aero is enabled, we prefer BitBlt() because it's faster and avoids // window flickering. Otherwise, we prefer PrintWindow() because BitBlt() may // render occluding windows on top of the desired window. // // When composition is enabled the DC returned by GetWindowDC() doesn't always // have window frame rendered correctly. Windows renders it only once and then // caches the result between captures. We hack it around by calling // PrintWindow() whenever window size changes, including the first time of // capturing - it somehow affects what we get from BitBlt() on the subsequent // captures. if (!IsAeroEnabled() || !previous_size_.equals(frame->size())) { result = PrintWindow(window_, mem_dc, 0); } // Aero is enabled or PrintWindow() failed, use BitBlt. if (!result) { result = BitBlt(mem_dc, 0, 0, frame->size().width(), frame->size().height(), window_dc, 0, 0, SRCCOPY); } SelectObject(mem_dc, previous_object); DeleteDC(mem_dc); ReleaseDC(window_, window_dc); previous_size_ = frame->size(); if (!result) { LOG(LS_ERROR) << "Both PrintWindow() and BitBlt() failed."; frame.reset(); } callback_->OnCaptureCompleted(frame.release()); } } // namespace // static WindowCapturer* WindowCapturer::Create(const DesktopCaptureOptions& options) { return new WindowCapturerWin(); } } // namespace webrtc <|endoftext|>
<commit_before><commit_msg>use OString::equalsL<commit_after><|endoftext|>
<commit_before>/****************************************************************************** ** Copyright (c) 2014-2015, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Hans Pabst (Intel Corp.) ******************************************************************************/ #include <libxstream_begin.h> #include <stdexcept> #include <algorithm> #include <cstring> #include <cstdio> #if defined(_OPENMP) # include <omp.h> #endif #include <libxstream_end.h> //#define COPY_NO_SYNC /** * This program is copying data to/from a copprocessor device (copy-in or copy-out). * A series of different sizes (up to a given / automatically selected amount) is * exercised in order to measure the bandwidth of the data transfers. The program * is multi-threaded (using only one thread by default) mainly to exercise the * thread-safety of LIBXSTREAM. There is no performance gain expected from using * multiple threads, remember that the number of streams determines the available * parallelism. The program is intentionally spartan (command line interface, etc.) * in order to keep it within bounds for an introductory code sample. The mechanism * selecting the stream to enqueue into as well as selecting the stream to be * synchronized shows the essence of the stream programing model. */ int main(int argc, char* argv[]) { try { size_t ndevices = 0; if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) { LIBXSTREAM_PRINT0(1, "No device found or device not ready!"); } const int device = static_cast<int>(ndevices) - 1; size_t allocatable = 0; libxstream_mem_info(device, &allocatable, 0); allocatable >>= 20; // MB const bool copyin = 1 < argc ? ('o' != *argv[1]) : true; const int nstreams = std::min(std::max(2 < argc ? std::atoi(argv[2]) : 2, 1), LIBXSTREAM_MAX_NSTREAMS); #if defined(_OPENMP) const int nthreads = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 1, 1), omp_get_max_threads()); #else //const int nthreads = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 1, 1), 1); LIBXSTREAM_PRINT0(1, "OpenMP support needed for performance results!"); #endif #if defined(LIBXSTREAM_OFFLOAD) const size_t nreserved = nstreams + 1; #else const size_t nreserved = nstreams + 2; #endif const size_t minsize = 8, maxsize = static_cast<size_t>(std::min(std::max(4 < argc ? std::atoi(argv[4]) : static_cast<int>(allocatable / nreserved), 1), 2048)) * (1 << 20); const int minrepeat = std::min(std::max(5 < argc ? std::atoi(argv[5]) : 8, 4), 2048); const int maxrepeat = std::min(std::max(6 < argc ? std::atoi(argv[6]) : 4096, minrepeat), 32768); int steps_repeat = 0, steps_size = 0; for (int nrepeat = minrepeat; nrepeat <= maxrepeat; nrepeat <<= 1) ++steps_repeat; for (size_t size = minsize; size <= maxsize; size <<= 1) ++steps_size; const int stride = 0 < steps_repeat ? (steps_size / steps_repeat + 1) : 1; struct { libxstream_stream* stream; void *mem_hst, *mem_dev; } copy[LIBXSTREAM_MAX_NSTREAMS]; memset(copy, 0, sizeof(copy)); // some initialization (avoid false positives with tools) for (int i = 0; i < nstreams; ++i) { char name[128]; LIBXSTREAM_SNPRINTF(name, sizeof(name), "Stream %i", i + 1); LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_create(&copy[i].stream, device, 0, name)); } if (copyin) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(-1/*host*/, &copy[0].mem_hst, maxsize, 0)); memset(copy[0].mem_hst, -1, maxsize); // some initialization (avoid false positives with tools) for (int i = 1; i < nstreams; ++i) { copy[i].mem_hst = copy[0].mem_hst; } for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(device, &copy[i].mem_dev, maxsize, 0)); } } else { // copy-out LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(device, &copy[0].mem_dev, maxsize, 0)); libxstream_memset_zero(copy[0].mem_dev, maxsize, copy[0].stream); for (int i = 1; i < nstreams; ++i) { copy[i].mem_dev = copy[0].mem_dev; } for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(-1/*host*/, &copy[i].mem_hst, maxsize, 0)); } } // start benchmark with no pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_wait(0)); int n = 0, nrepeat = maxrepeat; double maxval = 0, sumval = 0, runlns = 0, duration = 0; for (size_t size = minsize; size <= maxsize; size <<= 1, ++n) { if (0 < n && 0 == (n % stride)) { nrepeat >>= 1; } #if defined(_OPENMP) fprintf(stdout, "%lu Byte x %i: ", static_cast<unsigned long>(size), nrepeat); fflush(stdout); // make sure to show progress const double start = omp_get_wtime(); # pragma omp parallel for num_threads(nthreads) schedule(dynamic) #endif for (int i = 0; i < nrepeat; ++i) { const int j = i % nstreams; if (copyin) { LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_memcpy_h2d(copy[j].mem_hst, copy[j].mem_dev, size, copy[j].stream)); } else { // copy-out LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_memcpy_d2h(copy[j].mem_dev, copy[j].mem_hst, size, copy[j].stream)); } #if !defined(COPY_NO_SYNC) const int k = (j + 1) % nstreams; LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_sync(copy[k].stream)); #endif } // wait for all streams to complete pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_wait(0)); #if defined(_OPENMP) const double iduration = omp_get_wtime() - start; if (0 < iduration) { const double bandwidth = (1.0 * size * nrepeat) / ((1ul << 20) * iduration); fprintf(stdout, "%.1f MB/s\n", bandwidth); maxval = std::max(maxval, bandwidth); sumval += bandwidth; runlns = (runlns + std::log(bandwidth)) * (0 < n ? 0.5 : 1.0); duration += iduration; } else { fprintf(stdout, "-\n"); } #endif } if (copyin) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_deallocate(-1/*host*/, copy[0].mem_hst)); for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_deallocate(device, copy[i].mem_dev)); } } else { // copy-out LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_deallocate(device, copy[0].mem_dev)); for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_deallocate(-1/*host*/, copy[i].mem_hst)); } } for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_destroy(copy[i].stream)); } fprintf(stdout, "\n"); if (0 < n) { fprintf(stdout, "Finished after %.0f s\n", duration); fprintf(stdout, "max: %.0f MB/s\n", maxval); fprintf(stdout, "rgm: %.0f MB/s\n", std::exp(runlns)); fprintf(stdout, "avg: %.0f MB/s\n", sumval / n); } else { fprintf(stdout, "Finished\n"); } } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } catch(...) { fprintf(stderr, "Error: unknown exception caught!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Fixed initial (running) geometric mean value.<commit_after>/****************************************************************************** ** Copyright (c) 2014-2015, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Hans Pabst (Intel Corp.) ******************************************************************************/ #include <libxstream_begin.h> #include <stdexcept> #include <algorithm> #include <cstring> #include <cstdio> #if defined(_OPENMP) # include <omp.h> #endif #include <libxstream_end.h> //#define COPY_NO_SYNC /** * This program is copying data to/from a copprocessor device (copy-in or copy-out). * A series of different sizes (up to a given / automatically selected amount) is * exercised in order to measure the bandwidth of the data transfers. The program * is multi-threaded (using only one thread by default) mainly to exercise the * thread-safety of LIBXSTREAM. There is no performance gain expected from using * multiple threads, remember that the number of streams determines the available * parallelism. The program is intentionally spartan (command line interface, etc.) * in order to keep it within bounds for an introductory code sample. The mechanism * selecting the stream to enqueue into as well as selecting the stream to be * synchronized shows the essence of the stream programing model. */ int main(int argc, char* argv[]) { try { size_t ndevices = 0; if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) { LIBXSTREAM_PRINT0(1, "No device found or device not ready!"); } const int device = static_cast<int>(ndevices) - 1; size_t allocatable = 0; libxstream_mem_info(device, &allocatable, 0); allocatable >>= 20; // MB const bool copyin = 1 < argc ? ('o' != *argv[1]) : true; const int nstreams = std::min(std::max(2 < argc ? std::atoi(argv[2]) : 2, 1), LIBXSTREAM_MAX_NSTREAMS); #if defined(_OPENMP) const int nthreads = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 1, 1), omp_get_max_threads()); #else //const int nthreads = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 1, 1), 1); LIBXSTREAM_PRINT0(1, "OpenMP support needed for performance results!"); #endif #if defined(LIBXSTREAM_OFFLOAD) const size_t nreserved = nstreams + 1; #else const size_t nreserved = nstreams + 2; #endif const size_t minsize = 8, maxsize = static_cast<size_t>(std::min(std::max(4 < argc ? std::atoi(argv[4]) : static_cast<int>(allocatable / nreserved), 1), 2048)) * (1 << 20); const int minrepeat = std::min(std::max(5 < argc ? std::atoi(argv[5]) : 8, 4), 2048); const int maxrepeat = std::min(std::max(6 < argc ? std::atoi(argv[6]) : 4096, minrepeat), 32768); int steps_repeat = 0, steps_size = 0; for (int nrepeat = minrepeat; nrepeat <= maxrepeat; nrepeat <<= 1) ++steps_repeat; for (size_t size = minsize; size <= maxsize; size <<= 1) ++steps_size; const int stride = 0 < steps_repeat ? (steps_size / steps_repeat + 1) : 1; struct { libxstream_stream* stream; void *mem_hst, *mem_dev; } copy[LIBXSTREAM_MAX_NSTREAMS]; memset(copy, 0, sizeof(copy)); // some initialization (avoid false positives with tools) for (int i = 0; i < nstreams; ++i) { char name[128]; LIBXSTREAM_SNPRINTF(name, sizeof(name), "Stream %i", i + 1); LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_create(&copy[i].stream, device, 0, name)); } if (copyin) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(-1/*host*/, &copy[0].mem_hst, maxsize, 0)); memset(copy[0].mem_hst, -1, maxsize); // some initialization (avoid false positives with tools) for (int i = 1; i < nstreams; ++i) { copy[i].mem_hst = copy[0].mem_hst; } for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(device, &copy[i].mem_dev, maxsize, 0)); } } else { // copy-out LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(device, &copy[0].mem_dev, maxsize, 0)); libxstream_memset_zero(copy[0].mem_dev, maxsize, copy[0].stream); for (int i = 1; i < nstreams; ++i) { copy[i].mem_dev = copy[0].mem_dev; } for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_allocate(-1/*host*/, &copy[i].mem_hst, maxsize, 0)); } } // start benchmark with no pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_wait(0)); int n = 0, nrepeat = maxrepeat; double maxval = 0, sumval = 0, runlns = 0, duration = 0; for (size_t size = minsize; size <= maxsize; size <<= 1, ++n) { if (0 < n && 0 == (n % stride)) { nrepeat >>= 1; } #if defined(_OPENMP) fprintf(stdout, "%lu Byte x %i: ", static_cast<unsigned long>(size), nrepeat); fflush(stdout); // make sure to show progress const double start = omp_get_wtime(); # pragma omp parallel for num_threads(nthreads) schedule(dynamic) #endif for (int i = 0; i < nrepeat; ++i) { const int j = i % nstreams; if (copyin) { LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_memcpy_h2d(copy[j].mem_hst, copy[j].mem_dev, size, copy[j].stream)); } else { // copy-out LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_memcpy_d2h(copy[j].mem_dev, copy[j].mem_hst, size, copy[j].stream)); } #if !defined(COPY_NO_SYNC) const int k = (j + 1) % nstreams; LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_sync(copy[k].stream)); #endif } // wait for all streams to complete pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_wait(0)); #if defined(_OPENMP) const double iduration = omp_get_wtime() - start; if (0 < iduration) { const double bandwidth = (1.0 * size * nrepeat) / ((1ul << 20) * iduration); fprintf(stdout, "%.1f MB/s\n", bandwidth); maxval = std::max(maxval, bandwidth); sumval += bandwidth; runlns = (runlns + std::log(bandwidth)) * (0 < n ? 0.5 : 1.0); duration += iduration; } else { fprintf(stdout, "-\n"); } #endif } if (copyin) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_deallocate(-1/*host*/, copy[0].mem_hst)); for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_deallocate(device, copy[i].mem_dev)); } } else { // copy-out LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_deallocate(device, copy[0].mem_dev)); for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_mem_deallocate(-1/*host*/, copy[i].mem_hst)); } } for (int i = 0; i < nstreams; ++i) { LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_destroy(copy[i].stream)); } fprintf(stdout, "\n"); if (0 < n) { fprintf(stdout, "Finished after %.0f s\n", duration); fprintf(stdout, "max: %.0f MB/s\n", maxval); fprintf(stdout, "rgm: %.0f MB/s\n", std::exp(runlns) - 1.0); fprintf(stdout, "avg: %.0f MB/s\n", sumval / n); } else { fprintf(stdout, "Finished\n"); } } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } catch(...) { fprintf(stderr, "Error: unknown exception caught!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ** This file is part of the Ovi services plugin for the Maps and ** Navigation API. The use of these services, whether by use of the ** plugin or by other means, is governed by the terms and conditions ** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in ** this package, located in the directory containing the Ovi services ** plugin source code. ** ****************************************************************************/ #include "qgeomapreply_nokia.h" QGeoMapReplyNokia::QGeoMapReplyNokia(QNetworkReply *reply, const QGeoTiledMapRequest &request, QObject *parent) : QGeoTiledMapReply(request, parent), m_reply(reply) { m_reply->setParent(this); QVariant fromCache = m_reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute); setCached(fromCache.toBool()); connect(m_reply, SIGNAL(finished()), this, SLOT(networkFinished())); connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError))); connect(m_reply, SIGNAL(destroyed()), this, SLOT(replyDestroyed())); } QGeoMapReplyNokia::~QGeoMapReplyNokia() { } QNetworkReply* QGeoMapReplyNokia::networkReply() const { return m_reply; } void QGeoMapReplyNokia::abort() { if (!m_reply) return; m_reply->abort(); m_reply->deleteLater(); m_reply = 0; } void QGeoMapReplyNokia::replyDestroyed() { m_reply = 0; } void QGeoMapReplyNokia::networkFinished() { if (!m_reply) return; if (m_reply->error() != QNetworkReply::NoError) { return; } setMapImageData(m_reply->readAll()); setMapImageFormat("PNG"); setFinished(true); m_reply->deleteLater(); m_reply = 0; } void QGeoMapReplyNokia::networkError(QNetworkReply::NetworkError error) { if (!m_reply) return; if (error != QNetworkReply::OperationCanceledError) setError(QGeoTiledMapReply::CommunicationError, m_reply->errorString()); m_reply->deleteLater(); m_reply = 0; } <commit_msg>GeoServices Nokia plugin fix postEvent: Unexpected null receiver<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ** This file is part of the Ovi services plugin for the Maps and ** Navigation API. The use of these services, whether by use of the ** plugin or by other means, is governed by the terms and conditions ** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in ** this package, located in the directory containing the Ovi services ** plugin source code. ** ****************************************************************************/ #include "qgeomapreply_nokia.h" QGeoMapReplyNokia::QGeoMapReplyNokia(QNetworkReply *reply, const QGeoTiledMapRequest &request, QObject *parent) : QGeoTiledMapReply(request, parent), m_reply(reply) { m_reply->setParent(this); QVariant fromCache = m_reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute); setCached(fromCache.toBool()); connect(m_reply, SIGNAL(finished()), this, SLOT(networkFinished())); connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(networkError(QNetworkReply::NetworkError))); connect(m_reply, SIGNAL(destroyed()), this, SLOT(replyDestroyed())); } QGeoMapReplyNokia::~QGeoMapReplyNokia() { } QNetworkReply* QGeoMapReplyNokia::networkReply() const { return m_reply; } void QGeoMapReplyNokia::abort() { if (!m_reply) return; m_reply->abort(); } void QGeoMapReplyNokia::replyDestroyed() { m_reply = 0; } void QGeoMapReplyNokia::networkFinished() { if (!m_reply) return; if (m_reply->error() != QNetworkReply::NoError) { return; } setMapImageData(m_reply->readAll()); setMapImageFormat("PNG"); setFinished(true); m_reply->deleteLater(); m_reply = 0; } void QGeoMapReplyNokia::networkError(QNetworkReply::NetworkError error) { if (!m_reply) return; if (error != QNetworkReply::OperationCanceledError) setError(QGeoTiledMapReply::CommunicationError, m_reply->errorString()); m_reply->deleteLater(); m_reply = 0; } <|endoftext|>
<commit_before>// Copyright 2015 Markus Ilmola // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. #include <fstream> #include <string> #include "generator/generator.hpp" using namespace generator; static void generateAxis(SvgWriter& svg, Axis axis) { gml::dvec3 color{}; color[static_cast<unsigned>(axis)] = 1.0; gml::dvec3 end{}; end[static_cast<unsigned>(axis)] = 1.5; LinePath line{gml::dvec3{}, end, gml::dvec3{}, 15u}; auto xx = line.vertices(); auto prev = xx.generate().position; xx.next(); while (!xx.done()) { auto current = xx.generate().position; svg.writeLine(prev, current, color); prev = current; xx.next(); } } template <typename T> void generateShape(const std::string& filename) { SvgWriter svg{400, 400}; svg.ortho(-1.5, 1.5, -1.5, 1.5); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); svg.writeShape(T{}, true, true); std::ofstream file(filename+".svg"); file << svg.str(); } template <typename T> void generatePath(const std::string& filename) { SvgWriter svg{800, 400}; T path{}; svg.perspective(1.0, 1.0, 0.1, 10.0); svg.viewport(0, 0, 400, 400); svg.modelView( gml::translate(gml::dvec3{-0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-45.0), 0.0}) ); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); generateAxis(svg, Axis::Z); svg.writePath(path, true, true); svg.viewport(400, 0, 400, 400); svg.modelView( gml::translate(gml::dvec3{0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-135.0), 0.0}) ); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); generateAxis(svg, Axis::Z); svg.writePath(path, true, true); std::ofstream file(filename+".svg"); file << svg.str(); } template <typename T> void generateMesh(const std::string& filename) { SvgWriter svg{800, 400}; T mesh{}; svg.perspective(1.0, 1.0, 0.1, 10.0); svg.viewport(0, 0, 400, 400); svg.modelView( gml::translate(gml::dvec3{-0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-45.0), 0.0}) ); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); generateAxis(svg, Axis::Z); svg.writeMesh(mesh, true, true); svg.viewport(400, 0, 400, 400); svg.modelView( gml::translate(gml::dvec3{0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-135.0), 0.0}) ); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); generateAxis(svg, Axis::Z); svg.writeMesh(mesh, true, true); std::ofstream file(filename+".svg"); file << svg.str(); } int main() { // Shapes generateShape<CircleShape>("CircleShape"); generateShape<EmptyShape>("EmptyShape"); generateShape<LineShape>("LineShape"); generateShape<RectangleShape>("RectangleShape"); generateShape<RoundedRectangleShape>("RoundedRectangleShape"); // Paths generatePath<EmptyPath>("EmptyPath"); generatePath<HelixPath>("HelixPath"); generatePath<KnotPath>("KnotPath"); generatePath<LinePath>("LinePath"); // Meshes generateMesh<BoxMesh>("BoxMesh"); generateMesh<CappedCylinderMesh>("CappedCylinderMesh"); generateMesh<CappedConeMesh>("CappedConeMesh"); generateMesh<CappedTubeMesh>("CappedTubeMesh"); generateMesh<ConeMesh>("ConeMesh"); generateMesh<CapsuleMesh>("CapsuleMesh"); generateMesh<ConvexPolygonMesh>("ConvexPolygonMesh"); generateMesh<CylinderMesh>("CylinderMesh"); generateMesh<DodecahedronMesh>("DodecahedronMesh"); generateMesh<DiskMesh>("DiskMesh"); generateMesh<EmptyMesh>("EmptyMesh"); generateMesh<IcosahedronMesh>("IcosahedronMesh"); generateMesh<IcoSphereMesh>("IcoSphereMesh"); generateMesh<PlaneMesh>("PlaneMesh"); generateMesh<RoundedBoxMesh>("RoundedBoxMesh"); generateMesh<SphereMesh>("SphereMesh"); generateMesh<SphericalConeMesh>("SphericalConeMesh"); generateMesh<SphericalTriangleMesh>("SphericalTriangleMesh"); generateMesh<SpringMesh>("SpringMesh"); generateMesh<TorusKnotMesh>("TorusKnotMesh"); generateMesh<TorusMesh>("TorusMesh"); generateMesh<TriangleMesh>("TriangleMesh"); generateMesh<TubeMesh>("TubeMesh"); // Group picture SvgWriter svg{1000, 400}; svg.perspective(1.0, 1.0, 0.1, 10.0); svg.modelView( gml::translate(gml::dvec3{-0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-45.0), 0.0}) ); svg.viewport(0, 200, 200, 200); svg.writeMesh(SphereMesh{}); svg.viewport(200, 200, 200, 200); svg.writeMesh(TorusMesh{}); svg.viewport(400, 200, 200, 200); svg.writeMesh(RoundedBoxMesh{}); svg.viewport(600, 200, 200, 200); svg.writeMesh(CappedTubeMesh{}); svg.viewport(800, 200, 200, 200); svg.writeMesh(TorusKnotMesh{}); svg.viewport(0, 0, 200, 200); svg.writeMesh(IcoSphereMesh{}); svg.viewport(200, 0, 200, 200); svg.writeMesh(CappedCylinderMesh{}); svg.viewport(400, 0, 200, 200); svg.writeMesh(CapsuleMesh{}); svg.viewport(600, 0, 200, 200); svg.writeMesh(SpringMesh{}); svg.viewport(800, 0, 200, 200); svg.writeMesh(CappedConeMesh{}); std::ofstream file("GroupPicture.svg"); file << svg.str(); return 0; } <commit_msg>Deduce the template arguments when generating preview images.<commit_after>// Copyright 2015 Markus Ilmola // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. #include <fstream> #include <string> #include "generator/generator.hpp" using namespace generator; static void generateAxis(SvgWriter& svg, Axis axis) { gml::dvec3 color{}; color[static_cast<unsigned>(axis)] = 1.0; gml::dvec3 end{}; end[static_cast<unsigned>(axis)] = 1.5; LinePath line{gml::dvec3{}, end, gml::dvec3{}, 15u}; auto xx = line.vertices(); auto prev = xx.generate().position; xx.next(); while (!xx.done()) { auto current = xx.generate().position; svg.writeLine(prev, current, color); prev = current; xx.next(); } } template <typename Shape> void generateShape(const Shape& shape, const std::string& filename) { SvgWriter svg{400, 400}; svg.ortho(-1.5, 1.5, -1.5, 1.5); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); svg.writeShape(shape, true, true); std::ofstream file(filename+".svg"); file << svg.str(); } template <typename Path> void generatePath(const Path& path, const std::string& filename) { SvgWriter svg{800, 400}; svg.perspective(1.0, 1.0, 0.1, 10.0); svg.viewport(0, 0, 400, 400); svg.modelView( gml::translate(gml::dvec3{-0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-45.0), 0.0}) ); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); generateAxis(svg, Axis::Z); svg.writePath(path, true, true); svg.viewport(400, 0, 400, 400); svg.modelView( gml::translate(gml::dvec3{0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-135.0), 0.0}) ); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); generateAxis(svg, Axis::Z); svg.writePath(path, true, true); std::ofstream file(filename+".svg"); file << svg.str(); } template <typename Mesh> void generateMesh(const Mesh& mesh, const std::string& filename) { SvgWriter svg{800, 400}; svg.perspective(1.0, 1.0, 0.1, 10.0); svg.viewport(0, 0, 400, 400); svg.modelView( gml::translate(gml::dvec3{-0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-45.0), 0.0}) ); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); generateAxis(svg, Axis::Z); svg.writeMesh(mesh, true, true); svg.viewport(400, 0, 400, 400); svg.modelView( gml::translate(gml::dvec3{0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-135.0), 0.0}) ); generateAxis(svg, Axis::X); generateAxis(svg, Axis::Y); generateAxis(svg, Axis::Z); svg.writeMesh(mesh, true, true); std::ofstream file(filename+".svg"); file << svg.str(); } int main() { // Shapes generateShape(CircleShape{}, "CircleShape"); generateShape(EmptyShape{}, "EmptyShape"); generateShape(LineShape{}, "LineShape"); generateShape(RectangleShape{}, "RectangleShape"); generateShape(RoundedRectangleShape{}, "RoundedRectangleShape"); // Paths generatePath(EmptyPath{}, "EmptyPath"); generatePath(HelixPath{}, "HelixPath"); generatePath(KnotPath{}, "KnotPath"); generatePath(LinePath{}, "LinePath"); // Meshes generateMesh(BoxMesh{}, "BoxMesh"); generateMesh(CappedCylinderMesh{}, "CappedCylinderMesh"); generateMesh(CappedConeMesh{}, "CappedConeMesh"); generateMesh(CappedTubeMesh{}, "CappedTubeMesh"); generateMesh(ConeMesh{}, "ConeMesh"); generateMesh(CapsuleMesh{}, "CapsuleMesh"); generateMesh(ConvexPolygonMesh{}, "ConvexPolygonMesh"); generateMesh(CylinderMesh{}, "CylinderMesh"); generateMesh(DodecahedronMesh{}, "DodecahedronMesh"); generateMesh(DiskMesh{}, "DiskMesh"); generateMesh(EmptyMesh{}, "EmptyMesh"); generateMesh(IcosahedronMesh{}, "IcosahedronMesh"); generateMesh(IcoSphereMesh{}, "IcoSphereMesh"); generateMesh(PlaneMesh{}, "PlaneMesh"); generateMesh(RoundedBoxMesh{}, "RoundedBoxMesh"); generateMesh(SphereMesh{}, "SphereMesh"); generateMesh(SphericalConeMesh{}, "SphericalConeMesh"); generateMesh(SphericalTriangleMesh{}, "SphericalTriangleMesh"); generateMesh(SpringMesh{}, "SpringMesh"); generateMesh(TorusKnotMesh{}, "TorusKnotMesh"); generateMesh(TorusMesh{}, "TorusMesh"); generateMesh(TriangleMesh{}, "TriangleMesh"); generateMesh(TubeMesh{}, "TubeMesh"); // Group picture SvgWriter svg{1000, 400}; svg.perspective(1.0, 1.0, 0.1, 10.0); svg.modelView( gml::translate(gml::dvec3{-0.0, 0.0, -4.0}) * gml::rotate(gml::dvec3{gml::radians(45.0), 0.0, 0.0}) * gml::rotate(gml::dvec3{0.0, gml::radians(-45.0), 0.0}) ); svg.viewport(0, 200, 200, 200); svg.writeMesh(SphereMesh{}); svg.viewport(200, 200, 200, 200); svg.writeMesh(TorusMesh{}); svg.viewport(400, 200, 200, 200); svg.writeMesh(RoundedBoxMesh{}); svg.viewport(600, 200, 200, 200); svg.writeMesh(CappedTubeMesh{}); svg.viewport(800, 200, 200, 200); svg.writeMesh(TorusKnotMesh{}); svg.viewport(0, 0, 200, 200); svg.writeMesh(IcoSphereMesh{}); svg.viewport(200, 0, 200, 200); svg.writeMesh(CappedCylinderMesh{}); svg.viewport(400, 0, 200, 200); svg.writeMesh(CapsuleMesh{}); svg.viewport(600, 0, 200, 200); svg.writeMesh(SpringMesh{}); svg.viewport(800, 0, 200, 200); svg.writeMesh(CappedConeMesh{}); std::ofstream file("GroupPicture.svg"); file << svg.str(); return 0; } <|endoftext|>
<commit_before><commit_msg>Add IsWindowActive to the Mac plugin interpose list<commit_after><|endoftext|>
<commit_before><commit_msg>Modifies Installation return codes to not return success (0) if an existing version was launched. Omaha needs to know the correct error result if it is to show the right error message to the user.<commit_after><|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 LunarG, Inc. * All Rights Reserved. * * Based on glretrace_glx.cpp, which has * * Copyright 2011 Jose Fonseca * * 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. * **************************************************************************/ #include "glproc.hpp" #include "retrace.hpp" #include "glretrace.hpp" #include "os.hpp" #include "eglsize.hpp" #ifndef EGL_OPENGL_ES_API #define EGL_OPENGL_ES_API 0x30A0 #define EGL_OPENVG_API 0x30A1 #define EGL_OPENGL_API 0x30A2 #define EGL_CONTEXT_CLIENT_VERSION 0x3098 #endif using namespace glretrace; typedef std::map<unsigned long long, glws::Drawable *> DrawableMap; typedef std::map<unsigned long long, Context *> ContextMap; typedef std::map<unsigned long long, glws::Profile> ProfileMap; static DrawableMap drawable_map; static ContextMap context_map; static ProfileMap profile_map; static unsigned int current_api = EGL_OPENGL_ES_API; /* * FIXME: Ideally we would defer the context creation until the profile was * clear, as explained in https://github.com/apitrace/apitrace/issues/197 , * instead of guessing. For now, start with a guess of ES2 profile, which * should be the most common case for EGL. */ static glws::Profile last_profile = glws::PROFILE_ES2; static void createDrawable(unsigned long long orig_config, unsigned long long orig_surface); static glws::Drawable * getDrawable(unsigned long long surface_ptr) { if (surface_ptr == 0) { return NULL; } DrawableMap::const_iterator it; it = drawable_map.find(surface_ptr); if (it == drawable_map.end()) { // In Fennec we get the egl window surface from Java which isn't // traced, so just create a drawable if it doesn't exist in here createDrawable(0, surface_ptr); it = drawable_map.find(surface_ptr); assert(it != drawable_map.end()); } return (it != drawable_map.end()) ? it->second : NULL; } static Context * getContext(unsigned long long context_ptr) { if (context_ptr == 0) { return NULL; } ContextMap::const_iterator it; it = context_map.find(context_ptr); return (it != context_map.end()) ? it->second : NULL; } static void createDrawable(unsigned long long orig_config, unsigned long long orig_surface) { ProfileMap::iterator it = profile_map.find(orig_config); glws::Profile profile; // If the requested config is associated with a profile, use that // profile. Otherwise, assume that the last used profile is what // the user wants. if (it != profile_map.end()) { profile = it->second; } else { profile = last_profile; } glws::Drawable *drawable = glretrace::createDrawable(profile); drawable_map[orig_surface] = drawable; } static void retrace_eglCreateWindowSurface(trace::Call &call) { unsigned long long orig_config = call.arg(1).toUIntPtr(); unsigned long long orig_surface = call.ret->toUIntPtr(); createDrawable(orig_config, orig_surface); } static void retrace_eglCreatePbufferSurface(trace::Call &call) { unsigned long long orig_config = call.arg(1).toUIntPtr(); unsigned long long orig_surface = call.ret->toUIntPtr(); createDrawable(orig_config, orig_surface); // TODO: Respect the pbuffer dimensions too } static void retrace_eglDestroySurface(trace::Call &call) { unsigned long long orig_surface = call.arg(1).toUIntPtr(); DrawableMap::iterator it; it = drawable_map.find(orig_surface); if (it != drawable_map.end()) { glretrace::Context *currentContext = glretrace::getCurrentContext(); if (!currentContext || it->second != currentContext->drawable) { // TODO: reference count delete it->second; } drawable_map.erase(it); } } static void retrace_eglBindAPI(trace::Call &call) { current_api = call.arg(0).toUInt(); eglBindAPI(current_api); } static void retrace_eglCreateContext(trace::Call &call) { unsigned long long orig_context = call.ret->toUIntPtr(); unsigned long long orig_config = call.arg(1).toUIntPtr(); Context *share_context = getContext(call.arg(2).toUIntPtr()); trace::Array *attrib_array = call.arg(3).toArray(); glws::Profile profile; switch (current_api) { case EGL_OPENGL_API: profile = glws::PROFILE_COMPAT; break; case EGL_OPENGL_ES_API: default: profile = glws::PROFILE_ES1; if (attrib_array) { for (int i = 0; i < attrib_array->values.size(); i += 2) { int v = attrib_array->values[i]->toSInt(); if (v == EGL_CONTEXT_CLIENT_VERSION) { v = attrib_array->values[i + 1]->toSInt(); if (v == 2) profile = glws::PROFILE_ES2; break; } } } break; } Context *context = glretrace::createContext(share_context, profile); if (!context) { const char *name; switch (profile) { case glws::PROFILE_COMPAT: name = "OpenGL"; break; case glws::PROFILE_ES1: name = "OpenGL ES 1.1"; break; case glws::PROFILE_ES2: name = "OpenGL ES 2.0"; break; default: name = "unknown"; break; } retrace::warning(call) << "Failed to create " << name << " context.\n"; exit(1); } context_map[orig_context] = context; profile_map[orig_config] = profile; last_profile = profile; } static void retrace_eglDestroyContext(trace::Call &call) { unsigned long long orig_context = call.arg(1).toUIntPtr(); ContextMap::iterator it; it = context_map.find(orig_context); if (it != context_map.end()) { glretrace::Context *currentContext = glretrace::getCurrentContext(); if (it->second != currentContext) { // TODO: reference count delete it->second; } context_map.erase(it); } } static void retrace_eglMakeCurrent(trace::Call &call) { glws::Drawable *new_drawable = getDrawable(call.arg(1).toUIntPtr()); Context *new_context = getContext(call.arg(3).toUIntPtr()); glretrace::makeCurrent(call, new_drawable, new_context); } static void retrace_eglSwapBuffers(trace::Call &call) { glws::Drawable *drawable = getDrawable(call.arg(1).toUIntPtr()); frame_complete(call); if (retrace::doubleBuffer) { if (drawable) { drawable->swapBuffers(); } } else { glFlush(); } } const retrace::Entry glretrace::egl_callbacks[] = { {"eglGetError", &retrace::ignore}, {"eglGetDisplay", &retrace::ignore}, {"eglInitialize", &retrace::ignore}, {"eglTerminate", &retrace::ignore}, {"eglQueryString", &retrace::ignore}, {"eglGetConfigs", &retrace::ignore}, {"eglChooseConfig", &retrace::ignore}, {"eglGetConfigAttrib", &retrace::ignore}, {"eglCreateWindowSurface", &retrace_eglCreateWindowSurface}, {"eglCreatePbufferSurface", &retrace_eglCreatePbufferSurface}, //{"eglCreatePixmapSurface", &retrace::ignore}, {"eglDestroySurface", &retrace_eglDestroySurface}, {"eglQuerySurface", &retrace::ignore}, {"eglBindAPI", &retrace_eglBindAPI}, {"eglQueryAPI", &retrace::ignore}, //{"eglWaitClient", &retrace::ignore}, //{"eglReleaseThread", &retrace::ignore}, //{"eglCreatePbufferFromClientBuffer", &retrace::ignore}, //{"eglSurfaceAttrib", &retrace::ignore}, //{"eglBindTexImage", &retrace::ignore}, //{"eglReleaseTexImage", &retrace::ignore}, {"eglSwapInterval", &retrace::ignore}, {"eglCreateContext", &retrace_eglCreateContext}, {"eglDestroyContext", &retrace_eglDestroyContext}, {"eglMakeCurrent", &retrace_eglMakeCurrent}, {"eglGetCurrentContext", &retrace::ignore}, {"eglGetCurrentSurface", &retrace::ignore}, {"eglGetCurrentDisplay", &retrace::ignore}, {"eglQueryContext", &retrace::ignore}, {"eglWaitGL", &retrace::ignore}, {"eglWaitNative", &retrace::ignore}, {"eglSwapBuffers", &retrace_eglSwapBuffers}, //{"eglCopyBuffers", &retrace::ignore}, {"eglGetProcAddress", &retrace::ignore}, {"eglCreateImageKHR", &retrace::ignore}, {"eglDestroyImageKHR", &retrace::ignore}, {"glEGLImageTargetTexture2DOES", &retrace::ignore}, {NULL, NULL}, }; <commit_msg>eglretrace: Support GL_OES_surfaceless_context by creating a dummy drawable.<commit_after>/************************************************************************** * * Copyright 2011 LunarG, Inc. * All Rights Reserved. * * Based on glretrace_glx.cpp, which has * * Copyright 2011 Jose Fonseca * * 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. * **************************************************************************/ #include "glproc.hpp" #include "retrace.hpp" #include "glretrace.hpp" #include "os.hpp" #include "eglsize.hpp" #ifndef EGL_OPENGL_ES_API #define EGL_OPENGL_ES_API 0x30A0 #define EGL_OPENVG_API 0x30A1 #define EGL_OPENGL_API 0x30A2 #define EGL_CONTEXT_CLIENT_VERSION 0x3098 #endif using namespace glretrace; typedef std::map<unsigned long long, glws::Drawable *> DrawableMap; typedef std::map<unsigned long long, Context *> ContextMap; typedef std::map<unsigned long long, glws::Profile> ProfileMap; static DrawableMap drawable_map; static ContextMap context_map; static ProfileMap profile_map; static unsigned int current_api = EGL_OPENGL_ES_API; /* * FIXME: Ideally we would defer the context creation until the profile was * clear, as explained in https://github.com/apitrace/apitrace/issues/197 , * instead of guessing. For now, start with a guess of ES2 profile, which * should be the most common case for EGL. */ static glws::Profile last_profile = glws::PROFILE_ES2; static glws::Drawable *null_drawable = NULL; static void createDrawable(unsigned long long orig_config, unsigned long long orig_surface); static glws::Drawable * getDrawable(unsigned long long surface_ptr) { if (surface_ptr == 0) { return NULL; } DrawableMap::const_iterator it; it = drawable_map.find(surface_ptr); if (it == drawable_map.end()) { // In Fennec we get the egl window surface from Java which isn't // traced, so just create a drawable if it doesn't exist in here createDrawable(0, surface_ptr); it = drawable_map.find(surface_ptr); assert(it != drawable_map.end()); } return (it != drawable_map.end()) ? it->second : NULL; } static Context * getContext(unsigned long long context_ptr) { if (context_ptr == 0) { return NULL; } ContextMap::const_iterator it; it = context_map.find(context_ptr); return (it != context_map.end()) ? it->second : NULL; } static void createDrawable(unsigned long long orig_config, unsigned long long orig_surface) { ProfileMap::iterator it = profile_map.find(orig_config); glws::Profile profile; // If the requested config is associated with a profile, use that // profile. Otherwise, assume that the last used profile is what // the user wants. if (it != profile_map.end()) { profile = it->second; } else { profile = last_profile; } glws::Drawable *drawable = glretrace::createDrawable(profile); drawable_map[orig_surface] = drawable; } static void retrace_eglCreateWindowSurface(trace::Call &call) { unsigned long long orig_config = call.arg(1).toUIntPtr(); unsigned long long orig_surface = call.ret->toUIntPtr(); createDrawable(orig_config, orig_surface); } static void retrace_eglCreatePbufferSurface(trace::Call &call) { unsigned long long orig_config = call.arg(1).toUIntPtr(); unsigned long long orig_surface = call.ret->toUIntPtr(); createDrawable(orig_config, orig_surface); // TODO: Respect the pbuffer dimensions too } static void retrace_eglDestroySurface(trace::Call &call) { unsigned long long orig_surface = call.arg(1).toUIntPtr(); DrawableMap::iterator it; it = drawable_map.find(orig_surface); if (it != drawable_map.end()) { glretrace::Context *currentContext = glretrace::getCurrentContext(); if (!currentContext || it->second != currentContext->drawable) { // TODO: reference count delete it->second; } drawable_map.erase(it); } } static void retrace_eglBindAPI(trace::Call &call) { current_api = call.arg(0).toUInt(); eglBindAPI(current_api); } static void retrace_eglCreateContext(trace::Call &call) { unsigned long long orig_context = call.ret->toUIntPtr(); unsigned long long orig_config = call.arg(1).toUIntPtr(); Context *share_context = getContext(call.arg(2).toUIntPtr()); trace::Array *attrib_array = call.arg(3).toArray(); glws::Profile profile; switch (current_api) { case EGL_OPENGL_API: profile = glws::PROFILE_COMPAT; break; case EGL_OPENGL_ES_API: default: profile = glws::PROFILE_ES1; if (attrib_array) { for (int i = 0; i < attrib_array->values.size(); i += 2) { int v = attrib_array->values[i]->toSInt(); if (v == EGL_CONTEXT_CLIENT_VERSION) { v = attrib_array->values[i + 1]->toSInt(); if (v == 2) profile = glws::PROFILE_ES2; break; } } } break; } Context *context = glretrace::createContext(share_context, profile); if (!context) { const char *name; switch (profile) { case glws::PROFILE_COMPAT: name = "OpenGL"; break; case glws::PROFILE_ES1: name = "OpenGL ES 1.1"; break; case glws::PROFILE_ES2: name = "OpenGL ES 2.0"; break; default: name = "unknown"; break; } retrace::warning(call) << "Failed to create " << name << " context.\n"; exit(1); } context_map[orig_context] = context; profile_map[orig_config] = profile; last_profile = profile; } static void retrace_eglDestroyContext(trace::Call &call) { unsigned long long orig_context = call.arg(1).toUIntPtr(); ContextMap::iterator it; it = context_map.find(orig_context); if (it != context_map.end()) { glretrace::Context *currentContext = glretrace::getCurrentContext(); if (it->second != currentContext) { // TODO: reference count delete it->second; } context_map.erase(it); } } static void retrace_eglMakeCurrent(trace::Call &call) { if (!call.ret->toSInt()) { // Previously current rendering context and surfaces (if any) remain // unchanged. return; } glws::Drawable *new_drawable = getDrawable(call.arg(1).toUIntPtr()); Context *new_context = getContext(call.arg(3).toUIntPtr()); // Try to support GL_OES_surfaceless_context by creating a dummy drawable. if (new_context && !new_drawable) { if (!null_drawable) { null_drawable = glretrace::createDrawable(last_profile); } new_drawable = null_drawable; } glretrace::makeCurrent(call, new_drawable, new_context); } static void retrace_eglSwapBuffers(trace::Call &call) { glws::Drawable *drawable = getDrawable(call.arg(1).toUIntPtr()); frame_complete(call); if (retrace::doubleBuffer) { if (drawable) { drawable->swapBuffers(); } } else { glFlush(); } } const retrace::Entry glretrace::egl_callbacks[] = { {"eglGetError", &retrace::ignore}, {"eglGetDisplay", &retrace::ignore}, {"eglInitialize", &retrace::ignore}, {"eglTerminate", &retrace::ignore}, {"eglQueryString", &retrace::ignore}, {"eglGetConfigs", &retrace::ignore}, {"eglChooseConfig", &retrace::ignore}, {"eglGetConfigAttrib", &retrace::ignore}, {"eglCreateWindowSurface", &retrace_eglCreateWindowSurface}, {"eglCreatePbufferSurface", &retrace_eglCreatePbufferSurface}, //{"eglCreatePixmapSurface", &retrace::ignore}, {"eglDestroySurface", &retrace_eglDestroySurface}, {"eglQuerySurface", &retrace::ignore}, {"eglBindAPI", &retrace_eglBindAPI}, {"eglQueryAPI", &retrace::ignore}, //{"eglWaitClient", &retrace::ignore}, //{"eglReleaseThread", &retrace::ignore}, //{"eglCreatePbufferFromClientBuffer", &retrace::ignore}, //{"eglSurfaceAttrib", &retrace::ignore}, //{"eglBindTexImage", &retrace::ignore}, //{"eglReleaseTexImage", &retrace::ignore}, {"eglSwapInterval", &retrace::ignore}, {"eglCreateContext", &retrace_eglCreateContext}, {"eglDestroyContext", &retrace_eglDestroyContext}, {"eglMakeCurrent", &retrace_eglMakeCurrent}, {"eglGetCurrentContext", &retrace::ignore}, {"eglGetCurrentSurface", &retrace::ignore}, {"eglGetCurrentDisplay", &retrace::ignore}, {"eglQueryContext", &retrace::ignore}, {"eglWaitGL", &retrace::ignore}, {"eglWaitNative", &retrace::ignore}, {"eglSwapBuffers", &retrace_eglSwapBuffers}, //{"eglCopyBuffers", &retrace::ignore}, {"eglGetProcAddress", &retrace::ignore}, {"eglCreateImageKHR", &retrace::ignore}, {"eglDestroyImageKHR", &retrace::ignore}, {"glEGLImageTargetTexture2DOES", &retrace::ignore}, {NULL, NULL}, }; <|endoftext|>
<commit_before>#include <LSM303DLH.h> #include <Wire.h> #include <math.h> // Defines //////////////////////////////////////////////////////////////// // The Arduino two-wire interface uses a 7-bit number for the address, // and sets the last bit correctly based on reads and writes #define ACC_ADDRESS (0x30 >> 1) #define MAG_ADDRESS (0x3C >> 1) // Constructors //////////////////////////////////////////////////////////////// LSM303DLH::LSM303DLH(void) { // These are just some values for a particular unit; it is recommended that // a calibration be done for your particular unit. m_max.x = +540; m_max.y = +500; m_max.z = 180; m_min.x = -520; m_min.y = -570; m_min.z = -770; } // Public Methods ////////////////////////////////////////////////////////////// // Turns on the LSM303DLH's accelerometer and magnetometers and places them in normal // mode. void LSM303DLH::enableDefault(void) { // Enable Accelerometer // 0x27 = 0b00100111 // Normal power mode, all axes enabled writeAccReg(LSM303DLH_CTRL_REG1_A, 0x27); // Enable Magnetometer // 0x00 = 0b00000000 // Continuous conversion mode writeMagReg(LSM303DLH_MR_REG_M, 0x00); } // Writes an accelerometer register void LSM303DLH::writeAccReg(byte reg, byte value) { Wire.beginTransmission(ACC_ADDRESS); Wire.send(reg); Wire.send(value); Wire.endTransmission(); } // Reads an accelerometer register byte LSM303DLH::readAccReg(byte reg) { byte value; Wire.beginTransmission(ACC_ADDRESS); Wire.send(reg); Wire.endTransmission(); Wire.requestFrom(ACC_ADDRESS, 1); value = Wire.receive(); Wire.endTransmission(); return value; } // Writes a magnetometer register void LSM303DLH::writeMagReg(byte reg, byte value) { Wire.beginTransmission(MAG_ADDRESS); Wire.send(reg); Wire.send(value); Wire.endTransmission(); } // Reads a magnetometer register byte LSM303DLH::readMagReg(byte reg) { byte value; Wire.beginTransmission(MAG_ADDRESS); Wire.send(reg); Wire.endTransmission(); Wire.requestFrom(MAG_ADDRESS, 1); value = Wire.receive(); Wire.endTransmission(); return value; } // Reads the 3 accelerometer channels and stores them in vector a void LSM303DLH::readAcc(void) { Wire.beginTransmission(ACC_ADDRESS); // assert the MSB of the address to get the accelerometer // to do slave-transmit subaddress updating. Wire.send(LSM303DLH_OUT_X_L_A | (1 << 7)); Wire.endTransmission(); Wire.requestFrom(ACC_ADDRESS, 6); while (Wire.available() < 6); uint8_t xla = Wire.receive(); uint8_t xha = Wire.receive(); uint8_t yla = Wire.receive(); uint8_t yha = Wire.receive(); uint8_t zla = Wire.receive(); uint8_t zha = Wire.receive(); a.x = (xha << 8 | xla) >> 4; a.y = (yha << 8 | yla) >> 4; a.z = (zha << 8 | zla) >> 4; } // Reads the 3 magnetometer channels and stores them in vector m void LSM303DLH::readMag(void) { Wire.beginTransmission(MAG_ADDRESS); Wire.send(LSM303DLH_OUT_X_H_M); Wire.endTransmission(); Wire.requestFrom(MAG_ADDRESS, 6); while (Wire.available() < 6); uint8_t xhm = Wire.receive(); uint8_t xlm = Wire.receive(); uint8_t yhm = Wire.receive(); uint8_t ylm = Wire.receive(); uint8_t zhm = Wire.receive(); uint8_t zlm = Wire.receive(); m.x = (xhm << 8 | xlm); m.y = (yhm << 8 | ylm); m.z = (zhm << 8 | zlm); } // Reads all 6 channels of the LSM303DLH and stores them in the object variables void LSM303DLH::read(void) { readAcc(); readMag(); } // Returns the number of degrees from the -Y axis that it // is pointing. int LSM303DLH::heading(void) { return heading((vector){0,-1,0}); } // Returns the number of degrees from the from vector that it // is pointing. int LSM303DLH::heading(vector from) { // shift and scale m.x = (m.x - m_min.x) / (m_max.x - m_min.x) * 2 - 1.0; m.y = (m.y - m_min.y) / (m_max.y - m_min.y) * 2 - 1.0; m.z = (m.z - m_min.z) / (m_max.z - m_min.z) * 2 - 1.0; vector temp_a = a; // normalize vector_normalize(&temp_a); //vector_normalize(&m); // compute E and N vector E; vector N; vector_cross(&m, &temp_a, &E); vector_normalize(&E); vector_cross(&temp_a, &E, &N); // compute heading int heading = round(atan2(vector_dot(&E, &from), vector_dot(&N, &from)) * 180 / M_PI); if (heading < 0) heading += 360; return heading; } void LSM303DLH::vector_cross(const vector *a,const vector *b, vector *out) { out->x = a->y*b->z - a->z*b->y; out->y = a->z*b->x - a->x*b->z; out->z = a->x*b->y - a->y*b->x; } float LSM303DLH::vector_dot(const vector *a,const vector *b) { return a->x*b->x+a->y*b->y+a->z*b->z; } void LSM303DLH::vector_normalize(vector *a) { float mag = sqrt(vector_dot(a,a)); a->x /= mag; a->y /= mag; a->z /= mag; }<commit_msg>adds comment explaining the heading algorithm<commit_after>#include <LSM303DLH.h> #include <Wire.h> #include <math.h> // Defines //////////////////////////////////////////////////////////////// // The Arduino two-wire interface uses a 7-bit number for the address, // and sets the last bit correctly based on reads and writes #define ACC_ADDRESS (0x30 >> 1) #define MAG_ADDRESS (0x3C >> 1) // Constructors //////////////////////////////////////////////////////////////// LSM303DLH::LSM303DLH(void) { // These are just some values for a particular unit; it is recommended that // a calibration be done for your particular unit. m_max.x = +540; m_max.y = +500; m_max.z = 180; m_min.x = -520; m_min.y = -570; m_min.z = -770; } // Public Methods ////////////////////////////////////////////////////////////// // Turns on the LSM303DLH's accelerometer and magnetometers and places them in normal // mode. void LSM303DLH::enableDefault(void) { // Enable Accelerometer // 0x27 = 0b00100111 // Normal power mode, all axes enabled writeAccReg(LSM303DLH_CTRL_REG1_A, 0x27); // Enable Magnetometer // 0x00 = 0b00000000 // Continuous conversion mode writeMagReg(LSM303DLH_MR_REG_M, 0x00); } // Writes an accelerometer register void LSM303DLH::writeAccReg(byte reg, byte value) { Wire.beginTransmission(ACC_ADDRESS); Wire.send(reg); Wire.send(value); Wire.endTransmission(); } // Reads an accelerometer register byte LSM303DLH::readAccReg(byte reg) { byte value; Wire.beginTransmission(ACC_ADDRESS); Wire.send(reg); Wire.endTransmission(); Wire.requestFrom(ACC_ADDRESS, 1); value = Wire.receive(); Wire.endTransmission(); return value; } // Writes a magnetometer register void LSM303DLH::writeMagReg(byte reg, byte value) { Wire.beginTransmission(MAG_ADDRESS); Wire.send(reg); Wire.send(value); Wire.endTransmission(); } // Reads a magnetometer register byte LSM303DLH::readMagReg(byte reg) { byte value; Wire.beginTransmission(MAG_ADDRESS); Wire.send(reg); Wire.endTransmission(); Wire.requestFrom(MAG_ADDRESS, 1); value = Wire.receive(); Wire.endTransmission(); return value; } // Reads the 3 accelerometer channels and stores them in vector a void LSM303DLH::readAcc(void) { Wire.beginTransmission(ACC_ADDRESS); // assert the MSB of the address to get the accelerometer // to do slave-transmit subaddress updating. Wire.send(LSM303DLH_OUT_X_L_A | (1 << 7)); Wire.endTransmission(); Wire.requestFrom(ACC_ADDRESS, 6); while (Wire.available() < 6); uint8_t xla = Wire.receive(); uint8_t xha = Wire.receive(); uint8_t yla = Wire.receive(); uint8_t yha = Wire.receive(); uint8_t zla = Wire.receive(); uint8_t zha = Wire.receive(); a.x = (xha << 8 | xla) >> 4; a.y = (yha << 8 | yla) >> 4; a.z = (zha << 8 | zla) >> 4; } // Reads the 3 magnetometer channels and stores them in vector m void LSM303DLH::readMag(void) { Wire.beginTransmission(MAG_ADDRESS); Wire.send(LSM303DLH_OUT_X_H_M); Wire.endTransmission(); Wire.requestFrom(MAG_ADDRESS, 6); while (Wire.available() < 6); uint8_t xhm = Wire.receive(); uint8_t xlm = Wire.receive(); uint8_t yhm = Wire.receive(); uint8_t ylm = Wire.receive(); uint8_t zhm = Wire.receive(); uint8_t zlm = Wire.receive(); m.x = (xhm << 8 | xlm); m.y = (yhm << 8 | ylm); m.z = (zhm << 8 | zlm); } // Reads all 6 channels of the LSM303DLH and stores them in the object variables void LSM303DLH::read(void) { readAcc(); readMag(); } // Returns the number of degrees from the -Y axis that it // is pointing. int LSM303DLH::heading(void) { return heading((vector){0,-1,0}); } // Returns the number of degrees from the From vector projected into // the horizontal plane is away from north. // // Description of heading algorithm: // Shift and scale the magnetic reading based on calibration data to // to find the North vector. Use the acceleration readings to // determine the Down vector. The cross product of North and Down // vectors is East. The vectors East and North form a basis for the // horizontal plane. The From vector is projected into the horizontal // plane and the angle between the projected vector and north is // returned. int LSM303DLH::heading(vector from) { // shift and scale m.x = (m.x - m_min.x) / (m_max.x - m_min.x) * 2 - 1.0; m.y = (m.y - m_min.y) / (m_max.y - m_min.y) * 2 - 1.0; m.z = (m.z - m_min.z) / (m_max.z - m_min.z) * 2 - 1.0; vector temp_a = a; // normalize vector_normalize(&temp_a); //vector_normalize(&m); // compute E and N vector E; vector N; vector_cross(&m, &temp_a, &E); vector_normalize(&E); vector_cross(&temp_a, &E, &N); // compute heading int heading = round(atan2(vector_dot(&E, &from), vector_dot(&N, &from)) * 180 / M_PI); if (heading < 0) heading += 360; return heading; } void LSM303DLH::vector_cross(const vector *a,const vector *b, vector *out) { out->x = a->y*b->z - a->z*b->y; out->y = a->z*b->x - a->x*b->z; out->z = a->x*b->y - a->y*b->x; } float LSM303DLH::vector_dot(const vector *a,const vector *b) { return a->x*b->x+a->y*b->y+a->z*b->z; } void LSM303DLH::vector_normalize(vector *a) { float mag = sqrt(vector_dot(a,a)); a->x /= mag; a->y /= mag; a->z /= mag; } <|endoftext|>
<commit_before>/* PubSubClient.cpp - A simple client for MQTT. Nicholas O'Leary http://knolleary.net */ #include "PubSubClient.h" #include <string.h> PubSubClient::PubSubClient() { this->_client = NULL; } PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), Client& client) { this->_client = &client; this->callback = callback; this->ip = ip; this->port = port; this->domain = NULL; } PubSubClient::PubSubClient(char* domain, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), Client& client) { this->_client = &client; this->callback = callback; this->domain = domain; this->port = port; } boolean PubSubClient::connect(char *id) { return connect(id,NULL,NULL,0,0,0,0); } boolean PubSubClient::connect(char *id, char *user, char *pass) { return connect(id,user,pass,0,0,0,0); } boolean PubSubClient::connect(char *id, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage) { return connect(id,NULL,NULL,willTopic,willQos,willRetain,willMessage); } boolean PubSubClient::connect(char *id, char *user, char *pass, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage) { if (!connected()) { int result = 0; if (domain != NULL) { result = _client->connect(this->domain, this->port); } else { result = _client->connect(this->ip, this->port); } if (result) { nextMsgId = 1; uint8_t d[9] = {0x00,0x06,'M','Q','I','s','d','p',MQTTPROTOCOLVERSION}; // Leave room in the buffer for header and variable length field uint16_t length = 5; unsigned int j; for (j = 0;j<9;j++) { buffer[length++] = d[j]; } uint8_t v; if (willTopic) { v = 0x06|(willQos<<3)|(willRetain<<5); } else { v = 0x02; } if(user != NULL) { v = v|0x80; if(pass != NULL) { v = v|(0x80>>1); } } buffer[length++] = v; buffer[length++] = ((MQTT_KEEPALIVE) >> 8); buffer[length++] = ((MQTT_KEEPALIVE) & 0xFF); length = writeString(id,buffer,length); if (willTopic) { length = writeString(willTopic,buffer,length); length = writeString(willMessage,buffer,length); } if(user != NULL) { length = writeString(user,buffer,length); if(pass != NULL) { length = writeString(pass,buffer,length); } } write(MQTTCONNECT,buffer,length-5); lastInActivity = lastOutActivity = millis(); while (!_client->available()) { unsigned long t = millis(); if (t-lastInActivity > MQTT_KEEPALIVE*1000UL) { _client->stop(); return false; } } uint8_t llen; uint16_t len = readPacket(&llen); if (len == 4 && buffer[3] == 0) { lastInActivity = millis(); pingOutstanding = false; return true; } } _client->stop(); } return false; } uint8_t PubSubClient::readByte() { while(!_client->available()) {} return _client->read(); } uint16_t PubSubClient::readPacket(uint8_t* lengthLength) { uint16_t len = 0; buffer[len++] = readByte(); uint8_t multiplier = 1; uint16_t length = 0; uint8_t digit = 0; do { digit = readByte(); buffer[len++] = digit; length += (digit & 127) * multiplier; multiplier *= 128; } while ((digit & 128) != 0); *lengthLength = len-1; for (uint16_t i = 0;i<length;i++) { if (len < MQTT_MAX_PACKET_SIZE) { buffer[len++] = readByte(); } else { readByte(); len = 0; // This will cause the packet to be ignored. } } return len; } boolean PubSubClient::loop() { if (connected()) { unsigned long t = millis(); if ((t - lastInActivity > MQTT_KEEPALIVE*1000UL) || (t - lastOutActivity > MQTT_KEEPALIVE*1000UL)) { if (pingOutstanding) { _client->stop(); return false; } else { buffer[0] = MQTTPINGREQ; buffer[1] = 0; _client->write(buffer,2); lastOutActivity = t; lastInActivity = t; pingOutstanding = true; } } if (_client->available()) { uint8_t llen; uint16_t len = readPacket(&llen); if (len > 0) { lastInActivity = t; uint8_t type = buffer[0]&0xF0; if (type == MQTTPUBLISH) { if (callback) { uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2]; char topic[tl+1]; for (uint16_t i=0;i<tl;i++) { topic[i] = buffer[llen+3+i]; } topic[tl] = 0; // ignore msgID - only support QoS 0 subs uint8_t *payload = buffer+llen+3+tl; callback(topic,payload,len-llen-3-tl); } } else if (type == MQTTPINGREQ) { buffer[0] = MQTTPINGRESP; buffer[1] = 0; _client->write(buffer,2); } else if (type == MQTTPINGRESP) { pingOutstanding = false; } } } return true; } return false; } boolean PubSubClient::publish(char* topic, char* payload) { return publish(topic,(uint8_t*)payload,strlen(payload),false); } boolean PubSubClient::publish(char* topic, uint8_t* payload, unsigned int plength) { return publish(topic, payload, plength, false); } boolean PubSubClient::publish(char* topic, uint8_t* payload, unsigned int plength, boolean retained) { if (connected()) { // Leave room in the buffer for header and variable length field uint16_t length = 5; length = writeString(topic,buffer,length); uint16_t i; for (i=0;i<plength;i++) { buffer[length++] = payload[i]; } uint8_t header = MQTTPUBLISH; if (retained) { header |= 1; } return write(header,buffer,length-5); } return false; } boolean PubSubClient::publish_P(char* topic, uint8_t* PROGMEM payload, unsigned int plength, boolean retained) { uint8_t llen = 0; uint8_t digit; int rc; uint16_t tlen; int pos = 0; int i; uint8_t header; unsigned int len; if (!connected()) { return false; } tlen = strlen(topic); header = MQTTPUBLISH; if (retained) { header |= 1; } buffer[pos++] = header; len = plength + 2 + tlen; do { digit = len % 128; len = len / 128; if (len > 0) { digit |= 0x80; } buffer[pos++] = digit; llen++; } while(len>0); pos = writeString(topic,buffer,pos); rc += _client->write(buffer,pos); for (i=0;i<plength;i++) { rc += _client->write((char)pgm_read_byte_near(payload + i)); } lastOutActivity = millis(); return rc == len + 1 + plength; } boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) { uint8_t lenBuf[4]; uint8_t llen = 0; uint8_t digit; uint8_t pos = 0; uint8_t rc; uint8_t len = length; do { digit = len % 128; len = len / 128; if (len > 0) { digit |= 0x80; } lenBuf[pos++] = digit; llen++; } while(len>0); buf[4-llen] = header; for (int i=0;i<llen;i++) { buf[5-llen+i] = lenBuf[i]; } rc = _client->write(buf+(4-llen),length+1+llen); lastOutActivity = millis(); return (rc == 1+llen+length); } boolean PubSubClient::subscribe(char* topic) { if (connected()) { // Leave room in the buffer for header and variable length field uint16_t length = 5; nextMsgId++; if (nextMsgId == 0) { nextMsgId = 1; } buffer[length++] = (nextMsgId >> 8); buffer[length++] = (nextMsgId & 0xFF); length = writeString(topic, buffer,length); buffer[length++] = 0; // Only do QoS 0 subs return write(MQTTSUBSCRIBE|MQTTQOS1,buffer,length-5); } return false; } boolean PubSubClient::unsubscribe(char* topic) { if (connected()) { uint16_t length = 5; nextMsgId++; if (nextMsgId == 0) { nextMsgId = 1; } buffer[length++] = (nextMsgId >> 8); buffer[length++] = (nextMsgId & 0xFF); length = writeString(topic, buffer,length); return write(MQTTUNSUBSCRIBE|MQTTQOS1,buffer,length-5); } return false; } void PubSubClient::disconnect() { buffer[0] = MQTTDISCONNECT; buffer[1] = 0; _client->write(buffer,2); _client->stop(); lastInActivity = lastOutActivity = millis(); } uint16_t PubSubClient::writeString(char* string, uint8_t* buf, uint16_t pos) { char* idp = string; uint16_t i = 0; pos += 2; while (*idp) { buf[pos++] = *idp++; i++; } buf[pos-i-2] = (i >> 8); buf[pos-i-1] = (i & 0xFF); return pos; } boolean PubSubClient::connected() { boolean rc; if (_client == NULL ) { rc = false; } else { rc = (int)_client->connected(); if (!rc) _client->stop(); } return rc; } <commit_msg>Fixing bug for large message packets<commit_after>/* PubSubClient.cpp - A simple client for MQTT. Nicholas O'Leary http://knolleary.net */ #include "PubSubClient.h" #include <string.h> PubSubClient::PubSubClient() { this->_client = NULL; } PubSubClient::PubSubClient(uint8_t *ip, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), Client& client) { this->_client = &client; this->callback = callback; this->ip = ip; this->port = port; this->domain = NULL; } PubSubClient::PubSubClient(char* domain, uint16_t port, void (*callback)(char*,uint8_t*,unsigned int), Client& client) { this->_client = &client; this->callback = callback; this->domain = domain; this->port = port; } boolean PubSubClient::connect(char *id) { return connect(id,NULL,NULL,0,0,0,0); } boolean PubSubClient::connect(char *id, char *user, char *pass) { return connect(id,user,pass,0,0,0,0); } boolean PubSubClient::connect(char *id, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage) { return connect(id,NULL,NULL,willTopic,willQos,willRetain,willMessage); } boolean PubSubClient::connect(char *id, char *user, char *pass, char* willTopic, uint8_t willQos, uint8_t willRetain, char* willMessage) { if (!connected()) { int result = 0; if (domain != NULL) { result = _client->connect(this->domain, this->port); } else { result = _client->connect(this->ip, this->port); } if (result) { nextMsgId = 1; uint8_t d[9] = {0x00,0x06,'M','Q','I','s','d','p',MQTTPROTOCOLVERSION}; // Leave room in the buffer for header and variable length field uint16_t length = 5; unsigned int j; for (j = 0;j<9;j++) { buffer[length++] = d[j]; } uint8_t v; if (willTopic) { v = 0x06|(willQos<<3)|(willRetain<<5); } else { v = 0x02; } if(user != NULL) { v = v|0x80; if(pass != NULL) { v = v|(0x80>>1); } } buffer[length++] = v; buffer[length++] = ((MQTT_KEEPALIVE) >> 8); buffer[length++] = ((MQTT_KEEPALIVE) & 0xFF); length = writeString(id,buffer,length); if (willTopic) { length = writeString(willTopic,buffer,length); length = writeString(willMessage,buffer,length); } if(user != NULL) { length = writeString(user,buffer,length); if(pass != NULL) { length = writeString(pass,buffer,length); } } write(MQTTCONNECT,buffer,length-5); lastInActivity = lastOutActivity = millis(); while (!_client->available()) { unsigned long t = millis(); if (t-lastInActivity > MQTT_KEEPALIVE*1000UL) { _client->stop(); return false; } } uint8_t llen; uint16_t len = readPacket(&llen); if (len == 4 && buffer[3] == 0) { lastInActivity = millis(); pingOutstanding = false; return true; } } _client->stop(); } return false; } uint8_t PubSubClient::readByte() { while(!_client->available()) {} return _client->read(); } uint16_t PubSubClient::readPacket(uint8_t* lengthLength) { uint16_t len = 0; buffer[len++] = readByte(); uint32_t multiplier = 1; uint16_t length = 0; uint8_t digit = 0; do { digit = readByte(); buffer[len++] = digit; length += (digit & 127) * multiplier; multiplier *= 128; } while ((digit & 128) != 0); *lengthLength = len-1; for (uint16_t i = 0;i<length;i++) { if (len < MQTT_MAX_PACKET_SIZE) { buffer[len++] = readByte(); } else { readByte(); len = 0; // This will cause the packet to be ignored. } } return len; } boolean PubSubClient::loop() { if (connected()) { unsigned long t = millis(); if ((t - lastInActivity > MQTT_KEEPALIVE*1000UL) || (t - lastOutActivity > MQTT_KEEPALIVE*1000UL)) { if (pingOutstanding) { _client->stop(); return false; } else { buffer[0] = MQTTPINGREQ; buffer[1] = 0; _client->write(buffer,2); lastOutActivity = t; lastInActivity = t; pingOutstanding = true; } } if (_client->available()) { uint8_t llen; uint16_t len = readPacket(&llen); if (len > 0) { lastInActivity = t; uint8_t type = buffer[0]&0xF0; if (type == MQTTPUBLISH) { if (callback) { uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2]; char topic[tl+1]; for (uint16_t i=0;i<tl;i++) { topic[i] = buffer[llen+3+i]; } topic[tl] = 0; // ignore msgID - only support QoS 0 subs uint8_t *payload = buffer+llen+3+tl; callback(topic,payload,len-llen-3-tl); } } else if (type == MQTTPINGREQ) { buffer[0] = MQTTPINGRESP; buffer[1] = 0; _client->write(buffer,2); } else if (type == MQTTPINGRESP) { pingOutstanding = false; } } } return true; } return false; } boolean PubSubClient::publish(char* topic, char* payload) { return publish(topic,(uint8_t*)payload,strlen(payload),false); } boolean PubSubClient::publish(char* topic, uint8_t* payload, unsigned int plength) { return publish(topic, payload, plength, false); } boolean PubSubClient::publish(char* topic, uint8_t* payload, unsigned int plength, boolean retained) { if (connected()) { // Leave room in the buffer for header and variable length field uint16_t length = 5; length = writeString(topic,buffer,length); uint16_t i; for (i=0;i<plength;i++) { buffer[length++] = payload[i]; } uint8_t header = MQTTPUBLISH; if (retained) { header |= 1; } return write(header,buffer,length-5); } return false; } boolean PubSubClient::publish_P(char* topic, uint8_t* PROGMEM payload, unsigned int plength, boolean retained) { uint8_t llen = 0; uint8_t digit; int rc; uint16_t tlen; int pos = 0; int i; uint8_t header; unsigned int len; if (!connected()) { return false; } tlen = strlen(topic); header = MQTTPUBLISH; if (retained) { header |= 1; } buffer[pos++] = header; len = plength + 2 + tlen; do { digit = len % 128; len = len / 128; if (len > 0) { digit |= 0x80; } buffer[pos++] = digit; llen++; } while(len>0); pos = writeString(topic,buffer,pos); rc += _client->write(buffer,pos); for (i=0;i<plength;i++) { rc += _client->write((char)pgm_read_byte_near(payload + i)); } lastOutActivity = millis(); return rc == len + 1 + plength; } boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) { uint8_t lenBuf[4]; uint8_t llen = 0; uint8_t digit; uint8_t pos = 0; uint8_t rc; uint8_t len = length; do { digit = len % 128; len = len / 128; if (len > 0) { digit |= 0x80; } lenBuf[pos++] = digit; llen++; } while(len>0); buf[4-llen] = header; for (int i=0;i<llen;i++) { buf[5-llen+i] = lenBuf[i]; } rc = _client->write(buf+(4-llen),length+1+llen); lastOutActivity = millis(); return (rc == 1+llen+length); } boolean PubSubClient::subscribe(char* topic) { if (connected()) { // Leave room in the buffer for header and variable length field uint16_t length = 5; nextMsgId++; if (nextMsgId == 0) { nextMsgId = 1; } buffer[length++] = (nextMsgId >> 8); buffer[length++] = (nextMsgId & 0xFF); length = writeString(topic, buffer,length); buffer[length++] = 0; // Only do QoS 0 subs return write(MQTTSUBSCRIBE|MQTTQOS1,buffer,length-5); } return false; } boolean PubSubClient::unsubscribe(char* topic) { if (connected()) { uint16_t length = 5; nextMsgId++; if (nextMsgId == 0) { nextMsgId = 1; } buffer[length++] = (nextMsgId >> 8); buffer[length++] = (nextMsgId & 0xFF); length = writeString(topic, buffer,length); return write(MQTTUNSUBSCRIBE|MQTTQOS1,buffer,length-5); } return false; } void PubSubClient::disconnect() { buffer[0] = MQTTDISCONNECT; buffer[1] = 0; _client->write(buffer,2); _client->stop(); lastInActivity = lastOutActivity = millis(); } uint16_t PubSubClient::writeString(char* string, uint8_t* buf, uint16_t pos) { char* idp = string; uint16_t i = 0; pos += 2; while (*idp) { buf[pos++] = *idp++; i++; } buf[pos-i-2] = (i >> 8); buf[pos-i-1] = (i & 0xFF); return pos; } boolean PubSubClient::connected() { boolean rc; if (_client == NULL ) { rc = false; } else { rc = (int)_client->connected(); if (!rc) _client->stop(); } return rc; } <|endoftext|>
<commit_before>#include <vector> #include <deque> #include <stdio.h> #include <sys/mman.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <stdlib.h> // Ros #include "ros/ros.h" #include "std_msgs/String.h" #include <lps/LPSRange.h> // System V IPC #include <sys/shm.h> //Used for shared memory #include <sys/sem.h> //Used for semaphores union semun { int val; /* Value for SETVAL */ struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ struct seminfo *__buf; /* Buffer for IPC_INFO (Linux-specific) */ }; #include <math.h> #include <loligo/core/Options.h> #include <loligo/core/Log.h> #include <loligo/serial_cobs/Serial.h> #include <loligo/core/StringUtils.h> #include <loligo/serial_cobs/RangePacket.h> static struct Option options[] = { { "device", OpType(OP_REQ), "/dev/ttyUSB*", "tty interface for lps, generally /dev/ttyUSBx" }, { "device-speed", OpType(OP_REQ), "115200", "serial speed" }, { "log-files", OpType(OP_REQ), "stdout", "comma separated list of files to send logging output" }, { "log-level", OpType(OP_REQ), "verbose", "output messages up to this level" }, { "map=<filename>", OpType(OP_REQ), "", "svg file to load map from" }, { "help", OpType(OP_NON), "", "-show help message"}, { "", 0, "", ""} }; std::vector<Serial*> _s; bool addSerialDevice(const string device, const string speed) { if (!Serial::checkDeviceFile(device.c_str())) return false; Serial *s = new Serial('\0'); if (!s->openDevice(device.c_str(), speed.c_str())) { delete s; return false; } _s.push_back(s); return true; } int main(int argc, char *argv[]) { Options opts(argc, argv, options); // initialize logging Log::init(&opts); if (opts("help")) { std::cerr << "lpsmonitor - monitor lps tags." << std::endl; std::cerr << "Options:" << std::endl; opts.printHelp(0); return 0; } ros::init(argc, argv, "lps_talker"); ros::NodeHandle n; ros::Publisher lps_pub = n.advertise<lps::LPSRange>("lpsranges", 100); ros::Rate loop_rate(10); // Open serial ports std::vector<std::string> device = opts.getStrings("device"); std::string speed = opts.getString("device-speed"); for (unsigned i=0;i<device.size();i++) { string dev = device[i]; // check for wildcards size_t wc_pos = dev.find("*"); if (wc_pos != string::npos) { for (unsigned i=0;i<100;i++) { string devn = dev.substr(0, wc_pos) + StringUtils::stringf("%d", i); addSerialDevice(devn,speed); } continue; } addSerialDevice(dev,speed); } vector<int> stimeouts(_s.size(),0); char result[512]; while (ros::ok()) { Log::print(LOG_INFO, "Loop start\n"); bool didsomething = false; for (unsigned i=0;i<_s.size();i++) { if (stimeouts[i]>10) continue; // Trigger transmission uint8_t d=0;_s[i]->write_bytes(&d,1); usleep(10000); if (!_s[i]->read_available()) { if (_s[i]->wait_for_data(50) != 1) { ROS_DEBUG("%d no data?\n",i); stimeouts[i]++; continue; } } int n=20; while (_s[i]->wait_for_data(50) > 0 && n-->0) { size_t plen = _s[i]->read_packet(result, sizeof(result)-1); if (plen == 0) continue; if (plen < 0) continue; double t = ros::Time::now().toSec(); Packet p; bool preadok = p.readFrom((uint8_t*)result, plen); if (!preadok) continue; if (p.type() != PACKET_TYPE_RANGE) continue; RangePacket rp(p); Log::print(LOG_INFO, "Received range from %x, anchor_id=%x\n", rp.from(), rp.anchorid()); if (rp.anchorid() > 0xff) continue; ROS_INFO("%.2x->%.2x %d",rp.from(),rp.anchorid(),rp.dist()); lps::LPSRange rangemsg; rangemsg.tag_id=rp.from(); rangemsg.dist_mm=rp.dist(); rangemsg.anchor_id=rp.anchorid(); rangemsg.power=rp.power(); lps_pub.publish(rangemsg); didsomething = true; } } if (!didsomething) for (unsigned i=0;i<stimeouts.size();i++) stimeouts[i]--; ros::spinOnce(); loop_rate.sleep(); } return 0; } <commit_msg>Removed semaphore stuff and some log-debug<commit_after>#include <vector> #include <deque> #include <stdio.h> #include <sys/mman.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <stdlib.h> // Ros #include "ros/ros.h" #include "std_msgs/String.h" #include <lps/LPSRange.h> #include <math.h> #include <loligo/core/Options.h> #include <loligo/core/Log.h> #include <loligo/serial_cobs/Serial.h> #include <loligo/core/StringUtils.h> #include <loligo/serial_cobs/RangePacket.h> static struct Option options[] = { { "device", OpType(OP_REQ), "/dev/ttyUSB*", "tty interface for lps, generally /dev/ttyUSBx" }, { "device-speed", OpType(OP_REQ), "115200", "serial speed" }, { "log-files", OpType(OP_REQ), "stdout", "comma separated list of files to send logging output" }, { "log-level", OpType(OP_REQ), "verbose", "output messages up to this level" }, { "map=<filename>", OpType(OP_REQ), "", "svg file to load map from" }, { "help", OpType(OP_NON), "", "-show help message"}, { "", 0, "", ""} }; std::vector<Serial*> _s; bool addSerialDevice(const string device, const string speed) { if (!Serial::checkDeviceFile(device.c_str())) return false; Serial *s = new Serial('\0'); if (!s->openDevice(device.c_str(), speed.c_str())) { delete s; return false; } _s.push_back(s); return true; } int main(int argc, char *argv[]) { Options opts(argc, argv, options); // initialize logging Log::init(&opts); if (opts("help")) { std::cerr << "lpsmonitor - monitor lps tags." << std::endl; std::cerr << "Options:" << std::endl; opts.printHelp(0); return 0; } ros::init(argc, argv, "lps_talker"); ros::NodeHandle n; ros::Publisher lps_pub = n.advertise<lps::LPSRange>("lpsranges", 100); ros::Rate loop_rate(10); // Open serial ports std::vector<std::string> device = opts.getStrings("device"); std::string speed = opts.getString("device-speed"); for (unsigned i=0;i<device.size();i++) { string dev = device[i]; // check for wildcards size_t wc_pos = dev.find("*"); if (wc_pos != string::npos) { for (unsigned i=0;i<100;i++) { string devn = dev.substr(0, wc_pos) + StringUtils::stringf("%d", i); addSerialDevice(devn,speed); } continue; } addSerialDevice(dev,speed); } vector<int> stimeouts(_s.size(),0); char result[512]; while (ros::ok()) { Log::print(LOG_INFO, "Loop start\n"); bool didsomething = false; for (unsigned i=0;i<_s.size();i++) { if (stimeouts[i]>10) continue; // Trigger transmission uint8_t d=0;_s[i]->write_bytes(&d,1); usleep(10000); if (!_s[i]->read_available()) { if (_s[i]->wait_for_data(50) != 1) { ROS_DEBUG("%d no data?\n",i); stimeouts[i]++; continue; } } int n=20; while (_s[i]->wait_for_data(50) > 0 && n-->0) { size_t plen = _s[i]->read_packet(result, sizeof(result)-1); if (plen == 0) continue; if (plen < 0) continue; ros::Time t = ros::Time::now(); Packet p; bool preadok = p.readFrom((uint8_t*)result, plen); if (!preadok) continue; if (p.type() != PACKET_TYPE_RANGE) continue; RangePacket rp(p); if (rp.anchorid() > 0xff) continue; lps::LPSRange rangemsg; rangemsg.tag_id=rp.from(); rangemsg.dist_mm=rp.dist(); rangemsg.anchor_id=rp.anchorid(); rangemsg.power=rp.power(); ROS_INFO("%.2x->%.2x %6dmm",rp.from(),rp.anchorid(),rp.dist()); lps_pub.publish(rangemsg); didsomething = true; } } if (!didsomething) for (unsigned i=0;i<stimeouts.size();i++) stimeouts[i]--; ros::spinOnce(); loop_rate.sleep(); } return 0; } <|endoftext|>
<commit_before><commit_msg>Rename tests.<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2016 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <chrono> #include <unordered_map> #include <seastar/core/timer.hh> #include "utils/exceptions.hh" namespace utils { // Simple variant of the "LoadingCache" used for permissions in origin. typedef lowres_clock loading_cache_clock_type; template<typename _Tp> class timestamped_val { private: std::experimental::optional<_Tp> _opt_value; loading_cache_clock_type::time_point _loaded; loading_cache_clock_type::time_point _last_read; public: timestamped_val() : _loaded(loading_cache_clock_type::now()) , _last_read(_loaded) {} timestamped_val(const timestamped_val&) = default; timestamped_val(timestamped_val&&) = default; // Make sure copy/move-assignments don't go through the template below timestamped_val& operator=(const timestamped_val&) = default; timestamped_val& operator=(timestamped_val&) = default; timestamped_val& operator=(timestamped_val&&) = default; template <typename U> timestamped_val& operator=(U&& new_val) { _opt_value = std::forward<U>(new_val); _loaded = loading_cache_clock_type::now(); return *this; } const _Tp& value() { _last_read = loading_cache_clock_type::now(); return _opt_value.value(); } explicit operator bool() const noexcept { return bool(_opt_value); } loading_cache_clock_type::time_point last_read() const noexcept { return _last_read; } loading_cache_clock_type::time_point loaded() const noexcept { return _loaded; } }; class shared_mutex { private: lw_shared_ptr<semaphore> _mutex_ptr; public: shared_mutex() : _mutex_ptr(make_lw_shared<semaphore>(1)) {} semaphore& get() const noexcept { return *_mutex_ptr; } }; template<typename _Key, typename _Tp, typename _Hash = std::hash<_Key>, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator<std::pair<const _Key, timestamped_val<_Tp>>>, typename SharedMutexMapAlloc = std::allocator<std::pair<const _Key, shared_mutex>>> class loading_cache { private: typedef timestamped_val<_Tp> ts_value_type; typedef std::unordered_map<_Key, ts_value_type, _Hash, _Pred, _Alloc> map_type; typedef std::unordered_map<_Key, shared_mutex, _Hash, _Pred, SharedMutexMapAlloc> write_mutex_map_type; typedef loading_cache<_Key, _Tp, _Hash, _Pred, _Alloc> _MyType; public: typedef _Tp value_type; typedef typename map_type::key_type key_type; typedef typename map_type::allocator_type allocator_type; typedef typename map_type::hasher hasher; typedef typename map_type::key_equal key_equal; typedef typename map_type::iterator iterator; template<typename Func> loading_cache(size_t max_size, std::chrono::milliseconds expiry, std::chrono::milliseconds refresh, logging::logger& logger, Func&& load, const hasher& hf = hasher(), const key_equal& eql = key_equal(), const allocator_type& a = allocator_type()) : _map(10, hf, eql, a) , _max_size(max_size) , _expiry(expiry) , _refresh(refresh) , _logger(logger) , _load(std::forward<Func>(load)) { // If expiration period is zero - caching is disabled if (!caching_enabled()) { return; } // Sanity check: if expiration period is given then non-zero refresh period and maximal size are required if (_refresh == std::chrono::milliseconds(0) || _max_size == 0) { throw exceptions::configuration_exception("loading_cache: caching is enabled but refresh period and/or max_size are zero"); } _timer.set_callback([this] { on_timer(); }); _timer.arm(_refresh); } future<_Tp> get(const _Key& k) { // If caching is disabled - always load in the foreground if (!caching_enabled()) { return _load(k); } // If the key is not in the cache yet, then _map[k] is going to create a // new uninitialized value in the map. If the value is already in the // cache (the fast path) simply return the value. Otherwise, take the // mutex and try to load the value (the slow path). ts_value_type& ts_val = _map[k]; if (ts_val) { return make_ready_future<_Tp>(ts_val.value()); } else { return slow_load(k); } } private: bool caching_enabled() const { return _expiry != std::chrono::milliseconds(0); } future<_Tp> slow_load(const _Key& k) { // If the key is not in the cache yet, then _write_mutex_map[k] is going // to create a new value with the initialized mutex. In this case a // mutex is going to serialize the producers and only the first one is // going to actually issue a load operation and initialize // the value with the received result. The rest are going to see (and // read) the initialized value when they enter the critical section. shared_mutex sm = _write_mutex_map[k]; return with_semaphore(sm.get(), 1, [this, k] { ts_value_type& ts_val = _map[k]; if (ts_val) { return make_ready_future<_Tp>(ts_val.value()); } _logger.trace("{}: storing the value for the first time", k); return _load(k).then([this, k] (_Tp t) { // we have to "re-read" the _map here because the value may have been evicted by now ts_value_type& ts_val = _map[k]; ts_val = std::move(t); return make_ready_future<_Tp>(ts_val.value()); }); }).finally([sm] {}); } future<> reload(const _Key& k, ts_value_type& ts_val) { return _load(k).then_wrapped([this, &ts_val, &k] (auto&& f) { // The exceptions are related to the load operation itself. // We should ignore them for the background reads - if // they persist the value will age and will be reloaded in // the forground. If the foreground READ fails the error // will be propagated up to the user and will fail the // corresponding query. try { ts_val = f.get0(); } catch (std::exception& e) { _logger.debug("{}: reload failed: {}", k, e.what()); } catch (...) { _logger.debug("{}: reload failed: unknown error", k); } }); } // We really miss the std::erase_if()... :( void drop_expired() { auto now = loading_cache_clock_type::now(); auto i = _map.begin(); auto e = _map.end(); while (i != e) { // An entry should be discarded if it hasn't been reloaded for too long or nobody cares about it anymore auto since_last_read = now - i->second.last_read(); auto since_loaded = now - i->second.loaded(); if (_expiry < since_last_read || _expiry < since_loaded) { using namespace std::chrono; _logger.trace("drop_expired(): {}: dropping the entry: _expiry {}, ms passed since: loaded {} last_read {}", i->first, _expiry.count(), duration_cast<milliseconds>(since_loaded).count(), duration_cast<milliseconds>(since_last_read).count()); i = _map.erase(i); continue; } ++i; } } // Shrink the cache to the _max_size discarding the least recently used items void shrink() { if (_max_size != 0 && _map.size() > _max_size) { std::vector<iterator> tmp; tmp.reserve(_map.size()); iterator i = _map.begin(); while (i != _map.end()) { tmp.emplace_back(i++); } std::sort(tmp.begin(), tmp.end(), [] (iterator i1, iterator i2) { return i1->second.last_read() < i2->second.last_read(); }); tmp.resize(_map.size() - _max_size); std::for_each(tmp.begin(), tmp.end(), [this] (auto& k) { using namespace std::chrono; _logger.trace("shrink(): {}: dropping the entry: ms since last_read {}", k->first, duration_cast<milliseconds>(loading_cache_clock_type::now() - k->second.last_read()).count()); _map.erase(k); }); } } void on_timer() { _logger.trace("on_timer(): start"); auto timer_start_tp = loading_cache_clock_type::now(); // Clear all cached mutexes _write_mutex_map.clear(); // Clean up items that were not touched for the whole _expiry period. drop_expired(); // Remove the least recently used items if map is too big. shrink(); // Reload all those which vlaue needs to be reloaded. parallel_for_each(_map.begin(), _map.end(), [this, curr_time = timer_start_tp] (auto& i) { _logger.trace("on_timer(): {}: checking the value age", i.first); if (i.second && i.second.loaded() + _refresh < curr_time) { _logger.trace("on_timer(): {}: reloading the value", i.first); return this->reload(i.first, i.second); } return now(); }).finally([this, timer_start_tp] { _logger.trace("on_timer(): rearming"); _timer.arm(timer_start_tp + _refresh); }); } map_type _map; write_mutex_map_type _write_mutex_map; size_t _max_size; std::chrono::milliseconds _expiry; std::chrono::milliseconds _refresh; logging::logger& _logger; std::function<future<_Tp>(const _Key&)> _load; timer<lowres_clock> _timer; }; } <commit_msg>utils::loading_cache: make the underlying map to be an intrusive unordered_set<commit_after>/* * Copyright (C) 2016 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <chrono> #include <unordered_map> #include <boost/intrusive/unordered_set.hpp> #include <seastar/core/timer.hh> #include "utils/exceptions.hh" namespace bi = boost::intrusive; namespace utils { // Simple variant of the "LoadingCache" used for permissions in origin. typedef lowres_clock loading_cache_clock_type; template<typename _Tp, typename _Key, typename _Hash, typename _EqualPred> class timestamped_val : public bi::unordered_set_base_hook<> { public: typedef _Key key_type; typedef _Tp value_type; private: std::experimental::optional<_Tp> _opt_value; loading_cache_clock_type::time_point _loaded; loading_cache_clock_type::time_point _last_read; _Key _key; public: struct key_eq { bool operator()(const _Key& k, const timestamped_val& c) const { return _EqualPred()(k, c.key()); } bool operator()(const timestamped_val& c, const _Key& k) const { return _EqualPred()(c.key(), k); } }; timestamped_val(const _Key& key) : _loaded(loading_cache_clock_type::now()) , _last_read(_loaded) , _key(key) {} timestamped_val(_Key&& key) : _loaded(loading_cache_clock_type::now()) , _last_read(_loaded) , _key(std::move(key)) {} timestamped_val(const timestamped_val&) = default; timestamped_val(timestamped_val&&) = default; // Make sure copy/move-assignments don't go through the template below timestamped_val& operator=(const timestamped_val&) = default; timestamped_val& operator=(timestamped_val&) = default; timestamped_val& operator=(timestamped_val&&) = default; template <typename U> timestamped_val& operator=(U&& new_val) { _opt_value = std::forward<U>(new_val); _loaded = loading_cache_clock_type::now(); return *this; } const _Tp& value() { _last_read = loading_cache_clock_type::now(); return _opt_value.value(); } explicit operator bool() const noexcept { return bool(_opt_value); } loading_cache_clock_type::time_point last_read() const noexcept { return _last_read; } loading_cache_clock_type::time_point loaded() const noexcept { return _loaded; } const _Key& key() const { return _key; } friend bool operator==(const timestamped_val& a, const timestamped_val& b){ return _EqualPred()(a.key(), b.key()); } friend std::size_t hash_value(const timestamped_val& v) { return _Hash()(v.key()); } }; class shared_mutex { private: lw_shared_ptr<semaphore> _mutex_ptr; public: shared_mutex() : _mutex_ptr(make_lw_shared<semaphore>(1)) {} semaphore& get() const noexcept { return *_mutex_ptr; } }; template<typename _Key, typename _Tp, typename _Hash = std::hash<_Key>, typename _Pred = std::equal_to<_Key>, typename _Alloc = std::allocator<timestamped_val<_Tp, _Key, _Hash, _Pred>>, typename SharedMutexMapAlloc = std::allocator<std::pair<const _Key, shared_mutex>>> class loading_cache { private: typedef timestamped_val<_Tp, _Key, _Hash, _Pred> ts_value_type; typedef bi::unordered_set<ts_value_type> set_type; typedef std::unordered_map<_Key, shared_mutex, _Hash, _Pred, SharedMutexMapAlloc> write_mutex_map_type; typedef loading_cache<_Key, _Tp, _Hash, _Pred, _Alloc> _MyType; typedef typename set_type::bucket_traits bi_set_bucket_traits; static constexpr int num_buckets = 1021; // A prime number close to 1024 public: typedef _Tp value_type; typedef _Key key_type; typedef typename set_type::iterator iterator; template<typename Func> loading_cache(size_t max_size, std::chrono::milliseconds expiry, std::chrono::milliseconds refresh, logging::logger& logger, Func&& load) : _buckets(num_buckets) , _set(bi_set_bucket_traits(_buckets.data(), _buckets.size())) , _max_size(max_size) , _expiry(expiry) , _refresh(refresh) , _logger(logger) , _load(std::forward<Func>(load)) { // If expiration period is zero - caching is disabled if (!caching_enabled()) { return; } // Sanity check: if expiration period is given then non-zero refresh period and maximal size are required if (_refresh == std::chrono::milliseconds(0) || _max_size == 0) { throw exceptions::configuration_exception("loading_cache: caching is enabled but refresh period and/or max_size are zero"); } _timer.set_callback([this] { on_timer(); }); _timer.arm(_refresh); } ~loading_cache() { _set.clear_and_dispose([] (ts_value_type* ptr) { loading_cache::destroy_ts_value(ptr); }); } future<_Tp> get(const _Key& k) { // If caching is disabled - always load in the foreground if (!caching_enabled()) { return _load(k); } // If the key is not in the cache yet, then find_or_create() is going to // create a new uninitialized value in the map. If the value is already // in the cache (the fast path) simply return the value. Otherwise, take // the mutex and try to load the value (the slow path). iterator ts_value_it = find_or_create(k); if (*ts_value_it) { return make_ready_future<_Tp>(ts_value_it->value()); } else { return slow_load(k); } } private: bool caching_enabled() const { return _expiry != std::chrono::milliseconds(0); } /// Look for the entry with the given key. It it doesn't exist - create a new one and add it to the _set. /// /// \param k The key to look for /// /// \return An iterator to the value with the given key (always dirrerent from _set.end()) template <typename KeyType> iterator find_or_create(KeyType&& k) { iterator i = _set.find(k, _Hash(), typename ts_value_type::key_eq()); if (i == _set.end()) { ts_value_type* new_ts_val = _Alloc().allocate(1); new(new_ts_val) ts_value_type(std::forward<KeyType>(k)); auto p = _set.insert(*new_ts_val); i = p.first; } return i; } static void destroy_ts_value(ts_value_type* val) { val->~ts_value_type(); _Alloc().deallocate(val, 1); } future<_Tp> slow_load(const _Key& k) { // If the key is not in the cache yet, then _write_mutex_map[k] is going // to create a new value with the initialized mutex. The mutex is going // to serialize the producers and only the first one is going to // actually issue a load operation and initialize the value with the // received result. The rest are going to see (and read) the initialized // value when they enter the critical section. shared_mutex sm = _write_mutex_map[k]; return with_semaphore(sm.get(), 1, [this, k] { iterator ts_value_it = find_or_create(k); if (*ts_value_it) { return make_ready_future<_Tp>(ts_value_it->value()); } _logger.trace("{}: storing the value for the first time", k); return _load(k).then([this, k] (_Tp t) { // we have to "re-read" the _set here because the value may have been evicted by now iterator ts_value_it = find_or_create(std::move(k)); *ts_value_it = std::move(t); return make_ready_future<_Tp>(ts_value_it->value()); }); }).finally([sm] {}); } future<> reload(ts_value_type& ts_val) { return _load(ts_val.key()).then_wrapped([this, &ts_val] (auto&& f) { // The exceptions are related to the load operation itself. // We should ignore them for the background reads - if // they persist the value will age and will be reloaded in // the forground. If the foreground READ fails the error // will be propagated up to the user and will fail the // corresponding query. try { ts_val = f.get0(); } catch (std::exception& e) { _logger.debug("{}: reload failed: {}", ts_val.key(), e.what()); } catch (...) { _logger.debug("{}: reload failed: unknown error", ts_val.key()); } }); } void erase(iterator it) { _set.erase_and_dispose(it, [] (ts_value_type* ptr) { loading_cache::destroy_ts_value(ptr); }); } // We really miss the std::erase_if()... :( void drop_expired() { auto now = loading_cache_clock_type::now(); auto i = _set.begin(); auto e = _set.end(); while (i != e) { // An entry should be discarded if it hasn't been reloaded for too long or nobody cares about it anymore auto since_last_read = now - i->last_read(); auto since_loaded = now - i->loaded(); if (_expiry < since_last_read || _expiry < since_loaded) { using namespace std::chrono; _logger.trace("drop_expired(): {}: dropping the entry: _expiry {}, ms passed since: loaded {} last_read {}", i->key(), _expiry.count(), duration_cast<milliseconds>(since_loaded).count(), duration_cast<milliseconds>(since_last_read).count()); erase(i++); continue; } ++i; } } // Shrink the cache to the _max_size discarding the least recently used items void shrink() { if (_max_size != 0 && _set.size() > _max_size) { std::vector<iterator> tmp; tmp.reserve(_set.size()); iterator i = _set.begin(); while (i != _set.end()) { tmp.emplace_back(i++); } std::sort(tmp.begin(), tmp.end(), [] (iterator i1, iterator i2) { return i1->last_read() < i2->last_read(); }); tmp.resize(_set.size() - _max_size); std::for_each(tmp.begin(), tmp.end(), [this] (auto& k) { using namespace std::chrono; _logger.trace("shrink(): {}: dropping the entry: ms since last_read {}", k->key(), duration_cast<milliseconds>(loading_cache_clock_type::now() - k->last_read()).count()); this->erase(k); }); } } void on_timer() { _logger.trace("on_timer(): start"); auto timer_start_tp = loading_cache_clock_type::now(); // Clear all cached mutexes _write_mutex_map.clear(); // Clean up items that were not touched for the whole _expiry period. drop_expired(); // Remove the least recently used items if map is too big. shrink(); // Reload all those which vlaue needs to be reloaded. parallel_for_each(_set.begin(), _set.end(), [this, curr_time = timer_start_tp] (auto& ts_val) { _logger.trace("on_timer(): {}: checking the value age", ts_val.key()); if (ts_val && ts_val.loaded() + _refresh < curr_time) { _logger.trace("on_timer(): {}: reloading the value", ts_val.key()); return this->reload(ts_val); } return now(); }).finally([this, timer_start_tp] { _logger.trace("on_timer(): rearming"); _timer.arm(timer_start_tp + _refresh); }); } std::vector<typename set_type::bucket_type> _buckets; set_type _set; write_mutex_map_type _write_mutex_map; size_t _max_size; std::chrono::milliseconds _expiry; std::chrono::milliseconds _refresh; logging::logger& _logger; std::function<future<_Tp>(const _Key&)> _load; timer<lowres_clock> _timer; }; } <|endoftext|>
<commit_before>/* * Copyright (C) 2012 * Alessio Sclocco <a.sclocco@vu.nl> * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <string> #include <vector> #include <cmath> #include <cstring> using std::string; using std::vector; using std::make_pair; using std::pow; using std::ceil; #include <Exceptions.hpp> #include <CLData.hpp> #include <utils.hpp> #include <Kernel.hpp> #include <Observation.hpp> using isa::Exceptions::OpenCLError; using isa::OpenCL::CLData; using isa::utils::giga; using isa::utils::toStringValue; using isa::utils::toString; using isa::utils::replace; using isa::OpenCL::Kernel; using AstroData::Observation; #ifndef FOLDING_HPP #define FOLDING_HPP namespace PulsarSearch { // OpenCL folding algorithm template< typename T > class Folding : public Kernel< T > { public: Folding(string name, string dataType); void generateCode() throw (OpenCLError); void operator()(unsigned int second, CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError); inline void setNrDMsPerBlock(unsigned int DMs); inline void setObservation(Observation< T > * obs); private: unsigned int nrDMsPerBlock; cl::NDRange globalSize; cl::NDRange localSize; Observation< T > * observation; }; // Implementation template< typename T > Folding< T >::Folding(string name, string dataType) : Kernel< T >(name, dataType), nrDMsPerBlock(0), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), observation(0) {} template< typename T > void Folding< T >::generateCode() throw (OpenCLError) { // Begin kernel's template string nrSamplesPerSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerSecond()); string nrPaddedDMs_s = toStringValue< unsigned int >(observation->getNrPaddedDMs()); string nrPeriods_s = toStringValue< unsigned int >(observation->getNrPeriods()); string nrDMsPerBlock_s = toStringValue< unsigned int >(nrDMsPerBlock); string nrBins_s = toStringValue< unsigned int >(observation->getNrBins()); delete this->code; this->code = new string(); *(this->code) = "__kernel void " + this->name + "(const unsigned int second, __global const " + this->dataType + " * const restrict samples, __global " + this->dataType + " * const restrict bins, __global unsigned int * const restrict counters) {\n" "const unsigned int DM = (get_group_id(0) * " + nrDMsPerBlock_s + ") + get_local_id(0);\n" "const unsigned int period = get_group_id(1);\n" "const unsigned int periodValue = (get_group_id(1) + 1) * " + nrBins_s + ";\n" "const unsigned int bin = get_group_id(2);\n" "const unsigned int pCounter = counters[(get_group_id(2) * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (get_group_id(1) * " + nrPaddedDMs_s + ") + DM];\n" "unsigned int foldedCounter = 0;\n" + this->dataType + "foldedSample = 0;\n" "\n" "unsigned int sample = (bin * period) + bin + ((pCounter / (period + 1)) * periodValue) + (pCounter % (period + 1));\n" "if ( (sample % "+ nrSamplesPerSecond_s + ") == 0 ) {\n" "sample = 0;\n" "} else {\n" "sample = (sample % "+ nrSamplesPerSecond_s + ") - (sample / "+ nrSamplesPerSecond_s + ");\n" "}\n" "while ( sample < " + nrSamplesPerSecond_s + " ) {\n" "foldedSample += samples[(sample * " + nrPaddedDMs_s + ") + DM];\n" "foldedCounter++;\n" "if ( ((foldedCounter + pCounter) % (period + 1)) == 0 ) {\n" "sample += periodValue;\n" "} else {\n" "sample++;\n" "}\n" "}\n" "if ( foldedCounter > 0 ) {\n" "const unsigned int outputItem = (bin * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period * " + nrPaddedDMs_s + ") + DM;\n" "const "+ this->dataType + " pValue = bins[outputItem];\n" + this->dataType + " addedFraction = 0;" "addedFraction = convert_float(foldedCounter) / (foldedCounter + pCounter);\n" "foldedSample /= foldedCounter;\n" "counters[outputItem] = pCounter + foldedCounter;\n" "bins[outputItem] = (addedFraction * foldedSample) + ((1.0f - addedFraction) * pValue);\n" "}\n" "}\n"; globalSize = cl::NDRange(observation->getNrDMs(), observation->getNrPeriods(), observation->getNrBins()); localSize = cl::NDRange(nrDMsPerBlock, 1, 1); this->gflop = giga(static_cast< long long unsigned int >(observation->getNrDMs()) * observation->getNrPeriods() * observation->getNrSamplesPerSecond()); this->compile(); } template< typename T > void Folding< T >::operator()(unsigned int second, CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError) { this->setArgument(0, second); this->setArgument(1, *(input->getDeviceData())); this->setArgument(2, *(output->getDeviceData())); this->setArgument(3, *(counters->getDeviceData())); this->run(globalSize, localSize); } template< typename T > inline void Folding< T >::setNrDMsPerBlock(unsigned int DMs) { nrDMsPerBlock = DMs; } template< typename T > inline void Folding< T >::setObservation(Observation< T > * obs) { observation = obs; } } // PulsarSearch #endif // FOLDING_HPP <commit_msg>Typo in the OpenCL kernel.<commit_after>/* * Copyright (C) 2012 * Alessio Sclocco <a.sclocco@vu.nl> * * This program 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. * */ #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #include <string> #include <vector> #include <cmath> #include <cstring> using std::string; using std::vector; using std::make_pair; using std::pow; using std::ceil; #include <Exceptions.hpp> #include <CLData.hpp> #include <utils.hpp> #include <Kernel.hpp> #include <Observation.hpp> using isa::Exceptions::OpenCLError; using isa::OpenCL::CLData; using isa::utils::giga; using isa::utils::toStringValue; using isa::utils::toString; using isa::utils::replace; using isa::OpenCL::Kernel; using AstroData::Observation; #ifndef FOLDING_HPP #define FOLDING_HPP namespace PulsarSearch { // OpenCL folding algorithm template< typename T > class Folding : public Kernel< T > { public: Folding(string name, string dataType); void generateCode() throw (OpenCLError); void operator()(unsigned int second, CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError); inline void setNrDMsPerBlock(unsigned int DMs); inline void setObservation(Observation< T > * obs); private: unsigned int nrDMsPerBlock; cl::NDRange globalSize; cl::NDRange localSize; Observation< T > * observation; }; // Implementation template< typename T > Folding< T >::Folding(string name, string dataType) : Kernel< T >(name, dataType), nrDMsPerBlock(0), globalSize(cl::NDRange(1, 1, 1)), localSize(cl::NDRange(1, 1, 1)), observation(0) {} template< typename T > void Folding< T >::generateCode() throw (OpenCLError) { // Begin kernel's template string nrSamplesPerSecond_s = toStringValue< unsigned int >(observation->getNrSamplesPerSecond()); string nrPaddedDMs_s = toStringValue< unsigned int >(observation->getNrPaddedDMs()); string nrPeriods_s = toStringValue< unsigned int >(observation->getNrPeriods()); string nrDMsPerBlock_s = toStringValue< unsigned int >(nrDMsPerBlock); string nrBins_s = toStringValue< unsigned int >(observation->getNrBins()); delete this->code; this->code = new string(); *(this->code) = "__kernel void " + this->name + "(const unsigned int second, __global const " + this->dataType + " * const restrict samples, __global " + this->dataType + " * const restrict bins, __global unsigned int * const restrict counters) {\n" "const unsigned int DM = (get_group_id(0) * " + nrDMsPerBlock_s + ") + get_local_id(0);\n" "const unsigned int period = get_group_id(1);\n" "const unsigned int periodValue = (get_group_id(1) + 1) * " + nrBins_s + ";\n" "const unsigned int bin = get_group_id(2);\n" "const unsigned int pCounter = counters[(get_group_id(2) * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (get_group_id(1) * " + nrPaddedDMs_s + ") + DM];\n" "unsigned int foldedCounter = 0;\n" + this->dataType + " foldedSample = 0;\n" "\n" "unsigned int sample = (bin * period) + bin + ((pCounter / (period + 1)) * periodValue) + (pCounter % (period + 1));\n" "if ( (sample % "+ nrSamplesPerSecond_s + ") == 0 ) {\n" "sample = 0;\n" "} else {\n" "sample = (sample % "+ nrSamplesPerSecond_s + ") - (sample / "+ nrSamplesPerSecond_s + ");\n" "}\n" "while ( sample < " + nrSamplesPerSecond_s + " ) {\n" "foldedSample += samples[(sample * " + nrPaddedDMs_s + ") + DM];\n" "foldedCounter++;\n" "if ( ((foldedCounter + pCounter) % (period + 1)) == 0 ) {\n" "sample += periodValue;\n" "} else {\n" "sample++;\n" "}\n" "}\n" "if ( foldedCounter > 0 ) {\n" "const unsigned int outputItem = (bin * " + nrPeriods_s + " * " + nrPaddedDMs_s + ") + (period * " + nrPaddedDMs_s + ") + DM;\n" "const "+ this->dataType + " pValue = bins[outputItem];\n" + this->dataType + " addedFraction = 0;" "addedFraction = convert_float(foldedCounter) / (foldedCounter + pCounter);\n" "foldedSample /= foldedCounter;\n" "counters[outputItem] = pCounter + foldedCounter;\n" "bins[outputItem] = (addedFraction * foldedSample) + ((1.0f - addedFraction) * pValue);\n" "}\n" "}\n"; globalSize = cl::NDRange(observation->getNrDMs(), observation->getNrPeriods(), observation->getNrBins()); localSize = cl::NDRange(nrDMsPerBlock, 1, 1); this->gflop = giga(static_cast< long long unsigned int >(observation->getNrDMs()) * observation->getNrPeriods() * observation->getNrSamplesPerSecond()); this->compile(); } template< typename T > void Folding< T >::operator()(unsigned int second, CLData< T > * input, CLData< T > * output, CLData< unsigned int > * counters) throw (OpenCLError) { this->setArgument(0, second); this->setArgument(1, *(input->getDeviceData())); this->setArgument(2, *(output->getDeviceData())); this->setArgument(3, *(counters->getDeviceData())); this->run(globalSize, localSize); } template< typename T > inline void Folding< T >::setNrDMsPerBlock(unsigned int DMs) { nrDMsPerBlock = DMs; } template< typename T > inline void Folding< T >::setObservation(Observation< T > * obs) { observation = obs; } } // PulsarSearch #endif // FOLDING_HPP <|endoftext|>
<commit_before>#include <cassert> #include <cstring> #include <iostream> #include <map> #include <sstream> #include <stdexcept> #include <string> #include <vector> // 1) Try to use N4082's any class, or fall back to Boost's. // 2) Try to use N4082's string_view class, or fall back to std::string #ifdef __has_include # if __has_include(<experimental/any>) # include <experimental/any> # define BENCODE_ANY_NS std::experimental # else # include <boost/any.hpp> # define BENCODE_ANY_NS boost # endif # if __has_include(<experimental/string_view>) # include <experimental/string_view> # define BENCODE_HAS_STRING_VIEW # define BENCODE_STRING_VIEW std::experimental::string_view # else # define BENCODE_STRING_VIEW std::string # endif #else # include <boost/any.hpp> # define BENCODE_ANY_NS boost # define BENCODE_STRING_VIEW std::string #endif namespace bencode { using any = BENCODE_ANY_NS::any; using string = std::string; using integer = long long; using list = std::vector<BENCODE_ANY_NS::any>; using dict = std::map<std::string, BENCODE_ANY_NS::any>; #ifdef BENCODE_HAS_STRING_VIEW using string_view = BENCODE_STRING_VIEW; using dict_view = std::map<BENCODE_STRING_VIEW, BENCODE_ANY_NS::any>; #else using string_view = void; using dict_view = void; #endif template<typename T> BENCODE_ANY_NS::any decode(T &begin, T end); namespace detail { template<bool View, typename T> BENCODE_ANY_NS::any decode_data(T &begin, T end); template<typename T> integer decode_int_real(T &begin, T end) { assert(*begin == 'i'); ++begin; bool positive = true; if(*begin == '-') { positive = false; ++begin; } // TODO: handle overflow integer value = 0; for(; begin != end && std::isdigit(*begin); ++begin) value = value * 10 + *begin - '0'; if(begin == end) throw std::invalid_argument("unexpected end of string"); if(*begin != 'e') throw std::invalid_argument("expected 'e'"); ++begin; return positive ? value : -value; } template<bool View, typename T> inline integer decode_int(T &begin, T end) { return decode_int_real(begin, end); } template<bool View> struct str_reader { template<typename T, typename U> string operator ()(T &begin, T end, U len) { if(std::distance(begin, end) < static_cast<ssize_t>(len)) throw std::invalid_argument("unexpected end of string"); std::string value(len, 0); std::copy_n(begin, len, value.begin()); std::advance(begin, len); return value; } // XXX: This should be used for all single-pass iterators, not just // std::istreambuf_iterator. template<typename T, typename U> string operator ()(std::istreambuf_iterator<T> &begin, std::istreambuf_iterator<T> end, U len) { std::string value(len, 0); for(U i = 0; i < len; i++) { value[i] = *begin; if(++begin == end) throw std::invalid_argument("unexpected end of string"); } return value; } }; template<> struct str_reader<true> { template<typename T, typename U> string_view operator ()(T &begin, T end, U len) { if(std::distance(begin, end) < static_cast<ssize_t>(len)) throw std::invalid_argument("unexpected end of string"); string_view value(begin, len); std::advance(begin, len); return value; } }; template<bool View, typename T> typename std::conditional<View, string_view, string>::type decode_str(T &begin, T end) { assert(std::isdigit(*begin)); size_t len = 0; for(; begin != end && std::isdigit(*begin); ++begin) len = len * 10 + *begin - '0'; if(begin == end) throw std::invalid_argument("unexpected end of string"); if(*begin != ':') throw std::invalid_argument("expected ':'"); ++begin; return str_reader<View>{}(begin, end, len); } template<bool View, typename T> list decode_list(T &begin, T end) { assert(*begin == 'l'); ++begin; list value; while(begin != end && *begin != 'e') { value.push_back(decode_data<View>(begin, end)); } if(begin == end) throw std::invalid_argument("unexpected end of string"); ++begin; return value; } template<bool View, typename T> typename std::conditional<View, dict_view, dict>::type decode_dict(T &begin, T end) { assert(*begin == 'd'); ++begin; typename std::conditional<View, dict_view, dict>::type value; while(begin != end && *begin != 'e') { if(!std::isdigit(*begin)) throw std::invalid_argument("expected string token"); auto key = decode_str<View>(begin, end); value[key] = decode_data<View>(begin, end); } if(begin == end) throw std::invalid_argument("unexpected end of string"); ++begin; return value; } template<bool View, typename T> BENCODE_ANY_NS::any decode_data(T &begin, T end) { if(begin == end) return BENCODE_ANY_NS::any(); if(*begin == 'i') return decode_int<View>(begin, end); else if(*begin == 'l') return decode_list<View>(begin, end); else if(*begin == 'd') return decode_dict<View>(begin, end); else if(std::isdigit(*begin)) return decode_str<View>(begin, end); throw std::invalid_argument("unexpected type"); } } template<typename T> inline BENCODE_ANY_NS::any decode(T &begin, T end) { return detail::decode_data<false>(begin, end); } template<typename T> inline BENCODE_ANY_NS::any decode(const T &begin, T end) { T b(begin); return detail::decode_data<false>(b, end); } inline BENCODE_ANY_NS::any decode(const BENCODE_STRING_VIEW &s) { return decode(s.begin(), s.end()); } inline BENCODE_ANY_NS::any decode(std::istream &s) { std::istreambuf_iterator<char> begin(s), end; return decode(begin, end); } template<typename T> inline BENCODE_ANY_NS::any decode_view(T &begin, T end) { return detail::decode_data<true>(begin, end); } template<typename T> inline BENCODE_ANY_NS::any decode_view(const T &begin, T end) { T b(begin); return detail::decode_data<true>(b, end); } inline BENCODE_ANY_NS::any decode_view(const BENCODE_STRING_VIEW &s) { return decode_view(s.begin(), s.end()); } class list_encoder { public: inline list_encoder(std::ostream &os) : os(os) { os.put('l'); } template<typename T> inline list_encoder & add(T &&value); inline void end() { os.put('e'); } private: std::ostream &os; }; class dict_encoder { public: inline dict_encoder(std::ostream &os) : os(os) { os.put('d'); } template<typename T> inline dict_encoder & add(const BENCODE_STRING_VIEW &key, T &&value); inline void end() { os.put('e'); } private: std::ostream &os; }; // TODO: make these use unformatted output? inline void encode(std::ostream &os, integer value) { os << "i" << value << "e"; } inline void encode(std::ostream &os, const BENCODE_STRING_VIEW &value) { os << value.size() << ":" << value; } template<typename T> void encode(std::ostream &os, const std::vector<T> &value); template<typename T> void encode(std::ostream &os, const std::map<std::string, T> &value); // Overload for `any`, but only if the passed-in type is already `any`. Don't // accept an implicit conversion! template<typename T> auto encode(std::ostream &os, const T &value) -> typename std::enable_if<std::is_same<T, BENCODE_ANY_NS::any>::value>::type { using BENCODE_ANY_NS::any_cast; auto &type = value.type(); if(type == typeid(integer)) encode(os, any_cast<integer>(value)); else if(type == typeid(string)) encode(os, any_cast<string>(value)); else if(type == typeid(list)) encode(os, any_cast<list>(value)); else if(type == typeid(dict)) encode(os, any_cast<dict>(value)); else throw std::invalid_argument("unexpected type"); } template<typename T> void encode(std::ostream &os, const std::vector<T> &value) { list_encoder e(os); for(auto &&i : value) e.add(i); e.end(); } template<typename T> void encode(std::ostream &os, const std::map<std::string, T> &value) { dict_encoder e(os); for(auto &&i : value) e.add(i.first, i.second); e.end(); } namespace detail { inline void encode_list_items(list_encoder &) {} template<typename T, typename ...Rest> void encode_list_items(list_encoder &enc, T &&t, Rest &&...rest) { enc.add(std::forward<T>(t)); encode_list_items(enc, std::forward<Rest>(rest)...); } inline void encode_dict_items(dict_encoder &) {} template<typename Key, typename Value, typename ...Rest> void encode_dict_items(dict_encoder &enc, Key &&key, Value &&value, Rest &&...rest) { enc.add(std::forward<Key>(key), std::forward<Value>(value)); encode_dict_items(enc, std::forward<Rest>(rest)...); } } template<typename ...T> void encode_list(std::ostream &os, T &&...t) { list_encoder enc(os); detail::encode_list_items(enc, std::forward<T>(t)...); enc.end(); } template<typename ...T> void encode_dict(std::ostream &os, T &&...t) { dict_encoder enc(os); detail::encode_dict_items(enc, std::forward<T>(t)...); enc.end(); } template<typename T> inline list_encoder & list_encoder::add(T &&value) { encode(os, std::forward<T>(value)); return *this; } template<typename T> inline dict_encoder & dict_encoder::add(const BENCODE_STRING_VIEW &key, T &&value) { encode(os, key); encode(os, std::forward<T>(value)); return *this; } template<typename T> std::string encode(T &&t) { std::stringstream ss; encode(ss, t); return ss.str(); } } <commit_msg>Emplace the values into the dict for fewer copies<commit_after>#include <cassert> #include <cstring> #include <iostream> #include <map> #include <sstream> #include <stdexcept> #include <string> #include <vector> // 1) Try to use N4082's any class, or fall back to Boost's. // 2) Try to use N4082's string_view class, or fall back to std::string #ifdef __has_include # if __has_include(<experimental/any>) # include <experimental/any> # define BENCODE_ANY_NS std::experimental # else # include <boost/any.hpp> # define BENCODE_ANY_NS boost # endif # if __has_include(<experimental/string_view>) # include <experimental/string_view> # define BENCODE_HAS_STRING_VIEW # define BENCODE_STRING_VIEW std::experimental::string_view # else # define BENCODE_STRING_VIEW std::string # endif #else # include <boost/any.hpp> # define BENCODE_ANY_NS boost # define BENCODE_STRING_VIEW std::string #endif namespace bencode { using any = BENCODE_ANY_NS::any; using string = std::string; using integer = long long; using list = std::vector<BENCODE_ANY_NS::any>; using dict = std::map<std::string, BENCODE_ANY_NS::any>; #ifdef BENCODE_HAS_STRING_VIEW using string_view = BENCODE_STRING_VIEW; using dict_view = std::map<BENCODE_STRING_VIEW, BENCODE_ANY_NS::any>; #else using string_view = void; using dict_view = void; #endif template<typename T> BENCODE_ANY_NS::any decode(T &begin, T end); namespace detail { template<bool View, typename T> BENCODE_ANY_NS::any decode_data(T &begin, T end); template<typename T> integer decode_int_real(T &begin, T end) { assert(*begin == 'i'); ++begin; bool positive = true; if(*begin == '-') { positive = false; ++begin; } // TODO: handle overflow integer value = 0; for(; begin != end && std::isdigit(*begin); ++begin) value = value * 10 + *begin - '0'; if(begin == end) throw std::invalid_argument("unexpected end of string"); if(*begin != 'e') throw std::invalid_argument("expected 'e'"); ++begin; return positive ? value : -value; } template<bool View, typename T> inline integer decode_int(T &begin, T end) { return decode_int_real(begin, end); } template<bool View> struct str_reader { template<typename T, typename U> string operator ()(T &begin, T end, U len) { if(std::distance(begin, end) < static_cast<ssize_t>(len)) throw std::invalid_argument("unexpected end of string"); std::string value(len, 0); std::copy_n(begin, len, value.begin()); std::advance(begin, len); return value; } // XXX: This should be used for all single-pass iterators, not just // std::istreambuf_iterator. template<typename T, typename U> string operator ()(std::istreambuf_iterator<T> &begin, std::istreambuf_iterator<T> end, U len) { std::string value(len, 0); for(U i = 0; i < len; i++) { value[i] = *begin; if(++begin == end) throw std::invalid_argument("unexpected end of string"); } return value; } }; template<> struct str_reader<true> { template<typename T, typename U> string_view operator ()(T &begin, T end, U len) { if(std::distance(begin, end) < static_cast<ssize_t>(len)) throw std::invalid_argument("unexpected end of string"); string_view value(begin, len); std::advance(begin, len); return value; } }; template<bool View, typename T> typename std::conditional<View, string_view, string>::type decode_str(T &begin, T end) { assert(std::isdigit(*begin)); size_t len = 0; for(; begin != end && std::isdigit(*begin); ++begin) len = len * 10 + *begin - '0'; if(begin == end) throw std::invalid_argument("unexpected end of string"); if(*begin != ':') throw std::invalid_argument("expected ':'"); ++begin; return str_reader<View>{}(begin, end, len); } template<bool View, typename T> list decode_list(T &begin, T end) { assert(*begin == 'l'); ++begin; list value; while(begin != end && *begin != 'e') { value.push_back(decode_data<View>(begin, end)); } if(begin == end) throw std::invalid_argument("unexpected end of string"); ++begin; return value; } template<bool View, typename T> typename std::conditional<View, dict_view, dict>::type decode_dict(T &begin, T end) { assert(*begin == 'd'); ++begin; typename std::conditional<View, dict_view, dict>::type value; while(begin != end && *begin != 'e') { if(!std::isdigit(*begin)) throw std::invalid_argument("expected string token"); value.emplace(decode_str<View>(begin, end), decode_data<View>(begin, end)); } if(begin == end) throw std::invalid_argument("unexpected end of string"); ++begin; return value; } template<bool View, typename T> BENCODE_ANY_NS::any decode_data(T &begin, T end) { if(begin == end) return BENCODE_ANY_NS::any(); if(*begin == 'i') return decode_int<View>(begin, end); else if(*begin == 'l') return decode_list<View>(begin, end); else if(*begin == 'd') return decode_dict<View>(begin, end); else if(std::isdigit(*begin)) return decode_str<View>(begin, end); throw std::invalid_argument("unexpected type"); } } template<typename T> inline BENCODE_ANY_NS::any decode(T &begin, T end) { return detail::decode_data<false>(begin, end); } template<typename T> inline BENCODE_ANY_NS::any decode(const T &begin, T end) { T b(begin); return detail::decode_data<false>(b, end); } inline BENCODE_ANY_NS::any decode(const BENCODE_STRING_VIEW &s) { return decode(s.begin(), s.end()); } inline BENCODE_ANY_NS::any decode(std::istream &s) { std::istreambuf_iterator<char> begin(s), end; return decode(begin, end); } template<typename T> inline BENCODE_ANY_NS::any decode_view(T &begin, T end) { return detail::decode_data<true>(begin, end); } template<typename T> inline BENCODE_ANY_NS::any decode_view(const T &begin, T end) { T b(begin); return detail::decode_data<true>(b, end); } inline BENCODE_ANY_NS::any decode_view(const BENCODE_STRING_VIEW &s) { return decode_view(s.begin(), s.end()); } class list_encoder { public: inline list_encoder(std::ostream &os) : os(os) { os.put('l'); } template<typename T> inline list_encoder & add(T &&value); inline void end() { os.put('e'); } private: std::ostream &os; }; class dict_encoder { public: inline dict_encoder(std::ostream &os) : os(os) { os.put('d'); } template<typename T> inline dict_encoder & add(const BENCODE_STRING_VIEW &key, T &&value); inline void end() { os.put('e'); } private: std::ostream &os; }; // TODO: make these use unformatted output? inline void encode(std::ostream &os, integer value) { os << "i" << value << "e"; } inline void encode(std::ostream &os, const BENCODE_STRING_VIEW &value) { os << value.size() << ":" << value; } template<typename T> void encode(std::ostream &os, const std::vector<T> &value); template<typename T> void encode(std::ostream &os, const std::map<std::string, T> &value); // Overload for `any`, but only if the passed-in type is already `any`. Don't // accept an implicit conversion! template<typename T> auto encode(std::ostream &os, const T &value) -> typename std::enable_if<std::is_same<T, BENCODE_ANY_NS::any>::value>::type { using BENCODE_ANY_NS::any_cast; auto &type = value.type(); if(type == typeid(integer)) encode(os, any_cast<integer>(value)); else if(type == typeid(string)) encode(os, any_cast<string>(value)); else if(type == typeid(list)) encode(os, any_cast<list>(value)); else if(type == typeid(dict)) encode(os, any_cast<dict>(value)); else throw std::invalid_argument("unexpected type"); } template<typename T> void encode(std::ostream &os, const std::vector<T> &value) { list_encoder e(os); for(auto &&i : value) e.add(i); e.end(); } template<typename T> void encode(std::ostream &os, const std::map<std::string, T> &value) { dict_encoder e(os); for(auto &&i : value) e.add(i.first, i.second); e.end(); } namespace detail { inline void encode_list_items(list_encoder &) {} template<typename T, typename ...Rest> void encode_list_items(list_encoder &enc, T &&t, Rest &&...rest) { enc.add(std::forward<T>(t)); encode_list_items(enc, std::forward<Rest>(rest)...); } inline void encode_dict_items(dict_encoder &) {} template<typename Key, typename Value, typename ...Rest> void encode_dict_items(dict_encoder &enc, Key &&key, Value &&value, Rest &&...rest) { enc.add(std::forward<Key>(key), std::forward<Value>(value)); encode_dict_items(enc, std::forward<Rest>(rest)...); } } template<typename ...T> void encode_list(std::ostream &os, T &&...t) { list_encoder enc(os); detail::encode_list_items(enc, std::forward<T>(t)...); enc.end(); } template<typename ...T> void encode_dict(std::ostream &os, T &&...t) { dict_encoder enc(os); detail::encode_dict_items(enc, std::forward<T>(t)...); enc.end(); } template<typename T> inline list_encoder & list_encoder::add(T &&value) { encode(os, std::forward<T>(value)); return *this; } template<typename T> inline dict_encoder & dict_encoder::add(const BENCODE_STRING_VIEW &key, T &&value) { encode(os, key); encode(os, std::forward<T>(value)); return *this; } template<typename T> std::string encode(T &&t) { std::stringstream ss; encode(ss, t); return ss.str(); } } <|endoftext|>
<commit_before> #ifndef __BIG_INT_HPP__ #define __BIG_INT_HPP__ #include <cmath> #include <cstdint> #include <cstdlib> #include <ostream> #include <string> #include <tuple> #include <vector> namespace hausp { class big_int { friend std::ostream& operator<<(std::ostream&, const big_int&); using UNIT = uint32_t; using num_vector = std::vector<UNIT>; static constexpr auto UNIT_MAX = 999999999ULL; static constexpr auto UNIT_RADIX = 1000000000ULL; public: big_int() = default; template<typename T, std::enable_if_t<std::is_signed<T>::value, int> = 0> big_int(T); template<typename T, std::enable_if_t<std::is_unsigned<T>::value, int> = 0> big_int(T); big_int(const std::string&); operator std::string() const; private: num_vector data = {}; bool sign = false; static num_vector convert_base(uintmax_t); static num_vector convert_base(const std::string&); }; template<typename T, std::enable_if_t<std::is_signed<T>::value, int>> big_int::big_int(T value): data{convert_base(std::abs(value))}, sign{value < 0} { } template<typename T, std::enable_if_t<std::is_unsigned<T>::value, int>> big_int::big_int(T value): data{convert_base(value)} { } inline big_int::big_int(const std::string& str_value) { data = convert_base(str_value); } inline big_int::num_vector big_int::convert_base(uintmax_t value) { num_vector data; if (value > UNIT_MAX) { while (value > UNIT_MAX) { uintmax_t q = value / UNIT_RADIX; uintmax_t r = value % UNIT_RADIX; data.push_back(r); value = q; } if (value != 0) { data.push_back(value); } } else { data.push_back(value); } return data; } inline big_int::num_vector big_int::convert_base(const std::string& str_value) { num_vector data; auto i = str_value.size(); while (i > 0) { if (i > 8) { i = i - 9; data.push_back(std::stoull(str_value.substr(i, 9))); } else { data.push_back(std::stoull(str_value.substr(0, i))); i = 0; } } return data; } inline std::ostream& operator<<(std::ostream& out, const big_int& number) { if (number.sign) out << "-"; auto last = number.data.size() - 1; for (size_t i = last + 1; i > 0; --i) { auto index = i - 1; auto fragment = std::to_string(number.data[index]); if (index != last) { while (fragment.size() < 9) { fragment.insert(0, 1, '0'); } } out << fragment; } return out; } } #endif /* __BIG_INT_HPP__ */ <commit_msg>Comparison operators added<commit_after> #ifndef __BIG_INT_HPP__ #define __BIG_INT_HPP__ #include <cmath> #include <cstdint> #include <cstdlib> #include <string> #include <ostream> #include <tuple> #include <vector> namespace hausp { class big_int { // Friend non-member operators friend std::ostream& operator<<(std::ostream&, const big_int&); friend bool operator==(const big_int&, const big_int&); friend bool operator<(const big_int&, const big_int&); // Aliases using UNIT = uint32_t; using num_vector = std::vector<UNIT>; // Constant values static constexpr auto UNIT_MAX = 999999999ULL; static constexpr auto UNIT_RADIX = 1000000000ULL; static constexpr auto PRIMITIVE_MAX = UINT32_MAX; public: big_int() = default; template<typename T, std::enable_if_t<std::is_signed<T>::value, int> = 0> big_int(T); template<typename T, std::enable_if_t<std::is_unsigned<T>::value, int> = 0> big_int(T); big_int(const std::string&); private: num_vector data = {}; bool sign = false; static num_vector convert_base(uintmax_t); static num_vector convert_base(const std::string&); }; template<typename T, std::enable_if_t<std::is_signed<T>::value, int>> big_int::big_int(T value): data{convert_base(std::abs(value))}, sign{value < 0} { } template<typename T, std::enable_if_t<std::is_unsigned<T>::value, int>> big_int::big_int(T value): data{convert_base(value)} { } inline big_int::big_int(const std::string& str_value) { data = convert_base(str_value); } inline big_int::num_vector big_int::convert_base(uintmax_t value) { num_vector data; if (value > UNIT_MAX) { while (value > UNIT_MAX) { uintmax_t q = value / UNIT_RADIX; uintmax_t r = value % UNIT_RADIX; data.push_back(r); value = q; } if (value != 0) { data.push_back(value); } } else { data.push_back(value); } return data; } inline big_int::num_vector big_int::convert_base(const std::string& str_value) { num_vector data; auto i = str_value.size(); while (i > 0) { if (i > 8) { i = i - 9; data.push_back(std::stoull(str_value.substr(i, 9))); } else { data.push_back(std::stoull(str_value.substr(0, i))); i = 0; } } return data; } inline bool operator==(const big_int& lhs, const big_int& rhs) { if (lhs.sign != rhs.sign) { return false; } else if (lhs.data.size() == rhs.data.size()) { size_t i = lhs.data.size() - 1; while (i > 0 && lhs.data[i] == rhs.data[i]) --i; return i == 0 && lhs.data[i] == rhs.data[i]; } return false; } inline bool operator!=(const big_int& lhs, const big_int rhs) { return !(lhs == rhs); } inline bool operator<(const big_int& lhs, const big_int& rhs) { if (lhs.sign != rhs.sign) { return lhs.sign; } else if (lhs.data.size() == rhs.data.size()) { size_t i = lhs.data.size() - 1; while (i > 0 && lhs.data[i] == rhs.data[i]) --i; return lhs.data[i] < rhs.data[i]; } return lhs.data.size() < rhs.data.size(); } inline bool operator>(const big_int& lhs, const big_int& rhs) { return rhs < lhs; } inline bool operator<=(const big_int& lhs, const big_int& rhs) { return !(lhs > rhs); } inline bool operator>=(const big_int& lhs, const big_int& rhs) { return !(lhs < rhs); } inline std::ostream& operator<<(std::ostream& out, const big_int& number) { if (number.sign) out << "-"; auto last = number.data.size() - 1; for (size_t i = last + 1; i > 0; --i) { auto index = i - 1; auto fragment = std::to_string(number.data[index]); if (index != last) { while (fragment.size() < 9) { fragment.insert(0, 1, '0'); } } out << fragment; } return out; } } #endif /* __BIG_INT_HPP__ */ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <vector> #include <string> #include <iostream> #include "money.hpp" #include "date.hpp" #include "accounts.hpp" #include "assets.hpp" namespace budget { inline std::string red(const std::string& str){ return "\033[0;31m" + str + "\033[0;3047m"; } inline std::string green(const std::string& str){ return "\033[0;32m" + str + "\033[0;3047m"; } inline std::string cyan(const std::string& str){ return "\033[0;33m" + str + "\033[0;3047m"; } std::string format_money(const budget::money& m); std::string format_money_no_color(const budget::money& m); std::string format_money_reverse(const budget::money& m); /** * Returns the real size of a string. By default, accented characteres are * represented by several chars and make the length of the string being bigger * than its displayable length. This functionr returns only a size of 1 for an * accented chars. * \param value The string we want the real length for. * \return The real length of the string. */ size_t rsize(const std::string& value); size_t rsize_after(const std::string& value); template<typename T> void print_minimum(std::ostream& os, const T& value, size_t min_width){ auto str = to_string(value); auto old_width = os.width(); os.width(min_width + (str.size() - rsize(str))); os << str; os.width(old_width); } template<typename T> void print_minimum(const T& value, size_t min_width){ print_minimum(std::cout, value, min_width); } template<typename T> void print_minimum_left(std::ostream& os, const T& value, size_t min_width){ auto str = to_string(value); if(rsize(str) >= min_width){ os << str; } else { os << std::string(min_width - rsize(str), ' '); os << str; } } template<typename T> void print_minimum_left(const T& value, size_t min_width){ print_minimum_left(std::cout, value, min_width); } /** * Indicate if the given option was present in the list. If present, the option * is removed from the list. * \param option The full option name with any - included * \param args The command line arguments * \return true if the option was present, false otherwise. */ bool option(const std::string& option, std::vector<std::string>& args); /** * Return the value of the given option if present or the default value * otherwise * \param option The full option name with any - included * \param args The command line arguments * \return The string value of the option or the default value is not present. */ std::string option_value(const std::string& option, std::vector<std::string>& args, const std::string& value); std::string format_code(int attr, int fg, int bg); std::string format_reset(); template<typename T> bool check(const T&){ return true; } template<typename T, typename CheckerA, typename ...Checker> bool check(const T& value, CheckerA first, Checker... checkers){ if(!first(value)){ std::cout << first.message() << std::endl; return false; } return check(value, checkers...); } std::string get_string_complete(const std::vector<std::string>& choices); template<typename ...Checker> void edit_string_complete(std::string& ref, const std::string& title, const std::vector<std::string>& choices, Checker... checkers){ bool checked; do { std::cout << title << " [" << ref << "]: "; auto answer = get_string_complete(choices); if(!answer.empty()){ ref = answer; } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_string(std::string& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ ref = answer; } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_number(size_t& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ ref = to_number<size_t>(answer); } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_double(double& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ ref = to_number<double>(answer); } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_money(budget::money& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ ref = parse_money(answer); } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_date(date& ref, const std::string& title, Checker... checkers){ bool checked; do { try { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ bool math = false; if(answer[0] == '+'){ std::string str(std::next(answer.begin()), std::prev(answer.end())); if(answer.back() == 'd'){ ref += days(std::stoi(str)); math = true; } else if(answer.back() == 'm'){ ref += months(std::stoi(str)); math = true; } else if(answer.back() == 'y'){ ref += years(std::stoi(str)); math = true; } } else if(answer[0] == '-'){ std::string str(std::next(answer.begin()), std::prev(answer.end())); if(answer.back() == 'd'){ ref -= days(std::stoi(str)); math = true; } else if(answer.back() == 'm'){ ref -= months(std::stoi(str)); math = true; } else if(answer.back() == 'y'){ ref -= years(std::stoi(str)); math = true; } } if(!math) { ref = from_string(answer); } } checked = check(ref, checkers...); } catch(const date_exception& e){ std::cout << e.message() << std::endl; checked = false; } } while(!checked); } struct not_empty_checker { bool operator()(const std::string& value){ return !value.empty(); } std::string message(){ return "This value cannot be empty"; } }; struct not_negative_checker { bool operator()(const budget::money& amount){ return !(amount.dollars() < 0 || amount.cents() < 0); } std::string message(){ return "The amount cannot be negative"; } }; struct not_zero_checker { bool operator()(const budget::money& amount){ return amount.dollars() > 0 || amount.cents() > 0; } std::string message(){ return "The amount cannot be negative"; } }; struct account_checker { budget::date date; account_checker() : date(budget::local_day()) {} account_checker(budget::date date) : date(date) {} bool operator()(const std::string& value) { for (auto& account : all_accounts(date.year(), date.month())) { if (account.name == value) { return true; } } return false; } std::string message(){ return "The account does not exist"; } }; struct asset_checker { bool operator()(const std::string& value){ return asset_exists(value); } std::string message(){ return "The asset does not exist"; } }; struct share_asset_checker { bool operator()(const std::string& value){ return share_asset_exists(value); } std::string message(){ return "The asset does not exist or is not share based"; } }; template<size_t First, size_t Last> struct range_checker { bool operator()(const size_t& value){ return value >= First && value <= Last; } std::string message(){ std::string m = "Value must in the range ["; m += to_string(First); m += ", "; m += to_string(Last); m += "]"; return m; } }; struct one_of_checker { std::vector<std::string> values; one_of_checker(std::vector<std::string> values) : values(values){ //Nothing to init } bool operator()(const std::string& value){ for(auto& v : values){ if(value == v){ return true; } } return false; } std::string message(){ std::string value = "This value can only be one of these values ["; std::string comma = ""; for(auto& v : values){ value += comma; value += v; comma = ", "; } value += "]"; return value; } }; } //end of namespace budget <commit_msg>Signed number console support<commit_after>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <vector> #include <string> #include <iostream> #include "money.hpp" #include "date.hpp" #include "accounts.hpp" #include "assets.hpp" namespace budget { inline std::string red(const std::string& str){ return "\033[0;31m" + str + "\033[0;3047m"; } inline std::string green(const std::string& str){ return "\033[0;32m" + str + "\033[0;3047m"; } inline std::string cyan(const std::string& str){ return "\033[0;33m" + str + "\033[0;3047m"; } std::string format_money(const budget::money& m); std::string format_money_no_color(const budget::money& m); std::string format_money_reverse(const budget::money& m); /** * Returns the real size of a string. By default, accented characteres are * represented by several chars and make the length of the string being bigger * than its displayable length. This functionr returns only a size of 1 for an * accented chars. * \param value The string we want the real length for. * \return The real length of the string. */ size_t rsize(const std::string& value); size_t rsize_after(const std::string& value); template<typename T> void print_minimum(std::ostream& os, const T& value, size_t min_width){ auto str = to_string(value); auto old_width = os.width(); os.width(min_width + (str.size() - rsize(str))); os << str; os.width(old_width); } template<typename T> void print_minimum(const T& value, size_t min_width){ print_minimum(std::cout, value, min_width); } template<typename T> void print_minimum_left(std::ostream& os, const T& value, size_t min_width){ auto str = to_string(value); if(rsize(str) >= min_width){ os << str; } else { os << std::string(min_width - rsize(str), ' '); os << str; } } template<typename T> void print_minimum_left(const T& value, size_t min_width){ print_minimum_left(std::cout, value, min_width); } /** * Indicate if the given option was present in the list. If present, the option * is removed from the list. * \param option The full option name with any - included * \param args The command line arguments * \return true if the option was present, false otherwise. */ bool option(const std::string& option, std::vector<std::string>& args); /** * Return the value of the given option if present or the default value * otherwise * \param option The full option name with any - included * \param args The command line arguments * \return The string value of the option or the default value is not present. */ std::string option_value(const std::string& option, std::vector<std::string>& args, const std::string& value); std::string format_code(int attr, int fg, int bg); std::string format_reset(); template<typename T> bool check(const T&){ return true; } template<typename T, typename CheckerA, typename ...Checker> bool check(const T& value, CheckerA first, Checker... checkers){ if(!first(value)){ std::cout << first.message() << std::endl; return false; } return check(value, checkers...); } std::string get_string_complete(const std::vector<std::string>& choices); template<typename ...Checker> void edit_string_complete(std::string& ref, const std::string& title, const std::vector<std::string>& choices, Checker... checkers){ bool checked; do { std::cout << title << " [" << ref << "]: "; auto answer = get_string_complete(choices); if(!answer.empty()){ ref = answer; } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_string(std::string& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ ref = answer; } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_number(size_t& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ ref = to_number<size_t>(answer); } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_number(int64_t& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if (!answer.empty()) { ref = to_number<int64_t>(answer); } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_double(double& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ ref = to_number<double>(answer); } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_money(budget::money& ref, const std::string& title, Checker... checkers){ bool checked; do { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ ref = parse_money(answer); } checked = check(ref, checkers...); } while(!checked); } template<typename ...Checker> void edit_date(date& ref, const std::string& title, Checker... checkers){ bool checked; do { try { std::string answer; std::cout << title << " [" << ref << "]: "; std::getline(std::cin, answer); if(!answer.empty()){ bool math = false; if(answer[0] == '+'){ std::string str(std::next(answer.begin()), std::prev(answer.end())); if(answer.back() == 'd'){ ref += days(std::stoi(str)); math = true; } else if(answer.back() == 'm'){ ref += months(std::stoi(str)); math = true; } else if(answer.back() == 'y'){ ref += years(std::stoi(str)); math = true; } } else if(answer[0] == '-'){ std::string str(std::next(answer.begin()), std::prev(answer.end())); if(answer.back() == 'd'){ ref -= days(std::stoi(str)); math = true; } else if(answer.back() == 'm'){ ref -= months(std::stoi(str)); math = true; } else if(answer.back() == 'y'){ ref -= years(std::stoi(str)); math = true; } } if(!math) { ref = from_string(answer); } } checked = check(ref, checkers...); } catch(const date_exception& e){ std::cout << e.message() << std::endl; checked = false; } } while(!checked); } struct not_empty_checker { bool operator()(const std::string& value){ return !value.empty(); } std::string message(){ return "This value cannot be empty"; } }; struct not_negative_checker { bool operator()(const budget::money& amount){ return !(amount.dollars() < 0 || amount.cents() < 0); } std::string message(){ return "The amount cannot be negative"; } }; struct not_zero_checker { bool operator()(const budget::money& amount){ return amount.dollars() > 0 || amount.cents() > 0; } std::string message(){ return "The amount cannot be negative"; } }; struct account_checker { budget::date date; account_checker() : date(budget::local_day()) {} account_checker(budget::date date) : date(date) {} bool operator()(const std::string& value) { for (auto& account : all_accounts(date.year(), date.month())) { if (account.name == value) { return true; } } return false; } std::string message(){ return "The account does not exist"; } }; struct asset_checker { bool operator()(const std::string& value){ return asset_exists(value); } std::string message(){ return "The asset does not exist"; } }; struct share_asset_checker { bool operator()(const std::string& value){ return share_asset_exists(value); } std::string message(){ return "The asset does not exist or is not share based"; } }; template<size_t First, size_t Last> struct range_checker { bool operator()(const size_t& value){ return value >= First && value <= Last; } std::string message(){ std::string m = "Value must in the range ["; m += to_string(First); m += ", "; m += to_string(Last); m += "]"; return m; } }; struct one_of_checker { std::vector<std::string> values; one_of_checker(std::vector<std::string> values) : values(values){ //Nothing to init } bool operator()(const std::string& value){ for(auto& v : values){ if(value == v){ return true; } } return false; } std::string message(){ std::string value = "This value can only be one of these values ["; std::string comma = ""; for(auto& v : values){ value += comma; value += v; comma = ", "; } value += "]"; return value; } }; } //end of namespace budget <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_DBN_INL #define DLL_DBN_INL #include <tuple> #include "rbm.hpp" #include "tuple_utils.hpp" #include "dbn_trainer.hpp" #include "conjugate_gradient.hpp" #include "dbn_common.hpp" #include "svm_common.hpp" namespace dll { /*! * \brief A Deep Belief Network implementation */ template<typename Desc> struct dbn { using desc = Desc; using this_type = dbn<desc>; using tuple_type = typename desc::layers::tuple_type; tuple_type tuples; static constexpr const std::size_t layers = desc::layers::layers; template <std::size_t N> using rbm_type = typename std::tuple_element<N, tuple_type>::type; using weight = typename rbm_type<0>::weight; weight learning_rate = 0.77; weight initial_momentum = 0.5; ///< The initial momentum weight final_momentum = 0.9; ///< The final momentum applied after *final_momentum_epoch* epoch weight final_momentum_epoch = 6; ///< The epoch at which momentum change weight weight_cost = 0.0002; ///< The weight cost for weight decay weight momentum = 0; ///< The current momentum #ifdef DLL_SVM_SUPPORT svm::model svm_model; ///< The learned model svm::problem problem; ///< libsvm is stupid, therefore, you cannot destroy the problem if you want to use the model... bool svm_loaded = false; ///< Indicates if a SVM model has been loaded (and therefore must be saved) #endif //DLL_SVM_SUPPORT //No arguments by default dbn(){}; //No copying dbn(const dbn& dbn) = delete; dbn& operator=(const dbn& dbn) = delete; //No moving dbn(dbn&& dbn) = delete; dbn& operator=(dbn&& dbn) = delete; void display() const { std::size_t parameters = 0; std::cout << "DBN with " << layers << " layers" << std::endl; detail::for_each(tuples, [&parameters](auto& rbm){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_visible = rbm_t::num_visible; constexpr const auto num_hidden = rbm_t::num_hidden; parameters += num_visible * num_hidden; printf("\tRBM: %lu->%lu : %lu parameters\n", num_visible, num_hidden, num_visible * num_hidden); }); std::cout << "Total parameters: " << parameters << std::endl; } void store(std::ostream& os) const { detail::for_each(tuples, [&os](auto& rbm){ rbm.store(os); }); #ifdef DLL_SVM_SUPPORT svm_store(*this, os); #endif //DLL_SVM_SUPPORT } void load(std::istream& is){ detail::for_each(tuples, [&is](auto& rbm){ rbm.load(is); }); #ifdef DLL_SVM_SUPPORT svm_load(*this, is); #endif //DLL_SVM_SUPPORT } template<std::size_t N> auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type { return std::get<N>(tuples); } template<std::size_t N> constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type { return std::get<N>(tuples); } template<std::size_t N> static constexpr std::size_t num_visible(){ return rbm_type<N>::num_visible; } template<std::size_t N> static constexpr std::size_t num_hidden(){ return rbm_type<N>::num_hidden; } /*{{{ Pretrain */ /*! * \brief Pretrain the network by training all layers in an unsupervised * manner. */ template<typename Samples> void pretrain(const Samples& training_data, std::size_t max_epochs){ using training_t = std::vector<etl::dyn_vector<typename Samples::value_type::value_type>>; using watcher_t = typename desc::template watcher_t<this_type>; watcher_t watcher; watcher.pretraining_begin(*this); //Convert data to an useful form training_t data; data.reserve(training_data.size()); for(auto& sample : training_data){ data.emplace_back(sample); } training_t next_a; training_t next_s; auto input = std::ref(data); detail::for_each_i(tuples, [&watcher, this, &input, &next_a, &next_s, max_epochs](std::size_t I, auto& rbm){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_hidden = rbm_t::num_hidden; auto input_size = static_cast<const training_t&>(input).size(); //Train each layer but the last one if(rbm_t::hidden_unit != unit_type::EXP){ watcher.template pretrain_layer<rbm_t>(*this, I, input_size); rbm.template train< training_t, !watcher_t::ignore_sub, //Enable the RBM Watcher or not typename dbn_detail::rbm_watcher_t<watcher_t>::type> //Replace the RBM watcher if not void (static_cast<const training_t&>(input), max_epochs); //Get the activation probabilities for the next level if(I < layers - 1){ next_a.clear(); next_a.reserve(input_size); next_s.clear(); next_s.reserve(input_size); for(std::size_t i = 0; i < input_size; ++i){ next_a.emplace_back(num_hidden); next_s.emplace_back(num_hidden); } for(size_t i = 0; i < input_size; ++i){ rbm.activate_hidden(next_a[i], next_s[i], static_cast<const training_t&>(input)[i], static_cast<const training_t&>(input)[i]); } input = std::ref(next_a); } } }); watcher.pretraining_end(*this); } /*}}}*/ /*{{{ With labels */ template<typename Samples, typename Labels> void train_with_labels(const Samples& training_data, const Labels& training_labels, std::size_t labels, std::size_t max_epochs){ dll_assert(training_data.size() == training_labels.size(), "There must be the same number of values than labels"); dll_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); using training_t = std::vector<etl::dyn_vector<typename Samples::value_type::value_type>>; //Convert data to an useful form training_t data; data.reserve(training_data.size()); for(auto& sample : training_data){ data.emplace_back(sample); } auto input = std::cref(data); detail::for_each_i(tuples, [&input, &training_labels, labels, max_epochs](size_t I, auto& rbm){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_hidden = rbm_t::num_hidden; static training_t next; next.reserve(static_cast<const training_t&>(input).size()); rbm.train(static_cast<const training_t&>(input), max_epochs); if(I < layers - 1){ auto append_labels = (I + 1 == layers - 1); for(auto& training_item : static_cast<const training_t&>(input)){ etl::dyn_vector<weight> next_item_a(num_hidden + (append_labels ? labels : 0)); etl::dyn_vector<weight> next_item_s(num_hidden + (append_labels ? labels : 0)); rbm.activate_hidden(next_item_a, next_item_s, training_item, training_item); next.emplace_back(std::move(next_item_a)); } //If the next layers is the last layer if(append_labels){ for(size_t i = 0; i < training_labels.size(); ++i){ auto label = training_labels[i]; for(size_t l = 0; l < labels; ++l){ next[i][num_hidden + l] = label == l ? 1.0 : 0.0; } } } } input = std::cref(next); }); } template<typename TrainingItem> size_t predict_labels(const TrainingItem& item_data, std::size_t labels){ dll_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); etl::dyn_vector<typename TrainingItem::value_type> item(item_data); etl::dyn_vector<weight> output_a(num_visible<layers - 1>()); etl::dyn_vector<weight> output_s(num_visible<layers - 1>()); auto input_ref = std::cref(item); detail::for_each_i(tuples, [labels,&input_ref,&output_a,&output_s](size_t I, auto& rbm){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_hidden = rbm_t::num_hidden; auto& input = static_cast<const etl::dyn_vector<weight>&>(input_ref); if(I == layers - 1){ static etl::dyn_vector<weight> h1_a(num_hidden); static etl::dyn_vector<weight> h1_s(num_hidden); rbm.activate_hidden(h1_a, h1_s, input, input); rbm.activate_visible(h1_a, h1_s, output_a, output_s); } else { static etl::dyn_vector<weight> next_a(num_hidden); static etl::dyn_vector<weight> next_s(num_hidden); static etl::dyn_vector<weight> big_next_a(num_hidden + labels); rbm.activate_hidden(next_a, next_s, input, input); //If the next layers is the last layer if(I + 1 == layers - 1){ for(std::size_t i = 0; i < next_a.size(); ++i){ big_next_a[i] = next_a[i]; } for(size_t l = 0; l < labels; ++l){ big_next_a[num_hidden + l] = 0.1; } input_ref = std::cref(big_next_a); } else { input_ref = std::cref(next_a); } } }); size_t label = 0; weight max = 0; for(size_t l = 0; l < labels; ++l){ auto value = output_a[num_visible<layers - 1>() - labels + l]; if(value > max){ max = value; label = l; } } return label; } /*}}}*/ /*{{{ Predict */ //TODO Rename this template<typename Sample, typename Output> void predict_weights(const Sample& item_data, Output& result){ etl::dyn_vector<typename Sample::value_type> item(item_data); auto input = std::cref(item); detail::for_each_i(tuples, [&item, &input, &result](std::size_t I, auto& rbm){ if(I != layers - 1){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_hidden = rbm_t::num_hidden; static etl::dyn_vector<weight> next(num_hidden); static etl::dyn_vector<weight> next_s(num_hidden); rbm.activate_hidden(next, next_s, static_cast<const Sample&>(input), static_cast<const Sample&>(input)); input = std::cref(next); } }); constexpr const auto num_hidden = rbm_type<layers - 1>::num_hidden; static etl::dyn_vector<weight> next_s(num_hidden); layer<layers - 1>().activate_hidden(result, next_s, static_cast<const Sample&>(input), static_cast<const Sample&>(input)); } template<typename Sample> etl::dyn_vector<weight> predict_weights(const Sample& item_data){ etl::dyn_vector<weight> result(num_hidden<layers - 1>()); predict_weights(item_data, result); return result; } template<typename Weights> size_t predict_final(const Weights& result){ size_t label = 0; weight max = 0; for(size_t l = 0; l < result.size(); ++l){ auto value = result[l]; if(value > max){ max = value; label = l; } } return label; } template<typename Sample> size_t predict(const Sample& item){ auto result = predict_weights(item); return predict_final(result);; } /*}}}*/ /*{{{ Fine-tuning */ template<typename Samples, typename Labels> weight fine_tune(const Samples& training_data, Labels& labels, size_t max_epochs, size_t batch_size){ dll::dbn_trainer<this_type> trainer; return trainer.train(*this, training_data, labels, max_epochs, batch_size); } /*}}}*/ #ifdef DLL_SVM_SUPPORT /*{{{ SVM Training and prediction */ template<typename Samples, typename Labels> bool svm_train(const Samples& training_data, const Labels& labels){ auto n_samples = training_data.size(); std::vector<etl::dyn_vector<double>> svm_samples; //Get all the activation probabilities for(std::size_t i = 0; i < n_samples; ++i){ svm_samples.emplace_back(num_hidden<layers - 1>()); predict_weights(training_data[i], svm_samples[i]); } //static_cast ensure using the correct overload problem = svm::make_problem(labels, static_cast<const std::vector<etl::dyn_vector<double>>&>(svm_samples)); //TODO Give a way to set the paramters by the user auto parameters = svm::default_parameters(); parameters.svm_type = C_SVC; parameters.kernel_type = RBF; parameters.probability = 1; parameters.C = 2.8; parameters.gamma = 0.0073; //Make libsvm quiet svm::make_quiet(); //Make sure parameters are not messed up if(!svm::check(problem, parameters)){ return false; } //Train the SVM svm_model = svm::train(problem, parameters); svm_loaded = true; return true; } template<typename Sample> double svm_predict(const Sample& sample){ etl::dyn_vector<double> svm_sample(num_hidden<layers - 1>()); predict_weights(sample, svm_sample); return svm::predict(svm_model, svm_sample); } /*}}}*/ #endif //DLL_SVM_SUPPORT }; } //end of namespace dll #endif <commit_msg>Renaming<commit_after>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_DBN_INL #define DLL_DBN_INL #include <tuple> #include "rbm.hpp" #include "tuple_utils.hpp" #include "dbn_trainer.hpp" #include "conjugate_gradient.hpp" #include "dbn_common.hpp" #include "svm_common.hpp" namespace dll { /*! * \brief A Deep Belief Network implementation */ template<typename Desc> struct dbn { using desc = Desc; using this_type = dbn<desc>; using tuple_type = typename desc::layers::tuple_type; tuple_type tuples; static constexpr const std::size_t layers = desc::layers::layers; template <std::size_t N> using rbm_type = typename std::tuple_element<N, tuple_type>::type; using weight = typename rbm_type<0>::weight; weight learning_rate = 0.77; weight initial_momentum = 0.5; ///< The initial momentum weight final_momentum = 0.9; ///< The final momentum applied after *final_momentum_epoch* epoch weight final_momentum_epoch = 6; ///< The epoch at which momentum change weight weight_cost = 0.0002; ///< The weight cost for weight decay weight momentum = 0; ///< The current momentum #ifdef DLL_SVM_SUPPORT svm::model svm_model; ///< The learned model svm::problem problem; ///< libsvm is stupid, therefore, you cannot destroy the problem if you want to use the model... bool svm_loaded = false; ///< Indicates if a SVM model has been loaded (and therefore must be saved) #endif //DLL_SVM_SUPPORT //No arguments by default dbn(){}; //No copying dbn(const dbn& dbn) = delete; dbn& operator=(const dbn& dbn) = delete; //No moving dbn(dbn&& dbn) = delete; dbn& operator=(dbn&& dbn) = delete; void display() const { std::size_t parameters = 0; std::cout << "DBN with " << layers << " layers" << std::endl; detail::for_each(tuples, [&parameters](auto& rbm){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_visible = rbm_t::num_visible; constexpr const auto num_hidden = rbm_t::num_hidden; parameters += num_visible * num_hidden; printf("\tRBM: %lu->%lu : %lu parameters\n", num_visible, num_hidden, num_visible * num_hidden); }); std::cout << "Total parameters: " << parameters << std::endl; } void store(std::ostream& os) const { detail::for_each(tuples, [&os](auto& rbm){ rbm.store(os); }); #ifdef DLL_SVM_SUPPORT svm_store(*this, os); #endif //DLL_SVM_SUPPORT } void load(std::istream& is){ detail::for_each(tuples, [&is](auto& rbm){ rbm.load(is); }); #ifdef DLL_SVM_SUPPORT svm_load(*this, is); #endif //DLL_SVM_SUPPORT } template<std::size_t N> auto layer() -> typename std::add_lvalue_reference<rbm_type<N>>::type { return std::get<N>(tuples); } template<std::size_t N> constexpr auto layer() const -> typename std::add_lvalue_reference<typename std::add_const<rbm_type<N>>::type>::type { return std::get<N>(tuples); } template<std::size_t N> static constexpr std::size_t num_visible(){ return rbm_type<N>::num_visible; } template<std::size_t N> static constexpr std::size_t num_hidden(){ return rbm_type<N>::num_hidden; } /*{{{ Pretrain */ /*! * \brief Pretrain the network by training all layers in an unsupervised * manner. */ template<typename Samples> void pretrain(const Samples& training_data, std::size_t max_epochs){ using training_t = std::vector<etl::dyn_vector<typename Samples::value_type::value_type>>; using watcher_t = typename desc::template watcher_t<this_type>; watcher_t watcher; watcher.pretraining_begin(*this); //Convert data to an useful form training_t data; data.reserve(training_data.size()); for(auto& sample : training_data){ data.emplace_back(sample); } training_t next_a; training_t next_s; auto input = std::ref(data); detail::for_each_i(tuples, [&watcher, this, &input, &next_a, &next_s, max_epochs](std::size_t I, auto& rbm){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_hidden = rbm_t::num_hidden; auto input_size = static_cast<const training_t&>(input).size(); //Train each layer but the last one if(rbm_t::hidden_unit != unit_type::EXP){ watcher.template pretrain_layer<rbm_t>(*this, I, input_size); rbm.template train< training_t, !watcher_t::ignore_sub, //Enable the RBM Watcher or not typename dbn_detail::rbm_watcher_t<watcher_t>::type> //Replace the RBM watcher if not void (static_cast<const training_t&>(input), max_epochs); //Get the activation probabilities for the next level if(I < layers - 1){ next_a.clear(); next_a.reserve(input_size); next_s.clear(); next_s.reserve(input_size); for(std::size_t i = 0; i < input_size; ++i){ next_a.emplace_back(num_hidden); next_s.emplace_back(num_hidden); } for(size_t i = 0; i < input_size; ++i){ rbm.activate_hidden(next_a[i], next_s[i], static_cast<const training_t&>(input)[i], static_cast<const training_t&>(input)[i]); } input = std::ref(next_a); } } }); watcher.pretraining_end(*this); } /*}}}*/ /*{{{ With labels */ template<typename Samples, typename Labels> void train_with_labels(const Samples& training_data, const Labels& training_labels, std::size_t labels, std::size_t max_epochs){ dll_assert(training_data.size() == training_labels.size(), "There must be the same number of values than labels"); dll_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); using training_t = std::vector<etl::dyn_vector<typename Samples::value_type::value_type>>; //Convert data to an useful form training_t data; data.reserve(training_data.size()); for(auto& sample : training_data){ data.emplace_back(sample); } auto input = std::cref(data); detail::for_each_i(tuples, [&input, &training_labels, labels, max_epochs](size_t I, auto& rbm){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_hidden = rbm_t::num_hidden; static training_t next; next.reserve(static_cast<const training_t&>(input).size()); rbm.train(static_cast<const training_t&>(input), max_epochs); if(I < layers - 1){ auto append_labels = (I + 1 == layers - 1); for(auto& training_item : static_cast<const training_t&>(input)){ etl::dyn_vector<weight> next_item_a(num_hidden + (append_labels ? labels : 0)); etl::dyn_vector<weight> next_item_s(num_hidden + (append_labels ? labels : 0)); rbm.activate_hidden(next_item_a, next_item_s, training_item, training_item); next.emplace_back(std::move(next_item_a)); } //If the next layers is the last layer if(append_labels){ for(size_t i = 0; i < training_labels.size(); ++i){ auto label = training_labels[i]; for(size_t l = 0; l < labels; ++l){ next[i][num_hidden + l] = label == l ? 1.0 : 0.0; } } } } input = std::cref(next); }); } template<typename TrainingItem> size_t predict_labels(const TrainingItem& item_data, std::size_t labels){ dll_assert(num_visible<layers - 1>() == num_hidden<layers - 2>() + labels, "There is no room for the labels units"); etl::dyn_vector<typename TrainingItem::value_type> item(item_data); etl::dyn_vector<weight> output_a(num_visible<layers - 1>()); etl::dyn_vector<weight> output_s(num_visible<layers - 1>()); auto input_ref = std::cref(item); detail::for_each_i(tuples, [labels,&input_ref,&output_a,&output_s](size_t I, auto& rbm){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_hidden = rbm_t::num_hidden; auto& input = static_cast<const etl::dyn_vector<weight>&>(input_ref); if(I == layers - 1){ static etl::dyn_vector<weight> h1_a(num_hidden); static etl::dyn_vector<weight> h1_s(num_hidden); rbm.activate_hidden(h1_a, h1_s, input, input); rbm.activate_visible(h1_a, h1_s, output_a, output_s); } else { static etl::dyn_vector<weight> next_a(num_hidden); static etl::dyn_vector<weight> next_s(num_hidden); static etl::dyn_vector<weight> big_next_a(num_hidden + labels); rbm.activate_hidden(next_a, next_s, input, input); //If the next layers is the last layer if(I + 1 == layers - 1){ for(std::size_t i = 0; i < next_a.size(); ++i){ big_next_a[i] = next_a[i]; } for(size_t l = 0; l < labels; ++l){ big_next_a[num_hidden + l] = 0.1; } input_ref = std::cref(big_next_a); } else { input_ref = std::cref(next_a); } } }); size_t label = 0; weight max = 0; for(size_t l = 0; l < labels; ++l){ auto value = output_a[num_visible<layers - 1>() - labels + l]; if(value > max){ max = value; label = l; } } return label; } /*}}}*/ /*{{{ Predict */ //TODO Rename this template<typename Sample, typename Output> void activation_probabilities(const Sample& item_data, Output& result){ etl::dyn_vector<typename Sample::value_type> item(item_data); auto input = std::cref(item); detail::for_each_i(tuples, [&item, &input, &result](std::size_t I, auto& rbm){ if(I != layers - 1){ typedef typename std::remove_reference<decltype(rbm)>::type rbm_t; constexpr const auto num_hidden = rbm_t::num_hidden; static etl::dyn_vector<weight> next(num_hidden); static etl::dyn_vector<weight> next_s(num_hidden); rbm.activate_hidden(next, next_s, static_cast<const Sample&>(input), static_cast<const Sample&>(input)); input = std::cref(next); } }); constexpr const auto num_hidden = rbm_type<layers - 1>::num_hidden; static etl::dyn_vector<weight> next_s(num_hidden); layer<layers - 1>().activate_hidden(result, next_s, static_cast<const Sample&>(input), static_cast<const Sample&>(input)); } template<typename Sample> etl::dyn_vector<weight> activation_probabilities(const Sample& item_data){ etl::dyn_vector<weight> result(num_hidden<layers - 1>()); activation_probabilities(item_data, result); return result; } template<typename Weights> size_t predict_label(const Weights& result){ size_t label = 0; weight max = 0; for(size_t l = 0; l < result.size(); ++l){ auto value = result[l]; if(value > max){ max = value; label = l; } } return label; } template<typename Sample> size_t predict(const Sample& item){ auto result = activation_probabilities(item); return predict_label(result);; } /*}}}*/ /*{{{ Fine-tuning */ template<typename Samples, typename Labels> weight fine_tune(const Samples& training_data, Labels& labels, size_t max_epochs, size_t batch_size){ dll::dbn_trainer<this_type> trainer; return trainer.train(*this, training_data, labels, max_epochs, batch_size); } /*}}}*/ #ifdef DLL_SVM_SUPPORT /*{{{ SVM Training and prediction */ template<typename Samples, typename Labels> bool svm_train(const Samples& training_data, const Labels& labels){ auto n_samples = training_data.size(); std::vector<etl::dyn_vector<double>> svm_samples; //Get all the activation probabilities for(std::size_t i = 0; i < n_samples; ++i){ svm_samples.emplace_back(num_hidden<layers - 1>()); activation_probabilities(training_data[i], svm_samples[i]); } //static_cast ensure using the correct overload problem = svm::make_problem(labels, static_cast<const std::vector<etl::dyn_vector<double>>&>(svm_samples)); //TODO Give a way to set the paramters by the user auto parameters = svm::default_parameters(); parameters.svm_type = C_SVC; parameters.kernel_type = RBF; parameters.probability = 1; parameters.C = 2.8; parameters.gamma = 0.0073; //Make libsvm quiet svm::make_quiet(); //Make sure parameters are not messed up if(!svm::check(problem, parameters)){ return false; } //Train the SVM svm_model = svm::train(problem, parameters); svm_loaded = true; return true; } template<typename Sample> double svm_predict(const Sample& sample){ etl::dyn_vector<double> svm_sample(num_hidden<layers - 1>()); activation_probabilities(sample, svm_sample); return svm::predict(svm_model, svm_sample); } /*}}}*/ #endif //DLL_SVM_SUPPORT }; } //end of namespace dll #endif <|endoftext|>