text
stringlengths
54
60.6k
<commit_before>// $Id: AutoDeleteable_test.C,v 1.1 2000/08/22 16:59:43 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/CONCEPT/autoDeletable.h> /////////////////////////// using namespace BALL; class A: public AutoDeletable { }; START_TEST(class_name, "$Id: AutoDeleteable_test.C,v 1.1 2000/08/22 16:59:43 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// A* a_ptr; A* array_ptr; CHECK(AutoDeletable::void* operator new(size_t size) throw()) a_ptr = new A; array_ptr = new A[12]; RESULT CHECK(AutoDeletable::void* operator new(size_t size, void* ptr) throw()) // BAUSTELLE RESULT CHECK(AutoDeletable::void operator delete(void* ptr) throw()) // BAUSTELLE RESULT A a; a_ptr = new A; A array[12]; array_ptr = new A[12]; CHECK(AutoDeletable::~AutoDeletable()) delete a_ptr; delete array_ptr; // segfault ??? RESULT a_ptr = new A; array_ptr = new A[12]; CHECK(AutoDeletable::isAutoDeletable() const ) TEST_EQUAL(a.isAutoDeletable(), false) TEST_EQUAL(a_ptr->isAutoDeletable(), true) TEST_EQUAL(array_ptr->isAutoDeletable(), false) TEST_EQUAL(array->isAutoDeletable(), false) RESULT CHECK(AutoDeletable::setAutoDeletable(bool enable)) //BAUSTELLE RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed error in test for delete<commit_after>// $Id: AutoDeleteable_test.C,v 1.2 2000/08/23 01:02:07 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/CONCEPT/autoDeletable.h> /////////////////////////// using namespace BALL; class A: public AutoDeletable { }; START_TEST(class_name, "$Id: AutoDeleteable_test.C,v 1.2 2000/08/23 01:02:07 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// A* a_ptr; A* array_ptr; CHECK(AutoDeletable::void* operator new(size_t size) throw()) a_ptr = new A; array_ptr = new A[12]; RESULT CHECK(AutoDeletable::void* operator new(size_t size, void* ptr) throw()) // BAUSTELLE RESULT CHECK(AutoDeletable::void operator delete(void* ptr) throw()) // BAUSTELLE RESULT A a; a_ptr = new A; A array[12]; array_ptr = new A[12]; CHECK(AutoDeletable::~AutoDeletable()) delete a_ptr; delete [] array_ptr; RESULT a_ptr = new A; array_ptr = new A[12]; CHECK(AutoDeletable::isAutoDeletable() const ) TEST_EQUAL(a.isAutoDeletable(), false) TEST_EQUAL(a_ptr->isAutoDeletable(), true) TEST_EQUAL(array_ptr->isAutoDeletable(), false) TEST_EQUAL(array->isAutoDeletable(), false) RESULT CHECK(AutoDeletable::setAutoDeletable(bool enable)) //BAUSTELLE RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before><commit_msg>Gui: [skip ci] make Save logic of text document more intuitive<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ // ExpPWListDlg.cpp : implementation file // #include "stdafx.h" #include "ExpPWListDlg.h" #include "DboxMain.h" #include "corelib/MyString.h" #include "corelib/Util.h" #include "corelib/ItemData.h" #include "resource2.h" // Menu, Toolbar & Accelerator resources #include "resource3.h" // String resources using namespace std; ExpPWEntry::ExpPWEntry(const CItemData &ci, time_t now, time_t LTime) { group = ci.GetGroup(); title = ci.GetTitle(); user = ci.GetUser(); // Expired or Warning / Normal or Base - see image list below type = (LTime <= now ? 0 : 1) + (ci.IsBase() ? 2 : 0); expirylocdate = ci.GetLTimeL(); expiryexpdate = ci.GetLTimeExp(); expirytttdate = LTime; } // CExpPWListDlg dialog CExpPWListDlg::CExpPWListDlg(CWnd* pParent, const ExpiredList &expPWList, const CString& a_filespec) : CPWDialog(CExpPWListDlg::IDD, pParent), m_expPWList(expPWList) { const int FILE_DISP_LEN = 75; if (a_filespec.GetLength() > FILE_DISP_LEN) { // m_message = a_filespec.Right(FILE_DISP_LEN - 3); // truncate for display // m_message.Insert(0, _T("...")); m_message = a_filespec.Left(FILE_DISP_LEN/2-5) + _T(" ... ") + a_filespec.Right(FILE_DISP_LEN/2); } else { m_message = a_filespec; } m_iSortedColumn = -1; m_bSortAscending = TRUE; } CExpPWListDlg::~CExpPWListDlg() { } void CExpPWListDlg::DoDataExchange(CDataExchange* pDX) { CPWDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EXPIRED_PASSWORD_LIST, m_expPWListCtrl); DDX_Text(pDX, IDC_MESSAGE, m_message); } BEGIN_MESSAGE_MAP(CExpPWListDlg, CPWDialog) ON_BN_CLICKED(IDC_COPY_EXP_TO_CLIPBOARD, OnBnClickedCopyExpToClipboard) ON_BN_CLICKED(IDOK, OnOK) ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked) ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked) END_MESSAGE_MAP() // CExpPWListDlg message handlers BOOL CExpPWListDlg::OnInitDialog() { CPWDialog::OnInitDialog(); //m_expPWListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES ); CString cs_text; m_expPWListCtrl.InsertColumn(0, _T("")); cs_text.LoadString(IDS_GROUP); m_expPWListCtrl.InsertColumn(1, cs_text); cs_text.LoadString(IDS_TITLE); m_expPWListCtrl.InsertColumn(3, cs_text); cs_text.LoadString(IDS_USERNAME); m_expPWListCtrl.InsertColumn(3, cs_text); cs_text.LoadString(IDS_EXPIRYDATETIME); m_expPWListCtrl.InsertColumn(4, cs_text); m_pImageList = new CImageList(); // Number (4) same as total of warn/expired images below BOOL status = m_pImageList->Create(9, 9, ILC_COLOR, 4, 0); ASSERT(status != 0); CBitmap bitmap; bitmap.LoadBitmap(IDB_LEAF_EXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_WARNEXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_BASE_EXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_BASE_WARNEXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_SMALL); m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_NORMAL); int nPos = 0; ExpiredList::const_iterator itempos; for (itempos = m_expPWList.begin(); itempos != m_expPWList.end(); itempos++) { const ExpPWEntry exppwentry = *itempos; nPos = m_expPWListCtrl.InsertItem(nPos, NULL, exppwentry.type); m_expPWListCtrl.SetItemText(nPos, 1, exppwentry.group); m_expPWListCtrl.SetItemText(nPos, 2, exppwentry.title); m_expPWListCtrl.SetItemText(nPos, 3, exppwentry.user); m_expPWListCtrl.SetItemText(nPos, 4, exppwentry.expirylocdate); // original nPos == index in vector: save for Sort m_expPWListCtrl.SetItemData(nPos, static_cast<DWORD>(nPos)); } m_expPWListCtrl.SetRedraw(FALSE); for (int i = 0; i < 5; i++) { m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE); int nColumnWidth = m_expPWListCtrl.GetColumnWidth(i); m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER); int nHeaderWidth = m_expPWListCtrl.GetColumnWidth(i); m_expPWListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth)); } m_expPWListCtrl.SetRedraw(TRUE); return TRUE; } void CExpPWListDlg::OnOK() { delete m_pImageList; CPWDialog::OnOK(); } void CExpPWListDlg::OnBnClickedCopyExpToClipboard() { CString data(MAKEINTRESOURCE(IDS_COPYTITLE)); const CString CRLF = _T("\r\n"); const CString TAB = _T('\t'); ExpiredList::const_iterator itempos; for (itempos = m_expPWList.begin(); itempos != m_expPWList.end(); itempos++) { const ExpPWEntry exppwentry = *itempos; data = data + (CString)exppwentry.group + TAB + (CString)exppwentry.title + TAB + (CString)exppwentry.user + TAB + (CString)exppwentry.expiryexpdate + CRLF; } DboxMain *dbx = static_cast<DboxMain *>(GetParent()); dbx->SetClipboardData(data); } void CExpPWListDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult) { HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR; if(phdn->iButton == 0) { // User clicked on header using left mouse button if(phdn->iItem == m_iSortedColumn) m_bSortAscending = !m_bSortAscending; else m_bSortAscending = TRUE; m_iSortedColumn = phdn->iItem; m_expPWListCtrl.SortItems(ExpPWCompareFunc, (LPARAM)this); // Note: WINVER defines the minimum system level for which this is program compiled and // NOT the level of system it is running on! // In this case, these values are defined in Windows XP and later and supported // by V6 of comctl32.dll (supplied with Windows XP) and later. // They should be ignored by earlier levels of this dll or ..... // we can check the dll version (code available on request)! #if (WINVER < 0x0501) // These are already defined for WinXP and later #define HDF_SORTUP 0x0400 #define HDF_SORTDOWN 0x0200 #endif HDITEM HeaderItem; HeaderItem.mask = HDI_FORMAT; m_expPWListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem); // Turn off all arrows HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN); // Turn on the correct arrow HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN); m_expPWListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem); } *pResult = 0; } int CALLBACK CExpPWListDlg::ExpPWCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM closure) { CExpPWListDlg *self = (CExpPWListDlg*)closure; int nSortColumn = self->m_iSortedColumn; const ExpPWEntry pLHS = self->m_expPWList[lParam1]; const ExpPWEntry pRHS = self->m_expPWList[lParam2]; CMyString group1, title1, username1; CMyString group2, title2, username2; int type1, type2; time_t t1, t2; int iResult; switch(nSortColumn) { case 0: type1 = pLHS.type; type2 = pRHS.type; iResult = (type1 < type2) ? -1 : 1; break; case 1: group1 = pLHS.group; group2 = pRHS.group; iResult = ((CString)group1).CompareNoCase(group2); break; case 2: title1 = pLHS.title; title2 = pRHS.title; iResult = ((CString)title1).CompareNoCase(title2); break; case 3: username1 = pLHS.user; username2 = pRHS.user; iResult = ((CString)username1).CompareNoCase(username2); break; case 4: t1 = pLHS.expirytttdate; t2 = pRHS.expirytttdate; iResult = ((long) t1 < (long) t2) ? -1 : 1; break; default: iResult = 0; // should never happen - just keep compiler happy ASSERT(FALSE); } if (!self->m_bSortAscending) iResult *= -1; return iResult; } <commit_msg>Correct column number in Expired Password dialog<commit_after>/* * Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ // ExpPWListDlg.cpp : implementation file // #include "stdafx.h" #include "ExpPWListDlg.h" #include "DboxMain.h" #include "corelib/MyString.h" #include "corelib/Util.h" #include "corelib/ItemData.h" #include "resource2.h" // Menu, Toolbar & Accelerator resources #include "resource3.h" // String resources using namespace std; ExpPWEntry::ExpPWEntry(const CItemData &ci, time_t now, time_t LTime) { group = ci.GetGroup(); title = ci.GetTitle(); user = ci.GetUser(); // Expired or Warning / Normal or Base - see image list below type = (LTime <= now ? 0 : 1) + (ci.IsBase() ? 2 : 0); expirylocdate = ci.GetLTimeL(); expiryexpdate = ci.GetLTimeExp(); expirytttdate = LTime; } // CExpPWListDlg dialog CExpPWListDlg::CExpPWListDlg(CWnd* pParent, const ExpiredList &expPWList, const CString& a_filespec) : CPWDialog(CExpPWListDlg::IDD, pParent), m_expPWList(expPWList) { const int FILE_DISP_LEN = 75; if (a_filespec.GetLength() > FILE_DISP_LEN) { // m_message = a_filespec.Right(FILE_DISP_LEN - 3); // truncate for display // m_message.Insert(0, _T("...")); m_message = a_filespec.Left(FILE_DISP_LEN/2-5) + _T(" ... ") + a_filespec.Right(FILE_DISP_LEN/2); } else { m_message = a_filespec; } m_iSortedColumn = -1; m_bSortAscending = TRUE; } CExpPWListDlg::~CExpPWListDlg() { } void CExpPWListDlg::DoDataExchange(CDataExchange* pDX) { CPWDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EXPIRED_PASSWORD_LIST, m_expPWListCtrl); DDX_Text(pDX, IDC_MESSAGE, m_message); } BEGIN_MESSAGE_MAP(CExpPWListDlg, CPWDialog) ON_BN_CLICKED(IDC_COPY_EXP_TO_CLIPBOARD, OnBnClickedCopyExpToClipboard) ON_BN_CLICKED(IDOK, OnOK) ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked) ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked) END_MESSAGE_MAP() // CExpPWListDlg message handlers BOOL CExpPWListDlg::OnInitDialog() { CPWDialog::OnInitDialog(); //m_expPWListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES ); CString cs_text; m_expPWListCtrl.InsertColumn(0, _T("")); cs_text.LoadString(IDS_GROUP); m_expPWListCtrl.InsertColumn(1, cs_text); cs_text.LoadString(IDS_TITLE); m_expPWListCtrl.InsertColumn(2, cs_text); cs_text.LoadString(IDS_USERNAME); m_expPWListCtrl.InsertColumn(3, cs_text); cs_text.LoadString(IDS_EXPIRYDATETIME); m_expPWListCtrl.InsertColumn(4, cs_text); m_pImageList = new CImageList(); // Number (4) same as total of warn/expired images below BOOL status = m_pImageList->Create(9, 9, ILC_COLOR, 4, 0); ASSERT(status != 0); CBitmap bitmap; bitmap.LoadBitmap(IDB_LEAF_EXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_WARNEXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_BASE_EXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_BASE_WARNEXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_SMALL); m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_NORMAL); int nPos = 0; ExpiredList::const_iterator itempos; for (itempos = m_expPWList.begin(); itempos != m_expPWList.end(); itempos++) { const ExpPWEntry exppwentry = *itempos; nPos = m_expPWListCtrl.InsertItem(nPos, NULL, exppwentry.type); m_expPWListCtrl.SetItemText(nPos, 1, exppwentry.group); m_expPWListCtrl.SetItemText(nPos, 2, exppwentry.title); m_expPWListCtrl.SetItemText(nPos, 3, exppwentry.user); m_expPWListCtrl.SetItemText(nPos, 4, exppwentry.expirylocdate); // original nPos == index in vector: save for Sort m_expPWListCtrl.SetItemData(nPos, static_cast<DWORD>(nPos)); } m_expPWListCtrl.SetRedraw(FALSE); for (int i = 0; i < 5; i++) { m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE); int nColumnWidth = m_expPWListCtrl.GetColumnWidth(i); m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER); int nHeaderWidth = m_expPWListCtrl.GetColumnWidth(i); m_expPWListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth)); } m_expPWListCtrl.SetRedraw(TRUE); return TRUE; } void CExpPWListDlg::OnOK() { delete m_pImageList; CPWDialog::OnOK(); } void CExpPWListDlg::OnBnClickedCopyExpToClipboard() { CString data(MAKEINTRESOURCE(IDS_COPYTITLE)); const CString CRLF = _T("\r\n"); const CString TAB = _T('\t'); ExpiredList::const_iterator itempos; for (itempos = m_expPWList.begin(); itempos != m_expPWList.end(); itempos++) { const ExpPWEntry exppwentry = *itempos; data = data + (CString)exppwentry.group + TAB + (CString)exppwentry.title + TAB + (CString)exppwentry.user + TAB + (CString)exppwentry.expiryexpdate + CRLF; } DboxMain *dbx = static_cast<DboxMain *>(GetParent()); dbx->SetClipboardData(data); } void CExpPWListDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult) { HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR; if(phdn->iButton == 0) { // User clicked on header using left mouse button if(phdn->iItem == m_iSortedColumn) m_bSortAscending = !m_bSortAscending; else m_bSortAscending = TRUE; m_iSortedColumn = phdn->iItem; m_expPWListCtrl.SortItems(ExpPWCompareFunc, (LPARAM)this); // Note: WINVER defines the minimum system level for which this is program compiled and // NOT the level of system it is running on! // In this case, these values are defined in Windows XP and later and supported // by V6 of comctl32.dll (supplied with Windows XP) and later. // They should be ignored by earlier levels of this dll or ..... // we can check the dll version (code available on request)! #if (WINVER < 0x0501) // These are already defined for WinXP and later #define HDF_SORTUP 0x0400 #define HDF_SORTDOWN 0x0200 #endif HDITEM HeaderItem; HeaderItem.mask = HDI_FORMAT; m_expPWListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem); // Turn off all arrows HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN); // Turn on the correct arrow HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN); m_expPWListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem); } *pResult = 0; } int CALLBACK CExpPWListDlg::ExpPWCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM closure) { CExpPWListDlg *self = (CExpPWListDlg*)closure; int nSortColumn = self->m_iSortedColumn; const ExpPWEntry pLHS = self->m_expPWList[lParam1]; const ExpPWEntry pRHS = self->m_expPWList[lParam2]; CMyString group1, title1, username1; CMyString group2, title2, username2; int type1, type2; time_t t1, t2; int iResult; switch(nSortColumn) { case 0: type1 = pLHS.type; type2 = pRHS.type; iResult = (type1 < type2) ? -1 : 1; break; case 1: group1 = pLHS.group; group2 = pRHS.group; iResult = ((CString)group1).CompareNoCase(group2); break; case 2: title1 = pLHS.title; title2 = pRHS.title; iResult = ((CString)title1).CompareNoCase(title2); break; case 3: username1 = pLHS.user; username2 = pRHS.user; iResult = ((CString)username1).CompareNoCase(username2); break; case 4: t1 = pLHS.expirytttdate; t2 = pRHS.expirytttdate; iResult = ((long) t1 < (long) t2) ? -1 : 1; break; default: iResult = 0; // should never happen - just keep compiler happy ASSERT(FALSE); } if (!self->m_bSortAscending) iResult *= -1; return iResult; } <|endoftext|>
<commit_before>//===-- PathMappingList.cpp -------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <climits> #include <cstring> #include "lldb/Host/FileSystem.h" #include "lldb/Host/PosixApi.h" #include "lldb/Target/PathMappingList.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/lldb-private-enumerations.h" using namespace lldb; using namespace lldb_private; namespace { // We must normalize our path pairs that we store because if we don't then // things won't always work. We found a case where if we did: // (lldb) settings set target.source-map . /tmp // We would store a path pairs of "." and "/tmp" as raw strings. If the debug // info contains "./foo/bar.c", the path will get normalized to "foo/bar.c". // When PathMappingList::RemapPath() is called, it expects the path to start // with the raw path pair, which doesn't work anymore because the paths have // been normalized when the debug info was loaded. So we need to store // nomalized path pairs to ensure things match up. ConstString NormalizePath(const ConstString &path) { // If we use "path" to construct a FileSpec, it will normalize the path for // us. We then grab the string and turn it back into a ConstString. return ConstString(FileSpec(path.GetStringRef()).GetPath()); } } //---------------------------------------------------------------------- // PathMappingList constructor //---------------------------------------------------------------------- PathMappingList::PathMappingList() : m_pairs(), m_callback(nullptr), m_callback_baton(nullptr), m_mod_id(0) {} PathMappingList::PathMappingList(ChangedCallback callback, void *callback_baton) : m_pairs(), m_callback(callback), m_callback_baton(callback_baton), m_mod_id(0) {} PathMappingList::PathMappingList(const PathMappingList &rhs) : m_pairs(rhs.m_pairs), m_callback(nullptr), m_callback_baton(nullptr), m_mod_id(0) {} const PathMappingList &PathMappingList::operator=(const PathMappingList &rhs) { if (this != &rhs) { m_pairs = rhs.m_pairs; m_callback = nullptr; m_callback_baton = nullptr; m_mod_id = rhs.m_mod_id; } return *this; } PathMappingList::~PathMappingList() = default; void PathMappingList::Append(const ConstString &path, const ConstString &replacement, bool notify) { ++m_mod_id; m_pairs.emplace_back(pair(NormalizePath(path), NormalizePath(replacement))); if (notify && m_callback) m_callback(*this, m_callback_baton); } void PathMappingList::Append(const PathMappingList &rhs, bool notify) { ++m_mod_id; if (!rhs.m_pairs.empty()) { const_iterator pos, end = rhs.m_pairs.end(); for (pos = rhs.m_pairs.begin(); pos != end; ++pos) m_pairs.push_back(*pos); if (notify && m_callback) m_callback(*this, m_callback_baton); } } void PathMappingList::Insert(const ConstString &path, const ConstString &replacement, uint32_t index, bool notify) { ++m_mod_id; iterator insert_iter; if (index >= m_pairs.size()) insert_iter = m_pairs.end(); else insert_iter = m_pairs.begin() + index; m_pairs.emplace(insert_iter, pair(NormalizePath(path), NormalizePath(replacement))); if (notify && m_callback) m_callback(*this, m_callback_baton); } bool PathMappingList::Replace(const ConstString &path, const ConstString &replacement, uint32_t index, bool notify) { if (index >= m_pairs.size()) return false; ++m_mod_id; m_pairs[index] = pair(NormalizePath(path), NormalizePath(replacement)); if (notify && m_callback) m_callback(*this, m_callback_baton); return true; } bool PathMappingList::Remove(size_t index, bool notify) { if (index >= m_pairs.size()) return false; ++m_mod_id; iterator iter = m_pairs.begin() + index; m_pairs.erase(iter); if (notify && m_callback) m_callback(*this, m_callback_baton); return true; } // For clients which do not need the pair index dumped, pass a pair_index >= 0 // to only dump the indicated pair. void PathMappingList::Dump(Stream *s, int pair_index) { unsigned int numPairs = m_pairs.size(); if (pair_index < 0) { unsigned int index; for (index = 0; index < numPairs; ++index) s->Printf("[%d] \"%s\" -> \"%s\"\n", index, m_pairs[index].first.GetCString(), m_pairs[index].second.GetCString()); } else { if (static_cast<unsigned int>(pair_index) < numPairs) s->Printf("%s -> %s", m_pairs[pair_index].first.GetCString(), m_pairs[pair_index].second.GetCString()); } } void PathMappingList::Clear(bool notify) { if (!m_pairs.empty()) ++m_mod_id; m_pairs.clear(); if (notify && m_callback) m_callback(*this, m_callback_baton); } bool PathMappingList::RemapPath(const ConstString &path, ConstString &new_path) const { std::string remapped; if (RemapPath(path.GetStringRef(), remapped)) { new_path.SetString(remapped); return true; } return false; } bool PathMappingList::RemapPath(llvm::StringRef path, std::string &new_path) const { if (m_pairs.empty() || path.empty()) return false; LazyBool path_is_relative = eLazyBoolCalculate; for (const auto &it : m_pairs) { auto prefix = it.first.GetStringRef(); if (!path.consume_front(prefix)) { // Relative paths won't have a leading "./" in them unless "." is the // only thing in the relative path so we need to work around "." // carefully. if (prefix != ".") continue; // We need to figure out if the "path" argument is relative. If it is, // then we should remap, else skip this entry. if (path_is_relative == eLazyBoolCalculate) { path_is_relative = FileSpec(path).IsRelative() ? eLazyBoolYes : eLazyBoolNo; } if (!path_is_relative) continue; } FileSpec remapped(it.second.GetStringRef()); remapped.AppendPathComponent(path); new_path = remapped.GetPath(); return true; } return false; } bool PathMappingList::ReverseRemapPath(const FileSpec &file, FileSpec &fixed) const { std::string path = file.GetPath(); llvm::StringRef path_ref(path); for (const auto &it : m_pairs) { if (!path_ref.consume_front(it.second.GetStringRef())) continue; fixed.SetFile(it.first.GetStringRef(), FileSpec::Style::native); fixed.AppendPathComponent(path_ref); return true; } return false; } bool PathMappingList::FindFile(const FileSpec &orig_spec, FileSpec &new_spec) const { if (m_pairs.empty()) return false; std::string orig_path = orig_spec.GetPath(); if (orig_path.empty()) return false; bool orig_is_relative = orig_spec.IsRelative(); const_iterator pos, end = m_pairs.end(); for (pos = m_pairs.begin(); pos != end; ++pos) { llvm::StringRef orig_ref(orig_path); llvm::StringRef prefix_ref = pos->first.GetStringRef(); if (orig_ref.size() >= prefix_ref.size()) { // We consider a relative prefix or one of just "." to // mean "only apply to relative paths". bool prefix_is_relative = false; if (prefix_ref == ".") { prefix_is_relative = true; // Remove the "." since it will have been removed from the // FileSpec paths already. prefix_ref = prefix_ref.drop_front(); } else { FileSpec prefix_spec(prefix_ref, FileSpec::Style::native); prefix_is_relative = prefix_spec.IsRelative(); } if (prefix_is_relative != orig_is_relative) continue; if (orig_ref.consume_front(prefix_ref)) { new_spec.SetFile(pos->second.GetCString(), FileSpec::Style::native); new_spec.AppendPathComponent(orig_ref); if (FileSystem::Instance().Exists(new_spec)) return true; } } } new_spec.Clear(); return false; } bool PathMappingList::Replace(const ConstString &path, const ConstString &new_path, bool notify) { uint32_t idx = FindIndexForPath(path); if (idx < m_pairs.size()) { ++m_mod_id; m_pairs[idx].second = new_path; if (notify && m_callback) m_callback(*this, m_callback_baton); return true; } return false; } bool PathMappingList::Remove(const ConstString &path, bool notify) { iterator pos = FindIteratorForPath(path); if (pos != m_pairs.end()) { ++m_mod_id; m_pairs.erase(pos); if (notify && m_callback) m_callback(*this, m_callback_baton); return true; } return false; } PathMappingList::const_iterator PathMappingList::FindIteratorForPath(const ConstString &path) const { const_iterator pos; const_iterator begin = m_pairs.begin(); const_iterator end = m_pairs.end(); for (pos = begin; pos != end; ++pos) { if (pos->first == path) break; } return pos; } PathMappingList::iterator PathMappingList::FindIteratorForPath(const ConstString &path) { iterator pos; iterator begin = m_pairs.begin(); iterator end = m_pairs.end(); for (pos = begin; pos != end; ++pos) { if (pos->first == path) break; } return pos; } bool PathMappingList::GetPathsAtIndex(uint32_t idx, ConstString &path, ConstString &new_path) const { if (idx < m_pairs.size()) { path = m_pairs[idx].first; new_path = m_pairs[idx].second; return true; } return false; } uint32_t PathMappingList::FindIndexForPath(const ConstString &orig_path) const { const ConstString path = NormalizePath(orig_path); const_iterator pos; const_iterator begin = m_pairs.begin(); const_iterator end = m_pairs.end(); for (pos = begin; pos != end; ++pos) { if (pos->first == path) return std::distance(begin, pos); } return UINT32_MAX; } <commit_msg>Little more cleanup on https://reviews.llvm.org/D57552 Thanks Jonas... One more early continue and using a range where we had an iterator.<commit_after>//===-- PathMappingList.cpp -------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <climits> #include <cstring> #include "lldb/Host/FileSystem.h" #include "lldb/Host/PosixApi.h" #include "lldb/Target/PathMappingList.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/Stream.h" #include "lldb/lldb-private-enumerations.h" using namespace lldb; using namespace lldb_private; namespace { // We must normalize our path pairs that we store because if we don't then // things won't always work. We found a case where if we did: // (lldb) settings set target.source-map . /tmp // We would store a path pairs of "." and "/tmp" as raw strings. If the debug // info contains "./foo/bar.c", the path will get normalized to "foo/bar.c". // When PathMappingList::RemapPath() is called, it expects the path to start // with the raw path pair, which doesn't work anymore because the paths have // been normalized when the debug info was loaded. So we need to store // nomalized path pairs to ensure things match up. ConstString NormalizePath(const ConstString &path) { // If we use "path" to construct a FileSpec, it will normalize the path for // us. We then grab the string and turn it back into a ConstString. return ConstString(FileSpec(path.GetStringRef()).GetPath()); } } //---------------------------------------------------------------------- // PathMappingList constructor //---------------------------------------------------------------------- PathMappingList::PathMappingList() : m_pairs(), m_callback(nullptr), m_callback_baton(nullptr), m_mod_id(0) {} PathMappingList::PathMappingList(ChangedCallback callback, void *callback_baton) : m_pairs(), m_callback(callback), m_callback_baton(callback_baton), m_mod_id(0) {} PathMappingList::PathMappingList(const PathMappingList &rhs) : m_pairs(rhs.m_pairs), m_callback(nullptr), m_callback_baton(nullptr), m_mod_id(0) {} const PathMappingList &PathMappingList::operator=(const PathMappingList &rhs) { if (this != &rhs) { m_pairs = rhs.m_pairs; m_callback = nullptr; m_callback_baton = nullptr; m_mod_id = rhs.m_mod_id; } return *this; } PathMappingList::~PathMappingList() = default; void PathMappingList::Append(const ConstString &path, const ConstString &replacement, bool notify) { ++m_mod_id; m_pairs.emplace_back(pair(NormalizePath(path), NormalizePath(replacement))); if (notify && m_callback) m_callback(*this, m_callback_baton); } void PathMappingList::Append(const PathMappingList &rhs, bool notify) { ++m_mod_id; if (!rhs.m_pairs.empty()) { const_iterator pos, end = rhs.m_pairs.end(); for (pos = rhs.m_pairs.begin(); pos != end; ++pos) m_pairs.push_back(*pos); if (notify && m_callback) m_callback(*this, m_callback_baton); } } void PathMappingList::Insert(const ConstString &path, const ConstString &replacement, uint32_t index, bool notify) { ++m_mod_id; iterator insert_iter; if (index >= m_pairs.size()) insert_iter = m_pairs.end(); else insert_iter = m_pairs.begin() + index; m_pairs.emplace(insert_iter, pair(NormalizePath(path), NormalizePath(replacement))); if (notify && m_callback) m_callback(*this, m_callback_baton); } bool PathMappingList::Replace(const ConstString &path, const ConstString &replacement, uint32_t index, bool notify) { if (index >= m_pairs.size()) return false; ++m_mod_id; m_pairs[index] = pair(NormalizePath(path), NormalizePath(replacement)); if (notify && m_callback) m_callback(*this, m_callback_baton); return true; } bool PathMappingList::Remove(size_t index, bool notify) { if (index >= m_pairs.size()) return false; ++m_mod_id; iterator iter = m_pairs.begin() + index; m_pairs.erase(iter); if (notify && m_callback) m_callback(*this, m_callback_baton); return true; } // For clients which do not need the pair index dumped, pass a pair_index >= 0 // to only dump the indicated pair. void PathMappingList::Dump(Stream *s, int pair_index) { unsigned int numPairs = m_pairs.size(); if (pair_index < 0) { unsigned int index; for (index = 0; index < numPairs; ++index) s->Printf("[%d] \"%s\" -> \"%s\"\n", index, m_pairs[index].first.GetCString(), m_pairs[index].second.GetCString()); } else { if (static_cast<unsigned int>(pair_index) < numPairs) s->Printf("%s -> %s", m_pairs[pair_index].first.GetCString(), m_pairs[pair_index].second.GetCString()); } } void PathMappingList::Clear(bool notify) { if (!m_pairs.empty()) ++m_mod_id; m_pairs.clear(); if (notify && m_callback) m_callback(*this, m_callback_baton); } bool PathMappingList::RemapPath(const ConstString &path, ConstString &new_path) const { std::string remapped; if (RemapPath(path.GetStringRef(), remapped)) { new_path.SetString(remapped); return true; } return false; } bool PathMappingList::RemapPath(llvm::StringRef path, std::string &new_path) const { if (m_pairs.empty() || path.empty()) return false; LazyBool path_is_relative = eLazyBoolCalculate; for (const auto &it : m_pairs) { auto prefix = it.first.GetStringRef(); if (!path.consume_front(prefix)) { // Relative paths won't have a leading "./" in them unless "." is the // only thing in the relative path so we need to work around "." // carefully. if (prefix != ".") continue; // We need to figure out if the "path" argument is relative. If it is, // then we should remap, else skip this entry. if (path_is_relative == eLazyBoolCalculate) { path_is_relative = FileSpec(path).IsRelative() ? eLazyBoolYes : eLazyBoolNo; } if (!path_is_relative) continue; } FileSpec remapped(it.second.GetStringRef()); remapped.AppendPathComponent(path); new_path = remapped.GetPath(); return true; } return false; } bool PathMappingList::ReverseRemapPath(const FileSpec &file, FileSpec &fixed) const { std::string path = file.GetPath(); llvm::StringRef path_ref(path); for (const auto &it : m_pairs) { if (!path_ref.consume_front(it.second.GetStringRef())) continue; fixed.SetFile(it.first.GetStringRef(), FileSpec::Style::native); fixed.AppendPathComponent(path_ref); return true; } return false; } bool PathMappingList::FindFile(const FileSpec &orig_spec, FileSpec &new_spec) const { if (m_pairs.empty()) return false; std::string orig_path = orig_spec.GetPath(); if (orig_path.empty()) return false; bool orig_is_relative = orig_spec.IsRelative(); for (auto entry : m_pairs) { llvm::StringRef orig_ref(orig_path); llvm::StringRef prefix_ref = entry.first.GetStringRef(); if (orig_ref.size() < prefix_ref.size()) continue; // We consider a relative prefix or one of just "." to // mean "only apply to relative paths". bool prefix_is_relative = false; if (prefix_ref == ".") { prefix_is_relative = true; // Remove the "." since it will have been removed from the // FileSpec paths already. prefix_ref = prefix_ref.drop_front(); } else { FileSpec prefix_spec(prefix_ref, FileSpec::Style::native); prefix_is_relative = prefix_spec.IsRelative(); } if (prefix_is_relative != orig_is_relative) continue; if (orig_ref.consume_front(prefix_ref)) { new_spec.SetFile(entry.second.GetCString(), FileSpec::Style::native); new_spec.AppendPathComponent(orig_ref); if (FileSystem::Instance().Exists(new_spec)) return true; } } new_spec.Clear(); return false; } bool PathMappingList::Replace(const ConstString &path, const ConstString &new_path, bool notify) { uint32_t idx = FindIndexForPath(path); if (idx < m_pairs.size()) { ++m_mod_id; m_pairs[idx].second = new_path; if (notify && m_callback) m_callback(*this, m_callback_baton); return true; } return false; } bool PathMappingList::Remove(const ConstString &path, bool notify) { iterator pos = FindIteratorForPath(path); if (pos != m_pairs.end()) { ++m_mod_id; m_pairs.erase(pos); if (notify && m_callback) m_callback(*this, m_callback_baton); return true; } return false; } PathMappingList::const_iterator PathMappingList::FindIteratorForPath(const ConstString &path) const { const_iterator pos; const_iterator begin = m_pairs.begin(); const_iterator end = m_pairs.end(); for (pos = begin; pos != end; ++pos) { if (pos->first == path) break; } return pos; } PathMappingList::iterator PathMappingList::FindIteratorForPath(const ConstString &path) { iterator pos; iterator begin = m_pairs.begin(); iterator end = m_pairs.end(); for (pos = begin; pos != end; ++pos) { if (pos->first == path) break; } return pos; } bool PathMappingList::GetPathsAtIndex(uint32_t idx, ConstString &path, ConstString &new_path) const { if (idx < m_pairs.size()) { path = m_pairs[idx].first; new_path = m_pairs[idx].second; return true; } return false; } uint32_t PathMappingList::FindIndexForPath(const ConstString &orig_path) const { const ConstString path = NormalizePath(orig_path); const_iterator pos; const_iterator begin = m_pairs.begin(); const_iterator end = m_pairs.end(); for (pos = begin; pos != end; ++pos) { if (pos->first == path) return std::distance(begin, pos); } return UINT32_MAX; } <|endoftext|>
<commit_before>#ifndef PK_BINARYINDEXEDTREE2D_HPP #define PK_BINARYINDEXEDTREE2D_HPP namespace pk { namespace detail { struct binary_indexed_tree_2d_entry { binary_indexed_tree_2d_entry(const int x_, const int y_) : x(x_), y(y_) {} int x; int y; }; struct binary_indexed_tree_2d_subrange { binary_indexed_tree_2d_subrange(const int from_, const int to_) : from(from_), to(to_) {} int from; int to; }; } // namespace detail template<class ValueType, int Range1, int Range2> class binary_indexed_tree_2d { public: typedef ValueType value_type; typedef detail::binary_indexed_tree_2d_entry entry; typedef detail::binary_indexed_tree_2d_subrange subrange; binary_indexed_tree_2d(const int real_range_1_, const int real_range_2_) : real_range_1(real_range_1_), real_range_2(real_range_2_) { for(int x = 0; x < real_range_1; ++x) for(int y = 0; y < real_range_2; ++y) data[x][y] = value_type(); } void increase(entry e, const value_type& value) { while(e.x < real_range_1) { int y1 = e.y; while(y1 < real_range_2) { data[e.x][y1] += value; y1 |= y1 + 1; } e.x |= e.x + 1; } } void set(const entry& e, const value_type& value) { const value_type old_value = count_less_equal(e.x, e.y); increase(e, value - old_value); } int count_less_equal(int x, int y) const { value_type sum = value_type(); while(x >= 0) { int y1 = y; while(y1 >= 0) { sum += data[x][y1]; y1 &= y1 + 1; --y1; } x &= x + 1; --x; } return sum; } int count_in_range(const subrange& x_subrange, const subrange& y_subrange) const { return (count_less_equal(x_subrange.to, y_subrange.to) - count_less_equal(x_subrange.to, y_subrange.from - 1) - count_less_equal(x_subrange.from - 1, y_subrange.to) + count_less_equal(x_subrange.from - 1, y_subrange.from - 1)); } private: value_type data[Range1][Range2]; const int real_range_1; const int real_range_2; }; } // namespace pk #endif // PK_BINARYINDEXEDTREE2D_HPP <commit_msg>fix in binary_indexed_tree_2d::set()<commit_after>#ifndef PK_BINARYINDEXEDTREE2D_HPP #define PK_BINARYINDEXEDTREE2D_HPP namespace pk { namespace detail { struct binary_indexed_tree_2d_entry { binary_indexed_tree_2d_entry(const int x_, const int y_) : x(x_), y(y_) {} int x; int y; }; struct binary_indexed_tree_2d_subrange { binary_indexed_tree_2d_subrange(const int from_, const int to_) : from(from_), to(to_) {} int from; int to; }; } // namespace detail template<class ValueType, int Range1, int Range2> class binary_indexed_tree_2d { public: typedef ValueType value_type; typedef detail::binary_indexed_tree_2d_entry entry; typedef detail::binary_indexed_tree_2d_subrange subrange; binary_indexed_tree_2d(const int real_range_1_, const int real_range_2_) : real_range_1(real_range_1_), real_range_2(real_range_2_) { for(int x = 0; x < real_range_1; ++x) for(int y = 0; y < real_range_2; ++y) data[x][y] = value_type(); } void increase(entry e, const value_type& value) { while(e.x < real_range_1) { int y1 = e.y; while(y1 < real_range_2) { data[e.x][y1] += value; y1 |= y1 + 1; } e.x |= e.x + 1; } } void set(const entry& e, const value_type& value) { const value_type old_value = count_in_range(subrange(e.x, e.x), subrange(e.y, e.y)); increase(e, value - old_value); } int count_less_equal(int x, int y) const { value_type sum = value_type(); while(x >= 0) { int y1 = y; while(y1 >= 0) { sum += data[x][y1]; y1 &= y1 + 1; --y1; } x &= x + 1; --x; } return sum; } int count_in_range(const subrange& x_subrange, const subrange& y_subrange) const { return (count_less_equal(x_subrange.to, y_subrange.to) - count_less_equal(x_subrange.to, y_subrange.from - 1) - count_less_equal(x_subrange.from - 1, y_subrange.to) + count_less_equal(x_subrange.from - 1, y_subrange.from - 1)); } private: value_type data[Range1][Range2]; const int real_range_1; const int real_range_2; }; } // namespace pk #endif // PK_BINARYINDEXEDTREE2D_HPP <|endoftext|>
<commit_before><commit_msg>missing include limits<commit_after><|endoftext|>
<commit_before><commit_msg>Add newline to end of download_manager.cc<commit_after><|endoftext|>
<commit_before>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <graph/power.hh> using namespace parasols; Graph parasols::power(const Graph & graph, int n) { /* this is spectacularly dumb. we can do a lot better. */ Graph result = graph; for (int p = 1 ; p < n ; ++p) { Graph prev_result = result; for (int i = 0 ; i < graph.size() ; ++i) { for (int j = 0 ; j < graph.size() ; ++j) { if (i == j) continue; if (prev_result.adjacent(i, j)) { for (int k = 0 ; k < graph.size() ; ++k) { if (j == k) continue; if (graph.adjacent(i, k)) result.add_edge(j, k); } } } } } return result; } <commit_msg>Better power code<commit_after>/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #include <graph/power.hh> #include <limits> using namespace parasols; Graph parasols::power(const Graph & graph, int n) { std::vector<std::vector<int> > distances((graph.size())); for (auto & d : distances) d.resize((graph.size())); /* d(m, n) = infinity */ for (int i = 0 ; i < graph.size() ; ++i) for (int j = 0 ; j < graph.size() ; ++j) distances[i][j] = std::numeric_limits<int>::max(); /* d(m, m) = 0 */ for (int i = 0 ; i < graph.size() ; ++i) distances[i][i] = 0; /* d(m, n) = 1 if m, n in members and adjacent */ for (int i = 0 ; i < graph.size() ; ++i) for (int j = 0 ; j < graph.size() ; ++j) if (i != j && graph.adjacent(i, j)) distances[i][j] = 1; /* shorten */ for (int i = 0 ; i < graph.size() ; ++i) for (int j = 0 ; j < graph.size() ; ++j) for (int k = 0 ; k < graph.size() ; ++k) { if (distances[i][k] != std::numeric_limits<int>::max() && distances[k][j] != std::numeric_limits<int>::max()) { int d = distances[i][k] + distances[k][j]; if (distances[i][j] > d) distances[i][j] = d; } } Graph result; result.resize(graph.size()); for (int i = 0 ; i < graph.size() ; ++i) { for (int j = 0 ; j < graph.size() ; ++j) { if (i == j) continue; if (distances[i][j] <= n) result.add_edge(i, j); } } return result; } <|endoftext|>
<commit_before>#include "ROM.h" #include <fstream> #include <iostream> #include <iterator> #include <stdexcept> #include <cstring> // From https://stackoverflow.com/questions/15138353/reading-the-binary-file-into-the-vector-of-unsigned-chars ROM ROM::FromFile(const std::string& filename) { // Make file stream std::ifstream file(filename, std::ios::binary); if (!file.good()) { throw std::runtime_error("Bad Stream Status: does the file exist?"); } file.unsetf(std::ios::skipws); // Get file size std::streampos fileSize; file.seekg(0, std::ios::end); fileSize = file.tellg(); file.seekg(0, std::ios::beg); std::vector<uint8_t> bytes; bytes.reserve(fileSize); bytes.insert(bytes.begin(), std::istream_iterator<uint8_t>(file), std::istream_iterator<uint8_t>()); return ROM(bytes); } ROM::ROM(const std::vector<uint8_t>& bytes) { // Get header bytes from buffer const int headerSize = sizeof(ROMHeader); uint8_t headerBytes[headerSize]; std::copy(bytes.begin() + 0x100, bytes.begin() + 0x100 + headerSize, headerBytes); memcpy(&header, headerBytes, headerSize); // Create ROM MBC (Memory Bank Controller) from type switch (header.Type) { case ROM_ONLY: case ROM_RAM: case ROM_R_B: controller = new NoMBC(header.Type); break; case ROM_MBC1: case ROM_MBC1_RAM: case ROM_MBC1_R_B: controller = new MBC1(header.Type); break; case ROM_MBC3: case ROM_MBC3_RAM: case ROM_MBC3_R_B: controller = new MBC3(header.Type); break; default: throw std::logic_error("Unsupported MBC type"); } // Load content to ROM banks controller->LoadROM(header, bytes); //TODO load from .sav to RAM // The title can be either 15 or 13 characters, depending on target console std::string title; if (header.GBC.colorFlag == GBSupported || header.GBC.colorFlag == GBCOnly) { title = std::string(header.GBC.title); } else { title = std::string(header.GBTitle); } std::cout << "Loaded ROM: " << title << std::endl; } ROM::~ROM() { delete controller; } void ROM::debugPrintData() const { std::cout << "== ROM INFO ==" << std::endl; // The title can be either 15 or 13 characters, depending on target console if (header.GBC.colorFlag == GBSupported || header.GBC.colorFlag == GBCOnly) { std::cout << "Title (GBC format): " << std::string(header.GBC.title) << std::endl; std::cout << "Manufacturer Code: " << std::string(header.GBC.manCode) << std::endl; } else { std::cout << "Title (GB format): " << std::string(header.GBTitle) << std::endl; } // GBC features support std::string gbFlag = "GBC not supported"; if (header.GBC.colorFlag == GBSupported) gbFlag = "GBC features supported"; if (header.GBC.colorFlag == GBCOnly) gbFlag = "GBC Only"; std::cout << "GBC support: " << gbFlag << std::endl; // SGB features support std::string super = "SGB not supported"; if (header.superFlag == SGB) super = "SGB features supported"; std::cout << "SGB support: " << super << std::endl; // ROM/RAM types std::cout << "ROM Type: " << std::hex << header.Type << std::endl; std::cout << "ROM Size: " << std::hex << header.ROMSize << std::endl; std::cout << "RAM Size: " << std::hex << header.RAMSize << std::endl; // Manufacturer code(s) if (header.oldLicenseeCode != 0x33) { std::cout << "Licensee code (old): " << std::hex << (int) header.oldLicenseeCode << std::endl; } else { std::cout << "Licensee code (new): " << header.newLicenseeCode[0] << header.newLicenseeCode[1] << std::endl; } // Destination code and other infos std::cout << "Destination code: " << (header.destinationCode == Japanese ? "Japan Only" : "Non-Japanese") << std::endl; std::cout << "Mask ROM version: " << (int) header.maskROMVersion << std::endl; std::cout << "== END ROM INFO ==" << std::endl; } <commit_msg>Add more readable informations in the ROM info subcommand<commit_after>#include "ROM.h" #include <fstream> #include <iostream> #include <iterator> #include <stdexcept> #include <cstring> #include <map> // From https://stackoverflow.com/questions/15138353/reading-the-binary-file-into-the-vector-of-unsigned-chars ROM ROM::FromFile(const std::string& filename) { // Make file stream std::ifstream file(filename, std::ios::binary); if (!file.good()) { throw std::runtime_error("Bad Stream Status: does the file exist?"); } file.unsetf(std::ios::skipws); // Get file size std::streampos fileSize; file.seekg(0, std::ios::end); fileSize = file.tellg(); file.seekg(0, std::ios::beg); std::vector<uint8_t> bytes; bytes.reserve(fileSize); bytes.insert(bytes.begin(), std::istream_iterator<uint8_t>(file), std::istream_iterator<uint8_t>()); return ROM(bytes); } ROM::ROM(const std::vector<uint8_t>& bytes) { // Get header bytes from buffer const int headerSize = sizeof(ROMHeader); uint8_t headerBytes[headerSize]; std::copy(bytes.begin() + 0x100, bytes.begin() + 0x100 + headerSize, headerBytes); memcpy(&header, headerBytes, headerSize); // Create ROM MBC (Memory Bank Controller) from type switch (header.Type) { case ROM_ONLY: case ROM_RAM: case ROM_R_B: controller = new NoMBC(header.Type); break; case ROM_MBC1: case ROM_MBC1_RAM: case ROM_MBC1_R_B: controller = new MBC1(header.Type); break; case ROM_MBC3: case ROM_MBC3_RAM: case ROM_MBC3_R_B: controller = new MBC3(header.Type); break; default: throw std::logic_error("Unsupported MBC type"); } // Load content to ROM banks controller->LoadROM(header, bytes); //TODO load from .sav to RAM // The title can be either 15 or 13 characters, depending on target console std::string title; if (header.GBC.colorFlag == GBSupported || header.GBC.colorFlag == GBCOnly) { title = std::string(header.GBC.title); } else { title = std::string(header.GBTitle); } std::cout << "Loaded ROM: " << title << std::endl; } ROM::~ROM() { delete controller; } void ROM::debugPrintData() const { static const std::map<uint8_t, std::string> RomType = { {0x00, "ROM only"}, {0x08, "ROM + RAM"}, {0x09, "ROM + RAM + Battery"}, {0x01, "ROM + MBC1"}, {0x02, "ROM + MBC1 + RAM"}, {0x03, "ROM + MBC1 + RAM + Battery"}, {0x05, "ROM + MBC2"}, {0x06, "ROM + MBC2 + RAM + Battery"}, {0x11, "ROM + MBC3"}, {0x12, "ROM + MBC3 + RAM"}, {0x13, "ROM + MBC3 + RAM + Battery"}, {0x0f, "ROM + MBC3 + Timer + Battery"}, {0x10, "ROM + MBC3 + Timer + RAM + Battery"}, {0x19, "ROM + MBC5"}, {0x1a, "ROM + MBC5 + RAM"}, {0x1b, "ROM + MBC5 + RAM + Battery"}, {0x1c, "ROM + MBC5 + Rumble"}, {0x1d, "ROM + MBC5 + RAM + Rumble"}, {0x1e, "ROM + MBC5 + RAM + Rumble + Battery"}, {0x20, "ROM + MBC6 + RAM + Battery"}, {0x22, "ROM + MBC7 + RAM + Battery + Accelerometer"}, {0x0b, "ROM + MMM1"}, {0x0c, "ROM + MMM1 + RAM"}, {0x0d, "ROM + MMM1 + RAM + Battery"}, {0xfc, "ROM + Camera"}, {0xfd, "ROM + TAMA5"}, {0xfe, "ROM + HUC3"}, {0xff, "ROM + HUC1 + RAM + Battery"} }; static const std::string RomSize[] = { "32 kB, 2 banks", "64 kB, 4 banks", "128 kB, 8 banks", "256 kB, 16 banks", "512 kB, 32 banks", "1 MB, 64 banks", "2 MB, 128 banks", "4 MB, 256 banks", "8 MB, 512 banks" }; static const std::string RamSize[] = { "None", "2 kB, 1 bank", "8 kB, 1 bank", "32 kB, 4 banks", "128 kB, 16 banks", "64 kB, 8 banks" }; std::cout << "== ROM INFO ==" << std::endl; // The title can be either 15 or 13 characters, depending on target console if (header.GBC.colorFlag == GBSupported || header.GBC.colorFlag == GBCOnly) { std::cout << "Title (GBC format): " << std::string(header.GBC.title) << std::endl; std::cout << "Manufacturer Code: " << std::string(header.GBC.manCode) << std::endl; } else { std::cout << "Title (GB format): " << std::string(header.GBTitle) << std::endl; } // GBC features support std::string gbFlag = "GBC not supported"; if (header.GBC.colorFlag == GBSupported) gbFlag = "GBC features supported"; if (header.GBC.colorFlag == GBCOnly) gbFlag = "GBC Only"; std::cout << "GBC support: " << gbFlag << std::endl; // SGB features support std::string super = "SGB not supported"; if (header.superFlag == SGB) super = "SGB features supported"; std::cout << "SGB support: " << super << std::endl; // ROM/RAM types std::cout << "ROM Type: " << RomType.at(header.Type) << " (" << std::hex << (int)header.Type << ")" << std::endl; std::cout << "ROM Size: " << RomSize[(int)header.ROMSize] << " (" << std::hex << (int)header.ROMSize << ")" << std::endl; std::cout << "RAM Size: " << RamSize[(int)header.RAMSize] << " (" << std::hex << (int)header.RAMSize << ")" << std::endl; // Manufacturer code(s) if (header.oldLicenseeCode != 0x33) { std::cout << "Licensee code (old): " << std::hex << (int) header.oldLicenseeCode << std::endl; } else { std::cout << "Licensee code (new): " << header.newLicenseeCode[0] << header.newLicenseeCode[1] << std::endl; } // Destination code and other infos std::cout << "Destination code: " << (header.destinationCode == Japanese ? "Japan Only" : "Non-Japanese") << std::endl; std::cout << "Mask ROM version: " << (int) header.maskROMVersion << std::endl; std::cout << "== END ROM INFO ==" << std::endl; } <|endoftext|>
<commit_before>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2016 Liviu Ionescu. * * µOS++ 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, version 3. * * µOS++ 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 program. If not, see <http://www.gnu.org/licenses/>. */ #include <cmsis-plus/std/thread> #include <cmsis-plus/diag/trace.h> #include <cstdio> #include <iostream> using namespace os::cmsis; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" // ---------------------------------------------------------------------------- void task1 (void); void task2 (const void* args); void task3 (void* args); // ---------------------------------------------------------------------------- void task1 (void) { trace::printf ("task1()\n"); ; } void task2 (const void* args) { trace::printf ("task2(%p)\n", args); } void task3 (void* args) { trace::printf ("task3(%p)\n", args); } // ---------------------------------------------------------------------------- extern "C" void sleep_for_ticks (uint32_t); void sleep_for_ticks (uint32_t) { } // ---------------------------------------------------------------------------- int main (int argc, char* argv[]) { using namespace ::std::chrono; using namespace os::cmsis::std; using namespace os::cmsis; char c; thread th11 { task1 }; th11.native_handle ()->__run_function (); new int (); thread th12 { "th12", 777, task1 }; th12.native_handle ()->__run_function (); thread th13 { (char*) "th12", 777, task1 }; th13.native_handle ()->__run_function (); thread th21 { task2, &c }; th21.native_handle ()->__run_function (); thread th31 { task3, &c }; th31.native_handle ()->__run_function (); this_thread::sleep_for (milliseconds { 20 }); th11.native_handle ()->set_priority (rtos::Priority::high); th11.join (); th12.join (); th13.join (); th21.join (); th31.join (); trace::printf ("%s done.\n", argv[0]); return 0; } #pragma GCC diagnostic pop <commit_msg>update std test for chrono<commit_after>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2016 Liviu Ionescu. * * µOS++ 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, version 3. * * µOS++ 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 program. If not, see <http://www.gnu.org/licenses/>. */ #include <cmsis-plus/std/thread> #include <cmsis-plus/diag/trace.h> #include <cstdio> #include <iostream> #include <chrono> using namespace os::cmsis; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" // ---------------------------------------------------------------------------- void task1 (void); void task2 (const void* args); void task3 (void* args); // ---------------------------------------------------------------------------- void task1 (void) { trace::printf ("task1()\n"); } void task2 (const void* args) { trace::printf ("task2(%p)\n", args); } void task3 (void* args) { trace::printf ("task3(%p)\n", args); } // ---------------------------------------------------------------------------- extern "C" void sleep_for_ticks (uint32_t); void sleep_for_ticks (uint32_t) { } // ---------------------------------------------------------------------------- #if !defined(OS_INCLUDE_CMSIS_THREAD_VARIADICS) #error OS_INCLUDE_CMSIS_THREAD_VARIADICS #endif int main (int argc, char* argv[]) { using namespace ::std::chrono; using namespace os::cmsis::std; using namespace os::cmsis; using namespace os; char c; thread th11 { task1 }; th11.native_handle ()->__run_function (); new int (); thread th12 { new rtos::Thread { "th12", 777, rtos::Priority::normal, task1 } }; th12.native_handle ()->__run_function (); thread th13 { new rtos::Thread { (char*) "th13", 777, rtos::Priority::normal, task1 } }; th13.native_handle ()->__run_function (); #if 1 thread th21 { task2, &c }; th21.native_handle ()->__run_function (); thread th31 { task3, &c }; th31.native_handle ()->__run_function (); this_thread::sleep_for (microseconds (3001001)); this_thread::sleep_for (milliseconds (3001)); this_thread::sleep_for (seconds (3)); #if 0 int n = 70; this_thread::sleep_for (milliseconds (n)); #endif th11.native_handle ()->set_priority (rtos::Priority::high); th11.join (); th12.join (); th13.join (); th21.join (); th31.join (); #endif trace::printf ("%s done.\n", argv[0]); return 0; } #pragma GCC diagnostic pop <|endoftext|>
<commit_before>#include "Units.h" #include "RhoZ.h" using namespace GeFiCa; void RhoZ::DoSOR2(int idx) { if (fIsFixed[idx])return; // 2nd-order Successive Over-Relaxation double density=fImpurity[idx]*Qe; double drm=fdC1m[idx]; // dr_minus double drp=fdC1p[idx]; double dzm=fdC2m[idx]; double dzp=fdC2p[idx]; double pzm,pzp,prm,prp; // pzm: potential_z_plus if(idx>=fN1)pzm=fV[idx-fN1]; else pzm=fV[idx+fN1]; if(idx>=fN-fN1)pzp=fV[idx]; else pzp=fV[idx+fN1]; if(idx%fN1==0)prm=fV[idx]; else prm=fV[idx-1]; if(idx%fN1==fN1-1)prp=fV[idx]; else prp=fV[idx+1]; double tmp=(density/epsilon + 1/fC1[idx]*(prp-prm)/(drm+drp) +(prp/drp+prm/drm)*2/(drm+drp) + (pzp/dzp+pzm/dzm)*2/(dzp+dzm))/ ((1/drm+1/drp)*2/(drm+drp)+(1/dzp+1/dzm)*2/(dzp+dzm)); //find minmium and maxnium of all five grid, the new one should not go overthem. //find min double min=prm; double max=prm; if(min>prp)min=prp; if (min>pzp)min=pzp; if (min>pzm)min=pzm; //find max if(max<prp)max=prp; if (max<pzp)max=pzp; if (max<pzm)max=pzm; //if tmp is greater or smaller than max and min, set tmp to it. //over relax //fV[idx]=Csor*(tmp-fV[idx])+fV[idx]; //if need calculate depleted voltage double oldP=fV[idx]; tmp=Csor*(tmp-oldP)+oldP; if(tmp<min) { fV[idx]=min; fIsDepleted[idx]=false; } else if(tmp>max) { fV[idx]=max; fIsDepleted[idx]=false; } else fIsDepleted[idx]=true; if(fIsDepleted[idx]||V0==V1) fV[idx]=tmp; } //_____________________________________________________________________________ // double RhoZ::GetC() { Info("GetC", "Start..."); CalculatePotential(GeFiCa::kSOR2); // identify undepleted region // set impurity to zero double *tmpImpurity=fImpurity; for (int i=0;i<fN;i++) { if (fImpurity[i]!=0) { //impurity not clear,return //return -1; fImpurity=new double[fN]; for (int j=0;j<fN;j++) { fImpurity[j]=0; if (!fIsFixed[j] && !fIsDepleted[j]) fIsFixed[j]=true; } break; } } // calculate potential without impurity Nsor=0; CalculatePotential(GeFiCa::kSOR2); // set impurity back if(fImpurity!=tmpImpurity) delete []fImpurity; fImpurity=tmpImpurity; // calculate C based on CV^2/2 = epsilon int E^2 dx^3 / 2 double dV=V0-V1; if(dV<0)dV=-dV; double SumofElectricField=0; for(int i=0;i<fN;i++) { double e1=fE1[i]; double e2=fE2[i]; double dr=fdC1p[i]; double dz=fdC2p[i]; SumofElectricField+=(e1*e1+e2*e2)*fC1[i]*dr*dz; } double c=SumofElectricField*2*3.14159*epsilon/dV/dV; Info("GetC","%.2f pF",c/pF); return c; } <commit_msg>removed Nsor<commit_after>#include "Units.h" #include "RhoZ.h" using namespace GeFiCa; void RhoZ::DoSOR2(int idx) { if (fIsFixed[idx])return; // 2nd-order Successive Over-Relaxation double density=fImpurity[idx]*Qe; double drm=fdC1m[idx]; // dr_minus double drp=fdC1p[idx]; double dzm=fdC2m[idx]; double dzp=fdC2p[idx]; double pzm,pzp,prm,prp; // pzm: potential_z_plus if(idx>=fN1)pzm=fV[idx-fN1]; else pzm=fV[idx+fN1]; if(idx>=fN-fN1)pzp=fV[idx]; else pzp=fV[idx+fN1]; if(idx%fN1==0)prm=fV[idx]; else prm=fV[idx-1]; if(idx%fN1==fN1-1)prp=fV[idx]; else prp=fV[idx+1]; double tmp=(density/epsilon + 1/fC1[idx]*(prp-prm)/(drm+drp) +(prp/drp+prm/drm)*2/(drm+drp) + (pzp/dzp+pzm/dzm)*2/(dzp+dzm))/ ((1/drm+1/drp)*2/(drm+drp)+(1/dzp+1/dzm)*2/(dzp+dzm)); //find minmium and maxnium of all five grid, the new one should not go overthem. //find min double min=prm; double max=prm; if(min>prp)min=prp; if (min>pzp)min=pzp; if (min>pzm)min=pzm; //find max if(max<prp)max=prp; if (max<pzp)max=pzp; if (max<pzm)max=pzm; //if tmp is greater or smaller than max and min, set tmp to it. //over relax //fV[idx]=Csor*(tmp-fV[idx])+fV[idx]; //if need calculate depleted voltage double oldP=fV[idx]; tmp=Csor*(tmp-oldP)+oldP; if(tmp<min) { fV[idx]=min; fIsDepleted[idx]=false; } else if(tmp>max) { fV[idx]=max; fIsDepleted[idx]=false; } else fIsDepleted[idx]=true; if(fIsDepleted[idx]||V0==V1) fV[idx]=tmp; } //_____________________________________________________________________________ // double RhoZ::GetC() { Info("GetC", "Start..."); CalculatePotential(GeFiCa::kSOR2); // identify undepleted region // set impurity to zero double *tmpImpurity=fImpurity; for (int i=0;i<fN;i++) { if (fImpurity[i]!=0) { //impurity not clear,return //return -1; fImpurity=new double[fN]; for (int j=0;j<fN;j++) { fImpurity[j]=0; if (!fIsFixed[j] && !fIsDepleted[j]) fIsFixed[j]=true; } break; } } // calculate potential without impurity CalculatePotential(GeFiCa::kSOR2); // set impurity back if(fImpurity!=tmpImpurity) delete []fImpurity; fImpurity=tmpImpurity; // calculate C based on CV^2/2 = epsilon int E^2 dx^3 / 2 double dV=V0-V1; if(dV<0)dV=-dV; double SumofElectricField=0; for(int i=0;i<fN;i++) { double e1=fE1[i]; double e2=fE2[i]; double dr=fdC1p[i]; double dz=fdC2p[i]; SumofElectricField+=(e1*e1+e2*e2)*fC1[i]*dr*dz; } double c=SumofElectricField*2*3.14159*epsilon/dV/dV; Info("GetC","%.2f pF",c/pF); return c; } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "Copyright (c) 2011 Tokutek Inc. All rights reserved." #ident "$Id$" #include <toku_portability.h> #include <zlib.h> #include <lzma.h> #include "compress.h" #include "memory.h" #include "quicklz.h" #include "toku_assert.h" static inline enum toku_compression_method normalize_compression_method(enum toku_compression_method method) // Effect: resolve "friendly" names like "fast" and "small" into their real values. { switch (method) { case TOKU_DEFAULT_COMPRESSION_METHOD: case TOKU_FAST_COMPRESSION_METHOD: return TOKU_QUICKLZ_METHOD; case TOKU_SMALL_COMPRESSION_METHOD: return TOKU_LZMA_METHOD; default: return method; // everything else is fine } } size_t toku_compress_bound (enum toku_compression_method a, size_t size) // See compress.h for the specification of this function. { a = normalize_compression_method(a); switch (a) { case TOKU_NO_COMPRESSION: return size + 1; case TOKU_LZMA_METHOD: return 1+lzma_stream_buffer_bound(size); // We need one extra for the rfc1950-style header byte (bits -03 are TOKU_LZMA_METHOD (1), bits 4-7 are the compression level) case TOKU_QUICKLZ_METHOD: return size+400 + 1; // quicklz manual says 400 bytes is enough. We need one more byte for the rfc1950-style header byte. bits 0-3 are 9, bits 4-7 are the QLZ_COMPRESSION_LEVEL. case TOKU_ZLIB_METHOD: return compressBound (size); default: break; } // fall through for bad enum (thus compiler can warn us if we didn't use all the enums assert(0); return 0; } static const int zlib_compression_level = 5; void toku_compress (enum toku_compression_method a, // the following types and naming conventions come from zlib.h Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) // See compress.h for the specification of this function. { a = normalize_compression_method(a); assert(sourceLen < (1LL << 32)); switch (a) { case TOKU_NO_COMPRESSION: dest[0] = TOKU_NO_COMPRESSION; memcpy(dest + 1, source, sourceLen); *destLen = sourceLen + 1; return; case TOKU_ZLIB_METHOD: { int r = compress2(dest, destLen, source, sourceLen, zlib_compression_level); assert(r == Z_OK); assert((dest[0]&0xF) == TOKU_ZLIB_METHOD); return; } case TOKU_QUICKLZ_METHOD: { if (sourceLen==0) { // quicklz requires at least one byte, so we handle this ourselves assert(1 <= *destLen); *destLen = 1; } else { qlz_state_compress *XCALLOC(qsc); size_t actual_destlen = qlz_compress(source, (char*)(dest+1), sourceLen, qsc); assert(actual_destlen +1 <= *destLen); *destLen = actual_destlen+1; // add one for the rfc1950-style header byte. toku_free(qsc); } // Fill in that first byte dest[0] = TOKU_QUICKLZ_METHOD + (QLZ_COMPRESSION_LEVEL << 4); return; } case TOKU_LZMA_METHOD: { const int lzma_compression_level = 2; if (sourceLen==0) { // lzma version 4.999 requires at least one byte, so we'll do it ourselves. assert(1<=*destLen); *destLen = 1; } else { size_t out_pos = 1; lzma_ret r = lzma_easy_buffer_encode(lzma_compression_level, LZMA_CHECK_CRC32, NULL, source, sourceLen, dest, &out_pos, *destLen); assert(out_pos < *destLen); if (r != LZMA_OK) { fprintf(stderr, "lzma_easy_buffer_encode() returned %d\n", (int) r); } assert(r==LZMA_OK); *destLen = out_pos; } dest[0] = TOKU_LZMA_METHOD + (lzma_compression_level << 4); return; } default: break; } // default fall through to error. assert(0); } void toku_decompress (Bytef *dest, uLongf destLen, const Bytef *source, uLongf sourceLen) // See compress.h for the specification of this function. { assert(sourceLen>=1); // need at least one byte for the RFC header. switch (source[0] & 0xF) { case TOKU_NO_COMPRESSION: memcpy(dest, source + 1, sourceLen - 1); return; case TOKU_ZLIB_METHOD: { uLongf actual_destlen = destLen; int r = uncompress(dest, &actual_destlen, source, sourceLen); assert(r == Z_OK); assert(actual_destlen == destLen); return; } case TOKU_QUICKLZ_METHOD: if (sourceLen>1) { qlz_state_decompress *XCALLOC(qsd); uLongf actual_destlen = qlz_decompress((char*)source+1, dest, qsd); assert(actual_destlen == destLen); toku_free(qsd); } else { // length 1 means there is no data, so do nothing. assert(destLen==0); } return; case TOKU_LZMA_METHOD: { if (sourceLen>1) { uint64_t memlimit = UINT64_MAX; size_t out_pos = 0; size_t in_pos = 1; lzma_ret r = lzma_stream_buffer_decode(&memlimit, // memlimit, use UINT64_MAX to disable this check 0, // flags NULL, // allocator source, &in_pos, sourceLen, dest, &out_pos, destLen); assert(r==LZMA_OK); assert(out_pos == destLen); } else { // length 1 means there is no data, so do nothing. assert(destLen==0); } return; } } // default fall through to error. assert(0); } <commit_msg>fixes #5915 disable crc for lzma<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: #ident "Copyright (c) 2011 Tokutek Inc. All rights reserved." #ident "$Id$" #include <toku_portability.h> #include <zlib.h> #include <lzma.h> #include "compress.h" #include "memory.h" #include "quicklz.h" #include "toku_assert.h" static inline enum toku_compression_method normalize_compression_method(enum toku_compression_method method) // Effect: resolve "friendly" names like "fast" and "small" into their real values. { switch (method) { case TOKU_DEFAULT_COMPRESSION_METHOD: case TOKU_FAST_COMPRESSION_METHOD: return TOKU_QUICKLZ_METHOD; case TOKU_SMALL_COMPRESSION_METHOD: return TOKU_LZMA_METHOD; default: return method; // everything else is fine } } size_t toku_compress_bound (enum toku_compression_method a, size_t size) // See compress.h for the specification of this function. { a = normalize_compression_method(a); switch (a) { case TOKU_NO_COMPRESSION: return size + 1; case TOKU_LZMA_METHOD: return 1+lzma_stream_buffer_bound(size); // We need one extra for the rfc1950-style header byte (bits -03 are TOKU_LZMA_METHOD (1), bits 4-7 are the compression level) case TOKU_QUICKLZ_METHOD: return size+400 + 1; // quicklz manual says 400 bytes is enough. We need one more byte for the rfc1950-style header byte. bits 0-3 are 9, bits 4-7 are the QLZ_COMPRESSION_LEVEL. case TOKU_ZLIB_METHOD: return compressBound (size); default: break; } // fall through for bad enum (thus compiler can warn us if we didn't use all the enums assert(0); return 0; } static const int zlib_compression_level = 5; void toku_compress (enum toku_compression_method a, // the following types and naming conventions come from zlib.h Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) // See compress.h for the specification of this function. { a = normalize_compression_method(a); assert(sourceLen < (1LL << 32)); switch (a) { case TOKU_NO_COMPRESSION: dest[0] = TOKU_NO_COMPRESSION; memcpy(dest + 1, source, sourceLen); *destLen = sourceLen + 1; return; case TOKU_ZLIB_METHOD: { int r = compress2(dest, destLen, source, sourceLen, zlib_compression_level); assert(r == Z_OK); assert((dest[0]&0xF) == TOKU_ZLIB_METHOD); return; } case TOKU_QUICKLZ_METHOD: { if (sourceLen==0) { // quicklz requires at least one byte, so we handle this ourselves assert(1 <= *destLen); *destLen = 1; } else { qlz_state_compress *XCALLOC(qsc); size_t actual_destlen = qlz_compress(source, (char*)(dest+1), sourceLen, qsc); assert(actual_destlen +1 <= *destLen); *destLen = actual_destlen+1; // add one for the rfc1950-style header byte. toku_free(qsc); } // Fill in that first byte dest[0] = TOKU_QUICKLZ_METHOD + (QLZ_COMPRESSION_LEVEL << 4); return; } case TOKU_LZMA_METHOD: { const int lzma_compression_level = 2; if (sourceLen==0) { // lzma version 4.999 requires at least one byte, so we'll do it ourselves. assert(1<=*destLen); *destLen = 1; } else { size_t out_pos = 1; lzma_ret r = lzma_easy_buffer_encode(lzma_compression_level, LZMA_CHECK_NONE, NULL, source, sourceLen, dest, &out_pos, *destLen); assert(out_pos < *destLen); if (r != LZMA_OK) { fprintf(stderr, "lzma_easy_buffer_encode() returned %d\n", (int) r); } assert(r==LZMA_OK); *destLen = out_pos; } dest[0] = TOKU_LZMA_METHOD + (lzma_compression_level << 4); return; } default: break; } // default fall through to error. assert(0); } void toku_decompress (Bytef *dest, uLongf destLen, const Bytef *source, uLongf sourceLen) // See compress.h for the specification of this function. { assert(sourceLen>=1); // need at least one byte for the RFC header. switch (source[0] & 0xF) { case TOKU_NO_COMPRESSION: memcpy(dest, source + 1, sourceLen - 1); return; case TOKU_ZLIB_METHOD: { uLongf actual_destlen = destLen; int r = uncompress(dest, &actual_destlen, source, sourceLen); assert(r == Z_OK); assert(actual_destlen == destLen); return; } case TOKU_QUICKLZ_METHOD: if (sourceLen>1) { qlz_state_decompress *XCALLOC(qsd); uLongf actual_destlen = qlz_decompress((char*)source+1, dest, qsd); assert(actual_destlen == destLen); toku_free(qsd); } else { // length 1 means there is no data, so do nothing. assert(destLen==0); } return; case TOKU_LZMA_METHOD: { if (sourceLen>1) { uint64_t memlimit = UINT64_MAX; size_t out_pos = 0; size_t in_pos = 1; lzma_ret r = lzma_stream_buffer_decode(&memlimit, // memlimit, use UINT64_MAX to disable this check 0, // flags NULL, // allocator source, &in_pos, sourceLen, dest, &out_pos, destLen); assert(r==LZMA_OK); assert(out_pos == destLen); } else { // length 1 means there is no data, so do nothing. assert(destLen==0); } return; } } // default fall through to error. assert(0); } <|endoftext|>
<commit_before>// Copyright (c) 2012 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 "media/audio/null_audio_sink.h" #include "base/bind.h" #include "base/stringprintf.h" #include "base/sys_byteorder.h" #include "base/threading/platform_thread.h" namespace media { NullAudioSink::NullAudioSink() : initialized_(false), playback_rate_(0.0), playing_(false), callback_(NULL), thread_("NullAudioThread"), hash_audio_for_testing_(false) { } void NullAudioSink::Initialize(const AudioParameters& params, RenderCallback* callback) { DCHECK(!initialized_); params_ = params; audio_data_.reserve(params.channels()); for (int i = 0; i < params.channels(); ++i) { float* channel_data = new float[params.frames_per_buffer()]; audio_data_.push_back(channel_data); } if (hash_audio_for_testing_) { md5_channel_contexts_.reset(new base::MD5Context[params.channels()]); for (int i = 0; i < params.channels(); i++) base::MD5Init(&md5_channel_contexts_[i]); } callback_ = callback; initialized_ = true; } void NullAudioSink::Start() { if (!thread_.Start()) return; thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &NullAudioSink::FillBufferTask, this)); } void NullAudioSink::Stop() { SetPlaying(false); thread_.Stop(); } void NullAudioSink::Play() { SetPlaying(true); } void NullAudioSink::Pause(bool /* flush */) { SetPlaying(false); } void NullAudioSink::SetPlaybackRate(float rate) { base::AutoLock auto_lock(lock_); playback_rate_ = rate; } bool NullAudioSink::SetVolume(double volume) { // Audio is always muted. return volume == 0.0; } void NullAudioSink::GetVolume(double* volume) { // Audio is always muted. *volume = 0.0; } void NullAudioSink::SetPlaying(bool is_playing) { base::AutoLock auto_lock(lock_); playing_ = is_playing; } NullAudioSink::~NullAudioSink() { DCHECK(!thread_.IsRunning()); for (size_t i = 0; i < audio_data_.size(); ++i) delete [] audio_data_[i]; } void NullAudioSink::FillBufferTask() { base::AutoLock auto_lock(lock_); base::TimeDelta delay; // Only consume buffers when actually playing. if (playing_) { DCHECK_GT(playback_rate_, 0.0f); int requested_frames = params_.frames_per_buffer(); int frames_received = callback_->Render(audio_data_, requested_frames, 0); int frames_per_millisecond = params_.sample_rate() / base::Time::kMillisecondsPerSecond; if (hash_audio_for_testing_ && frames_received > 0) { DCHECK_EQ(sizeof(float), sizeof(uint32)); int channels = audio_data_.size(); for (int channel_idx = 0; channel_idx < channels; ++channel_idx) { for (int frame_idx = 0; frame_idx < frames_received; frame_idx++) { // Convert float to uint32 w/o conversion loss. uint32 frame = base::ByteSwapToLE32(*reinterpret_cast<uint32*>( &audio_data_[channel_idx][frame_idx])); base::MD5Update( &md5_channel_contexts_[channel_idx], base::StringPiece( reinterpret_cast<char*>(&frame), sizeof(frame))); } } } // Calculate our sleep duration, taking playback rate into consideration. delay = base::TimeDelta::FromMilliseconds( frames_received / (frames_per_millisecond * playback_rate_)); } else { // If paused, sleep for 10 milliseconds before polling again. delay = base::TimeDelta::FromMilliseconds(10); } // Sleep for at least one millisecond so we don't spin the CPU. MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&NullAudioSink::FillBufferTask, this), std::max(delay, base::TimeDelta::FromMilliseconds(1))); } void NullAudioSink::StartAudioHashForTesting() { DCHECK(!initialized_); hash_audio_for_testing_ = true; } std::string NullAudioSink::GetAudioHashForTesting() { DCHECK(hash_audio_for_testing_); // If initialize failed or was never called, ensure we return an empty hash. if (!initialized_) { md5_channel_contexts_.reset(new base::MD5Context[1]); base::MD5Init(&md5_channel_contexts_[0]); } // Hash all channels into the first channel. base::MD5Digest digest; for (size_t i = 1; i < audio_data_.size(); i++) { base::MD5Final(&digest, &md5_channel_contexts_[i]); base::MD5Update(&md5_channel_contexts_[0], base::StringPiece( reinterpret_cast<char*>(&digest), sizeof(base::MD5Digest))); } base::MD5Final(&digest, &md5_channel_contexts_[0]); return base::MD5DigestToBase16(digest); } } // namespace media <commit_msg>Fix address casting in audio hashing.<commit_after>// Copyright (c) 2012 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 "media/audio/null_audio_sink.h" #include "base/bind.h" #include "base/stringprintf.h" #include "base/sys_byteorder.h" #include "base/threading/platform_thread.h" namespace media { NullAudioSink::NullAudioSink() : initialized_(false), playback_rate_(0.0), playing_(false), callback_(NULL), thread_("NullAudioThread"), hash_audio_for_testing_(false) { } void NullAudioSink::Initialize(const AudioParameters& params, RenderCallback* callback) { DCHECK(!initialized_); params_ = params; audio_data_.reserve(params.channels()); for (int i = 0; i < params.channels(); ++i) { float* channel_data = new float[params.frames_per_buffer()]; audio_data_.push_back(channel_data); } if (hash_audio_for_testing_) { md5_channel_contexts_.reset(new base::MD5Context[params.channels()]); for (int i = 0; i < params.channels(); i++) base::MD5Init(&md5_channel_contexts_[i]); } callback_ = callback; initialized_ = true; } void NullAudioSink::Start() { if (!thread_.Start()) return; thread_.message_loop()->PostTask(FROM_HERE, base::Bind( &NullAudioSink::FillBufferTask, this)); } void NullAudioSink::Stop() { SetPlaying(false); thread_.Stop(); } void NullAudioSink::Play() { SetPlaying(true); } void NullAudioSink::Pause(bool /* flush */) { SetPlaying(false); } void NullAudioSink::SetPlaybackRate(float rate) { base::AutoLock auto_lock(lock_); playback_rate_ = rate; } bool NullAudioSink::SetVolume(double volume) { // Audio is always muted. return volume == 0.0; } void NullAudioSink::GetVolume(double* volume) { // Audio is always muted. *volume = 0.0; } void NullAudioSink::SetPlaying(bool is_playing) { base::AutoLock auto_lock(lock_); playing_ = is_playing; } NullAudioSink::~NullAudioSink() { DCHECK(!thread_.IsRunning()); for (size_t i = 0; i < audio_data_.size(); ++i) delete [] audio_data_[i]; } void NullAudioSink::FillBufferTask() { base::AutoLock auto_lock(lock_); base::TimeDelta delay; // Only consume buffers when actually playing. if (playing_) { DCHECK_GT(playback_rate_, 0.0f); int requested_frames = params_.frames_per_buffer(); int frames_received = callback_->Render(audio_data_, requested_frames, 0); int frames_per_millisecond = params_.sample_rate() / base::Time::kMillisecondsPerSecond; if (hash_audio_for_testing_ && frames_received > 0) { DCHECK_EQ(sizeof(float), sizeof(uint32)); int channels = audio_data_.size(); for (int channel_idx = 0; channel_idx < channels; ++channel_idx) { float* channel = audio_data_[channel_idx]; for (int frame_idx = 0; frame_idx < frames_received; frame_idx++) { // Convert float to uint32 w/o conversion loss. uint32 frame = base::ByteSwapToLE32( bit_cast<uint32>(channel[frame_idx])); base::MD5Update( &md5_channel_contexts_[channel_idx], base::StringPiece( reinterpret_cast<char*>(&frame), sizeof(frame))); } } } // Calculate our sleep duration, taking playback rate into consideration. delay = base::TimeDelta::FromMilliseconds( frames_received / (frames_per_millisecond * playback_rate_)); } else { // If paused, sleep for 10 milliseconds before polling again. delay = base::TimeDelta::FromMilliseconds(10); } // Sleep for at least one millisecond so we don't spin the CPU. MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&NullAudioSink::FillBufferTask, this), std::max(delay, base::TimeDelta::FromMilliseconds(1))); } void NullAudioSink::StartAudioHashForTesting() { DCHECK(!initialized_); hash_audio_for_testing_ = true; } std::string NullAudioSink::GetAudioHashForTesting() { DCHECK(hash_audio_for_testing_); // If initialize failed or was never called, ensure we return an empty hash. if (!initialized_) { md5_channel_contexts_.reset(new base::MD5Context[1]); base::MD5Init(&md5_channel_contexts_[0]); } // Hash all channels into the first channel. base::MD5Digest digest; for (size_t i = 1; i < audio_data_.size(); i++) { base::MD5Final(&digest, &md5_channel_contexts_[i]); base::MD5Update(&md5_channel_contexts_[0], base::StringPiece( reinterpret_cast<char*>(&digest), sizeof(base::MD5Digest))); } base::MD5Final(&digest, &md5_channel_contexts_[0]); return base::MD5DigestToBase16(digest); } } // namespace media <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/lite/tools/benchmark/benchmark_performance_options.h" #include <algorithm> #include <iomanip> #include <memory> #include <sstream> #include <utility> #include "tensorflow/core/util/stats_calculator.h" #include "tensorflow/lite/c/c_api_internal.h" #if defined(__ANDROID__) #include "tensorflow/lite/delegates/gpu/gl_delegate.h" #endif #include "tensorflow/lite/profiling/time.h" #include "tensorflow/lite/tools/benchmark/benchmark_params.h" #include "tensorflow/lite/tools/benchmark/benchmark_utils.h" #include "tensorflow/lite/tools/benchmark/logging.h" #include "tensorflow/lite/tools/command_line_flags.h" namespace tflite { namespace benchmark { void MultiRunStatsRecorder::OnBenchmarkStart(const BenchmarkParams& params) { current_run_name_.clear(); if (params.Get<bool>("use_nnapi")) { current_run_name_ = "nnapi"; return; } if (params.Get<bool>("use_gpu")) { #if defined(__ANDROID__) const bool allow_precision_loss = params.Get<bool>("gpu_precision_loss_allowed"); const std::string precision_tag = allow_precision_loss ? "fp16" : "fp32"; current_run_name_ = "gpu(" + precision_tag + ")"; #else current_run_name_ = "gpu(fp16, fastest)-default"; #endif return; } // Handle cases run on CPU // Note: could use std::to_string to convert an integer to string but it // requires C++11. std::stringstream sstm; sstm << "cpu w/ " << params.Get<int32_t>("num_threads") << " threads"; current_run_name_ = sstm.str(); } void MultiRunStatsRecorder::OnBenchmarkEnd(const BenchmarkResults& results) { each_run_stats_.emplace_back(std::make_pair(current_run_name_, results)); } void MultiRunStatsRecorder::OutputStats() { // Make a 80-character-long header. TFLITE_LOG(INFO) << "\n==============Summary of All Runs w/ Different " "Performance Options=============="; std::sort(each_run_stats_.begin(), each_run_stats_.end(), EachRunStatsEntryComparator()); for (const auto& run_stats : each_run_stats_) { std::stringstream stream; // Output the name of this run first. stream << std::setw(26) << run_stats.first << ": "; run_stats.second.inference_time_us().OutputToStream(&stream); TFLITE_LOG(INFO) << stream.str(); } } BenchmarkPerformanceOptions::BenchmarkPerformanceOptions( BenchmarkModel* single_option_run) : BenchmarkPerformanceOptions(DefaultParams(), single_option_run, DefaultRunStatsRecorder()) {} BenchmarkPerformanceOptions::BenchmarkPerformanceOptions( BenchmarkParams params, BenchmarkModel* single_option_run, std::unique_ptr<MultiRunStatsRecorder> all_run_stats) : params_(std::move(params)), single_option_run_(single_option_run), single_option_run_params_(single_option_run->mutable_params()), all_run_stats_(std::move(all_run_stats)) { single_option_run_->AddListener(all_run_stats_.get()); } BenchmarkParams BenchmarkPerformanceOptions::DefaultParams() { BenchmarkParams params; params.AddParam("perf_options_list", BenchmarkParam::Create<std::string>("all")); params.AddParam("option_benchmark_run_delay", BenchmarkParam::Create<float>(-1.0f)); params.AddParam("random_shuffle_benchmark_runs", BenchmarkParam::Create<bool>(true)); return params; } std::unique_ptr<MultiRunStatsRecorder> BenchmarkPerformanceOptions::DefaultRunStatsRecorder() { return std::unique_ptr<MultiRunStatsRecorder>(new MultiRunStatsRecorder()); } std::vector<Flag> BenchmarkPerformanceOptions::GetFlags() { return { CreateFlag<std::string>( "perf_options_list", &params_, "A comma-separated list of TFLite performance options to benchmark. " "By default, all performance options are benchmarked."), CreateFlag<float>("option_benchmark_run_delay", &params_, "The delay between two consecutive runs of " "benchmarking performance options in seconds."), CreateFlag<bool>( "random_shuffle_benchmark_runs", &params_, "Whether to perform all benchmark runs, each of which has different " "performance options, in a random order. It is enabled by default."), }; } bool BenchmarkPerformanceOptions::ParseFlags(int* argc, char** argv) { auto flag_list = GetFlags(); const bool parse_result = Flags::Parse(argc, const_cast<const char**>(argv), flag_list); if (!parse_result) { std::string usage = Flags::Usage(argv[0], flag_list); TFLITE_LOG(ERROR) << usage; return false; } // Parse the value of --perf_options_list to find performance options to be // benchmarked. return ParsePerfOptions(); } bool BenchmarkPerformanceOptions::ParsePerfOptions() { const auto& perf_options_list = params_.Get<std::string>("perf_options_list"); if (!util::SplitAndParse(perf_options_list, ',', &perf_options_)) { TFLITE_LOG(ERROR) << "Cannot parse --perf_options_list: '" << perf_options_list << "'. Please double-check its value."; perf_options_.clear(); return false; } const auto valid_options = GetValidPerfOptions(); bool is_valid = true; for (const auto& option : perf_options_) { if (std::find(valid_options.begin(), valid_options.end(), option) == valid_options.end()) { is_valid = false; break; } } if (!is_valid) { std::string valid_options_str; for (int i = 0; i < valid_options.size() - 1; ++i) { valid_options_str += (valid_options[i] + ", "); } valid_options_str += valid_options.back(); TFLITE_LOG(ERROR) << "There are invalid perf options in --perf_options_list: '" << perf_options_list << "'. Valid perf options are: [" << valid_options_str << "]"; perf_options_.clear(); return false; } return true; } std::vector<std::string> BenchmarkPerformanceOptions::GetValidPerfOptions() const { return {"all", "cpu", "gpu", "nnapi"}; } bool BenchmarkPerformanceOptions::HasOption(const std::string& option) const { return std::find(perf_options_.begin(), perf_options_.end(), option) != perf_options_.end(); } void BenchmarkPerformanceOptions::ResetPerformanceOptions() { single_option_run_params_->Set<int32_t>("num_threads", 1); single_option_run_params_->Set<bool>("use_gpu", false); #if defined(__ANDROID__) single_option_run_params_->Set<bool>("gpu_precision_loss_allowed", true); #endif single_option_run_params_->Set<bool>("use_nnapi", false); } void BenchmarkPerformanceOptions::CreatePerformanceOptions() { TFLITE_LOG(INFO) << "The list of TFLite runtime options to be benchmarked: [" << params_.Get<std::string>("perf_options_list") << "]"; const bool benchmark_all = HasOption("all"); if (benchmark_all || HasOption("cpu")) { const std::vector<int> num_threads = {1, 2, 4}; for (const int count : num_threads) { BenchmarkParams params; params.AddParam("num_threads", BenchmarkParam::Create<int32_t>(count)); all_run_params_.emplace_back(std::move(params)); } } if (benchmark_all || HasOption("gpu")) { #if defined(__ANDROID__) const std::vector<bool> allow_precision_loss = {true, false}; const std::vector<int32_t> gl_obj_types = {TFLITE_GL_OBJECT_TYPE_TEXTURE, TFLITE_GL_OBJECT_TYPE_BUFFER}; for (const auto precision_loss : allow_precision_loss) { for (const auto obj_type : gl_obj_types) { BenchmarkParams params; params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true)); params.AddParam("gpu_precision_loss_allowed", BenchmarkParam::Create<bool>(precision_loss)); all_run_params_.emplace_back(std::move(params)); } } #endif // Note by default, gpu delegate allows to operate on lower precision and // uses the fastest GL object type. BenchmarkParams params; params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true)); all_run_params_.emplace_back(std::move(params)); } if (benchmark_all || HasOption("nnapi")) { BenchmarkParams params; params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true)); all_run_params_.emplace_back(std::move(params)); } } void BenchmarkPerformanceOptions::Run(int argc, char** argv) { // We first parse flags for single-option runs to get information like // parameters of the input model etc. if (single_option_run_->ParseFlags(&argc, argv) != kTfLiteOk) return; // Now, we parse flags that are specified for this particular binary. if (!ParseFlags(&argc, argv)) return; // Now, the remaining are unrecognized flags and we simply print them out. for (int i = 1; i < argc; ++i) { TFLITE_LOG(WARN) << "WARNING: unrecognized commandline flag: " << argv[i]; } CreatePerformanceOptions(); if (params_.Get<bool>("random_shuffle_benchmark_runs")) { std::random_shuffle(all_run_params_.begin(), all_run_params_.end()); } // Now perform all runs, each with different performance-affecting parameters. for (const auto& run_params : all_run_params_) { // Reset all performance-related options before any runs. ResetPerformanceOptions(); single_option_run_params_->Set(run_params); util::SleepForSeconds(params_.Get<float>("option_benchmark_run_delay")); single_option_run_->Run(); } all_run_stats_->OutputStats(); } } // namespace benchmark } // namespace tflite <commit_msg>Change imported header file to resolve build error.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. 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 "tensorflow/lite/tools/benchmark/benchmark_performance_options.h" #include <algorithm> #include <iomanip> #include <memory> #include <sstream> #include <utility> #include "tensorflow/core/util/stats_calculator.h" #include "tensorflow/lite/c/c_api_internal.h" #if defined(__ANDROID__) #include "tensorflow/lite/delegates/gpu/delegate.h" #endif #include "tensorflow/lite/profiling/time.h" #include "tensorflow/lite/tools/benchmark/benchmark_params.h" #include "tensorflow/lite/tools/benchmark/benchmark_utils.h" #include "tensorflow/lite/tools/benchmark/logging.h" #include "tensorflow/lite/tools/command_line_flags.h" namespace tflite { namespace benchmark { void MultiRunStatsRecorder::OnBenchmarkStart(const BenchmarkParams& params) { current_run_name_.clear(); if (params.Get<bool>("use_nnapi")) { current_run_name_ = "nnapi"; return; } if (params.Get<bool>("use_gpu")) { #if defined(__ANDROID__) const bool allow_precision_loss = params.Get<bool>("gpu_precision_loss_allowed"); const std::string precision_tag = allow_precision_loss ? "fp16" : "fp32"; current_run_name_ = "gpu(" + precision_tag + ")"; #else current_run_name_ = "gpu(fp16, fastest)-default"; #endif return; } // Handle cases run on CPU // Note: could use std::to_string to convert an integer to string but it // requires C++11. std::stringstream sstm; sstm << "cpu w/ " << params.Get<int32_t>("num_threads") << " threads"; current_run_name_ = sstm.str(); } void MultiRunStatsRecorder::OnBenchmarkEnd(const BenchmarkResults& results) { each_run_stats_.emplace_back(std::make_pair(current_run_name_, results)); } void MultiRunStatsRecorder::OutputStats() { // Make a 80-character-long header. TFLITE_LOG(INFO) << "\n==============Summary of All Runs w/ Different " "Performance Options=============="; std::sort(each_run_stats_.begin(), each_run_stats_.end(), EachRunStatsEntryComparator()); for (const auto& run_stats : each_run_stats_) { std::stringstream stream; // Output the name of this run first. stream << std::setw(26) << run_stats.first << ": "; run_stats.second.inference_time_us().OutputToStream(&stream); TFLITE_LOG(INFO) << stream.str(); } } BenchmarkPerformanceOptions::BenchmarkPerformanceOptions( BenchmarkModel* single_option_run) : BenchmarkPerformanceOptions(DefaultParams(), single_option_run, DefaultRunStatsRecorder()) {} BenchmarkPerformanceOptions::BenchmarkPerformanceOptions( BenchmarkParams params, BenchmarkModel* single_option_run, std::unique_ptr<MultiRunStatsRecorder> all_run_stats) : params_(std::move(params)), single_option_run_(single_option_run), single_option_run_params_(single_option_run->mutable_params()), all_run_stats_(std::move(all_run_stats)) { single_option_run_->AddListener(all_run_stats_.get()); } BenchmarkParams BenchmarkPerformanceOptions::DefaultParams() { BenchmarkParams params; params.AddParam("perf_options_list", BenchmarkParam::Create<std::string>("all")); params.AddParam("option_benchmark_run_delay", BenchmarkParam::Create<float>(-1.0f)); params.AddParam("random_shuffle_benchmark_runs", BenchmarkParam::Create<bool>(true)); return params; } std::unique_ptr<MultiRunStatsRecorder> BenchmarkPerformanceOptions::DefaultRunStatsRecorder() { return std::unique_ptr<MultiRunStatsRecorder>(new MultiRunStatsRecorder()); } std::vector<Flag> BenchmarkPerformanceOptions::GetFlags() { return { CreateFlag<std::string>( "perf_options_list", &params_, "A comma-separated list of TFLite performance options to benchmark. " "By default, all performance options are benchmarked."), CreateFlag<float>("option_benchmark_run_delay", &params_, "The delay between two consecutive runs of " "benchmarking performance options in seconds."), CreateFlag<bool>( "random_shuffle_benchmark_runs", &params_, "Whether to perform all benchmark runs, each of which has different " "performance options, in a random order. It is enabled by default."), }; } bool BenchmarkPerformanceOptions::ParseFlags(int* argc, char** argv) { auto flag_list = GetFlags(); const bool parse_result = Flags::Parse(argc, const_cast<const char**>(argv), flag_list); if (!parse_result) { std::string usage = Flags::Usage(argv[0], flag_list); TFLITE_LOG(ERROR) << usage; return false; } // Parse the value of --perf_options_list to find performance options to be // benchmarked. return ParsePerfOptions(); } bool BenchmarkPerformanceOptions::ParsePerfOptions() { const auto& perf_options_list = params_.Get<std::string>("perf_options_list"); if (!util::SplitAndParse(perf_options_list, ',', &perf_options_)) { TFLITE_LOG(ERROR) << "Cannot parse --perf_options_list: '" << perf_options_list << "'. Please double-check its value."; perf_options_.clear(); return false; } const auto valid_options = GetValidPerfOptions(); bool is_valid = true; for (const auto& option : perf_options_) { if (std::find(valid_options.begin(), valid_options.end(), option) == valid_options.end()) { is_valid = false; break; } } if (!is_valid) { std::string valid_options_str; for (int i = 0; i < valid_options.size() - 1; ++i) { valid_options_str += (valid_options[i] + ", "); } valid_options_str += valid_options.back(); TFLITE_LOG(ERROR) << "There are invalid perf options in --perf_options_list: '" << perf_options_list << "'. Valid perf options are: [" << valid_options_str << "]"; perf_options_.clear(); return false; } return true; } std::vector<std::string> BenchmarkPerformanceOptions::GetValidPerfOptions() const { return {"all", "cpu", "gpu", "nnapi"}; } bool BenchmarkPerformanceOptions::HasOption(const std::string& option) const { return std::find(perf_options_.begin(), perf_options_.end(), option) != perf_options_.end(); } void BenchmarkPerformanceOptions::ResetPerformanceOptions() { single_option_run_params_->Set<int32_t>("num_threads", 1); single_option_run_params_->Set<bool>("use_gpu", false); #if defined(__ANDROID__) single_option_run_params_->Set<bool>("gpu_precision_loss_allowed", true); #endif single_option_run_params_->Set<bool>("use_nnapi", false); } void BenchmarkPerformanceOptions::CreatePerformanceOptions() { TFLITE_LOG(INFO) << "The list of TFLite runtime options to be benchmarked: [" << params_.Get<std::string>("perf_options_list") << "]"; const bool benchmark_all = HasOption("all"); if (benchmark_all || HasOption("cpu")) { const std::vector<int> num_threads = {1, 2, 4}; for (const int count : num_threads) { BenchmarkParams params; params.AddParam("num_threads", BenchmarkParam::Create<int32_t>(count)); all_run_params_.emplace_back(std::move(params)); } } if (benchmark_all || HasOption("gpu")) { #if defined(__ANDROID__) const std::vector<bool> allow_precision_loss = {true, false}; const std::vector<int32_t> gl_obj_types = {TFLITE_GL_OBJECT_TYPE_TEXTURE, TFLITE_GL_OBJECT_TYPE_BUFFER}; for (const auto precision_loss : allow_precision_loss) { for (const auto obj_type : gl_obj_types) { BenchmarkParams params; params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true)); params.AddParam("gpu_precision_loss_allowed", BenchmarkParam::Create<bool>(precision_loss)); all_run_params_.emplace_back(std::move(params)); } } #endif // Note by default, gpu delegate allows to operate on lower precision and // uses the fastest GL object type. BenchmarkParams params; params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true)); all_run_params_.emplace_back(std::move(params)); } if (benchmark_all || HasOption("nnapi")) { BenchmarkParams params; params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true)); all_run_params_.emplace_back(std::move(params)); } } void BenchmarkPerformanceOptions::Run(int argc, char** argv) { // We first parse flags for single-option runs to get information like // parameters of the input model etc. if (single_option_run_->ParseFlags(&argc, argv) != kTfLiteOk) return; // Now, we parse flags that are specified for this particular binary. if (!ParseFlags(&argc, argv)) return; // Now, the remaining are unrecognized flags and we simply print them out. for (int i = 1; i < argc; ++i) { TFLITE_LOG(WARN) << "WARNING: unrecognized commandline flag: " << argv[i]; } CreatePerformanceOptions(); if (params_.Get<bool>("random_shuffle_benchmark_runs")) { std::random_shuffle(all_run_params_.begin(), all_run_params_.end()); } // Now perform all runs, each with different performance-affecting parameters. for (const auto& run_params : all_run_params_) { // Reset all performance-related options before any runs. ResetPerformanceOptions(); single_option_run_params_->Set(run_params); util::SleepForSeconds(params_.Get<float>("option_benchmark_run_delay")); single_option_run_->Run(); } all_run_stats_->OutputStats(); } } // namespace benchmark } // namespace tflite <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "chrome/browser/gtk/location_bar_view_gtk.h" #include <string> #include "base/basictypes.h" #include "base/gfx/gtk_util.h" #include "base/logging.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/alternate_nav_url_fetcher.h" #include "chrome/browser/autocomplete/autocomplete_edit_view_gtk.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/gtk_util.h" #include "chrome/common/page_transition_types.h" #include "skia/include/SkBitmap.h" #include "webkit/glue/window_open_disposition.h" namespace { // We are positioned with a little bit of extra space that we don't use now. const int kTopMargin = 1; const int kBottomMargin = 1; // We don't want to edit control's text to be right against the edge. const int kEditLeftRightPadding = 4; // We draw a border on the top and bottom (but not on left or right). const int kBorderThickness = 1; // TODO(deanm): Eventually this should be painted with the background png // image, but for now we get pretty close by just drawing a solid border. const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4); } // namespace // static const GdkColor LocationBarViewGtk::kBackgroundColorByLevel[3] = { GDK_COLOR_RGB(255, 245, 195), // SecurityLevel SECURE: Yellow. GDK_COLOR_RGB(255, 255, 255), // SecurityLevel NORMAL: White. GDK_COLOR_RGB(255, 255, 255), // SecurityLevel INSECURE: White. }; LocationBarViewGtk::LocationBarViewGtk(CommandUpdater* command_updater, ToolbarModel* toolbar_model, AutocompletePopupPositioner* popup_positioner) : profile_(NULL), command_updater_(command_updater), toolbar_model_(toolbar_model), popup_positioner_(popup_positioner), disposition_(CURRENT_TAB), transition_(PageTransition::TYPED) { } LocationBarViewGtk::~LocationBarViewGtk() { // All of our widgets should have be children of / owned by the alignment. alignment_.Destroy(); } void LocationBarViewGtk::Init() { location_entry_.reset(new AutocompleteEditViewGtk(this, toolbar_model_, profile_, command_updater_, popup_positioner_)); location_entry_->Init(); alignment_.Own(gtk_alignment_new(0.0, 0.0, 1.0, 1.0)); gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_.get()), kTopMargin + kBorderThickness, kBottomMargin + kBorderThickness, kEditLeftRightPadding, kEditLeftRightPadding); // We will paint for the alignment, to paint the background and border. gtk_widget_set_app_paintable(alignment_.get(), TRUE); // Have GTK double buffer around the expose signal. gtk_widget_set_double_buffered(alignment_.get(), TRUE); g_signal_connect(alignment_.get(), "expose-event", G_CALLBACK(&HandleExposeThunk), this); gtk_container_add(GTK_CONTAINER(alignment_.get()), location_entry_->widget()); } void LocationBarViewGtk::SetProfile(Profile* profile) { profile_ = profile; } void LocationBarViewGtk::Update(const TabContents* contents) { location_entry_->Update(contents); // The security level (background color) could have changed, etc. gtk_widget_queue_draw(alignment_.get()); } void LocationBarViewGtk::OnAutocompleteAccept(const GURL& url, WindowOpenDisposition disposition, PageTransition::Type transition, const GURL& alternate_nav_url) { if (!url.is_valid()) return; location_input_ = UTF8ToWide(url.spec()); disposition_ = disposition; transition_ = transition; if (!command_updater_) return; if (!alternate_nav_url.is_valid()) { command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL); return; } scoped_ptr<AlternateNavURLFetcher> fetcher( new AlternateNavURLFetcher(alternate_nav_url)); // The AlternateNavURLFetcher will listen for the pending navigation // notification that will be issued as a result of the "open URL." It // will automatically install itself into that navigation controller. command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL); if (fetcher->state() == AlternateNavURLFetcher::NOT_STARTED) { // I'm not sure this should be reachable, but I'm not also sure enough // that it shouldn't to stick in a NOTREACHED(). In any case, this is // harmless; we can simply let the fetcher get deleted here and it will // clean itself up properly. } else { fetcher.release(); // The navigation controller will delete the fetcher. } } void LocationBarViewGtk::OnChanged() { // TODO(deanm): Here is where we would do layout when we have things like // the keyword display, ssl icons, etc. } void LocationBarViewGtk::OnInputInProgress(bool in_progress) { NOTIMPLEMENTED(); } SkBitmap LocationBarViewGtk::GetFavIcon() const { NOTIMPLEMENTED(); return SkBitmap(); } std::wstring LocationBarViewGtk::GetTitle() const { NOTIMPLEMENTED(); return std::wstring(); } void LocationBarViewGtk::ShowFirstRunBubble() { NOTIMPLEMENTED(); } std::wstring LocationBarViewGtk::GetInputString() const { return location_input_; } WindowOpenDisposition LocationBarViewGtk::GetWindowOpenDisposition() const { return disposition_; } PageTransition::Type LocationBarViewGtk::GetPageTransition() const { return transition_; } void LocationBarViewGtk::AcceptInput() { AcceptInputWithDisposition(CURRENT_TAB); } void LocationBarViewGtk::AcceptInputWithDisposition( WindowOpenDisposition disposition) { location_entry_->model()->AcceptInput(disposition, false); } void LocationBarViewGtk::FocusLocation() { location_entry_->SetFocus(); location_entry_->SelectAll(true); } void LocationBarViewGtk::FocusSearch() { location_entry_->SetUserText(L"?"); location_entry_->SetFocus(); } void LocationBarViewGtk::UpdatePageActions() { NOTIMPLEMENTED(); } void LocationBarViewGtk::SaveStateToContents(TabContents* contents) { NOTIMPLEMENTED(); } void LocationBarViewGtk::Revert() { NOTIMPLEMENTED(); } gboolean LocationBarViewGtk::HandleExpose(GtkWidget* widget, GdkEventExpose* event) { GdkDrawable* drawable = GDK_DRAWABLE(event->window); GdkGC* gc = gdk_gc_new(drawable); GdkRectangle* alloc_rect = &alignment_.get()->allocation; // The area outside of our margin, which includes the border. GdkRectangle inner_rect = { alloc_rect->x, alloc_rect->y + kTopMargin, alloc_rect->width, alloc_rect->height - kTopMargin - kBottomMargin}; // Draw our 1px border. TODO(deanm): Maybe this would be cleaner as an // overdrawn stroked rect with a clip to the allocation? gdk_gc_set_rgb_fg_color(gc, &kBorderColor); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y, inner_rect.width, kBorderThickness); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y + inner_rect.height - kBorderThickness, inner_rect.width, kBorderThickness); // Draw the background within the border. gdk_gc_set_rgb_fg_color(gc, &kBackgroundColorByLevel[toolbar_model_->GetSchemeSecurityLevel()]); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y + kBorderThickness, inner_rect.width, inner_rect.height - (kBorderThickness * 2)); g_object_unref(gc); return FALSE; // Continue propagating the expose. } <commit_msg>Redraw the location bar on reload. This change is Gtk+ port of 100198.<commit_after>// Copyright (c) 2009 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 "chrome/browser/gtk/location_bar_view_gtk.h" #include <string> #include "base/basictypes.h" #include "base/gfx/gtk_util.h" #include "base/logging.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/alternate_nav_url_fetcher.h" #include "chrome/browser/autocomplete/autocomplete_edit_view_gtk.h" #include "chrome/browser/command_updater.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/gtk_util.h" #include "chrome/common/page_transition_types.h" #include "skia/include/SkBitmap.h" #include "webkit/glue/window_open_disposition.h" namespace { // We are positioned with a little bit of extra space that we don't use now. const int kTopMargin = 1; const int kBottomMargin = 1; // We don't want to edit control's text to be right against the edge. const int kEditLeftRightPadding = 4; // We draw a border on the top and bottom (but not on left or right). const int kBorderThickness = 1; // TODO(deanm): Eventually this should be painted with the background png // image, but for now we get pretty close by just drawing a solid border. const GdkColor kBorderColor = GDK_COLOR_RGB(0xbe, 0xc8, 0xd4); } // namespace // static const GdkColor LocationBarViewGtk::kBackgroundColorByLevel[3] = { GDK_COLOR_RGB(255, 245, 195), // SecurityLevel SECURE: Yellow. GDK_COLOR_RGB(255, 255, 255), // SecurityLevel NORMAL: White. GDK_COLOR_RGB(255, 255, 255), // SecurityLevel INSECURE: White. }; LocationBarViewGtk::LocationBarViewGtk(CommandUpdater* command_updater, ToolbarModel* toolbar_model, AutocompletePopupPositioner* popup_positioner) : profile_(NULL), command_updater_(command_updater), toolbar_model_(toolbar_model), popup_positioner_(popup_positioner), disposition_(CURRENT_TAB), transition_(PageTransition::TYPED) { } LocationBarViewGtk::~LocationBarViewGtk() { // All of our widgets should have be children of / owned by the alignment. alignment_.Destroy(); } void LocationBarViewGtk::Init() { location_entry_.reset(new AutocompleteEditViewGtk(this, toolbar_model_, profile_, command_updater_, popup_positioner_)); location_entry_->Init(); alignment_.Own(gtk_alignment_new(0.0, 0.0, 1.0, 1.0)); gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_.get()), kTopMargin + kBorderThickness, kBottomMargin + kBorderThickness, kEditLeftRightPadding, kEditLeftRightPadding); // We will paint for the alignment, to paint the background and border. gtk_widget_set_app_paintable(alignment_.get(), TRUE); // Have GTK double buffer around the expose signal. gtk_widget_set_double_buffered(alignment_.get(), TRUE); g_signal_connect(alignment_.get(), "expose-event", G_CALLBACK(&HandleExposeThunk), this); gtk_container_add(GTK_CONTAINER(alignment_.get()), location_entry_->widget()); } void LocationBarViewGtk::SetProfile(Profile* profile) { profile_ = profile; } void LocationBarViewGtk::Update(const TabContents* contents) { location_entry_->Update(contents); // The security level (background color) could have changed, etc. gtk_widget_queue_draw(alignment_.get()); } void LocationBarViewGtk::OnAutocompleteAccept(const GURL& url, WindowOpenDisposition disposition, PageTransition::Type transition, const GURL& alternate_nav_url) { if (!url.is_valid()) return; location_input_ = UTF8ToWide(url.spec()); disposition_ = disposition; transition_ = transition; if (!command_updater_) return; if (!alternate_nav_url.is_valid()) { command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL); return; } scoped_ptr<AlternateNavURLFetcher> fetcher( new AlternateNavURLFetcher(alternate_nav_url)); // The AlternateNavURLFetcher will listen for the pending navigation // notification that will be issued as a result of the "open URL." It // will automatically install itself into that navigation controller. command_updater_->ExecuteCommand(IDC_OPEN_CURRENT_URL); if (fetcher->state() == AlternateNavURLFetcher::NOT_STARTED) { // I'm not sure this should be reachable, but I'm not also sure enough // that it shouldn't to stick in a NOTREACHED(). In any case, this is // harmless; we can simply let the fetcher get deleted here and it will // clean itself up properly. } else { fetcher.release(); // The navigation controller will delete the fetcher. } } void LocationBarViewGtk::OnChanged() { // TODO(deanm): Here is where we would do layout when we have things like // the keyword display, ssl icons, etc. } void LocationBarViewGtk::OnInputInProgress(bool in_progress) { NOTIMPLEMENTED(); } SkBitmap LocationBarViewGtk::GetFavIcon() const { NOTIMPLEMENTED(); return SkBitmap(); } std::wstring LocationBarViewGtk::GetTitle() const { NOTIMPLEMENTED(); return std::wstring(); } void LocationBarViewGtk::ShowFirstRunBubble() { NOTIMPLEMENTED(); } std::wstring LocationBarViewGtk::GetInputString() const { return location_input_; } WindowOpenDisposition LocationBarViewGtk::GetWindowOpenDisposition() const { return disposition_; } PageTransition::Type LocationBarViewGtk::GetPageTransition() const { return transition_; } void LocationBarViewGtk::AcceptInput() { AcceptInputWithDisposition(CURRENT_TAB); } void LocationBarViewGtk::AcceptInputWithDisposition( WindowOpenDisposition disposition) { location_entry_->model()->AcceptInput(disposition, false); } void LocationBarViewGtk::FocusLocation() { location_entry_->SetFocus(); location_entry_->SelectAll(true); } void LocationBarViewGtk::FocusSearch() { location_entry_->SetUserText(L"?"); location_entry_->SetFocus(); } void LocationBarViewGtk::UpdatePageActions() { NOTIMPLEMENTED(); } void LocationBarViewGtk::SaveStateToContents(TabContents* contents) { NOTIMPLEMENTED(); } void LocationBarViewGtk::Revert() { location_entry_->RevertAll(); } gboolean LocationBarViewGtk::HandleExpose(GtkWidget* widget, GdkEventExpose* event) { GdkDrawable* drawable = GDK_DRAWABLE(event->window); GdkGC* gc = gdk_gc_new(drawable); GdkRectangle* alloc_rect = &alignment_.get()->allocation; // The area outside of our margin, which includes the border. GdkRectangle inner_rect = { alloc_rect->x, alloc_rect->y + kTopMargin, alloc_rect->width, alloc_rect->height - kTopMargin - kBottomMargin}; // Draw our 1px border. TODO(deanm): Maybe this would be cleaner as an // overdrawn stroked rect with a clip to the allocation? gdk_gc_set_rgb_fg_color(gc, &kBorderColor); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y, inner_rect.width, kBorderThickness); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y + inner_rect.height - kBorderThickness, inner_rect.width, kBorderThickness); // Draw the background within the border. gdk_gc_set_rgb_fg_color(gc, &kBackgroundColorByLevel[toolbar_model_->GetSchemeSecurityLevel()]); gdk_draw_rectangle(drawable, gc, TRUE, inner_rect.x, inner_rect.y + kBorderThickness, inner_rect.width, inner_rect.height - (kBorderThickness * 2)); g_object_unref(gc); return FALSE; // Continue propagating the expose. } <|endoftext|>
<commit_before><commit_msg>Fix the position of the throbber for pinned tabs. It was wrong before, but we repainted the whole pinned tab so it wasn't as obvious. With this change, the throbber is placed where the favicon will go.<commit_after><|endoftext|>
<commit_before>///\file conn_http_progressive.cpp ///\brief Contains the main code for the HTTP Progressive Connector #include <iostream> #include <queue> #include <sstream> #include <cstdlib> #include <cstdio> #include <cmath> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <mist/socket.h> #include <mist/http_parser.h> #include <mist/dtsc.h> #include <mist/ogg.h> #include <mist/amf.h> #include <mist/config.h> #include <mist/stream.h> #include <mist/timing.h> ///\brief Holds everything unique to HTTP Connectors. namespace Connector_HTTP { ///\brief Main function for the HTTP Progressive Connector ///\param conn A socket describing the connection the client. ///\return The exit code of the connector. int progressiveConnector(Socket::Connection conn){ bool progressive_has_sent_header = false;//Indicates whether we have sent a header. bool ready4data = false; //Set to true when streaming is to begin. DTSC::Stream Strm; //Incoming stream buffer. HTTP::Parser HTTP_R, HTTP_S;//HTTP Receiver en HTTP Sender. bool inited = false;//Whether the stream is initialized Socket::Connection ss( -1);//The Stream Socket, used to connect to the desired stream. std::string streamname;//Will contain the name of the stream. //MP4 specific variables //OGG specific variables /*OGG::headerPages oggMeta; OGG::Page curOggPage; std::map <long long unsigned int, std::vector<JSON::Value> > DTSCBuffer; std::map <long long unsigned int, long long unsigned int> prevGran;*/ unsigned int lastStats = 0;//Indicates the last time that we have sent stats to the server socket. unsigned int seek_sec = 0;//Seek position in ms unsigned int seek_byte = 0;//Seek position in bytes int videoID = -1; int audioID = -1; while (conn.connected()){ //Only attempt to parse input when not yet init'ed. if ( !inited){ if (conn.Received().size() || conn.spool()){ //make sure it ends in a \n if ( *(conn.Received().get().rbegin()) != '\n'){ std::string tmp = conn.Received().get(); conn.Received().get().clear(); if (conn.Received().size()){ conn.Received().get().insert(0, tmp); }else{ conn.Received().append(tmp); } } if (HTTP_R.Read(conn.Received().get())){ #if DEBUG >= 5 std::cout << "Received request: " << HTTP_R.getUrl() << std::endl; #endif conn.setHost(HTTP_R.GetHeader("X-Origin")); //we assume the URL is the stream name with a 3 letter extension streamname = HTTP_R.getUrl().substr(1); size_t extDot = streamname.rfind('.'); if (extDot != std::string::npos){ streamname.resize(extDot); }; //strip the extension int start = 0; if ( !HTTP_R.GetVar("start").empty()){ start = atoi(HTTP_R.GetVar("start").c_str()); } if ( !HTTP_R.GetVar("starttime").empty()){ start = atoi(HTTP_R.GetVar("starttime").c_str()); } if ( !HTTP_R.GetVar("apstart").empty()){ start = atoi(HTTP_R.GetVar("apstart").c_str()); } if ( !HTTP_R.GetVar("ec_seek").empty()){ start = atoi(HTTP_R.GetVar("ec_seek").c_str()); } if ( !HTTP_R.GetVar("fs").empty()){ start = atoi(HTTP_R.GetVar("fs").c_str()); } //under 3 hours we assume seconds, otherwise byte position if (start < 10800){ seek_sec = start * 1000; //ms, not s }else{ seek_byte = start; //divide by 1mbit, then *1000 for ms. } ready4data = true; HTTP_R.Clean(); //clean for any possible next requests } } } if (ready4data){ if ( !inited){ //we are ready, connect the socket! ss = Util::Stream::getStream(streamname); if ( !ss.connected()){ #if DEBUG >= 1 fprintf(stderr, "Could not connect to server for %s!\n", streamname.c_str()); #endif ss.close(); HTTP_S.Clean(); HTTP_S.SetBody("No such stream is available on the system. Please try again.\n"); conn.SendNow(HTTP_S.BuildResponse("404", "Not found")); ready4data = false; continue; } //wait until we have a header while ( !Strm.metadata && ss.connected()){ if (ss.spool()){ Strm.parsePacket(ss.Received()); //read the metadata }else{ Util::sleep(5); } } int byterate = 0; for (JSON::ObjIter objIt = Strm.metadata["tracks"].ObjBegin(); objIt != Strm.metadata["tracks"].ObjEnd(); objIt++){ if (videoID == -1 && objIt->second["type"].asString() == "video"){ videoID = objIt->second["trackid"].asInt(); } if (audioID == -1 && objIt->second["type"].asString() == "audio"){ audioID = objIt->second["trackid"].asInt(); } } if (videoID != -1){ byterate += Strm.getTrackById(videoID)["bps"].asInt(); } if (audioID != -1){ byterate += Strm.getTrackById(audioID)["bps"].asInt(); } if ( !byterate){byterate = 1;} seek_sec = (seek_byte / byterate) * 1000; std::stringstream cmd; cmd << "t"; if (videoID != -1){ cmd << " " << videoID; } if (audioID != -1){ cmd << " " << audioID; } cmd << "\ns " << seek_sec << "\np\n"; ss.SendNow(cmd.str().c_str(), cmd.str().size()); inited = true; } unsigned int now = Util::epoch(); if (now != lastStats){ lastStats = now; ss.SendNow(conn.getStats("HTTP_Progressive_Ogg").c_str()); } if (ss.spool()){ while (Strm.parsePacket(ss.Received())){ if ( !progressive_has_sent_header){ HTTP_S.Clean(); //make sure no parts of old requests are left in any buffers HTTP_S.SetHeader("Content-Type", "video/ogg"); //Send the correct content-type for FLV files HTTP_S.protocol = "HTTP/1.0"; conn.SendNow(HTTP_S.BuildResponse("200", "OK")); //no SetBody = unknown length - this is intentional, we will stream the entire file //Fill in header here progressive_has_sent_header = true; } //parse DTSC to MP4 here } }else{ Util::sleep(1); } if ( !ss.connected()){ break; } } } conn.close(); ss.SendNow(conn.getStats("HTTP_Dynamic").c_str()); ss.close(); return 0; } //Progressive_Connector main function } //Connector_HTTP namespace ///\brief The standard process-spawning main function. int main(int argc, char ** argv){ Util::Config conf(argv[0], PACKAGE_VERSION); JSON::Value capa; capa["desc"] = "Enables HTTP protocol progressive streaming."; capa["deps"] = "HTTP"; capa["url_rel"] = "/$.mp4"; capa["url_match"] = "/$.mp4"; capa["url_handler"] = "http"; capa["url_type"] = "mp4"; capa["socket"] = "http_progressive_mp4"; conf.addBasicConnectorOptions(capa); conf.parseArgs(argc, argv); if (conf.getBool("json")){ std::cout << capa.toString() << std::endl; return -1; } Socket::Server server_socket = Socket::Server("/tmp/mist/http_progressive_mp4"); if ( !server_socket.connected()){ return 1; } conf.activate(); while (server_socket.connected() && conf.is_active){ Socket::Connection S = server_socket.accept(); if (S.connected()){ //check if the new connection is valid pid_t myid = fork(); if (myid == 0){ //if new child, start MAINHANDLER return Connector_HTTP::progressiveConnector(S); }else{ //otherwise, do nothing or output debugging text #if DEBUG >= 5 fprintf(stderr, "Spawned new process %i for socket %i\n", (int)myid, S.getSocket()); #endif } } } //while connected server_socket.close(); return 0; } //main <commit_msg>MP4 progressive now bleeding edge!<commit_after>///\file conn_http_progressive.cpp ///\brief Contains the main code for the HTTP Progressive Connector #include <iostream> #include <queue> #include <sstream> #include <cstdlib> #include <cstdio> #include <cmath> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <mist/socket.h> #include <mist/http_parser.h> #include <mist/dtsc.h> #include <mist/mp4.h> #include <mist/amf.h> #include <mist/config.h> #include <mist/stream.h> #include <mist/timing.h> ///\brief Holds everything unique to HTTP Connectors. namespace Connector_HTTP { ///\brief Main function for the HTTP Progressive Connector ///\param conn A socket describing the connection the client. ///\return The exit code of the connector. int progressiveConnector(Socket::Connection conn){ bool progressive_has_sent_header = false;//Indicates whether we have sent a header. bool ready4data = false; //Set to true when streaming is to begin. DTSC::Stream Strm; //Incoming stream buffer. HTTP::Parser HTTP_R, HTTP_S;//HTTP Receiver en HTTP Sender. bool inited = false;//Whether the stream is initialized Socket::Connection ss( -1);//The Stream Socket, used to connect to the desired stream. std::string streamname;//Will contain the name of the stream. //MP4 specific variables MP4::DTSC2MP4Converter Conv; unsigned int lastStats = 0;//Indicates the last time that we have sent stats to the server socket. unsigned int seek_sec = 0;//Seek position in ms unsigned int seek_byte = 0;//Seek position in bytes int videoID = -1; int audioID = -1; while (conn.connected()){ //Only attempt to parse input when not yet init'ed. if ( !inited){ if (conn.Received().size() || conn.spool()){ //make sure it ends in a \n if ( *(conn.Received().get().rbegin()) != '\n'){ std::string tmp = conn.Received().get(); conn.Received().get().clear(); if (conn.Received().size()){ conn.Received().get().insert(0, tmp); }else{ conn.Received().append(tmp); } } if (HTTP_R.Read(conn.Received().get())){ #if DEBUG >= 5 std::cout << "Received request: " << HTTP_R.getUrl() << std::endl; #endif conn.setHost(HTTP_R.GetHeader("X-Origin")); //we assume the URL is the stream name with a 3 letter extension streamname = HTTP_R.getUrl().substr(1); size_t extDot = streamname.rfind('.'); if (extDot != std::string::npos){ streamname.resize(extDot); }; //strip the extension int start = 0; if ( !HTTP_R.GetVar("start").empty()){ start = atoi(HTTP_R.GetVar("start").c_str()); } if ( !HTTP_R.GetVar("starttime").empty()){ start = atoi(HTTP_R.GetVar("starttime").c_str()); } if ( !HTTP_R.GetVar("apstart").empty()){ start = atoi(HTTP_R.GetVar("apstart").c_str()); } if ( !HTTP_R.GetVar("ec_seek").empty()){ start = atoi(HTTP_R.GetVar("ec_seek").c_str()); } if ( !HTTP_R.GetVar("fs").empty()){ start = atoi(HTTP_R.GetVar("fs").c_str()); } //under 3 hours we assume seconds, otherwise byte position if (start < 10800){ seek_sec = start * 1000; //ms, not s }else{ seek_byte = start; //divide by 1mbit, then *1000 for ms. } ready4data = true; HTTP_R.Clean(); //clean for any possible next requests } } } if (ready4data){ if ( !inited){ //we are ready, connect the socket! ss = Util::Stream::getStream(streamname); if ( !ss.connected()){ #if DEBUG >= 1 fprintf(stderr, "Could not connect to server for %s!\n", streamname.c_str()); #endif ss.close(); HTTP_S.Clean(); HTTP_S.SetBody("No such stream is available on the system. Please try again.\n"); conn.SendNow(HTTP_S.BuildResponse("404", "Not found")); ready4data = false; continue; } //wait until we have a header while ( !Strm.metadata && ss.connected()){ if (ss.spool()){ Strm.parsePacket(ss.Received()); //read the metadata }else{ Util::sleep(5); } } int byterate = 0; for (JSON::ObjIter objIt = Strm.metadata["tracks"].ObjBegin(); objIt != Strm.metadata["tracks"].ObjEnd(); objIt++){ if (videoID == -1 && objIt->second["type"].asString() == "video"){ videoID = objIt->second["trackid"].asInt(); } if (audioID == -1 && objIt->second["type"].asString() == "audio"){ audioID = objIt->second["trackid"].asInt(); } } if (videoID != -1){ byterate += Strm.getTrackById(videoID)["bps"].asInt(); } if (audioID != -1){ byterate += Strm.getTrackById(audioID)["bps"].asInt(); } if ( !byterate){byterate = 1;} seek_sec = (seek_byte / byterate) * 1000; std::stringstream cmd; cmd << "t"; if (videoID != -1){ cmd << " " << videoID; } if (audioID != -1){ cmd << " " << audioID; } cmd << "\ns " << seek_sec << "\np\n"; ss.SendNow(cmd.str().c_str(), cmd.str().size()); inited = true; } unsigned int now = Util::epoch(); if (now != lastStats){ lastStats = now; ss.SendNow(conn.getStats("HTTP_Progressive_MP4").c_str()); } if (ss.spool()){ while (Strm.parsePacket(ss.Received())){ if ( !progressive_has_sent_header){ HTTP_S.Clean(); //make sure no parts of old requests are left in any buffers HTTP_S.SetHeader("Content-Type", "video/MP4"); //Send the correct content-type for FLV files HTTP_S.protocol = "HTTP/1.0"; conn.SendNow(HTTP_S.BuildResponse("200", "OK")); //no SetBody = unknown length - this is intentional, we will stream the entire file //Fill in header here ss.SendNow(Conv.DTSCMeta2MP4Header(Strm.metadata));//SENDING MP4HADER progressive_has_sent_header = true; } //parse DTSC to MP4 here Conv.parseDTSC(Strm.getPacket());//parse 1 file DTSC packet if(Conv.sendReady()){//if the converter has a part to send out ss.SendNow(Conv.sendString());//send out and clear Convverter buffer } } }else{ Util::sleep(1); } if ( !ss.connected()){ break; } } } conn.close(); ss.SendNow(conn.getStats("HTTP_Dynamic").c_str()); ss.close(); return 0; } //Progressive_Connector main function } //Connector_HTTP namespace ///\brief The standard process-spawning main function. int main(int argc, char ** argv){ Util::Config conf(argv[0], PACKAGE_VERSION); JSON::Value capa; capa["desc"] = "Enables HTTP protocol progressive streaming."; capa["deps"] = "HTTP"; capa["url_rel"] = "/$.mp4"; capa["url_match"] = "/$.mp4"; capa["url_handler"] = "http"; capa["url_type"] = "mp4"; capa["socket"] = "http_progressive_mp4"; conf.addBasicConnectorOptions(capa); conf.parseArgs(argc, argv); if (conf.getBool("json")){ std::cout << capa.toString() << std::endl; return -1; } Socket::Server server_socket = Socket::Server("/tmp/mist/http_progressive_mp4"); if ( !server_socket.connected()){ return 1; } conf.activate(); while (server_socket.connected() && conf.is_active){ Socket::Connection S = server_socket.accept(); if (S.connected()){ //check if the new connection is valid pid_t myid = fork(); if (myid == 0){ //if new child, start MAINHANDLER return Connector_HTTP::progressiveConnector(S); }else{ //otherwise, do nothing or output debugging text #if DEBUG >= 5 fprintf(stderr, "Spawned new process %i for socket %i\n", (int)myid, S.getSocket()); #endif } } } //while connected server_socket.close(); return 0; } //main <|endoftext|>
<commit_before>/* * Copyright (c) 2016 Fastly, Inc. * * 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. */ /* * This file implements a test harness for using h2o with LibFuzzer. * See http://llvm.org/docs/LibFuzzer.html for more info. */ #define H2O_USE_EPOLL 1 #include <string.h> #include <errno.h> #include <limits.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/select.h> #include <sys/wait.h> #include <unistd.h> #include <fcntl.h> #include "h2o.h" #include "h2o/http1.h" #include "h2o/http2.h" #include "h2o/url.h" #include "h2o/memcached.h" #if !defined(HTTP1) && !defined(HTTP2) #error "Please defined one of HTTP1 or HTTP2" #endif #if defined(HTTP1) && defined(HTTP2) #error "Please defined one of HTTP1 or HTTP2, but not both" #endif static h2o_globalconf_t config; static h2o_context_t ctx; static h2o_accept_ctx_t accept_ctx; static int client_timeout_ms; static char unix_listener[PATH_MAX]; /* * Registers a request handler with h2o */ static h2o_pathconf_t *register_handler(h2o_hostconf_t *hostconf, const char *path, int (*on_req)(h2o_handler_t *, h2o_req_t *)) { h2o_pathconf_t *pathconf = h2o_config_register_path(hostconf, path, 0); h2o_handler_t *handler = h2o_create_handler(pathconf, sizeof(*handler)); handler->on_req = on_req; return pathconf; } /* * Request handler used for testing. Returns a basic "200 OK" response. */ static int chunked_test(h2o_handler_t *self, h2o_req_t *req) { static h2o_generator_t generator = {NULL, NULL}; if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET"))) return -1; h2o_iovec_t body = h2o_strdup(&req->pool, "hello world\n", SIZE_MAX); req->res.status = 200; req->res.reason = "OK"; h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, NULL, H2O_STRLIT("text/plain")); h2o_start_response(req, &generator); h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL); return 0; } /* copy from src to dst, return true if src has EOF */ static int drain(int fd) { char buf[4096]; ssize_t n; n = read(fd, buf, sizeof(buf)); if (n <= 0) { return 1; } return 0; } /* A request sent from client thread to h2o server */ struct writer_thread_arg { char *buf; size_t len; int fd; h2o_barrier_t barrier; }; /* * Reads writer_thread_arg from fd and stores to buf */ static void read_fully(int fd, char *buf, size_t len) { int done = 0; while (len) { int ret; while ((ret = read(fd, buf + done, len)) == -1 && errno == EINTR) ; if (ret <= 0) { abort(); } done += ret; len -= ret; } } /* * Writes the writer_thread_args at buf to fd */ static void write_fully(int fd, char *buf, size_t len, int abort_on_err) { int done = 0; while (len) { int ret; while ((ret = write(fd, buf + done, len)) == -1 && errno == EINTR) ; if (ret <= 0) { if (abort_on_err) abort(); else return; } done += ret; len -= ret; } } #define OK_RESP \ "HTTP/1.0 200 OK\r\n" \ "Connection: Close\r\n\r\nOk" #define OK_RESP_LEN (sizeof(OK_RESP) - 1) void *upstream_thread(void *arg) { char *dirname = (char *)arg; char path[PATH_MAX]; char rbuf[1 * 1024 * 1024]; snprintf(path, sizeof(path), "/%s/_.sock", dirname); int sd = socket(AF_UNIX, SOCK_STREAM, 0); if (sd < 0) { abort(); } struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); if (bind(sd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { abort(); } if (listen(sd, 100) != 0) { abort(); } while (1) { struct sockaddr_un caddr; socklen_t slen = 0; int cfs = accept(sd, (struct sockaddr *)&caddr, &slen); if (cfs < 0) { continue; } read(cfs, rbuf, sizeof(rbuf)); write_fully(cfs, (char *)OK_RESP, OK_RESP_LEN, 0); close(cfs); } } /* * Thread: Loops writing fuzzed req to socket and then reading results back. * Acts as a client to h2o. *arg points to file descripter to read * writer_thread_args from. */ void *writer_thread(void *arg) { int rfd = (long)arg; while (1) { int pos, sockinp, sockoutp, cnt, len; char *buf; struct writer_thread_arg *wta; /* Get fuzzed request */ read_fully(rfd, (char *)&wta, sizeof(wta)); pos = 0; sockinp = wta->fd; sockoutp = wta->fd; cnt = 0; buf = wta->buf; len = wta->len; /* * Send fuzzed req and read results until the socket is closed (or * something spurious happens) */ while (cnt++ < 20 && (pos < len || sockinp >= 0)) { #define MARKER "\n--MARK--\n" /* send 1 packet */ if (pos < len) { char *p = (char *)memmem(buf + pos, len - pos, MARKER, sizeof(MARKER) - 1); if (p) { int l = p - (buf + pos); write(sockoutp, buf + pos, l); pos += l; pos += sizeof(MARKER) - 1; } } else { if (sockinp >= 0) { shutdown(sockinp, SHUT_WR); } } /* drain socket */ if (sockinp >= 0) { struct timeval timeo; fd_set rd; int n; FD_ZERO(&rd); FD_SET(sockinp, &rd); timeo.tv_sec = 0; timeo.tv_usec = client_timeout_ms * 1000; n = select(sockinp + 1, &rd, NULL, NULL, &timeo); if (n > 0 && FD_ISSET(sockinp, &rd) && drain(sockinp)) { sockinp = -1; } } } close(wta->fd); h2o_barrier_wait(&wta->barrier); h2o_barrier_destroy(&wta->barrier); free(wta); } } /* * Creates socket pair and passes fuzzed req to a thread (the HTTP[/2] client) * for writing to the target h2o server. Returns the server socket fd. */ static int feeder(int sfd, char *buf, size_t len, h2o_barrier_t **barrier) { int pair[2]; struct writer_thread_arg *wta; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) return -1; wta = (struct writer_thread_arg *)malloc(sizeof(*wta)); wta->fd = pair[0]; wta->buf = buf; wta->len = len; h2o_barrier_init(&wta->barrier, 2); *barrier = &wta->barrier; write_fully(sfd, (char *)&wta, sizeof(wta), 1); return pair[1]; } /* * Creates/connects socket pair for client/server interaction and passes * fuzzed request to client for sending. * Returns server socket fd. */ static int create_accepted(int sfd, char *buf, size_t len, h2o_barrier_t **barrier) { int fd; h2o_socket_t *sock; struct timeval connected_at = *h2o_get_timestamp(&ctx, NULL, NULL); /* Create an HTTP[/2] client that will send the fuzzed request */ fd = feeder(sfd, buf, len, barrier); if (fd < 0) { abort(); } /* Pass the server socket to h2o and invoke request processing */ sock = h2o_evloop_socket_create(ctx.loop, fd, H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION); #if defined(HTTP1) h2o_http1_accept(&accept_ctx, sock, connected_at); #else h2o_http2_accept(&accept_ctx, sock, connected_at); #endif return fd; } /* * Returns true if fd if valid. Used to determine when connection is closed. */ static int is_valid_fd(int fd) { return fcntl(fd, F_GETFD) != -1 || errno != EBADF; } /* * Entry point for libfuzzer. * See http://llvm.org/docs/LibFuzzer.html for more info */ static int init_done; static int job_queue[2]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int c; h2o_loop_t *loop; h2o_hostconf_t *hostconf; pthread_t twriter; pthread_t tupstream; /* * Perform one-time initialization */ if (!init_done) { const char *client_timeout_ms_str; static char tmpname[] = "/tmp/h2o-fuzz-XXXXXX"; char *dirname; h2o_url_t upstream; signal(SIGPIPE, SIG_IGN); dirname = mkdtemp(tmpname); snprintf(unix_listener, sizeof(unix_listener), "http://[unix://%s/_.sock]/proxy", dirname); if ((client_timeout_ms_str = getenv("H2O_FUZZER_CLIENT_TIMEOUT")) != NULL) client_timeout_ms = atoi(client_timeout_ms_str); if (!client_timeout_ms) client_timeout_ms = 10; /* Create a single h2o host with multiple request handlers */ h2o_config_init(&config); config.http2.idle_timeout = 10 * 1000; config.http1.req_timeout = 10 * 1000; config.proxy.io_timeout = 10 * 1000; h2o_proxy_config_vars_t proxy_config = {}; proxy_config.io_timeout = 10 * 1000; hostconf = h2o_config_register_host(&config, h2o_iovec_init(H2O_STRLIT(unix_listener)), 65535); register_handler(hostconf, "/chunked-test", chunked_test); h2o_url_parse(unix_listener, strlen(unix_listener), &upstream); h2o_socketpool_t *sockpool = new h2o_socketpool_t(); h2o_socketpool_target_t *target = h2o_socketpool_target_create(&upstream, NULL); h2o_socketpool_init_specific(sockpool, SIZE_MAX /* FIXME */, &target, 1, NULL); h2o_socketpool_set_timeout(sockpool, 2000); h2o_socketpool_set_ssl_ctx(sockpool, NULL); h2o_proxy_register_reverse_proxy(h2o_config_register_path(hostconf, "/reproxy-test", 0), &proxy_config, sockpool); h2o_file_register(h2o_config_register_path(hostconf, "/", 0), "./examples/doc_root", NULL, NULL, 0); loop = h2o_evloop_create(); h2o_context_init(&ctx, loop, &config); accept_ctx.ctx = &ctx; accept_ctx.hosts = config.hosts; /* Create a thread to act as the HTTP client */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, job_queue) != 0) { abort(); } if (pthread_create(&twriter, NULL, writer_thread, (void *)(long)job_queue[1]) != 0) { abort(); } if (pthread_create(&tupstream, NULL, upstream_thread, dirname) != 0) { abort(); } init_done = 1; } /* * Pass fuzzed request to client thread and get h2o server socket for * use below */ h2o_barrier_t *end; c = create_accepted(job_queue[0], (char *)Data, (size_t)Size, &end); if (c < 0) { goto Error; } /* Loop until the connection is closed by the client or server */ while (is_valid_fd(c)) { h2o_evloop_run(ctx.loop, 10); } h2o_barrier_wait(end); return 0; Error: return 1; } <commit_msg>fix fuzzer build error<commit_after>/* * Copyright (c) 2016 Fastly, Inc. * * 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. */ /* * This file implements a test harness for using h2o with LibFuzzer. * See http://llvm.org/docs/LibFuzzer.html for more info. */ #define H2O_USE_EPOLL 1 #include <string.h> #include <errno.h> #include <limits.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/select.h> #include <sys/wait.h> #include <unistd.h> #include <fcntl.h> #include "h2o.h" #include "h2o/http1.h" #include "h2o/http2.h" #include "h2o/url.h" #include "h2o/memcached.h" #if !defined(HTTP1) && !defined(HTTP2) #error "Please defined one of HTTP1 or HTTP2" #endif #if defined(HTTP1) && defined(HTTP2) #error "Please defined one of HTTP1 or HTTP2, but not both" #endif static h2o_globalconf_t config; static h2o_context_t ctx; static h2o_accept_ctx_t accept_ctx; static int client_timeout_ms; static char unix_listener[PATH_MAX]; /* * Registers a request handler with h2o */ static h2o_pathconf_t *register_handler(h2o_hostconf_t *hostconf, const char *path, int (*on_req)(h2o_handler_t *, h2o_req_t *)) { h2o_pathconf_t *pathconf = h2o_config_register_path(hostconf, path, 0); h2o_handler_t *handler = h2o_create_handler(pathconf, sizeof(*handler)); handler->on_req = on_req; return pathconf; } /* * Request handler used for testing. Returns a basic "200 OK" response. */ static int chunked_test(h2o_handler_t *self, h2o_req_t *req) { static h2o_generator_t generator = {NULL, NULL}; if (!h2o_memis(req->method.base, req->method.len, H2O_STRLIT("GET"))) return -1; h2o_iovec_t body = h2o_strdup(&req->pool, "hello world\n", SIZE_MAX); req->res.status = 200; req->res.reason = "OK"; h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_CONTENT_TYPE, NULL, H2O_STRLIT("text/plain")); h2o_start_response(req, &generator); h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL); return 0; } /* copy from src to dst, return true if src has EOF */ static int drain(int fd) { char buf[4096]; ssize_t n; n = read(fd, buf, sizeof(buf)); if (n <= 0) { return 1; } return 0; } /* A request sent from client thread to h2o server */ struct writer_thread_arg { char *buf; size_t len; int fd; h2o_barrier_t barrier; }; /* * Reads writer_thread_arg from fd and stores to buf */ static void read_fully(int fd, char *buf, size_t len) { int done = 0; while (len) { int ret; while ((ret = read(fd, buf + done, len)) == -1 && errno == EINTR) ; if (ret <= 0) { abort(); } done += ret; len -= ret; } } /* * Writes the writer_thread_args at buf to fd */ static void write_fully(int fd, char *buf, size_t len, int abort_on_err) { int done = 0; while (len) { int ret; while ((ret = write(fd, buf + done, len)) == -1 && errno == EINTR) ; if (ret <= 0) { if (abort_on_err) abort(); else return; } done += ret; len -= ret; } } #define OK_RESP \ "HTTP/1.0 200 OK\r\n" \ "Connection: Close\r\n\r\nOk" #define OK_RESP_LEN (sizeof(OK_RESP) - 1) void *upstream_thread(void *arg) { char *dirname = (char *)arg; char path[PATH_MAX]; char rbuf[1 * 1024 * 1024]; snprintf(path, sizeof(path), "/%s/_.sock", dirname); int sd = socket(AF_UNIX, SOCK_STREAM, 0); if (sd < 0) { abort(); } struct sockaddr_un addr; memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); if (bind(sd, (struct sockaddr *)&addr, sizeof(addr)) != 0) { abort(); } if (listen(sd, 100) != 0) { abort(); } while (1) { struct sockaddr_un caddr; socklen_t slen = 0; int cfs = accept(sd, (struct sockaddr *)&caddr, &slen); if (cfs < 0) { continue; } read(cfs, rbuf, sizeof(rbuf)); write_fully(cfs, (char *)OK_RESP, OK_RESP_LEN, 0); close(cfs); } } /* * Thread: Loops writing fuzzed req to socket and then reading results back. * Acts as a client to h2o. *arg points to file descripter to read * writer_thread_args from. */ void *writer_thread(void *arg) { int rfd = (long)arg; while (1) { int pos, sockinp, sockoutp, cnt, len; char *buf; struct writer_thread_arg *wta; /* Get fuzzed request */ read_fully(rfd, (char *)&wta, sizeof(wta)); pos = 0; sockinp = wta->fd; sockoutp = wta->fd; cnt = 0; buf = wta->buf; len = wta->len; /* * Send fuzzed req and read results until the socket is closed (or * something spurious happens) */ while (cnt++ < 20 && (pos < len || sockinp >= 0)) { #define MARKER "\n--MARK--\n" /* send 1 packet */ if (pos < len) { char *p = (char *)memmem(buf + pos, len - pos, MARKER, sizeof(MARKER) - 1); if (p) { int l = p - (buf + pos); write(sockoutp, buf + pos, l); pos += l; pos += sizeof(MARKER) - 1; } } else { if (sockinp >= 0) { shutdown(sockinp, SHUT_WR); } } /* drain socket */ if (sockinp >= 0) { struct timeval timeo; fd_set rd; int n; FD_ZERO(&rd); FD_SET(sockinp, &rd); timeo.tv_sec = 0; timeo.tv_usec = client_timeout_ms * 1000; n = select(sockinp + 1, &rd, NULL, NULL, &timeo); if (n > 0 && FD_ISSET(sockinp, &rd) && drain(sockinp)) { sockinp = -1; } } } close(wta->fd); h2o_barrier_wait(&wta->barrier); h2o_barrier_destroy(&wta->barrier); free(wta); } } /* * Creates socket pair and passes fuzzed req to a thread (the HTTP[/2] client) * for writing to the target h2o server. Returns the server socket fd. */ static int feeder(int sfd, char *buf, size_t len, h2o_barrier_t **barrier) { int pair[2]; struct writer_thread_arg *wta; if (socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) return -1; wta = (struct writer_thread_arg *)malloc(sizeof(*wta)); wta->fd = pair[0]; wta->buf = buf; wta->len = len; h2o_barrier_init(&wta->barrier, 2); *barrier = &wta->barrier; write_fully(sfd, (char *)&wta, sizeof(wta), 1); return pair[1]; } /* * Creates/connects socket pair for client/server interaction and passes * fuzzed request to client for sending. * Returns server socket fd. */ static int create_accepted(int sfd, char *buf, size_t len, h2o_barrier_t **barrier) { int fd; h2o_socket_t *sock; struct timeval connected_at = *h2o_get_timestamp(&ctx, NULL, NULL); /* Create an HTTP[/2] client that will send the fuzzed request */ fd = feeder(sfd, buf, len, barrier); if (fd < 0) { abort(); } /* Pass the server socket to h2o and invoke request processing */ sock = h2o_evloop_socket_create(ctx.loop, fd, H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION); #if defined(HTTP1) h2o_http1_accept(&accept_ctx, sock, connected_at); #else h2o_http2_accept(&accept_ctx, sock, connected_at); #endif return fd; } /* * Returns true if fd if valid. Used to determine when connection is closed. */ static int is_valid_fd(int fd) { return fcntl(fd, F_GETFD) != -1 || errno != EBADF; } /* * Entry point for libfuzzer. * See http://llvm.org/docs/LibFuzzer.html for more info */ static int init_done; static int job_queue[2]; extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { int c; h2o_loop_t *loop; h2o_hostconf_t *hostconf; pthread_t twriter; pthread_t tupstream; /* * Perform one-time initialization */ if (!init_done) { const char *client_timeout_ms_str; static char tmpname[] = "/tmp/h2o-fuzz-XXXXXX"; char *dirname; h2o_url_t upstream; signal(SIGPIPE, SIG_IGN); dirname = mkdtemp(tmpname); snprintf(unix_listener, sizeof(unix_listener), "http://[unix://%s/_.sock]/proxy", dirname); if ((client_timeout_ms_str = getenv("H2O_FUZZER_CLIENT_TIMEOUT")) != NULL) client_timeout_ms = atoi(client_timeout_ms_str); if (!client_timeout_ms) client_timeout_ms = 10; /* Create a single h2o host with multiple request handlers */ h2o_config_init(&config); config.http2.idle_timeout = 10 * 1000; config.http1.req_timeout = 10 * 1000; config.proxy.io_timeout = 10 * 1000; h2o_proxy_config_vars_t proxy_config = {}; proxy_config.io_timeout = 10 * 1000; hostconf = h2o_config_register_host(&config, h2o_iovec_init(H2O_STRLIT(unix_listener)), 65535); register_handler(hostconf, "/chunked-test", chunked_test); h2o_url_parse(unix_listener, strlen(unix_listener), &upstream); h2o_socketpool_t *sockpool = new h2o_socketpool_t(); h2o_socketpool_target_t *target = h2o_socketpool_create_target(&upstream, NULL); h2o_socketpool_init_specific(sockpool, SIZE_MAX /* FIXME */, &target, 1, NULL); h2o_socketpool_set_timeout(sockpool, 2000); h2o_socketpool_set_ssl_ctx(sockpool, NULL); h2o_proxy_register_reverse_proxy(h2o_config_register_path(hostconf, "/reproxy-test", 0), &proxy_config, sockpool); h2o_file_register(h2o_config_register_path(hostconf, "/", 0), "./examples/doc_root", NULL, NULL, 0); loop = h2o_evloop_create(); h2o_context_init(&ctx, loop, &config); accept_ctx.ctx = &ctx; accept_ctx.hosts = config.hosts; /* Create a thread to act as the HTTP client */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, job_queue) != 0) { abort(); } if (pthread_create(&twriter, NULL, writer_thread, (void *)(long)job_queue[1]) != 0) { abort(); } if (pthread_create(&tupstream, NULL, upstream_thread, dirname) != 0) { abort(); } init_done = 1; } /* * Pass fuzzed request to client thread and get h2o server socket for * use below */ h2o_barrier_t *end; c = create_accepted(job_queue[0], (char *)Data, (size_t)Size, &end); if (c < 0) { goto Error; } /* Loop until the connection is closed by the client or server */ while (is_valid_fd(c)) { h2o_evloop_run(ctx.loop, 10); } h2o_barrier_wait(end); return 0; Error: return 1; } <|endoftext|>
<commit_before>/* Copyright (c) 2012 Research In Motion Limited. * * 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 "app.hpp" #include <bb/cascades/AbstractPane> #include <bb/cascades/Application> #include <bb/cascades/QmlDocument> #include <bb/data/JsonDataAccess> #include <bb/cascades/ImageView> #include <list> using namespace bb::cascades; //const char* const App::galleryUrl = "http://imgur.com/gallery/"; const char* const App::galleryUrl = "https://api.imgur.com/3/gallery/"; //https://api.imgur.com/3/gallery/hot/viral/0.json //https://api.imgur.com/3/gallery/hot/viral/0.json App::App(QObject *parent) : QObject(parent), m_model(new QListDataModel<QObject*>()), iml(NULL) { // Register custom type to QML qmlRegisterType<AbstractLoader>(); m_model->setParent(this); // Create the UI QmlDocument* qml = QmlDocument::create("asset:///main.qml").parent(this); qml->setContextProperty("_app", this); root = qml->createRootObject<AbstractPane>(); Application::instance()->setScene(root); } void App::loadGallery(QString type, QString page) { m_model->clear(); emit modelChanged(); // Creates the network request and sets the destination URL. const QUrl url(galleryUrl + type + "/viral/page/" + page + ".json"); loadJson(url); } void App::loadJson(QUrl url) { QNetworkRequest request(url); request.setRawHeader("Authorization", ImageLoader::clientId); QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); sslConfig.setPeerVerifyDepth(1); sslConfig.setProtocol(QSsl::TlsV1); sslConfig.setSslOption(QSsl::SslOptionDisableSessionTickets, true); request.setSslConfiguration(sslConfig); // Creates the network access manager and connects a custom slot to its finished signal QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(this); connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(jsonReceived(QNetworkReply*))); // Sends the HTTP request. networkAccessManager->get(request); } void App::loadBigImage(QVariantList indexPath) { this->currentIndex = indexPath; QObject* o = qvariant_cast<QObject*>(m_model->data(indexPath)); AbstractLoader *bigImage = qobject_cast<AbstractLoader*>(o); if (bigImage->type() == 0) { iml = new ImageLoader(bigImage->origImageUrl(), bigImage->origImageUrl(), bigImage->title(), this); connect(iml, SIGNAL(titleChanged()), this, SLOT(displayImage())); iml->load(); } else { // hm, this is not an image, instead something different // -> lets get the next level of json infos QUrl url(bigImage->origImageUrl()); loadJson(url); } } void App::loadNext() { int currentSize = this->currentIndex[0].toInt(); if (currentSize < m_model->size() - 1) { this->currentIndex[0].setValue(currentSize + 1); loadBigImage(this->currentIndex); } } void App::loadImages() { // Call the load() method for each ImageLoader instance inside the model qDebug() << "FMI ######## model size:" << m_model->size(); for (int row = 0; row < m_model->size(); ++row) { qDebug() << "FMI ######## load picture " << row; qobject_cast<AbstractLoader*>(m_model->value(row))->load(); } } bb::cascades::DataModel* App::model() const { return m_model; } /* * Received gallery json file, now parse the data */ void App::jsonReceived(QNetworkReply * reply) { bb::data::JsonDataAccess jda; if (reply->error() == QNetworkReply::NoError) { int available = reply->bytesAvailable(); QString replyString; if (available > 0) { int bufSize = sizeof(char) * available + sizeof(char); QByteArray buffer(bufSize, 0); reply->read(buffer.data(), available); replyString = QString::fromUtf8(buffer); } qDebug() << replyString; QVariantMap jsonva = jda.loadFromBuffer(replyString).toMap(); QVariantList jsonvaList = jsonva.find("data")->toList(); if (jda.hasError()) { bb::data::DataAccessError error = jda.error(); qDebug() << "JSON loading error: " << error.errorType() << ": " << error.errorMessage(); return; } // iterate list int i = 0; for (QList<QVariant>::iterator it = jsonvaList.begin(); (it != jsonvaList.end() && i < 10); it++) { QVariantMap image = it->toMap(); QString title = image["title"].toString(); bool is_album = image["is_album"].toBool(); QString link = image["link"].toString(); QString linkLittle = image["link"].toString().insert(link.length() - 4, "b"); qDebug() << "FMI ######### adding " << link; if (!is_album) { m_model->append(new ImageLoader(linkLittle, link, title, this)); } else { if (image.find("images") != image.end()) { std::list<AlbumPic*> *albumPics = 0; // we are already in an album, not in the gallery QVariantList jsonAlbumList = image.find("images")->toList(); for (QList<QVariant>::iterator ait = jsonAlbumList.begin(); ait != jsonAlbumList.end(); ait++) { QVariantMap albumImage = ait->toMap(); QString description = albumImage["description"].toString(); QString albumPicUrl = albumImage["link"].toString(); albumPics->push_back(new AlbumPic(albumPicUrl, description)); } m_model->append(new AlbumLoader(albumPics, link, link, title, this)); } else { m_model->append(new AlbumLoader(linkLittle, link, title, this)); } } i++; } } else qDebug() << "FMI ######### error: " << reply->errorString(); reply->deleteLater(); loadImages(); } QVariant App::image() const { QVariant result = ""; if (iml) { // check pointer result = iml->image(); } return result; } QString App::imageTitle() const { QString result = ""; if (iml) { // check pointer result = iml->title(); } return result; } QUrl App::imageUrl() const { QUrl result; if (iml) { // check pointer result.setUrl(iml->origImageUrl()); } qDebug() << "FMI ########## ------------ result1:" << result; return result; } int App::type() const { int result; if (iml) { // check pointer result = iml->type(); } qDebug() << "FMI ########## ------------ result2:" << result; return result; } void App::displayImage() { emit imageChanged(); emit imageTitleChanged(); emit imageUrlChanged(); } <commit_msg>working without albums<commit_after>/* Copyright (c) 2012 Research In Motion Limited. * * 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 "app.hpp" #include <bb/cascades/AbstractPane> #include <bb/cascades/Application> #include <bb/cascades/QmlDocument> #include <bb/data/JsonDataAccess> #include <bb/cascades/ImageView> #include <list> using namespace bb::cascades; //const char* const App::galleryUrl = "http://imgur.com/gallery/"; const char* const App::galleryUrl = "https://api.imgur.com/3/gallery/"; //https://api.imgur.com/3/gallery/hot/viral/0.json //https://api.imgur.com/3/gallery/hot/viral/0.json App::App(QObject *parent) : QObject(parent), m_model(new QListDataModel<QObject*>()), iml(NULL) { // Register custom type to QML qmlRegisterType<AbstractLoader>(); m_model->setParent(this); // Create the UI QmlDocument* qml = QmlDocument::create("asset:///main.qml").parent(this); qml->setContextProperty("_app", this); root = qml->createRootObject<AbstractPane>(); Application::instance()->setScene(root); } void App::loadGallery(QString type, QString page) { m_model->clear(); emit modelChanged(); // Creates the network request and sets the destination URL. const QUrl url(galleryUrl + type + "/viral/page/" + page + ".json"); loadJson(url); } void App::loadJson(QUrl url) { QNetworkRequest request(url); request.setRawHeader("Authorization", ImageLoader::clientId); QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); sslConfig.setPeerVerifyDepth(1); sslConfig.setProtocol(QSsl::TlsV1); sslConfig.setSslOption(QSsl::SslOptionDisableSessionTickets, true); request.setSslConfiguration(sslConfig); // Creates the network access manager and connects a custom slot to its finished signal QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(this); connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(jsonReceived(QNetworkReply*))); // Sends the HTTP request. networkAccessManager->get(request); } void App::loadBigImage(QVariantList indexPath) { this->currentIndex = indexPath; QObject* o = qvariant_cast<QObject*>(m_model->data(indexPath)); AbstractLoader *bigImage = qobject_cast<AbstractLoader*>(o); if (bigImage->type() == 0) { iml = new ImageLoader(bigImage->origImageUrl(), bigImage->origImageUrl(), bigImage->title(), this); connect(iml, SIGNAL(titleChanged()), this, SLOT(displayImage())); iml->load(); } // else // { // // hm, this is not an image, instead something different // // -> lets get the next level of json infos // QUrl url(bigImage->origImageUrl()); // loadJson(url); // } } void App::loadNext() { int currentSize = this->currentIndex[0].toInt(); if (currentSize < m_model->size() - 1) { this->currentIndex[0].setValue(currentSize + 1); loadBigImage(this->currentIndex); } } void App::loadImages() { // Call the load() method for each ImageLoader instance inside the model qDebug() << "FMI ######## model size:" << m_model->size(); for (int row = 0; row < m_model->size(); ++row) { qDebug() << "FMI ######## load picture " << row; qobject_cast<AbstractLoader*>(m_model->value(row))->load(); } } bb::cascades::DataModel* App::model() const { return m_model; } /* * Received gallery json file, now parse the data */ void App::jsonReceived(QNetworkReply * reply) { bb::data::JsonDataAccess jda; if (reply->error() == QNetworkReply::NoError) { int available = reply->bytesAvailable(); QString replyString; if (available > 0) { int bufSize = sizeof(char) * available + sizeof(char); QByteArray buffer(bufSize, 0); reply->read(buffer.data(), available); replyString = QString::fromUtf8(buffer); } qDebug() << replyString; QVariantMap jsonva = jda.loadFromBuffer(replyString).toMap(); QVariantList jsonvaList = jsonva.find("data")->toList(); if (jda.hasError()) { bb::data::DataAccessError error = jda.error(); qDebug() << "JSON loading error: " << error.errorType() << ": " << error.errorMessage(); return; } // iterate list int i = 0; for (QList<QVariant>::iterator it = jsonvaList.begin(); (it != jsonvaList.end() && i < 10); it++) { QVariantMap image = it->toMap(); QString title = image["title"].toString(); bool is_album = image["is_album"].toBool(); QString link = image["link"].toString(); QString linkLittle = image["link"].toString().insert(link.length() - 4, "b"); qDebug() << "FMI ######### adding " << link; if (!is_album) { m_model->append(new ImageLoader(linkLittle, link, title, this)); } // else // { // if (image.find("images") != image.end()) // { // std::list<AlbumPic*> *albumPics = 0; // // we are already in an album, not in the gallery // QVariantList jsonAlbumList = image.find("images")->toList(); // for (QList<QVariant>::iterator ait = jsonAlbumList.begin(); ait != jsonAlbumList.end(); ait++) // { // QVariantMap albumImage = ait->toMap(); // // QString description = albumImage["description"].toString(); // QString albumPicUrl = albumImage["link"].toString(); // albumPics->push_back(new AlbumPic(albumPicUrl, description)); // } // m_model->append(new AlbumLoader(albumPics, link, link, title, this)); // } // else // { // m_model->append(new AlbumLoader(linkLittle, link, title, this)); // } // } i++; } } else qDebug() << "FMI ######### error: " << reply->errorString(); reply->deleteLater(); loadImages(); } QVariant App::image() const { QVariant result = ""; if (iml) { // check pointer result = iml->image(); } return result; } QString App::imageTitle() const { QString result = ""; if (iml) { // check pointer result = iml->title(); } return result; } QUrl App::imageUrl() const { QUrl result; if (iml) { // check pointer result.setUrl(iml->origImageUrl()); } qDebug() << "FMI ########## ------------ result1:" << result; return result; } int App::type() const { int result; if (iml) { // check pointer result = iml->type(); } qDebug() << "FMI ########## ------------ result2:" << result; return result; } void App::displayImage() { emit imageChanged(); emit imageTitleChanged(); emit imageUrlChanged(); } <|endoftext|>
<commit_before><commit_msg>Use more useful floating point format in debug output<commit_after><|endoftext|>
<commit_before>// SciTE - Scintilla based Text Editor /** @file GUIGTK.cxx ** Interface to platform GUI facilities. ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla. **/ // Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <time.h> #include <string> #include <gtk/gtk.h> #include "Scintilla.h" #include "ScintillaWidget.h" #include "GUI.h" namespace GUI { gui_string StringFromUTF8(const char *s) { if (s) return gui_string(s); else return gui_string(""); } std::string UTF8FromString(const gui_string &s) { return s; } gui_string StringFromInteger(int i) { char number[32]; sprintf(number, "%0d", i); return gui_string(number); } static GtkWidget *PWidget(WindowID wid) { return reinterpret_cast<GtkWidget *>(wid); } void Window::Destroy() { if (wid) gtk_widget_destroy(GTK_WIDGET(wid)); wid = 0; } bool Window::HasFocus() { return GTK_WIDGET_HAS_FOCUS(wid); } Rectangle Window::GetPosition() { // Before any size allocated pretend its 1000 wide so not scrolled Rectangle rc(0, 0, 1000, 1000); if (wid) { rc.left = PWidget(wid)->allocation.x; rc.top = PWidget(wid)->allocation.y; if (PWidget(wid)->allocation.width > 20) { rc.right = rc.left + PWidget(wid)->allocation.width; rc.bottom = rc.top + PWidget(wid)->allocation.height; } } return rc; } void Window::SetPosition(Rectangle rc) { GtkAllocation alloc; alloc.x = rc.left; alloc.y = rc.top; alloc.width = rc.Width(); alloc.height = rc.Height(); gtk_widget_size_allocate(PWidget(wid), &alloc); } Rectangle Window::GetClientPosition() { // On GTK+, the client position is the window position return GetPosition(); } void Window::Show(bool show) { if (show) gtk_widget_show(PWidget(wid)); } void Window::InvalidateAll() { if (wid) { gtk_widget_queue_draw(PWidget(wid)); } } void Window::SetTitle(const char *s) { gtk_window_set_title(GTK_WINDOW(wid), s); } void Menu::CreatePopUp() { Destroy(); mid = gtk_menu_new(); g_object_ref_sink(G_OBJECT(mid)); } void Menu::Destroy() { if (mid) g_object_unref(mid); mid = 0; } static void MenuPositionFunc(GtkMenu *, gint *x, gint *y, gboolean *, gpointer userData) { sptr_t intFromPointer = reinterpret_cast<sptr_t>(userData); *x = intFromPointer & 0xffff; *y = intFromPointer >> 16; } void Menu::Show(Point pt, Window &) { int screenHeight = gdk_screen_height(); int screenWidth = gdk_screen_width(); GtkMenu *widget = reinterpret_cast<GtkMenu *>(mid); gtk_widget_show_all(GTK_WIDGET(widget)); GtkRequisition requisition; gtk_widget_size_request(GTK_WIDGET(widget), &requisition); if ((pt.x + requisition.width) > screenWidth) { pt.x = screenWidth - requisition.width; } if ((pt.y + requisition.height) > screenHeight) { pt.y = screenHeight - requisition.height; } gtk_menu_popup(widget, NULL, NULL, MenuPositionFunc, reinterpret_cast<void *>((pt.y << 16) | pt.x), 0, gtk_get_current_event_time()); } ElapsedTime::ElapsedTime() { GTimeVal curTime; g_get_current_time(&curTime); bigBit = curTime.tv_sec; littleBit = curTime.tv_usec; } double ElapsedTime::Duration(bool reset) { GTimeVal curTime; g_get_current_time(&curTime); long endBigBit = curTime.tv_sec; long endLittleBit = curTime.tv_usec; double result = 1000000.0 * (endBigBit - bigBit); result += endLittleBit - littleBit; result /= 1000000.0; if (reset) { bigBit = endBigBit; littleBit = endLittleBit; } return result; } sptr_t ScintillaWindow::Send(unsigned int msg, uptr_t wParam, sptr_t lParam) { return scintilla_send_message(SCINTILLA(GetID()), msg, wParam, lParam); } sptr_t ScintillaWindow::SendPointer(unsigned int msg, uptr_t wParam, void *lParam) { return scintilla_send_message(SCINTILLA(GetID()), msg, wParam, reinterpret_cast<sptr_t>(lParam)); } bool IsDBCSLeadByte(int codePage, char ch) { // Byte ranges found in Wikipedia articles with relevant search strings in each case unsigned char uch = static_cast<unsigned char>(ch); switch (codePage) { case 932: // Shift_jis return ((uch >= 0x81) && (uch <= 0x9F)) || ((uch >= 0xE0) && (uch <= 0xEF)); case 936: // GBK return (uch >= 0x81) && (uch <= 0xFE); case 950: // Big5 return (uch >= 0x81) && (uch <= 0xFE); // Korean EUC-KR may be code page 949. } return false; } } <commit_msg>Allow building on GTK+ versions before 2.10.<commit_after>// SciTE - Scintilla based Text Editor /** @file GUIGTK.cxx ** Interface to platform GUI facilities. ** Split off from Scintilla's Platform.h to avoid SciTE depending on implementation of Scintilla. **/ // Copyright 1998-2010 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <time.h> #include <string> #include <gtk/gtk.h> #include "Scintilla.h" #include "ScintillaWidget.h" #include "GUI.h" namespace GUI { gui_string StringFromUTF8(const char *s) { if (s) return gui_string(s); else return gui_string(""); } std::string UTF8FromString(const gui_string &s) { return s; } gui_string StringFromInteger(int i) { char number[32]; sprintf(number, "%0d", i); return gui_string(number); } static GtkWidget *PWidget(WindowID wid) { return reinterpret_cast<GtkWidget *>(wid); } void Window::Destroy() { if (wid) gtk_widget_destroy(GTK_WIDGET(wid)); wid = 0; } bool Window::HasFocus() { return GTK_WIDGET_HAS_FOCUS(wid); } Rectangle Window::GetPosition() { // Before any size allocated pretend its 1000 wide so not scrolled Rectangle rc(0, 0, 1000, 1000); if (wid) { rc.left = PWidget(wid)->allocation.x; rc.top = PWidget(wid)->allocation.y; if (PWidget(wid)->allocation.width > 20) { rc.right = rc.left + PWidget(wid)->allocation.width; rc.bottom = rc.top + PWidget(wid)->allocation.height; } } return rc; } void Window::SetPosition(Rectangle rc) { GtkAllocation alloc; alloc.x = rc.left; alloc.y = rc.top; alloc.width = rc.Width(); alloc.height = rc.Height(); gtk_widget_size_allocate(PWidget(wid), &alloc); } Rectangle Window::GetClientPosition() { // On GTK+, the client position is the window position return GetPosition(); } void Window::Show(bool show) { if (show) gtk_widget_show(PWidget(wid)); } void Window::InvalidateAll() { if (wid) { gtk_widget_queue_draw(PWidget(wid)); } } void Window::SetTitle(const char *s) { gtk_window_set_title(GTK_WINDOW(wid), s); } void Menu::CreatePopUp() { Destroy(); mid = gtk_menu_new(); #if GLIB_CHECK_VERSION(2,10,0) g_object_ref_sink(G_OBJECT(mid)); #else g_object_ref(G_OBJECT(mid)); gtk_object_sink(GTK_OBJECT(G_OBJECT(mid))); #endif } void Menu::Destroy() { if (mid) g_object_unref(mid); mid = 0; } static void MenuPositionFunc(GtkMenu *, gint *x, gint *y, gboolean *, gpointer userData) { sptr_t intFromPointer = reinterpret_cast<sptr_t>(userData); *x = intFromPointer & 0xffff; *y = intFromPointer >> 16; } void Menu::Show(Point pt, Window &) { int screenHeight = gdk_screen_height(); int screenWidth = gdk_screen_width(); GtkMenu *widget = reinterpret_cast<GtkMenu *>(mid); gtk_widget_show_all(GTK_WIDGET(widget)); GtkRequisition requisition; gtk_widget_size_request(GTK_WIDGET(widget), &requisition); if ((pt.x + requisition.width) > screenWidth) { pt.x = screenWidth - requisition.width; } if ((pt.y + requisition.height) > screenHeight) { pt.y = screenHeight - requisition.height; } gtk_menu_popup(widget, NULL, NULL, MenuPositionFunc, reinterpret_cast<void *>((pt.y << 16) | pt.x), 0, gtk_get_current_event_time()); } ElapsedTime::ElapsedTime() { GTimeVal curTime; g_get_current_time(&curTime); bigBit = curTime.tv_sec; littleBit = curTime.tv_usec; } double ElapsedTime::Duration(bool reset) { GTimeVal curTime; g_get_current_time(&curTime); long endBigBit = curTime.tv_sec; long endLittleBit = curTime.tv_usec; double result = 1000000.0 * (endBigBit - bigBit); result += endLittleBit - littleBit; result /= 1000000.0; if (reset) { bigBit = endBigBit; littleBit = endLittleBit; } return result; } sptr_t ScintillaWindow::Send(unsigned int msg, uptr_t wParam, sptr_t lParam) { return scintilla_send_message(SCINTILLA(GetID()), msg, wParam, lParam); } sptr_t ScintillaWindow::SendPointer(unsigned int msg, uptr_t wParam, void *lParam) { return scintilla_send_message(SCINTILLA(GetID()), msg, wParam, reinterpret_cast<sptr_t>(lParam)); } bool IsDBCSLeadByte(int codePage, char ch) { // Byte ranges found in Wikipedia articles with relevant search strings in each case unsigned char uch = static_cast<unsigned char>(ch); switch (codePage) { case 932: // Shift_jis return ((uch >= 0x81) && (uch <= 0x9F)) || ((uch >= 0xE0) && (uch <= 0xEF)); case 936: // GBK return (uch >= 0x81) && (uch <= 0xFE); case 950: // Big5 return (uch >= 0x81) && (uch <= 0xFE); // Korean EUC-KR may be code page 949. } return false; } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(SOLARISDEFINITIONS_HEADER_GUARD_1357924680) #define SOLARISDEFINITIONS_HEADER_GUARD_1357924680 // --------------------------------------------------------------------------- // A define in the build for each project is also used to control whether // the export keyword is from the project's viewpoint or the client's. // These defines provide the platform specific keywords that they need // to do this. // --------------------------------------------------------------------------- #define XALAN_PLATFORM_EXPORT #define XALAN_PLATFORM_IMPORT #define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT #define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT #if __SUNPRO_CC_COMPAT >= 5 #define XALAN_SIZE_T_IN_NAMESPACE_STD #define XALAN_SIGNAL_IN_STD // Standard allocators don't seem to work correctly with this compiler. // I don't know if this is their bug, or ours... #define XALAN_NO_STD_ALLOCATORS #else // Sun Workshop 4.2 _does_ support new cast syntax, but it's // broken with extra cv-qualifiers, so we'll use old-style casts. #define XALAN_OLD_STYLE_CASTS // Standard allocators don't seem to work correctly with STLport. // I don't know if this is their bug, or ours... #define XALAN_NO_STD_ALLOCATORS #define XALAN_STLPORT_STL #define XALAN_NO_DEFAULT_BUILTIN_ARRAY_INITIALIZATION #define XALAN_OLD_STREAMS #define XALAN_NO_NAMESPACES #define XALAN_NO_MUTABLE #define XALAN_SGI_BASED_STL #define XALAN_NO_MEMBER_TEMPLATES #define XALAN_BOOL_AS_INT #define XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS #define XALAN_NO_COVARIANT_RETURN_TYPE // STL Port Definitions #define __STL_NO_SGI_IOSTREAMS #define _REENTRANT #include <stl/_config.h> #endif #define XALAN_NO_STD_NUMERIC_LIMITS #define XALAN_XALANDOMCHAR_USHORT_MISMATCH #define XALAN_POSIX2_AVAILABLE #define XALAN_UNALIGNED #endif // SOLARISDEFINITIONS_HEADER_GUARD_1357924680 <commit_msg>Use a different macro to control compilation. Fixes problem with earlier versions of the compiler which don't support certain language features.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2002 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(SOLARISDEFINITIONS_HEADER_GUARD_1357924680) #define SOLARISDEFINITIONS_HEADER_GUARD_1357924680 // --------------------------------------------------------------------------- // A define in the build for each project is also used to control whether // the export keyword is from the project's viewpoint or the client's. // These defines provide the platform specific keywords that they need // to do this. // --------------------------------------------------------------------------- #define XALAN_PLATFORM_EXPORT #define XALAN_PLATFORM_IMPORT #define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT #define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT #if __SUNPRO_CC >= 0x530 #define XALAN_SIZE_T_IN_NAMESPACE_STD #define XALAN_SIGNAL_IN_STD // Standard allocators don't seem to work correctly with this compiler. // I don't know if this is their bug, or ours... #define XALAN_NO_STD_ALLOCATORS #else // Sun Workshop 4.2 _does_ support new cast syntax, but it's // broken with extra cv-qualifiers, so we'll use old-style casts. #define XALAN_OLD_STYLE_CASTS // Standard allocators don't seem to work correctly with STLport. // I don't know if this is their bug, or ours... #define XALAN_NO_STD_ALLOCATORS #define XALAN_STLPORT_STL #define XALAN_NO_DEFAULT_BUILTIN_ARRAY_INITIALIZATION #define XALAN_OLD_STREAMS #define XALAN_NO_NAMESPACES #define XALAN_NO_MUTABLE #define XALAN_SGI_BASED_STL #define XALAN_NO_MEMBER_TEMPLATES #define XALAN_BOOL_AS_INT #define XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS #define XALAN_NO_COVARIANT_RETURN_TYPE // STL Port Definitions #define __STL_NO_SGI_IOSTREAMS #define _REENTRANT #include <stl/_config.h> #endif #define XALAN_NO_STD_NUMERIC_LIMITS #define XALAN_XALANDOMCHAR_USHORT_MISMATCH #define XALAN_POSIX2_AVAILABLE #define XALAN_UNALIGNED #endif // SOLARISDEFINITIONS_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>// Copyright 2013 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 "chrome/browser/chromeos/input_method/component_extension_ime_manager_impl.h" #include "base/logging.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_manifest_constants.h" #include "content/public/browser/browser_thread.h" namespace chromeos { namespace { struct WhitelistedComponentExtensionIME { const char* id; const char* path; } whitelisted_component_extension[] = { { "fpfbhcjppmaeaijcidgiibchfbnhbelj", "/usr/share/chromeos-assets/input_methods/nacl_mozc", }, }; extensions::ComponentLoader* GetComponentLoader() { Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord(); extensions::ExtensionSystem* extension_system = extensions::ExtensionSystem::Get(profile); ExtensionService* extension_service = extension_system->extension_service(); return extension_service->component_loader(); } } // namespace ComponentExtensionIMEManagerImpl::ComponentExtensionIMEManagerImpl() : is_initialized_(false), weak_ptr_factory_(this) { } ComponentExtensionIMEManagerImpl::~ComponentExtensionIMEManagerImpl() { } std::vector<ComponentExtensionIME> ComponentExtensionIMEManagerImpl::ListIME() { DCHECK(thread_checker_.CalledOnValidThread()); return component_extension_list_; } bool ComponentExtensionIMEManagerImpl::Load(const std::string& extension_id, const base::FilePath& file_path) { DCHECK(thread_checker_.CalledOnValidThread()); if (loaded_extension_id_.find(extension_id) != loaded_extension_id_.end()) return false; const std::string loaded_extension_id = GetComponentLoader()->AddOrReplace(file_path); DCHECK_EQ(loaded_extension_id, extension_id); loaded_extension_id_.insert(extension_id); return true; } bool ComponentExtensionIMEManagerImpl::Unload(const std::string& extension_id, const base::FilePath& file_path) { DCHECK(thread_checker_.CalledOnValidThread()); if (loaded_extension_id_.find(extension_id) == loaded_extension_id_.end()) return false; GetComponentLoader()->Remove(extension_id); loaded_extension_id_.erase(extension_id); return true; } scoped_ptr<DictionaryValue> ComponentExtensionIMEManagerImpl::GetManifest( const base::FilePath& file_path) { std::string error; scoped_ptr<DictionaryValue> manifest( extension_file_util::LoadManifest(file_path, &error)); if (!manifest.get()) LOG(ERROR) << "Failed at getting manifest"; if (!extension_l10n_util::LocalizeExtension(file_path, manifest.get(), &error)) LOG(ERROR) << "Localization failed"; return manifest.Pass(); } void ComponentExtensionIMEManagerImpl::Initialize( const scoped_refptr<base::SequencedTaskRunner>& file_task_runner, const base::Closure& callback) { DCHECK(!is_initialized_); std::vector<ComponentExtensionIME>* component_extension_ime_list = new std::vector<ComponentExtensionIME>; file_task_runner->PostTaskAndReply( FROM_HERE, base::Bind(&ComponentExtensionIMEManagerImpl::ReadComponentExtensionsInfo, base::Unretained(component_extension_ime_list)), base::Bind( &ComponentExtensionIMEManagerImpl::OnReadComponentExtensionsInfo, weak_ptr_factory_.GetWeakPtr(), base::Owned(component_extension_ime_list), callback)); } bool ComponentExtensionIMEManagerImpl::IsInitialized() { return is_initialized_; } // static bool ComponentExtensionIMEManagerImpl::ReadEngineComponent( const DictionaryValue& dict, IBusComponent::EngineDescription* out) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); DCHECK(out); std::string type; if (!dict.GetString(extension_manifest_keys::kType, &type)) return false; if (type != "ime") return false; if (!dict.GetString(extension_manifest_keys::kId, &out->engine_id)) return false; if (!dict.GetString(extension_manifest_keys::kName, &out->display_name)) return false; if (!dict.GetString(extension_manifest_keys::kLanguage, &out->language_code)) return false; const ListValue* layouts = NULL; if (!dict.GetList(extension_manifest_keys::kLayouts, &layouts)) return false; if (layouts->GetSize() > 0) { if (!layouts->GetString(0, &out->layout)) return false; } return true; } // static bool ComponentExtensionIMEManagerImpl::ReadExtensionInfo( const DictionaryValue& manifest, ComponentExtensionIME* out) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); if (!manifest.GetString(extension_manifest_keys::kDescription, &out->description)) return false; // TODO(nona): option page handling. return true; } // static void ComponentExtensionIMEManagerImpl::ReadComponentExtensionsInfo( std::vector<ComponentExtensionIME>* out_imes) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); DCHECK(out_imes); for (size_t i = 0; i < arraysize(whitelisted_component_extension); ++i) { const base::FilePath extension_path = base::FilePath( whitelisted_component_extension[i].path); scoped_ptr<DictionaryValue> manifest = GetManifest(extension_path); if (!manifest.get()) continue; ComponentExtensionIME component_ime; if (!ReadExtensionInfo(*manifest.get(), &component_ime)) continue; const ListValue* component_list; if (!manifest->GetList(extension_manifest_keys::kInputComponents, &component_list)) continue; for (size_t i = 0; i < component_list->GetSize(); ++i) { const DictionaryValue* dictionary; if (!component_list->GetDictionary(i, &dictionary)) continue; IBusComponent::EngineDescription engine; ReadEngineComponent(*dictionary, &engine); component_ime.engines.push_back(engine); } out_imes->push_back(component_ime); } } void ComponentExtensionIMEManagerImpl::OnReadComponentExtensionsInfo( std::vector<ComponentExtensionIME>* result, const base::Closure& callback) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(result); component_extension_list_ = *result; is_initialized_ = true; callback.Run(); } } // namespace chromeos <commit_msg>Avoid crash when the component extension is not exists.<commit_after>// Copyright 2013 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 "chrome/browser/chromeos/input_method/component_extension_ime_manager_impl.h" #include "base/file_util.h" #include "base/logging.h" #include "chrome/browser/extensions/component_loader.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_manifest_constants.h" #include "content/public/browser/browser_thread.h" namespace chromeos { namespace { struct WhitelistedComponentExtensionIME { const char* id; const char* path; } whitelisted_component_extension[] = { { "fpfbhcjppmaeaijcidgiibchfbnhbelj", "/usr/share/chromeos-assets/input_methods/nacl_mozc", }, }; extensions::ComponentLoader* GetComponentLoader() { Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord(); extensions::ExtensionSystem* extension_system = extensions::ExtensionSystem::Get(profile); ExtensionService* extension_service = extension_system->extension_service(); return extension_service->component_loader(); } } // namespace ComponentExtensionIMEManagerImpl::ComponentExtensionIMEManagerImpl() : is_initialized_(false), weak_ptr_factory_(this) { } ComponentExtensionIMEManagerImpl::~ComponentExtensionIMEManagerImpl() { } std::vector<ComponentExtensionIME> ComponentExtensionIMEManagerImpl::ListIME() { DCHECK(thread_checker_.CalledOnValidThread()); return component_extension_list_; } bool ComponentExtensionIMEManagerImpl::Load(const std::string& extension_id, const base::FilePath& file_path) { DCHECK(thread_checker_.CalledOnValidThread()); if (loaded_extension_id_.find(extension_id) != loaded_extension_id_.end()) return false; const std::string loaded_extension_id = GetComponentLoader()->AddOrReplace(file_path); DCHECK_EQ(loaded_extension_id, extension_id); loaded_extension_id_.insert(extension_id); return true; } bool ComponentExtensionIMEManagerImpl::Unload(const std::string& extension_id, const base::FilePath& file_path) { DCHECK(thread_checker_.CalledOnValidThread()); if (loaded_extension_id_.find(extension_id) == loaded_extension_id_.end()) return false; GetComponentLoader()->Remove(extension_id); loaded_extension_id_.erase(extension_id); return true; } scoped_ptr<DictionaryValue> ComponentExtensionIMEManagerImpl::GetManifest( const base::FilePath& file_path) { std::string error; scoped_ptr<DictionaryValue> manifest( extension_file_util::LoadManifest(file_path, &error)); if (!manifest.get()) LOG(ERROR) << "Failed at getting manifest"; if (!extension_l10n_util::LocalizeExtension(file_path, manifest.get(), &error)) LOG(ERROR) << "Localization failed"; return manifest.Pass(); } void ComponentExtensionIMEManagerImpl::Initialize( const scoped_refptr<base::SequencedTaskRunner>& file_task_runner, const base::Closure& callback) { DCHECK(!is_initialized_); std::vector<ComponentExtensionIME>* component_extension_ime_list = new std::vector<ComponentExtensionIME>; file_task_runner->PostTaskAndReply( FROM_HERE, base::Bind(&ComponentExtensionIMEManagerImpl::ReadComponentExtensionsInfo, base::Unretained(component_extension_ime_list)), base::Bind( &ComponentExtensionIMEManagerImpl::OnReadComponentExtensionsInfo, weak_ptr_factory_.GetWeakPtr(), base::Owned(component_extension_ime_list), callback)); } bool ComponentExtensionIMEManagerImpl::IsInitialized() { return is_initialized_; } // static bool ComponentExtensionIMEManagerImpl::ReadEngineComponent( const DictionaryValue& dict, IBusComponent::EngineDescription* out) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); DCHECK(out); std::string type; if (!dict.GetString(extension_manifest_keys::kType, &type)) return false; if (type != "ime") return false; if (!dict.GetString(extension_manifest_keys::kId, &out->engine_id)) return false; if (!dict.GetString(extension_manifest_keys::kName, &out->display_name)) return false; if (!dict.GetString(extension_manifest_keys::kLanguage, &out->language_code)) return false; const ListValue* layouts = NULL; if (!dict.GetList(extension_manifest_keys::kLayouts, &layouts)) return false; if (layouts->GetSize() > 0) { if (!layouts->GetString(0, &out->layout)) return false; } return true; } // static bool ComponentExtensionIMEManagerImpl::ReadExtensionInfo( const DictionaryValue& manifest, ComponentExtensionIME* out) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); if (!manifest.GetString(extension_manifest_keys::kDescription, &out->description)) return false; // TODO(nona): option page handling. return true; } // static void ComponentExtensionIMEManagerImpl::ReadComponentExtensionsInfo( std::vector<ComponentExtensionIME>* out_imes) { DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE)); DCHECK(out_imes); for (size_t i = 0; i < arraysize(whitelisted_component_extension); ++i) { const base::FilePath extension_path = base::FilePath( whitelisted_component_extension[i].path); if (!file_util::PathExists(extension_path)) continue; scoped_ptr<DictionaryValue> manifest = GetManifest(extension_path); if (!manifest.get()) continue; ComponentExtensionIME component_ime; if (!ReadExtensionInfo(*manifest.get(), &component_ime)) continue; const ListValue* component_list; if (!manifest->GetList(extension_manifest_keys::kInputComponents, &component_list)) continue; for (size_t i = 0; i < component_list->GetSize(); ++i) { const DictionaryValue* dictionary; if (!component_list->GetDictionary(i, &dictionary)) continue; IBusComponent::EngineDescription engine; ReadEngineComponent(*dictionary, &engine); component_ime.engines.push_back(engine); } out_imes->push_back(component_ime); } } void ComponentExtensionIMEManagerImpl::OnReadComponentExtensionsInfo( std::vector<ComponentExtensionIME>* result, const base::Closure& callback) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(result); component_extension_list_ = *result; is_initialized_ = true; callback.Run(); } } // namespace chromeos <|endoftext|>
<commit_before>#include <ossim/elevation/ossimDtedElevationDatabase.h> #include <ossim/base/ossimDirectory.h> #include <ossim/base/ossimGeoidManager.h> #include <ossim/base/ossimNotify.h> #include <ossim/base/ossimPreferences.h> #include <ossim/base/ossimTrace.h> #include <sstream> #include <iomanip> #include <cstdlib> /* for abs(int) */ static ossimTrace traceDebug("ossimDtedElevationDatabase:debug"); RTTI_DEF1(ossimDtedElevationDatabase, "ossimDtedElevationDatabase", ossimElevationCellDatabase); ossimDtedElevationDatabase::ossimDtedElevationDatabase() : ossimElevationCellDatabase(), m_extension(""), m_upcase(false), m_lastHandler(0), m_mutex() { } ossimDtedElevationDatabase::ossimDtedElevationDatabase(const ossimDtedElevationDatabase& rhs) : ossimElevationCellDatabase(rhs), m_extension(rhs.m_extension), m_upcase(rhs.m_upcase), m_lastHandler(0), // Do not copy this to get a unique handler for thread. m_mutex() { } ossimDtedElevationDatabase::~ossimDtedElevationDatabase() { } ossimObject* ossimDtedElevationDatabase::dup() const { ossimDtedElevationDatabase* duped = new ossimDtedElevationDatabase(*this); return duped; } double ossimDtedElevationDatabase::getHeightAboveMSL(const ossimGpt& gpt) { if(!isSourceEnabled()) return ossim::nan(); std::lock_guard<std::mutex> lock(m_mutex); double result = ossim::nan(); if(m_lastHandler.valid() && m_lastHandler->pointHasCoverage(gpt)) { result = m_lastHandler->getHeightAboveMSL(gpt); } else { m_lastHandler = getOrCreateCellHandler(gpt); if(m_lastHandler.valid()) result = m_lastHandler->getHeightAboveMSL(gpt); } return result; } double ossimDtedElevationDatabase::getHeightAboveEllipsoid(const ossimGpt& gpt) { double h = getHeightAboveMSL(gpt); if(h != ossim::nan()) { double offset = getOffsetFromEllipsoid(gpt); h += offset; } return h; } bool ossimDtedElevationDatabase::open(const ossimString& connectionString) { bool result = false; ossimFilename file = ossimFilename(connectionString); result = openDtedDirectory(file); return result; } bool ossimDtedElevationDatabase::openDtedDirectory(const ossimFilename& dir) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open entered ...\n" << "dir: " << dir << "\n"; } bool result = dir.isDir(); if(result) { if ( m_extension.size() == 0 ) { //--- // This sets extension by doing a directory scan and is now depricated. // Use "extension" key in preferences to avoid this. Example: // elevation_manager.elevation_source0.extension: dt2 //--- result = inititializeExtension( dir ); if ( !result && traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open: WARNING " << "Scan for dted extension failed!\n" << "Can be set in ossim preferences. Example:\n" << "elevation_manager.elevation_source0.extension: .dt2\n"; } } // Set the geoid: if( !m_geoid.valid() ) { m_geoid = ossimGeoidManager::instance()->findGeoidByShortName("geoid1996", false); if(!m_geoid.valid()&&traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open: WARNING " << "Unable to load goeid grid 1996 for DTED database\n"; } } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open result:" << (result?"true":"false") << "\n"; } return result; } bool ossimDtedElevationDatabase::getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const { bool result = false; m_mutex.lock(); ossimDtedElevationDatabase* thisPtr = const_cast<ossimDtedElevationDatabase*>(this); ossimRefPtr<ossimElevCellHandler> tempHandler = thisPtr->getOrCreateCellHandler(gpt); m_mutex.unlock(); if(tempHandler.valid()) { result = tempHandler->getAccuracyInfo(info, gpt); } return result; } void ossimDtedElevationDatabase::createRelativePath(ossimFilename& file, const ossimGpt& gpt)const { ossimFilename lon, lat; int ilon = static_cast<int>(floor(gpt.lond())); if (ilon < 0) { lon = m_upcase?"W":"w"; } else { lon = m_upcase?"E":"e"; } ilon = abs(ilon); std::ostringstream s1; s1 << std::setfill('0') << std::setw(3)<< ilon; lon += s1.str().c_str();//ossimString::toString(ilon); int ilat = static_cast<int>(floor(gpt.latd())); if (ilat < 0) { lat += m_upcase?"S":"s"; } else { lat += m_upcase?"N":"n"; } ilat = abs(ilat); std::ostringstream s2; s2<< std::setfill('0') << std::setw(2)<< ilat; lat += s2.str().c_str(); file = lon.dirCat(lat+m_extension); } ossimRefPtr<ossimElevCellHandler> ossimDtedElevationDatabase::createCell(const ossimGpt& gpt) { ossimRefPtr<ossimElevCellHandler> result = 0; ossimFilename f; createFullPath(f, gpt); if(f.exists()) { ossimRefPtr<ossimDtedHandler> h = new ossimDtedHandler(f, m_memoryMapCellsFlag); if (!(h->getErrorStatus())) { result = h.get(); } } return result; } bool ossimDtedElevationDatabase::loadState(const ossimKeywordlist& kwl, const char* prefix ) { bool result = ossimElevationCellDatabase::loadState(kwl, prefix); if(result) { if(!m_connectionString.empty()&&ossimFilename(m_connectionString).exists()) { // Look for "extension" keyword. std::string pref = (prefix?prefix:""); std::string key = "extension"; ossimString val = ossimPreferences::instance()->preferencesKWL().findKey( pref, key ); if ( val.size() ) { if ( val.string()[0] != '.' ) { m_extension = "."; m_extension += val; ossimNotify(ossimNotifyLevel_WARN) << "\nossimDtedElevationDatabase::loadState: WARNING\n" << "Key value for \"extension\" does not start with a dot!\n" << "Consider changing \"" << val << "\" to \"" << m_extension << "\"\n" << std::endl; } else { m_extension = val; } } else if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimDtedElevationDatabase::loadState: NOTICE\n" << "Key lookup for \"extension\" failed!\n" << "Can be set in ossim preferences. Example:\n" << pref << key << ": .dt2\n\n"; } key = "upcase"; val = ossimPreferences::instance()->preferencesKWL().findKey( pref, key ); if ( val.size() ) { m_upcase = val.toBool(); } else if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimDtedElevationDatabase::loadState: NOTICE\n" << "Key lookup for \"upcase\" failed!\n" << "Can be set in ossim preferences. Example:\n" << pref << key << ": false\n\n"; } result = open(m_connectionString); } else { // can't open the connection because it does not exists or empty result = false; } } return result; } bool ossimDtedElevationDatabase::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "extension", m_extension, true); kwl.add(prefix, "upcase", m_upcase, true); bool result = ossimElevationCellDatabase::saveState(kwl, prefix); return result; } std::ostream& ossimDtedElevationDatabase::print(ostream& out) const { ossimKeywordlist kwl; saveState(kwl); out << "\nossimDtedElevationDatabase @ "<< (ossim_uint64) this << "\n" << kwl <<ends; return out; } bool ossimDtedElevationDatabase::inititializeExtension( const ossimFilename& dir ) { ossim_uint32 count = 0; ossim_uint32 maxCount = 10; ossimDirectory od; bool result = od.open(dir); if(result) { result = false; ossimFilename f; // Get the first directory. od.getFirst(f, ossimDirectory::OSSIM_DIR_DIRS); do { ++count; // Must be a directory. if (f.isDir()) { // Discard any full path. ossimFilename fileOnly = f.file(); // Downcase it. Note have sites with upper case. (drb) // fileOnly.downcase(); //--- // Longitude subdir check: // Must start with 'e', 'E', 'w' or 'W'. //--- bool foundCell = ( ( (fileOnly.c_str()[0] == 'e') || (fileOnly.c_str()[0] == 'w') || (fileOnly.c_str()[0] == 'E') || (fileOnly.c_str()[0] == 'W') ) && (fileOnly.size() == 4)); if(foundCell) { ossim_uint32 maxCount2 = 10; ossim_uint32 count2 = 0; ossimDirectory d2; // Open the longitude subdir: if(d2.open(f)) { d2.getFirst(f, ossimDirectory::OSSIM_DIR_FILES); do { // The DTED directory may be polluted with cell statistics files and other // non-DEM items. Skip if not of the expected extension (OLK 10/2017): if (f.ext().match("[dD][tT][0-2]").empty()) continue; ossimRefPtr<ossimDtedHandler> dtedHandler = new ossimDtedHandler(); if(dtedHandler->open(f, false)) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open: Found dted file " << f << "\n"; } result = true; m_extension = "."+f.ext(); m_connectionString = dir; m_meanSpacing = dtedHandler->getMeanSpacingMeters(); } dtedHandler->close(); dtedHandler = 0; ++count2; } while(!result&&d2.getNext(f)&&(count2 < maxCount2)); } } } } while(!result&&(od.getNext(f))&&(count < maxCount)); } return result; } // End: ossimDtedElevationDatabase::inititializeExtension( dir ) <commit_msg>Added comments<commit_after>#include <ossim/elevation/ossimDtedElevationDatabase.h> #include <ossim/base/ossimDirectory.h> #include <ossim/base/ossimGeoidManager.h> #include <ossim/base/ossimNotify.h> #include <ossim/base/ossimPreferences.h> #include <ossim/base/ossimTrace.h> #include <sstream> #include <iomanip> #include <cstdlib> /* for abs(int) */ static ossimTrace traceDebug("ossimDtedElevationDatabase:debug"); RTTI_DEF1(ossimDtedElevationDatabase, "ossimDtedElevationDatabase", ossimElevationCellDatabase); ossimDtedElevationDatabase::ossimDtedElevationDatabase() : ossimElevationCellDatabase(), m_extension(""), m_upcase(false), m_lastHandler(0), m_mutex() { } ossimDtedElevationDatabase::ossimDtedElevationDatabase(const ossimDtedElevationDatabase& rhs) : ossimElevationCellDatabase(rhs), m_extension(rhs.m_extension), m_upcase(rhs.m_upcase), m_lastHandler(0), // Do not copy this to get a unique handler for thread. m_mutex() { } ossimDtedElevationDatabase::~ossimDtedElevationDatabase() { } ossimObject* ossimDtedElevationDatabase::dup() const { ossimDtedElevationDatabase* duped = new ossimDtedElevationDatabase(*this); return duped; } double ossimDtedElevationDatabase::getHeightAboveMSL(const ossimGpt& gpt) { if(!isSourceEnabled()) return ossim::nan(); std::lock_guard<std::mutex> lock(m_mutex); double result = ossim::nan(); if(m_lastHandler.valid() && m_lastHandler->pointHasCoverage(gpt)) { result = m_lastHandler->getHeightAboveMSL(gpt); } else { m_lastHandler = getOrCreateCellHandler(gpt); if(m_lastHandler.valid()) result = m_lastHandler->getHeightAboveMSL(gpt); } return result; } double ossimDtedElevationDatabase::getHeightAboveEllipsoid(const ossimGpt& gpt) { double h = getHeightAboveMSL(gpt); if(h != ossim::nan()) { double offset = getOffsetFromEllipsoid(gpt); h += offset; } return h; } bool ossimDtedElevationDatabase::open(const ossimString& connectionString) { bool result = false; ossimFilename file = ossimFilename(connectionString); result = openDtedDirectory(file); return result; } bool ossimDtedElevationDatabase::openDtedDirectory(const ossimFilename& dir) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open entered ...\n" << "dir: " << dir << "\n"; } bool result = dir.isDir(); if(result) { if ( m_extension.size() == 0 ) { //--- // This sets extension by doing a directory scan for files with "dt*". // Use "extension" key in preferences to avoid this. Example: // elevation_manager.elevation_source0.extension: dt2. //--- result = inititializeExtension( dir ); if ( !result && traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open: WARNING " << "Scan for dted extension failed!\n" << "Can be set in ossim preferences. Example:\n" << "elevation_manager.elevation_source0.extension: .dt2\n"; } } // Set the geoid: if( !m_geoid.valid() ) { m_geoid = ossimGeoidManager::instance()->findGeoidByShortName("geoid1996", false); if(!m_geoid.valid()&&traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open: WARNING " << "Unable to load goeid grid 1996 for DTED database\n"; } } } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open result:" << (result?"true":"false") << "\n"; } return result; } bool ossimDtedElevationDatabase::getAccuracyInfo(ossimElevationAccuracyInfo& info, const ossimGpt& gpt) const { bool result = false; m_mutex.lock(); ossimDtedElevationDatabase* thisPtr = const_cast<ossimDtedElevationDatabase*>(this); ossimRefPtr<ossimElevCellHandler> tempHandler = thisPtr->getOrCreateCellHandler(gpt); m_mutex.unlock(); if(tempHandler.valid()) { result = tempHandler->getAccuracyInfo(info, gpt); } return result; } void ossimDtedElevationDatabase::createRelativePath(ossimFilename& file, const ossimGpt& gpt)const { ossimFilename lon, lat; int ilon = static_cast<int>(floor(gpt.lond())); if (ilon < 0) { lon = m_upcase?"W":"w"; } else { lon = m_upcase?"E":"e"; } ilon = abs(ilon); std::ostringstream s1; s1 << std::setfill('0') << std::setw(3)<< ilon; lon += s1.str().c_str();//ossimString::toString(ilon); int ilat = static_cast<int>(floor(gpt.latd())); if (ilat < 0) { lat += m_upcase?"S":"s"; } else { lat += m_upcase?"N":"n"; } ilat = abs(ilat); std::ostringstream s2; s2<< std::setfill('0') << std::setw(2)<< ilat; lat += s2.str().c_str(); file = lon.dirCat(lat+m_extension); } ossimRefPtr<ossimElevCellHandler> ossimDtedElevationDatabase::createCell(const ossimGpt& gpt) { ossimRefPtr<ossimElevCellHandler> result = 0; ossimFilename f; createFullPath(f, gpt); if(f.exists()) { ossimRefPtr<ossimDtedHandler> h = new ossimDtedHandler(f, m_memoryMapCellsFlag); if (!(h->getErrorStatus())) { result = h.get(); } } return result; } bool ossimDtedElevationDatabase::loadState(const ossimKeywordlist& kwl, const char* prefix ) { bool result = ossimElevationCellDatabase::loadState(kwl, prefix); if(result) { if(!m_connectionString.empty()&&ossimFilename(m_connectionString).exists()) { // Look for "extension" keyword. std::string pref = (prefix?prefix:""); std::string key = "extension"; ossimString val = ossimPreferences::instance()->preferencesKWL().findKey( pref, key ); if ( val.size() ) { if ( val.string()[0] != '.' ) { m_extension = "."; m_extension += val; ossimNotify(ossimNotifyLevel_WARN) << "\nossimDtedElevationDatabase::loadState: WARNING\n" << "Key value for \"extension\" does not start with a dot!\n" << "Consider changing \"" << val << "\" to \"" << m_extension << "\"\n" << std::endl; } else { m_extension = val; } } else if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimDtedElevationDatabase::loadState: NOTICE\n" << "Key lookup for \"extension\" failed!\n" << "Can be set in ossim preferences. Example:\n" << pref << key << ": .dt2\n\n"; } key = "upcase"; val = ossimPreferences::instance()->preferencesKWL().findKey( pref, key ); if ( val.size() ) { m_upcase = val.toBool(); } else if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_DEBUG) << "\nossimDtedElevationDatabase::loadState: NOTICE\n" << "Key lookup for \"upcase\" failed!\n" << "Can be set in ossim preferences. Example:\n" << pref << key << ": false\n\n"; } result = open(m_connectionString); } else { // can't open the connection because it does not exists or empty result = false; } } return result; } bool ossimDtedElevationDatabase::saveState(ossimKeywordlist& kwl, const char* prefix)const { kwl.add(prefix, "extension", m_extension, true); kwl.add(prefix, "upcase", m_upcase, true); bool result = ossimElevationCellDatabase::saveState(kwl, prefix); return result; } std::ostream& ossimDtedElevationDatabase::print(ostream& out) const { ossimKeywordlist kwl; saveState(kwl); out << "\nossimDtedElevationDatabase @ "<< (ossim_uint64) this << "\n" << kwl <<ends; return out; } bool ossimDtedElevationDatabase::inititializeExtension( const ossimFilename& dir ) { ossim_uint32 count = 0; ossim_uint32 maxCount = 10; ossimDirectory od; bool result = od.open(dir); if(result) { result = false; ossimFilename f; // Get the first directory. od.getFirst(f, ossimDirectory::OSSIM_DIR_DIRS); do { ++count; // Must be a directory. if (f.isDir()) { // Discard any full path. ossimFilename fileOnly = f.file(); // Downcase it. Note have sites with upper case. (drb) // fileOnly.downcase(); //--- // Longitude subdir check: // Must start with 'e', 'E', 'w' or 'W'. //--- bool foundCell = ( ( (fileOnly.c_str()[0] == 'e') || (fileOnly.c_str()[0] == 'w') || (fileOnly.c_str()[0] == 'E') || (fileOnly.c_str()[0] == 'W') ) && (fileOnly.size() == 4)); if(foundCell) { ossim_uint32 maxCount2 = 10; ossim_uint32 count2 = 0; ossimDirectory d2; // Open the longitude subdir: if(d2.open(f)) { d2.getFirst(f, ossimDirectory::OSSIM_DIR_FILES); do { // The DTED directory may be polluted with cell statistics files and other // non-DEM items. Skip if not of the expected extension (OLK 10/2017): if (f.ext().match("[dD][tT][0-2]").empty()) continue; ossimRefPtr<ossimDtedHandler> dtedHandler = new ossimDtedHandler(); if(dtedHandler->open(f, false)) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimDtedElevationDatabase::open: Found dted file " << f << "\n"; } result = true; m_extension = "."+f.ext(); m_connectionString = dir; m_meanSpacing = dtedHandler->getMeanSpacingMeters(); } dtedHandler->close(); dtedHandler = 0; ++count2; } while(!result&&d2.getNext(f)&&(count2 < maxCount2)); } } } } while(!result&&(od.getNext(f))&&(count < maxCount)); } return result; } // End: ossimDtedElevationDatabase::inititializeExtension( dir ) <|endoftext|>
<commit_before>float rotx, roty, rotz; class Player{ public: float x,y,z; float lookat_x,lookat_y,lookat_z; }; class Level{ private: string cur_level_path; string cur_level; Model_OBJ *room; Model_OBJ *inv; Model_OBJ *player; int g_rotation; Player *p; bool flipped; public: Level(string &l); void display(); void keyPress(unsigned char ch, int x, int y); void specialKeyPress(int key, int x, int y); void flip(); }; void Level::flip() { flipped = !flipped; } Level::Level(string &l) { cur_level = l; cur_level_path = "../rooms/" + l +"_alt.obj"; inv = new Model_OBJ; player = new Model_OBJ; room = new Model_OBJ; inv->Load("../rooms/Level_1.obj"); player->Load("../models/Tux.obj"); room->Load(&cur_level_path[0]); //&cur_level_path[0] might avoid warning but is it safe? g_rotation = 0; p = new Player; p->x = 0; p->y = -1; p->z = -3; p->lookat_x = 0; p->lookat_y = 1; p->lookat_z = 0; } void Level::display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glRotatef(roty, 0, 1, 0); glRotatef(rotx, 1, 0, 0); glTranslatef(p->x,p->y,p->z); player->Draw(); if(flipped){ glRotatef(180,1,0,0); } //gluLookAt( p->x,p->y,p->z - 2, p->lookat_x + p->x,p->lookat_y,p->lookat_z +p->z, 0,1,0); room->Draw(); glRotatef(180,1,0,0); inv->Draw(); glutSwapBuffers(); glFlush(); } void Level::keyPress(unsigned char key, int x, int y) { cout<<key<<endl; //normal key press events if( key == 'w') { p->z+=0.3; } else if( key == 's') { p->z-=0.3; } else if(key == 'a') { p->x+=0.3; } else if(key == 'd') { p->x-=0.3; } else if(key == 'q') { flip(); } glutPostRedisplay(); } void Level::specialKeyPress(int key,int x,int y) { if ( key == GLUT_KEY_LEFT ) { roty += 1.0; if(roty>=360)roty-=360; } if ( key == GLUT_KEY_RIGHT ) { roty -= 1.0; if(roty<=0)roty+=360; } if ( key == GLUT_KEY_UP ) { rotx += 1.0; if(rotx>=360)rotx-=360; } if ( key == GLUT_KEY_DOWN ) { rotx -= 1.0; if(rotx<=0)rotx+=360; } glutPostRedisplay(); //Handle arrow, function keys etc } <commit_msg>Test colour<commit_after>float rotx, roty, rotz; class Player{ public: float x,y,z; float lookat_x,lookat_y,lookat_z; }; class Level{ private: string cur_level_path; string cur_level; Model_OBJ *room; Model_OBJ *inv; Model_OBJ *player; int g_rotation; Player *p; bool flipped; public: Level(string &l); void display(); void keyPress(unsigned char ch, int x, int y); void specialKeyPress(int key, int x, int y); void flip(); }; void Level::flip() { flipped = !flipped; } Level::Level(string &l) { cur_level = l; cur_level_path = "../rooms/" + l +"_alt.obj"; inv = new Model_OBJ; player = new Model_OBJ; room = new Model_OBJ; inv->Load("../rooms/Level_1.obj"); player->Load("../models/Tux.obj"); room->Load(&cur_level_path[0]); //&cur_level_path[0] might avoid warning but is it safe? g_rotation = 0; p = new Player; p->x = 0; p->y = -1; p->z = -3; p->lookat_x = 0; p->lookat_y = 1; p->lookat_z = 0; } void Level::display() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glRotatef(roty, 0, 1, 0); glRotatef(rotx, 1, 0, 0); glTranslatef(p->x,p->y,p->z); glColor3f(1,1,1); player->Draw(); if(flipped){ glRotatef(180,1,0,0); } //gluLookAt( p->x,p->y,p->z - 2, p->lookat_x + p->x,p->lookat_y,p->lookat_z +p->z, 0,1,0); glColor3f(0,1,0); room->Draw(); glRotatef(180,1,0,0); inv->Draw(); glutSwapBuffers(); glFlush(); } void Level::keyPress(unsigned char key, int x, int y) { cout<<key<<endl; //normal key press events if( key == 'w') { p->z+=0.3; } else if( key == 's') { p->z-=0.3; } else if(key == 'a') { p->x+=0.3; } else if(key == 'd') { p->x-=0.3; } else if(key == 'q') { flip(); } glutPostRedisplay(); } void Level::specialKeyPress(int key,int x,int y) { if ( key == GLUT_KEY_LEFT ) { roty += 1.0; if(roty>=360)roty-=360; } if ( key == GLUT_KEY_RIGHT ) { roty -= 1.0; if(roty<=0)roty+=360; } if ( key == GLUT_KEY_UP ) { rotx += 1.0; if(rotx>=360)rotx-=360; } if ( key == GLUT_KEY_DOWN ) { rotx -= 1.0; if(rotx<=0)rotx+=360; } glutPostRedisplay(); //Handle arrow, function keys etc } <|endoftext|>
<commit_before>#include <iostream> #include <gtest/gtest.h> #include "../pipeline.h" #include "../channel.h" #include <thread> class ChannelTest : testing::Test { }; using cmd = cu::pipeline<int>; cmd::link generator() { return [](cmd::in&, cmd::out& yield) { for (auto& s : {100, 200, 300}) { std::cout << "I am generator and push " << s << std::endl; yield(s); } }; } cmd::link link1() { return [](cmd::in& source, cmd::out& yield) { for (auto& s : source) { std::cout << "I am link1 and push " << s << std::endl; yield(s); } }; } cmd::link link2() { return [](cmd::in& source, cmd::out& yield) { for (auto& s : source) { std::cout << "I am link2 and push " << s << std::endl; yield(s); } }; } cmd::link link3() { return [](cmd::in& source, cmd::out& yield) { for (auto& s : source) { std::cout << "I am link3 and push " << s << std::endl; yield(s); } }; } int filter(int s) { std::cout << "I am filter and push " << s*2 << std::endl; return s*2; } void filter2(int s) { std::cout << "I am filter received " << s << " but not modified" << std::endl; } TEST(ChannelTest, goroutines_or_something_like_that) { // pipeline // cmd(generator(), link1(), link2(), link3()); auto handler = [](int s) { std::cout << "<fib> received: " << s << " but not modified" << std::endl; }; // channel cu::channel<int> go(filter, filter2, handler); std::thread t1([&](){ go << 100; }); std::thread t2([&](){ go << 200; }); std::cout << "recv1 is " << go.get() << std::endl; std::cout << "recv2 is " << go.get() << std::endl; t1.join(); t2.join(); } <commit_msg>Update test_channel.cpp<commit_after>#include <iostream> #include <gtest/gtest.h> #include "../pipeline.h" #include "../channel.h" #include <thread> class ChannelTest : testing::Test { }; using cmd = cu::pipeline<int>; cmd::link generator() { return [](cmd::in&, cmd::out& yield) { for (auto& s : {100, 200, 300}) { std::cout << "I am generator and push " << s << std::endl; yield(s); } }; } cmd::link link1() { return [](cmd::in& source, cmd::out& yield) { for (auto& s : source) { std::cout << "I am link1 and push " << s << std::endl; yield(s); } }; } cmd::link link2() { return [](cmd::in& source, cmd::out& yield) { for (auto& s : source) { std::cout << "I am link2 and push " << s << std::endl; yield(s); } }; } cmd::link link3() { return [](cmd::in& source, cmd::out& yield) { for (auto& s : source) { std::cout << "I am link3 and push " << s << std::endl; yield(s); } }; } void filter1(int s) { std::cout << "1. I am filter received " << s << " but not modified" << std::endl; } int filter2(int s) { std::cout << "2. I am filter and push " << s*2 << std::endl; return s*2; } TEST(ChannelTest, goroutines_or_something_like_that) { // pipeline // cmd(generator(), link1(), link2(), link3()); auto handler = [](int s) { std::cout << "3. received: " << s << " but not modified" << std::endl; }; // channel cu::channel<int> go(filter2, handler); go.connect(filter1); std::thread t1([&](){ go << 100; }); std::thread t2([&](){ go << 200; }); std::cout << "4. recv1 is " << go.get() << std::endl; std::cout << "4. recv2 is " << go.get() << std::endl; t1.join(); t2.join(); } <|endoftext|>
<commit_before><commit_msg>remove gamepad hint from credits<commit_after><|endoftext|>
<commit_before>#include "master.hpp" namespace factor { void factor_vm::init_card_decks() { cards_offset = (cell)data->cards - addr_to_card(data->start); decks_offset = (cell)data->decks - addr_to_deck(data->start); } data_heap::data_heap(cell young_size_, cell aging_size_, cell tenured_size_) { young_size_ = align(young_size_,deck_size); aging_size_ = align(aging_size_,deck_size); tenured_size_ = align(tenured_size_,deck_size); young_size = young_size_; aging_size = aging_size_; tenured_size = tenured_size_; cell total_size = young_size + 2 * aging_size + tenured_size + deck_size; seg = new segment(total_size,false); cell cards_size = addr_to_card(total_size); cards = new card[cards_size]; cards_end = cards + cards_size; memset(cards,0,cards_size); cell decks_size = addr_to_deck(total_size); decks = new card_deck[decks_size]; decks_end = decks + decks_size; memset(decks,0,decks_size); start = align(seg->start,deck_size); tenured = new tenured_space(tenured_size,start); aging = new aging_space(aging_size,tenured->end); aging_semispace = new aging_space(aging_size,aging->end); nursery = new nursery_space(young_size,aging_semispace->end); assert(seg->end - nursery->end <= deck_size); } data_heap::~data_heap() { delete seg; delete nursery; delete aging; delete aging_semispace; delete tenured; delete[] cards; delete[] decks; } data_heap *data_heap::grow(cell requested_bytes) { cell new_tenured_size = (tenured_size * 2) + requested_bytes; return new data_heap(young_size, aging_size, new_tenured_size); } template<typename Generation> void data_heap::clear_cards(Generation *gen) { cell first_card = addr_to_card(gen->start - start); cell last_card = addr_to_card(gen->end - start); memset(&cards[first_card],0,last_card - first_card); } template<typename Generation> void data_heap::clear_decks(Generation *gen) { cell first_deck = addr_to_deck(gen->start - start); cell last_deck = addr_to_deck(gen->end - start); memset(&decks[first_deck],0,last_deck - first_deck); } void data_heap::reset_generation(nursery_space *gen) { gen->here = gen->start; } void data_heap::reset_generation(aging_space *gen) { gen->here = gen->start; clear_cards(gen); clear_decks(gen); gen->starts.clear_object_start_offsets(); } void data_heap::reset_generation(tenured_space *gen) { clear_cards(gen); clear_decks(gen); } bool data_heap::low_memory_p() { return (tenured->free_space() <= nursery->size + aging->size); } void data_heap::mark_all_cards() { memset(cards,-1,cards_end - cards); memset(decks,-1,decks_end - decks); } void factor_vm::set_data_heap(data_heap *data_) { data = data_; nursery = *data->nursery; init_card_decks(); } void factor_vm::init_data_heap(cell young_size, cell aging_size, cell tenured_size) { set_data_heap(new data_heap(young_size,aging_size,tenured_size)); } /* Size of the object pointed to by an untagged pointer */ cell object::size() const { if(free_p()) return ((free_heap_block *)this)->size(); switch(type()) { case ARRAY_TYPE: return align(array_size((array*)this),data_alignment); case BIGNUM_TYPE: return align(array_size((bignum*)this),data_alignment); case BYTE_ARRAY_TYPE: return align(array_size((byte_array*)this),data_alignment); case STRING_TYPE: return align(string_size(string_capacity((string*)this)),data_alignment); case TUPLE_TYPE: { tuple_layout *layout = (tuple_layout *)UNTAG(((tuple *)this)->layout); return align(tuple_size(layout),data_alignment); } case QUOTATION_TYPE: return align(sizeof(quotation),data_alignment); case WORD_TYPE: return align(sizeof(word),data_alignment); case FLOAT_TYPE: return align(sizeof(boxed_float),data_alignment); case DLL_TYPE: return align(sizeof(dll),data_alignment); case ALIEN_TYPE: return align(sizeof(alien),data_alignment); case WRAPPER_TYPE: return align(sizeof(wrapper),data_alignment); case CALLSTACK_TYPE: return align(callstack_size(untag_fixnum(((callstack *)this)->length)),data_alignment); default: critical_error("Invalid header",(cell)this); return 0; /* can't happen */ } } /* The number of cells from the start of the object which should be scanned by the GC. Some types have a binary payload at the end (string, word, DLL) which we ignore. */ cell object::binary_payload_start() const { if(free_p()) return 0; switch(type()) { /* these objects do not refer to other objects at all */ case FLOAT_TYPE: case BYTE_ARRAY_TYPE: case BIGNUM_TYPE: case CALLSTACK_TYPE: return 0; /* these objects have some binary data at the end */ case WORD_TYPE: return sizeof(word) - sizeof(cell) * 3; case ALIEN_TYPE: return sizeof(cell) * 3; case DLL_TYPE: return sizeof(cell) * 2; case QUOTATION_TYPE: return sizeof(quotation) - sizeof(cell) * 2; case STRING_TYPE: return sizeof(string); /* everything else consists entirely of pointers */ case ARRAY_TYPE: return array_size<array>(array_capacity((array*)this)); case TUPLE_TYPE: return tuple_size(untag<tuple_layout>(((tuple *)this)->layout)); case WRAPPER_TYPE: return sizeof(wrapper); default: critical_error("Invalid header",(cell)this); return 0; /* can't happen */ } } data_heap_room factor_vm::data_room() { data_heap_room room; room.nursery_size = nursery.size; room.nursery_occupied = nursery.occupied_space(); room.nursery_free = nursery.free_space(); room.aging_size = data->aging->size; room.aging_occupied = data->aging->occupied_space(); room.aging_free = data->aging->free_space(); room.tenured_size = data->tenured->size; room.tenured_occupied = data->tenured->occupied_space(); room.tenured_total_free = data->tenured->free_space(); room.tenured_contiguous_free = data->tenured->largest_free_block(); room.tenured_free_block_count = data->tenured->free_block_count(); room.cards = data->cards_end - data->cards; room.decks = data->decks_end - data->decks; room.mark_stack = mark_stack.capacity() * sizeof(cell); return room; } void factor_vm::primitive_data_room() { data_heap_room room = data_room(); dpush(tag<byte_array>(byte_array_from_value(&room))); } struct object_accumulator { cell type; std::vector<cell> objects; explicit object_accumulator(cell type_) : type(type_) {} void operator()(object *obj) { if(type == TYPE_COUNT || obj->type() == type) objects.push_back(tag_dynamic(obj)); } }; cell factor_vm::instances(cell type) { object_accumulator accum(type); each_object(accum); cell object_count = accum.objects.size(); data_roots.push_back(data_root_range(&accum.objects[0],object_count)); array *objects = allot_array(object_count,false_object); memcpy(objects->data(),&accum.objects[0],object_count * sizeof(cell)); data_roots.pop_back(); return tag<array>(objects); } void factor_vm::primitive_all_instances() { primitive_full_gc(); dpush(instances(TYPE_COUNT)); } cell factor_vm::find_all_words() { return instances(WORD_TYPE); } } <commit_msg>vm: be more eager to do a full collection to avoid fragmentation leading to heap growth<commit_after>#include "master.hpp" namespace factor { void factor_vm::init_card_decks() { cards_offset = (cell)data->cards - addr_to_card(data->start); decks_offset = (cell)data->decks - addr_to_deck(data->start); } data_heap::data_heap(cell young_size_, cell aging_size_, cell tenured_size_) { young_size_ = align(young_size_,deck_size); aging_size_ = align(aging_size_,deck_size); tenured_size_ = align(tenured_size_,deck_size); young_size = young_size_; aging_size = aging_size_; tenured_size = tenured_size_; cell total_size = young_size + 2 * aging_size + tenured_size + deck_size; seg = new segment(total_size,false); cell cards_size = addr_to_card(total_size); cards = new card[cards_size]; cards_end = cards + cards_size; memset(cards,0,cards_size); cell decks_size = addr_to_deck(total_size); decks = new card_deck[decks_size]; decks_end = decks + decks_size; memset(decks,0,decks_size); start = align(seg->start,deck_size); tenured = new tenured_space(tenured_size,start); aging = new aging_space(aging_size,tenured->end); aging_semispace = new aging_space(aging_size,aging->end); nursery = new nursery_space(young_size,aging_semispace->end); assert(seg->end - nursery->end <= deck_size); } data_heap::~data_heap() { delete seg; delete nursery; delete aging; delete aging_semispace; delete tenured; delete[] cards; delete[] decks; } data_heap *data_heap::grow(cell requested_bytes) { cell new_tenured_size = (tenured_size * 2) + requested_bytes; return new data_heap(young_size, aging_size, new_tenured_size); } template<typename Generation> void data_heap::clear_cards(Generation *gen) { cell first_card = addr_to_card(gen->start - start); cell last_card = addr_to_card(gen->end - start); memset(&cards[first_card],0,last_card - first_card); } template<typename Generation> void data_heap::clear_decks(Generation *gen) { cell first_deck = addr_to_deck(gen->start - start); cell last_deck = addr_to_deck(gen->end - start); memset(&decks[first_deck],0,last_deck - first_deck); } void data_heap::reset_generation(nursery_space *gen) { gen->here = gen->start; } void data_heap::reset_generation(aging_space *gen) { gen->here = gen->start; clear_cards(gen); clear_decks(gen); gen->starts.clear_object_start_offsets(); } void data_heap::reset_generation(tenured_space *gen) { clear_cards(gen); clear_decks(gen); } bool data_heap::low_memory_p() { return (tenured->largest_free_block() <= nursery->size + aging->size); } void data_heap::mark_all_cards() { memset(cards,-1,cards_end - cards); memset(decks,-1,decks_end - decks); } void factor_vm::set_data_heap(data_heap *data_) { data = data_; nursery = *data->nursery; init_card_decks(); } void factor_vm::init_data_heap(cell young_size, cell aging_size, cell tenured_size) { set_data_heap(new data_heap(young_size,aging_size,tenured_size)); } /* Size of the object pointed to by an untagged pointer */ cell object::size() const { if(free_p()) return ((free_heap_block *)this)->size(); switch(type()) { case ARRAY_TYPE: return align(array_size((array*)this),data_alignment); case BIGNUM_TYPE: return align(array_size((bignum*)this),data_alignment); case BYTE_ARRAY_TYPE: return align(array_size((byte_array*)this),data_alignment); case STRING_TYPE: return align(string_size(string_capacity((string*)this)),data_alignment); case TUPLE_TYPE: { tuple_layout *layout = (tuple_layout *)UNTAG(((tuple *)this)->layout); return align(tuple_size(layout),data_alignment); } case QUOTATION_TYPE: return align(sizeof(quotation),data_alignment); case WORD_TYPE: return align(sizeof(word),data_alignment); case FLOAT_TYPE: return align(sizeof(boxed_float),data_alignment); case DLL_TYPE: return align(sizeof(dll),data_alignment); case ALIEN_TYPE: return align(sizeof(alien),data_alignment); case WRAPPER_TYPE: return align(sizeof(wrapper),data_alignment); case CALLSTACK_TYPE: return align(callstack_size(untag_fixnum(((callstack *)this)->length)),data_alignment); default: critical_error("Invalid header",(cell)this); return 0; /* can't happen */ } } /* The number of cells from the start of the object which should be scanned by the GC. Some types have a binary payload at the end (string, word, DLL) which we ignore. */ cell object::binary_payload_start() const { if(free_p()) return 0; switch(type()) { /* these objects do not refer to other objects at all */ case FLOAT_TYPE: case BYTE_ARRAY_TYPE: case BIGNUM_TYPE: case CALLSTACK_TYPE: return 0; /* these objects have some binary data at the end */ case WORD_TYPE: return sizeof(word) - sizeof(cell) * 3; case ALIEN_TYPE: return sizeof(cell) * 3; case DLL_TYPE: return sizeof(cell) * 2; case QUOTATION_TYPE: return sizeof(quotation) - sizeof(cell) * 2; case STRING_TYPE: return sizeof(string); /* everything else consists entirely of pointers */ case ARRAY_TYPE: return array_size<array>(array_capacity((array*)this)); case TUPLE_TYPE: return tuple_size(untag<tuple_layout>(((tuple *)this)->layout)); case WRAPPER_TYPE: return sizeof(wrapper); default: critical_error("Invalid header",(cell)this); return 0; /* can't happen */ } } data_heap_room factor_vm::data_room() { data_heap_room room; room.nursery_size = nursery.size; room.nursery_occupied = nursery.occupied_space(); room.nursery_free = nursery.free_space(); room.aging_size = data->aging->size; room.aging_occupied = data->aging->occupied_space(); room.aging_free = data->aging->free_space(); room.tenured_size = data->tenured->size; room.tenured_occupied = data->tenured->occupied_space(); room.tenured_total_free = data->tenured->free_space(); room.tenured_contiguous_free = data->tenured->largest_free_block(); room.tenured_free_block_count = data->tenured->free_block_count(); room.cards = data->cards_end - data->cards; room.decks = data->decks_end - data->decks; room.mark_stack = mark_stack.capacity() * sizeof(cell); return room; } void factor_vm::primitive_data_room() { data_heap_room room = data_room(); dpush(tag<byte_array>(byte_array_from_value(&room))); } struct object_accumulator { cell type; std::vector<cell> objects; explicit object_accumulator(cell type_) : type(type_) {} void operator()(object *obj) { if(type == TYPE_COUNT || obj->type() == type) objects.push_back(tag_dynamic(obj)); } }; cell factor_vm::instances(cell type) { object_accumulator accum(type); each_object(accum); cell object_count = accum.objects.size(); data_roots.push_back(data_root_range(&accum.objects[0],object_count)); array *objects = allot_array(object_count,false_object); memcpy(objects->data(),&accum.objects[0],object_count * sizeof(cell)); data_roots.pop_back(); return tag<array>(objects); } void factor_vm::primitive_all_instances() { primitive_full_gc(); dpush(instances(TYPE_COUNT)); } cell factor_vm::find_all_words() { return instances(WORD_TYPE); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: appdata.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:52:33 $ * * 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 _SFX_APPDATA_HXX #define _SFX_APPDATA_HXX #include <tools/link.hxx> #include <tools/list.hxx> #include <svtools/lstner.hxx> #include <bitset.hxx> #include <objsh.hxx> class SfxTaskManager; class SfxApplication; class SvBindingTransportFactory; class SvLockBytesFactory; class SfxIniDefaultManager; class DataLockByteFactory_Impl; class SvStrings; class Config; class PopupMenu; class SfxBmkMenu; class SvVerbList; class SfxProgress; class SfxConfigManager; class SfxChildWinFactArr_Impl; class SfxToolBoxConfig; class SfxMacro; class SfxDdeDocTopics_Impl; class DdeService; class SfxEventConfiguration; class SfxMacroConfig; class SvFactory; class SotFactory; class SfxItemPool; class SfxInitLinkList; class SfxFilterMatcher; class DemoData_Impl; class SfxExplorer; class SfxMenuBarManager; class StopButtonTimer_Impl; class SvUShorts; class SfxNodeData_Impl; class SfxSIDList_Impl; struct SfxFrameObjectFactoryPtr; struct SfxPluginObjectFactoryPtr; struct SfxPluginObjectFactoryPtr; class ISfxTemplateCommon; class SfxAnchorJobList_Impl; class SfxFilterMatcher; class INetConnection; class SfxINetPlugInService; class SfxTrash; class SfxSimpleLockBytesFactoryMemberList; class CntUpdateResults_Impl; class SfxIniDefaultManager; class SfxFolderCfgList_Impl; class SfxCancelManager; class ISfxModule; struct SfxDownload_Impl; class SvBindStatusCallback; class SfxStatusDispatcher; class SfxDesktop; class SfxDdeTriggerTopic_Impl; class OfaMiscCfg; class SvLibrary; class SfxDocumentTemplates; DECLARE_LIST( ConnectionList_Impl, INetConnection * ); class StopButtonTimer_Impl : public Timer { BOOL bState; protected: virtual void Timeout(); public: StopButtonTimer_Impl(); void SetButtonState( BOOL bStateP ); BOOL GetButtonState() const { return bState; } }; //========================================================================= // SfxFolderState //========================================================================= /* [Beschreibung] Elemente dieser Aufzaehlung geben den Zustand eines Ordners an: SFX_FOLDERSTATE_EMPTY der Ordner hat keine Unterordner SFX_FOLDERSTATE_CONTENT der Ordner hat Unterordner SFX_FOLDERSTATE_UNKNOWN es ist nicht bekannt, ob Unterordner vorhanden sind */ enum SfxFolderState { SFX_FOLDERSTATE_EMPTY = 0, SFX_FOLDERSTATE_CONTENT = 1, SFX_FOLDERSTATE_UNKNOWN = 2 }; //========================================================================= // SfxAppData_Impl //========================================================================= class SfxFrameArr_Impl; class SfxAppData_Impl : public SfxListener { public: SfxConfigManager* pAppCfg; SfxProgress* pProgress; SfxItemPool* pPool; SfxChildWinFactArr_Impl* pFactArr; SfxMacro* pMacro; SvLibrary* pODKLib; String aLastDir; String aLastFilter; char nConfigManagerAvailable; IndexBitSet aIndexBitSet; DdeService* pDdeService; // wollen wir DDE machen? SfxDdeDocTopics_Impl* pDocTopics; SfxEventConfiguration* pEventConfig; SotFactory* pSfxApplicationObjectFactory; USHORT nAsynchronCalls; SvVerbList* pVerbs; USHORT nBasicCallLevel; USHORT nRescheduleLocks; USHORT nInReschedule; DemoData_Impl* pDemoData; SfxInitLinkList* pInitLinkList; Timer aLateInitTimer; SfxFilterMatcher* pMatcher; SfxExplorer* pExplorer; String aSaveAsTarget; String aUserEMailAddr; ConnectionList_Impl aConnectionList; SfxObjectFactory* pSfxPlugInObjectShellFactory; Window* pDefFocusWin; SfxMenuBarManager* pAppManager; SfxFrameObjectFactoryPtr* pSfxFrameObjectFactoryPtr; List aPendingInitFactories; SfxIniDefaultManager* pIniDefMgr; String aLogicAppName; SfxINetPlugInService* pPlugService; StopButtonTimer_Impl* pStopButtonTimer; SfxCancelManager* pCancelMgr; USHORT nDocModalMode; SvUShorts* pDisabledSlotList; Config* pFilterIni; ISfxModule* pISfxModule; String aLastNewURL; SfxPluginObjectFactoryPtr* pSfxPluginObjectFactoryPtr; SfxNodeData_Impl* pNodeData_Impl; SfxSIDList_Impl* pSIDList_Impl; ISfxTemplateCommon* pTemplateCommon; Window* pActiveInplaceWindow; SfxAnchorJobList_Impl* pAnchorJobList; ResMgr* pLabelResMgr; USHORT nDemoKind; SfxFrameArr_Impl* pTopFrames; SfxTrash* pTrash; SvStrings* pSecureURLs; USHORT nAutoTabPageId; DataLockByteFactory_Impl* pDataLockBytesFactory; USHORT nExecutingSID; CntUpdateResults_Impl* pNewMessages; USHORT nNewMessages; SvLockBytesFactory* pImageLockBytesFactory; SvLockBytesFactory* pInfoLockBytesFactory; SfxBmkMenu* pNewMenu; SfxBmkMenu* pBookmarkMenu; SfxBmkMenu* pAutoPilotMenu; SfxBmkMenu* pStartMenu; SfxStatusDispatcher* pAppDispatch; SfxDdeTriggerTopic_Impl* pTriggerTopic; DdeService* pDdeService2; SvStrings* pExtBrwOnExceptionList; SvStrings* pExtBrwOffExceptionList; OfaMiscCfg* pMiscConfig; SfxObjectShell* pThisDocument; BYTE bMultiQuickSearch; BYTE bShowFsysExtension; BYTE bUseExternBrowser; BOOL bAccelEnabled : 1; BOOL bIBMTitle : 1; BOOL bOLEResize : 1; BOOL bDirectAliveCount : 1; BOOL bInQuit : 1; BOOL bStbWasVisible : 1; BOOL bSessionFailed : 1; BOOL bOLEAutomation : 1; BOOL bInvalidateOnUnlock : 1; BOOL bBean : 1; BOOL bMinimized : 1; BOOL bInvisible : 1; BOOL bSmartBeamer : 1; BOOL bInException : 1; BOOL bNewMessagesBlinker : 1; BOOL bNewTaskForNewMessages : 1; BOOL bBeamerSwitchedOn : 1; BOOL bLateInit_BrowseRegistrationPage : 1; USHORT nAppEvent; SfxDocumentTemplates* pTemplates; String aOpenList; String aPrintList; String aUcbUrl; SfxAppData_Impl( SfxApplication* pApp ); ~SfxAppData_Impl(); PopupMenu* GetPopupMenu( USHORT nSid, BOOL bBig=FALSE, BOOL bNew=FALSE ); virtual void Notify( SfxBroadcaster &rBC, const SfxHint &rHint ); DECL_STATIC_LINK( SfxAppData_Impl, CreateDataLockBytesFactory, void* ); void ResetNewMessages( const String &rFolderULR ); void LoadNewMessages(); void SaveNewMessages(); void UpdateApplicationSettings( BOOL bDontHide ); SfxDocumentTemplates* GetDocumentTemplates(); }; extern void FATToVFat_Impl( String& ); #include <svtools/poolitem.hxx> class SfxPtrItem : public SfxPoolItem { void* pPtr; public: TYPEINFO(); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const { return new SfxPtrItem( *this ); } virtual int operator==( const SfxPoolItem& rL) const { return ((SfxPtrItem&)rL).pPtr == pPtr; } SfxPtrItem( USHORT nWhich, void * pValue ) : SfxPoolItem( nWhich ) { pPtr = pValue; } void* GetValue() const { return pPtr; } }; #endif // #ifndef _SFX_APPDATA_HXX <commit_msg>Cleanup; new Options classes<commit_after>/************************************************************************* * * $RCSfile: appdata.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: mba $ $Date: 2000-09-28 11:29:31 $ * * 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 _SFX_APPDATA_HXX #define _SFX_APPDATA_HXX #include <tools/link.hxx> #include <tools/list.hxx> #include <svtools/lstner.hxx> #include <vcl/timer.hxx> #include <tools/string.hxx> #include "bitset.hxx" class SfxApplication; class SvStrings; class Config; class PopupMenu; class SfxBmkMenu; class SvVerbList; class SfxProgress; class SfxConfigManager; class SfxChildWinFactArr_Impl; class SfxToolBoxConfig; class SfxDdeDocTopics_Impl; class DdeService; class SfxEventConfiguration; class SfxMacroConfig; class SfxItemPool; class SfxInitLinkList; class SfxFilterMatcher; class SvUShorts; struct SfxFrameObjectFactoryPtr; struct SfxPluginObjectFactoryPtr; class ISfxTemplateCommon; class SfxFilterMatcher; class SfxCancelManager; class SfxStatusDispatcher; class SfxDdeTriggerTopic_Impl; class OfaMiscCfg; class SfxDocumentTemplates; class SfxFrameArr_Impl; class SvtSaveOptions; class SvtUndoOptions; class SvtHelpOptions; class SfxObjectFactory; class SfxObjectShell; class ResMgr; class Window; class StopButtonTimer_Impl : public Timer { BOOL bState; protected: virtual void Timeout(); public: StopButtonTimer_Impl(); void SetButtonState( BOOL bStateP ); BOOL GetButtonState() const { return bState; } }; //========================================================================= // SfxAppData_Impl //========================================================================= class SfxAppData_Impl : public SfxListener { public: IndexBitSet aIndexBitSet; // for counting noname documents List aPendingInitFactories; // late filter init Timer aLateInitTimer; String aLastDir; // for IO dialog String aLastFilter; // for IO dialog String aLastNewURL; // for AppControl String aOpenList; // command line arguments String aPrintList; // command line arguments String aUcbUrl; // command line arguments // DDE stuff DdeService* pDdeService; SfxDdeDocTopics_Impl* pDocTopics; SfxDdeTriggerTopic_Impl* pTriggerTopic; DdeService* pDdeService2; // single instance classes SfxChildWinFactArr_Impl* pFactArr; SfxPluginObjectFactoryPtr* pSfxPluginObjectFactoryPtr; SfxObjectFactory* pSfxPlugInObjectShellFactory; SfxFrameObjectFactoryPtr* pSfxFrameObjectFactoryPtr; SfxFrameArr_Impl* pTopFrames; // special members SfxInitLinkList* pInitLinkList; StopButtonTimer_Impl* pStopButtonTimer; // application members SfxFilterMatcher* pMatcher; SfxCancelManager* pCancelMgr; ResMgr* pLabelResMgr; SfxStatusDispatcher* pAppDispatch; SfxConfigManager* pAppCfg; SfxDocumentTemplates* pTemplates; // global pointers SvVerbList* pVerbs; Config* pFilterIni; SfxItemPool* pPool; SfxEventConfiguration* pEventConfig; SvUShorts* pDisabledSlotList; SvStrings* pSecureURLs; SfxBmkMenu* pNewMenu; SfxBmkMenu* pAutoPilotMenu; OfaMiscCfg* pMiscConfig; SvtSaveOptions* pSaveOptions; SvtUndoOptions* pUndoOptions; SvtHelpOptions* pHelpOptions; // "current" functionality SfxObjectShell* pThisDocument; SfxProgress* pProgress; Window* pDefFocusWin; ISfxTemplateCommon* pTemplateCommon; USHORT nDocModalMode; // counts documents in modal mode USHORT nAutoTabPageId; USHORT nExecutingSID; USHORT nBasicCallLevel; USHORT nRescheduleLocks; USHORT nInReschedule; USHORT nAsynchronCalls; USHORT nAppEvent; // command line interpretation BOOL bDirectAliveCount : 1; BOOL bInQuit : 1; BOOL bInvalidateOnUnlock : 1; BOOL bBean : 1; BOOL bMinimized : 1; BOOL bInvisible : 1; BOOL bInException : 1; BOOL bPlugged : 1; BOOL bOLEResize : 1; SfxAppData_Impl( SfxApplication* ); ~SfxAppData_Impl(); PopupMenu* GetPopupMenu( USHORT nSid, BOOL bBig=FALSE, BOOL bNew=FALSE ); virtual void Notify( SfxBroadcaster &rBC, const SfxHint &rHint ); void UpdateApplicationSettings( BOOL bDontHide ); SfxDocumentTemplates* GetDocumentTemplates(); DECL_STATIC_LINK( SfxAppData_Impl, CreateDocumentTemplates, void* ); }; #endif // #ifndef _SFX_APPDATA_HXX <|endoftext|>
<commit_before><commit_msg>A set of patches from Kein-Hong Man to improve handling of barewords, numbers, special variables, and here documents.<commit_after><|endoftext|>
<commit_before>#include <../recurse.hpp> #include <QHash> int main(int argc, char *argv[]) { Recurse app(argc, argv); // http options QHash<QString, QVariant> http_options; http_options["port"] = 3000; // https options QHash<QString, QVariant> https_options; https_options["port"] = 3020; https_options["private_key"] = "./priv.pem"; https_options["certificate"] = "./cert.pem"; app.http_server(http_options); app.https_server(https_options); app.use([](auto &ctx, auto next) { qDebug() << "got a new request from" << ctx.request.ip; next(); }); app.use([](auto &ctx) { ctx.response.send("Hello, world"); }); qDebug() << "start listening..."; auto ret = app.listen(); if (ret.error()) { qDebug() << "error upon listening:" << ret.lastError(); } }; <commit_msg>example: remove extra ;<commit_after>#include <../recurse.hpp> #include <QHash> int main(int argc, char *argv[]) { Recurse app(argc, argv); // http options QHash<QString, QVariant> http_options; http_options["port"] = 3000; // https options QHash<QString, QVariant> https_options; https_options["port"] = 3020; https_options["private_key"] = "./priv.pem"; https_options["certificate"] = "./cert.pem"; app.http_server(http_options); app.https_server(https_options); app.use([](auto &ctx, auto next) { qDebug() << "got a new request from" << ctx.request.ip; next(); }); app.use([](auto &ctx) { ctx.response.send("Hello, world"); }); qDebug() << "start listening..."; auto ret = app.listen(); if (ret.error()) { qDebug() << "error upon listening:" << ret.lastError(); } } <|endoftext|>
<commit_before><commit_msg>Changed ListBox::Clear() only to detach/attach the header row if it was already attached.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2012 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 <gtest/gtest.h> #include <string> #include <sys/wait.h> #include "base/bind.h" #include "base/eintr_wrapper.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "chrome/browser/chromeos/process_proxy/process_proxy_registry.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; namespace { // The test line must have all distinct characters. const char kTestLineToSend[] = "abcdefgh\n"; const char kTestLineExpected[] = "abcdefgh\r\n"; const char kCatCommand[] = "cat"; const char kStdoutType[] = "stdout"; const int kTestLineNum = 100; class TestRunner { public: virtual ~TestRunner() {} virtual void SetupExpectations(pid_t pid) = 0; virtual void OnSomeRead(pid_t pid, const std::string& type, const std::string& output) = 0; virtual void StartRegistryTest(ProcessProxyRegistry* registry) = 0; protected: pid_t pid_; }; class RegistryTestRunner : public TestRunner { public: virtual ~RegistryTestRunner() {} virtual void SetupExpectations(pid_t pid) OVERRIDE { pid_ = pid; left_to_check_index_[0] = 0; left_to_check_index_[1] = 0; // We consider that a line processing has started if a value in // left_to_check__[index] is set to 0, thus -2. lines_left_ = 2 * kTestLineNum - 2; expected_line_ = kTestLineExpected; } // Method to test validity of received input. We will receive two streams of // the same data. (input will be echoed twice by the testing process). Each // stream will contain the same string repeated |kTestLineNum| times. So we // have to match 2 * |kTestLineNum| lines. The problem is the received lines // from different streams may be interleaved (e.g. we may receive // abc|abcdef|defgh|gh). To deal with that, we allow to test received text // against two lines. The lines MUST NOT have two same characters for this // algorithm to work. virtual void OnSomeRead(pid_t pid, const std::string& type, const std::string& output) OVERRIDE { EXPECT_EQ(type, kStdoutType); EXPECT_EQ(pid_, pid); bool valid = true; for (size_t i = 0; i < output.length(); i++) { // The character output[i] should be next in at least one of the lines we // are testing. valid = (ProcessReceivedCharacter(output[i], 0) || ProcessReceivedCharacter(output[i], 1)); EXPECT_TRUE(valid) << "Received: " << output; } if (!valid || TestSucceeded()) { content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } } virtual void StartRegistryTest(ProcessProxyRegistry* registry) OVERRIDE { for (int i = 0; i < kTestLineNum; i++) { EXPECT_TRUE(registry->SendInput(pid_, kTestLineToSend)); } } private: bool ProcessReceivedCharacter(char received, size_t stream) { if (stream < 0 || stream >= arraysize(left_to_check_index_)) return false; bool success = left_to_check_index_[stream] < expected_line_.length() && expected_line_[left_to_check_index_[stream]] == received; if (success) left_to_check_index_[stream]++; if (left_to_check_index_[stream] == expected_line_.length() && lines_left_ > 0) { // Take another line to test for this stream, if there are any lines left. // If not, this stream is done. left_to_check_index_[stream] = 0; lines_left_--; } return success; } bool TestSucceeded() { return left_to_check_index_[0] == expected_line_.length() && left_to_check_index_[1] == expected_line_.length() && lines_left_ == 0; } size_t left_to_check_index_[2]; size_t lines_left_; std::string expected_line_; }; class RegistryNotifiedOnProcessExitTestRunner : public TestRunner { public: virtual ~RegistryNotifiedOnProcessExitTestRunner() {} virtual void SetupExpectations(pid_t pid) OVERRIDE { output_received_ = false; pid_ = pid; } virtual void OnSomeRead(pid_t pid, const std::string& type, const std::string& output) OVERRIDE { EXPECT_EQ(pid_, pid); if (!output_received_) { output_received_ = true; EXPECT_EQ(type, "stdout"); EXPECT_EQ(output, "p"); base::KillProcess(pid_, 0 , true); return; } EXPECT_EQ("exit", type); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } virtual void StartRegistryTest(ProcessProxyRegistry* registry) { EXPECT_TRUE(registry->SendInput(pid_, "p")); } private: bool output_received_; }; class SigIntTestRunner : public TestRunner { public: virtual ~SigIntTestRunner() {} virtual void SetupExpectations(pid_t pid) OVERRIDE { pid_ = pid; } virtual void OnSomeRead(pid_t pid, const std::string& type, const std::string& output) OVERRIDE { EXPECT_EQ(pid_, pid); // We may receive ^C on stdout, but we don't care about that, as long as we // eventually received exit event. if (type == "exit") { content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } } virtual void StartRegistryTest(ProcessProxyRegistry* registry) { // Send SingInt and verify the process exited. EXPECT_TRUE(registry->SendInput(pid_, "\003")); } private: bool output_received_; }; } // namespace class ProcessProxyTest : public InProcessBrowserTest { public: ProcessProxyTest() {} ~ProcessProxyTest() {} protected: void InitRegistryTest() { registry_ = ProcessProxyRegistry::Get(); EXPECT_TRUE(registry_->OpenProcess(kCatCommand, &pid_, base::Bind(&TestRunner::OnSomeRead, base::Unretained(test_runner_.get())))); test_runner_->SetupExpectations(pid_); test_runner_->StartRegistryTest(registry_); } void EndRegistryTest() { registry_->CloseProcess(pid_); base::TerminationStatus status = base::GetTerminationStatus(pid_, NULL); EXPECT_NE(base::TERMINATION_STATUS_STILL_RUNNING, status); if (status == base::TERMINATION_STATUS_STILL_RUNNING) base::KillProcess(pid_, 0, true); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } void RunTest() { BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&ProcessProxyTest::InitRegistryTest, base::Unretained(this))); // Wait until all data from output watcher is received (QuitTask will be // fired on watcher thread). ui_test_utils::RunMessageLoop(); BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&ProcessProxyTest::EndRegistryTest, base::Unretained(this))); // Wait until we clean up the process proxy. ui_test_utils::RunMessageLoop(); } scoped_ptr<TestRunner> test_runner_; private: ProcessProxyRegistry* registry_; pid_t pid_; }; // Test will open new process that will run cat command, and verify data we // write to process gets echoed back. IN_PROC_BROWSER_TEST_F(ProcessProxyTest, RegistryTest) { test_runner_.reset(new RegistryTestRunner()); RunTest(); } // Open new process, then kill it. Verifiy that we detect when the process dies. IN_PROC_BROWSER_TEST_F(ProcessProxyTest, RegistryNotifiedOnProcessExit) { test_runner_.reset(new RegistryNotifiedOnProcessExitTestRunner()); RunTest(); } // Test verifies that \003 message send to process is processed as SigInt. // Timing out on the waterfall: http://crbug.com/115064 IN_PROC_BROWSER_TEST_F(ProcessProxyTest, DISABLED_SigInt) { test_runner_.reset(new SigIntTestRunner()); RunTest(); } <commit_msg>Fix clang compile error<commit_after>// Copyright (c) 2012 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 <gtest/gtest.h> #include <string> #include <sys/wait.h> #include "base/bind.h" #include "base/eintr_wrapper.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "chrome/browser/chromeos/process_proxy/process_proxy_registry.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; namespace { // The test line must have all distinct characters. const char kTestLineToSend[] = "abcdefgh\n"; const char kTestLineExpected[] = "abcdefgh\r\n"; const char kCatCommand[] = "cat"; const char kStdoutType[] = "stdout"; const int kTestLineNum = 100; class TestRunner { public: virtual ~TestRunner() {} virtual void SetupExpectations(pid_t pid) = 0; virtual void OnSomeRead(pid_t pid, const std::string& type, const std::string& output) = 0; virtual void StartRegistryTest(ProcessProxyRegistry* registry) = 0; protected: pid_t pid_; }; class RegistryTestRunner : public TestRunner { public: virtual ~RegistryTestRunner() {} virtual void SetupExpectations(pid_t pid) OVERRIDE { pid_ = pid; left_to_check_index_[0] = 0; left_to_check_index_[1] = 0; // We consider that a line processing has started if a value in // left_to_check__[index] is set to 0, thus -2. lines_left_ = 2 * kTestLineNum - 2; expected_line_ = kTestLineExpected; } // Method to test validity of received input. We will receive two streams of // the same data. (input will be echoed twice by the testing process). Each // stream will contain the same string repeated |kTestLineNum| times. So we // have to match 2 * |kTestLineNum| lines. The problem is the received lines // from different streams may be interleaved (e.g. we may receive // abc|abcdef|defgh|gh). To deal with that, we allow to test received text // against two lines. The lines MUST NOT have two same characters for this // algorithm to work. virtual void OnSomeRead(pid_t pid, const std::string& type, const std::string& output) OVERRIDE { EXPECT_EQ(type, kStdoutType); EXPECT_EQ(pid_, pid); bool valid = true; for (size_t i = 0; i < output.length(); i++) { // The character output[i] should be next in at least one of the lines we // are testing. valid = (ProcessReceivedCharacter(output[i], 0) || ProcessReceivedCharacter(output[i], 1)); EXPECT_TRUE(valid) << "Received: " << output; } if (!valid || TestSucceeded()) { content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } } virtual void StartRegistryTest(ProcessProxyRegistry* registry) OVERRIDE { for (int i = 0; i < kTestLineNum; i++) { EXPECT_TRUE(registry->SendInput(pid_, kTestLineToSend)); } } private: bool ProcessReceivedCharacter(char received, size_t stream) { if (stream >= arraysize(left_to_check_index_)) return false; bool success = left_to_check_index_[stream] < expected_line_.length() && expected_line_[left_to_check_index_[stream]] == received; if (success) left_to_check_index_[stream]++; if (left_to_check_index_[stream] == expected_line_.length() && lines_left_ > 0) { // Take another line to test for this stream, if there are any lines left. // If not, this stream is done. left_to_check_index_[stream] = 0; lines_left_--; } return success; } bool TestSucceeded() { return left_to_check_index_[0] == expected_line_.length() && left_to_check_index_[1] == expected_line_.length() && lines_left_ == 0; } size_t left_to_check_index_[2]; size_t lines_left_; std::string expected_line_; }; class RegistryNotifiedOnProcessExitTestRunner : public TestRunner { public: virtual ~RegistryNotifiedOnProcessExitTestRunner() {} virtual void SetupExpectations(pid_t pid) OVERRIDE { output_received_ = false; pid_ = pid; } virtual void OnSomeRead(pid_t pid, const std::string& type, const std::string& output) OVERRIDE { EXPECT_EQ(pid_, pid); if (!output_received_) { output_received_ = true; EXPECT_EQ(type, "stdout"); EXPECT_EQ(output, "p"); base::KillProcess(pid_, 0 , true); return; } EXPECT_EQ("exit", type); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } virtual void StartRegistryTest(ProcessProxyRegistry* registry) { EXPECT_TRUE(registry->SendInput(pid_, "p")); } private: bool output_received_; }; class SigIntTestRunner : public TestRunner { public: virtual ~SigIntTestRunner() {} virtual void SetupExpectations(pid_t pid) OVERRIDE { pid_ = pid; } virtual void OnSomeRead(pid_t pid, const std::string& type, const std::string& output) OVERRIDE { EXPECT_EQ(pid_, pid); // We may receive ^C on stdout, but we don't care about that, as long as we // eventually received exit event. if (type == "exit") { content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } } virtual void StartRegistryTest(ProcessProxyRegistry* registry) { // Send SingInt and verify the process exited. EXPECT_TRUE(registry->SendInput(pid_, "\003")); } private: bool output_received_; }; } // namespace class ProcessProxyTest : public InProcessBrowserTest { public: ProcessProxyTest() {} ~ProcessProxyTest() {} protected: void InitRegistryTest() { registry_ = ProcessProxyRegistry::Get(); EXPECT_TRUE(registry_->OpenProcess(kCatCommand, &pid_, base::Bind(&TestRunner::OnSomeRead, base::Unretained(test_runner_.get())))); test_runner_->SetupExpectations(pid_); test_runner_->StartRegistryTest(registry_); } void EndRegistryTest() { registry_->CloseProcess(pid_); base::TerminationStatus status = base::GetTerminationStatus(pid_, NULL); EXPECT_NE(base::TERMINATION_STATUS_STILL_RUNNING, status); if (status == base::TERMINATION_STATUS_STILL_RUNNING) base::KillProcess(pid_, 0, true); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure()); } void RunTest() { BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&ProcessProxyTest::InitRegistryTest, base::Unretained(this))); // Wait until all data from output watcher is received (QuitTask will be // fired on watcher thread). ui_test_utils::RunMessageLoop(); BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&ProcessProxyTest::EndRegistryTest, base::Unretained(this))); // Wait until we clean up the process proxy. ui_test_utils::RunMessageLoop(); } scoped_ptr<TestRunner> test_runner_; private: ProcessProxyRegistry* registry_; pid_t pid_; }; // Test will open new process that will run cat command, and verify data we // write to process gets echoed back. IN_PROC_BROWSER_TEST_F(ProcessProxyTest, RegistryTest) { test_runner_.reset(new RegistryTestRunner()); RunTest(); } // Open new process, then kill it. Verifiy that we detect when the process dies. IN_PROC_BROWSER_TEST_F(ProcessProxyTest, RegistryNotifiedOnProcessExit) { test_runner_.reset(new RegistryNotifiedOnProcessExitTestRunner()); RunTest(); } // Test verifies that \003 message send to process is processed as SigInt. // Timing out on the waterfall: http://crbug.com/115064 IN_PROC_BROWSER_TEST_F(ProcessProxyTest, DISABLED_SigInt) { test_runner_.reset(new SigIntTestRunner()); RunTest(); } <|endoftext|>
<commit_before>#include "pjobrunnerpool.h" #include <assert.h> #include <iostream> PJobRunnerPool::PJobRunnerPool() { connect(&m_scanner, SIGNAL(found_pjob_runner(PJobRunnerSessionWrapper*)), this, SLOT(found_pjob_runner(PJobRunnerSessionWrapper*))); connect(&m_scanner, SIGNAL(finished_scanning()), this, SLOT(search_finished())); connect(&m_scanner, SIGNAL(probing_host(QHostAddress)), this, SLOT(scanner_is_probing(QHostAddress))); } PJobRunnerPool& PJobRunnerPool::instance(){ static PJobRunnerPool pool; return pool; } QList<QHostAddress> PJobRunnerPool::known_pjob_runners() const{ return m_known_pjob_runners; } void PJobRunnerPool::start_search_network(const QNetworkInterface& i){ m_backup_list = m_known_pjob_runners; if(!m_scanner.isRunning()){ m_scanner.set_network_interface(i); emit network_scan_started(); m_scanner.start(); } } void PJobRunnerPool::stop_search_network(){ m_scanner.stop_scan(); } void PJobRunnerPool::found_pjob_runner(PJobRunnerSessionWrapper* session){ QHostAddress new_peer = session->peer(); if(!m_info_sessions.contains(new_peer)){ m_info_sessions[new_peer] = session; }else delete session; if(!m_known_pjob_runners.contains(new_peer)){ m_known_pjob_runners.append(new_peer); emit found_new_pjob_runner(new_peer); } } void PJobRunnerPool::search_finished(){ foreach(QHostAddress host, m_backup_list){ if(!m_known_pjob_runners.contains(host)) emit lost_pjob_runner(host); } emit network_scan_finished(); } void PJobRunnerPool::scanner_is_probing(QHostAddress host){ emit probing_host(host); } QString PJobRunnerPool::hostname(QHostAddress host) const{ assert(m_info_sessions.contains(host)); return m_info_sessions[host]->hostname(); } QString PJobRunnerPool::platform(QHostAddress host) const{ assert(m_info_sessions.contains(host)); return m_info_sessions[host]->platform(); } unsigned int PJobRunnerPool::max_thread_count() const{ unsigned int count = 0; foreach(QHostAddress host, m_known_pjob_runners){ try{ PJobRunnerSessionWrapper session(host); count += session.max_process_count(); }catch(...){ std::cout << "Ups!" << std::endl; } } return count; } bool PJobRunnerPool::is_scanning(){ return m_scanner.isRunning(); } unsigned int PJobRunnerPool::max_thread_count_for_host(QHostAddress host) const{ QHash<QHostAddress, PJobRunnerSessionWrapper*>::const_iterator it = m_info_sessions.find(host); if(it == m_info_sessions.end()){ try{ PJobRunnerSessionWrapper session(host); return session.max_process_count(); }catch(...){ std::cout << "Ups2!" << std::endl; } } return it.value()->max_process_count(); } unsigned int PJobRunnerPool::thread_count_for_host(QHostAddress host) const{ unsigned int retries = 0; while(retries < 3){ try{ QHash<QHostAddress, PJobRunnerSessionWrapper*>::const_iterator it = m_info_sessions.find(host); if(it == m_info_sessions.end()){ PJobRunnerSessionWrapper session(host); return session.process_count(); } return it.value()->process_count(); }catch(LostConnectionException e){ retries++; } } return 0; } unsigned int PJobRunnerPool::thread_count() const{ unsigned int count=0; foreach(QHostAddress host, known_pjob_runners()){ count += thread_count_for_host(host); } return count; } void PJobRunnerPool::remove(QHostAddress host){ m_known_pjob_runners.removeOne(host); m_info_sessions.remove(host); } <commit_msg>Uncaught exception fix.<commit_after>#include "pjobrunnerpool.h" #include <assert.h> #include <iostream> PJobRunnerPool::PJobRunnerPool() { connect(&m_scanner, SIGNAL(found_pjob_runner(PJobRunnerSessionWrapper*)), this, SLOT(found_pjob_runner(PJobRunnerSessionWrapper*))); connect(&m_scanner, SIGNAL(finished_scanning()), this, SLOT(search_finished())); connect(&m_scanner, SIGNAL(probing_host(QHostAddress)), this, SLOT(scanner_is_probing(QHostAddress))); } PJobRunnerPool& PJobRunnerPool::instance(){ static PJobRunnerPool pool; return pool; } QList<QHostAddress> PJobRunnerPool::known_pjob_runners() const{ return m_known_pjob_runners; } void PJobRunnerPool::start_search_network(const QNetworkInterface& i){ m_backup_list = m_known_pjob_runners; if(!m_scanner.isRunning()){ m_scanner.set_network_interface(i); emit network_scan_started(); m_scanner.start(); } } void PJobRunnerPool::stop_search_network(){ m_scanner.stop_scan(); } void PJobRunnerPool::found_pjob_runner(PJobRunnerSessionWrapper* session){ QHostAddress new_peer = session->peer(); if(!m_info_sessions.contains(new_peer)){ m_info_sessions[new_peer] = session; }else delete session; if(!m_known_pjob_runners.contains(new_peer)){ m_known_pjob_runners.append(new_peer); emit found_new_pjob_runner(new_peer); } } void PJobRunnerPool::search_finished(){ foreach(QHostAddress host, m_backup_list){ if(!m_known_pjob_runners.contains(host)) emit lost_pjob_runner(host); } emit network_scan_finished(); } void PJobRunnerPool::scanner_is_probing(QHostAddress host){ emit probing_host(host); } QString PJobRunnerPool::hostname(QHostAddress host) const{ assert(m_info_sessions.contains(host)); return m_info_sessions[host]->hostname(); } QString PJobRunnerPool::platform(QHostAddress host) const{ assert(m_info_sessions.contains(host)); return m_info_sessions[host]->platform(); } unsigned int PJobRunnerPool::max_thread_count() const{ unsigned int count = 0; foreach(QHostAddress host, m_known_pjob_runners){ try{ PJobRunnerSessionWrapper session(host); count += session.max_process_count(); }catch(...){ std::cout << "Ups!" << std::endl; } } return count; } bool PJobRunnerPool::is_scanning(){ return m_scanner.isRunning(); } unsigned int PJobRunnerPool::max_thread_count_for_host(QHostAddress host) const{ QHash<QHostAddress, PJobRunnerSessionWrapper*>::const_iterator it = m_info_sessions.find(host); if(it == m_info_sessions.end()){ try{ PJobRunnerSessionWrapper session(host); return session.max_process_count(); }catch(...){ std::cout << "Ups2!" << std::endl; } } return it.value()->max_process_count(); } unsigned int PJobRunnerPool::thread_count_for_host(QHostAddress host) const{ unsigned int retries = 0; while(retries < 3){ try{ QHash<QHostAddress, PJobRunnerSessionWrapper*>::const_iterator it = m_info_sessions.find(host); if(it == m_info_sessions.end()){ PJobRunnerSessionWrapper session(host); return session.process_count(); } return it.value()->process_count(); }catch(LostConnectionException e){ retries++; }catch(QString s){ retries++; } } return 0; } unsigned int PJobRunnerPool::thread_count() const{ unsigned int count=0; foreach(QHostAddress host, known_pjob_runners()){ count += thread_count_for_host(host); } return count; } void PJobRunnerPool::remove(QHostAddress host){ m_known_pjob_runners.removeOne(host); m_info_sessions.remove(host); } <|endoftext|>
<commit_before>#include "sajson.h" #include <assert.h> using namespace sajson; inline bool success(const document& doc) { if (!doc.is_valid()) { fprintf(stderr, "%s\n", doc.get_error_message_as_cstring()); return false; } return true; } struct jsonstats { jsonstats() : null_count(0) , false_count(0) , true_count(0) , number_count(0) , object_count(0) , array_count(0) , string_count(0) , total_string_length(0) , total_array_length(0) , total_object_length(0) , total_number_value(0) {} size_t null_count; size_t false_count; size_t true_count; size_t number_count; size_t object_count; size_t array_count; size_t string_count; size_t total_string_length; size_t total_array_length; size_t total_object_length; double total_number_value; }; void traverse(jsonstats& stats, const sajson::value& node) { using namespace sajson; switch (node.get_type()) { case TYPE_NULL: ++stats.null_count; break; case TYPE_FALSE: ++stats.false_count; break; case TYPE_TRUE: ++stats.true_count; break; case TYPE_ARRAY: { ++stats.array_count; auto length = node.get_length(); stats.total_array_length += length; for (size_t i = 0; i < length; ++i) { traverse(stats, node.get_array_element(i)); } break; } case TYPE_OBJECT: { ++stats.object_count; auto length = node.get_length(); stats.total_object_length += length; for (auto i = 0u; i < length; ++i) { traverse(stats, node.get_object_value(i)); } break; } case TYPE_STRING: ++stats.string_count; stats.total_string_length += node.get_string_length(); break; case TYPE_DOUBLE: case TYPE_INTEGER: ++stats.number_count; stats.total_number_value += node.get_number_value(); break; default: assert(false && "unknown node type"); } } int main(int argc, char** argv) { FILE* file = fopen(argv[1], "rb"); if (!file) { fprintf(stderr, "Failed to open file\n"); return 1; } fseek(file, 0, SEEK_END); size_t length = ftell(file); fseek(file, 0, SEEK_SET); // "leak" char* buffer = new char[length]; if (length != fread(buffer, 1, length, file)) { fprintf(stderr, "Failed to read entire file\n"); return 1; } fclose(file); const sajson::document& document = sajson::parse( sajson::dynamic_allocation(), mutable_string_view(length, buffer)); if (!success(document)) { return 1; } jsonstats stats; traverse(stats, document.get_root()); printf("object count: %d\n", (int)stats.object_count); printf("array count: %d\n", (int)stats.array_count); printf("bool count: %d\n", (int)stats.true_count + (int)stats.false_count); printf("number count: %d\n", (int)stats.number_count); printf("string count: %d\n", (int)stats.string_count); printf("null count: %d\n", (int)stats.null_count); } <commit_msg>Fix memory leaks<commit_after>#include "sajson.h" #include <assert.h> using namespace sajson; inline bool success(const document& doc) { if (!doc.is_valid()) { fprintf(stderr, "%s\n", doc.get_error_message_as_cstring()); return false; } return true; } struct jsonstats { jsonstats() : null_count(0) , false_count(0) , true_count(0) , number_count(0) , object_count(0) , array_count(0) , string_count(0) , total_string_length(0) , total_array_length(0) , total_object_length(0) , total_number_value(0) {} size_t null_count; size_t false_count; size_t true_count; size_t number_count; size_t object_count; size_t array_count; size_t string_count; size_t total_string_length; size_t total_array_length; size_t total_object_length; double total_number_value; }; void traverse(jsonstats& stats, const sajson::value& node) { using namespace sajson; switch (node.get_type()) { case TYPE_NULL: ++stats.null_count; break; case TYPE_FALSE: ++stats.false_count; break; case TYPE_TRUE: ++stats.true_count; break; case TYPE_ARRAY: { ++stats.array_count; auto length = node.get_length(); stats.total_array_length += length; for (size_t i = 0; i < length; ++i) { traverse(stats, node.get_array_element(i)); } break; } case TYPE_OBJECT: { ++stats.object_count; auto length = node.get_length(); stats.total_object_length += length; for (auto i = 0u; i < length; ++i) { traverse(stats, node.get_object_value(i)); } break; } case TYPE_STRING: ++stats.string_count; stats.total_string_length += node.get_string_length(); break; case TYPE_DOUBLE: case TYPE_INTEGER: ++stats.number_count; stats.total_number_value += node.get_number_value(); break; default: assert(false && "unknown node type"); } } int main(int argc, char** argv) { FILE* file = fopen(argv[1], "rb"); if (!file) { fprintf(stderr, "Failed to open file\n"); return 1; } fseek(file, 0, SEEK_END); size_t length = ftell(file); fseek(file, 0, SEEK_SET); char* buffer = new char[length]; if (length != fread(buffer, 1, length, file)) { fclose(file); delete[] buffer; fprintf(stderr, "Failed to read entire file\n"); return 1; } fclose(file); const sajson::document& document = sajson::parse( sajson::dynamic_allocation(), mutable_string_view(length, buffer)); if (!success(document)) { fclose(file); delete[] buffer; return 1; } jsonstats stats; traverse(stats, document.get_root()); printf("object count: %d\n", (int)stats.object_count); printf("array count: %d\n", (int)stats.array_count); printf("bool count: %d\n", (int)stats.true_count + (int)stats.false_count); printf("number count: %d\n", (int)stats.number_count); printf("string count: %d\n", (int)stats.string_count); printf("null count: %d\n", (int)stats.null_count); fclose(file); delete[] buffer; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "base/file_util.h" #include "base/path_service.h" #include "base/perftimer.h" #include "base/time.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" using base::TimeDelta; namespace { // Returns the directory name where the "typical" user data is that we use for // testing. FilePath ComputeTypicalUserDataSource() { FilePath source_history_file; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &source_history_file)); source_history_file = source_history_file.AppendASCII("profiles") .AppendASCII("typical_history"); return source_history_file; } class NewTabUIStartupTest : public UITest { public: NewTabUIStartupTest() { show_window_ = true; } void SetUp() {} void TearDown() {} static const int kNumCycles = 5; void PrintTimings(const char* label, TimeDelta timings[kNumCycles], bool important) { std::string times; for (int i = 0; i < kNumCycles; ++i) StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF()); PrintResultList("new_tab", "", label, times, "ms", important); } // Run the test, by bringing up a browser and timing the new tab startup. // |want_warm| is true if we should output warm-disk timings, false if // we should report cold timings. void RunStartupTest(const char* label, bool want_warm, bool important) { // Install the location of the test profile file. set_template_user_data(ComputeTypicalUserDataSource().ToWStringHack()); TimeDelta timings[kNumCycles]; for (int i = 0; i < kNumCycles; ++i) { UITest::SetUp(); // Switch to the "new tab" tab, which should be any new tab after the // first (the first is about:blank). BrowserProxy* window = automation()->GetBrowserWindow(0); ASSERT_TRUE(window); int tab_count = -1; ASSERT_TRUE(window->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Hit ctl-t and wait for the tab to load. window->ApplyAccelerator(IDC_NEW_TAB); ASSERT_TRUE(window->WaitForTabCountToBecome(2, 5000)); int load_time; ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); timings[i] = TimeDelta::FromMilliseconds(load_time); if (want_warm) { // Bring up a second tab, now that we've already shown one tab. window->ApplyAccelerator(IDC_NEW_TAB); ASSERT_TRUE(window->WaitForTabCountToBecome(3, 5000)); ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); timings[i] = TimeDelta::FromMilliseconds(load_time); } delete window; UITest::TearDown(); } PrintTimings(label, timings, important); } }; // TODO(pamg): run these tests with a reference build? TEST_F(NewTabUIStartupTest, PerfCold) { RunStartupTest("tab_cold", false /* not cold */, true /* important */); } TEST_F(NewTabUIStartupTest, DISABLED_PerfWarm) { RunStartupTest("tab_warm", true /* cold */, false /* not important */); } } // namespace <commit_msg>Fix errant comments on parameters. BUG=none TEST=none Review URL: http://codereview.chromium.org/112062<commit_after>// Copyright (c) 2006-2008 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 "base/file_util.h" #include "base/path_service.h" #include "base/perftimer.h" #include "base/time.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" using base::TimeDelta; namespace { // Returns the directory name where the "typical" user data is that we use for // testing. FilePath ComputeTypicalUserDataSource() { FilePath source_history_file; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &source_history_file)); source_history_file = source_history_file.AppendASCII("profiles") .AppendASCII("typical_history"); return source_history_file; } class NewTabUIStartupTest : public UITest { public: NewTabUIStartupTest() { show_window_ = true; } void SetUp() {} void TearDown() {} static const int kNumCycles = 5; void PrintTimings(const char* label, TimeDelta timings[kNumCycles], bool important) { std::string times; for (int i = 0; i < kNumCycles; ++i) StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF()); PrintResultList("new_tab", "", label, times, "ms", important); } // Run the test, by bringing up a browser and timing the new tab startup. // |want_warm| is true if we should output warm-disk timings, false if // we should report cold timings. void RunStartupTest(const char* label, bool want_warm, bool important) { // Install the location of the test profile file. set_template_user_data(ComputeTypicalUserDataSource().ToWStringHack()); TimeDelta timings[kNumCycles]; for (int i = 0; i < kNumCycles; ++i) { UITest::SetUp(); // Switch to the "new tab" tab, which should be any new tab after the // first (the first is about:blank). BrowserProxy* window = automation()->GetBrowserWindow(0); ASSERT_TRUE(window); int tab_count = -1; ASSERT_TRUE(window->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Hit ctl-t and wait for the tab to load. window->ApplyAccelerator(IDC_NEW_TAB); ASSERT_TRUE(window->WaitForTabCountToBecome(2, 5000)); int load_time; ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); timings[i] = TimeDelta::FromMilliseconds(load_time); if (want_warm) { // Bring up a second tab, now that we've already shown one tab. window->ApplyAccelerator(IDC_NEW_TAB); ASSERT_TRUE(window->WaitForTabCountToBecome(3, 5000)); ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); timings[i] = TimeDelta::FromMilliseconds(load_time); } delete window; UITest::TearDown(); } PrintTimings(label, timings, important); } }; // TODO(pamg): run these tests with a reference build? TEST_F(NewTabUIStartupTest, PerfCold) { RunStartupTest("tab_cold", false /* cold */, true /* important */); } TEST_F(NewTabUIStartupTest, DISABLED_PerfWarm) { RunStartupTest("tab_warm", true /* warm */, false /* not important */); } } // namespace <|endoftext|>
<commit_before>#include <unistd.h> #include <cstring> #include <fstream> #include <linux/limits.h> #include "Macros.h" #include "Environment.h" namespace magpie { gc<String> getCoreLibDir() { char* relativePath[PATH_MAX]; int len = readlink("/proc/self/exe", relativePath, PATH_MAX - 1); ASSERT(len != -1, "Executable path too long."); relativePath[len] = '\0'; // Cut off file name from path char* lastSep = NULL; for (char* c = relativePath; *c != '\0'; c++) { if (*c == '/') { lastSep = c; } } if (lastSep != NULL) { *lastSep = '\0'; } // Find the magpie main directory relative to the executable. // TODO(bob): Hack. Try to work from the build directory too. if (strstr(relativePath, "1/out") != 0) { strncat(relativePath, "/../../..", PATH_MAX); } // Add core library directory. strncat(relativePath, "/core", PATH_MAX); // Canonicalize the path. char path[PATH_MAX]; realpath(relativePath, path); return String::create(path); } // Reads a file from the given path into a String. gc<String> readFile(gc<String> path) { // TODO(bob): Use platform-native API for this? using namespace std; ifstream stream(path->cString()); if (stream.fail()) return gc<String>(); // From: http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring. string str; // Allocate a std::string big enough for the file. stream.seekg(0, ios::end); str.reserve(stream.tellg()); stream.seekg(0, ios::beg); // Read it in. str.assign((istreambuf_iterator<char>(stream)), istreambuf_iterator<char>()); return String::create(str.c_str()); } }<commit_msg>fix pointer type<commit_after>#include <unistd.h> #include <cstring> #include <fstream> #include <linux/limits.h> #include "Macros.h" #include "Environment.h" namespace magpie { gc<String> getCoreLibDir() { char relativePath[PATH_MAX]; int len = readlink("/proc/self/exe", relativePath, PATH_MAX - 1); ASSERT(len != -1, "Executable path too long."); relativePath[len] = '\0'; // Cut off file name from path char* lastSep = NULL; for (char* c = relativePath; *c != '\0'; c++) { if (*c == '/') { lastSep = c; } } if (lastSep != NULL) { *lastSep = '\0'; } // Find the magpie main directory relative to the executable. // TODO(bob): Hack. Try to work from the build directory too. if (strstr(relativePath, "1/out") != 0) { strncat(relativePath, "/../../..", PATH_MAX); } // Add core library directory. strncat(relativePath, "/core", PATH_MAX); // Canonicalize the path. char path[PATH_MAX]; realpath(relativePath, path); return String::create(path); } // Reads a file from the given path into a String. gc<String> readFile(gc<String> path) { // TODO(bob): Use platform-native API for this? using namespace std; ifstream stream(path->cString()); if (stream.fail()) return gc<String>(); // From: http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring. string str; // Allocate a std::string big enough for the file. stream.seekg(0, ios::end); str.reserve(stream.tellg()); stream.seekg(0, ios::beg); // Read it in. str.assign((istreambuf_iterator<char>(stream)), istreambuf_iterator<char>()); return String::create(str.c_str()); } } <|endoftext|>
<commit_before><commit_msg>fix type error build error in android react native<commit_after><|endoftext|>
<commit_before>/* * Contact groups model * This file is based on TelepathyQt4Yell Models * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com> * * 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 <TelepathyQt4/ContactManager> #include <TelepathyQt4/Contact> #include <TelepathyQt4/PendingReady> #include "groups-model.h" #include "groups-model-item.h" #include "proxy-tree-node.h" #include "accounts-model.h" #include "contact-model-item.h" #include <KDebug> struct GroupsModel::Private { Private(AccountsModel *am) : mAM(am) { } TreeNode *node(const QModelIndex &index) const; AccountsModel *mAM; TreeNode *mTree; }; TreeNode *GroupsModel::Private::node(const QModelIndex &index) const { TreeNode *node = reinterpret_cast<TreeNode *>(index.internalPointer()); return node ? node : mTree; } GroupsModel::GroupsModel(AccountsModel *am, QObject *parent) : QAbstractItemModel(parent), mPriv(new GroupsModel::Private(am)) { mPriv->mTree = new TreeNode; connect(mPriv->mTree, SIGNAL(changed(TreeNode*)), SLOT(onItemChanged(TreeNode*))); connect(mPriv->mTree, SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)), SLOT(onItemsAdded(TreeNode*,QList<TreeNode*>))); connect(mPriv->mTree, SIGNAL(childrenRemoved(TreeNode*,int,int)), SLOT(onItemsRemoved(TreeNode*,int,int))); loadAccountsModel(); QHash<int, QByteArray> roles; roles[GroupNameRole] = "groupName"; setRoleNames(roles); } GroupsModel::~GroupsModel() { delete mPriv->mTree; delete mPriv; } int GroupsModel::columnCount(const QModelIndex &parent) const { return 1; } int GroupsModel::rowCount(const QModelIndex &parent) const { return mPriv->node(parent)->size(); } QVariant GroupsModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } return mPriv->node(index)->data(role); } Qt::ItemFlags GroupsModel::flags(const QModelIndex &index) const { if (index.isValid()) { return Qt::ItemIsEnabled; } return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } bool GroupsModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid()) { mPriv->node(index)->setData(role, value); } return false; } QModelIndex GroupsModel::index(int row, int column, const QModelIndex &parent) const { TreeNode *parentNode = mPriv->node(parent); if (row < parentNode->size()) { return createIndex(row, column, parentNode->childAt(row)); } return QModelIndex(); } QModelIndex GroupsModel::index(TreeNode *node) const { if (node->parent()) { return createIndex(node->parent()->indexOf(node), 0, node); } else { return QModelIndex(); } } QModelIndex GroupsModel::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } TreeNode *currentNode = mPriv->node(index); if (currentNode->parent()) { return GroupsModel::index(currentNode->parent()); } else { // no parent: return root node return QModelIndex(); } } void GroupsModel::onItemChanged(TreeNode* node) { emit dataChanged(index(node), index(node)); } void GroupsModel::onItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes) { QModelIndex parentIndex = index(parent); int currentSize = rowCount(parentIndex); beginInsertRows(parentIndex, currentSize, currentSize + nodes.size() - 1); foreach (TreeNode *node, nodes) { parent->addChild(node); } endInsertRows(); } void GroupsModel::onItemsRemoved(TreeNode *parent, int first, int last) { kDebug(); QModelIndex parentIndex = index(parent); QList<TreeNode *> removedItems; beginRemoveRows(parentIndex, first, last); for (int i = last; i >= first; i--) { parent->childAt(i)->remove(); } endRemoveRows(); } void GroupsModel::onSourceItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes) { kDebug() << "Adding" << nodes.size() << "nodes..."; QModelIndex parentIndex = index(parent); int currentSize = rowCount(parentIndex); foreach (TreeNode *node, nodes) { ContactModelItem *contactItem = qobject_cast<ContactModelItem*>(node); QStringList groups = contactItem->contact()->groups(); addContactToGroups(contactItem, groups); } } void GroupsModel::onSourceItemsRemoved(TreeNode* parent, int first, int last) { } void GroupsModel::loadAccountsModel() { for (int x = 0; x < mPriv->mAM->rowCount(); x++) { QModelIndex parent = mPriv->mAM->index(x, 0); for (int i = 0; i < mPriv->mAM->rowCount(parent); i++) { if (mPriv->mAM->data(mPriv->mAM->index(i, 0, parent), AccountsModel::ItemRole).userType() == qMetaTypeId<ContactModelItem*>()) { QStringList groups = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent), AccountsModel::GroupsRole).toStringList(); ContactModelItem *contactItem = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent), AccountsModel::ItemRole).value<ContactModelItem*>(); addContactToGroups(contactItem, groups); } } //we need to connect accounts onItemsAdded/onItemsRemoved to watch for changes //and process them directly (directly add/remove the nodes) AccountsModelItem *accountItem = mPriv->mAM->data(parent, AccountsModel::ItemRole).value<AccountsModelItem*>(); connect(accountItem, SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)), this, SLOT(onSourceItemsAdded(TreeNode*,QList<TreeNode*>))); connect(accountItem, SIGNAL(childrenRemoved(TreeNode*,int,int)), this, SLOT(onSourceItemsRemoved(TreeNode*,int,int))); kDebug() << "Connecting" << accountItem->account()->displayName() << "to groups model"; } } void GroupsModel::onContactAddedToGroup(const QString& group) { addContactToGroups(qobject_cast<ProxyTreeNode*>(sender()), group); } void GroupsModel::onContactRemovedFromGroup(const QString& group) { removeContactFromGroup(qobject_cast<ProxyTreeNode*>(sender()), group); } void GroupsModel::removeContactFromGroup(ProxyTreeNode* proxyNode, const QString& group) { kDebug() << "Removing contact from" << group; QStringList contactGroups = proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->groups(); kDebug() << "Left groups are:" << contactGroups; contactGroups.removeOne(group); //if the contact really is in that group, remove it if (qobject_cast<GroupsModelItem*>(proxyNode->parent())->groupName() == group) { disconnect(proxyNode, SIGNAL(contactAddedToGroup(QString)), 0, 0); disconnect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)), 0, 0); //if the the contact has no groups left, then put it in Ungroupped group if (contactGroups.isEmpty()) { addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), contactGroups); } // beginRemoveRows(index(proxyNode->parent()), proxyNode->parent()->indexOf(proxyNode), proxyNode->parent()->indexOf(proxyNode)); qobject_cast<GroupsModelItem*>(proxyNode->parent())->removeProxyContact(proxyNode); // endRemoveRows(); } } void GroupsModel::addContactToGroups(ProxyTreeNode* proxyNode, const QString& group) { addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), group); } void GroupsModel::addContactToGroups(ContactModelItem* contactItem, const QString& group) { addContactToGroups(contactItem, QStringList(group)); } void GroupsModel::addContactToGroups(ContactModelItem* contactItem, QStringList groups) { kDebug() << "Contact groups:" << groups; //check if the contact is in Ungroupped group, if it is, it needs to be removed from there bool checkUngroupped = false; //if the contact has no groups, create an 'Ungroupped' group for it if (groups.isEmpty()) { groups.append("Ungroupped"); //FIXME i18n } else { checkUngroupped = true; } groups.removeDuplicates(); foreach (QString group, groups) { bool groupExists = false; GroupsModelItem *groupItem; kDebug() << "Adding" << contactItem->contact()->alias() << "to" << group; //check if the group already exists first for (int i = 0; i < mPriv->mTree->children().size(); i++) { // foreach (GroupsModelItem *savedGroupItem, mPriv->mTree->children()) { GroupsModelItem *savedGroupItem = qobject_cast<GroupsModelItem*>(mPriv->mTree->childAt(i)); if (savedGroupItem->groupName() == group) { groupExists = true; kDebug() << "Existing group found for" << group; groupItem = savedGroupItem; if (!checkUngroupped) { break; } } if (checkUngroupped) { if (savedGroupItem->groupName() == "Ungroupped") { for (int i = 0; i < savedGroupItem->size(); i++) { ProxyTreeNode *tmpNode = qobject_cast<ProxyTreeNode*>(savedGroupItem->childAt(i)); if (tmpNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->id() == contactItem->contact()->id()) { removeContactFromGroup(tmpNode, QString("Ungroupped")); if (groupExists) { break; } } } } } } if (!groupExists) { kDebug() << "Creating new group for" << group; groupItem = new GroupsModelItem(group); onItemsAdded(mPriv->mTree, QList<TreeNode *>() << groupItem); } ProxyTreeNode *proxyNode = new ProxyTreeNode(contactItem); groupItem->addProxyContact(proxyNode); connect(proxyNode, SIGNAL(contactAddedToGroup(QString)), this, SLOT(onContactAddedToGroup(QString))); connect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)), this, SLOT(onContactRemovedFromGroup(QString))); } } <commit_msg>Fix typo<commit_after>/* * Contact groups model * This file is based on TelepathyQt4Yell Models * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com> * * 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 <TelepathyQt4/ContactManager> #include <TelepathyQt4/Contact> #include <TelepathyQt4/PendingReady> #include "groups-model.h" #include "groups-model-item.h" #include "proxy-tree-node.h" #include "accounts-model.h" #include "contact-model-item.h" #include <KDebug> struct GroupsModel::Private { Private(AccountsModel *am) : mAM(am) { } TreeNode *node(const QModelIndex &index) const; AccountsModel *mAM; TreeNode *mTree; }; TreeNode *GroupsModel::Private::node(const QModelIndex &index) const { TreeNode *node = reinterpret_cast<TreeNode *>(index.internalPointer()); return node ? node : mTree; } GroupsModel::GroupsModel(AccountsModel *am, QObject *parent) : QAbstractItemModel(parent), mPriv(new GroupsModel::Private(am)) { mPriv->mTree = new TreeNode; connect(mPriv->mTree, SIGNAL(changed(TreeNode*)), SLOT(onItemChanged(TreeNode*))); connect(mPriv->mTree, SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)), SLOT(onItemsAdded(TreeNode*,QList<TreeNode*>))); connect(mPriv->mTree, SIGNAL(childrenRemoved(TreeNode*,int,int)), SLOT(onItemsRemoved(TreeNode*,int,int))); loadAccountsModel(); QHash<int, QByteArray> roles; roles[GroupNameRole] = "groupName"; setRoleNames(roles); } GroupsModel::~GroupsModel() { delete mPriv->mTree; delete mPriv; } int GroupsModel::columnCount(const QModelIndex &parent) const { return 1; } int GroupsModel::rowCount(const QModelIndex &parent) const { return mPriv->node(parent)->size(); } QVariant GroupsModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } return mPriv->node(index)->data(role); } Qt::ItemFlags GroupsModel::flags(const QModelIndex &index) const { if (index.isValid()) { return Qt::ItemIsEnabled; } return QAbstractItemModel::flags(index) | Qt::ItemIsEditable; } bool GroupsModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (index.isValid()) { mPriv->node(index)->setData(role, value); } return false; } QModelIndex GroupsModel::index(int row, int column, const QModelIndex &parent) const { TreeNode *parentNode = mPriv->node(parent); if (row < parentNode->size()) { return createIndex(row, column, parentNode->childAt(row)); } return QModelIndex(); } QModelIndex GroupsModel::index(TreeNode *node) const { if (node->parent()) { return createIndex(node->parent()->indexOf(node), 0, node); } else { return QModelIndex(); } } QModelIndex GroupsModel::parent(const QModelIndex &index) const { if (!index.isValid()) { return QModelIndex(); } TreeNode *currentNode = mPriv->node(index); if (currentNode->parent()) { return GroupsModel::index(currentNode->parent()); } else { // no parent: return root node return QModelIndex(); } } void GroupsModel::onItemChanged(TreeNode* node) { emit dataChanged(index(node), index(node)); } void GroupsModel::onItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes) { QModelIndex parentIndex = index(parent); int currentSize = rowCount(parentIndex); beginInsertRows(parentIndex, currentSize, currentSize + nodes.size() - 1); foreach (TreeNode *node, nodes) { parent->addChild(node); } endInsertRows(); } void GroupsModel::onItemsRemoved(TreeNode *parent, int first, int last) { kDebug(); QModelIndex parentIndex = index(parent); QList<TreeNode *> removedItems; beginRemoveRows(parentIndex, first, last); for (int i = last; i >= first; i--) { parent->childAt(i)->remove(); } endRemoveRows(); } void GroupsModel::onSourceItemsAdded(TreeNode *parent, const QList<TreeNode *> &nodes) { kDebug() << "Adding" << nodes.size() << "nodes..."; QModelIndex parentIndex = index(parent); int currentSize = rowCount(parentIndex); foreach (TreeNode *node, nodes) { ContactModelItem *contactItem = qobject_cast<ContactModelItem*>(node); QStringList groups = contactItem->contact()->groups(); addContactToGroups(contactItem, groups); } } void GroupsModel::onSourceItemsRemoved(TreeNode* parent, int first, int last) { } void GroupsModel::loadAccountsModel() { for (int x = 0; x < mPriv->mAM->rowCount(); x++) { QModelIndex parent = mPriv->mAM->index(x, 0); for (int i = 0; i < mPriv->mAM->rowCount(parent); i++) { if (mPriv->mAM->data(mPriv->mAM->index(i, 0, parent), AccountsModel::ItemRole).userType() == qMetaTypeId<ContactModelItem*>()) { QStringList groups = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent), AccountsModel::GroupsRole).toStringList(); ContactModelItem *contactItem = mPriv->mAM->data(mPriv->mAM->index(i, 0, parent), AccountsModel::ItemRole).value<ContactModelItem*>(); addContactToGroups(contactItem, groups); } } //we need to connect accounts onItemsAdded/onItemsRemoved to watch for changes //and process them directly (directly add/remove the nodes) AccountsModelItem *accountItem = mPriv->mAM->data(parent, AccountsModel::ItemRole).value<AccountsModelItem*>(); connect(accountItem, SIGNAL(childrenAdded(TreeNode*,QList<TreeNode*>)), this, SLOT(onSourceItemsAdded(TreeNode*,QList<TreeNode*>))); connect(accountItem, SIGNAL(childrenRemoved(TreeNode*,int,int)), this, SLOT(onSourceItemsRemoved(TreeNode*,int,int))); kDebug() << "Connecting" << accountItem->account()->displayName() << "to groups model"; } } void GroupsModel::onContactAddedToGroup(const QString& group) { addContactToGroups(qobject_cast<ProxyTreeNode*>(sender()), group); } void GroupsModel::onContactRemovedFromGroup(const QString& group) { removeContactFromGroup(qobject_cast<ProxyTreeNode*>(sender()), group); } void GroupsModel::removeContactFromGroup(ProxyTreeNode* proxyNode, const QString& group) { kDebug() << "Removing contact from" << group; QStringList contactGroups = proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->groups(); kDebug() << "Left groups are:" << contactGroups; contactGroups.removeOne(group); //if the contact really is in that group, remove it if (qobject_cast<GroupsModelItem*>(proxyNode->parent())->groupName() == group) { disconnect(proxyNode, SIGNAL(contactAddedToGroup(QString)), 0, 0); disconnect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)), 0, 0); //if the the contact has no groups left, then put it in Ungrouped group if (contactGroups.isEmpty()) { addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), contactGroups); } // beginRemoveRows(index(proxyNode->parent()), proxyNode->parent()->indexOf(proxyNode), proxyNode->parent()->indexOf(proxyNode)); qobject_cast<GroupsModelItem*>(proxyNode->parent())->removeProxyContact(proxyNode); // endRemoveRows(); } } void GroupsModel::addContactToGroups(ProxyTreeNode* proxyNode, const QString& group) { addContactToGroups(proxyNode->data(AccountsModel::ItemRole).value<ContactModelItem*>(), group); } void GroupsModel::addContactToGroups(ContactModelItem* contactItem, const QString& group) { addContactToGroups(contactItem, QStringList(group)); } void GroupsModel::addContactToGroups(ContactModelItem* contactItem, QStringList groups) { kDebug() << "Contact groups:" << groups; //check if the contact is in Ungrouped group, if it is, it needs to be removed from there bool checkUngrouped = false; //if the contact has no groups, create an 'Ungrouped' group for it if (groups.isEmpty()) { groups.append("Ungrouped"); //FIXME i18n } else { checkUngrouped = true; } groups.removeDuplicates(); foreach (QString group, groups) { bool groupExists = false; GroupsModelItem *groupItem; kDebug() << "Adding" << contactItem->contact()->alias() << "to" << group; //check if the group already exists first for (int i = 0; i < mPriv->mTree->children().size(); i++) { // foreach (GroupsModelItem *savedGroupItem, mPriv->mTree->children()) { GroupsModelItem *savedGroupItem = qobject_cast<GroupsModelItem*>(mPriv->mTree->childAt(i)); if (savedGroupItem->groupName() == group) { groupExists = true; kDebug() << "Existing group found for" << group; groupItem = savedGroupItem; if (!checkUngrouped) { break; } } if (checkUngrouped) { if (savedGroupItem->groupName() == "Ungrouped") { for (int i = 0; i < savedGroupItem->size(); i++) { ProxyTreeNode *tmpNode = qobject_cast<ProxyTreeNode*>(savedGroupItem->childAt(i)); if (tmpNode->data(AccountsModel::ItemRole).value<ContactModelItem*>()->contact()->id() == contactItem->contact()->id()) { removeContactFromGroup(tmpNode, QString("Ungrouped")); if (groupExists) { break; } } } } } } if (!groupExists) { kDebug() << "Creating new group for" << group; groupItem = new GroupsModelItem(group); onItemsAdded(mPriv->mTree, QList<TreeNode *>() << groupItem); } ProxyTreeNode *proxyNode = new ProxyTreeNode(contactItem); groupItem->addProxyContact(proxyNode); connect(proxyNode, SIGNAL(contactAddedToGroup(QString)), this, SLOT(onContactAddedToGroup(QString))); connect(proxyNode, SIGNAL(contactRemovedFromGroup(QString)), this, SLOT(onContactRemovedFromGroup(QString))); } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(URISUPPORT_HEADER_GUARD_1357924680) #define URISUPPORT_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <PlatformSupport/PlatformSupportDefinitions.hpp> #include <memory> #include <util/XMLURL.hpp> #include <XalanDOM/XalanDOMString.hpp> #include <PlatformSupport/XSLException.hpp> class XALAN_PLATFORMSUPPORT_EXPORT URISupport { public: #if defined(XALAN_NO_NAMESPACES) typedef auto_ptr<XMLURL> URLAutoPtrType; #else typedef std::auto_ptr<XMLURL> URLAutoPtrType; #endif /** * Determine the fully qualified URI for a string. * * @param urlString string to qualify * @return auto pointer to fully qualified URI */ static URLAutoPtrType getURLFromString(const XalanDOMString& urlString); /** * Determine the fully qualified URI for a string. * * @param urlString string to qualify * @param base base location for URI * @return auto pointer to fully qualified URI */ static URLAutoPtrType getURLFromString( const XalanDOMString& urlString, const XalanDOMString& base); /** * Normalizes the string passed in, replacing * \ with /. * * @param urlString string to qualify * @return a reference to the passed parameter */ static XalanDOMString& NormalizeURIText(XalanDOMString& uriString); class InvalidURIException : public XSLException { public: /** * Construct an InvalidURIException. * * @param theMessage the error message */ InvalidURIException(const XalanDOMString& theMessage); virtual ~InvalidURIException(); }; }; #endif // URISUPPORT_HEADER_GUARD_1357924680 <commit_msg>New functions.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(URISUPPORT_HEADER_GUARD_1357924680) #define URISUPPORT_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <PlatformSupport/PlatformSupportDefinitions.hpp> #include <memory> #include <util/XMLURL.hpp> #include <XalanDOM/XalanDOMString.hpp> #include <PlatformSupport/XSLException.hpp> class XALAN_PLATFORMSUPPORT_EXPORT URISupport { public: #if defined(XALAN_NO_NAMESPACES) typedef auto_ptr<XMLURL> URLAutoPtrType; #else typedef std::auto_ptr<XMLURL> URLAutoPtrType; #endif /** * Determine the fully qualified URI for a string. * * @param urlString string to qualify * @return auto pointer to fully qualified URI */ static URLAutoPtrType getURLFromString(const XalanDOMString& urlString); /** * Determine the fully qualified URI for a string. * * @param urlString string to qualify * @return string to fully qualified URI */ static XalanDOMString getURLStringFromString( const XalanDOMString& urlString); /** * Determine the fully qualified URI for a string. * * @param urlString string to qualify * @param base base location for URI * @return auto pointer to fully qualified URI */ static URLAutoPtrType getURLFromString( const XalanDOMString& urlString, const XalanDOMString& base); /** * Determine the fully qualified URI for a string. * * @param urlString string to qualify * @param base base location for URI * @return string to fully qualified URI */ static XalanDOMString getURLStringFromString( const XalanDOMString& urlString, const XalanDOMString& base); /** * Normalizes the string passed in, replacing * \ with /. * * @param urlString string to qualify * @return a reference to the passed parameter */ static XalanDOMString& NormalizeURIText(XalanDOMString& uriString); class InvalidURIException : public XSLException { public: /** * Construct an InvalidURIException. * * @param theMessage the error message */ InvalidURIException(const XalanDOMString& theMessage); virtual ~InvalidURIException(); }; }; #endif // URISUPPORT_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>#include "audio_facade.h" #include "audio_engine.h" #include "audio_handle_impl.h" #include "audio_emitter_behaviour.h" #include "halley/support/console.h" #include "halley/support/logger.h" #include "halley/core/resources/resources.h" #include "audio_event.h" using namespace Halley; AudioFacade::AudioFacade(AudioOutputAPI& o, SystemAPI& system) : output(o) , system(system) , running(false) , ownAudioThread(o.needsAudioThread()) { } AudioFacade::~AudioFacade() { AudioFacade::stopPlayback(); } void AudioFacade::setResources(Resources& res) { resources = &res; } void AudioFacade::init() { std::cout << ConsoleColour(Console::GREEN) << "\nInitializing audio...\n" << ConsoleColour(); std::cout << "Audio devices available:" << std::endl; int i = 0; for (auto& device: getAudioDevices()) { std::cout << "\t" << i++ << ": " << device->getName() << std::endl; } } void AudioFacade::deInit() { stopPlayback(); } Vector<std::unique_ptr<const AudioDevice>> AudioFacade::getAudioDevices() { return output.getAudioDevices(); } void AudioFacade::startPlayback(int deviceNumber) { if (started) { stopPlayback(); } auto devices = getAudioDevices(); if (int(devices.size()) > deviceNumber) { engine = std::make_unique<AudioEngine>(); AudioSpec format; format.bufferSize = 1024; format.format = AudioSampleFormat::Float; format.numChannels = 2; format.sampleRate = 48000; audioSpec = output.openAudioDevice(format, devices.at(deviceNumber).get(), [this]() { onNeedBuffer(); }); started = true; std::cout << "Audio Playback started.\n"; std::cout << "\tDevice: " << devices.at(deviceNumber)->getName() << " [" << deviceNumber << "]\n"; std::cout << "\tSample rate: " << audioSpec.sampleRate << "\n"; std::cout << "\tChannels: " << audioSpec.numChannels << "\n"; std::cout << "\tFormat: " << toString(audioSpec.format) << "\n"; std::cout << "\tBuffer size: " << audioSpec.bufferSize << std::endl; resumePlayback(); } } void AudioFacade::stopPlayback() { if (started) { pausePlayback(); musicTracks.clear(); engine.reset(); started = false; } } void AudioFacade::resumePlayback() { if (started) { if (running) { pausePlayback(); } engine->start(audioSpec, output); running = true; if (ownAudioThread) { audioThread = system.createThread("Audio", [this]() { run(); }); } output.startPlayback(); } } void AudioFacade::pausePlayback() { if (running) { { std::unique_lock<std::mutex> lock(audioMutex); running = false; engine->pause(); } if (ownAudioThread) { audioThread.join(); audioThread = {}; } output.stopPlayback(); } } AudioHandle AudioFacade::postEvent(const String& name, AudioPosition position) { auto event = resources->get<AudioEvent>(name); event->loadDependencies(*resources); size_t id = uniqueId++; enqueue([=] () { engine->postEvent(id, event, position); }); return std::make_shared<AudioHandleImpl>(*this, id); } AudioHandle AudioFacade::playMusic(const String& eventName, int track) { float fadeInTime = 0; bool hasFade = fadeInTime > 0.0001f; stopMusic(track, 0.5f); auto handle = postEvent(eventName, AudioPosition::makeFixed()); musicTracks[track] = handle; if (hasFade) { handle->setGain(0.0f); handle->setBehaviour(std::make_unique<AudioEmitterFadeBehaviour>(fadeInTime, 1.0f, false)); } return handle; } AudioHandle AudioFacade::play(std::shared_ptr<const IAudioClip> clip, AudioPosition position, float volume, bool loop) { size_t id = uniqueId++; enqueue([=] () { engine->play(id, clip, position, volume, loop); }); return std::make_shared<AudioHandleImpl>(*this, id); } AudioHandle AudioFacade::getMusic(int track) { auto iter = musicTracks.find(track); if (iter != musicTracks.end()) { return iter->second; } else { return AudioHandle(); } } void AudioFacade::stopMusic(int track, float fadeOutTime) { auto iter = musicTracks.find(track); if (iter != musicTracks.end()) { stopMusic(iter->second, fadeOutTime); musicTracks.erase(iter); } } void AudioFacade::stopAllMusic(float fadeOutTime) { for (auto& m: musicTracks) { stopMusic(m.second, fadeOutTime); } musicTracks.clear(); } void AudioFacade::setMasterVolume(float volume) { enqueue([=] () { engine->setMasterGain(volumeToGain(volume)); }); } void AudioFacade::setGroupVolume(const String& groupName, float volume) { enqueue([=] () { engine->setGroupGain(groupName, volumeToGain(volume)); }); } void AudioFacade::stopMusic(AudioHandle& handle, float fadeOutTime) { if (fadeOutTime > 0.001f) { handle->setBehaviour(std::make_unique<AudioEmitterFadeBehaviour>(fadeOutTime, 0.0f, true)); } else { handle->stop(); } } void AudioFacade::onNeedBuffer() { if (!ownAudioThread) { stepAudio(); } } void AudioFacade::setListener(AudioListenerData listener) { enqueue([=] () { engine->setListener(listener); }); } void AudioFacade::onAudioException(std::exception& e) { std::unique_lock<std::mutex> lock(exceptionMutex); exceptions.emplace_back(e.what()); } void AudioFacade::run() { while (running) { stepAudio(); } } void AudioFacade::stepAudio() { try { { std::unique_lock<std::mutex> lock(audioMutex); if (!running) { return; } std::swap(inbox, inboxProcessing); inbox.clear(); playingSoundsNext = engine->getPlayingSounds(); } for (auto& action : inboxProcessing) { action(); } if (ownAudioThread) { engine->run(); } else { engine->generateBuffer(); } } catch (std::exception& e) { onAudioException(e); } } void AudioFacade::enqueue(std::function<void()> action) { if (running) { outbox.emplace_back(std::move(action)); } } void AudioFacade::pump() { { std::unique_lock<std::mutex> lock(exceptionMutex); if (!exceptions.empty()) { for (size_t i = 0; i + 1 < exceptions.size(); ++i) { Logger::logError(exceptions[i]); } const auto e = exceptions.back(); exceptions.clear(); stopPlayback(); throw Exception(e); } } if (running) { std::unique_lock<std::mutex> lock(audioMutex); if (!outbox.empty()) { size_t i = inbox.size(); inbox.resize(i + outbox.size()); for (auto& o: outbox) { inbox[i++] = std::move(o); } outbox.clear(); } playingSounds = playingSoundsNext; } else { inbox.clear(); outbox.clear(); } } <commit_msg>Ensure that audio device is closed before program termination.<commit_after>#include "audio_facade.h" #include "audio_engine.h" #include "audio_handle_impl.h" #include "audio_emitter_behaviour.h" #include "halley/support/console.h" #include "halley/support/logger.h" #include "halley/core/resources/resources.h" #include "audio_event.h" using namespace Halley; AudioFacade::AudioFacade(AudioOutputAPI& o, SystemAPI& system) : output(o) , system(system) , running(false) , ownAudioThread(o.needsAudioThread()) { } AudioFacade::~AudioFacade() { AudioFacade::stopPlayback(); } void AudioFacade::setResources(Resources& res) { resources = &res; } void AudioFacade::init() { std::cout << ConsoleColour(Console::GREEN) << "\nInitializing audio...\n" << ConsoleColour(); std::cout << "Audio devices available:" << std::endl; int i = 0; for (auto& device: getAudioDevices()) { std::cout << "\t" << i++ << ": " << device->getName() << std::endl; } } void AudioFacade::deInit() { stopPlayback(); } Vector<std::unique_ptr<const AudioDevice>> AudioFacade::getAudioDevices() { return output.getAudioDevices(); } void AudioFacade::startPlayback(int deviceNumber) { if (started) { stopPlayback(); } auto devices = getAudioDevices(); if (int(devices.size()) > deviceNumber) { engine = std::make_unique<AudioEngine>(); AudioSpec format; format.bufferSize = 1024; format.format = AudioSampleFormat::Float; format.numChannels = 2; format.sampleRate = 48000; audioSpec = output.openAudioDevice(format, devices.at(deviceNumber).get(), [this]() { onNeedBuffer(); }); started = true; std::cout << "Audio Playback started.\n"; std::cout << "\tDevice: " << devices.at(deviceNumber)->getName() << " [" << deviceNumber << "]\n"; std::cout << "\tSample rate: " << audioSpec.sampleRate << "\n"; std::cout << "\tChannels: " << audioSpec.numChannels << "\n"; std::cout << "\tFormat: " << toString(audioSpec.format) << "\n"; std::cout << "\tBuffer size: " << audioSpec.bufferSize << std::endl; resumePlayback(); } } void AudioFacade::stopPlayback() { if (started) { pausePlayback(); musicTracks.clear(); engine.reset(); output.closeAudioDevice(); started = false; } } void AudioFacade::resumePlayback() { if (started) { if (running) { pausePlayback(); } engine->start(audioSpec, output); running = true; if (ownAudioThread) { audioThread = system.createThread("Audio", [this]() { run(); }); } output.startPlayback(); } } void AudioFacade::pausePlayback() { if (running) { { std::unique_lock<std::mutex> lock(audioMutex); running = false; engine->pause(); } if (ownAudioThread) { audioThread.join(); audioThread = {}; } output.stopPlayback(); } } AudioHandle AudioFacade::postEvent(const String& name, AudioPosition position) { auto event = resources->get<AudioEvent>(name); event->loadDependencies(*resources); size_t id = uniqueId++; enqueue([=] () { engine->postEvent(id, event, position); }); return std::make_shared<AudioHandleImpl>(*this, id); } AudioHandle AudioFacade::playMusic(const String& eventName, int track) { float fadeInTime = 0; bool hasFade = fadeInTime > 0.0001f; stopMusic(track, 0.5f); auto handle = postEvent(eventName, AudioPosition::makeFixed()); musicTracks[track] = handle; if (hasFade) { handle->setGain(0.0f); handle->setBehaviour(std::make_unique<AudioEmitterFadeBehaviour>(fadeInTime, 1.0f, false)); } return handle; } AudioHandle AudioFacade::play(std::shared_ptr<const IAudioClip> clip, AudioPosition position, float volume, bool loop) { size_t id = uniqueId++; enqueue([=] () { engine->play(id, clip, position, volume, loop); }); return std::make_shared<AudioHandleImpl>(*this, id); } AudioHandle AudioFacade::getMusic(int track) { auto iter = musicTracks.find(track); if (iter != musicTracks.end()) { return iter->second; } else { return AudioHandle(); } } void AudioFacade::stopMusic(int track, float fadeOutTime) { auto iter = musicTracks.find(track); if (iter != musicTracks.end()) { stopMusic(iter->second, fadeOutTime); musicTracks.erase(iter); } } void AudioFacade::stopAllMusic(float fadeOutTime) { for (auto& m: musicTracks) { stopMusic(m.second, fadeOutTime); } musicTracks.clear(); } void AudioFacade::setMasterVolume(float volume) { enqueue([=] () { engine->setMasterGain(volumeToGain(volume)); }); } void AudioFacade::setGroupVolume(const String& groupName, float volume) { enqueue([=] () { engine->setGroupGain(groupName, volumeToGain(volume)); }); } void AudioFacade::stopMusic(AudioHandle& handle, float fadeOutTime) { if (fadeOutTime > 0.001f) { handle->setBehaviour(std::make_unique<AudioEmitterFadeBehaviour>(fadeOutTime, 0.0f, true)); } else { handle->stop(); } } void AudioFacade::onNeedBuffer() { if (!ownAudioThread) { stepAudio(); } } void AudioFacade::setListener(AudioListenerData listener) { enqueue([=] () { engine->setListener(listener); }); } void AudioFacade::onAudioException(std::exception& e) { std::unique_lock<std::mutex> lock(exceptionMutex); exceptions.emplace_back(e.what()); } void AudioFacade::run() { while (running) { stepAudio(); } } void AudioFacade::stepAudio() { try { { std::unique_lock<std::mutex> lock(audioMutex); if (!running) { return; } std::swap(inbox, inboxProcessing); inbox.clear(); playingSoundsNext = engine->getPlayingSounds(); } for (auto& action : inboxProcessing) { action(); } if (ownAudioThread) { engine->run(); } else { engine->generateBuffer(); } } catch (std::exception& e) { onAudioException(e); } } void AudioFacade::enqueue(std::function<void()> action) { if (running) { outbox.emplace_back(std::move(action)); } } void AudioFacade::pump() { { std::unique_lock<std::mutex> lock(exceptionMutex); if (!exceptions.empty()) { for (size_t i = 0; i + 1 < exceptions.size(); ++i) { Logger::logError(exceptions[i]); } const auto e = exceptions.back(); exceptions.clear(); stopPlayback(); throw Exception(e); } } if (running) { std::unique_lock<std::mutex> lock(audioMutex); if (!outbox.empty()) { size_t i = inbox.size(); inbox.resize(i + outbox.size()); for (auto& o: outbox) { inbox[i++] = std::move(o); } outbox.clear(); } playingSounds = playingSoundsNext; } else { inbox.clear(); outbox.clear(); } } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "iconbuttonpage.h" #include <MLabel> #include <MLayout> #include <MLocale> #include <MApplicationPage> #include <MGridLayoutPolicy> #include <MLinearLayoutPolicy> #include <MButton> #include <MButtonGroup> #include <MDebug> #include <MApplication> #include <QGraphicsLinearLayout> IconButtonPage::IconButtonPage() : TemplatePage(), iconButton1(0), iconButton2(0) { gid = TemplatePage::Buttons; } IconButtonPage::~IconButtonPage() { } QString IconButtonPage::timedemoTitle() { return "IconButton"; } void IconButtonPage::createContent() { TemplatePage::createContent(); QGraphicsWidget *w = new QGraphicsWidget(); w->setMinimumSize(container->minimumWidth(), 5); w->setMaximumSize(container->minimumWidth(), 5); containerPolicy->setSpacing(40); containerPolicy->addItem(w); //containerPolicy->addStretch(); // Icon buttons iconButton1 = new MButton(); iconButton1->setViewType(MButton::iconType); iconButton1->setIconID("icon-l-common-video-playback"); containerPolicy->addItem(iconButton1, Qt::AlignCenter); iconButton2 = new MButton(); iconButton2->setViewType(MButton::iconType); iconButton2->setIconID("icon-l-games"); iconButton2->setMaximumWidth(175); containerPolicy->addItem(iconButton2, Qt::AlignCenter); containerPolicy->addStretch(); retranslateUi(); } void IconButtonPage::retranslateUi() { //% "Icon Button" setTitle(qtTrId("xx_icon_button_page_title")); if (!isContentCreated()) return; //% "Icon Buttons have an icon and can have a text label. " //% "Icon button differs from push button by its visual presentation: " //% "it does not have button-style edges like a Push Button does.\n\n " //% "Icon Buttons are used in e.g. Toolbars." infoLabel->setText("<a></a>" + qtTrId("xx_icon_button_page_info_label")); //% "Lorem ipsum" iconButton2->setText(qtTrId("xx_icon_button_page_icon_button2")); } <commit_msg>Changes: Fixed Widgetsgallery iconbuttonpage layout.<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "iconbuttonpage.h" #include <MLabel> #include <MLayout> #include <MLocale> #include <MApplicationPage> #include <MGridLayoutPolicy> #include <MLinearLayoutPolicy> #include <MButton> #include <MButtonGroup> #include <MDebug> #include <MApplication> #include <QGraphicsLinearLayout> IconButtonPage::IconButtonPage() : TemplatePage(), iconButton1(0), iconButton2(0) { gid = TemplatePage::Buttons; } IconButtonPage::~IconButtonPage() { } QString IconButtonPage::timedemoTitle() { return "IconButton"; } void IconButtonPage::createContent() { TemplatePage::createContent(); QGraphicsWidget *w = new QGraphicsWidget(); w->setMinimumSize(container->minimumWidth(), 5); w->setMaximumSize(container->maximumWidth(), 5); containerPolicy->setSpacing(40); containerPolicy->addItem(w); //containerPolicy->addStretch(); // Icon buttons iconButton1 = new MButton(); iconButton1->setViewType(MButton::iconType); iconButton1->setIconID("icon-l-common-video-playback"); containerPolicy->addItem(iconButton1, Qt::AlignCenter); iconButton2 = new MButton(); iconButton2->setViewType(MButton::iconType); iconButton2->setIconID("icon-l-games"); iconButton2->setMaximumWidth(175); containerPolicy->addItem(iconButton2, Qt::AlignCenter); containerPolicy->addStretch(); retranslateUi(); } void IconButtonPage::retranslateUi() { //% "Icon Button" setTitle(qtTrId("xx_icon_button_page_title")); if (!isContentCreated()) return; //% "Icon Buttons have an icon and can have a text label. " //% "Icon button differs from push button by its visual presentation: " //% "it does not have button-style edges like a Push Button does.\n\n " //% "Icon Buttons are used in e.g. Toolbars." infoLabel->setText("<a></a>" + qtTrId("xx_icon_button_page_info_label")); //% "Lorem ipsum" iconButton2->setText(qtTrId("xx_icon_button_page_icon_button2")); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: template.cxx,v $ * * $Revision: 1.14 $ * * last change: $Author: hr $ $Date: 2003-03-19 16:19: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 "template.hxx" #include "templateimpl.hxx" #ifndef CONFIGMGR_SETNODEACCESS_HXX #include "setnodeaccess.hxx" #endif #ifndef CONFIGMGR_API_APITYPES_HXX_ #include "apitypes.hxx" #endif namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- // class TemplateProvider //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TemplateProvider::TemplateProvider() : m_aImpl() { } //----------------------------------------------------------------------------- TemplateProvider::TemplateProvider(TemplateManagerRef const & xProvider, RequestOptions const& aOptions) : m_aImpl( new TemplateProvider_Impl(xProvider,aOptions) ) { } //----------------------------------------------------------------------------- TemplateProvider::TemplateProvider(TemplateProvider const& aOther) : m_aImpl(aOther.m_aImpl) { } //----------------------------------------------------------------------------- TemplateProvider& TemplateProvider::operator =(TemplateProvider const& aOther) { m_aImpl = aOther.m_aImpl; return *this; } //----------------------------------------------------------------------------- TemplateProvider::~TemplateProvider() { } //----------------------------------------------------------------------------- // class SpecialTemplateProvider //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- SpecialTemplateProvider::SpecialTemplateProvider() : m_aImpl( new SpecialTemplateProvider_Impl() ) { } //----------------------------------------------------------------------------- SpecialTemplateProvider::SpecialTemplateProvider(SpecialTemplateProvider const& aOther) : m_aImpl(aOther.m_aImpl) { } //----------------------------------------------------------------------------- SpecialTemplateProvider& SpecialTemplateProvider::operator =(SpecialTemplateProvider const& aOther) { m_aImpl = aOther.m_aImpl; return *this; } //----------------------------------------------------------------------------- SpecialTemplateProvider::~SpecialTemplateProvider() { } //----------------------------------------------------------------------------- // class Template //----------------------------------------------------------------------------- Template::Template(Name const& aName, Name const& aModule,UnoType const& aType) : m_aName(aName) , m_aModule(aModule) , m_aInstanceType(aType) { } //----------------------------------------------------------------------------- bool Template::isInstanceTypeKnown() const { OSL_ASSERT( TemplateImplHelper::getNoTypeAvailable().getTypeClass() == uno::TypeClass_VOID ); return m_aInstanceType.getTypeClass() != uno::TypeClass_VOID; } //----------------------------------------------------------------------------- /// checks if this is a 'value' template bool Template::isInstanceValue() const { OSL_ENSURE( isInstanceTypeKnown(), "Template instance type unknown - cannot determine kind"); return m_aInstanceType.getTypeClass() != uno::TypeClass_INTERFACE; } //----------------------------------------------------------------------------- UnoType Template::getInstanceType() const { OSL_ENSURE( isInstanceTypeKnown(), "Template instance type unknown - returning invalid (VOID) type"); return m_aInstanceType; } //----------------------------------------------------------------------------- /// get the path where the template is located OUString Template::getPathString() const { TemplateName aNames(m_aName,m_aModule); return aNames.makePathString( ); } //----------------------------------------------------------------------------- TemplateHolder makeSimpleTemplate(UnoType const& aType, SpecialTemplateProvider const& aProvider) { TemplateName aNames(aType,false); return TemplateImplHelper::makeSpecialTemplate( aNames, aProvider, aType); } //----------------------------------------------------------------------------- TemplateHolder makeTreeTemplate(OUString const& sName, OUString const& sModule, SpecialTemplateProvider const& aProvider) { TemplateName aNames( sName,sModule ); return TemplateImplHelper::makeSpecialTemplate( aNames,aProvider, configapi::getUnoInterfaceType()); } //----------------------------------------------------------------------------- TemplateHolder makeSetElementTemplate(data::SetNodeAccess const& _aSet, TemplateProvider const& _aProvider) { TemplateName aNames( _aSet.getElementTemplateName(), _aSet.getElementTemplateModule() ); return TemplateImplHelper::makeElementTemplateWithType(aNames, _aProvider, _aSet); } //----------------------------------------------------------------------------- } } <commit_msg>INTEGRATION: CWS ooo19126 (1.14.194); FILE MERGED 2005/09/05 17:05:32 rt 1.14.194.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: template.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:34:13 $ * * 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 * ************************************************************************/ #include "template.hxx" #include "templateimpl.hxx" #ifndef CONFIGMGR_SETNODEACCESS_HXX #include "setnodeaccess.hxx" #endif #ifndef CONFIGMGR_API_APITYPES_HXX_ #include "apitypes.hxx" #endif namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- // class TemplateProvider //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TemplateProvider::TemplateProvider() : m_aImpl() { } //----------------------------------------------------------------------------- TemplateProvider::TemplateProvider(TemplateManagerRef const & xProvider, RequestOptions const& aOptions) : m_aImpl( new TemplateProvider_Impl(xProvider,aOptions) ) { } //----------------------------------------------------------------------------- TemplateProvider::TemplateProvider(TemplateProvider const& aOther) : m_aImpl(aOther.m_aImpl) { } //----------------------------------------------------------------------------- TemplateProvider& TemplateProvider::operator =(TemplateProvider const& aOther) { m_aImpl = aOther.m_aImpl; return *this; } //----------------------------------------------------------------------------- TemplateProvider::~TemplateProvider() { } //----------------------------------------------------------------------------- // class SpecialTemplateProvider //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- SpecialTemplateProvider::SpecialTemplateProvider() : m_aImpl( new SpecialTemplateProvider_Impl() ) { } //----------------------------------------------------------------------------- SpecialTemplateProvider::SpecialTemplateProvider(SpecialTemplateProvider const& aOther) : m_aImpl(aOther.m_aImpl) { } //----------------------------------------------------------------------------- SpecialTemplateProvider& SpecialTemplateProvider::operator =(SpecialTemplateProvider const& aOther) { m_aImpl = aOther.m_aImpl; return *this; } //----------------------------------------------------------------------------- SpecialTemplateProvider::~SpecialTemplateProvider() { } //----------------------------------------------------------------------------- // class Template //----------------------------------------------------------------------------- Template::Template(Name const& aName, Name const& aModule,UnoType const& aType) : m_aName(aName) , m_aModule(aModule) , m_aInstanceType(aType) { } //----------------------------------------------------------------------------- bool Template::isInstanceTypeKnown() const { OSL_ASSERT( TemplateImplHelper::getNoTypeAvailable().getTypeClass() == uno::TypeClass_VOID ); return m_aInstanceType.getTypeClass() != uno::TypeClass_VOID; } //----------------------------------------------------------------------------- /// checks if this is a 'value' template bool Template::isInstanceValue() const { OSL_ENSURE( isInstanceTypeKnown(), "Template instance type unknown - cannot determine kind"); return m_aInstanceType.getTypeClass() != uno::TypeClass_INTERFACE; } //----------------------------------------------------------------------------- UnoType Template::getInstanceType() const { OSL_ENSURE( isInstanceTypeKnown(), "Template instance type unknown - returning invalid (VOID) type"); return m_aInstanceType; } //----------------------------------------------------------------------------- /// get the path where the template is located OUString Template::getPathString() const { TemplateName aNames(m_aName,m_aModule); return aNames.makePathString( ); } //----------------------------------------------------------------------------- TemplateHolder makeSimpleTemplate(UnoType const& aType, SpecialTemplateProvider const& aProvider) { TemplateName aNames(aType,false); return TemplateImplHelper::makeSpecialTemplate( aNames, aProvider, aType); } //----------------------------------------------------------------------------- TemplateHolder makeTreeTemplate(OUString const& sName, OUString const& sModule, SpecialTemplateProvider const& aProvider) { TemplateName aNames( sName,sModule ); return TemplateImplHelper::makeSpecialTemplate( aNames,aProvider, configapi::getUnoInterfaceType()); } //----------------------------------------------------------------------------- TemplateHolder makeSetElementTemplate(data::SetNodeAccess const& _aSet, TemplateProvider const& _aProvider) { TemplateName aNames( _aSet.getElementTemplateName(), _aSet.getElementTemplateModule() ); return TemplateImplHelper::makeElementTemplateWithType(aNames, _aProvider, _aSet); } //----------------------------------------------------------------------------- } } <|endoftext|>
<commit_before>#include "Halide.h" using namespace Halide; Expr u16(Expr x) { return cast<uint16_t>(x); } Expr u8(Expr x) { return cast<uint8_t>(x); } // Define a 1D Gaussian blur (a [1 4 6 4 1] filter) of 5 elements. Expr blur5(Expr x0, Expr x1, Expr x2, Expr x3, Expr x4) { return u8((u16(x0) + 4*u16(x1) + 6*u16(x2) + 4*u16(x3) + u16(x4) + 8)/16); } int main(int argc, char **argv) { Target target = get_target_from_environment(); std::cout << "Target: " << target.to_string() << "\n"; Var x("x"), y("y"), c("c"); // Takes an 8-bit input image. ImageParam input(UInt(8), 3); // Apply a boundary condition to the input. Func input_bounded = BoundaryConditions::repeat_edge(input); // Implement this as a separable blur in y followed by x. Func blur_y("blur_y"); blur_y(x, y, c) = blur5(input_bounded(x, y - 2, c), input_bounded(x, y - 1, c), input_bounded(x, y, c), input_bounded(x, y + 1, c), input_bounded(x, y + 2, c)); Func blur("blur"); blur(x, y, c) = blur5(blur_y(x - 2, y, c), blur_y(x - 1, y, c), blur_y(x, y, c), blur_y(x + 1, y, c), blur_y(x + 2, y, c)); // Schedule. // Require the input and output to have 3 channels. blur.bound(c, 0, 3); input.set_min(2, 0).set_extent(2, 3); if (target.features_any_of({Target::HVX_64, Target::HVX_128})) { const int vector_size = target.has_feature(Target::HVX_128) ? 128 : 64; // The strategy here is to split each scanline of the result // into chunks of multiples of the vector size, computing the // blur in y at each chunk. We use the RoundUp tail strategy to // keep the last chunk's memory accesses aligned. Var xo("xo"), xi("xi"); blur.compute_root() .hexagon() .split(x, xo, xi, vector_size*2, TailStrategy::RoundUp) .vectorize(xi, vector_size) .parallel(y, 16); blur_y.compute_at(blur, xo) .vectorize(x, vector_size, TailStrategy::RoundUp); // Require scanlines of the input and output to be aligned. auto blur_buffer = blur.output_buffer(); input.set_host_alignment(vector_size); blur_buffer.set_host_alignment(vector_size); input.set_min(0, 0).set_extent(0, (input.extent(0)/vector_size)*vector_size); blur_buffer.set_min(0, 0).set_extent(0, (blur_buffer.extent(0)/vector_size)*vector_size); for (int i = 1; i < 3; i++) { input.set_stride(i, (input.stride(i)/vector_size)*vector_size); blur_buffer.set_stride(i, (blur_buffer.stride(i)/vector_size)*vector_size); } } else { const int vector_size = target.natural_vector_size<uint8_t>(); blur.compute_root() .parallel(y, 16) .vectorize(x, vector_size); blur_y.compute_at(blur, y) .vectorize(x, vector_size); } std::stringstream hdr; hdr << argv[2] << ".h"; blur.compile_to_header(hdr.str(), {input}, argv[2], target); std::stringstream obj; obj << argv[1] << ".o"; blur.compile_to_object(obj.str(), {input}, argv[2], target); return 0; } <commit_msg>Don't use short casts.<commit_after>#include "Halide.h" using namespace Halide; // Define a 1D Gaussian blur (a [1 4 6 4 1] filter) of 5 elements. Expr blur5(Expr x0, Expr x1, Expr x2, Expr x3, Expr x4) { // Widen to 16 bits, so we don't overflow while computing the stencil. x0 = cast<uint16_t>(x0); x1 = cast<uint16_t>(x1); x2 = cast<uint16_t>(x2); x3 = cast<uint16_t>(x3); x4 = cast<uint16_t>(x4); return cast<uint8_t>((x0 + 4*x1 + 6*x2 + 4*x3 + x4 + 8)/16); } int main(int argc, char **argv) { Target target = get_target_from_environment(); std::cout << "Target: " << target.to_string() << "\n"; Var x("x"), y("y"), c("c"); // Takes an 8-bit input image. ImageParam input(UInt(8), 3); // Apply a boundary condition to the input. Func input_bounded = BoundaryConditions::repeat_edge(input); // Implement this as a separable blur in y followed by x. Func blur_y("blur_y"); blur_y(x, y, c) = blur5(input_bounded(x, y - 2, c), input_bounded(x, y - 1, c), input_bounded(x, y, c), input_bounded(x, y + 1, c), input_bounded(x, y + 2, c)); Func blur("blur"); blur(x, y, c) = blur5(blur_y(x - 2, y, c), blur_y(x - 1, y, c), blur_y(x, y, c), blur_y(x + 1, y, c), blur_y(x + 2, y, c)); // Schedule. // Require the input and output to have 3 channels. blur.bound(c, 0, 3); input.set_min(2, 0).set_extent(2, 3); if (target.features_any_of({Target::HVX_64, Target::HVX_128})) { const int vector_size = target.has_feature(Target::HVX_128) ? 128 : 64; // The strategy here is to split each scanline of the result // into chunks of multiples of the vector size, computing the // blur in y at each chunk. We use the RoundUp tail strategy to // keep the last chunk's memory accesses aligned. Var xo("xo"), xi("xi"); blur.compute_root() .hexagon() .split(x, xo, xi, vector_size*2, TailStrategy::RoundUp) .vectorize(xi, vector_size) .parallel(y, 16); blur_y.compute_at(blur, xo) .vectorize(x, vector_size, TailStrategy::RoundUp); // Require scanlines of the input and output to be aligned. auto blur_buffer = blur.output_buffer(); input.set_host_alignment(vector_size); blur_buffer.set_host_alignment(vector_size); input.set_min(0, 0).set_extent(0, (input.extent(0)/vector_size)*vector_size); blur_buffer.set_min(0, 0).set_extent(0, (blur_buffer.extent(0)/vector_size)*vector_size); for (int i = 1; i < 3; i++) { input.set_stride(i, (input.stride(i)/vector_size)*vector_size); blur_buffer.set_stride(i, (blur_buffer.stride(i)/vector_size)*vector_size); } } else { const int vector_size = target.natural_vector_size<uint8_t>(); blur.compute_root() .parallel(y, 16) .vectorize(x, vector_size); blur_y.compute_at(blur, y) .vectorize(x, vector_size); } std::stringstream hdr; hdr << argv[2] << ".h"; blur.compile_to_header(hdr.str(), {input}, argv[2], target); std::stringstream obj; obj << argv[1] << ".o"; blur.compile_to_object(obj.str(), {input}, argv[2], target); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. 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 "tubeConvertTubesToDensityImage.h" #include "tubeCLIProgressReporter.h" #include "tubeMessage.h" #include <itkImageFileReader.h> #include <itkSpatialObjectReader.h> #include <itkTimeProbesCollectorBase.h> #include "ConvertTubesToDensityImageCLP.h" int DoIt( int argc, char * argv[] ); /** Main work happens here */ template< unsigned int Dimension > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; /*Typedefs..*/ typedef float TPixel; typedef itk::Vector< TPixel, Dimension > TangentPixelType; typedef itk::Image< TPixel, Dimension > DensityImageType; typedef itk::Image< TPixel, Dimension > RadiusImageType; typedef itk::Image< TangentPixelType, Dimension > TangentImageType; typedef itk::Image< unsigned char, Dimension > TemplateImageType; typedef itk::ImageFileReader< TemplateImageType > TemplateImageReaderType; /** Max Intensity value */ TPixel max_densityIntensity = 2048; typedef tube::ConvertTubesToDensityImage< TPixel, Dimension > TubeToDensityImageBuilderType; typedef typename TubeToDensityImageBuilderType::TubeGroupType TubesType; typedef itk::SpatialObjectReader< Dimension > TubesReaderType; double progress = 0.0; itk::TimeProbesCollectorBase timeCollector; tube::CLIProgressReporter progressReporter( "tubeDensityImageRadiusBuilder", CLPProcessInformation ); progressReporter.Start(); progressReporter.Report( progress ); typename TubeToDensityImageBuilderType::Pointer builder = TubeToDensityImageBuilderType::New(); builder->SetMaxDensityIntensity( max_densityIntensity ); // Const if( !inputTemplateImage.empty() ) { std::cout << "Trying to use template image as constraints!" << std::endl; timeCollector.Start( "Loading template image" ); typename TemplateImageReaderType::Pointer imTemplateReader; imTemplateReader = TemplateImageReaderType::New(); imTemplateReader->SetFileName( inputTemplateImage.c_str() ); imTemplateReader->Update(); typename TemplateImageType::Pointer imT = imTemplateReader->GetOutput(); typename TubeToDensityImageBuilderType::SizeType size; double spacing[Dimension]; for( unsigned int i = 0; i < Dimension; i++ ) { size[i] = imT->GetLargestPossibleRegion().GetSize()[i]; spacing[i] = imT->GetSpacing()[i]; } builder->SetSize( size ); builder->SetSpacing( spacing ); timeCollector.Stop( "Loading template image" ); } else { std::cout << "Trying to use user-specified constraints!" << std::endl; if( !outputSize.size() ) { std::cerr << "Output size is missing!" << std::endl; return -1; } typename TubeToDensityImageBuilderType::SizeType sizeValue; for( unsigned int i = 0; i < Dimension; i++ ) { sizeValue[i] = outputSize[i]; } builder->SetSize( sizeValue ); if( !outputSpacing.size() ) { std::cerr << "Output spacing is missing!" << std::endl; return -1; } double sp[Dimension]; for( unsigned int i = 0; i < Dimension; i++ ) { sp[i] = outputSpacing[i]; } builder->SetSpacing( sp ); } builder->SetUseSquareDistance( useSquareDistance ); typename TubesReaderType::Pointer reader = TubesReaderType::New(); try { reader->SetFileName( inputTubeFile.c_str() ); std::cout << "Reading Tube group... "; reader->Update(); std::cout << "Done." << std::endl; } catch( ... ) { std::cerr << "Error:: No readable Tubes found " << std::endl; return EXIT_FAILURE; } builder->SetInputTubeGroup( reader->GetGroup() ); progress = 0.1; // At about 10% done progressReporter.Report( progress ); timeCollector.Start( "Update filter" ); builder->Update(); timeCollector.Stop( "Update filter" ); progress = 0.8; // At about 80% done after filter progressReporter.Report( progress ); timeCollector.Start( "Save data" ); std::cout << "Writing image: " << outputDensityImage.c_str() << std::endl; typedef itk::ImageFileWriter< DensityImageType > WriterType_d; typename WriterType_d::Pointer writer_d = WriterType_d::New(); writer_d->SetFileName( outputDensityImage.c_str() ); writer_d->SetInput( builder->GetDensityMapImage() ); writer_d->SetUseCompression(true); writer_d->Update(); std::cout << "Writing image: " << outputRadiusImage.c_str() << std::endl; typedef itk::ImageFileWriter< RadiusImageType > WriterType_r; typename WriterType_r::Pointer writer_r = WriterType_r::New(); writer_r->SetFileName( outputRadiusImage.c_str() ); writer_r->SetInput( builder->GetRadiusMapImage() ); writer_r->SetUseCompression( true ); writer_r->Update(); std::cout << "Writing image: " << outputTangentImage.c_str() << std::endl; typedef itk::ImageFileWriter< TangentImageType > WriterType_t; typename WriterType_t::Pointer writer_t = WriterType_t::New(); writer_t->SetFileName( outputTangentImage.c_str() ); writer_t->SetInput( builder->GetTangentMapImage() ); writer_t->SetUseCompression( true ); writer_t->Update(); timeCollector.Stop( "Save data" ); progress = 1.0; progressReporter.Report( progress ); progressReporter.End(); timeCollector.Report(); return EXIT_SUCCESS; } // Main int main( int argc, char * argv[] ) { try { PARSE_ARGS; } catch( const std::exception & err ) { tube::ErrorMessage( err.what() ); return EXIT_FAILURE; } PARSE_ARGS; MetaScene *mScene = new MetaScene; mScene->Read( inputTubeFile.c_str() ); if( mScene->GetObjectList()->empty() ) { tubeWarningMacro( << "Input Tube file has no spatial objects" ); delete mScene; return EXIT_SUCCESS; } switch( mScene->GetObjectList()->front()->NDims() ) { case 2: { bool result = DoIt<2>( argc, argv ); delete mScene; return result; break; } case 3: { bool result = DoIt<3>( argc, argv ); delete mScene; return result; break; } default: { tubeErrorMacro( << "Error: Only 2D and 3D data is currently supported." ); delete mScene; return EXIT_FAILURE; break; } } return EXIT_FAILURE; } <commit_msg>COMP: Remove compiler warning.<commit_after>/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. All rights reserved. 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 "tubeConvertTubesToDensityImage.h" #include "tubeCLIProgressReporter.h" #include "tubeMessage.h" #include <itkImageFileReader.h> #include <itkSpatialObjectReader.h> #include <itkTimeProbesCollectorBase.h> #include "ConvertTubesToDensityImageCLP.h" int DoIt( int argc, char * argv[] ); /** Main work happens here */ template< unsigned int Dimension > int DoIt( int argc, char * argv[] ) { PARSE_ARGS; /*Typedefs..*/ typedef float TPixel; typedef itk::Vector< TPixel, Dimension > TangentPixelType; typedef itk::Image< TPixel, Dimension > DensityImageType; typedef itk::Image< TPixel, Dimension > RadiusImageType; typedef itk::Image< TangentPixelType, Dimension > TangentImageType; typedef itk::Image< unsigned char, Dimension > TemplateImageType; typedef itk::ImageFileReader< TemplateImageType > TemplateImageReaderType; /** Max Intensity value */ TPixel max_densityIntensity = 2048; typedef tube::ConvertTubesToDensityImage< TPixel, Dimension > TubeToDensityImageBuilderType; typedef itk::SpatialObjectReader< Dimension > TubesReaderType; double progress = 0.0; itk::TimeProbesCollectorBase timeCollector; tube::CLIProgressReporter progressReporter( "tubeDensityImageRadiusBuilder", CLPProcessInformation ); progressReporter.Start(); progressReporter.Report( progress ); typename TubeToDensityImageBuilderType::Pointer builder = TubeToDensityImageBuilderType::New(); builder->SetMaxDensityIntensity( max_densityIntensity ); // Const if( !inputTemplateImage.empty() ) { std::cout << "Trying to use template image as constraints!" << std::endl; timeCollector.Start( "Loading template image" ); typename TemplateImageReaderType::Pointer imTemplateReader; imTemplateReader = TemplateImageReaderType::New(); imTemplateReader->SetFileName( inputTemplateImage.c_str() ); imTemplateReader->Update(); typename TemplateImageType::Pointer imT = imTemplateReader->GetOutput(); typename TubeToDensityImageBuilderType::SizeType size; double spacing[Dimension]; for( unsigned int i = 0; i < Dimension; i++ ) { size[i] = imT->GetLargestPossibleRegion().GetSize()[i]; spacing[i] = imT->GetSpacing()[i]; } builder->SetSize( size ); builder->SetSpacing( spacing ); timeCollector.Stop( "Loading template image" ); } else { std::cout << "Trying to use user-specified constraints!" << std::endl; if( !outputSize.size() ) { std::cerr << "Output size is missing!" << std::endl; return -1; } typename TubeToDensityImageBuilderType::SizeType sizeValue; for( unsigned int i = 0; i < Dimension; i++ ) { sizeValue[i] = outputSize[i]; } builder->SetSize( sizeValue ); if( !outputSpacing.size() ) { std::cerr << "Output spacing is missing!" << std::endl; return -1; } double sp[Dimension]; for( unsigned int i = 0; i < Dimension; i++ ) { sp[i] = outputSpacing[i]; } builder->SetSpacing( sp ); } builder->SetUseSquareDistance( useSquareDistance ); typename TubesReaderType::Pointer reader = TubesReaderType::New(); try { reader->SetFileName( inputTubeFile.c_str() ); std::cout << "Reading Tube group... "; reader->Update(); std::cout << "Done." << std::endl; } catch( ... ) { std::cerr << "Error:: No readable Tubes found " << std::endl; return EXIT_FAILURE; } builder->SetInputTubeGroup( reader->GetGroup() ); progress = 0.1; // At about 10% done progressReporter.Report( progress ); timeCollector.Start( "Update filter" ); builder->Update(); timeCollector.Stop( "Update filter" ); progress = 0.8; // At about 80% done after filter progressReporter.Report( progress ); timeCollector.Start( "Save data" ); std::cout << "Writing image: " << outputDensityImage.c_str() << std::endl; typedef itk::ImageFileWriter< DensityImageType > WriterType_d; typename WriterType_d::Pointer writer_d = WriterType_d::New(); writer_d->SetFileName( outputDensityImage.c_str() ); writer_d->SetInput( builder->GetDensityMapImage() ); writer_d->SetUseCompression(true); writer_d->Update(); std::cout << "Writing image: " << outputRadiusImage.c_str() << std::endl; typedef itk::ImageFileWriter< RadiusImageType > WriterType_r; typename WriterType_r::Pointer writer_r = WriterType_r::New(); writer_r->SetFileName( outputRadiusImage.c_str() ); writer_r->SetInput( builder->GetRadiusMapImage() ); writer_r->SetUseCompression( true ); writer_r->Update(); std::cout << "Writing image: " << outputTangentImage.c_str() << std::endl; typedef itk::ImageFileWriter< TangentImageType > WriterType_t; typename WriterType_t::Pointer writer_t = WriterType_t::New(); writer_t->SetFileName( outputTangentImage.c_str() ); writer_t->SetInput( builder->GetTangentMapImage() ); writer_t->SetUseCompression( true ); writer_t->Update(); timeCollector.Stop( "Save data" ); progress = 1.0; progressReporter.Report( progress ); progressReporter.End(); timeCollector.Report(); return EXIT_SUCCESS; } // Main int main( int argc, char * argv[] ) { try { PARSE_ARGS; } catch( const std::exception & err ) { tube::ErrorMessage( err.what() ); return EXIT_FAILURE; } PARSE_ARGS; MetaScene *mScene = new MetaScene; mScene->Read( inputTubeFile.c_str() ); if( mScene->GetObjectList()->empty() ) { tubeWarningMacro( << "Input Tube file has no spatial objects" ); delete mScene; return EXIT_SUCCESS; } switch( mScene->GetObjectList()->front()->NDims() ) { case 2: { bool result = DoIt<2>( argc, argv ); delete mScene; return result; break; } case 3: { bool result = DoIt<3>( argc, argv ); delete mScene; return result; break; } default: { tubeErrorMacro( << "Error: Only 2D and 3D data is currently supported." ); delete mScene; return EXIT_FAILURE; break; } } return EXIT_FAILURE; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: schemaparser.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:41:45 $ * * 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 * ************************************************************************/ #include "schemaparser.hxx" // ----------------------------------------------------------------------------- #ifndef CONFIGMGR_WRAPEXCEPTION_HXX #include "wrapexception.hxx" #endif #define WRAP_PARSE_EXCEPTIONS() \ PASS_EXCEPTION(sax::SAXException) \ PASS_EXCEPTION(uno::RuntimeException) \ WRAP_CONFIGDATA_EXCEPTIONS( raiseParseException ) \ WRAP_OTHER_EXCEPTIONS( raiseParseException ) #define WRAP_PARSE_EXCEPTIONS_MSG( msg ) \ PASS_EXCEPTION(sax::SAXException) \ PASS_EXCEPTION(uno::RuntimeException) \ WRAP_CONFIGDATA_EXCEPTIONS1( raiseParseException, msg ) \ WRAP_OTHER_EXCEPTIONS1( raiseParseException, msg ) // ----------------------------------------------------------------------------- namespace configmgr { // ----------------------------------------------------------------------------- namespace xml { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace sax = ::com::sun::star::xml::sax; // ----------------------------------------------------------------------------- SchemaParser::SchemaParser(Context const & _xContext, uno::Reference< backenduno::XSchemaHandler > const & _xHandler, Select _selector) : BasicParser(_xContext) , m_xHandler(_xHandler) , m_sComponent() , m_selector(_selector) , m_selected(selectNone) { if (!m_xHandler.is()) { OUString sMessage(RTL_CONSTASCII_USTRINGPARAM("Cannot create SchemaParser: Unexpected NULL Handler")); throw uno::RuntimeException(sMessage, *this); } OSL_ENSURE(m_selector != selectNone, "Warning: Schema handler will handle no part of the schema"); } // ----------------------------------------------------------------------------- SchemaParser::~SchemaParser() { } // ----------------------------------------------------------------------------- void SAL_CALL SchemaParser::startDocument( ) throw (sax::SAXException, uno::RuntimeException) { BasicParser::startDocument(); OSL_ENSURE(isEmptyNode(), "BasicParser does not mark new document as empty"); m_sComponent = OUString(); m_selected = selectNone; } // ----------------------------------------------------------------------------- void SAL_CALL SchemaParser::endDocument( ) throw (sax::SAXException, uno::RuntimeException) { if (isSelected()) raiseParseException("Schema XML Parser: Invalid XML: Document ends while section is open"); if (isEmptyNode()) OSL_TRACE("Configuration Parser: XML schema document ended without any data"); BasicParser::endDocument(); } // ----------------------------------------------------------------------------- void SAL_CALL SchemaParser::startElement( const OUString& aName, const uno::Reference< sax::XAttributeList >& xAttribs ) throw (sax::SAXException, uno::RuntimeException) { if ( this->isSkipping() ) { this->startSkipping( aName, xAttribs ); return; } ElementInfo aInfo = getDataParser().parseElementInfo(aName,xAttribs); try { switch (aInfo.type) { case ElementType::schema: this->startSchema(aInfo,xAttribs); break; case ElementType::component: this->startSection(selectComponent, aInfo, xAttribs); break; case ElementType::templates: this->startSection(selectTemplates, aInfo, xAttribs); break; case ElementType::import: this->handleImport(aInfo,xAttribs); this->startSkipping( aName, xAttribs ); break; case ElementType::uses: this->startSkipping( aName, xAttribs ); break; case ElementType::instance: this->handleInstance(aInfo,xAttribs); this->startSkipping( aName, xAttribs ); break; case ElementType::item_type: this->handleItemType(aInfo,xAttribs); this->startSkipping( aName, xAttribs ); break; case ElementType::layer: case ElementType::node: raiseParseException( "Schema XML parser - Invalid data: found unspecified 'node' element.\n"); // fall thru case ElementType::group: case ElementType::set: this->startNode(aInfo,xAttribs); OSL_ASSERT( this->isInNode() ); break; case ElementType::property: this->startProperty(aInfo,xAttribs); OSL_ASSERT( this->isInUnhandledProperty() ); break; case ElementType::value: this->startValueData(xAttribs); OSL_ASSERT( this->isInValueData() ); break; default: // skip unknown elements OSL_ENSURE( aInfo.type <= ElementType::other, "Schema XML parser - Error: invalid element type value\n"); OSL_ENSURE( aInfo.type >= ElementType::other, "Schema XML parser - Unexpected: found layer element in schema data\n"); // accept (and skip) unknown (ElementType::other) tags in schema to allow documentation and constraints to pass without assertion //OSL_ENSURE( aInfo.type < ElementType::other, "Schema XML parser - Warning: ignoring unknown element tag\n"); this->startSkipping( aName, xAttribs ); OSL_ASSERT( this->isSkipping() ); return; } } WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Starting Element") OSL_ENSURE(aInfo.op == Operation::none || this->isSkipping(), "Schema Parser: The 'op' attribute is not supported in a schema"); } // ----------------------------------------------------------------------------- void SAL_CALL SchemaParser::endElement( const OUString& aName ) throw (sax::SAXException, uno::RuntimeException) { if ( this->wasSkipping(aName) ) return; try { if ( this->isInValueData()) this->endValueData(); else if (this->isInProperty()) this->endProperty(); else if (this->isInNode()) this->endNode(); else if (this->isSelected()) this->endSection(); else this->endSchema(); } WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Ending Element") } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void SchemaParser::startSchema( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { m_sComponent = aInfo.name; m_xHandler->startSchema(); } // ----------------------------------------------------------------------------- void SchemaParser::endSchema( ) { m_xHandler->endSchema(); m_sComponent = OUString(); } // ----------------------------------------------------------------------------- bool SchemaParser::select(Select _select) { if (isSelected()) raiseParseException("Schema XML parser - Invalid data: found start of section while a section is still open.\n"); m_selected = static_cast<Select>(m_selector & _select); return m_selected != 0; } // ----------------------------------------------------------------------------- void SchemaParser::startSection( Select _select, ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { if (this->select(_select)) { if (_select == selectComponent) { m_xHandler->startComponent(m_sComponent); } } else startSkipping(aInfo.name,xAttribs); } // ----------------------------------------------------------------------------- void SchemaParser::endSection( ) { if (m_selected == selectComponent) { m_xHandler->endComponent(); } m_selected = selectNone; } // ----------------------------------------------------------------------------- void SchemaParser::handleImport( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { OUString aComponent; if (getDataParser().getImportComponent(xAttribs,aComponent)) m_xHandler->importComponent(aComponent); else raiseParseException("Schema XML parser - Invalid data: Missing component attribute for import directive.\n"); } // ----------------------------------------------------------------------------- void SchemaParser::handleInstance( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { backenduno::TemplateIdentifier aTemplate; if (getDataParser().getInstanceType(xAttribs, aTemplate.Name, aTemplate.Component)) m_xHandler->addInstance(aInfo.name, aTemplate); else raiseParseException("Schema XML parser - Invalid data: Missing type information for instantiation directive.\n"); } // ----------------------------------------------------------------------------- void SchemaParser::handleItemType( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { backenduno::TemplateIdentifier aTemplate; if (getDataParser().getInstanceType(xAttribs, aTemplate.Name, aTemplate.Component)) m_xHandler->addItemType(aTemplate); else raiseParseException("Schema XML parser - Invalid data: Missing type information for instantiation directive.\n"); } // ----------------------------------------------------------------------------- void SchemaParser::startNode( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { bool bStartTemplate = ( !isInNode() && m_selected == selectTemplates ); BasicParser::startNode(aInfo,xAttribs); OSL_ASSERT(aInfo.type == ElementType::set || aInfo.type == ElementType::group); using backenduno::TemplateIdentifier; if (aInfo.type == ElementType::group) { if (bStartTemplate) m_xHandler->startGroupTemplate( TemplateIdentifier(aInfo.name,m_sComponent), aInfo.flags ); else m_xHandler->startGroup( aInfo.name, aInfo.flags ); } else { TemplateIdentifier aItemType; if (!getDataParser().getSetElementType(xAttribs, aItemType.Name, aItemType.Component)) raiseParseException("Schema XML parser - Invalid data: Missing item-type information for set node.\n"); if (bStartTemplate) m_xHandler->startSetTemplate( TemplateIdentifier(aInfo.name,m_sComponent), aInfo.flags, aItemType ); else m_xHandler->startSet( aInfo.name, aInfo.flags, aItemType ); } } // ----------------------------------------------------------------------------- void SchemaParser::endNode() { BasicParser::endNode(); bool bEndedTemplate = ( !isInNode() && m_selected == selectTemplates ); if (bEndedTemplate) m_xHandler->endTemplate(); else m_xHandler->endNode(); } // ----------------------------------------------------------------------------- void SchemaParser::startProperty( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { BasicParser::startProperty(aInfo,xAttribs); OSL_ENSURE( isInUnhandledProperty(), "Property not recognizable as unhandled"); } // ----------------------------------------------------------------------------- void SchemaParser::endProperty() { if (isInUnhandledProperty()) { ElementInfo const & aInfo = this->getActiveNodeInfo(); m_xHandler->addProperty(aInfo.name, aInfo.flags, getActivePropertyType()); } BasicParser::endProperty(); } // ----------------------------------------------------------------------------- void SchemaParser::startValueData(const uno::Reference< sax::XAttributeList >& xAttribs) { OSL_ENSURE( this->isInUnhandledProperty(),"Schema XML parser - multiple values in property are not permitted in the schema.\n"); BasicParser::startValueData(xAttribs); if (this->isValueDataLocalized()) getLogger().warning("Language attributes on values are ignored in the schema.", "endValueData()","configuration::xml::SchemaParser"); } // ----------------------------------------------------------------------------- void SchemaParser::endValueData() { uno::Any aValue = this->getCurrentValue(); ElementInfo const & aInfo = this->getActiveNodeInfo(); if (aValue.hasValue()) { m_xHandler->addPropertyWithDefault(aInfo.name,aInfo.flags,aValue); } else { getLogger().warning("Found deprecated explicit NIL value in schema data.", "endValueData()","configuration::xml::SchemaParser"); m_xHandler->addProperty(aInfo.name,aInfo.flags,getActivePropertyType()); } BasicParser::endValueData(); OSL_ENSURE( !isInUnhandledProperty(), "Property not recognizable as handled"); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace // ----------------------------------------------------------------------------- } // namespace <commit_msg>INTEGRATION: CWS warnings01 (1.10.4); FILE MERGED 2005/11/01 12:47:45 cd 1.10.4.1: #i53898# Warning free code for sun solaris compiler<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: schemaparser.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2006-06-19 23:36:50 $ * * 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 * ************************************************************************/ #include "schemaparser.hxx" // ----------------------------------------------------------------------------- #ifndef CONFIGMGR_WRAPEXCEPTION_HXX #include "wrapexception.hxx" #endif #define WRAP_PARSE_EXCEPTIONS() \ PASS_EXCEPTION(sax::SAXException) \ PASS_EXCEPTION(uno::RuntimeException) \ WRAP_CONFIGDATA_EXCEPTIONS( raiseParseException ) \ WRAP_OTHER_EXCEPTIONS( raiseParseException ) #define WRAP_PARSE_EXCEPTIONS_MSG( msg ) \ PASS_EXCEPTION(sax::SAXException) \ PASS_EXCEPTION(uno::RuntimeException) \ WRAP_CONFIGDATA_EXCEPTIONS1( raiseParseException, msg ) \ WRAP_OTHER_EXCEPTIONS1( raiseParseException, msg ) // ----------------------------------------------------------------------------- namespace configmgr { // ----------------------------------------------------------------------------- namespace xml { // ----------------------------------------------------------------------------- namespace uno = ::com::sun::star::uno; namespace sax = ::com::sun::star::xml::sax; // ----------------------------------------------------------------------------- SchemaParser::SchemaParser(Context const & _xContext, uno::Reference< backenduno::XSchemaHandler > const & _xHandler, Select _selector) : BasicParser(_xContext) , m_xHandler(_xHandler) , m_sComponent() , m_selector(_selector) , m_selected(selectNone) { if (!m_xHandler.is()) { OUString sMessage(RTL_CONSTASCII_USTRINGPARAM("Cannot create SchemaParser: Unexpected NULL Handler")); throw uno::RuntimeException(sMessage, *this); } OSL_ENSURE(m_selector != selectNone, "Warning: Schema handler will handle no part of the schema"); } // ----------------------------------------------------------------------------- SchemaParser::~SchemaParser() { } // ----------------------------------------------------------------------------- void SAL_CALL SchemaParser::startDocument( ) throw (sax::SAXException, uno::RuntimeException) { BasicParser::startDocument(); OSL_ENSURE(isEmptyNode(), "BasicParser does not mark new document as empty"); m_sComponent = OUString(); m_selected = selectNone; } // ----------------------------------------------------------------------------- void SAL_CALL SchemaParser::endDocument( ) throw (sax::SAXException, uno::RuntimeException) { if (isSelected()) raiseParseException("Schema XML Parser: Invalid XML: Document ends while section is open"); if (isEmptyNode()) OSL_TRACE("Configuration Parser: XML schema document ended without any data"); BasicParser::endDocument(); } // ----------------------------------------------------------------------------- void SAL_CALL SchemaParser::startElement( const OUString& aName, const uno::Reference< sax::XAttributeList >& xAttribs ) throw (sax::SAXException, uno::RuntimeException) { if ( this->isSkipping() ) { this->startSkipping( aName, xAttribs ); return; } ElementInfo aInfo = getDataParser().parseElementInfo(aName,xAttribs); try { switch (aInfo.type) { case ElementType::schema: this->startSchema(aInfo,xAttribs); break; case ElementType::component: this->startSection(selectComponent, aInfo, xAttribs); break; case ElementType::templates: this->startSection(selectTemplates, aInfo, xAttribs); break; case ElementType::import: this->handleImport(aInfo,xAttribs); this->startSkipping( aName, xAttribs ); break; case ElementType::uses: this->startSkipping( aName, xAttribs ); break; case ElementType::instance: this->handleInstance(aInfo,xAttribs); this->startSkipping( aName, xAttribs ); break; case ElementType::item_type: this->handleItemType(aInfo,xAttribs); this->startSkipping( aName, xAttribs ); break; case ElementType::layer: case ElementType::node: raiseParseException( "Schema XML parser - Invalid data: found unspecified 'node' element.\n"); // fall thru case ElementType::group: case ElementType::set: this->startNode(aInfo,xAttribs); OSL_ASSERT( this->isInNode() ); break; case ElementType::property: this->startProperty(aInfo,xAttribs); OSL_ASSERT( this->isInUnhandledProperty() ); break; case ElementType::value: this->startValueData(xAttribs); OSL_ASSERT( this->isInValueData() ); break; default: // skip unknown elements OSL_ENSURE( aInfo.type <= ElementType::other, "Schema XML parser - Error: invalid element type value\n"); OSL_ENSURE( aInfo.type >= ElementType::other, "Schema XML parser - Unexpected: found layer element in schema data\n"); // accept (and skip) unknown (ElementType::other) tags in schema to allow documentation and constraints to pass without assertion //OSL_ENSURE( aInfo.type < ElementType::other, "Schema XML parser - Warning: ignoring unknown element tag\n"); this->startSkipping( aName, xAttribs ); OSL_ASSERT( this->isSkipping() ); return; } } WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Starting Element") OSL_ENSURE(aInfo.op == Operation::none || this->isSkipping(), "Schema Parser: The 'op' attribute is not supported in a schema"); } // ----------------------------------------------------------------------------- void SAL_CALL SchemaParser::endElement( const OUString& aName ) throw (sax::SAXException, uno::RuntimeException) { if ( this->wasSkipping(aName) ) return; try { if ( this->isInValueData()) this->endValueData(); else if (this->isInProperty()) this->endProperty(); else if (this->isInNode()) this->endNode(); else if (this->isSelected()) this->endSection(); else this->endSchema(); } WRAP_PARSE_EXCEPTIONS_MSG("LayerParser - Ending Element") } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void SchemaParser::startSchema( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& /*xAttribs*/ ) { m_sComponent = aInfo.name; m_xHandler->startSchema(); } // ----------------------------------------------------------------------------- void SchemaParser::endSchema( ) { m_xHandler->endSchema(); m_sComponent = OUString(); } // ----------------------------------------------------------------------------- bool SchemaParser::select(Select _select) { if (isSelected()) raiseParseException("Schema XML parser - Invalid data: found start of section while a section is still open.\n"); m_selected = static_cast<Select>(m_selector & _select); return m_selected != 0; } // ----------------------------------------------------------------------------- void SchemaParser::startSection( Select _select, ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { if (this->select(_select)) { if (_select == selectComponent) { m_xHandler->startComponent(m_sComponent); } } else startSkipping(aInfo.name,xAttribs); } // ----------------------------------------------------------------------------- void SchemaParser::endSection( ) { if (m_selected == selectComponent) { m_xHandler->endComponent(); } m_selected = selectNone; } // ----------------------------------------------------------------------------- void SchemaParser::handleImport( ElementInfo const & /*aInfo*/, const uno::Reference< sax::XAttributeList >& xAttribs ) { OUString aComponent; if (getDataParser().getImportComponent(xAttribs,aComponent)) m_xHandler->importComponent(aComponent); else raiseParseException("Schema XML parser - Invalid data: Missing component attribute for import directive.\n"); } // ----------------------------------------------------------------------------- void SchemaParser::handleInstance( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { backenduno::TemplateIdentifier aTemplate; if (getDataParser().getInstanceType(xAttribs, aTemplate.Name, aTemplate.Component)) m_xHandler->addInstance(aInfo.name, aTemplate); else raiseParseException("Schema XML parser - Invalid data: Missing type information for instantiation directive.\n"); } // ----------------------------------------------------------------------------- void SchemaParser::handleItemType( ElementInfo const & /*aInfo*/, const uno::Reference< sax::XAttributeList >& xAttribs ) { backenduno::TemplateIdentifier aTemplate; if (getDataParser().getInstanceType(xAttribs, aTemplate.Name, aTemplate.Component)) m_xHandler->addItemType(aTemplate); else raiseParseException("Schema XML parser - Invalid data: Missing type information for instantiation directive.\n"); } // ----------------------------------------------------------------------------- void SchemaParser::startNode( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { bool bStartTemplate = ( !isInNode() && m_selected == selectTemplates ); BasicParser::startNode(aInfo,xAttribs); OSL_ASSERT(aInfo.type == ElementType::set || aInfo.type == ElementType::group); using backenduno::TemplateIdentifier; if (aInfo.type == ElementType::group) { if (bStartTemplate) m_xHandler->startGroupTemplate( TemplateIdentifier(aInfo.name,m_sComponent), aInfo.flags ); else m_xHandler->startGroup( aInfo.name, aInfo.flags ); } else { TemplateIdentifier aItemType; if (!getDataParser().getSetElementType(xAttribs, aItemType.Name, aItemType.Component)) raiseParseException("Schema XML parser - Invalid data: Missing item-type information for set node.\n"); if (bStartTemplate) m_xHandler->startSetTemplate( TemplateIdentifier(aInfo.name,m_sComponent), aInfo.flags, aItemType ); else m_xHandler->startSet( aInfo.name, aInfo.flags, aItemType ); } } // ----------------------------------------------------------------------------- void SchemaParser::endNode() { BasicParser::endNode(); bool bEndedTemplate = ( !isInNode() && m_selected == selectTemplates ); if (bEndedTemplate) m_xHandler->endTemplate(); else m_xHandler->endNode(); } // ----------------------------------------------------------------------------- void SchemaParser::startProperty( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs ) { BasicParser::startProperty(aInfo,xAttribs); OSL_ENSURE( isInUnhandledProperty(), "Property not recognizable as unhandled"); } // ----------------------------------------------------------------------------- void SchemaParser::endProperty() { if (isInUnhandledProperty()) { ElementInfo const & aInfo = this->getActiveNodeInfo(); m_xHandler->addProperty(aInfo.name, aInfo.flags, getActivePropertyType()); } BasicParser::endProperty(); } // ----------------------------------------------------------------------------- void SchemaParser::startValueData(const uno::Reference< sax::XAttributeList >& xAttribs) { OSL_ENSURE( this->isInUnhandledProperty(),"Schema XML parser - multiple values in property are not permitted in the schema.\n"); BasicParser::startValueData(xAttribs); if (this->isValueDataLocalized()) getLogger().warning("Language attributes on values are ignored in the schema.", "endValueData()","configuration::xml::SchemaParser"); } // ----------------------------------------------------------------------------- void SchemaParser::endValueData() { uno::Any aValue = this->getCurrentValue(); ElementInfo const & aInfo = this->getActiveNodeInfo(); if (aValue.hasValue()) { m_xHandler->addPropertyWithDefault(aInfo.name,aInfo.flags,aValue); } else { getLogger().warning("Found deprecated explicit NIL value in schema data.", "endValueData()","configuration::xml::SchemaParser"); m_xHandler->addProperty(aInfo.name,aInfo.flags,getActivePropertyType()); } BasicParser::endValueData(); OSL_ENSURE( !isInUnhandledProperty(), "Property not recognizable as handled"); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace // ----------------------------------------------------------------------------- } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <reddcoinprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <reddcoinaddress>\n" "Reveals the private key corresponding to <reddcoinaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Reddcoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } <commit_msg>Add check for valid keys in `importprivkey`<commit_after>// Copyright (c) 2009-2012 Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" // for pwalletMain #include "bitcoinrpc.h" #include "ui_interface.h" #include "base58.h" #include <boost/lexical_cast.hpp> #define printf OutputDebugStringF using namespace json_spirit; using namespace std; class CTxDump { public: CBlockIndex *pindex; int64 nValue; bool fSpent; CWalletTx* ptx; int nOut; CTxDump(CWalletTx* ptx = NULL, int nOut = -1) { pindex = NULL; nValue = 0; fSpent = false; this->ptx = ptx; this->nOut = nOut; } }; Value importprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey <reddcoinprivkey> [label] [rescan=true]\n" "Adds a private key (as returned by dumpprivkey) to your wallet."); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); CKeyID vchAddress = pubkey.GetID(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); { LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->MarkDirty(); pwalletMain->SetAddressBookName(vchAddress, strLabel); if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); pwalletMain->ReacceptWalletTransactions(); } } return Value::null; } Value dumpprivkey(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey <reddcoinaddress>\n" "Reveals the private key corresponding to <reddcoinaddress>."); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Reddcoin address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } <|endoftext|>
<commit_before>#include "data.h" #include <cassert> #include <map> #include <vector> namespace redsea { std::string getLCDchar(int code) { assert (code >= 32); const std::vector<std::string> char_map ({ " ","!","\\\"","#","¤","%","&","'","(",")","*","+",",","-",".","/", "0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?", "@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O", "P","Q","R","S","T","U","V","W","X","Y","Z","[","\\","]","―","_", "‖","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o", "p","q","r","s","t","u","v","w","x","y","z","{","|","}","¯"," ", "á","à","é","è","í","ì","ó","ò","ú","ù","Ñ","Ç","Ş","β","¡","IJ", "â","ä","ê","ë","î","ï","ô","ö","û","ü","ñ","ç","ş","ǧ","ı","ij", "ª","α","©","‰","Ǧ","ě","ň","ő","π","€","£","$","←","↑","→","↓", "º","¹","²","³","±","İ","ń","ű","µ","¿","÷","°","¼","½","¾","§", "Á","À","É","È","Í","Ì","Ó","Ò","Ú","Ù","Ř","Č","Š","Ž","Ð","Ŀ", "Â","Ä","Ê","Ë","Î","Ï","Ô","Ö","Û","Ü","ř","č","š","ž","đ","ŀ", "Ã","Å","Æ","Œ","ŷ","Ý","Õ","Ø","Þ","Ŋ","Ŕ","Ć","Ś","Ź","Ŧ","ð", "ã","å","æ","œ","ŵ","ý","õ","ø","þ","ŋ","ŕ","ć","ś","ź","ŧ"," "}); return char_map[code - 32]; } std::string getPTYname(int pty) { assert (pty >= 0 && pty <= 32); const std::vector<std::string> pty_names ({ "No PTY", "News", "Current Affairs", "Information", "Sport", "Education", "Drama", "Cultures", "Science", "Varied Speech","Pop Music", "Rock Music", "Easy Listening","Light Classics M","Serious Classics","Other Music", "Weather & Metr", "Finance", "Children's Progs", "Social Affairs", "Religion", "Phone In", "Travel & Touring", "Leisure & Hobby", "Jazz Music", "Country Music", "National Music", "Oldies Music", "Folk Music", "Documentary", "Alarm Test", "Alarm - Alarm !" }); return pty_names[pty]; } std::string getCountryString(uint16_t pi, uint16_t ecc) { const std::map<uint16_t,std::vector<std::string>> country_codes ({ {0xA0,{"us","us","us","us","us","us","us","us","us","us","us","--","us","us","--"}}, {0xA1,{"--","--","--","--","--","--","--","--","--","--","ca","ca","ca","ca","gl"}}, {0xA2,{"ai","ag","ec","fk","bb","bz","ky","cr","cu","ar","br","bm","an","gp","bs"}}, {0xA3,{"bo","co","jm","mq","gf","py","ni","--","pa","dm","do","cl","gd","tc","gy"}}, {0xA4,{"gt","hn","aw","--","ms","tt","pe","sr","uy","kn","lc","sv","ht","ve","--"}}, {0xA5,{"--","--","--","--","--","--","--","--","--","--","mx","vc","mx","mx","mx"}}, {0xA6,{"--","--","--","--","--","--","--","--","--","--","--","--","--","--","pm"}}, {0xD0,{"cm","cf","dj","mg","ml","ao","gq","ga","gn","za","bf","cg","tg","bj","mw"}}, {0xD1,{"na","lr","gh","mr","st","cv","sn","gm","bi","--","bw","km","tz","et","bg"}}, {0xD2,{"sl","zw","mz","ug","sz","ke","so","ne","td","gw","zr","ci","tz","zm","--"}}, {0xD3,{"--","--","eh","--","rw","ls","--","sc","--","mu","--","sd","--","--","--"}}, {0xE0,{"de","dz","ad","il","it","be","ru","ps","al","at","hu","mt","de","--","eg"}}, {0xE1,{"gr","cy","sm","ch","jo","fi","lu","bg","dk","gi","iq","gb","ly","ro","fr"}}, {0xE2,{"ma","cz","pl","va","sk","sy","tn","--","li","is","mc","lt","yu","es","no"}}, {0xE3,{"ie","ie","tr","mk","tj","--","--","nl","lv","lb","az","hr","kz","se","by"}}, {0xE4,{"md","ee","kg","--","--","ua","--","pt","si","am","uz","ge","--","tm","ba"}}, {0xF0,{"au","au","au","au","au","au","au","au","sa","af","mm","cn","kp","bh","my"}}, {0xF1,{"ki","bt","bd","pk","fj","om","nr","ir","nz","sb","bn","lk","tw","kr","hk"}}, {0xF2,{"kw","qa","kh","ws","in","mo","vn","ph","jp","sg","mv","id","ae","np","vu"}}, {0xF3,{"la","th","to","--","--","--","--","--","pg","--","ye","--","--","fm","mn"}} }); std::string result("--"); uint16_t pi_cc = pi >> 12; if (country_codes.find(ecc) != country_codes.end() && pi_cc > 0) { result = country_codes.at(ecc).at(pi_cc-1); } return result; } std::string getLanguageString(uint16_t code) { std::vector<std::string> languages ({ "Unknown","Albanian","Breton","Catalan", "Croatian","Welsh","Czech","Danish", "German","English","Spanish","Esperanto", "Estonian","Basque","Faroese","French", "Frisian","Irish","Gaelic","Galician", "Icelandic","Italian","Lappish","Latin", "Latvian","Luxembourgian","Lithuanian","Hungarian", "Maltese","Dutch","Norwegian","Occitan", "Polish","Portuguese","Romanian","Romansh", "Serbian","Slovak","Slovene","Finnish", "Swedish","Turkish","Flemish","Walloon", "","","","", "","","","", "","","","", "","","","", "","","","", "Background","","","", "","Zulu","Vietnamese","Uzbek", "Urdu","Ukrainian","Thai","Telugu", "Tatar","Tamil","Tadzhik","Swahili", "SrananTongo","Somali","Sinhalese","Shona", "Serbo-Croat","Ruthenian","Russian","Quechua", "Pushtu","Punjabi","Persian","Papamiento", "Oriya","Nepali","Ndebele","Marathi", "Moldovian","Malaysian","Malagasay","Macedonian", "Laotian","Korean","Khmer","Kazakh", "Kannada","Japanese","Indonesian","Hindi", "Hebrew","Hausa","Gurani","Gujurati", "Greek","Georgian","Fulani","Dari", "Churash","Chinese","Burmese","Bulgarian", "Bengali","Belorussian","Bambora","Azerbaijan", "Assamese","Armenian","Arabic","Amharic" }); std::string result(""); if (code < languages.size()) { result = languages[code]; } return result; } std::string getAppName(uint16_t aid) { std::map<uint16_t,std::string> oda_apps({ { 0x0000, "None" }, { 0x0093, "Cross referencing DAB within RDS" }, { 0x0BCB, "Leisure & Practical Info for Drivers" }, { 0x0C24, "ELECTRABEL-DSM 7" }, { 0x0CC1, "Wireless Playground broadcast control signal" }, { 0x0D45, "RDS-TMC: ALERT-C / EN ISO 14819-1" }, { 0x0D8B, "ELECTRABEL-DSM 18" }, { 0x0E2C, "ELECTRABEL-DSM 3" }, { 0x0E31, "ELECTRABEL-DSM 13" }, { 0x0F87, "ELECTRABEL-DSM 2" }, { 0x125F, "I-FM-RDS for fixed and mobile devices" }, { 0x1BDA, "ELECTRABEL-DSM 1" }, { 0x1C5E, "ELECTRABEL-DSM 20" }, { 0x1C68, "ITIS In-vehicle data base" }, { 0x1CB1, "ELECTRABEL-DSM 10" }, { 0x1D47, "ELECTRABEL-DSM 4" }, { 0x1DC2, "CITIBUS 4" }, { 0x1DC5, "Encrypted TTI using ALERT-Plus" }, { 0x1E8F, "ELECTRABEL-DSM 17" }, { 0x4AA1, "RASANT" }, { 0x4AB7, "ELECTRABEL-DSM 9" }, { 0x4BA2, "ELECTRABEL-DSM 5" }, { 0x4BD7, "RadioText+ (RT+)" }, { 0x4C59, "CITIBUS 2" }, { 0x4D87, "Radio Commerce System (RCS)" }, { 0x4D95, "ELECTRABEL-DSM 16" }, { 0x4D9A, "ELECTRABEL-DSM 11" }, { 0x5757, "Personal weather station" }, { 0x6552, "Enhanced RadioText (eRT)" }, { 0x7373, "Enhanced early warning system" }, { 0xC350, "NRSC Song Title and Artist" }, { 0xC3A1, "Personal Radio Service" }, { 0xC3B0, "iTunes Tagging" }, { 0xC3C3, "NAVTEQ Traffic Plus" }, { 0xC4D4, "eEAS" }, { 0xC549, "Smart Grid Broadcast Channel" }, { 0xC563, "ID Logic" }, { 0xC6A7, "Veil Enabled Interactive Device" }, { 0xC737, "Utility Message Channel (UMC)" }, { 0xCB73, "CITIBUS 1" }, { 0xCB97, "ELECTRABEL-DSM 14" }, { 0xCC21, "CITIBUS 3" }, { 0xCD46, "RDS-TMC: ALERT-C" }, { 0xCD47, "RDS-TMC: ALERT-C" }, { 0xCD9E, "ELECTRABEL-DSM 8" }, { 0xCE6B, "Encrypted TTI using ALERT-Plus" }, { 0xE123, "APS Gateway" }, { 0xE1C1, "Action code" }, { 0xE319, "ELECTRABEL-DSM 12" }, { 0xE411, "Beacon downlink" }, { 0xE440, "ELECTRABEL-DSM 15" }, { 0xE4A6, "ELECTRABEL-DSM 19" }, { 0xE5D7, "ELECTRABEL-DSM 6" }, { 0xE911, "EAS open protocol" } }); std::string result(""); if (oda_apps.find(aid) != oda_apps.end()) { result = oda_apps[aid]; } return result; } } <commit_msg>ODA app name defaults to (Unknown)<commit_after>#include "data.h" #include <cassert> #include <map> #include <vector> namespace redsea { std::string getLCDchar(int code) { assert (code >= 32); const std::vector<std::string> char_map ({ " ","!","\\\"","#","¤","%","&","'","(",")","*","+",",","-",".","/", "0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?", "@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O", "P","Q","R","S","T","U","V","W","X","Y","Z","[","\\","]","―","_", "‖","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o", "p","q","r","s","t","u","v","w","x","y","z","{","|","}","¯"," ", "á","à","é","è","í","ì","ó","ò","ú","ù","Ñ","Ç","Ş","β","¡","IJ", "â","ä","ê","ë","î","ï","ô","ö","û","ü","ñ","ç","ş","ǧ","ı","ij", "ª","α","©","‰","Ǧ","ě","ň","ő","π","€","£","$","←","↑","→","↓", "º","¹","²","³","±","İ","ń","ű","µ","¿","÷","°","¼","½","¾","§", "Á","À","É","È","Í","Ì","Ó","Ò","Ú","Ù","Ř","Č","Š","Ž","Ð","Ŀ", "Â","Ä","Ê","Ë","Î","Ï","Ô","Ö","Û","Ü","ř","č","š","ž","đ","ŀ", "Ã","Å","Æ","Œ","ŷ","Ý","Õ","Ø","Þ","Ŋ","Ŕ","Ć","Ś","Ź","Ŧ","ð", "ã","å","æ","œ","ŵ","ý","õ","ø","þ","ŋ","ŕ","ć","ś","ź","ŧ"," "}); return char_map[code - 32]; } std::string getPTYname(int pty) { assert (pty >= 0 && pty <= 32); const std::vector<std::string> pty_names ({ "No PTY", "News", "Current Affairs", "Information", "Sport", "Education", "Drama", "Cultures", "Science", "Varied Speech","Pop Music", "Rock Music", "Easy Listening","Light Classics M","Serious Classics","Other Music", "Weather & Metr", "Finance", "Children's Progs", "Social Affairs", "Religion", "Phone In", "Travel & Touring", "Leisure & Hobby", "Jazz Music", "Country Music", "National Music", "Oldies Music", "Folk Music", "Documentary", "Alarm Test", "Alarm - Alarm !" }); return pty_names[pty]; } std::string getCountryString(uint16_t pi, uint16_t ecc) { const std::map<uint16_t,std::vector<std::string>> country_codes ({ {0xA0,{"us","us","us","us","us","us","us","us","us","us","us","--","us","us","--"}}, {0xA1,{"--","--","--","--","--","--","--","--","--","--","ca","ca","ca","ca","gl"}}, {0xA2,{"ai","ag","ec","fk","bb","bz","ky","cr","cu","ar","br","bm","an","gp","bs"}}, {0xA3,{"bo","co","jm","mq","gf","py","ni","--","pa","dm","do","cl","gd","tc","gy"}}, {0xA4,{"gt","hn","aw","--","ms","tt","pe","sr","uy","kn","lc","sv","ht","ve","--"}}, {0xA5,{"--","--","--","--","--","--","--","--","--","--","mx","vc","mx","mx","mx"}}, {0xA6,{"--","--","--","--","--","--","--","--","--","--","--","--","--","--","pm"}}, {0xD0,{"cm","cf","dj","mg","ml","ao","gq","ga","gn","za","bf","cg","tg","bj","mw"}}, {0xD1,{"na","lr","gh","mr","st","cv","sn","gm","bi","--","bw","km","tz","et","bg"}}, {0xD2,{"sl","zw","mz","ug","sz","ke","so","ne","td","gw","zr","ci","tz","zm","--"}}, {0xD3,{"--","--","eh","--","rw","ls","--","sc","--","mu","--","sd","--","--","--"}}, {0xE0,{"de","dz","ad","il","it","be","ru","ps","al","at","hu","mt","de","--","eg"}}, {0xE1,{"gr","cy","sm","ch","jo","fi","lu","bg","dk","gi","iq","gb","ly","ro","fr"}}, {0xE2,{"ma","cz","pl","va","sk","sy","tn","--","li","is","mc","lt","yu","es","no"}}, {0xE3,{"ie","ie","tr","mk","tj","--","--","nl","lv","lb","az","hr","kz","se","by"}}, {0xE4,{"md","ee","kg","--","--","ua","--","pt","si","am","uz","ge","--","tm","ba"}}, {0xF0,{"au","au","au","au","au","au","au","au","sa","af","mm","cn","kp","bh","my"}}, {0xF1,{"ki","bt","bd","pk","fj","om","nr","ir","nz","sb","bn","lk","tw","kr","hk"}}, {0xF2,{"kw","qa","kh","ws","in","mo","vn","ph","jp","sg","mv","id","ae","np","vu"}}, {0xF3,{"la","th","to","--","--","--","--","--","pg","--","ye","--","--","fm","mn"}} }); std::string result("--"); uint16_t pi_cc = pi >> 12; if (country_codes.find(ecc) != country_codes.end() && pi_cc > 0) { result = country_codes.at(ecc).at(pi_cc-1); } return result; } std::string getLanguageString(uint16_t code) { std::vector<std::string> languages ({ "Unknown","Albanian","Breton","Catalan", "Croatian","Welsh","Czech","Danish", "German","English","Spanish","Esperanto", "Estonian","Basque","Faroese","French", "Frisian","Irish","Gaelic","Galician", "Icelandic","Italian","Lappish","Latin", "Latvian","Luxembourgian","Lithuanian","Hungarian", "Maltese","Dutch","Norwegian","Occitan", "Polish","Portuguese","Romanian","Romansh", "Serbian","Slovak","Slovene","Finnish", "Swedish","Turkish","Flemish","Walloon", "","","","", "","","","", "","","","", "","","","", "","","","", "Background","","","", "","Zulu","Vietnamese","Uzbek", "Urdu","Ukrainian","Thai","Telugu", "Tatar","Tamil","Tadzhik","Swahili", "SrananTongo","Somali","Sinhalese","Shona", "Serbo-Croat","Ruthenian","Russian","Quechua", "Pushtu","Punjabi","Persian","Papamiento", "Oriya","Nepali","Ndebele","Marathi", "Moldovian","Malaysian","Malagasay","Macedonian", "Laotian","Korean","Khmer","Kazakh", "Kannada","Japanese","Indonesian","Hindi", "Hebrew","Hausa","Gurani","Gujurati", "Greek","Georgian","Fulani","Dari", "Churash","Chinese","Burmese","Bulgarian", "Bengali","Belorussian","Bambora","Azerbaijan", "Assamese","Armenian","Arabic","Amharic" }); std::string result(""); if (code < languages.size()) { result = languages[code]; } return result; } std::string getAppName(uint16_t aid) { std::map<uint16_t,std::string> oda_apps({ { 0x0000, "None" }, { 0x0093, "Cross referencing DAB within RDS" }, { 0x0BCB, "Leisure & Practical Info for Drivers" }, { 0x0C24, "ELECTRABEL-DSM 7" }, { 0x0CC1, "Wireless Playground broadcast control signal" }, { 0x0D45, "RDS-TMC: ALERT-C / EN ISO 14819-1" }, { 0x0D8B, "ELECTRABEL-DSM 18" }, { 0x0E2C, "ELECTRABEL-DSM 3" }, { 0x0E31, "ELECTRABEL-DSM 13" }, { 0x0F87, "ELECTRABEL-DSM 2" }, { 0x125F, "I-FM-RDS for fixed and mobile devices" }, { 0x1BDA, "ELECTRABEL-DSM 1" }, { 0x1C5E, "ELECTRABEL-DSM 20" }, { 0x1C68, "ITIS In-vehicle data base" }, { 0x1CB1, "ELECTRABEL-DSM 10" }, { 0x1D47, "ELECTRABEL-DSM 4" }, { 0x1DC2, "CITIBUS 4" }, { 0x1DC5, "Encrypted TTI using ALERT-Plus" }, { 0x1E8F, "ELECTRABEL-DSM 17" }, { 0x4AA1, "RASANT" }, { 0x4AB7, "ELECTRABEL-DSM 9" }, { 0x4BA2, "ELECTRABEL-DSM 5" }, { 0x4BD7, "RadioText+ (RT+)" }, { 0x4C59, "CITIBUS 2" }, { 0x4D87, "Radio Commerce System (RCS)" }, { 0x4D95, "ELECTRABEL-DSM 16" }, { 0x4D9A, "ELECTRABEL-DSM 11" }, { 0x5757, "Personal weather station" }, { 0x6552, "Enhanced RadioText (eRT)" }, { 0x7373, "Enhanced early warning system" }, { 0xC350, "NRSC Song Title and Artist" }, { 0xC3A1, "Personal Radio Service" }, { 0xC3B0, "iTunes Tagging" }, { 0xC3C3, "NAVTEQ Traffic Plus" }, { 0xC4D4, "eEAS" }, { 0xC549, "Smart Grid Broadcast Channel" }, { 0xC563, "ID Logic" }, { 0xC6A7, "Veil Enabled Interactive Device" }, { 0xC737, "Utility Message Channel (UMC)" }, { 0xCB73, "CITIBUS 1" }, { 0xCB97, "ELECTRABEL-DSM 14" }, { 0xCC21, "CITIBUS 3" }, { 0xCD46, "RDS-TMC: ALERT-C" }, { 0xCD47, "RDS-TMC: ALERT-C" }, { 0xCD9E, "ELECTRABEL-DSM 8" }, { 0xCE6B, "Encrypted TTI using ALERT-Plus" }, { 0xE123, "APS Gateway" }, { 0xE1C1, "Action code" }, { 0xE319, "ELECTRABEL-DSM 12" }, { 0xE411, "Beacon downlink" }, { 0xE440, "ELECTRABEL-DSM 15" }, { 0xE4A6, "ELECTRABEL-DSM 19" }, { 0xE5D7, "ELECTRABEL-DSM 6" }, { 0xE911, "EAS open protocol" } }); std::string result("(Unknown)"); if (oda_apps.find(aid) != oda_apps.end()) { result = oda_apps[aid]; } return result; } } <|endoftext|>
<commit_before>// Copyright 2014 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 "apps/ui/native_app_window.h" #include "chrome/browser/apps/app_browsertest_util.h" using extensions::Extension; namespace apps { namespace { typedef extensions::PlatformAppBrowserTest AppWindowBrowserTest; // This test is disabled on Linux because of the unpredictable nature of native // windows. We cannot assume that the window manager will insert any title bar // at all, so the test may fail on certain window managers. #if defined(TOOLKIT_GTK) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) #define MAYBE_FrameInsetsForDefaultFrame DISABLED_FrameInsetsForDefaultFrame #else #define MAYBE_FrameInsetsForDefaultFrame FrameInsetsForDefaultFrame #endif // Verifies that the NativeAppWindows implement GetFrameInsets() correctly. // See crbug.com/346115 IN_PROC_BROWSER_TEST_F(AppWindowBrowserTest, MAYBE_FrameInsetsForDefaultFrame) { AppWindow* app_window = CreateTestAppWindow("{}"); NativeAppWindow* native_window = app_window->GetBaseWindow(); gfx::Insets insets = native_window->GetFrameInsets(); // It is a reasonable assumption that the top padding must be greater than // the bottom padding due to the title bar. EXPECT_TRUE(insets.top() > insets.bottom()); CloseAppWindow(app_window); } // This test is also disabled on Linux because frame: color is ignored on stable // and beta channels (so it can fail the same as the previous test). // TODO(benwells): Re-enable on Linux after frame: color is on stable. #if defined(TOOLKIT_GTK) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) #define MAYBE_FrameInsetsForColoredFrame DISABLED_FrameInsetsForColoredFrame #else #define MAYBE_FrameInsetsForColoredFrame FrameInsetsForColoredFrame #endif // Verifies that the NativeAppWindows implement GetFrameInsets() correctly. // See crbug.com/346115 IN_PROC_BROWSER_TEST_F(AppWindowBrowserTest, MAYBE_FrameInsetsForColoredFrame) { AppWindow* app_window = CreateTestAppWindow("{ \"frame\": { \"color\": \"#ffffff\" } }"); NativeAppWindow* native_window = app_window->GetBaseWindow(); gfx::Insets insets = native_window->GetFrameInsets(); // It is a reasonable assumption that the top padding must be greater than // the bottom padding due to the title bar. EXPECT_TRUE(insets.top() > insets.bottom()); CloseAppWindow(app_window); } // Verifies that the NativeAppWindows implement GetFrameInsets() correctly for // frameless windows. IN_PROC_BROWSER_TEST_F(AppWindowBrowserTest, FrameInsetsForNoFrame) { AppWindow* app_window = CreateTestAppWindow("{ \"frame\": \"none\" }"); NativeAppWindow* native_window = app_window->GetBaseWindow(); gfx::Insets insets = native_window->GetFrameInsets(); // All insets must be zero. EXPECT_EQ(0, insets.top()); EXPECT_EQ(0, insets.bottom()); EXPECT_EQ(0, insets.left()); EXPECT_EQ(0, insets.right()); CloseAppWindow(app_window); } } // namespace } // namespace apps <commit_msg>Minor cleanup of app_window_browsertest.<commit_after>// Copyright 2014 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 "apps/ui/native_app_window.h" #include "chrome/browser/apps/app_browsertest_util.h" using extensions::Extension; namespace apps { namespace { typedef extensions::PlatformAppBrowserTest AppWindowBrowserTest; // This test is disabled on Linux because of the unpredictable nature of native // windows. We cannot assume that the window manager will insert any title bar // at all, so the test may fail on certain window managers. #if defined(TOOLKIT_GTK) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) #define MAYBE_FrameInsetsForDefaultFrame DISABLED_FrameInsetsForDefaultFrame #else #define MAYBE_FrameInsetsForDefaultFrame FrameInsetsForDefaultFrame #endif // Verifies that the NativeAppWindows implement GetFrameInsets() correctly. // See http://crbug.com/346115 IN_PROC_BROWSER_TEST_F(AppWindowBrowserTest, MAYBE_FrameInsetsForDefaultFrame) { AppWindow* app_window = CreateTestAppWindow("{}"); NativeAppWindow* native_window = app_window->GetBaseWindow(); gfx::Insets insets = native_window->GetFrameInsets(); // It is a reasonable assumption that the top padding must be greater than // the bottom padding due to the title bar. EXPECT_GT(insets.top(), insets.bottom()); CloseAppWindow(app_window); } // This test is also disabled on Linux because frame: color is ignored on stable // and beta channels (so it can fail the same as the previous test). // TODO(benwells): Re-enable on Linux after frame: color is on stable. #if defined(TOOLKIT_GTK) || (defined(OS_LINUX) && !defined(OS_CHROMEOS)) #define MAYBE_FrameInsetsForColoredFrame DISABLED_FrameInsetsForColoredFrame #else #define MAYBE_FrameInsetsForColoredFrame FrameInsetsForColoredFrame #endif // Verifies that the NativeAppWindows implement GetFrameInsets() correctly. // See http://crbug.com/346115 IN_PROC_BROWSER_TEST_F(AppWindowBrowserTest, MAYBE_FrameInsetsForColoredFrame) { AppWindow* app_window = CreateTestAppWindow("{ \"frame\": { \"color\": \"#ffffff\" } }"); NativeAppWindow* native_window = app_window->GetBaseWindow(); gfx::Insets insets = native_window->GetFrameInsets(); // It is a reasonable assumption that the top padding must be greater than // the bottom padding due to the title bar. EXPECT_GT(insets.top(), insets.bottom()); CloseAppWindow(app_window); } // Verifies that the NativeAppWindows implement GetFrameInsets() correctly for // frameless windows. IN_PROC_BROWSER_TEST_F(AppWindowBrowserTest, FrameInsetsForNoFrame) { AppWindow* app_window = CreateTestAppWindow("{ \"frame\": \"none\" }"); NativeAppWindow* native_window = app_window->GetBaseWindow(); gfx::Insets insets = native_window->GetFrameInsets(); // All insets must be zero. EXPECT_EQ(0, insets.top()); EXPECT_EQ(0, insets.bottom()); EXPECT_EQ(0, insets.left()); EXPECT_EQ(0, insets.right()); CloseAppWindow(app_window); } } // namespace } // namespace apps <|endoftext|>
<commit_before>#include <aerial_autonomy/estimators/tracking_vector_estimator.h> #include <aerial_autonomy/log/log.h> #include <glog/logging.h> TrackingVectorEstimator::TrackingVectorEstimator( TrackingVectorEstimatorConfig config, std::chrono::duration<double> propagation_step) : config_(config), filter_(3, 3, 3, CV_64F), zero_tolerance_(1e-6), initial_state_initialized_(false) { // Assuming x = [Marker direction] and u = [velocity] // Transition matrix filter_.transitionMatrix = cv::Mat_<double>::eye(3, 3); filter_.controlMatrix = -propagation_step.count() * cv::Mat_<double>::eye(3, 3); // Measurement matrix filter_.measurementMatrix = cv::Mat_<double>::eye(3, 3); // Check stdeviation vectors checkStdVector(config_.marker_process_stdev()); checkStdVector(config_.marker_meas_stdev()); checkStdVector(config_.marker_initial_stdev()); checkStdVector(config_.marker_dilation_stdev()); // Noise matrices setCovarianceMatrix(filter_.processNoiseCov, config_.marker_process_stdev()); setCovarianceMatrix(filter_.measurementNoiseCov, config_.marker_meas_stdev()); // Save variables marker_dilation_stdev_ = tf::Vector3(config_.marker_dilation_stdev().x(), config_.marker_dilation_stdev().y(), config_.marker_dilation_stdev().z()); marker_meas_stdev_ = tf::Vector3(config_.marker_meas_stdev().x(), config_.marker_meas_stdev().y(), config_.marker_meas_stdev().z()); // Set initial state initializeState(tf::Vector3(0, 0, 0)); DATA_HEADER("tracking_vector_estimator") << "Measured_Marker_x" << "Measured_Marker_y" << "Measured_Marker_z" << "Marker_x" << "Marker_y" << "Marker_z" << "Meas_noise_x" << "Meas_noise_y" << "Meas_noise_z" << "Noise_x" << "Noise_y" << "Noise_z" << DataStream::endl; } void TrackingVectorEstimator::initializeState(tf::Vector3 marker_direction) { VLOG(1) << "Initializing KF with Marker dirxn: " << marker_direction.x() << marker_direction.y() << marker_direction.z(); filter_.statePre = (cv::Mat_<double>(3, 1) << marker_direction.x(), marker_direction.y(), marker_direction.z()); setCovarianceMatrix(filter_.errorCovPost, config_.marker_initial_stdev()); filter_.statePre.copyTo(filter_.statePost); initial_state_initialized_ = true; } void TrackingVectorEstimator::predict(tf::Vector3 velocity) { cv::Mat_<double> control = (cv::Mat_<double>(3, 1) << velocity.x(), velocity.y(), velocity.z()); filter_.predict(control); } void TrackingVectorEstimator::setMeasurementCovariance( cv::Mat &covariance_mat, std::chrono::time_point<std::chrono::high_resolution_clock> marker_time_stamp) { double dt = std::chrono::duration<double>( std::chrono::high_resolution_clock::now() - marker_time_stamp) .count(); if (dt < 0) { LOG(WARNING) << "dt negative: " << dt; dt = 0; } tf::Vector3 current_meas_stdev = marker_meas_stdev_ + dt * marker_dilation_stdev_; setCovarianceMatrix(covariance_mat, current_meas_stdev); } void TrackingVectorEstimator::correct( tf::Vector3 marker_direction, std::chrono::time_point<std::chrono::high_resolution_clock> marker_time_stamp) { if (!initial_state_initialized_) { initializeState(marker_direction); return; } cv::Mat_<double> measurement = (cv::Mat_<double>(3, 1) << marker_direction.x(), marker_direction.y(), marker_direction.z()); setMeasurementCovariance(filter_.measurementNoiseCov, marker_time_stamp); filter_.correct(measurement); // Log data tf::Vector3 marker_noise = getMarkerNoise(); auto state = filter_.statePost; auto &data_stream = Log::instance()["tracking_vector_estimator"]; data_stream << DataStream::startl; for (int i = 0; i < 3; ++i) { data_stream << measurement.at<double>(i); } for (int i = 0; i < 3; ++i) { data_stream << state.at<double>(i); } for (int i = 0; i < 3; ++i) { data_stream << sqrt(filter_.measurementNoiseCov.at<double>(i, i)); } for (int i = 0; i < 3; ++i) { data_stream << marker_noise[i]; } data_stream << DataStream::endl; } <commit_msg>Print warning if time difference is too high in estimator<commit_after>#include <aerial_autonomy/estimators/tracking_vector_estimator.h> #include <aerial_autonomy/log/log.h> #include <glog/logging.h> TrackingVectorEstimator::TrackingVectorEstimator( TrackingVectorEstimatorConfig config, std::chrono::duration<double> propagation_step) : config_(config), filter_(3, 3, 3, CV_64F), zero_tolerance_(1e-6), initial_state_initialized_(false) { // Assuming x = [Marker direction] and u = [velocity] // Transition matrix filter_.transitionMatrix = cv::Mat_<double>::eye(3, 3); filter_.controlMatrix = -propagation_step.count() * cv::Mat_<double>::eye(3, 3); // Measurement matrix filter_.measurementMatrix = cv::Mat_<double>::eye(3, 3); // Check stdeviation vectors checkStdVector(config_.marker_process_stdev()); checkStdVector(config_.marker_meas_stdev()); checkStdVector(config_.marker_initial_stdev()); checkStdVector(config_.marker_dilation_stdev()); // Noise matrices setCovarianceMatrix(filter_.processNoiseCov, config_.marker_process_stdev()); setCovarianceMatrix(filter_.measurementNoiseCov, config_.marker_meas_stdev()); // Save variables marker_dilation_stdev_ = tf::Vector3(config_.marker_dilation_stdev().x(), config_.marker_dilation_stdev().y(), config_.marker_dilation_stdev().z()); marker_meas_stdev_ = tf::Vector3(config_.marker_meas_stdev().x(), config_.marker_meas_stdev().y(), config_.marker_meas_stdev().z()); // Set initial state initializeState(tf::Vector3(0, 0, 0)); DATA_HEADER("tracking_vector_estimator") << "Measured_Marker_x" << "Measured_Marker_y" << "Measured_Marker_z" << "Marker_x" << "Marker_y" << "Marker_z" << "Meas_noise_x" << "Meas_noise_y" << "Meas_noise_z" << "Noise_x" << "Noise_y" << "Noise_z" << DataStream::endl; } void TrackingVectorEstimator::initializeState(tf::Vector3 marker_direction) { VLOG(1) << "Initializing KF with Marker dirxn: " << marker_direction.x() << marker_direction.y() << marker_direction.z(); filter_.statePre = (cv::Mat_<double>(3, 1) << marker_direction.x(), marker_direction.y(), marker_direction.z()); setCovarianceMatrix(filter_.errorCovPost, config_.marker_initial_stdev()); filter_.statePre.copyTo(filter_.statePost); initial_state_initialized_ = true; } void TrackingVectorEstimator::predict(tf::Vector3 velocity) { cv::Mat_<double> control = (cv::Mat_<double>(3, 1) << velocity.x(), velocity.y(), velocity.z()); filter_.predict(control); } void TrackingVectorEstimator::setMeasurementCovariance( cv::Mat &covariance_mat, std::chrono::time_point<std::chrono::high_resolution_clock> marker_time_stamp) { double dt = std::chrono::duration<double>( std::chrono::high_resolution_clock::now() - marker_time_stamp) .count(); if (dt < 0) { LOG(WARNING) << "dt negative: " << dt; dt = 0; } else if (dt > 1.0) { LOG(WARNING) << "dt too high: " << dt; dt = 1.0; } tf::Vector3 current_meas_stdev = marker_meas_stdev_ + dt * marker_dilation_stdev_; setCovarianceMatrix(covariance_mat, current_meas_stdev); } void TrackingVectorEstimator::correct( tf::Vector3 marker_direction, std::chrono::time_point<std::chrono::high_resolution_clock> marker_time_stamp) { if (!initial_state_initialized_) { initializeState(marker_direction); return; } cv::Mat_<double> measurement = (cv::Mat_<double>(3, 1) << marker_direction.x(), marker_direction.y(), marker_direction.z()); setMeasurementCovariance(filter_.measurementNoiseCov, marker_time_stamp); filter_.correct(measurement); // Log data tf::Vector3 marker_noise = getMarkerNoise(); auto state = filter_.statePost; auto &data_stream = Log::instance()["tracking_vector_estimator"]; data_stream << DataStream::startl; for (int i = 0; i < 3; ++i) { data_stream << measurement.at<double>(i); } for (int i = 0; i < 3; ++i) { data_stream << state.at<double>(i); } for (int i = 0; i < 3; ++i) { data_stream << sqrt(filter_.measurementNoiseCov.at<double>(i, i)); } for (int i = 0; i < 3; ++i) { data_stream << marker_noise[i]; } data_stream << DataStream::endl; } <|endoftext|>
<commit_before>// Copyright 2016 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 "gpu_surface_gl.h" #if OS_MACOSX || OS_IOS #include <OpenGLES/ES2/gl.h> #include <OpenGLES/ES2/glext.h> #else #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #endif #include "flutter/glue/trace_event.h" #include "lib/fxl/arraysize.h" #include "lib/fxl/logging.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrContextOptions.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" namespace shell { // Default maximum number of budgeted resources in the cache. static const int kGrCacheMaxCount = 8192; // Default maximum number of bytes of GPU memory of budgeted resources in the // cache. static const size_t kGrCacheMaxByteSize = 512 * (1 << 20); GPUSurfaceGL::GPUSurfaceGL(GPUSurfaceGLDelegate* delegate) : delegate_(delegate), weak_factory_(this) { if (!delegate_->GLContextMakeCurrent()) { FXL_LOG(ERROR) << "Could not make the context current to setup the gr context."; return; } GrContextOptions options; options.fAvoidStencilBuffers = true; auto context = GrContext::MakeGL(GrGLMakeNativeInterface(), options); if (context == nullptr) { FXL_LOG(ERROR) << "Failed to setup Skia Gr context."; return; } context_ = std::move(context); context_->setResourceCacheLimits(kGrCacheMaxCount, kGrCacheMaxByteSize); delegate_->GLContextClearCurrent(); valid_ = true; } GPUSurfaceGL::~GPUSurfaceGL() { if (!valid_) { return; } if (!delegate_->GLContextMakeCurrent()) { FXL_LOG(ERROR) << "Could not make the context current to destroy the " "GrContext resources."; return; } onscreen_surface_ = nullptr; context_->releaseResourcesAndAbandonContext(); context_ = nullptr; delegate_->GLContextClearCurrent(); } bool GPUSurfaceGL::IsValid() { return valid_; } static SkColorType FirstSupportedColorType(GrContext* context, GLenum* format) { #define RETURN_IF_RENDERABLE(x, y) \ if (context->colorTypeSupportedAsSurface((x))) { \ *format = (y); \ return (x); \ } RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GL_RGBA8_OES); RETURN_IF_RENDERABLE(kARGB_4444_SkColorType, GL_RGBA4); RETURN_IF_RENDERABLE(kRGB_565_SkColorType, GL_RGB565); return kUnknown_SkColorType; } static sk_sp<SkSurface> WrapOnscreenSurface(GrContext* context, const SkISize& size, intptr_t fbo) { GLenum format; const SkColorType color_type = FirstSupportedColorType(context, &format); const GrGLFramebufferInfo framebuffer_info = { .fFBOID = static_cast<GrGLuint>(fbo), .fFormat = format, }; GrBackendRenderTarget render_target(size.fWidth, // width size.fHeight, // height 0, // sample count 0, // stencil bits (TODO) framebuffer_info // framebuffer info ); sk_sp<SkColorSpace> colorspace = nullptr; SkSurfaceProps surface_props( SkSurfaceProps::InitType::kLegacyFontHost_InitType); return SkSurface::MakeFromBackendRenderTarget( context, // gr context render_target, // render target GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin, // origin color_type, // color type colorspace, // colorspace &surface_props // surface properties ); } static sk_sp<SkSurface> CreateOffscreenSurface(GrContext* context, const SkISize& size) { const SkImageInfo image_info = SkImageInfo::MakeN32(size.fWidth, size.fHeight, kOpaque_SkAlphaType); const SkSurfaceProps surface_props( SkSurfaceProps::InitType::kLegacyFontHost_InitType); return SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, image_info, 0, kBottomLeft_GrSurfaceOrigin, &surface_props); } bool GPUSurfaceGL::CreateOrUpdateSurfaces(const SkISize& size) { if (onscreen_surface_ != nullptr && size == SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height())) { // Surface size appears unchanged. So bail. return true; } // We need to do some updates. TRACE_EVENT0("flutter", "UpdateSurfacesSize"); // Either way, we need to get rid of previous surface. onscreen_surface_ = nullptr; offscreen_surface_ = nullptr; if (size.isEmpty()) { FXL_LOG(ERROR) << "Cannot create surfaces of empty size."; return false; } sk_sp<SkSurface> onscreen_surface, offscreen_surface; onscreen_surface = WrapOnscreenSurface(context_.get(), size, delegate_->GLContextFBO()); if (onscreen_surface == nullptr) { // If the onscreen surface could not be wrapped. There is absolutely no // point in moving forward. FXL_LOG(ERROR) << "Could not wrap onscreen surface."; return false; } if (delegate_->UseOffscreenSurface()) { offscreen_surface = CreateOffscreenSurface(context_.get(), size); if (offscreen_surface == nullptr) { FXL_LOG(ERROR) << "Could not create offscreen surface."; return false; } } onscreen_surface_ = std::move(onscreen_surface); offscreen_surface_ = std::move(offscreen_surface); return true; } std::unique_ptr<SurfaceFrame> GPUSurfaceGL::AcquireFrame(const SkISize& size) { if (delegate_ == nullptr) { return nullptr; } if (!delegate_->GLContextMakeCurrent()) { FXL_LOG(ERROR) << "Could not make the context current to acquire the frame."; return nullptr; } sk_sp<SkSurface> surface = AcquireRenderSurface(size); if (surface == nullptr) { return nullptr; } auto weak_this = weak_factory_.GetWeakPtr(); SurfaceFrame::SubmitCallback submit_callback = [weak_this](const SurfaceFrame& surface_frame, SkCanvas* canvas) { return weak_this ? weak_this->PresentSurface(canvas) : false; }; return std::make_unique<SurfaceFrame>(surface, submit_callback); } bool GPUSurfaceGL::PresentSurface(SkCanvas* canvas) { if (delegate_ == nullptr || canvas == nullptr || context_ == nullptr) { return false; } if (offscreen_surface_ != nullptr) { TRACE_EVENT0("flutter", "CopyTextureOnscreen"); SkPaint paint; onscreen_surface_->getCanvas()->drawImage( offscreen_surface_->makeImageSnapshot(), 0, 0, &paint); } { TRACE_EVENT0("flutter", "SkCanvas::Flush"); onscreen_surface_->getCanvas()->flush(); } delegate_->GLContextPresent(); return true; } sk_sp<SkSurface> GPUSurfaceGL::AcquireRenderSurface(const SkISize& size) { if (!CreateOrUpdateSurfaces(size)) { return nullptr; } return offscreen_surface_ != nullptr ? offscreen_surface_ : onscreen_surface_; } GrContext* GPUSurfaceGL::GetContext() { return context_.get(); } } // namespace shell <commit_msg>Fix GPUSurfaceGL includes on macOS (#4844)<commit_after>// Copyright 2016 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 "gpu_surface_gl.h" #if OS_IOS #include <OpenGLES/ES2/gl.h> #include <OpenGLES/ES2/glext.h> #elif OS_MACOSX #include <OpenGL/gl3.h> #else #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #endif #include "flutter/glue/trace_event.h" #include "lib/fxl/arraysize.h" #include "lib/fxl/logging.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/GrContextOptions.h" #include "third_party/skia/include/gpu/gl/GrGLInterface.h" namespace shell { // Default maximum number of budgeted resources in the cache. static const int kGrCacheMaxCount = 8192; // Default maximum number of bytes of GPU memory of budgeted resources in the // cache. static const size_t kGrCacheMaxByteSize = 512 * (1 << 20); GPUSurfaceGL::GPUSurfaceGL(GPUSurfaceGLDelegate* delegate) : delegate_(delegate), weak_factory_(this) { if (!delegate_->GLContextMakeCurrent()) { FXL_LOG(ERROR) << "Could not make the context current to setup the gr context."; return; } GrContextOptions options; options.fAvoidStencilBuffers = true; auto context = GrContext::MakeGL(GrGLMakeNativeInterface(), options); if (context == nullptr) { FXL_LOG(ERROR) << "Failed to setup Skia Gr context."; return; } context_ = std::move(context); context_->setResourceCacheLimits(kGrCacheMaxCount, kGrCacheMaxByteSize); delegate_->GLContextClearCurrent(); valid_ = true; } GPUSurfaceGL::~GPUSurfaceGL() { if (!valid_) { return; } if (!delegate_->GLContextMakeCurrent()) { FXL_LOG(ERROR) << "Could not make the context current to destroy the " "GrContext resources."; return; } onscreen_surface_ = nullptr; context_->releaseResourcesAndAbandonContext(); context_ = nullptr; delegate_->GLContextClearCurrent(); } bool GPUSurfaceGL::IsValid() { return valid_; } static SkColorType FirstSupportedColorType(GrContext* context, GLenum* format) { #define RETURN_IF_RENDERABLE(x, y) \ if (context->colorTypeSupportedAsSurface((x))) { \ *format = (y); \ return (x); \ } #if OS_MACOSX RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GL_RGBA8); #else RETURN_IF_RENDERABLE(kRGBA_8888_SkColorType, GL_RGBA8_OES); #endif RETURN_IF_RENDERABLE(kARGB_4444_SkColorType, GL_RGBA4); RETURN_IF_RENDERABLE(kRGB_565_SkColorType, GL_RGB565); return kUnknown_SkColorType; } static sk_sp<SkSurface> WrapOnscreenSurface(GrContext* context, const SkISize& size, intptr_t fbo) { GLenum format; const SkColorType color_type = FirstSupportedColorType(context, &format); const GrGLFramebufferInfo framebuffer_info = { .fFBOID = static_cast<GrGLuint>(fbo), .fFormat = format, }; GrBackendRenderTarget render_target(size.fWidth, // width size.fHeight, // height 0, // sample count 0, // stencil bits (TODO) framebuffer_info // framebuffer info ); sk_sp<SkColorSpace> colorspace = nullptr; SkSurfaceProps surface_props( SkSurfaceProps::InitType::kLegacyFontHost_InitType); return SkSurface::MakeFromBackendRenderTarget( context, // gr context render_target, // render target GrSurfaceOrigin::kBottomLeft_GrSurfaceOrigin, // origin color_type, // color type colorspace, // colorspace &surface_props // surface properties ); } static sk_sp<SkSurface> CreateOffscreenSurface(GrContext* context, const SkISize& size) { const SkImageInfo image_info = SkImageInfo::MakeN32(size.fWidth, size.fHeight, kOpaque_SkAlphaType); const SkSurfaceProps surface_props( SkSurfaceProps::InitType::kLegacyFontHost_InitType); return SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, image_info, 0, kBottomLeft_GrSurfaceOrigin, &surface_props); } bool GPUSurfaceGL::CreateOrUpdateSurfaces(const SkISize& size) { if (onscreen_surface_ != nullptr && size == SkISize::Make(onscreen_surface_->width(), onscreen_surface_->height())) { // Surface size appears unchanged. So bail. return true; } // We need to do some updates. TRACE_EVENT0("flutter", "UpdateSurfacesSize"); // Either way, we need to get rid of previous surface. onscreen_surface_ = nullptr; offscreen_surface_ = nullptr; if (size.isEmpty()) { FXL_LOG(ERROR) << "Cannot create surfaces of empty size."; return false; } sk_sp<SkSurface> onscreen_surface, offscreen_surface; onscreen_surface = WrapOnscreenSurface(context_.get(), size, delegate_->GLContextFBO()); if (onscreen_surface == nullptr) { // If the onscreen surface could not be wrapped. There is absolutely no // point in moving forward. FXL_LOG(ERROR) << "Could not wrap onscreen surface."; return false; } if (delegate_->UseOffscreenSurface()) { offscreen_surface = CreateOffscreenSurface(context_.get(), size); if (offscreen_surface == nullptr) { FXL_LOG(ERROR) << "Could not create offscreen surface."; return false; } } onscreen_surface_ = std::move(onscreen_surface); offscreen_surface_ = std::move(offscreen_surface); return true; } std::unique_ptr<SurfaceFrame> GPUSurfaceGL::AcquireFrame(const SkISize& size) { if (delegate_ == nullptr) { return nullptr; } if (!delegate_->GLContextMakeCurrent()) { FXL_LOG(ERROR) << "Could not make the context current to acquire the frame."; return nullptr; } sk_sp<SkSurface> surface = AcquireRenderSurface(size); if (surface == nullptr) { return nullptr; } auto weak_this = weak_factory_.GetWeakPtr(); SurfaceFrame::SubmitCallback submit_callback = [weak_this](const SurfaceFrame& surface_frame, SkCanvas* canvas) { return weak_this ? weak_this->PresentSurface(canvas) : false; }; return std::make_unique<SurfaceFrame>(surface, submit_callback); } bool GPUSurfaceGL::PresentSurface(SkCanvas* canvas) { if (delegate_ == nullptr || canvas == nullptr || context_ == nullptr) { return false; } if (offscreen_surface_ != nullptr) { TRACE_EVENT0("flutter", "CopyTextureOnscreen"); SkPaint paint; onscreen_surface_->getCanvas()->drawImage( offscreen_surface_->makeImageSnapshot(), 0, 0, &paint); } { TRACE_EVENT0("flutter", "SkCanvas::Flush"); onscreen_surface_->getCanvas()->flush(); } delegate_->GLContextPresent(); return true; } sk_sp<SkSurface> GPUSurfaceGL::AcquireRenderSurface(const SkISize& size) { if (!CreateOrUpdateSurfaces(size)) { return nullptr; } return offscreen_surface_ != nullptr ? offscreen_surface_ : onscreen_surface_; } GrContext* GPUSurfaceGL::GetContext() { return context_.get(); } } // namespace shell <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "init.h" #include "main.h" #include "net.h" #include "netbase.h" #include "rpcserver.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #include "walletdb.h" #endif #include <stdint.h> #include <boost/assign/list_of.hpp> #include "json/json_spirit_utils.h" #include "json/json_spirit_value.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info.\n" "\nResult:\n" "{\n" " \"version\": xxxxx, (numeric) the server version\n" " \"protocolversion\": xxxxx, (numeric) the protocol version\n" " \"walletversion\": xxxxx, (numeric) the wallet version\n" " \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"timeoffset\": xxxxx, (numeric) the time offset\n" " \"connections\": xxxxx, (numeric) the number of connections\n" " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"testnet\": true|false, (boolean) if the server is using testnet or not\n" " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n" " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n" " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in btc/kb\n" " \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in btc/kb\n" " \"errors\": \"...\" (string) any error messages\n" "}\n" "\nExamples:\n" + HelpExampleCli("getinfo", "") + HelpExampleRpc("getinfo", "") ); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj; obj.push_back(Pair("mastercoreversion", (int)1091008)); // strip the initial '10' : for tagged release go to 10007, etc. obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); #ifdef ENABLE_WALLET if (pwalletMain) { obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); } #endif obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("timeoffset", GetTimeOffset())); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", TestNet())); #ifdef ENABLE_WALLET if (pwalletMain) { obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); } if (pwalletMain && pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", nWalletUnlockTime)); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); #endif obj.push_back(Pair("relayfee", ValueFromAmount(CTransaction::nMinRelayTxFee))); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } #ifdef ENABLE_WALLET class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; #endif Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress \"bitcoinaddress\"\n" "\nReturn information about the given bitcoin address.\n" "\nArguments:\n" "1. \"bitcoinaddress\" (string, required) The bitcoin address to validate\n" "\nResult:\n" "{\n" " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n" " \"address\" : \"bitcoinaddress\", (string) The bitcoin address validated\n" " \"ismine\" : true|false, (boolean) If the address is yours or not\n" " \"isscript\" : true|false, (boolean) If the key is a script\n" " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n" " \"iscompressed\" : true|false, (boolean) If the address is compressed\n" " \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n" "}\n" "\nExamples:\n" + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") ); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); #ifdef ENABLE_WALLET bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false; ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain && pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name)); #endif } return ret; } // // Used by addmultisigaddress / createmultisig: // CScript _createmultisig_redeemScript(const Array& params) { int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); #ifdef ENABLE_WALLET // Case 1: Bitcoin address and we have full public key: CBitcoinAddress address(ks); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks)); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else #endif if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } else { throw runtime_error(" Invalid public key: "+ks); } } CScript result; result.SetMultisig(nRequired, pubkeys); if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) throw runtime_error( strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE)); return result; } Value createmultisig(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 2) { string msg = "createmultisig nrequired [\"key\",...]\n" "\nCreates a multi-signature address with n signature of m keys required.\n" "It returns a json object with the address and redeemScript.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n" "2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n" " [\n" " \"key\" (string) bitcoin address or hex-encoded public key\n" " ,...\n" " ]\n" "\nResult:\n" "{\n" " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n" " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n" "}\n" "\nExamples:\n" "\nCreate a multisig address from 2 addresses\n" + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") ; throw runtime_error(msg); } // Construct using pay-to-script-hash: CScript inner = _createmultisig_redeemScript(params); CScriptID innerID = inner.GetID(); CBitcoinAddress address(innerID); Object result; result.push_back(Pair("address", address.ToString())); result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end()))); return result; } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage \"bitcoinaddress\" \"signature\" \"message\"\n" "\nVerify a signed message\n" "\nArguments:\n" "1. \"bitcoinaddress\" (string, required) The bitcoin address to use for the signature.\n" "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n" "3. \"message\" (string, required) The message that was signed.\n" "\nResult:\n" "true|false (boolean) If the signature is verified or not.\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"") ); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == keyID); } <commit_msg>version bump<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "init.h" #include "main.h" #include "net.h" #include "netbase.h" #include "rpcserver.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #include "walletdb.h" #endif #include <stdint.h> #include <boost/assign/list_of.hpp> #include "json/json_spirit_utils.h" #include "json/json_spirit_value.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info.\n" "\nResult:\n" "{\n" " \"version\": xxxxx, (numeric) the server version\n" " \"protocolversion\": xxxxx, (numeric) the protocol version\n" " \"walletversion\": xxxxx, (numeric) the wallet version\n" " \"balance\": xxxxxxx, (numeric) the total bitcoin balance of the wallet\n" " \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n" " \"timeoffset\": xxxxx, (numeric) the time offset\n" " \"connections\": xxxxx, (numeric) the number of connections\n" " \"proxy\": \"host:port\", (string, optional) the proxy used by the server\n" " \"difficulty\": xxxxxx, (numeric) the current difficulty\n" " \"testnet\": true|false, (boolean) if the server is using testnet or not\n" " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n" " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n" " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" " \"paytxfee\": x.xxxx, (numeric) the transaction fee set in btc/kb\n" " \"relayfee\": x.xxxx, (numeric) minimum relay fee for non-free transactions in btc/kb\n" " \"errors\": \"...\" (string) any error messages\n" "}\n" "\nExamples:\n" + HelpExampleCli("getinfo", "") + HelpExampleRpc("getinfo", "") ); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj; obj.push_back(Pair("mastercoreversion", (int)1101008)); // strip the initial '10' : for tagged release go to 10007, etc. obj.push_back(Pair("version", (int)CLIENT_VERSION)); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); #ifdef ENABLE_WALLET if (pwalletMain) { obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); } #endif obj.push_back(Pair("blocks", (int)chainActive.Height())); obj.push_back(Pair("timeoffset", GetTimeOffset())); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("testnet", TestNet())); #ifdef ENABLE_WALLET if (pwalletMain) { obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); } if (pwalletMain && pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", nWalletUnlockTime)); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); #endif obj.push_back(Pair("relayfee", ValueFromAmount(CTransaction::nMinRelayTxFee))); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } #ifdef ENABLE_WALLET class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; #endif Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress \"bitcoinaddress\"\n" "\nReturn information about the given bitcoin address.\n" "\nArguments:\n" "1. \"bitcoinaddress\" (string, required) The bitcoin address to validate\n" "\nResult:\n" "{\n" " \"isvalid\" : true|false, (boolean) If the address is valid or not. If not, this is the only property returned.\n" " \"address\" : \"bitcoinaddress\", (string) The bitcoin address validated\n" " \"ismine\" : true|false, (boolean) If the address is yours or not\n" " \"isscript\" : true|false, (boolean) If the key is a script\n" " \"pubkey\" : \"publickeyhex\", (string) The hex value of the raw public key\n" " \"iscompressed\" : true|false, (boolean) If the address is compressed\n" " \"account\" : \"account\" (string) The account associated with the address, \"\" is the default account\n" "}\n" "\nExamples:\n" + HelpExampleCli("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") + HelpExampleRpc("validateaddress", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"") ); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); #ifdef ENABLE_WALLET bool fMine = pwalletMain ? IsMine(*pwalletMain, dest) : false; ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain && pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest].name)); #endif } return ret; } // // Used by addmultisigaddress / createmultisig: // CScript _createmultisig_redeemScript(const Array& params) { int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %u keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CPubKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); #ifdef ENABLE_WALLET // Case 1: Bitcoin address and we have full public key: CBitcoinAddress address(ks); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks)); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } // Case 2: hex public key else #endif if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsFullyValid()) throw runtime_error(" Invalid public key: "+ks); pubkeys[i] = vchPubKey; } else { throw runtime_error(" Invalid public key: "+ks); } } CScript result; result.SetMultisig(nRequired, pubkeys); if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) throw runtime_error( strprintf("redeemScript exceeds size limit: %d > %d", result.size(), MAX_SCRIPT_ELEMENT_SIZE)); return result; } Value createmultisig(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 2) { string msg = "createmultisig nrequired [\"key\",...]\n" "\nCreates a multi-signature address with n signature of m keys required.\n" "It returns a json object with the address and redeemScript.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n" "2. \"keys\" (string, required) A json array of keys which are bitcoin addresses or hex-encoded public keys\n" " [\n" " \"key\" (string) bitcoin address or hex-encoded public key\n" " ,...\n" " ]\n" "\nResult:\n" "{\n" " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n" " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n" "}\n" "\nExamples:\n" "\nCreate a multisig address from 2 addresses\n" + HelpExampleCli("createmultisig", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("createmultisig", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") ; throw runtime_error(msg); } // Construct using pay-to-script-hash: CScript inner = _createmultisig_redeemScript(params); CScriptID innerID = inner.GetID(); CBitcoinAddress address(innerID); Object result; result.push_back(Pair("address", address.ToString())); result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end()))); return result; } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage \"bitcoinaddress\" \"signature\" \"message\"\n" "\nVerify a signed message\n" "\nArguments:\n" "1. \"bitcoinaddress\" (string, required) The bitcoin address to use for the signature.\n" "2. \"signature\" (string, required) The signature provided by the signer in base 64 encoding (see signmessage).\n" "3. \"message\" (string, required) The message that was signed.\n" "\nResult:\n" "true|false (boolean) If the signature is verified or not.\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ\", \"signature\", \"my message\"") ); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) return false; return (pubkey.GetID() == keyID); } <|endoftext|>
<commit_before>#include "array_view.hh" #include "vector.hh" namespace Kakoune { template<typename T> struct MirroredArray : public ArrayView<T> { MirroredArray(ArrayView<T> data, int size) : ArrayView<T>(data), size(size) { kak_assert(2 * size + 1 <= data.size()); } T& operator[](int n) { return ArrayView<T>::operator[](n + size); } const T& operator[](int n) const { return ArrayView<T>::operator[](n + size); } private: int size; }; struct Snake{ int x, y, u, v; bool add; }; template<typename Iterator> Snake find_end_snake_of_further_reaching_dpath(Iterator a, int N, Iterator b, int M, const MirroredArray<int>& V, const int D, const int k) { int x; // our position along a const bool add = k == -D or (k != D and V[k-1] < V[k+1]); // if diagonal on the right goes further along x than diagonal on the left, // then we take a vertical edge from it to this diagonal, hence x = V[k+1] if (add) x = V[k+1]; // else, we take an horizontal edge from our left diagonal,x = V[k-1]+1 else x = V[k-1]+1; int y = x - k; // we are by construction on diagonal k, so our position along // b (y) is x - k. int u = x, v = y; // follow end snake along diagonal k while (u < N and v < M and a[u] == b[v]) ++u, ++v; return { x, y, u, v, add }; } struct SnakeLen : Snake { SnakeLen(Snake s, int d) : Snake(s), d(d) {} int d; }; template<typename Iterator> SnakeLen find_middle_snake(Iterator a, int N, Iterator b, int M, ArrayView<int> data1, ArrayView<int> data2) { const int delta = N - M; MirroredArray<int> V1{data1, N + M}; MirroredArray<int> V2{data2, N + M}; std::reverse_iterator<Iterator> ra{a + N}, rb{b + M}; for (int D = 0; D <= (M + N + 1) / 2; ++D) { for (int k1 = -D; k1 <= D; k1 += 2) { auto p = find_end_snake_of_further_reaching_dpath(a, N, b, M, V1, D, k1); V1[k1] = p.u; const int k2 = -(k1 - delta); if ((delta % 2 != 0) and -(D-1) <= k2 and k2 <= (D-1)) { if (V1[k1] + V2[k2] >= N) return { p, 2 * D - 1 };// return last snake on forward path } } for (int k2 = -D; k2 <= D; k2 += 2) { auto p = find_end_snake_of_further_reaching_dpath(ra, N, rb, M, V2, D, k2); V2[k2] = p.u; const int k1 = -(k2 - delta); if ((delta % 2 == 0) and -D <= k1 and k1 <= D) { if (V1[k1] + V2[k2] >= N) return { { N - p.u, M - p.v, N - p.x , M - p.y } , 2 * D };// return last snake on reverse path } } } kak_assert(false); } template<typename Iterator> struct Diff { bool add; Iterator begin; Iterator end; }; template<typename Iterator> void find_diff_rec(Iterator a, size_t N, Iterator b, size_t M, ArrayView<int> data1, ArrayView<int> data2, Vector<Diff<Iterator>>& diffs) { if (N > 0 and M > 0) { auto middle_snake = find_middle_snake(a, N, b, M, data1, data2); if (middle_snake.d > 1) { find_diff_rec(a, middle_snake.x, b, middle_snake.y, data1, data2, diffs); find_diff_rec(a + middle_snake.u, N - middle_snake.u, b + middle_snake.v, M - middle_snake.v, data1, data2, diffs); } else if (middle_snake.d == 1) { int diag = 0; while (a[diag] == b[diag]) ++diag; if (middle_snake.add) diffs.push_back({true, b + middle_snake.y, b + middle_snake.y + 1}); else diffs.push_back({false, a + middle_snake.x-1, a + middle_snake.x}); } } else if (M > 0) diffs.push_back({true, b, b + M}); else if (N > 0) diffs.push_back({false, a, a + N}); } template<typename Iterator> void compact_diffs(Vector<Diff<Iterator>>& diffs) { if (diffs.size() < 2) return; auto out_it = diffs.begin(); for (auto it = out_it + 1; it != diffs.end(); ++it) { if (it->add == out_it->add and it->begin == out_it->end) out_it->end = it->end; else if (++out_it != it) *out_it = *it; } } template<typename Iterator> Vector<Diff<Iterator>> find_diff(Iterator a, size_t N, Iterator b, size_t M) { Vector<int> data(4 * (N+M)); Vector<Diff<Iterator>> diffs; const size_t max_D_size = 2 * (N + M) + 1; find_diff_rec(a, N, b, M, {data.data(), max_D_size}, {data.data() + max_D_size, max_D_size}, diffs); // compact_diffs(diffs); return diffs; } } <commit_msg>Fix diff implementation and change the Diff struct format<commit_after>#include "array_view.hh" #include "vector.hh" #include <functional> #include <iterator> namespace Kakoune { template<typename T> struct MirroredArray : public ArrayView<T> { MirroredArray(ArrayView<T> data, int size) : ArrayView<T>(data), size(size) { kak_assert(2 * size + 1 <= data.size()); } T& operator[](int n) { return ArrayView<T>::operator[](n + size); } const T& operator[](int n) const { return ArrayView<T>::operator[](n + size); } private: int size; }; struct Snake{ int x, y, u, v; bool add; }; template<typename Iterator, typename Equal> Snake find_end_snake_of_further_reaching_dpath(Iterator a, int N, Iterator b, int M, const MirroredArray<int>& V, const int D, const int k, Equal eq) { int x; // our position along a const bool add = k == -D or (k != D and V[k-1] < V[k+1]); // if diagonal on the right goes further along x than diagonal on the left, // then we take a vertical edge from it to this diagonal, hence x = V[k+1] if (add) x = V[k+1]; // else, we take an horizontal edge from our left diagonal,x = V[k-1]+1 else x = V[k-1]+1; int y = x - k; // we are by construction on diagonal k, so our position along // b (y) is x - k. int u = x, v = y; // follow end snake along diagonal k while (u < N and v < M and eq(a[u], b[v])) ++u, ++v; return { x, y, u, v, add }; } struct SnakeLen : Snake { SnakeLen(Snake s, int d) : Snake(s), d(d) {} int d; }; template<typename Iterator, typename Equal> SnakeLen find_middle_snake(Iterator a, int N, Iterator b, int M, ArrayView<int> data1, ArrayView<int> data2, Equal eq) { const int delta = N - M; MirroredArray<int> V1{data1, N + M}; MirroredArray<int> V2{data2, N + M}; std::reverse_iterator<Iterator> ra{a + N}, rb{b + M}; for (int D = 0; D <= (M + N + 1) / 2; ++D) { for (int k1 = -D; k1 <= D; k1 += 2) { auto p = find_end_snake_of_further_reaching_dpath(a, N, b, M, V1, D, k1, eq); V1[k1] = p.u; const int k2 = -(k1 - delta); if ((delta % 2 != 0) and -(D-1) <= k2 and k2 <= (D-1)) { if (V1[k1] + V2[k2] >= N) return { p, 2 * D - 1 };// return last snake on forward path } } for (int k2 = -D; k2 <= D; k2 += 2) { auto p = find_end_snake_of_further_reaching_dpath(ra, N, rb, M, V2, D, k2, eq); V2[k2] = p.u; const int k1 = -(k2 - delta); if ((delta % 2 == 0) and -D <= k1 and k1 <= D) { if (V1[k1] + V2[k2] >= N) return { { N - p.u, M - p.v, N - p.x , M - p.y } , 2 * D };// return last snake on reverse path } } } kak_assert(false); return { {}, 0 }; } struct Diff { enum { Keep, Add, Remove } mode; int len; int posB; }; template<typename Iterator, typename Equal> void find_diff_rec(Iterator a, int offA, int lenA, Iterator b, int offB, int lenB, ArrayView<int> data1, ArrayView<int> data2, Equal eq, Vector<Diff>& diffs) { if (lenA > 0 and lenB > 0) { auto middle_snake = find_middle_snake(a + offA, lenA, b + offB, lenB, data1, data2, eq); if (middle_snake.d > 1) { find_diff_rec(a, offA, middle_snake.x, b, offB, middle_snake.y, data1, data2, eq, diffs); if (int len = middle_snake.u - middle_snake.x) diffs.push_back({Diff::Keep, len, 0}); find_diff_rec(a, offA + middle_snake.u, lenA - middle_snake.u, b, offB + middle_snake.v, lenB - middle_snake.v, data1, data2, eq, diffs); } else if (middle_snake.d == 1) { int diag = 0; while (eq(a[offA + diag], b[offB + diag])) ++diag; if (diag != 0) diffs.push_back({Diff::Keep, diag, 0}); if (middle_snake.add) diffs.push_back({Diff::Add, 1, offB + middle_snake.y-1}); else diffs.push_back({Diff::Remove, 1, 0}); } } else if (lenB > 0) diffs.push_back({Diff::Add, lenB, offB}); else if (lenA > 0) diffs.push_back({Diff::Remove, lenA, 0}); } inline void compact_diffs(Vector<Diff>& diffs) { if (diffs.size() < 2) return; auto out_it = diffs.begin(); for (auto it = out_it + 1; it != diffs.end(); ++it) { if (it->mode == out_it->mode and (it->mode != Diff::Add or it->posB == out_it->posB + out_it->len)) out_it->len += it->len; else if (++out_it != it) *out_it = *it; } diffs.erase(out_it+1, diffs.end()); } template<typename Iterator, typename Equal = std::equal_to<typename std::iterator_traits<Iterator>::value_type>> Vector<Diff> find_diff(Iterator a, int N, Iterator b, int M, Equal eq = Equal{}) { const int max = 2 * (N + M) + 1; Vector<int> data(2*max); Vector<Diff> diffs; find_diff_rec(a, 0, N, b, 0, M, {data.data(), (size_t)max}, {data.data() + max, (size_t)max}, eq, diffs); compact_diffs(diffs); return diffs; } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Execution_SharedStaticData_inl_ #define _Stroika_Foundation_Execution_SharedStaticData_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" #include "Common.h" namespace Stroika { namespace Foundation { namespace Execution { namespace Private_ { // hack to avoid #include of Thread.h for Thread::SuppressInterruptionInContext bool SharedStaticData_DTORHelper_ ( #if qStroika_Foundation_Execution_SpinLock_IsFasterThan_mutex SpinLock* m, #else mutex* m, #endif unsigned int* cu); } /* ******************************************************************************** ******************************** SharedStaticData<T> *************************** ******************************************************************************** */ template <typename T> T* SharedStaticData<T>::sOnceObj_; template <typename T> #if qStroika_Foundation_Execution_SpinLock_IsFasterThan_mutex SpinLock SharedStaticData<T>::sMutex_; #else mutex SharedStaticData<T>::sMutex_; #endif template <typename T> unsigned int SharedStaticData<T>::sCountUses_ = 0; template <typename T> SharedStaticData<T>::SharedStaticData () { #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (sMutex_); #else auto critSec{make_unique_lock (sMutex_)}; #endif ++sCountUses_; if (sCountUses_ == 1) { sOnceObj_ = new T{}; } #if qDebug Stroika_Foundation_Debug_ValgrindDisableHelgrind (sCountUses_); // beacuse use in asserts - read there - safe/OK even without lock Stroika_Foundation_Debug_ValgrindDisableHelgrind (sOnceObj_); // maybe not non-const get, but count on other later to provide interlock/checking #endif } template <typename T> SharedStaticData<T>::~SharedStaticData () { if (Private_::SharedStaticData_DTORHelper_ (&sMutex_, &sCountUses_)) { Assert (sCountUses_ == 0); delete sOnceObj_; sOnceObj_ = nullptr; } } template <typename T> inline T& SharedStaticData<T>::Get () { // no need to lock since no way to destroy value while 'this' object still exists Ensure (sCountUses_ >= 1); EnsureNotNull (sOnceObj_); return *sOnceObj_; } template <typename T> inline const T& SharedStaticData<T>::Get () const { // no need to lock since no way to destroy value while 'this' object still exists Ensure (sCountUses_ >= 1); EnsureNotNull (sOnceObj_); return *sOnceObj_; } } } } #endif /*_Stroika_Foundation_Execution_SharedStaticData_inl_*/ <commit_msg>silence another warning<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Execution_SharedStaticData_inl_ #define _Stroika_Foundation_Execution_SharedStaticData_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" #include "Common.h" namespace Stroika { namespace Foundation { namespace Execution { DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wdeprecated-declarations\""); namespace Private_ { // hack to avoid #include of Thread.h for Thread::SuppressInterruptionInContext bool SharedStaticData_DTORHelper_ ( #if qStroika_Foundation_Execution_SpinLock_IsFasterThan_mutex SpinLock* m, #else mutex* m, #endif unsigned int* cu); } /* ******************************************************************************** ******************************** SharedStaticData<T> *************************** ******************************************************************************** */ template <typename T> T* SharedStaticData<T>::sOnceObj_; template <typename T> #if qStroika_Foundation_Execution_SpinLock_IsFasterThan_mutex SpinLock SharedStaticData<T>::sMutex_; #else mutex SharedStaticData<T>::sMutex_; #endif template <typename T> unsigned int SharedStaticData<T>::sCountUses_ = 0; template <typename T> SharedStaticData<T>::SharedStaticData () { #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (sMutex_); #else auto critSec{make_unique_lock (sMutex_)}; #endif ++sCountUses_; if (sCountUses_ == 1) { sOnceObj_ = new T{}; } #if qDebug Stroika_Foundation_Debug_ValgrindDisableHelgrind (sCountUses_); // beacuse use in asserts - read there - safe/OK even without lock Stroika_Foundation_Debug_ValgrindDisableHelgrind (sOnceObj_); // maybe not non-const get, but count on other later to provide interlock/checking #endif } template <typename T> SharedStaticData<T>::~SharedStaticData () { if (Private_::SharedStaticData_DTORHelper_ (&sMutex_, &sCountUses_)) { Assert (sCountUses_ == 0); delete sOnceObj_; sOnceObj_ = nullptr; } } template <typename T> inline T& SharedStaticData<T>::Get () { // no need to lock since no way to destroy value while 'this' object still exists Ensure (sCountUses_ >= 1); EnsureNotNull (sOnceObj_); return *sOnceObj_; } template <typename T> inline const T& SharedStaticData<T>::Get () const { // no need to lock since no way to destroy value while 'this' object still exists Ensure (sCountUses_ >= 1); EnsureNotNull (sOnceObj_); return *sOnceObj_; } DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wdeprecated-declarations\""); } } } #endif /*_Stroika_Foundation_Execution_SharedStaticData_inl_*/ <|endoftext|>
<commit_before>// (c) ZaKlaus 2016; Apache 2 Licensed, see LICENSE;; #if !defined(DZM_H) #define _CRT_SECURE_NO_WARNINGS #include <stdint.h> #include <stddef.h> #include <limits.h> #include <float.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #if defined(__linux) #include <readline/readline.h> #include <readline/history.h> static inline FILE * read_input(FILE *Stream) { char *Buffer = readline(""); FILE *NewStream = Stream; if(Buffer[0] != 0) { add_history(Buffer); NewStream = fmemopen((void *)Buffer, strlen(Buffer), "r"); } return(NewStream); } #else static inline FILE * read_input(FILE *Stream) { return(Stream); } #endif typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef int32 bool32; typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; typedef intptr_t intptr; typedef uintptr_t uintptr; typedef size_t memory_index; typedef size_t mi; typedef float real32; typedef double real64; typedef int8 s8; typedef int8 s08; typedef int16 s16; typedef int32 s32; typedef int64 s64; typedef bool32 b32; typedef uint8 u8; typedef uint8 u08; typedef uint16 u16; typedef uint32 u32; typedef uint64 u64; typedef real32 r32; typedef real64 r64; typedef uintptr_t umm; #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #if !defined(COMPILER_MSVC) #define COMPILER_MSVC 0 #endif #if !defined(COMPILER_LLVM) #define COMPILER_LLVM 0 #endif #include "../dzm_ver.hpp" #define MAKE(Type, Value) make_object(Type, (void *)&Value) #define MAKE1(Type, Value, Value1) make_object(Type, (void *)&Value, (void *)&Value1) #define MAKE2(Type, Value, Value1, Value2) make_object(Type, (void *)&Value, (void *)&Value1, (void *)&Value2) #define MAKE3(Type, Value, Value1, Value2, Value3) make_object(Type, (void *)&Value, (void *)&Value1, (void *)&Value2, (void *)&Value3) #if defined(COMPILER_MSVC) #define TRAP() *(int *)0 = 0 #elif defined(COMPILER_LLVM) || defined(__APPLE__) #define TRAP() __builtin_trap() #else #define TRAP() volatile *(int *)0 = 0 #endif #define IGNORE(x) x #ifdef DZM_SLOW #define zassert(Expression) if(!(Expression)) {TRAP();} #else #define zassert(Expression) #endif #define InvalidCodePath zassert(!"InvalidCodePath") #define InvalidDefaultCase default: {InvalidCodePath;} break #define Unreachable(Statement) return(Statement) #define Kilobytes(Value) ((Value)*1024LL) #define Megabytes(Value) (Kilobytes(Value)*1024LL) #define Gigabytes(Value) (Megabytes(Value)*1024LL) #define Terabytes(Value) (Gigabytes(Value)*1024LL) #define AlignPow2(Value, Alignment) ((Value + ((Alignment) - 1)) & ~((Alignment) - 1)) #define Align4(Value) ((Value + 3) & ~3) #define Align8(Value) ((Value + 7) & ~7) #define Align16(Value) ((Value + 15) & ~15) #define STRINGIFY(X) #X #define CONCAT(X,Y) X##Y #define SQUOTE(X, I, C) char __s_quote__I; sprintf(__s_quote__I, "'%s'", X); C = #define UL_ (u8 *) #define L_ (s8 *) #define MAX_VM_SIZE 4096 * 1024 * 32 static inline void zero_size(memory_index Size, void *Ptr) { uint8 *Byte = (uint8 *)Ptr; while(Size--) { *Byte++ = 0; } } #define ArrayCount(Array) (sizeof(Array) / sizeof((Array)[0])) #ifdef DZM_ELEVATED #undef _ELEVATED #define _ELEVATED 1 #else #undef _ELEVATED #define _ELEVATED 0 #endif // == Memory Manager #include "dzm_mem.hpp" // == Util #include "dzm_utl.hpp" #include "dzm_log.hpp" // == Interpreter #include "lang/dzm_mdl.hpp" #include "lang/dzm_lex.hpp" #include "lang/dzm_evl.hpp" #include "lang/dzm_prt.hpp" #include "lang/dzm_rep.hpp" #define DZM_H #endif<commit_msg>Another fixes.<commit_after>// (c) ZaKlaus 2016; Apache 2 Licensed, see LICENSE;; #if !defined(DZM_H) #define _CRT_SECURE_NO_WARNINGS #include <stdint.h> #include <stddef.h> #include <limits.h> #include <float.h> #define __STDC_FORMAT_MACROS #include <inttypes.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #if defined(__linux) #include <readline/readline.h> #include <readline/history.h> static inline FILE * read_input(FILE *Stream) { char *Buffer = readline(""); FILE *NewStream = Stream; if(Buffer[0] != 0) { add_history(Buffer); NewStream = fmemopen((void *)Buffer, strlen(Buffer), "r"); } return(NewStream); } #else static inline FILE * read_input(FILE *Stream) { return(Stream); } #endif typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef int32 bool32; typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; typedef intptr_t intptr; typedef uintptr_t uintptr; typedef size_t memory_index; typedef size_t mi; typedef float real32; typedef double real64; typedef int8 s8; typedef int8 s08; typedef int16 s16; typedef int32 s32; typedef int64 s64; typedef bool32 b32; typedef uint8 u8; typedef uint8 u08; typedef uint16 u16; typedef uint32 u32; typedef uint64 u64; typedef real32 r32; typedef real64 r64; typedef uintptr_t umm; #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #if !defined(COMPILER_MSVC) #define COMPILER_MSVC 0 #endif #if !defined(COMPILER_LLVM) #define COMPILER_LLVM 0 #endif #include "../dzm_ver.hpp" #define MAKE(Type, Value) make_object(Type, (void *)&Value) #define MAKE1(Type, Value, Value1) make_object(Type, (void *)&Value, (void *)&Value1) #define MAKE2(Type, Value, Value1, Value2) make_object(Type, (void *)&Value, (void *)&Value1, (void *)&Value2) #define MAKE3(Type, Value, Value1, Value2, Value3) make_object(Type, (void *)&Value, (void *)&Value1, (void *)&Value2, (void *)&Value3) #if defined(COMPILER_MSVC) && defined(_WIN32) #define TRAP() *(int *)0 = 0 #elif defined(COMPILER_LLVM) || defined(__APPLE__) #define TRAP() __builtin_trap() #else #define TRAP() volatile *(int *)0 = 0 #endif #define IGNORE(x) x #ifdef DZM_SLOW #define zassert(Expression) if(!(Expression)) {TRAP();} #else #define zassert(Expression) #endif #define InvalidCodePath zassert(!"InvalidCodePath") #define InvalidDefaultCase default: {InvalidCodePath;} break #define Unreachable(Statement) return(Statement) #define Kilobytes(Value) ((Value)*1024LL) #define Megabytes(Value) (Kilobytes(Value)*1024LL) #define Gigabytes(Value) (Megabytes(Value)*1024LL) #define Terabytes(Value) (Gigabytes(Value)*1024LL) #define AlignPow2(Value, Alignment) ((Value + ((Alignment) - 1)) & ~((Alignment) - 1)) #define Align4(Value) ((Value + 3) & ~3) #define Align8(Value) ((Value + 7) & ~7) #define Align16(Value) ((Value + 15) & ~15) #define STRINGIFY(X) #X #define CONCAT(X,Y) X##Y #define SQUOTE(X, I, C) char __s_quote__I; sprintf(__s_quote__I, "'%s'", X); C = #define UL_ (u8 *) #define L_ (s8 *) #define MAX_VM_SIZE 4096 * 1024 * 32 static inline void zero_size(memory_index Size, void *Ptr) { uint8 *Byte = (uint8 *)Ptr; while(Size--) { *Byte++ = 0; } } #define ArrayCount(Array) (sizeof(Array) / sizeof((Array)[0])) #ifdef DZM_ELEVATED #undef _ELEVATED #define _ELEVATED 1 #else #undef _ELEVATED #define _ELEVATED 0 #endif // == Memory Manager #include "dzm_mem.hpp" // == Util #include "dzm_utl.hpp" #include "dzm_log.hpp" // == Interpreter #include "lang/dzm_mdl.hpp" #include "lang/dzm_lex.hpp" #include "lang/dzm_evl.hpp" #include "lang/dzm_prt.hpp" #include "lang/dzm_rep.hpp" #define DZM_H #endif<|endoftext|>
<commit_before>// ------------------------------------------------------------- // CUDPP -- CUDA Data Parallel Primitives library // ------------------------------------------------------------- // $Revision: $ // $Date: $ // ------------------------------------------------------------- // This source code is distributed under the terms of license.txt in // the root directory of this source distribution. // ------------------------------------------------------------- /** * @file * test_sa.cpp * * @brief Host testrig routines to exercise cudpp's suffix array functionality. */ #include <cstring> #include <iostream> #include <cuda_runtime_api.h> #include <time.h> #include "cudpp.h" #include "cudpp_testrig_options.h" #include "cudpp_testrig_utils.h" #include "cuda_util.h" #include "stopwatch.h" #include "commandline.h" #include "comparearrays.h" #include "sparse.h" using namespace cudpp_app; int suffixArrayTest(int argc, const char **argv, const CUDPPConfiguration &config, const testrigOptions &testOptions) { int retval = 0; cudpp_app::StopWatch timer; bool quiet = checkCommandLineFlag(argc, (const char**) argv, "quiet"); unsigned int test[] = {39, 128, 256, 512, 513, 1000, 1024, 1025, 32768, 45537, 65536, 131072, 262144, 500001, 524288, 1048577, 1048576, 1048581}; int numTests = sizeof(test) / sizeof(test[0]); int numElements; size_t freeMem, totalMem; CUDA_SAFE_CALL(cudaMemGetInfo(&freeMem, &totalMem)); unsigned int memNeeded = test[numTests-1] * sizeof(unsigned char); while (memNeeded > 0.015 * freeMem) { numTests -= 1; memNeeded = test[numTests-1] * sizeof(unsigned char); if(numTests == 0) { fprintf(stderr, "suffixArrayTest: Error, not enough memory to run test\n"); return retval; } } numElements = test[numTests-1] + numTests; // maximum test size if(testOptions.skiplongtests) { numTests -= 3; } bool oneTest = false; if (commandLineArg(numElements, argc, (const char**) argv, "n")) { oneTest = true; numTests = 1; test[0] = numElements; } // Initialize CUDPP CUDPPHandle plan; CUDPPResult result = CUDPP_SUCCESS; CUDPPHandle theCudpp; result = cudppCreate(&theCudpp); if (result != CUDPP_SUCCESS) { if (!quiet) fprintf(stderr, "Error initializing CUDPP Library\n"); retval = (oneTest) ? 1 : numTests; return retval; } result = cudppPlan(theCudpp, &plan, config, numElements, 1, 0); if(result != CUDPP_SUCCESS) { if (!quiet) fprintf(stderr, "Error in plan creation\n"); retval = (oneTest) ? 1 : numTests; return retval; } // allocate host memory to store input data unsigned char* i_data = new unsigned char[numElements]; unsigned int* reference = new unsigned int[numElements+3]; // allocate device memory input and output arrays unsigned char* d_idata = (unsigned char *) NULL; unsigned int* d_odata = (unsigned int *) NULL; CUDA_SAFE_CALL(cudaMalloc((void**) &d_idata, numElements*sizeof(unsigned char))); CUDA_SAFE_CALL(cudaMalloc((void**) &d_odata, (numElements+1)*sizeof(unsigned int))); for(int k=0; k<numTests; k++) { if(!quiet) { printf("Running a Suffix Array test of %u %s nodes\n", test[k], datatypeToString(config.datatype)); fflush(stdout); } // initialize the input data on the host srand(95835); for(int j=0; j<test[k]; ++j) i_data[j] = (unsigned char)(rand()%128+1); CUDA_SAFE_CALL(cudaMemcpy(d_idata, i_data, sizeof(unsigned char) * test[k], cudaMemcpyHostToDevice)); CUDA_SAFE_CALL(cudaMemset(d_odata, 0, sizeof(unsigned int) * (test[k]+1))); // allocate host memory to store the output data unsigned int* o_data = (unsigned int*) malloc(sizeof(unsigned int) * test[k]); memset(reference, 0, sizeof(unsigned int) * (test[k]+3)); computeSaGold(i_data, reference, test[k]); // Run the SA // run once to avoid timing startup overhead. result = cudppSuffixArray(plan, d_idata, d_odata, test[k]); if (result != CUDPP_SUCCESS) { if(!quiet) printf("Error in cudppSuffixArray call in testSa (make sure your device is at" " least compute version 2.0)\n"); retval = numTests; } else { timer.reset(); timer.start(); for(int i=0; i<testOptions.numIterations; i++) cudppSuffixArray(plan, d_idata, d_odata, test[k]); CUDA_SAFE_CALL(cudaThreadSynchronize()); timer.stop(); } d_odata = d_odata+1; CUDA_SAFE_CALL(cudaMemcpy(o_data, d_odata, sizeof(unsigned int) * test[k], cudaMemcpyDeviceToHost)); bool result = compareArrays<unsigned int> (reference, o_data, test[k]); free(o_data); retval += result ? 0 : 1; if(!quiet) { printf("test %s\n", result ? "PASSED" : "FAILED"); printf("Average execution time: %f ms\n", timer.getTime() / testOptions.numIterations); } else printf("\t%10d\t%0.4f\n", test[k], timer.getTime() / testOptions.numIterations); } result = cudppDestroyPlan(plan); if (result != CUDPP_SUCCESS) { if (!quiet) printf("Error destroying CUDPPPlan for Suffix Array\n"); } result = cudppDestroy(theCudpp); if (result != CUDPP_SUCCESS) { if(!quiet) printf("Error shutting down CUDPP Library.\n"); } delete [] reference; delete [] i_data; cudaFree(d_odata); cudaFree(d_idata); return retval; } int testSuffixArray(int argc, const char **argv, const CUDPPConfiguration *configPtr) { testrigOptions testOptions; setOptions(argc, argv, testOptions); CUDPPConfiguration config; config.algorithm = CUDPP_SA; config.options = 0; if (configPtr != NULL) { config = *configPtr; } else { config.datatype = CUDPP_UCHAR; } return suffixArrayTest(argc, argv, config, testOptions); } // Leave this at the end of the file // Local Variables: // mode:c++ // c-file-style: "NVIDIA" // End: <commit_msg>fixed issue in suffix array tests where the wrong memory address is cudafreed<commit_after>// ------------------------------------------------------------- // CUDPP -- CUDA Data Parallel Primitives library // ------------------------------------------------------------- // $Revision: $ // $Date: $ // ------------------------------------------------------------- // This source code is distributed under the terms of license.txt in // the root directory of this source distribution. // ------------------------------------------------------------- /** * @file * test_sa.cpp * * @brief Host testrig routines to exercise cudpp's suffix array functionality. */ #include <cstring> #include <iostream> #include <cuda_runtime_api.h> #include <time.h> #include "cudpp.h" #include "cudpp_testrig_options.h" #include "cudpp_testrig_utils.h" #include "cuda_util.h" #include "stopwatch.h" #include "commandline.h" #include "comparearrays.h" #include "sparse.h" using namespace cudpp_app; int suffixArrayTest(int argc, const char **argv, const CUDPPConfiguration &config, const testrigOptions &testOptions) { int retval = 0; cudpp_app::StopWatch timer; bool quiet = checkCommandLineFlag(argc, (const char**) argv, "quiet"); unsigned int test[] = {39, 128, 256, 512, 513, 1000, 1024, 1025, 32768, 45537, 65536, 131072, 262144, 500001, 524288, 1048577, 1048576, 1048581}; int numTests = sizeof(test) / sizeof(test[0]); int numElements; size_t freeMem, totalMem; CUDA_SAFE_CALL(cudaMemGetInfo(&freeMem, &totalMem)); unsigned int memNeeded = test[numTests-1] * sizeof(unsigned char); while (memNeeded > 0.015 * freeMem) { numTests -= 1; memNeeded = test[numTests-1] * sizeof(unsigned char); if(numTests == 0) { fprintf(stderr, "suffixArrayTest: Error, not enough memory to run test\n"); return retval; } } numElements = test[numTests-1] + numTests; // maximum test size if(testOptions.skiplongtests) { numTests -= 3; } bool oneTest = false; if (commandLineArg(numElements, argc, (const char**) argv, "n")) { oneTest = true; numTests = 1; test[0] = numElements; } // Initialize CUDPP CUDPPHandle plan; CUDPPResult result = CUDPP_SUCCESS; CUDPPHandle theCudpp; result = cudppCreate(&theCudpp); if (result != CUDPP_SUCCESS) { if (!quiet) fprintf(stderr, "Error initializing CUDPP Library\n"); retval = (oneTest) ? 1 : numTests; return retval; } result = cudppPlan(theCudpp, &plan, config, numElements, 1, 0); if(result != CUDPP_SUCCESS) { if (!quiet) fprintf(stderr, "Error in plan creation\n"); retval = (oneTest) ? 1 : numTests; return retval; } // allocate host memory to store input data unsigned char* i_data = new unsigned char[numElements]; unsigned int* reference = new unsigned int[numElements+3]; // allocate device memory input and output arrays unsigned char* d_idata = (unsigned char *) NULL; unsigned int* d_odata = (unsigned int *) NULL; CUDA_SAFE_CALL(cudaMalloc((void**) &d_idata, numElements*sizeof(unsigned char))); CUDA_SAFE_CALL(cudaMalloc((void**) &d_odata, (numElements+1)*sizeof(unsigned int))); for(int k=0; k<numTests; k++) { if(!quiet) { printf("Running a Suffix Array test of %u %s nodes\n", test[k], datatypeToString(config.datatype)); fflush(stdout); } // initialize the input data on the host srand(95835); for(int j=0; j<test[k]; ++j) i_data[j] = (unsigned char)(rand()%128+1); CUDA_SAFE_CALL(cudaMemcpy(d_idata, i_data, sizeof(unsigned char) * test[k], cudaMemcpyHostToDevice)); CUDA_SAFE_CALL(cudaMemset(d_odata, 0, sizeof(unsigned int) * (test[k]+1))); // allocate host memory to store the output data unsigned int* o_data = (unsigned int*) malloc(sizeof(unsigned int) * test[k]); memset(reference, 0, sizeof(unsigned int) * (test[k]+3)); computeSaGold(i_data, reference, test[k]); // Run the SA // run once to avoid timing startup overhead. result = cudppSuffixArray(plan, d_idata, d_odata, test[k]); if (result != CUDPP_SUCCESS) { if(!quiet) printf("Error in cudppSuffixArray call in testSa (make sure your device is at" " least compute version 2.0)\n"); retval = numTests; } else { timer.reset(); timer.start(); for(int i=0; i<testOptions.numIterations; i++) cudppSuffixArray(plan, d_idata, d_odata, test[k]); CUDA_SAFE_CALL(cudaThreadSynchronize()); timer.stop(); } CUDA_SAFE_CALL(cudaMemcpy(o_data, d_odata + 1, sizeof(unsigned int) * test[k], cudaMemcpyDeviceToHost)); bool result = compareArrays<unsigned int> (reference, o_data, test[k]); free(o_data); retval += result ? 0 : 1; if(!quiet) { printf("test %s\n", result ? "PASSED" : "FAILED"); printf("Average execution time: %f ms\n", timer.getTime() / testOptions.numIterations); } else printf("\t%10d\t%0.4f\n", test[k], timer.getTime() / testOptions.numIterations); } result = cudppDestroyPlan(plan); if (result != CUDPP_SUCCESS) { if (!quiet) printf("Error destroying CUDPPPlan for Suffix Array\n"); } result = cudppDestroy(theCudpp); if (result != CUDPP_SUCCESS) { if(!quiet) printf("Error shutting down CUDPP Library.\n"); } delete [] reference; delete [] i_data; cudaFree(d_odata); cudaFree(d_idata); return retval; } int testSuffixArray(int argc, const char **argv, const CUDPPConfiguration *configPtr) { testrigOptions testOptions; setOptions(argc, argv, testOptions); CUDPPConfiguration config; config.algorithm = CUDPP_SA; config.options = 0; if (configPtr != NULL) { config = *configPtr; } else { config.datatype = CUDPP_UCHAR; } return suffixArrayTest(argc, argv, config, testOptions); } // Leave this at the end of the file // Local Variables: // mode:c++ // c-file-style: "NVIDIA" // End: <|endoftext|>
<commit_before>/// Implementation of init_tasks.hpp /// /// (c) Koheron #include "init_tasks.hpp" #include <cstdio> #include <cstring> extern "C" { #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <ifaddrs.h> } #include "../drivers/core/wr_register.hpp" InitTasks::InitTasks(Klib::DevMem& dev_mem_) : dev_mem(dev_mem_) {} #define LED_ADDR 0x43C00000 #define MAP_SIZE 4096 #define LED_OFFSET 0x0 void InitTasks::show_ip_on_leds() { // http://stackoverflow.com/questions/20800319/how-to-get-my-ip-address-in-c-linux struct ifaddrs *addrs; getifaddrs(&addrs); ifaddrs *tmp = addrs; // Turn all the leds ON Klib::MemMapID dev_num = dev_mem.AddMemoryMap(LED_ADDR, 16*MAP_SIZE); Klib::WriteReg32(dev_mem.GetBaseAddr(dev_num) + LED_OFFSET, 255); char interface[] = "eth0"; while(tmp) { // Works only for IPv4 address if(tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) { struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr; int val = strcmp(tmp->ifa_name,interface); if(val != 0) { tmp = tmp->ifa_next; continue; } // Interface found printf("Interface %s found: %s\n", tmp->ifa_name, inet_ntoa(pAddr->sin_addr)); uint32_t ip = htonl(pAddr->sin_addr.s_addr); // Write IP address in FPGA memory // The 8 Least Significant Bits should be connected to the FPGA LEDs Klib::WriteReg32(dev_mem.GetBaseAddr(dev_num) + LED_OFFSET, ip); break; } tmp = tmp->ifa_next; } freeifaddrs(addrs); dev_mem.RmMemoryMap(dev_num); } <commit_msg>Update init_tasks.cpp<commit_after>/// Implementation of init_tasks.hpp /// /// (c) Koheron #include "init_tasks.hpp" #include <cstdio> #include <cstring> extern "C" { #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <ifaddrs.h> } #include "../drivers/core/wr_register.hpp" InitTasks::InitTasks(Klib::DevMem& dev_mem_) : dev_mem(dev_mem_) {} #define LED_ADDR 0x60000000 #define MAP_SIZE 4096 #define LED_OFFSET 0x0 void InitTasks::show_ip_on_leds() { // http://stackoverflow.com/questions/20800319/how-to-get-my-ip-address-in-c-linux struct ifaddrs *addrs; getifaddrs(&addrs); ifaddrs *tmp = addrs; // Turn all the leds ON Klib::MemMapID dev_num = dev_mem.AddMemoryMap(LED_ADDR, 16*MAP_SIZE); Klib::WriteReg32(dev_mem.GetBaseAddr(dev_num) + LED_OFFSET, 255); char interface[] = "eth0"; while(tmp) { // Works only for IPv4 address if(tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET) { struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr; int val = strcmp(tmp->ifa_name,interface); if(val != 0) { tmp = tmp->ifa_next; continue; } // Interface found printf("Interface %s found: %s\n", tmp->ifa_name, inet_ntoa(pAddr->sin_addr)); uint32_t ip = htonl(pAddr->sin_addr.s_addr); // Write IP address in FPGA memory // The 8 Least Significant Bits should be connected to the FPGA LEDs Klib::WriteReg32(dev_mem.GetBaseAddr(dev_num) + LED_OFFSET, ip); break; } tmp = tmp->ifa_next; } freeifaddrs(addrs); dev_mem.RmMemoryMap(dev_num); } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbChangeLabelImageFilter.h" #include "otbStandardWriterWatcher.h" #include "otbStatisticsXMLFileReader.h" #include "otbShiftScaleVectorImageFilter.h" #include "otbImageClassificationFilter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbImageToVectorImageCastFilter.h" #include "otbMachineLearningModelFactory.h" namespace otb { namespace Wrapper { class ImageClassifier : public Application { public: /** Standard class typedefs. */ typedef ImageClassifier Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ImageClassifier, otb::Application); /** Filters typedef */ typedef UInt16ImageType OutputImageType; typedef UInt8ImageType MaskImageType; typedef itk::VariableLengthVector<FloatVectorImageType::InternalPixelType> MeasurementType; typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; typedef otb::ShiftScaleVectorImageFilter<FloatVectorImageType, FloatVectorImageType> RescalerType; typedef otb::ImageClassificationFilter<FloatVectorImageType, OutputImageType, MaskImageType> ClassificationFilterType; typedef ClassificationFilterType::Pointer ClassificationFilterPointerType; typedef ClassificationFilterType::ModelType ModelType; typedef ModelType::Pointer ModelPointerType; typedef ClassificationFilterType::ValueType ValueType; typedef ClassificationFilterType::LabelType LabelType; typedef otb::MachineLearningModelFactory<ValueType, LabelType> MachineLearningModelFactoryType; typedef ClassificationFilterType::ConfidenceImageType ConfidenceImageType; protected: ~ImageClassifier() ITK_OVERRIDE { MachineLearningModelFactoryType::CleanFactories(); } private: void DoInit() ITK_OVERRIDE { SetName("ImageClassifier"); SetDescription("Performs a classification of the input image according to a model file."); // Documentation SetDocName("Image Classification"); SetDocLongDescription("This application performs an image classification based on a model file produced by the TrainImagesClassifier application. Pixels of the output image will contain the class labels decided by the classifier (maximal class label = 65535). The input pixels can be optionally centered and reduced according to the statistics file produced by the ComputeImagesStatistics application. An optional input mask can be provided, in which case only input image pixels whose corresponding mask value is greater than 0 will be classified. The remaining of pixels will be given the label 0 in the output image."); SetDocLimitations("The input image must have the same type, order and number of bands than the images used to produce the statistics file and the SVM model file. If a statistics file was used during training by the TrainImagesClassifier, it is mandatory to use the same statistics file for classification. If an input mask is used, its size must match the input image size."); SetDocAuthors("OTB-Team"); SetDocSeeAlso("TrainImagesClassifier, ValidateImagesClassifier, ComputeImagesStatistics"); AddDocTag(Tags::Learning); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription( "in", "The input image to classify."); AddParameter(ParameterType_InputImage, "mask", "Input Mask"); SetParameterDescription( "mask", "The mask allows restricting classification of the input image to the area where mask pixel values are greater than 0."); MandatoryOff("mask"); AddParameter(ParameterType_InputFilename, "model", "Model file"); SetParameterDescription("model", "A model file (produced by TrainImagesClassifier application, maximal class label = 65535)."); AddParameter(ParameterType_InputFilename, "imstat", "Statistics file"); SetParameterDescription("imstat", "A XML file containing mean and standard deviation to center and reduce samples before classification (produced by ComputeImagesStatistics application)."); MandatoryOff("imstat"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription( "out", "Output image containing class labels"); SetDefaultOutputPixelType( "out", ImagePixelType_uint8); AddParameter(ParameterType_OutputImage, "confmap", "Confidence map"); SetParameterDescription( "confmap", "Confidence map of the produced classification. The confidence index depends on the model : \n" " - LibSVM : difference between the two highest probabilities (needs a model with probability estimates, so that classes probabilities can be computed for each sample)\n" " - OpenCV\n" " * Boost : sum of votes\n" " * DecisionTree : (not supported)\n" " * GradientBoostedTree : (not supported)\n" " * KNearestNeighbors : number of neighbors with the same label\n" " * NeuralNetwork : difference between the two highest responses\n" " * NormalBayes : (not supported)\n" " * RandomForest : Confidence (proportion of votes for the majority class). Margin (normalized difference of the votes of the 2 majority classes) is not available for now.\n" " * SVM : distance to margin (only works for 2-class models)\n"); SetDefaultOutputPixelType( "confmap", ImagePixelType_double); MandatoryOff("confmap"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_1_ortho.tif"); SetDocExampleParameterValue("imstat", "EstimateImageStatisticsQB1.xml"); SetDocExampleParameterValue("model", "clsvmModelQB1.svm"); SetDocExampleParameterValue("out", "clLabeledImageQB1.tif"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { // Nothing to do here : all parameters are independent } void DoExecute() ITK_OVERRIDE { // Load input image FloatVectorImageType::Pointer inImage = GetParameterImage("in"); inImage->UpdateOutputInformation(); // Load svm model otbAppLogINFO("Loading model"); m_Model = MachineLearningModelFactoryType::CreateMachineLearningModel(GetParameterString("model"), MachineLearningModelFactoryType::ReadMode); if (m_Model.IsNull()) { otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model") << " : unsupported model type"); } m_Model->Load(GetParameterString("model")); otbAppLogINFO("Model loaded"); // Normalize input image (optional) StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); MeasurementType meanMeasurementVector; MeasurementType stddevMeasurementVector; m_Rescaler = RescalerType::New(); // Classify m_ClassificationFilter = ClassificationFilterType::New(); m_ClassificationFilter->SetModel(m_Model); // Normalize input image if asked if(IsParameterEnabled("imstat") ) { otbAppLogINFO("Input image normalization activated."); // Load input image statistics statisticsReader->SetFileName(GetParameterString("imstat")); meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); otbAppLogINFO( "mean used: " << meanMeasurementVector ); otbAppLogINFO( "standard deviation used: " << stddevMeasurementVector ); // Rescale vector image m_Rescaler->SetScale(stddevMeasurementVector); m_Rescaler->SetShift(meanMeasurementVector); m_Rescaler->SetInput(inImage); m_ClassificationFilter->SetInput(m_Rescaler->GetOutput()); } else { otbAppLogINFO("Input image normalization deactivated."); m_ClassificationFilter->SetInput(inImage); } if(IsParameterEnabled("mask")) { otbAppLogINFO("Using input mask"); // Load mask image and cast into LabeledImageType MaskImageType::Pointer inMask = GetParameterUInt8Image("mask"); m_ClassificationFilter->SetInputMask(inMask); } SetParameterOutputImage<OutputImageType>("out", m_ClassificationFilter->GetOutput()); // output confidence map if (IsParameterEnabled("confmap") && HasValue("confmap")) { m_ClassificationFilter->SetUseConfidenceMap(true); if (m_Model->HasConfidenceIndex()) { SetParameterOutputImage<ConfidenceImageType>("confmap",m_ClassificationFilter->GetOutputConfidence()); } else { otbAppLogWARNING("Confidence map requested but the classifier doesn't support it!"); this->DisableParameter("confmap"); } } } ClassificationFilterType::Pointer m_ClassificationFilter; ModelPointerType m_Model; RescalerType::Pointer m_Rescaler; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::ImageClassifier) <commit_msg>ENH: standardize MachineLearningModel output type in ImageClassifier<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbChangeLabelImageFilter.h" #include "otbStandardWriterWatcher.h" #include "otbStatisticsXMLFileReader.h" #include "otbShiftScaleVectorImageFilter.h" #include "otbImageClassificationFilter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbImageToVectorImageCastFilter.h" #include "otbMachineLearningModelFactory.h" namespace otb { namespace Wrapper { class ImageClassifier : public Application { public: /** Standard class typedefs. */ typedef ImageClassifier Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ImageClassifier, otb::Application); /** Filters typedef */ //typedef UInt16ImageType OutputImageType; typedef Int32ImageType OutputImageType; typedef UInt8ImageType MaskImageType; typedef itk::VariableLengthVector<FloatVectorImageType::InternalPixelType> MeasurementType; typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; typedef otb::ShiftScaleVectorImageFilter<FloatVectorImageType, FloatVectorImageType> RescalerType; typedef otb::ImageClassificationFilter<FloatVectorImageType, OutputImageType, MaskImageType> ClassificationFilterType; typedef ClassificationFilterType::Pointer ClassificationFilterPointerType; typedef ClassificationFilterType::ModelType ModelType; typedef ModelType::Pointer ModelPointerType; typedef ClassificationFilterType::ValueType ValueType; typedef ClassificationFilterType::LabelType LabelType; typedef otb::MachineLearningModelFactory<ValueType, LabelType> MachineLearningModelFactoryType; typedef ClassificationFilterType::ConfidenceImageType ConfidenceImageType; protected: ~ImageClassifier() ITK_OVERRIDE { MachineLearningModelFactoryType::CleanFactories(); } private: void DoInit() ITK_OVERRIDE { SetName("ImageClassifier"); SetDescription("Performs a classification of the input image according to a model file."); // Documentation SetDocName("Image Classification"); SetDocLongDescription("This application performs an image classification based on a model file produced by the TrainImagesClassifier application. Pixels of the output image will contain the class labels decided by the classifier (maximal class label = 65535). The input pixels can be optionally centered and reduced according to the statistics file produced by the ComputeImagesStatistics application. An optional input mask can be provided, in which case only input image pixels whose corresponding mask value is greater than 0 will be classified. The remaining of pixels will be given the label 0 in the output image."); SetDocLimitations("The input image must have the same type, order and number of bands than the images used to produce the statistics file and the SVM model file. If a statistics file was used during training by the TrainImagesClassifier, it is mandatory to use the same statistics file for classification. If an input mask is used, its size must match the input image size."); SetDocAuthors("OTB-Team"); SetDocSeeAlso("TrainImagesClassifier, ValidateImagesClassifier, ComputeImagesStatistics"); AddDocTag(Tags::Learning); AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription( "in", "The input image to classify."); AddParameter(ParameterType_InputImage, "mask", "Input Mask"); SetParameterDescription( "mask", "The mask allows restricting classification of the input image to the area where mask pixel values are greater than 0."); MandatoryOff("mask"); AddParameter(ParameterType_InputFilename, "model", "Model file"); SetParameterDescription("model", "A model file (produced by TrainImagesClassifier application, maximal class label = 65535)."); AddParameter(ParameterType_InputFilename, "imstat", "Statistics file"); SetParameterDescription("imstat", "A XML file containing mean and standard deviation to center and reduce samples before classification (produced by ComputeImagesStatistics application)."); MandatoryOff("imstat"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription( "out", "Output image containing class labels"); SetDefaultOutputPixelType( "out", ImagePixelType_uint8); AddParameter(ParameterType_OutputImage, "confmap", "Confidence map"); SetParameterDescription( "confmap", "Confidence map of the produced classification. The confidence index depends on the model : \n" " - LibSVM : difference between the two highest probabilities (needs a model with probability estimates, so that classes probabilities can be computed for each sample)\n" " - OpenCV\n" " * Boost : sum of votes\n" " * DecisionTree : (not supported)\n" " * GradientBoostedTree : (not supported)\n" " * KNearestNeighbors : number of neighbors with the same label\n" " * NeuralNetwork : difference between the two highest responses\n" " * NormalBayes : (not supported)\n" " * RandomForest : Confidence (proportion of votes for the majority class). Margin (normalized difference of the votes of the 2 majority classes) is not available for now.\n" " * SVM : distance to margin (only works for 2-class models)\n"); SetDefaultOutputPixelType( "confmap", ImagePixelType_double); MandatoryOff("confmap"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_1_ortho.tif"); SetDocExampleParameterValue("imstat", "EstimateImageStatisticsQB1.xml"); SetDocExampleParameterValue("model", "clsvmModelQB1.svm"); SetDocExampleParameterValue("out", "clLabeledImageQB1.tif"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { // Nothing to do here : all parameters are independent } void DoExecute() ITK_OVERRIDE { // Load input image FloatVectorImageType::Pointer inImage = GetParameterImage("in"); inImage->UpdateOutputInformation(); // Load svm model otbAppLogINFO("Loading model"); m_Model = MachineLearningModelFactoryType::CreateMachineLearningModel(GetParameterString("model"), MachineLearningModelFactoryType::ReadMode); if (m_Model.IsNull()) { otbAppLogFATAL(<< "Error when loading model " << GetParameterString("model") << " : unsupported model type"); } m_Model->Load(GetParameterString("model")); otbAppLogINFO("Model loaded"); // Normalize input image (optional) StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); MeasurementType meanMeasurementVector; MeasurementType stddevMeasurementVector; m_Rescaler = RescalerType::New(); // Classify m_ClassificationFilter = ClassificationFilterType::New(); m_ClassificationFilter->SetModel(m_Model); // Normalize input image if asked if(IsParameterEnabled("imstat") ) { otbAppLogINFO("Input image normalization activated."); // Load input image statistics statisticsReader->SetFileName(GetParameterString("imstat")); meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); otbAppLogINFO( "mean used: " << meanMeasurementVector ); otbAppLogINFO( "standard deviation used: " << stddevMeasurementVector ); // Rescale vector image m_Rescaler->SetScale(stddevMeasurementVector); m_Rescaler->SetShift(meanMeasurementVector); m_Rescaler->SetInput(inImage); m_ClassificationFilter->SetInput(m_Rescaler->GetOutput()); } else { otbAppLogINFO("Input image normalization deactivated."); m_ClassificationFilter->SetInput(inImage); } if(IsParameterEnabled("mask")) { otbAppLogINFO("Using input mask"); // Load mask image and cast into LabeledImageType MaskImageType::Pointer inMask = GetParameterUInt8Image("mask"); m_ClassificationFilter->SetInputMask(inMask); } SetParameterOutputImage<OutputImageType>("out", m_ClassificationFilter->GetOutput()); // output confidence map if (IsParameterEnabled("confmap") && HasValue("confmap")) { m_ClassificationFilter->SetUseConfidenceMap(true); if (m_Model->HasConfidenceIndex()) { SetParameterOutputImage<ConfidenceImageType>("confmap",m_ClassificationFilter->GetOutputConfidence()); } else { otbAppLogWARNING("Confidence map requested but the classifier doesn't support it!"); this->DisableParameter("confmap"); } } } ClassificationFilterType::Pointer m_ClassificationFilter; ModelPointerType m_Model; RescalerType::Pointer m_Rescaler; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::ImageClassifier) <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbReciprocalHAlphaImageFilter.h" #include "otbReciprocalBarnesDecompImageFilter.h" #include "otbReciprocalHuynenDecompImageFilter.h" #include "otbReciprocalPauliDecompImageFilter.h" #include "otbSinclairReciprocalImageFilter.h" #include "otbSinclairToReciprocalCoherencyMatrixFunctor.h" #include "otbPerBandVectorImageFilter.h" #include "itkMeanImageFilter.h" #include "otbNRIBandImagesToOneNComplexBandsImage.h" namespace otb { namespace Wrapper { class SARDecompositions : public Application { public: /** Standard class typedefs. */ typedef SARDecompositions Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef otb::Functor::SinclairToReciprocalCoherencyMatrixFunctor<ComplexDoubleImageType::PixelType, ComplexDoubleImageType::PixelType, ComplexDoubleImageType::PixelType, ComplexDoubleVectorImageType::PixelType> FunctorType; typedef SinclairReciprocalImageFilter<ComplexDoubleImageType, ComplexDoubleImageType, ComplexDoubleImageType, ComplexDoubleVectorImageType, FunctorType > SRFilterType; typedef itk::MeanImageFilter<ComplexDoubleImageType, ComplexDoubleImageType> MeanFilterType; typedef otb::PerBandVectorImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType, MeanFilterType> PerBandMeanFilterType; //typedef otb::NRIBandImagesToOneNComplexBandsImage<DoubleVectorImageType, ComplexDoubleVectorImageType> NRITOOneCFilterType; typedef otb::ReciprocalHAlphaImageFilter<ComplexDoubleVectorImageType, DoubleVectorImageType> HAFilterType; typedef otb::ReciprocalBarnesDecompImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType> BarnesFilterType; typedef otb::ReciprocalHuynenDecompImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType> HuynenFilterType; //typedef otb::ReciprocalPauliDecompImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType> PauliFilterType; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(SARDecompositions, otb::Application); private: void DoInit() { SetName("SARDecompositions"); SetDescription("From one-band complex images (each one related to an element of the Sinclair matrix), returns the selected decomposition."); // Documentation SetDocName("SARDecompositions"); SetDocLongDescription("From one-band complex images (HH, HV, VH, VV), returns the selected decomposition.\n \n" "All the decompositions implemented are intended for the mono-static case (transmitter and receiver are co-located).\n" "There are two kinds of decomposition : coherent ones and incoherent ones.\n" "In the coherent case, only the Pauli decomposition is available.\n" "In the incoherent case, there the decompositions available : Huynen, Barnes, and H-alpha-A.\n" "User must provide three one-band complex images HH, HV or VH, and VV (mono-static case <=> HV = VH).\n" "Incoherent decompositions consist in averaging 3x3 complex coherency/covariance matrices; the user must provide the size of the averaging window, thanks to the parameter inco.kernelsize.\n " ); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("SARPolarMatrixConvert, SARPolarSynth"); AddDocTag(Tags::SAR); AddParameter(ParameterType_ComplexInputImage, "inhh", "Input Image"); SetParameterDescription("inhh", "Input image (HH)"); AddParameter(ParameterType_ComplexInputImage, "inhv", "Input Image"); SetParameterDescription("inhv", "Input image (HV)"); MandatoryOff("inhv"); AddParameter(ParameterType_ComplexInputImage, "invh", "Input Image"); SetParameterDescription("invh", "Input image (VH)"); MandatoryOff("invh"); AddParameter(ParameterType_ComplexInputImage, "invv", "Input Image"); SetParameterDescription("invv", "Input image (VV)"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "Output image"); AddParameter(ParameterType_Choice, "decomp", "Decompositions"); AddChoice("decomp.haa","H-alpha-A incoherent decomposition"); SetParameterDescription("decomp.haa","H-alpha-A incoherent decomposition"); AddChoice("decomp.barnes","Barnes incoherent decomposition"); SetParameterDescription("decomp.barnes","Barnes incoherent decomposition"); AddParameter(ParameterType_Group,"inco","Incoherent decompositions"); SetParameterDescription("inco","This group allows setting parameters related to the incoherent decompositions."); AddParameter(ParameterType_Int, "inco.kernelsize", "Kernel size for spatial incoherent averaging."); SetParameterDescription("inco.kernelsize", "Minute (0-59)"); SetMinimumParameterIntValue("inco.kernelsize", 1); SetDefaultParameterInt("inco.kernelsize", 3); MandatoryOff("inco.kernelsize"); AddRAMParameter(); // Default values SetDefaultParameterInt("decomp", 0); // H-alpha-A // Doc example parameter settings SetDocExampleParameterValue("inhh", "HH.tif"); SetDocExampleParameterValue("invh", "VH.tif"); SetDocExampleParameterValue("invv", "VV.tif"); SetDocExampleParameterValue("decomp", "haa"); SetDocExampleParameterValue("out", "HaA.tif"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { bool inhv = HasUserValue("inhv"); bool invh = HasUserValue("invh"); if ( (!inhv) && (!invh) ) otbAppLogFATAL( << "Parameter inhv or invh not set. Please provide a HV or a VH complex image."); m_SRFilter = SRFilterType::New(); m_HAFilter = HAFilterType::New(); m_MeanFilter = PerBandMeanFilterType::New(); MeanFilterType::InputSizeType radius; m_BarnesFilter = BarnesFilterType::New(); switch (GetParameterInt("decomp")) { case 0: // H-alpha-A if (inhv) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("inhv")); else if (invh) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("invh")); m_SRFilter->SetInputHH(GetParameterComplexDoubleImage("inhh")); m_SRFilter->SetInputVV(GetParameterComplexDoubleImage("invv")); radius.Fill( GetParameterInt("inco.kernelsize") ); m_MeanFilter->GetFilter()->SetRadius(radius); m_MeanFilter->SetInput(m_SRFilter->GetOutput()); m_HAFilter->SetInput(m_MeanFilter->GetOutput()); SetParameterOutputImage("out", m_HAFilter->GetOutput() ); break; case 1: // Barnes if (inhv) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("inhv")); else if (invh) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("invh")); m_SRFilter->SetInputHH(GetParameterComplexDoubleImage("inhh")); m_SRFilter->SetInputVV(GetParameterComplexDoubleImage("invv")); radius.Fill( GetParameterInt("inco.kernelsize") ); m_MeanFilter->GetFilter()->SetRadius(radius); m_MeanFilter->SetInput(m_SRFilter->GetOutput()); m_BarnesFilter->SetInput(m_MeanFilter->GetOutput()); SetParameterComplexOutputImage("out", m_BarnesFilter->GetOutput() ); break; } } //MCPSFilterType::Pointer m_MCPSFilter; SRFilterType::Pointer m_SRFilter; HAFilterType::Pointer m_HAFilter; BarnesFilterType::Pointer m_BarnesFilter; PerBandMeanFilterType::Pointer m_MeanFilter; }; } //end namespace Wrapper } //end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::SARDecompositions) <commit_msg>ENH: SARDecompositions app now outputs complex images<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbReciprocalHAlphaImageFilter.h" #include "otbReciprocalBarnesDecompImageFilter.h" #include "otbReciprocalHuynenDecompImageFilter.h" #include "otbReciprocalPauliDecompImageFilter.h" #include "otbSinclairReciprocalImageFilter.h" #include "otbSinclairToReciprocalCoherencyMatrixFunctor.h" #include "otbPerBandVectorImageFilter.h" #include "itkMeanImageFilter.h" #include "otbNRIBandImagesToOneNComplexBandsImage.h" namespace otb { namespace Wrapper { class SARDecompositions : public Application { public: /** Standard class typedefs. */ typedef SARDecompositions Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; typedef otb::Functor::SinclairToReciprocalCoherencyMatrixFunctor<ComplexDoubleImageType::PixelType, ComplexDoubleImageType::PixelType, ComplexDoubleImageType::PixelType, ComplexDoubleVectorImageType::PixelType> FunctorType; typedef SinclairReciprocalImageFilter<ComplexDoubleImageType, ComplexDoubleImageType, ComplexDoubleImageType, ComplexDoubleVectorImageType, FunctorType > SRFilterType; typedef itk::MeanImageFilter<ComplexDoubleImageType, ComplexDoubleImageType> MeanFilterType; typedef otb::PerBandVectorImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType, MeanFilterType> PerBandMeanFilterType; //typedef otb::NRIBandImagesToOneNComplexBandsImage<DoubleVectorImageType, ComplexDoubleVectorImageType> NRITOOneCFilterType; typedef otb::ReciprocalHAlphaImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType> HAFilterType; typedef otb::ReciprocalBarnesDecompImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType> BarnesFilterType; typedef otb::ReciprocalHuynenDecompImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType> HuynenFilterType; //typedef otb::ReciprocalPauliDecompImageFilter<ComplexDoubleVectorImageType, ComplexDoubleVectorImageType> PauliFilterType; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(SARDecompositions, otb::Application); private: void DoInit() { SetName("SARDecompositions"); SetDescription("From one-band complex images (each one related to an element of the Sinclair matrix), returns the selected decomposition."); // Documentation SetDocName("SARDecompositions"); SetDocLongDescription("From one-band complex images (HH, HV, VH, VV), returns the selected decomposition.\n \n" "All the decompositions implemented are intended for the mono-static case (transmitter and receiver are co-located).\n" "There are two kinds of decomposition : coherent ones and incoherent ones.\n" "In the coherent case, only the Pauli decomposition is available.\n" "In the incoherent case, there the decompositions available : Huynen, Barnes, and H-alpha-A.\n" "User must provide three one-band complex images HH, HV or VH, and VV (mono-static case <=> HV = VH).\n" "Incoherent decompositions consist in averaging 3x3 complex coherency/covariance matrices; the user must provide the size of the averaging window, thanks to the parameter inco.kernelsize.\n " ); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("SARPolarMatrixConvert, SARPolarSynth"); AddDocTag(Tags::SAR); AddParameter(ParameterType_ComplexInputImage, "inhh", "Input Image"); SetParameterDescription("inhh", "Input image (HH)"); AddParameter(ParameterType_ComplexInputImage, "inhv", "Input Image"); SetParameterDescription("inhv", "Input image (HV)"); MandatoryOff("inhv"); AddParameter(ParameterType_ComplexInputImage, "invh", "Input Image"); SetParameterDescription("invh", "Input image (VH)"); MandatoryOff("invh"); AddParameter(ParameterType_ComplexInputImage, "invv", "Input Image"); SetParameterDescription("invv", "Input image (VV)"); AddParameter(ParameterType_ComplexOutputImage, "out", "Output Image"); SetParameterDescription("out", "Output image"); AddParameter(ParameterType_Choice, "decomp", "Decompositions"); AddChoice("decomp.haa","H-alpha-A incoherent decomposition"); SetParameterDescription("decomp.haa","H-alpha-A incoherent decomposition"); AddChoice("decomp.barnes","Barnes incoherent decomposition"); SetParameterDescription("decomp.barnes","Barnes incoherent decomposition"); AddParameter(ParameterType_Group,"inco","Incoherent decompositions"); SetParameterDescription("inco","This group allows setting parameters related to the incoherent decompositions."); AddParameter(ParameterType_Int, "inco.kernelsize", "Kernel size for spatial incoherent averaging."); SetParameterDescription("inco.kernelsize", "Minute (0-59)"); SetMinimumParameterIntValue("inco.kernelsize", 1); SetDefaultParameterInt("inco.kernelsize", 3); MandatoryOff("inco.kernelsize"); AddRAMParameter(); // Default values SetDefaultParameterInt("decomp", 0); // H-alpha-A // Doc example parameter settings SetDocExampleParameterValue("inhh", "HH.tif"); SetDocExampleParameterValue("invh", "VH.tif"); SetDocExampleParameterValue("invv", "VV.tif"); SetDocExampleParameterValue("decomp", "haa"); SetDocExampleParameterValue("out", "HaA.tif"); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { bool inhv = HasUserValue("inhv"); bool invh = HasUserValue("invh"); if ( (!inhv) && (!invh) ) otbAppLogFATAL( << "Parameter inhv or invh not set. Please provide a HV or a VH complex image."); m_SRFilter = SRFilterType::New(); m_HAFilter = HAFilterType::New(); m_MeanFilter = PerBandMeanFilterType::New(); MeanFilterType::InputSizeType radius; m_BarnesFilter = BarnesFilterType::New(); switch (GetParameterInt("decomp")) { case 0: // H-alpha-A if (inhv) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("inhv")); else if (invh) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("invh")); m_SRFilter->SetInputHH(GetParameterComplexDoubleImage("inhh")); m_SRFilter->SetInputVV(GetParameterComplexDoubleImage("invv")); radius.Fill( GetParameterInt("inco.kernelsize") ); m_MeanFilter->GetFilter()->SetRadius(radius); m_MeanFilter->SetInput(m_SRFilter->GetOutput()); m_HAFilter->SetInput(m_MeanFilter->GetOutput()); SetParameterComplexOutputImage("out", m_HAFilter->GetOutput() ); break; case 1: // Barnes if (inhv) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("inhv")); else if (invh) m_SRFilter->SetInputHV_VH(GetParameterComplexDoubleImage("invh")); m_SRFilter->SetInputHH(GetParameterComplexDoubleImage("inhh")); m_SRFilter->SetInputVV(GetParameterComplexDoubleImage("invv")); radius.Fill( GetParameterInt("inco.kernelsize") ); m_MeanFilter->GetFilter()->SetRadius(radius); m_MeanFilter->SetInput(m_SRFilter->GetOutput()); m_BarnesFilter->SetInput(m_MeanFilter->GetOutput()); SetParameterComplexOutputImage("out", m_BarnesFilter->GetOutput() ); break; } } //MCPSFilterType::Pointer m_MCPSFilter; SRFilterType::Pointer m_SRFilter; HAFilterType::Pointer m_HAFilter; BarnesFilterType::Pointer m_BarnesFilter; PerBandMeanFilterType::Pointer m_MeanFilter; }; } //end namespace Wrapper } //end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::SARDecompositions) <|endoftext|>
<commit_before>//===-- SICodeEmitter.cpp - SI Code Emitter -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The SI code emitter produces machine code that can be executed directly on // the GPU device. // //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUCodeEmitter.h" #include "AMDGPUUtil.h" #include "SIInstrInfo.h" #include "SIMachineFunctionInfo.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Target/TargetMachine.h" #include <map> #include <stdio.h> #define LITERAL_REG 255 #define VGPR_BIT(src_idx) (1ULL << (9 * src_idx - 1)) using namespace llvm; namespace { class SICodeEmitter : public MachineFunctionPass, public AMDGPUCodeEmitter { private: static char ID; formatted_raw_ostream &_OS; const TargetMachine *TM; //Program Info unsigned MaxSGPR; unsigned MaxVGPR; unsigned CurrentInstrIndex; std::map<int, unsigned> BBIndexes; void InitProgramInfo(MachineFunction &MF); void EmitState(MachineFunction & MF); void emitInstr(MachineInstr &MI); void outputBytes(uint64_t value, unsigned bytes); unsigned GPRAlign(const MachineInstr &MI, unsigned OpNo, unsigned shift) const; public: SICodeEmitter(formatted_raw_ostream &OS) : MachineFunctionPass(ID), _OS(OS), TM(NULL), MaxSGPR(0), MaxVGPR(0), CurrentInstrIndex(0) { } const char *getPassName() const { return "SI Code Emitter"; } bool runOnMachineFunction(MachineFunction &MF); /// getMachineOpValue - Return the encoding for MO virtual uint64_t getMachineOpValue(const MachineInstr &MI, const MachineOperand &MO) const; /// GPR4AlignEncode - Encoding for when 4 consectuive registers are used virtual unsigned GPR4AlignEncode(const MachineInstr &MI, unsigned OpNo) const; /// GPR2AlignEncode - Encoding for when 2 consecutive registers are used virtual unsigned GPR2AlignEncode(const MachineInstr &MI, unsigned OpNo) const; /// i32LiteralEncode - Encode an i32 literal this is used as an operand /// for an instruction in place of a register. virtual uint64_t i32LiteralEncode(const MachineInstr &MI, unsigned OpNo) const; /// SMRDmemriEncode - Encoding for SMRD indexed loads virtual uint32_t SMRDmemriEncode(const MachineInstr &MI, unsigned OpNo) const; /// VOPPostEncode - Post-Encoder method for VOP instructions virtual uint64_t VOPPostEncode(const MachineInstr &MI, uint64_t Value) const; }; } char SICodeEmitter::ID = 0; FunctionPass *llvm::createSICodeEmitterPass(formatted_raw_ostream &OS) { return new SICodeEmitter(OS); } void SICodeEmitter::EmitState(MachineFunction & MF) { SIMachineFunctionInfo * MFI = MF.getInfo<SIMachineFunctionInfo>(); outputBytes(MaxSGPR + 1, 4); outputBytes(MaxVGPR + 1, 4); outputBytes(MFI->spi_ps_input_addr, 4); } void SICodeEmitter::InitProgramInfo(MachineFunction &MF) { unsigned InstrIndex = 0; bool VCCUsed = false; const SIRegisterInfo * RI = static_cast<const SIRegisterInfo*>(TM->getRegisterInfo()); for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end(); BB != BB_E; ++BB) { MachineBasicBlock &MBB = *BB; BBIndexes[MBB.getNumber()] = InstrIndex; InstrIndex += MBB.size(); for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) { MachineInstr &MI = *I; unsigned numOperands = MI.getNumOperands(); for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) { MachineOperand & MO = MI.getOperand(op_idx); unsigned maxUsed; unsigned width = 0; bool isSGPR = false; unsigned reg; unsigned hwReg; if (!MO.isReg()) { continue; } reg = MO.getReg(); if (reg == AMDGPU::VCC) { VCCUsed = true; continue; } if (AMDGPU::SReg_32RegClass.contains(reg)) { isSGPR = true; width = 1; } else if (AMDGPU::VReg_32RegClass.contains(reg)) { isSGPR = false; width = 1; } else if (AMDGPU::SReg_64RegClass.contains(reg)) { isSGPR = true; width = 2; } else if (AMDGPU::VReg_64RegClass.contains(reg)) { isSGPR = false; width = 2; } else if (AMDGPU::SReg_128RegClass.contains(reg)) { isSGPR = true; width = 4; } else if (AMDGPU::VReg_128RegClass.contains(reg)) { isSGPR = false; width = 4; } else if (AMDGPU::SReg_256RegClass.contains(reg)) { isSGPR = true; width = 8; } else { assert("!Unknown register class"); } hwReg = RI->getHWRegNum(reg); maxUsed = hwReg + width - 1; if (isSGPR) { MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR; } else { MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR; } } } } if (VCCUsed) { MaxSGPR += 2; } } bool SICodeEmitter::runOnMachineFunction(MachineFunction &MF) { TM = &MF.getTarget(); const AMDGPUSubtarget &STM = TM->getSubtarget<AMDGPUSubtarget>(); if (STM.dumpCode()) { MF.dump(); } InitProgramInfo(MF); EmitState(MF); for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end(); BB != BB_E; ++BB) { MachineBasicBlock &MBB = *BB; for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) { MachineInstr &MI = *I; if (MI.getOpcode() != AMDGPU::KILL && MI.getOpcode() != AMDGPU::RETURN) { emitInstr(MI); CurrentInstrIndex++; } } } // Emit S_END_PGM MachineInstr * End = BuildMI(MF, DebugLoc(), TM->getInstrInfo()->get(AMDGPU::S_ENDPGM)); emitInstr(*End); return false; } void SICodeEmitter::emitInstr(MachineInstr &MI) { const SIInstrInfo * SII = static_cast<const SIInstrInfo*>(TM->getInstrInfo()); uint64_t hwInst = getBinaryCodeForInstr(MI); if ((hwInst & 0xffffffff) == 0xffffffff) { fprintf(stderr, "Unsupported Instruction: \n"); MI.dump(); abort(); } unsigned bytes = SII->getEncodingBytes(MI); outputBytes(hwInst, bytes); } uint64_t SICodeEmitter::getMachineOpValue(const MachineInstr &MI, const MachineOperand &MO) const { const SIRegisterInfo * RI = static_cast<const SIRegisterInfo*>(TM->getRegisterInfo()); switch(MO.getType()) { case MachineOperand::MO_Register: return RI->getBinaryCode(MO.getReg()); case MachineOperand::MO_Immediate: return MO.getImm(); case MachineOperand::MO_FPImmediate: // XXX: Not all instructions can use inline literals // XXX: We should make sure this is a 32-bit constant return LITERAL_REG | (MO.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue() << 32); case MachineOperand::MO_MachineBasicBlock: return (*BBIndexes.find(MI.getParent()->getNumber())).second - CurrentInstrIndex - 1; default: llvm_unreachable("Encoding of this operand type is not supported yet."); break; } } unsigned SICodeEmitter::GPRAlign(const MachineInstr &MI, unsigned OpNo, unsigned shift) const { const SIRegisterInfo * RI = static_cast<const SIRegisterInfo*>(TM->getRegisterInfo()); unsigned regCode = RI->getHWRegNum(MI.getOperand(OpNo).getReg()); return regCode >> shift; } unsigned SICodeEmitter::GPR4AlignEncode(const MachineInstr &MI, unsigned OpNo) const { return GPRAlign(MI, OpNo, 2); } unsigned SICodeEmitter::GPR2AlignEncode(const MachineInstr &MI, unsigned OpNo) const { return GPRAlign(MI, OpNo, 1); } uint64_t SICodeEmitter::i32LiteralEncode(const MachineInstr &MI, unsigned OpNo) const { return LITERAL_REG | (MI.getOperand(OpNo).getImm() << 32); } #define SMRD_OFFSET_MASK 0xff #define SMRD_IMM_SHIFT 8 #define SMRD_SBASE_MASK 0x3f #define SMRD_SBASE_SHIFT 9 /// SMRDmemriEncode - This function is responsibe for encoding the offset /// and the base ptr for SMRD instructions it should return a bit string in /// this format: /// /// OFFSET = bits{7-0} /// IMM = bits{8} /// SBASE = bits{14-9} /// uint32_t SICodeEmitter::SMRDmemriEncode(const MachineInstr &MI, unsigned OpNo) const { uint32_t encoding; const MachineOperand &OffsetOp = MI.getOperand(OpNo + 1); //XXX: Use this function for SMRD loads with register offsets assert(OffsetOp.isImm()); encoding = (getMachineOpValue(MI, OffsetOp) & SMRD_OFFSET_MASK) | (1 << SMRD_IMM_SHIFT) //XXX If the Offset is a register we shouldn't set this bit | ((GPR2AlignEncode(MI, OpNo) & SMRD_SBASE_MASK) << SMRD_SBASE_SHIFT) ; return encoding; } /// Set the "VGPR" bit for VOP args that can take either a VGPR or a SGPR. /// XXX: It would be nice if we could handle this without a PostEncode function. uint64_t SICodeEmitter::VOPPostEncode(const MachineInstr &MI, uint64_t Value) const { const SIInstrInfo * SII = static_cast<const SIInstrInfo*>(TM->getInstrInfo()); unsigned encodingType = SII->getEncodingType(MI); unsigned numSrcOps; unsigned vgprBitOffset; if (encodingType == SIInstrEncodingType::VOP3) { numSrcOps = 3; vgprBitOffset = 32; } else { numSrcOps = 1; vgprBitOffset = 0; } // Add one to skip over the destination reg operand. for (unsigned opIdx = 1; opIdx < numSrcOps + 1; opIdx++) { if (!MI.getOperand(opIdx).isReg()) { continue; } unsigned reg = MI.getOperand(opIdx).getReg(); if (AMDGPU::VReg_32RegClass.contains(reg) || AMDGPU::VReg_64RegClass.contains(reg)) { Value |= (VGPR_BIT(opIdx)) << vgprBitOffset; } } return Value; } void SICodeEmitter::outputBytes(uint64_t value, unsigned bytes) { for (unsigned i = 0; i < bytes; i++) { _OS.write((uint8_t) ((value >> (8 * i)) & 0xff)); } } <commit_msg>radeon/llvm: fix fp immediates on SI<commit_after>//===-- SICodeEmitter.cpp - SI Code Emitter -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The SI code emitter produces machine code that can be executed directly on // the GPU device. // //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUCodeEmitter.h" #include "AMDGPUUtil.h" #include "SIInstrInfo.h" #include "SIMachineFunctionInfo.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Target/TargetMachine.h" #include <map> #include <stdio.h> #define LITERAL_REG 255 #define VGPR_BIT(src_idx) (1ULL << (9 * src_idx - 1)) using namespace llvm; namespace { class SICodeEmitter : public MachineFunctionPass, public AMDGPUCodeEmitter { private: static char ID; formatted_raw_ostream &_OS; const TargetMachine *TM; //Program Info unsigned MaxSGPR; unsigned MaxVGPR; unsigned CurrentInstrIndex; std::map<int, unsigned> BBIndexes; void InitProgramInfo(MachineFunction &MF); void EmitState(MachineFunction & MF); void emitInstr(MachineInstr &MI); void outputBytes(uint64_t value, unsigned bytes); unsigned GPRAlign(const MachineInstr &MI, unsigned OpNo, unsigned shift) const; public: SICodeEmitter(formatted_raw_ostream &OS) : MachineFunctionPass(ID), _OS(OS), TM(NULL), MaxSGPR(0), MaxVGPR(0), CurrentInstrIndex(0) { } const char *getPassName() const { return "SI Code Emitter"; } bool runOnMachineFunction(MachineFunction &MF); /// getMachineOpValue - Return the encoding for MO virtual uint64_t getMachineOpValue(const MachineInstr &MI, const MachineOperand &MO) const; /// GPR4AlignEncode - Encoding for when 4 consectuive registers are used virtual unsigned GPR4AlignEncode(const MachineInstr &MI, unsigned OpNo) const; /// GPR2AlignEncode - Encoding for when 2 consecutive registers are used virtual unsigned GPR2AlignEncode(const MachineInstr &MI, unsigned OpNo) const; /// i32LiteralEncode - Encode an i32 literal this is used as an operand /// for an instruction in place of a register. virtual uint64_t i32LiteralEncode(const MachineInstr &MI, unsigned OpNo) const; /// SMRDmemriEncode - Encoding for SMRD indexed loads virtual uint32_t SMRDmemriEncode(const MachineInstr &MI, unsigned OpNo) const; /// VOPPostEncode - Post-Encoder method for VOP instructions virtual uint64_t VOPPostEncode(const MachineInstr &MI, uint64_t Value) const; }; } char SICodeEmitter::ID = 0; FunctionPass *llvm::createSICodeEmitterPass(formatted_raw_ostream &OS) { return new SICodeEmitter(OS); } void SICodeEmitter::EmitState(MachineFunction & MF) { SIMachineFunctionInfo * MFI = MF.getInfo<SIMachineFunctionInfo>(); outputBytes(MaxSGPR + 1, 4); outputBytes(MaxVGPR + 1, 4); outputBytes(MFI->spi_ps_input_addr, 4); } void SICodeEmitter::InitProgramInfo(MachineFunction &MF) { unsigned InstrIndex = 0; bool VCCUsed = false; const SIRegisterInfo * RI = static_cast<const SIRegisterInfo*>(TM->getRegisterInfo()); for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end(); BB != BB_E; ++BB) { MachineBasicBlock &MBB = *BB; BBIndexes[MBB.getNumber()] = InstrIndex; InstrIndex += MBB.size(); for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) { MachineInstr &MI = *I; unsigned numOperands = MI.getNumOperands(); for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) { MachineOperand & MO = MI.getOperand(op_idx); unsigned maxUsed; unsigned width = 0; bool isSGPR = false; unsigned reg; unsigned hwReg; if (!MO.isReg()) { continue; } reg = MO.getReg(); if (reg == AMDGPU::VCC) { VCCUsed = true; continue; } if (AMDGPU::SReg_32RegClass.contains(reg)) { isSGPR = true; width = 1; } else if (AMDGPU::VReg_32RegClass.contains(reg)) { isSGPR = false; width = 1; } else if (AMDGPU::SReg_64RegClass.contains(reg)) { isSGPR = true; width = 2; } else if (AMDGPU::VReg_64RegClass.contains(reg)) { isSGPR = false; width = 2; } else if (AMDGPU::SReg_128RegClass.contains(reg)) { isSGPR = true; width = 4; } else if (AMDGPU::VReg_128RegClass.contains(reg)) { isSGPR = false; width = 4; } else if (AMDGPU::SReg_256RegClass.contains(reg)) { isSGPR = true; width = 8; } else { assert("!Unknown register class"); } hwReg = RI->getHWRegNum(reg); maxUsed = hwReg + width - 1; if (isSGPR) { MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR; } else { MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR; } } } } if (VCCUsed) { MaxSGPR += 2; } } bool SICodeEmitter::runOnMachineFunction(MachineFunction &MF) { TM = &MF.getTarget(); const AMDGPUSubtarget &STM = TM->getSubtarget<AMDGPUSubtarget>(); if (STM.dumpCode()) { MF.dump(); } InitProgramInfo(MF); EmitState(MF); for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end(); BB != BB_E; ++BB) { MachineBasicBlock &MBB = *BB; for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) { MachineInstr &MI = *I; if (MI.getOpcode() != AMDGPU::KILL && MI.getOpcode() != AMDGPU::RETURN) { emitInstr(MI); CurrentInstrIndex++; } } } // Emit S_END_PGM MachineInstr * End = BuildMI(MF, DebugLoc(), TM->getInstrInfo()->get(AMDGPU::S_ENDPGM)); emitInstr(*End); return false; } void SICodeEmitter::emitInstr(MachineInstr &MI) { const SIInstrInfo * SII = static_cast<const SIInstrInfo*>(TM->getInstrInfo()); uint64_t hwInst = getBinaryCodeForInstr(MI); if ((hwInst & 0xffffffff) == 0xffffffff) { fprintf(stderr, "Unsupported Instruction: \n"); MI.dump(); abort(); } unsigned bytes = SII->getEncodingBytes(MI); outputBytes(hwInst, bytes); } uint64_t SICodeEmitter::getMachineOpValue(const MachineInstr &MI, const MachineOperand &MO) const { const SIRegisterInfo * RI = static_cast<const SIRegisterInfo*>(TM->getRegisterInfo()); switch(MO.getType()) { case MachineOperand::MO_Register: return RI->getBinaryCode(MO.getReg()); case MachineOperand::MO_Immediate: return MO.getImm(); case MachineOperand::MO_FPImmediate: // XXX: Not all instructions can use inline literals // XXX: We should make sure this is a 32-bit constant return LITERAL_REG; case MachineOperand::MO_MachineBasicBlock: return (*BBIndexes.find(MI.getParent()->getNumber())).second - CurrentInstrIndex - 1; default: llvm_unreachable("Encoding of this operand type is not supported yet."); break; } } unsigned SICodeEmitter::GPRAlign(const MachineInstr &MI, unsigned OpNo, unsigned shift) const { const SIRegisterInfo * RI = static_cast<const SIRegisterInfo*>(TM->getRegisterInfo()); unsigned regCode = RI->getHWRegNum(MI.getOperand(OpNo).getReg()); return regCode >> shift; } unsigned SICodeEmitter::GPR4AlignEncode(const MachineInstr &MI, unsigned OpNo) const { return GPRAlign(MI, OpNo, 2); } unsigned SICodeEmitter::GPR2AlignEncode(const MachineInstr &MI, unsigned OpNo) const { return GPRAlign(MI, OpNo, 1); } uint64_t SICodeEmitter::i32LiteralEncode(const MachineInstr &MI, unsigned OpNo) const { return LITERAL_REG | (MI.getOperand(OpNo).getImm() << 32); } #define SMRD_OFFSET_MASK 0xff #define SMRD_IMM_SHIFT 8 #define SMRD_SBASE_MASK 0x3f #define SMRD_SBASE_SHIFT 9 /// SMRDmemriEncode - This function is responsibe for encoding the offset /// and the base ptr for SMRD instructions it should return a bit string in /// this format: /// /// OFFSET = bits{7-0} /// IMM = bits{8} /// SBASE = bits{14-9} /// uint32_t SICodeEmitter::SMRDmemriEncode(const MachineInstr &MI, unsigned OpNo) const { uint32_t encoding; const MachineOperand &OffsetOp = MI.getOperand(OpNo + 1); //XXX: Use this function for SMRD loads with register offsets assert(OffsetOp.isImm()); encoding = (getMachineOpValue(MI, OffsetOp) & SMRD_OFFSET_MASK) | (1 << SMRD_IMM_SHIFT) //XXX If the Offset is a register we shouldn't set this bit | ((GPR2AlignEncode(MI, OpNo) & SMRD_SBASE_MASK) << SMRD_SBASE_SHIFT) ; return encoding; } /// Set the "VGPR" bit for VOP args that can take either a VGPR or a SGPR. /// XXX: It would be nice if we could handle this without a PostEncode function. uint64_t SICodeEmitter::VOPPostEncode(const MachineInstr &MI, uint64_t Value) const { const SIInstrInfo * SII = static_cast<const SIInstrInfo*>(TM->getInstrInfo()); unsigned encodingType = SII->getEncodingType(MI); unsigned numSrcOps; unsigned vgprBitOffset; if (encodingType == SIInstrEncodingType::VOP3) { numSrcOps = 3; vgprBitOffset = 32; } else { numSrcOps = 1; vgprBitOffset = 0; } // Add one to skip over the destination reg operand. for (unsigned opIdx = 1; opIdx < numSrcOps + 1; opIdx++) { const MachineOperand &MO = MI.getOperand(opIdx); switch(MO.getType()) { case MachineOperand::MO_Register: { unsigned reg = MI.getOperand(opIdx).getReg(); if (AMDGPU::VReg_32RegClass.contains(reg) || AMDGPU::VReg_64RegClass.contains(reg)) { Value |= (VGPR_BIT(opIdx)) << vgprBitOffset; } } break; case MachineOperand::MO_FPImmediate: // XXX: Not all instructions can use inline literals // XXX: We should make sure this is a 32-bit constant Value |= (MO.getFPImm()->getValueAPF().bitcastToAPInt().getZExtValue() << 32); continue; default: break; } } return Value; } void SICodeEmitter::outputBytes(uint64_t value, unsigned bytes) { for (unsigned i = 0; i < bytes; i++) { _OS.write((uint8_t) ((value >> (8 * i)) & 0xff)); } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and contributors * * 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.txt * * 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 "selxSuperElastixFilterCustomComponents.h" #include "selxNiftyregReadImageComponent.h" #include "selxNiftyregWriteImageComponent.h" #include "selxNiftyregWriteImageComponent.h" #include "selxItkToNiftiImageSourceComponent.h" #include "selxNiftiToItkImageSinkComponent.h" #include "selxItkImageSourceComponent.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "selxNiftyregf3dComponent.h" #include "selxNiftyregSplineToDisplacementFieldComponent.h" #include "selxDisplacementFieldNiftiToItkImageSinkComponent.h" #include "selxNiftyregAladinComponent.h" #include "selxDataManager.h" #include "gtest/gtest.h" #include "_reg_tools.h" namespace selx { class NiftyregDisplacementTest : public ::testing::Test { public: typedef Blueprint::Pointer BlueprintPointer; typedef Blueprint::ParameterMapType ParameterMapType; typedef Blueprint::ParameterValueType ParameterValueType; typedef DataManager DataManagerType; /** register all example components */ typedef TypeList< ItkToNiftiImageSourceComponent< 2, float >, NiftiToItkImageSinkComponent< 2, float >, ItkImageSourceComponent< 2, float >, ItkToNiftiImageSourceComponent< 3, float >, NiftiToItkImageSinkComponent< 3, float >, ItkImageSourceComponent< 3, float >, DisplacementFieldNiftiToItkImageSinkComponent< 2, float>> RegisterComponents; typedef SuperElastixFilterCustomComponents< RegisterComponents > SuperElastixFilterType; virtual void SetUp() { // Instantiate SuperElastixFilter before each test and // register the components we want to have available in SuperElastix superElastixFilter = SuperElastixFilterCustomComponents< RegisterComponents >::New(); dataManager = DataManagerType::New(); logger = Logger::New(); logger->AddStream("cout", std::cout); logger->SetLogLevel(LogLevel::TRC); } virtual void TearDown() { // Unregister all components after each test itk::ObjectFactoryBase::UnRegisterAllFactories(); // Delete the SuperElastixFilter after each test superElastixFilter = nullptr; } BlueprintPointer blueprint; Logger::Pointer logger; SuperElastixFilterBase::Pointer superElastixFilter; DataManagerType::Pointer dataManager; }; TEST_F( NiftyregDisplacementTest, displacement_conversion ) { /** make example blueprint configuration */ // Generate an nifti image on the fly int size = 64; int dim[8] = {3, size, size, size, 1, 1, 1, 1}; nifti_image *floating_image = nifti_make_new_nim(dim, NIFTI_TYPE_FLOAT32, true); float *imgPtr = static_cast<float>(floating_image->data); for(int i=0; i<floating_image->nvox; ++i){ imgPtr[i] = i; } // Create a deformation field that embeds an affine transformation mat44 affine; affine.m[0][0]=0.8.f;affine.m[0][1]=0.1f;affine.m[0][2]=0.1f;affine.m[0][3]=-5.f; affine.m[0][0]=0.1f;affine.m[0][1]=1.1f;affine.m[0][2]=0.1f;affine.m[0][3]=1.f; affine.m[0][0]=0.1f;affine.m[0][1]=0.1f;affine.m[0][2]=1.f;affine.m[0][3]=5.f; affine.m[0][0]=0.f;affine.m[0][1]=0.f;affine.m[0][2]=0.f;affine.m[3][3]=1.f; nifti_image *transFieldImage = nifti_copy_nim_info(floating_image); transFieldImage->dim[0]=transFieldImage->ndim=5; transFieldImage->dim[1]=transFieldImage->nx=floating_image->nx; transFieldImage->dim[2]=transFieldImage->ny=floating_image->ny; transFieldImage->dim[3]=transFieldImage->nz=floating_image->nz; transFieldImage->dim[4]=transFieldImage->nt=1; transFieldImage->pixdim[4]=transFieldImage->dt=1.0; transFieldImage->dim[5]=transFieldImage->nu=floating_image->nz>1?3:2; transFieldImage->dim[6]=transFieldImage->nv=1; transFieldImage->dim[7]=transFieldImage->nw=1; transFieldImage->nvox =(size_t)transFieldImage->nx* transFieldImage->ny*transFieldImage->nz* transFieldImage->nt*transFieldImage->nu; transFieldImage->scl_slope=1.f; transFieldImage->scl_inter=0.f; transFieldImage->datatype = NIFTI_TYPE_FLOAT32; transFieldImage->nbyper = sizeof(float); transFieldImage->data = (void *)calloc(transFieldImage->nvox, transFieldImage->nbyper); reg_affine_getDeformationField(&affine, transFieldImage); // Apply the deformation to the floating image nifti_image* warped_image = nifti_copy_nim_info(floating_image); warped_image->data = (void *)calloc(warped_image->nvox,warped_image->nbyper); reg_resampleImage(floating_image, warped_image, transFieldImage, NULL, 0, // nearest neighbour interpolation 0); // 0 padding // Convert the deformation field into a displacement field reg_getDisplacementFromDeformation(transFieldImage); // NEED TO ADD THE SELX PART HERE // NEED TO ADD THE COMPARISON HERE nifti_image_free(floating_image); nifti_image_free(warped_image); nifti_image_free(transFieldImage); } } <commit_msg>WIP: Extended unit test with itk warp comparision #257<commit_after>/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and contributors * * 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.txt * * 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 "selxSuperElastixFilterCustomComponents.h" #include "selxNiftyregReadImageComponent.h" #include "selxNiftyregWriteImageComponent.h" #include "selxNiftyregWriteImageComponent.h" #include "selxItkToNiftiImageSourceComponent.h" #include "selxNiftiToItkImageSinkComponent.h" #include "selxItkImageSourceComponent.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "selxNiftyregf3dComponent.h" #include "selxNiftyregSplineToDisplacementFieldComponent.h" #include "selxDisplacementFieldNiftiToItkImageSinkComponent.h" #include "selxNiftyregAladinComponent.h" #include "itkDisplacementFieldTransform.h" #include "itkResampleImageFilter.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include <itkTestingComparisonImageFilter.h> #include "selxDataManager.h" #include "gtest/gtest.h" #include "_reg_tools.h" namespace selx { class NiftyregDisplacementTest : public ::testing::Test { public: typedef Blueprint::Pointer BlueprintPointer; typedef Blueprint::ParameterMapType ParameterMapType; typedef Blueprint::ParameterValueType ParameterValueType; typedef DataManager DataManagerType; /** register all example components */ typedef TypeList< ItkToNiftiImageSourceComponent< 2, float >, NiftiToItkImageSinkComponent< 2, float >, ItkImageSourceComponent< 2, float >, ItkToNiftiImageSourceComponent< 3, float >, NiftiToItkImageSinkComponent< 3, float >, ItkImageSourceComponent< 3, float >, DisplacementFieldNiftiToItkImageSinkComponent< 2, float>> RegisterComponents; typedef SuperElastixFilterCustomComponents< RegisterComponents > SuperElastixFilterType; virtual void SetUp() { // Instantiate SuperElastixFilter before each test and // register the components we want to have available in SuperElastix superElastixFilter = SuperElastixFilterCustomComponents< RegisterComponents >::New(); dataManager = DataManagerType::New(); logger = Logger::New(); logger->AddStream("cout", std::cout); logger->SetLogLevel(LogLevel::TRC); } virtual void TearDown() { // Unregister all components after each test itk::ObjectFactoryBase::UnRegisterAllFactories(); // Delete the SuperElastixFilter after each test superElastixFilter = nullptr; } BlueprintPointer blueprint; Logger::Pointer logger; SuperElastixFilterBase::Pointer superElastixFilter; DataManagerType::Pointer dataManager; }; TEST_F( NiftyregDisplacementTest, displacement_conversion ) { /** make example blueprint configuration */ // Generate an nifti image on the fly int size = 64; int dim[8] = {3, size, size, size, 1, 1, 1, 1}; nifti_image *floating_image = nifti_make_new_nim(dim, NIFTI_TYPE_FLOAT32, true); floating_image->qform_code = 1; float *imgPtr = static_cast<float*>(floating_image->data); for(int i=0; i<floating_image->nvox; ++i){ imgPtr[i] = i; } // Create a deformation field that embeds an affine transformation mat44 affine; affine.m[0][0]=0.8f;affine.m[0][1]=0.1f;affine.m[0][2]=0.1f;affine.m[0][3]=-5.f; affine.m[1][0]=0.1f;affine.m[1][1]=1.1f;affine.m[1][2]=0.1f;affine.m[1][3]=1.f; affine.m[2][0]=0.1f;affine.m[2][1]=0.1f;affine.m[1][2]=1.f;affine.m[2][3]=5.f; affine.m[3][0]=0.f;affine.m[3][1]=0.f;affine.m[1][2]=0.f;affine.m[3][3]=1.f; reg_mat44_eye(&affine); nifti_image *transFieldImage = nifti_copy_nim_info(floating_image); transFieldImage->dim[0]=transFieldImage->ndim=5; transFieldImage->dim[1]=transFieldImage->nx=floating_image->nx; transFieldImage->dim[2]=transFieldImage->ny=floating_image->ny; transFieldImage->dim[3]=transFieldImage->nz=floating_image->nz; transFieldImage->dim[4]=transFieldImage->nt=1; transFieldImage->pixdim[4]=transFieldImage->dt=1.0; transFieldImage->dim[5]=transFieldImage->nu=floating_image->nz>1?3:2; transFieldImage->dim[6]=transFieldImage->nv=1; transFieldImage->dim[7]=transFieldImage->nw=1; transFieldImage->nvox =(size_t)transFieldImage->nx* transFieldImage->ny*transFieldImage->nz* transFieldImage->nt*transFieldImage->nu; transFieldImage->scl_slope=1.f; transFieldImage->scl_inter=0.f; transFieldImage->datatype = NIFTI_TYPE_FLOAT32; transFieldImage->nbyper = sizeof(float); transFieldImage->data = (void *)calloc(transFieldImage->nvox, transFieldImage->nbyper); reg_affine_getDeformationField(&affine, transFieldImage); // Apply the deformation to the floating image nifti_image* warped_image = nifti_copy_nim_info(floating_image); warped_image->data = (void *)calloc(warped_image->nvox,warped_image->nbyper); reg_resampleImage(floating_image, warped_image, transFieldImage, NULL, 0, // nearest neighbour interpolation 0); // 0 padding // Convert the deformation field into a displacement field reg_getDisplacementFromDeformation(transFieldImage); float *dispPtrX = static_cast<float *>(transFieldImage->data); float *dispPtrY = static_cast<float *>(&dispPtrX[warped_image->nvox]); float *dispPtrZ = static_cast<float *>(&dispPtrY[warped_image->nvox]); for (int v = 0; v<warped_image->nvox; v++) { dispPtrX[v] *= -1.f; dispPtrY[v] *= -1.f; } reg_io_WriteImageFile(warped_image,"NiftyregDisplacementTest_displacement_conversion_nifty.nii"); // NEED TO ADD THE SELX PART HERE using itkImageType = itk::Image<float, 3>; std::shared_ptr< nifti_image > nifti_floating_image(floating_image, nifti_image_free); auto itkImage = selx::NiftiToItkImage<itkImageType, float>::Convert(nifti_floating_image); using CoordRepType = float; using itkDisplacementType = itk::Image<itk::Vector<CoordRepType,3>, 3>; std::shared_ptr< nifti_image > nifti_transFieldImage(transFieldImage, nifti_image_free); auto itkDisplacementImage = selx::NiftiToItkImage<itkDisplacementType, float>::Convert(nifti_transFieldImage); using DisplacementFieldTransformType = itk::DisplacementFieldTransform< CoordRepType, 3 >; using DisplacementFieldTransformPointer = typename DisplacementFieldTransformType::Pointer; using ResampleImageFilterType = itk::ResampleImageFilter< itkImageType, itkImageType, CoordRepType >; using ResampleImageFilterPointer = typename ResampleImageFilterType::Pointer; using NearestNeighborInterpolatorType = itk::NearestNeighborInterpolateImageFunction< itkImageType, typename itkImageType::PixelType>; using NearestNeighborInterpolatorTypePointer = typename NearestNeighborInterpolatorType::Pointer; auto displacementFieldTransform = DisplacementFieldTransformType::New(); auto resampleImageFilter = ResampleImageFilterType::New(); resampleImageFilter->SetInput(itkImage); resampleImageFilter->SetTransform(displacementFieldTransform.GetPointer()); auto nearestNeighborInterpolator = NearestNeighborInterpolatorType::New(); resampleImageFilter->SetInterpolator(nearestNeighborInterpolator); itkDisplacementImage->Update(); displacementFieldTransform->SetDisplacementField(itkDisplacementImage); resampleImageFilter->SetOutputParametersFromImage(itkDisplacementImage); //resampleImageFilter->Update(); auto itkwarped = resampleImageFilter->GetOutput(); auto itkwriter = itk::ImageFileWriter<itkImageType>::New(); itkwriter->SetInput(itkwarped); itkwriter->SetFileName("NiftyregDisplacementTest_displacement_conversion_itk.nii"); itkwriter->Update(); // NEED TO ADD THE COMPARISON HERE std::shared_ptr< nifti_image > nifti_warped_image(warped_image, nifti_image_free); auto itk_nifti_warped_image = selx::NiftiToItkImage<itkImageType, float>::Convert(nifti_warped_image); auto diff = itk::Testing::ComparisonImageFilter<itkImageType,itkImageType>::New(); diff->SetValidInput(itk_nifti_warped_image); //diff->SetTestInput(itk_nifti_warped_image); //diff->SetValidInput(resampleImageFilter->GetOutput()); diff->SetTestInput(resampleImageFilter->GetOutput()); diff->SetDifferenceThreshold(0.0); //diff->SetToleranceRadius(radiusTolerance); diff->UpdateLargestPossibleRegion(); bool differenceFailed = false; const double averageIntensityDifference = diff->GetTotalDifference(); //nifti_image_free(floating_image); //nifti_image_free(warped_image); //nifti_image_free(transFieldImage); } } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- MusicBrainz -- The Internet music metadatabase Copyright (C) 2000 Robert Kaye 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ ----------------------------------------------------------------------------*/ #include <stdio.h> #include "musicbrainz.h" #include "queries.h" struct Queries { char *name, *value; int numArgs; char *arg1, *arg2, *arg3, *arg4; }; const char *SUBMIT_LYRICS_QUERY= " <MQ:Query>SubmitTrack</MQ:Query>\n" " <DC:Title>Big Time TWO</DC:Title>\n" " <DC:Creator>Peter another Gabriel</DC:Creator>\n" " <MM:Album>So des ca</MM:Album>\n" " <DC:Relation track=\"9\"/>\n" " <MM:SyncEvents>\n" //" <rdf:Description about=\"http://usenet4free.com?grp=alt.music.lyrics&art=26819\">\n" " <rdf:Description>\n" " <DC:Contributor>Red Hot Lyrics Man</DC:Contributor>\n" " <DC:Type type=\"lyrics\"/>\n" " <DC:Date>2000-07-27</DC:Date>\n" " <rdf:Seq>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"00:02.451\">Hello World</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"00:06.882\">Sing along</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"01:03.096\">Make</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"01:09.478\">it</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"01:13.516\">all</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"01:41.744\">clear.</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " </rdf:Seq>\n" " </rdf:Description>\n" " </MM:SyncEvents>\n"; Queries queries[] = { { "GetCDInfoFromCDIndexId", MB_GetCDInfoFromCDIndexID, 1, "CD Index ID", "", "", "" }, { "FindArtist", MB_FindArtistByName, 1, "Artist Name", "", "", "" }, { "FindTrack", MB_FindTrackByName, 3, "Track Name", "Album Name", "Artist Name", "" }, { "FindAlbumsByArtist", MB_FindAlbumsByArtistName, 1, "Artist Name", "", "", "" }, { "FindAlbum", MB_FindAlbumByName, 1, "Album Name", "", "", "" }, { "FindDistinctGUID", MB_FindDistinctGUID, 2, "Track Name", "Artist Name", "", "" }, { "GetArtist", MB_GetArtistById , 1, "Artist ID", "", "", "" }, { "GetAlbum", MB_GetAlbumById , 1, "Album ID", "", "", "" }, { "GetAlbumsByArtist", MB_GetAlbumsByArtistId , 1, "Artist ID", "", "", "" }, { "GetTrack", MB_GetTrackById , 1, "Track ID", "", "", "" }, { "GetTrackGUID", MB_GetTrackByGUID , 1, "Track GUID", "", "", "" }, { "GetSyncText", MB_GetSyncTextById , 1, "Track ID", "", "", "" }, { "GetCDInfo", MB_GetCDInfo , 0, "", "", "", "" }, { "GetCDTOC", MB_GetCDTOC , 0, "", "", "", "" }, { "AssociateCD", MB_AssociateCD , 0, "", "", "", "" }, { "\0", "\0", 0, "", "", "", "" } }; #ifdef WIN32 #define strcasecmp stricmp #endif int main(void) { MusicBrainz o; string error, data; bool ret; Queries *p; char szLine[256], *szCmd, *ptr, szLast[100]; string xml, qarg, query, server; vector<string> args; // Set the server you want to use. Defaults to www.musicbrainz.org:80 server = string("musicbrainz.eorbit.net"); o.SetServer(server, 80); // Tell the client library to return data in ISO8859-1 and not UTF-8 o.UseUTF8(0); // If you need to use a proxy, uncomment/edit the following line // as appropriate //o.SetProxy("proxy.mydomain.com", 80); for(;;) { query = ""; printf("query> "); fflush(stdout); if (fgets(szLine, 255, stdin) < 0) break; if (strncmp(szLine, "!!", 2) == 0) { printf("%s\n", szLast); strcpy(szLine, szLast); } else strcpy(szLast, szLine); szLine[strlen(szLine) - 1] = 0; szCmd = strtok(szLine, " "); if (szCmd == NULL) continue; args.clear(); for(;;) { ptr = strtok(NULL, " "); if (!ptr) break; if (*ptr == '\"' && !(*(ptr + strlen(ptr) - 1) == '\"')) { qarg = string(ptr + 1); for(;;) { ptr = strtok(NULL, " "); if (!ptr) break; if (*(ptr + strlen(ptr) - 1) == '\"') { *(ptr + strlen(ptr) - 1) = 0; qarg += string(" ") + string(ptr); ptr = (char *)qarg.c_str(); break; } qarg += string(" ") + string(ptr); } if (!ptr) { continue; } } if (*ptr == '\"' && *(ptr + strlen(ptr) - 1) == '\"') { *(ptr + strlen(ptr) - 1) = 0; args.push_back(string(ptr + 1)); } else { if (strcmp(ptr, "\"\"") == 0) *ptr = 0; args.push_back(string(ptr)); } } if (strncmp(szCmd, "bye", 3) == 0 || strncmp(szCmd, "quit", 4) == 0 || strncmp(szCmd, "exit", 4) == 0) { break; } if (strncmp(szCmd, "help", 4) == 0) { printf("Available commands: Arguments:\n\n"); for(p = queries; *p->name; p++) { printf("%-34s ", p->name); if (strlen(p->arg1)) printf("<%s> ", p->arg1); if (strlen(p->arg2)) printf("<%s> ", p->arg2); if (strlen(p->arg3)) printf("<%s> ", p->arg3); if (strlen(p->arg4)) printf("<%s> ", p->arg4); printf("\n"); } printf("exit/quit/bye [quit]\n"); printf("submit [get web submit URL]\n"); printf("info [help on a command]\n"); continue; } if (strncmp(szCmd, "lyrics", 6) == 0) { query = string(SUBMIT_LYRICS_QUERY); } if (strncmp(szCmd, "submit", 6) == 0) { string url; ret = o.GetWebSubmitURL(url); if (ret) printf("URL: %s\n", url.c_str()); else printf("Could not determine web submit url.\n"); continue; } if (strncmp(szCmd, "info", 4) == 0) { for(p = queries; p->name; p++) { if (strcasecmp(szCmd + 5, p->name) == 0) { printf("usage: %s ", p->name); if (strlen(p->arg1)) printf("<%s> ", p->arg1); if (strlen(p->arg2)) printf("<%s> ", p->arg2); if (strlen(p->arg3)) printf("<%s> ", p->arg3); if (strlen(p->arg4)) printf("<%s> ", p->arg4); printf("\n"); break; } } if (p->name == NULL) printf("No info available for %s\n", szCmd + 5); continue; } if (query.length() == 0) { for(p = queries; p->name; p++) { if (strcasecmp(szCmd, p->name) == 0) break; } if (p->name == NULL) { printf("Unknown query.\n"); continue; } query = string(p->value); } ret = o.Query(query, &args); if (!ret) { o.GetQueryError(error); printf("Query failed: %s\n", error.c_str()); continue; } printf("Query ok. Items returned: %d\n", o.GetNumItems()); o.GetResultRDF(xml); printf("Returned RDF object:\n\n%s\n", xml.c_str()); } return 0; } <commit_msg>Fixed the server<commit_after>/* -------------------------------------------------------------------------- MusicBrainz -- The Internet music metadatabase Copyright (C) 2000 Robert Kaye 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ ----------------------------------------------------------------------------*/ #include <stdio.h> #include "musicbrainz.h" #include "queries.h" struct Queries { char *name, *value; int numArgs; char *arg1, *arg2, *arg3, *arg4; }; const char *SUBMIT_LYRICS_QUERY= " <MQ:Query>SubmitTrack</MQ:Query>\n" " <DC:Title>Big Time TWO</DC:Title>\n" " <DC:Creator>Peter another Gabriel</DC:Creator>\n" " <MM:Album>So des ca</MM:Album>\n" " <DC:Relation track=\"9\"/>\n" " <MM:SyncEvents>\n" //" <rdf:Description about=\"http://usenet4free.com?grp=alt.music.lyrics&art=26819\">\n" " <rdf:Description>\n" " <DC:Contributor>Red Hot Lyrics Man</DC:Contributor>\n" " <DC:Type type=\"lyrics\"/>\n" " <DC:Date>2000-07-27</DC:Date>\n" " <rdf:Seq>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"00:02.451\">Hello World</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"00:06.882\">Sing along</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"01:03.096\">Make</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"01:09.478\">it</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"01:13.516\">all</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " <rdf:li>\n" " <rdf:Description>\n" " <MM:SyncText ts=\"01:41.744\">clear.</MM:SyncText>\n" " </rdf:Description>\n" " </rdf:li>\n" " </rdf:Seq>\n" " </rdf:Description>\n" " </MM:SyncEvents>\n"; Queries queries[] = { { "GetCDInfoFromCDIndexId", MB_GetCDInfoFromCDIndexID, 1, "CD Index ID", "", "", "" }, { "FindArtist", MB_FindArtistByName, 1, "Artist Name", "", "", "" }, { "FindTrack", MB_FindTrackByName, 3, "Track Name", "Album Name", "Artist Name", "" }, { "FindAlbumsByArtist", MB_FindAlbumsByArtistName, 1, "Artist Name", "", "", "" }, { "FindAlbum", MB_FindAlbumByName, 1, "Album Name", "", "", "" }, { "FindDistinctGUID", MB_FindDistinctGUID, 2, "Track Name", "Artist Name", "", "" }, { "GetArtist", MB_GetArtistById , 1, "Artist ID", "", "", "" }, { "GetAlbum", MB_GetAlbumById , 1, "Album ID", "", "", "" }, { "GetAlbumsByArtist", MB_GetAlbumsByArtistId , 1, "Artist ID", "", "", "" }, { "GetTrack", MB_GetTrackById , 1, "Track ID", "", "", "" }, { "GetTrackGUID", MB_GetTrackByGUID , 1, "Track GUID", "", "", "" }, { "GetSyncText", MB_GetSyncTextById , 1, "Track ID", "", "", "" }, { "GetCDInfo", MB_GetCDInfo , 0, "", "", "", "" }, { "GetCDTOC", MB_GetCDTOC , 0, "", "", "", "" }, { "AssociateCD", MB_AssociateCD , 0, "", "", "", "" }, { "\0", "\0", 0, "", "", "", "" } }; #ifdef WIN32 #define strcasecmp stricmp #endif int main(void) { MusicBrainz o; string error, data; bool ret; Queries *p; char szLine[256], *szCmd, *ptr, szLast[100]; string xml, qarg, query, server; vector<string> args; // Set the server you want to use. Defaults to www.musicbrainz.org:80 //server = string("www.musicbrainz.org"); o.SetServer(server, 80); // Tell the client library to return data in ISO8859-1 and not UTF-8 o.UseUTF8(0); // If you need to use a proxy, uncomment/edit the following line // as appropriate //o.SetProxy("proxy.mydomain.com", 80); for(;;) { query = ""; printf("query> "); fflush(stdout); if (fgets(szLine, 255, stdin) < 0) break; if (strncmp(szLine, "!!", 2) == 0) { printf("%s\n", szLast); strcpy(szLine, szLast); } else strcpy(szLast, szLine); szLine[strlen(szLine) - 1] = 0; szCmd = strtok(szLine, " "); if (szCmd == NULL) continue; args.clear(); for(;;) { ptr = strtok(NULL, " "); if (!ptr) break; if (*ptr == '\"' && !(*(ptr + strlen(ptr) - 1) == '\"')) { qarg = string(ptr + 1); for(;;) { ptr = strtok(NULL, " "); if (!ptr) break; if (*(ptr + strlen(ptr) - 1) == '\"') { *(ptr + strlen(ptr) - 1) = 0; qarg += string(" ") + string(ptr); ptr = (char *)qarg.c_str(); break; } qarg += string(" ") + string(ptr); } if (!ptr) { continue; } } if (*ptr == '\"' && *(ptr + strlen(ptr) - 1) == '\"') { *(ptr + strlen(ptr) - 1) = 0; args.push_back(string(ptr + 1)); } else { if (strcmp(ptr, "\"\"") == 0) *ptr = 0; args.push_back(string(ptr)); } } if (strncmp(szCmd, "bye", 3) == 0 || strncmp(szCmd, "quit", 4) == 0 || strncmp(szCmd, "exit", 4) == 0) { break; } if (strncmp(szCmd, "help", 4) == 0) { printf("Available commands: Arguments:\n\n"); for(p = queries; *p->name; p++) { printf("%-34s ", p->name); if (strlen(p->arg1)) printf("<%s> ", p->arg1); if (strlen(p->arg2)) printf("<%s> ", p->arg2); if (strlen(p->arg3)) printf("<%s> ", p->arg3); if (strlen(p->arg4)) printf("<%s> ", p->arg4); printf("\n"); } printf("exit/quit/bye [quit]\n"); printf("submit [get web submit URL]\n"); printf("info [help on a command]\n"); continue; } if (strncmp(szCmd, "lyrics", 6) == 0) { query = string(SUBMIT_LYRICS_QUERY); } if (strncmp(szCmd, "submit", 6) == 0) { string url; ret = o.GetWebSubmitURL(url); if (ret) printf("URL: %s\n", url.c_str()); else printf("Could not determine web submit url.\n"); continue; } if (strncmp(szCmd, "info", 4) == 0) { for(p = queries; p->name; p++) { if (strcasecmp(szCmd + 5, p->name) == 0) { printf("usage: %s ", p->name); if (strlen(p->arg1)) printf("<%s> ", p->arg1); if (strlen(p->arg2)) printf("<%s> ", p->arg2); if (strlen(p->arg3)) printf("<%s> ", p->arg3); if (strlen(p->arg4)) printf("<%s> ", p->arg4); printf("\n"); break; } } if (p->name == NULL) printf("No info available for %s\n", szCmd + 5); continue; } if (query.length() == 0) { for(p = queries; p->name; p++) { if (strcasecmp(szCmd, p->name) == 0) break; } if (p->name == NULL) { printf("Unknown query.\n"); continue; } query = string(p->value); } ret = o.Query(query, &args); if (!ret) { o.GetQueryError(error); printf("Query failed: %s\n", error.c_str()); continue; } printf("Query ok. Items returned: %d\n", o.GetNumItems()); o.GetResultRDF(xml); printf("Returned RDF object:\n\n%s\n", xml.c_str()); } return 0; } <|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) 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 <gtest/gtest.h> #include "main/mtypes.h" #include "main/macros.h" #include "util/ralloc.h" #include "uniform_initializer_utils.h" #include <stdio.h> void fill_storage_array_with_sentinels(gl_constant_value *storage, unsigned data_size, unsigned red_zone_size) { for (unsigned i = 0; i < data_size; i++) storage[i].u = 0xDEADBEEF; for (unsigned i = 0; i < red_zone_size; i++) storage[data_size + i].u = 0xBADDC0DE; } /** * Verfiy that markers past the end of the real uniform are unmodified */ static ::testing::AssertionResult red_zone_is_intact(gl_constant_value *storage, unsigned data_size, unsigned red_zone_size) { for (unsigned i = 0; i < red_zone_size; i++) { const unsigned idx = data_size + i; if (storage[idx].u != 0xBADDC0DE) return ::testing::AssertionFailure() << "storage[" << idx << "].u = " << storage[idx].u << ", exepected data values = " << data_size << ", red-zone size = " << red_zone_size; } return ::testing::AssertionSuccess(); } static const int values[] = { 2, 0, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53 }; /** * Generate a single data element. * * This is by both \c generate_data and \c generate_array_data to create the * data. */ static void generate_data_element(void *mem_ctx, const glsl_type *type, ir_constant *&val, unsigned data_index_base) { /* Set the initial data values for the generated constant. */ ir_constant_data data; memset(&data, 0, sizeof(data)); for (unsigned i = 0; i < type->components(); i++) { const unsigned idx = (i + data_index_base) % Elements(values); switch (type->base_type) { case GLSL_TYPE_UINT: case GLSL_TYPE_INT: case GLSL_TYPE_SAMPLER: data.i[i] = values[idx]; break; case GLSL_TYPE_FLOAT: data.f[i] = float(values[idx]); break; case GLSL_TYPE_BOOL: data.b[i] = bool(values[idx]); break; case GLSL_TYPE_ATOMIC_UINT: case GLSL_TYPE_STRUCT: case GLSL_TYPE_ARRAY: case GLSL_TYPE_VOID: case GLSL_TYPE_ERROR: case GLSL_TYPE_INTERFACE: ASSERT_TRUE(false); break; } } /* Generate and verify the constant. */ val = new(mem_ctx) ir_constant(type, &data); for (unsigned i = 0; i < type->components(); i++) { switch (type->base_type) { case GLSL_TYPE_UINT: case GLSL_TYPE_INT: case GLSL_TYPE_SAMPLER: ASSERT_EQ(data.i[i], val->value.i[i]); break; case GLSL_TYPE_FLOAT: ASSERT_EQ(data.f[i], val->value.f[i]); break; case GLSL_TYPE_BOOL: ASSERT_EQ(data.b[i], val->value.b[i]); break; case GLSL_TYPE_ATOMIC_UINT: case GLSL_TYPE_STRUCT: case GLSL_TYPE_ARRAY: case GLSL_TYPE_VOID: case GLSL_TYPE_ERROR: case GLSL_TYPE_INTERFACE: ASSERT_TRUE(false); break; } } } void generate_data(void *mem_ctx, enum glsl_base_type base_type, unsigned columns, unsigned rows, ir_constant *&val) { /* Determine what the type of the generated constant should be. */ const glsl_type *const type = glsl_type::get_instance(base_type, rows, columns); ASSERT_FALSE(type->is_error()); generate_data_element(mem_ctx, type, val, 0); } void generate_array_data(void *mem_ctx, enum glsl_base_type base_type, unsigned columns, unsigned rows, unsigned array_size, ir_constant *&val) { /* Determine what the type of the generated constant should be. */ const glsl_type *const element_type = glsl_type::get_instance(base_type, rows, columns); ASSERT_FALSE(element_type->is_error()); const glsl_type *const array_type = glsl_type::get_array_instance(element_type, array_size); ASSERT_FALSE(array_type->is_error()); /* Set the initial data values for the generated constant. */ exec_list values_for_array; for (unsigned i = 0; i < array_size; i++) { ir_constant *element; generate_data_element(mem_ctx, element_type, element, i); values_for_array.push_tail(element); } val = new(mem_ctx) ir_constant(array_type, &values_for_array); } /** * Verify that the data stored for the uniform matches the initializer * * \param storage Backing storage for the uniform * \param storage_array_size Array size of the backing storage. This must be * less than or equal to the array size of the type * of \c val. If \c val is not an array, this must * be zero. * \param val Value of the initializer for the unifrom. * \param red_zone */ void verify_data(gl_constant_value *storage, unsigned storage_array_size, ir_constant *val, unsigned red_zone_size, unsigned int boolean_true) { if (val->type->base_type == GLSL_TYPE_ARRAY) { const glsl_type *const element_type = val->array_elements[0]->type; for (unsigned i = 0; i < storage_array_size; i++) { verify_data(storage + (i * element_type->components()), 0, val->array_elements[i], 0, boolean_true); } const unsigned components = element_type->components(); if (red_zone_size > 0) { EXPECT_TRUE(red_zone_is_intact(storage, storage_array_size * components, red_zone_size)); } } else { ASSERT_EQ(0u, storage_array_size); for (unsigned i = 0; i < val->type->components(); i++) { switch (val->type->base_type) { case GLSL_TYPE_UINT: case GLSL_TYPE_INT: case GLSL_TYPE_SAMPLER: EXPECT_EQ(val->value.i[i], storage[i].i); break; case GLSL_TYPE_FLOAT: EXPECT_EQ(val->value.f[i], storage[i].f); break; case GLSL_TYPE_BOOL: EXPECT_EQ(val->value.b[i] ? boolean_true : 0, storage[i].i); break; case GLSL_TYPE_ATOMIC_UINT: case GLSL_TYPE_STRUCT: case GLSL_TYPE_ARRAY: case GLSL_TYPE_VOID: case GLSL_TYPE_ERROR: case GLSL_TYPE_INTERFACE: ASSERT_TRUE(false); break; } } if (red_zone_size > 0) { EXPECT_TRUE(red_zone_is_intact(storage, val->type->components(), red_zone_size)); } } } <commit_msg>glsl/tests: add IMAGE type.<commit_after>/* * Copyright © 2012 Intel Corporation * * 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 (including the next * paragraph) 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 <gtest/gtest.h> #include "main/mtypes.h" #include "main/macros.h" #include "util/ralloc.h" #include "uniform_initializer_utils.h" #include <stdio.h> void fill_storage_array_with_sentinels(gl_constant_value *storage, unsigned data_size, unsigned red_zone_size) { for (unsigned i = 0; i < data_size; i++) storage[i].u = 0xDEADBEEF; for (unsigned i = 0; i < red_zone_size; i++) storage[data_size + i].u = 0xBADDC0DE; } /** * Verfiy that markers past the end of the real uniform are unmodified */ static ::testing::AssertionResult red_zone_is_intact(gl_constant_value *storage, unsigned data_size, unsigned red_zone_size) { for (unsigned i = 0; i < red_zone_size; i++) { const unsigned idx = data_size + i; if (storage[idx].u != 0xBADDC0DE) return ::testing::AssertionFailure() << "storage[" << idx << "].u = " << storage[idx].u << ", exepected data values = " << data_size << ", red-zone size = " << red_zone_size; } return ::testing::AssertionSuccess(); } static const int values[] = { 2, 0, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53 }; /** * Generate a single data element. * * This is by both \c generate_data and \c generate_array_data to create the * data. */ static void generate_data_element(void *mem_ctx, const glsl_type *type, ir_constant *&val, unsigned data_index_base) { /* Set the initial data values for the generated constant. */ ir_constant_data data; memset(&data, 0, sizeof(data)); for (unsigned i = 0; i < type->components(); i++) { const unsigned idx = (i + data_index_base) % Elements(values); switch (type->base_type) { case GLSL_TYPE_UINT: case GLSL_TYPE_INT: case GLSL_TYPE_SAMPLER: case GLSL_TYPE_IMAGE: data.i[i] = values[idx]; break; case GLSL_TYPE_FLOAT: data.f[i] = float(values[idx]); break; case GLSL_TYPE_BOOL: data.b[i] = bool(values[idx]); break; case GLSL_TYPE_ATOMIC_UINT: case GLSL_TYPE_STRUCT: case GLSL_TYPE_ARRAY: case GLSL_TYPE_VOID: case GLSL_TYPE_ERROR: case GLSL_TYPE_INTERFACE: ASSERT_TRUE(false); break; } } /* Generate and verify the constant. */ val = new(mem_ctx) ir_constant(type, &data); for (unsigned i = 0; i < type->components(); i++) { switch (type->base_type) { case GLSL_TYPE_UINT: case GLSL_TYPE_INT: case GLSL_TYPE_SAMPLER: case GLSL_TYPE_IMAGE: ASSERT_EQ(data.i[i], val->value.i[i]); break; case GLSL_TYPE_FLOAT: ASSERT_EQ(data.f[i], val->value.f[i]); break; case GLSL_TYPE_BOOL: ASSERT_EQ(data.b[i], val->value.b[i]); break; case GLSL_TYPE_ATOMIC_UINT: case GLSL_TYPE_STRUCT: case GLSL_TYPE_ARRAY: case GLSL_TYPE_VOID: case GLSL_TYPE_ERROR: case GLSL_TYPE_INTERFACE: ASSERT_TRUE(false); break; } } } void generate_data(void *mem_ctx, enum glsl_base_type base_type, unsigned columns, unsigned rows, ir_constant *&val) { /* Determine what the type of the generated constant should be. */ const glsl_type *const type = glsl_type::get_instance(base_type, rows, columns); ASSERT_FALSE(type->is_error()); generate_data_element(mem_ctx, type, val, 0); } void generate_array_data(void *mem_ctx, enum glsl_base_type base_type, unsigned columns, unsigned rows, unsigned array_size, ir_constant *&val) { /* Determine what the type of the generated constant should be. */ const glsl_type *const element_type = glsl_type::get_instance(base_type, rows, columns); ASSERT_FALSE(element_type->is_error()); const glsl_type *const array_type = glsl_type::get_array_instance(element_type, array_size); ASSERT_FALSE(array_type->is_error()); /* Set the initial data values for the generated constant. */ exec_list values_for_array; for (unsigned i = 0; i < array_size; i++) { ir_constant *element; generate_data_element(mem_ctx, element_type, element, i); values_for_array.push_tail(element); } val = new(mem_ctx) ir_constant(array_type, &values_for_array); } /** * Verify that the data stored for the uniform matches the initializer * * \param storage Backing storage for the uniform * \param storage_array_size Array size of the backing storage. This must be * less than or equal to the array size of the type * of \c val. If \c val is not an array, this must * be zero. * \param val Value of the initializer for the unifrom. * \param red_zone */ void verify_data(gl_constant_value *storage, unsigned storage_array_size, ir_constant *val, unsigned red_zone_size, unsigned int boolean_true) { if (val->type->base_type == GLSL_TYPE_ARRAY) { const glsl_type *const element_type = val->array_elements[0]->type; for (unsigned i = 0; i < storage_array_size; i++) { verify_data(storage + (i * element_type->components()), 0, val->array_elements[i], 0, boolean_true); } const unsigned components = element_type->components(); if (red_zone_size > 0) { EXPECT_TRUE(red_zone_is_intact(storage, storage_array_size * components, red_zone_size)); } } else { ASSERT_EQ(0u, storage_array_size); for (unsigned i = 0; i < val->type->components(); i++) { switch (val->type->base_type) { case GLSL_TYPE_UINT: case GLSL_TYPE_INT: case GLSL_TYPE_SAMPLER: case GLSL_TYPE_IMAGE: EXPECT_EQ(val->value.i[i], storage[i].i); break; case GLSL_TYPE_FLOAT: EXPECT_EQ(val->value.f[i], storage[i].f); break; case GLSL_TYPE_BOOL: EXPECT_EQ(val->value.b[i] ? boolean_true : 0, storage[i].i); break; case GLSL_TYPE_ATOMIC_UINT: case GLSL_TYPE_STRUCT: case GLSL_TYPE_ARRAY: case GLSL_TYPE_VOID: case GLSL_TYPE_ERROR: case GLSL_TYPE_INTERFACE: ASSERT_TRUE(false); break; } } if (red_zone_size > 0) { EXPECT_TRUE(red_zone_is_intact(storage, val->type->components(), red_zone_size)); } } } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, 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. * */ #include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/filters/approximate_voxel_grid.h> #include <pcl/filters/voxel_grid.h> #include <pcl/console/parse.h> #include <pcl/common/time.h> #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ double now = pcl::getTime (); \ ++count; \ if (now - last >= 1.0) \ { \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) template <typename PointType> class OpenNIVoxelGrid { public: typedef pcl::PointCloud<PointType> Cloud; typedef typename Cloud::Ptr CloudPtr; typedef typename Cloud::ConstPtr CloudConstPtr; OpenNIVoxelGrid (const std::string& device_id = "", const std::string& field_name = "z", float min_v = 0, float max_v = 5.0, float leaf_size_x = 0.01, float leaf_size_y = 0.01, float leaf_size_z = 0.01) : viewer ("PCL OpenNI VoxelGrid Viewer") , device_id_(device_id) { grid_.setLeafSize (leaf_size_x, leaf_size_y, leaf_size_z); grid_.setFilterFieldName (field_name); grid_.setFilterLimits (min_v, max_v); } void cloud_cb_ (const CloudConstPtr& cloud) { set (cloud); } void set (const CloudConstPtr& cloud) { //lock while we set our cloud; boost::mutex::scoped_lock lock (mtx_); cloud_ = cloud; } CloudPtr get () { //lock while we swap our cloud and reset it. boost::mutex::scoped_lock lock (mtx_); CloudPtr temp_cloud (new Cloud); grid_.setInputCloud (cloud_); grid_.filter (*temp_cloud); return (temp_cloud); } void run () { pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_); boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIVoxelGrid::cloud_cb_, this, _1); boost::signals2::connection c = interface->registerCallback (f); interface->start (); while (!viewer.wasStopped ()) { if (cloud_) { FPS_CALC ("drawing"); //the call to get() sets the cloud_ to null; viewer.showCloud (get ()); } } interface->stop (); } pcl::ApproximateVoxelGrid<PointType> grid_; pcl::visualization::CloudViewer viewer; std::string device_id_; boost::mutex mtx_; CloudConstPtr cloud_; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n" << "where options are:\n -minmax min-max :: set the ApproximateVoxelGrid min-max cutting values (default: 0-5.0)\n" << " -field X :: use field/dimension 'X' to filter data on (default: 'z')\n" << " -leaf x, y, z :: set the ApproximateVoxelGrid leaf size (default: 0.01)\n"; openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl << " bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl << " <serial-number> (only in Linux and for devices which provide serial numbers)" << endl; } } else cout << "No devices connected." << endl; } int main (int argc, char ** argv) { if (pcl::console::find_argument (argc, argv, "-h") != -1) usage (argv); double min_v = 0, max_v = 5.0; pcl::console::parse_2x_arguments (argc, argv, "-minmax", min_v, max_v, false); std::string field_name ("z"); pcl::console::parse_argument (argc, argv, "-field", field_name); PCL_INFO ("Filtering data on %s between %f -> %f.\n", field_name.c_str (), min_v, max_v); double leaf_x = 0.01, leaf_y = 0.01, leaf_z = 0.01; pcl::console::parse_3x_arguments (argc, argv, "-leaf", leaf_x, leaf_y, leaf_z, false); PCL_INFO ("Using %f, %f, %f as a leaf size for VoxelGrid.\n", leaf_x, leaf_y, leaf_z); pcl::OpenNIGrabber grabber (""); if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ()) { OpenNIVoxelGrid<pcl::PointXYZRGB> v ("", field_name, min_v, max_v, leaf_x, leaf_y, leaf_z); v.run (); } else { OpenNIVoxelGrid<pcl::PointXYZ> v ("", field_name, min_v, max_v, leaf_x, leaf_y, leaf_z); v.run (); } return (0); } <commit_msg>fixed a compiler error<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, 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. * */ #include <boost/thread/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/io/openni_camera/openni_driver.h> #include <pcl/filters/approximate_voxel_grid.h> #include <pcl/filters/voxel_grid.h> #include <pcl/console/parse.h> #include <pcl/common/time.h> #define FPS_CALC(_WHAT_) \ do \ { \ static unsigned count = 0;\ static double last = pcl::getTime ();\ double now = pcl::getTime (); \ ++count; \ if (now - last >= 1.0) \ { \ std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \ count = 0; \ last = now; \ } \ }while(false) template <typename PointType> class OpenNIVoxelGrid { public: typedef pcl::PointCloud<PointType> Cloud; typedef typename Cloud::Ptr CloudPtr; typedef typename Cloud::ConstPtr CloudConstPtr; OpenNIVoxelGrid (const std::string& device_id = "", const std::string& field_name = "z", float min_v = 0, float max_v = 5.0, float leaf_size_x = 0.01, float leaf_size_y = 0.01, float leaf_size_z = 0.01) : viewer ("PCL OpenNI VoxelGrid Viewer") , device_id_(device_id) { grid_.setLeafSize (leaf_size_x, leaf_size_y, leaf_size_z); //grid_.setFilterFieldName (field_name); //grid_.setFilterLimits (min_v, max_v); } void cloud_cb_ (const CloudConstPtr& cloud) { set (cloud); } void set (const CloudConstPtr& cloud) { //lock while we set our cloud; boost::mutex::scoped_lock lock (mtx_); cloud_ = cloud; } CloudPtr get () { //lock while we swap our cloud and reset it. boost::mutex::scoped_lock lock (mtx_); CloudPtr temp_cloud (new Cloud); grid_.setInputCloud (cloud_); grid_.filter (*temp_cloud); return (temp_cloud); } void run () { pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_); boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIVoxelGrid::cloud_cb_, this, _1); boost::signals2::connection c = interface->registerCallback (f); interface->start (); while (!viewer.wasStopped ()) { if (cloud_) { FPS_CALC ("drawing"); //the call to get() sets the cloud_ to null; viewer.showCloud (get ()); } } interface->stop (); } pcl::ApproximateVoxelGrid<PointType> grid_; pcl::visualization::CloudViewer viewer; std::string device_id_; boost::mutex mtx_; CloudConstPtr cloud_; }; void usage (char ** argv) { std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n" << "where options are:\n -minmax min-max :: set the ApproximateVoxelGrid min-max cutting values (default: 0-5.0)\n" << " -field X :: use field/dimension 'X' to filter data on (default: 'z')\n" << " -leaf x, y, z :: set the ApproximateVoxelGrid leaf size (default: 0.01)\n"; openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance (); if (driver.getNumberDevices () > 0) { for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx) { cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx) << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl; cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl << " bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl << " <serial-number> (only in Linux and for devices which provide serial numbers)" << endl; } } else cout << "No devices connected." << endl; } int main (int argc, char ** argv) { if (pcl::console::find_argument (argc, argv, "-h") != -1) usage (argv); double min_v = 0, max_v = 5.0; pcl::console::parse_2x_arguments (argc, argv, "-minmax", min_v, max_v, false); std::string field_name ("z"); pcl::console::parse_argument (argc, argv, "-field", field_name); PCL_INFO ("Filtering data on %s between %f -> %f.\n", field_name.c_str (), min_v, max_v); double leaf_x = 0.01, leaf_y = 0.01, leaf_z = 0.01; pcl::console::parse_3x_arguments (argc, argv, "-leaf", leaf_x, leaf_y, leaf_z, false); PCL_INFO ("Using %f, %f, %f as a leaf size for VoxelGrid.\n", leaf_x, leaf_y, leaf_z); pcl::OpenNIGrabber grabber (""); if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ()) { OpenNIVoxelGrid<pcl::PointXYZRGB> v ("", field_name, min_v, max_v, leaf_x, leaf_y, leaf_z); v.run (); } else { OpenNIVoxelGrid<pcl::PointXYZ> v ("", field_name, min_v, max_v, leaf_x, leaf_y, leaf_z); v.run (); } return (0); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: durationhdl.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2008-03-12 10:51:02 $ * * 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_xmloff.hxx" #ifndef _XMLOFF_PROPERTYHANDLER_DURATIONS_HXX #include "durationhdl.hxx" #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_ #include <com/sun/star/util/DateTime.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; // --------------------------------------------------------------------------- sal_Bool XMLDurationMS16PropHdl_Impl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& ) const { DateTime aTime; if( !SvXMLUnitConverter::convertTime( aTime, rStrImpValue ) ) return false; const sal_Int16 nMS = ( ( aTime.Hours * 60 + aTime.Minutes ) * 60 + aTime.Seconds ) * 100 + aTime.HundredthSeconds; rValue <<= nMS; return sal_True; } sal_Bool XMLDurationMS16PropHdl_Impl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& ) const { sal_Int16 nMS = sal_Int16(); if(rValue >>= nMS) { OUStringBuffer aOut; DateTime aTime( nMS, 0, 0, 0, 0, 0, 0 ); SvXMLUnitConverter::convertTime( aOut, aTime ); rStrExpValue = aOut.makeStringAndClear(); return sal_True; } return sal_False; } XMLDurationMS16PropHdl_Impl::~XMLDurationMS16PropHdl_Impl() { } <commit_msg>INTEGRATION: CWS changefileheader (1.7.18); FILE MERGED 2008/04/01 16:09:55 thb 1.7.18.3: #i85898# Stripping all external header guards 2008/04/01 13:05:02 thb 1.7.18.2: #i85898# Stripping all external header guards 2008/03/31 16:28:22 rt 1.7.18.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: durationhdl.cxx,v $ * $Revision: 1.8 $ * * 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_xmloff.hxx" #include "durationhdl.hxx" #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/util/DateTime.hpp> #include <rtl/ustrbuf.hxx> #include <xmloff/xmluconv.hxx> using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::util; // --------------------------------------------------------------------------- sal_Bool XMLDurationMS16PropHdl_Impl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& ) const { DateTime aTime; if( !SvXMLUnitConverter::convertTime( aTime, rStrImpValue ) ) return false; const sal_Int16 nMS = ( ( aTime.Hours * 60 + aTime.Minutes ) * 60 + aTime.Seconds ) * 100 + aTime.HundredthSeconds; rValue <<= nMS; return sal_True; } sal_Bool XMLDurationMS16PropHdl_Impl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& ) const { sal_Int16 nMS = sal_Int16(); if(rValue >>= nMS) { OUStringBuffer aOut; DateTime aTime( nMS, 0, 0, 0, 0, 0, 0 ); SvXMLUnitConverter::convertTime( aOut, aTime ); rStrExpValue = aOut.makeStringAndClear(); return sal_True; } return sal_False; } XMLDurationMS16PropHdl_Impl::~XMLDurationMS16PropHdl_Impl() { } <|endoftext|>
<commit_before>#include "sipfieldparsing.h" #include "sipconversions.h" #include <QRegularExpression> #include <QDebug> // TODO: Support SIPS uri scheme. Needed for TLS bool parseURI(QString values, SIP_URI& uri); bool parseParameterNameToValue(std::shared_ptr<QList<SIPParameter>> parameters, QString name, QString& value); bool parseUint(QString values, uint& number); bool parseURI(QString values, SIP_URI& uri) { // RFC3261_TODO: Try to understand other than sip: addresses such as "tel:" and give error? // TLS TODO: Support sips QRegularExpression re_field("(\\w+ )?<sip:(\\w+)@([\\w\.:]+)>"); QRegularExpressionMatch field_match = re_field.match(values); if(field_match.hasMatch() && (field_match.lastCapturedIndex() == 4 || field_match.lastCapturedIndex() == 3)) { uri.realname = field_match.captured(1); uri.username = field_match.captured(2); uri.host = field_match.captured(3); return true; } return false; } bool parseParameterNameToValue(std::shared_ptr<QList<SIPParameter>> parameters, QString name, QString& value) { if(parameters != nullptr) { for(SIPParameter parameter : *parameters) { if(parameter.name == name) { value = parameter.value; return true; } } } return false; } bool parseUint(QString values, uint& number) { QRegularExpression re_field("(\\d+)"); QRegularExpressionMatch field_match = re_field.match(values); if(field_match.hasMatch() && field_match.lastCapturedIndex() == 1) { number = values.toUInt(); return true; } return false; } bool parseToField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); Q_ASSERT(message->dialog); if(!parseURI(field.values, message->to)) { return false; } parseParameterNameToValue(field.parameters, "tag", message->dialog->toTag); return true; } bool parseFromField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); Q_ASSERT(message->dialog); if(!parseURI(field.values, message->from)) { return false; } parseParameterNameToValue(field.parameters, "tag", message->dialog->fromTag); return true; } bool parseCSeqField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); QRegularExpression re_field("(\\d+) (\\w+)"); QRegularExpressionMatch field_match = re_field.match(field.values); if(field_match.hasMatch() && field_match.lastCapturedIndex() == 2) { message->cSeq = field_match.captured(1).toUInt(); message->transactionRequest = stringToRequest(field_match.captured(2)); return true; } return false; } bool parseCallIDField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); Q_ASSERT(message->dialog); QRegularExpression re_field("(\\S+)"); QRegularExpressionMatch field_match = re_field.match(field.values); if(field_match.hasMatch() && field_match.lastCapturedIndex() == 1) { message->dialog->callID = field.values; return true; } return false; } bool parseViaField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); QRegularExpression re_field("SIP\/(\\d\.\\d)\/(\\w+) ([\\w\.:]+)"); QRegularExpressionMatch field_match = re_field.match(field.values); if(!field_match.hasMatch() || field_match.lastCapturedIndex() < 3) { return false; } else if(field_match.lastCapturedIndex() == 3) { ViaInfo via = {stringToConnection(field_match.captured(2)), field_match.captured(1), field_match.captured(3), ""}; parseParameterNameToValue(field.parameters, "branch", via.branch); message->senderReplyAddress.push_back(via); } else { return false; } return true; } bool parseMaxForwardsField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); return parseUint(field.values, message->maxForwards); } bool parseContactField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); return parseURI(field.values, message->contact); } bool parseContentTypeField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); QRegularExpression re_field("(\\w+/\\w+)"); QRegularExpressionMatch field_match = re_field.match(field.values); if(field_match.hasMatch() && field_match.lastCapturedIndex() == 1) { message->content.type = stringToContentType(field_match.captured(1)); return true; } return false; } bool parseContentLengthField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); return parseUint(field.values, message->content.length); } bool parseServerField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); message->server = field.values; return true; } bool isLinePresent(QString name, QList<SIPField>& fields) { for(SIPField field : fields) { if(field.name == name) { return true; } } qDebug() << "Did not find header:" << name; return false; } bool parseParameter(QString text, SIPParameter& parameter) { QRegularExpression re_parameter("([^=]+)=([^;]+)"); QRegularExpressionMatch parameter_match = re_parameter.match(text); if(parameter_match.hasMatch() && parameter_match.lastCapturedIndex() == 2) { parameter.name = parameter_match.captured(1); parameter.value = parameter_match.captured(2); return true; } return false; } <commit_msg>feature(Transport): Parse connection type from URI.<commit_after>#include "sipfieldparsing.h" #include "sipconversions.h" #include <QRegularExpression> #include <QDebug> // TODO: Support SIPS uri scheme. Needed for TLS bool parseURI(QString values, SIP_URI& uri); ConnectionType parseUritype(QString type); bool parseParameterNameToValue(std::shared_ptr<QList<SIPParameter>> parameters, QString name, QString& value); bool parseUint(QString values, uint& number); bool parseURI(QString values, SIP_URI& uri) { // TODO: parse quotation marks in real name QRegularExpression re_field("(\\w+ )?<(\\w+):(\\w+)@([\\w\.:]+)>"); QRegularExpressionMatch field_match = re_field.match(values); // number of matches depends whether real name was given if (field_match.hasMatch()) { if (field_match.lastCapturedIndex() == 4) { uri.realname = field_match.captured(1); uri.connection = parseUritype(field_match.captured(2)); uri.username = field_match.captured(3); uri.host = field_match.captured(4); } else if(field_match.lastCapturedIndex() == 3) { uri.connection = parseUritype(field_match.captured(1)); uri.username = field_match.captured(2); uri.host = field_match.captured(3); } return uri.connection != ANY; } return false; } ConnectionType parseUritype(QString type) { if (type == "sip") { return TCP; } else if (type == "sips") { return TLS; } else if (type == "tel") { return TEL; } else { qDebug() << "ERROR: Could not identify connection type:" << type; } return ANY; } bool parseParameterNameToValue(std::shared_ptr<QList<SIPParameter>> parameters, QString name, QString& value) { if(parameters != nullptr) { for(SIPParameter parameter : *parameters) { if(parameter.name == name) { value = parameter.value; return true; } } } return false; } bool parseUint(QString values, uint& number) { QRegularExpression re_field("(\\d+)"); QRegularExpressionMatch field_match = re_field.match(values); if(field_match.hasMatch() && field_match.lastCapturedIndex() == 1) { number = values.toUInt(); return true; } return false; } bool parseToField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); Q_ASSERT(message->dialog); if(!parseURI(field.values, message->to)) { return false; } parseParameterNameToValue(field.parameters, "tag", message->dialog->toTag); return true; } bool parseFromField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); Q_ASSERT(message->dialog); if(!parseURI(field.values, message->from)) { return false; } parseParameterNameToValue(field.parameters, "tag", message->dialog->fromTag); return true; } bool parseCSeqField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); QRegularExpression re_field("(\\d+) (\\w+)"); QRegularExpressionMatch field_match = re_field.match(field.values); if(field_match.hasMatch() && field_match.lastCapturedIndex() == 2) { message->cSeq = field_match.captured(1).toUInt(); message->transactionRequest = stringToRequest(field_match.captured(2)); return true; } return false; } bool parseCallIDField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); Q_ASSERT(message->dialog); QRegularExpression re_field("(\\S+)"); QRegularExpressionMatch field_match = re_field.match(field.values); if(field_match.hasMatch() && field_match.lastCapturedIndex() == 1) { message->dialog->callID = field.values; return true; } return false; } bool parseViaField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); QRegularExpression re_field("SIP\/(\\d\.\\d)\/(\\w+) ([\\w\.:]+)"); QRegularExpressionMatch field_match = re_field.match(field.values); if(!field_match.hasMatch() || field_match.lastCapturedIndex() < 3) { return false; } else if(field_match.lastCapturedIndex() == 3) { ViaInfo via = {stringToConnection(field_match.captured(2)), field_match.captured(1), field_match.captured(3), ""}; parseParameterNameToValue(field.parameters, "branch", via.branch); message->senderReplyAddress.push_back(via); } else { return false; } return true; } bool parseMaxForwardsField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); return parseUint(field.values, message->maxForwards); } bool parseContactField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); return parseURI(field.values, message->contact); } bool parseContentTypeField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); QRegularExpression re_field("(\\w+/\\w+)"); QRegularExpressionMatch field_match = re_field.match(field.values); if(field_match.hasMatch() && field_match.lastCapturedIndex() == 1) { message->content.type = stringToContentType(field_match.captured(1)); return true; } return false; } bool parseContentLengthField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); return parseUint(field.values, message->content.length); } bool parseServerField(SIPField& field, std::shared_ptr<SIPMessageInfo> message) { Q_ASSERT(message); message->server = field.values; return true; } bool isLinePresent(QString name, QList<SIPField>& fields) { for(SIPField field : fields) { if(field.name == name) { return true; } } qDebug() << "Did not find header:" << name; return false; } bool parseParameter(QString text, SIPParameter& parameter) { QRegularExpression re_parameter("([^=]+)=([^;]+)"); QRegularExpressionMatch parameter_match = re_parameter.match(text); if(parameter_match.hasMatch() && parameter_match.lastCapturedIndex() == 2) { parameter.name = parameter_match.captured(1); parameter.value = parameter_match.captured(2); return true; } return false; } <|endoftext|>
<commit_before>#include "iteration/group/group_solve_iteration.h" namespace bart { namespace iteration { namespace group { template <int dim> GroupSolveIteration<dim>::GroupSolveIteration( std::unique_ptr<GroupSolver> group_solver_ptr, std::unique_ptr<ConvergenceChecker> convergence_checker_ptr, std::unique_ptr<MomentCalculator> moment_calculator_ptr, const std::shared_ptr<GroupSolution> &group_solution_ptr, const std::shared_ptr<SourceUpdater> &source_updater_ptr, const std::shared_ptr<Reporter> &reporter_ptr) : group_solver_ptr_(std::move(group_solver_ptr)), convergence_checker_ptr_(std::move(convergence_checker_ptr)), moment_calculator_ptr_(std::move(moment_calculator_ptr)), group_solution_ptr_(group_solution_ptr), source_updater_ptr_(source_updater_ptr), reporter_ptr_(reporter_ptr) {} template<int dim> void GroupSolveIteration<dim>::Iterate(system::System &system) { const int total_groups = system.current_moments->total_groups(); const int total_angles = group_solution_ptr_->total_angles(); system::moments::MomentVector current_scalar_flux, previous_scalar_flux; if (reporter_ptr_ != nullptr) reporter_ptr_->Report("..Inner iterations"); for (int group = 0; group < total_groups; ++group) { if (reporter_ptr_ != nullptr) { std::string report{"....Group: "}; report += std::to_string(group); reporter_ptr_->Report(report); } convergence::Status convergence_status; convergence_checker_ptr_->Reset(); do { previous_scalar_flux = current_scalar_flux; SolveGroup(group, system); current_scalar_flux = GetScalarFlux(group, system); if (convergence_status.iteration_number == 0) { previous_scalar_flux = current_scalar_flux; previous_scalar_flux = 0; } convergence_status = CheckConvergence(current_scalar_flux, previous_scalar_flux); if (reporter_ptr_ != nullptr) reporter_ptr_->Report(convergence_status); if (!convergence_status.is_complete) { for (int angle = 0; angle < total_angles; ++angle) UpdateSystem(system, group, angle); } } while (!convergence_status.is_complete); UpdateCurrentMoments(system, group); } } template <int dim> void GroupSolveIteration<dim>::SolveGroup(int group, system::System &system) { group_solver_ptr_->SolveGroup(group, system, *group_solution_ptr_); } template <int dim> system::moments::MomentVector GroupSolveIteration<dim>::GetScalarFlux( const int group, system::System &) { return moment_calculator_ptr_->CalculateMoment(group_solution_ptr_.get(), group, 0, 0); } template <int dim> convergence::Status GroupSolveIteration<dim>::CheckConvergence( system::moments::MomentVector &current_iteration, system::moments::MomentVector &previous_iteration) { return convergence_checker_ptr_->CheckFinalConvergence(current_iteration, previous_iteration); } template <int dim> void GroupSolveIteration<dim>::UpdateCurrentMoments(system::System &system, const int group) { auto& current_moments = *system.current_moments; const int max_harmonic_l = current_moments.max_harmonic_l(); for (int l = 0; l <= max_harmonic_l; ++l) { for (int m = -l; m <= l; ++m) { current_moments[{group, l, m}] = moment_calculator_ptr_->CalculateMoment( group_solution_ptr_.get(), group, l, m); } } } template class GroupSolveIteration<1>; template class GroupSolveIteration<2>; template class GroupSolveIteration<3>; } // namespace group } // namespace iteration } // namespace bart <commit_msg>edited reported text by GroupSolveIteration<commit_after>#include "iteration/group/group_solve_iteration.h" namespace bart { namespace iteration { namespace group { template <int dim> GroupSolveIteration<dim>::GroupSolveIteration( std::unique_ptr<GroupSolver> group_solver_ptr, std::unique_ptr<ConvergenceChecker> convergence_checker_ptr, std::unique_ptr<MomentCalculator> moment_calculator_ptr, const std::shared_ptr<GroupSolution> &group_solution_ptr, const std::shared_ptr<SourceUpdater> &source_updater_ptr, const std::shared_ptr<Reporter> &reporter_ptr) : group_solver_ptr_(std::move(group_solver_ptr)), convergence_checker_ptr_(std::move(convergence_checker_ptr)), moment_calculator_ptr_(std::move(moment_calculator_ptr)), group_solution_ptr_(group_solution_ptr), source_updater_ptr_(source_updater_ptr), reporter_ptr_(reporter_ptr) {} template<int dim> void GroupSolveIteration<dim>::Iterate(system::System &system) { const int total_groups = system.current_moments->total_groups(); const int total_angles = group_solution_ptr_->total_angles(); system::moments::MomentVector current_scalar_flux, previous_scalar_flux; if (reporter_ptr_ != nullptr) reporter_ptr_->Report("..Inner group iteration\n"); for (int group = 0; group < total_groups; ++group) { if (reporter_ptr_ != nullptr) { std::string report{"....Group: "}; report += std::to_string(group); report += "\n"; reporter_ptr_->Report(report); } convergence::Status convergence_status; convergence_checker_ptr_->Reset(); do { previous_scalar_flux = current_scalar_flux; SolveGroup(group, system); current_scalar_flux = GetScalarFlux(group, system); if (convergence_status.iteration_number == 0) { previous_scalar_flux = current_scalar_flux; previous_scalar_flux = 0; } convergence_status = CheckConvergence(current_scalar_flux, previous_scalar_flux); if (reporter_ptr_ != nullptr) reporter_ptr_->Report(convergence_status); if (!convergence_status.is_complete) { for (int angle = 0; angle < total_angles; ++angle) UpdateSystem(system, group, angle); } } while (!convergence_status.is_complete); UpdateCurrentMoments(system, group); } } template <int dim> void GroupSolveIteration<dim>::SolveGroup(int group, system::System &system) { group_solver_ptr_->SolveGroup(group, system, *group_solution_ptr_); } template <int dim> system::moments::MomentVector GroupSolveIteration<dim>::GetScalarFlux( const int group, system::System &) { return moment_calculator_ptr_->CalculateMoment(group_solution_ptr_.get(), group, 0, 0); } template <int dim> convergence::Status GroupSolveIteration<dim>::CheckConvergence( system::moments::MomentVector &current_iteration, system::moments::MomentVector &previous_iteration) { return convergence_checker_ptr_->CheckFinalConvergence(current_iteration, previous_iteration); } template <int dim> void GroupSolveIteration<dim>::UpdateCurrentMoments(system::System &system, const int group) { auto& current_moments = *system.current_moments; const int max_harmonic_l = current_moments.max_harmonic_l(); for (int l = 0; l <= max_harmonic_l; ++l) { for (int m = -l; m <= l; ++m) { current_moments[{group, l, m}] = moment_calculator_ptr_->CalculateMoment( group_solution_ptr_.get(), group, l, m); } } } template class GroupSolveIteration<1>; template class GroupSolveIteration<2>; template class GroupSolveIteration<3>; } // namespace group } // namespace iteration } // namespace bart <|endoftext|>
<commit_before>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen * * 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 "audio_oboe.hpp" #include "dsp/dsp.hpp" #include "util.hpp" #include <cmath> #include <vector> #include <algorithm> #include <oboe/Oboe.h> namespace Granite { namespace Audio { void set_oboe_low_latency_parameters(unsigned sample_rate, unsigned block_frames) { // For OpenSL ES fallback path. oboe::DefaultStreamValues::SampleRate = sample_rate; oboe::DefaultStreamValues::FramesPerBurst = block_frames; } struct OboeBackend : Backend, oboe::AudioStreamCallback { OboeBackend(BackendCallback &callback) : Backend(callback) { } ~OboeBackend(); bool init(float target_sample_rate, unsigned channels); const char *get_backend_name() override { return "Oboe"; } float get_sample_rate() override { return sample_rate; } unsigned get_num_channels() override { return num_channels; } bool start() override; bool stop() override; void heartbeat() override; oboe::AudioStream *stream = nullptr; std::vector<float> mix_buffers[Backend::MaxAudioChannels]; float *mix_buffers_ptr[Backend::MaxAudioChannels] = {}; oboe::AudioFormat format = oboe::AudioFormat::Unspecified; float sample_rate = 0.0f; double inv_sample_rate = 0.0; unsigned num_channels = 0; int64_t frame_count = 0; int32_t frames_per_callback = 0; int32_t old_underrun_count = 0; bool is_active = false; double last_latency = 0.0; oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboe_stream, void *audio_data, int32_t num_frames) override; }; OboeBackend::~OboeBackend() { stop(); if (stream) stream->close(); stream = nullptr; } bool OboeBackend::init(float, unsigned channels) { oboe::AudioStreamBuilder builder; builder.setDirection(oboe::Direction::Output); builder.setPerformanceMode(oboe::PerformanceMode::LowLatency); builder.setCallback(this); builder.setAudioApi(oboe::AudioApi::OpenSLES); builder.setChannelCount(channels); builder.setContentType(oboe::ContentType::Music); builder.setSharingMode(oboe::SharingMode::Shared); builder.setUsage(oboe::Usage::Game); if (builder.openStream(&stream) != oboe::Result::OK) { LOGE("Failed to create Oboe stream!\n"); return false; } sample_rate = stream->getSampleRate(); inv_sample_rate = 1.0 / sample_rate; num_channels = unsigned(stream->getChannelCount()); format = stream->getFormat(); frames_per_callback = stream->getFramesPerCallback(); if (frames_per_callback == oboe::kUnspecified) frames_per_callback = stream->getFramesPerBurst(); // Allocate mix-buffers. // If we have to generate more than this in a callback, iterate multiple times ... for (unsigned c = 0; c < num_channels; c++) { mix_buffers[c].resize(frames_per_callback); mix_buffers_ptr[c] = mix_buffers[c].data(); } callback.set_backend_parameters(sample_rate, num_channels, size_t(frames_per_callback)); // Set initial latency estimate. last_latency = double(stream->getBufferSizeInFrames()) * inv_sample_rate; callback.set_latency_usec(uint32_t(last_latency * 1e6)); return true; } oboe::DataCallbackResult OboeBackend::onAudioReady( oboe::AudioStream *oboe_stream, void *audio_data, int32_t num_frames) { auto xrun_count = oboe_stream->getXRunCount(); if (xrun_count.error() == oboe::Result::OK) { int32_t underrun_count = xrun_count.value(); if (underrun_count > old_underrun_count) { LOGW("Oboe: observed %d new underruns.", underrun_count - old_underrun_count); old_underrun_count = underrun_count; } } // Update measured latency. // Can fail spuriously, don't update latency estimate in that case. int64_t frame_position, time_ns; if (oboe_stream->getTimestamp(CLOCK_MONOTONIC, &frame_position, &time_ns) == oboe::Result::OK) { timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { int64_t current_ns = ts.tv_sec * 1000000000 + ts.tv_nsec; // Extrapolate play counter based on timestamp. double playing_time = double(frame_position) * inv_sample_rate; playing_time += 1e-9 * double(current_ns - time_ns); double pushed_time = double(frame_count) * inv_sample_rate; double latency = pushed_time - playing_time; if (latency < 0.0) latency = 0.0; // Interpolate latency over time for a smoother result. last_latency = 0.95 * last_latency + 0.05 * latency; callback.set_latency_usec(uint32_t(last_latency * 1e6)); //LOGI("Measured latency: %.3f ms\n", last_latency * 1000.0); } } frame_count += num_frames; union { int16_t *i16; float *f32; void *data; } u; u.data = audio_data; // Ideally we'll only run this once, but you never know ... while (num_frames) { auto to_render = std::min(num_frames, frames_per_callback); callback.mix_samples(mix_buffers_ptr, size_t(to_render)); // Deal with whatever format AAudio wants. // Convert from deinterleaved F32 to whatever. if (format == oboe::AudioFormat::Float && num_channels == 2) { DSP::interleave_stereo_f32(u.f32, mix_buffers_ptr[0], mix_buffers_ptr[1], size_t(to_render)); u.f32 += to_render * 2; } else if (format == oboe::AudioFormat::Float) { for (int f = 0; f < to_render; f++) for (unsigned c = 0; c < num_channels; c++) *u.f32++ = mix_buffers[c][f]; } else if (format == oboe::AudioFormat::I16 && num_channels == 2) { DSP::interleave_stereo_f32_i16(u.i16, mix_buffers_ptr[0], mix_buffers_ptr[1], size_t(to_render)); u.i16 += to_render * 2; } else { for (int f = 0; f < to_render; f++) for (unsigned c = 0; c < num_channels; c++) *u.i16++ = DSP::f32_to_i16(mix_buffers[c][f]); } num_frames -= to_render; } return oboe::DataCallbackResult::Continue; } // Called periodically from the main loop, just in case we need to recover from a device lost. void OboeBackend::heartbeat() { } bool OboeBackend::start() { if (is_active) return false; if (!stream) return false; callback.on_backend_start(); frame_count = 0; old_underrun_count = 0; // Starts async, and will pull from callback. oboe::Result res; if ((res = stream->requestStart()) != oboe::Result::OK) { LOGE("Oboe: Failed to start stream (%s).\n", oboe::convertToText(res)); return false; } is_active = true; return true; } bool OboeBackend::stop() { if (!is_active) return false; if (!stream) return false; oboe::Result res; if ((res = stream->stop(1000000)) != oboe::Result::OK) { LOGE("Oboe: Failed to stop stream (%s).\n", oboe::convertToText(res)); return false; } callback.on_backend_stop(); is_active = false; return true; } Backend *create_oboe_backend(BackendCallback &callback, float sample_rate, unsigned channels) { auto *oboe = new OboeBackend(callback); if (!oboe->init(sample_rate, channels)) { delete oboe; return nullptr; } return oboe; } } } <commit_msg>Oboe: Deal with DeviceDisconnected events.<commit_after>/* Copyright (c) 2017-2019 Hans-Kristian Arntzen * * 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 "audio_oboe.hpp" #include "dsp/dsp.hpp" #include "util.hpp" #include <cmath> #include <vector> #include <algorithm> #include <oboe/Oboe.h> namespace Granite { namespace Audio { void set_oboe_low_latency_parameters(unsigned sample_rate, unsigned block_frames) { // For OpenSL ES fallback path. oboe::DefaultStreamValues::SampleRate = sample_rate; oboe::DefaultStreamValues::FramesPerBurst = block_frames; } struct OboeBackend : Backend, oboe::AudioStreamCallback { OboeBackend(BackendCallback &callback) : Backend(callback) { device_alive.test_and_set(); } ~OboeBackend(); bool init(float target_sample_rate, unsigned channels); const char *get_backend_name() override { return "Oboe"; } float get_sample_rate() override { return sample_rate; } unsigned get_num_channels() override { return num_channels; } bool start() override; bool stop() override; void heartbeat() override; oboe::AudioStream *stream = nullptr; std::vector<float> mix_buffers[Backend::MaxAudioChannels]; float *mix_buffers_ptr[Backend::MaxAudioChannels] = {}; oboe::AudioFormat format = oboe::AudioFormat::Unspecified; float sample_rate = 0.0f; double inv_sample_rate = 0.0; unsigned num_channels = 0; int64_t frame_count = 0; int32_t frames_per_callback = 0; int32_t old_underrun_count = 0; bool is_active = false; double last_latency = 0.0; oboe::DataCallbackResult onAudioReady(oboe::AudioStream *oboe_stream, void *audio_data, int32_t num_frames) override; void onErrorBeforeClose(oboe::AudioStream *oboe_stream, oboe::Result error) override; void onErrorAfterClose(oboe::AudioStream *oboe_stream, oboe::Result error) override; void setup_stream_builder(oboe::AudioStreamBuilder &builder); bool reinit(); std::atomic_flag device_alive; }; OboeBackend::~OboeBackend() { stop(); if (stream) stream->close(); stream = nullptr; } bool OboeBackend::reinit() { // Apparently the error callbacks can be called multiple times // from reading some Oboe samples. bool ret = init(0.0f, num_channels); if (!ret) return false; if (is_active) { is_active = false; if (!start()) return false; LOGI("Oboe: Recovered from disconnect!\n"); } return true; } void OboeBackend::setup_stream_builder(oboe::AudioStreamBuilder &builder) { builder.setDirection(oboe::Direction::Output); builder.setPerformanceMode(oboe::PerformanceMode::LowLatency); builder.setCallback(this); //builder.setAudioApi(oboe::AudioApi::OpenSLES); builder.setChannelCount(num_channels); builder.setContentType(oboe::ContentType::Music); builder.setSharingMode(oboe::SharingMode::Shared); builder.setUsage(oboe::Usage::Game); // If we have already committed to a sample rate, keep using it. if (sample_rate != 0.0f) builder.setSampleRate(int32_t(sample_rate)); } bool OboeBackend::init(float, unsigned channels) { num_channels = channels; oboe::AudioStreamBuilder builder; setup_stream_builder(builder); if (builder.openStream(&stream) != oboe::Result::OK) { LOGE("Failed to create Oboe stream!\n"); return false; } sample_rate = stream->getSampleRate(); inv_sample_rate = 1.0 / sample_rate; num_channels = unsigned(stream->getChannelCount()); format = stream->getFormat(); if (!frames_per_callback) { frames_per_callback = stream->getFramesPerCallback(); if (frames_per_callback == oboe::kUnspecified) frames_per_callback = stream->getFramesPerBurst(); // Allocate mix-buffers. // If we have to generate more than this in a callback, iterate multiple times ... for (unsigned c = 0; c < num_channels; c++) { mix_buffers[c].resize(frames_per_callback); mix_buffers_ptr[c] = mix_buffers[c].data(); } callback.set_backend_parameters(sample_rate, num_channels, size_t(frames_per_callback)); } // Set initial latency estimate. last_latency = double(stream->getBufferSizeInFrames()) * inv_sample_rate; callback.set_latency_usec(uint32_t(last_latency * 1e6)); return true; } void OboeBackend::onErrorBeforeClose(oboe::AudioStream *, oboe::Result error) { LOGW("Oboe: Error before close: %s.\n", oboe::convertToText(error)); } void OboeBackend::onErrorAfterClose(oboe::AudioStream *, oboe::Result error) { LOGW("Oboe: Error after close: %s.\n", oboe::convertToText(error)); if (error == oboe::Result::ErrorDisconnected) device_alive.clear(std::memory_order_release); } oboe::DataCallbackResult OboeBackend::onAudioReady( oboe::AudioStream *oboe_stream, void *audio_data, int32_t num_frames) { auto xrun_count = oboe_stream->getXRunCount(); if (xrun_count.error() == oboe::Result::OK) { int32_t underrun_count = xrun_count.value(); if (underrun_count > old_underrun_count) { LOGW("Oboe: observed %d new underruns.", underrun_count - old_underrun_count); old_underrun_count = underrun_count; } } // Update measured latency. // Can fail spuriously, don't update latency estimate in that case. int64_t frame_position, time_ns; if (oboe_stream->getTimestamp(CLOCK_MONOTONIC, &frame_position, &time_ns) == oboe::Result::OK) { timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { int64_t current_ns = ts.tv_sec * 1000000000 + ts.tv_nsec; // Extrapolate play counter based on timestamp. double playing_time = double(frame_position) * inv_sample_rate; playing_time += 1e-9 * double(current_ns - time_ns); double pushed_time = double(frame_count) * inv_sample_rate; double latency = pushed_time - playing_time; if (latency < 0.0) latency = 0.0; // Interpolate latency over time for a smoother result. last_latency = 0.95 * last_latency + 0.05 * latency; callback.set_latency_usec(uint32_t(last_latency * 1e6)); //LOGI("Measured latency: %.3f ms\n", last_latency * 1000.0); } } frame_count += num_frames; union { int16_t *i16; float *f32; void *data; } u; u.data = audio_data; // Ideally we'll only run this loop once, but you never know ... while (num_frames) { auto to_render = std::min(num_frames, frames_per_callback); callback.mix_samples(mix_buffers_ptr, size_t(to_render)); // Deal with whatever format AAudio wants. // Convert from deinterleaved F32 to whatever. if (format == oboe::AudioFormat::Float && num_channels == 2) { DSP::interleave_stereo_f32(u.f32, mix_buffers_ptr[0], mix_buffers_ptr[1], size_t(to_render)); u.f32 += to_render * 2; } else if (format == oboe::AudioFormat::Float) { for (int f = 0; f < to_render; f++) for (unsigned c = 0; c < num_channels; c++) *u.f32++ = mix_buffers[c][f]; } else if (format == oboe::AudioFormat::I16 && num_channels == 2) { DSP::interleave_stereo_f32_i16(u.i16, mix_buffers_ptr[0], mix_buffers_ptr[1], size_t(to_render)); u.i16 += to_render * 2; } else { for (int f = 0; f < to_render; f++) for (unsigned c = 0; c < num_channels; c++) *u.i16++ = DSP::f32_to_i16(mix_buffers[c][f]); } num_frames -= to_render; } return oboe::DataCallbackResult::Continue; } // Called periodically from the main loop, just in case we need to recover from a device lost. void OboeBackend::heartbeat() { if (!device_alive.test_and_set(std::memory_order_acquire)) { stream = nullptr; if (!reinit()) LOGE("Oboe: Failed to reinit stream.\n"); } } bool OboeBackend::start() { if (is_active) return false; if (!stream) return false; callback.on_backend_start(); frame_count = 0; old_underrun_count = 0; // Starts async, and will pull from callback. oboe::Result res; if ((res = stream->requestStart()) != oboe::Result::OK) { LOGE("Oboe: Failed to start stream (%s).\n", oboe::convertToText(res)); return false; } is_active = true; return true; } bool OboeBackend::stop() { if (!is_active) return false; if (!stream) return false; oboe::Result res; if ((res = stream->stop(1000000)) != oboe::Result::OK) { LOGE("Oboe: Failed to stop stream (%s).\n", oboe::convertToText(res)); return false; } callback.on_backend_stop(); is_active = false; return true; } Backend *create_oboe_backend(BackendCallback &callback, float sample_rate, unsigned channels) { auto *oboe = new OboeBackend(callback); if (!oboe->init(sample_rate, channels)) { delete oboe; return nullptr; } return oboe; } } } <|endoftext|>
<commit_before>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2022 Antti Nuortimo. // // This program 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. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "callback_engine.hpp" #include "callback_object.hpp" #include "input_parameters_and_any_value_to_any_value_callback_with_universe.hpp" #include "code/ylikuutio/data/any_value.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <optional> // std::optional namespace yli::ontology { class Universe; } namespace yli::callback { void CallbackEngine::bind_callback_object(yli::callback::CallbackObject* const callback_object) { yli::hierarchy::bind_child_to_parent<yli::callback::CallbackObject*>( callback_object, this->callback_object_pointer_vector, this->free_callback_objectID_queue, this->number_of_callback_objects); } CallbackEngine::CallbackEngine(yli::ontology::Universe& universe) : universe { universe } { // constructor. } CallbackEngine::~CallbackEngine() { // destructor. std::cout << "This callback engine will be destroyed.\n"; // destroy all callback objects of this callback engine. std::cout << "All callback objects of this callback engine will be destroyed.\n"; yli::hierarchy::delete_children<yli::callback::CallbackObject*>(this->callback_object_pointer_vector, this->number_of_callback_objects); } yli::callback::CallbackObject* CallbackEngine::create_callback_object() { return new yli::callback::CallbackObject(this); } yli::callback::CallbackObject* CallbackEngine::create_callback_object(const InputParametersAndAnyValueToAnyValueCallbackWithUniverse callback) { return new yli::callback::CallbackObject(callback, this); } void CallbackEngine::set_callback_object_pointer(const std::size_t childID, yli::callback::CallbackObject* const child_pointer) { yli::hierarchy::set_child_pointer(childID, child_pointer, this->callback_object_pointer_vector, this->free_callback_objectID_queue, this->number_of_callback_objects); } std::optional<yli::data::AnyValue> CallbackEngine::execute(const yli::data::AnyValue& any_value) { std::optional<yli::data::AnyValue> return_any_value; bool is_any_callback_object_executed { false }; // execute all callbacks. for (std::size_t child_i = 0; child_i < this->callback_object_pointer_vector.size(); child_i++) { yli::callback::CallbackObject* callback_object_pointer = static_cast<yli::callback::CallbackObject*>(this->callback_object_pointer_vector[child_i]); if (callback_object_pointer != nullptr) { return_any_value = callback_object_pointer->execute(any_value); is_any_callback_object_executed = true; this->return_values.emplace_back(return_any_value); } else { this->return_values.emplace_back(std::nullopt); } } this->return_values.clear(); if (is_any_callback_object_executed) { return return_any_value; } return std::nullopt; } std::size_t CallbackEngine::get_n_of_return_values() const { return this->return_values.size(); } std::optional<yli::data::AnyValue> CallbackEngine::get_nth_return_value(std::size_t n) const { // note: indexing of `n` begins from 0. std::size_t n_of_return_values = this->get_n_of_return_values(); if (n_of_return_values <= n) { return std::nullopt; } return this->return_values.at(n_of_return_values - 1); } std::optional<yli::data::AnyValue> CallbackEngine::get_previous_return_value() const { std::size_t n_of_return_values = this->get_n_of_return_values(); if (n_of_return_values == 0) { return std::nullopt; } return this->return_values.back(); } yli::ontology::Universe& CallbackEngine::get_universe() const { return this->universe; } } <commit_msg>`CallbackEngine`: remove unnecessary `std::cout` output.<commit_after>// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2022 Antti Nuortimo. // // This program 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. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "callback_engine.hpp" #include "callback_object.hpp" #include "input_parameters_and_any_value_to_any_value_callback_with_universe.hpp" #include "code/ylikuutio/data/any_value.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include standard headers #include <cstddef> // std::size_t #include <optional> // std::optional namespace yli::ontology { class Universe; } namespace yli::callback { void CallbackEngine::bind_callback_object(yli::callback::CallbackObject* const callback_object) { yli::hierarchy::bind_child_to_parent<yli::callback::CallbackObject*>( callback_object, this->callback_object_pointer_vector, this->free_callback_objectID_queue, this->number_of_callback_objects); } CallbackEngine::CallbackEngine(yli::ontology::Universe& universe) : universe { universe } { // constructor. } CallbackEngine::~CallbackEngine() { // destroy all callback objects of this callback engine. yli::hierarchy::delete_children<yli::callback::CallbackObject*>(this->callback_object_pointer_vector, this->number_of_callback_objects); } yli::callback::CallbackObject* CallbackEngine::create_callback_object() { return new yli::callback::CallbackObject(this); } yli::callback::CallbackObject* CallbackEngine::create_callback_object(const InputParametersAndAnyValueToAnyValueCallbackWithUniverse callback) { return new yli::callback::CallbackObject(callback, this); } void CallbackEngine::set_callback_object_pointer(const std::size_t childID, yli::callback::CallbackObject* const child_pointer) { yli::hierarchy::set_child_pointer(childID, child_pointer, this->callback_object_pointer_vector, this->free_callback_objectID_queue, this->number_of_callback_objects); } std::optional<yli::data::AnyValue> CallbackEngine::execute(const yli::data::AnyValue& any_value) { std::optional<yli::data::AnyValue> return_any_value; bool is_any_callback_object_executed { false }; // execute all callbacks. for (std::size_t child_i = 0; child_i < this->callback_object_pointer_vector.size(); child_i++) { yli::callback::CallbackObject* callback_object_pointer = static_cast<yli::callback::CallbackObject*>(this->callback_object_pointer_vector[child_i]); if (callback_object_pointer != nullptr) { return_any_value = callback_object_pointer->execute(any_value); is_any_callback_object_executed = true; this->return_values.emplace_back(return_any_value); } else { this->return_values.emplace_back(std::nullopt); } } this->return_values.clear(); if (is_any_callback_object_executed) { return return_any_value; } return std::nullopt; } std::size_t CallbackEngine::get_n_of_return_values() const { return this->return_values.size(); } std::optional<yli::data::AnyValue> CallbackEngine::get_nth_return_value(std::size_t n) const { // note: indexing of `n` begins from 0. std::size_t n_of_return_values = this->get_n_of_return_values(); if (n_of_return_values <= n) { return std::nullopt; } return this->return_values.at(n_of_return_values - 1); } std::optional<yli::data::AnyValue> CallbackEngine::get_previous_return_value() const { std::size_t n_of_return_values = this->get_n_of_return_values(); if (n_of_return_values == 0) { return std::nullopt; } return this->return_values.back(); } yli::ontology::Universe& CallbackEngine::get_universe() const { return this->universe; } } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 the Stanford University 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. */ #include <map> #include <cstdlib> #include "booksim.hpp" #include "traffic.hpp" #include "network.hpp" #include "random_utils.hpp" #include "misc_utils.hpp" map<string, tTrafficFunction> gTrafficFunctionMap; int gResetTraffic = 0; int gStepTraffic = 0; void src_dest_bin( int source, int dest, int lg ) { int b, t; cout << "from: "; t = source; for ( b = 0; b < lg; ++b ) { cout << ( ( t >> ( lg - b - 1 ) ) & 0x1 ); } cout << " to "; t = dest; for ( b = 0; b < lg; ++b ) { cout << ( ( t >> ( lg - b - 1 ) ) & 0x1 ); } cout << endl; } /* Add Traffic functions here */ //============================================================= int uniform( int source, int total_nodes ) { return RandomInt( total_nodes - 1 ); } //============================================================= int bitcomp( int source, int total_nodes ) { int lg = log_two( total_nodes ); int mask = total_nodes - 1; int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'bitcomp' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } dest = ( ~source ) & mask; return dest; } //============================================================= int transpose( int source, int total_nodes ) { int lg = log_two( total_nodes ); int mask_lo = (1 << (lg/2)) - 1; int mask_hi = mask_lo << (lg/2); int dest; if ( ( ( 1 << lg ) != total_nodes ) || ( lg & 0x1 ) ) { cout << "Error: The 'transpose' traffic pattern requires the number of" << " nodes to be an even power of two!" << endl; exit(-1); } dest = ( ( source >> (lg/2) ) & mask_lo ) | ( ( source << (lg/2) ) & mask_hi ); return dest; } //============================================================= int bitrev( int source, int total_nodes ) { int lg = log_two( total_nodes ); int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'bitrev' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } // If you were fancy you could do this in O(log log total_nodes) // instructions, but I'm not dest = 0; for ( int b = 0; b < lg; ++b ) { dest |= ( ( source >> b ) & 0x1 ) << ( lg - b - 1 ); } return dest; } //============================================================= int shuffle( int source, int total_nodes ) { int lg = log_two( total_nodes ); int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'shuffle' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } dest = ( ( source << 1 ) & ( total_nodes - 1 ) ) | ( ( source >> ( lg - 1 ) ) & 0x1 ); return dest; } //============================================================= int tornado( int source, int total_nodes ) { int offset = 1; int dest = 0; for ( int n = 0; n < realgn; ++n ) { dest += offset * ( ( ( source / offset ) % realgk + ( realgk/2 - 1 ) ) % realgk ); offset *= realgk; } //cout<<source<<" "<<dest<<endl; return dest; } //============================================================= int neighbor( int source, int total_nodes ) { int offset = 1; int dest = 0; for ( int n = 0; n < realgn; ++n ) { dest += offset * ( ( ( source / offset ) % realgk + 1 ) % realgk ); offset *= realgk; } //cout<<"Source "<<source<<" destination "<<dest<<endl; return dest; } //============================================================= int *gPerm = 0; int gPermSeed; void GenerateRandomPerm( int total_nodes ) { int ind; int i,j; int cnt; unsigned long prev_rand; prev_rand = RandomIntLong( ); RandomSeed( gPermSeed ); if ( !gPerm ) { gPerm = new int [total_nodes]; } for ( i = 0; i < total_nodes; ++i ) { gPerm[i] = -1; } for ( i = 0; i < total_nodes; ++i ) { ind = RandomInt( total_nodes - 1 - i ); j = 0; cnt = 0; while( ( cnt < ind ) || ( gPerm[j] != -1 ) ) { if ( gPerm[j] == -1 ) { ++cnt; } ++j; if ( j >= total_nodes ) { cout << "ERROR: GenerateRandomPerm( ) internal error" << endl; exit(-1); } } gPerm[j] = i; } RandomSeed( prev_rand ); } int randperm( int source, int total_nodes ) { if ( gResetTraffic || !gPerm ) { GenerateRandomPerm( total_nodes ); gResetTraffic = 0; } return gPerm[source]; } //============================================================= int diagonal( int source, int total_nodes ) { int t = RandomInt( 2 ); int d; // 2/3 of traffic goes from source->source // 1/3 of traffic goes from source->(source+1)%total_nodes if ( t == 0 ) { d = ( source + 1 ) % total_nodes; } else { d = source; } return d; } //============================================================= int asymmetric( int source, int total_nodes ) { int d; int half = total_nodes / 2; d = ( source % half ) + RandomInt( 1 ) * half; return d; } //============================================================= int taper64( int source, int total_nodes ) { int d; if ( total_nodes != 64 ) { cout << "Error: The 'taper64' traffic pattern requires the number of" << " nodes to be 64!" << endl; exit(-1); } if (RandomInt(1)) { d = (64 + source + 8*(RandomInt(2) - 1) + (RandomInt(2) - 1)) % 64; } else { d = RandomInt( total_nodes - 1 ); } return d; } //============================================================= int badperm_dfly( int source, int total_nodes ) { int grp_size_routers = powi(realgk, realgn - 1); int grp_size_nodes = grp_size_routers * realgk; int temp; int dest; temp = (int) (source / grp_size_nodes); dest = (RandomInt(grp_size_nodes - 1) + (temp+1)*grp_size_nodes ) % total_nodes; return dest; } int badperm_dflynew( int source, int total_nodes ) { int grp_size_routers = 2*realgk; int grp_size_nodes = grp_size_routers * realgk; int temp; int dest; temp = (int) (source / grp_size_nodes); dest = (RandomInt(grp_size_nodes - 1) + (temp+1)*grp_size_nodes ) % total_nodes; return dest; } void InitializeTrafficMap( ) { /* Register Traffic functions here */ gTrafficFunctionMap["uniform"] = &uniform; // "Bit" patterns gTrafficFunctionMap["bitcomp"] = &bitcomp; gTrafficFunctionMap["bitrev"] = &bitrev; gTrafficFunctionMap["transpose"] = &transpose; gTrafficFunctionMap["shuffle"] = &shuffle; // "Digit" patterns gTrafficFunctionMap["tornado"] = &tornado; gTrafficFunctionMap["neighbor"] = &neighbor; // Other patterns gTrafficFunctionMap["randperm"] = &randperm; gTrafficFunctionMap["diagonal"] = &diagonal; gTrafficFunctionMap["asymmetric"] = &asymmetric; gTrafficFunctionMap["taper64"] = &taper64; gTrafficFunctionMap["bad_dragon"] = &badperm_dflynew; } void ResetTrafficFunction( ) { gResetTraffic++; } void StepTrafficFunction( ) { gStepTraffic++; } tTrafficFunction GetTrafficFunction( const Configuration& config ) { if(config.GetInt( "c" )!=1){ int temp = config.GetInt("xr"); realgk = temp*gK; realgn = gN; } else { realgk = gK; realgn = gN; } string topo; config.GetStr( "topology", topo ); map<string, tTrafficFunction>::const_iterator match; tTrafficFunction tf; string fn; config.GetStr( "traffic", fn, "none" ); match = gTrafficFunctionMap.find( fn ); if ( match != gTrafficFunctionMap.end( ) ) { tf = match->second; } else { cout << "Error: Undefined traffic pattern '" << fn << "'." << endl; exit(-1); } gPermSeed = config.GetInt( "perm_seed" ); //seed the network RandomSeed(config.GetInt("seed")); return tf; } <commit_msg>add Ted's adversarial traffic pattern for dragonfly networks<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 the Stanford University 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. */ #include <map> #include <cstdlib> #include "booksim.hpp" #include "traffic.hpp" #include "network.hpp" #include "random_utils.hpp" #include "misc_utils.hpp" map<string, tTrafficFunction> gTrafficFunctionMap; int gResetTraffic = 0; int gStepTraffic = 0; void src_dest_bin( int source, int dest, int lg ) { int b, t; cout << "from: "; t = source; for ( b = 0; b < lg; ++b ) { cout << ( ( t >> ( lg - b - 1 ) ) & 0x1 ); } cout << " to "; t = dest; for ( b = 0; b < lg; ++b ) { cout << ( ( t >> ( lg - b - 1 ) ) & 0x1 ); } cout << endl; } /* Add Traffic functions here */ //============================================================= int uniform( int source, int total_nodes ) { return RandomInt( total_nodes - 1 ); } //============================================================= int bitcomp( int source, int total_nodes ) { int lg = log_two( total_nodes ); int mask = total_nodes - 1; int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'bitcomp' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } dest = ( ~source ) & mask; return dest; } //============================================================= int transpose( int source, int total_nodes ) { int lg = log_two( total_nodes ); int mask_lo = (1 << (lg/2)) - 1; int mask_hi = mask_lo << (lg/2); int dest; if ( ( ( 1 << lg ) != total_nodes ) || ( lg & 0x1 ) ) { cout << "Error: The 'transpose' traffic pattern requires the number of" << " nodes to be an even power of two!" << endl; exit(-1); } dest = ( ( source >> (lg/2) ) & mask_lo ) | ( ( source << (lg/2) ) & mask_hi ); return dest; } //============================================================= int bitrev( int source, int total_nodes ) { int lg = log_two( total_nodes ); int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'bitrev' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } // If you were fancy you could do this in O(log log total_nodes) // instructions, but I'm not dest = 0; for ( int b = 0; b < lg; ++b ) { dest |= ( ( source >> b ) & 0x1 ) << ( lg - b - 1 ); } return dest; } //============================================================= int shuffle( int source, int total_nodes ) { int lg = log_two( total_nodes ); int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'shuffle' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } dest = ( ( source << 1 ) & ( total_nodes - 1 ) ) | ( ( source >> ( lg - 1 ) ) & 0x1 ); return dest; } //============================================================= int tornado( int source, int total_nodes ) { int offset = 1; int dest = 0; for ( int n = 0; n < realgn; ++n ) { dest += offset * ( ( ( source / offset ) % realgk + ( realgk/2 - 1 ) ) % realgk ); offset *= realgk; } //cout<<source<<" "<<dest<<endl; return dest; } //============================================================= int neighbor( int source, int total_nodes ) { int offset = 1; int dest = 0; for ( int n = 0; n < realgn; ++n ) { dest += offset * ( ( ( source / offset ) % realgk + 1 ) % realgk ); offset *= realgk; } //cout<<"Source "<<source<<" destination "<<dest<<endl; return dest; } //============================================================= int *gPerm = 0; int gPermSeed; void GenerateRandomPerm( int total_nodes ) { int ind; int i,j; int cnt; unsigned long prev_rand; prev_rand = RandomIntLong( ); RandomSeed( gPermSeed ); if ( !gPerm ) { gPerm = new int [total_nodes]; } for ( i = 0; i < total_nodes; ++i ) { gPerm[i] = -1; } for ( i = 0; i < total_nodes; ++i ) { ind = RandomInt( total_nodes - 1 - i ); j = 0; cnt = 0; while( ( cnt < ind ) || ( gPerm[j] != -1 ) ) { if ( gPerm[j] == -1 ) { ++cnt; } ++j; if ( j >= total_nodes ) { cout << "ERROR: GenerateRandomPerm( ) internal error" << endl; exit(-1); } } gPerm[j] = i; } RandomSeed( prev_rand ); } int randperm( int source, int total_nodes ) { if ( gResetTraffic || !gPerm ) { GenerateRandomPerm( total_nodes ); gResetTraffic = 0; } return gPerm[source]; } //============================================================= int diagonal( int source, int total_nodes ) { int t = RandomInt( 2 ); int d; // 2/3 of traffic goes from source->source // 1/3 of traffic goes from source->(source+1)%total_nodes if ( t == 0 ) { d = ( source + 1 ) % total_nodes; } else { d = source; } return d; } //============================================================= int asymmetric( int source, int total_nodes ) { int d; int half = total_nodes / 2; d = ( source % half ) + RandomInt( 1 ) * half; return d; } //============================================================= int taper64( int source, int total_nodes ) { int d; if ( total_nodes != 64 ) { cout << "Error: The 'taper64' traffic pattern requires the number of" << " nodes to be 64!" << endl; exit(-1); } if (RandomInt(1)) { d = (64 + source + 8*(RandomInt(2) - 1) + (RandomInt(2) - 1)) % 64; } else { d = RandomInt( total_nodes - 1 ); } return d; } //============================================================= int badperm_dfly( int source, int total_nodes ) { int grp_size_routers = powi(realgk, realgn - 1); int grp_size_nodes = grp_size_routers * realgk; int temp; int dest; temp = (int) (source / grp_size_nodes); dest = (RandomInt(grp_size_nodes - 1) + (temp+1)*grp_size_nodes ) % total_nodes; return dest; } int badperm_dflynew( int source, int total_nodes ) { int grp_size_routers = 2*realgk; int grp_size_nodes = grp_size_routers * realgk; int temp; int dest; temp = (int) (source / grp_size_nodes); dest = (RandomInt(grp_size_nodes - 1) + (temp+1)*grp_size_nodes ) % total_nodes; return dest; } int badperm_yarc(int source, int total_nodes){ int row = (int)(source/realgk); int col = (int)(source%realgk); return RandomInt(realgk-1)*realgk+row; } void InitializeTrafficMap( ) { /* Register Traffic functions here */ gTrafficFunctionMap["uniform"] = &uniform; // "Bit" patterns gTrafficFunctionMap["bitcomp"] = &bitcomp; gTrafficFunctionMap["bitrev"] = &bitrev; gTrafficFunctionMap["transpose"] = &transpose; gTrafficFunctionMap["shuffle"] = &shuffle; // "Digit" patterns gTrafficFunctionMap["tornado"] = &tornado; gTrafficFunctionMap["neighbor"] = &neighbor; // Other patterns gTrafficFunctionMap["randperm"] = &randperm; gTrafficFunctionMap["diagonal"] = &diagonal; gTrafficFunctionMap["asymmetric"] = &asymmetric; gTrafficFunctionMap["taper64"] = &taper64; gTrafficFunctionMap["bad_dragon"] = &badperm_dflynew; gTrafficFunctionMap["badperm_yarc"] = &badperm_yarc; } void ResetTrafficFunction( ) { gResetTraffic++; } void StepTrafficFunction( ) { gStepTraffic++; } tTrafficFunction GetTrafficFunction( const Configuration& config ) { if(config.GetInt( "c" )!=1){ int temp = config.GetInt("xr"); realgk = temp*gK; realgn = gN; } else { realgk = gK; realgn = gN; } string topo; config.GetStr( "topology", topo ); map<string, tTrafficFunction>::const_iterator match; tTrafficFunction tf; string fn; config.GetStr( "traffic", fn, "none" ); match = gTrafficFunctionMap.find( fn ); if ( match != gTrafficFunctionMap.end( ) ) { tf = match->second; } else { cout << "Error: Undefined traffic pattern '" << fn << "'." << endl; exit(-1); } gPermSeed = config.GetInt( "perm_seed" ); //seed the network RandomSeed(config.GetInt("seed")); return tf; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include "de_web_plugin_private.h" #ifdef Q_OS_UNIX #include <unistd.h> #endif #ifdef Q_OS_UNIX static const char *pwsalt = "$1$8282jdkmskwiu29291"; // $1$ for MD5 #endif ApiAuth::ApiAuth() : needSaveDatabase(false), state(StateNormal) { } /*! Init authentification and security. */ void DeRestPluginPrivate::initAuthentification() { bool ok = false; if (gwConfig.contains("gwusername") && gwConfig.contains("gwpassword")) { gwAdminUserName = gwConfig["gwusername"].toString(); gwAdminPasswordHash = gwConfig["gwpassword"].toString(); if (!gwAdminUserName.isEmpty() && !gwAdminPasswordHash.isEmpty()) { ok = true; } } if (!ok) { // generate default username and password gwAdminUserName = "delight"; gwAdminPasswordHash = "delight"; DBG_Printf(DBG_INFO, "create default username and password\n"); // combine username:password QString comb = QString("%1:%2").arg(gwAdminUserName).arg(gwAdminPasswordHash); // create base64 encoded version as used in HTTP basic authentification QString hash = comb.toLocal8Bit().toBase64(); gwAdminPasswordHash = encryptString(hash); queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY); } } /*! Use HTTP basic authentification to check if the request has valid credentials to create API key. */ bool DeRestPluginPrivate::allowedToCreateApikey(const ApiRequest &req) { if (req.hdr.hasKey("Authorization")) { QStringList ls = req.hdr.value("Authorization").split(' '); if ((ls.size() > 1) && ls[0] == "Basic") { QString enc = encryptString(ls[1]); if (enc == gwAdminPasswordHash) { return true; } DBG_Printf(DBG_INFO, "Invalid admin password hash: %s\n", qPrintable(enc)); } } return false; } /*! Checks if the request is authenticated to access the API. \retval true if authenticated \retval false if not authenticated and the rsp http status is set to 403 Forbidden and JSON error is appended */ bool DeRestPluginPrivate::checkApikeyAuthentification(const ApiRequest &req, ApiResponse &rsp) { QString apikey = req.apikey(); if (apikey.isEmpty()) { return false; } std::vector<ApiAuth>::iterator i = apiAuths.begin(); std::vector<ApiAuth>::iterator end = apiAuths.end(); for (; i != end; ++i) { if (apikey == i->apikey) { i->lastUseDate = QDateTime::currentDateTimeUtc(); // fill in useragent string if not already exist if (i->useragent.isEmpty()) { if (req.hdr.hasKey("User-Agent")) { i->useragent = req.hdr.value("User-Agent"); DBG_Printf(DBG_HTTP, "set useragent '%s' for apikey '%s'\n", qPrintable(i->useragent), qPrintable(i->apikey)); } } i->needSaveDatabase = true; if (!apiAuthSaveDatabaseTime.isValid() || apiAuthSaveDatabaseTime.elapsed() > (1000 * 60 * 30)) { apiAuthSaveDatabaseTime.start(); queSaveDb(DB_AUTH, DB_LONG_SAVE_DELAY); } return true; } } #if 0 // allow non registered devices to use the api if the link button is pressed if (gwLinkButton) { ApiAuth auth; auth.needSaveDatabase = true; auth.apikey = apikey; auth.devicetype = "unknown"; auth.createDate = QDateTime::currentDateTimeUtc(); auth.lastUseDate = QDateTime::currentDateTimeUtc(); apiAuths.push_back(auth); queSaveDb(DB_AUTH, DB_SHORT_SAVE_DELAY); return true; } #endif rsp.httpStatus = HttpStatusForbidden; rsp.list.append(errorToMap(ERR_UNAUTHORIZED_USER, req.path.join("/"), "unauthorized user")); return false; } /*! Encrypts a string with using crypt() MD5 + salt. (unix only) \param str the input string \return the encrypted string on success or the unchanged input string on fail */ QString DeRestPluginPrivate::encryptString(const QString &str) { #ifdef Q_OS_UNIX // further encrypt and salt the hash const char *enc = crypt(str.toLocal8Bit().constData(), pwsalt); if (enc) { return QString(enc); } else { DBG_Printf(DBG_ERROR, "crypt(): %s failed\n", qPrintable(str)); // fall through and return str } #endif // Q_OS_UNIX return str; } <commit_msg>Fix authentification via deleted apikeys<commit_after>/* * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include "de_web_plugin_private.h" #ifdef Q_OS_UNIX #include <unistd.h> #endif #ifdef Q_OS_UNIX static const char *pwsalt = "$1$8282jdkmskwiu29291"; // $1$ for MD5 #endif ApiAuth::ApiAuth() : needSaveDatabase(false), state(StateNormal) { } /*! Init authentification and security. */ void DeRestPluginPrivate::initAuthentification() { bool ok = false; if (gwConfig.contains("gwusername") && gwConfig.contains("gwpassword")) { gwAdminUserName = gwConfig["gwusername"].toString(); gwAdminPasswordHash = gwConfig["gwpassword"].toString(); if (!gwAdminUserName.isEmpty() && !gwAdminPasswordHash.isEmpty()) { ok = true; } } if (!ok) { // generate default username and password gwAdminUserName = "delight"; gwAdminPasswordHash = "delight"; DBG_Printf(DBG_INFO, "create default username and password\n"); // combine username:password QString comb = QString("%1:%2").arg(gwAdminUserName).arg(gwAdminPasswordHash); // create base64 encoded version as used in HTTP basic authentification QString hash = comb.toLocal8Bit().toBase64(); gwAdminPasswordHash = encryptString(hash); queSaveDb(DB_CONFIG, DB_SHORT_SAVE_DELAY); } } /*! Use HTTP basic authentification to check if the request has valid credentials to create API key. */ bool DeRestPluginPrivate::allowedToCreateApikey(const ApiRequest &req) { if (req.hdr.hasKey("Authorization")) { QStringList ls = req.hdr.value("Authorization").split(' '); if ((ls.size() > 1) && ls[0] == "Basic") { QString enc = encryptString(ls[1]); if (enc == gwAdminPasswordHash) { return true; } DBG_Printf(DBG_INFO, "Invalid admin password hash: %s\n", qPrintable(enc)); } } return false; } /*! Checks if the request is authenticated to access the API. \retval true if authenticated \retval false if not authenticated and the rsp http status is set to 403 Forbidden and JSON error is appended */ bool DeRestPluginPrivate::checkApikeyAuthentification(const ApiRequest &req, ApiResponse &rsp) { QString apikey = req.apikey(); if (apikey.isEmpty()) { return false; } std::vector<ApiAuth>::iterator i = apiAuths.begin(); std::vector<ApiAuth>::iterator end = apiAuths.end(); for (; i != end; ++i) { if (apikey == i->apikey && i->state == ApiAuth::StateNormal) { i->lastUseDate = QDateTime::currentDateTimeUtc(); // fill in useragent string if not already exist if (i->useragent.isEmpty()) { if (req.hdr.hasKey("User-Agent")) { i->useragent = req.hdr.value("User-Agent"); DBG_Printf(DBG_HTTP, "set useragent '%s' for apikey '%s'\n", qPrintable(i->useragent), qPrintable(i->apikey)); } } i->needSaveDatabase = true; if (!apiAuthSaveDatabaseTime.isValid() || apiAuthSaveDatabaseTime.elapsed() > (1000 * 60 * 30)) { apiAuthSaveDatabaseTime.start(); queSaveDb(DB_AUTH, DB_LONG_SAVE_DELAY); } return true; } } #if 0 // allow non registered devices to use the api if the link button is pressed if (gwLinkButton) { ApiAuth auth; auth.needSaveDatabase = true; auth.apikey = apikey; auth.devicetype = "unknown"; auth.createDate = QDateTime::currentDateTimeUtc(); auth.lastUseDate = QDateTime::currentDateTimeUtc(); apiAuths.push_back(auth); queSaveDb(DB_AUTH, DB_SHORT_SAVE_DELAY); return true; } #endif rsp.httpStatus = HttpStatusForbidden; rsp.list.append(errorToMap(ERR_UNAUTHORIZED_USER, req.path.join("/"), "unauthorized user")); return false; } /*! Encrypts a string with using crypt() MD5 + salt. (unix only) \param str the input string \return the encrypted string on success or the unchanged input string on fail */ QString DeRestPluginPrivate::encryptString(const QString &str) { #ifdef Q_OS_UNIX // further encrypt and salt the hash const char *enc = crypt(str.toLocal8Bit().constData(), pwsalt); if (enc) { return QString(enc); } else { DBG_Printf(DBG_ERROR, "crypt(): %s failed\n", qPrintable(str)); // fall through and return str } #endif // Q_OS_UNIX return str; } <|endoftext|>
<commit_before>/* * StructureContainerComponent.cpp * * Created on: 09/02/2012 * Author: victor */ #include "StructureContainerComponent.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/tangible/components/vendor/VendorDataComponent.h" bool StructureContainerComponent::checkContainerPermission(SceneObject* sceneObject, CreatureObject* creature, uint16 permission) { StructureObject* building = dynamic_cast<StructureObject*>(sceneObject); if(permission == ContainerPermissions::MOVEVENDOR) { if(building->isPublicStructure() && (building->isOnPermissionList("VENDOR", creature) || building->isOnAdminList(creature))) return true; else { if(building->isPrivateStructure()) creature->sendSystemMessage("@player_structure:vendor_public_only"); // else creature->sendSystemMessage("@player_structure:drop_npc_vendor_perm"); // You do not have vendor permission in this building return false; } } if (building->isOwnerOf(creature) || building->isOnAdminList(creature)) return true; if ((permission == ContainerPermissions::OPEN) && building->isStaticObject()) return true; if (building->isBuildingObject()) { BuildingObject* buio = cast<BuildingObject*>(building); if (!buio->isAllowedEntry(creature)) return false; } return ContainerComponent::checkContainerPermission(sceneObject, creature, permission); } <commit_msg>[fixed] Pushed TA's structure container fix to prevent terminals from being removed from buildings.<commit_after>/* * StructureContainerComponent.cpp * * Created on: 09/02/2012 * Author: victor */ #include "StructureContainerComponent.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/tangible/components/vendor/VendorDataComponent.h" bool StructureContainerComponent::checkContainerPermission(SceneObject* sceneObject, CreatureObject* creature, uint16 permission) { StructureObject* building = dynamic_cast<StructureObject*>(sceneObject); if(permission == ContainerPermissions::MOVEVENDOR) { if(building->isPublicStructure() && (building->isOnPermissionList("VENDOR", creature) || building->isOnAdminList(creature))) return true; else { if(building->isPrivateStructure()) creature->sendSystemMessage("@player_structure:vendor_public_only"); // else creature->sendSystemMessage("@player_structure:drop_npc_vendor_perm"); // You do not have vendor permission in this building return false; } } if(permission != ContainerPermissions::OPEN && building->containsChildObject(sceneObject)) return false; if (building->isOwnerOf(creature) || building->isOnAdminList(creature)) return true; if ((permission == ContainerPermissions::OPEN) && building->isStaticObject()) return true; if (building->isBuildingObject()) { BuildingObject* buio = cast<BuildingObject*>(building); if (!buio->isAllowedEntry(creature)) return false; } return ContainerComponent::checkContainerPermission(sceneObject, creature, permission); } <|endoftext|>
<commit_before>// g++ -o glxtest glxtest.cpp -lX11 -lGL // g++ glxcontext.cpp -lX11 -lGL -I/usr/include/python2.7 -lpython2.7 -lboost_python -DPYTHON_WRAPPER -shared -fPIC -o glxcontext.so #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <exception> #include <string> #include <sstream> #include <vector> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <GL/gl.h> #include <GL/glx.h> #ifdef PYTHON_WRAPPER #include <boost/python.hpp> #endif #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*); std::vector<std::pair<int, int> > get_default_context_attribs() { std::vector<std::pair<int, int> > context_attribs; context_attribs.push_back(std::pair<int, int>(GLX_CONTEXT_MAJOR_VERSION_ARB, 4)); context_attribs.push_back(std::pair<int, int>(GLX_CONTEXT_MINOR_VERSION_ARB, 0)); context_attribs.push_back(std::pair<int, int>(GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | GLX_CONTEXT_CORE_PROFILE_BIT_ARB)); return context_attribs; } const std::vector<std::pair<int, int> > default_context_attribs = get_default_context_attribs(); class GLXError: virtual public std::exception { public: GLXError(const std::string &message="unknown error") throw(): message(message) {} virtual ~GLXError() throw() {} virtual const char *what() const throw() { return message.c_str(); } private: const std::string message; }; class Context { public: Context(const std::string &display_name=":0.0", const std::vector<std::pair<int, int> > &context_attribs=default_context_attribs); Context(const Context &other); ~Context(); void bind(); bool is_direct() const; private: void error(const char *message); bool has_glx_extension(const char *name); int *refcount; int (*old_error_handler)(Display*, XErrorEvent*); Display *display; int glx_major, glx_minor; int num_fb_configs; GLXFBConfig *fb_configs; GLXPbuffer pbuffer; glXCreateContextAttribsARBProc glXCreateContextAttribsARB; GLXContext old_context; GLXDrawable old_drawable; GLXDrawable old_read_drawable; GLXContext context; }; static int error_handler(Display *display, XErrorEvent *event) { char buffer[2048]; XGetErrorText(display, event->error_code, buffer, sizeof(buffer)); throw GLXError(buffer); return 0; } bool Context::has_glx_extension(const char *name) { const char *extensions = glXQueryExtensionsString(display, DefaultScreen(display)); std::istringstream s(extensions); std::string sub; while (s) { s >> sub; if (sub == name) return true; } return false; } Context::Context(const Context &other): refcount(other.refcount), display(other.display), glx_major(other.glx_major), glx_minor(other.glx_minor), num_fb_configs(other.num_fb_configs), fb_configs(other.fb_configs), glXCreateContextAttribsARB(other.glXCreateContextAttribsARB), old_context(other.old_context), context(other.context) { (*refcount)++; } Context::Context(const std::string &display_name, const std::vector<std::pair<int, int> > &context_attribs): refcount(new int(1)), display(NULL), glx_major(0), glx_minor(0), num_fb_configs(0), fb_configs(NULL), glXCreateContextAttribsARB(NULL), old_context(NULL), context(NULL) { int context_attribs_array[2 * context_attribs.size() + 1]; for (size_t i = 0; i < context_attribs.size(); ++i) { context_attribs_array[2 * i] = context_attribs[i].first; context_attribs_array[2 * i + 1] = context_attribs[i].second; } context_attribs_array[2 * context_attribs.size()] = None; const int attrib_list[] = { None }; old_error_handler = XSetErrorHandler(&error_handler); if ((display = XOpenDisplay(display_name.c_str())) == NULL) throw GLXError("could not open X display"); if (!glXQueryVersion(display, &glx_major, &glx_minor)) throw GLXError("could not get GLX version"); if (((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) throw GLXError("need at least GLX 1.3"); if (!(fb_configs = glXChooseFBConfig(display, DefaultScreen(display), attrib_list, &num_fb_configs))) throw GLXError("could not determine valid framebuffer configurations"); if (!num_fb_configs) throw GLXError("no valid framebuffer configurations"); if (!(pbuffer = glXCreatePbuffer(display, fb_configs[0], attrib_list))) throw GLXError("could not create pixel buffer"); old_context = glXGetCurrentContext(); old_drawable = glXGetCurrentDrawable(); old_read_drawable = glXGetCurrentReadDrawable(); if (!has_glx_extension("GLX_ARB_create_context")) throw GLXError("could not find GLX_ARB_create_context extension"); if (!(glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB"))) throw GLXError("could not find glXCreateContextAttribsARB"); if (!(context = glXCreateContextAttribsARB(display, fb_configs[0], 0, True, context_attribs_array))) throw GLXError("could not create GLX context"); } void Context::bind() { if (!(glXMakeContextCurrent(display, pbuffer, pbuffer, context))) throw GLXError("could not make GLX context current"); } bool Context::is_direct() const { return glXIsDirect(display, context); } Context::~Context() { (*refcount)--; if (!refcount) { if (display && old_context) glXMakeContextCurrent(display, old_drawable, old_read_drawable, old_context); if (display && context) glXDestroyContext(display, context); if (display) glXDestroyPbuffer(display, pbuffer); if (fb_configs) XFree(fb_configs); if (display) XCloseDisplay(display); XSetErrorHandler(old_error_handler); delete refcount; } } #ifdef PYTHON_WRAPPER using namespace boost::python; PyObject *type_GLXError = NULL; void translateGLXError(GLXError const &e) { PyErr_SetString(type_GLXError, e.what()); } PyObject* createExceptionClass(const char* name, PyObject* baseTypeObj=PyExc_Exception) { std::string scopeName = extract<std::string>(scope().attr("__name__")); std::string qualifiedName0 = scopeName + "." + name; char* qualifiedName1 = const_cast<char*>(qualifiedName0.c_str()); PyObject* typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, 0); if(!typeObj) throw_error_already_set(); scope().attr(name) = handle<>(borrowed(typeObj)); return typeObj; } BOOST_PYTHON_MODULE(glxcontext) { type_GLXError = createExceptionClass("GLXError"); register_exception_translator<GLXError>(translateGLXError); class_<Context>("GLXContext", init<optional<const std::string &, const std::vector<std::pair<int, int> > &> >( // TODO translator for vector<pair<int, int> > from kwargs args("display_name", "context_attribs"), "Create a new GLX context.") ) .add_property("is_direct", &Context::is_direct) ; } #else int main(int argc, const char *argv[]) { Context context; glClearColor(1.0, 1.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glFlush(); return 0; } #endif <commit_msg>add bind to python interface<commit_after>// g++ -o glxtest glxtest.cpp -lX11 -lGL // g++ glxcontext.cpp -lX11 -lGL -I/usr/include/python2.7 -lpython2.7 -lboost_python -DPYTHON_WRAPPER -shared -fPIC -o glxcontext.so #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <exception> #include <string> #include <sstream> #include <vector> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <GL/gl.h> #include <GL/glx.h> #ifdef PYTHON_WRAPPER #include <boost/python.hpp> #endif #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 typedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*); std::vector<std::pair<int, int> > get_default_context_attribs() { std::vector<std::pair<int, int> > context_attribs; context_attribs.push_back(std::pair<int, int>(GLX_CONTEXT_MAJOR_VERSION_ARB, 4)); context_attribs.push_back(std::pair<int, int>(GLX_CONTEXT_MINOR_VERSION_ARB, 0)); context_attribs.push_back(std::pair<int, int>(GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | GLX_CONTEXT_CORE_PROFILE_BIT_ARB)); return context_attribs; } const std::vector<std::pair<int, int> > default_context_attribs = get_default_context_attribs(); class GLXError: virtual public std::exception { public: GLXError(const std::string &message="unknown error") throw(): message(message) {} virtual ~GLXError() throw() {} virtual const char *what() const throw() { return message.c_str(); } private: const std::string message; }; class Context { public: Context(const std::string &display_name=":0.0", const std::vector<std::pair<int, int> > &context_attribs=default_context_attribs); Context(const Context &other); ~Context(); void bind(); bool is_direct() const; private: void error(const char *message); bool has_glx_extension(const char *name); int *refcount; int (*old_error_handler)(Display*, XErrorEvent*); Display *display; int glx_major, glx_minor; int num_fb_configs; GLXFBConfig *fb_configs; GLXPbuffer pbuffer; glXCreateContextAttribsARBProc glXCreateContextAttribsARB; GLXContext old_context; GLXDrawable old_drawable; GLXDrawable old_read_drawable; GLXContext context; }; static int error_handler(Display *display, XErrorEvent *event) { char buffer[2048]; XGetErrorText(display, event->error_code, buffer, sizeof(buffer)); throw GLXError(buffer); return 0; } bool Context::has_glx_extension(const char *name) { const char *extensions = glXQueryExtensionsString(display, DefaultScreen(display)); std::istringstream s(extensions); std::string sub; while (s) { s >> sub; if (sub == name) return true; } return false; } Context::Context(const Context &other): refcount(other.refcount), display(other.display), glx_major(other.glx_major), glx_minor(other.glx_minor), num_fb_configs(other.num_fb_configs), fb_configs(other.fb_configs), glXCreateContextAttribsARB(other.glXCreateContextAttribsARB), old_context(other.old_context), context(other.context) { (*refcount)++; } Context::Context(const std::string &display_name, const std::vector<std::pair<int, int> > &context_attribs): refcount(new int(1)), display(NULL), glx_major(0), glx_minor(0), num_fb_configs(0), fb_configs(NULL), glXCreateContextAttribsARB(NULL), old_context(NULL), context(NULL) { int context_attribs_array[2 * context_attribs.size() + 1]; for (size_t i = 0; i < context_attribs.size(); ++i) { context_attribs_array[2 * i] = context_attribs[i].first; context_attribs_array[2 * i + 1] = context_attribs[i].second; } context_attribs_array[2 * context_attribs.size()] = None; const int attrib_list[] = { None }; old_error_handler = XSetErrorHandler(&error_handler); if ((display = XOpenDisplay(display_name.c_str())) == NULL) throw GLXError("could not open X display"); if (!glXQueryVersion(display, &glx_major, &glx_minor)) throw GLXError("could not get GLX version"); if (((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1)) throw GLXError("need at least GLX 1.3"); if (!(fb_configs = glXChooseFBConfig(display, DefaultScreen(display), attrib_list, &num_fb_configs))) throw GLXError("could not determine valid framebuffer configurations"); if (!num_fb_configs) throw GLXError("no valid framebuffer configurations"); if (!(pbuffer = glXCreatePbuffer(display, fb_configs[0], attrib_list))) throw GLXError("could not create pixel buffer"); old_context = glXGetCurrentContext(); old_drawable = glXGetCurrentDrawable(); old_read_drawable = glXGetCurrentReadDrawable(); if (!has_glx_extension("GLX_ARB_create_context")) throw GLXError("could not find GLX_ARB_create_context extension"); if (!(glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB"))) throw GLXError("could not find glXCreateContextAttribsARB"); if (!(context = glXCreateContextAttribsARB(display, fb_configs[0], 0, True, context_attribs_array))) throw GLXError("could not create GLX context"); } void Context::bind() { if (!(glXMakeContextCurrent(display, pbuffer, pbuffer, context))) throw GLXError("could not make GLX context current"); } bool Context::is_direct() const { return glXIsDirect(display, context); } Context::~Context() { (*refcount)--; if (!refcount) { if (display && old_context) glXMakeContextCurrent(display, old_drawable, old_read_drawable, old_context); if (display && context) glXDestroyContext(display, context); if (display) glXDestroyPbuffer(display, pbuffer); if (fb_configs) XFree(fb_configs); if (display) XCloseDisplay(display); XSetErrorHandler(old_error_handler); delete refcount; } } #ifdef PYTHON_WRAPPER using namespace boost::python; PyObject *type_GLXError = NULL; void translateGLXError(GLXError const &e) { PyErr_SetString(type_GLXError, e.what()); } PyObject* createExceptionClass(const char* name, PyObject* baseTypeObj=PyExc_Exception) { std::string scopeName = extract<std::string>(scope().attr("__name__")); std::string qualifiedName0 = scopeName + "." + name; char* qualifiedName1 = const_cast<char*>(qualifiedName0.c_str()); PyObject* typeObj = PyErr_NewException(qualifiedName1, baseTypeObj, 0); if(!typeObj) throw_error_already_set(); scope().attr(name) = handle<>(borrowed(typeObj)); return typeObj; } BOOST_PYTHON_MODULE(glxcontext) { type_GLXError = createExceptionClass("GLXError"); register_exception_translator<GLXError>(translateGLXError); class_<Context>("GLXContext", init<optional<const std::string &, const std::vector<std::pair<int, int> > &> >( // TODO translator for vector<pair<int, int> > from kwargs args("display_name", "context_attribs"), "Create a new GLX context.") ) .add_property("is_direct", &Context::is_direct) .def("bind", &Context::bind) ; } #else int main(int argc, const char *argv[]) { Context context; glClearColor(1.0, 1.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glFlush(); return 0; } #endif <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkConnectomicsNetworkThresholder.h" #include <mitkConnectomicsStatisticsCalculator.h> #include "vnl/vnl_random.h" mitk::ConnectomicsNetworkThresholder::ConnectomicsNetworkThresholder() : m_Network( 0 ) , m_ThresholdingScheme( mitk::ConnectomicsNetworkThresholder::ThresholdBased ) , m_TargetThreshold( 0.0 ) , m_TargetDensity( 1.0 ) { } mitk::ConnectomicsNetworkThresholder::~ConnectomicsNetworkThresholder() { } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsNetworkThresholder::GetThresholdedNetwork() { mitk::ConnectomicsNetwork::Pointer result; if( ! CheckValidity() ) { MITK_ERROR << "Aborting"; return m_Network; } switch(m_ThresholdingScheme) { case RandomRemovalOfWeakest : { result = ThresholdByRandomRemoval( m_Network, m_TargetDensity ); break; } case LargestLowerThanDensity : { result = ThresholdBelowDensity( m_Network, m_TargetDensity ); break; } case ThresholdBased : { result = Threshold( m_Network, m_TargetThreshold ); break; } default : { MITK_ERROR << "Specified unknown Thresholding Scheme"; result = m_Network; } } return result; } bool mitk::ConnectomicsNetworkThresholder::CheckValidity() { bool valid(true); if( m_Network.IsNull() ) { valid = false; MITK_ERROR << "Network is NULL."; } switch(m_ThresholdingScheme) { case RandomRemovalOfWeakest : case LargestLowerThanDensity : { if( m_TargetDensity < 0.0 ) { valid = false; MITK_ERROR << "Target density is negative."; } if( m_TargetDensity > 1.0 ) { valid = false; MITK_ERROR << "Target density is larger than 1."; } break; } case ThresholdBased : { if( m_TargetThreshold < 0 ) { valid = false; MITK_ERROR << "Target threshold is negative."; } break; } default : { valid = false; MITK_ERROR << "Specified unknown Thresholding Scheme"; } } return valid; } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsNetworkThresholder::ThresholdByRandomRemoval( mitk::ConnectomicsNetwork::Pointer input, double targetDensity ) { mitk::ConnectomicsNetwork::Pointer result = mitk::ConnectomicsNetwork::New(); result->ImportNetwort( input ); mitk::ConnectomicsStatisticsCalculator::Pointer calculator = mitk::ConnectomicsStatisticsCalculator::New(); calculator->SetNetwork( result ); calculator->Update(); //the random number generator vnl_random rng( (unsigned int) rand() ); bool notBelow( targetDensity < calculator->GetConnectionDensity() ); double minWeight( result->GetMaximumWeight() ); int count( 0 ); while( notBelow ) { // result = Threshold( result, loop ); std::vector< EdgeDescriptorType > candidateVector; // determine minimum weight and number of edges having that weight NetworkType* boostGraph = result->GetBoostGraph(); EdgeIteratorType iterator, end; // sets iterator to start end end to end boost::tie(iterator, end) = boost::edges( *boostGraph ); for ( ; iterator != end; ++iterator) { double tempWeight; // the value of an iterator is a descriptor tempWeight = (*boostGraph)[ *iterator ].weight; if( mitk::Equal( tempWeight, minWeight ) ) { candidateVector.push_back( *iterator ); count++; } else if( tempWeight < minWeight ) { candidateVector.clear(); candidateVector.push_back( *iterator ); minWeight = tempWeight; count = 1; } } // Which to delete int deleteNumber( rng.lrand32( count - 1 ) ); boost::remove_edge( candidateVector.at( deleteNumber ), *boostGraph ); calculator->SetNetwork( result ); calculator->Update(); notBelow = targetDensity < calculator->GetConnectionDensity(); } result->UpdateIDs(); return result; } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsNetworkThresholder::ThresholdBelowDensity( mitk::ConnectomicsNetwork::Pointer input, double targetDensity ) { mitk::ConnectomicsNetwork::Pointer result = mitk::ConnectomicsNetwork::New(); result->ImportNetwort( input ); mitk::ConnectomicsStatisticsCalculator::Pointer calculator = mitk::ConnectomicsStatisticsCalculator::New(); calculator->SetNetwork( result ); calculator->Update(); bool notBelow( targetDensity < calculator->GetConnectionDensity() ); for( int loop( 1 ); notBelow; loop++ ) { result = Threshold( result, loop ); calculator->SetNetwork( result ); calculator->Update(); notBelow = targetDensity < calculator->GetConnectionDensity(); } return result; } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsNetworkThresholder::Threshold( mitk::ConnectomicsNetwork::Pointer input, double targetThreshold ) { mitk::ConnectomicsNetwork::Pointer result = mitk::ConnectomicsNetwork::New(); result->ImportNetwort( input ); NetworkType* boostGraph = result->GetBoostGraph(); EdgeIteratorType iterator, end; // set to true if iterators are invalidated by deleting an edge bool edgeHasBeenRemoved( true ); // if no edge has been removed in the last loop, we are done while( edgeHasBeenRemoved ) { edgeHasBeenRemoved = false; // sets iterator to start and end to end boost::tie(iterator, end) = boost::edges( *boostGraph ); bool endReached( false ); while( !edgeHasBeenRemoved && !endReached ) { if( iterator != end ) { // If the edge is below the target threshold it is deleted if( (*boostGraph)[ *iterator ].weight < targetThreshold ) { edgeHasBeenRemoved = true; // this invalidates all iterators boost::remove_edge( *iterator, *boostGraph ); } else { ++iterator; } } else { endReached = true; } } } result->UpdateIDs(); return result; } <commit_msg>Properly initialize variables<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkConnectomicsNetworkThresholder.h" #include <mitkConnectomicsStatisticsCalculator.h> #include "vnl/vnl_random.h" mitk::ConnectomicsNetworkThresholder::ConnectomicsNetworkThresholder() : m_Network( 0 ) , m_ThresholdingScheme( mitk::ConnectomicsNetworkThresholder::ThresholdBased ) , m_TargetThreshold( 0.0 ) , m_TargetDensity( 1.0 ) { } mitk::ConnectomicsNetworkThresholder::~ConnectomicsNetworkThresholder() { } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsNetworkThresholder::GetThresholdedNetwork() { mitk::ConnectomicsNetwork::Pointer result; if( ! CheckValidity() ) { MITK_ERROR << "Aborting"; return m_Network; } switch(m_ThresholdingScheme) { case RandomRemovalOfWeakest : { result = ThresholdByRandomRemoval( m_Network, m_TargetDensity ); break; } case LargestLowerThanDensity : { result = ThresholdBelowDensity( m_Network, m_TargetDensity ); break; } case ThresholdBased : { result = Threshold( m_Network, m_TargetThreshold ); break; } default : { MITK_ERROR << "Specified unknown Thresholding Scheme"; result = m_Network; } } return result; } bool mitk::ConnectomicsNetworkThresholder::CheckValidity() { bool valid(true); if( m_Network.IsNull() ) { valid = false; MITK_ERROR << "Network is NULL."; } switch(m_ThresholdingScheme) { case RandomRemovalOfWeakest : case LargestLowerThanDensity : { if( m_TargetDensity < 0.0 ) { valid = false; MITK_ERROR << "Target density is negative."; } if( m_TargetDensity > 1.0 ) { valid = false; MITK_ERROR << "Target density is larger than 1."; } break; } case ThresholdBased : { if( m_TargetThreshold < 0 ) { valid = false; MITK_ERROR << "Target threshold is negative."; } break; } default : { valid = false; MITK_ERROR << "Specified unknown Thresholding Scheme"; } } return valid; } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsNetworkThresholder::ThresholdByRandomRemoval( mitk::ConnectomicsNetwork::Pointer input, double targetDensity ) { mitk::ConnectomicsNetwork::Pointer result = mitk::ConnectomicsNetwork::New(); result->ImportNetwort( input ); mitk::ConnectomicsStatisticsCalculator::Pointer calculator = mitk::ConnectomicsStatisticsCalculator::New(); calculator->SetNetwork( result ); calculator->Update(); //the random number generator vnl_random rng( (unsigned int) rand() ); bool notBelow( targetDensity < calculator->GetConnectionDensity() ); double minWeight( result->GetMaximumWeight() ); int count( 0 ); while( notBelow ) { // result = Threshold( result, loop ); std::vector< EdgeDescriptorType > candidateVector; minWeight = result->GetMaximumWeight(); count = 0; // determine minimum weight and number of edges having that weight NetworkType* boostGraph = result->GetBoostGraph(); EdgeIteratorType iterator, end; // sets iterator to start end end to end boost::tie(iterator, end) = boost::edges( *boostGraph ); for ( ; iterator != end; ++iterator) { double tempWeight; // the value of an iterator is a descriptor tempWeight = (*boostGraph)[ *iterator ].weight; if( mitk::Equal( tempWeight, minWeight ) ) { candidateVector.push_back( *iterator ); count++; } else if( tempWeight < minWeight ) { candidateVector.clear(); candidateVector.push_back( *iterator ); minWeight = tempWeight; count = 1; } } // Which to delete int deleteNumber( rng.lrand32( count - 1 ) ); boost::remove_edge( candidateVector.at( deleteNumber ), *boostGraph ); calculator->SetNetwork( result ); calculator->Update(); notBelow = targetDensity < calculator->GetConnectionDensity(); } result->UpdateIDs(); return result; } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsNetworkThresholder::ThresholdBelowDensity( mitk::ConnectomicsNetwork::Pointer input, double targetDensity ) { mitk::ConnectomicsNetwork::Pointer result = mitk::ConnectomicsNetwork::New(); result->ImportNetwort( input ); mitk::ConnectomicsStatisticsCalculator::Pointer calculator = mitk::ConnectomicsStatisticsCalculator::New(); calculator->SetNetwork( result ); calculator->Update(); bool notBelow( targetDensity < calculator->GetConnectionDensity() ); for( int loop( 1 ); notBelow; loop++ ) { result = Threshold( result, loop ); calculator->SetNetwork( result ); calculator->Update(); notBelow = targetDensity < calculator->GetConnectionDensity(); } return result; } mitk::ConnectomicsNetwork::Pointer mitk::ConnectomicsNetworkThresholder::Threshold( mitk::ConnectomicsNetwork::Pointer input, double targetThreshold ) { mitk::ConnectomicsNetwork::Pointer result = mitk::ConnectomicsNetwork::New(); result->ImportNetwort( input ); NetworkType* boostGraph = result->GetBoostGraph(); EdgeIteratorType iterator, end; // set to true if iterators are invalidated by deleting an edge bool edgeHasBeenRemoved( true ); // if no edge has been removed in the last loop, we are done while( edgeHasBeenRemoved ) { edgeHasBeenRemoved = false; // sets iterator to start and end to end boost::tie(iterator, end) = boost::edges( *boostGraph ); bool endReached( false ); while( !edgeHasBeenRemoved && !endReached ) { if( iterator != end ) { // If the edge is below the target threshold it is deleted if( (*boostGraph)[ *iterator ].weight < targetThreshold ) { edgeHasBeenRemoved = true; // this invalidates all iterators boost::remove_edge( *iterator, *boostGraph ); } else { ++iterator; } } else { endReached = true; } } } result->UpdateIDs(); return result; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <iostream> #define MAXSTRLEN 255 // 用户可在255以内定义最大串长 typedef unsigned char SString[MAXSTRLEN+1]; // 0号单元存放串的长度 void get_next(SString T,int next[]){ int i,j; next[1]=0; j=0; while(i<T[0]){ if(j == 0 || T[i]==T[j]){ ++i; ++j; next[i]=j; } else{ j=next[j]; } } } int main(){ int next[MAXSTRLEN]; SString S; int n,i,j; char ch; scanf("%d",&n); // 指定要验证NEXT值的字符串个数 ch=getchar(); for(i=1;i<=n;i++) { ch=getchar(); for(j=1;j<=MAXSTRLEN&&(ch!='\n');j++) // 录入字符串 { S[j]=ch; ch=getchar(); } S[0]=j-1; S[j]=0; // S[0]用于存储字符串中字符个数 printf("%s\n",S+1); get_next(S,next); printf("%d",j); printf("NEXT J is:"); for(j=1;j<=S[0];j++) printf("%d\n",*next[j]); printf("\n"); } } <commit_msg>update uoj8591<commit_after>#include <cstdio> #include <cstdlib> #include <iostream> #define MAXSTRLEN 255 // 用户可在255以内定义最大串长 typedef unsigned char SString[MAXSTRLEN+1]; // 0号单元存放串的长度 void get_next(SString T,int next[]){ int i,j; next[1]=0; j=0; while(i<T[0]){ if(j == 0 || T[i]==T[j]){ ++i; ++j; next[i]=j; } else{ j=next[j]; } } } int main(){ int next[MAXSTRLEN]; SString S; int n,i,j; char ch; scanf("%d",&n); // 指定要验证NEXT值的字符串个数 ch=getchar(); for(i=1;i<=n;i++) { ch=getchar(); for(j=1;j<=MAXSTRLEN&&(ch!='\n');j++) // 录入字符串 { S[j]=ch; ch=getchar(); } S[0]=j-1; S[j]=0; // S[0]用于存储字符串中字符个数 printf("%s\n",S+1); get_next(S,next); printf("%d",j); printf("NEXT J is:"); for(j=1;j<=S[0];j++) printf("%d\n",next[j]); printf("\n"); } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-POS-test" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-POS" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>//===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==// // // This file implements the generic AliasAnalysis interface which is used as the // common interface used by all clients and implementations of alias analysis. // // This file also implements the default version of the AliasAnalysis interface // that is to be used when no other implementation is specified. This does some // simple tests that detect obvious cases: two different global pointers cannot // alias, a global cannot alias a malloc, two different mallocs cannot alias, // etc. // // This alias analysis implementation really isn't very good for anything, but // it is very fast, and makes a nice clean default implementation. Because it // handles lots of little corner cases, other, more complex, alias analysis // implementations may choose to rely on this pass to resolve these simple and // easy cases. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/BasicAliasAnalysis.h" #include "llvm/BasicBlock.h" #include "llvm/Support/InstVisitor.h" #include "llvm/iMemory.h" #include "llvm/iOther.h" #include "llvm/Constants.h" #include "llvm/GlobalValue.h" #include "llvm/DerivedTypes.h" // Register the AliasAnalysis interface, providing a nice name to refer to. namespace { RegisterAnalysisGroup<AliasAnalysis> Z("Alias Analysis"); } // CanModify - Define a little visitor class that is used to check to see if // arbitrary chunks of code can modify a specified pointer. // namespace { struct CanModify : public InstVisitor<CanModify, bool> { AliasAnalysis &AA; const Value *Ptr; CanModify(AliasAnalysis *aa, const Value *ptr) : AA(*aa), Ptr(ptr) {} bool visitInvokeInst(InvokeInst &II) { return AA.canInvokeModify(II, Ptr); } bool visitCallInst(CallInst &CI) { return AA.canCallModify(CI, Ptr); } bool visitStoreInst(StoreInst &SI) { return AA.alias(Ptr, SI.getOperand(1)); } // Other instructions do not alias anything. bool visitInstruction(Instruction &I) { return false; } }; } // AliasAnalysis destructor: DO NOT move this to the header file for // AliasAnalysis or else clients of the AliasAnalysis class may not depend on // the AliasAnalysis.o file in the current .a file, causing alias analysis // support to not be included in the tool correctly! // AliasAnalysis::~AliasAnalysis() {} /// canBasicBlockModify - Return true if it is possible for execution of the /// specified basic block to modify the value pointed to by Ptr. /// bool AliasAnalysis::canBasicBlockModify(const BasicBlock &bb, const Value *Ptr) { CanModify CM(this, Ptr); BasicBlock &BB = const_cast<BasicBlock&>(bb); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (CM.visit(I)) // Check every instruction in the basic block... return true; return false; } /// canInstructionRangeModify - Return true if it is possible for the execution /// of the specified instructions to modify the value pointed to by Ptr. The /// instructions to consider are all of the instructions in the range of [I1,I2] /// INCLUSIVE. I1 and I2 must be in the same basic block. /// bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1, const Instruction &I2, const Value *Ptr) { assert(I1.getParent() == I2.getParent() && "Instructions not in same basic block!"); CanModify CM(this, Ptr); BasicBlock::iterator I = const_cast<Instruction*>(&I1); BasicBlock::iterator E = const_cast<Instruction*>(&I2); ++E; // Convert from inclusive to exclusive range. for (; I != E; ++I) if (CM.visit(I)) // Check every instruction in the basic block... return true; return false; } //===----------------------------------------------------------------------===// // BasicAliasAnalysis Pass Implementation //===----------------------------------------------------------------------===// // // Because of the way .a files work, the implementation of the // BasicAliasAnalysis class MUST be in the AliasAnalysis file itself, or else we // run the risk of AliasAnalysis being used, but the default implementation not // being linked into the tool that uses it. As such, we register and implement // the class here. // namespace { // Register this pass... RegisterOpt<BasicAliasAnalysis> X("basicaa", "Basic Alias Analysis (default AA impl)"); // Declare that we implement the AliasAnalysis interface RegisterAnalysisGroup<AliasAnalysis, BasicAliasAnalysis, true> Y; } // End of anonymous namespace // hasUniqueAddress - Return true if the static inline bool hasUniqueAddress(const Value *V) { return isa<GlobalValue>(V) || isa<MallocInst>(V) || isa<AllocaInst>(V); } static const Value *getUnderlyingObject(const Value *V) { if (!isa<PointerType>(V->getType())) return 0; // If we are at some type of object... return it. if (hasUniqueAddress(V)) return V; // Traverse through different addressing mechanisms... if (const Instruction *I = dyn_cast<Instruction>(V)) { if (isa<CastInst>(I) || isa<GetElementPtrInst>(I)) return getUnderlyingObject(I->getOperand(0)); } return 0; } // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such // as array references. Note that this function is heavily tail recursive. // Hopefully we have a smart C++ compiler. :) // AliasAnalysis::Result BasicAliasAnalysis::alias(const Value *V1, const Value *V2) { // Strip off constant pointer refs if they exist if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V1)) V1 = CPR->getValue(); if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V2)) V2 = CPR->getValue(); // Are we checking for alias of the same value? if (V1 == V2) return MustAlias; if ((!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType())) && V1->getType() != Type::LongTy && V2->getType() != Type::LongTy) return NoAlias; // Scalars cannot alias each other // Strip off cast instructions... if (const Instruction *I = dyn_cast<CastInst>(V1)) return alias(I->getOperand(0), V2); if (const Instruction *I = dyn_cast<CastInst>(V2)) return alias(V1, I->getOperand(0)); // If we have two gep instructions with identical indices, return an alias // result equal to the alias result of the original pointer... // if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(V1)) if (const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(V2)) if (GEP1->getNumOperands() == GEP2->getNumOperands() && GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType()) { if (std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1)) return alias(GEP1->getOperand(0), GEP2->getOperand(0)); // If all of the indexes to the getelementptr are constant, but // different (well we already know they are different), then we know // that there cannot be an alias here if the two base pointers DO alias. // bool AllConstant = true; for (unsigned i = 1, e = GEP1->getNumOperands(); i != e; ++i) if (!isa<Constant>(GEP1->getOperand(i)) || !isa<Constant>(GEP2->getOperand(i))) { AllConstant = false; break; } // If we are all constant, then look at where the the base pointers // alias. If they are known not to alias, then we are dealing with two // different arrays or something, so no alias is possible. If they are // known to be the same object, then we cannot alias because we are // indexing into a different part of the object. As usual, MayAlias // doesn't tell us anything. // if (AllConstant && alias(GEP1->getOperand(0), GEP2->getOperand(0)) != MayAlias) return NoAlias; } // Figure out what objects these things are pointing to if we can... const Value *O1 = getUnderlyingObject(V1); const Value *O2 = getUnderlyingObject(V2); // Pointing at a discernable object? if (O1 && O2) { // If they are two different objects, we know that we have no alias... if (O1 != O2) return NoAlias; // If they are the same object, they we can look at the indexes. If they // index off of the object is the same for both pointers, they must alias. // If they are provably different, they must not alias. Otherwise, we can't // tell anything. } else if (O1 && isa<ConstantPointerNull>(V2)) { return NoAlias; // Unique values don't alias null } else if (O2 && isa<ConstantPointerNull>(V1)) { return NoAlias; // Unique values don't alias null } // Check to see if these two pointers are related by a getelementptr // instruction. If one pointer is a GEP with a non-zero index of the other // pointer, we know they cannot alias. // if (isa<GetElementPtrInst>(V2)) std::swap(V1, V2); if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V1)) if (GEP->getOperand(0) == V2) { // If there is at least one non-zero constant index, we know they cannot // alias. for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i) if (const Constant *C = dyn_cast<Constant>(GEP->getOperand(i))) if (!C->isNullValue()) return NoAlias; } return MayAlias; } <commit_msg> - Checkin of the alias analysis work: * Takes into account the size of the memory reference to determine aliasing. * Expose mod/ref information in a more consistent way * BasicAA can now disambiguate A[i][1] and A[j][2] for conservative request sizes<commit_after>//===- AliasAnalysis.cpp - Generic Alias Analysis Interface Implementation -==// // // This file implements the generic AliasAnalysis interface which is used as the // common interface used by all clients and implementations of alias analysis. // // This file also implements the default version of the AliasAnalysis interface // that is to be used when no other implementation is specified. This does some // simple tests that detect obvious cases: two different global pointers cannot // alias, a global cannot alias a malloc, two different mallocs cannot alias, // etc. // // This alias analysis implementation really isn't very good for anything, but // it is very fast, and makes a nice clean default implementation. Because it // handles lots of little corner cases, other, more complex, alias analysis // implementations may choose to rely on this pass to resolve these simple and // easy cases. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/BasicAliasAnalysis.h" #include "llvm/BasicBlock.h" #include "llvm/iMemory.h" #include "llvm/iOther.h" #include "llvm/Constants.h" #include "llvm/ConstantHandling.h" #include "llvm/GlobalValue.h" #include "llvm/DerivedTypes.h" #include "llvm/Target/TargetData.h" // Register the AliasAnalysis interface, providing a nice name to refer to. namespace { RegisterAnalysisGroup<AliasAnalysis> Z("Alias Analysis"); } AliasAnalysis::ModRefResult AliasAnalysis::getModRefInfo(LoadInst *L, Value *P, unsigned Size) { return alias(L->getOperand(0), TD->getTypeSize(L->getType()), P, Size) ? Ref : NoModRef; } AliasAnalysis::ModRefResult AliasAnalysis::getModRefInfo(StoreInst *S, Value *P, unsigned Size) { return alias(S->getOperand(1), TD->getTypeSize(S->getOperand(0)->getType()), P, Size) ? Mod : NoModRef; } // AliasAnalysis destructor: DO NOT move this to the header file for // AliasAnalysis or else clients of the AliasAnalysis class may not depend on // the AliasAnalysis.o file in the current .a file, causing alias analysis // support to not be included in the tool correctly! // AliasAnalysis::~AliasAnalysis() {} /// setTargetData - Subclasses must call this method to initialize the /// AliasAnalysis interface before any other methods are called. /// void AliasAnalysis::InitializeAliasAnalysis(Pass *P) { TD = &P->getAnalysis<TargetData>(); } // getAnalysisUsage - All alias analysis implementations should invoke this // directly (using AliasAnalysis::getAnalysisUsage(AU)) to make sure that // TargetData is required by the pass. void AliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetData>(); // All AA's need TargetData. } /// canBasicBlockModify - Return true if it is possible for execution of the /// specified basic block to modify the value pointed to by Ptr. /// bool AliasAnalysis::canBasicBlockModify(const BasicBlock &BB, const Value *Ptr, unsigned Size) { return canInstructionRangeModify(BB.front(), BB.back(), Ptr, Size); } /// canInstructionRangeModify - Return true if it is possible for the execution /// of the specified instructions to modify the value pointed to by Ptr. The /// instructions to consider are all of the instructions in the range of [I1,I2] /// INCLUSIVE. I1 and I2 must be in the same basic block. /// bool AliasAnalysis::canInstructionRangeModify(const Instruction &I1, const Instruction &I2, const Value *Ptr, unsigned Size) { assert(I1.getParent() == I2.getParent() && "Instructions not in same basic block!"); BasicBlock::iterator I = const_cast<Instruction*>(&I1); BasicBlock::iterator E = const_cast<Instruction*>(&I2); ++E; // Convert from inclusive to exclusive range. for (; I != E; ++I) // Check every instruction in range if (getModRefInfo(I, const_cast<Value*>(Ptr), Size) & Mod) return true; return false; } //===----------------------------------------------------------------------===// // BasicAliasAnalysis Pass Implementation //===----------------------------------------------------------------------===// // // Because of the way .a files work, the implementation of the // BasicAliasAnalysis class MUST be in the AliasAnalysis file itself, or else we // run the risk of AliasAnalysis being used, but the default implementation not // being linked into the tool that uses it. As such, we register and implement // the class here. // namespace { // Register this pass... RegisterOpt<BasicAliasAnalysis> X("basicaa", "Basic Alias Analysis (default AA impl)"); // Declare that we implement the AliasAnalysis interface RegisterAnalysisGroup<AliasAnalysis, BasicAliasAnalysis, true> Y; } // End of anonymous namespace void BasicAliasAnalysis::initializePass() { InitializeAliasAnalysis(this); } // hasUniqueAddress - Return true if the static inline bool hasUniqueAddress(const Value *V) { return isa<GlobalValue>(V) || isa<MallocInst>(V) || isa<AllocaInst>(V); } static const Value *getUnderlyingObject(const Value *V) { if (!isa<PointerType>(V->getType())) return 0; // If we are at some type of object... return it. if (hasUniqueAddress(V)) return V; // Traverse through different addressing mechanisms... if (const Instruction *I = dyn_cast<Instruction>(V)) { if (isa<CastInst>(I) || isa<GetElementPtrInst>(I)) return getUnderlyingObject(I->getOperand(0)); } return 0; } // alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such // as array references. Note that this function is heavily tail recursive. // Hopefully we have a smart C++ compiler. :) // AliasAnalysis::AliasResult BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size, const Value *V2, unsigned V2Size) { // Strip off constant pointer refs if they exist if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V1)) V1 = CPR->getValue(); if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V2)) V2 = CPR->getValue(); // Are we checking for alias of the same value? if (V1 == V2) return MustAlias; if ((!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType())) && V1->getType() != Type::LongTy && V2->getType() != Type::LongTy) return NoAlias; // Scalars cannot alias each other // Strip off cast instructions... if (const Instruction *I = dyn_cast<CastInst>(V1)) return alias(I->getOperand(0), V1Size, V2, V2Size); if (const Instruction *I = dyn_cast<CastInst>(V2)) return alias(V1, V1Size, I->getOperand(0), V2Size); // Figure out what objects these things are pointing to if we can... const Value *O1 = getUnderlyingObject(V1); const Value *O2 = getUnderlyingObject(V2); // Pointing at a discernable object? if (O1 && O2) { // If they are two different objects, we know that we have no alias... if (O1 != O2) return NoAlias; // If they are the same object, they we can look at the indexes. If they // index off of the object is the same for both pointers, they must alias. // If they are provably different, they must not alias. Otherwise, we can't // tell anything. } else if (O1 && isa<ConstantPointerNull>(V2)) { return NoAlias; // Unique values don't alias null } else if (O2 && isa<ConstantPointerNull>(V1)) { return NoAlias; // Unique values don't alias null } // If we have two gep instructions with identical indices, return an alias // result equal to the alias result of the original pointer... // if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(V1)) if (const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(V2)) if (GEP1->getNumOperands() == GEP2->getNumOperands() && GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType()) { AliasResult GAlias = CheckGEPInstructions((GetElementPtrInst*)GEP1, V1Size, (GetElementPtrInst*)GEP2, V2Size); if (GAlias != MayAlias) return GAlias; } // Check to see if these two pointers are related by a getelementptr // instruction. If one pointer is a GEP with a non-zero index of the other // pointer, we know they cannot alias. // if (isa<GetElementPtrInst>(V2)) { std::swap(V1, V2); std::swap(V1Size, V2Size); } if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V1)) if (GEP->getOperand(0) == V2) { // If there is at least one non-zero constant index, we know they cannot // alias. for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i) if (const Constant *C = dyn_cast<Constant>(GEP->getOperand(i))) if (!C->isNullValue()) return NoAlias; } return MayAlias; } // CheckGEPInstructions - Check two GEP instructions of compatible types and // equal number of arguments. This checks to see if the index expressions // preclude the pointers from aliasing... // AliasAnalysis::AliasResult BasicAliasAnalysis::CheckGEPInstructions(GetElementPtrInst *GEP1, unsigned G1S, GetElementPtrInst *GEP2, unsigned G2S){ // Do the base pointers alias? AliasResult BaseAlias = alias(GEP1->getOperand(0), G1S, GEP2->getOperand(0), G2S); if (BaseAlias != MustAlias) // No or May alias: We cannot add anything... return BaseAlias; // Find the (possibly empty) initial sequence of equal values... unsigned NumGEPOperands = GEP1->getNumOperands(); unsigned UnequalOper = 1; while (UnequalOper != NumGEPOperands && GEP1->getOperand(UnequalOper) == GEP2->getOperand(UnequalOper)) ++UnequalOper; // If all operands equal each other, then the derived pointers must // alias each other... if (UnequalOper == NumGEPOperands) return MustAlias; // So now we know that the indexes derived from the base pointers, // which are known to alias, are different. We can still determine a // no-alias result if there are differing constant pairs in the index // chain. For example: // A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S)) // unsigned SizeMax = std::max(G1S, G2S); if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work... // Scan for the first operand that is constant and unequal in the // two getelemenptrs... unsigned FirstConstantOper = UnequalOper; for (; FirstConstantOper != NumGEPOperands; ++FirstConstantOper) { const Value *G1Oper = GEP1->getOperand(FirstConstantOper); const Value *G2Oper = GEP2->getOperand(FirstConstantOper); if (G1Oper != G2Oper && // Found non-equal constant indexes... isa<Constant>(G1Oper) && isa<Constant>(G2Oper)) { // Make sure they are comparable... and make sure the GEP with // the smaller leading constant is GEP1. ConstantBool *Compare = *cast<Constant>(GEP1->getOperand(FirstConstantOper)) > *cast<Constant>(GEP2->getOperand(FirstConstantOper)); if (Compare) { // If they are comparable... if (Compare->getValue()) std::swap(GEP1, GEP2); // Make GEP1 < GEP2 break; } } } // No constant operands, we cannot tell anything... if (FirstConstantOper == NumGEPOperands) return MayAlias; // If there are non-equal constants arguments, then we can figure // out a minimum known delta between the two index expressions... at // this point we know that the first constant index of GEP1 is less // than the first constant index of GEP2. // std::vector<Value*> Indices1; Indices1.reserve(NumGEPOperands-1); for (unsigned i = 1; i != FirstConstantOper; ++i) Indices1.push_back(Constant::getNullValue(GEP1->getOperand(i) ->getType())); std::vector<Value*> Indices2; Indices2.reserve(NumGEPOperands-1); Indices2 = Indices1; // Copy the zeros prefix... // Add the two known constant operands... Indices1.push_back((Value*)GEP1->getOperand(FirstConstantOper)); Indices2.push_back((Value*)GEP2->getOperand(FirstConstantOper)); const Type *GEPPointerTy = GEP1->getOperand(0)->getType(); // Loop over the rest of the operands... for (unsigned i = FirstConstantOper+1; i!=NumGEPOperands; ++i){ const Value *Op1 = GEP1->getOperand(i); const Value *Op2 = GEP1->getOperand(i); if (Op1 == Op2) { // If they are equal, use a zero index... Indices1.push_back(Constant::getNullValue(Op1->getType())); Indices2.push_back(Indices1.back()); } else { if (isa<Constant>(Op1)) Indices1.push_back((Value*)Op1); else { // GEP1 is known to produce a value less than GEP2. To be // conservatively correct, we must assume the largest // possible constant is used in this position. This cannot // be the initial index to the GEP instructions (because we // know we have at least one element before this one with // the different constant arguments), so we know that the // current index must be into either a struct or array. // Because of this, we can calculate the maximum value // possible. // const Type *ElTy = GEP1->getIndexedType(GEPPointerTy, Indices1, true); if (const StructType *STy = dyn_cast<StructType>(ElTy)) { Indices1.push_back(ConstantUInt::get(Type::UByteTy, STy->getNumContainedTypes())); } else { Indices1.push_back(ConstantSInt::get(Type::LongTy, cast<ArrayType>(ElTy)->getNumElements())); } } if (isa<Constant>(Op2)) Indices2.push_back((Value*)Op2); else // Conservatively assume the minimum value for this index Indices2.push_back(Constant::getNullValue(Op1->getType())); } } unsigned Offset1 = getTargetData().getIndexedOffset(GEPPointerTy, Indices1); unsigned Offset2 = getTargetData().getIndexedOffset(GEPPointerTy, Indices2); assert(Offset1 < Offset2 &&"There is at least one different constant here!"); if (Offset2-Offset1 >= SizeMax) { //std::cerr << "Determined that these two GEP's don't alias [" // << SizeMax << " bytes]: \n" << *GEP1 << *GEP2; return NoAlias; } return MayAlias; } <|endoftext|>
<commit_before>#include "ExampleGame/Components/GameScripts/Units/PlayerUnit.h" #include "ExampleGame/Components/Grid/GridCell.h" #include "ExampleGame/Components/Grid/GridManager.h" #include "ExampleGame/Components/Grid/GridNavigator.h" #include "ExampleGame/GameSingletons/GameSingletons.h" #include "ExampleGame/Messages/Declarations.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/Core/Engine.h" #include "Vajra/Engine/Input/Input.h" PlayerUnit::PlayerUnit() : BaseUnit() { this->init(); } PlayerUnit::PlayerUnit(Object* object_) : BaseUnit(object_) { this->init(); } PlayerUnit::~PlayerUnit() { this->destroy(); } void PlayerUnit::init() { this->unitType = UnitType::UNIT_TYPE_ASSASSIN; this->inputState = InputState::INPUT_STATE_WAIT; this->touchNearUnit = false; this->performingSpecial = false; this->moveSpeed = 2.5f; this->turnSpeedDegrees = 360.0f; this->gridNavRef->SetMovementSpeed(this->moveSpeed); this->gridNavRef->SetTurnSpeedDegrees(this->turnSpeedDegrees); this->addSubscriptionToMessageType(MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION, this->GetTypeId(), false); } void PlayerUnit::destroy() { this->removeSubscriptionToAllMessageTypes(this->GetTypeId()); } void PlayerUnit::HandleMessage(MessageChunk messageChunk) { BaseUnit::HandleMessage(messageChunk); switch(messageChunk->GetMessageType()) { case MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION: if(this->performingSpecial) { onSpecialEnd(); } break; default: break; } } void PlayerUnit::OnTouch(int touchId, GridCell* touchedCell) { if(ENGINE->GetInput()->GetTouch(touchId).phase == TouchPhase::Began) { this->touchStartPos = ENGINE->GetInput()->GetTouch(touchId).pos; this->setTouchNearUnit(); } if(this->performingSpecial) { return; } switch(this->inputState) { case InputState::INPUT_STATE_WAIT: this->onSelectedTouch(); break; case InputState::INPUT_STATE_NAV: this->onNavTouch(touchId, touchedCell); break; case InputState::INPUT_STATE_SPECIAL: this->onSpecialTouch(touchId); break; default: break; } } void PlayerUnit::OnDeselect() { this->inputState = InputState::INPUT_STATE_WAIT; } void PlayerUnit::onSelectedTouch() { this->inputState = InputState::INPUT_STATE_NAV; } void PlayerUnit::startSpecial() { this->performingSpecial = true; this->gridNavRef->SetDestination(this->gameObjectRef->GetTransform()->GetPosition()); } void PlayerUnit::onSpecialEnd() { this->performingSpecial = false; this->inputState = InputState::INPUT_STATE_NAV; } void PlayerUnit::onNavTouch(int touchId, GridCell* touchedCell) { if(this->isSpecialTouch(touchId)) { this->inputState = InputState::INPUT_STATE_SPECIAL; } else { if(ENGINE->GetInput()->GetTouch(touchId).phase == TouchPhase::Ended) { this->gridNavRef->SetDestination(touchedCell->x, touchedCell->z); } } } void PlayerUnit::setTouchNearUnit() { glm::vec3 gridPos = SINGLETONS->GetGridManager()->TouchPositionToGridPosition(touchStartPos); if(glm::distance(gridPos, this->gameObjectRef->GetTransform()->GetPosition()) < 1.5f) { this->touchNearUnit = true; } else { this->touchNearUnit = false; } } <commit_msg>Added gridNav stop to specials to fix rotation bug<commit_after>#include "ExampleGame/Components/GameScripts/Units/PlayerUnit.h" #include "ExampleGame/Components/Grid/GridCell.h" #include "ExampleGame/Components/Grid/GridManager.h" #include "ExampleGame/Components/Grid/GridNavigator.h" #include "ExampleGame/GameSingletons/GameSingletons.h" #include "ExampleGame/Messages/Declarations.h" #include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h" #include "Vajra/Engine/Core/Engine.h" #include "Vajra/Engine/Input/Input.h" PlayerUnit::PlayerUnit() : BaseUnit() { this->init(); } PlayerUnit::PlayerUnit(Object* object_) : BaseUnit(object_) { this->init(); } PlayerUnit::~PlayerUnit() { this->destroy(); } void PlayerUnit::init() { this->unitType = UnitType::UNIT_TYPE_ASSASSIN; this->inputState = InputState::INPUT_STATE_WAIT; this->touchNearUnit = false; this->performingSpecial = false; this->moveSpeed = 2.5f; this->turnSpeedDegrees = 360.0f; this->gridNavRef->SetMovementSpeed(this->moveSpeed); this->gridNavRef->SetTurnSpeedDegrees(this->turnSpeedDegrees); this->addSubscriptionToMessageType(MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION, this->GetTypeId(), false); } void PlayerUnit::destroy() { this->removeSubscriptionToAllMessageTypes(this->GetTypeId()); } void PlayerUnit::HandleMessage(MessageChunk messageChunk) { BaseUnit::HandleMessage(messageChunk); switch(messageChunk->GetMessageType()) { case MESSAGE_TYPE_NAVIGATION_REACHED_DESTINATION: if(this->performingSpecial) { onSpecialEnd(); } break; default: break; } } void PlayerUnit::OnTouch(int touchId, GridCell* touchedCell) { if(ENGINE->GetInput()->GetTouch(touchId).phase == TouchPhase::Began) { this->touchStartPos = ENGINE->GetInput()->GetTouch(touchId).pos; this->setTouchNearUnit(); } if(this->performingSpecial) { return; } switch(this->inputState) { case InputState::INPUT_STATE_WAIT: this->onSelectedTouch(); break; case InputState::INPUT_STATE_NAV: this->onNavTouch(touchId, touchedCell); break; case InputState::INPUT_STATE_SPECIAL: this->onSpecialTouch(touchId); break; default: break; } } void PlayerUnit::OnDeselect() { this->inputState = InputState::INPUT_STATE_WAIT; } void PlayerUnit::onSelectedTouch() { this->inputState = InputState::INPUT_STATE_NAV; } void PlayerUnit::startSpecial() { this->performingSpecial = true; } void PlayerUnit::onSpecialEnd() { this->performingSpecial = false; this->inputState = InputState::INPUT_STATE_NAV; } void PlayerUnit::onNavTouch(int touchId, GridCell* touchedCell) { if(this->isSpecialTouch(touchId)) { this->inputState = InputState::INPUT_STATE_SPECIAL; this->gridNavRef->StopNavigation(); } else { if(ENGINE->GetInput()->GetTouch(touchId).phase == TouchPhase::Ended) { this->gridNavRef->SetDestination(touchedCell->x, touchedCell->z); } } } void PlayerUnit::setTouchNearUnit() { glm::vec3 gridPos = SINGLETONS->GetGridManager()->TouchPositionToGridPosition(touchStartPos); if(glm::distance(gridPos, this->gameObjectRef->GetTransform()->GetPosition()) < 1.5f) { this->touchNearUnit = true; } else { this->touchNearUnit = false; } } <|endoftext|>
<commit_before>//===--- lib/CodeGen/DIE.cpp - DWARF Info Entries -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Data structures for DWARF info entries. // //===----------------------------------------------------------------------===// #include "DIE.h" #include "DwarfPrinter.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Target/TargetData.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" using namespace llvm; //===----------------------------------------------------------------------===// // DIEAbbrevData Implementation //===----------------------------------------------------------------------===// /// Profile - Used to gather unique data for the abbreviation folding set. /// void DIEAbbrevData::Profile(FoldingSetNodeID &ID) const { ID.AddInteger(Attribute); ID.AddInteger(Form); } //===----------------------------------------------------------------------===// // DIEAbbrev Implementation //===----------------------------------------------------------------------===// /// Profile - Used to gather unique data for the abbreviation folding set. /// void DIEAbbrev::Profile(FoldingSetNodeID &ID) const { ID.AddInteger(Tag); ID.AddInteger(ChildrenFlag); // For each attribute description. for (unsigned i = 0, N = Data.size(); i < N; ++i) Data[i].Profile(ID); } /// Emit - Print the abbreviation using the specified asm printer. /// void DIEAbbrev::Emit(const AsmPrinter *Asm) const { // Emit its Dwarf tag type. Asm->EmitULEB128Bytes(Tag); Asm->EOL(dwarf::TagString(Tag)); // Emit whether it has children DIEs. Asm->EmitULEB128Bytes(ChildrenFlag); Asm->EOL(dwarf::ChildrenString(ChildrenFlag)); // For each attribute description. for (unsigned i = 0, N = Data.size(); i < N; ++i) { const DIEAbbrevData &AttrData = Data[i]; // Emit attribute type. Asm->EmitULEB128Bytes(AttrData.getAttribute()); Asm->EOL(dwarf::AttributeString(AttrData.getAttribute())); // Emit form type. Asm->EmitULEB128Bytes(AttrData.getForm()); Asm->EOL(dwarf::FormEncodingString(AttrData.getForm())); } // Mark end of abbreviation. Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(1)"); Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(2)"); } #ifndef NDEBUG void DIEAbbrev::print(raw_ostream &O) { O << "Abbreviation @" << format("0x%lx", (long)(intptr_t)this) << " " << dwarf::TagString(Tag) << " " << dwarf::ChildrenString(ChildrenFlag) << '\n'; for (unsigned i = 0, N = Data.size(); i < N; ++i) { O << " " << dwarf::AttributeString(Data[i].getAttribute()) << " " << dwarf::FormEncodingString(Data[i].getForm()) << '\n'; } } void DIEAbbrev::dump() { print(errs()); } #endif //===----------------------------------------------------------------------===// // DIE Implementation //===----------------------------------------------------------------------===// DIE::~DIE() { for (unsigned i = 0, N = Children.size(); i < N; ++i) delete Children[i]; } /// addSiblingOffset - Add a sibling offset field to the front of the DIE. /// void DIE::addSiblingOffset() { DIEInteger *DI = new DIEInteger(0); Values.insert(Values.begin(), DI); Abbrev.AddFirstAttribute(dwarf::DW_AT_sibling, dwarf::DW_FORM_ref4); } #ifndef NDEBUG void DIE::print(raw_ostream &O, unsigned IncIndent) { IndentCount += IncIndent; const std::string Indent(IndentCount, ' '); bool isBlock = Abbrev.getTag() == 0; if (!isBlock) { O << Indent << "Die: " << format("0x%lx", (long)(intptr_t)this) << ", Offset: " << Offset << ", Size: " << Size << "\n"; O << Indent << dwarf::TagString(Abbrev.getTag()) << " " << dwarf::ChildrenString(Abbrev.getChildrenFlag()); } else { O << "Size: " << Size; } O << "\n"; const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData(); IndentCount += 2; for (unsigned i = 0, N = Data.size(); i < N; ++i) { O << Indent; if (!isBlock) O << dwarf::AttributeString(Data[i].getAttribute()); else O << "Blk[" << i << "]"; O << " " << dwarf::FormEncodingString(Data[i].getForm()) << " "; Values[i]->print(O); O << "\n"; } IndentCount -= 2; for (unsigned j = 0, M = Children.size(); j < M; ++j) { Children[j]->print(O, 4); } if (!isBlock) O << "\n"; IndentCount -= IncIndent; } void DIE::dump() { print(errs()); } #endif #ifndef NDEBUG void DIEValue::dump() { print(errs()); } #endif //===----------------------------------------------------------------------===// // DIEInteger Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit integer of appropriate size. /// void DIEInteger::EmitValue(Dwarf *D, unsigned Form) const { const AsmPrinter *Asm = D->getAsm(); switch (Form) { case dwarf::DW_FORM_flag: // Fall thru case dwarf::DW_FORM_ref1: // Fall thru case dwarf::DW_FORM_data1: Asm->EmitInt8(Integer); break; case dwarf::DW_FORM_ref2: // Fall thru case dwarf::DW_FORM_data2: Asm->EmitInt16(Integer); break; case dwarf::DW_FORM_ref4: // Fall thru case dwarf::DW_FORM_data4: Asm->EmitInt32(Integer); break; case dwarf::DW_FORM_ref8: // Fall thru case dwarf::DW_FORM_data8: Asm->EmitInt64(Integer); break; case dwarf::DW_FORM_udata: Asm->EmitULEB128Bytes(Integer); break; case dwarf::DW_FORM_sdata: Asm->EmitSLEB128Bytes(Integer); break; default: llvm_unreachable("DIE Value form not supported yet"); } } /// SizeOf - Determine size of integer value in bytes. /// unsigned DIEInteger::SizeOf(const TargetData *TD, unsigned Form) const { switch (Form) { case dwarf::DW_FORM_flag: // Fall thru case dwarf::DW_FORM_ref1: // Fall thru case dwarf::DW_FORM_data1: return sizeof(int8_t); case dwarf::DW_FORM_ref2: // Fall thru case dwarf::DW_FORM_data2: return sizeof(int16_t); case dwarf::DW_FORM_ref4: // Fall thru case dwarf::DW_FORM_data4: return sizeof(int32_t); case dwarf::DW_FORM_ref8: // Fall thru case dwarf::DW_FORM_data8: return sizeof(int64_t); case dwarf::DW_FORM_udata: return MCAsmInfo::getULEB128Size(Integer); case dwarf::DW_FORM_sdata: return MCAsmInfo::getSLEB128Size(Integer); default: llvm_unreachable("DIE Value form not supported yet"); break; } return 0; } #ifndef NDEBUG void DIEInteger::print(raw_ostream &O) { O << "Int: " << (int64_t)Integer << format(" 0x%llx", (unsigned long long)Integer); } #endif //===----------------------------------------------------------------------===// // DIEString Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit string value. /// void DIEString::EmitValue(Dwarf *D, unsigned Form) const { D->getAsm()->EmitString(Str); } #ifndef NDEBUG void DIEString::print(raw_ostream &O) { O << "Str: \"" << Str << "\""; } #endif //===----------------------------------------------------------------------===// // DIEDwarfLabel Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit label value. /// void DIEDwarfLabel::EmitValue(Dwarf *D, unsigned Form) const { bool IsSmall = Form == dwarf::DW_FORM_data4; D->EmitReference(Label, false, IsSmall); } /// SizeOf - Determine size of label value in bytes. /// unsigned DIEDwarfLabel::SizeOf(const TargetData *TD, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; return TD->getPointerSize(); } #ifndef NDEBUG void DIEDwarfLabel::print(raw_ostream &O) { O << "Lbl: "; Label.print(O); } #endif //===----------------------------------------------------------------------===// // DIEObjectLabel Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit label value. /// void DIEObjectLabel::EmitValue(Dwarf *D, unsigned Form) const { bool IsSmall = Form == dwarf::DW_FORM_data4; D->EmitReference(Label, false, IsSmall); } /// SizeOf - Determine size of label value in bytes. /// unsigned DIEObjectLabel::SizeOf(const TargetData *TD, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; return TD->getPointerSize(); } #ifndef NDEBUG void DIEObjectLabel::print(raw_ostream &O) { O << "Obj: " << Label; } #endif //===----------------------------------------------------------------------===// // DIESectionOffset Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit delta value. /// void DIESectionOffset::EmitValue(Dwarf *D, unsigned Form) const { bool IsSmall = Form == dwarf::DW_FORM_data4; D->EmitSectionOffset(Label.getTag(), Section.getTag(), Label.getNumber(), Section.getNumber(), IsSmall, IsEH, UseSet); } /// SizeOf - Determine size of delta value in bytes. /// unsigned DIESectionOffset::SizeOf(const TargetData *TD, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; return TD->getPointerSize(); } #ifndef NDEBUG void DIESectionOffset::print(raw_ostream &O) { O << "Off: "; Label.print(O); O << "-"; Section.print(O); O << "-" << IsEH << "-" << UseSet; } #endif //===----------------------------------------------------------------------===// // DIEDelta Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit delta value. /// void DIEDelta::EmitValue(Dwarf *D, unsigned Form) const { bool IsSmall = Form == dwarf::DW_FORM_data4; D->EmitDifference(LabelHi, LabelLo, IsSmall); } /// SizeOf - Determine size of delta value in bytes. /// unsigned DIEDelta::SizeOf(const TargetData *TD, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; return TD->getPointerSize(); } #ifndef NDEBUG void DIEDelta::print(raw_ostream &O) { O << "Del: "; LabelHi.print(O); O << "-"; LabelLo.print(O); } #endif //===----------------------------------------------------------------------===// // DIEEntry Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit debug information entry offset. /// void DIEEntry::EmitValue(Dwarf *D, unsigned Form) const { D->getAsm()->EmitInt32(Entry->getOffset()); } #ifndef NDEBUG void DIEEntry::print(raw_ostream &O) { O << format("Die: 0x%lx", (long)(intptr_t)Entry); } #endif //===----------------------------------------------------------------------===// // DIEBlock Implementation //===----------------------------------------------------------------------===// /// ComputeSize - calculate the size of the block. /// unsigned DIEBlock::ComputeSize(const TargetData *TD) { if (!Size) { const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData(); for (unsigned i = 0, N = Values.size(); i < N; ++i) Size += Values[i]->SizeOf(TD, AbbrevData[i].getForm()); } return Size; } /// EmitValue - Emit block data. /// void DIEBlock::EmitValue(Dwarf *D, unsigned Form) const { const AsmPrinter *Asm = D->getAsm(); switch (Form) { case dwarf::DW_FORM_block1: Asm->EmitInt8(Size); break; case dwarf::DW_FORM_block2: Asm->EmitInt16(Size); break; case dwarf::DW_FORM_block4: Asm->EmitInt32(Size); break; case dwarf::DW_FORM_block: Asm->EmitULEB128Bytes(Size); break; default: llvm_unreachable("Improper form for block"); break; } const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData(); for (unsigned i = 0, N = Values.size(); i < N; ++i) { Asm->EOL(); Values[i]->EmitValue(D, AbbrevData[i].getForm()); } } /// SizeOf - Determine size of block data in bytes. /// unsigned DIEBlock::SizeOf(const TargetData *TD, unsigned Form) const { switch (Form) { case dwarf::DW_FORM_block1: return Size + sizeof(int8_t); case dwarf::DW_FORM_block2: return Size + sizeof(int16_t); case dwarf::DW_FORM_block4: return Size + sizeof(int32_t); case dwarf::DW_FORM_block: return Size + MCAsmInfo::getULEB128Size(Size); default: llvm_unreachable("Improper form for block"); break; } return 0; } #ifndef NDEBUG void DIEBlock::print(raw_ostream &O) { O << "Blk: "; DIE::print(O, 5); } #endif <commit_msg><commit_after>//===--- lib/CodeGen/DIE.cpp - DWARF Info Entries -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Data structures for DWARF info entries. // //===----------------------------------------------------------------------===// #include "DIE.h" #include "DwarfPrinter.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Target/TargetData.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" using namespace llvm; //===----------------------------------------------------------------------===// // DIEAbbrevData Implementation //===----------------------------------------------------------------------===// /// Profile - Used to gather unique data for the abbreviation folding set. /// void DIEAbbrevData::Profile(FoldingSetNodeID &ID) const { ID.AddInteger(Attribute); ID.AddInteger(Form); } //===----------------------------------------------------------------------===// // DIEAbbrev Implementation //===----------------------------------------------------------------------===// /// Profile - Used to gather unique data for the abbreviation folding set. /// void DIEAbbrev::Profile(FoldingSetNodeID &ID) const { ID.AddInteger(Tag); ID.AddInteger(ChildrenFlag); // For each attribute description. for (unsigned i = 0, N = Data.size(); i < N; ++i) Data[i].Profile(ID); } /// Emit - Print the abbreviation using the specified asm printer. /// void DIEAbbrev::Emit(const AsmPrinter *Asm) const { // Emit its Dwarf tag type. Asm->EmitULEB128Bytes(Tag); Asm->EOL(dwarf::TagString(Tag)); // Emit whether it has children DIEs. Asm->EmitULEB128Bytes(ChildrenFlag); Asm->EOL(dwarf::ChildrenString(ChildrenFlag)); // For each attribute description. for (unsigned i = 0, N = Data.size(); i < N; ++i) { const DIEAbbrevData &AttrData = Data[i]; // Emit attribute type. Asm->EmitULEB128Bytes(AttrData.getAttribute()); Asm->EOL(dwarf::AttributeString(AttrData.getAttribute())); // Emit form type. Asm->EmitULEB128Bytes(AttrData.getForm()); Asm->EOL(dwarf::FormEncodingString(AttrData.getForm())); } // Mark end of abbreviation. Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(1)"); Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(2)"); } #ifndef NDEBUG void DIEAbbrev::print(raw_ostream &O) { O << "Abbreviation @" << format("0x%lx", (long)(intptr_t)this) << " " << dwarf::TagString(Tag) << " " << dwarf::ChildrenString(ChildrenFlag) << '\n'; for (unsigned i = 0, N = Data.size(); i < N; ++i) { O << " " << dwarf::AttributeString(Data[i].getAttribute()) << " " << dwarf::FormEncodingString(Data[i].getForm()) << '\n'; } } void DIEAbbrev::dump() { print(dbgs()); } #endif //===----------------------------------------------------------------------===// // DIE Implementation //===----------------------------------------------------------------------===// DIE::~DIE() { for (unsigned i = 0, N = Children.size(); i < N; ++i) delete Children[i]; } /// addSiblingOffset - Add a sibling offset field to the front of the DIE. /// void DIE::addSiblingOffset() { DIEInteger *DI = new DIEInteger(0); Values.insert(Values.begin(), DI); Abbrev.AddFirstAttribute(dwarf::DW_AT_sibling, dwarf::DW_FORM_ref4); } #ifndef NDEBUG void DIE::print(raw_ostream &O, unsigned IncIndent) { IndentCount += IncIndent; const std::string Indent(IndentCount, ' '); bool isBlock = Abbrev.getTag() == 0; if (!isBlock) { O << Indent << "Die: " << format("0x%lx", (long)(intptr_t)this) << ", Offset: " << Offset << ", Size: " << Size << "\n"; O << Indent << dwarf::TagString(Abbrev.getTag()) << " " << dwarf::ChildrenString(Abbrev.getChildrenFlag()); } else { O << "Size: " << Size; } O << "\n"; const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData(); IndentCount += 2; for (unsigned i = 0, N = Data.size(); i < N; ++i) { O << Indent; if (!isBlock) O << dwarf::AttributeString(Data[i].getAttribute()); else O << "Blk[" << i << "]"; O << " " << dwarf::FormEncodingString(Data[i].getForm()) << " "; Values[i]->print(O); O << "\n"; } IndentCount -= 2; for (unsigned j = 0, M = Children.size(); j < M; ++j) { Children[j]->print(O, 4); } if (!isBlock) O << "\n"; IndentCount -= IncIndent; } void DIE::dump() { print(dbgs()); } #endif #ifndef NDEBUG void DIEValue::dump() { print(dbgs()); } #endif //===----------------------------------------------------------------------===// // DIEInteger Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit integer of appropriate size. /// void DIEInteger::EmitValue(Dwarf *D, unsigned Form) const { const AsmPrinter *Asm = D->getAsm(); switch (Form) { case dwarf::DW_FORM_flag: // Fall thru case dwarf::DW_FORM_ref1: // Fall thru case dwarf::DW_FORM_data1: Asm->EmitInt8(Integer); break; case dwarf::DW_FORM_ref2: // Fall thru case dwarf::DW_FORM_data2: Asm->EmitInt16(Integer); break; case dwarf::DW_FORM_ref4: // Fall thru case dwarf::DW_FORM_data4: Asm->EmitInt32(Integer); break; case dwarf::DW_FORM_ref8: // Fall thru case dwarf::DW_FORM_data8: Asm->EmitInt64(Integer); break; case dwarf::DW_FORM_udata: Asm->EmitULEB128Bytes(Integer); break; case dwarf::DW_FORM_sdata: Asm->EmitSLEB128Bytes(Integer); break; default: llvm_unreachable("DIE Value form not supported yet"); } } /// SizeOf - Determine size of integer value in bytes. /// unsigned DIEInteger::SizeOf(const TargetData *TD, unsigned Form) const { switch (Form) { case dwarf::DW_FORM_flag: // Fall thru case dwarf::DW_FORM_ref1: // Fall thru case dwarf::DW_FORM_data1: return sizeof(int8_t); case dwarf::DW_FORM_ref2: // Fall thru case dwarf::DW_FORM_data2: return sizeof(int16_t); case dwarf::DW_FORM_ref4: // Fall thru case dwarf::DW_FORM_data4: return sizeof(int32_t); case dwarf::DW_FORM_ref8: // Fall thru case dwarf::DW_FORM_data8: return sizeof(int64_t); case dwarf::DW_FORM_udata: return MCAsmInfo::getULEB128Size(Integer); case dwarf::DW_FORM_sdata: return MCAsmInfo::getSLEB128Size(Integer); default: llvm_unreachable("DIE Value form not supported yet"); break; } return 0; } #ifndef NDEBUG void DIEInteger::print(raw_ostream &O) { O << "Int: " << (int64_t)Integer << format(" 0x%llx", (unsigned long long)Integer); } #endif //===----------------------------------------------------------------------===// // DIEString Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit string value. /// void DIEString::EmitValue(Dwarf *D, unsigned Form) const { D->getAsm()->EmitString(Str); } #ifndef NDEBUG void DIEString::print(raw_ostream &O) { O << "Str: \"" << Str << "\""; } #endif //===----------------------------------------------------------------------===// // DIEDwarfLabel Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit label value. /// void DIEDwarfLabel::EmitValue(Dwarf *D, unsigned Form) const { bool IsSmall = Form == dwarf::DW_FORM_data4; D->EmitReference(Label, false, IsSmall); } /// SizeOf - Determine size of label value in bytes. /// unsigned DIEDwarfLabel::SizeOf(const TargetData *TD, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; return TD->getPointerSize(); } #ifndef NDEBUG void DIEDwarfLabel::print(raw_ostream &O) { O << "Lbl: "; Label.print(O); } #endif //===----------------------------------------------------------------------===// // DIEObjectLabel Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit label value. /// void DIEObjectLabel::EmitValue(Dwarf *D, unsigned Form) const { bool IsSmall = Form == dwarf::DW_FORM_data4; D->EmitReference(Label, false, IsSmall); } /// SizeOf - Determine size of label value in bytes. /// unsigned DIEObjectLabel::SizeOf(const TargetData *TD, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; return TD->getPointerSize(); } #ifndef NDEBUG void DIEObjectLabel::print(raw_ostream &O) { O << "Obj: " << Label; } #endif //===----------------------------------------------------------------------===// // DIESectionOffset Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit delta value. /// void DIESectionOffset::EmitValue(Dwarf *D, unsigned Form) const { bool IsSmall = Form == dwarf::DW_FORM_data4; D->EmitSectionOffset(Label.getTag(), Section.getTag(), Label.getNumber(), Section.getNumber(), IsSmall, IsEH, UseSet); } /// SizeOf - Determine size of delta value in bytes. /// unsigned DIESectionOffset::SizeOf(const TargetData *TD, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; return TD->getPointerSize(); } #ifndef NDEBUG void DIESectionOffset::print(raw_ostream &O) { O << "Off: "; Label.print(O); O << "-"; Section.print(O); O << "-" << IsEH << "-" << UseSet; } #endif //===----------------------------------------------------------------------===// // DIEDelta Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit delta value. /// void DIEDelta::EmitValue(Dwarf *D, unsigned Form) const { bool IsSmall = Form == dwarf::DW_FORM_data4; D->EmitDifference(LabelHi, LabelLo, IsSmall); } /// SizeOf - Determine size of delta value in bytes. /// unsigned DIEDelta::SizeOf(const TargetData *TD, unsigned Form) const { if (Form == dwarf::DW_FORM_data4) return 4; return TD->getPointerSize(); } #ifndef NDEBUG void DIEDelta::print(raw_ostream &O) { O << "Del: "; LabelHi.print(O); O << "-"; LabelLo.print(O); } #endif //===----------------------------------------------------------------------===// // DIEEntry Implementation //===----------------------------------------------------------------------===// /// EmitValue - Emit debug information entry offset. /// void DIEEntry::EmitValue(Dwarf *D, unsigned Form) const { D->getAsm()->EmitInt32(Entry->getOffset()); } #ifndef NDEBUG void DIEEntry::print(raw_ostream &O) { O << format("Die: 0x%lx", (long)(intptr_t)Entry); } #endif //===----------------------------------------------------------------------===// // DIEBlock Implementation //===----------------------------------------------------------------------===// /// ComputeSize - calculate the size of the block. /// unsigned DIEBlock::ComputeSize(const TargetData *TD) { if (!Size) { const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData(); for (unsigned i = 0, N = Values.size(); i < N; ++i) Size += Values[i]->SizeOf(TD, AbbrevData[i].getForm()); } return Size; } /// EmitValue - Emit block data. /// void DIEBlock::EmitValue(Dwarf *D, unsigned Form) const { const AsmPrinter *Asm = D->getAsm(); switch (Form) { case dwarf::DW_FORM_block1: Asm->EmitInt8(Size); break; case dwarf::DW_FORM_block2: Asm->EmitInt16(Size); break; case dwarf::DW_FORM_block4: Asm->EmitInt32(Size); break; case dwarf::DW_FORM_block: Asm->EmitULEB128Bytes(Size); break; default: llvm_unreachable("Improper form for block"); break; } const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData(); for (unsigned i = 0, N = Values.size(); i < N; ++i) { Asm->EOL(); Values[i]->EmitValue(D, AbbrevData[i].getForm()); } } /// SizeOf - Determine size of block data in bytes. /// unsigned DIEBlock::SizeOf(const TargetData *TD, unsigned Form) const { switch (Form) { case dwarf::DW_FORM_block1: return Size + sizeof(int8_t); case dwarf::DW_FORM_block2: return Size + sizeof(int16_t); case dwarf::DW_FORM_block4: return Size + sizeof(int32_t); case dwarf::DW_FORM_block: return Size + MCAsmInfo::getULEB128Size(Size); default: llvm_unreachable("Improper form for block"); break; } return 0; } #ifndef NDEBUG void DIEBlock::print(raw_ostream &O) { O << "Blk: "; DIE::print(O, 5); } #endif <|endoftext|>
<commit_before>/* * * Copyright 2015, Google 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 Google 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. * */ #include <node.h> #include <nan.h> #include <v8.h> #include "grpc/grpc.h" #include "call.h" #include "channel.h" #include "server.h" #include "completion_queue_async_worker.h" #include "credentials.h" #include "server_credentials.h" using v8::Local; using v8::Value; using v8::Object; using v8::Uint32; using v8::String; void InitStatusConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> status = Nan::New<Object>(); Nan::Set(exports, Nan::New("status").ToLocalChecked(), status); Local<Value> OK(Nan::New<Uint32, uint32_t>(GRPC_STATUS_OK)); Nan::Set(status, Nan::New("OK").ToLocalChecked(), OK); Local<Value> CANCELLED(Nan::New<Uint32, uint32_t>(GRPC_STATUS_CANCELLED)); Nan::Set(status, Nan::New("CANCELLED").ToLocalChecked(), CANCELLED); Local<Value> UNKNOWN(Nan::New<Uint32, uint32_t>(GRPC_STATUS_UNKNOWN)); Nan::Set(status, Nan::New("UNKNOWN").ToLocalChecked(), UNKNOWN); Local<Value> INVALID_ARGUMENT( Nan::New<Uint32, uint32_t>(GRPC_STATUS_INVALID_ARGUMENT)); Nan::Set(status, Nan::New("INVALID_ARGUMENT").ToLocalChecked(), INVALID_ARGUMENT); Local<Value> DEADLINE_EXCEEDED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_DEADLINE_EXCEEDED)); Nan::Set(status, Nan::New("DEADLINE_EXCEEDED").ToLocalChecked(), DEADLINE_EXCEEDED); Local<Value> NOT_FOUND(Nan::New<Uint32, uint32_t>(GRPC_STATUS_NOT_FOUND)); Nan::Set(status, Nan::New("NOT_FOUND").ToLocalChecked(), NOT_FOUND); Local<Value> ALREADY_EXISTS( Nan::New<Uint32, uint32_t>(GRPC_STATUS_ALREADY_EXISTS)); Nan::Set(status, Nan::New("ALREADY_EXISTS").ToLocalChecked(), ALREADY_EXISTS); Local<Value> PERMISSION_DENIED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_PERMISSION_DENIED)); Nan::Set(status, Nan::New("PERMISSION_DENIED").ToLocalChecked(), PERMISSION_DENIED); Local<Value> UNAUTHENTICATED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_UNAUTHENTICATED)); Nan::Set(status, Nan::New("UNAUTHENTICATED").ToLocalChecked(), UNAUTHENTICATED); Local<Value> RESOURCE_EXHAUSTED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_RESOURCE_EXHAUSTED)); Nan::Set(status, Nan::New("RESOURCE_EXHAUSTED").ToLocalChecked(), RESOURCE_EXHAUSTED); Local<Value> FAILED_PRECONDITION( Nan::New<Uint32, uint32_t>(GRPC_STATUS_FAILED_PRECONDITION)); Nan::Set(status, Nan::New("FAILED_PRECONDITION").ToLocalChecked(), FAILED_PRECONDITION); Local<Value> ABORTED(Nan::New<Uint32, uint32_t>(GRPC_STATUS_ABORTED)); Nan::Set(status, Nan::New("ABORTED").ToLocalChecked(), ABORTED); Local<Value> OUT_OF_RANGE( Nan::New<Uint32, uint32_t>(GRPC_STATUS_OUT_OF_RANGE)); Nan::Set(status, Nan::New("OUT_OF_RANGE").ToLocalChecked(), OUT_OF_RANGE); Local<Value> UNIMPLEMENTED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_UNIMPLEMENTED)); Nan::Set(status, Nan::New("UNIMPLEMENTED").ToLocalChecked(), UNIMPLEMENTED); Local<Value> INTERNAL(Nan::New<Uint32, uint32_t>(GRPC_STATUS_INTERNAL)); Nan::Set(status, Nan::New("INTERNAL").ToLocalChecked(), INTERNAL); Local<Value> UNAVAILABLE(Nan::New<Uint32, uint32_t>(GRPC_STATUS_UNAVAILABLE)); Nan::Set(status, Nan::New("UNAVAILABLE").ToLocalChecked(), UNAVAILABLE); Local<Value> DATA_LOSS(Nan::New<Uint32, uint32_t>(GRPC_STATUS_DATA_LOSS)); Nan::Set(status, Nan::New("DATA_LOSS").ToLocalChecked(), DATA_LOSS); } void InitCallErrorConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> call_error = Nan::New<Object>(); Nan::Set(exports, Nan::New("callError").ToLocalChecked(), call_error); Local<Value> OK(Nan::New<Uint32, uint32_t>(GRPC_CALL_OK)); Nan::Set(call_error, Nan::New("OK").ToLocalChecked(), OK); Local<Value> ERROR(Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR)); Nan::Set(call_error, Nan::New("ERROR").ToLocalChecked(), ERROR); Local<Value> NOT_ON_SERVER( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_ON_SERVER)); Nan::Set(call_error, Nan::New("NOT_ON_SERVER").ToLocalChecked(), NOT_ON_SERVER); Local<Value> NOT_ON_CLIENT( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_ON_CLIENT)); Nan::Set(call_error, Nan::New("NOT_ON_CLIENT").ToLocalChecked(), NOT_ON_CLIENT); Local<Value> ALREADY_INVOKED( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_ALREADY_INVOKED)); Nan::Set(call_error, Nan::New("ALREADY_INVOKED").ToLocalChecked(), ALREADY_INVOKED); Local<Value> NOT_INVOKED( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_INVOKED)); Nan::Set(call_error, Nan::New("NOT_INVOKED").ToLocalChecked(), NOT_INVOKED); Local<Value> ALREADY_FINISHED( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_ALREADY_FINISHED)); Nan::Set(call_error, Nan::New("ALREADY_FINISHED").ToLocalChecked(), ALREADY_FINISHED); Local<Value> TOO_MANY_OPERATIONS( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_TOO_MANY_OPERATIONS)); Nan::Set(call_error, Nan::New("TOO_MANY_OPERATIONS").ToLocalChecked(), TOO_MANY_OPERATIONS); Local<Value> INVALID_FLAGS( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_INVALID_FLAGS)); Nan::Set(call_error, Nan::New("INVALID_FLAGS").ToLocalChecked(), INVALID_FLAGS); } void InitOpTypeConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> op_type = Nan::New<Object>(); Nan::Set(exports, Nan::New("opType").ToLocalChecked(), op_type); Local<Value> SEND_INITIAL_METADATA( Nan::New<Uint32, uint32_t>(GRPC_OP_SEND_INITIAL_METADATA)); Nan::Set(op_type, Nan::New("SEND_INITIAL_METADATA").ToLocalChecked(), SEND_INITIAL_METADATA); Local<Value> SEND_MESSAGE( Nan::New<Uint32, uint32_t>(GRPC_OP_SEND_MESSAGE)); Nan::Set(op_type, Nan::New("SEND_MESSAGE").ToLocalChecked(), SEND_MESSAGE); Local<Value> SEND_CLOSE_FROM_CLIENT( Nan::New<Uint32, uint32_t>(GRPC_OP_SEND_CLOSE_FROM_CLIENT)); Nan::Set(op_type, Nan::New("SEND_CLOSE_FROM_CLIENT").ToLocalChecked(), SEND_CLOSE_FROM_CLIENT); Local<Value> SEND_STATUS_FROM_SERVER( Nan::New<Uint32, uint32_t>(GRPC_OP_SEND_STATUS_FROM_SERVER)); Nan::Set(op_type, Nan::New("SEND_STATUS_FROM_SERVER").ToLocalChecked(), SEND_STATUS_FROM_SERVER); Local<Value> RECV_INITIAL_METADATA( Nan::New<Uint32, uint32_t>(GRPC_OP_RECV_INITIAL_METADATA)); Nan::Set(op_type, Nan::New("RECV_INITIAL_METADATA").ToLocalChecked(), RECV_INITIAL_METADATA); Local<Value> RECV_MESSAGE( Nan::New<Uint32, uint32_t>(GRPC_OP_RECV_MESSAGE)); Nan::Set(op_type, Nan::New("RECV_MESSAGE").ToLocalChecked(), RECV_MESSAGE); Local<Value> RECV_STATUS_ON_CLIENT( Nan::New<Uint32, uint32_t>(GRPC_OP_RECV_STATUS_ON_CLIENT)); Nan::Set(op_type, Nan::New("RECV_STATUS_ON_CLIENT").ToLocalChecked(), RECV_STATUS_ON_CLIENT); Local<Value> RECV_CLOSE_ON_SERVER( Nan::New<Uint32, uint32_t>(GRPC_OP_RECV_CLOSE_ON_SERVER)); Nan::Set(op_type, Nan::New("RECV_CLOSE_ON_SERVER").ToLocalChecked(), RECV_CLOSE_ON_SERVER); } void InitPropagateConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> propagate = Nan::New<Object>(); Nan::Set(exports, Nan::New("propagate").ToLocalChecked(), propagate); Local<Value> DEADLINE(Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_DEADLINE)); Nan::Set(propagate, Nan::New("DEADLINE").ToLocalChecked(), DEADLINE); Local<Value> CENSUS_STATS_CONTEXT( Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_CENSUS_STATS_CONTEXT)); Nan::Set(propagate, Nan::New("CENSUS_STATS_CONTEXT").ToLocalChecked(), CENSUS_STATS_CONTEXT); Local<Value> CENSUS_TRACING_CONTEXT( Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT)); Nan::Set(propagate, Nan::New("CENSUS_TRACING_CONTEXT").ToLocalChecked(), CENSUS_TRACING_CONTEXT); Local<Value> CANCELLATION( Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_CANCELLATION)); Nan::Set(propagate, Nan::New("CANCELLATION").ToLocalChecked(), CANCELLATION); Local<Value> DEFAULTS(Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_DEFAULTS)); Nan::Set(propagate, Nan::New("DEFAULTS").ToLocalChecked(), DEFAULTS); } void InitConnectivityStateConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> channel_state = Nan::New<Object>(); Nan::Set(exports, Nan::New("connectivityState").ToLocalChecked(), channel_state); Local<Value> IDLE(Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_IDLE)); Nan::Set(channel_state, Nan::New("IDLE").ToLocalChecked(), IDLE); Local<Value> CONNECTING(Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_CONNECTING)); Nan::Set(channel_state, Nan::New("CONNECTING").ToLocalChecked(), CONNECTING); Local<Value> READY(Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_READY)); Nan::Set(channel_state, Nan::New("READY").ToLocalChecked(), READY); Local<Value> TRANSIENT_FAILURE( Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_TRANSIENT_FAILURE)); Nan::Set(channel_state, Nan::New("TRANSIENT_FAILURE").ToLocalChecked(), TRANSIENT_FAILURE); Local<Value> FATAL_FAILURE( Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_FATAL_FAILURE)); Nan::Set(channel_state, Nan::New("FATAL_FAILURE").ToLocalChecked(), FATAL_FAILURE); } void InitWriteFlags(Local<Object> exports) { Nan::HandleScope scope; Local<Object> write_flags = Nan::New<Object>(); Nan::Set(exports, Nan::New("writeFlags").ToLocalChecked(), write_flags); Local<Value> BUFFER_HINT(Nan::New<Uint32, uint32_t>(GRPC_WRITE_BUFFER_HINT)); Nan::Set(write_flags, Nan::New("BUFFER_HINT").ToLocalChecked(), BUFFER_HINT); Local<Value> NO_COMPRESS(Nan::New<Uint32, uint32_t>(GRPC_WRITE_NO_COMPRESS)); Nan::Set(write_flags, Nan::New("NO_COMPRESS").ToLocalChecked(), NO_COMPRESS); } void init(Local<Object> exports) { Nan::HandleScope scope; grpc_init(); InitStatusConstants(exports); InitCallErrorConstants(exports); InitOpTypeConstants(exports); InitPropagateConstants(exports); InitConnectivityStateConstants(exports); InitWriteFlags(exports); grpc::node::Call::Init(exports); grpc::node::Channel::Init(exports); grpc::node::Server::Init(exports); grpc::node::CompletionQueueAsyncWorker::Init(exports); grpc::node::Credentials::Init(exports); grpc::node::ServerCredentials::Init(exports); } NODE_MODULE(grpc, init) <commit_msg>Fixed node extension module name<commit_after>/* * * Copyright 2015, Google 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 Google 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. * */ #include <node.h> #include <nan.h> #include <v8.h> #include "grpc/grpc.h" #include "call.h" #include "channel.h" #include "server.h" #include "completion_queue_async_worker.h" #include "credentials.h" #include "server_credentials.h" using v8::Local; using v8::Value; using v8::Object; using v8::Uint32; using v8::String; void InitStatusConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> status = Nan::New<Object>(); Nan::Set(exports, Nan::New("status").ToLocalChecked(), status); Local<Value> OK(Nan::New<Uint32, uint32_t>(GRPC_STATUS_OK)); Nan::Set(status, Nan::New("OK").ToLocalChecked(), OK); Local<Value> CANCELLED(Nan::New<Uint32, uint32_t>(GRPC_STATUS_CANCELLED)); Nan::Set(status, Nan::New("CANCELLED").ToLocalChecked(), CANCELLED); Local<Value> UNKNOWN(Nan::New<Uint32, uint32_t>(GRPC_STATUS_UNKNOWN)); Nan::Set(status, Nan::New("UNKNOWN").ToLocalChecked(), UNKNOWN); Local<Value> INVALID_ARGUMENT( Nan::New<Uint32, uint32_t>(GRPC_STATUS_INVALID_ARGUMENT)); Nan::Set(status, Nan::New("INVALID_ARGUMENT").ToLocalChecked(), INVALID_ARGUMENT); Local<Value> DEADLINE_EXCEEDED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_DEADLINE_EXCEEDED)); Nan::Set(status, Nan::New("DEADLINE_EXCEEDED").ToLocalChecked(), DEADLINE_EXCEEDED); Local<Value> NOT_FOUND(Nan::New<Uint32, uint32_t>(GRPC_STATUS_NOT_FOUND)); Nan::Set(status, Nan::New("NOT_FOUND").ToLocalChecked(), NOT_FOUND); Local<Value> ALREADY_EXISTS( Nan::New<Uint32, uint32_t>(GRPC_STATUS_ALREADY_EXISTS)); Nan::Set(status, Nan::New("ALREADY_EXISTS").ToLocalChecked(), ALREADY_EXISTS); Local<Value> PERMISSION_DENIED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_PERMISSION_DENIED)); Nan::Set(status, Nan::New("PERMISSION_DENIED").ToLocalChecked(), PERMISSION_DENIED); Local<Value> UNAUTHENTICATED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_UNAUTHENTICATED)); Nan::Set(status, Nan::New("UNAUTHENTICATED").ToLocalChecked(), UNAUTHENTICATED); Local<Value> RESOURCE_EXHAUSTED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_RESOURCE_EXHAUSTED)); Nan::Set(status, Nan::New("RESOURCE_EXHAUSTED").ToLocalChecked(), RESOURCE_EXHAUSTED); Local<Value> FAILED_PRECONDITION( Nan::New<Uint32, uint32_t>(GRPC_STATUS_FAILED_PRECONDITION)); Nan::Set(status, Nan::New("FAILED_PRECONDITION").ToLocalChecked(), FAILED_PRECONDITION); Local<Value> ABORTED(Nan::New<Uint32, uint32_t>(GRPC_STATUS_ABORTED)); Nan::Set(status, Nan::New("ABORTED").ToLocalChecked(), ABORTED); Local<Value> OUT_OF_RANGE( Nan::New<Uint32, uint32_t>(GRPC_STATUS_OUT_OF_RANGE)); Nan::Set(status, Nan::New("OUT_OF_RANGE").ToLocalChecked(), OUT_OF_RANGE); Local<Value> UNIMPLEMENTED( Nan::New<Uint32, uint32_t>(GRPC_STATUS_UNIMPLEMENTED)); Nan::Set(status, Nan::New("UNIMPLEMENTED").ToLocalChecked(), UNIMPLEMENTED); Local<Value> INTERNAL(Nan::New<Uint32, uint32_t>(GRPC_STATUS_INTERNAL)); Nan::Set(status, Nan::New("INTERNAL").ToLocalChecked(), INTERNAL); Local<Value> UNAVAILABLE(Nan::New<Uint32, uint32_t>(GRPC_STATUS_UNAVAILABLE)); Nan::Set(status, Nan::New("UNAVAILABLE").ToLocalChecked(), UNAVAILABLE); Local<Value> DATA_LOSS(Nan::New<Uint32, uint32_t>(GRPC_STATUS_DATA_LOSS)); Nan::Set(status, Nan::New("DATA_LOSS").ToLocalChecked(), DATA_LOSS); } void InitCallErrorConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> call_error = Nan::New<Object>(); Nan::Set(exports, Nan::New("callError").ToLocalChecked(), call_error); Local<Value> OK(Nan::New<Uint32, uint32_t>(GRPC_CALL_OK)); Nan::Set(call_error, Nan::New("OK").ToLocalChecked(), OK); Local<Value> ERROR(Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR)); Nan::Set(call_error, Nan::New("ERROR").ToLocalChecked(), ERROR); Local<Value> NOT_ON_SERVER( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_ON_SERVER)); Nan::Set(call_error, Nan::New("NOT_ON_SERVER").ToLocalChecked(), NOT_ON_SERVER); Local<Value> NOT_ON_CLIENT( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_ON_CLIENT)); Nan::Set(call_error, Nan::New("NOT_ON_CLIENT").ToLocalChecked(), NOT_ON_CLIENT); Local<Value> ALREADY_INVOKED( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_ALREADY_INVOKED)); Nan::Set(call_error, Nan::New("ALREADY_INVOKED").ToLocalChecked(), ALREADY_INVOKED); Local<Value> NOT_INVOKED( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_NOT_INVOKED)); Nan::Set(call_error, Nan::New("NOT_INVOKED").ToLocalChecked(), NOT_INVOKED); Local<Value> ALREADY_FINISHED( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_ALREADY_FINISHED)); Nan::Set(call_error, Nan::New("ALREADY_FINISHED").ToLocalChecked(), ALREADY_FINISHED); Local<Value> TOO_MANY_OPERATIONS( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_TOO_MANY_OPERATIONS)); Nan::Set(call_error, Nan::New("TOO_MANY_OPERATIONS").ToLocalChecked(), TOO_MANY_OPERATIONS); Local<Value> INVALID_FLAGS( Nan::New<Uint32, uint32_t>(GRPC_CALL_ERROR_INVALID_FLAGS)); Nan::Set(call_error, Nan::New("INVALID_FLAGS").ToLocalChecked(), INVALID_FLAGS); } void InitOpTypeConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> op_type = Nan::New<Object>(); Nan::Set(exports, Nan::New("opType").ToLocalChecked(), op_type); Local<Value> SEND_INITIAL_METADATA( Nan::New<Uint32, uint32_t>(GRPC_OP_SEND_INITIAL_METADATA)); Nan::Set(op_type, Nan::New("SEND_INITIAL_METADATA").ToLocalChecked(), SEND_INITIAL_METADATA); Local<Value> SEND_MESSAGE( Nan::New<Uint32, uint32_t>(GRPC_OP_SEND_MESSAGE)); Nan::Set(op_type, Nan::New("SEND_MESSAGE").ToLocalChecked(), SEND_MESSAGE); Local<Value> SEND_CLOSE_FROM_CLIENT( Nan::New<Uint32, uint32_t>(GRPC_OP_SEND_CLOSE_FROM_CLIENT)); Nan::Set(op_type, Nan::New("SEND_CLOSE_FROM_CLIENT").ToLocalChecked(), SEND_CLOSE_FROM_CLIENT); Local<Value> SEND_STATUS_FROM_SERVER( Nan::New<Uint32, uint32_t>(GRPC_OP_SEND_STATUS_FROM_SERVER)); Nan::Set(op_type, Nan::New("SEND_STATUS_FROM_SERVER").ToLocalChecked(), SEND_STATUS_FROM_SERVER); Local<Value> RECV_INITIAL_METADATA( Nan::New<Uint32, uint32_t>(GRPC_OP_RECV_INITIAL_METADATA)); Nan::Set(op_type, Nan::New("RECV_INITIAL_METADATA").ToLocalChecked(), RECV_INITIAL_METADATA); Local<Value> RECV_MESSAGE( Nan::New<Uint32, uint32_t>(GRPC_OP_RECV_MESSAGE)); Nan::Set(op_type, Nan::New("RECV_MESSAGE").ToLocalChecked(), RECV_MESSAGE); Local<Value> RECV_STATUS_ON_CLIENT( Nan::New<Uint32, uint32_t>(GRPC_OP_RECV_STATUS_ON_CLIENT)); Nan::Set(op_type, Nan::New("RECV_STATUS_ON_CLIENT").ToLocalChecked(), RECV_STATUS_ON_CLIENT); Local<Value> RECV_CLOSE_ON_SERVER( Nan::New<Uint32, uint32_t>(GRPC_OP_RECV_CLOSE_ON_SERVER)); Nan::Set(op_type, Nan::New("RECV_CLOSE_ON_SERVER").ToLocalChecked(), RECV_CLOSE_ON_SERVER); } void InitPropagateConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> propagate = Nan::New<Object>(); Nan::Set(exports, Nan::New("propagate").ToLocalChecked(), propagate); Local<Value> DEADLINE(Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_DEADLINE)); Nan::Set(propagate, Nan::New("DEADLINE").ToLocalChecked(), DEADLINE); Local<Value> CENSUS_STATS_CONTEXT( Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_CENSUS_STATS_CONTEXT)); Nan::Set(propagate, Nan::New("CENSUS_STATS_CONTEXT").ToLocalChecked(), CENSUS_STATS_CONTEXT); Local<Value> CENSUS_TRACING_CONTEXT( Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT)); Nan::Set(propagate, Nan::New("CENSUS_TRACING_CONTEXT").ToLocalChecked(), CENSUS_TRACING_CONTEXT); Local<Value> CANCELLATION( Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_CANCELLATION)); Nan::Set(propagate, Nan::New("CANCELLATION").ToLocalChecked(), CANCELLATION); Local<Value> DEFAULTS(Nan::New<Uint32, uint32_t>(GRPC_PROPAGATE_DEFAULTS)); Nan::Set(propagate, Nan::New("DEFAULTS").ToLocalChecked(), DEFAULTS); } void InitConnectivityStateConstants(Local<Object> exports) { Nan::HandleScope scope; Local<Object> channel_state = Nan::New<Object>(); Nan::Set(exports, Nan::New("connectivityState").ToLocalChecked(), channel_state); Local<Value> IDLE(Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_IDLE)); Nan::Set(channel_state, Nan::New("IDLE").ToLocalChecked(), IDLE); Local<Value> CONNECTING(Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_CONNECTING)); Nan::Set(channel_state, Nan::New("CONNECTING").ToLocalChecked(), CONNECTING); Local<Value> READY(Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_READY)); Nan::Set(channel_state, Nan::New("READY").ToLocalChecked(), READY); Local<Value> TRANSIENT_FAILURE( Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_TRANSIENT_FAILURE)); Nan::Set(channel_state, Nan::New("TRANSIENT_FAILURE").ToLocalChecked(), TRANSIENT_FAILURE); Local<Value> FATAL_FAILURE( Nan::New<Uint32, uint32_t>(GRPC_CHANNEL_FATAL_FAILURE)); Nan::Set(channel_state, Nan::New("FATAL_FAILURE").ToLocalChecked(), FATAL_FAILURE); } void InitWriteFlags(Local<Object> exports) { Nan::HandleScope scope; Local<Object> write_flags = Nan::New<Object>(); Nan::Set(exports, Nan::New("writeFlags").ToLocalChecked(), write_flags); Local<Value> BUFFER_HINT(Nan::New<Uint32, uint32_t>(GRPC_WRITE_BUFFER_HINT)); Nan::Set(write_flags, Nan::New("BUFFER_HINT").ToLocalChecked(), BUFFER_HINT); Local<Value> NO_COMPRESS(Nan::New<Uint32, uint32_t>(GRPC_WRITE_NO_COMPRESS)); Nan::Set(write_flags, Nan::New("NO_COMPRESS").ToLocalChecked(), NO_COMPRESS); } void init(Local<Object> exports) { Nan::HandleScope scope; grpc_init(); InitStatusConstants(exports); InitCallErrorConstants(exports); InitOpTypeConstants(exports); InitPropagateConstants(exports); InitConnectivityStateConstants(exports); InitWriteFlags(exports); grpc::node::Call::Init(exports); grpc::node::Channel::Init(exports); grpc::node::Server::Init(exports); grpc::node::CompletionQueueAsyncWorker::Init(exports); grpc::node::Credentials::Init(exports); grpc::node::ServerCredentials::Init(exports); } NODE_MODULE(grpc_node, init) <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld 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 "flusspferd/xml/xml.hpp" #include "flusspferd/xml/context.hpp" #include "flusspferd/xml/parse.hpp" #include "flusspferd/xml/push_parser.hpp" #include "flusspferd/xml/node.hpp" #include "flusspferd/xml/document.hpp" #include "flusspferd/xml/text.hpp" #include "flusspferd/xml/namespace.hpp" #include "flusspferd/xml/reference.hpp" #include "flusspferd/xml/attribute.hpp" #include "flusspferd/xml/processing_instruction.hpp" #include "flusspferd/function_adapter.hpp" #include "flusspferd/local_root_scope.hpp" #include "flusspferd/create.hpp" #include "flusspferd/string.hpp" #include "flusspferd/security.hpp" #include <boost/thread/once.hpp> #include <libxml/xmlIO.h> #include <libxml/xpath.h> using namespace flusspferd; using namespace flusspferd::xml; extern "C" value flusspferd_load(object container) { return load_xml(container); } static void safety_io_callbacks(); static void once() { LIBXML_TEST_VERSION xmlXPathInit(); safety_io_callbacks(); } static boost::once_flag once_flag; object flusspferd::xml::load_xml(object container) { local_root_scope scope; value previous = container.get_property("XML"); if (previous.is_object()) return previous.to_object(); boost::call_once(once_flag, &once); object XML = flusspferd::create_object(); load_class<node>(XML); load_class<document>(XML); load_class<text>(XML); load_class<comment>(XML); load_class<cdata_section>(XML); load_class<reference_>(XML); load_class<processing_instruction>(XML); load_class<attribute_>(XML); load_class<namespace_>(XML); load_class<push_parser>(XML); create_native_function(XML, "parseBlob", &parse_blob); create_native_function(XML, "parseFile", &parse_file); load_class<xml::context>(XML); container.define_property( "XML", XML, object::read_only_property | object::dont_enumerate); return XML; } template<int (*OldMatch)(char const *), unsigned mode> static int safety_match(char const *name) { if (!OldMatch(name)) return 0; std::string path(name); std::size_t nonletter = path.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); if (nonletter != 0 && nonletter != std::string::npos && path[nonletter] == ':') return flusspferd::security::get().check_url(path, mode); else return flusspferd::security::get().check_path(path, mode); } static void safety_io_callbacks() { xmlCleanupInputCallbacks(); xmlCleanupOutputCallbacks(); #define REG_INPUT(name) \ xmlRegisterInputCallbacks( \ safety_match<name ## Match, security::READ>, \ name ## Open, \ name ## Read, \ name ## Close) \ /**/ REG_INPUT(xmlFile); REG_INPUT(xmlIOHTTP); // disable any output xmlRegisterOutputCallbacks(0, 0, 0, 0); } <commit_msg>XML: forgot BOOST_ONCE_INIT<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld 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 "flusspferd/xml/xml.hpp" #include "flusspferd/xml/context.hpp" #include "flusspferd/xml/parse.hpp" #include "flusspferd/xml/push_parser.hpp" #include "flusspferd/xml/node.hpp" #include "flusspferd/xml/document.hpp" #include "flusspferd/xml/text.hpp" #include "flusspferd/xml/namespace.hpp" #include "flusspferd/xml/reference.hpp" #include "flusspferd/xml/attribute.hpp" #include "flusspferd/xml/processing_instruction.hpp" #include "flusspferd/function_adapter.hpp" #include "flusspferd/local_root_scope.hpp" #include "flusspferd/create.hpp" #include "flusspferd/string.hpp" #include "flusspferd/security.hpp" #include <boost/thread/once.hpp> #include <libxml/xmlIO.h> #include <libxml/xpath.h> using namespace flusspferd; using namespace flusspferd::xml; extern "C" value flusspferd_load(object container) { return load_xml(container); } static void safety_io_callbacks(); static void once() { LIBXML_TEST_VERSION xmlXPathInit(); safety_io_callbacks(); } static boost::once_flag once_flag = BOOST_ONCE_INIT; object flusspferd::xml::load_xml(object container) { local_root_scope scope; value previous = container.get_property("XML"); if (previous.is_object()) return previous.to_object(); boost::call_once(once_flag, &once); object XML = flusspferd::create_object(); load_class<node>(XML); load_class<document>(XML); load_class<text>(XML); load_class<comment>(XML); load_class<cdata_section>(XML); load_class<reference_>(XML); load_class<processing_instruction>(XML); load_class<attribute_>(XML); load_class<namespace_>(XML); load_class<push_parser>(XML); create_native_function(XML, "parseBlob", &parse_blob); create_native_function(XML, "parseFile", &parse_file); load_class<xml::context>(XML); container.define_property( "XML", XML, object::read_only_property | object::dont_enumerate); return XML; } template<int (*OldMatch)(char const *), unsigned mode> static int safety_match(char const *name) { if (!OldMatch(name)) return 0; std::string path(name); std::size_t nonletter = path.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); if (nonletter != 0 && nonletter != std::string::npos && path[nonletter] == ':') return flusspferd::security::get().check_url(path, mode); else return flusspferd::security::get().check_path(path, mode); } static void safety_io_callbacks() { xmlCleanupInputCallbacks(); xmlCleanupOutputCallbacks(); #define REG_INPUT(name) \ xmlRegisterInputCallbacks( \ safety_match<name ## Match, security::READ>, \ name ## Open, \ name ## Read, \ name ## Close) \ /**/ REG_INPUT(xmlFile); REG_INPUT(xmlIOHTTP); // disable any output xmlRegisterOutputCallbacks(0, 0, 0, 0); } <|endoftext|>
<commit_before>/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker 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 Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Fermín Galán */ #include <stdint.h> #include <utility> #include <map> #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/string.h" #include "common/globals.h" #include "common/statistics.h" #include "common/sem.h" #include "common/RenderFormat.h" #include "common/defaultValues.h" #include "alarmMgr/alarmMgr.h" #include "mongoBackend/MongoGlobal.h" #include "mongoBackend/TriggeredSubscription.h" #include "mongoBackend/connectionOperations.h" #include "mongoBackend/mongoConnectionPool.h" #include "mongoBackend/safeMongo.h" #include "mongoBackend/dbConstants.h" #include "mongoBackend/MongoCommonRegister.h" /* **************************************************************************** * * USING */ using mongo::BSONArrayBuilder; using mongo::BSONObjBuilder; using mongo::BSONObj; using mongo::BSONElement; using mongo::DBClientBase; using mongo::DBClientCursor; using mongo::OID; /* **************************************************************************** * * processRegisterContext - * * This function has a slightly different behaviour depending on whether the id * parameter is null (new registration case) or not null (update case), in * particular: * * - In the new registration case, the _id is generated and insert() is used to * put the document in the DB. * - In the update case, the _id is set according to the argument 'id' and update() is * used to put the document in the DB. */ HttpStatusCode processRegisterContext ( RegisterContextRequest* requestP, RegisterContextResponse* responseP, OID* id, const std::string& tenant, const std::string& servicePath, const std::string& format, const std::string& fiwareCorrelator ) { std::string err; /* If expiration is not present, then use a default one */ if (requestP->duration.isEmpty()) { requestP->duration.set(DEFAULT_DURATION); } /* Calculate expiration (using the current time and the duration field in the request) */ long long expiration = getCurrentTime() + requestP->duration.parse(); LM_T(LmtMongo, ("Registration expiration: %lu", expiration)); /* Create the mongoDB registration document */ BSONObjBuilder reg; OID oid; if (id == NULL) { oid.init(); } else { oid = *id; } reg.append("_id", oid); reg.append(REG_EXPIRATION, expiration); // FIXME P4: See issue #3078 reg.append(REG_SERVICE_PATH, servicePath.empty() ? SERVICE_PATH_ROOT : servicePath); reg.append(REG_FORMAT, format); BSONArrayBuilder contextRegistration; for (unsigned int ix = 0; ix < requestP->contextRegistrationVector.size(); ++ix) { ContextRegistration* cr = requestP->contextRegistrationVector[ix]; BSONArrayBuilder entities; for (unsigned int jx = 0; jx < cr->entityIdVector.size(); ++jx) { EntityId* en = cr->entityIdVector[jx]; if (en->type.empty()) { entities.append(BSON(REG_ENTITY_ID << en->id)); LM_T(LmtMongo, ("Entity registration: {id: %s}", en->id.c_str())); } else { entities.append(BSON(REG_ENTITY_ID << en->id << REG_ENTITY_TYPE << en->type)); LM_T(LmtMongo, ("Entity registration: {id: %s, type: %s}", en->id.c_str(), en->type.c_str())); } } BSONArrayBuilder attrs; for (unsigned int jx = 0; jx < cr->contextRegistrationAttributeVector.size(); ++jx) { ContextRegistrationAttribute* cra = cr->contextRegistrationAttributeVector[jx]; attrs.append(BSON(REG_ATTRS_NAME << cra->name << REG_ATTRS_TYPE << cra->type)); LM_T(LmtMongo, ("Attribute registration: {name: %s, type: %s}", cra->name.c_str(), cra->type.c_str())); } contextRegistration.append( BSON( REG_ENTITIES << entities.arr() << REG_ATTRS << attrs.arr() << REG_PROVIDING_APPLICATION << requestP->contextRegistrationVector[ix]->providingApplication.get())); LM_T(LmtMongo, ("providingApplication registration: %s", requestP->contextRegistrationVector[ix]->providingApplication.c_str())); } reg.append(REG_CONTEXT_REGISTRATION, contextRegistration.arr()); /* Note that we are using upsert = "true". This means that if the document doesn't previously * exist in the collection, it is created. Thus, this way both uses of registerContext are OK * (either new registration or updating an existing one) */ if (!collectionUpdate(getRegistrationsCollectionName(tenant), BSON("_id" << oid), reg.obj(), true, &err)) { responseP->errorCode.fill(SccReceiverInternalError, err); return SccOk; } // Fill the response element responseP->duration = requestP->duration; responseP->registrationId.set(oid.toString()); responseP->errorCode.fill(SccOk); return SccOk; } <commit_msg>FIX wrongly solved merge conflict<commit_after>/* * * Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker 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. * * Orion Context Broker 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 Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Fermín Galán */ #include <stdint.h> #include <utility> #include <map> #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/string.h" #include "common/globals.h" #include "common/statistics.h" #include "common/sem.h" #include "common/RenderFormat.h" #include "common/defaultValues.h" #include "alarmMgr/alarmMgr.h" #include "mongoBackend/MongoGlobal.h" #include "mongoBackend/TriggeredSubscription.h" #include "mongoBackend/connectionOperations.h" #include "mongoBackend/mongoConnectionPool.h" #include "mongoBackend/safeMongo.h" #include "mongoBackend/dbConstants.h" #include "mongoBackend/MongoCommonRegister.h" /* **************************************************************************** * * USING */ using mongo::BSONArrayBuilder; using mongo::BSONObjBuilder; using mongo::BSONObj; using mongo::BSONElement; using mongo::DBClientBase; using mongo::DBClientCursor; using mongo::OID; /* **************************************************************************** * * processRegisterContext - * * This function has a slightly different behaviour depending on whether the id * parameter is null (new registration case) or not null (update case), in * particular: * * - In the new registration case, the _id is generated and insert() is used to * put the document in the DB. * - In the update case, the _id is set according to the argument 'id' and update() is * used to put the document in the DB. */ HttpStatusCode processRegisterContext ( RegisterContextRequest* requestP, RegisterContextResponse* responseP, OID* id, const std::string& tenant, const std::string& servicePath, const std::string& format, const std::string& fiwareCorrelator ) { std::string err; /* If expiration is not present, then use a default one */ if (requestP->duration.isEmpty()) { requestP->duration.set(DEFAULT_DURATION); } /* Calculate expiration (using the current time and the duration field in the request) */ long long expiration = getCurrentTime() + requestP->duration.parse(); LM_T(LmtMongo, ("Registration expiration: %lu", expiration)); /* Create the mongoDB registration document */ BSONObjBuilder reg; OID oid; if (id == NULL) { oid.init(); } else { oid = *id; } reg.append("_id", oid); reg.append(REG_EXPIRATION, expiration); // FIXME P4: See issue #3078 reg.append(REG_SERVICE_PATH, servicePath.empty() ? SERVICE_PATH_ROOT : servicePath); reg.append(REG_FORMAT, format); // In NGISv1 forwarding mode is always "all" reg.append(REG_FORWARDING_MODE, "all"); BSONArrayBuilder contextRegistration; for (unsigned int ix = 0; ix < requestP->contextRegistrationVector.size(); ++ix) { ContextRegistration* cr = requestP->contextRegistrationVector[ix]; BSONArrayBuilder entities; for (unsigned int jx = 0; jx < cr->entityIdVector.size(); ++jx) { EntityId* en = cr->entityIdVector[jx]; if (en->type.empty()) { entities.append(BSON(REG_ENTITY_ID << en->id)); LM_T(LmtMongo, ("Entity registration: {id: %s}", en->id.c_str())); } else { entities.append(BSON(REG_ENTITY_ID << en->id << REG_ENTITY_TYPE << en->type)); LM_T(LmtMongo, ("Entity registration: {id: %s, type: %s}", en->id.c_str(), en->type.c_str())); } } BSONArrayBuilder attrs; for (unsigned int jx = 0; jx < cr->contextRegistrationAttributeVector.size(); ++jx) { ContextRegistrationAttribute* cra = cr->contextRegistrationAttributeVector[jx]; attrs.append(BSON(REG_ATTRS_NAME << cra->name << REG_ATTRS_TYPE << cra->type)); LM_T(LmtMongo, ("Attribute registration: {name: %s, type: %s}", cra->name.c_str(), cra->type.c_str())); } contextRegistration.append( BSON( REG_ENTITIES << entities.arr() << REG_ATTRS << attrs.arr() << REG_PROVIDING_APPLICATION << requestP->contextRegistrationVector[ix]->providingApplication.get())); LM_T(LmtMongo, ("providingApplication registration: %s", requestP->contextRegistrationVector[ix]->providingApplication.c_str())); } reg.append(REG_CONTEXT_REGISTRATION, contextRegistration.arr()); /* Note that we are using upsert = "true". This means that if the document doesn't previously * exist in the collection, it is created. Thus, this way both uses of registerContext are OK * (either new registration or updating an existing one) */ if (!collectionUpdate(getRegistrationsCollectionName(tenant), BSON("_id" << oid), reg.obj(), true, &err)) { responseP->errorCode.fill(SccReceiverInternalError, err); return SccOk; } // Fill the response element responseP->duration = requestP->duration; responseP->registrationId.set(oid.toString()); responseP->errorCode.fill(SccOk); return SccOk; } <|endoftext|>
<commit_before>#include "amgdata.h" using namespace std; AMGData::AMGData(){ } AMGData::~AMGData(){ } bool AMGData::CreateDBs(){ try{ if(CreateBaseballDB()){ if(CreateStockDB()){ } else{ return false; } } else{ return false; } } catch(exception &e){ return false; } return true; } bool AMGData::CreateBaseballDB(){ try{ string longSQL = "create table if not exists baseball_stats(player_name text primary"; longSQL += "key,games_played integer default '0',average real default '0.00',salary real"; longSQL += "default '0.00')"; AMGSQLite dbSession = AMGSQLite(basePath + "/db/baseball.db"); if(dbSession.RunQuery(longSQL)){ } else{ return false; } dbSession.RunQuery("delete from baseball_stats"); } catch(exception &e){ } return true; } bool AMGData::CreateStockDB(){ try{ string longSQL = "create table if not exists stock_stats(company_name text,ticker text"; longSQL += "primary key,country text,price real default '0.00',exchange_rate real default"; longSQL += "shares_outstanding real default '0.00',net_income real default"; longSQL += "'0.00',market_value real default '0.00',pe_ratio real default '0.00')"; AMGSQLite dbSession = AMGSQLite(basePath + "/db/stocks.db"); if(dbSession.RunQuery(longSQL)){ } else{ return false; } dbSession.RunQuery("delete from stock_stats"); } catch(exception &e){ } return true; } bool AMGData::InsertBaseball(BaseballStatRecord a){ try{ AMGSQLite dbSession = AMGSQLite(basePath + "/db/baseball.db"); string longQuery = "insert into baseball_stats (player_name,games_played, average, salary) values "; longQuery += ("('" + a.name + "','" + to_string(a.games) + "','" + to_string(a.average) + "','" + to_string(a.salary) + "')"); dbSession.RunQuery(longQuery); } catch(exception &e){ return false; } return true; } bool AMGData::InsertStock(StockStatRecord a){ try{ AMGSQLite dbSession = AMGSQLite(basePath + "/db/stocks.db"); string longQuery = "insert into stock_stats (company_name,ticker, country, price, exchange_rate"; longQuery += ",net_income, market_value, pe_ratio) values ('"; longQuery += (a.companyName + "','" + a.name + "','" + a.exchangeCountry + "','" + to_string(a.price) + "','" + to_string(a.exchangeRate) + "','"); longQuery += (to_string(a.netIncome) + "','" + to_string(a.marketValueUsd) + "','" + to_string(a.peRatio) + "')"); dbSession.RunQuery(longQuery); } catch(exception &e){ return false; } return true; } <commit_msg>Fixed shares_outstanding column in stocks database.<commit_after>#include "amgdata.h" using namespace std; AMGData::AMGData(){ } AMGData::~AMGData(){ } bool AMGData::CreateDBs(){ try{ if(CreateBaseballDB()){ if(CreateStockDB()){ } else{ return false; } } else{ return false; } } catch(exception &e){ return false; } return true; } bool AMGData::CreateBaseballDB(){ try{ string longSQL = "create table if not exists baseball_stats(player_name text primary"; longSQL += "key,games_played integer default '0',average real default '0.00',salary real"; longSQL += "default '0.00')"; AMGSQLite dbSession = AMGSQLite(basePath + "/db/baseball.db"); if(dbSession.RunQuery(longSQL)){ } else{ return false; } dbSession.RunQuery("delete from baseball_stats"); } catch(exception &e){ } return true; } bool AMGData::CreateStockDB(){ try{ string longSQL = "create table if not exists stock_stats(company_name text,ticker text"; longSQL += "primary key,country text,price real default '0.00',exchange_rate real default '0.00',"; longSQL += "shares_outstanding real default '0.00',net_income real default"; longSQL += "'0.00',market_value real default '0.00',pe_ratio real default '0.00')"; AMGSQLite dbSession = AMGSQLite(basePath + "/db/stocks.db"); if(dbSession.RunQuery(longSQL)){ } else{ return false; } dbSession.RunQuery("delete from stock_stats"); } catch(exception &e){ } return true; } bool AMGData::InsertBaseball(BaseballStatRecord a){ try{ AMGSQLite dbSession = AMGSQLite(basePath + "/db/baseball.db"); string longQuery = "insert into baseball_stats (player_name,games_played, average, salary) values "; longQuery += ("('" + a.name + "','" + to_string(a.games) + "','" + to_string(a.average) + "','" + to_string(a.salary) + "')"); dbSession.RunQuery(longQuery); } catch(exception &e){ return false; } return true; } bool AMGData::InsertStock(StockStatRecord a){ try{ AMGSQLite dbSession = AMGSQLite(basePath + "/db/stocks.db"); string longQuery = "insert into stock_stats (company_name,ticker, country, price, exchange_rate"; longQuery += ",net_income, market_value, pe_ratio,shares_outstanding) values ('"; longQuery += (a.companyName + "','" + a.name + "','" + a.exchangeCountry + "','" + to_string(a.price) + "','" + to_string(a.exchangeRate) + "','"); longQuery += (to_string(a.netIncome) + "','" + to_string(a.marketValueUsd) + "','" + to_string(a.peRatio) + "' + to_string(a.sharesOutstanding))"); dbSession.RunQuery(longQuery); } catch(exception &e){ return false; } return true; } <|endoftext|>
<commit_before>/* * * Copyright (c) 2020 Project CHIP Authors * * 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 "Server.h" #include <errno.h> #include <utility> #include <lib/dnssd/minimal_mdns/core/DnsHeader.h> namespace mdns { namespace Minimal { namespace { class ShutdownOnError { public: ShutdownOnError(ServerBase * s) : mServer(s) {} ~ShutdownOnError() { if (mServer != nullptr) { mServer->Shutdown(); } } CHIP_ERROR ReturnSuccess() { mServer = nullptr; return CHIP_NO_ERROR; } private: ServerBase * mServer; }; /** * Extracts the Listening UDP Endpoint from an underlying ServerBase::EndpointInfo */ class ListenSocketPickerDelegate : public ServerBase::BroadcastSendDelegate { public: chip::Inet::UDPEndPoint * Accept(ServerBase::EndpointInfo * info) override { return info->mListenUdp; } }; #if CHIP_MINMDNS_USE_EPHEMERAL_UNICAST_PORT /** * Extracts the Querying UDP Endpoint from an underlying ServerBase::EndpointInfo */ class QuerySocketPickerDelegate : public ServerBase::BroadcastSendDelegate { public: chip::Inet::UDPEndPoint * Accept(ServerBase::EndpointInfo * info) override { return info->mUnicastQueryUdp; } }; #else using QuerySocketPickerDelegate = ListenSocketPickerDelegate; #endif /** * Validates that an endpoint belongs to a specific interface/ip address type before forwarding the * endpoint accept logic to another BroadcastSendDelegate. * * Usage like: * * SomeDelegate *child = ....; * InterfaceTypeFilterDelegate filter(interfaceId, IPAddressType::IPv6, child); * * UDPEndPoint *udp = filter.Accept(endpointInfo); */ class InterfaceTypeFilterDelegate : public ServerBase::BroadcastSendDelegate { public: InterfaceTypeFilterDelegate(chip::Inet::InterfaceId interface, chip::Inet::IPAddressType type, ServerBase::BroadcastSendDelegate * child) : mInterface(interface), mAddressType(type), mChild(child) {} chip::Inet::UDPEndPoint * Accept(ServerBase::EndpointInfo * info) override { if ((info->mInterfaceId != mInterface) && (info->mInterfaceId != chip::Inet::InterfaceId::Null())) { return nullptr; } if ((mAddressType != chip::Inet::IPAddressType::kAny) && (info->mAddressType != mAddressType)) { return nullptr; } return mChild->Accept(info); } private: chip::Inet::InterfaceId mInterface; chip::Inet::IPAddressType mAddressType; ServerBase::BroadcastSendDelegate * mChild = nullptr; }; } // namespace namespace BroadcastIpAddresses { // Get standard mDNS Broadcast addresses void GetIpv6Into(chip::Inet::IPAddress & dest) { if (!chip::Inet::IPAddress::FromString("FF02::FB", dest)) { ChipLogError(Discovery, "Failed to parse standard IPv6 broadcast address"); } } void GetIpv4Into(chip::Inet::IPAddress & dest) { if (!chip::Inet::IPAddress::FromString("224.0.0.251", dest)) { ChipLogError(Discovery, "Failed to parse standard IPv4 broadcast address"); } } } // namespace BroadcastIpAddresses namespace { CHIP_ERROR JoinMulticastGroup(chip::Inet::InterfaceId interfaceId, chip::Inet::UDPEndPoint * endpoint, chip::Inet::IPAddressType addressType) { chip::Inet::IPAddress address; if (addressType == chip::Inet::IPAddressType::kIPv6) { BroadcastIpAddresses::GetIpv6Into(address); #if INET_CONFIG_ENABLE_IPV4 } else if (addressType == chip::Inet::IPAddressType::kIPv4) { BroadcastIpAddresses::GetIpv4Into(address); #endif // INET_CONFIG_ENABLE_IPV4 } else { return CHIP_ERROR_INVALID_ARGUMENT; } return endpoint->JoinMulticastGroup(interfaceId, address); } const char * AddressTypeStr(chip::Inet::IPAddressType addressType) { switch (addressType) { case chip::Inet::IPAddressType::kIPv6: return "IPv6"; #if INET_CONFIG_ENABLE_IPV4 case chip::Inet::IPAddressType::kIPv4: return "IPv4"; #endif // INET_CONFIG_ENABLE_IPV4 default: return "UNKNOWN"; } } } // namespace ServerBase::~ServerBase() { Shutdown(); } void ServerBase::Shutdown() { mEndpoints.ForEachActiveObject([&](auto * endpoint) { ShutdownEndpoint(*endpoint); return chip::Loop::Continue; }); } void ServerBase::ShutdownEndpoint(EndpointInfo & aEndpoint) { mEndpoints.ReleaseObject(&aEndpoint); } bool ServerBase::IsListening() const { bool listening = false; mEndpoints.ForEachActiveObject([&](auto * endpoint) { if (endpoint->mListenUdp != nullptr) { listening = true; return chip::Loop::Break; } return chip::Loop::Continue; }); return listening; } CHIP_ERROR ServerBase::Listen(chip::Inet::EndPointManager<chip::Inet::UDPEndPoint> * udpEndPointManager, ListenIterator * it, uint16_t port) { Shutdown(); // ensure everything starts fresh chip::Inet::InterfaceId interfaceId = chip::Inet::InterfaceId::Null(); chip::Inet::IPAddressType addressType; ShutdownOnError autoShutdown(this); while (it->Next(&interfaceId, &addressType)) { chip::Inet::UDPEndPoint * listenUdp; ReturnErrorOnFailure(udpEndPointManager->NewEndPoint(&listenUdp)); std::unique_ptr<chip::Inet::UDPEndPoint, EndpointInfo::EndPointDeletor> endPointHolder(listenUdp, {}); ReturnErrorOnFailure(listenUdp->Bind(addressType, chip::Inet::IPAddress::Any, port, interfaceId)); ReturnErrorOnFailure(listenUdp->Listen(OnUdpPacketReceived, nullptr /*OnReceiveError*/, this)); CHIP_ERROR err = JoinMulticastGroup(interfaceId, listenUdp, addressType); if (err != CHIP_NO_ERROR) { char interfaceName[chip::Inet::InterfaceId::kMaxIfNameLength]; interfaceId.GetInterfaceName(interfaceName, sizeof(interfaceName)); // Log only as non-fatal error. Failure to join will mean we reply to unicast queries only. ChipLogError(DeviceLayer, "MDNS failed to join multicast group on %s for address type %s: %s", interfaceName, AddressTypeStr(addressType), chip::ErrorStr(err)); } #if CHIP_MINMDNS_USE_EPHEMERAL_UNICAST_PORT // Separate UDP endpoint for unicast queries, bound to 0 (i.e. pick random ephemeral port) // - helps in not having conflicts on port 5353, will receive unicast replies directly // - has a *DRAWBACK* of unicast queries being considered LEGACY by mdns since they do // not originate from 5353 and the answers will include a query section. chip::Inet::UDPEndPoint * unicastQueryUdp; ReturnErrorOnFailure(udpEndPointManager->NewEndPoint(&unicastQueryUdp)); std::unique_ptr<chip::Inet::UDPEndPoint, EndpointInfo::EndPointDeletor> endPointHolderUnicast(unicastQueryUdp, {}); ReturnErrorOnFailure(unicastQueryUdp->Bind(addressType, chip::Inet::IPAddress::Any, 0, interfaceId)); ReturnErrorOnFailure(unicastQueryUdp->Listen(OnUdpPacketReceived, nullptr /*OnReceiveError*/, this)); #endif #if CHIP_MINMDNS_USE_EPHEMERAL_UNICAST_PORT if (endPointHolder || endPointHolderUnicast) { // If allocation fails, the rref will not be consumed, so that the endpoint will also be freed correctly mEndpoints.CreateObject(interfaceId, addressType, std::move(endPointHolder), std::move(endPointHolderUnicast)); } #else if (endPointHolder) { // If allocation fails, the rref will not be consumed, so that the endpoint will also be freed correctly mEndpoints.CreateObject(interfaceId, addressType, std::move(endPointHolder)); } #endif } return autoShutdown.ReturnSuccess(); } CHIP_ERROR ServerBase::DirectSend(chip::System::PacketBufferHandle && data, const chip::Inet::IPAddress & addr, uint16_t port, chip::Inet::InterfaceId interface) { CHIP_ERROR err = CHIP_ERROR_NOT_CONNECTED; mEndpoints.ForEachActiveObject([&](auto * info) { if (info->mListenUdp == nullptr) { return chip::Loop::Continue; } if (info->mAddressType != addr.Type()) { return chip::Loop::Continue; } chip::Inet::InterfaceId boundIf = info->mListenUdp->GetBoundInterface(); if ((boundIf.IsPresent()) && (boundIf != interface)) { return chip::Loop::Continue; } err = info->mListenUdp->SendTo(addr, port, std::move(data)); return chip::Loop::Break; }); return err; } CHIP_ERROR ServerBase::BroadcastUnicastQuery(chip::System::PacketBufferHandle && data, uint16_t port) { QuerySocketPickerDelegate socketPicker; return BroadcastImpl(std::move(data), port, &socketPicker); } CHIP_ERROR ServerBase::BroadcastUnicastQuery(chip::System::PacketBufferHandle && data, uint16_t port, chip::Inet::InterfaceId interface, chip::Inet::IPAddressType addressType) { QuerySocketPickerDelegate socketPicker; InterfaceTypeFilterDelegate filter(interface, addressType, &socketPicker); return BroadcastImpl(std::move(data), port, &filter); } CHIP_ERROR ServerBase::BroadcastSend(chip::System::PacketBufferHandle && data, uint16_t port, chip::Inet::InterfaceId interface, chip::Inet::IPAddressType addressType) { ListenSocketPickerDelegate socketPicker; InterfaceTypeFilterDelegate filter(interface, addressType, &socketPicker); return BroadcastImpl(std::move(data), port, &filter); } CHIP_ERROR ServerBase::BroadcastSend(chip::System::PacketBufferHandle && data, uint16_t port) { ListenSocketPickerDelegate socketPicker; return BroadcastImpl(std::move(data), port, &socketPicker); } CHIP_ERROR ServerBase::BroadcastImpl(chip::System::PacketBufferHandle && data, uint16_t port, BroadcastSendDelegate * delegate) { // Broadcast requires sending data multiple times, each of which may error // out, yet broadcast only has a single error code. // // The general logic of error handling is: // - if no send done at all, return error // - if at least one broadcast succeeds, assume success overall // + some internal consistency validations for state error. bool hadSuccesfulSend = false; CHIP_ERROR lastError = CHIP_ERROR_NO_ENDPOINT; if (chip::Loop::Break == mEndpoints.ForEachActiveObject([&](auto * info) { chip::Inet::UDPEndPoint * udp = delegate->Accept(info); if (udp == nullptr) { return chip::Loop::Continue; } CHIP_ERROR err; /// The same packet needs to be sent over potentially multiple interfaces. /// LWIP does not like having a pbuf sent over serparate interfaces, hence we create a copy /// for sending via `CloneData` /// /// TODO: this wastes one copy of the data and that could be optimized away if (info->mAddressType == chip::Inet::IPAddressType::kIPv6) { err = udp->SendTo(mIpv6BroadcastAddress, port, data.CloneData(), udp->GetBoundInterface()); } #if INET_CONFIG_ENABLE_IPV4 else if (info->mAddressType == chip::Inet::IPAddressType::kIPv4) { err = udp->SendTo(mIpv4BroadcastAddress, port, data.CloneData(), udp->GetBoundInterface()); } #endif else { // This is a general error of internal consistency: every address has a known type. Fail completely otherwise. lastError = CHIP_ERROR_INCORRECT_STATE; return chip::Loop::Break; } if (err == CHIP_NO_ERROR) { hadSuccesfulSend = true; } else { ChipLogError(Discovery, "Attempt to mDNS broadcast failed: %s", chip::ErrorStr(err)); lastError = err; } return chip::Loop::Continue; })) { return lastError; } if (!hadSuccesfulSend) { return lastError; } return CHIP_NO_ERROR; } void ServerBase::OnUdpPacketReceived(chip::Inet::UDPEndPoint * endPoint, chip::System::PacketBufferHandle && buffer, const chip::Inet::IPPacketInfo * info) { ServerBase * srv = static_cast<ServerBase *>(endPoint->mAppState); if (!srv->mDelegate) { return; } mdns::Minimal::BytesRange data(buffer->Start(), buffer->Start() + buffer->DataLength()); if (data.Size() < HeaderRef::kSizeBytes) { ChipLogError(Discovery, "Packet to small for mDNS data: %d bytes", static_cast<int>(data.Size())); return; } if (HeaderRef(const_cast<uint8_t *>(data.Start())).GetFlags().IsQuery()) { srv->mDelegate->OnQuery(data, info); } else { srv->mDelegate->OnResponse(data, info); } } } // namespace Minimal } // namespace mdns <commit_msg>Fix mDNS UDP leak when JoinMulticastGroup fails (#13184)<commit_after>/* * * Copyright (c) 2020 Project CHIP Authors * * 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 "Server.h" #include <errno.h> #include <utility> #include <lib/dnssd/minimal_mdns/core/DnsHeader.h> namespace mdns { namespace Minimal { namespace { class ShutdownOnError { public: ShutdownOnError(ServerBase * s) : mServer(s) {} ~ShutdownOnError() { if (mServer != nullptr) { mServer->Shutdown(); } } CHIP_ERROR ReturnSuccess() { mServer = nullptr; return CHIP_NO_ERROR; } private: ServerBase * mServer; }; /** * Extracts the Listening UDP Endpoint from an underlying ServerBase::EndpointInfo */ class ListenSocketPickerDelegate : public ServerBase::BroadcastSendDelegate { public: chip::Inet::UDPEndPoint * Accept(ServerBase::EndpointInfo * info) override { return info->mListenUdp; } }; #if CHIP_MINMDNS_USE_EPHEMERAL_UNICAST_PORT /** * Extracts the Querying UDP Endpoint from an underlying ServerBase::EndpointInfo */ class QuerySocketPickerDelegate : public ServerBase::BroadcastSendDelegate { public: chip::Inet::UDPEndPoint * Accept(ServerBase::EndpointInfo * info) override { return info->mUnicastQueryUdp; } }; #else using QuerySocketPickerDelegate = ListenSocketPickerDelegate; #endif /** * Validates that an endpoint belongs to a specific interface/ip address type before forwarding the * endpoint accept logic to another BroadcastSendDelegate. * * Usage like: * * SomeDelegate *child = ....; * InterfaceTypeFilterDelegate filter(interfaceId, IPAddressType::IPv6, child); * * UDPEndPoint *udp = filter.Accept(endpointInfo); */ class InterfaceTypeFilterDelegate : public ServerBase::BroadcastSendDelegate { public: InterfaceTypeFilterDelegate(chip::Inet::InterfaceId interface, chip::Inet::IPAddressType type, ServerBase::BroadcastSendDelegate * child) : mInterface(interface), mAddressType(type), mChild(child) {} chip::Inet::UDPEndPoint * Accept(ServerBase::EndpointInfo * info) override { if ((info->mInterfaceId != mInterface) && (info->mInterfaceId != chip::Inet::InterfaceId::Null())) { return nullptr; } if ((mAddressType != chip::Inet::IPAddressType::kAny) && (info->mAddressType != mAddressType)) { return nullptr; } return mChild->Accept(info); } private: chip::Inet::InterfaceId mInterface; chip::Inet::IPAddressType mAddressType; ServerBase::BroadcastSendDelegate * mChild = nullptr; }; } // namespace namespace BroadcastIpAddresses { // Get standard mDNS Broadcast addresses void GetIpv6Into(chip::Inet::IPAddress & dest) { if (!chip::Inet::IPAddress::FromString("FF02::FB", dest)) { ChipLogError(Discovery, "Failed to parse standard IPv6 broadcast address"); } } void GetIpv4Into(chip::Inet::IPAddress & dest) { if (!chip::Inet::IPAddress::FromString("224.0.0.251", dest)) { ChipLogError(Discovery, "Failed to parse standard IPv4 broadcast address"); } } } // namespace BroadcastIpAddresses namespace { CHIP_ERROR JoinMulticastGroup(chip::Inet::InterfaceId interfaceId, chip::Inet::UDPEndPoint * endpoint, chip::Inet::IPAddressType addressType) { chip::Inet::IPAddress address; if (addressType == chip::Inet::IPAddressType::kIPv6) { BroadcastIpAddresses::GetIpv6Into(address); #if INET_CONFIG_ENABLE_IPV4 } else if (addressType == chip::Inet::IPAddressType::kIPv4) { BroadcastIpAddresses::GetIpv4Into(address); #endif // INET_CONFIG_ENABLE_IPV4 } else { return CHIP_ERROR_INVALID_ARGUMENT; } return endpoint->JoinMulticastGroup(interfaceId, address); } const char * AddressTypeStr(chip::Inet::IPAddressType addressType) { switch (addressType) { case chip::Inet::IPAddressType::kIPv6: return "IPv6"; #if INET_CONFIG_ENABLE_IPV4 case chip::Inet::IPAddressType::kIPv4: return "IPv4"; #endif // INET_CONFIG_ENABLE_IPV4 default: return "UNKNOWN"; } } } // namespace ServerBase::~ServerBase() { Shutdown(); } void ServerBase::Shutdown() { mEndpoints.ForEachActiveObject([&](auto * endpoint) { ShutdownEndpoint(*endpoint); return chip::Loop::Continue; }); } void ServerBase::ShutdownEndpoint(EndpointInfo & aEndpoint) { mEndpoints.ReleaseObject(&aEndpoint); } bool ServerBase::IsListening() const { bool listening = false; mEndpoints.ForEachActiveObject([&](auto * endpoint) { if (endpoint->mListenUdp != nullptr) { listening = true; return chip::Loop::Break; } return chip::Loop::Continue; }); return listening; } CHIP_ERROR ServerBase::Listen(chip::Inet::EndPointManager<chip::Inet::UDPEndPoint> * udpEndPointManager, ListenIterator * it, uint16_t port) { Shutdown(); // ensure everything starts fresh chip::Inet::InterfaceId interfaceId = chip::Inet::InterfaceId::Null(); chip::Inet::IPAddressType addressType; ShutdownOnError autoShutdown(this); while (it->Next(&interfaceId, &addressType)) { chip::Inet::UDPEndPoint * listenUdp; ReturnErrorOnFailure(udpEndPointManager->NewEndPoint(&listenUdp)); std::unique_ptr<chip::Inet::UDPEndPoint, EndpointInfo::EndPointDeletor> endPointHolder(listenUdp, {}); ReturnErrorOnFailure(listenUdp->Bind(addressType, chip::Inet::IPAddress::Any, port, interfaceId)); ReturnErrorOnFailure(listenUdp->Listen(OnUdpPacketReceived, nullptr /*OnReceiveError*/, this)); CHIP_ERROR err = JoinMulticastGroup(interfaceId, listenUdp, addressType); if (err != CHIP_NO_ERROR) { char interfaceName[chip::Inet::InterfaceId::kMaxIfNameLength]; interfaceId.GetInterfaceName(interfaceName, sizeof(interfaceName)); // Log only as non-fatal error. Failure to join will mean we reply to unicast queries only. ChipLogError(DeviceLayer, "MDNS failed to join multicast group on %s for address type %s: %s", interfaceName, AddressTypeStr(addressType), chip::ErrorStr(err)); endPointHolder.reset(); } #if CHIP_MINMDNS_USE_EPHEMERAL_UNICAST_PORT // Separate UDP endpoint for unicast queries, bound to 0 (i.e. pick random ephemeral port) // - helps in not having conflicts on port 5353, will receive unicast replies directly // - has a *DRAWBACK* of unicast queries being considered LEGACY by mdns since they do // not originate from 5353 and the answers will include a query section. chip::Inet::UDPEndPoint * unicastQueryUdp; ReturnErrorOnFailure(udpEndPointManager->NewEndPoint(&unicastQueryUdp)); std::unique_ptr<chip::Inet::UDPEndPoint, EndpointInfo::EndPointDeletor> endPointHolderUnicast(unicastQueryUdp, {}); ReturnErrorOnFailure(unicastQueryUdp->Bind(addressType, chip::Inet::IPAddress::Any, 0, interfaceId)); ReturnErrorOnFailure(unicastQueryUdp->Listen(OnUdpPacketReceived, nullptr /*OnReceiveError*/, this)); #endif #if CHIP_MINMDNS_USE_EPHEMERAL_UNICAST_PORT if (endPointHolder || endPointHolderUnicast) { // If allocation fails, the rref will not be consumed, so that the endpoint will also be freed correctly mEndpoints.CreateObject(interfaceId, addressType, std::move(endPointHolder), std::move(endPointHolderUnicast)); } #else if (endPointHolder) { // If allocation fails, the rref will not be consumed, so that the endpoint will also be freed correctly mEndpoints.CreateObject(interfaceId, addressType, std::move(endPointHolder)); } #endif } return autoShutdown.ReturnSuccess(); } CHIP_ERROR ServerBase::DirectSend(chip::System::PacketBufferHandle && data, const chip::Inet::IPAddress & addr, uint16_t port, chip::Inet::InterfaceId interface) { CHIP_ERROR err = CHIP_ERROR_NOT_CONNECTED; mEndpoints.ForEachActiveObject([&](auto * info) { if (info->mListenUdp == nullptr) { return chip::Loop::Continue; } if (info->mAddressType != addr.Type()) { return chip::Loop::Continue; } chip::Inet::InterfaceId boundIf = info->mListenUdp->GetBoundInterface(); if ((boundIf.IsPresent()) && (boundIf != interface)) { return chip::Loop::Continue; } err = info->mListenUdp->SendTo(addr, port, std::move(data)); return chip::Loop::Break; }); return err; } CHIP_ERROR ServerBase::BroadcastUnicastQuery(chip::System::PacketBufferHandle && data, uint16_t port) { QuerySocketPickerDelegate socketPicker; return BroadcastImpl(std::move(data), port, &socketPicker); } CHIP_ERROR ServerBase::BroadcastUnicastQuery(chip::System::PacketBufferHandle && data, uint16_t port, chip::Inet::InterfaceId interface, chip::Inet::IPAddressType addressType) { QuerySocketPickerDelegate socketPicker; InterfaceTypeFilterDelegate filter(interface, addressType, &socketPicker); return BroadcastImpl(std::move(data), port, &filter); } CHIP_ERROR ServerBase::BroadcastSend(chip::System::PacketBufferHandle && data, uint16_t port, chip::Inet::InterfaceId interface, chip::Inet::IPAddressType addressType) { ListenSocketPickerDelegate socketPicker; InterfaceTypeFilterDelegate filter(interface, addressType, &socketPicker); return BroadcastImpl(std::move(data), port, &filter); } CHIP_ERROR ServerBase::BroadcastSend(chip::System::PacketBufferHandle && data, uint16_t port) { ListenSocketPickerDelegate socketPicker; return BroadcastImpl(std::move(data), port, &socketPicker); } CHIP_ERROR ServerBase::BroadcastImpl(chip::System::PacketBufferHandle && data, uint16_t port, BroadcastSendDelegate * delegate) { // Broadcast requires sending data multiple times, each of which may error // out, yet broadcast only has a single error code. // // The general logic of error handling is: // - if no send done at all, return error // - if at least one broadcast succeeds, assume success overall // + some internal consistency validations for state error. bool hadSuccesfulSend = false; CHIP_ERROR lastError = CHIP_ERROR_NO_ENDPOINT; if (chip::Loop::Break == mEndpoints.ForEachActiveObject([&](auto * info) { chip::Inet::UDPEndPoint * udp = delegate->Accept(info); if (udp == nullptr) { return chip::Loop::Continue; } CHIP_ERROR err; /// The same packet needs to be sent over potentially multiple interfaces. /// LWIP does not like having a pbuf sent over serparate interfaces, hence we create a copy /// for sending via `CloneData` /// /// TODO: this wastes one copy of the data and that could be optimized away if (info->mAddressType == chip::Inet::IPAddressType::kIPv6) { err = udp->SendTo(mIpv6BroadcastAddress, port, data.CloneData(), udp->GetBoundInterface()); } #if INET_CONFIG_ENABLE_IPV4 else if (info->mAddressType == chip::Inet::IPAddressType::kIPv4) { err = udp->SendTo(mIpv4BroadcastAddress, port, data.CloneData(), udp->GetBoundInterface()); } #endif else { // This is a general error of internal consistency: every address has a known type. Fail completely otherwise. lastError = CHIP_ERROR_INCORRECT_STATE; return chip::Loop::Break; } if (err == CHIP_NO_ERROR) { hadSuccesfulSend = true; } else { ChipLogError(Discovery, "Attempt to mDNS broadcast failed: %s", chip::ErrorStr(err)); lastError = err; } return chip::Loop::Continue; })) { return lastError; } if (!hadSuccesfulSend) { return lastError; } return CHIP_NO_ERROR; } void ServerBase::OnUdpPacketReceived(chip::Inet::UDPEndPoint * endPoint, chip::System::PacketBufferHandle && buffer, const chip::Inet::IPPacketInfo * info) { ServerBase * srv = static_cast<ServerBase *>(endPoint->mAppState); if (!srv->mDelegate) { return; } mdns::Minimal::BytesRange data(buffer->Start(), buffer->Start() + buffer->DataLength()); if (data.Size() < HeaderRef::kSizeBytes) { ChipLogError(Discovery, "Packet to small for mDNS data: %d bytes", static_cast<int>(data.Size())); return; } if (HeaderRef(const_cast<uint8_t *>(data.Start())).GetFlags().IsQuery()) { srv->mDelegate->OnQuery(data, info); } else { srv->mDelegate->OnResponse(data, info); } } } // namespace Minimal } // namespace mdns <|endoftext|>
<commit_before>//===--- HTMLDiagnostics.cpp - HTML Diagnostics for Paths ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the HTMLDiagnostics object. // //===----------------------------------------------------------------------===// #include "clang/Driver/HTMLDiagnostics.h" #include "clang/Analysis/PathDiagnostic.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/FileManager.h" #include "clang/Rewrite/Rewriter.h" #include "clang/Rewrite/HTMLRewrite.h" #include "clang/Lex/Lexer.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Streams.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include <fstream> using namespace clang; //===----------------------------------------------------------------------===// // Boilerplate. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN HTMLDiagnostics : public PathDiagnosticClient { llvm::sys::Path Directory, FilePrefix; bool createdDir, noDir; Preprocessor* PP; PreprocessorFactory* PPF; std::vector<const PathDiagnostic*> BatchedDiags; public: HTMLDiagnostics(const std::string& prefix, Preprocessor* pp, PreprocessorFactory* ppf); virtual ~HTMLDiagnostics(); virtual void HandlePathDiagnostic(const PathDiagnostic* D); void HandlePiece(Rewriter& R, unsigned BugFileID, const PathDiagnosticPiece& P, unsigned num, unsigned max); void HighlightRange(Rewriter& R, unsigned BugFileID, SourceRange Range); void ReportDiag(const PathDiagnostic& D); }; } // end anonymous namespace HTMLDiagnostics::HTMLDiagnostics(const std::string& prefix, Preprocessor* pp, PreprocessorFactory* ppf) : Directory(prefix), FilePrefix(prefix), createdDir(false), noDir(false), PP(pp), PPF(ppf) { // All html files begin with "report" FilePrefix.appendComponent("report"); } PathDiagnosticClient* clang::CreateHTMLDiagnosticClient(const std::string& prefix, Preprocessor* PP, PreprocessorFactory* PPF) { return new HTMLDiagnostics(prefix, PP, PPF); } //===----------------------------------------------------------------------===// // Report processing. //===----------------------------------------------------------------------===// void HTMLDiagnostics::HandlePathDiagnostic(const PathDiagnostic* D) { if (!D) return; if (D->empty()) { delete D; return; } BatchedDiags.push_back(D); } HTMLDiagnostics::~HTMLDiagnostics() { while (!BatchedDiags.empty()) { const PathDiagnostic* D = BatchedDiags.back(); BatchedDiags.pop_back(); ReportDiag(*D); delete D; } } void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) { // Create the HTML directory if it is missing. if (!createdDir) { createdDir = true; std::string ErrorMsg; Directory.createDirectoryOnDisk(true, &ErrorMsg); if (!Directory.isDirectory()) { llvm::cerr << "warning: could not create directory '" << Directory.toString() << "'\n" << "reason: " << ErrorMsg << '\n'; noDir = true; return; } } if (noDir) return; SourceManager& SMgr = D.begin()->getLocation().getManager(); unsigned FileID = 0; bool FileIDInitialized = false; // Verify that the entire path is from the same FileID. for (PathDiagnostic::const_iterator I=D.begin(), E=D.end(); I != E; ++I) { FullSourceLoc L = I->getLocation(); if (!L.isFileID()) return; // FIXME: Emit a warning? if (!FileIDInitialized) { FileID = L.getCanonicalFileID(); FileIDInitialized = true; } else if (L.getCanonicalFileID() != FileID) return; // FIXME: Emit a warning? // Check the source ranges. for (PathDiagnosticPiece::range_iterator RI=I->ranges_begin(), RE=I->ranges_end(); RI!=RE; ++RI) { SourceLocation L = RI->getBegin(); if (!L.isFileID()) return; // FIXME: Emit a warning? if (SMgr.getCanonicalFileID(L) != FileID) return; // FIXME: Emit a warning? L = RI->getEnd(); if (!L.isFileID()) return; // FIXME: Emit a warning? if (SMgr.getCanonicalFileID(L) != FileID) return; // FIXME: Emit a warning? } } if (!FileIDInitialized) return; // FIXME: Emit a warning? // Create a new rewriter to generate HTML. Rewriter R(SMgr); // Process the path. unsigned n = D.size(); unsigned max = n; for (PathDiagnostic::const_reverse_iterator I=D.rbegin(), E=D.rend(); I!=E; ++I, --n) { HandlePiece(R, FileID, *I, n, max); } // Add line numbers, header, footer, etc. // unsigned FileID = R.getSourceMgr().getMainFileID(); html::EscapeText(R, FileID); html::AddLineNumbers(R, FileID); // If we have a preprocessor, relex the file and syntax highlight. // We might not have a preprocessor if we come from a deserialized AST file, // for example. if (PP) html::SyntaxHighlight(R, FileID, *PP); // FIXME: We eventually want to use PPF to create a fresh Preprocessor, // once we have worked out the bugs. // // if (PPF) html::HighlightMacros(R, FileID, *PPF); // if (PP) html::HighlightMacros(R, FileID, *PP); // Get the full directory name of the analyzed file. const FileEntry* Entry = SMgr.getFileEntryForID(FileID); // This is a cludge; basically we want to append either the full // working directory if we have no directory information. This is // a work in progress. std::string DirName = ""; if (!llvm::sys::Path(Entry->getName()).isAbsolute()) { llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory(); DirName = P.toString() + "/"; } // Add the name of the file as an <h1> tag. { std::string s; llvm::raw_string_ostream os(s); os << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n" "<tr><td class=\"rowname\">File:</td><td>" << html::EscapeText(DirName) << html::EscapeText(Entry->getName()) << "</td></tr>\n<tr><td class=\"rowname\">Location:</td><td>" "<a href=\"#EndPath\">line " << (*D.rbegin()).getLocation().getLogicalLineNumber() << ", column " << (*D.rbegin()).getLocation().getLogicalColumnNumber() << "</a></td></tr>\n" "<tr><td class=\"rowname\">Description:</td><td>" << D.getDescription() << "</td></tr>\n"; // Output any other meta data. for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end(); I!=E; ++I) { os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n"; } os << "</table>\n<h3>Annotated Source Code</h3>\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } // Embed meta-data tags. const std::string& BugDesc = D.getDescription(); if (!BugDesc.empty()) { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGDESC " << BugDesc << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } const std::string& BugCategory = D.getCategory(); if (!BugCategory.empty()) { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGLINE " << D.back()->getLocation().getLogicalLineNumber() << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGPATHLENGTH " << D.size() << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } // Add CSS, header, and footer. html::AddHeaderFooterInternalBuiltinCSS(R, FileID, Entry->getName()); // Get the rewrite buffer. const RewriteBuffer *Buf = R.getRewriteBufferFor(FileID); if (!Buf) { llvm::cerr << "warning: no diagnostics generated for main file.\n"; return; } // Create the stream to write out the HTML. std::ofstream os; { // Create a path for the target HTML file. llvm::sys::Path F(FilePrefix); F.makeUnique(false, NULL); // Rename the file with an HTML extension. llvm::sys::Path H(F); H.appendSuffix("html"); F.renamePathOnDisk(H, NULL); os.open(H.toString().c_str()); if (!os) { llvm::cerr << "warning: could not create file '" << F.toString() << "'\n"; return; } } // Emit the HTML to disk. for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I) os << *I; } void HTMLDiagnostics::HandlePiece(Rewriter& R, unsigned BugFileID, const PathDiagnosticPiece& P, unsigned num, unsigned max) { // For now, just draw a box above the line in question, and emit the // warning. FullSourceLoc Pos = P.getLocation(); if (!Pos.isValid()) return; SourceManager& SM = R.getSourceMgr(); FullSourceLoc LPos = Pos.getLogicalLoc(); unsigned FileID = SM.getCanonicalFileID(LPos.getLocation()); assert (&LPos.getManager() == &SM && "SourceManagers are different!"); if (LPos.getCanonicalFileID() != BugFileID) return; const llvm::MemoryBuffer *Buf = SM.getBuffer(FileID); const char* FileStart = Buf->getBufferStart(); // Compute the column number. Rewind from the current position to the start // of the line. unsigned ColNo = LPos.getColumnNumber(); const char *TokLogicalPtr = LPos.getCharacterData(); const char *LineStart = TokLogicalPtr-ColNo; // Only compute LineEnd if we display below a line. const char *LineEnd = TokLogicalPtr; if (P.getDisplayHint() == PathDiagnosticPiece::Below) { const char* FileEnd = Buf->getBufferEnd(); while (*LineEnd != '\n' && LineEnd != FileEnd) ++LineEnd; } // Compute the margin offset by counting tabs and non-tabs. unsigned PosNo = 0; for (const char* c = LineStart; c != TokLogicalPtr; ++c) PosNo += *c == '\t' ? 8 : 1; // Create the html for the message. { // Get the string and determining its maximum substring. const std::string& Msg = P.getString(); unsigned max_token = 0; unsigned cnt = 0; unsigned len = Msg.size(); for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I) switch (*I) { default: ++cnt; continue; case ' ': case '\t': case '\n': if (cnt > max_token) max_token = cnt; cnt = 0; } if (cnt > max_token) max_token = cnt; // Next, determine the approximate size of the message bubble in em. unsigned em; const unsigned max_line = 80; if (max_token >= max_line) em = max_token / 2; else { unsigned characters = max_line; unsigned lines = len / max_line; if (lines > 0) { for (; characters > max_token; --characters) if (len / characters > lines) { ++characters; break; } } em = characters / 2; } // Now generate the message bubble. std::string s; llvm::raw_string_ostream os(s); os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\""; if (num == max) os << "EndPath"; else os << "Path" << num; os << "\" class=\"msg\" style=\"margin-left:" << PosNo << "ex"; if (em < max_line/2) os << "; max-width:" << em << "em"; os << "\">"; if (max > 1) os << "<span class=\"PathIndex\">[" << num << "]</span> "; os << html::EscapeText(Msg) << "</div></td></tr>"; // Insert the new html. unsigned DisplayPos = 0; switch (P.getDisplayHint()) { case PathDiagnosticPiece::Above: DisplayPos = LineStart - FileStart; break; case PathDiagnosticPiece::Below: DisplayPos = LineEnd - FileStart; break; default: assert (false && "Unhandled hint."); } R.InsertStrBefore(SourceLocation::getFileLoc(FileID, DisplayPos), os.str()); } // Now highlight the ranges. for (const SourceRange *I = P.ranges_begin(), *E = P.ranges_end(); I != E; ++I) HighlightRange(R, FileID, *I); } void HTMLDiagnostics::HighlightRange(Rewriter& R, unsigned BugFileID, SourceRange Range) { SourceManager& SM = R.getSourceMgr(); SourceLocation LogicalStart = SM.getLogicalLoc(Range.getBegin()); unsigned StartLineNo = SM.getLineNumber(LogicalStart); SourceLocation LogicalEnd = SM.getLogicalLoc(Range.getEnd()); unsigned EndLineNo = SM.getLineNumber(LogicalEnd); if (EndLineNo < StartLineNo) return; if (SM.getCanonicalFileID(LogicalStart) != BugFileID || SM.getCanonicalFileID(LogicalEnd) != BugFileID) return; // Compute the column number of the end. unsigned EndColNo = SM.getColumnNumber(LogicalEnd); unsigned OldEndColNo = EndColNo; if (EndColNo) { // Add in the length of the token, so that we cover multi-char tokens. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM) - 1; } // Highlight the range. Make the span tag the outermost tag for the // selected range. SourceLocation E = LogicalEnd.getFileLocWithOffset(EndColNo - OldEndColNo); html::HighlightRange(R, LogicalStart, E, "<span class=\"mrange\">", "</span>"); } <commit_msg>Output "REPORTHEADER" and "REPORTSUMMARYEXTRA" tags for use with scan-view.<commit_after>//===--- HTMLDiagnostics.cpp - HTML Diagnostics for Paths ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the HTMLDiagnostics object. // //===----------------------------------------------------------------------===// #include "clang/Driver/HTMLDiagnostics.h" #include "clang/Analysis/PathDiagnostic.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/FileManager.h" #include "clang/Rewrite/Rewriter.h" #include "clang/Rewrite/HTMLRewrite.h" #include "clang/Lex/Lexer.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Streams.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Path.h" #include <fstream> using namespace clang; //===----------------------------------------------------------------------===// // Boilerplate. //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN HTMLDiagnostics : public PathDiagnosticClient { llvm::sys::Path Directory, FilePrefix; bool createdDir, noDir; Preprocessor* PP; PreprocessorFactory* PPF; std::vector<const PathDiagnostic*> BatchedDiags; public: HTMLDiagnostics(const std::string& prefix, Preprocessor* pp, PreprocessorFactory* ppf); virtual ~HTMLDiagnostics(); virtual void HandlePathDiagnostic(const PathDiagnostic* D); void HandlePiece(Rewriter& R, unsigned BugFileID, const PathDiagnosticPiece& P, unsigned num, unsigned max); void HighlightRange(Rewriter& R, unsigned BugFileID, SourceRange Range); void ReportDiag(const PathDiagnostic& D); }; } // end anonymous namespace HTMLDiagnostics::HTMLDiagnostics(const std::string& prefix, Preprocessor* pp, PreprocessorFactory* ppf) : Directory(prefix), FilePrefix(prefix), createdDir(false), noDir(false), PP(pp), PPF(ppf) { // All html files begin with "report" FilePrefix.appendComponent("report"); } PathDiagnosticClient* clang::CreateHTMLDiagnosticClient(const std::string& prefix, Preprocessor* PP, PreprocessorFactory* PPF) { return new HTMLDiagnostics(prefix, PP, PPF); } //===----------------------------------------------------------------------===// // Report processing. //===----------------------------------------------------------------------===// void HTMLDiagnostics::HandlePathDiagnostic(const PathDiagnostic* D) { if (!D) return; if (D->empty()) { delete D; return; } BatchedDiags.push_back(D); } HTMLDiagnostics::~HTMLDiagnostics() { while (!BatchedDiags.empty()) { const PathDiagnostic* D = BatchedDiags.back(); BatchedDiags.pop_back(); ReportDiag(*D); delete D; } } void HTMLDiagnostics::ReportDiag(const PathDiagnostic& D) { // Create the HTML directory if it is missing. if (!createdDir) { createdDir = true; std::string ErrorMsg; Directory.createDirectoryOnDisk(true, &ErrorMsg); if (!Directory.isDirectory()) { llvm::cerr << "warning: could not create directory '" << Directory.toString() << "'\n" << "reason: " << ErrorMsg << '\n'; noDir = true; return; } } if (noDir) return; SourceManager& SMgr = D.begin()->getLocation().getManager(); unsigned FileID = 0; bool FileIDInitialized = false; // Verify that the entire path is from the same FileID. for (PathDiagnostic::const_iterator I=D.begin(), E=D.end(); I != E; ++I) { FullSourceLoc L = I->getLocation(); if (!L.isFileID()) return; // FIXME: Emit a warning? if (!FileIDInitialized) { FileID = L.getCanonicalFileID(); FileIDInitialized = true; } else if (L.getCanonicalFileID() != FileID) return; // FIXME: Emit a warning? // Check the source ranges. for (PathDiagnosticPiece::range_iterator RI=I->ranges_begin(), RE=I->ranges_end(); RI!=RE; ++RI) { SourceLocation L = RI->getBegin(); if (!L.isFileID()) return; // FIXME: Emit a warning? if (SMgr.getCanonicalFileID(L) != FileID) return; // FIXME: Emit a warning? L = RI->getEnd(); if (!L.isFileID()) return; // FIXME: Emit a warning? if (SMgr.getCanonicalFileID(L) != FileID) return; // FIXME: Emit a warning? } } if (!FileIDInitialized) return; // FIXME: Emit a warning? // Create a new rewriter to generate HTML. Rewriter R(SMgr); // Process the path. unsigned n = D.size(); unsigned max = n; for (PathDiagnostic::const_reverse_iterator I=D.rbegin(), E=D.rend(); I!=E; ++I, --n) { HandlePiece(R, FileID, *I, n, max); } // Add line numbers, header, footer, etc. // unsigned FileID = R.getSourceMgr().getMainFileID(); html::EscapeText(R, FileID); html::AddLineNumbers(R, FileID); // If we have a preprocessor, relex the file and syntax highlight. // We might not have a preprocessor if we come from a deserialized AST file, // for example. if (PP) html::SyntaxHighlight(R, FileID, *PP); // FIXME: We eventually want to use PPF to create a fresh Preprocessor, // once we have worked out the bugs. // // if (PPF) html::HighlightMacros(R, FileID, *PPF); // if (PP) html::HighlightMacros(R, FileID, *PP); // Get the full directory name of the analyzed file. const FileEntry* Entry = SMgr.getFileEntryForID(FileID); // This is a cludge; basically we want to append either the full // working directory if we have no directory information. This is // a work in progress. std::string DirName = ""; if (!llvm::sys::Path(Entry->getName()).isAbsolute()) { llvm::sys::Path P = llvm::sys::Path::GetCurrentDirectory(); DirName = P.toString() + "/"; } // Add the name of the file as an <h1> tag. { std::string s; llvm::raw_string_ostream os(s); os << "<!-- REPORTHEADER -->\n" << "<h3>Bug Summary</h3>\n<table class=\"simpletable\">\n" "<tr><td class=\"rowname\">File:</td><td>" << html::EscapeText(DirName) << html::EscapeText(Entry->getName()) << "</td></tr>\n<tr><td class=\"rowname\">Location:</td><td>" "<a href=\"#EndPath\">line " << (*D.rbegin()).getLocation().getLogicalLineNumber() << ", column " << (*D.rbegin()).getLocation().getLogicalColumnNumber() << "</a></td></tr>\n" "<tr><td class=\"rowname\">Description:</td><td>" << D.getDescription() << "</td></tr>\n"; // Output any other meta data. for (PathDiagnostic::meta_iterator I=D.meta_begin(), E=D.meta_end(); I!=E; ++I) { os << "<tr><td></td><td>" << html::EscapeText(*I) << "</td></tr>\n"; } os << "</table>\n<!-- REPORTSUMMARYEXTRA -->\n" "<h3>Annotated Source Code</h3>\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } // Embed meta-data tags. const std::string& BugDesc = D.getDescription(); if (!BugDesc.empty()) { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGDESC " << BugDesc << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } const std::string& BugCategory = D.getCategory(); if (!BugCategory.empty()) { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGCATEGORY " << BugCategory << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGFILE " << DirName << Entry->getName() << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGLINE " << D.back()->getLocation().getLogicalLineNumber() << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } { std::string s; llvm::raw_string_ostream os(s); os << "\n<!-- BUGPATHLENGTH " << D.size() << " -->\n"; R.InsertStrBefore(SourceLocation::getFileLoc(FileID, 0), os.str()); } // Add CSS, header, and footer. html::AddHeaderFooterInternalBuiltinCSS(R, FileID, Entry->getName()); // Get the rewrite buffer. const RewriteBuffer *Buf = R.getRewriteBufferFor(FileID); if (!Buf) { llvm::cerr << "warning: no diagnostics generated for main file.\n"; return; } // Create the stream to write out the HTML. std::ofstream os; { // Create a path for the target HTML file. llvm::sys::Path F(FilePrefix); F.makeUnique(false, NULL); // Rename the file with an HTML extension. llvm::sys::Path H(F); H.appendSuffix("html"); F.renamePathOnDisk(H, NULL); os.open(H.toString().c_str()); if (!os) { llvm::cerr << "warning: could not create file '" << F.toString() << "'\n"; return; } } // Emit the HTML to disk. for (RewriteBuffer::iterator I = Buf->begin(), E = Buf->end(); I!=E; ++I) os << *I; } void HTMLDiagnostics::HandlePiece(Rewriter& R, unsigned BugFileID, const PathDiagnosticPiece& P, unsigned num, unsigned max) { // For now, just draw a box above the line in question, and emit the // warning. FullSourceLoc Pos = P.getLocation(); if (!Pos.isValid()) return; SourceManager& SM = R.getSourceMgr(); FullSourceLoc LPos = Pos.getLogicalLoc(); unsigned FileID = SM.getCanonicalFileID(LPos.getLocation()); assert (&LPos.getManager() == &SM && "SourceManagers are different!"); if (LPos.getCanonicalFileID() != BugFileID) return; const llvm::MemoryBuffer *Buf = SM.getBuffer(FileID); const char* FileStart = Buf->getBufferStart(); // Compute the column number. Rewind from the current position to the start // of the line. unsigned ColNo = LPos.getColumnNumber(); const char *TokLogicalPtr = LPos.getCharacterData(); const char *LineStart = TokLogicalPtr-ColNo; // Only compute LineEnd if we display below a line. const char *LineEnd = TokLogicalPtr; if (P.getDisplayHint() == PathDiagnosticPiece::Below) { const char* FileEnd = Buf->getBufferEnd(); while (*LineEnd != '\n' && LineEnd != FileEnd) ++LineEnd; } // Compute the margin offset by counting tabs and non-tabs. unsigned PosNo = 0; for (const char* c = LineStart; c != TokLogicalPtr; ++c) PosNo += *c == '\t' ? 8 : 1; // Create the html for the message. { // Get the string and determining its maximum substring. const std::string& Msg = P.getString(); unsigned max_token = 0; unsigned cnt = 0; unsigned len = Msg.size(); for (std::string::const_iterator I=Msg.begin(), E=Msg.end(); I!=E; ++I) switch (*I) { default: ++cnt; continue; case ' ': case '\t': case '\n': if (cnt > max_token) max_token = cnt; cnt = 0; } if (cnt > max_token) max_token = cnt; // Next, determine the approximate size of the message bubble in em. unsigned em; const unsigned max_line = 80; if (max_token >= max_line) em = max_token / 2; else { unsigned characters = max_line; unsigned lines = len / max_line; if (lines > 0) { for (; characters > max_token; --characters) if (len / characters > lines) { ++characters; break; } } em = characters / 2; } // Now generate the message bubble. std::string s; llvm::raw_string_ostream os(s); os << "\n<tr><td class=\"num\"></td><td class=\"line\"><div id=\""; if (num == max) os << "EndPath"; else os << "Path" << num; os << "\" class=\"msg\" style=\"margin-left:" << PosNo << "ex"; if (em < max_line/2) os << "; max-width:" << em << "em"; os << "\">"; if (max > 1) os << "<span class=\"PathIndex\">[" << num << "]</span> "; os << html::EscapeText(Msg) << "</div></td></tr>"; // Insert the new html. unsigned DisplayPos = 0; switch (P.getDisplayHint()) { case PathDiagnosticPiece::Above: DisplayPos = LineStart - FileStart; break; case PathDiagnosticPiece::Below: DisplayPos = LineEnd - FileStart; break; default: assert (false && "Unhandled hint."); } R.InsertStrBefore(SourceLocation::getFileLoc(FileID, DisplayPos), os.str()); } // Now highlight the ranges. for (const SourceRange *I = P.ranges_begin(), *E = P.ranges_end(); I != E; ++I) HighlightRange(R, FileID, *I); } void HTMLDiagnostics::HighlightRange(Rewriter& R, unsigned BugFileID, SourceRange Range) { SourceManager& SM = R.getSourceMgr(); SourceLocation LogicalStart = SM.getLogicalLoc(Range.getBegin()); unsigned StartLineNo = SM.getLineNumber(LogicalStart); SourceLocation LogicalEnd = SM.getLogicalLoc(Range.getEnd()); unsigned EndLineNo = SM.getLineNumber(LogicalEnd); if (EndLineNo < StartLineNo) return; if (SM.getCanonicalFileID(LogicalStart) != BugFileID || SM.getCanonicalFileID(LogicalEnd) != BugFileID) return; // Compute the column number of the end. unsigned EndColNo = SM.getColumnNumber(LogicalEnd); unsigned OldEndColNo = EndColNo; if (EndColNo) { // Add in the length of the token, so that we cover multi-char tokens. EndColNo += Lexer::MeasureTokenLength(Range.getEnd(), SM) - 1; } // Highlight the range. Make the span tag the outermost tag for the // selected range. SourceLocation E = LogicalEnd.getFileLocWithOffset(EndColNo - OldEndColNo); html::HighlightRange(R, LogicalStart, E, "<span class=\"mrange\">", "</span>"); } <|endoftext|>
<commit_before>// @file irc.cpp // @brief Implementation of the IRC class, which implements the // User, Message and Chat abstract classes. // #include <sstream> // std::stringstream #include "irc.h" std::deque<std::string> Split(std::string pretext, char delim) { std::deque<std::string> sans_delim; std::string tokens; std::stringstream sstream(pretext); while (std::getline(sstream, tokens, delim)) { sans_delim.push_back(tokens); } return sans_delim; } //----------------------------// // User Class Implementation. // //----------------------------// IRCUser::IRCUser(void) { std::cout << "Creating User" << std::endl; } bool IRCUser::Equals(User *u) { return true; } //-------------------------------// // Message Class Implementation. // //-------------------------------// std::string IRCMessage::GetString() { return str; } IRCMessage::IRCMessage(std::string s) { // We don't know if the prefix is actually present. int prefixEnd = -1; // The prefix is actually present. if (s.at(0) == ':') { // The end is before the first space. prefixEnd = s.find_first_of(' '); // Save the prefix. (Note: we ca further segment it later.) prefix = s.substr(1, prefixEnd - 1); if (prefix.find('!') != prefix.npos) { nickname = prefix.substr(0, prefix.find('!')); } } size_t trailBegin = s.find(" :"); // Check if there is a trailing message. if (trailBegin != s.npos) { // Save the trail (char after colon to end of string). str = s.substr(trailBegin + 2, s.npos); } // argList = Split(s.substr(prefixEnd + 1, (trailBegin - prefixEnd - 1)), ' '); //we want a list of the arguments so we can seperately address them if (!argList.empty()) { command = argList.at(0); argList.pop_front(); } // Trim the \r\n if (str.length() > 2) { str = str.substr(0, str.length() - 2); } } IRCUser* IRCMessage::GetUser() { return new IRCUser; } IRCMessage* IRCMessage::Respond(std::string s) { return new IRCMessage(s); } //----------------------------// // Chat Class Implementation. // //----------------------------// IRCChat::IRCChat(void) { std::cout << "Creating Chat" << std::endl; } void IRCChat::Connect(std::string server, std::string port, std::string user, std::string password) { socket = new Socket(server, port); socket->Send("PASS PASSWORD\r\n"); socket->Send("NICK BlueBot\r\n"); socket->Send("USER BlueBot localhost servername :GreenBot\r\n"); socket->Send("JOIN #greenbot\r\n"); } IRCMessage* IRCChat::GetMessage() { IRCMessage *m = NULL; while (!m) { m = new IRCMessage(socket->Recv()); if (m->command == "PING") { socket->Send("PONG :" + m->str + "\r\n"); delete m; } } return m; } void IRCChat::SendMessage(Message *m) { return; } <commit_msg>fixed comment location<commit_after>// @file irc.cpp // @brief Implementation of the IRC class, which implements the // User, Message and Chat abstract classes. // #include <sstream> // std::stringstream #include "irc.h" std::deque<std::string> Split(std::string pretext, char delim) { std::deque<std::string> sans_delim; std::string tokens; std::stringstream sstream(pretext); while (std::getline(sstream, tokens, delim)) { sans_delim.push_back(tokens); } return sans_delim; } //----------------------------// // User Class Implementation. // //----------------------------// IRCUser::IRCUser(void) { std::cout << "Creating User" << std::endl; } bool IRCUser::Equals(User *u) { return true; } //-------------------------------// // Message Class Implementation. // //-------------------------------// std::string IRCMessage::GetString() { return str; } IRCMessage::IRCMessage(std::string s) { // We don't know if the prefix is actually present. int prefixEnd = -1; // The prefix is actually present. if (s.at(0) == ':') { // The end is before the first space. prefixEnd = s.find_first_of(' '); // Save the prefix. (Note: we ca further segment it later.) prefix = s.substr(1, prefixEnd - 1); if (prefix.find('!') != prefix.npos) { nickname = prefix.substr(0, prefix.find('!')); } } size_t trailBegin = s.find(" :"); // Check if there is a trailing message. if (trailBegin != s.npos) { // Save the trail (char after colon to end of string). str = s.substr(trailBegin + 2, s.npos); } // We get a list of the arguments. argList = Split(s.substr(prefixEnd + 1, (trailBegin - prefixEnd - 1)), ' '); if (!argList.empty()) { command = argList.at(0); argList.pop_front(); } // Trim the \r\n if (str.length() > 2) { str = str.substr(0, str.length() - 2); } } IRCUser* IRCMessage::GetUser() { return new IRCUser; } IRCMessage* IRCMessage::Respond(std::string s) { return new IRCMessage(s); } //----------------------------// // Chat Class Implementation. // //----------------------------// IRCChat::IRCChat(void) { std::cout << "Creating Chat" << std::endl; } void IRCChat::Connect(std::string server, std::string port, std::string user, std::string password) { socket = new Socket(server, port); socket->Send("PASS PASSWORD\r\n"); socket->Send("NICK BlueBot\r\n"); socket->Send("USER BlueBot localhost servername :GreenBot\r\n"); socket->Send("JOIN #greenbot\r\n"); } IRCMessage* IRCChat::GetMessage() { IRCMessage *m = NULL; while (!m) { m = new IRCMessage(socket->Recv()); if (m->command == "PING") { socket->Send("PONG :" + m->str + "\r\n"); delete m; } } return m; } void IRCChat::SendMessage(Message *m) { return; } <|endoftext|>
<commit_before>// Copyright (c) 2009 libmv authors. // // 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 "libmv/correspondence/feature_matching.h" #include "libmv/correspondence/ArrayMatcher.h" #include "libmv/correspondence/ArrayMatcher_BruteForce.h" #include "libmv/correspondence/ArrayMatcher_Kdtree_Flann.h" #include "libmv/correspondence/ArrayMatcher_Kdtree.h" // Compute candidate matches between 2 sets of features. Two features A and B // are a candidate match if A is the nearest neighbor of B and B is the nearest // neighbor of A. void FindCandidateMatches(const FeatureSet &left, const FeatureSet &right, Matches *matches, eLibmvMatchMethod eMatchMethod) { if (left.features.size() == 0 || right.features.size() == 0 ) { return; } int descriptorSize = left.features[0].descriptor.coords.size(); correspondence::ArrayMatcher<float> * pArrayMatcherA = NULL; correspondence::ArrayMatcher<float> * pArrayMatcherB = NULL; switch (eMatchMethod) { case eMATCH_KDTREE: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree<float>; pArrayMatcherB = new correspondence::ArrayMatcher_Kdtree<float>; } break; case eMATCH_KDTREE_FLANN: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree_Flann<float>; pArrayMatcherB = new correspondence::ArrayMatcher_Kdtree_Flann<float>; } break; case eMATCH_LINEAR: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_BruteForce<float>; pArrayMatcherB = new correspondence::ArrayMatcher_BruteForce<float>; } break; }; if (pArrayMatcherA != NULL && pArrayMatcherB != NULL) { // Paste the necessary data in contiguous arrays. float * arrayA = FeatureSet::FeatureSetDescriptorsToContiguousArray(left); float * arrayB = FeatureSet::FeatureSetDescriptorsToContiguousArray(right); libmv::vector<int> indices, indicesReverse; libmv::vector<float> distances, distancesReverse; bool breturn = false; if (pArrayMatcherA->build(arrayA,left.features.size(),descriptorSize) && pArrayMatcherB->build(arrayB,right.features.size(),descriptorSize) ) { const int NN = 1; breturn = pArrayMatcherB->searchNeighbours(arrayA,left.features.size(), &indices, &distances, NN) && pArrayMatcherA->searchNeighbours(arrayB,right.features.size(), &indicesReverse, &distancesReverse, NN); } delete pArrayMatcherA; delete pArrayMatcherB; delete [] arrayA; delete [] arrayB; // From putative matches get symmetric matches. if (breturn) { //TODO(pmoulon) clear previous matches. int max_track_number = 0; for (size_t i = 0; i < indices.size(); ++i) { // Add the matche only if we have a symetric result. if (i == indicesReverse[indices[i]]) { matches->Insert(0, max_track_number, &left.features[i]); matches->Insert(1, max_track_number, &right.features[indices[i]]); ++max_track_number; } } } else { LOG(INFO) << "[FindCandidateMatches] Cannot compute symmetric matches."; } } else { LOG(INFO) << "[FindCandidateMatches] Unknow input match method."; } } float * FeatureSet::FeatureSetDescriptorsToContiguousArray ( const FeatureSet & featureSet ) { if (featureSet.features.size() == 0) { return NULL; } int descriptorSize = featureSet.features[0].descriptor.coords.size(); // Allocate and paste the necessary data. float * array = new float[featureSet.features.size()*descriptorSize]; //-- Paste data in the contiguous array : for (int i = 0; i < (int)featureSet.features.size(); ++i) { for (int j = 0;j < descriptorSize; ++j) array[descriptorSize*i + j] = (float)featureSet.features[i][j]; } return array; } // Compute candidate matches between 2 sets of features with a ratio. void FindCandidateMatches_Ratio(const FeatureSet &left, const FeatureSet &right, Matches *matches, eLibmvMatchMethod eMatchMethod, float fRatio) { if (left.features.size() == 0 || right.features.size() == 0 ) { return; } int descriptorSize = left.features[0].descriptor.coords.size(); correspondence::ArrayMatcher<float> * pArrayMatcherA = NULL; switch (eMatchMethod) { case eMATCH_KDTREE: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree<float>; } break; case eMATCH_KDTREE_FLANN: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree_Flann<float>; } break; case eMATCH_LINEAR: { // Build the arrays matcher in order to compute matches pair. LOG(INFO) << "Not yet implemented."; return; } break; }; const int NN = 2; if (pArrayMatcherA != NULL) { // Paste the necessary data in contiguous arrays. float * arrayA = FeatureSet::FeatureSetDescriptorsToContiguousArray(left); float * arrayB = FeatureSet::FeatureSetDescriptorsToContiguousArray(right); libmv::vector<int> indices; libmv::vector<float> distances; bool breturn = false; if (pArrayMatcherA->build(arrayB,right.features.size(),descriptorSize)) { breturn = pArrayMatcherA->searchNeighbours(arrayA,left.features.size(), &indices, &distances, NN); } delete pArrayMatcherA; delete [] arrayA; delete [] arrayB; // From putative matches get matches that fit the "Ratio" heuristic. if (breturn) { //TODO(pmoulon) clear previous matches. int max_track_number = 0; for (size_t i = 0; i < left.features.size(); ++i) { // Test distance ratio : float distance0 = distances[i*NN]; float distance1 = distances[i*NN+NN-1]; if (distance0 < fRatio * distance1) { matches->Insert(0, max_track_number, &left.features[i]); matches->Insert(1, max_track_number, &right.features[indices[i*NN]]); ++max_track_number; } } } else { LOG(INFO) << "[FindCandidateMatches_Ratio] Cannot compute matches."; } } else { LOG(INFO) << "[FindCandidateMatches_Ratio] Unknow input match method."; } } // Compute correspondences that match between 2 sets of features with a ratio. void FindCorrespondences(const FeatureSet &left, const FeatureSet &right, std::map<size_t, size_t> *correspondences, eLibmvMatchMethod eMatchMethod, float fRatio) { if (left.features.size() == 0 || right.features.size() == 0 ) { return; } int descriptorSize = left.features[0].descriptor.coords.size(); correspondence::ArrayMatcher<float> * pArrayMatcherA = NULL; switch (eMatchMethod) { case eMATCH_KDTREE: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree<float>; } break; case eMATCH_KDTREE_FLANN: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree_Flann<float>; } break; case eMATCH_LINEAR: { // Build the arrays matcher in order to compute matches pair. LOG(INFO) << "Not yet implemented."; return; } break; }; const int NN = 2; if (pArrayMatcherA != NULL) { // Paste the necessary data in contiguous arrays. float * arrayA = FeatureSet::FeatureSetDescriptorsToContiguousArray(left); float * arrayB = FeatureSet::FeatureSetDescriptorsToContiguousArray(right); libmv::vector<int> indices; libmv::vector<float> distances; bool breturn = false; if (pArrayMatcherA->build(arrayB,right.features.size(),descriptorSize)) { breturn = pArrayMatcherA->searchNeighbours(arrayA,left.features.size(), &indices, &distances, NN); } delete pArrayMatcherA; delete [] arrayA; delete [] arrayB; // From putative matches get matches that fit the "Ratio" heuristic. if (breturn) { for (size_t i = 0; i < left.features.size(); ++i) { // Test distance ratio : float distance0 = distances[i*NN]; float distance1 = distances[i*NN+NN-1]; if (distance0 < fRatio * distance1) { (*correspondences)[i] = indices[i*NN]; } } } else { LOG(INFO) << "[FindCandidateMatches_Ratio] Cannot compute matches."; } } else { LOG(INFO) << "[FindCandidateMatches_Ratio] Unknow input match method."; } }<commit_msg>Fixed a small logging typo<commit_after>// Copyright (c) 2009 libmv authors. // // 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 "libmv/correspondence/feature_matching.h" #include "libmv/correspondence/ArrayMatcher.h" #include "libmv/correspondence/ArrayMatcher_BruteForce.h" #include "libmv/correspondence/ArrayMatcher_Kdtree_Flann.h" #include "libmv/correspondence/ArrayMatcher_Kdtree.h" // Compute candidate matches between 2 sets of features. Two features A and B // are a candidate match if A is the nearest neighbor of B and B is the nearest // neighbor of A. void FindCandidateMatches(const FeatureSet &left, const FeatureSet &right, Matches *matches, eLibmvMatchMethod eMatchMethod) { if (left.features.size() == 0 || right.features.size() == 0 ) { return; } int descriptorSize = left.features[0].descriptor.coords.size(); correspondence::ArrayMatcher<float> * pArrayMatcherA = NULL; correspondence::ArrayMatcher<float> * pArrayMatcherB = NULL; switch (eMatchMethod) { case eMATCH_KDTREE: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree<float>; pArrayMatcherB = new correspondence::ArrayMatcher_Kdtree<float>; } break; case eMATCH_KDTREE_FLANN: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree_Flann<float>; pArrayMatcherB = new correspondence::ArrayMatcher_Kdtree_Flann<float>; } break; case eMATCH_LINEAR: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_BruteForce<float>; pArrayMatcherB = new correspondence::ArrayMatcher_BruteForce<float>; } break; }; if (pArrayMatcherA != NULL && pArrayMatcherB != NULL) { // Paste the necessary data in contiguous arrays. float * arrayA = FeatureSet::FeatureSetDescriptorsToContiguousArray(left); float * arrayB = FeatureSet::FeatureSetDescriptorsToContiguousArray(right); libmv::vector<int> indices, indicesReverse; libmv::vector<float> distances, distancesReverse; bool breturn = false; if (pArrayMatcherA->build(arrayA,left.features.size(),descriptorSize) && pArrayMatcherB->build(arrayB,right.features.size(),descriptorSize) ) { const int NN = 1; breturn = pArrayMatcherB->searchNeighbours(arrayA,left.features.size(), &indices, &distances, NN) && pArrayMatcherA->searchNeighbours(arrayB,right.features.size(), &indicesReverse, &distancesReverse, NN); } delete pArrayMatcherA; delete pArrayMatcherB; delete [] arrayA; delete [] arrayB; // From putative matches get symmetric matches. if (breturn) { //TODO(pmoulon) clear previous matches. int max_track_number = 0; for (size_t i = 0; i < indices.size(); ++i) { // Add the matche only if we have a symetric result. if (i == indicesReverse[indices[i]]) { matches->Insert(0, max_track_number, &left.features[i]); matches->Insert(1, max_track_number, &right.features[indices[i]]); ++max_track_number; } } } else { LOG(INFO) << "[FindCandidateMatches] Cannot compute symmetric matches."; } } else { LOG(INFO) << "[FindCandidateMatches] Unknown input match method."; } } float * FeatureSet::FeatureSetDescriptorsToContiguousArray ( const FeatureSet & featureSet ) { if (featureSet.features.size() == 0) { return NULL; } int descriptorSize = featureSet.features[0].descriptor.coords.size(); // Allocate and paste the necessary data. float * array = new float[featureSet.features.size()*descriptorSize]; //-- Paste data in the contiguous array : for (int i = 0; i < (int)featureSet.features.size(); ++i) { for (int j = 0;j < descriptorSize; ++j) array[descriptorSize*i + j] = (float)featureSet.features[i][j]; } return array; } // Compute candidate matches between 2 sets of features with a ratio. void FindCandidateMatches_Ratio(const FeatureSet &left, const FeatureSet &right, Matches *matches, eLibmvMatchMethod eMatchMethod, float fRatio) { if (left.features.size() == 0 || right.features.size() == 0 ) { return; } int descriptorSize = left.features[0].descriptor.coords.size(); correspondence::ArrayMatcher<float> * pArrayMatcherA = NULL; switch (eMatchMethod) { case eMATCH_KDTREE: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree<float>; } break; case eMATCH_KDTREE_FLANN: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree_Flann<float>; } break; case eMATCH_LINEAR: { // Build the arrays matcher in order to compute matches pair. LOG(INFO) << "Not yet implemented."; return; } break; }; const int NN = 2; if (pArrayMatcherA != NULL) { // Paste the necessary data in contiguous arrays. float * arrayA = FeatureSet::FeatureSetDescriptorsToContiguousArray(left); float * arrayB = FeatureSet::FeatureSetDescriptorsToContiguousArray(right); libmv::vector<int> indices; libmv::vector<float> distances; bool breturn = false; if (pArrayMatcherA->build(arrayB,right.features.size(),descriptorSize)) { breturn = pArrayMatcherA->searchNeighbours(arrayA,left.features.size(), &indices, &distances, NN); } delete pArrayMatcherA; delete [] arrayA; delete [] arrayB; // From putative matches get matches that fit the "Ratio" heuristic. if (breturn) { //TODO(pmoulon) clear previous matches. int max_track_number = 0; for (size_t i = 0; i < left.features.size(); ++i) { // Test distance ratio : float distance0 = distances[i*NN]; float distance1 = distances[i*NN+NN-1]; if (distance0 < fRatio * distance1) { matches->Insert(0, max_track_number, &left.features[i]); matches->Insert(1, max_track_number, &right.features[indices[i*NN]]); ++max_track_number; } } } else { LOG(INFO) << "[FindCandidateMatches_Ratio] Cannot compute matches."; } } else { LOG(INFO) << "[FindCandidateMatches_Ratio] Unknow input match method."; } } // Compute correspondences that match between 2 sets of features with a ratio. void FindCorrespondences(const FeatureSet &left, const FeatureSet &right, std::map<size_t, size_t> *correspondences, eLibmvMatchMethod eMatchMethod, float fRatio) { if (left.features.size() == 0 || right.features.size() == 0 ) { return; } int descriptorSize = left.features[0].descriptor.coords.size(); correspondence::ArrayMatcher<float> * pArrayMatcherA = NULL; switch (eMatchMethod) { case eMATCH_KDTREE: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree<float>; } break; case eMATCH_KDTREE_FLANN: { // Build the arrays matcher in order to compute matches pair. pArrayMatcherA = new correspondence::ArrayMatcher_Kdtree_Flann<float>; } break; case eMATCH_LINEAR: { // Build the arrays matcher in order to compute matches pair. LOG(INFO) << "Not yet implemented."; return; } break; }; const int NN = 2; if (pArrayMatcherA != NULL) { // Paste the necessary data in contiguous arrays. float * arrayA = FeatureSet::FeatureSetDescriptorsToContiguousArray(left); float * arrayB = FeatureSet::FeatureSetDescriptorsToContiguousArray(right); libmv::vector<int> indices; libmv::vector<float> distances; bool breturn = false; if (pArrayMatcherA->build(arrayB,right.features.size(),descriptorSize)) { breturn = pArrayMatcherA->searchNeighbours(arrayA,left.features.size(), &indices, &distances, NN); } delete pArrayMatcherA; delete [] arrayA; delete [] arrayB; // From putative matches get matches that fit the "Ratio" heuristic. if (breturn) { for (size_t i = 0; i < left.features.size(); ++i) { // Test distance ratio : float distance0 = distances[i*NN]; float distance1 = distances[i*NN+NN-1]; if (distance0 < fRatio * distance1) { (*correspondences)[i] = indices[i*NN]; } } } else { LOG(INFO) << "[FindCandidateMatches_Ratio] Cannot compute matches."; } } else { LOG(INFO) << "[FindCandidateMatches_Ratio] Unknow input match method."; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: seekableinput.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-05-10 17:33:49 $ * * 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 _COMPHELPER_STREAM_SEEKABLEINPUT_HXX_ #define _COMPHELPER_STREAM_SEEKABLEINPUT_HXX_ #ifndef _OSL_MUTEX_HXX_ //autogen wg. ::osl::Mutex #include <osl/mutex.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif namespace comphelper { class OSeekableInputWrapper : public ::cppu::WeakImplHelper2< ::com::sun::star::io::XInputStream, ::com::sun::star::io::XSeekable > { ::osl::Mutex m_aMutex; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory; ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > m_xOriginalStream; ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > m_xCopyInput; ::com::sun::star::uno::Reference< ::com::sun::star::io::XSeekable > m_xCopySeek; private: void PrepareCopy_Impl(); public: OSeekableInputWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory ); virtual ~OSeekableInputWrapper(); static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > CheckSeekableCanWrap( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory ); // XInputStream virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL available() throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL closeInput() throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); // XSeekable virtual void SAL_CALL seek( sal_Int64 location ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual sal_Int64 SAL_CALL getPosition() throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual sal_Int64 SAL_CALL getLength() throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); }; } // namespace comphelper #endif <commit_msg>INTEGRATION: CWS visibility02 (1.2.82); FILE MERGED 2005/01/26 18:49:56 mhu 1.2.82.1: #i38608# More classes / symbols need to be exported.<commit_after>/************************************************************************* * * $RCSfile: seekableinput.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2005-02-16 16:01:00 $ * * 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 _COMPHELPER_STREAM_SEEKABLEINPUT_HXX_ #define _COMPHELPER_STREAM_SEEKABLEINPUT_HXX_ #ifndef _OSL_MUTEX_HXX_ //autogen wg. ::osl::Mutex #include <osl/mutex.hxx> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_ #include <com/sun/star/io/XSeekable.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef INCLUDED_COMPHELPERDLLAPI_H #include "comphelper/comphelperdllapi.h" #endif namespace comphelper { class COMPHELPER_DLLPUBLIC OSeekableInputWrapper : public ::cppu::WeakImplHelper2< ::com::sun::star::io::XInputStream, ::com::sun::star::io::XSeekable > { ::osl::Mutex m_aMutex; ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory; ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > m_xOriginalStream; ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > m_xCopyInput; ::com::sun::star::uno::Reference< ::com::sun::star::io::XSeekable > m_xCopySeek; private: COMPHELPER_DLLPRIVATE void PrepareCopy_Impl(); public: OSeekableInputWrapper( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory ); virtual ~OSeekableInputWrapper(); static ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > CheckSeekableCanWrap( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xInStream, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xFactory ); // XInputStream virtual sal_Int32 SAL_CALL readBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL readSomeBytes( ::com::sun::star::uno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL skipBytes( sal_Int32 nBytesToSkip ) throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::BufferSizeExceededException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL available() throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL closeInput() throw (::com::sun::star::io::NotConnectedException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); // XSeekable virtual void SAL_CALL seek( sal_Int64 location ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual sal_Int64 SAL_CALL getPosition() throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); virtual sal_Int64 SAL_CALL getLength() throw (::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException); }; } // namespace comphelper #endif <|endoftext|>
<commit_before>// Copyright (c) 2011 libmv authors. // // 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 <cstdio> #include "libmv/logging/logging.h" #include "libmv/simple_pipeline/bundle.h" #include "libmv/simple_pipeline/intersect.h" #include "libmv/simple_pipeline/resect.h" #include "libmv/simple_pipeline/reconstruction.h" #include "libmv/simple_pipeline/tracks.h" #include "libmv/simple_pipeline/camera_intrinsics.h" namespace libmv { namespace { // These are "strategy" classes which make it possible to use the same code for // both projective and euclidean reconstruction. // FIXME(MatthiasF): OOP would achieve the same goal while avoiding // template bloat and making interface changes much easier. struct EuclideanPipelineRoutines { typedef EuclideanReconstruction Reconstruction; typedef EuclideanCamera Camera; typedef EuclideanPoint Point; static void Bundle(const Tracks &tracks, EuclideanReconstruction *reconstruction) { EuclideanBundle(tracks, reconstruction); } static bool Resect(const vector<Marker> &markers, EuclideanReconstruction *reconstruction, bool final_pass) { return EuclideanResect(markers, reconstruction, final_pass); } static bool Intersect(const vector<Marker> &markers, EuclideanReconstruction *reconstruction) { return EuclideanIntersect(markers, reconstruction); } static Marker ProjectMarker(const EuclideanPoint &point, const EuclideanCamera &camera, const CameraIntrinsics &intrinsics) { Vec3 projected = camera.R * point.X + camera.t; projected /= projected(2); Marker reprojected_marker; intrinsics.ApplyIntrinsics(projected(0), projected(1), &reprojected_marker.x, &reprojected_marker.y); reprojected_marker.image = camera.image; reprojected_marker.track = point.track; return reprojected_marker; } }; struct ProjectivePipelineRoutines { typedef ProjectiveReconstruction Reconstruction; typedef ProjectiveCamera Camera; typedef ProjectivePoint Point; static void Bundle(const Tracks &tracks, ProjectiveReconstruction *reconstruction) { ProjectiveBundle(tracks, reconstruction); } static bool Resect(const vector<Marker> &markers, ProjectiveReconstruction *reconstruction, bool final_pass) { return ProjectiveResect(markers, reconstruction); } static bool Intersect(const vector<Marker> &markers, ProjectiveReconstruction *reconstruction) { return ProjectiveIntersect(markers, reconstruction); } static Marker ProjectMarker(const ProjectivePoint &point, const ProjectiveCamera &camera, const CameraIntrinsics &intrinsics) { Vec3 projected = camera.P * point.X; projected /= projected(2); Marker reprojected_marker; intrinsics.ApplyIntrinsics(projected(0), projected(1), &reprojected_marker.x, &reprojected_marker.y); reprojected_marker.image = camera.image; reprojected_marker.track = point.track; return reprojected_marker; } }; } // namespace template<typename PipelineRoutines> void InternalCompleteReconstruction( const Tracks &tracks, typename PipelineRoutines::Reconstruction *reconstruction) { int max_track = tracks.MaxTrack(); int max_image = tracks.MaxImage(); int num_resects = -1; int num_intersects = -1; LG << "Max track: " << max_track; LG << "Max image: " << max_image; LG << "Number of markers: " << tracks.NumMarkers(); while (num_resects != 0 || num_intersects != 0) { // Do all possible intersections. num_intersects = 0; for (int track = 0; track <= max_track; ++track) { if (reconstruction->PointForTrack(track)) { LG << "Skipping point: " << track; continue; } vector<Marker> all_markers = tracks.MarkersForTrack(track); LG << "Got " << all_markers.size() << " markers for track " << track; vector<Marker> reconstructed_markers; for (int i = 0; i < all_markers.size(); ++i) { if (reconstruction->CameraForImage(all_markers[i].image)) { reconstructed_markers.push_back(all_markers[i]); } } LG << "Got " << reconstructed_markers.size() << " reconstructed markers for track " << track; if (reconstructed_markers.size() >= 2) { PipelineRoutines::Intersect(reconstructed_markers, reconstruction); num_intersects++; LG << "Ran Intersect() for track " << track; } } if (num_intersects) { PipelineRoutines::Bundle(tracks, reconstruction); LG << "Ran Bundle() after intersections."; } LG << "Did " << num_intersects << " intersects."; // Do all possible resections. num_resects = 0; for (int image = 0; image <= max_image; ++image) { if (reconstruction->CameraForImage(image)) { LG << "Skipping frame: " << image; continue; } vector<Marker> all_markers = tracks.MarkersInImage(image); LG << "Got " << all_markers.size() << " markers for image " << image; vector<Marker> reconstructed_markers; for (int i = 0; i < all_markers.size(); ++i) { if (reconstruction->PointForTrack(all_markers[i].track)) { reconstructed_markers.push_back(all_markers[i]); } } LG << "Got " << reconstructed_markers.size() << " reconstructed markers for image " << image; if (reconstructed_markers.size() >= 5) { if (PipelineRoutines::Resect(reconstructed_markers, reconstruction, false)) { num_resects++; LG << "Ran Resect() for image " << image; } else { LG << "Failed Resect() for image " << image; } } } if (num_resects) { PipelineRoutines::Bundle(tracks, reconstruction); } LG << "Did " << num_resects << " resects."; } // One last pass... num_resects = 0; for (int image = 0; image <= max_image; ++image) { if (reconstruction->CameraForImage(image)) { LG << "Skipping frame: " << image; continue; } vector<Marker> all_markers = tracks.MarkersInImage(image); vector<Marker> reconstructed_markers; for (int i = 0; i < all_markers.size(); ++i) { if (reconstruction->PointForTrack(all_markers[i].track)) { reconstructed_markers.push_back(all_markers[i]); } } if (reconstructed_markers.size() >= 5) { if (PipelineRoutines::Resect(reconstructed_markers, reconstruction, true)) { num_resects++; LG << "Ran Resect() for image " << image; } else { LG << "Failed Resect() for image " << image; } } } if (num_resects) { PipelineRoutines::Bundle(tracks, reconstruction); } } template<typename PipelineRoutines> double InternalReprojectionError(const Tracks &image_tracks, const typename PipelineRoutines::Reconstruction &reconstruction, const CameraIntrinsics &intrinsics) { int num_skipped = 0; int num_reprojected = 0; double total_error = 0.0; vector<Marker> markers = image_tracks.AllMarkers(); for (int i = 0; i < markers.size(); ++i) { const typename PipelineRoutines::Camera *camera = reconstruction.CameraForImage(markers[i].image); const typename PipelineRoutines::Point *point = reconstruction.PointForTrack(markers[i].track); if (!camera || !point) { num_skipped++; continue; } num_reprojected++; Marker reprojected_marker = PipelineRoutines::ProjectMarker(*point, *camera, intrinsics); double ex = reprojected_marker.x - markers[i].x; double ey = reprojected_marker.y - markers[i].y; const int N = 100; char line[N]; snprintf(line, N, "image %-3d track %-3d " "x %7.1f y %7.1f " "rx %7.1f ry %7.1f " "ex %7.1f ey %7.1f" " e %7.1f", markers[i].image, markers[i].track, markers[i].x, markers[i].y, reprojected_marker.x, reprojected_marker.y, ex, ey, sqrt(ex*ex + ey*ey)); //LG << line; total_error += sqrt(ex*ex + ey*ey); } LG << "Skipped " << num_skipped << " markers."; LG << "Reprojected " << num_reprojected << " markers."; LG << "Total error: " << total_error; LG << "Average error: " << (total_error / num_reprojected) << " [pixels]."; return total_error / num_reprojected; } double EuclideanReprojectionError(const Tracks &image_tracks, const EuclideanReconstruction &reconstruction, const CameraIntrinsics &intrinsics) { return InternalReprojectionError<EuclideanPipelineRoutines>(image_tracks, reconstruction, intrinsics); } double ProjectiveReprojectionError( const Tracks &image_tracks, const ProjectiveReconstruction &reconstruction, const CameraIntrinsics &intrinsics) { return InternalReprojectionError<ProjectivePipelineRoutines>(image_tracks, reconstruction, intrinsics); } void EuclideanCompleteReconstruction(const Tracks &tracks, EuclideanReconstruction *reconstruction) { InternalCompleteReconstruction<EuclideanPipelineRoutines>(tracks, reconstruction); } void ProjectiveCompleteReconstruction(const Tracks &tracks, ProjectiveReconstruction *reconstruction) { InternalCompleteReconstruction<ProjectivePipelineRoutines>(tracks, reconstruction); } void InvertIntrinsicsForTracks(const Tracks &raw_tracks, const CameraIntrinsics &camera_intrinsics, Tracks *calibrated_tracks) { vector<Marker> markers = raw_tracks.AllMarkers(); for (int i = 0; i < markers.size(); ++i) { camera_intrinsics.InvertIntrinsics(markers[i].x, markers[i].y, &(markers[i].x), &(markers[i].y)); } *calibrated_tracks = Tracks(markers); } } // namespace libmv <commit_msg>Fix compilation with MSVC where snprintf function is declared as unsafe and _snprintf should be used instead.<commit_after>// Copyright (c) 2011 libmv authors. // // 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 <cstdio> #include "libmv/logging/logging.h" #include "libmv/simple_pipeline/bundle.h" #include "libmv/simple_pipeline/intersect.h" #include "libmv/simple_pipeline/resect.h" #include "libmv/simple_pipeline/reconstruction.h" #include "libmv/simple_pipeline/tracks.h" #include "libmv/simple_pipeline/camera_intrinsics.h" #ifdef _MSC_VER # define snprintf _snprintf #endif namespace libmv { namespace { // These are "strategy" classes which make it possible to use the same code for // both projective and euclidean reconstruction. // FIXME(MatthiasF): OOP would achieve the same goal while avoiding // template bloat and making interface changes much easier. struct EuclideanPipelineRoutines { typedef EuclideanReconstruction Reconstruction; typedef EuclideanCamera Camera; typedef EuclideanPoint Point; static void Bundle(const Tracks &tracks, EuclideanReconstruction *reconstruction) { EuclideanBundle(tracks, reconstruction); } static bool Resect(const vector<Marker> &markers, EuclideanReconstruction *reconstruction, bool final_pass) { return EuclideanResect(markers, reconstruction, final_pass); } static bool Intersect(const vector<Marker> &markers, EuclideanReconstruction *reconstruction) { return EuclideanIntersect(markers, reconstruction); } static Marker ProjectMarker(const EuclideanPoint &point, const EuclideanCamera &camera, const CameraIntrinsics &intrinsics) { Vec3 projected = camera.R * point.X + camera.t; projected /= projected(2); Marker reprojected_marker; intrinsics.ApplyIntrinsics(projected(0), projected(1), &reprojected_marker.x, &reprojected_marker.y); reprojected_marker.image = camera.image; reprojected_marker.track = point.track; return reprojected_marker; } }; struct ProjectivePipelineRoutines { typedef ProjectiveReconstruction Reconstruction; typedef ProjectiveCamera Camera; typedef ProjectivePoint Point; static void Bundle(const Tracks &tracks, ProjectiveReconstruction *reconstruction) { ProjectiveBundle(tracks, reconstruction); } static bool Resect(const vector<Marker> &markers, ProjectiveReconstruction *reconstruction, bool final_pass) { return ProjectiveResect(markers, reconstruction); } static bool Intersect(const vector<Marker> &markers, ProjectiveReconstruction *reconstruction) { return ProjectiveIntersect(markers, reconstruction); } static Marker ProjectMarker(const ProjectivePoint &point, const ProjectiveCamera &camera, const CameraIntrinsics &intrinsics) { Vec3 projected = camera.P * point.X; projected /= projected(2); Marker reprojected_marker; intrinsics.ApplyIntrinsics(projected(0), projected(1), &reprojected_marker.x, &reprojected_marker.y); reprojected_marker.image = camera.image; reprojected_marker.track = point.track; return reprojected_marker; } }; } // namespace template<typename PipelineRoutines> void InternalCompleteReconstruction( const Tracks &tracks, typename PipelineRoutines::Reconstruction *reconstruction) { int max_track = tracks.MaxTrack(); int max_image = tracks.MaxImage(); int num_resects = -1; int num_intersects = -1; LG << "Max track: " << max_track; LG << "Max image: " << max_image; LG << "Number of markers: " << tracks.NumMarkers(); while (num_resects != 0 || num_intersects != 0) { // Do all possible intersections. num_intersects = 0; for (int track = 0; track <= max_track; ++track) { if (reconstruction->PointForTrack(track)) { LG << "Skipping point: " << track; continue; } vector<Marker> all_markers = tracks.MarkersForTrack(track); LG << "Got " << all_markers.size() << " markers for track " << track; vector<Marker> reconstructed_markers; for (int i = 0; i < all_markers.size(); ++i) { if (reconstruction->CameraForImage(all_markers[i].image)) { reconstructed_markers.push_back(all_markers[i]); } } LG << "Got " << reconstructed_markers.size() << " reconstructed markers for track " << track; if (reconstructed_markers.size() >= 2) { PipelineRoutines::Intersect(reconstructed_markers, reconstruction); num_intersects++; LG << "Ran Intersect() for track " << track; } } if (num_intersects) { PipelineRoutines::Bundle(tracks, reconstruction); LG << "Ran Bundle() after intersections."; } LG << "Did " << num_intersects << " intersects."; // Do all possible resections. num_resects = 0; for (int image = 0; image <= max_image; ++image) { if (reconstruction->CameraForImage(image)) { LG << "Skipping frame: " << image; continue; } vector<Marker> all_markers = tracks.MarkersInImage(image); LG << "Got " << all_markers.size() << " markers for image " << image; vector<Marker> reconstructed_markers; for (int i = 0; i < all_markers.size(); ++i) { if (reconstruction->PointForTrack(all_markers[i].track)) { reconstructed_markers.push_back(all_markers[i]); } } LG << "Got " << reconstructed_markers.size() << " reconstructed markers for image " << image; if (reconstructed_markers.size() >= 5) { if (PipelineRoutines::Resect(reconstructed_markers, reconstruction, false)) { num_resects++; LG << "Ran Resect() for image " << image; } else { LG << "Failed Resect() for image " << image; } } } if (num_resects) { PipelineRoutines::Bundle(tracks, reconstruction); } LG << "Did " << num_resects << " resects."; } // One last pass... num_resects = 0; for (int image = 0; image <= max_image; ++image) { if (reconstruction->CameraForImage(image)) { LG << "Skipping frame: " << image; continue; } vector<Marker> all_markers = tracks.MarkersInImage(image); vector<Marker> reconstructed_markers; for (int i = 0; i < all_markers.size(); ++i) { if (reconstruction->PointForTrack(all_markers[i].track)) { reconstructed_markers.push_back(all_markers[i]); } } if (reconstructed_markers.size() >= 5) { if (PipelineRoutines::Resect(reconstructed_markers, reconstruction, true)) { num_resects++; LG << "Ran Resect() for image " << image; } else { LG << "Failed Resect() for image " << image; } } } if (num_resects) { PipelineRoutines::Bundle(tracks, reconstruction); } } template<typename PipelineRoutines> double InternalReprojectionError(const Tracks &image_tracks, const typename PipelineRoutines::Reconstruction &reconstruction, const CameraIntrinsics &intrinsics) { int num_skipped = 0; int num_reprojected = 0; double total_error = 0.0; vector<Marker> markers = image_tracks.AllMarkers(); for (int i = 0; i < markers.size(); ++i) { const typename PipelineRoutines::Camera *camera = reconstruction.CameraForImage(markers[i].image); const typename PipelineRoutines::Point *point = reconstruction.PointForTrack(markers[i].track); if (!camera || !point) { num_skipped++; continue; } num_reprojected++; Marker reprojected_marker = PipelineRoutines::ProjectMarker(*point, *camera, intrinsics); double ex = reprojected_marker.x - markers[i].x; double ey = reprojected_marker.y - markers[i].y; const int N = 100; char line[N]; snprintf(line, N, "image %-3d track %-3d " "x %7.1f y %7.1f " "rx %7.1f ry %7.1f " "ex %7.1f ey %7.1f" " e %7.1f", markers[i].image, markers[i].track, markers[i].x, markers[i].y, reprojected_marker.x, reprojected_marker.y, ex, ey, sqrt(ex*ex + ey*ey)); //LG << line; total_error += sqrt(ex*ex + ey*ey); } LG << "Skipped " << num_skipped << " markers."; LG << "Reprojected " << num_reprojected << " markers."; LG << "Total error: " << total_error; LG << "Average error: " << (total_error / num_reprojected) << " [pixels]."; return total_error / num_reprojected; } double EuclideanReprojectionError(const Tracks &image_tracks, const EuclideanReconstruction &reconstruction, const CameraIntrinsics &intrinsics) { return InternalReprojectionError<EuclideanPipelineRoutines>(image_tracks, reconstruction, intrinsics); } double ProjectiveReprojectionError( const Tracks &image_tracks, const ProjectiveReconstruction &reconstruction, const CameraIntrinsics &intrinsics) { return InternalReprojectionError<ProjectivePipelineRoutines>(image_tracks, reconstruction, intrinsics); } void EuclideanCompleteReconstruction(const Tracks &tracks, EuclideanReconstruction *reconstruction) { InternalCompleteReconstruction<EuclideanPipelineRoutines>(tracks, reconstruction); } void ProjectiveCompleteReconstruction(const Tracks &tracks, ProjectiveReconstruction *reconstruction) { InternalCompleteReconstruction<ProjectivePipelineRoutines>(tracks, reconstruction); } void InvertIntrinsicsForTracks(const Tracks &raw_tracks, const CameraIntrinsics &camera_intrinsics, Tracks *calibrated_tracks) { vector<Marker> markers = raw_tracks.AllMarkers(); for (int i = 0; i < markers.size(); ++i) { camera_intrinsics.InvertIntrinsics(markers[i].x, markers[i].y, &(markers[i].x), &(markers[i].y)); } *calibrated_tracks = Tracks(markers); } } // namespace libmv <|endoftext|>
<commit_before>/** * @file loger.cpp * * @brief implementation main * * @author Matus Blaho * @version 1.0 */ #include "loger.h" #include "config.h" #include "connectionHandler.h" #include "adaServerSender.h" #include "adaServerReceiver.h" #include <termios.h> #include <Poco/Exception.h> using namespace Poco; Config *c; WorkerPool *wpool = NULL; sem_t connectionSem; std::atomic<unsigned long> connCount; AdaServerReceiver *receiver; AdaServerSender *sender; std::thread *SenderThread; Loger *SenderLog; Loger *ReceiverLog; bool sigint =false; SSLContainer *sslCont; static pthread_mutex_t *lockarray; static void lock_callback(int mode, int type, char *file, int line) { (void)file; (void)line; if (mode & CRYPTO_LOCK) { pthread_mutex_lock(&(lockarray[type])); } else { pthread_mutex_unlock(&(lockarray[type])); } } static unsigned long thread_id(void) { unsigned long ret; ret=(unsigned long)pthread_self(); return(ret); } static void init_locks(void) { int i; lockarray=(pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); for (i=0; i<CRYPTO_num_locks(); i++) { pthread_mutex_init(&(lockarray[i]),NULL); } CRYPTO_set_id_callback((unsigned long (*)())thread_id); CRYPTO_set_locking_callback((void (*)(int, int, const char*, int))lock_callback); } static void kill_locks(void) { int i; CRYPTO_set_locking_callback(NULL); for (i=0; i<CRYPTO_num_locks(); i++) pthread_mutex_destroy(&(lockarray[i])); OPENSSL_free(lockarray); } void sig_handler(int signo) //on signals to turn of clear { if ((signo == SIGINT)||(signo == SIGTERM)) { sigint = true; receiver->LogINT(); sender->LogINT(); delete (sslCont); delete (c); delete (wpool); delete (sender); delete (receiver); sem_destroy(&connectionSem); delete (SenderThread); delete (SenderLog); delete (ReceiverLog); kill_locks(); ERR_remove_state(0); ERR_free_strings(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); } exit(EXIT_SUCCESS); } std::string buildConnString(std::string DBName, std::string User, std::string Password) //building connection string to database { std::string result; result.clear(); if(DBName.empty()) { return (""); } if (User.empty()) { return ("dbname=" + DBName); } if (Password.empty()) { std::cout<<"Enter password for user :"<<User<<std::endl; struct termios tty; tcgetattr(STDIN_FILENO, &tty); tty.c_lflag &= ~ECHO; (void) tcsetattr(STDIN_FILENO, TCSANOW, &tty); std::cin>>Password; tcgetattr(STDIN_FILENO, &tty); tty.c_lflag |= ECHO; (void) tcsetattr(STDIN_FILENO, TCSANOW, &tty); std::cout<<"Password readed"<<std::endl; result = "dbname="+ DBName + " user=" + User + " password=" + Password; return (result); } result = "dbname="+ DBName + " user=" + User + " password=" + Password; return(result); } int main(int argc, char **argv) //main body of application { if (argc < 2) { std::cerr<<"Path to configuration file was not given."<<std::endl; exit(EXIT_FAILURE); } pid_t pid, sid; std::cout<<"Reading configuration"<<std::endl; c = new Config(); try { c->setConfig(argv[1]); } catch(Exception &e) { std::cerr << e.displayText() << std::endl; std::cerr << "Failed to parse configuration" << std::endl; delete c; return EXIT_FAILURE; } std::string connStr = buildConnString(c->DBName(),c->User(),c->Password()); /* Fork off the parent process */ if (c->Mode()!=0) //start as deamon { std::cout<<"Starting deamonization"<<std::endl; pid = fork(); if (pid < 0) { std::cerr<<"Deamonzation failed! Running in teminal mode."<<std::endl; } else { /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { delete(c); exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); /* Open any logs here */ /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ exit(EXIT_FAILURE); } int proces_id=getpid(); //std::cout<<"Creating stop script in current directory"<<std::endl; std::ofstream stopSCR; stopSCR.open("stop_ada_server.sh", std::ios::out|std::ios::trunc); stopSCR<<"kill -SIGINT "<<proces_id<<std::endl; stopSCR.close(); /* Change the current working directory */ if ((chdir("/")) < 0) { /* Log the failure */ exit(EXIT_FAILURE); } //std::cout<<"Finishing deamonization"<<std::endl; /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } } else { std::cout<<"Server started in terminal(debug) mode"<<std::endl; int proces_id=getpid(); //std::cout<<"Creating stop script in current directory"<<std::endl; std::ofstream stopSCR; stopSCR.open("stop_ada_server.sh", std::ios::out|std::ios::trunc); stopSCR<<"kill -SIGINT "<<proces_id<<std::endl; stopSCR.close(); } SSL_load_error_strings(); SSL_library_init(); OpenSSL_add_all_algorithms(); SenderLog = new Loger(); ReceiverLog = new Loger(); SenderLog->SetLogger(c->SenderVerbosity(),c->SenderMaxFiles(),c->SenderMaxLines(),c->SenderFileNaming(),c->SenderPath(),"SENDER",c->SenderToSTD()); ReceiverLog->SetLogger(c->ReceiverVerbosity(),c->ReceiverMaxFiles(),c->ReceiverMaxLines(),c->ReceiverFileNaming(),c->SenderPath(),"RECEIVER",c->ReceiverToSTD()); if (signal(SIGINT, sig_handler) == SIG_ERR) { SenderLog->WriteMessage(ERR," [Main Process] Unable to catch SIGINT"); } if (signal(SIGTERM, sig_handler) == SIG_ERR) { SenderLog->WriteMessage(ERR," [Main Process] Unable to catch SIGTERM"); } if (signal(SIGHUP, SIG_IGN) == SIG_ERR) { SenderLog->WriteMessage(ERR," [Main Process] Unable to mask SIGHUP"); } if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { SenderLog->WriteMessage(ERR," [Main Process] Unable to mask SIGPIPE"); } sslCont = new SSLContainer(ReceiverLog); wpool = WorkerPool::CreatePool(ReceiverLog,SenderLog,connStr,c,sslCont); init_locks(); if ((wpool==NULL)||(wpool->Limit()<=0)) { SenderLog->WriteMessage(FATAL," [Main Process] 0 connections to DB unable to serve, terminating!"); delete (c); delete wpool; delete SenderLog; delete ReceiverLog; exit(EXIT_FAILURE); } else { int semVal = wpool->Limit(); SenderLog->WriteMessage(INFO,"[Main Process] Maximal connection count : " + std::to_string(semVal)); ReceiverLog->WriteMessage(INFO,"[Main Process] Maximal connection count : " + std::to_string(semVal)); sem_init(&connectionSem,0,semVal); wpool->SetSemaphore(&connectionSem); SenderLog->WriteMessage(TRACE,"[Main Process] Creating Sender"); ReceiverLog->WriteMessage(TRACE,"[Main Process] Creating Sender"); sender = new AdaServerSender(&connectionSem,wpool,SenderLog,c); SenderLog->WriteMessage(TRACE,"[Main Process] Creating Receiver"); ReceiverLog->WriteMessage(TRACE,"[Main Process] Creating Receiver"); receiver = new AdaServerReceiver(&connectionSem,wpool,ReceiverLog,c); SenderLog->WriteMessage(INFO,"[Main Process] Starting Sender"); ReceiverLog->WriteMessage(INFO,"[Main Process] Starting Sender"); SenderThread = new std::thread( [ ] { sender->Start(); }); SenderThread->detach(); ReceiverLog->WriteMessage(INFO,"[Main Process] Starting Receiver"); SenderLog->WriteMessage(INFO,"[Main Process] Starting Receiver"); receiver->Start(); } if (!sigint) { delete (c); delete (wpool); delete (sender); delete (receiver); CRYPTO_cleanup_all_ex_data(); kill_locks(); ERR_remove_state(0); ERR_free_strings(); EVP_cleanup(); sem_destroy(&connectionSem); delete (SenderThread); delete (SenderLog); delete (ReceiverLog); exit(EXIT_FAILURE); } return (0); } <commit_msg>ada_server: extract function startDaemon<commit_after>/** * @file loger.cpp * * @brief implementation main * * @author Matus Blaho * @version 1.0 */ #include "loger.h" #include "config.h" #include "connectionHandler.h" #include "adaServerSender.h" #include "adaServerReceiver.h" #include <termios.h> #include <Poco/Exception.h> using namespace Poco; Config *c; WorkerPool *wpool = NULL; sem_t connectionSem; std::atomic<unsigned long> connCount; AdaServerReceiver *receiver; AdaServerSender *sender; std::thread *SenderThread; Loger *SenderLog; Loger *ReceiverLog; bool sigint =false; SSLContainer *sslCont; static pthread_mutex_t *lockarray; static void lock_callback(int mode, int type, char *file, int line) { (void)file; (void)line; if (mode & CRYPTO_LOCK) { pthread_mutex_lock(&(lockarray[type])); } else { pthread_mutex_unlock(&(lockarray[type])); } } static unsigned long thread_id(void) { unsigned long ret; ret=(unsigned long)pthread_self(); return(ret); } static void init_locks(void) { int i; lockarray=(pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); for (i=0; i<CRYPTO_num_locks(); i++) { pthread_mutex_init(&(lockarray[i]),NULL); } CRYPTO_set_id_callback((unsigned long (*)())thread_id); CRYPTO_set_locking_callback((void (*)(int, int, const char*, int))lock_callback); } static void kill_locks(void) { int i; CRYPTO_set_locking_callback(NULL); for (i=0; i<CRYPTO_num_locks(); i++) pthread_mutex_destroy(&(lockarray[i])); OPENSSL_free(lockarray); } void sig_handler(int signo) //on signals to turn of clear { if ((signo == SIGINT)||(signo == SIGTERM)) { sigint = true; receiver->LogINT(); sender->LogINT(); delete (sslCont); delete (c); delete (wpool); delete (sender); delete (receiver); sem_destroy(&connectionSem); delete (SenderThread); delete (SenderLog); delete (ReceiverLog); kill_locks(); ERR_remove_state(0); ERR_free_strings(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); } exit(EXIT_SUCCESS); } std::string buildConnString(std::string DBName, std::string User, std::string Password) //building connection string to database { std::string result; result.clear(); if(DBName.empty()) { return (""); } if (User.empty()) { return ("dbname=" + DBName); } if (Password.empty()) { std::cout<<"Enter password for user :"<<User<<std::endl; struct termios tty; tcgetattr(STDIN_FILENO, &tty); tty.c_lflag &= ~ECHO; (void) tcsetattr(STDIN_FILENO, TCSANOW, &tty); std::cin>>Password; tcgetattr(STDIN_FILENO, &tty); tty.c_lflag |= ECHO; (void) tcsetattr(STDIN_FILENO, TCSANOW, &tty); std::cout<<"Password readed"<<std::endl; result = "dbname="+ DBName + " user=" + User + " password=" + Password; return (result); } result = "dbname="+ DBName + " user=" + User + " password=" + Password; return(result); } static void startDaemon(void) { pid_t pid, sid; std::cout<<"Starting deamonization"<<std::endl; pid = fork(); if (pid < 0) { std::cerr<<"Deamonzation failed! Running in teminal mode."<<std::endl; } else { /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { delete(c); exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); /* Open any logs here */ /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ exit(EXIT_FAILURE); } int proces_id = getpid(); //std::cout<<"Creating stop script in current directory"<<std::endl; std::ofstream stopSCR; stopSCR.open("stop_ada_server.sh", std::ios::out|std::ios::trunc); stopSCR<<"kill -SIGINT "<<proces_id<<std::endl; stopSCR.close(); /* Change the current working directory */ if ((chdir("/")) < 0) { /* Log the failure */ exit(EXIT_FAILURE); } //std::cout<<"Finishing deamonization"<<std::endl; /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } } int main(int argc, char **argv) //main body of application { if (argc < 2) { std::cerr<<"Path to configuration file was not given."<<std::endl; exit(EXIT_FAILURE); } std::cout<<"Reading configuration"<<std::endl; c = new Config(); try { c->setConfig(argv[1]); } catch(Exception &e) { std::cerr << e.displayText() << std::endl; std::cerr << "Failed to parse configuration" << std::endl; delete c; return EXIT_FAILURE; } std::string connStr = buildConnString(c->DBName(),c->User(),c->Password()); /* Fork off the parent process */ if (c->Mode()!=0) //start as deamon { startDaemon(); } else { std::cout<<"Server started in terminal(debug) mode"<<std::endl; int proces_id=getpid(); //std::cout<<"Creating stop script in current directory"<<std::endl; std::ofstream stopSCR; stopSCR.open("stop_ada_server.sh", std::ios::out|std::ios::trunc); stopSCR<<"kill -SIGINT "<<proces_id<<std::endl; stopSCR.close(); } SSL_load_error_strings(); SSL_library_init(); OpenSSL_add_all_algorithms(); SenderLog = new Loger(); ReceiverLog = new Loger(); SenderLog->SetLogger(c->SenderVerbosity(),c->SenderMaxFiles(),c->SenderMaxLines(),c->SenderFileNaming(),c->SenderPath(),"SENDER",c->SenderToSTD()); ReceiverLog->SetLogger(c->ReceiverVerbosity(),c->ReceiverMaxFiles(),c->ReceiverMaxLines(),c->ReceiverFileNaming(),c->SenderPath(),"RECEIVER",c->ReceiverToSTD()); if (signal(SIGINT, sig_handler) == SIG_ERR) { SenderLog->WriteMessage(ERR," [Main Process] Unable to catch SIGINT"); } if (signal(SIGTERM, sig_handler) == SIG_ERR) { SenderLog->WriteMessage(ERR," [Main Process] Unable to catch SIGTERM"); } if (signal(SIGHUP, SIG_IGN) == SIG_ERR) { SenderLog->WriteMessage(ERR," [Main Process] Unable to mask SIGHUP"); } if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { SenderLog->WriteMessage(ERR," [Main Process] Unable to mask SIGPIPE"); } sslCont = new SSLContainer(ReceiverLog); wpool = WorkerPool::CreatePool(ReceiverLog,SenderLog,connStr,c,sslCont); init_locks(); if ((wpool==NULL)||(wpool->Limit()<=0)) { SenderLog->WriteMessage(FATAL," [Main Process] 0 connections to DB unable to serve, terminating!"); delete (c); delete wpool; delete SenderLog; delete ReceiverLog; exit(EXIT_FAILURE); } else { int semVal = wpool->Limit(); SenderLog->WriteMessage(INFO,"[Main Process] Maximal connection count : " + std::to_string(semVal)); ReceiverLog->WriteMessage(INFO,"[Main Process] Maximal connection count : " + std::to_string(semVal)); sem_init(&connectionSem,0,semVal); wpool->SetSemaphore(&connectionSem); SenderLog->WriteMessage(TRACE,"[Main Process] Creating Sender"); ReceiverLog->WriteMessage(TRACE,"[Main Process] Creating Sender"); sender = new AdaServerSender(&connectionSem,wpool,SenderLog,c); SenderLog->WriteMessage(TRACE,"[Main Process] Creating Receiver"); ReceiverLog->WriteMessage(TRACE,"[Main Process] Creating Receiver"); receiver = new AdaServerReceiver(&connectionSem,wpool,ReceiverLog,c); SenderLog->WriteMessage(INFO,"[Main Process] Starting Sender"); ReceiverLog->WriteMessage(INFO,"[Main Process] Starting Sender"); SenderThread = new std::thread( [ ] { sender->Start(); }); SenderThread->detach(); ReceiverLog->WriteMessage(INFO,"[Main Process] Starting Receiver"); SenderLog->WriteMessage(INFO,"[Main Process] Starting Receiver"); receiver->Start(); } if (!sigint) { delete (c); delete (wpool); delete (sender); delete (receiver); CRYPTO_cleanup_all_ex_data(); kill_locks(); ERR_remove_state(0); ERR_free_strings(); EVP_cleanup(); sem_destroy(&connectionSem); delete (SenderThread); delete (SenderLog); delete (ReceiverLog); exit(EXIT_FAILURE); } return (0); } <|endoftext|>
<commit_before>#include <iostream> #include <iterator> #include <sstream> #include <unordered_map> #include <stdexcept> #include <memory> #include <random> #include <cmath> #include <GL/glew.h> #include <GL/glut.h> #include "scope.hh" #include "parser.hh" #include "value.hh" #include "exception.hh" #include "draw/input.h" #include "draw/texture.h" #include "draw/render_target.h" #include "draw/draw2d.h" namespace izna { std::shared_ptr<scope> cur_scope = nullptr; class break_stmt: public std::exception {}; class next_stmt : public std::exception {}; void pushScope() { cur_scope = std::make_shared<scope>(cur_scope); } void popScope() { cur_scope = cur_scope->m_prev; } value eval_tree(std::shared_ptr<node> node); value ExecFunc(value func_val, std::vector<value> &&args) { value result; if (func_val.isFunc()) { auto &f = func_val.toFunc(); auto previous_scope = cur_scope; cur_scope = f.scope; pushScope(); { auto cur_param = f.params; auto cur_arg = args.begin(); while (cur_param != nullptr) { cur_scope->setValue(cur_param->m_string, *cur_arg); cur_param = cur_param->m_right; ++cur_arg; } result = eval_tree(f.stmt); } popScope(); cur_scope = previous_scope; } else if (func_val.isNativeFunc()) { auto f = func_val.toNativeFunc(); result = f(args); } else { throw type_error(); } return result; } value eval_tree(std::shared_ptr<node> node) { if (!node) { return value(); } switch (node->m_op) { case OP_ADD: return eval_tree(node->m_left).Add(eval_tree(node->m_right)); case OP_SUBTRACT: return eval_tree(node->m_left).Sub(eval_tree(node->m_right)); case OP_MULTIPLY: return eval_tree(node->m_left).Mul(eval_tree(node->m_right)); case OP_DIVIDE: return eval_tree(node->m_left).Div(eval_tree(node->m_right)); case OP_MODULO: return eval_tree(node->m_left).Mod(eval_tree(node->m_right)); case OP_LOGICAL_OR: return eval_tree(node->m_left).LOr(eval_tree(node->m_right)); case OP_LOGICAL_AND: return eval_tree(node->m_left).LAnd(eval_tree(node->m_right)); case OP_EQ: return eval_tree(node->m_left).Eq(eval_tree(node->m_right)); case OP_NE: return eval_tree(node->m_left).Ne(eval_tree(node->m_right)); case OP_LESS: return eval_tree(node->m_left).Less(eval_tree(node->m_right)); case OP_LESS_EQ: return eval_tree(node->m_left).LessEq(eval_tree(node->m_right)); case OP_GREATER: return eval_tree(node->m_left).Greater(eval_tree(node->m_right)); case OP_GREATER_EQ: return eval_tree(node->m_left).GreaterEq(eval_tree(node->m_right)); case OP_ASSIGN: return eval_tree(node->m_left).Assign(eval_tree(node->m_right)); case OP_NEG: return eval_tree(node->m_left).Neg(); case OP_IDENTIFIER: { auto v = cur_scope->getValue(node->m_string); if (!v) { cur_scope->setValue(node->m_string, value()); v = cur_scope->getValue(node->m_string); } return value(v); } case OP_CONST: return *(node->m_value); case OP_CLOSURE: { auto &func = node->m_value->toFunc(); func.scope = cur_scope; return *(node->m_value); } case OP_CONTINUE: eval_tree(node->m_left); return eval_tree(node->m_right); case OP_IF: { if (eval_tree(node->m_cond).toBoolean()) { return eval_tree(node->m_left); } else { return eval_tree(node->m_right); } } case OP_NEXT: throw next_stmt(); case OP_BREAK: throw break_stmt(); case OP_WHILE: { value val = value(); for(;;) { if (!eval_tree(node->m_cond).toBoolean()) { break; } try { val = eval_tree(node->m_left); } catch (next_stmt) { } catch (break_stmt) { break; } } return val; } case OP_EXECFUNC: { pushScope(); std::vector<value> args; auto cur_arg = node->m_right; while (cur_arg != nullptr) { args.push_back(eval_tree(cur_arg->m_left)); cur_arg = cur_arg->m_right; } value result = ExecFunc(eval_tree(node->m_left), std::move(args)); popScope(); return result; } case OP_ARRAY: { std::vector<value> arr; auto cur_elem = node->m_left; while (cur_elem != nullptr) { arr.push_back(eval_tree(cur_elem->m_left)); cur_elem = cur_elem->m_right; } return value(std::move(arr)); } case OP_OBJECT: { std::unordered_map<std::string, value> obj; auto cur_elem = node->m_left; while (cur_elem != nullptr) { obj[cur_elem->m_left->m_string] = eval_tree(cur_elem->m_left->m_right); cur_elem = cur_elem->m_right; } return value(std::move(obj)); } case OP_INDEX: { auto lv = eval_tree(node->m_left); if (lv.isArray()) { auto &arr = lv.toArray(); int rv_int; if (node->m_right) { rv_int = eval_tree(node->m_right).toInteger(); } else { rv_int = arr.size(); } if (arr.size() <= rv_int) { while (arr.capacity() <= rv_int) { if (arr.capacity() == 0) { arr.reserve(1); } else { arr.reserve(arr.capacity() * 2); } } arr.resize(rv_int + 1); } return value(&arr[rv_int]); } else if (lv.isObject()) { auto &obj = lv.toUnorderedMap(); return value(&obj[eval_tree(node->m_right).toString()]); } } } return value(); } } //izna const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; const char *WINDOW_TITLE = "iznagame"; const int TIMER_INTERVAL = 16; void Reshape(int w, int h); void Timer(int); bool InitResources(); void Draw(); std::vector<stg::Texture_ptr> g_textures; izna::value g_drawfunc; stg::input::Key GetKey(std::string str) { if (str == "ESC") { return stg::input::Key::Esc(); } else if(str == "UP") { return stg::input::Key::Up(); } else if(str == "DOWN") { return stg::input::Key::Down(); } else if(str == "LEFT") { return stg::input::Key::Left(); } else if(str == "RIGHT") { return stg::input::Key::Right(); } else { return stg::input::Key(str[0]); } } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutCreateWindow(WINDOW_TITLE); glutDisplayFunc(Draw); glutReshapeFunc(Reshape); glutTimerFunc(TIMER_INTERVAL, Timer, 0); if (glewInit() != GLEW_OK) { std::cerr << "ERROR: Failed to initialize GLEW" << std::endl; return 1; } if (!GLEW_EXT_framebuffer_object) { std::cerr << "ERROR: EXT_framebuffer_objet is not supported in this environment" << std::endl; return 1; } stg::input::Init(); if (!InitResources()) { return 1; } { std::string str((std::istreambuf_iterator<char>(std::cin)), (std::istreambuf_iterator<char>())); izna::parser_params params(str.c_str(), str.size()); izna::parser parser(params); if (parser.parse() != 0 || !params.root) { std::cout << "Failed to parse the input file." << std::endl; return 1; } izna::pushScope(); izna::cur_scope->setValue( "print", izna::value([](std::vector<izna::value> args) -> izna::value { std::cout << args[0].toString(); return izna::value(); }) ); izna::cur_scope->setValue( "LoadPNG", izna::value([](std::vector<izna::value> args) -> izna::value { g_textures.push_back(stg::LoadPNG(args[0].toString().c_str())); return izna::value(static_cast<int>(g_textures.size() - 1)); }) ); izna::cur_scope->setValue( "MainLoop", izna::value([](std::vector<izna::value> args) -> izna::value { g_drawfunc = args[0]; return izna::value(); }) ); izna::cur_scope->setValue( "Draw", izna::value([](std::vector<izna::value> args) -> izna::value { stg::Drawer2D( g_textures[args[0].toInteger()], args[1].toInteger(), args[2].toInteger()).Apply(); return izna::value(); }) ); izna::cur_scope->setValue( "KeyIsPushed", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(GetKey(args[0].toString()).IsPushed()); }) ); izna::cur_scope->setValue( "KeyIsHolded", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(GetKey(args[0].toString()).IsHolded()); }) ); izna::cur_scope->setValue( "KeyIsReleased", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(GetKey(args[0].toString()).IsReleased()); }) ); izna::cur_scope->setValue( "Draw", izna::value([](std::vector<izna::value> args) -> izna::value { stg::Drawer2D( g_textures[args[0].toInteger()], args[1].toInteger(), args[2].toInteger()).Apply(); return izna::value(); }) ); izna::cur_scope->setValue( "sin", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(std::sin(args[0].toReal())); }) ); izna::cur_scope->setValue( "cos", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(std::cos(args[0].toReal())); }) ); izna::cur_scope->setValue( "tan", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(std::tan(args[0].toReal())); }) ); izna::cur_scope->setValue( "rand", izna::value([](std::vector<izna::value> args) -> izna::value { static std::mt19937 mt; std::uniform_real_distribution<double> rand_range(0.0, 1.0); return izna::value(rand_range(mt)); }) ); izna::cur_scope->setValue( "ArraySize", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(static_cast<int>(args[0].toArray().size())); }) ); izna::cur_scope->setValue( "ArrayPushBack", izna::value([](std::vector<izna::value> args) -> izna::value { args[0].toArray().push_back(args[1]); return izna::value(); }) ); izna::eval_tree(params.root); glutMainLoop(); izna::popScope(); } return 0; } void Reshape(int w, int h) { if (w != WINDOW_WIDTH || h != WINDOW_HEIGHT) { glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT); } } void Timer(int) { glutPostRedisplay(); glutTimerFunc(TIMER_INTERVAL, Timer, 0); } bool InitResources() { return true; } void Draw() { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); stg::Draw2D([](){ ExecFunc(g_drawfunc, std::vector<izna::value>()); }); glFlush(); glutSwapBuffers(); stg::input::Update(); } <commit_msg>for console applications<commit_after>#include <iostream> #include <iterator> #include <sstream> #include <unordered_map> #include <stdexcept> #include <memory> #include <random> #include <cmath> #include <GL/glew.h> #include <GL/glut.h> #include "scope.hh" #include "parser.hh" #include "value.hh" #include "exception.hh" #include "draw/input.h" #include "draw/texture.h" #include "draw/render_target.h" #include "draw/draw2d.h" namespace izna { std::shared_ptr<scope> cur_scope = nullptr; class break_stmt: public std::exception {}; class next_stmt : public std::exception {}; void pushScope() { cur_scope = std::make_shared<scope>(cur_scope); } void popScope() { cur_scope = cur_scope->m_prev; } value eval_tree(std::shared_ptr<node> node); value ExecFunc(value func_val, std::vector<value> &&args) { value result; if (func_val.isFunc()) { auto &f = func_val.toFunc(); auto previous_scope = cur_scope; cur_scope = f.scope; pushScope(); { auto cur_param = f.params; auto cur_arg = args.begin(); while (cur_param != nullptr) { cur_scope->setValue(cur_param->m_string, *cur_arg); cur_param = cur_param->m_right; ++cur_arg; } result = eval_tree(f.stmt); } popScope(); cur_scope = previous_scope; } else if (func_val.isNativeFunc()) { auto f = func_val.toNativeFunc(); result = f(args); } else { throw type_error(); } return result; } value eval_tree(std::shared_ptr<node> node) { if (!node) { return value(); } switch (node->m_op) { case OP_ADD: return eval_tree(node->m_left).Add(eval_tree(node->m_right)); case OP_SUBTRACT: return eval_tree(node->m_left).Sub(eval_tree(node->m_right)); case OP_MULTIPLY: return eval_tree(node->m_left).Mul(eval_tree(node->m_right)); case OP_DIVIDE: return eval_tree(node->m_left).Div(eval_tree(node->m_right)); case OP_MODULO: return eval_tree(node->m_left).Mod(eval_tree(node->m_right)); case OP_LOGICAL_OR: return eval_tree(node->m_left).LOr(eval_tree(node->m_right)); case OP_LOGICAL_AND: return eval_tree(node->m_left).LAnd(eval_tree(node->m_right)); case OP_EQ: return eval_tree(node->m_left).Eq(eval_tree(node->m_right)); case OP_NE: return eval_tree(node->m_left).Ne(eval_tree(node->m_right)); case OP_LESS: return eval_tree(node->m_left).Less(eval_tree(node->m_right)); case OP_LESS_EQ: return eval_tree(node->m_left).LessEq(eval_tree(node->m_right)); case OP_GREATER: return eval_tree(node->m_left).Greater(eval_tree(node->m_right)); case OP_GREATER_EQ: return eval_tree(node->m_left).GreaterEq(eval_tree(node->m_right)); case OP_ASSIGN: return eval_tree(node->m_left).Assign(eval_tree(node->m_right)); case OP_NEG: return eval_tree(node->m_left).Neg(); case OP_IDENTIFIER: { auto v = cur_scope->getValue(node->m_string); if (!v) { cur_scope->setValue(node->m_string, value()); v = cur_scope->getValue(node->m_string); } return value(v); } case OP_CONST: return *(node->m_value); case OP_CLOSURE: { auto &func = node->m_value->toFunc(); func.scope = cur_scope; return *(node->m_value); } case OP_CONTINUE: eval_tree(node->m_left); return eval_tree(node->m_right); case OP_IF: { if (eval_tree(node->m_cond).toBoolean()) { return eval_tree(node->m_left); } else { return eval_tree(node->m_right); } } case OP_NEXT: throw next_stmt(); case OP_BREAK: throw break_stmt(); case OP_WHILE: { value val = value(); for(;;) { if (!eval_tree(node->m_cond).toBoolean()) { break; } try { val = eval_tree(node->m_left); } catch (next_stmt) { } catch (break_stmt) { break; } } return val; } case OP_EXECFUNC: { pushScope(); std::vector<value> args; auto cur_arg = node->m_right; while (cur_arg != nullptr) { args.push_back(eval_tree(cur_arg->m_left)); cur_arg = cur_arg->m_right; } value result = ExecFunc(eval_tree(node->m_left), std::move(args)); popScope(); return result; } case OP_ARRAY: { std::vector<value> arr; auto cur_elem = node->m_left; while (cur_elem != nullptr) { arr.push_back(eval_tree(cur_elem->m_left)); cur_elem = cur_elem->m_right; } return value(std::move(arr)); } case OP_OBJECT: { std::unordered_map<std::string, value> obj; auto cur_elem = node->m_left; while (cur_elem != nullptr) { obj[cur_elem->m_left->m_string] = eval_tree(cur_elem->m_left->m_right); cur_elem = cur_elem->m_right; } return value(std::move(obj)); } case OP_INDEX: { auto lv = eval_tree(node->m_left); if (lv.isArray()) { auto &arr = lv.toArray(); int rv_int; if (node->m_right) { rv_int = eval_tree(node->m_right).toInteger(); } else { rv_int = arr.size(); } if (arr.size() <= rv_int) { while (arr.capacity() <= rv_int) { if (arr.capacity() == 0) { arr.reserve(1); } else { arr.reserve(arr.capacity() * 2); } } arr.resize(rv_int + 1); } return value(&arr[rv_int]); } else if (lv.isObject()) { auto &obj = lv.toUnorderedMap(); return value(&obj[eval_tree(node->m_right).toString()]); } } } return value(); } } //izna const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; const char *WINDOW_TITLE = "iznagame"; const int TIMER_INTERVAL = 16; void Reshape(int w, int h); void Timer(int); bool InitResources(); void Draw(); std::vector<stg::Texture_ptr> g_textures; izna::value g_drawfunc; stg::input::Key GetKey(std::string str) { if (str == "ESC") { return stg::input::Key::Esc(); } else if(str == "UP") { return stg::input::Key::Up(); } else if(str == "DOWN") { return stg::input::Key::Down(); } else if(str == "LEFT") { return stg::input::Key::Left(); } else if(str == "RIGHT") { return stg::input::Key::Right(); } else { return stg::input::Key(str[0]); } } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutCreateWindow(WINDOW_TITLE); glutDisplayFunc(Draw); glutReshapeFunc(Reshape); glutTimerFunc(TIMER_INTERVAL, Timer, 0); if (glewInit() != GLEW_OK) { std::cerr << "ERROR: Failed to initialize GLEW" << std::endl; return 1; } if (!GLEW_EXT_framebuffer_object) { std::cerr << "ERROR: EXT_framebuffer_objet is not supported in this environment" << std::endl; return 1; } stg::input::Init(); if (!InitResources()) { return 1; } { std::string str((std::istreambuf_iterator<char>(std::cin)), (std::istreambuf_iterator<char>())); izna::parser_params params(str.c_str(), str.size()); izna::parser parser(params); if (parser.parse() != 0 || !params.root) { std::cout << "Failed to parse the input file." << std::endl; return 1; } izna::pushScope(); izna::cur_scope->setValue( "print", izna::value([](std::vector<izna::value> args) -> izna::value { std::cout << args[0].toString(); return izna::value(); }) ); izna::cur_scope->setValue( "LoadPNG", izna::value([](std::vector<izna::value> args) -> izna::value { g_textures.push_back(stg::LoadPNG(args[0].toString().c_str())); return izna::value(static_cast<int>(g_textures.size() - 1)); }) ); izna::cur_scope->setValue( "MainLoop", izna::value([](std::vector<izna::value> args) -> izna::value { g_drawfunc = args[0]; return izna::value(); }) ); izna::cur_scope->setValue( "Draw", izna::value([](std::vector<izna::value> args) -> izna::value { stg::Drawer2D( g_textures[args[0].toInteger()], args[1].toInteger(), args[2].toInteger()).Apply(); return izna::value(); }) ); izna::cur_scope->setValue( "KeyIsPushed", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(GetKey(args[0].toString()).IsPushed()); }) ); izna::cur_scope->setValue( "KeyIsHolded", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(GetKey(args[0].toString()).IsHolded()); }) ); izna::cur_scope->setValue( "KeyIsReleased", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(GetKey(args[0].toString()).IsReleased()); }) ); izna::cur_scope->setValue( "Draw", izna::value([](std::vector<izna::value> args) -> izna::value { stg::Drawer2D( g_textures[args[0].toInteger()], args[1].toInteger(), args[2].toInteger()).Apply(); return izna::value(); }) ); izna::cur_scope->setValue( "sin", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(std::sin(args[0].toReal())); }) ); izna::cur_scope->setValue( "cos", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(std::cos(args[0].toReal())); }) ); izna::cur_scope->setValue( "tan", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(std::tan(args[0].toReal())); }) ); izna::cur_scope->setValue( "rand", izna::value([](std::vector<izna::value> args) -> izna::value { static std::mt19937 mt; std::uniform_real_distribution<double> rand_range(0.0, 1.0); return izna::value(rand_range(mt)); }) ); izna::cur_scope->setValue( "ArraySize", izna::value([](std::vector<izna::value> args) -> izna::value { return izna::value(static_cast<int>(args[0].toArray().size())); }) ); izna::cur_scope->setValue( "ArrayPushBack", izna::value([](std::vector<izna::value> args) -> izna::value { args[0].toArray().push_back(args[1]); return izna::value(); }) ); izna::eval_tree(params.root); if (!g_drawfunc.isNil()) { glutMainLoop(); } izna::popScope(); } return 0; } void Reshape(int w, int h) { if (w != WINDOW_WIDTH || h != WINDOW_HEIGHT) { glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT); } } void Timer(int) { glutPostRedisplay(); glutTimerFunc(TIMER_INTERVAL, Timer, 0); } bool InitResources() { return true; } void Draw() { glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); stg::Draw2D([](){ ExecFunc(g_drawfunc, std::vector<izna::value>()); }); glFlush(); glutSwapBuffers(); stg::input::Update(); } <|endoftext|>
<commit_before>/* * This file is part of the LibreOffice project. * * Based on LLVM/Clang. * * This file is distributed under the University of Illinois Open Source * License. See LICENSE.TXT for details. * */ #include "plugin.hxx" #include <clang/Lex/Preprocessor.h> namespace loplugin { /* This is a compile check. Feature macros from config_XXX.h headers are always #defined (to 1 or 0 in case of yes/no settings). It is a mistake to use #ifdef/#ifndef/defined to check them. Using 1/0 instead of defined/undefined avoids undetected problems when e.g. the necessary #include of the config_XXX.h file is missing. */ class CheckConfigMacros : public PPCallbacks , public Plugin { public: explicit CheckConfigMacros( CompilerInstance& compiler ); virtual void run() override; #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 virtual void MacroDefined( const Token& macroToken, const MacroInfo* info ) override; virtual void MacroUndefined( const Token& macroToken, const MacroInfo* info ) override; virtual void Ifdef( SourceLocation location, const Token& macroToken ) override; virtual void Ifndef( SourceLocation location, const Token& macroToken ) override; virtual void Defined( const Token& macroToken ) override; #else virtual void MacroDefined( const Token& macroToken, const MacroDirective* info ) override; virtual void MacroUndefined( const Token& macroToken, const MacroDirective* info ) override; virtual void Ifdef( SourceLocation location, const Token& macroToken, const MacroDirective* info ) override; virtual void Ifndef( SourceLocation location, const Token& macroToken, const MacroDirective* info ) override; virtual void Defined( const Token& macroToken, const MacroDirective* info ) override; #endif private: void checkMacro( const Token& macroToken, SourceLocation location ); std::set< string > configMacros; }; CheckConfigMacros::CheckConfigMacros( CompilerInstance& compiler ) : Plugin( compiler ) { compiler.getPreprocessor().addPPCallbacks( this ); } void CheckConfigMacros::run() { // nothing, only check preprocessor usage } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::MacroDefined( const Token& macroToken, const MacroInfo* info ) { SourceLocation location = info->getDefinitionLoc(); #else void CheckConfigMacros::MacroDefined( const Token& macroToken, const MacroDirective* info ) { SourceLocation location = info->getLocation(); #endif const char* filename = compiler.getSourceManager().getPresumedLoc( location ).getFilename(); if( filename != NULL && ( strncmp( filename, BUILDDIR "/config_host/", strlen( BUILDDIR "/config_host/" )) == 0 || strncmp( filename, BUILDDIR "/config_build/", strlen( BUILDDIR "/config_build/" )) == 0 )) { // fprintf(stderr,"DEF: %s %s\n", macroToken.getIdentifierInfo()->getName().data(), filename ); configMacros.insert( macroToken.getIdentifierInfo()->getName()); } } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::MacroUndefined( const Token& macroToken, const MacroInfo* ) #else void CheckConfigMacros::MacroUndefined( const Token& macroToken, const MacroDirective* ) #endif { configMacros.erase( macroToken.getIdentifierInfo()->getName()); } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::Ifdef( SourceLocation location, const Token& macroToken ) #else void CheckConfigMacros::Ifdef( SourceLocation location, const Token& macroToken, const MacroDirective* ) #endif { checkMacro( macroToken, location ); } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::Ifndef( SourceLocation location, const Token& macroToken ) #else void CheckConfigMacros::Ifndef( SourceLocation location, const Token& macroToken, const MacroDirective* ) #endif { checkMacro( macroToken, location ); } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::Defined( const Token& macroToken ) #else void CheckConfigMacros::Defined( const Token& macroToken, const MacroDirective* ) #endif { checkMacro( macroToken, macroToken.getLocation()); } void CheckConfigMacros::checkMacro( const Token& macroToken, SourceLocation location ) { if( configMacros.find( macroToken.getIdentifierInfo()->getName()) != configMacros.end()) { report( DiagnosticsEngine::Error, "checking whether a config macro %0 is defined", location ) << macroToken.getIdentifierInfo()->getName(); report( DiagnosticsEngine::Note, "use #if instead of #ifdef/#ifndef/defined", location ); } } static Plugin::Registration< CheckConfigMacros > X( "bodynotinblock" ); } // namespace <commit_msg>Adapt to PPCallbacks.h changes on Clang trunk towards 3.4<commit_after>/* * This file is part of the LibreOffice project. * * Based on LLVM/Clang. * * This file is distributed under the University of Illinois Open Source * License. See LICENSE.TXT for details. * */ #include "plugin.hxx" #include <clang/Lex/Preprocessor.h> namespace loplugin { /* This is a compile check. Feature macros from config_XXX.h headers are always #defined (to 1 or 0 in case of yes/no settings). It is a mistake to use #ifdef/#ifndef/defined to check them. Using 1/0 instead of defined/undefined avoids undetected problems when e.g. the necessary #include of the config_XXX.h file is missing. */ class CheckConfigMacros : public PPCallbacks , public Plugin { public: explicit CheckConfigMacros( CompilerInstance& compiler ); virtual void run() override; #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 virtual void MacroDefined( const Token& macroToken, const MacroInfo* info ) override; virtual void MacroUndefined( const Token& macroToken, const MacroInfo* info ) override; virtual void Ifdef( SourceLocation location, const Token& macroToken ) override; virtual void Ifndef( SourceLocation location, const Token& macroToken ) override; virtual void Defined( const Token& macroToken ) override; #else virtual void MacroDefined( const Token& macroToken, const MacroDirective* info ) override; virtual void MacroUndefined( const Token& macroToken, const MacroDirective* info ) override; virtual void Ifdef( SourceLocation location, const Token& macroToken, const MacroDirective* info ) override; virtual void Ifndef( SourceLocation location, const Token& macroToken, const MacroDirective* info ) override; #if __clang_major__ == 3 && __clang_minor__ < 4 virtual void Defined( const Token& macroToken, const MacroDirective* info ) override; #else virtual void Defined( const Token& macroToken, const MacroDirective* info, SourceRange Range ) override; #endif #endif private: void checkMacro( const Token& macroToken, SourceLocation location ); std::set< string > configMacros; }; CheckConfigMacros::CheckConfigMacros( CompilerInstance& compiler ) : Plugin( compiler ) { compiler.getPreprocessor().addPPCallbacks( this ); } void CheckConfigMacros::run() { // nothing, only check preprocessor usage } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::MacroDefined( const Token& macroToken, const MacroInfo* info ) { SourceLocation location = info->getDefinitionLoc(); #else void CheckConfigMacros::MacroDefined( const Token& macroToken, const MacroDirective* info ) { SourceLocation location = info->getLocation(); #endif const char* filename = compiler.getSourceManager().getPresumedLoc( location ).getFilename(); if( filename != NULL && ( strncmp( filename, BUILDDIR "/config_host/", strlen( BUILDDIR "/config_host/" )) == 0 || strncmp( filename, BUILDDIR "/config_build/", strlen( BUILDDIR "/config_build/" )) == 0 )) { // fprintf(stderr,"DEF: %s %s\n", macroToken.getIdentifierInfo()->getName().data(), filename ); configMacros.insert( macroToken.getIdentifierInfo()->getName()); } } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::MacroUndefined( const Token& macroToken, const MacroInfo* ) #else void CheckConfigMacros::MacroUndefined( const Token& macroToken, const MacroDirective* ) #endif { configMacros.erase( macroToken.getIdentifierInfo()->getName()); } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::Ifdef( SourceLocation location, const Token& macroToken ) #else void CheckConfigMacros::Ifdef( SourceLocation location, const Token& macroToken, const MacroDirective* ) #endif { checkMacro( macroToken, location ); } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::Ifndef( SourceLocation location, const Token& macroToken ) #else void CheckConfigMacros::Ifndef( SourceLocation location, const Token& macroToken, const MacroDirective* ) #endif { checkMacro( macroToken, location ); } #if __clang_major__ < 3 || __clang_major__ == 3 && __clang_minor__ < 3 void CheckConfigMacros::Defined( const Token& macroToken ) #elif __clang_major__ == 3 && __clang_minor__ < 4 void CheckConfigMacros::Defined( const Token& macroToken, const MacroDirective* ) #else void CheckConfigMacros::Defined( const Token& macroToken, const MacroDirective* , SourceRange ) #endif { checkMacro( macroToken, macroToken.getLocation()); } void CheckConfigMacros::checkMacro( const Token& macroToken, SourceLocation location ) { if( configMacros.find( macroToken.getIdentifierInfo()->getName()) != configMacros.end()) { report( DiagnosticsEngine::Error, "checking whether a config macro %0 is defined", location ) << macroToken.getIdentifierInfo()->getName(); report( DiagnosticsEngine::Note, "use #if instead of #ifdef/#ifndef/defined", location ); } } static Plugin::Registration< CheckConfigMacros > X( "bodynotinblock" ); } // namespace <|endoftext|>
<commit_before><commit_msg>more overrides<commit_after><|endoftext|>
<commit_before>// Standard includes #include <iostream> #include <cstdlib> #include <unistd.h> #include <cmath> #include <string.h> #include <inttypes.h> #include <fstream> #include <limits.h> // Serial includes #include <stdio.h> /* Standard input/output definitions */ #include <string.h> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ # #ifdef __linux #include <sys/ioctl.h> #endif #include "serialwifly.h" using std::string; using namespace std; // TODO: Investigate this parameter... what exactly does it do? #define WD 1000 /** * Start serial connection over one some port * * *port should be of the format "/dev/ttyUSB0" */ int start_connection(char *port) { int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY); return fd; } /** * This puts you in command mode * Must wait 250 ms before */ int commandmode(int fd) { // First, we must make sure we are in command mode // For now, let's assume we just booted up write(fd, "exit\r", 5); usleep(WD); write(fd, "exit\r", 5); usleep(WD); /* Give it the turn on command */ /* Must wait 250 ms before and after giving $$$ command */ /* To be safe, I wait 300 ms */ write(fd, "$$$", 3); usleep(300000); return 0; } /** * Parses output from scan command. * Searches for SSID provided. * Returns the RSSI value of that SSID, as an int. */ int getrssi(char *buf, char *ssid) { char *delim = (char *) "\n"; char *token = strtok(buf, delim); int rssi_value = INT_MAX; while (token) { if (strstr(token, ssid) != NULL) { char *comma_delim = (char *) ","; char *jam_token = strtok(token, comma_delim); jam_token = strtok(0, comma_delim); jam_token = strtok(0, comma_delim); rssi_value = atoi(jam_token); token = NULL; } else { token = strtok(0, delim); } } return rssi_value; } /** * Scans the channels and returns the rssi of the specified SSID */ int scanrssi(int fd, char *ssid) { char buf[1000]; write(fd, "scan 10\r", 8); usleep(1000000); read(fd, buf, sizeof(buf)); return getrssi(buf, ssid); } /** * Scans numtimes times and prints rssi values to a line in a file */ int scanrssi_f(int fd, char *ssid, FILE *f, int numtimes) { int rssi_value, i; for (i = 1; i <= (numtimes-1); i++) { rssi_value = scanrssi(fd, ssid); fprintf(f, "%i,", rssi_value); //printf("rssi_value = %i\n", rssi_value); } /* Don't include comma for last one */ rssi_value = scanrssi(fd, ssid); fprintf(f, "%i\n", rssi_value); //printf("rssi_value = %i\n", rssi_value); return rssi; } /** * Scans numtimes times and prints rssi values to a line in a file */ int scanrssi_2(int fd1, int fd2, char *ssid, FILE *f1, FILE *f2, int numtimes) { int rssi_1, rssi_2, i; for (i = 1; i <= (numtimes-1); i++) { rssi_1 = scanrssi(fd1, ssid); rssi_2 = scanrssi(fd2, ssid); fprintf(f1, "%i,", rssi_1); fprintf(f2, "%i,", rssi_2); printf("Wifly 1 RSSI = %i\n", rssi_1); printf("Wifly 2 RSSI = %i\n", rssi_2); } /* Don't include comma for last one */ rssi_1 = scanrssi(fd1, ssid); rssi_2 = scanrssi(fd2, ssid); fprintf(f1, "%i\n", rssi_1); fprintf(f2, "%i\n", rssi_2); printf("Wifly 1 RSSI = %i\n", rssi_1); printf("Wifly 2 RSSI = %i\n", rssi_2); return 0; } <commit_msg>fix typo in rssi return value<commit_after>// Standard includes #include <iostream> #include <cstdlib> #include <unistd.h> #include <cmath> #include <string.h> #include <inttypes.h> #include <fstream> #include <limits.h> // Serial includes #include <stdio.h> /* Standard input/output definitions */ #include <string.h> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ # #ifdef __linux #include <sys/ioctl.h> #endif #include "serialwifly.h" using std::string; using namespace std; // TODO: Investigate this parameter... what exactly does it do? #define WD 1000 /** * Start serial connection over one some port * * *port should be of the format "/dev/ttyUSB0" */ int start_connection(char *port) { int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY); return fd; } /** * This puts you in command mode * Must wait 250 ms before */ int commandmode(int fd) { // First, we must make sure we are in command mode // For now, let's assume we just booted up write(fd, "exit\r", 5); usleep(WD); write(fd, "exit\r", 5); usleep(WD); /* Give it the turn on command */ /* Must wait 250 ms before and after giving $$$ command */ /* To be safe, I wait 300 ms */ write(fd, "$$$", 3); usleep(300000); return 0; } /** * Parses output from scan command. * Searches for SSID provided. * Returns the RSSI value of that SSID, as an int. */ int getrssi(char *buf, char *ssid) { char *delim = (char *) "\n"; char *token = strtok(buf, delim); int rssi_value = INT_MAX; while (token) { if (strstr(token, ssid) != NULL) { char *comma_delim = (char *) ","; char *jam_token = strtok(token, comma_delim); jam_token = strtok(0, comma_delim); jam_token = strtok(0, comma_delim); rssi_value = atoi(jam_token); token = NULL; } else { token = strtok(0, delim); } } return rssi_value; } /** * Scans the channels and returns the rssi of the specified SSID */ int scanrssi(int fd, char *ssid) { char buf[1000]; write(fd, "scan 10\r", 8); usleep(1000000); read(fd, buf, sizeof(buf)); return getrssi(buf, ssid); } /** * Scans numtimes times and prints rssi values to a line in a file */ int scanrssi_f(int fd, char *ssid, FILE *f, int numtimes) { int rssi_value, i; for (i = 1; i <= (numtimes-1); i++) { rssi_value = scanrssi(fd, ssid); fprintf(f, "%i,", rssi_value); //printf("rssi_value = %i\n", rssi_value); } /* Don't include comma for last one */ rssi_value = scanrssi(fd, ssid); fprintf(f, "%i\n", rssi_value); //printf("rssi_value = %i\n", rssi_value); return rssi_value; } /** * Scans numtimes times and prints rssi values to a line in a file */ int scanrssi_2(int fd1, int fd2, char *ssid, FILE *f1, FILE *f2, int numtimes) { int rssi_1, rssi_2, i; for (i = 1; i <= (numtimes-1); i++) { rssi_1 = scanrssi(fd1, ssid); rssi_2 = scanrssi(fd2, ssid); fprintf(f1, "%i,", rssi_1); fprintf(f2, "%i,", rssi_2); printf("Wifly 1 RSSI = %i\n", rssi_1); printf("Wifly 2 RSSI = %i\n", rssi_2); } /* Don't include comma for last one */ rssi_1 = scanrssi(fd1, ssid); rssi_2 = scanrssi(fd2, ssid); fprintf(f1, "%i\n", rssi_1); fprintf(f2, "%i\n", rssi_2); printf("Wifly 1 RSSI = %i\n", rssi_1); printf("Wifly 2 RSSI = %i\n", rssi_2); return 0; } <|endoftext|>
<commit_before>#include <typeinfo> #include <array> #include <algorithm> #include "gtest.h" #include "util/optional.hpp" using namespace nest::mc::util; TEST(optionalm,ctors) { optional<int> a,b(3),c=b,d=4; ASSERT_FALSE((bool)a); ASSERT_TRUE((bool)b); ASSERT_TRUE((bool)c); ASSERT_TRUE((bool)d); EXPECT_EQ(3,b.get()); EXPECT_EQ(3,c.get()); EXPECT_EQ(4,d.get()); } TEST(optionalm,unset_throw) { optional<int> a; int check=10; try { a.get(); } catch(optional_unset_error &e) { ++check; } EXPECT_EQ(11,check); check=20; a=2; try { a.get(); } catch(optional_unset_error &e) { ++check; } EXPECT_EQ(20,check); check=30; a.reset(); try { a.get(); } catch(optional_unset_error &e) { ++check; } EXPECT_EQ(31,check); } TEST(optionalm,deref) { struct foo { int a; explicit foo(int a_): a(a_) {} double value() { return 3.0*a; } }; optional<foo> f=foo(2); EXPECT_EQ(6.0,f->value()); EXPECT_EQ(2,(*f).a); } TEST(optionalm,ctor_conv) { optional<std::array<int,3>> x{{1,2,3}}; EXPECT_EQ(3u,x->size()); } TEST(optionalm,ctor_ref) { int v=10; optional<int &> a(v); EXPECT_EQ(10,a.get()); v=20; EXPECT_EQ(20,a.get()); optional<int &> b(a),c=b,d=v; EXPECT_EQ(&(a.get()),&(b.get())); EXPECT_EQ(&(a.get()),&(c.get())); EXPECT_EQ(&(a.get()),&(d.get())); } TEST(optionalm,assign_returns) { optional<int> a=3; auto b=(a=4); EXPECT_EQ(typeid(optional<int>),typeid(b)); auto bp=&(a=4); EXPECT_EQ(&a,bp); } TEST(optionalm,assign_reference) { double a=3.0; optional<double &> ar; optional<double &> br; ar = a; EXPECT_TRUE(ar); *ar = 5.0; EXPECT_EQ(5.0, a); br = ar; EXPECT_TRUE(br); *br = 7.0; EXPECT_EQ(7.0, a); } struct nomove { int value; nomove(): value(0) {} nomove(int i): value(i) {} nomove(const nomove &n): value(n.value) {} nomove(nomove &&n) = delete; nomove &operator=(const nomove &n) { value=n.value; return *this; } bool operator==(const nomove &them) const { return them.value==value; } bool operator!=(const nomove &them) const { return !(*this==them); } }; TEST(optionalm,ctor_nomove) { optional<nomove> a(nomove(3)); EXPECT_EQ(nomove(3),a.get()); optional<nomove> b; b=a; EXPECT_EQ(nomove(3),b.get()); b=optional<nomove>(nomove(4)); EXPECT_EQ(nomove(4),b.get()); } struct nocopy { int value; nocopy(): value(0) {} nocopy(int i): value(i) {} nocopy(const nocopy &n) = delete; nocopy(nocopy &&n) { value=n.value; n.value=0; } nocopy &operator=(const nocopy &n) = delete; nocopy &operator=(nocopy &&n) { value=n.value; n.value=-1; return *this; } bool operator==(const nocopy &them) const { return them.value==value; } bool operator!=(const nocopy &them) const { return !(*this==them); } }; TEST(optionalm,ctor_nocopy) { optional<nocopy> a(nocopy(5)); EXPECT_EQ(nocopy(5),a.get()); optional<nocopy> b(std::move(a)); EXPECT_EQ(nocopy(5),b.get()); EXPECT_EQ(0,a.get().value); b=optional<nocopy>(nocopy(6)); EXPECT_EQ(nocopy(6),b.get()); } static optional<double> odd_half(int n) { optional<double> h; if (n%2==1) h=n/2.0; return h; } TEST(optionalm,bind) { optional<int> a; auto b=a.bind(odd_half); EXPECT_EQ(typeid(optional<double>),typeid(b)); a=10; b=a.bind(odd_half); EXPECT_FALSE((bool)b); a=11; b=a.bind(odd_half); EXPECT_TRUE((bool)b); EXPECT_EQ(5.5,b.get()); b=a >> odd_half >> [](double x) { return (int)x; } >> odd_half; EXPECT_TRUE((bool)b); EXPECT_EQ(2.5,b.get()); } TEST(optionalm,void) { optional<void> a,b(true),c(a),d=b,e(false); EXPECT_FALSE((bool)a); EXPECT_TRUE((bool)b); EXPECT_FALSE((bool)c); EXPECT_TRUE((bool)d); EXPECT_TRUE((bool)e); auto x=a >> []() { return 1; }; EXPECT_FALSE((bool)x); x=b >> []() { return 1; }; EXPECT_TRUE((bool)x); EXPECT_EQ(1,x.get()); } TEST(optionalm,bind_to_void) { optional<int> a,b(3); int call_count=0; auto vf=[&call_count](int i) -> void { ++call_count; }; auto x=a >> vf; EXPECT_EQ(typeid(optional<void>),typeid(x)); EXPECT_FALSE((bool)x); EXPECT_EQ(0,call_count); call_count=0; x=b >> vf; EXPECT_TRUE((bool)x); EXPECT_EQ(1,call_count); } TEST(optionalm,bind_to_optional_void) { optional<int> a,b(3),c(4); int count=0; auto count_if_odd=[&count](int i) { return i%2?(++count,optional<void>(true)):optional<void>(); }; auto x=a >> count_if_odd; EXPECT_EQ(typeid(optional<void>),typeid(x)); EXPECT_FALSE((bool)x); EXPECT_EQ(0,count); count=0; x=b >> count_if_odd; EXPECT_TRUE((bool)x); EXPECT_EQ(1,count); count=0; x=c >> count_if_odd; EXPECT_FALSE((bool)x); EXPECT_EQ(0,count); } TEST(optionalm,bind_with_ref) { optional<int> a=10; a >> [](int &v) {++v; }; EXPECT_EQ(11,*a); } struct check_cref { int operator()(const int &) { return 10; } int operator()(int &) { return 11; } }; TEST(optionalm,bind_constness) { check_cref checker; optional<int> a=1; int v=*(a >> checker); EXPECT_EQ(11,v); const optional<int> b=1; v=*(b >> checker); EXPECT_EQ(10,v); } TEST(optionalm,conversion) { optional<double> a(3),b=5; EXPECT_TRUE((bool)a); EXPECT_TRUE((bool)b); EXPECT_EQ(3.0,a.get()); EXPECT_EQ(5.0,b.get()); optional<int> x; optional<double> c(x); optional<double> d=optional<int>(); EXPECT_FALSE((bool)c); EXPECT_FALSE((bool)d); auto doubler=[](double x) { return x*2; }; auto y=optional<int>(3) >> doubler; EXPECT_TRUE((bool)y); EXPECT_EQ(6.0,y.get()); } TEST(optionalm,or_operator) { optional<const char *> default_msg="default"; auto x=(char *)0 | default_msg; EXPECT_TRUE((bool)x); EXPECT_STREQ("default",x.get()); auto y="something" | default_msg; EXPECT_TRUE((bool)y); EXPECT_STREQ("something",y.get()); optional<int> a(1),b,c(3); EXPECT_EQ(1,*(a|b|c)); EXPECT_EQ(1,*(a|c|b)); EXPECT_EQ(1,*(b|a|c)); EXPECT_EQ(3,*(b|c|a)); EXPECT_EQ(3,*(c|a|b)); EXPECT_EQ(3,*(c|b|a)); } TEST(optionalm,and_operator) { optional<int> a(1); optional<double> b(2.0); auto ab=a&b; auto ba=b&a; EXPECT_EQ(typeid(ab),typeid(b)); EXPECT_EQ(typeid(ba),typeid(a)); EXPECT_EQ(2.0,*ab); EXPECT_EQ(1,*ba); auto zb=false & b; EXPECT_EQ(typeid(zb),typeid(b)); EXPECT_FALSE((bool)zb); auto b3=b & 3; EXPECT_EQ(typeid(b3),typeid(optional<int>)); EXPECT_TRUE((bool)b3); EXPECT_EQ(3,*b3); } TEST(optionalm,provided) { std::array<int,3> qs={1,0,3}; std::array<int,3> ps={14,14,14}; std::array<int,3> rs; std::transform(ps.begin(),ps.end(),qs.begin(),rs.begin(), [](int p,int q) { return *( provided(q!=0) >> [=]() { return p/q; } | -1 ); }); EXPECT_EQ(14,rs[0]); EXPECT_EQ(-1,rs[1]); EXPECT_EQ(4,rs[2]); } <commit_msg>Address coding style issue<commit_after>#include <typeinfo> #include <array> #include <algorithm> #include "gtest.h" #include "util/optional.hpp" using namespace nest::mc::util; TEST(optionalm,ctors) { optional<int> a,b(3),c=b,d=4; ASSERT_FALSE((bool)a); ASSERT_TRUE((bool)b); ASSERT_TRUE((bool)c); ASSERT_TRUE((bool)d); EXPECT_EQ(3,b.get()); EXPECT_EQ(3,c.get()); EXPECT_EQ(4,d.get()); } TEST(optionalm,unset_throw) { optional<int> a; int check=10; try { a.get(); } catch(optional_unset_error &e) { ++check; } EXPECT_EQ(11,check); check=20; a=2; try { a.get(); } catch(optional_unset_error &e) { ++check; } EXPECT_EQ(20,check); check=30; a.reset(); try { a.get(); } catch(optional_unset_error &e) { ++check; } EXPECT_EQ(31,check); } TEST(optionalm,deref) { struct foo { int a; explicit foo(int a_): a(a_) {} double value() { return 3.0*a; } }; optional<foo> f=foo(2); EXPECT_EQ(6.0,f->value()); EXPECT_EQ(2,(*f).a); } TEST(optionalm,ctor_conv) { optional<std::array<int,3>> x{{1,2,3}}; EXPECT_EQ(3u,x->size()); } TEST(optionalm,ctor_ref) { int v=10; optional<int &> a(v); EXPECT_EQ(10,a.get()); v=20; EXPECT_EQ(20,a.get()); optional<int &> b(a),c=b,d=v; EXPECT_EQ(&(a.get()),&(b.get())); EXPECT_EQ(&(a.get()),&(c.get())); EXPECT_EQ(&(a.get()),&(d.get())); } TEST(optionalm,assign_returns) { optional<int> a=3; auto b=(a=4); EXPECT_EQ(typeid(optional<int>),typeid(b)); auto bp=&(a=4); EXPECT_EQ(&a,bp); } TEST(optionalm,assign_reference) { double a=3.0; optional<double&> ar; optional<double&> br; ar = a; EXPECT_TRUE(ar); *ar = 5.0; EXPECT_EQ(5.0, a); br = ar; EXPECT_TRUE(br); *br = 7.0; EXPECT_EQ(7.0, a); } struct nomove { int value; nomove(): value(0) {} nomove(int i): value(i) {} nomove(const nomove &n): value(n.value) {} nomove(nomove &&n) = delete; nomove &operator=(const nomove &n) { value=n.value; return *this; } bool operator==(const nomove &them) const { return them.value==value; } bool operator!=(const nomove &them) const { return !(*this==them); } }; TEST(optionalm,ctor_nomove) { optional<nomove> a(nomove(3)); EXPECT_EQ(nomove(3),a.get()); optional<nomove> b; b=a; EXPECT_EQ(nomove(3),b.get()); b=optional<nomove>(nomove(4)); EXPECT_EQ(nomove(4),b.get()); } struct nocopy { int value; nocopy(): value(0) {} nocopy(int i): value(i) {} nocopy(const nocopy &n) = delete; nocopy(nocopy &&n) { value=n.value; n.value=0; } nocopy &operator=(const nocopy &n) = delete; nocopy &operator=(nocopy &&n) { value=n.value; n.value=-1; return *this; } bool operator==(const nocopy &them) const { return them.value==value; } bool operator!=(const nocopy &them) const { return !(*this==them); } }; TEST(optionalm,ctor_nocopy) { optional<nocopy> a(nocopy(5)); EXPECT_EQ(nocopy(5),a.get()); optional<nocopy> b(std::move(a)); EXPECT_EQ(nocopy(5),b.get()); EXPECT_EQ(0,a.get().value); b=optional<nocopy>(nocopy(6)); EXPECT_EQ(nocopy(6),b.get()); } static optional<double> odd_half(int n) { optional<double> h; if (n%2==1) h=n/2.0; return h; } TEST(optionalm,bind) { optional<int> a; auto b=a.bind(odd_half); EXPECT_EQ(typeid(optional<double>),typeid(b)); a=10; b=a.bind(odd_half); EXPECT_FALSE((bool)b); a=11; b=a.bind(odd_half); EXPECT_TRUE((bool)b); EXPECT_EQ(5.5,b.get()); b=a >> odd_half >> [](double x) { return (int)x; } >> odd_half; EXPECT_TRUE((bool)b); EXPECT_EQ(2.5,b.get()); } TEST(optionalm,void) { optional<void> a,b(true),c(a),d=b,e(false); EXPECT_FALSE((bool)a); EXPECT_TRUE((bool)b); EXPECT_FALSE((bool)c); EXPECT_TRUE((bool)d); EXPECT_TRUE((bool)e); auto x=a >> []() { return 1; }; EXPECT_FALSE((bool)x); x=b >> []() { return 1; }; EXPECT_TRUE((bool)x); EXPECT_EQ(1,x.get()); } TEST(optionalm,bind_to_void) { optional<int> a,b(3); int call_count=0; auto vf=[&call_count](int i) -> void { ++call_count; }; auto x=a >> vf; EXPECT_EQ(typeid(optional<void>),typeid(x)); EXPECT_FALSE((bool)x); EXPECT_EQ(0,call_count); call_count=0; x=b >> vf; EXPECT_TRUE((bool)x); EXPECT_EQ(1,call_count); } TEST(optionalm,bind_to_optional_void) { optional<int> a,b(3),c(4); int count=0; auto count_if_odd=[&count](int i) { return i%2?(++count,optional<void>(true)):optional<void>(); }; auto x=a >> count_if_odd; EXPECT_EQ(typeid(optional<void>),typeid(x)); EXPECT_FALSE((bool)x); EXPECT_EQ(0,count); count=0; x=b >> count_if_odd; EXPECT_TRUE((bool)x); EXPECT_EQ(1,count); count=0; x=c >> count_if_odd; EXPECT_FALSE((bool)x); EXPECT_EQ(0,count); } TEST(optionalm,bind_with_ref) { optional<int> a=10; a >> [](int &v) {++v; }; EXPECT_EQ(11,*a); } struct check_cref { int operator()(const int &) { return 10; } int operator()(int &) { return 11; } }; TEST(optionalm,bind_constness) { check_cref checker; optional<int> a=1; int v=*(a >> checker); EXPECT_EQ(11,v); const optional<int> b=1; v=*(b >> checker); EXPECT_EQ(10,v); } TEST(optionalm,conversion) { optional<double> a(3),b=5; EXPECT_TRUE((bool)a); EXPECT_TRUE((bool)b); EXPECT_EQ(3.0,a.get()); EXPECT_EQ(5.0,b.get()); optional<int> x; optional<double> c(x); optional<double> d=optional<int>(); EXPECT_FALSE((bool)c); EXPECT_FALSE((bool)d); auto doubler=[](double x) { return x*2; }; auto y=optional<int>(3) >> doubler; EXPECT_TRUE((bool)y); EXPECT_EQ(6.0,y.get()); } TEST(optionalm,or_operator) { optional<const char *> default_msg="default"; auto x=(char *)0 | default_msg; EXPECT_TRUE((bool)x); EXPECT_STREQ("default",x.get()); auto y="something" | default_msg; EXPECT_TRUE((bool)y); EXPECT_STREQ("something",y.get()); optional<int> a(1),b,c(3); EXPECT_EQ(1,*(a|b|c)); EXPECT_EQ(1,*(a|c|b)); EXPECT_EQ(1,*(b|a|c)); EXPECT_EQ(3,*(b|c|a)); EXPECT_EQ(3,*(c|a|b)); EXPECT_EQ(3,*(c|b|a)); } TEST(optionalm,and_operator) { optional<int> a(1); optional<double> b(2.0); auto ab=a&b; auto ba=b&a; EXPECT_EQ(typeid(ab),typeid(b)); EXPECT_EQ(typeid(ba),typeid(a)); EXPECT_EQ(2.0,*ab); EXPECT_EQ(1,*ba); auto zb=false & b; EXPECT_EQ(typeid(zb),typeid(b)); EXPECT_FALSE((bool)zb); auto b3=b & 3; EXPECT_EQ(typeid(b3),typeid(optional<int>)); EXPECT_TRUE((bool)b3); EXPECT_EQ(3,*b3); } TEST(optionalm,provided) { std::array<int,3> qs={1,0,3}; std::array<int,3> ps={14,14,14}; std::array<int,3> rs; std::transform(ps.begin(),ps.end(),qs.begin(),rs.begin(), [](int p,int q) { return *( provided(q!=0) >> [=]() { return p/q; } | -1 ); }); EXPECT_EQ(14,rs[0]); EXPECT_EQ(-1,rs[1]); EXPECT_EQ(4,rs[2]); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <cmath> #include <assert.h> #include <gtest/gtest.h> #include "../parallel_async.h" #include "../task.h" class ParallelTest : testing::Test { ; }; TEST(ParallelTest, test_parallel) { auto result = asyncply::parallel( []() { return 9.0; }, []() { return 7.0; }, []() { return 10.0; }, []() { return 6.0; }); ASSERT_EQ(result, 32.0); } <commit_msg>Update test_parallel.cpp<commit_after>#include <iostream> #include <vector> #include <cmath> #include <assert.h> #include <gtest/gtest.h> #include "../parallel_async.h" #include "../task.h" class ParallelTest : testing::Test { ; }; #if 0 TEST(ParallelTest, test_parallel) { auto result = asyncply::parallel( []() { return 9.0; }, []() { return 7.0; }, []() { return 10.0; }, []() { return 6.0; }); ASSERT_EQ(result, 32.0); } #endif <|endoftext|>
<commit_before>/* This file is part of Ingen. * Copyright (C) 2007 Dave Robillard <http://drobilla.net> * * Ingen is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * Ingen 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 details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "QueuedEventSource.h" #include "QueuedEvent.h" #include "PostProcessor.h" #include "ThreadManager.h" #include <sys/mman.h> #include <iostream> using std::cout; using std::cerr; using std::endl; namespace Ingen { QueuedEventSource::QueuedEventSource(size_t queued_size, size_t stamped_size) : _front(0), _back(0), _prepared_back(0), _size(queued_size+1), _blocking_semaphore(0), _stamped_queue(stamped_size) { _events = (QueuedEvent**)calloc(_size, sizeof(QueuedEvent*)); mlock(_events, _size * sizeof(QueuedEvent*)); Thread::set_context(THREAD_PRE_PROCESS); assert(context() == THREAD_PRE_PROCESS); set_name("QueuedEventSource"); Thread::start(); } QueuedEventSource::~QueuedEventSource() { Thread::stop(); free(_events); } /** Push an unprepared event onto the queue. */ void QueuedEventSource::push_queued(QueuedEvent* const ev) { assert(!ev->is_prepared()); if (_events[_back] != NULL) { cerr << "[QueuedEventSource] Error: Queue is full! Event is lost, please report!" << endl; delete ev; } else { _events[_back] = ev; _back = (_back + 1) % _size; whip(); } } /** Process all events for a cycle. * * Executed events will be pushed to @a dest. */ void QueuedEventSource::process(PostProcessor& dest, SampleCount nframes, FrameTime cycle_start, FrameTime cycle_end) { assert(ThreadManager::current_thread_id() == THREAD_PROCESS); Event* ev = NULL; /* Limit the maximum number of queued events to process per cycle. This * makes the process callback (more) realtime-safe by preventing being * choked by events coming in faster than they can be processed. * FIXME: test this and figure out a good value */ const unsigned int MAX_QUEUED_EVENTS = nframes / 100; unsigned int num_events_processed = 0; /* FIXME: Merge these next two loops into one */ while ((ev = pop_earliest_queued_before(cycle_end))) { ev->execute(nframes, cycle_start, cycle_end); dest.push(ev); if (++num_events_processed > MAX_QUEUED_EVENTS) break; } while ((ev = pop_earliest_stamped_before(cycle_end))) { ev->execute(nframes, cycle_start, cycle_end); dest.push(ev); ++num_events_processed; } if (num_events_processed > 0) dest.whip(); //else // cerr << "NO PROC: queued: " << unprepared_events() << ", stamped: " << !_stamped_queue.empty() << endl; } /** Pops the prepared event at the front of the prepare queue, if it exists. * * This method will only pop events that have been prepared, and are * stamped before the time passed. In other words, it may return NULL * even if there are events pending in the queue. The events returned are * actually QueuedEvents, but after this they are "normal" events and the * engine deals with them just like a realtime in-band event. The engine will * not use the timestamps of the returned events in any way, since it is free * to execute these non-time-stamped events whenever it wants (at whatever rate * it wants). */ Event* QueuedEventSource::pop_earliest_queued_before(const SampleCount time) { assert(ThreadManager::current_thread_id() == THREAD_PROCESS); QueuedEvent* const front_event = _events[_front]; // Pop if (front_event && front_event->is_prepared() && front_event->time() < time) { _events[_front] = NULL; _front = (_front + 1) % _size; return front_event; } else { return NULL; } } // Private // /** Signal that the blocking event is finished. * * When this is called preparing will resume. This MUST be called by * blocking events in their post_process() method. */ void QueuedEventSource::unblock() { _blocking_semaphore.post(); } /** Pre-process a single event */ void QueuedEventSource::_whipped() { QueuedEvent* const ev = _events[_prepared_back]; if (!ev) return; assert(!ev->is_prepared()); ev->pre_process(); assert(ev->is_prepared()); _prepared_back = (_prepared_back+1) % _size; // If event was blocking, wait for event to being run through the // process thread before preparing the next event if (ev->is_blocking()) _blocking_semaphore.wait(); } } // namespace Ingen <commit_msg>Added harsher assertion in hopes of catching bug earlier.<commit_after>/* This file is part of Ingen. * Copyright (C) 2007 Dave Robillard <http://drobilla.net> * * Ingen is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * Ingen 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 details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "QueuedEventSource.h" #include "QueuedEvent.h" #include "PostProcessor.h" #include "ThreadManager.h" #include <sys/mman.h> #include <iostream> using std::cout; using std::cerr; using std::endl; namespace Ingen { QueuedEventSource::QueuedEventSource(size_t queued_size, size_t stamped_size) : _front(0), _back(0), _prepared_back(0), _size(queued_size+1), _blocking_semaphore(0), _stamped_queue(stamped_size) { _events = (QueuedEvent**)calloc(_size, sizeof(QueuedEvent*)); mlock(_events, _size * sizeof(QueuedEvent*)); Thread::set_context(THREAD_PRE_PROCESS); assert(context() == THREAD_PRE_PROCESS); set_name("QueuedEventSource"); Thread::start(); } QueuedEventSource::~QueuedEventSource() { Thread::stop(); free(_events); } /** Push an unprepared event onto the queue. */ void QueuedEventSource::push_queued(QueuedEvent* const ev) { assert(!ev->is_prepared()); if (_events[_back] != NULL) { cerr << "[QueuedEventSource] Error: Queue is full! Event is lost, please report!" << endl; delete ev; } else { _events[_back] = ev; _back = (_back + 1) % _size; whip(); } } /** Process all events for a cycle. * * Executed events will be pushed to @a dest. */ void QueuedEventSource::process(PostProcessor& dest, SampleCount nframes, FrameTime cycle_start, FrameTime cycle_end) { assert(ThreadManager::current_thread_id() == THREAD_PROCESS); Event* ev = NULL; /* Limit the maximum number of queued events to process per cycle. This * makes the process callback (more) realtime-safe by preventing being * choked by events coming in faster than they can be processed. * FIXME: test this and figure out a good value */ const unsigned int MAX_QUEUED_EVENTS = nframes / 100; unsigned int num_events_processed = 0; /* FIXME: Merge these next two loops into one */ while ((ev = pop_earliest_queued_before(cycle_end))) { ev->execute(nframes, cycle_start, cycle_end); dest.push(ev); if (++num_events_processed > MAX_QUEUED_EVENTS) break; } while ((ev = pop_earliest_stamped_before(cycle_end))) { ev->execute(nframes, cycle_start, cycle_end); dest.push(ev); ++num_events_processed; } if (num_events_processed > 0) dest.whip(); //else // cerr << "NO PROC: queued: " << unprepared_events() << ", stamped: " << !_stamped_queue.empty() << endl; } /** Pops the prepared event at the front of the prepare queue, if it exists. * * This method will only pop events that have been prepared, and are * stamped before the time passed. In other words, it may return NULL * even if there are events pending in the queue. The events returned are * actually QueuedEvents, but after this they are "normal" events and the * engine deals with them just like a realtime in-band event. The engine will * not use the timestamps of the returned events in any way, since it is free * to execute these non-time-stamped events whenever it wants (at whatever rate * it wants). */ Event* QueuedEventSource::pop_earliest_queued_before(const SampleCount time) { assert(ThreadManager::current_thread_id() == THREAD_PROCESS); QueuedEvent* const front_event = _events[_front]; // Pop if (front_event && front_event->is_prepared() && front_event->time() < time) { _events[_front] = NULL; _front = (_front + 1) % _size; return front_event; } else { return NULL; } } // Private // /** Signal that the blocking event is finished. * * When this is called preparing will resume. This MUST be called by * blocking events in their post_process() method. */ void QueuedEventSource::unblock() { _blocking_semaphore.post(); } /** Pre-process a single event */ void QueuedEventSource::_whipped() { QueuedEvent* const ev = _events[_prepared_back]; assert(ev); assert(!ev->is_prepared()); ev->pre_process(); assert(ev->is_prepared()); _prepared_back = (_prepared_back+1) % _size; // If event was blocking, wait for event to being run through the // process thread before preparing the next event if (ev->is_blocking()) _blocking_semaphore.wait(); } } // namespace Ingen <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg 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 the author 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. */ #include "libtorrent/pch.hpp" #include "libtorrent/lsd.hpp" #include "libtorrent/io.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/xml_parse.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #include <boost/thread/mutex.hpp> #include <cstdlib> using boost::bind; using namespace libtorrent; address_v4 lsd::lsd_multicast_address; udp::endpoint lsd::lsd_multicast_endpoint; lsd::lsd(io_service& ios, address const& listen_interface , peer_callback_t const& cb) : m_callback(cb) , m_retry_count(0) , m_socket(ios) , m_broadcast_timer(ios) , m_disabled(false) { // Bittorrent Local discovery multicast address and port lsd_multicast_address = address_v4::from_string("239.192.152.143"); lsd_multicast_endpoint = udp::endpoint(lsd_multicast_address, 6771); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc); #endif assert(lsd_multicast_address.is_multicast()); rebind(listen_interface); } lsd::~lsd() {} void lsd::rebind(address const& listen_interface) { address_v4 local_ip; if (listen_interface.is_v4() && listen_interface != address_v4::from_string("0.0.0.0")) { local_ip = listen_interface.to_v4(); } else { // make a best guess of the interface we're using and its IP udp::resolver r(m_socket.io_service()); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); for (;i != udp::resolver_iterator(); ++i) { if (i->endpoint().address().is_v4()) break; } if (i == udp::resolver_iterator()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "local host name did not resolve to an IPv4 address. " "disabling local service discovery" << std::endl; #endif m_disabled = true; return; } local_ip = i->endpoint().address().to_v4(); } try { // the local interface hasn't changed if (m_socket.is_open() && m_socket.local_endpoint().address() == local_ip) return; m_socket.close(); using namespace asio::ip::multicast; m_socket.open(udp::v4()); m_socket.set_option(datagram_socket::reuse_address(true)); m_socket.bind(udp::endpoint(local_ip, 6771)); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "local ip: " << local_ip << std::endl; #endif m_socket.set_option(join_group(lsd_multicast_address)); m_socket.set_option(outbound_interface(address_v4())); m_socket.set_option(enable_loopback(false)); m_socket.set_option(hops(255)); } catch (std::exception& e) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "socket multicast error " << e.what() << ". disabling local service discovery" << std::endl; #endif m_disabled = true; return; } m_disabled = false; setup_receive(); } void lsd::announce(sha1_hash const& ih, int listen_port) { if (m_disabled) return; std::stringstream btsearch; btsearch << "BT-SEARCH * HTTP/1.1\r\n" "Host: 239.192.152.143:6771\r\n" "Port: " << listen_port << "\r\n" "Infohash: " << ih << "\r\n" "\r\n\r\n"; std::string const& msg = btsearch.str(); m_retry_count = 0; asio::error_code ec; m_socket.send_to(asio::buffer(msg.c_str(), msg.size() - 1) , lsd_multicast_endpoint, ec); if (ec) { m_disabled = true; return; } #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " ==> announce: ih: " << ih << " port: " << listen_port << std::endl; #endif m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg)); } void lsd::resend_announce(asio::error_code const& e, std::string msg) try { if (e) return; m_socket.send_to(asio::buffer(msg, msg.size() - 1) , lsd_multicast_endpoint); ++m_retry_count; if (m_retry_count >= 5) return; m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg)); } catch (std::exception&) {} void lsd::on_announce(asio::error_code const& e , std::size_t bytes_transferred) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== on_announce" << std::endl; #endif using namespace libtorrent::detail; if (e) return; char* p = m_receive_buffer; char* end = m_receive_buffer + bytes_transferred; char* line = std::find(p, end, '\n'); for (char* i = p; i < line; ++i) *i = std::tolower(*i); if (line == end || std::strcmp("bt-search", p)) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== Got incorrect method in announce" << std::string(p, line) << std::endl; #endif setup_receive(); return; } p = line + 1; int port = 0; sha1_hash ih(0); while (p != end) { line = std::find(p, end, '\n'); if (line == end) break; *line = 0; for (char* i = p; i < line; ++i) *i = std::tolower(*i); if (!strcmp(p, "port:")) { port = atoi(p + 5); } else if (!strcmp(p, "infohash:")) { ih = boost::lexical_cast<sha1_hash>(p + 9); } p = line + 1; } if (!ih.is_all_zeros() && port != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== Got incoming local announce " << m_remote.address() << ":" << port << " ih: " << ih << std::endl; #endif // we got an announce, pass it on through the callback try { m_callback(tcp::endpoint(m_remote.address(), port), ih); } catch (std::exception&) {} } setup_receive(); } void lsd::setup_receive() try { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " *** setup_receive" << std::endl; #endif assert(m_socket.is_open()); m_socket.async_receive_from(asio::buffer(m_receive_buffer , sizeof(m_receive_buffer)), m_remote, bind(&lsd::on_announce, this, _1, _2)); } catch (std::exception&) {} void lsd::close() { m_socket.close(); } <commit_msg>fixed typo in last check in<commit_after>/* Copyright (c) 2007, Arvid Norberg 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 the author 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. */ #include "libtorrent/pch.hpp" #include "libtorrent/lsd.hpp" #include "libtorrent/io.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/xml_parse.hpp" #include <boost/bind.hpp> #include <boost/ref.hpp> #include <asio/ip/host_name.hpp> #include <asio/ip/multicast.hpp> #include <boost/thread/mutex.hpp> #include <cstdlib> using boost::bind; using namespace libtorrent; address_v4 lsd::lsd_multicast_address; udp::endpoint lsd::lsd_multicast_endpoint; lsd::lsd(io_service& ios, address const& listen_interface , peer_callback_t const& cb) : m_callback(cb) , m_retry_count(0) , m_socket(ios) , m_broadcast_timer(ios) , m_disabled(false) { // Bittorrent Local discovery multicast address and port lsd_multicast_address = address_v4::from_string("239.192.152.143"); lsd_multicast_endpoint = udp::endpoint(lsd_multicast_address, 6771); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log.open("lsd.log", std::ios::in | std::ios::out | std::ios::trunc); #endif assert(lsd_multicast_address.is_multicast()); rebind(listen_interface); } lsd::~lsd() {} void lsd::rebind(address const& listen_interface) { address_v4 local_ip; if (listen_interface.is_v4() && listen_interface != address_v4::from_string("0.0.0.0")) { local_ip = listen_interface.to_v4(); } else { // make a best guess of the interface we're using and its IP udp::resolver r(m_socket.io_service()); udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0")); for (;i != udp::resolver_iterator(); ++i) { if (i->endpoint().address().is_v4()) break; } if (i == udp::resolver_iterator()) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "local host name did not resolve to an IPv4 address. " "disabling local service discovery" << std::endl; #endif m_disabled = true; return; } local_ip = i->endpoint().address().to_v4(); } try { // the local interface hasn't changed if (m_socket.is_open() && m_socket.local_endpoint().address() == local_ip) return; m_socket.close(); using namespace asio::ip::multicast; m_socket.open(udp::v4()); m_socket.set_option(datagram_socket::reuse_address(true)); m_socket.bind(udp::endpoint(local_ip, 6771)); #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "local ip: " << local_ip << std::endl; #endif m_socket.set_option(join_group(lsd_multicast_address)); m_socket.set_option(outbound_interface(address_v4())); m_socket.set_option(enable_loopback(false)); m_socket.set_option(hops(255)); } catch (std::exception& e) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << "socket multicast error " << e.what() << ". disabling local service discovery" << std::endl; #endif m_disabled = true; return; } m_disabled = false; setup_receive(); } void lsd::announce(sha1_hash const& ih, int listen_port) { if (m_disabled) return; std::stringstream btsearch; btsearch << "BT-SEARCH * HTTP/1.1\r\n" "Host: 239.192.152.143:6771\r\n" "Port: " << listen_port << "\r\n" "Infohash: " << ih << "\r\n" "\r\n\r\n"; std::string const& msg = btsearch.str(); m_retry_count = 0; asio::error_code ec; m_socket.send_to(asio::buffer(msg.c_str(), msg.size() - 1) , lsd_multicast_endpoint, 0, ec); if (ec) { m_disabled = true; return; } #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " ==> announce: ih: " << ih << " port: " << listen_port << std::endl; #endif m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg)); } void lsd::resend_announce(asio::error_code const& e, std::string msg) try { if (e) return; m_socket.send_to(asio::buffer(msg, msg.size() - 1) , lsd_multicast_endpoint); ++m_retry_count; if (m_retry_count >= 5) return; m_broadcast_timer.expires_from_now(milliseconds(250 * m_retry_count)); m_broadcast_timer.async_wait(bind(&lsd::resend_announce, this, _1, msg)); } catch (std::exception&) {} void lsd::on_announce(asio::error_code const& e , std::size_t bytes_transferred) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== on_announce" << std::endl; #endif using namespace libtorrent::detail; if (e) return; char* p = m_receive_buffer; char* end = m_receive_buffer + bytes_transferred; char* line = std::find(p, end, '\n'); for (char* i = p; i < line; ++i) *i = std::tolower(*i); if (line == end || std::strcmp("bt-search", p)) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== Got incorrect method in announce" << std::string(p, line) << std::endl; #endif setup_receive(); return; } p = line + 1; int port = 0; sha1_hash ih(0); while (p != end) { line = std::find(p, end, '\n'); if (line == end) break; *line = 0; for (char* i = p; i < line; ++i) *i = std::tolower(*i); if (!strcmp(p, "port:")) { port = atoi(p + 5); } else if (!strcmp(p, "infohash:")) { ih = boost::lexical_cast<sha1_hash>(p + 9); } p = line + 1; } if (!ih.is_all_zeros() && port != 0) { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " <== Got incoming local announce " << m_remote.address() << ":" << port << " ih: " << ih << std::endl; #endif // we got an announce, pass it on through the callback try { m_callback(tcp::endpoint(m_remote.address(), port), ih); } catch (std::exception&) {} } setup_receive(); } void lsd::setup_receive() try { #if defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING) m_log << time_now_string() << " *** setup_receive" << std::endl; #endif assert(m_socket.is_open()); m_socket.async_receive_from(asio::buffer(m_receive_buffer , sizeof(m_receive_buffer)), m_remote, bind(&lsd::on_announce, this, _1, _2)); } catch (std::exception&) {} void lsd::close() { m_socket.close(); } <|endoftext|>
<commit_before>/** * @file main.cc * @brief gcsa_locate main program. * * Uses GCSA2 index to locate k-mers in the underlying graph. * * @author Ali Ghaffaari (\@cartoonist), <ali.ghaffaari@mpi-inf.mpg.de> * * @internal * Created: Thu Aug 03, 2017 04:37 * Organization: Max-Planck-Institut fuer Informatik * Copyright: Copyright (c) 2017, Ali Ghaffaari * * This source code is released under the terms of the MIT License. * See LICENSE file for more information. */ #include <cstdlib> #include <fstream> #include <vector> #include <string> #include <seqan/arg_parse.h> #include <gcsa/gcsa.h> #include <config.h> #include "seed.h" #include "timer.h" #include "options.h" #include "release.h" seqan::ArgumentParser::ParseResult parse_args( Options& options, int argc, char* argv[] ); void setup_argparser( seqan::ArgumentParser& parser ); inline void get_option_values( Options& options, seqan::ArgumentParser& parser ); void locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len, bool nonoverlapping, std::string& output_name ); int main( int argc, char* argv[] ) { // Parse the command line. Options options; auto res = parse_args( options, argc, argv ); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; locate_seeds( options.seq_filename, options.gcsa_filename, options.seed_len, options.nonoverlapping, options.output_filename ); return EXIT_SUCCESS; } void locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len, bool nonoverlapping, std::string& output_name ) { std::ifstream seq_file( seq_name, std::ifstream::in | std::ifstream::binary ); if ( !seq_file ) { throw std::runtime_error("could not open file '" + seq_name + "'" ); } std::ifstream gcsa_file( gcsa_name, std::ifstream::in | std::ifstream::binary ); if ( !gcsa_file ) { throw std::runtime_error("could not open file '" + gcsa_name + "'" ); } gcsa::GCSA index; std::vector< std::string > sequences; std::vector< std::string > patterns; std::vector< gcsa::node_type > results; std::cout << "Loading GCSA index..." << std::endl; index.load( gcsa_file ); std::cout << "Loading sequences..." << std::endl; { auto timer = Timer( "sequences" ); std::string line; while ( std::getline( seq_file, line ) ) { sequences.push_back( line ); } } std::cout << "Loaded " << sequences.size() << " sequences in " << Timer::get_duration( "sequences" ).count() << " us." << std::endl; std::cout << "Generating patterns..." << std::endl; { auto timer = Timer( "patterns" ); if ( nonoverlapping ) { seeding( patterns, sequences, seed_len, GreedyNonOverlapping() ); } else { seeding( patterns, sequences, seed_len, GreedyOverlapping() ); } } std::cout << "Generated " << patterns.size() << " patterns in " << Timer::get_duration( "patterns" ).count() << " us." << std::endl; std::cout << "Locating patterns..." << std::endl; { auto timer = Timer( "locate" ); for ( const auto& p : patterns ) { gcsa::range_type range = index.find( p ); index.locate( range, results, true ); } } std::cout << "Located " << results.size() << " occurrences in " << Timer::get_duration( "locate" ).count() << " us." << std::endl; std::cout << "Writing occurrences into file..." << std::endl; std::ofstream output_file( output_name, std::ofstream::out ); for ( auto && r : results ) { output_file << gcsa::Node::id( r ) << "\t" << gcsa::Node::offset( r ) << std::endl; } } inline seqan::ArgumentParser::ParseResult parse_args( Options& options, int argc, char* argv[] ) { // setup ArgumentParser. seqan::ArgumentParser parser( release::name ); setup_argparser( parser ); // Embedding program's meta data and build information. setShortDescription( parser, release::short_desc ); setVersion( parser, release::version ); setDate( parser, LAST_MOD_DATE ); addDescription( parser, release::desc ); // parse command line. auto res = seqan::parse( parser, argc, argv ); // only extract options if the program will continue after parse_args() if ( res != seqan::ArgumentParser::PARSE_OK ) { return res; } get_option_values( options, parser ); return seqan::ArgumentParser::PARSE_OK; } inline void setup_argparser( seqan::ArgumentParser& parser ) { // positional arguments. std::string POSARG1 = "SEQ_FILE"; // add usage line. addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fI" + POSARG1 + "\\fP\""); // sequence file -- positional argument. seqan::ArgParseArgument seq_arg( seqan::ArgParseArgument::INPUT_FILE, POSARG1 ); addArgument( parser, seq_arg ); // GCSA2 index file -- **required** option. seqan::ArgParseOption gcsa_arg( "g", "gcsa", "GCSA2 index file.", seqan::ArgParseArgument::INPUT_FILE, "GCSA2_FILE" ); setValidValues( gcsa_arg, gcsa::GCSA::EXTENSION ); addOption( parser, gcsa_arg ); setRequired( parser, "g" ); // Seed length. addOption( parser, seqan::ArgParseOption( "l", "seed-len", "Seed length.", seqan::ArgParseArgument::INTEGER, "INT" ) ); setRequired( parser, "l" ); // Overlapping seeds? addOption( parser, seqan::ArgParseOption( "n", "non-overlapping", "Use non-overlapping seeds." ) ); // Output file. seqan::ArgParseOption output_arg( "o", "output", "Write positions where sequences are matched.", seqan::ArgParseArgument::OUTPUT_FILE, "OUTPUT" ); addOption( parser, output_arg ); setRequired( parser, "o" ); } inline void get_option_values( Options& options, seqan::ArgumentParser& parser ) { getArgumentValue( options.seq_filename, parser, 0 ); getOptionValue( options.gcsa_filename, parser, "gcsa" ); getOptionValue( options.output_filename, parser, "output" ); getOptionValue( options.seed_len, parser, "seed-len" ); options.nonoverlapping = isSet( parser, "non-overlapping" ); } <commit_msg>Handle SIGUSR1 for reporting<commit_after>/** * @file main.cc * @brief gcsa_locate main program. * * Uses GCSA2 index to locate k-mers in the underlying graph. * * @author Ali Ghaffaari (\@cartoonist), <ali.ghaffaari@mpi-inf.mpg.de> * * @internal * Created: Thu Aug 03, 2017 04:37 * Organization: Max-Planck-Institut fuer Informatik * Copyright: Copyright (c) 2017, Ali Ghaffaari * * This source code is released under the terms of the MIT License. * See LICENSE file for more information. */ #include <cstdlib> #include <csignal> #include <iostream> #include <fstream> #include <vector> #include <string> #include <seqan/arg_parse.h> #include <gcsa/gcsa.h> #include <config.h> #include "seed.h" #include "timer.h" #include "options.h" #include "release.h" seqan::ArgumentParser::ParseResult parse_args( Options& options, int argc, char* argv[] ); void setup_argparser( seqan::ArgumentParser& parser ); inline void get_option_values( Options& options, seqan::ArgumentParser& parser ); void locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len, bool nonoverlapping, std::string& output_name ); void signal_handler( int signal ); std::size_t done_idx = 0; std::size_t total_no = 0; int main( int argc, char* argv[] ) { // Parse the command line. Options options; auto res = parse_args( options, argc, argv ); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; /* Install signal handler */ std::signal( SIGUSR1, signal_handler ); locate_seeds( options.seq_filename, options.gcsa_filename, options.seed_len, options.nonoverlapping, options.output_filename ); return EXIT_SUCCESS; } void signal_handler( int signal ) { std::cout << "Located " << ::done_idx << " out of " << ::total_no << " in " << Timer::get_lap( "locate" ).count() << " us: " << ::done_idx * 100 / total_no << "% done." << std::endl; } void locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len, bool nonoverlapping, std::string& output_name ) { std::ifstream seq_file( seq_name, std::ifstream::in | std::ifstream::binary ); if ( !seq_file ) { throw std::runtime_error("could not open file '" + seq_name + "'" ); } std::ifstream gcsa_file( gcsa_name, std::ifstream::in | std::ifstream::binary ); if ( !gcsa_file ) { throw std::runtime_error("could not open file '" + gcsa_name + "'" ); } gcsa::GCSA index; std::vector< std::string > sequences; std::vector< std::string > patterns; std::vector< gcsa::node_type > results; std::cout << "Loading GCSA index..." << std::endl; index.load( gcsa_file ); std::cout << "Loading sequences..." << std::endl; { auto timer = Timer( "sequences" ); std::string line; while ( std::getline( seq_file, line ) ) { sequences.push_back( line ); } } std::cout << "Loaded " << sequences.size() << " sequences in " << Timer::get_duration( "sequences" ).count() << " us." << std::endl; std::cout << "Generating patterns..." << std::endl; { auto timer = Timer( "patterns" ); if ( nonoverlapping ) { seeding( patterns, sequences, seed_len, GreedyNonOverlapping() ); } else { seeding( patterns, sequences, seed_len, GreedyOverlapping() ); } } ::total_no = patterns.size(); std::cout << "Generated " << patterns.size() << " patterns in " << Timer::get_duration( "patterns" ).count() << " us." << std::endl; std::cout << "Locating patterns..." << std::endl; { auto timer = Timer( "locate" ); for ( const auto& p : patterns ) { gcsa::range_type range = index.find( p ); index.locate( range, results, true ); ::done_idx++; } } std::cout << "Located " << results.size() << " occurrences in " << Timer::get_duration( "locate" ).count() << " us." << std::endl; std::cout << "Writing occurrences into file..." << std::endl; std::ofstream output_file( output_name, std::ofstream::out ); for ( auto && r : results ) { output_file << gcsa::Node::id( r ) << "\t" << gcsa::Node::offset( r ) << std::endl; } } inline seqan::ArgumentParser::ParseResult parse_args( Options& options, int argc, char* argv[] ) { // setup ArgumentParser. seqan::ArgumentParser parser( release::name ); setup_argparser( parser ); // Embedding program's meta data and build information. setShortDescription( parser, release::short_desc ); setVersion( parser, release::version ); setDate( parser, LAST_MOD_DATE ); addDescription( parser, release::desc ); // parse command line. auto res = seqan::parse( parser, argc, argv ); // only extract options if the program will continue after parse_args() if ( res != seqan::ArgumentParser::PARSE_OK ) { return res; } get_option_values( options, parser ); return seqan::ArgumentParser::PARSE_OK; } inline void setup_argparser( seqan::ArgumentParser& parser ) { // positional arguments. std::string POSARG1 = "SEQ_FILE"; // add usage line. addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fI" + POSARG1 + "\\fP\""); // sequence file -- positional argument. seqan::ArgParseArgument seq_arg( seqan::ArgParseArgument::INPUT_FILE, POSARG1 ); addArgument( parser, seq_arg ); // GCSA2 index file -- **required** option. seqan::ArgParseOption gcsa_arg( "g", "gcsa", "GCSA2 index file.", seqan::ArgParseArgument::INPUT_FILE, "GCSA2_FILE" ); setValidValues( gcsa_arg, gcsa::GCSA::EXTENSION ); addOption( parser, gcsa_arg ); setRequired( parser, "g" ); // Seed length. addOption( parser, seqan::ArgParseOption( "l", "seed-len", "Seed length.", seqan::ArgParseArgument::INTEGER, "INT" ) ); setRequired( parser, "l" ); // Overlapping seeds? addOption( parser, seqan::ArgParseOption( "n", "non-overlapping", "Use non-overlapping seeds." ) ); // Output file. seqan::ArgParseOption output_arg( "o", "output", "Write positions where sequences are matched.", seqan::ArgParseArgument::OUTPUT_FILE, "OUTPUT" ); addOption( parser, output_arg ); setRequired( parser, "o" ); } inline void get_option_values( Options& options, seqan::ArgumentParser& parser ) { getArgumentValue( options.seq_filename, parser, 0 ); getOptionValue( options.gcsa_filename, parser, "gcsa" ); getOptionValue( options.output_filename, parser, "output" ); getOptionValue( options.seed_len, parser, "seed-len" ); options.nonoverlapping = isSet( parser, "non-overlapping" ); } <|endoftext|>
<commit_before>//===-- Local.cpp - Functions to perform local transformations ------------===// // // 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 family of functions perform various local transformations to the // program. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Support/MathExtras.h" #include <cerrno> #include <cmath> using namespace llvm; //===----------------------------------------------------------------------===// // Local constant propagation... // /// doConstantPropagation - If an instruction references constants, try to fold /// them together... /// bool llvm::doConstantPropagation(BasicBlock::iterator &II) { if (Constant *C = ConstantFoldInstruction(II)) { // Replaces all of the uses of a variable with uses of the constant. II->replaceAllUsesWith(C); // Remove the instruction from the basic block... II = II->getParent()->getInstList().erase(II); return true; } return false; } /// ConstantFoldInstruction - Attempt to constant fold the specified /// instruction. If successful, the constant result is returned, if not, null /// is returned. Note that this function can only fail when attempting to fold /// instructions like loads and stores, which have no constant expression form. /// Constant *llvm::ConstantFoldInstruction(Instruction *I) { if (PHINode *PN = dyn_cast<PHINode>(I)) { if (PN->getNumIncomingValues() == 0) return Constant::getNullValue(PN->getType()); Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0)); if (Result == 0) return 0; // Handle PHI nodes specially here... for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN) return 0; // Not all the same incoming constants... // If we reach here, all incoming values are the same constant. return Result; } else if (CallInst *CI = dyn_cast<CallInst>(I)) { if (Function *F = CI->getCalledFunction()) if (canConstantFoldCallTo(F)) { std::vector<Constant*> Args; for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i))) Args.push_back(Op); else return 0; return ConstantFoldCall(F, Args); } return 0; } Constant *Op0 = 0, *Op1 = 0; switch (I->getNumOperands()) { default: case 2: Op1 = dyn_cast<Constant>(I->getOperand(1)); if (Op1 == 0) return 0; // Not a constant?, can't fold case 1: Op0 = dyn_cast<Constant>(I->getOperand(0)); if (Op0 == 0) return 0; // Not a constant?, can't fold break; case 0: return 0; } if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) return ConstantExpr::get(I->getOpcode(), Op0, Op1); switch (I->getOpcode()) { default: return 0; case Instruction::Cast: return ConstantExpr::getCast(Op0, I->getType()); case Instruction::Select: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getSelect(Op0, Op1, Op2); return 0; case Instruction::ExtractElement: return ConstantExpr::getExtractElement(Op0, Op1); case Instruction::GetElementPtr: std::vector<Constant*> IdxList; IdxList.reserve(I->getNumOperands()-1); if (Op1) IdxList.push_back(Op1); for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i) if (Constant *C = dyn_cast<Constant>(I->getOperand(i))) IdxList.push_back(C); else return 0; // Non-constant operand return ConstantExpr::getGetElementPtr(Op0, IdxList); } } // ConstantFoldTerminator - If a terminator instruction is predicated on a // constant value, convert it into an unconditional branch to the constant // destination. // bool llvm::ConstantFoldTerminator(BasicBlock *BB) { TerminatorInst *T = BB->getTerminator(); // Branch - See if we are conditional jumping on constant if (BranchInst *BI = dyn_cast<BranchInst>(T)) { if (BI->isUnconditional()) return false; // Can't optimize uncond branch BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0)); BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1)); if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) { // Are we branching on constant? // YES. Change to unconditional branch... BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; //cerr << "Function: " << T->getParent()->getParent() // << "\nRemoving branch from " << T->getParent() // << "\n\nTo: " << OldDest << endl; // Let the basic block know that we are letting go of it. Based on this, // it will adjust it's PHI nodes. assert(BI->getParent() && "Terminator not inserted in block!"); OldDest->removePredecessor(BI->getParent()); // Set the unconditional destination, and change the insn to be an // unconditional branch. BI->setUnconditionalDest(Destination); return true; } else if (Dest2 == Dest1) { // Conditional branch to same location? // This branch matches something like this: // br bool %cond, label %Dest, label %Dest // and changes it into: br label %Dest // Let the basic block know that we are letting go of one copy of it. assert(BI->getParent() && "Terminator not inserted in block!"); Dest1->removePredecessor(BI->getParent()); // Change a conditional branch to unconditional. BI->setUnconditionalDest(Dest1); return true; } } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { // If we are switching on a constant, we can convert the switch into a // single branch instruction! ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest BasicBlock *DefaultDest = TheOnlyDest; assert(TheOnlyDest == SI->getDefaultDest() && "Default destination is not successor #0?"); // Figure out which case it goes to... for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? if (SI->getSuccessorValue(i) == CI) { TheOnlyDest = SI->getSuccessor(i); break; } // Check to see if this branch is going to the same place as the default // dest. If so, eliminate it as an explicit compare. if (SI->getSuccessor(i) == DefaultDest) { // Remove this entry... DefaultDest->removePredecessor(SI->getParent()); SI->removeCase(i); --i; --e; // Don't skip an entry... continue; } // Otherwise, check to see if the switch only branches to one destination. // We do this by reseting "TheOnlyDest" to null when we find two non-equal // destinations. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0; } if (CI && !TheOnlyDest) { // Branching on a constant, but not any of the cases, go to the default // successor. TheOnlyDest = SI->getDefaultDest(); } // If we found a single destination that we can fold the switch into, do so // now. if (TheOnlyDest) { // Insert the new branch.. new BranchInst(TheOnlyDest, SI); BasicBlock *BB = SI->getParent(); // Remove entries from PHI nodes which we no longer branch to... for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? BasicBlock *Succ = SI->getSuccessor(i); if (Succ == TheOnlyDest) TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest else Succ->removePredecessor(BB); } // Delete the old switch... BB->getInstList().erase(SI); return true; } else if (SI->getNumSuccessors() == 2) { // Otherwise, we can fold this switch into a conditional branch // instruction if it has only one non-default destination. Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(), SI->getSuccessorValue(1), "cond", SI); // Insert the new branch... new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI); // Delete the old switch... SI->getParent()->getInstList().erase(SI); return true; } } return false; } /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a /// getelementptr constantexpr, return the constant value being addressed by the /// constant expression, or null if something is funny and we can't decide. Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE) { if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType())) return 0; // Do not allow stepping over the value! // Loop over all of the operands, tracking down which value we are // addressing... gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); for (++I; I != E; ++I) if (const StructType *STy = dyn_cast<StructType>(*I)) { ConstantUInt *CU = cast<ConstantUInt>(I.getOperand()); assert(CU->getValue() < STy->getNumElements() && "Struct index out of range!"); unsigned El = (unsigned)CU->getValue(); if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) { C = CS->getOperand(El); } else if (isa<ConstantAggregateZero>(C)) { C = Constant::getNullValue(STy->getElementType(El)); } else if (isa<UndefValue>(C)) { C = UndefValue::get(STy->getElementType(El)); } else { return 0; } } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) { const ArrayType *ATy = cast<ArrayType>(*I); if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0; if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) C = CA->getOperand((unsigned)CI->getRawValue()); else if (isa<ConstantAggregateZero>(C)) C = Constant::getNullValue(ATy->getElementType()); else if (isa<UndefValue>(C)) C = UndefValue::get(ATy->getElementType()); else return 0; } else { return 0; } return C; } //===----------------------------------------------------------------------===// // Local dead code elimination... // bool llvm::isInstructionTriviallyDead(Instruction *I) { if (!I->use_empty() || isa<TerminatorInst>(I)) return false; if (!I->mayWriteToMemory()) return true; if (CallInst *CI = dyn_cast<CallInst>(I)) if (Function *F = CI->getCalledFunction()) switch (F->getIntrinsicID()) { default: break; case Intrinsic::returnaddress: case Intrinsic::frameaddress: case Intrinsic::stacksave: case Intrinsic::isunordered_f32: case Intrinsic::isunordered_f64: case Intrinsic::bswap_i16: case Intrinsic::bswap_i32: case Intrinsic::bswap_i64: case Intrinsic::ctpop_i8: case Intrinsic::ctpop_i16: case Intrinsic::ctpop_i32: case Intrinsic::ctpop_i64: case Intrinsic::ctlz_i8: case Intrinsic::ctlz_i16: case Intrinsic::ctlz_i32: case Intrinsic::ctlz_i64: case Intrinsic::cttz_i8: case Intrinsic::cttz_i16: case Intrinsic::cttz_i32: case Intrinsic::cttz_i64: case Intrinsic::sqrt_f32: case Intrinsic::sqrt_f64: return true; // These intrinsics have no side effects. } return false; } // dceInstruction - Inspect the instruction at *BBI and figure out if it's // [trivially] dead. If so, remove the instruction and update the iterator // to point to the instruction that immediately succeeded the original // instruction. // bool llvm::dceInstruction(BasicBlock::iterator &BBI) { // Look for un"used" definitions... if (isInstructionTriviallyDead(BBI)) { BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye return true; } return false; } <commit_msg>Constant folding support for the insertelement operation.<commit_after>//===-- Local.cpp - Functions to perform local transformations ------------===// // // 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 family of functions perform various local transformations to the // program. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Support/MathExtras.h" #include <cerrno> #include <cmath> using namespace llvm; //===----------------------------------------------------------------------===// // Local constant propagation... // /// doConstantPropagation - If an instruction references constants, try to fold /// them together... /// bool llvm::doConstantPropagation(BasicBlock::iterator &II) { if (Constant *C = ConstantFoldInstruction(II)) { // Replaces all of the uses of a variable with uses of the constant. II->replaceAllUsesWith(C); // Remove the instruction from the basic block... II = II->getParent()->getInstList().erase(II); return true; } return false; } /// ConstantFoldInstruction - Attempt to constant fold the specified /// instruction. If successful, the constant result is returned, if not, null /// is returned. Note that this function can only fail when attempting to fold /// instructions like loads and stores, which have no constant expression form. /// Constant *llvm::ConstantFoldInstruction(Instruction *I) { if (PHINode *PN = dyn_cast<PHINode>(I)) { if (PN->getNumIncomingValues() == 0) return Constant::getNullValue(PN->getType()); Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0)); if (Result == 0) return 0; // Handle PHI nodes specially here... for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i) if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN) return 0; // Not all the same incoming constants... // If we reach here, all incoming values are the same constant. return Result; } else if (CallInst *CI = dyn_cast<CallInst>(I)) { if (Function *F = CI->getCalledFunction()) if (canConstantFoldCallTo(F)) { std::vector<Constant*> Args; for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i) if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i))) Args.push_back(Op); else return 0; return ConstantFoldCall(F, Args); } return 0; } Constant *Op0 = 0, *Op1 = 0; switch (I->getNumOperands()) { default: case 2: Op1 = dyn_cast<Constant>(I->getOperand(1)); if (Op1 == 0) return 0; // Not a constant?, can't fold case 1: Op0 = dyn_cast<Constant>(I->getOperand(0)); if (Op0 == 0) return 0; // Not a constant?, can't fold break; case 0: return 0; } if (isa<BinaryOperator>(I) || isa<ShiftInst>(I)) return ConstantExpr::get(I->getOpcode(), Op0, Op1); switch (I->getOpcode()) { default: return 0; case Instruction::Cast: return ConstantExpr::getCast(Op0, I->getType()); case Instruction::Select: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getSelect(Op0, Op1, Op2); return 0; case Instruction::ExtractElement: return ConstantExpr::getExtractElement(Op0, Op1); case Instruction::InsertElement: if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2))) return ConstantExpr::getInsertElement(Op0, Op1, Op2); case Instruction::GetElementPtr: std::vector<Constant*> IdxList; IdxList.reserve(I->getNumOperands()-1); if (Op1) IdxList.push_back(Op1); for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i) if (Constant *C = dyn_cast<Constant>(I->getOperand(i))) IdxList.push_back(C); else return 0; // Non-constant operand return ConstantExpr::getGetElementPtr(Op0, IdxList); } } // ConstantFoldTerminator - If a terminator instruction is predicated on a // constant value, convert it into an unconditional branch to the constant // destination. // bool llvm::ConstantFoldTerminator(BasicBlock *BB) { TerminatorInst *T = BB->getTerminator(); // Branch - See if we are conditional jumping on constant if (BranchInst *BI = dyn_cast<BranchInst>(T)) { if (BI->isUnconditional()) return false; // Can't optimize uncond branch BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0)); BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1)); if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) { // Are we branching on constant? // YES. Change to unconditional branch... BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2; BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1; //cerr << "Function: " << T->getParent()->getParent() // << "\nRemoving branch from " << T->getParent() // << "\n\nTo: " << OldDest << endl; // Let the basic block know that we are letting go of it. Based on this, // it will adjust it's PHI nodes. assert(BI->getParent() && "Terminator not inserted in block!"); OldDest->removePredecessor(BI->getParent()); // Set the unconditional destination, and change the insn to be an // unconditional branch. BI->setUnconditionalDest(Destination); return true; } else if (Dest2 == Dest1) { // Conditional branch to same location? // This branch matches something like this: // br bool %cond, label %Dest, label %Dest // and changes it into: br label %Dest // Let the basic block know that we are letting go of one copy of it. assert(BI->getParent() && "Terminator not inserted in block!"); Dest1->removePredecessor(BI->getParent()); // Change a conditional branch to unconditional. BI->setUnconditionalDest(Dest1); return true; } } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) { // If we are switching on a constant, we can convert the switch into a // single branch instruction! ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition()); BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest BasicBlock *DefaultDest = TheOnlyDest; assert(TheOnlyDest == SI->getDefaultDest() && "Default destination is not successor #0?"); // Figure out which case it goes to... for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? if (SI->getSuccessorValue(i) == CI) { TheOnlyDest = SI->getSuccessor(i); break; } // Check to see if this branch is going to the same place as the default // dest. If so, eliminate it as an explicit compare. if (SI->getSuccessor(i) == DefaultDest) { // Remove this entry... DefaultDest->removePredecessor(SI->getParent()); SI->removeCase(i); --i; --e; // Don't skip an entry... continue; } // Otherwise, check to see if the switch only branches to one destination. // We do this by reseting "TheOnlyDest" to null when we find two non-equal // destinations. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0; } if (CI && !TheOnlyDest) { // Branching on a constant, but not any of the cases, go to the default // successor. TheOnlyDest = SI->getDefaultDest(); } // If we found a single destination that we can fold the switch into, do so // now. if (TheOnlyDest) { // Insert the new branch.. new BranchInst(TheOnlyDest, SI); BasicBlock *BB = SI->getParent(); // Remove entries from PHI nodes which we no longer branch to... for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) { // Found case matching a constant operand? BasicBlock *Succ = SI->getSuccessor(i); if (Succ == TheOnlyDest) TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest else Succ->removePredecessor(BB); } // Delete the old switch... BB->getInstList().erase(SI); return true; } else if (SI->getNumSuccessors() == 2) { // Otherwise, we can fold this switch into a conditional branch // instruction if it has only one non-default destination. Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(), SI->getSuccessorValue(1), "cond", SI); // Insert the new branch... new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI); // Delete the old switch... SI->getParent()->getInstList().erase(SI); return true; } } return false; } /// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a /// getelementptr constantexpr, return the constant value being addressed by the /// constant expression, or null if something is funny and we can't decide. Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, ConstantExpr *CE) { if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType())) return 0; // Do not allow stepping over the value! // Loop over all of the operands, tracking down which value we are // addressing... gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE); for (++I; I != E; ++I) if (const StructType *STy = dyn_cast<StructType>(*I)) { ConstantUInt *CU = cast<ConstantUInt>(I.getOperand()); assert(CU->getValue() < STy->getNumElements() && "Struct index out of range!"); unsigned El = (unsigned)CU->getValue(); if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) { C = CS->getOperand(El); } else if (isa<ConstantAggregateZero>(C)) { C = Constant::getNullValue(STy->getElementType(El)); } else if (isa<UndefValue>(C)) { C = UndefValue::get(STy->getElementType(El)); } else { return 0; } } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) { const ArrayType *ATy = cast<ArrayType>(*I); if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0; if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) C = CA->getOperand((unsigned)CI->getRawValue()); else if (isa<ConstantAggregateZero>(C)) C = Constant::getNullValue(ATy->getElementType()); else if (isa<UndefValue>(C)) C = UndefValue::get(ATy->getElementType()); else return 0; } else { return 0; } return C; } //===----------------------------------------------------------------------===// // Local dead code elimination... // bool llvm::isInstructionTriviallyDead(Instruction *I) { if (!I->use_empty() || isa<TerminatorInst>(I)) return false; if (!I->mayWriteToMemory()) return true; if (CallInst *CI = dyn_cast<CallInst>(I)) if (Function *F = CI->getCalledFunction()) switch (F->getIntrinsicID()) { default: break; case Intrinsic::returnaddress: case Intrinsic::frameaddress: case Intrinsic::stacksave: case Intrinsic::isunordered_f32: case Intrinsic::isunordered_f64: case Intrinsic::bswap_i16: case Intrinsic::bswap_i32: case Intrinsic::bswap_i64: case Intrinsic::ctpop_i8: case Intrinsic::ctpop_i16: case Intrinsic::ctpop_i32: case Intrinsic::ctpop_i64: case Intrinsic::ctlz_i8: case Intrinsic::ctlz_i16: case Intrinsic::ctlz_i32: case Intrinsic::ctlz_i64: case Intrinsic::cttz_i8: case Intrinsic::cttz_i16: case Intrinsic::cttz_i32: case Intrinsic::cttz_i64: case Intrinsic::sqrt_f32: case Intrinsic::sqrt_f64: return true; // These intrinsics have no side effects. } return false; } // dceInstruction - Inspect the instruction at *BBI and figure out if it's // [trivially] dead. If so, remove the instruction and update the iterator // to point to the instruction that immediately succeeded the original // instruction. // bool llvm::dceInstruction(BasicBlock::iterator &BBI) { // Look for un"used" definitions... if (isInstructionTriviallyDead(BBI)) { BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye return true; } return false; } <|endoftext|>