text
stringlengths 54
60.6k
|
---|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
#include "internal/iso8601_converter.hxx"
#include "internal/utilities.hxx"
#include <sstream>
#include <iomanip>
//-----------------------------------
/* Converts ISO 8601 conform date/time
represenation to the representation
conforming to the current locale
*/
std::wstring iso8601_date_to_local_date(const std::wstring& isoDate )
{
const std::wstring CONST_SPACE(L" ");
::std::wstring ws8601DateTime(isoDate);
if ( ws8601DateTime.length() == 19 )
{
std::string asDateTime = WStringToString( ws8601DateTime );
SYSTEMTIME DateTime;
DateTime.wYear = ( unsigned short )strtol( asDateTime.substr( 0, 4 ).c_str(), NULL, 10 );
DateTime.wMonth = ( unsigned short )strtol( asDateTime.substr( 5, 2 ).c_str(), NULL, 10 );
DateTime.wDayOfWeek = 0;
DateTime.wDay = ( unsigned short )strtol( asDateTime.substr( 8, 2 ).c_str(), NULL, 10 );
DateTime.wHour = ( unsigned short )strtol( asDateTime.substr( 11,2 ).c_str(), NULL, 10 );
DateTime.wMinute = ( unsigned short )strtol( asDateTime.substr( 14,2 ).c_str(), NULL, 10 );
DateTime.wSecond = ( unsigned short )strtol( asDateTime.substr( 17,2 ).c_str(), NULL, 10 );
DateTime.wMilliseconds = 0;
//get Date info from structure
WCHAR DateBuffer[ MAX_PATH ];
int DateSize = GetDateFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&DateTime,
NULL,
DateBuffer,
MAX_PATH );
if ( DateSize )
ws8601DateTime.assign(DateBuffer);
else
ws8601DateTime = StringToWString( asDateTime );
//get Time info from structure
WCHAR TimeBuffer[ MAX_PATH ];
int TimeSize = GetTimeFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&DateTime,
NULL,
TimeBuffer,
MAX_PATH );
if ( TimeSize )
{
ws8601DateTime.append(L" ");
ws8601DateTime.append(TimeBuffer);
}
else
ws8601DateTime = StringToWString( asDateTime );
}
return ws8601DateTime;
}
//------------------------------------
/* Converts ISO 8601 conform duration
representation to the representation
conforming to the current locale
Expect format PTnHnMnS according to
ISO 8601 where n is abitrary number
of digits
*/
std::wstring iso8601_duration_to_local_duration(const std::wstring& iso8601duration)
{
std::wstring days;
std::wstring hours;
std::wstring minutes;
std::wstring seconds;
std::wstring::const_iterator iter = iso8601duration.begin();
std::wstring::const_iterator iter_end = iso8601duration.end();
std::wstring num;
for (/**/; iter != iter_end; ++iter)
{
if (isdigit(*iter))
{
num += *iter;
}
else
{
if (*iter == L'D' || *iter == L'd')
days = num;
else if (*iter == L'H' || *iter == L'h')
hours = num;
else if (*iter == L'M' || *iter == L'm')
minutes = num;
else if (*iter == L'S' || *iter == L's')
seconds = num;
num.clear();
}
}
if (days.length() > 0)
{
int h = ((_wtoi(days.c_str()) * 24) + _wtoi(hours.c_str()));
wchar_t buff[10];
_itow(h, buff, 10);
hours = buff;
}
#if defined(_MSC_VER) //&& defined(_M_X64)
std::wostringstream oss;
oss << std::setw(2) << std::setfill(wchar_t('0')) << hours << L":" <<
std::setw(2) << std::setfill(wchar_t('0')) << minutes << L":" <<
std::setw(2) << std::setfill(wchar_t('0')) << seconds;
return oss.str();
#elif defined( __MINGW32__ )
#define ADD_AS_PREFILLED( st, out ) \
if ( st.length() == 0 ) \
out += L"00"; \
else if ( st.length() == 1 ) \
out += L"0"; \
out += st;
std::wstring result;
ADD_AS_PREFILLED( hours, result )
result += L":";
ADD_AS_PREFILLED( minutes, result )
result += L":";
ADD_AS_PREFILLED( seconds, result )
return result;
#undef ADD_AS_PREFILLED
#endif
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Missing include<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
#include "sal/config.h"
#include <stdlib.h>
#include "internal/iso8601_converter.hxx"
#include "internal/utilities.hxx"
#include <sstream>
#include <iomanip>
//-----------------------------------
/* Converts ISO 8601 conform date/time
represenation to the representation
conforming to the current locale
*/
std::wstring iso8601_date_to_local_date(const std::wstring& isoDate )
{
const std::wstring CONST_SPACE(L" ");
::std::wstring ws8601DateTime(isoDate);
if ( ws8601DateTime.length() == 19 )
{
std::string asDateTime = WStringToString( ws8601DateTime );
SYSTEMTIME DateTime;
DateTime.wYear = ( unsigned short )strtol( asDateTime.substr( 0, 4 ).c_str(), NULL, 10 );
DateTime.wMonth = ( unsigned short )strtol( asDateTime.substr( 5, 2 ).c_str(), NULL, 10 );
DateTime.wDayOfWeek = 0;
DateTime.wDay = ( unsigned short )strtol( asDateTime.substr( 8, 2 ).c_str(), NULL, 10 );
DateTime.wHour = ( unsigned short )strtol( asDateTime.substr( 11,2 ).c_str(), NULL, 10 );
DateTime.wMinute = ( unsigned short )strtol( asDateTime.substr( 14,2 ).c_str(), NULL, 10 );
DateTime.wSecond = ( unsigned short )strtol( asDateTime.substr( 17,2 ).c_str(), NULL, 10 );
DateTime.wMilliseconds = 0;
//get Date info from structure
WCHAR DateBuffer[ MAX_PATH ];
int DateSize = GetDateFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&DateTime,
NULL,
DateBuffer,
MAX_PATH );
if ( DateSize )
ws8601DateTime.assign(DateBuffer);
else
ws8601DateTime = StringToWString( asDateTime );
//get Time info from structure
WCHAR TimeBuffer[ MAX_PATH ];
int TimeSize = GetTimeFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&DateTime,
NULL,
TimeBuffer,
MAX_PATH );
if ( TimeSize )
{
ws8601DateTime.append(L" ");
ws8601DateTime.append(TimeBuffer);
}
else
ws8601DateTime = StringToWString( asDateTime );
}
return ws8601DateTime;
}
//------------------------------------
/* Converts ISO 8601 conform duration
representation to the representation
conforming to the current locale
Expect format PTnHnMnS according to
ISO 8601 where n is abitrary number
of digits
*/
std::wstring iso8601_duration_to_local_duration(const std::wstring& iso8601duration)
{
std::wstring days;
std::wstring hours;
std::wstring minutes;
std::wstring seconds;
std::wstring::const_iterator iter = iso8601duration.begin();
std::wstring::const_iterator iter_end = iso8601duration.end();
std::wstring num;
for (/**/; iter != iter_end; ++iter)
{
if (isdigit(*iter))
{
num += *iter;
}
else
{
if (*iter == L'D' || *iter == L'd')
days = num;
else if (*iter == L'H' || *iter == L'h')
hours = num;
else if (*iter == L'M' || *iter == L'm')
minutes = num;
else if (*iter == L'S' || *iter == L's')
seconds = num;
num.clear();
}
}
if (days.length() > 0)
{
int h = ((_wtoi(days.c_str()) * 24) + _wtoi(hours.c_str()));
wchar_t buff[10];
_itow(h, buff, 10);
hours = buff;
}
#if defined(_MSC_VER) //&& defined(_M_X64)
std::wostringstream oss;
oss << std::setw(2) << std::setfill(wchar_t('0')) << hours << L":" <<
std::setw(2) << std::setfill(wchar_t('0')) << minutes << L":" <<
std::setw(2) << std::setfill(wchar_t('0')) << seconds;
return oss.str();
#elif defined( __MINGW32__ )
#define ADD_AS_PREFILLED( st, out ) \
if ( st.length() == 0 ) \
out += L"00"; \
else if ( st.length() == 1 ) \
out += L"0"; \
out += st;
std::wstring result;
ADD_AS_PREFILLED( hours, result )
result += L":";
ADD_AS_PREFILLED( minutes, result )
result += L":";
ADD_AS_PREFILLED( seconds, result )
return result;
#undef ADD_AS_PREFILLED
#endif
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 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 [email protected].
*
* 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/>.
*/
#include "XalanParsedURI.hpp"
#include "XalanUnicode.hpp"
XALAN_CPP_NAMESPACE_BEGIN
#if defined(XALAN_INLINE_INITIALIZATION) && !defined(XALAN_INLINE_INITIALIZATION_IS_DEFINITION_BUG)
const int XalanParsedURI::d_scheme;
const int XalanParsedURI::d_authority;
const int XalanParsedURI::d_query;
const int XalanParsedURI::d_fragment;
#endif
/* Merge the components back into a complete URI string */
XalanDOMString XalanParsedURI::make() const
{
XalanDOMString uri;
if (m_defined & d_scheme)
{
uri += m_scheme;
uri += XalanUnicode::charColon;
}
if (m_defined & d_authority)
{
uri += XalanUnicode::charSolidus;
uri += XalanUnicode::charSolidus;
uri += m_authority;
}
uri += m_path;
if (m_defined & d_query)
{
uri += XalanUnicode::charQuestionMark;
uri += m_query;
}
if (m_defined & d_fragment)
{
uri += XalanUnicode::charNumberSign;
uri += m_fragment;
}
return uri;
}
/* Parse a URI into component parts.
Essentially implements the regex ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
*/
void XalanParsedURI::parse(
const XalanDOMChar* uriString,
XalanDOMString::size_type uriStringLen
)
{
XalanDOMString::size_type index = 0;
// Clear the components present mask
m_defined = 0;
// Scheme portion
while (index < uriStringLen &&
uriString[index] != XalanUnicode::charColon &&
uriString[index] != XalanUnicode::charSolidus &&
uriString[index] != XalanUnicode::charQuestionMark &&
uriString[index] != XalanUnicode::charNumberSign)
{
++index;
}
if (index > 0 && uriString[index] == XalanUnicode::charColon)
{
m_scheme = XalanDOMString(uriString, index);
++index;
m_defined |= d_scheme;
}
else
{
index = 0;
m_scheme.clear();
}
// Authority portion
if (index < uriStringLen - 1 &&
uriString[index] == XalanUnicode::charSolidus &&
uriString[index+1] == XalanUnicode::charSolidus)
{
index += 2;
XalanDOMString::size_type authority = index;
while (index < uriStringLen &&
uriString[index] != XalanUnicode::charSolidus &&
uriString[index] != XalanUnicode::charQuestionMark &&
uriString[index] != XalanUnicode::charNumberSign)
{
++index;
}
m_authority = XalanDOMString(uriString + authority, index - authority);
m_defined |= d_authority;
}
else
{
m_authority.clear();
}
// Path portion
XalanDOMString::size_type path = index;
while (index < uriStringLen &&
uriString[index] != XalanUnicode::charQuestionMark &&
uriString[index] != XalanUnicode::charNumberSign)
{
++index;
}
m_path = XalanDOMString(uriString + path, index - path);
// Query portion
if (index < uriStringLen && uriString[index] == XalanUnicode::charQuestionMark)
{
++index;
XalanDOMString::size_type query = index;
while (index < uriStringLen &&
uriString[index] != XalanUnicode::charNumberSign)
{
++index;
}
m_query = XalanDOMString(uriString + query, index - query);
m_defined |= d_query;
}
else
{
m_query.clear();
}
// Fragment portion
if (index < uriStringLen && uriString[index] == XalanUnicode::charNumberSign)
{
++index;
m_fragment = XalanDOMString(uriString + index, uriStringLen - index);
m_defined |= d_fragment;
}
else
{
m_fragment.clear();
}
}
/* Case insensitive comparison for URIs. Limited to A-Za-z */
static int ci_equals(const XalanDOMString &s1, const XalanDOMString &s2)
{
if (s1.length() != s2.length())
return false;
const XalanDOMChar *p1 = s1.c_str(), *p2 = s2.c_str();
for ( ; *p1 ; p1++, p2++)
{
XalanDOMChar c1 = *p1, c2 = *p2;
if (c1 >= XalanUnicode::charLetter_A && c1 <= XalanUnicode::charLetter_Z)
c1 = XalanUnicode::charLetter_a + (c1 - XalanUnicode::charLetter_A);
if (c2 >= XalanUnicode::charLetter_A && c2 <= XalanUnicode::charLetter_Z)
c2 = XalanUnicode::charLetter_a + (c2 - XalanUnicode::charLetter_A);
if (c1 != c2)
return false;
}
return true;
}
/* Resolve this URI relative to another according to RFC2396, section 5.2 */
void XalanParsedURI::resolve(
const XalanParsedURI &base
)
{
// Handle references to the current document (step 2)
if ((m_defined & (d_scheme | d_authority | d_query)) == 0 &&
m_path.empty())
{
m_scheme = base.m_scheme;
m_authority = base.m_authority;
m_path = base.m_path;
m_query = base.m_query;
// There is an error/unclarity in the specification in step 2 in that
// it doesn't state that the fragment should be inherited; however
// it is clear from the examples that it should be
if (!(m_defined & d_fragment))
{
m_fragment = base.m_fragment;
}
m_defined |= base.m_defined;
return;
}
// A defined scheme component implies that this is an absolute URI (step 3)
// Also allow a scheme without authority that matches the base scheme to be
// interpreted as a relative URI
if (!(m_defined & d_scheme) || (
(base.m_defined & d_scheme) && !(m_defined & d_authority)
&& ci_equals(m_scheme, base.m_scheme)))
{
// Inherit the base scheme
m_scheme = base.m_scheme;
m_defined |= d_scheme;
// Step 4: If the authority is unm_defined then inherit it, otherwise skip to step 7
if (!(m_defined & d_authority))
{
// Inherit the base authority
m_authority = base.m_authority;
m_defined |= d_authority;
// Step 5: if the path starts with a / then it is absolute
if (!(m_path.length() > 0 && m_path[0] == XalanUnicode::charSolidus))
{
// Step 6: merge relative path components
// a) strip off characters after the right most slash in the base path
XalanDOMString::size_type pathEnd = base.m_path.length();
while (pathEnd > 0 && base.m_path[pathEnd - 1] != XalanUnicode::charSolidus)
{
--pathEnd;
}
if (pathEnd > 0)
{
// b) append relative path
// This inserts the path portion from base...
m_path.insert(0, base.m_path, 0, pathEnd);
}
else
{
// TODO, maybe raise an error here as this
// is a severely wonky looking URI
}
// c)->g remove various "./" and "../" segments
for (XalanDOMString::size_type index = 0; index < m_path.length(); )
{
// remove '<segment>/../' and ./
if (m_path[index] == XalanUnicode::charFullStop)
{
if (index < m_path.length()-1 &&
m_path[index+1] == XalanUnicode::charSolidus) // ./
{
m_path.erase(index,2);
continue;
}
else if (index == m_path.length()-1) // trailing /.
{
m_path.erase(index,1);
continue;
}
// Note: also strips leading ../ in an attempt to get
// something out of a bad m_path
else if (index < m_path.length()-2 &&
m_path[index+1] == XalanUnicode::charFullStop &&
m_path[index+2] == XalanUnicode::charSolidus) // ../
{
int end = index+2;
if (index > 0) --index;
for ( ; index > 0 && m_path[index-1] != XalanUnicode::charSolidus; index--)
;
if (index > 0) --index;
m_path.erase(index,end-index);
continue;
}
else if (index == m_path.length()-2 &&
m_path[index+1] == XalanUnicode::charFullStop) // trailing /..
{
int end = index+2;
if (index > 0) --index;
for ( ; index > 0 && m_path[index-1] != XalanUnicode::charSolidus; index--)
;
m_path.erase(index,end-index);
continue;
}
}
for ( ; index < m_path.length() && m_path[index] != XalanUnicode::charSolidus ; ++index)
{
}
++index;
}
}
}
}
}
/* Static helper function to perform a resolve without mucking about with this class */
XalanDOMString XalanParsedURI::resolve(
const XalanDOMChar *relative,
XalanDOMString::size_type relativeLen,
const XalanDOMChar *base,
XalanDOMString::size_type baseLen
)
{
XalanParsedURI relativeURI(relative, relativeLen);
XalanParsedURI baseURI(base, baseLen);
relativeURI.resolve(baseURI);
return relativeURI.make();
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Fixed inappropriate uses of int instead of XalanDOMString::size_type.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2003 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 [email protected].
*
* 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/>.
*/
#include "XalanParsedURI.hpp"
#include "XalanUnicode.hpp"
XALAN_CPP_NAMESPACE_BEGIN
#if defined(XALAN_INLINE_INITIALIZATION) && !defined(XALAN_INLINE_INITIALIZATION_IS_DEFINITION_BUG)
const int XalanParsedURI::d_scheme;
const int XalanParsedURI::d_authority;
const int XalanParsedURI::d_query;
const int XalanParsedURI::d_fragment;
#endif
/* Merge the components back into a complete URI string */
XalanDOMString XalanParsedURI::make() const
{
XalanDOMString uri;
if (m_defined & d_scheme)
{
uri += m_scheme;
uri += XalanUnicode::charColon;
}
if (m_defined & d_authority)
{
uri += XalanUnicode::charSolidus;
uri += XalanUnicode::charSolidus;
uri += m_authority;
}
uri += m_path;
if (m_defined & d_query)
{
uri += XalanUnicode::charQuestionMark;
uri += m_query;
}
if (m_defined & d_fragment)
{
uri += XalanUnicode::charNumberSign;
uri += m_fragment;
}
return uri;
}
/* Parse a URI into component parts.
Essentially implements the regex ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
*/
void XalanParsedURI::parse(
const XalanDOMChar* uriString,
XalanDOMString::size_type uriStringLen
)
{
XalanDOMString::size_type index = 0;
// Clear the components present mask
m_defined = 0;
// Scheme portion
while (index < uriStringLen &&
uriString[index] != XalanUnicode::charColon &&
uriString[index] != XalanUnicode::charSolidus &&
uriString[index] != XalanUnicode::charQuestionMark &&
uriString[index] != XalanUnicode::charNumberSign)
{
++index;
}
if (index > 0 && uriString[index] == XalanUnicode::charColon)
{
m_scheme = XalanDOMString(uriString, index);
++index;
m_defined |= d_scheme;
}
else
{
index = 0;
m_scheme.clear();
}
// Authority portion
if (index < uriStringLen - 1 &&
uriString[index] == XalanUnicode::charSolidus &&
uriString[index+1] == XalanUnicode::charSolidus)
{
index += 2;
XalanDOMString::size_type authority = index;
while (index < uriStringLen &&
uriString[index] != XalanUnicode::charSolidus &&
uriString[index] != XalanUnicode::charQuestionMark &&
uriString[index] != XalanUnicode::charNumberSign)
{
++index;
}
m_authority = XalanDOMString(uriString + authority, index - authority);
m_defined |= d_authority;
}
else
{
m_authority.clear();
}
// Path portion
XalanDOMString::size_type path = index;
while (index < uriStringLen &&
uriString[index] != XalanUnicode::charQuestionMark &&
uriString[index] != XalanUnicode::charNumberSign)
{
++index;
}
m_path = XalanDOMString(uriString + path, index - path);
// Query portion
if (index < uriStringLen && uriString[index] == XalanUnicode::charQuestionMark)
{
++index;
XalanDOMString::size_type query = index;
while (index < uriStringLen &&
uriString[index] != XalanUnicode::charNumberSign)
{
++index;
}
m_query = XalanDOMString(uriString + query, index - query);
m_defined |= d_query;
}
else
{
m_query.clear();
}
// Fragment portion
if (index < uriStringLen && uriString[index] == XalanUnicode::charNumberSign)
{
++index;
m_fragment = XalanDOMString(uriString + index, uriStringLen - index);
m_defined |= d_fragment;
}
else
{
m_fragment.clear();
}
}
/* Case insensitive comparison for URIs. Limited to A-Za-z */
static int ci_equals(const XalanDOMString &s1, const XalanDOMString &s2)
{
if (s1.length() != s2.length())
return false;
const XalanDOMChar *p1 = s1.c_str(), *p2 = s2.c_str();
for ( ; *p1 ; p1++, p2++)
{
XalanDOMChar c1 = *p1, c2 = *p2;
if (c1 >= XalanUnicode::charLetter_A && c1 <= XalanUnicode::charLetter_Z)
c1 = XalanUnicode::charLetter_a + (c1 - XalanUnicode::charLetter_A);
if (c2 >= XalanUnicode::charLetter_A && c2 <= XalanUnicode::charLetter_Z)
c2 = XalanUnicode::charLetter_a + (c2 - XalanUnicode::charLetter_A);
if (c1 != c2)
return false;
}
return true;
}
/* Resolve this URI relative to another according to RFC2396, section 5.2 */
void XalanParsedURI::resolve(
const XalanParsedURI &base
)
{
// Handle references to the current document (step 2)
if ((m_defined & (d_scheme | d_authority | d_query)) == 0 &&
m_path.empty())
{
m_scheme = base.m_scheme;
m_authority = base.m_authority;
m_path = base.m_path;
m_query = base.m_query;
// There is an error/unclarity in the specification in step 2 in that
// it doesn't state that the fragment should be inherited; however
// it is clear from the examples that it should be
if (!(m_defined & d_fragment))
{
m_fragment = base.m_fragment;
}
m_defined |= base.m_defined;
return;
}
// A defined scheme component implies that this is an absolute URI (step 3)
// Also allow a scheme without authority that matches the base scheme to be
// interpreted as a relative URI
if (!(m_defined & d_scheme) || (
(base.m_defined & d_scheme) && !(m_defined & d_authority)
&& ci_equals(m_scheme, base.m_scheme)))
{
// Inherit the base scheme
m_scheme = base.m_scheme;
m_defined |= d_scheme;
// Step 4: If the authority is unm_defined then inherit it, otherwise skip to step 7
if (!(m_defined & d_authority))
{
// Inherit the base authority
m_authority = base.m_authority;
m_defined |= d_authority;
// Step 5: if the path starts with a / then it is absolute
if (!(m_path.length() > 0 && m_path[0] == XalanUnicode::charSolidus))
{
// Step 6: merge relative path components
// a) strip off characters after the right most slash in the base path
XalanDOMString::size_type pathEnd = base.m_path.length();
while (pathEnd > 0 && base.m_path[pathEnd - 1] != XalanUnicode::charSolidus)
{
--pathEnd;
}
if (pathEnd > 0)
{
// b) append relative path
// This inserts the path portion from base...
m_path.insert(0, base.m_path, 0, pathEnd);
}
else
{
// TODO, maybe raise an error here as this
// is a severely wonky looking URI
}
// c)->g remove various "./" and "../" segments
for (XalanDOMString::size_type index = 0; index < m_path.length(); )
{
// remove '<segment>/../' and ./
if (m_path[index] == XalanUnicode::charFullStop)
{
if (index < m_path.length()-1 &&
m_path[index+1] == XalanUnicode::charSolidus) // ./
{
m_path.erase(index,2);
continue;
}
else if (index == m_path.length()-1) // trailing /.
{
m_path.erase(index,1);
continue;
}
// Note: also strips leading ../ in an attempt to get
// something out of a bad m_path
else if (index < m_path.length()-2 &&
m_path[index+1] == XalanUnicode::charFullStop &&
m_path[index+2] == XalanUnicode::charSolidus) // ../
{
const XalanDOMString::size_type end = index + 2;
if (index > 0) --index;
for ( ; index > 0 && m_path[index-1] != XalanUnicode::charSolidus; index--)
;
if (index > 0) --index;
m_path.erase(index, end - index);
continue;
}
else if (index == m_path.length()-2 &&
m_path[index+1] == XalanUnicode::charFullStop) // trailing /..
{
const XalanDOMString::size_type end = index + 2;
if (index > 0) --index;
for ( ; index > 0 && m_path[index-1] != XalanUnicode::charSolidus; index--)
;
m_path.erase(index, end - index);
continue;
}
}
for ( ; index < m_path.length() && m_path[index] != XalanUnicode::charSolidus ; ++index)
{
}
++index;
}
}
}
}
}
/* Static helper function to perform a resolve without mucking about with this class */
XalanDOMString XalanParsedURI::resolve(
const XalanDOMChar *relative,
XalanDOMString::size_type relativeLen,
const XalanDOMChar *base,
XalanDOMString::size_type baseLen
)
{
XalanParsedURI relativeURI(relative, relativeLen);
XalanParsedURI baseURI(base, baseLen);
relativeURI.resolve(baseURI);
return relativeURI.make();
}
XALAN_CPP_NAMESPACE_END
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -fexceptions -fsyntax-only -verify %s -std=c++0x
struct S {
virtual ~S();
auto a; // expected-error{{'auto' not allowed in struct member}}
auto *b; // expected-error{{'auto' not allowed in struct member}}
const auto c; // expected-error{{'auto' not allowed in struct member}}
void f() throw (auto); // expected-error{{'auto' not allowed here}}
friend auto; // expected-error{{'auto' not allowed in struct member}}
operator auto(); // expected-error{{'auto' not allowed here}}
};
typedef auto *AutoPtr; // expected-error{{'auto' not allowed in typedef}}
typedef auto Fun(int a) -> decltype(a + a);
void g(auto a) { // expected-error{{'auto' not allowed in function prototype}}
try { }
catch (auto &a) { } // expected-error{{'auto' not allowed in exception declaration}}
catch (const auto a) { } // expected-error{{'auto' not allowed in exception declaration}}
try { } catch (auto a) { } // expected-error{{'auto' not allowed in exception declaration}}
}
void h(auto a[10]) { // expected-error{{'auto' not allowed in function prototype}}
}
void i(const auto a) { // expected-error{{'auto' not allowed in function prototype}}
}
namespace std {
class type_info;
}
template<typename T> struct U {};
void j() {
(void)typeid(auto); // expected-error{{'auto' not allowed here}}
(void)sizeof(auto); // expected-error{{'auto' not allowed here}}
(void)__alignof(auto); // expected-error{{'auto' not allowed here}}
// FIXME: don't issue the second diagnostic for this error.
U<auto> v; // expected-error{{'auto' not allowed in template argument}} unexpected-error{{C++ requires a type specifier}}
int n;
(void)dynamic_cast<auto&>(S()); // expected-error{{'auto' not allowed here}}
(void)static_cast<auto*>(&n); // expected-error{{'auto' not allowed here}}
(void)reinterpret_cast<auto*>(&n); // expected-error{{'auto' not allowed here}}
(void)const_cast<auto>(n); // expected-error{{'auto' not allowed here}}
(void)*(auto*)(&n); // expected-error{{'auto' not allowed here}}
(void)auto(n); // expected-error{{expected expression}}
(void)auto{n}; // expected-error{{expected expression}}
}
template <auto a = 10> class C { }; // expected-error{{'auto' not allowed in template parameter}}
int ints[] = {1, 2, 3};
template <const auto (*a)[3] = &ints> class D { }; // expected-error{{'auto' not allowed in template parameter}}
enum E : auto {}; // expected-error{{'auto' not allowed here}}
struct F : auto {}; // expected-error{{expected class name}}
template<typename T = auto> struct G { }; // expected-error{{'auto' not allowed here}}
using A = auto; // expected-error{{expected ';'}} expected-error{{requires a qualified name}}
// Whether this is illegal depends on the interpretation of [decl.spec.auto]p2 and p3,
// and in particular the "Otherwise, ..." at the start of p3.
namespace TrailingReturnType {
// FIXME: don't issue the second diagnostic for this error.
auto f() -> auto; // expected-error{{'auto' not allowed here}} unexpected-error{{without trailing return type}}
int g();
auto (*h)() -> auto = &g; // expected-error{{'auto' not allowed here}}
auto (*i)() = &g; // ok; auto deduced as int.
auto (*j)() -> int = i; // ok; no deduction.
}
<commit_msg>Add reference to PR 9278 for archaeologists.<commit_after>// RUN: %clang_cc1 -fexceptions -fsyntax-only -verify %s -std=c++0x
struct S {
virtual ~S();
auto a; // expected-error{{'auto' not allowed in struct member}}
auto *b; // expected-error{{'auto' not allowed in struct member}}
const auto c; // expected-error{{'auto' not allowed in struct member}}
void f() throw (auto); // expected-error{{'auto' not allowed here}}
friend auto; // expected-error{{'auto' not allowed in struct member}}
operator auto(); // expected-error{{'auto' not allowed here}}
};
// PR 9278: auto is not allowed in typedefs, except with a trailing return type.
typedef auto *AutoPtr; // expected-error{{'auto' not allowed in typedef}}
typedef auto Fun(int a) -> decltype(a + a);
void g(auto a) { // expected-error{{'auto' not allowed in function prototype}}
try { }
catch (auto &a) { } // expected-error{{'auto' not allowed in exception declaration}}
catch (const auto a) { } // expected-error{{'auto' not allowed in exception declaration}}
try { } catch (auto a) { } // expected-error{{'auto' not allowed in exception declaration}}
}
void h(auto a[10]) { // expected-error{{'auto' not allowed in function prototype}}
}
void i(const auto a) { // expected-error{{'auto' not allowed in function prototype}}
}
namespace std {
class type_info;
}
template<typename T> struct U {};
void j() {
(void)typeid(auto); // expected-error{{'auto' not allowed here}}
(void)sizeof(auto); // expected-error{{'auto' not allowed here}}
(void)__alignof(auto); // expected-error{{'auto' not allowed here}}
// FIXME: don't issue the second diagnostic for this error.
U<auto> v; // expected-error{{'auto' not allowed in template argument}} unexpected-error{{C++ requires a type specifier}}
int n;
(void)dynamic_cast<auto&>(S()); // expected-error{{'auto' not allowed here}}
(void)static_cast<auto*>(&n); // expected-error{{'auto' not allowed here}}
(void)reinterpret_cast<auto*>(&n); // expected-error{{'auto' not allowed here}}
(void)const_cast<auto>(n); // expected-error{{'auto' not allowed here}}
(void)*(auto*)(&n); // expected-error{{'auto' not allowed here}}
(void)auto(n); // expected-error{{expected expression}}
(void)auto{n}; // expected-error{{expected expression}}
}
template <auto a = 10> class C { }; // expected-error{{'auto' not allowed in template parameter}}
int ints[] = {1, 2, 3};
template <const auto (*a)[3] = &ints> class D { }; // expected-error{{'auto' not allowed in template parameter}}
enum E : auto {}; // expected-error{{'auto' not allowed here}}
struct F : auto {}; // expected-error{{expected class name}}
template<typename T = auto> struct G { }; // expected-error{{'auto' not allowed here}}
using A = auto; // expected-error{{expected ';'}} expected-error{{requires a qualified name}}
// Whether this is illegal depends on the interpretation of [decl.spec.auto]p2 and p3,
// and in particular the "Otherwise, ..." at the start of p3.
namespace TrailingReturnType {
// FIXME: don't issue the second diagnostic for this error.
auto f() -> auto; // expected-error{{'auto' not allowed here}} unexpected-error{{without trailing return type}}
int g();
auto (*h)() -> auto = &g; // expected-error{{'auto' not allowed here}}
auto (*i)() = &g; // ok; auto deduced as int.
auto (*j)() -> int = i; // ok; no deduction.
}
<|endoftext|> |
<commit_before>#include "assert.hh"
#include "exception.hh"
#include "debug.hh"
#include <sys/types.h>
#include <unistd.h>
namespace Kakoune
{
struct assert_failed : logic_error
{
assert_failed(const String& message)
: m_message(message) {}
const char* what() const override { return m_message.c_str(); }
private:
String m_message;
};
void on_assert_failed(const char* message)
{
String debug_info = "pid: " + to_string(getpid());
write_debug("assert failed: '"_str + message + "' " + debug_info);
int res = system(("xmessage -buttons 'quit:0,ignore:1' '"_str +
message + "\n[Debug Infos]\n" + debug_info + "'").c_str());
switch (res)
{
case -1:
case 0:
throw assert_failed(message);
case 1:
return;
}
}
}
<commit_msg>Use Win32 MessageBox for asserts on cygwin<commit_after>#include "assert.hh"
#include "exception.hh"
#include "debug.hh"
#if defined(__CYGWIN__)
#include <windows.h>
#endif
#include <sys/types.h>
#include <unistd.h>
namespace Kakoune
{
struct assert_failed : logic_error
{
assert_failed(const String& message)
: m_message(message) {}
const char* what() const override { return m_message.c_str(); }
private:
String m_message;
};
void on_assert_failed(const char* message)
{
String debug_info = "pid: " + to_string(getpid());
write_debug("assert failed: '"_str + message + "' " + debug_info);
const auto msg = message + "\n[Debug Infos]\n"_str + debug_info;
#if defined(__CYGWIN__)
int res = MessageBox(NULL, msg.c_str(), "Kakoune: assert failed",
MB_OKCANCEL | MB_ICONERROR);
switch (res)
{
case IDCANCEL:
throw assert_failed(message);
case IDOK:
return;
}
#else
int res = system(("xmessage -buttons 'quit:0,ignore:1' '" + msg + "'").c_str());
switch (res)
{
case -1:
case 0:
throw assert_failed(message);
case 1:
return;
}
#endif
}
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2013 Danny Y., Rapptz
// 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.
#ifndef SOL_STATE_HPP
#define SOL_STATE_HPP
#include "error.hpp"
#include "table.hpp"
#include <memory>
namespace sol {
namespace detail {
template<class T, class...>
struct are_same : std::true_type {};
template<class T, class U, class... Args>
struct are_same<T, U, Args...> : std::integral_constant<bool, std::is_same<T, U>::value && are_same<T, Args...>::value> {};
int atpanic(lua_State* L) {
std::string err = lua_tostring(L, -1);
throw sol_error(err);
}
} // detail
enum class lib : char {
base,
package,
coroutine,
string,
os,
math,
table,
debug,
bit32,
io,
count
};
class state {
private:
std::unique_ptr<lua_State, void(*)(lua_State*)> L;
table reg;
table global;
public:
state():
L(luaL_newstate(), lua_close),
reg(L.get(), LUA_REGISTRYINDEX),
global(reg.get<table>(LUA_RIDX_GLOBALS)) {
lua_atpanic(L.get(), detail::atpanic);
}
template<typename... Args>
void open_libraries(Args&&... args) {
static_assert(detail::are_same<lib, Args...>::value, "all types must be libraries");
if(sizeof...(args) == 0) {
luaL_openlibs(L.get());
return;
}
lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... };
for(auto&& library : libraries) {
switch(library) {
case lib::base:
luaL_requiref(L.get(), "base", luaopen_base, 1);
break;
case lib::package:
luaL_requiref(L.get(), "package", luaopen_package, 1);
break;
case lib::coroutine:
luaL_requiref(L.get(), "coroutine", luaopen_coroutine, 1);
break;
case lib::string:
luaL_requiref(L.get(), "string", luaopen_string, 1);
break;
case lib::table:
luaL_requiref(L.get(), "table", luaopen_table, 1);
break;
case lib::math:
luaL_requiref(L.get(), "math", luaopen_math, 1);
break;
case lib::bit32:
luaL_requiref(L.get(), "bit32", luaopen_bit32, 1);
break;
case lib::io:
luaL_requiref(L.get(), "io", luaopen_io, 1);
break;
case lib::os:
luaL_requiref(L.get(), "os", luaopen_os, 1);
break;
case lib::debug:
luaL_requiref(L.get(), "debug", luaopen_debug, 1);
break;
case lib::count:
break;
}
}
}
void script(const std::string& code) {
if(luaL_dostring(L.get(), code.c_str())) {
lua_error(L.get());
}
}
void open_file(const std::string& filename) {
if (luaL_dofile(L.get(), filename.c_str())) {
lua_error(L.get());
}
}
template<typename... Args, typename... Keys>
typename multi_return<Args...>::type get(Keys&&... keys) const {
return global.get(types<Args...>(), std::forward<Keys>(keys)...);
}
template<typename T, typename U>
state& set(T&& key, U&& value) {
global.set(std::forward<T>(key), std::forward<U>(value));
return *this;
}
template<typename T, typename TFx>
state& set_function(T&& key, TFx&& fx) {
global.set_function(std::forward<T>(key), std::forward<TFx>(fx));
return *this;
}
template<typename T, typename TFx, typename TM>
state& set_function(T&& key, TFx&& fx, TM& mem) {
global.set_function(std::forward<T>(key), std::forward<TFx>(fx), mem);
return *this;
}
template<typename T>
table create_table(T&& key, int narr = 0, int nrec = 0) {
lua_createtable(L.get(), narr, nrec);
table result(L.get());
lua_pop(L.get(), 1);
global.set(std::forward<T>(key), result);
return result;
}
table create_table(int narr = 0, int nrec = 0) {
lua_createtable(L.get(), narr, nrec);
table result(L.get());
lua_pop(L.get(), 1);
return result;
}
table global_table() const {
return global;
}
table registry() const {
return reg;
}
template <typename T>
proxy<table, T> operator[](T&& key) {
return global[std::forward<T>(key)];
}
template <typename T>
proxy<const table, T> operator[](T&& key) const {
return global[std::forward<T>(key)];
}
};
} // sol
#endif // SOL_STATE_HPP<commit_msg>Add lua_state function to retrieve the lua_State pointer<commit_after>// The MIT License (MIT)
// Copyright (c) 2013 Danny Y., Rapptz
// 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.
#ifndef SOL_STATE_HPP
#define SOL_STATE_HPP
#include "error.hpp"
#include "table.hpp"
#include <memory>
namespace sol {
namespace detail {
template<class T, class...>
struct are_same : std::true_type {};
template<class T, class U, class... Args>
struct are_same<T, U, Args...> : std::integral_constant<bool, std::is_same<T, U>::value && are_same<T, Args...>::value> {};
int atpanic(lua_State* L) {
std::string err = lua_tostring(L, -1);
throw sol_error(err);
}
} // detail
enum class lib : char {
base,
package,
coroutine,
string,
os,
math,
table,
debug,
bit32,
io,
count
};
class state {
private:
std::unique_ptr<lua_State, void(*)(lua_State*)> L;
table reg;
table global;
public:
state():
L(luaL_newstate(), lua_close),
reg(L.get(), LUA_REGISTRYINDEX),
global(reg.get<table>(LUA_RIDX_GLOBALS)) {
lua_atpanic(L.get(), detail::atpanic);
}
template<typename... Args>
void open_libraries(Args&&... args) {
static_assert(detail::are_same<lib, Args...>::value, "all types must be libraries");
if(sizeof...(args) == 0) {
luaL_openlibs(L.get());
return;
}
lib libraries[1 + sizeof...(args)] = { lib::count, std::forward<Args>(args)... };
for(auto&& library : libraries) {
switch(library) {
case lib::base:
luaL_requiref(L.get(), "base", luaopen_base, 1);
break;
case lib::package:
luaL_requiref(L.get(), "package", luaopen_package, 1);
break;
case lib::coroutine:
luaL_requiref(L.get(), "coroutine", luaopen_coroutine, 1);
break;
case lib::string:
luaL_requiref(L.get(), "string", luaopen_string, 1);
break;
case lib::table:
luaL_requiref(L.get(), "table", luaopen_table, 1);
break;
case lib::math:
luaL_requiref(L.get(), "math", luaopen_math, 1);
break;
case lib::bit32:
luaL_requiref(L.get(), "bit32", luaopen_bit32, 1);
break;
case lib::io:
luaL_requiref(L.get(), "io", luaopen_io, 1);
break;
case lib::os:
luaL_requiref(L.get(), "os", luaopen_os, 1);
break;
case lib::debug:
luaL_requiref(L.get(), "debug", luaopen_debug, 1);
break;
case lib::count:
break;
}
}
}
void script(const std::string& code) {
if(luaL_dostring(L.get(), code.c_str())) {
lua_error(L.get());
}
}
void open_file(const std::string& filename) {
if (luaL_dofile(L.get(), filename.c_str())) {
lua_error(L.get());
}
}
template<typename... Args, typename... Keys>
typename multi_return<Args...>::type get(Keys&&... keys) const {
return global.get(types<Args...>(), std::forward<Keys>(keys)...);
}
template<typename T, typename U>
state& set(T&& key, U&& value) {
global.set(std::forward<T>(key), std::forward<U>(value));
return *this;
}
template<typename T, typename TFx>
state& set_function(T&& key, TFx&& fx) {
global.set_function(std::forward<T>(key), std::forward<TFx>(fx));
return *this;
}
template<typename T, typename TFx, typename TM>
state& set_function(T&& key, TFx&& fx, TM& mem) {
global.set_function(std::forward<T>(key), std::forward<TFx>(fx), mem);
return *this;
}
template<typename T>
table create_table(T&& key, int narr = 0, int nrec = 0) {
lua_createtable(L.get(), narr, nrec);
table result(L.get());
lua_pop(L.get(), 1);
global.set(std::forward<T>(key), result);
return result;
}
table create_table(int narr = 0, int nrec = 0) {
lua_createtable(L.get(), narr, nrec);
table result(L.get());
lua_pop(L.get(), 1);
return result;
}
table global_table() const {
return global;
}
table registry() const {
return reg;
}
template <typename T>
proxy<table, T> operator[](T&& key) {
return global[std::forward<T>(key)];
}
template <typename T>
proxy<const table, T> operator[](T&& key) const {
return global[std::forward<T>(key)];
}
lua_State* lua_state() const {
return L.get();
}
};
} // sol
#endif // SOL_STATE_HPP<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_WINDOWS_SHELL_HPP__
#define __STOUT_OS_WINDOWS_SHELL_HPP__
#include <process.h>
#include <stdarg.h> // For va_list, va_start, etc.
#include <ostream>
#include <string>
#include <stout/try.hpp>
#include <stout/os/raw/argv.hpp>
namespace os {
namespace Shell {
// Canonical constants used as platform-dependent args to `exec` calls.
// `name` is the command name, `arg0` is the first argument received
// by the callee, usually the command name and `arg1` is the second
// command argument received by the callee.
constexpr const char* name = "cmd.exe";
constexpr const char* arg0 = "cmd";
constexpr const char* arg1 = "/c";
} // namespace Shell {
/**
* Runs a shell command with optional arguments.
*
* This assumes that a successful execution will result in the exit code
* for the command to be `EXIT_SUCCESS`; in this case, the contents
* of the `Try` will be the contents of `stdout`.
*
* If the exit code is non-zero or the process was signaled, we will
* return an appropriate error message; but *not* `stderr`.
*
* If the caller needs to examine the contents of `stderr` it should
* be redirected to `stdout` (using, e.g., "2>&1 || true" in the command
* string). The `|| true` is required to obtain a success exit
* code in case of errors, and still obtain `stderr`, as piped to
* `stdout`.
*
* @param fmt the formatting string that contains the command to execute
* in the underlying shell.
* @param t optional arguments for `fmt`.
*
* @return the output from running the specified command with the shell; or
* an error message if the command's exit code is non-zero.
*/
template <typename... T>
Try<std::string> shell(const std::string& fmt, const T&... t)
{
const Try<std::string> command = strings::internal::format(fmt, t...);
if (command.isError()) {
return Error(command.error());
}
FILE* file;
std::ostringstream stdoutstr;
if ((file = _popen(command.get().c_str(), "r")) == nullptr) {
return Error("Failed to run '" + command.get() + "'");
}
char line[1024];
// NOTE(vinod): Ideally the if and while loops should be interchanged. But
// we get a broken pipe error if we don't read the output and simply close.
while (fgets(line, sizeof(line), file) != nullptr) {
stdoutstr << line;
}
if (ferror(file) != 0) {
_pclose(file); // Ignoring result since we already have an error.
return Error("Error reading output of '" + command.get() + "'");
}
int status;
if ((status = _pclose(file)) == -1) {
return Error("Failed to get status of '" + command.get() + "'");
}
return stdoutstr.str();
}
// Executes a command by calling "cmd /c <command>", and returns
// after the command has been completed. Returns 0 if succeeds, and
// return -1 on error.
//
// The returned value from `_spawnlp` represents child exit code when
// `_P_WAIT` is used.
inline int system(const std::string& command)
{
return static_cast<int>(::_spawnlp(
_P_WAIT, Shell::name, Shell::arg0, Shell::arg1, command.c_str(), nullptr));
}
// Executes a command by calling "<command> <arguments...>", and
// returns after the command has been completed. Returns 0 if
// succeeds, and -1 on error.
inline int spawn(
const std::string& command,
const std::vector<std::string>& arguments)
{
return ::_spawnvp(_P_WAIT, command.c_str(), os::raw::Argv(arguments));
}
// On Windows, the `_spawnlp` call creates a new process.
// In order to emulate the semantics of `execlp`, we spawn with `_P_WAIT`,
// which forces the parent process to block on the child. When the child exits,
// the exit code is propagated back through the parent via `exit()`.
//
// The returned value from `_spawnlp` represents child exit code when
// `_P_WAIT` is used.
template<typename... T>
inline int execlp(const char* file, T... t)
{
exit(static_cast<int>(::_spawnlp(_P_WAIT, file, t...));
return 0;
}
// On Windows, the `_spawnvp` call creates a new process.
// In order to emulate the semantics of `execvp`, we spawn with `_P_WAIT`,
// which forces the parent process to block on the child. When the child exits,
// the exit code is propagated back through the parent via `exit()`.
//
// The returned value from `_spawnlp` represents child exit code when
// `_P_WAIT` is used.
inline int execvp(const char* file, char* const argv[])
{
exit(static_cast<int>(::_spawnvp(_P_WAIT, file, argv));
return 0;
}
// Concatenates multiple command-line arguments and escapes the values.
// If `arg` is not specified (or takes the value `0`), the function will
// scan `argv` until a `nullptr` is encountered.
inline std::string stringify_args(char** argv, unsigned long argc = 0)
{
std::string arg_line = "";
unsigned long index = 0;
while ((argc == 0 || index < argc) && argv[index] != nullptr) {
// TODO(dpravat): (MESOS-5522) Format these args for all cases.
// Specifically, we need to:
// (1) Add double quotes around arguments that contain special
// characters, like spaces and tabs.
// (2) Escape any existing double quotes and backslashes.
arg_line = strings::join(" ", arg_line, argv[index++]);
}
return arg_line;
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_SHELL_HPP__
<commit_msg>Windows: Fix typo in `windows/shell.hpp`.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_WINDOWS_SHELL_HPP__
#define __STOUT_OS_WINDOWS_SHELL_HPP__
#include <process.h>
#include <stdarg.h> // For va_list, va_start, etc.
#include <ostream>
#include <string>
#include <stout/try.hpp>
#include <stout/os/raw/argv.hpp>
namespace os {
namespace Shell {
// Canonical constants used as platform-dependent args to `exec` calls.
// `name` is the command name, `arg0` is the first argument received
// by the callee, usually the command name and `arg1` is the second
// command argument received by the callee.
constexpr const char* name = "cmd.exe";
constexpr const char* arg0 = "cmd";
constexpr const char* arg1 = "/c";
} // namespace Shell {
/**
* Runs a shell command with optional arguments.
*
* This assumes that a successful execution will result in the exit code
* for the command to be `EXIT_SUCCESS`; in this case, the contents
* of the `Try` will be the contents of `stdout`.
*
* If the exit code is non-zero or the process was signaled, we will
* return an appropriate error message; but *not* `stderr`.
*
* If the caller needs to examine the contents of `stderr` it should
* be redirected to `stdout` (using, e.g., "2>&1 || true" in the command
* string). The `|| true` is required to obtain a success exit
* code in case of errors, and still obtain `stderr`, as piped to
* `stdout`.
*
* @param fmt the formatting string that contains the command to execute
* in the underlying shell.
* @param t optional arguments for `fmt`.
*
* @return the output from running the specified command with the shell; or
* an error message if the command's exit code is non-zero.
*/
template <typename... T>
Try<std::string> shell(const std::string& fmt, const T&... t)
{
const Try<std::string> command = strings::internal::format(fmt, t...);
if (command.isError()) {
return Error(command.error());
}
FILE* file;
std::ostringstream stdoutstr;
if ((file = _popen(command.get().c_str(), "r")) == nullptr) {
return Error("Failed to run '" + command.get() + "'");
}
char line[1024];
// NOTE(vinod): Ideally the if and while loops should be interchanged. But
// we get a broken pipe error if we don't read the output and simply close.
while (fgets(line, sizeof(line), file) != nullptr) {
stdoutstr << line;
}
if (ferror(file) != 0) {
_pclose(file); // Ignoring result since we already have an error.
return Error("Error reading output of '" + command.get() + "'");
}
int status;
if ((status = _pclose(file)) == -1) {
return Error("Failed to get status of '" + command.get() + "'");
}
return stdoutstr.str();
}
// Executes a command by calling "cmd /c <command>", and returns
// after the command has been completed. Returns 0 if succeeds, and
// return -1 on error.
//
// The returned value from `_spawnlp` represents child exit code when
// `_P_WAIT` is used.
inline int system(const std::string& command)
{
return static_cast<int>(::_spawnlp(
_P_WAIT, Shell::name, Shell::arg0, Shell::arg1, command.c_str(), nullptr));
}
// Executes a command by calling "<command> <arguments...>", and
// returns after the command has been completed. Returns 0 if
// succeeds, and -1 on error.
inline int spawn(
const std::string& command,
const std::vector<std::string>& arguments)
{
return ::_spawnvp(_P_WAIT, command.c_str(), os::raw::Argv(arguments));
}
// On Windows, the `_spawnlp` call creates a new process.
// In order to emulate the semantics of `execlp`, we spawn with `_P_WAIT`,
// which forces the parent process to block on the child. When the child exits,
// the exit code is propagated back through the parent via `exit()`.
//
// The returned value from `_spawnlp` represents child exit code when
// `_P_WAIT` is used.
template<typename... T>
inline int execlp(const char* file, T... t)
{
exit(static_cast<int>(::_spawnlp(_P_WAIT, file, t...)));
return 0;
}
// On Windows, the `_spawnvp` call creates a new process.
// In order to emulate the semantics of `execvp`, we spawn with `_P_WAIT`,
// which forces the parent process to block on the child. When the child exits,
// the exit code is propagated back through the parent via `exit()`.
//
// The returned value from `_spawnlp` represents child exit code when
// `_P_WAIT` is used.
inline int execvp(const char* file, char* const argv[])
{
exit(static_cast<int>(::_spawnvp(_P_WAIT, file, argv)));
return 0;
}
// Concatenates multiple command-line arguments and escapes the values.
// If `arg` is not specified (or takes the value `0`), the function will
// scan `argv` until a `nullptr` is encountered.
inline std::string stringify_args(char** argv, unsigned long argc = 0)
{
std::string arg_line = "";
unsigned long index = 0;
while ((argc == 0 || index < argc) && argv[index] != nullptr) {
// TODO(dpravat): (MESOS-5522) Format these args for all cases.
// Specifically, we need to:
// (1) Add double quotes around arguments that contain special
// characters, like spaces and tabs.
// (2) Escape any existing double quotes and backslashes.
arg_line = strings::join(" ", arg_line, argv[index++]);
}
return arg_line;
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_SHELL_HPP__
<|endoftext|> |
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_WINDOWS_SHELL_HPP__
#define __STOUT_OS_WINDOWS_SHELL_HPP__
#include <process.h>
#include <processthreadsapi.h>
#include <shellapi.h>
#include <synchapi.h>
#include <stdarg.h> // For va_list, va_start, etc.
#include <algorithm>
#include <array>
#include <map>
#include <string>
#include <vector>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>
#include <stout/os/int_fd.hpp>
#include <stout/os/pipe.hpp>
#include <stout/os/windows/exec.hpp>
namespace os {
namespace Shell {
// Canonical constants used as platform-dependent args to `exec` calls.
// `name` is the command name, `arg0` is the first argument received
// by the callee, usually the command name and `arg1` is the second
// command argument received by the callee.
constexpr const char* name = "cmd.exe";
constexpr const char* arg0 = "cmd.exe";
constexpr const char* arg1 = "/c";
} // namespace Shell {
template <typename... T>
Try<std::string> shell(const std::string& fmt, const T&... t)
{
using std::array;
using std::string;
using std::vector;
const Try<string> command = strings::format(fmt, t...);
if (command.isError()) {
return Error(command.error());
}
// This function is intended to pass the arguments to the default
// shell, so we first add the arguments `cmd.exe cmd.exe /c`,
// followed by the command and arguments given.
vector<string> args = {os::Shell::name, os::Shell::arg0, os::Shell::arg1};
{ // Minimize the lifetime of the system allocated buffer.
//
// NOTE: This API returns a pointer to an array of `wchar_t*`,
// similar to `argv`. Each pointer to a null-terminated Unicode
// string represents an individual argument found on the command
// line. We use this because we cannot just split on whitespace.
int argc;
const std::unique_ptr<wchar_t*, decltype(&::LocalFree)> argv(
::CommandLineToArgvW(wide_stringify(command.get()).data(), &argc),
&::LocalFree);
if (argv == nullptr) {
return WindowsError();
}
for (int i = 0; i < argc; ++i) {
args.push_back(stringify(std::wstring(argv.get()[i])));
}
}
// This function is intended to return only the `stdout` of the
// command; but since we have to redirect all of `stdin`, `stdout`,
// `stderr` if we want to redirect any one of them, we redirect
// `stdin` and `stderr` to `NUL`, and `stdout` to a pipe.
Try<int_fd> stdin_ = os::open(os::DEV_NULL, O_RDONLY);
if (stdin_.isError()) {
return Error(stdin_.error());
}
Try<array<int_fd, 2>> stdout_ = os::pipe();
if (stdout_.isError()) {
return Error(stdout_.error());
}
Try<int_fd> stderr_ = os::open(os::DEV_NULL, O_WRONLY);
if (stderr_.isError()) {
return Error(stderr_.error());
}
// Ensure the file descriptors are closed when we leave this scope.
struct Closer
{
vector<int_fd> fds;
~Closer()
{
foreach (int_fd& fd, fds) {
os::close(fd);
}
}
} closer = {{stdin_.get(), stdout_.get()[0], stderr_.get()}};
array<int_fd, 3> pipes = {stdin_.get(), stdout_.get()[1], stderr_.get()};
using namespace os::windows::internal;
Try<ProcessData> process_data =
create_process(args.front(), args, None(), false, pipes);
if (process_data.isError()) {
return Error(process_data.error());
}
// Close the child end of the stdout pipe and then read until EOF.
os::close(stdout_.get()[1]);
string out;
Result<string> part = None();
do {
part = os::read(stdout_.get()[0], 1024);
if (part.isSome()) {
out += part.get();
}
} while (part.isSome());
// Wait for the process synchronously.
::WaitForSingleObject(process_data->process_handle.get_handle(), INFINITE);
DWORD status;
if (!::GetExitCodeProcess(
process_data->process_handle.get_handle(), &status)) {
return Error("Failed to `GetExitCodeProcess`: " + command.get());
}
if (status == 0) {
return out;
}
return Error(
"Failed to execute '" + command.get() +
"'; the command was either "
"not found or exited with a non-zero exit status: " +
stringify(status));
}
inline Option<int> system(const std::string& command)
{
return os::spawn(Shell::name, {Shell::arg0, Shell::arg1, command});
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_SHELL_HPP__
<commit_msg>Fixed a compilation issue on Windows with os::spawn.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __STOUT_OS_WINDOWS_SHELL_HPP__
#define __STOUT_OS_WINDOWS_SHELL_HPP__
#include <process.h>
#include <processthreadsapi.h>
#include <shellapi.h>
#include <synchapi.h>
#include <stdarg.h> // For va_list, va_start, etc.
#include <algorithm>
#include <array>
#include <map>
#include <string>
#include <vector>
#include <stout/error.hpp>
#include <stout/foreach.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/try.hpp>
#include <stout/windows.hpp>
#include <stout/os/int_fd.hpp>
#include <stout/os/pipe.hpp>
#include <stout/os/windows/exec.hpp>
namespace os {
namespace Shell {
// Canonical constants used as platform-dependent args to `exec` calls.
// `name` is the command name, `arg0` is the first argument received
// by the callee, usually the command name and `arg1` is the second
// command argument received by the callee.
constexpr const char* name = "cmd.exe";
constexpr const char* arg0 = "cmd.exe";
constexpr const char* arg1 = "/c";
} // namespace Shell {
template <typename... T>
Try<std::string> shell(const std::string& fmt, const T&... t)
{
using std::array;
using std::string;
using std::vector;
const Try<string> command = strings::format(fmt, t...);
if (command.isError()) {
return Error(command.error());
}
// This function is intended to pass the arguments to the default
// shell, so we first add the arguments `cmd.exe cmd.exe /c`,
// followed by the command and arguments given.
vector<string> args = {os::Shell::name, os::Shell::arg0, os::Shell::arg1};
{ // Minimize the lifetime of the system allocated buffer.
//
// NOTE: This API returns a pointer to an array of `wchar_t*`,
// similar to `argv`. Each pointer to a null-terminated Unicode
// string represents an individual argument found on the command
// line. We use this because we cannot just split on whitespace.
int argc;
const std::unique_ptr<wchar_t*, decltype(&::LocalFree)> argv(
::CommandLineToArgvW(wide_stringify(command.get()).data(), &argc),
&::LocalFree);
if (argv == nullptr) {
return WindowsError();
}
for (int i = 0; i < argc; ++i) {
args.push_back(stringify(std::wstring(argv.get()[i])));
}
}
// This function is intended to return only the `stdout` of the
// command; but since we have to redirect all of `stdin`, `stdout`,
// `stderr` if we want to redirect any one of them, we redirect
// `stdin` and `stderr` to `NUL`, and `stdout` to a pipe.
Try<int_fd> stdin_ = os::open(os::DEV_NULL, O_RDONLY);
if (stdin_.isError()) {
return Error(stdin_.error());
}
Try<array<int_fd, 2>> stdout_ = os::pipe();
if (stdout_.isError()) {
return Error(stdout_.error());
}
Try<int_fd> stderr_ = os::open(os::DEV_NULL, O_WRONLY);
if (stderr_.isError()) {
return Error(stderr_.error());
}
// Ensure the file descriptors are closed when we leave this scope.
struct Closer
{
vector<int_fd> fds;
~Closer()
{
foreach (int_fd& fd, fds) {
os::close(fd);
}
}
} closer = {{stdin_.get(), stdout_.get()[0], stderr_.get()}};
array<int_fd, 3> pipes = {stdin_.get(), stdout_.get()[1], stderr_.get()};
using namespace os::windows::internal;
Try<ProcessData> process_data =
create_process(args.front(), args, None(), false, pipes);
if (process_data.isError()) {
return Error(process_data.error());
}
// Close the child end of the stdout pipe and then read until EOF.
os::close(stdout_.get()[1]);
string out;
Result<string> part = None();
do {
part = os::read(stdout_.get()[0], 1024);
if (part.isSome()) {
out += part.get();
}
} while (part.isSome());
// Wait for the process synchronously.
::WaitForSingleObject(process_data->process_handle.get_handle(), INFINITE);
DWORD status;
if (!::GetExitCodeProcess(
process_data->process_handle.get_handle(), &status)) {
return Error("Failed to `GetExitCodeProcess`: " + command.get());
}
if (status == 0) {
return out;
}
return Error(
"Failed to execute '" + command.get() +
"'; the command was either "
"not found or exited with a non-zero exit status: " +
stringify(status));
}
inline Option<int> system(const std::string& command)
{
return os::spawn(Shell::name, {Shell::arg0, Shell::arg1, command}, None());
}
} // namespace os {
#endif // __STOUT_OS_WINDOWS_SHELL_HPP__
<|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 "otbImageToLuminanceImageFilter.h"
#include "otbLuminanceToReflectanceImageFilter.h"
#include "otbReflectanceToSurfaceReflectanceImageFilter.h"
#include "otbMultiplyByScalarImageFilter.h"
namespace otb
{
enum
{
Level_TOA,
Level_TOC
};
enum
{
Aerosol_NoAerosol,
Aerosol_Continental,
Aerosol_Maritime,
Aerosol_Urban,
Aerosol_Desertic,
};
namespace Wrapper
{
class OpticalCalibration : public Application
{
public:
/** Standard class typedefs. */
typedef OpticalCalibration Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(OpticalCalibration, Application);
typedef ImageToLuminanceImageFilter<UInt16VectorImageType,
DoubleVectorImageType> ImageToLuminanceImageFilterType;
typedef LuminanceToReflectanceImageFilter<DoubleVectorImageType,
DoubleVectorImageType> LuminanceToReflectanceImageFilterType;
typedef otb::MultiplyByScalarImageFilter<DoubleVectorImageType,
DoubleVectorImageType> ScaleFilterType;
typedef ReflectanceToSurfaceReflectanceImageFilter<DoubleVectorImageType,
DoubleVectorImageType> ReflectanceToSurfaceReflectanceImageFilterType;
typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType FilterFunctionValuesType;
typedef FilterFunctionValuesType::ValuesVectorType ValuesVectorType;
typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType;
typedef AtmosphericCorrectionParametersType::AerosolModelType AerosolModelType;
private:
OpticalCalibration()
{
SetName("OpticalCalibration");
SetDescription("Perform optical calibration TOA/TOC (Top Of Atmosphere/Top Of Canopy). Supported sensors: QuickBird, Ikonos, WorldView2, Formosat, Spot5");
// Documentation
SetDocName("Optical calibration application");
SetDocLongDescription("The application allows to convert pixel values from DN (for Digital Numbers) to physically interpretable and comparable values.Calibrated values are called surface reflectivity and its values lie in the range [0, 1].\nThe first level is called Top Of Atmosphere (TOA) reflectivity. It takes into account the sensor gain, sensor spectral response and the solar illumination.\nThe second level is called Top Of Canopy (TOC) reflectivity. In addition to sensor gain and solar illumination, it takes into account the optical thickness of the atmosphere, the atmospheric pressure, the water vapor amount, the ozone amount, as well as the composition and amount of aerosol gasses.\nIt is also possible to indicate an AERONET file which contains atmospheric parameters (version 1 and version 2 of Aeronet file are supported.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("The OTB CookBook");
AddDocTag(Tags::Calibration);
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input Image Filename");
AddParameter(ParameterType_OutputImage, "out", "Output Image Filename");
SetParameterDescription("out","Calibrated Image Filename");
AddParameter(ParameterType_RAM, "ram", "Available RAM");
SetDefaultParameterInt("ram", 256);
MandatoryOff("ram");
AddParameter(ParameterType_Choice, "level", "Calibration Level");
AddChoice("level.toa", "TOA : Top Of Atmosphere");
AddChoice("level.toc", "TOC : Top Of Canopy (EXPERIMENTAL)");
SetParameterString("level", "toa");
AddParameter(ParameterType_Empty, "milli", "Convert to milli reflectance");
SetParameterDescription("milli", "Output milli-reflectance instead of reflectance.\n"
"This allows to put save the image in integer pixel type (in the range [0, 1000] instead of floating point in the range [0, 1].");
DisableParameter("milli");
MandatoryOff("milli");
AddParameter(ParameterType_Filename, "rsr", "Relative Spectral Response File");
std::ostringstream oss;
oss << "Sensor relative spectral response file"<<std::endl;
oss << "By default the application gets these informations in the metadata";
SetParameterDescription("rsr", oss.str());
MandatoryOff("rsr");
AddParameter(ParameterType_Group,"atmo","Atmospheric parameters");
SetParameterDescription("atmo","This group allows to set the atmospheric parameters.");
AddParameter(ParameterType_Choice, "atmo.aerosol", "Aerosol Model");
AddChoice("atmo.aerosol.noaersol", "No Aerosol Model");
AddChoice("atmo.aerosol.continental", "Continental");
AddChoice("atmo.aerosol.maritime", "Maritime");
AddChoice("atmo.aerosol.urban", "Urban");
AddChoice("atmo.aerosol.desertic", "Desertic");
AddParameter(ParameterType_Float, "atmo.oz", "Ozone Amount");
AddParameter(ParameterType_Float, "atmo.wa", "Water Vapor Amount");
AddParameter(ParameterType_Float, "atmo.pressure", "Atmospheric Pressure");
AddParameter(ParameterType_Float, "atmo.opt", "Aerosol Optical Thickness");
SetDefaultParameterFloat("atmo.oz", 0.);
SetDefaultParameterFloat("atmo.wa", 2.5);
SetDefaultParameterFloat("atmo.pressure", 1030.);
SetDefaultParameterFloat("atmo.opt", 0.2);
MandatoryOff("atmo.oz");
MandatoryOff("atmo.wa");
MandatoryOff("atmo.pressure");
MandatoryOff("atmo.opt");
AddParameter(ParameterType_Filename, "atmo.aeronet", "Aeronet File");
SetParameterDescription("atmo.aeronet","Aeronet file containing atmospheric parameters");
MandatoryOff("atmo.aeronet");
// Doc example parameter settings
SetDocExampleParameterValue("in", "WV2_MUL_ROI_1000_100.tif");
SetDocExampleParameterValue("level", "toa");
SetDocExampleParameterValue("out", "OpticalCalibration.tif");
}
void DoUpdateParameters()
{
// Nothing to update
}
void DoExecute()
{
UInt16VectorImageType::Pointer inImage = GetParameterUInt16VectorImage("in");
//Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance
itk::MetaDataDictionary dict = inImage->GetMetaDataDictionary();
OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict);
// Test if needed data are available : an exception will be thrown
// if one the following Get* return failure. the exception is then
// caught in the Wrapper::Application class which redirect it to
// the logger
// ImageToLuminance
lImageMetadataInterface->GetPhysicalGain();
lImageMetadataInterface->GetPhysicalBias();
// LuminanceToReflectance
lImageMetadataInterface->GetDay();
lImageMetadataInterface->GetMonth();
lImageMetadataInterface->GetSolarIrradiance();
lImageMetadataInterface->GetSunElevation();
m_ImageToLuminanceFilter = ImageToLuminanceImageFilterType::New();
m_LuminanceToReflectanceFilter = LuminanceToReflectanceImageFilterType::New();
m_ReflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New();
m_ImageToLuminanceFilter->SetInput(inImage);
m_LuminanceToReflectanceFilter->SetInput(m_ImageToLuminanceFilter->GetOutput());
m_ReflectanceToSurfaceReflectanceFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());
m_ScaleFilter = ScaleFilterType::New();
m_ScaleFilter->InPlaceOn();
switch ( GetParameterInt("level") )
{
case Level_TOA:
{
m_LuminanceToReflectanceFilter->UpdateOutputInformation();
m_ScaleFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());
}
break;
case Level_TOC:
{
m_AtmosphericParam = m_ReflectanceToSurfaceReflectanceFilter->GetCorrectionParameters();
//AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL;
switch ( GetParameterInt("atmo.aerosol") )
{
case Aerosol_Desertic:
{
// Aerosol_Desertic correspond to 4 in the enum but actually in
// the class atmosphericParam it is known as parameter 5
m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(5));
}
break;
default:
{
m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(GetParameterInt("atmo.aerosol")));
}
break;
}
// Set the atmospheric param
m_AtmosphericParam->SetOzoneAmount(GetParameterFloat("atmo.oz"));
m_AtmosphericParam->SetWaterVaporAmount(GetParameterFloat("atmo.wa"));
m_AtmosphericParam->SetAtmosphericPressure(GetParameterFloat("atmo.pressure"));
m_AtmosphericParam->SetAerosolOptical(GetParameterFloat("atmo.opt"));
// Relative Spectral Response File
if (IsParameterEnabled("rsr"))
{
m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(GetParameterString("rsr"));
}
else
{
m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionCoef(lImageMetadataInterface->GetSpectralSensitivity());
}
// Aeronet file
if (IsParameterEnabled("atmo.aeronet"))
{
m_ReflectanceToSurfaceReflectanceFilter->SetAeronetFileName(GetParameterString("atmo.aeronet"));
}
//
AtmosphericRadiativeTerms::Pointer radTerms = AtmosphericRadiativeTerms::New();
radTerms->ValuesInitialization(inImage->GetNumberOfComponentsPerPixel());
m_ReflectanceToSurfaceReflectanceFilter->SetAtmosphericRadiativeTerms(radTerms);
m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(true);
m_ReflectanceToSurfaceReflectanceFilter->GenerateAtmosphericRadiativeTerms();
m_ReflectanceToSurfaceReflectanceFilter->GenerateParameters();
m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);
//rescale the surface reflectance in milli-reflectance
m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();
m_ScaleFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());
}
break;
}
// Output Image
const double scale = IsParameterEnabled("milli") ? 1000.0 : 1.0;
m_ScaleFilter->SetCoef(scale);
SetParameterOutputImage("out", m_ScaleFilter->GetOutput());
}
ImageToLuminanceImageFilterType ::Pointer m_ImageToLuminanceFilter;
LuminanceToReflectanceImageFilterType::Pointer m_LuminanceToReflectanceFilter;
ReflectanceToSurfaceReflectanceImageFilterType::Pointer m_ReflectanceToSurfaceReflectanceFilter;
ScaleFilterType::Pointer m_ScaleFilter;
AtmosphericCorrectionParametersType::Pointer m_AtmosphericParam;
};
}// namespace Wrapper
} // namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::OpticalCalibration)
<commit_msg>STY:remove end of lines<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 "otbImageToLuminanceImageFilter.h"
#include "otbLuminanceToReflectanceImageFilter.h"
#include "otbReflectanceToSurfaceReflectanceImageFilter.h"
#include "otbMultiplyByScalarImageFilter.h"
namespace otb
{
enum
{
Level_TOA,
Level_TOC
};
enum
{
Aerosol_NoAerosol,
Aerosol_Continental,
Aerosol_Maritime,
Aerosol_Urban,
Aerosol_Desertic,
};
namespace Wrapper
{
class OpticalCalibration : public Application
{
public:
/** Standard class typedefs. */
typedef OpticalCalibration Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(OpticalCalibration, Application);
typedef ImageToLuminanceImageFilter<UInt16VectorImageType,
DoubleVectorImageType> ImageToLuminanceImageFilterType;
typedef LuminanceToReflectanceImageFilter<DoubleVectorImageType,
DoubleVectorImageType> LuminanceToReflectanceImageFilterType;
typedef otb::MultiplyByScalarImageFilter<DoubleVectorImageType,
DoubleVectorImageType> ScaleFilterType;
typedef ReflectanceToSurfaceReflectanceImageFilter<DoubleVectorImageType,
DoubleVectorImageType> ReflectanceToSurfaceReflectanceImageFilterType;
typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType FilterFunctionValuesType;
typedef FilterFunctionValuesType::ValuesVectorType ValuesVectorType;
typedef AtmosphericCorrectionParameters AtmosphericCorrectionParametersType;
typedef AtmosphericCorrectionParametersType::AerosolModelType AerosolModelType;
private:
OpticalCalibration()
{
SetName("OpticalCalibration");
SetDescription("Perform optical calibration TOA/TOC (Top Of Atmosphere/Top Of Canopy). Supported sensors: QuickBird, Ikonos, WorldView2, Formosat, Spot5");
// Documentation
SetDocName("Optical calibration application");
SetDocLongDescription("The application allows to convert pixel values from DN (for Digital Numbers) to physically interpretable and comparable values.Calibrated values are called surface reflectivity and its values lie in the range [0, 1].\nThe first level is called Top Of Atmosphere (TOA) reflectivity. It takes into account the sensor gain, sensor spectral response and the solar illumination.\nThe second level is called Top Of Canopy (TOC) reflectivity. In addition to sensor gain and solar illumination, it takes into account the optical thickness of the atmosphere, the atmospheric pressure, the water vapor amount, the ozone amount, as well as the composition and amount of aerosol gasses.\nIt is also possible to indicate an AERONET file which contains atmospheric parameters (version 1 and version 2 of Aeronet file are supported.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("The OTB CookBook");
AddDocTag(Tags::Calibration);
}
void DoCreateParameters()
{
AddParameter(ParameterType_InputImage, "in", "Input Image Filename");
AddParameter(ParameterType_OutputImage, "out", "Output Image Filename");
SetParameterDescription("out","Calibrated Image Filename");
AddParameter(ParameterType_RAM, "ram", "Available RAM");
SetDefaultParameterInt("ram", 256);
MandatoryOff("ram");
AddParameter(ParameterType_Choice, "level", "Calibration Level");
AddChoice("level.toa", "TOA : Top Of Atmosphere");
AddChoice("level.toc", "TOC : Top Of Canopy (EXPERIMENTAL)");
SetParameterString("level", "toa");
AddParameter(ParameterType_Empty, "milli", "Convert to milli reflectance");
SetParameterDescription("milli", "Output milli-reflectance instead of reflectance.\n"
"This allows to put save the image in integer pixel type (in the range [0, 1000] instead of floating point in the range [0, 1].");
DisableParameter("milli");
MandatoryOff("milli");
AddParameter(ParameterType_Filename, "rsr", "Relative Spectral Response File");
std::ostringstream oss;
oss << "Sensor relative spectral response file"<<std::endl;
oss << "By default the application gets these informations in the metadata";
SetParameterDescription("rsr", oss.str());
MandatoryOff("rsr");
AddParameter(ParameterType_Group,"atmo","Atmospheric parameters");
SetParameterDescription("atmo","This group allows to set the atmospheric parameters.");
AddParameter(ParameterType_Choice, "atmo.aerosol", "Aerosol Model");
AddChoice("atmo.aerosol.noaersol", "No Aerosol Model");
AddChoice("atmo.aerosol.continental", "Continental");
AddChoice("atmo.aerosol.maritime", "Maritime");
AddChoice("atmo.aerosol.urban", "Urban");
AddChoice("atmo.aerosol.desertic", "Desertic");
AddParameter(ParameterType_Float, "atmo.oz", "Ozone Amount");
AddParameter(ParameterType_Float, "atmo.wa", "Water Vapor Amount");
AddParameter(ParameterType_Float, "atmo.pressure", "Atmospheric Pressure");
AddParameter(ParameterType_Float, "atmo.opt", "Aerosol Optical Thickness");
SetDefaultParameterFloat("atmo.oz", 0.);
SetDefaultParameterFloat("atmo.wa", 2.5);
SetDefaultParameterFloat("atmo.pressure", 1030.);
SetDefaultParameterFloat("atmo.opt", 0.2);
MandatoryOff("atmo.oz");
MandatoryOff("atmo.wa");
MandatoryOff("atmo.pressure");
MandatoryOff("atmo.opt");
AddParameter(ParameterType_Filename, "atmo.aeronet", "Aeronet File");
SetParameterDescription("atmo.aeronet","Aeronet file containing atmospheric parameters");
MandatoryOff("atmo.aeronet");
// Doc example parameter settings
SetDocExampleParameterValue("in", "WV2_MUL_ROI_1000_100.tif");
SetDocExampleParameterValue("level", "toa");
SetDocExampleParameterValue("out", "OpticalCalibration.tif");
}
void DoUpdateParameters()
{
// Nothing to update
}
void DoExecute()
{
UInt16VectorImageType::Pointer inImage = GetParameterUInt16VectorImage("in");
//Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance
itk::MetaDataDictionary dict = inImage->GetMetaDataDictionary();
OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict);
// Test if needed data are available : an exception will be thrown
// if one the following Get* return failure. the exception is then
// caught in the Wrapper::Application class which redirect it to
// the logger
// ImageToLuminance
lImageMetadataInterface->GetPhysicalGain();
lImageMetadataInterface->GetPhysicalBias();
// LuminanceToReflectance
lImageMetadataInterface->GetDay();
lImageMetadataInterface->GetMonth();
lImageMetadataInterface->GetSolarIrradiance();
lImageMetadataInterface->GetSunElevation();
m_ImageToLuminanceFilter = ImageToLuminanceImageFilterType::New();
m_LuminanceToReflectanceFilter = LuminanceToReflectanceImageFilterType::New();
m_ReflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New();
m_ImageToLuminanceFilter->SetInput(inImage);
m_LuminanceToReflectanceFilter->SetInput(m_ImageToLuminanceFilter->GetOutput());
m_ReflectanceToSurfaceReflectanceFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());
m_ScaleFilter = ScaleFilterType::New();
m_ScaleFilter->InPlaceOn();
switch ( GetParameterInt("level") )
{
case Level_TOA:
{
m_LuminanceToReflectanceFilter->UpdateOutputInformation();
m_ScaleFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());
}
break;
case Level_TOC:
{
m_AtmosphericParam = m_ReflectanceToSurfaceReflectanceFilter->GetCorrectionParameters();
//AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL;
switch ( GetParameterInt("atmo.aerosol") )
{
case Aerosol_Desertic:
{
// Aerosol_Desertic correspond to 4 in the enum but actually in
// the class atmosphericParam it is known as parameter 5
m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(5));
}
break;
default:
{
m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(GetParameterInt("atmo.aerosol")));
}
break;
}
// Set the atmospheric param
m_AtmosphericParam->SetOzoneAmount(GetParameterFloat("atmo.oz"));
m_AtmosphericParam->SetWaterVaporAmount(GetParameterFloat("atmo.wa"));
m_AtmosphericParam->SetAtmosphericPressure(GetParameterFloat("atmo.pressure"));
m_AtmosphericParam->SetAerosolOptical(GetParameterFloat("atmo.opt"));
// Relative Spectral Response File
if (IsParameterEnabled("rsr"))
{
m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(GetParameterString("rsr"));
}
else
{
m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionCoef(lImageMetadataInterface->GetSpectralSensitivity());
}
// Aeronet file
if (IsParameterEnabled("atmo.aeronet"))
{
m_ReflectanceToSurfaceReflectanceFilter->SetAeronetFileName(GetParameterString("atmo.aeronet"));
}
//
AtmosphericRadiativeTerms::Pointer radTerms = AtmosphericRadiativeTerms::New();
radTerms->ValuesInitialization(inImage->GetNumberOfComponentsPerPixel());
m_ReflectanceToSurfaceReflectanceFilter->SetAtmosphericRadiativeTerms(radTerms);
m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(true);
m_ReflectanceToSurfaceReflectanceFilter->GenerateAtmosphericRadiativeTerms();
m_ReflectanceToSurfaceReflectanceFilter->GenerateParameters();
m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);
//rescale the surface reflectance in milli-reflectance
m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();
m_ScaleFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());
}
break;
}
// Output Image
const double scale = IsParameterEnabled("milli") ? 1000.0 : 1.0;
m_ScaleFilter->SetCoef(scale);
SetParameterOutputImage("out", m_ScaleFilter->GetOutput());
}
ImageToLuminanceImageFilterType ::Pointer m_ImageToLuminanceFilter;
LuminanceToReflectanceImageFilterType::Pointer m_LuminanceToReflectanceFilter;
ReflectanceToSurfaceReflectanceImageFilterType::Pointer m_ReflectanceToSurfaceReflectanceFilter;
ScaleFilterType::Pointer m_ScaleFilter;
AtmosphericCorrectionParametersType::Pointer m_AtmosphericParam;
};
}// namespace Wrapper
} // namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::OpticalCalibration)
<|endoftext|> |
<commit_before>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <v8.h>
#include <node.h>
#include <node_version.h>
#include <node_buffer.h>
#include <openssl/bn.h>
#include <openssl/buffer.h>
#include "common.h"
using namespace std;
using namespace v8;
using namespace node;
static const char* BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// input: Buffer, output: string
static Handle<Value>
base58_encode (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: a Buffer");
}
if (!Buffer::HasInstance(args[0])) {
return VException("One argument expected: a Buffer");
}
v8::Handle<v8::Object> buf = args[0]->ToObject();
unsigned char *buf_data = (unsigned char *) Buffer::Data(buf);
int buf_length = Buffer::Length(buf);
BN_CTX *ctx = BN_CTX_new();
BIGNUM *bn = BN_bin2bn(buf_data, buf_length, NULL);
BIGNUM *bn58 = BN_new();
BN_set_word(bn58, 58);
BIGNUM *bn0 = BN_new();
BN_set_word(bn0, 0);
BIGNUM *dv = BN_new();
BIGNUM *rem = BN_new();
// TODO: compute safe length
char *str = new char[100];
unsigned int c;
int i, j, j2;
i = 0;
while (BN_cmp(bn, bn0) > 0) {
if (!BN_div(dv, rem, bn, bn58, ctx)) {
delete[] str;
return VException("BN_div failed");
}
if (bn != dv) {
BN_free(bn);
bn = dv;
}
c = BN_get_word(rem);
str[i] = BASE58_ALPHABET[c];
i++;
}
// Leading zeros
for (j = 0; j < buf_length; j++) {
if (buf_data[j] != 0) {
break;
}
str[i] = BASE58_ALPHABET[0];
i++;
}
// Terminator
str[i] = 0;
// Reverse string
int numSwaps = (i / 2);
char tmp;
for (j = 0; j < numSwaps; j++) {
j2 = i - 1 - j;
tmp = str[j];
str[j] = str[j2];
str[j2] = tmp;
}
BN_free(bn);
BN_free(bn58);
BN_free(bn0);
BN_free(rem);
BN_CTX_free(ctx);
Local<String> ret = String::New(str);
delete [] str;
return scope.Close(ret);
}
// input: string, output: Buffer
static Handle<Value>
base58_decode (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: a String");
}
if (!args[0]->IsString()) {
return VException("One argument expected: a String");
}
BN_CTX *ctx = BN_CTX_new();
BIGNUM *bn58 = BN_new();
BN_set_word(bn58, 58);
BIGNUM *bn = BN_new();
BN_set_word(bn, 0);
BIGNUM *bnChar = BN_new();
String::Utf8Value str(args[0]->ToString());
char *psz = *str;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++) {
const char* p1 = strchr(BASE58_ALPHABET, *p);
if (p1 == NULL) {
while (isspace(*p))
p++;
if (*p != '\0')
return VException("Error");
break;
}
BN_set_word(bnChar, p1 - BASE58_ALPHABET);
if (!BN_mul(bn, bn, bn58, ctx))
return VException("BN_mul failed");
if (!BN_add(bn, bn, bnChar))
return VException("BN_add failed");
}
// Get bignum as little endian data
unsigned int tmpLen = BN_num_bytes(bn);
unsigned char *tmp = (unsigned char *)malloc(tmpLen);
BN_bn2bin(bn, tmp);
// Trim off sign byte if present
if (tmpLen >= 2 && tmp[tmpLen-1] == 0 && tmp[tmpLen-2] >= 0x80)
tmpLen--;
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == BASE58_ALPHABET[0]; p++)
nLeadingZeros++;
// Allocate buffer and zero it
Buffer *buf = Buffer::New(nLeadingZeros + tmpLen);
char* data = Buffer::Data(buf);
memset(data, 0, nLeadingZeros + tmpLen);
memcpy(data+nLeadingZeros, tmp, tmpLen);
BN_free(bn58);
BN_free(bn);
BN_free(bnChar);
BN_CTX_free(ctx);
free(tmp);
return scope.Close(buf->handle_);
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("base58_encode"), FunctionTemplate::New(base58_encode)->GetFunction());
target->Set(String::New("base58_decode"), FunctionTemplate::New(base58_decode)->GetFunction());
}
NODE_MODULE(base58, init)
<commit_msg>base58.cc: Fix many memory leaks<commit_after>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
#include <v8.h>
#include <node.h>
#include <node_version.h>
#include <node_buffer.h>
#include <openssl/bn.h>
#include <openssl/buffer.h>
#include "common.h"
using namespace std;
using namespace v8;
using namespace node;
static const char* BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// input: Buffer, output: string
static Handle<Value>
base58_encode (const Arguments& args)
{
HandleScope scope;
if (args.Length() != 1) {
return VException("One argument expected: a Buffer");
}
if (!Buffer::HasInstance(args[0])) {
return VException("One argument expected: a Buffer");
}
v8::Handle<v8::Object> buf = args[0]->ToObject();
unsigned char *buf_data = (unsigned char *) Buffer::Data(buf);
int buf_length = Buffer::Length(buf);
BN_CTX *ctx = BN_CTX_new();
BIGNUM *bn = BN_bin2bn(buf_data, buf_length, NULL);
BIGNUM *bn58 = BN_new();
BN_set_word(bn58, 58);
BIGNUM *bn0 = BN_new();
BN_set_word(bn0, 0);
BIGNUM *dv = BN_new();
BIGNUM *rem = BN_new();
// FIXME! compute safe length.
char *str = new char[100];
unsigned int c;
int i, j, j2;
i = 0;
while (BN_cmp(bn, bn0) > 0) {
if (!BN_div(dv, rem, bn, bn58, ctx)) {
BN_free(bn);
BN_free(bn58);
BN_free(bn0);
if (bn != dv)
BN_free(dv);
BN_free(rem);
BN_CTX_free(ctx);
delete [] str;
return VException("BN_div failed");
}
if (bn != dv) {
BN_free(bn);
bn = dv;
}
c = BN_get_word(rem);
str[i] = BASE58_ALPHABET[c];
i++;
}
// Leading zeros
for (j = 0; j < buf_length; j++) {
if (buf_data[j] != 0) {
break;
}
str[i] = BASE58_ALPHABET[0];
i++;
}
// Terminator
str[i] = 0;
// Reverse string
int numSwaps = (i / 2);
char tmp;
for (j = 0; j < numSwaps; j++) {
j2 = i - 1 - j;
tmp = str[j];
str[j] = str[j2];
str[j2] = tmp;
}
BN_free(bn);
BN_free(bn58);
BN_free(bn0);
BN_free(rem);
BN_CTX_free(ctx);
Local<String> ret = String::New(str);
delete [] str;
return scope.Close(ret);
}
// input: string, output: Buffer
static Handle<Value>
base58_decode (const Arguments& args)
{
HandleScope scope;
const char *errmsg = NULL;
int nLeadingZeros = 0;
Buffer *buf = NULL;
char* data = NULL;
unsigned int tmpLen = 0;
unsigned char *tmp = NULL;
if (args.Length() != 1) {
return VException("One argument expected: a String");
}
if (!args[0]->IsString()) {
return VException("One argument expected: a String");
}
BN_CTX *ctx = BN_CTX_new();
BIGNUM *bn58 = BN_new();
BN_set_word(bn58, 58);
BIGNUM *bn = BN_new();
BN_set_word(bn, 0);
BIGNUM *bnChar = BN_new();
String::Utf8Value str(args[0]->ToString());
char *psz = *str;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++) {
const char* p1 = strchr(BASE58_ALPHABET, *p);
if (p1 == NULL) {
while (isspace(*p))
p++;
if (*p != '\0') {
errmsg = "Error";
goto err_out;
}
break;
}
BN_set_word(bnChar, p1 - BASE58_ALPHABET);
if (!BN_mul(bn, bn, bn58, ctx)) {
errmsg = "BN_mul failed";
goto err_out;
}
if (!BN_add(bn, bn, bnChar)) {
errmsg = "BN_add failed";
goto err_out;
}
}
// Get bignum as little endian data
tmpLen = BN_num_bytes(bn);
tmp = (unsigned char *)malloc(tmpLen);
BN_bn2bin(bn, tmp);
// Trim off sign byte if present
if (tmpLen >= 2 && tmp[tmpLen-1] == 0 && tmp[tmpLen-2] >= 0x80)
tmpLen--;
// Restore leading zeros
for (const char* p = psz; *p == BASE58_ALPHABET[0]; p++)
nLeadingZeros++;
// Allocate buffer and zero it
buf = Buffer::New(nLeadingZeros + tmpLen);
data = Buffer::Data(buf);
memset(data, 0, nLeadingZeros + tmpLen);
memcpy(data+nLeadingZeros, tmp, tmpLen);
BN_free(bn58);
BN_free(bn);
BN_free(bnChar);
BN_CTX_free(ctx);
free(tmp);
return scope.Close(buf->handle_);
err_out:
BN_free(bn58);
BN_free(bn);
BN_free(bnChar);
BN_CTX_free(ctx);
return VException(errmsg);
}
extern "C" void
init (Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("base58_encode"), FunctionTemplate::New(base58_encode)->GetFunction());
target->Set(String::New("base58_decode"), FunctionTemplate::New(base58_decode)->GetFunction());
}
NODE_MODULE(base58, init)
<|endoftext|> |
<commit_before>/****************************************************************************
*
* NAME: smbPitchShift.cpp
* VERSION: 1.2
* HOME URL: http://blogs.zynaptiq.com/bernsee
* KNOWN BUGS: none
*
* SYNOPSIS: Routine for doing pitch shifting while maintaining
* duration using the Short Time Fourier Transform.
*
* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5
* (one octave down) and 2. (one octave up). A value of exactly 1 does not change
* the pitch. numSampsToProcess tells the routine how many samples in indata[0...
* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...
* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the
* data in-place). fftFrameSize defines the FFT frame size used for the
* processing. Typical values are 1024, 2048 and 4096. It may be any value <=
* MAX_FRAME_LENGTH but it MUST be a power of 2. oversamp is the STFT
* oversampling factor which also determines the overlap between adjacent STFT
* frames. It should at least be 4 for moderate scaling ratios. A value of 32 is
* recommended for best quality. sampleRate takes the sample rate for the signal
* in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in
* indata[] should be in the range [-1.0, 1.0), which is also the output range
* for the data, make sure you scale the data accordingly (for 16bit signed integers
* you would have to divide (and multiply) by 32768).
*
* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
*
* The Wide Open License (WOL)
*
* Permission to use, copy, modify, distribute and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice and this license appear in all source copies.
* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF
* ANY KIND. See http://www.dspguru.com/wol.htm for more information.
*
*****************************************************************************/
#ifndef SMBPITCHSHIFT_HPP
#define SMBPITCHSHIFT_HPP
#include <algorithm>
#include <cmath>
#include <complex>
#include <cstring>
namespace smb
{
static const float PI = 3.14159265358979323846F;
static const unsigned long MAX_FRAME_LENGTH = 8192;
static void fft(std::complex<float>* fftBuffer, unsigned long fftFrameSize, long sign)
{
for (unsigned long i = 1; i < fftFrameSize - 1; i++)
{
unsigned long j = 0;
for (unsigned long bitm = 1; bitm < fftFrameSize; bitm <<= 1)
{
if (i & bitm) j++;
j <<= 1;
}
j >>= 1;
if (i < j)
std::swap(fftBuffer[i], fftBuffer[j]);
}
unsigned long step = 2;
for (unsigned long i = 1; i < fftFrameSize; i <<= 1, step <<= 1)
{
unsigned long step2 = step >> 1;
float arg = PI / step2;
std::complex<float> w{std::cos(arg), std::sin(arg) * sign};
std::complex<float> u{1.0, 0.0};
for (unsigned long j = 0; j < step2; j++)
{
for (unsigned long k = j; k < fftFrameSize; k += step)
{
// don't use operator* because it is slow
// temp = fftBuffer[k + step2] * u
std::complex<float> temp;
temp.real(fftBuffer[k + step2].real() * u.real() - fftBuffer[k + step2].imag() * u.imag());
temp.imag(fftBuffer[k + step2].real() * u.imag() + fftBuffer[k + step2].imag() * u.real());
fftBuffer[k + step2] = fftBuffer[k] - temp;
fftBuffer[k] += temp;
}
// don't use operator*= because it is slow
// u *= w;
float tempReal = u.real();
u.real(tempReal * w.real() - u.imag() * w.imag());
u.imag(tempReal * w.imag() + u.imag() * w.real());
}
}
}
class PitchShift
{
public:
PitchShift()
{
std::fill(std::begin(inFIFO), std::end(inFIFO), 0.0F);
std::fill(std::begin(outFIFO), std::end(outFIFO), 0.0F);
std::fill(std::begin(fftWorksp), std::end(fftWorksp), std::complex<float>{0.0F, 0.0F});
std::fill(std::begin(lastPhase), std::end(lastPhase), 0.0F);
std::fill(std::begin(sumPhase), std::end(sumPhase), 0.0F);
std::fill(std::begin(outputAccum), std::end(outputAccum), 0.0F);
std::fill(std::begin(anaFreq), std::end(anaFreq), 0.0F);
std::fill(std::begin(anaMagn), std::end(anaMagn), 0.0F);
}
/*
Routine process(). See top of file for explanation
Purpose: doing pitch shifting while maintaining duration using the Short
Time Fourier Transform.
Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
*/
void process(float pitchShift, unsigned long numSampsToProcess, unsigned long fftFrameSize,
unsigned long oversamp, float sampleRate, float* indata, float* outdata)
{
// set up some handy variables
unsigned long fftFrameSize2 = fftFrameSize / 2;
unsigned long stepSize = fftFrameSize / oversamp;
float freqPerBin = sampleRate / static_cast<float>(fftFrameSize);
float expct = 2.0F * PI * static_cast<float>(stepSize) / static_cast<float>(fftFrameSize);
unsigned long inFifoLatency = fftFrameSize - stepSize;
if (rover == 0) rover = inFifoLatency;
// main processing loop
for (unsigned long i = 0; i < numSampsToProcess; i++)
{
// As long as we have not yet collected enough data just read in
inFIFO[rover] = indata[i];
outdata[i] = outFIFO[rover - inFifoLatency];
rover++;
// now we have enough data for processing
if (rover >= fftFrameSize)
{
rover = inFifoLatency;
// do windowing and re,im interleave
for (unsigned long k = 0; k < fftFrameSize; k++)
{
float window = -0.5F * std::cos(2.0F * PI * static_cast<float>(k) / static_cast<float>(fftFrameSize)) + 0.5F;
fftWorksp[k].real(inFIFO[k] * window);
fftWorksp[k].imag(0.0F);
}
// ***************** ANALYSIS *******************
// do transform
fft(fftWorksp, fftFrameSize, -1);
// this is the analysis step
for (unsigned long k = 0; k <= fftFrameSize2; k++)
{
// de-interlace FFT buffer
float real = fftWorksp[k].real();
float imag = fftWorksp[k].imag();
// compute magnitude and phase
float magn = 2.0F * sqrtf(real * real + imag * imag);
float phase;
float signx = (imag > 0.0F) ? 1.0F : -1.0F;
if (imag == 0.0F) phase = 0.0F;
else if (real == 0.0F) phase = signx * PI / 2.0F;
else phase = std::atan2(imag, real);
// compute phase difference
float tmp = phase - lastPhase[k];
lastPhase[k] = phase;
// subtract expected phase difference
tmp -= static_cast<float>(k) * expct;
// map delta phase into +/- Pi interval
long qpd = static_cast<long>(tmp / PI);
if (qpd >= 0) qpd += qpd & 1;
else qpd -= qpd & 1;
tmp -= PI * static_cast<float>(qpd);
// get deviation from bin frequency from the +/- Pi interval
tmp = oversamp * tmp / (2.0F * PI);
// compute the k-th partials' true frequency
tmp = static_cast<float>(k) * freqPerBin + tmp * freqPerBin;
// store magnitude and true frequency in analysis arrays
anaMagn[k] = magn;
anaFreq[k] = tmp;
}
// ***************** PROCESSING *******************
// this does the actual pitch shifting
std::fill(std::begin(synMagn), std::begin(synMagn) + fftFrameSize, 0.0F);
std::fill(std::begin(synFreq), std::begin(synFreq) + fftFrameSize, 0.0F);
for (unsigned long k = 0; k <= fftFrameSize2; k++)
{
unsigned long index = static_cast<unsigned long>(k * pitchShift);
if (index <= fftFrameSize2)
{
synMagn[index] += anaMagn[k];
synFreq[index] = anaFreq[k] * pitchShift;
}
}
// ***************** SYNTHESIS *******************
// this is the synthesis step
for (unsigned long k = 0; k <= fftFrameSize2; k++)
{
// get magnitude and true frequency from synthesis arrays
float magn = synMagn[k];
float tmp = synFreq[k];
// subtract bin mid frequency
tmp -= static_cast<float>(k) * freqPerBin;
// get bin deviation from freq deviation
tmp /= freqPerBin;
// take oversampling factor into account
tmp = 2.0F * PI * tmp / oversamp;
// add the overlap phase advance back in
tmp += static_cast<float>(k) * expct;
// accumulate delta phase to get bin phase
sumPhase[k] += tmp;
float phase = sumPhase[k];
// get real and imag part and re-interleave
fftWorksp[k].real(magn * std::cos(phase));
fftWorksp[k].imag(magn * std::sin(phase));
}
// zero negative frequencies
for (unsigned long k = fftFrameSize + 1; k < fftFrameSize; k++) fftWorksp[k] = {0.0F, 0.0F};
// do inverse transform
fft(fftWorksp, fftFrameSize, 1);
// do windowing and add to output accumulator
for (unsigned long k = 0; k < fftFrameSize; k++)
{
float window = -0.5F * cos(2.0F * PI * static_cast<float>(k) / static_cast<float>(fftFrameSize)) + 0.5F;
outputAccum[k] += 2.0F * window * fftWorksp[k].real() / (fftFrameSize2 * oversamp);
}
unsigned long k;
for (k = 0 ; k < stepSize; k++) outFIFO[k] = outputAccum[k];
// shift accumulator
unsigned long j;
for (j = 0; k < fftFrameSize; k++, j++) outputAccum[j] = outputAccum[k];
for (; j < fftFrameSize; j++) outputAccum[j] = 0.0;
// move input FIFO
for (k = 0; k < inFifoLatency; k++) inFIFO[k] = inFIFO[k + stepSize];
}
}
}
private:
float inFIFO[MAX_FRAME_LENGTH];
float outFIFO[MAX_FRAME_LENGTH];
std::complex<float> fftWorksp[MAX_FRAME_LENGTH];
float lastPhase[MAX_FRAME_LENGTH / 2 + 1];
float sumPhase[MAX_FRAME_LENGTH / 2 + 1];
float outputAccum[2 * MAX_FRAME_LENGTH];
float anaFreq[MAX_FRAME_LENGTH];
float anaMagn[MAX_FRAME_LENGTH];
float synFreq[MAX_FRAME_LENGTH];
float synMagn[MAX_FRAME_LENGTH];
unsigned long rover = 0;
};
}
#endif
<commit_msg>Use own implementation of complex<commit_after>/****************************************************************************
*
* NAME: smbPitchShift.cpp
* VERSION: 1.2
* HOME URL: http://blogs.zynaptiq.com/bernsee
* KNOWN BUGS: none
*
* SYNOPSIS: Routine for doing pitch shifting while maintaining
* duration using the Short Time Fourier Transform.
*
* DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5
* (one octave down) and 2. (one octave up). A value of exactly 1 does not change
* the pitch. numSampsToProcess tells the routine how many samples in indata[0...
* numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ...
* numSampsToProcess-1]. The two buffers can be identical (ie. it can process the
* data in-place). fftFrameSize defines the FFT frame size used for the
* processing. Typical values are 1024, 2048 and 4096. It may be any value <=
* MAX_FRAME_LENGTH but it MUST be a power of 2. oversamp is the STFT
* oversampling factor which also determines the overlap between adjacent STFT
* frames. It should at least be 4 for moderate scaling ratios. A value of 32 is
* recommended for best quality. sampleRate takes the sample rate for the signal
* in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in
* indata[] should be in the range [-1.0, 1.0), which is also the output range
* for the data, make sure you scale the data accordingly (for 16bit signed integers
* you would have to divide (and multiply) by 32768).
*
* COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
*
* The Wide Open License (WOL)
*
* Permission to use, copy, modify, distribute and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice and this license appear in all source copies.
* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF
* ANY KIND. See http://www.dspguru.com/wol.htm for more information.
*
*****************************************************************************/
#ifndef SMBPITCHSHIFT_HPP
#define SMBPITCHSHIFT_HPP
#include <algorithm>
#include <cmath>
#include <cstring>
namespace smb
{
static const float PI = 3.14159265358979323846F;
static const unsigned long MAX_FRAME_LENGTH = 8192;
// Use own implementation because std::complex has a poor performance
template<class T>
struct Complex
{
inline Complex<T> operator+(const Complex& other)
{
return Complex{real + other.real, imag + other.imag};
}
inline Complex<T>& operator+=(const Complex& other)
{
real += other.real;
imag += other.imag;
return *this;
}
inline Complex<T> operator-(const Complex& other)
{
return Complex{real - other.real, imag - other.imag};
}
inline Complex<T>& operator-=(const Complex& other)
{
real -= other.real;
imag -= other.imag;
return *this;
}
inline Complex<T> operator*(const Complex& other)
{
return Complex{real * other.real - imag * other.imag, real * other.imag + imag * other.real};
}
inline Complex<T>& operator*=(const Complex& other)
{
float tempReal = real;
real = tempReal * other.real - imag * other.imag;
imag = tempReal * other.imag + imag * other.real;
return *this;
}
T real;
T imag;
};
static void fft(Complex<float>* fftBuffer, unsigned long fftFrameSize, long sign)
{
for (unsigned long i = 1; i < fftFrameSize - 1; i++)
{
unsigned long j = 0;
for (unsigned long bitm = 1; bitm < fftFrameSize; bitm <<= 1)
{
if (i & bitm) j++;
j <<= 1;
}
j >>= 1;
if (i < j)
std::swap(fftBuffer[i], fftBuffer[j]);
}
unsigned long step = 2;
for (unsigned long i = 1; i < fftFrameSize; i <<= 1, step <<= 1)
{
unsigned long step2 = step >> 1;
float arg = PI / step2;
Complex<float> w{std::cos(arg), std::sin(arg) * sign};
Complex<float> u{1.0, 0.0};
for (unsigned long j = 0; j < step2; j++)
{
for (unsigned long k = j; k < fftFrameSize; k += step)
{
Complex<float> temp = fftBuffer[k + step2] * u;
fftBuffer[k + step2] = fftBuffer[k] - temp;
fftBuffer[k] += temp;
}
u *= w;
}
}
}
class PitchShift
{
public:
PitchShift()
{
std::fill(std::begin(inFIFO), std::end(inFIFO), 0.0F);
std::fill(std::begin(outFIFO), std::end(outFIFO), 0.0F);
std::fill(std::begin(fftWorksp), std::end(fftWorksp), Complex<float>{0.0F, 0.0F});
std::fill(std::begin(lastPhase), std::end(lastPhase), 0.0F);
std::fill(std::begin(sumPhase), std::end(sumPhase), 0.0F);
std::fill(std::begin(outputAccum), std::end(outputAccum), 0.0F);
std::fill(std::begin(anaFreq), std::end(anaFreq), 0.0F);
std::fill(std::begin(anaMagn), std::end(anaMagn), 0.0F);
}
/*
Routine process(). See top of file for explanation
Purpose: doing pitch shifting while maintaining duration using the Short
Time Fourier Transform.
Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com>
*/
void process(float pitchShift, unsigned long numSampsToProcess, unsigned long fftFrameSize,
unsigned long oversamp, float sampleRate, float* indata, float* outdata)
{
// set up some handy variables
unsigned long fftFrameSize2 = fftFrameSize / 2;
unsigned long stepSize = fftFrameSize / oversamp;
float freqPerBin = sampleRate / static_cast<float>(fftFrameSize);
float expct = 2.0F * PI * static_cast<float>(stepSize) / static_cast<float>(fftFrameSize);
unsigned long inFifoLatency = fftFrameSize - stepSize;
if (rover == 0) rover = inFifoLatency;
// main processing loop
for (unsigned long i = 0; i < numSampsToProcess; i++)
{
// As long as we have not yet collected enough data just read in
inFIFO[rover] = indata[i];
outdata[i] = outFIFO[rover - inFifoLatency];
rover++;
// now we have enough data for processing
if (rover >= fftFrameSize)
{
rover = inFifoLatency;
// do windowing and re,im interleave
for (unsigned long k = 0; k < fftFrameSize; k++)
{
float window = -0.5F * std::cos(2.0F * PI * static_cast<float>(k) / static_cast<float>(fftFrameSize)) + 0.5F;
fftWorksp[k].real = inFIFO[k] * window;
fftWorksp[k].imag = 0.0F;
}
// ***************** ANALYSIS *******************
// do transform
fft(fftWorksp, fftFrameSize, -1);
// this is the analysis step
for (unsigned long k = 0; k <= fftFrameSize2; k++)
{
// de-interlace FFT buffer
float real = fftWorksp[k].real;
float imag = fftWorksp[k].imag;
// compute magnitude and phase
float magn = 2.0F * sqrtf(real * real + imag * imag);
float phase;
float signx = (imag > 0.0F) ? 1.0F : -1.0F;
if (imag == 0.0F) phase = 0.0F;
else if (real == 0.0F) phase = signx * PI / 2.0F;
else phase = std::atan2(imag, real);
// compute phase difference
float tmp = phase - lastPhase[k];
lastPhase[k] = phase;
// subtract expected phase difference
tmp -= static_cast<float>(k) * expct;
// map delta phase into +/- Pi interval
long qpd = static_cast<long>(tmp / PI);
if (qpd >= 0) qpd += qpd & 1;
else qpd -= qpd & 1;
tmp -= PI * static_cast<float>(qpd);
// get deviation from bin frequency from the +/- Pi interval
tmp = oversamp * tmp / (2.0F * PI);
// compute the k-th partials' true frequency
tmp = static_cast<float>(k) * freqPerBin + tmp * freqPerBin;
// store magnitude and true frequency in analysis arrays
anaMagn[k] = magn;
anaFreq[k] = tmp;
}
// ***************** PROCESSING *******************
// this does the actual pitch shifting
std::fill(std::begin(synMagn), std::begin(synMagn) + fftFrameSize, 0.0F);
std::fill(std::begin(synFreq), std::begin(synFreq) + fftFrameSize, 0.0F);
for (unsigned long k = 0; k <= fftFrameSize2; k++)
{
unsigned long index = static_cast<unsigned long>(k * pitchShift);
if (index <= fftFrameSize2)
{
synMagn[index] += anaMagn[k];
synFreq[index] = anaFreq[k] * pitchShift;
}
}
// ***************** SYNTHESIS *******************
// this is the synthesis step
for (unsigned long k = 0; k <= fftFrameSize2; k++)
{
// get magnitude and true frequency from synthesis arrays
float magn = synMagn[k];
float tmp = synFreq[k];
// subtract bin mid frequency
tmp -= static_cast<float>(k) * freqPerBin;
// get bin deviation from freq deviation
tmp /= freqPerBin;
// take oversampling factor into account
tmp = 2.0F * PI * tmp / oversamp;
// add the overlap phase advance back in
tmp += static_cast<float>(k) * expct;
// accumulate delta phase to get bin phase
sumPhase[k] += tmp;
float phase = sumPhase[k];
// get real and imag part and re-interleave
fftWorksp[k].real = magn * std::cos(phase);
fftWorksp[k].imag = magn * std::sin(phase);
}
// zero negative frequencies
for (unsigned long k = fftFrameSize + 1; k < fftFrameSize; k++) fftWorksp[k] = {0.0F, 0.0F};
// do inverse transform
fft(fftWorksp, fftFrameSize, 1);
// do windowing and add to output accumulator
for (unsigned long k = 0; k < fftFrameSize; k++)
{
float window = -0.5F * cos(2.0F * PI * static_cast<float>(k) / static_cast<float>(fftFrameSize)) + 0.5F;
outputAccum[k] += 2.0F * window * fftWorksp[k].real / (fftFrameSize2 * oversamp);
}
unsigned long k;
for (k = 0 ; k < stepSize; k++) outFIFO[k] = outputAccum[k];
// shift accumulator
unsigned long j;
for (j = 0; k < fftFrameSize; k++, j++) outputAccum[j] = outputAccum[k];
for (; j < fftFrameSize; j++) outputAccum[j] = 0.0;
// move input FIFO
for (k = 0; k < inFifoLatency; k++) inFIFO[k] = inFIFO[k + stepSize];
}
}
}
private:
float inFIFO[MAX_FRAME_LENGTH];
float outFIFO[MAX_FRAME_LENGTH];
Complex<float> fftWorksp[MAX_FRAME_LENGTH];
float lastPhase[MAX_FRAME_LENGTH / 2 + 1];
float sumPhase[MAX_FRAME_LENGTH / 2 + 1];
float outputAccum[2 * MAX_FRAME_LENGTH];
float anaFreq[MAX_FRAME_LENGTH];
float anaMagn[MAX_FRAME_LENGTH];
float synFreq[MAX_FRAME_LENGTH];
float synMagn[MAX_FRAME_LENGTH];
unsigned long rover = 0;
};
}
#endif
<|endoftext|> |
<commit_before>#include "document.h"
using namespace std;
namespace wano {
Document::Document(shared_ptr<EventQueue> eq) :
buffer(),
eq{ eq }
{
curs.x = 0;
curs.y = 0;
buffer.push_back(make_shared<vector<int>>(0));
}
coord Document::insCh(int ch) {
auto by = buffer[curs.y];
by->insert(by->begin() + curs.x, ch);
return this->cursRight();
}
coord Document::delCh() {
auto by = buffer[curs.y];
if (curs.x < by->size()) {
by->erase(by->begin() + curs.x);
}
return curs;
}
coord Document::newLine() {
// TODO:: Split current line if needed
buffer.insert(buffer.begin() + curs.y + 1, make_shared<vector<int>>(0));
return this->cursMove(0, curs.y + 1);
}
coord Document::cursMove(int x, int y) {
bool changedY = false;
// Don't bother doing operations on unchanged coordinates
if (y != curs.y) {
changedY = true;
if (y < 0) {
curs.y = 0;
}
else if (buffer.size() > y) {
curs.y = y;
}
else {
curs.y = buffer.size() - 1;
}
}
// If y changed, x may have to move
if (x != curs.x || changedY) {
auto by = buffer[curs.y];
if (x < 0) {
curs.x = 0;
}
else if (by->size() >= x) {
curs.x = x;
}
else {
curs.x = by->size();
}
}
this->eq->fire<coord>(DOC_MOVE, curs);
return curs;
}
coord Document::cursRight(int num) {
return this->cursMove(curs.x + num, curs.y);
}
coord Document::cursRight() {
return this->cursRight(1);
}
coord Document::cursLeft(int num) {
return this->cursMove(curs.x - num, curs.y);
}
coord Document::cursLeft() {
return this->cursLeft(1);
}
coord Document::cursDown(int num) {
return this->cursMove(curs.x, curs.y + num);
}
coord Document::cursDown() {
return this->cursDown(1);
}
coord Document::cursUp(int num) {
return this->cursMove(curs.x, curs.y - num);
}
coord Document::cursUp() {
return this->cursUp(1);
}
coord Document::cursEnd() {
auto by = buffer[curs.y];
return this->cursMove(by->size(), curs.y);
}
coord Document::cursHome() {
return this->cursMove(0, curs.y);
}
vector<int> Document::readLine(int line) {
// Copying may not be the way to go, but it is a pretty
// small vector
return vector<int>(*buffer[line]);
}
}<commit_msg>Fixed typo in variable type<commit_after>#include "document.h"
using namespace std;
namespace wano {
Document::Document(shared_ptr<EventQueue> eq) :
buffer(),
eq{ eq }
{
curs.x = 0;
curs.y = 0;
buffer.push_back(make_shared<vector<int>>(0));
}
coord Document::insCh(int ch) {
auto by = buffer[curs.y];
by->insert(by->begin() + curs.x, ch);
return this->cursRight();
}
coord Document::delCh() {
auto by = buffer[curs.y];
if (curs.x < by->size()) {
by->erase(by->begin() + curs.x);
}
return curs;
}
coord Document::newLine() {
// TODO:: Split current line if needed
buffer.insert(buffer.begin() + curs.y + 1, make_shared<vector<int>>(0));
return this->cursMove(0, curs.y + 1);
}
coord Document::cursMove(int x, int y) {
auto changedY = false;
// Don't bother doing operations on unchanged coordinates
if (y != curs.y) {
changedY = true;
if (y < 0) {
curs.y = 0;
}
else if (buffer.size() > y) {
curs.y = y;
}
else {
curs.y = buffer.size() - 1;
}
}
// If y changed, x may have to move
if (x != curs.x || changedY) {
auto by = buffer[curs.y];
if (x < 0) {
curs.x = 0;
}
else if (by->size() >= x) {
curs.x = x;
}
else {
curs.x = by->size();
}
}
this->eq->fire<coord>(DOC_MOVE, curs);
return curs;
}
coord Document::cursRight(int num) {
return this->cursMove(curs.x + num, curs.y);
}
coord Document::cursRight() {
return this->cursRight(1);
}
coord Document::cursLeft(int num) {
return this->cursMove(curs.x - num, curs.y);
}
coord Document::cursLeft() {
return this->cursLeft(1);
}
coord Document::cursDown(int num) {
return this->cursMove(curs.x, curs.y + num);
}
coord Document::cursDown() {
return this->cursDown(1);
}
coord Document::cursUp(int num) {
return this->cursMove(curs.x, curs.y - num);
}
coord Document::cursUp() {
return this->cursUp(1);
}
coord Document::cursEnd() {
auto by = buffer[curs.y];
return this->cursMove(by->size(), curs.y);
}
coord Document::cursHome() {
return this->cursMove(0, curs.y);
}
vector<int> Document::readLine(int line) {
// Copying may not be the way to go, but it is a pretty
// small vector
return vector<int>(*buffer[line]);
}
}
<|endoftext|> |
<commit_before>// game.m.cpp
#include "engine/build.g.h"
#include "engine/input/input.h"
#include "engine/rendering/renderer.h"
#include "engine/scene/scene.h"
#include "engine/scene/test_input_controller.h"
#include "engine/util/input_utils.h"
#include "engine/util/game_utils.h"
int main( int argc, char *argv[] )
{
using namespace std;
using namespace StevensDev;
using namespace StevensDev::sgdu;
int i;
// print out debug information
cout << "CS 585 Intro to Game Development" << endl;
cout << "Game" << endl;
cout << "Version: " << GAME_VERSION << endl;
cout << "Arguments: ";
for ( i = 1; i < argc; ++i )
{
cout << argv[i] << " ";
}
cout << endl;
// set up game
sgdi::Input& input = sgdi::Input::inst();
sgds::Scene& scene = sgds::Scene::inst();
sgdr::Renderer renderer;
assert( renderer.loadTexture( "block", "res/texture/block.png" ) );
sgdr::RenderableSprite sprite( renderer.getTexture( "block" ) );
renderer.addSprite( &sprite );
scene.addTickable( &input );
scene.setRenderer( &renderer );
renderer.setupWindow( 800, 600 );
while ( renderer.isActive() )
{
scene.tick();
}
cout << "Finished. Exiting..." << endl;
return 0;
}<commit_msg>Remove invalid import<commit_after>// game.m.cpp
#include "engine/build.g.h"
#include "engine/input/input.h"
#include "engine/rendering/renderer.h"
#include "engine/scene/scene.h"
#include "engine/util/input_utils.h"
#include "engine/util/game_utils.h"
int main( int argc, char *argv[] )
{
using namespace std;
using namespace StevensDev;
using namespace StevensDev::sgdu;
int i;
// print out debug information
cout << "CS 585 Intro to Game Development" << endl;
cout << "Game" << endl;
cout << "Version: " << GAME_VERSION << endl;
cout << "Arguments: ";
for ( i = 1; i < argc; ++i )
{
cout << argv[i] << " ";
}
cout << endl;
// set up game
sgdi::Input& input = sgdi::Input::inst();
sgds::Scene& scene = sgds::Scene::inst();
sgdr::Renderer renderer;
assert( renderer.loadTexture( "block", "res/texture/block.png" ) );
sgdr::RenderableSprite sprite( renderer.getTexture( "block" ) );
renderer.addSprite( &sprite );
scene.addTickable( &input );
scene.setRenderer( &renderer );
renderer.setupWindow( 800, 600 );
while ( renderer.isActive() )
{
scene.tick();
}
cout << "Finished. Exiting..." << endl;
return 0;
}<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file calc_array.cpp
\author
\date 02.05.2011
\brief -
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/calc/calc_array.h"
#include "simulator/runtime/rdo_array.h"
#include "simulator/runtime/rdo_res_type.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOCalcArraySize
// --------------------------------------------------------------------------------
RDOCalcArraySize::RDOCalcArraySize(CREF(LPRDOCalc) pCalc)
: m_pCalc(pCalc)
{}
RDOValue RDOCalcArraySize::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pCalc->calcValue(pRuntime);
CREF(LPRDOArrayValue) pArrayValue = value.getPointerSafety<RDOArrayType>();
ASSERT(pArrayValue);
return pArrayValue->size();
}
// --------------------------------------------------------------------------------
// -------------------- RDOCalcArrayItem
// --------------------------------------------------------------------------------
RDOCalcArrayItem::RDOCalcArrayItem(CREF(LPRDOCalc) pArray, CREF(LPRDOCalc) pArrayInd)
: m_pArray (pArray )
, m_pArrayInd(pArrayInd)
{
ASSERT(m_pArray );
ASSERT(m_pArrayInd);
setSrcInfo(m_pArrayInd->srcInfo());
}
RDOValue RDOCalcArrayItem::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pArray->calcValue(pRuntime);
CREF(LPRDOArrayValue) pArrayValue = value.getPointerSafety<RDOArrayType>();
ASSERT(pArrayValue);
return pArrayValue->getItem(m_pArrayInd->calcValue(pRuntime));
}
// --------------------------------------------------------------------------------
// -------------------- RDOCalcArrayItemParam
// --------------------------------------------------------------------------------
RDOCalcArrayItemParam::RDOCalcArrayItemParam(CREF(LPRDOCalc) pArray, CREF(LPRDOCalc) pArrayInd, CREF(LPRDOCalc) pParamInd)
: m_pArray (pArray )
, m_pArrayInd(pArrayInd)
, m_pParamInd(pParamInd)
{
ASSERT(m_pArray );
ASSERT(m_pArrayInd);
ASSERT(m_pParamInd);
setSrcInfo(m_pArrayInd->srcInfo());
}
RDOValue RDOCalcArrayItemParam::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pArray->calcValue(pRuntime);
RDOValue param_ind = m_pParamInd->calcValue(pRuntime);
CREF(LPRDOArrayValue) pArrayValue = value.getPointerSafety<RDOArrayType>();
ASSERT(pArrayValue);
RDOValue pArrayItem = pArrayValue->getItem(m_pArrayInd->calcValue(pRuntime));
LPRDOResource pResource = pArrayItem.getPointerSafety<RDOResourceType>();
ASSERT(pResource);
return pResource->getParam(param_ind.getInt());
}
// --------------------------------------------------------------------------------
// -------------------- RDOCalcSetArrayItem
// --------------------------------------------------------------------------------
RDOCalcSetArrayItem::RDOCalcSetArrayItem(CREF(LPRDOCalc) pArray, CREF(LPRDOCalc) pArrayInd, CREF(LPRDOCalc) pSetItem)
: m_pArray (pArray )
, m_pArrayInd(pArrayInd)
, m_pSetItem (pSetItem )
{
ASSERT(m_pArray );
ASSERT(m_pArrayInd);
ASSERT(m_pSetItem );
setSrcInfo(m_pArrayInd->srcInfo());
}
RDOValue RDOCalcSetArrayItem::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pArray->calcValue(pRuntime);
CREF(LPRDOArrayValue) pArrayValue = value.getPointerSafety<RDOArrayType>();
ASSERT(pArrayValue);
pArrayValue->setItem(m_pArrayInd->calcValue(pRuntime), m_pSetItem->calcValue(pRuntime));
return value;
}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - форматирование<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file calc_array.cpp
\author
\date 02.05.2011
\brief -
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/calc/calc_array.h"
#include "simulator/runtime/rdo_array.h"
#include "simulator/runtime/rdo_res_type.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOCalcArraySize
// --------------------------------------------------------------------------------
RDOCalcArraySize::RDOCalcArraySize(CREF(LPRDOCalc) pCalc)
: m_pCalc(pCalc)
{}
RDOValue RDOCalcArraySize::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pCalc->calcValue(pRuntime);
CREF(LPRDOArrayValue) pArrayValue = value.getPointerSafety<RDOArrayType>();
ASSERT(pArrayValue);
return pArrayValue->size();
}
// --------------------------------------------------------------------------------
// -------------------- RDOCalcArrayItem
// --------------------------------------------------------------------------------
RDOCalcArrayItem::RDOCalcArrayItem(CREF(LPRDOCalc) pArray, CREF(LPRDOCalc) pArrayInd)
: m_pArray (pArray )
, m_pArrayInd(pArrayInd)
{
ASSERT(m_pArray );
ASSERT(m_pArrayInd);
setSrcInfo(m_pArrayInd->srcInfo());
}
RDOValue RDOCalcArrayItem::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pArray->calcValue(pRuntime);
CREF(LPRDOArrayValue) pArrayValue = value.getPointerSafety<RDOArrayType>();
ASSERT(pArrayValue);
return pArrayValue->getItem(m_pArrayInd->calcValue(pRuntime));
}
// --------------------------------------------------------------------------------
// -------------------- RDOCalcArrayItemParam
// --------------------------------------------------------------------------------
RDOCalcArrayItemParam::RDOCalcArrayItemParam(CREF(LPRDOCalc) pArray, CREF(LPRDOCalc) pArrayInd, CREF(LPRDOCalc) pParamInd)
: m_pArray (pArray )
, m_pArrayInd(pArrayInd)
, m_pParamInd(pParamInd)
{
ASSERT(m_pArray );
ASSERT(m_pArrayInd);
ASSERT(m_pParamInd);
setSrcInfo(m_pArrayInd->srcInfo());
}
RDOValue RDOCalcArrayItemParam::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pArray->calcValue(pRuntime);
RDOValue param_ind = m_pParamInd->calcValue(pRuntime);
CREF(LPRDOArrayValue) pArrayValue = value.getPointerSafety<RDOArrayType>();
ASSERT(pArrayValue);
RDOValue pArrayItem = pArrayValue->getItem(m_pArrayInd->calcValue(pRuntime));
LPRDOResource pResource = pArrayItem.getPointerSafety<RDOResourceType>();
ASSERT(pResource);
return pResource->getParam(param_ind.getInt());
}
// --------------------------------------------------------------------------------
// -------------------- RDOCalcSetArrayItem
// --------------------------------------------------------------------------------
RDOCalcSetArrayItem::RDOCalcSetArrayItem(CREF(LPRDOCalc) pArray, CREF(LPRDOCalc) pArrayInd, CREF(LPRDOCalc) pSetItem)
: m_pArray (pArray )
, m_pArrayInd(pArrayInd)
, m_pSetItem (pSetItem )
{
ASSERT(m_pArray );
ASSERT(m_pArrayInd);
ASSERT(m_pSetItem );
setSrcInfo(m_pArrayInd->srcInfo());
}
RDOValue RDOCalcSetArrayItem::doCalc(CREF(LPRDORuntime) pRuntime)
{
RDOValue value = m_pArray->calcValue(pRuntime);
CREF(LPRDOArrayValue) pArrayValue = value.getPointerSafety<RDOArrayType>();
ASSERT(pArrayValue);
pArrayValue->setItem(m_pArrayInd->calcValue(pRuntime), m_pSetItem->calcValue(pRuntime));
return value;
}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|> |
<commit_before>/**
* \file
* \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-03-19
*/
#include "distortos/scheduler/getScheduler.hpp"
#include "distortos/scheduler/Scheduler.hpp"
#include "distortos/chip/CMSIS-proxy.h"
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Wrapper for void* distortos::scheduler::getScheduler().switchContext(void*)
*
* \param [in] stackPointer is the current value of current thread's stack pointer
*
* \return new thread's stack pointer
*/
extern "C" void* schedulerSwitchContextWrapper(void* const stackPointer)
{
return distortos::scheduler::getScheduler().switchContext(stackPointer);
}
/**
* \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* Performs the context switch.
*/
extern "C" __attribute__ ((naked)) void PendSV_Handler()
{
asm volatile
(
" mrs r0, PSP \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" stmdb r0!, {r4-r11, lr} \n" // save context of current thread
#else
" stmdb r0!, {r4-r11} \n" // save context of current thread
" mov r4, lr \n"
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
" \n"
" bl schedulerSwitchContextWrapper \n" // switch context
" \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" ldmia r0!, {r4-r11, lr} \n" // load context of new thread
#else
" mov lr, r4 \n"
" ldmia r0!, {r4-r11} \n" // load context of new thread
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
" msr PSP, r0 \n"
" \n"
" bx lr \n" // return to new thread
);
__builtin_unreachable();
}
<commit_msg>ARMv7-M, PendSV_Handler(): formatting change<commit_after>/**
* \file
* \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-03-19
*/
#include "distortos/scheduler/getScheduler.hpp"
#include "distortos/scheduler/Scheduler.hpp"
#include "distortos/chip/CMSIS-proxy.h"
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief Wrapper for void* distortos::scheduler::getScheduler().switchContext(void*)
*
* \param [in] stackPointer is the current value of current thread's stack pointer
*
* \return new thread's stack pointer
*/
extern "C" void* schedulerSwitchContextWrapper(void* const stackPointer)
{
return distortos::scheduler::getScheduler().switchContext(stackPointer);
}
/**
* \brief PendSV_Handler() for ARMv7-M (Cortex-M3 / Cortex-M4)
*
* Performs the context switch.
*/
extern "C" __attribute__ ((naked)) void PendSV_Handler()
{
asm volatile
(
" mrs r0, PSP \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" stmdb r0!, {r4-r11, lr} \n" // save context of current thread
#else
" stmdb r0!, {r4-r11} \n" // save context of current thread
" mov r4, lr \n"
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
" \n"
" bl schedulerSwitchContextWrapper \n" // switch context
" \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" ldmia r0!, {r4-r11, lr} \n" // load context of new thread
#else
" mov lr, r4 \n"
" ldmia r0!, {r4-r11} \n" // load context of new thread
#endif // __FPU_PRESENT == 1 && __FPU_USED == 1
" msr PSP, r0 \n"
" \n"
" bx lr \n" // return to new thread
);
__builtin_unreachable();
}
<|endoftext|> |
<commit_before>
#include <iostream>
//#include <boost/bind.hpp>
//
//#include <boost/test/included/unit_test.hpp>
#include <FFLLAPI.h>
#include <DefuzzVarObj.h>
#include <FFLLBase.h>
#include <FuzzyModelBase.h>
#include <FuzzyVariableBase.h>
#include <FuzzyOutVariable.h>
#include <RuleArray.h>
#include <MemberFuncTrap.h>
#include <MemberFuncTri.h>
#include <MemberFuncSCurve.h>
#include <MemberFuncSingle.h>
#include <FuzzySetBase.h>
int main( int argc, char* argv[] )
{
FuzzyModelBase* testModel = new FuzzyModelBase();// = new FuzzyModelBase();
testModel->init(); //create model with empty rule array
//const Char* c = model->get_model_name();
testModel->FuzzyModelBase::set_defuzz_method(0); // set DEFUZZ_COG method
testModel->FuzzyModelBase::set_inference_method(0);
testModel->FuzzyModelBase::set_composition_method(0);
//FuzzyModelBase* pmodel = &model;
std::wstring name1(L"inputVariable1");
const wchar_t* szInputVariable1 = name1.c_str();
std::wstring name2(L"outVariable1");
const wchar_t* szOutVariable1 = name2.c_str();
std::wstring name3(L"inputVariable2");
const wchar_t* szInputVariable2 = name3.c_str();
FuzzyVariableBase* inputVar1 = new FuzzyVariableBase(testModel);// create new inputVar
int i = inputVar1->init(szInputVariable1, 34.5, 45.3, true);//left x value, right x value? // if no name is passed in name it "Variable 0"
// ASSERT(i == -1);
FuzzyVariableBase* inputVar2 = new FuzzyVariableBase(testModel);
int k = inputVar2->init(szInputVariable2, 34.5, 45.3, true);
// ASSERT(k == -1);
FuzzyOutVariable* outVariable1 = new FuzzyOutVariable(testModel); // create new outVar
int j = outVariable1->init(szOutVariable1, 23.4, 56.5, true); //return 0 if success
// ASSERT(j == -1);
testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
testModel->add_output_variable(szOutVariable1, 23.4, 56.5, true);
// set atributes for InputVariable1
inputVar1->set_dom_array_count(100); // discrete y
inputVar1->set_x_array_count(100); //discrete x
inputVar1->set_index(0);
// FuzzySets for InputVariable1
FuzzySetBase* set1Var1 = new FuzzySetBase(inputVar1);
// Set attributes for set1Var1
FuzzySetBase* set2Var1 = new FuzzySetBase(inputVar1);
FuzzySetBase* set3Var1 = new FuzzySetBase(inputVar1);
// FuzzySets for InputVariable2
FuzzySetBase* set1Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* set2Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* set3Var2 = new FuzzySetBase(inputVar2);
// Membership functions for sets in InputVariable1
MemberFuncTrap* functionTrap1 = new MemberFuncTrap(set1Var1);
DOMType* arrayDegreeOfMembership = new DOMType[];
// arrayDegreeOfMembership = (1,2,4,5,6,7,8,9,8,7,6,5,4,3,2,1);
//FuzzyVariableBase *var = testModel->get_var(OUTPUT_IDX);
// this code used for automaic create model from api
}<commit_msg> - продолжение теста<commit_after>
#include <iostream>
//#include <boost/bind.hpp>
//
//#include <boost/test/included/unit_test.hpp>
#include <FFLLAPI.h>
#include <DefuzzVarObj.h>
#include <FFLLBase.h>
#include <FuzzyModelBase.h>
#include <FuzzyVariableBase.h>
#include <FuzzyOutVariable.h>
#include <RuleArray.h>
#include <MemberFuncTrap.h>
#include <MemberFuncTri.h>
#include <MemberFuncSCurve.h>
#include <MemberFuncSingle.h>
#include <FuzzySetBase.h>
int main( int argc, char* argv[] )
{
FuzzyModelBase* testModel = new FuzzyModelBase();// = new FuzzyModelBase();
testModel->init(); //create model with empty rule array
//const Char* c = model->get_model_name();
testModel->FuzzyModelBase::set_defuzz_method(0); // set DEFUZZ_COG method
testModel->FuzzyModelBase::set_inference_method(0);
testModel->FuzzyModelBase::set_composition_method(0);
//FuzzyModelBase* pmodel = &model;
std::wstring name1(L"inputVariable1");
const wchar_t* szInputVariable1 = name1.c_str();
std::wstring name2(L"outVariable1");
const wchar_t* szOutVariable1 = name2.c_str();
std::wstring name3(L"inputVariable2");
const wchar_t* szInputVariable2 = name3.c_str();
std::wstring nameSet(L"set1Var1");
wchar_t* wset_name1 = convert_to_wide_char("set1Var1");
FuzzyVariableBase* inputVar1 = new FuzzyVariableBase(testModel);// create new inputVar
int i = inputVar1->init(szInputVariable1, 34.5, 45.3, true);//left x value, right x value? // if no name is passed in name it "Variable 0"
inputVar1->add_set(inputVar1->new_set(wset_name1,25,inputVar1,0,30,2));
inputVar1->set_x_array_count(100);
// inputVar1->set_right_x(25);
// inputVar1->set_ramp(1,0,0);
//inputVar1->set_dom_array_count(20);
// inputVar1->set_left_x(0);
// ASSERT(i == -1);
FuzzyVariableBase* inputVar2 = new FuzzyVariableBase(testModel);
int k = inputVar2->init(szInputVariable2, 34.5, 45.3, true);
// ASSERT(k == -1);
FuzzyOutVariable* outVariable1 = new FuzzyOutVariable(testModel); // create new outVar
int j = outVariable1->init(szOutVariable1, 23.4, 56.5, true); //return 0 if success
// ASSERT(j == -1);
testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
testModel->add_input_variable(szInputVariable1, 34.5, 45.3, true);
testModel->add_output_variable(szOutVariable1, 23.4, 56.5, true);
// set atributes for InputVariable1
inputVar1->set_dom_array_count(100); // discrete y
inputVar1->set_x_array_count(100); //discrete x
inputVar1->set_index(0);
// FuzzySets for InputVariable1
FuzzySetBase* set1Var1 = new FuzzySetBase(inputVar1);
// Set attributes for set1Var1
FuzzySetBase* set2Var1 = new FuzzySetBase(inputVar1);
FuzzySetBase* set3Var1 = new FuzzySetBase(inputVar1);
// FuzzySets for InputVariable2
FuzzySetBase* set1Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* set2Var2 = new FuzzySetBase(inputVar2);
FuzzySetBase* set3Var2 = new FuzzySetBase(inputVar2);
// Membership functions for sets in InputVariable1
MemberFuncTrap* functionTrap1 = new MemberFuncTrap(set1Var1);
functionTrap1->init();
functionTrap1->set_ramp(1,0); // RAMP_NA
functionTrap1->init();
functionTrap1->set_node(0,25,0);
functionTrap1->set_node(1,27,1); // 4 point for trap
functionTrap1->set_node(2,30,1);
functionTrap1->set_node(3,32,0);
wchar_t* wset_name = convert_to_wide_char("Set1Var1");
// FuzzySetBase* set = new_set(wset_name, 0, inputVar1, 3, 0, 2);
functionTrap1->get_start_x();
functionTrap1->get_end_x();
functionTrap1->get_node_x(2);
functionTrap1->get_node_y(2);
functionTrap1->get_ramp();
functionTrap1->get_center_x();
// functionTrap1->get_dom();
// functionTrap1->get_value();
DOMType* arrayDegreeOfMembership = new DOMType[];
// arrayDegreeOfMembership = (1,2,4,5,6,7,8,9,8,7,6,5,4,3,2,1);
//FuzzyVariableBase *var = testModel->get_var(OUTPUT_IDX);
// this code used for automaic create model from api
}<|endoftext|> |
<commit_before>/*
* CrissCross
* A multi-purpose cross-platform library.
*
* A product of Uplink Laboratories.
*
* (c) 2006-2007 Steven Noonan.
* Licensed under the New BSD License.
*
*/
#include <crisscross/universal_include.h>
#include <crisscross/debug.h>
#include <crisscross/core_io.h>
#include <crisscross/system.h>
using namespace CrissCross::System;
namespace CrissCross
{
namespace IO
{
CoreIOReader::CoreIOReader ( FILE * _fileBuffer, bool _isUnicode, LineEndingType _lnEnding ):
m_fileInputPointer ( _fileBuffer ),
m_unicode ( _isUnicode )
{
SetLineEndings ( _lnEnding );
}
CoreIOReader::~CoreIOReader ()
{
}
bool
CoreIOReader::EndOfFile ()
{
CoreAssert ( this != NULL );
if ( !m_fileInputPointer )
return true;
return ( feof ( m_fileInputPointer ) != 0 );
}
void
CoreIOReader::Flush ()
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
fflush ( m_fileInputPointer );
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
}
bool
CoreIOReader::IsOpen ()
{
CoreAssert ( this != NULL );
if ( m_fileInputPointer == NULL )
return false;
else
return true;
}
int
CoreIOReader::Forward ( cc_int64_t _position )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
int res = Seek ( _position, SEEK_CUR );
return ( res == 0 );
}
cc_int64_t
CoreIOReader::Length ()
{
CoreAssert ( this != NULL );
CoreAssert ( IsOpen() );
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
fpos64_t lastpos, endpos;
#ifdef TARGET_OS_WINDOWS
lastpos = _ftelli64 ( m_fileInputPointer );
_fseeki64 ( m_fileInputPointer, 0, SEEK_END );
endpos = _ftelli64 ( m_fileInputPointer );
_fseeki64 ( m_fileInputPointer, lastpos, SEEK_SET );
#elif defined ( TARGET_OS_MACOSX )
fgetpos ( m_fileInputPointer, &lastpos );
fseek ( m_fileInputPointer, 0, SEEK_END );
fgetpos ( m_fileInputPointer, &endpos );
fsetpos ( m_fileInputPointer, &lastpos );
#else
fgetpos64 ( m_fileInputPointer, &lastpos );
fseeko64 ( m_fileInputPointer, 0, SEEK_END );
fgetpos64 ( m_fileInputPointer, &endpos );
fsetpos64 ( m_fileInputPointer, &lastpos );
#endif
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
#if defined ( TARGET_OS_WINDOWS ) || defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_FREEBSD ) || \
defined ( TARGET_OS_NETBSD ) || defined ( TARGET_OS_OPENBSD ) || defined ( TARGET_COMPILER_CYGWIN )
return endpos;
#elif defined ( TARGET_OS_LINUX )
return endpos.__pos;
#endif
}
int
CoreIOReader::Read ( char *_destination )
{
CoreAssert ( this != NULL );
CoreAssert ( _destination != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
*_destination = (char)fgetc ( m_fileInputPointer );
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
return sizeof(char);
}
int
CoreIOReader::Read ( char *_buffer, size_t _bufferLength, size_t _bufferIndex, size_t _count )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
size_t retval;
CoreAssert ( _buffer != NULL );
CoreAssert ( _bufferLength - _bufferIndex > _count );
CoreAssert ( _count > 0 );
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
retval = fread ( &_buffer[_bufferIndex], sizeof(char), _count, m_fileInputPointer );
_buffer[_bufferIndex + retval] = '\x0';
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
return (int)retval;
}
int
CoreIOReader::ReadLine ( char *_buffer, size_t _bufferLength )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
// We use fgets because it detects line endings.
_buffer[0] = '\x0';
fgets ( _buffer, (int)_bufferLength, m_fileInputPointer );
// Detect line endings.
char *endl = NULL;
char *cr = strchr ( _buffer, '\r' );
char *lf = strchr ( _buffer, '\n' );
char *crlf = strstr ( _buffer, "\r\n" );
if ( crlf ) { SetLineEndings ( CC_LN_CRLF ); endl = crlf; }
else if ( cr ) { SetLineEndings ( CC_LN_CR ); endl = cr; }
else if ( lf ) { SetLineEndings ( CC_LN_LF ); endl = lf; }
if ( endl )
*endl = '\x0';
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
return (int)strlen ( _buffer );
}
int
CoreIOReader::ReadLine ( std::string &_string )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
char c = (char) fgetc ( m_fileInputPointer );
if ( c == (char)EOF )
return 0;
static std::string buffer;
while ( c != (char)EOF && c != '\n' )
{
buffer += c;
c = (char)fgetc ( m_fileInputPointer );
}
int len = (int)buffer.length ();
if ( len && buffer[len - 1] == '\r' )
buffer.resize ( len - 1 );
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
_string = buffer;
return (int)_string.length() * sizeof ( char );
}
int
CoreIOReader::Seek ( cc_int64_t _position, int _origin )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
#ifdef TARGET_OS_WINDOWS
int res = _fseeki64 ( m_fileInputPointer, _position, _origin );
#else
int res = fseeko64 ( m_fileInputPointer, _position, _origin );
#endif
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
return res;
}
int
CoreIOReader::Seek ( cc_int64_t _position )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
int res = Seek ( _position, SEEK_SET );
return ( res == 0 );
}
CrissCross::Errors
CoreIOReader::SetLineEndings ( LineEndingType _ending )
{
CoreAssert ( this != NULL );
if ( _ending == CC_LN_NATIVE )
{
#if defined ( TARGET_OS_WINDOWS )
_ending = CC_LN_CRLF;
#elif defined ( TARGET_OS_LINUX ) || defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_FREEBSD ) || defined ( TARGET_OS_NETBSD ) || defined ( TARGET_OS_OPENBSD )
_ending = CC_LN_LF;
#else
# error You are not using a supported OS.
#endif
}
switch ( _ending )
{
case CC_LN_CR:
sprintf ( m_lineEnding, "\r" );
break;
case CC_LN_LF:
sprintf ( m_lineEnding, "\n" );
break;
case CC_LN_CRLF:
sprintf ( m_lineEnding, "\r\n" );
break;
default:
return CC_ERR_BADPARAMETER;
}
return CC_ERR_NONE;
}
}
}
<commit_msg>Correcting data types issue.<commit_after>/*
* CrissCross
* A multi-purpose cross-platform library.
*
* A product of Uplink Laboratories.
*
* (c) 2006-2007 Steven Noonan.
* Licensed under the New BSD License.
*
*/
#include <crisscross/universal_include.h>
#include <crisscross/debug.h>
#include <crisscross/core_io.h>
#include <crisscross/system.h>
using namespace CrissCross::System;
namespace CrissCross
{
namespace IO
{
CoreIOReader::CoreIOReader ( FILE * _fileBuffer, bool _isUnicode, LineEndingType _lnEnding ):
m_fileInputPointer ( _fileBuffer ),
m_unicode ( _isUnicode )
{
SetLineEndings ( _lnEnding );
}
CoreIOReader::~CoreIOReader ()
{
}
bool
CoreIOReader::EndOfFile ()
{
CoreAssert ( this != NULL );
if ( !m_fileInputPointer )
return true;
return ( feof ( m_fileInputPointer ) != 0 );
}
void
CoreIOReader::Flush ()
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
fflush ( m_fileInputPointer );
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
}
bool
CoreIOReader::IsOpen ()
{
CoreAssert ( this != NULL );
if ( m_fileInputPointer == NULL )
return false;
else
return true;
}
int
CoreIOReader::Forward ( cc_int64_t _position )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
int res = Seek ( _position, SEEK_CUR );
return ( res == 0 );
}
cc_int64_t
CoreIOReader::Length ()
{
CoreAssert ( this != NULL );
CoreAssert ( IsOpen() );
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
fpos64_t lastpos, endpos;
#ifdef TARGET_OS_WINDOWS
lastpos = _ftelli64 ( m_fileInputPointer );
_fseeki64 ( m_fileInputPointer, 0, SEEK_END );
endpos = _ftelli64 ( m_fileInputPointer );
_fseeki64 ( m_fileInputPointer, lastpos, SEEK_SET );
#elif defined ( TARGET_OS_MACOSX )
fgetpos ( m_fileInputPointer, &lastpos );
fseek ( m_fileInputPointer, 0, SEEK_END );
fgetpos ( m_fileInputPointer, &endpos );
fsetpos ( m_fileInputPointer, &lastpos );
#else
fgetpos64 ( m_fileInputPointer, &lastpos );
fseeko64 ( m_fileInputPointer, 0, SEEK_END );
fgetpos64 ( m_fileInputPointer, &endpos );
fsetpos64 ( m_fileInputPointer, &lastpos );
#endif
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
#if defined ( TARGET_OS_WINDOWS ) || defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_FREEBSD ) || \
defined ( TARGET_OS_NETBSD ) || defined ( TARGET_OS_OPENBSD ) || defined ( TARGET_COMPILER_CYGWIN )
return endpos;
#elif defined ( TARGET_OS_LINUX )
return endpos.__pos;
#endif
}
int
CoreIOReader::Read ( char *_destination )
{
CoreAssert ( this != NULL );
CoreAssert ( _destination != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
*_destination = (char)fgetc ( m_fileInputPointer );
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
return sizeof(char);
}
int
CoreIOReader::Read ( char *_buffer, size_t _bufferLength, size_t _bufferIndex, size_t _count )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
size_t retval;
CoreAssert ( _buffer != NULL );
CoreAssert ( _bufferLength - _bufferIndex > _count );
CoreAssert ( _count > 0 );
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
retval = fread ( &_buffer[_bufferIndex], sizeof(char), _count, m_fileInputPointer );
_buffer[_bufferIndex + retval] = '\x0';
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
return (int)retval;
}
int
CoreIOReader::ReadLine ( char *_buffer, size_t _bufferLength )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
// We use fgets because it detects line endings.
_buffer[0] = '\x0';
fgets ( _buffer, (int)_bufferLength, m_fileInputPointer );
// Detect line endings.
char *endl = NULL;
char *cr = strchr ( _buffer, '\r' );
char *lf = strchr ( _buffer, '\n' );
char *crlf = strstr ( _buffer, "\r\n" );
if ( crlf ) { SetLineEndings ( CC_LN_CRLF ); endl = crlf; }
else if ( cr ) { SetLineEndings ( CC_LN_CR ); endl = cr; }
else if ( lf ) { SetLineEndings ( CC_LN_LF ); endl = lf; }
if ( endl )
*endl = '\x0';
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
return (int)strlen ( _buffer );
}
int
CoreIOReader::ReadLine ( std::string &_string )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
char c = (char) fgetc ( m_fileInputPointer );
if ( c == (char)EOF )
return 0;
static std::string buffer;
while ( c != (char)EOF && c != '\n' )
{
buffer += c;
c = (char)fgetc ( m_fileInputPointer );
}
int len = (int)buffer.length ();
if ( len && buffer[len - 1] == '\r' )
buffer.resize ( len - 1 );
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
_string = buffer;
return (int)_string.length() * sizeof ( char );
}
int
CoreIOReader::Seek ( cc_int64_t _position, int _origin )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
#ifndef __GNUC__
m_ioMutex.Lock ();
#endif
#ifdef TARGET_OS_WINDOWS
int res = _fseeki64 ( m_fileInputPointer, _position, _origin );
#elif defined ( TARGET_OS_MACOSX )
int res = fseek ( m_fileInputPointer, _position, _origin );
#endif
int res = fseeko64 ( m_fileInputPointer, _position, _origin );
#endif
#ifndef __GNUC__
m_ioMutex.Unlock ();
#endif
return res;
}
int
CoreIOReader::Seek ( cc_int64_t _position )
{
CoreAssert ( this != NULL );
if ( !IsOpen() ) return CC_ERR_INVALID_BUFFER;
int res = Seek ( _position, SEEK_SET );
return ( res == 0 );
}
CrissCross::Errors
CoreIOReader::SetLineEndings ( LineEndingType _ending )
{
CoreAssert ( this != NULL );
if ( _ending == CC_LN_NATIVE )
{
#if defined ( TARGET_OS_WINDOWS )
_ending = CC_LN_CRLF;
#elif defined ( TARGET_OS_LINUX ) || defined ( TARGET_OS_MACOSX ) || defined ( TARGET_OS_FREEBSD ) || defined ( TARGET_OS_NETBSD ) || defined ( TARGET_OS_OPENBSD )
_ending = CC_LN_LF;
#else
# error You are not using a supported OS.
#endif
}
switch ( _ending )
{
case CC_LN_CR:
sprintf ( m_lineEnding, "\r" );
break;
case CC_LN_LF:
sprintf ( m_lineEnding, "\n" );
break;
case CC_LN_CRLF:
sprintf ( m_lineEnding, "\r\n" );
break;
default:
return CC_ERR_BADPARAMETER;
}
return CC_ERR_NONE;
}
}
}
<|endoftext|> |
<commit_before>/**
* Doit.cpp
* Doit is a basic exec shell that supports background tasks.
*
* @author Arthur Lockman <[email protected]>
*/
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <iomanip>
#include <time.h>
using namespace std;
/**
* Print a stat returned from the getrusage() function.
*/
void printStat(char const *stat, long val)
{
cout << left << setw(29) << stat << right << setw(10) << val << endl;
}
/**
* Main function.
* @param argc The argument count.
* @param argv The arguments as text.
*/
int main(int argc, char **argv)
{
if (argc == 1)
{
cout << "Executing as shell..." << endl;
//Exec as shell
}
else if (argc > 1)
{
int pid;
struct timeval start;
gettimeofday(&start, NULL);
long start_ms = start.tv_sec * 1000 + start.tv_usec / 1000;
//Exec given command
if ((pid = fork()) < 0) //fork failed
{
cerr << "Fork error!" << endl;
}
else if (pid == 0) //is child
{
char *argvNew[argc];
for (int i = 1; i < argc; i++)
{
argvNew[i - 1] = argv[i];
}
argvNew[argc - 1] = NULL;
if (execvp(argvNew[0], argvNew) < 0)
{
cerr << "Execvp error!" << endl;
exit(1);
}
}
else //is parent
{
struct rusage childUsage;
wait(0);
cout << "Child finished." << endl;
struct timeval end;
gettimeofday(&end, NULL);
long end_ms = end.tv_sec * 1000 + end.tv_usec / 1000;
getrusage(RUSAGE_CHILDREN, &childUsage);
printStat("Wall Clock Time:", end_ms - start_ms);
printStat("User CPU Time:", 345678);
printStat("System CPU Time:", 134134);
printStat("Max RSS:", childUsage.ru_maxrss);
printStat("Integral Shared Memory Size:", childUsage.ru_ixrss);
printStat("Integral Unshared Data Size:", childUsage.ru_idrss);
printStat("Integral Unshared Stack Size:", childUsage.ru_isrss);
printStat("Page Reclaims:", childUsage.ru_minflt);
printStat("Page Faults:", childUsage.ru_majflt);
printStat("Swaps:", childUsage.ru_nswap);
printStat("Block Input Operations:", childUsage.ru_inblock);
printStat("Block Output Operations:", childUsage.ru_oublock);
printStat("IPC Messages Sent:", childUsage.ru_msgsnd);
printStat("IPC Messages Received:", childUsage.ru_msgrcv);
printStat("Signals Received:", childUsage.ru_nsignals);
printStat("Voluntary Context Switches:", childUsage.ru_nvcsw);
printStat("Involuntary Context Switches:", childUsage.ru_nivcsw);
}
}
}
<commit_msg>Added basic shell outline.<commit_after>/**
* Doit.cpp
* Doit is a basic exec shell that supports background tasks.
*
* @author Arthur Lockman <[email protected]>
*/
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <iomanip>
#include <time.h>
using namespace std;
/**
* Print a stat returned from the getrusage() function.
*/
void printStat(char const *stat, long val)
{
cout << left << setw(29) << stat << right << setw(10) << val << endl;
}
/**
* Main function.
* @param argc The argument count.
* @param argv The arguments as text.
*/
int main(int argc, char **argv)
{
if (argc == 1)
{
cout << "Executing as shell..." << endl;
int halt = 0;
while (!halt)
{
cout << "% ";
string cmd;
getline(cin, cmd);
cout << "Read: " << cmd << endl;
if (cmd == "exit")
halt = 1;
//TODO: Parse commands
int pid;
if ((pid = fork()) < 0) //fork failed
{
cerr << "Fork error!" << endl;
}
else if (pid == 0) //is child
{
//TODO: exec parsed process
}
else //is parent
{
wait(0);
//TODO: Does this need to print stats?
}
}
}
else if (argc > 1)
{
int pid;
struct timeval start;
gettimeofday(&start, NULL);
long start_ms = start.tv_sec * 1000 + start.tv_usec / 1000;
//Exec given command
if ((pid = fork()) < 0) //fork failed
{
cerr << "Fork error!" << endl;
}
else if (pid == 0) //is child
{
char *argvNew[argc];
for (int i = 1; i < argc; i++)
{
argvNew[i - 1] = argv[i];
}
argvNew[argc - 1] = NULL;
if (execvp(argvNew[0], argvNew) < 0)
{
cerr << "Execvp error!" << endl;
exit(1);
}
}
else //is parent
{
struct rusage childUsage;
wait(0);
cout << endl << "Child finished." << endl;
struct timeval end;
gettimeofday(&end, NULL);
long end_ms = end.tv_sec * 1000 + end.tv_usec / 1000;
getrusage(RUSAGE_CHILDREN, &childUsage);
printStat("Wall Clock Time:", end_ms - start_ms);
printStat("User CPU Time:", childUsage.ru_utime.tv_sec * 1000 + childUsage.ru_utime.tv_usec / 1000);
printStat("System CPU Time:", childUsage.ru_stime.tv_sec * 1000 + childUsage.ru_stime.tv_usec / 1000);
printStat("Max RSS:", childUsage.ru_maxrss);
printStat("Integral Shared Memory Size:", childUsage.ru_ixrss);
printStat("Integral Unshared Data Size:", childUsage.ru_idrss);
printStat("Integral Unshared Stack Size:", childUsage.ru_isrss);
printStat("Page Reclaims:", childUsage.ru_minflt);
printStat("Page Faults:", childUsage.ru_majflt);
printStat("Swaps:", childUsage.ru_nswap);
printStat("Block Input Operations:", childUsage.ru_inblock);
printStat("Block Output Operations:", childUsage.ru_oublock);
printStat("IPC Messages Sent:", childUsage.ru_msgsnd);
printStat("IPC Messages Received:", childUsage.ru_msgrcv);
printStat("Signals Received:", childUsage.ru_nsignals);
printStat("Voluntary Context Switches:", childUsage.ru_nvcsw);
printStat("Involuntary Context Switches:", childUsage.ru_nivcsw);
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <ox/mc/read.hpp>
#ifdef OX_USE_STDLIB
#include <ox/oc/read.hpp>
#endif
#include <ox/std/string.hpp>
#include <ox/std/vector.hpp>
#include "format.hpp"
namespace ox {
namespace detail {
struct ClawHeader {
String typeName;
int typeVersion = -1;
ClawFormat fmt = ClawFormat::None;
const char *data = nullptr;
std::size_t dataSize = 0;
};
Result<ClawHeader> readHeader(const char *buff, std::size_t buffLen) noexcept;
}
Result<Vector<char>> stripClawHeader(const char *buff, std::size_t buffLen) noexcept;
template<typename T>
Error readClaw(const char *buff, std::size_t buffLen, T *val) {
oxRequire(header, detail::readHeader(buff, buffLen));
switch (header.fmt) {
case ClawFormat::Metal:
{
MetalClawReader reader(bit_cast<uint8_t*>(header.data), buffLen);
return model(&reader, val);
}
#ifdef OX_USE_STDLIB
case ClawFormat::Organic:
{
OrganicClawReader reader(bit_cast<uint8_t*>(header.data), buffLen);
return model(&reader, val);
}
#endif
case ClawFormat::None:
return OxError(1);
}
return OxError(1);
}
template<typename T>
Result<T> readClaw(const char *buff, std::size_t buffLen) {
T val;
oxReturnError(readClaw(buff, buffLen, &val));
return ox::move(val);
}
template<typename T>
Result<T> readClaw(const Vector<char> &buff) {
return readClaw<T>(buff.data(), buff.size());
}
}
<commit_msg>[ox/claw] Cleanup<commit_after>/*
* Copyright 2015 - 2021 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <ox/mc/read.hpp>
#ifdef OX_USE_STDLIB
#include <ox/oc/read.hpp>
#endif
#include <ox/std/string.hpp>
#include <ox/std/vector.hpp>
#include "format.hpp"
namespace ox {
namespace detail {
struct ClawHeader {
String typeName;
int typeVersion = -1;
ClawFormat fmt = ClawFormat::None;
const char *data = nullptr;
std::size_t dataSize = 0;
};
Result<ClawHeader> readHeader(const char *buff, std::size_t buffLen) noexcept;
}
Result<Vector<char>> stripClawHeader(const char *buff, std::size_t buffLen) noexcept;
template<typename T>
Error readClaw(const char *buff, std::size_t buffLen, T *val) {
oxRequire(header, detail::readHeader(buff, buffLen));
switch (header.fmt) {
case ClawFormat::Metal:
{
MetalClawReader reader(bit_cast<uint8_t*>(header.data), buffLen);
return model(&reader, val);
}
#ifdef OX_USE_STDLIB
case ClawFormat::Organic:
{
OrganicClawReader reader(bit_cast<uint8_t*>(header.data), buffLen);
return model(&reader, val);
}
#endif
case ClawFormat::None:
return OxError(1);
}
return OxError(1);
}
template<typename T>
Result<T> readClaw(const char *buff, std::size_t buffLen) {
T val;
oxReturnError(readClaw(buff, buffLen, &val));
return move(val);
}
template<typename T>
Result<T> readClaw(const Vector<char> &buff) {
return readClaw<T>(buff.data(), buff.size());
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <map>
#include <node.h>
#include "PSATResult.h"
#include "calculator/EstimateFLA.h"
using namespace v8;
using namespace std;
Isolate* iso;
Local<Object> inp;
double Get(const char *nm) {
auto r = inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
if (isnan(r)) {
cout << nm;
assert(!"number");
}
return r;
}
void Results(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
inp = args[0]->ToObject();
auto r = Object::New(iso);
auto drive = (Pump::Drive)(int)Get("drive");
auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");
Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_specified"),Get("pump_rated_speed"),drive,
Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed")));
Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"),
effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin"));
Financial fin(Get("fraction"),Get("cost"));
FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1),
Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage"));
PSATResult psat(pump,motor,fin,fd);
psat.calculateExisting();
psat.calculateOptimal();
auto ex = psat.getExisting(), opt = psat.getOptimal();
map<const char *,vector<double>> out = {
{"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}},
{"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}},
{"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}},
{"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}},
{"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}},
{"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}},
{"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}},
{"Motor Power", {ex.motorPower_,opt.motorPower_}},
{"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}},
{"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}},
{"Savings Potential", {psat.getAnnualSavingsPotential(),0}},
{"Optimization Rating", {psat.getOptimizationRating(),0}}
};
for(auto p: out) {
auto a = Array::New(iso);
a->Set(0,Number::New(iso,p.second[0]));
a->Set(1,Number::New(iso,p.second[1]));
r->Set(String::NewFromUtf8(iso,p.first),a);
}
args.GetReturnValue().Set(r);
}
void EstFLA(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
inp = args[0]->ToObject();
EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::LineFrequency)(int)(!Get("line")),(Motor::EfficiencyClass)(int)Get("efficiency_class"),
Get("efficiency"),Get("motor_rated_voltage"));
fla.calculate();
args.GetReturnValue().Set(fla.getEstimatedFLA());
}
//TODO round vs js round; loosen up to make next test case
void Check(double exp, double act, const char* nm="") {
//cout << "e " << exp << "; a " << act << endl;
// if (isnan(act) || (abs(exp-act)>.01*exp)) {
auto p = 10;
if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) {
printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
assert(!"equal");
}
}
void Check100(double exp, double act, const char* nm="") {
Check(exp,act*100,nm);
}
void Test(const FunctionCallbackInfo<Value>& args) {
EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460);
fla.calculate();
Check(225.8,fla.getEstimatedFLA());
#define BASE \
Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\
1,1,1,Pump::Speed::NOT_FIXED_SPEED);\
Motor motor(Motor::LineFrequency::FREQ60,200,1780,\
Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\
Financial fin(1,.05);\
FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\
150,0,460);
#define CALC \
PSATResult psat(pump,motor,fin,fd);\
psat.calculateExisting();\
auto ex = psat.getExisting();
for (int i=1; i<=10000; i=i+2) {
BASE
CALC
Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME");
}
{
BASE
motor.setMotorRpm(1786);
fd.setMotorPower(80);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(79.1,ex.motorPowerFactor_);
Check(127,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
motor.setMotorRatedPower(100);
motor.setFullLoadAmps(113.8);
CALC
Check(101.8,ex.motorShaftPower_);
Check100(94.9,ex.motorEfficiency_);
Check100(86.7,ex.motorPowerFactor_);
Check(115.8,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
fd.setVoltage(260);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(138.8,ex.motorPowerFactor_);
Check(128,ex.motorCurrent_);
}
{
BASE
motor.setMotorRpm(1200);
fd.setMotorPower(80);
motor.setFullLoadAmps(235.3);
CALC
Check(101.4,ex.motorShaftPower_);
Check100(94.5,ex.motorEfficiency_);
Check100(74.3,ex.motorPowerFactor_);
Check(135.1,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(111.855);
CALC
Check(143.4,ex.motorShaftPower_);
Check100(95.6,ex.motorEfficiency_);
Check100(84.3,ex.motorPowerFactor_);
Check(166.5,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
motor.setMotorRatedVoltage(200);
motor.setFullLoadAmps(519.3);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(35.2,ex.motorPowerFactor_);
Check(285,ex.motorCurrent_);
}
{
BASE
CALC
Check(217.1,ex.motorCurrent_);
}
{
BASE
fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT);
fd.setMotorAmps(218);
fd.setMotorPower(0);
CALC
Check(150.7,ex.motorPower_);
Check100(72.5,ex.pumpEfficiency_);
}
{
BASE
fd.setMotorPower(80);
CALC
Check(700.8,ex.annualEnergy_);
}
{
BASE
fin.setOperatingFraction(.25);
CALC
Check(328.5,ex.annualEnergy_);
Check(16.4,ex.annualCost_);
}
{
BASE
motor.setFullLoadAmps(300);
CALC
Check(288.9,ex.motorCurrent_);
}
{
BASE
motor.setEfficiencyClass(Motor::EfficiencyClass(0));
CALC
Check(213.7,ex.motorCurrent_);
}
{
BASE
motor.setEfficiencyClass(Motor::EfficiencyClass(2));
motor.setSpecifiedEfficiency(75);
CALC
Check(173.7,ex.motorCurrent_);
}
cout << "done";
}
void Wtf(const FunctionCallbackInfo<Value>& args) {
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "results", Results);
NODE_SET_METHOD(exports, "estFLA", EstFLA);
NODE_SET_METHOD(exports, "test", Test);
NODE_SET_METHOD(exports, "wtf", Wtf);
}
NODE_MODULE(bridge, Init)
<commit_msg>no message<commit_after>#include <iostream>
#include <vector>
#include <map>
#include <node.h>
#include "PSATResult.h"
#include "calculator/EstimateFLA.h"
using namespace v8;
using namespace std;
Isolate* iso;
Local<Object> inp;
double Get(const char *nm) {
auto r = inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
if (isnan(r)) {
cout << nm;
assert(!"number");
}
return r;
}
void Results(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
inp = args[0]->ToObject();
auto r = Object::New(iso);
auto drive = (Pump::Drive)(int)Get("drive");
auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class");
Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_specified"),Get("pump_rated_speed"),drive,
Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed")));
Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"),
effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin"));
Financial fin(Get("fraction"),Get("cost"));
FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1),
Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage"));
PSATResult psat(pump,motor,fin,fd);
psat.calculateExisting();
psat.calculateOptimal();
auto ex = psat.getExisting(), opt = psat.getOptimal();
map<const char *,vector<double>> out = {
{"Pump Efficiency",{ex.pumpEfficiency_*100,opt.pumpEfficiency_*100}},
{"Motor Rated Power",{ex.motorRatedPower_,opt.motorRatedPower_}},
{"Motor Shaft Power",{ex.motorShaftPower_,opt.motorShaftPower_}},
{"Pump Shaft Power",{ex.pumpShaftPower_,opt.pumpShaftPower_}},
{"Motor Efficiency",{ex.motorEfficiency_,opt.motorEfficiency_}},
{"Motor Power Factor",{ex.motorPowerFactor_,opt.motorPowerFactor_}},
{"Motor Current",{ex.motorCurrent_,opt.motorCurrent_}},
{"Motor Power", {ex.motorPower_,opt.motorPower_}},
{"Annual Energy", {ex.annualEnergy_,opt.annualEnergy_}},
{"Annual Cost", {ex.annualCost_*1000,opt.annualCost_*1000}},
{"Savings Potential", {psat.getAnnualSavingsPotential(),0}},
{"Optimization Rating", {psat.getOptimizationRating(),0}}
};
for(auto p: out) {
auto a = Array::New(iso);
a->Set(0,Number::New(iso,p.second[0]));
a->Set(1,Number::New(iso,p.second[1]));
r->Set(String::NewFromUtf8(iso,p.first),a);
}
args.GetReturnValue().Set(r);
}
void EstFLA(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
inp = args[0]->ToObject();
EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::LineFrequency)(int)(!Get("line")),(Motor::EfficiencyClass)(int)Get("efficiency_class"),
Get("efficiency"),Get("motor_rated_voltage"));
fla.calculate();
args.GetReturnValue().Set(fla.getEstimatedFLA());
}
//TODO round vs js round; loosen up to make next test case
void Check(double exp, double act, const char* nm="") {
//cout << "e " << exp << "; a " << act << endl;
// if (isnan(act) || (abs(exp-act)>.01*exp)) {
auto p = 10;
if (isnan(act) || ( (round(exp*p)/p)!=round(act*p)/p)) {
printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act);
assert(!"equal");
}
}
void Check100(double exp, double act, const char* nm="") {
Check(exp,act*100,nm);
}
void Test(const FunctionCallbackInfo<Value>& args) {
EstimateFLA fla(200,1780,(Motor::LineFrequency)1,(Motor::EfficiencyClass)(1),0,460);
fla.calculate();
Check(225.8,fla.getEstimatedFLA());
#define BASE \
Pump pump(Pump::Style::END_SUCTION_ANSI_API,0,1780,Pump::Drive::DIRECT_DRIVE,\
1,1,1,Pump::Speed::NOT_FIXED_SPEED);\
Motor motor(Motor::LineFrequency::FREQ60,200,1780,\
Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\
Financial fin(1,.05);\
FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\
150,0,460);
#define CALC \
PSATResult psat(pump,motor,fin,fd);\
psat.calculateExisting();\
auto ex = psat.getExisting();
for (int i=1; i<=10000; i=i+2) {
BASE
CALC
Check(ex.motorShaftPower_,ex.motorShaftPower_,"SAME");
}
{
BASE
motor.setMotorRpm(1786);
fd.setMotorPower(80);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(79.1,ex.motorPowerFactor_);
Check(127,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
motor.setMotorRatedPower(100);
motor.setFullLoadAmps(113.8);
CALC
Check(101.8,ex.motorShaftPower_);
Check100(94.9,ex.motorEfficiency_);
Check100(86.7,ex.motorPowerFactor_);
Check(115.8,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
fd.setVoltage(260);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(138.8,ex.motorPowerFactor_);
Check(128,ex.motorCurrent_);
}
{
BASE
motor.setMotorRpm(1200);
fd.setMotorPower(80);
motor.setFullLoadAmps(235.3);
CALC
Check(101.4,ex.motorShaftPower_);
Check100(94.5,ex.motorEfficiency_);
Check100(74.3,ex.motorPowerFactor_);
Check(135.1,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(111.855);
CALC
Check(143.4,ex.motorShaftPower_);
Check100(95.6,ex.motorEfficiency_);
Check100(84.3,ex.motorPowerFactor_);
Check(166.5,ex.motorCurrent_);
}
{
BASE
fd.setMotorPower(80);
motor.setMotorRatedVoltage(200);
motor.setFullLoadAmps(519.3);
CALC
Check(101.9,ex.motorShaftPower_);
Check100(95,ex.motorEfficiency_);
Check100(35.2,ex.motorPowerFactor_);
Check(284.9,ex.motorCurrent_);
}
{
BASE
CALC
Check(217.5,ex.motorCurrent_);
}
{
BASE
fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT);
fd.setMotorAmps(218);
fd.setMotorPower(0);
CALC
Check(150.4,ex.motorPower_);
Check100(72.5,ex.pumpEfficiency_);
}
{
BASE
fd.setMotorPower(80);
CALC
Check(700.8,ex.annualEnergy_);
}
{
BASE
fin.setOperatingFraction(.25);
CALC
Check(328.5,ex.annualEnergy_);
Check(16.4,ex.annualCost_);
}
{
BASE
motor.setFullLoadAmps(300);
CALC
Check(288.9,ex.motorCurrent_);
}
{
BASE
motor.setEfficiencyClass(Motor::EfficiencyClass(0));
CALC
Check(213.7,ex.motorCurrent_);
}
{
BASE
motor.setEfficiencyClass(Motor::EfficiencyClass(2));
motor.setSpecifiedEfficiency(75);
CALC
Check(173.7,ex.motorCurrent_);
}
cout << "done";
}
void Wtf(const FunctionCallbackInfo<Value>& args) {
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "results", Results);
NODE_SET_METHOD(exports, "estFLA", EstFLA);
NODE_SET_METHOD(exports, "test", Test);
NODE_SET_METHOD(exports, "wtf", Wtf);
}
NODE_MODULE(bridge, Init)
<|endoftext|> |
<commit_before>#include <node.h>
#include <initializer_list>
#include "Pump.h"
#include "calculator/PumpEfficiency.h"
#include "calculator/OptimalPumpEfficiency.h"
#include "calculator/MotorRatedPower.h"
#include "calculator/OptimalMotorRatedPower.h"
#include "calculator/MotorShaftPower.h"
#include "calculator/OptimalMotorShaftPower.h"
#include "calculator/PumpShaftPower.h"
#include "calculator/OptimalPumpShaftPower.h"
#include "calculator/MotorEfficiency.h"
#include "calculator/OptimalMotorEfficiency.h"
#include "calculator/MotorPowerFactor.h"
#include "calculator/OptimalMotorPowerFactor.h"
#include "calculator/MotorCurrent.h"
#include "calculator/OptimalMotorCurrent.h"
#include "calculator/MotorPower.h"
#include "calculator/OptimalMotorPower.h"
#include "AnnualEnergy.h"
#include "AnnualCost.h"
#include "AnnualSavingsPotential.h"
#include "OptimizationRating.h"
using namespace v8;
Local<Array> r;
Isolate* iso;
Local<Object> inp;
void set(std::initializer_list <double> args) {
for (auto d : args) {
r->Set(r->Length(),Number::New(iso,d));
}
}
double get(const char *nm) {
return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
r = Array::New(iso);
inp = args[0]->ToObject();
auto loadMeth = get("motor_field_power")>0 ? FieldData::LoadEstimationMethod::POWER : FieldData::LoadEstimationMethod::CURRENT;
auto drive = static_cast<Pump::Drive>(get("drive"));
auto effCls = static_cast<Motor::EfficiencyClass>(get("efficiency_class"));
set({
(new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(),//pumpShaftPower
(new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rated_speed"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),//
get("motor_rated_power"),
(new OptimalMotorRatedPower(0,get("margin")))->calculate(),//motorshaftpower
(new MotorShaftPower(0,0))->calculate(),//motor eff, motor power (sometimes inp? sometimes calc)
(new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower
(new PumpShaftPower(0,drive))->calculate(),//motorshaftpower
(new OptimalPumpShaftPower(get("flow"),get("head"),get("specific_gravity"),0))->calculate(),//pumpeff
(new MotorEfficiency(get("line"),get("motor_rated_speed"),effCls,get("motor_rated_power"),
loadMeth,0,0,get("field_voltage")))->calculate(),//motorKwh??, motor amps
(new OptimalMotorEfficiency(get("motor_rated_power"),0))->calculate(),//motor shaft power
(new MotorPowerFactor(get("line"),get("rpm"),effCls,get("power_rating"),
loadMeth,0,0,get("field_voltage")))->calculate(),//motor kwh,motor a
(new OptimalMotorPowerFactor(get("motor_rated_power"),0))->calculate(),//motor power
(new MotorCurrent(0,0,get("field_voltage")))->calculate(),//motor a, motor power
(new OptimalMotorCurrent(0,get("field_voltage")))->calculate(),//motor power
(new MotorPower(0,0,0,get("field_voltage")))->calculate(),//motor power (makes no sense, it IS motor power), motor a, motorpf
(new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff
(new AnnualEnergy(0,get("fraction")))->calculate(),//motorpower
(new AnnualEnergy(0,get("fraction")))->calculate(),//motorpower
(new AnnualCost(0,get("cost")))->calculate(),//ex ann energy
(new AnnualCost(0,get("cost")))->calculate(),//opt ann energy
-1,
(new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost
-1,
(new OptimizationRating(0,0))->calculate()//ex an cost, opt an cost
});
args.GetReturnValue().Set(r);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "results", Results);
}
NODE_MODULE(bridge, init)
<commit_msg>no message<commit_after>#include <node.h>
#include <initializer_list>
#include "Pump.h"
#include "calculator/PumpEfficiency.h"
#include "calculator/OptimalPumpEfficiency.h"
#include "calculator/MotorRatedPower.h"
#include "calculator/OptimalMotorRatedPower.h"
#include "calculator/MotorShaftPower.h"
#include "calculator/OptimalMotorShaftPower.h"
#include "calculator/PumpShaftPower.h"
#include "calculator/OptimalPumpShaftPower.h"
#include "calculator/MotorEfficiency.h"
#include "calculator/OptimalMotorEfficiency.h"
#include "calculator/MotorPowerFactor.h"
#include "calculator/OptimalMotorPowerFactor.h"
#include "calculator/MotorCurrent.h"
#include "calculator/OptimalMotorCurrent.h"
#include "calculator/MotorPower.h"
#include "calculator/OptimalMotorPower.h"
#include "AnnualEnergy.h"
#include "AnnualCost.h"
#include "AnnualSavingsPotential.h"
#include "OptimizationRating.h"
using namespace v8;
Local<Array> r;
Isolate* iso;
Local<Object> inp;
void set(std::initializer_list <double> args) {
for (auto d : args) {
r->Set(r->Length(),Number::New(iso,d));
}
}
double get(const char *nm) {
return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue();
}
void Results(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
r = Array::New(iso);
inp = args[0]->ToObject();
auto loadMeth = get("motor_field_power")>0 ? FieldData::LoadEstimationMethod::POWER : FieldData::LoadEstimationMethod::CURRENT;
auto drive = static_cast<Pump::Drive>(get("drive"));
auto effCls = static_cast<Motor::EfficiencyClass>(get("efficiency_class"));
double mp = get("motor_field_power")>0 ? get("motor_field_power") : (new MotorPower(0,get("motor_field_current"),0,get("field_voltage")))->calculate();//motor power (makes no sense, it IS motor power), motor a, motorpf
double mc = get("motor_field_current")>0 ? get("motor_field_current") : (new MotorCurrent(0,get("motor_field_power"),get("field_voltage")))->calculate();//motor a, motor power, recursive arg!!
set({
(new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(),//pumpShaftPower
(new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rated_speed"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(),//
get("motor_rated_power"),
(new OptimalMotorRatedPower(0,get("margin")))->calculate(),//motorshaftpower
(new MotorShaftPower(0,0))->calculate(),//motor eff, motor power (sometimes inp? sometimes calc)
(new OptimalMotorShaftPower(0,drive))->calculate(),//pumpshaftpower
(new PumpShaftPower(0,drive))->calculate(),//motorshaftpower
(new OptimalPumpShaftPower(get("flow"),get("head"),get("specific_gravity"),0))->calculate(),//pumpeff
(new MotorEfficiency(get("line"),get("motor_rated_speed"),effCls,get("motor_rated_power"),
loadMeth,0,0,get("field_voltage")))->calculate(),//motorKwh??, motor amps
(new OptimalMotorEfficiency(get("motor_rated_power"),0))->calculate(),//motor shaft power
(new MotorPowerFactor(get("line"),get("rpm"),effCls,get("power_rating"),
loadMeth,0,0,get("field_voltage")))->calculate(),//motor kwh,motor a
(new OptimalMotorPowerFactor(get("motor_rated_power"),0))->calculate(),//motor power
mc,
(new OptimalMotorCurrent(0,get("field_voltage")))->calculate(),//opt motor power
mp,
(new OptimalMotorPower(0,0))->calculate(),//motorshaftpower, motor eff
(new AnnualEnergy(mp,get("fraction")))->calculate(),//motorpower
(new AnnualEnergy(0,get("fraction")))->calculate(),//opt motorpower
(new AnnualCost(0,get("cost")))->calculate(),//ex ann energy
(new AnnualCost(0,get("cost")))->calculate(),//opt ann energy
-1,
(new AnnualSavingsPotential(0,0))->calculate(),//ex an cost, opt an cost
-1,
(new OptimizationRating(0,0))->calculate()//ex an cost, opt an cost
});
args.GetReturnValue().Set(r);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "results", Results);
}
NODE_MODULE(bridge, init)
<|endoftext|> |
<commit_before>#include <node.h>
#include "../api//Pump.h"
#include "../api/Calculator/PumpEfficiency.h"
#include "../api/Calculator/OptimalPumpEfficiency.h"
#include "../api/Calculator/MotorRatedPower.h"
#include "../api/Calculator/OptimalMotorRatedPower.h"
#include "../api/Calculator/MotorShaftPower.h"
#include "../api/Calculator/OptimalMotorShaftPower.h"
#include "../api/Calculator/PumpShaftPower.h"
#include "../api/Calculator/OptimalPumpShaftPower.h"
using namespace v8;
Local<Array> r;
Isolate* iso;
void set(double v1, double v2) {
r->Set(r->Length(),Number::New(iso,v1));
r->Set(r->Length(),Number::New(iso,v2));
}
void Results(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
r = Array::New(iso);
set((new PumpEfficiency(0,0,0,0))->calculate(),
(new OptimalPumpEfficiency(Pump::Style::END_SUCTION_SLURRY,0,0,0,0,0,Pump::Speed::FIXED_SPECIFIC_SPEED))->calculate());
set((new MotorRatedPower(0))->calculate(),(new OptimalMotorRatedPower(0,0))->calculate());
set((new MotorShaftPower(0,0))->calculate(),(new OptimalMotorShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate());
set((new PumpShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(),(new OptimalPumpShaftPower(0,0,0,0))->calculate());
args.GetReturnValue().Set(r);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "results", Results);
}
NODE_MODULE(bridge, init)
<commit_msg>no message<commit_after>#include <node.h>
#include "../api//Pump.h"
#include "../api/Calculator/PumpEfficiency.h"
#include "../api/Calculator/OptimalPumpEfficiency.h"
#include "../api/Calculator/MotorRatedPower.h"
#include "../api/Calculator/OptimalMotorRatedPower.h"
#include "../api/Calculator/MotorShaftPower.h"
#include "../api/Calculator/OptimalMotorShaftPower.h"
#include "../api/Calculator/PumpShaftPower.h"
#include "../api/Calculator/OptimalPumpShaftPower.h"
#include "../api/Calculator/MotorEfficiency.h"
#include "../api/Calculator/OptimalMotorEfficiency.h"
using namespace v8;
Local<Array> r;
Isolate* iso;
void set(double v1, double v2) {
r->Set(r->Length(),Number::New(iso,v1));
r->Set(r->Length(),Number::New(iso,v2));
}
void Results(const FunctionCallbackInfo<Value>& args) {
iso = args.GetIsolate();
r = Array::New(iso);
set((new PumpEfficiency(0,0,0,0))->calculate(),
(new OptimalPumpEfficiency(Pump::Style::END_SUCTION_SLURRY,0,0,0,0,0,Pump::Speed::FIXED_SPECIFIC_SPEED))->calculate());
set((new MotorRatedPower(0))->calculate(),(new OptimalMotorRatedPower(0,0))->calculate());
set((new MotorShaftPower(0,0))->calculate(),(new OptimalMotorShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate());
set((new PumpShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(),(new OptimalPumpShaftPower(0,0,0,0))->calculate());
set((new MotorEfficiency(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(),
(new OptimalMotorEfficiency(0,0))->calculate());
args.GetReturnValue().Set(r);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "results", Results);
}
NODE_MODULE(bridge, init)
<|endoftext|> |
<commit_before>#include "Board.h"
#include "Pawn.h"
#include "Rook.h"
#include "Knight.h"
#include "Bishop.h"
#include "Queen.h"
#include "King.h"
#include <iostream>
#include <sstream>
namespace Chess {
Board::Board() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
pieces[x][y] = nullptr;
}
}
// Black pawns
for (int x = 0; x < 8; x++) {
pieces[x][6] = new Pawn(Position(x, 6), false);
}
// White pawns
for (int x = 0; x < 8; x++) {
pieces[x][1] = new Pawn(Position(x, 1), true);
}
// Rooks
pieces[0][7] = new Rook(Position(0, 7), false);
pieces[7][7] = new Rook(Position(7, 7), false);
pieces[0][0] = new Rook(Position(0, 0), true);
pieces[7][0] = new Rook(Position(7, 0), true);
// Knights
pieces[1][7] = new Knight(Position(1, 7), false);
pieces[6][7] = new Knight(Position(6, 7), false);
pieces[1][0] = new Knight(Position(1, 0), true);
pieces[6][0] = new Knight(Position(6, 0), true);
// Bishops
pieces[2][7] = new Bishop(Position(2, 7), false);
pieces[5][7] = new Bishop(Position(5, 7), false);
pieces[2][0] = new Bishop(Position(2, 0), true);
pieces[5][0] = new Bishop(Position(5, 0), true);
// Queens
pieces[3][7] = new Queen(Position(3, 7), false);
pieces[3][0] = new Queen(Position(3, 0), true);
// Kings
pieces[4][7] = new King(Position(4, 7), false);
pieces[4][0] = new King(Position(4, 0), true);
addBoardToMap();
}
Board::~Board() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
if (pieces[x][y] != nullptr)
delete pieces[x][y];
}
}
}
GameState Board::getState() const {
return state;
}
Piece* Board::getPiece(const Position& position) const {
return pieces[position.x][position.y];
}
bool Board::mustPromote() {
return needsToPromote;
}
bool Board::move(const Position& oldPosition, const Position& newPosition) {
Piece* piece = getPiece(oldPosition);
Piece* targetPiece = getPiece(newPosition);
if (piece != nullptr) {
// Check if the piece is of the right color.
if (piece->isWhite() == (turn % 2 == 0)) {
halfMovesSinceCapture++;
// Check if the move is legal.
if (piece->isLegal(*this, newPosition)) {
pieces[oldPosition.x][oldPosition.y] = nullptr;
// En passant.
if (pieces[newPosition.x][newPosition.y] == nullptr && (piece->notation() == 'p' || piece->notation() == 'P') && newPosition.x != oldPosition.x){
if (piece->isWhite()) {
delete pieces[newPosition.x][newPosition.y - 1];
pieces[newPosition.x][newPosition.y - 1] = nullptr;
halfMovesSinceCapture = 0;
} else {
delete pieces[newPosition.x][newPosition.y + 1];
pieces[newPosition.x][newPosition.y + 1] = nullptr;
halfMovesSinceCapture = 0;
}
}
// Castling
if (piece->notation() == 'k' || piece->notation() == 'K') {
if (newPosition.x - oldPosition.x == 2){
Piece* tempPiece = getPiece(Position(7, newPosition.y));
pieces[7][newPosition.y] = nullptr;
pieces[5][newPosition.y] = tempPiece;
tempPiece->move(Position(5, newPosition.y));
} else if (newPosition.x - oldPosition.x == -2) {
Piece* tempPiece = getPiece(Position(0, newPosition.y));
pieces[0][newPosition.y] = nullptr;
pieces[3][newPosition.y] = tempPiece;
tempPiece->move(Position(3, newPosition.y));
}
}
// Delete captured enemy piece.
if (pieces[newPosition.x][newPosition.y] != nullptr){
delete pieces[newPosition.x][newPosition.y];
halfMovesSinceCapture = 0;
}
// Update pieces and piece position
pieces[newPosition.x][newPosition.y] = piece;
if (piece->notation() == 'p' || piece->notation() == 'P')
halfMovesSinceCapture = 0;
piece->move(newPosition);
// Promote pawns
if(newPosition.y == 7 || newPosition.y == 0){
if (piece->notation() == 'p' || piece->notation() == 'P'){
needsToPromote = true;
}
}
// Set and reset lastMovedPiece
if (lastMovedPawn != nullptr){
if (lastMovedPawn->getLastMoveWasDouble()){
//lastMovedPawn->resetLastMoveWasDouble(); //orsakar krasch..
}
}
lastMovedPawn = dynamic_cast<Pawn*>(getPiece(newPosition));
turn++;
if (state == GameState::BLACKPLAYS)
state = GameState::WHITEPLAYS;
else
state = GameState::BLACKPLAYS;
std::string tempstring = toFENString(false);
std::cout << tempstring << '\n';
addBoardToMap();
if(isThreeFoldRepitition())
state = GameState::DRAW;
if (isFiftyMoveSincePawnOrCapture())
state = GameState::DRAW;
checkWin();
return true;
}
}
}
return false;
}
bool Board::willLeaveKingChecked(const Position& oldPosition, const Position& newPosition) {
Piece* oldPiece = getPiece(oldPosition);
Piece* newPiece = getPiece(newPosition);
Piece* piece;
switch (oldPiece->notation()) {
case 'Q':
case 'q':
piece = new Queen(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'K':
case 'k':
piece = new King(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'P':
case 'p':
piece = new Pawn(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'R':
case 'r':
piece = new Rook(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'B':
case 'b':
piece = new Bishop(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'N':
case 'n':
piece = new Knight(oldPiece->getPosition(), oldPiece->isWhite());
break;
}
pieces[newPosition.x][newPosition.y] = piece;
piece->move(newPosition);
pieces[oldPosition.x][oldPosition.y] = nullptr;
King* king = getKing((turn % 2 == 0));
bool checked = king->isChecked(*this);
delete piece;
pieces[newPosition.x][newPosition.y] = newPiece;
pieces[oldPosition.x][oldPosition.y] = oldPiece;
return checked;
}
void Board::promotePawn(Piece* pawn, PromoteTypes type) {
Position position = pawn->getPosition();
bool white = pawn->isWhite();
delete pawn;
switch (type) {
case PromoteTypes::QUEEN:
pieces[position.x][position.y] = new Queen(position, white);
break;
case PromoteTypes::ROOK:
pieces[position.x][position.y] = new Rook(position, white);
break;
case PromoteTypes::BISHOP:
pieces[position.x][position.y] = new Bishop(position, white);
break;
case PromoteTypes::KNIGHT:
pieces[position.x][position.y] = new Knight(position, white);
break;
}
needsToPromote = false;
}
void Board::addBoardToMap() {
std::string tempstring = toFENString(false);
if (previousBoards.find(tempstring) == previousBoards.end()) {
previousBoards[tempstring] = 0;
} else{
previousBoards[tempstring] += 1;
}
}
std::string Board::toFENString(bool addExtraData) const {
std::string tempstring;
int emptyCounter = 0;
for (int y = 7; y >= 0; y--) {
for (int x = 0; x < 8; x++){
if (pieces[x][y] == nullptr)
emptyCounter++;
else {
if (emptyCounter != 0)
tempstring += std::to_string(emptyCounter);
tempstring.append(1, pieces[x][y]->notation());
emptyCounter = 0;
}
}
if (emptyCounter != 0) {
tempstring += std::to_string(emptyCounter);
emptyCounter = 0;
}
tempstring += '/';
}
// Who played the turn?
if (state == GameState::BLACKPLAYS)
tempstring += "w";
else
tempstring += "b";
if (addExtraData) {
// Number of half turns since last capture or pawn move.
tempstring += ' ' + std::to_string(halfMovesSinceCapture) + ' ';
// Number of full moves.
tempstring += std::to_string((turn+1) / 2);
}
return tempstring;
}
bool Board::isThreeFoldRepitition() {
return previousBoards[toFENString(false)] == 3;
}
bool Board::isFiftyMoveSincePawnOrCapture() const{
if (halfMovesSinceCapture >= 100)
return true;
return false;
}
void Board::checkWin() {
bool white = (state == GameState::WHITEPLAYS);
bool canMove = false;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr && piece->isWhite() == white) {
if (!piece->legalMoves(*this).empty()) {
canMove = true;
break;
}
}
}
}
if (!canMove) {
if (getKing(white)->isChecked(*this)) {
if (white)
state = GameState::BLACKWIN;
else
state = GameState::WHITEWIN;
} else {
state = GameState::DRAW;
}
}
}
King* Board::getKing(bool white) const {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr && piece->notation() == (white ? 'K' : 'k'))
return dynamic_cast<King*>(piece);
}
}
return nullptr;
}
}<commit_msg>Simplify isFiftyMovesSincePawnOrCapture<commit_after>#include "Board.h"
#include "Pawn.h"
#include "Rook.h"
#include "Knight.h"
#include "Bishop.h"
#include "Queen.h"
#include "King.h"
#include <iostream>
#include <sstream>
namespace Chess {
Board::Board() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
pieces[x][y] = nullptr;
}
}
// Black pawns
for (int x = 0; x < 8; x++) {
pieces[x][6] = new Pawn(Position(x, 6), false);
}
// White pawns
for (int x = 0; x < 8; x++) {
pieces[x][1] = new Pawn(Position(x, 1), true);
}
// Rooks
pieces[0][7] = new Rook(Position(0, 7), false);
pieces[7][7] = new Rook(Position(7, 7), false);
pieces[0][0] = new Rook(Position(0, 0), true);
pieces[7][0] = new Rook(Position(7, 0), true);
// Knights
pieces[1][7] = new Knight(Position(1, 7), false);
pieces[6][7] = new Knight(Position(6, 7), false);
pieces[1][0] = new Knight(Position(1, 0), true);
pieces[6][0] = new Knight(Position(6, 0), true);
// Bishops
pieces[2][7] = new Bishop(Position(2, 7), false);
pieces[5][7] = new Bishop(Position(5, 7), false);
pieces[2][0] = new Bishop(Position(2, 0), true);
pieces[5][0] = new Bishop(Position(5, 0), true);
// Queens
pieces[3][7] = new Queen(Position(3, 7), false);
pieces[3][0] = new Queen(Position(3, 0), true);
// Kings
pieces[4][7] = new King(Position(4, 7), false);
pieces[4][0] = new King(Position(4, 0), true);
addBoardToMap();
}
Board::~Board() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
if (pieces[x][y] != nullptr)
delete pieces[x][y];
}
}
}
GameState Board::getState() const {
return state;
}
Piece* Board::getPiece(const Position& position) const {
return pieces[position.x][position.y];
}
bool Board::mustPromote() {
return needsToPromote;
}
bool Board::move(const Position& oldPosition, const Position& newPosition) {
Piece* piece = getPiece(oldPosition);
Piece* targetPiece = getPiece(newPosition);
if (piece != nullptr) {
// Check if the piece is of the right color.
if (piece->isWhite() == (turn % 2 == 0)) {
halfMovesSinceCapture++;
// Check if the move is legal.
if (piece->isLegal(*this, newPosition)) {
pieces[oldPosition.x][oldPosition.y] = nullptr;
// En passant.
if (pieces[newPosition.x][newPosition.y] == nullptr && (piece->notation() == 'p' || piece->notation() == 'P') && newPosition.x != oldPosition.x){
if (piece->isWhite()) {
delete pieces[newPosition.x][newPosition.y - 1];
pieces[newPosition.x][newPosition.y - 1] = nullptr;
halfMovesSinceCapture = 0;
} else {
delete pieces[newPosition.x][newPosition.y + 1];
pieces[newPosition.x][newPosition.y + 1] = nullptr;
halfMovesSinceCapture = 0;
}
}
// Castling
if (piece->notation() == 'k' || piece->notation() == 'K') {
if (newPosition.x - oldPosition.x == 2){
Piece* tempPiece = getPiece(Position(7, newPosition.y));
pieces[7][newPosition.y] = nullptr;
pieces[5][newPosition.y] = tempPiece;
tempPiece->move(Position(5, newPosition.y));
} else if (newPosition.x - oldPosition.x == -2) {
Piece* tempPiece = getPiece(Position(0, newPosition.y));
pieces[0][newPosition.y] = nullptr;
pieces[3][newPosition.y] = tempPiece;
tempPiece->move(Position(3, newPosition.y));
}
}
// Delete captured enemy piece.
if (pieces[newPosition.x][newPosition.y] != nullptr){
delete pieces[newPosition.x][newPosition.y];
halfMovesSinceCapture = 0;
}
// Update pieces and piece position
pieces[newPosition.x][newPosition.y] = piece;
if (piece->notation() == 'p' || piece->notation() == 'P')
halfMovesSinceCapture = 0;
piece->move(newPosition);
// Promote pawns
if(newPosition.y == 7 || newPosition.y == 0){
if (piece->notation() == 'p' || piece->notation() == 'P'){
needsToPromote = true;
}
}
// Set and reset lastMovedPiece
if (lastMovedPawn != nullptr){
if (lastMovedPawn->getLastMoveWasDouble()){
//lastMovedPawn->resetLastMoveWasDouble(); //orsakar krasch..
}
}
lastMovedPawn = dynamic_cast<Pawn*>(getPiece(newPosition));
turn++;
if (state == GameState::BLACKPLAYS)
state = GameState::WHITEPLAYS;
else
state = GameState::BLACKPLAYS;
std::string tempstring = toFENString(false);
std::cout << tempstring << '\n';
addBoardToMap();
if(isThreeFoldRepitition())
state = GameState::DRAW;
if (isFiftyMoveSincePawnOrCapture())
state = GameState::DRAW;
checkWin();
return true;
}
}
}
return false;
}
bool Board::willLeaveKingChecked(const Position& oldPosition, const Position& newPosition) {
Piece* oldPiece = getPiece(oldPosition);
Piece* newPiece = getPiece(newPosition);
Piece* piece;
switch (oldPiece->notation()) {
case 'Q':
case 'q':
piece = new Queen(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'K':
case 'k':
piece = new King(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'P':
case 'p':
piece = new Pawn(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'R':
case 'r':
piece = new Rook(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'B':
case 'b':
piece = new Bishop(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'N':
case 'n':
piece = new Knight(oldPiece->getPosition(), oldPiece->isWhite());
break;
}
pieces[newPosition.x][newPosition.y] = piece;
piece->move(newPosition);
pieces[oldPosition.x][oldPosition.y] = nullptr;
King* king = getKing((turn % 2 == 0));
bool checked = king->isChecked(*this);
delete piece;
pieces[newPosition.x][newPosition.y] = newPiece;
pieces[oldPosition.x][oldPosition.y] = oldPiece;
return checked;
}
void Board::promotePawn(Piece* pawn, PromoteTypes type) {
Position position = pawn->getPosition();
bool white = pawn->isWhite();
delete pawn;
switch (type) {
case PromoteTypes::QUEEN:
pieces[position.x][position.y] = new Queen(position, white);
break;
case PromoteTypes::ROOK:
pieces[position.x][position.y] = new Rook(position, white);
break;
case PromoteTypes::BISHOP:
pieces[position.x][position.y] = new Bishop(position, white);
break;
case PromoteTypes::KNIGHT:
pieces[position.x][position.y] = new Knight(position, white);
break;
}
needsToPromote = false;
}
void Board::addBoardToMap() {
std::string tempstring = toFENString(false);
if (previousBoards.find(tempstring) == previousBoards.end()) {
previousBoards[tempstring] = 0;
} else{
previousBoards[tempstring] += 1;
}
}
std::string Board::toFENString(bool addExtraData) const {
std::string tempstring;
int emptyCounter = 0;
for (int y = 7; y >= 0; y--) {
for (int x = 0; x < 8; x++){
if (pieces[x][y] == nullptr)
emptyCounter++;
else {
if (emptyCounter != 0)
tempstring += std::to_string(emptyCounter);
tempstring.append(1, pieces[x][y]->notation());
emptyCounter = 0;
}
}
if (emptyCounter != 0) {
tempstring += std::to_string(emptyCounter);
emptyCounter = 0;
}
tempstring += '/';
}
// Who played the turn?
if (state == GameState::BLACKPLAYS)
tempstring += "w";
else
tempstring += "b";
if (addExtraData) {
// Number of half turns since last capture or pawn move.
tempstring += ' ' + std::to_string(halfMovesSinceCapture) + ' ';
// Number of full moves.
tempstring += std::to_string((turn+1) / 2);
}
return tempstring;
}
bool Board::isThreeFoldRepitition() {
return previousBoards[toFENString(false)] == 3;
}
bool Board::isFiftyMoveSincePawnOrCapture() const {
return halfMovesSinceCapture >= 100;
}
void Board::checkWin() {
bool white = (state == GameState::WHITEPLAYS);
bool canMove = false;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr && piece->isWhite() == white) {
if (!piece->legalMoves(*this).empty()) {
canMove = true;
break;
}
}
}
}
if (!canMove) {
if (getKing(white)->isChecked(*this)) {
if (white)
state = GameState::BLACKWIN;
else
state = GameState::WHITEWIN;
} else {
state = GameState::DRAW;
}
}
}
King* Board::getKing(bool white) const {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr && piece->notation() == (white ? 'K' : 'k'))
return dynamic_cast<King*>(piece);
}
}
return nullptr;
}
}<|endoftext|> |
<commit_before>#include "BTU/btu_PID_lite.cpp"
#include "mbed.h"
#define NUM_FLOATS 4
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.1
#define MISSION_TIMEOUT 10.0
#define ERROR_THRESHOLD 0.15
#define SUCCESS_TIME 5.0
#define UNWOUND_POS 91.0
#include "MODSERIAL.h"
#include "SerialComm.h"
MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);
// LocalFileSystem local("local");
// bool clk = true;
BTU btu = BTU();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float setVal = 0.0; // meters
Ticker Mission;
float timeout = 0.0;
float successTime = 0.0;
int missionDepth = 0.0;
bool missionStarted = false;
void terminateMission() {
Mission.detach();
counter = 0;
inMission = 0;
timeout = 0.0;
successTime = 0.0;
missionStarted = false;
btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
}
bool checkThreshold() {
float error = btu.getDepth() - missionDepth;
// float error = btu.getServoPos() - missionDepth;
float absError = (error > 0) ? error : (-1 * error);
return (absError <= ERROR_THRESHOLD);
}
void runMission() {
counter = (counter + 1) % 20;
if(!counter) {
TestLED = !TestLED;
}
if(btu.getDepth() >= DEPTH_THRESHOLD) {
inMission = 1;
missionStarted = true;
}
if(!missionStarted) {
return;
}
btu.runCycle(missionDepth);
successTime += ((int) checkThreshold() * TIMESTEP);
if (successTime >= SUCCESS_TIME) {
missionSuccess = 1;
terminateMission();
return;
}
if (timeout >= MISSION_TIMEOUT) {
missionSuccess = 0;
terminateMission();
return;
}
timeout += TIMESTEP;
}
void startMission(float kc, float taui, float taud, float setDepth) {
terminateMission();
missionSuccess = 0;
missionDepth = setDepth;
btu.update(DEPTH_CTRL_MODE, kc, taui, taud);
// btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
Mission.attach(&runMission, TIMESTEP);
}
int main() {
pcSerial.printf("Start!\n");
SerialComm serialComm(&pcSerial);
btu.init();
pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
TestLED = 0;
float valueFloats[NUM_FLOATS];
while(1) {
// depth = btu.getDepth();
// if (mode == DEPTH_CTRL_MODE) {
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - depth);
// } else if (mode == SPEC_POSITION_CTRL_MODE) {
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, pos_er:%.4f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - btu.getServoPos());
// } else {
// pcSerial.printf("m:%d, s:%.2f, cu:%.2f, de:%.2f\r\n", btu.getMode(), setVal, btu.getServoPos(), depth);
// }
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, pos_er:%.4f, th:%d, to:%.2f, st:%.2f\r\n", btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), setVal - btu.getServoPos(), checkThreshold(), timeout, successTime);
if(serialComm.checkIfNewMessage()) {
serialComm.getFloats(valueFloats, NUM_FLOATS);
// mode = (int) valueFloats[0];
Kc = valueFloats[0];
TauI = valueFloats[1];
TauD = valueFloats[2];
setVal = valueFloats[3];
startMission(Kc, TauI, TauD, setVal);
}
wait_ms(500);
TestLED2 = !TestLED2;
}
}
<commit_msg>added logging<commit_after>#include "BTU/btu_PID_lite.cpp"
#include "mbed.h"
#define NUM_FLOATS 4
#define TIMESTEP 0.05
#define DEPTH_THRESHOLD 0.1
#define MISSION_TIMEOUT 60.0
#define ERROR_THRESHOLD 0.15
#define SUCCESS_TIME 5.0
#define UNWOUND_POS 91.0
#include "MODSERIAL.h"
#include "SerialComm.h"
MODSERIAL pcSerial(USBTX, USBRX);
// AnalogIn pot1(p15);
DigitalOut TestLED(LED1);
DigitalOut TestLED2(LED2);
DigitalOut inMission(LED3);
DigitalOut missionSuccess(LED4);
LocalFileSystem local("local");
// bool clk = true;
BTU btu = BTU();
int counter = 0;
int mode = 2;
float Kc = 1.0;
float TauI = 0.0;
float TauD = 0.0;
float setVal = 0.0; // meters
Ticker Mission;
float timeout = 0.0;
float successTime = 0.0;
int missionDepth = 0.0;
bool missionStarted = false;
FILE *fp;
void terminateMission() {
Mission.detach();
fclose(fp);
counter = 0;
inMission = 0;
timeout = 0.0;
successTime = 0.0;
missionStarted = false;
btu.updateAndRunCycle(POSITION_CTRL_MODE, UNWOUND_POS);
}
bool checkThreshold() {
float error = btu.getDepth() - missionDepth;
// float error = btu.getServoPos() - missionDepth;
float absError = (error > 0) ? error : (-1 * error);
return (absError <= ERROR_THRESHOLD);
}
void runMission() {
counter = (counter + 1) % 20;
if(!counter) {
TestLED = !TestLED;
}
if(btu.getDepth() >= DEPTH_THRESHOLD) {
inMission = 1;
missionStarted = true;
}
if(!missionStarted) {
return;
}
btu.runCycle(missionDepth);
successTime += ((int) checkThreshold() * TIMESTEP);
if (successTime >= SUCCESS_TIME) {
missionSuccess = 1;
terminateMission();
return;
}
if (timeout >= MISSION_TIMEOUT) {
missionSuccess = 0;
terminateMission();
return;
}
timeout += TIMESTEP;
}
void startMission(float kc, float taui, float taud, float setDepth) {
terminateMission();
fp = fopen("/local/log", "w");
fprintf(fp, "MISSION START, TARGET: %.2f\r\n", setDepth);
missionSuccess = 0;
missionDepth = setDepth;
btu.update(DEPTH_CTRL_MODE, kc, taui, taud);
// btu.update(SPEC_POSITION_CTRL_MODE, kc, taui, taud);
Mission.attach(&runMission, TIMESTEP);
}
int main() {
pcSerial.printf("Start!\n");
SerialComm serialComm(&pcSerial);
btu.init();
pcSerial.printf("pressure at start: %.6f\r\n", btu.getPressure());
TestLED = 0;
float valueFloats[NUM_FLOATS];
while(1) {
// depth = btu.getDepth();
// if (mode == DEPTH_CTRL_MODE) {
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - depth);
// } else if (mode == SPEC_POSITION_CTRL_MODE) {
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, pos_er:%.4f\r\n",
// btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - btu.getServoPos());
// } else {
// pcSerial.printf("m:%d, s:%.2f, cu:%.2f, de:%.2f\r\n", btu.getMode(), setVal, btu.getServoPos(), depth);
// }
// pcSerial.printf("m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, pos_er:%.4f, th:%d, to:%.2f, st:%.2f\r\n", btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), setVal - btu.getServoPos(), checkThreshold(), timeout, successTime);
if(inMission) {
float depth = btu.getDepth();
fprintf(fp, "m:%d, kc:%f, ti:%f, td:%f, s:%.2f, cu:%.2f, de:%.2f, depth_er:%.4f, to:%.2f\r\n",
btu.getMode(), btu.getKc(), btu.getTauI(), btu.getTauD(), setVal, btu.getServoPos(), depth, setVal - depth, timeout);
}
if(serialComm.checkIfNewMessage()) {
serialComm.getFloats(valueFloats, NUM_FLOATS);
// mode = (int) valueFloats[0];
Kc = valueFloats[0];
TauI = valueFloats[1];
TauD = valueFloats[2];
setVal = valueFloats[3];
startMission(Kc, TauI, TauD, setVal);
}
wait_ms(500);
TestLED2 = !TestLED2;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: comboboxtoolbarcontroller.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:17:57 $
*
* 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_framework.hxx"
#ifndef __FRAMEWORK_UIELEMENT_COMBOBOXTOOLBARCONTROLLER_HXX
#include "uielement/comboboxtoolbarcontroller.hxx"
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <vcl/toolbox.hxx>
#include <vcl/combobox.hxx>
#include <tools/urlobj.hxx>
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;
namespace framework
{
// ------------------------------------------------------------------
// Wrapper class to notify controller about events from combobox.
// Unfortunaltly the events are notifed through virtual methods instead
// of Listeners.
class ComboBoxControl : public ComboBox
{
public:
ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener );
virtual ~ComboBoxControl();
virtual void Select();
virtual void DoubleClick();
virtual void Modify();
virtual void KeyInput( const ::KeyEvent& rKEvt );
virtual void GetFocus();
virtual void LoseFocus();
virtual long PreNotify( NotifyEvent& rNEvt );
private:
IComboBoxListener* m_pComboBoxListener;
};
ComboBoxControl::ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener ) :
ComboBox( pParent, nStyle )
, m_pComboBoxListener( pComboBoxListener )
{
}
ComboBoxControl::~ComboBoxControl()
{
m_pComboBoxListener = 0;
}
void ComboBoxControl::Select()
{
ComboBox::Select();
if ( m_pComboBoxListener )
m_pComboBoxListener->Select();
}
void ComboBoxControl::DoubleClick()
{
ComboBox::DoubleClick();
if ( m_pComboBoxListener )
m_pComboBoxListener->DoubleClick();
}
void ComboBoxControl::Modify()
{
ComboBox::Modify();
if ( m_pComboBoxListener )
m_pComboBoxListener->Modify();
}
void ComboBoxControl::KeyInput( const ::KeyEvent& rKEvt )
{
ComboBox::KeyInput( rKEvt );
if ( m_pComboBoxListener )
m_pComboBoxListener->KeyInput( rKEvt );
}
void ComboBoxControl::GetFocus()
{
ComboBox::GetFocus();
if ( m_pComboBoxListener )
m_pComboBoxListener->GetFocus();
}
void ComboBoxControl::LoseFocus()
{
ComboBox::LoseFocus();
if ( m_pComboBoxListener )
m_pComboBoxListener->LoseFocus();
}
long ComboBoxControl::PreNotify( NotifyEvent& rNEvt )
{
long nRet( 0 );
if ( m_pComboBoxListener )
nRet = m_pComboBoxListener->PreNotify( rNEvt );
if ( nRet == 0 )
nRet = ComboBox::PreNotify( rNEvt );
return nRet;
}
// ------------------------------------------------------------------
ComboboxToolbarController::ComboboxToolbarController(
const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& rFrame,
ToolBar* pToolbar,
USHORT nID,
sal_Int32 nWidth,
const OUString& aCommand ) :
ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )
, m_pComboBox( 0 )
{
m_pComboBox = new ComboBoxControl( m_pToolbar, WB_DROPDOWN, this );
if ( nWidth == 0 )
nWidth = 100;
// default dropdown size
::Size aLogicalSize( 8, 160 );
::Size aPixelSize = m_pComboBox->LogicToPixel( aLogicalSize, MAP_APPFONT );
m_pComboBox->SetSizePixel( ::Size( nWidth, aPixelSize.Height() ));
m_pToolbar->SetItemWindow( m_nID, m_pComboBox );
m_pComboBox->SetDropDownLineCount( 5 );
}
// ------------------------------------------------------------------
ComboboxToolbarController::~ComboboxToolbarController()
{
}
// ------------------------------------------------------------------
void SAL_CALL ComboboxToolbarController::dispose()
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
m_pToolbar->SetItemWindow( m_nID, 0 );
delete m_pComboBox;
ComplexToolbarController::dispose();
m_pComboBox = 0;
}
// ------------------------------------------------------------------
void SAL_CALL ComboboxToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
Reference< XDispatch > xDispatch;
Reference< XURLTransformer > xURLTransformer;
OUString aCommandURL;
OUString aSelectedText;
::com::sun::star::util::URL aTargetURL;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
throw DisposedException();
if ( m_bInitialized &&
m_xFrame.is() &&
m_xServiceManager.is() &&
m_aCommandURL.getLength() )
{
xURLTransformer = m_xURLTransformer;
xDispatch = getDispatchFromCommand( m_aCommandURL );
aCommandURL = m_aCommandURL;
aTargetURL = getInitializedURL();
aSelectedText = m_pComboBox->GetText();
}
}
if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
{
Sequence<PropertyValue> aArgs( 2 );
// Add key modifier to argument list
aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
aArgs[0].Value <<= KeyModifier;
aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
aArgs[1].Value <<= aSelectedText;
// Execute dispatch asynchronously
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
}
}
// ------------------------------------------------------------------
void ComboboxToolbarController::Select()
{
if ( m_pComboBox->GetEntryCount() > 0 )
{
Window::PointerState aState = m_pComboBox->GetPointerState();
sal_uInt16 nKeyModifier = sal_uInt16( aState.mnState & KEY_MODTYPE );
execute( nKeyModifier );
}
}
void ComboboxToolbarController::DoubleClick()
{
}
void ComboboxToolbarController::Modify()
{
notifyTextChanged( m_pComboBox->GetText() );
}
void ComboboxToolbarController::KeyInput( const ::KeyEvent& )
{
}
void ComboboxToolbarController::GetFocus()
{
notifyFocusGet();
}
void ComboboxToolbarController::LoseFocus()
{
notifyFocusLost();
}
long ComboboxToolbarController::PreNotify( NotifyEvent& rNEvt )
{
if( rNEvt.GetType() == EVENT_KEYINPUT )
{
const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();
const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();
if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )
{
// Call execute only with non-empty text
if ( m_pComboBox->GetText().Len() > 0 )
execute( rKeyCode.GetModifier() );
return 1;
}
}
return 0;
}
// --------------------------------------------------------
void ComboboxToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
if ( rControlCommand.Command.equalsAsciiL( "SetText", 7 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
rtl::OUString aText;
rControlCommand.Arguments[i].Value >>= aText;
m_pComboBox->SetText( aText );
// send notification
notifyTextChanged( aText );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "SetList", 7 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "List", 4 ))
{
Sequence< OUString > aList;
m_pComboBox->Clear();
rControlCommand.Arguments[i].Value >>= aList;
for ( sal_Int32 j = 0; j < aList.getLength(); j++ )
m_pComboBox->InsertEntry( aList[j] );
// send notification
uno::Sequence< beans::NamedValue > aInfo( 1 );
aInfo[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "List" ));
aInfo[0].Value <<= aList;
addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ListChanged" )),
getDispatchFromCommand( m_aCommandURL ),
aInfo );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "AddEntry", 8 ))
{
sal_uInt16 nPos( COMBOBOX_APPEND );
rtl::OUString aText;
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
if ( rControlCommand.Arguments[i].Value >>= aText )
m_pComboBox->InsertEntry( aText, nPos );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "InsertEntry", 11 ))
{
sal_uInt16 nPos( COMBOBOX_APPEND );
rtl::OUString aText;
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nTmpPos;
if ( rControlCommand.Arguments[i].Value >>= nTmpPos )
{
if (( nTmpPos >= 0 ) &&
( nTmpPos < sal_Int32( m_pComboBox->GetEntryCount() )))
nPos = sal_uInt16( nTmpPos );
}
}
else if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
rControlCommand.Arguments[i].Value >>= aText;
}
m_pComboBox->InsertEntry( aText, nPos );
}
else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryPos", 14 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nPos( -1 );
if ( rControlCommand.Arguments[i].Value >>= nPos )
{
if ( nPos < sal_Int32( m_pComboBox->GetEntryCount() ))
m_pComboBox->RemoveEntry( sal_uInt16( nPos ));
}
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryText", 15 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
rtl::OUString aText;
if ( rControlCommand.Arguments[i].Value >>= aText )
m_pComboBox->RemoveEntry( aText );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "SetDropDownLines", 16 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Lines", 5 ))
{
sal_Int32 nValue( 5 );
rControlCommand.Arguments[i].Value >>= nValue;
m_pComboBox->SetDropDownLineCount( sal_uInt16( nValue ));
break;
}
}
}
}
} // namespace
<commit_msg>INTEGRATION: CWS pj65 (1.6.32); FILE MERGED 2006/10/31 14:05:51 pjanik 1.6.32.1: #i71027#: prevent warnings on Mac OS X with gcc 4.0.1.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: comboboxtoolbarcontroller.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2006-11-21 17:21:28 $
*
* 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_framework.hxx"
#ifndef __FRAMEWORK_UIELEMENT_COMBOBOXTOOLBARCONTROLLER_HXX
#include "uielement/comboboxtoolbarcontroller.hxx"
#endif
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <vcl/toolbox.hxx>
#include <vcl/combobox.hxx>
#include <tools/urlobj.hxx>
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;
namespace framework
{
// ------------------------------------------------------------------
// Wrapper class to notify controller about events from combobox.
// Unfortunaltly the events are notifed through virtual methods instead
// of Listeners.
class ComboBoxControl : public ComboBox
{
public:
ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener );
virtual ~ComboBoxControl();
virtual void Select();
virtual void DoubleClick();
virtual void Modify();
virtual void KeyInput( const ::KeyEvent& rKEvt );
virtual void GetFocus();
virtual void LoseFocus();
virtual long PreNotify( NotifyEvent& rNEvt );
private:
IComboBoxListener* m_pComboBoxListener;
};
ComboBoxControl::ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener ) :
ComboBox( pParent, nStyle )
, m_pComboBoxListener( pComboBoxListener )
{
}
ComboBoxControl::~ComboBoxControl()
{
m_pComboBoxListener = 0;
}
void ComboBoxControl::Select()
{
ComboBox::Select();
if ( m_pComboBoxListener )
m_pComboBoxListener->Select();
}
void ComboBoxControl::DoubleClick()
{
ComboBox::DoubleClick();
if ( m_pComboBoxListener )
m_pComboBoxListener->DoubleClick();
}
void ComboBoxControl::Modify()
{
ComboBox::Modify();
if ( m_pComboBoxListener )
m_pComboBoxListener->Modify();
}
void ComboBoxControl::KeyInput( const ::KeyEvent& rKEvt )
{
ComboBox::KeyInput( rKEvt );
if ( m_pComboBoxListener )
m_pComboBoxListener->KeyInput( rKEvt );
}
void ComboBoxControl::GetFocus()
{
ComboBox::GetFocus();
if ( m_pComboBoxListener )
m_pComboBoxListener->GetFocus();
}
void ComboBoxControl::LoseFocus()
{
ComboBox::LoseFocus();
if ( m_pComboBoxListener )
m_pComboBoxListener->LoseFocus();
}
long ComboBoxControl::PreNotify( NotifyEvent& rNEvt )
{
long nRet( 0 );
if ( m_pComboBoxListener )
nRet = m_pComboBoxListener->PreNotify( rNEvt );
if ( nRet == 0 )
nRet = ComboBox::PreNotify( rNEvt );
return nRet;
}
// ------------------------------------------------------------------
ComboboxToolbarController::ComboboxToolbarController(
const Reference< XMultiServiceFactory >& rServiceManager,
const Reference< XFrame >& rFrame,
ToolBar* pToolbar,
USHORT nID,
sal_Int32 nWidth,
const OUString& aCommand ) :
ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )
, m_pComboBox( 0 )
{
m_pComboBox = new ComboBoxControl( m_pToolbar, WB_DROPDOWN, this );
if ( nWidth == 0 )
nWidth = 100;
// default dropdown size
::Size aLogicalSize( 8, 160 );
::Size aPixelSize = m_pComboBox->LogicToPixel( aLogicalSize, MAP_APPFONT );
m_pComboBox->SetSizePixel( ::Size( nWidth, aPixelSize.Height() ));
m_pToolbar->SetItemWindow( m_nID, m_pComboBox );
m_pComboBox->SetDropDownLineCount( 5 );
}
// ------------------------------------------------------------------
ComboboxToolbarController::~ComboboxToolbarController()
{
}
// ------------------------------------------------------------------
void SAL_CALL ComboboxToolbarController::dispose()
throw ( RuntimeException )
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
m_pToolbar->SetItemWindow( m_nID, 0 );
delete m_pComboBox;
ComplexToolbarController::dispose();
m_pComboBox = 0;
}
// ------------------------------------------------------------------
void SAL_CALL ComboboxToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
Reference< XDispatch > xDispatch;
Reference< XURLTransformer > xURLTransformer;
OUString aCommandURL;
OUString aSelectedText;
::com::sun::star::util::URL aTargetURL;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
if ( m_bDisposed )
throw DisposedException();
if ( m_bInitialized &&
m_xFrame.is() &&
m_xServiceManager.is() &&
m_aCommandURL.getLength() )
{
xURLTransformer = m_xURLTransformer;
xDispatch = getDispatchFromCommand( m_aCommandURL );
aCommandURL = m_aCommandURL;
aTargetURL = getInitializedURL();
aSelectedText = m_pComboBox->GetText();
}
}
if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
{
Sequence<PropertyValue> aArgs( 2 );
// Add key modifier to argument list
aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
aArgs[0].Value <<= KeyModifier;
aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
aArgs[1].Value <<= aSelectedText;
// Execute dispatch asynchronously
ExecuteInfo* pExecuteInfo = new ExecuteInfo;
pExecuteInfo->xDispatch = xDispatch;
pExecuteInfo->aTargetURL = aTargetURL;
pExecuteInfo->aArgs = aArgs;
Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
}
}
// ------------------------------------------------------------------
void ComboboxToolbarController::Select()
{
if ( m_pComboBox->GetEntryCount() > 0 )
{
Window::PointerState aState = m_pComboBox->GetPointerState();
sal_uInt16 nKeyModifier = sal_uInt16( aState.mnState & KEY_MODTYPE );
execute( nKeyModifier );
}
}
void ComboboxToolbarController::DoubleClick()
{
}
void ComboboxToolbarController::Modify()
{
notifyTextChanged( m_pComboBox->GetText() );
}
void ComboboxToolbarController::KeyInput( const ::KeyEvent& )
{
}
void ComboboxToolbarController::GetFocus()
{
notifyFocusGet();
}
void ComboboxToolbarController::LoseFocus()
{
notifyFocusLost();
}
long ComboboxToolbarController::PreNotify( NotifyEvent& rNEvt )
{
if( rNEvt.GetType() == EVENT_KEYINPUT )
{
const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();
const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();
if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )
{
// Call execute only with non-empty text
if ( m_pComboBox->GetText().Len() > 0 )
execute( rKeyCode.GetModifier() );
return 1;
}
}
return 0;
}
// --------------------------------------------------------
void ComboboxToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
if ( rControlCommand.Command.equalsAsciiL( "SetText", 7 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
rtl::OUString aText;
rControlCommand.Arguments[i].Value >>= aText;
m_pComboBox->SetText( aText );
// send notification
notifyTextChanged( aText );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "SetList", 7 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "List", 4 ))
{
Sequence< OUString > aList;
m_pComboBox->Clear();
rControlCommand.Arguments[i].Value >>= aList;
for ( sal_Int32 j = 0; j < aList.getLength(); j++ )
m_pComboBox->InsertEntry( aList[j] );
// send notification
uno::Sequence< beans::NamedValue > aInfo( 1 );
aInfo[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "List" ));
aInfo[0].Value <<= aList;
addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ListChanged" )),
getDispatchFromCommand( m_aCommandURL ),
aInfo );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "AddEntry", 8 ))
{
sal_uInt16 nPos( COMBOBOX_APPEND );
rtl::OUString aText;
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
if ( rControlCommand.Arguments[i].Value >>= aText )
m_pComboBox->InsertEntry( aText, nPos );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "InsertEntry", 11 ))
{
sal_uInt16 nPos( COMBOBOX_APPEND );
rtl::OUString aText;
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nTmpPos = 0;
if ( rControlCommand.Arguments[i].Value >>= nTmpPos )
{
if (( nTmpPos >= 0 ) &&
( nTmpPos < sal_Int32( m_pComboBox->GetEntryCount() )))
nPos = sal_uInt16( nTmpPos );
}
}
else if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
rControlCommand.Arguments[i].Value >>= aText;
}
m_pComboBox->InsertEntry( aText, nPos );
}
else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryPos", 14 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
{
sal_Int32 nPos( -1 );
if ( rControlCommand.Arguments[i].Value >>= nPos )
{
if ( nPos < sal_Int32( m_pComboBox->GetEntryCount() ))
m_pComboBox->RemoveEntry( sal_uInt16( nPos ));
}
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryText", 15 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
{
rtl::OUString aText;
if ( rControlCommand.Arguments[i].Value >>= aText )
m_pComboBox->RemoveEntry( aText );
break;
}
}
}
else if ( rControlCommand.Command.equalsAsciiL( "SetDropDownLines", 16 ))
{
for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
{
if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Lines", 5 ))
{
sal_Int32 nValue( 5 );
rControlCommand.Arguments[i].Value >>= nValue;
m_pComboBox->SetDropDownLineCount( sal_uInt16( nValue ));
break;
}
}
}
}
} // namespace
<|endoftext|> |
<commit_before>#include "testing/testing.hpp"
#include "routing/routing_quality/waypoints.hpp"
using namespace routing_quality;
// Test on preferring better but longer roads should be grouped in this file.
namespace
{
// Secondary should be preferred against residential.
UNIT_TEST(RoutingQuality_RussiaMoscowTushino)
{
TEST(CheckCarRoute({55.84398, 37.45018} /* start */, {55.85489, 37.43784} /* finish */,
{{{55.84343, 37.43949}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_TurkeyIzmirArea)
{
TEST(CheckCarRoute({38.80146, 26.97696} /* start */, {39.0837, 26.90977} /* finish */,
{{{39.08146, 27.11798}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_BosniaAndHerzegovina)
{
TEST(CheckCarRoute({42.71401, 18.30412} /* start */, {42.95101, 18.08966} /* finish */,
{{{42.88222,17.9919}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_CzechiaPrague)
{
TEST(CheckCarRoute({50.10159, 14.43324} /* start */, {50.20976, 14.43361} /* finish */,
{{{50.15078, 14.49205}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_FinlandHelsinki)
{
TEST(CheckCarRoute({60.16741, 24.94255} /* start */, {64.13182, 28.38784} /* finish */,
{{{60.95453, 25.6951}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_USAOklahoma)
{
TEST(CheckCarRoute({35.39166, -97.55402} /* start */, {35.38452, -97.5742} /* finish */,
{{{35.39912, -97.57622}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_IranSouth)
{
TEST(CheckCarRoute({32.45088, 51.76419} /* start */, {32.97067, 51.50399} /* finish */,
{{{32.67021, 51.64323}, {32.68752, 51.63387}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_EindhovenNetherlands)
{
TEST(CheckCarRoute({50.91974, 5.33535} /* start */, {51.92532, 5.49066} /* finish */,
{{{51.42016, 5.42881}, {51.44316, 5.42723}, {51.50230, 5.47485}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_GeteborgasSweden)
{
TEST(CheckCarRoute({57.77064, 11.88079} /* start */, {57.71231, 11.93157} /* finish */,
{{{57.74912, 11.87343}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_CigilTurkey)
{
TEST(CheckCarRoute({38.48175, 27.12952} /* start */, {38.47558, 27.06765} /* finish */,
{{{38.4898049, 27.1016266}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_KatowicePoland)
{
TEST(CheckCarRoute({50.37282, 18.75667} /* start */, {50.83499, 19.14612} /* finish */,
{{{50.422229, 19.04746}, {50.48831, 19.21423}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_KrasnoyarskBratsk)
{
TEST(CheckCarRoute({56.009, 92.873} /* start */, {56.163, 101.611} /* finish */,
{{{55.89285, 97.99953}, {54.59928, 100.60402}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_VoronezhSochi)
{
TEST(CheckCarRoute({51.65487, 39.21293} /* start */, {43.58547, 39.72311} /* finish */,
{{{46.14169, 39.85306}, {45.17069, 39.10869},
{45.02157, 39.12510}, {44.54344, 38.95853}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_BerlinkaWarsawPoland)
{
TEST(CheckCarRoute({54.41616, 20.05675} /* start */, {52.18937, 20.94026} /* finish */,
{{{54.24278, 19.66106}, {54.13679, 19.45166},
{54.06452, 19.62416}, {53.69769, 19.98204},
{53.11194, 20.40002}, {52.62966, 20.38488}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_LenOblBadPaving)
{
TEST(CheckCarRoute({60.23884, 29.71603} /* start */, {60.29083, 29.80333} /* finish */,
{{{60.2510134, 29.790209}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_MosOblBadPaving)
{
TEST(CheckCarRoute({55.93849, 36.02792} /* start */, {55.93566, 36.05074} /* finish */,
{{{55.92321, 36.04630}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_LatviaUnpaved)
{
TEST(CheckCarRoute({56.62992, 25.77175} /* start */, {56.61453, 25.78400} /* finish */,
{{{56.62377, 25.81015}, {56.61755, 25.80894}}} /* reference track */),
());
}
} // namespace
<commit_msg>[routing] routing quality tests fixes.<commit_after>#include "testing/testing.hpp"
#include "routing/routing_quality/waypoints.hpp"
using namespace routing_quality;
// Test on preferring better but longer roads should be grouped in this file.
namespace
{
// Secondary should be preferred against residential.
UNIT_TEST(RoutingQuality_RussiaMoscowTushino)
{
TEST(CheckCarRoute({55.84398, 37.45018} /* start */, {55.85489, 37.43784} /* finish */,
{{{55.84343, 37.43949}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_TurkeyIzmirArea)
{
TEST(CheckCarRoute({38.80146, 26.97696} /* start */, {39.0837, 26.90977} /* finish */,
{{{39.08146, 27.11798}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_BosniaAndHerzegovina)
{
TEST(CheckCarRoute({42.71401, 18.30412} /* start */, {42.95101, 18.08966} /* finish */,
{{{42.88222,17.9919}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_CzechiaPrague)
{
TEST(CheckCarRoute({50.10159, 14.43324} /* start */, {50.20976, 14.43361} /* finish */,
{{{50.15078, 14.49205}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_FinlandHelsinki)
{
TEST(CheckCarRoute({60.16741, 24.94255} /* start */, {64.13182, 28.38784} /* finish */,
{{{60.95453, 25.6951}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_USAOklahoma)
{
TEST(CheckCarRoute({35.39166, -97.55402} /* start */, {35.38452, -97.5742} /* finish */,
{{{35.39912, -97.57622}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_IranSouth)
{
TEST(CheckCarRoute({32.45088, 51.76419} /* start */, {32.97067, 51.50399} /* finish */,
{{{32.67021, 51.64323}, {32.68752, 51.63387}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_EindhovenNetherlands)
{
TEST(CheckCarRoute({50.91974, 5.33535} /* start */, {51.92532, 5.49066} /* finish */,
{{{51.42016, 5.42881}, {51.44316, 5.42723}, {51.50230, 5.47485}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_GeteborgasSweden)
{
TEST(CheckCarRoute({57.77064, 11.88079} /* start */, {57.71231, 11.93157} /* finish */,
{{{57.74912, 11.87343}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_CigilTurkey)
{
TEST(CheckCarRoute({38.48175, 27.12952} /* start */, {38.47558, 27.06765} /* finish */,
{{{38.4898049, 27.1016266}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_KatowicePoland)
{
TEST(CheckCarRoute({50.37282, 18.75667} /* start */, {50.83499, 19.14612} /* finish */,
{{{50.422229, 19.04746}, {50.48831, 19.21423}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_KrasnoyarskBratsk)
{
TEST(CheckCarRoute({56.009, 92.873} /* start */, {56.163, 101.611} /* finish */,
{{{55.89285, 97.99953}, {54.59928, 100.60402}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_VoronezhSochi)
{
TEST(CheckCarRoute({51.65487, 39.21293} /* start */, {43.58547, 39.72311} /* finish */,
{{{46.14169, 39.85306}, {45.17069, 39.10869},
{45.02157, 39.12510}, {44.54344, 38.95853}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_BerlinkaWarsawPoland)
{
TEST(CheckCarRoute({54.41616, 20.05675} /* start */, {52.18937, 20.94026} /* finish */,
{{{54.24278, 19.66106}, {54.13679, 19.45166},
{54.06452, 19.62416}, {53.69769, 19.98204},
{53.11194, 20.40002}, {52.62966, 20.38488}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_LenOblBadPaving)
{
TEST(CheckCarRoute({60.23884, 29.71603} /* start */, {60.29083, 29.80333} /* finish */,
{{{60.2510134, 29.790209}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_MosOblBadPaving)
{
TEST(CheckCarRoute({55.93849, 36.02792} /* start */, {55.93567, 36.0533} /* finish */,
{{{55.92321, 36.04630}}} /* reference track */),
());
}
UNIT_TEST(RoutingQuality_LatviaUnpaved)
{
TEST(CheckCarRoute({56.62992, 25.77175} /* start */, {56.61453, 25.78400} /* finish */,
{{{56.62377, 25.81015}, {56.61755, 25.80894}}} /* reference track */),
());
}
} // namespace
<|endoftext|> |
<commit_before>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QI_EXECUTION_CONTEXT_HPP_
#define _QI_EXECUTION_CONTEXT_HPP_
#include <boost/function.hpp>
#include <qi/clock.hpp>
#include <qi/api.hpp>
namespace qi
{
template <typename T>
class Future;
namespace detail
{
// This class is kind of a hack to deprecate the old versions of async/post etc without deprecating the correct use of
// the new ones. This class is just a strong alias to boost::function
template <typename T>
struct Function : boost::function<T>
{
using boost::function<T>::function;
};
}
class QI_API ExecutionContext
{
public:
virtual ~ExecutionContext() {}
// DEPRECATED STUFF
/// call a callback asynchronously to be executed on tp
/// @deprecated since 2.5
QI_API_DEPRECATED virtual qi::Future<void> async(const boost::function<void()>& callback,
qi::SteadyClockTimePoint tp) = 0;
/// call a callback asynchronously to be executed in delay
/// @deprecated since 2.5
QI_API_DEPRECATED virtual qi::Future<void> async(const boost::function<void()>& callback,
qi::Duration delay) = 0;
/// call a callback asynchronously to be executed in delay
/// @deprecated since 2.5
template <typename R>
QI_API_DEPRECATED typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
async(const boost::function<R()>& callback,
qi::Duration delay);
/// call a callback asynchronously to be executed on tp
/// @deprecated since 2.5
template <typename R>
QI_API_DEPRECATED typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
async(const boost::function<R()>& callback, qi::SteadyClockTimePoint tp);
/// @deprecated since 2.5
template <typename R>
QI_API_DEPRECATED qi::Future<R> async(const detail::Function<R()>& callback)
{
return asyncDelay(callback, qi::Duration(0));
}
// END OF DEPRECATED STUFF
/// post a callback to be executed as soon as possible
template <typename F>
void post(F&& callback);
/// call a callback asynchronously to be executed on tp
template <typename F>
auto asyncAt(F&& callback, qi::SteadyClockTimePoint tp) -> qi::Future<typename std::decay<decltype(callback())>::type>;
/// call a callback asynchronously to be executed in delay
template <typename F>
auto asyncDelay(F&& callback, qi::Duration delay) -> qi::Future<typename std::decay<decltype(callback())>::type>;
template <typename F>
auto async(F&& callback) -> decltype(asyncDelay(std::forward<F>(callback), qi::Duration(0)))
{
return asyncDelay(std::forward<F>(callback), qi::Duration(0));
}
/// return true if the current thread is in this context
virtual bool isInThisContext() = 0;
protected:
virtual void postImpl(boost::function<void()> callback) = 0;
virtual qi::Future<void> asyncAtImpl(boost::function<void()> cb, qi::SteadyClockTimePoint tp) = 0;
virtual qi::Future<void> asyncDelayImpl(boost::function<void()> cb, qi::Duration delay) = 0;
};
}
#include <qi/detail/future_fwd.hpp>
namespace qi
{
namespace detail
{
template <typename T>
class DelayedPromise: public Promise<T>
{
public:
void setup(boost::function<void (qi::Promise<T>)> cancelCallback, FutureCallbackType async = FutureCallbackType_Async)
{
Promise<T>::setup(cancelCallback, async);
}
};
template <typename R>
void setValue(qi::Promise<R>& p, const boost::function<R()>& f)
{
p.setValue(f());
}
template <>
inline void setValue<void>(qi::Promise<void>& p, const boost::function<void()>& f)
{
f();
p.setValue(0);
}
template <typename R>
void callAndSet(qi::Promise<R> p, boost::function<R()> f)
{
try
{
setValue<R>(p, f);
}
catch (const std::exception& e)
{
p.setError(e.what());
}
catch(...)
{
p.setError("unknown exception");
}
}
template <typename R>
void checkCanceled(qi::Future<void> f, qi::Promise<R> p)
{
if (f.wait() == FutureState_Canceled)
p.setCanceled();
// Nothing to do for other states.
}
}
template <typename R>
typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
ExecutionContext::async(const boost::function<R()>& callback,
qi::Duration delay)
{
detail::DelayedPromise<R> promise;
qi::Future<void> f = async(boost::function<void()>(boost::bind(
detail::callAndSet<R>, promise, callback)),
delay);
promise.setup(
boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<R>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename R>
typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
ExecutionContext::async(const boost::function<R()>& callback,
qi::SteadyClockTimePoint tp)
{
detail::DelayedPromise<R> promise;
qi::Future<void> f = async(boost::function<void()>(boost::bind(
detail::callAndSet<R>, promise, callback)),
tp);
promise.setup(
boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<R>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename F>
void ExecutionContext::post(F&& callback)
{
postImpl(std::forward<F>(callback));
}
template <typename ReturnType, typename Callback>
struct ToPost
{
detail::DelayedPromise<ReturnType> promise;
Callback callback;
ToPost(Callback cb) :
callback(std::move(cb))
{}
void operator()()
{
detail::callAndSet<ReturnType>(std::move(promise), std::move(callback));
}
};
template <typename F>
auto ExecutionContext::asyncAt(F&& callback, qi::SteadyClockTimePoint tp) -> qi::Future<typename std::decay<decltype(callback())>::type>
{
using ReturnType = typename std::decay<decltype(callback())>::type;
ToPost<ReturnType, typename std::decay<F>::type> topost(std::move(callback));
auto promise = topost.promise;
qi::Future<void> f = asyncAtImpl(std::move(topost), tp);
promise.setup(boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<ReturnType>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename F>
auto ExecutionContext::asyncDelay(F&& callback, qi::Duration delay) -> qi::Future<typename std::decay<decltype(callback())>::type>
{
using ReturnType = typename std::decay<decltype(callback())>::type;
ToPost<ReturnType, typename std::decay<F>::type> topost(std::move(callback));
auto promise = topost.promise;
qi::Future<void> f = asyncDelayImpl(std::move(topost), delay);
promise.setup(boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<ReturnType>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
}
#endif
<commit_msg>Fixed: vs2013 does not manage using directive with parent type constr.<commit_after>#pragma once
/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#ifndef _QI_EXECUTION_CONTEXT_HPP_
#define _QI_EXECUTION_CONTEXT_HPP_
#include <boost/function.hpp>
#include <qi/clock.hpp>
#include <qi/api.hpp>
namespace qi
{
template <typename T>
class Future;
namespace detail
{
// This class is kind of a hack to deprecate the old versions of async/post etc without deprecating the correct use of
// the new ones. This class is just a strong alias to boost::function
template <typename T>
struct Function : boost::function<T>
{
template<class... Args>
Function(Args&&... args)
: boost::function<T>(std::forward<Args>(args)...)
{}
};
}
class QI_API ExecutionContext
{
public:
virtual ~ExecutionContext() {}
// DEPRECATED STUFF
/// call a callback asynchronously to be executed on tp
/// @deprecated since 2.5
QI_API_DEPRECATED virtual qi::Future<void> async(const boost::function<void()>& callback,
qi::SteadyClockTimePoint tp) = 0;
/// call a callback asynchronously to be executed in delay
/// @deprecated since 2.5
QI_API_DEPRECATED virtual qi::Future<void> async(const boost::function<void()>& callback,
qi::Duration delay) = 0;
/// call a callback asynchronously to be executed in delay
/// @deprecated since 2.5
template <typename R>
QI_API_DEPRECATED typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
async(const boost::function<R()>& callback,
qi::Duration delay);
/// call a callback asynchronously to be executed on tp
/// @deprecated since 2.5
template <typename R>
QI_API_DEPRECATED typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
async(const boost::function<R()>& callback, qi::SteadyClockTimePoint tp);
/// @deprecated since 2.5
template <typename R>
QI_API_DEPRECATED qi::Future<R> async(const detail::Function<R()>& callback)
{
return asyncDelay(callback, qi::Duration(0));
}
// END OF DEPRECATED STUFF
/// post a callback to be executed as soon as possible
template <typename F>
void post(F&& callback);
/// call a callback asynchronously to be executed on tp
template <typename F>
auto asyncAt(F&& callback, qi::SteadyClockTimePoint tp) -> qi::Future<typename std::decay<decltype(callback())>::type>;
/// call a callback asynchronously to be executed in delay
template <typename F>
auto asyncDelay(F&& callback, qi::Duration delay) -> qi::Future<typename std::decay<decltype(callback())>::type>;
template <typename F>
auto async(F&& callback) -> decltype(asyncDelay(std::forward<F>(callback), qi::Duration(0)))
{
return asyncDelay(std::forward<F>(callback), qi::Duration(0));
}
/// return true if the current thread is in this context
virtual bool isInThisContext() = 0;
protected:
virtual void postImpl(boost::function<void()> callback) = 0;
virtual qi::Future<void> asyncAtImpl(boost::function<void()> cb, qi::SteadyClockTimePoint tp) = 0;
virtual qi::Future<void> asyncDelayImpl(boost::function<void()> cb, qi::Duration delay) = 0;
};
}
#include <qi/detail/future_fwd.hpp>
namespace qi
{
namespace detail
{
template <typename T>
class DelayedPromise: public Promise<T>
{
public:
void setup(boost::function<void (qi::Promise<T>)> cancelCallback, FutureCallbackType async = FutureCallbackType_Async)
{
Promise<T>::setup(cancelCallback, async);
}
};
template <typename R>
void setValue(qi::Promise<R>& p, const boost::function<R()>& f)
{
p.setValue(f());
}
template <>
inline void setValue<void>(qi::Promise<void>& p, const boost::function<void()>& f)
{
f();
p.setValue(0);
}
template <typename R>
void callAndSet(qi::Promise<R> p, boost::function<R()> f)
{
try
{
setValue<R>(p, f);
}
catch (const std::exception& e)
{
p.setError(e.what());
}
catch(...)
{
p.setError("unknown exception");
}
}
template <typename R>
void checkCanceled(qi::Future<void> f, qi::Promise<R> p)
{
if (f.wait() == FutureState_Canceled)
p.setCanceled();
// Nothing to do for other states.
}
}
template <typename R>
typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
ExecutionContext::async(const boost::function<R()>& callback,
qi::Duration delay)
{
detail::DelayedPromise<R> promise;
qi::Future<void> f = async(boost::function<void()>(boost::bind(
detail::callAndSet<R>, promise, callback)),
delay);
promise.setup(
boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<R>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename R>
typename boost::disable_if<boost::is_same<R, void>,
qi::Future<R> >::type
ExecutionContext::async(const boost::function<R()>& callback,
qi::SteadyClockTimePoint tp)
{
detail::DelayedPromise<R> promise;
qi::Future<void> f = async(boost::function<void()>(boost::bind(
detail::callAndSet<R>, promise, callback)),
tp);
promise.setup(
boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<R>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename F>
void ExecutionContext::post(F&& callback)
{
postImpl(std::forward<F>(callback));
}
template <typename ReturnType, typename Callback>
struct ToPost
{
detail::DelayedPromise<ReturnType> promise;
Callback callback;
ToPost(Callback cb) :
callback(std::move(cb))
{}
void operator()()
{
detail::callAndSet<ReturnType>(std::move(promise), std::move(callback));
}
};
template <typename F>
auto ExecutionContext::asyncAt(F&& callback, qi::SteadyClockTimePoint tp) -> qi::Future<typename std::decay<decltype(callback())>::type>
{
using ReturnType = typename std::decay<decltype(callback())>::type;
ToPost<ReturnType, typename std::decay<F>::type> topost(std::move(callback));
auto promise = topost.promise;
qi::Future<void> f = asyncAtImpl(std::move(topost), tp);
promise.setup(boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<ReturnType>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
template <typename F>
auto ExecutionContext::asyncDelay(F&& callback, qi::Duration delay) -> qi::Future<typename std::decay<decltype(callback())>::type>
{
using ReturnType = typename std::decay<decltype(callback())>::type;
ToPost<ReturnType, typename std::decay<F>::type> topost(std::move(callback));
auto promise = topost.promise;
qi::Future<void> f = asyncDelayImpl(std::move(topost), delay);
promise.setup(boost::bind(&detail::futureCancelAdapter<void>,
boost::weak_ptr<detail::FutureBaseTyped<void> >(f.impl())));
f.connect(boost::bind(&detail::checkCanceled<ReturnType>, _1, promise), FutureCallbackType_Sync);
return promise.future();
}
}
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2010 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include "libforestdb/forestdb.h"
#include "common.h"
#include "internal_types.h"
#include "btree_var_kv_ops.h"
#include "hbtrie.h"
#include "fdb_internal.h"
#include "memleak.h"
#ifdef __DEBUG
#ifndef __DEBUG_FDB
#undef DBG
#undef DBGCMD
#undef DBGSW
#define DBG(...)
#define DBGCMD(...)
#define DBGSW(n, ...)
#endif
#endif
LIBFDB_API
fdb_status fdb_get_kv(FdbKvsHandle *handle,
const void *key, size_t keylen,
void **value_out, size_t *valuelen_out)
{
fdb_doc *doc = NULL;
fdb_status fs;
if (key == NULL || keylen == 0 || keylen > FDB_MAX_KEYLEN ||
value_out == NULL || valuelen_out == NULL ||
(handle->kvs_config.custom_cmp &&
keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
return FDB_RESULT_INVALID_ARGS;
}
fs = fdb_doc_create(&doc, key, keylen, NULL, 0, NULL, 0);
if (fs != FDB_RESULT_SUCCESS) { // LCOV_EXCL_START
if (doc) {
fdb_doc_free(doc);
}
fdb_log(&handle->log_callback, fs,
"Warning: Failed to allocate fdb_doc instance for key '%s' in "
"fdb_get_kv API.", (const char *)key);
return fs;
} // LCOV_EXCL_STOP
fs = fdb_get(handle, doc);
if (fs != FDB_RESULT_SUCCESS) {
if (doc) {
fdb_doc_free(doc);
}
return fs;
}
*value_out = doc->body;
*valuelen_out = doc->bodylen;
if (doc->key) free(doc->key);
if (doc->meta) free(doc->meta);
free(doc);
return fs;
}
LIBFDB_API
fdb_status fdb_set_kv(FdbKvsHandle *handle,
const void *key, size_t keylen,
const void *value, size_t valuelen)
{
fdb_doc *doc;
fdb_status fs;
if (key == NULL || keylen == 0 || keylen > FDB_MAX_KEYLEN ||
(handle->kvs_config.custom_cmp &&
keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
return FDB_RESULT_INVALID_ARGS;
}
fs = fdb_doc_create(&doc, key, keylen, NULL, 0, value, valuelen);
if (fs != FDB_RESULT_SUCCESS) { // LCOV_EXCL_START
if (doc) {
fdb_doc_free(doc);
}
fdb_log(&handle->log_callback, fs,
"Warning: Failed to allocate fdb_doc instance for key '%s' in "
"fdb_set_kv API.", (const char *)key);
return fs;
} // LCOV_EXCL_STOP
fs = fdb_set(handle, doc);
if (fs != FDB_RESULT_SUCCESS) {
if (doc) {
fdb_doc_free(doc);
}
return fs;
}
fdb_doc_free(doc);
return fs;
}
LIBFDB_API
fdb_status fdb_del_kv(FdbKvsHandle *handle,
const void *key, size_t keylen)
{
fdb_doc *doc;
fdb_status fs;
if (key == NULL || keylen == 0 || keylen > FDB_MAX_KEYLEN ||
(handle->kvs_config.custom_cmp &&
keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
return FDB_RESULT_INVALID_ARGS;
}
fs = fdb_doc_create(&doc, key, keylen, NULL, 0, NULL, 0);
if (fs != FDB_RESULT_SUCCESS) { // LCOV_EXCL_START
if (doc) {
fdb_doc_free(doc);
}
fdb_log(&handle->log_callback, fs,
"Warning: Failed to allocate fdb_doc instance for key '%s' in "
"fdb_del_kv API.", (const char *)key);
return fs;
} // LCOV_EXCL_STOP
fs = fdb_del(handle, doc);
if (fs != FDB_RESULT_SUCCESS) {
fdb_doc_free(doc);
return fs;
}
fdb_doc_free(doc);
return fs;
}
LIBFDB_API
fdb_status fdb_free_block(void *ptr)
{
free(ptr);
return FDB_RESULT_SUCCESS;
}
<commit_msg>Protect api_wrappers from INVALID_HANDLE error<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2010 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include "libforestdb/forestdb.h"
#include "common.h"
#include "internal_types.h"
#include "btree_var_kv_ops.h"
#include "hbtrie.h"
#include "fdb_internal.h"
#include "memleak.h"
#ifdef __DEBUG
#ifndef __DEBUG_FDB
#undef DBG
#undef DBGCMD
#undef DBGSW
#define DBG(...)
#define DBGCMD(...)
#define DBGSW(n, ...)
#endif
#endif
LIBFDB_API
fdb_status fdb_get_kv(FdbKvsHandle *handle,
const void *key, size_t keylen,
void **value_out, size_t *valuelen_out)
{
if (!handle) {
return FDB_RESULT_INVALID_HANDLE;
}
fdb_doc *doc = NULL;
fdb_status fs;
if (key == NULL || keylen == 0 || keylen > FDB_MAX_KEYLEN ||
value_out == NULL || valuelen_out == NULL ||
(handle->kvs_config.custom_cmp &&
keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
return FDB_RESULT_INVALID_ARGS;
}
fs = fdb_doc_create(&doc, key, keylen, NULL, 0, NULL, 0);
if (fs != FDB_RESULT_SUCCESS) { // LCOV_EXCL_START
if (doc) {
fdb_doc_free(doc);
}
fdb_log(&handle->log_callback, fs,
"Warning: Failed to allocate fdb_doc instance for key '%s' in "
"fdb_get_kv API.", (const char *)key);
return fs;
} // LCOV_EXCL_STOP
fs = fdb_get(handle, doc);
if (fs != FDB_RESULT_SUCCESS) {
if (doc) {
fdb_doc_free(doc);
}
return fs;
}
*value_out = doc->body;
*valuelen_out = doc->bodylen;
if (doc->key) free(doc->key);
if (doc->meta) free(doc->meta);
free(doc);
return fs;
}
LIBFDB_API
fdb_status fdb_set_kv(FdbKvsHandle *handle,
const void *key, size_t keylen,
const void *value, size_t valuelen)
{
if (!handle) {
return FDB_RESULT_INVALID_HANDLE;
}
fdb_doc *doc;
fdb_status fs;
if (key == NULL || keylen == 0 || keylen > FDB_MAX_KEYLEN ||
(handle->kvs_config.custom_cmp &&
keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
return FDB_RESULT_INVALID_ARGS;
}
fs = fdb_doc_create(&doc, key, keylen, NULL, 0, value, valuelen);
if (fs != FDB_RESULT_SUCCESS) { // LCOV_EXCL_START
if (doc) {
fdb_doc_free(doc);
}
fdb_log(&handle->log_callback, fs,
"Warning: Failed to allocate fdb_doc instance for key '%s' in "
"fdb_set_kv API.", (const char *)key);
return fs;
} // LCOV_EXCL_STOP
fs = fdb_set(handle, doc);
if (fs != FDB_RESULT_SUCCESS) {
if (doc) {
fdb_doc_free(doc);
}
return fs;
}
fdb_doc_free(doc);
return fs;
}
LIBFDB_API
fdb_status fdb_del_kv(FdbKvsHandle *handle,
const void *key, size_t keylen)
{
if (!handle) {
return FDB_RESULT_INVALID_HANDLE;
}
fdb_doc *doc;
fdb_status fs;
if (key == NULL || keylen == 0 || keylen > FDB_MAX_KEYLEN ||
(handle->kvs_config.custom_cmp &&
keylen > handle->config.blocksize - HBTRIE_HEADROOM)) {
return FDB_RESULT_INVALID_ARGS;
}
fs = fdb_doc_create(&doc, key, keylen, NULL, 0, NULL, 0);
if (fs != FDB_RESULT_SUCCESS) { // LCOV_EXCL_START
if (doc) {
fdb_doc_free(doc);
}
fdb_log(&handle->log_callback, fs,
"Warning: Failed to allocate fdb_doc instance for key '%s' in "
"fdb_del_kv API.", (const char *)key);
return fs;
} // LCOV_EXCL_STOP
fs = fdb_del(handle, doc);
if (fs != FDB_RESULT_SUCCESS) {
fdb_doc_free(doc);
return fs;
}
fdb_doc_free(doc);
return fs;
}
LIBFDB_API
fdb_status fdb_free_block(void *ptr)
{
free(ptr);
return FDB_RESULT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "contexttyperegistryinfo.h"
#include "logging.h"
#include "loggingfeatures.h"
#include <QMutex>
#include <QMutexLocker>
#include <QCoreApplication>
#include "nanoxml.h"
ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = NULL;
/* Public */
ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance()
{
static QMutex mutex;
QMutexLocker locker(&mutex);
if (! registryInstance) {
contextDebug() << F_TYPES << "Creating ContextTypeRegistryInfo instance";
registryInstance = new ContextTypeRegistryInfo;
// Move the backend to the main thread
registryInstance->moveToThread(QCoreApplication::instance()->thread());
}
return registryInstance;
}
/// Returns the full path to the registry directory. Takes the
/// \c CONTEXT_TYPES env variable into account.
QString ContextTypeRegistryInfo::registryPath()
{
const char *regpath = getenv("CONTEXT_TYPES");
if (! regpath)
regpath = DEFAULT_CONTEXT_TYPES;
return QString(regpath);
}
/// Returns the full path to the core property declaration file. Takes
/// the \c CONTEXT_CORE_TYPES env variable into account.
QString ContextTypeRegistryInfo::coreTypesPath()
{
const char *corepath = getenv("CONTEXT_CORE_TYPES");
if (! corepath)
corepath = DEFAULT_CONTEXT_CORE_TYPES;
return QString(corepath);
}
/* Private */
ContextTypeRegistryInfo::ContextTypeRegistryInfo()
{
contextDebug() << F_TYPES << "Reading core types from:" << ContextTypeRegistryInfo::coreTypesPath();
NanoXml parser(ContextTypeRegistryInfo::coreTypesPath());
if (parser.didFail())
contextWarning() << F_TYPES << "Reading core types failed, parsing error";
else
coreTree = parser.result();
}
<commit_msg>Revert "Read core types in constructor."<commit_after>/*
* Copyright (C) 2008 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "contexttyperegistryinfo.h"
#include "logging.h"
#include "loggingfeatures.h"
#include <QMutex>
#include <QMutexLocker>
#include <QCoreApplication>
#include "nanoxml.h"
ContextTypeRegistryInfo* ContextTypeRegistryInfo::registryInstance = NULL;
/* Public */
ContextTypeRegistryInfo* ContextTypeRegistryInfo::instance()
{
static QMutex mutex;
QMutexLocker locker(&mutex);
if (! registryInstance) {
contextDebug() << F_TYPES << "Creating ContextTypeRegistryInfo instance";
registryInstance = new ContextTypeRegistryInfo;
// Move the backend to the main thread
registryInstance->moveToThread(QCoreApplication::instance()->thread());
}
return registryInstance;
}
/// Returns the full path to the registry directory. Takes the
/// \c CONTEXT_TYPES env variable into account.
QString ContextTypeRegistryInfo::registryPath()
{
const char *regpath = getenv("CONTEXT_TYPES");
if (! regpath)
regpath = DEFAULT_CONTEXT_TYPES;
return QString(regpath);
}
/// Returns the full path to the core property declaration file. Takes
/// the \c CONTEXT_CORE_TYPES env variable into account.
QString ContextTypeRegistryInfo::coreTypesPath()
{
const char *corepath = getenv("CONTEXT_CORE_TYPES");
if (! corepath)
corepath = DEFAULT_CONTEXT_CORE_TYPES;
return QString(corepath);
}
/* Private */
ContextTypeRegistryInfo::ContextTypeRegistryInfo()
{
}
<|endoftext|> |
<commit_before>#include "resizeHandler.h"
#include <algorithm>
ResizeHandler::ResizeHandler(
NodeElement* const resizingNode
, ElementImpl* const elementImpl
)
: mResizingNode(resizingNode)
, mElementImpl(elementImpl)
{
}
void ResizeHandler::resize(QRectF newContents, QPointF newPos) const
{
newContents.moveTo(0, 0);
sortChildrenIfNeeded();
gripeIfMinimizesToChildrenContainer(newContents);
QRectF con = newContents;
if (!mResizingNode->isFolded()) {
resizeAccordingToChildren(newContents, newPos);
}
normalizeSize(newContents);
newContents.moveTo(newPos);
mResizingNode->setGeometry(newContents);
mResizingNode->storeGeometry();
parentResizeCall();
/*
if (SettingsManager::value("ActivateGrid").toBool()) {
mResizingNode->alignToGrid();
}
*/
}
qreal ResizeHandler::maxChildWidth() const
{
qreal maxChildWidthValue = 0;
foreach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {
const NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);
if (!curItem) {
continue;
}
maxChildWidthValue = qMax(maxChildWidthValue, curItem->contentsRect().width());
}
if (maxChildWidthValue == 0) {
maxChildWidthValue = mResizingNode->childrenBoundingRect().width();
}
return maxChildWidthValue;
}
void ResizeHandler::sortChildrenIfNeeded() const
{
if (!mElementImpl->isSortingContainer()) {
return;
}
int const sizeOfForestalling = mElementImpl->sizeOfForestalling();
qreal curChildY = sizeOfForestalling + mTitlePadding;
qreal const maxChildWidthValue = maxChildWidth();
foreach (QGraphicsItem* const childItem, mResizingNode->childItems()) {
QGraphicsRectItem* const placeholder = mResizingNode->placeholder();
if(placeholder != NULL && childItem == placeholder) {
QRectF const rect(sizeOfForestalling, curChildY,
maxChildWidthValue, placeholder->rect().height());
placeholder->setRect(rect);
curChildY += placeholder->rect().height() + mChildSpacing;
}
NodeElement* const curItem = dynamic_cast<NodeElement* const>(childItem);
if (!curItem) {
continue;
}
qreal const necessaryWidth =
mElementImpl->maximizesChildren()
? maxChildWidthValue
: curItem->contentsRect().width();
QRectF const rect(sizeOfForestalling, curChildY, necessaryWidth, curItem->contentsRect().height());
curItem->setGeometry(rect);
curItem->storeGeometry();
curChildY += curItem->contentsRect().height() + mElementImpl->sizeOfChildrenForestalling() + mChildSpacing;
}
}
void ResizeHandler::gripeIfMinimizesToChildrenContainer(QRectF& contents) const
{
if (mElementImpl->minimizesToChildren()) {
contents = QRectF();
}
}
void ResizeHandler::parentResizeCall() const
{
NodeElement* const parItem = dynamic_cast<NodeElement* const>(mResizingNode->parentItem());
if (parItem) {
ResizeHandler const handler(parItem, parItem->elementImpl());
handler.resize(parItem->contentsRect(), parItem->pos());
}
}
void ResizeHandler::normalizeSize(QRectF& newContents) const
{
if (newContents.width() < mMinSize) {
newContents.setWidth(mResizingNode->foldedContentsRect().width());
}
if (newContents.height() < mMinSize) {
newContents.setHeight(mResizingNode->foldedContentsRect().height());
}
}
void ResizeHandler::resizeAccordingToChildren(QRectF& newContents, QPointF& newPos) const
{
/*
* AAAA!!! Who knows why is this code existed????!!!
*
foreach (QGraphicsItem *childItem, childItems()) {
NodeElement* curItem = dynamic_cast<NodeElement*>(childItem);
if (curItem && curItem->isPort() && newContents != mContents) {
curItem->resizeChild(newContents, mContents);
}
}
*/
/// Vector of minimum negative XY child deflection from top left corner.
QPointF const childDeflectionVector = childDeflection();
moveChildren(-childDeflectionVector);
newPos += childDeflectionVector;
newContents.setBottomRight(newContents.bottomRight() - childDeflectionVector);
expandByChildren(newContents);
}
QPointF ResizeHandler::childDeflection() const
{
QPointF childDeflectionVector = QPointF(0, 0);
int const sizeOfForestalling = mElementImpl->sizeOfForestalling();
foreach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {
const NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);
if (!curItem || curItem->isPort()) {
continue;
}
childDeflectionVector.setX(qMin(curItem->pos().x() - sizeOfForestalling, childDeflectionVector.x()));
childDeflectionVector.setY(qMin(curItem->pos().y() - sizeOfForestalling, childDeflectionVector.y()));
}
return childDeflectionVector;
}
void ResizeHandler::printChildPos() const
{
foreach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {
const NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);
if (!curItem || curItem->isPort()) {
continue;
}
qDebug() << "child pos: " << curItem->pos();
}
}
void ResizeHandler::moveChildren(QPointF const &shift) const
{
qreal const sizeOfForestalling = mElementImpl->sizeOfForestalling();
foreach (QGraphicsItem* const childItem, mResizingNode->childItems()) {
NodeElement* const curItem = dynamic_cast<NodeElement* const>(childItem);
if (!curItem || curItem->isPort()) {
continue;
}
curItem->moveBy(shift.x(), shift.y());
QPointF pos(qMax(curItem->pos().x(), sizeOfForestalling)
, qMax(curItem->pos().y(), sizeOfForestalling));
///returns object to the parent area
curItem->setPos(pos);
}
}
void ResizeHandler::expandByChildren(QRectF& contents) const
{
int const sizeOfForestalling = mElementImpl->sizeOfForestalling();
foreach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {
QRectF curChildItemBoundingRect = childBoundingRect(childItem, contents);
if (curChildItemBoundingRect.width() == 0 || curChildItemBoundingRect.height() == 0) {
continue;
}
// it seems to be more appropriate to use childItem->pos() but it causes
// bad behaviour when dropping one element to another
curChildItemBoundingRect.translate(childItem->scenePos() - mResizingNode->scenePos());
contents.setLeft(qMin(curChildItemBoundingRect.left() - sizeOfForestalling
, contents.left()));
contents.setRight(qMax(curChildItemBoundingRect.right() + sizeOfForestalling
, contents.right()));
contents.setTop(qMin(curChildItemBoundingRect.top() - sizeOfForestalling
, contents.top()));
contents.setBottom(qMax(curChildItemBoundingRect.bottom() + sizeOfForestalling
, contents.bottom()));
}
}
QRectF ResizeHandler::childBoundingRect(const QGraphicsItem* const childItem, QRectF const &contents) const
{
QRectF boundingRect;
if (childItem == mResizingNode->placeholder()) {
boundingRect = childItem->boundingRect();
int const sizeOfForestalling = mElementImpl->sizeOfForestalling();
boundingRect.setLeft(contents.left() + sizeOfForestalling);
boundingRect.setRight(contents.right() - sizeOfForestalling);
return boundingRect;
}
const NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);
if (curItem && !curItem->isPort()) {
boundingRect = curItem->contentsRect();
}
return boundingRect;
}
<commit_msg>Grid alignment enable.<commit_after>#include "resizeHandler.h"
#include <algorithm>
ResizeHandler::ResizeHandler(
NodeElement* const resizingNode
, ElementImpl* const elementImpl
)
: mResizingNode(resizingNode)
, mElementImpl(elementImpl)
{
}
void ResizeHandler::resize(QRectF newContents, QPointF newPos) const
{
newContents.moveTo(0, 0);
sortChildrenIfNeeded();
gripeIfMinimizesToChildrenContainer(newContents);
QRectF con = newContents;
if (!mResizingNode->isFolded()) {
resizeAccordingToChildren(newContents, newPos);
}
normalizeSize(newContents);
newContents.moveTo(newPos);
mResizingNode->setGeometry(newContents);
if (SettingsManager::value("ActivateGrid").toBool()) {
mResizingNode->alignToGrid();
}
mResizingNode->storeGeometry();
parentResizeCall();
}
qreal ResizeHandler::maxChildWidth() const
{
qreal maxChildWidthValue = 0;
foreach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {
const NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);
if (!curItem) {
continue;
}
maxChildWidthValue = qMax(maxChildWidthValue, curItem->contentsRect().width());
}
if (maxChildWidthValue == 0) {
maxChildWidthValue = mResizingNode->childrenBoundingRect().width();
}
return maxChildWidthValue;
}
void ResizeHandler::sortChildrenIfNeeded() const
{
if (!mElementImpl->isSortingContainer()) {
return;
}
int const sizeOfForestalling = mElementImpl->sizeOfForestalling();
qreal curChildY = sizeOfForestalling + mTitlePadding;
qreal const maxChildWidthValue = maxChildWidth();
foreach (QGraphicsItem* const childItem, mResizingNode->childItems()) {
QGraphicsRectItem* const placeholder = mResizingNode->placeholder();
if(placeholder != NULL && childItem == placeholder) {
QRectF const rect(sizeOfForestalling, curChildY,
maxChildWidthValue, placeholder->rect().height());
placeholder->setRect(rect);
curChildY += placeholder->rect().height() + mChildSpacing;
}
NodeElement* const curItem = dynamic_cast<NodeElement* const>(childItem);
if (!curItem) {
continue;
}
qreal const necessaryWidth =
mElementImpl->maximizesChildren()
? maxChildWidthValue
: curItem->contentsRect().width();
QRectF const rect(sizeOfForestalling, curChildY, necessaryWidth, curItem->contentsRect().height());
curItem->setGeometry(rect);
curItem->storeGeometry();
curChildY += curItem->contentsRect().height() + mElementImpl->sizeOfChildrenForestalling() + mChildSpacing;
}
}
void ResizeHandler::gripeIfMinimizesToChildrenContainer(QRectF& contents) const
{
if (mElementImpl->minimizesToChildren()) {
contents = QRectF();
}
}
void ResizeHandler::parentResizeCall() const
{
NodeElement* const parItem = dynamic_cast<NodeElement* const>(mResizingNode->parentItem());
if (parItem) {
ResizeHandler const handler(parItem, parItem->elementImpl());
handler.resize(parItem->contentsRect(), parItem->pos());
}
}
void ResizeHandler::normalizeSize(QRectF& newContents) const
{
if (newContents.width() < mMinSize) {
newContents.setWidth(mResizingNode->foldedContentsRect().width());
}
if (newContents.height() < mMinSize) {
newContents.setHeight(mResizingNode->foldedContentsRect().height());
}
}
void ResizeHandler::resizeAccordingToChildren(QRectF& newContents, QPointF& newPos) const
{
/*
* AAAA!!! Who knows why is this code existed????!!!
*
foreach (QGraphicsItem *childItem, childItems()) {
NodeElement* curItem = dynamic_cast<NodeElement*>(childItem);
if (curItem && curItem->isPort() && newContents != mContents) {
curItem->resizeChild(newContents, mContents);
}
}
*/
/// Vector of minimum negative XY child deflection from top left corner.
QPointF const childDeflectionVector = childDeflection();
moveChildren(-childDeflectionVector);
newPos += childDeflectionVector;
newContents.setBottomRight(newContents.bottomRight() - childDeflectionVector);
expandByChildren(newContents);
}
QPointF ResizeHandler::childDeflection() const
{
QPointF childDeflectionVector = QPointF(0, 0);
int const sizeOfForestalling = mElementImpl->sizeOfForestalling();
foreach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {
const NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);
if (!curItem || curItem->isPort()) {
continue;
}
childDeflectionVector.setX(qMin(curItem->pos().x() - sizeOfForestalling, childDeflectionVector.x()));
childDeflectionVector.setY(qMin(curItem->pos().y() - sizeOfForestalling, childDeflectionVector.y()));
}
return childDeflectionVector;
}
void ResizeHandler::printChildPos() const
{
foreach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {
const NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);
if (!curItem || curItem->isPort()) {
continue;
}
qDebug() << "child pos: " << curItem->pos();
}
}
void ResizeHandler::moveChildren(QPointF const &shift) const
{
qreal const sizeOfForestalling = mElementImpl->sizeOfForestalling();
foreach (QGraphicsItem* const childItem, mResizingNode->childItems()) {
NodeElement* const curItem = dynamic_cast<NodeElement* const>(childItem);
if (!curItem || curItem->isPort()) {
continue;
}
curItem->moveBy(shift.x(), shift.y());
QPointF pos(qMax(curItem->pos().x(), sizeOfForestalling)
, qMax(curItem->pos().y(), sizeOfForestalling));
///returns object to the parent area
curItem->setPos(pos);
}
}
void ResizeHandler::expandByChildren(QRectF& contents) const
{
int const sizeOfForestalling = mElementImpl->sizeOfForestalling();
foreach (const QGraphicsItem* const childItem, mResizingNode->childItems()) {
QRectF curChildItemBoundingRect = childBoundingRect(childItem, contents);
if (curChildItemBoundingRect.width() == 0 || curChildItemBoundingRect.height() == 0) {
continue;
}
// it seems to be more appropriate to use childItem->pos() but it causes
// bad behaviour when dropping one element to another
curChildItemBoundingRect.translate(childItem->scenePos() - mResizingNode->scenePos());
contents.setLeft(qMin(curChildItemBoundingRect.left() - sizeOfForestalling
, contents.left()));
contents.setRight(qMax(curChildItemBoundingRect.right() + sizeOfForestalling
, contents.right()));
contents.setTop(qMin(curChildItemBoundingRect.top() - sizeOfForestalling
, contents.top()));
contents.setBottom(qMax(curChildItemBoundingRect.bottom() + sizeOfForestalling
, contents.bottom()));
}
}
QRectF ResizeHandler::childBoundingRect(const QGraphicsItem* const childItem, QRectF const &contents) const
{
QRectF boundingRect;
if (childItem == mResizingNode->placeholder()) {
boundingRect = childItem->boundingRect();
int const sizeOfForestalling = mElementImpl->sizeOfForestalling();
boundingRect.setLeft(contents.left() + sizeOfForestalling);
boundingRect.setRight(contents.right() - sizeOfForestalling);
return boundingRect;
}
const NodeElement* const curItem = dynamic_cast<const NodeElement* const>(childItem);
if (curItem && !curItem->isPort()) {
boundingRect = curItem->contentsRect();
}
return boundingRect;
}
<|endoftext|> |
<commit_before>#include <util/singleton.h>
#include <util/scheduler.h>
#include <util/timer.h>
#include <iostream>
#include <map>
#include <boost/thread.hpp>
using namespace std;
namespace izenelib{
namespace util{
class QueueTimer : public Timer
{
public:
QueueTimer(void (*callback)(void *),
void *arg,
uint32_t due_time,
uint32_t period)
:callback_(callback),
arg_(arg),
due_time_(due_time),
period_(period)
{}
bool start()
{
return Timer::start(due_time_, period_);
}
bool startNow()
{
return Timer::start(0, period_);
}
virtual void signaled()
{
callback_(arg_);
}
private:
void (*callback_)(void *);
void *arg_;
uint32_t due_time_;
uint32_t period_;
};
struct ScheduleOP
{
std::string name;
uint32_t default_interval;
uint32_t delay_start;
boost::function<void (int)> callback;
QueueTimer* timer;
volatile bool running;
volatile bool immediatly_running;
boost::mutex jobmutex;
};
class SchedulerImpl
{
public:
SchedulerImpl() {}
virtual ~SchedulerImpl()
{
removeAllJobs();
}
void removeAllJobs()
{
boost::mutex::scoped_lock l(mutex_);
for (std::map<std::string, boost::shared_ptr<ScheduleOP> >::iterator itr = jobs_.begin();
itr != jobs_.end(); ++itr)
{
boost::shared_ptr<ScheduleOP> job = itr->second;
if (job->timer)
{
job->timer->stop();
delete job->timer;
job->timer = NULL;
}
while (job->immediatly_running)
cond_.wait(l);
}
jobs_.clear();
}
bool addJob(const string &name, uint32_t default_interval,
uint32_t delay_start, const boost::function<void (int)>& func)
{
boost::mutex::scoped_lock l(mutex_);
std::map<string, boost::shared_ptr<ScheduleOP> >::iterator find_itr = jobs_.find(name);
if (find_itr != jobs_.end())
return false;
boost::shared_ptr<ScheduleOP> newjob(new ScheduleOP());
newjob->name = name;
newjob->default_interval = default_interval;
newjob->delay_start = delay_start;
newjob->callback = func;
newjob->timer = NULL;
newjob->running = false;
newjob->immediatly_running = false;
std::pair<std::map<std::string, boost::shared_ptr<ScheduleOP> >::iterator, bool> result
= jobs_.insert(make_pair(name, newjob));
if (!result.second)
{
return false;
}
boost::shared_ptr<ScheduleOP> job = result.first->second;
uint32_t delay = job->delay_start;
job->timer = new QueueTimer(&timerCallback, job.get(), delay,
job->default_interval);
if (job->timer == NULL)
{
return false;
}
const bool started = job->timer->start();
if (started)
{
return true;
}
else
{
delete job->timer;
job->timer = NULL;
return false;
}
}
bool runJobImmediatly(const std::string& name, int calltype, bool sync)
{
boost::mutex::scoped_lock l(mutex_);
std::map<std::string, boost::shared_ptr<ScheduleOP> >::iterator itr = jobs_.find(name);
if (itr == jobs_.end())
{
std::cout << "schedule job not found:" << name << std::endl;
return false;
}
boost::shared_ptr<ScheduleOP> job = itr->second;
if (job && job->timer)
{
int retry = 5;
while (job->running || job->immediatly_running)
{
if (retry-- < 0)
{
std::cout << "schedule job already running:" << name << std::endl;
return false;
}
sleep(1);
}
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
if (job->running || job->immediatly_running)
return false;
job->immediatly_running = true;
}
mutex_.unlock();
try{
boost::scoped_ptr<boost::thread> run_thread;
run_thread.reset(new boost::thread(boost::bind(job->callback, calltype)));
run_thread->join();
} catch(const std::exception& e) {
std::cout << "run job exception: " << e.what() << std::endl;
mutex_.lock();
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
job->immediatly_running = false;
}
cond_.notify_all();
throw e;
}
mutex_.lock();
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
job->immediatly_running = false;
}
cond_.notify_all();
return true;
}
std::cout << "schedule job timer null:" << name << std::endl;
return false;
}
bool removeJob(const std::string &name)
{
boost::mutex::scoped_lock l(mutex_);
std::map<std::string, boost::shared_ptr<ScheduleOP> >::iterator itr = jobs_.find(name);
if (itr == jobs_.end())
{
return false;
}
else
{
boost::shared_ptr<ScheduleOP> job = itr->second;
if (job->timer != NULL)
{
job->timer->stop();
delete job->timer;
job->timer = NULL;
}
while (job->immediatly_running)
cond_.wait(l);
jobs_.erase(itr);
return true;
}
}
private:
static void timerCallback(void *param)
{
ScheduleOP *job = reinterpret_cast<ScheduleOP *>(param);
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
if (job->running || job->immediatly_running)
return;
job->running = true;
}
job->callback(0);
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
job->running = false;
}
}
std::map<std::string, boost::shared_ptr<ScheduleOP> > jobs_;
boost::condition_variable cond_;
boost::mutex mutex_;
};
bool Scheduler::addJob(const string &name, uint32_t default_interval,
uint32_t delay_start, const boost::function<void (int)>& func)
{
return Singleton<SchedulerImpl>::get()->addJob(name, default_interval, delay_start, func);
}
bool Scheduler::removeJob(const string &name)
{
return Singleton<SchedulerImpl>::get()->removeJob(name);
}
void Scheduler::removeAllJobs()
{
Singleton<SchedulerImpl>::get()->removeAllJobs();
}
bool Scheduler::runJobImmediatly(const std::string& name, int calltype, bool sync)
{
return Singleton<SchedulerImpl>::get()->runJobImmediatly(name, calltype, sync);
}
}
}
<commit_msg>fix scheduler<commit_after>#include <util/singleton.h>
#include <util/scheduler.h>
#include <util/timer.h>
#include <iostream>
#include <map>
#include <boost/thread.hpp>
using namespace std;
namespace izenelib{
namespace util{
class QueueTimer : public Timer
{
public:
QueueTimer(void (*callback)(void *),
void *arg,
uint32_t due_time,
uint32_t period)
:callback_(callback),
arg_(arg),
due_time_(due_time),
period_(period)
{}
bool start()
{
return Timer::start(due_time_, period_);
}
bool startNow()
{
return Timer::start(0, period_);
}
virtual void signaled()
{
callback_(arg_);
}
private:
void (*callback_)(void *);
void *arg_;
uint32_t due_time_;
uint32_t period_;
};
struct ScheduleOP
{
std::string name;
uint32_t default_interval;
uint32_t delay_start;
boost::function<void (int)> callback;
QueueTimer* timer;
volatile bool running;
volatile bool immediatly_running;
boost::mutex jobmutex;
};
class SchedulerImpl
{
public:
SchedulerImpl() {}
virtual ~SchedulerImpl()
{
removeAllJobs();
}
void removeAllJobs()
{
boost::mutex::scoped_lock l(mutex_);
for (std::map<std::string, boost::shared_ptr<ScheduleOP> >::iterator itr = jobs_.begin();
itr != jobs_.end(); ++itr)
{
boost::shared_ptr<ScheduleOP> job = itr->second;
if (job->timer)
{
job->timer->stop();
delete job->timer;
job->timer = NULL;
}
}
jobs_.clear();
}
bool addJob(const string &name, uint32_t default_interval,
uint32_t delay_start, const boost::function<void (int)>& func)
{
boost::mutex::scoped_lock l(mutex_);
std::map<string, boost::shared_ptr<ScheduleOP> >::iterator find_itr = jobs_.find(name);
if (find_itr != jobs_.end())
return false;
boost::shared_ptr<ScheduleOP> newjob(new ScheduleOP());
newjob->name = name;
newjob->default_interval = default_interval;
newjob->delay_start = delay_start;
newjob->callback = func;
newjob->timer = NULL;
newjob->running = false;
newjob->immediatly_running = false;
std::pair<std::map<std::string, boost::shared_ptr<ScheduleOP> >::iterator, bool> result
= jobs_.insert(make_pair(name, newjob));
if (!result.second)
{
return false;
}
boost::shared_ptr<ScheduleOP> job = result.first->second;
uint32_t delay = job->delay_start;
job->timer = new QueueTimer(&timerCallback, job.get(), delay,
job->default_interval);
if (job->timer == NULL)
{
return false;
}
const bool started = job->timer->start();
if (started)
{
return true;
}
else
{
delete job->timer;
job->timer = NULL;
return false;
}
}
bool runJobImmediatly(const std::string& name, int calltype, bool sync)
{
boost::shared_ptr<ScheduleOP> job;
{
boost::mutex::scoped_lock l(mutex_);
std::map<std::string, boost::shared_ptr<ScheduleOP> >::iterator itr = jobs_.find(name);
if (itr == jobs_.end())
{
std::cout << "schedule job not found:" << name << std::endl;
return false;
}
job = itr->second;
}
if (job)
{
int retry = 5;
while (job->running || job->immediatly_running)
{
if (retry-- < 0)
{
std::cout << "schedule job already running:" << name << std::endl;
return false;
}
sleep(1);
}
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
if (job->running || job->immediatly_running)
return false;
job->immediatly_running = true;
}
try{
boost::scoped_ptr<boost::thread> run_thread;
run_thread.reset(new boost::thread(boost::bind(job->callback, calltype)));
run_thread->join();
} catch(const std::exception& e) {
std::cout << "run job exception: " << e.what() << std::endl;
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
job->immediatly_running = false;
}
throw e;
}
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
job->immediatly_running = false;
}
return true;
}
std::cout << "schedule job null:" << name << std::endl;
return false;
}
bool removeJob(const std::string &name)
{
boost::mutex::scoped_lock l(mutex_);
std::map<std::string, boost::shared_ptr<ScheduleOP> >::iterator itr = jobs_.find(name);
if (itr == jobs_.end())
{
return false;
}
else
{
boost::shared_ptr<ScheduleOP> job = itr->second;
if (job->timer != NULL)
{
job->timer->stop();
delete job->timer;
job->timer = NULL;
}
jobs_.erase(itr);
return true;
}
}
private:
static void timerCallback(void *param)
{
ScheduleOP *job = reinterpret_cast<ScheduleOP *>(param);
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
if (job->running || job->immediatly_running)
return;
job->running = true;
}
job->callback(0);
{
boost::mutex::scoped_lock job_guard(job->jobmutex);
job->running = false;
}
}
std::map<std::string, boost::shared_ptr<ScheduleOP> > jobs_;
boost::condition_variable cond_;
boost::mutex mutex_;
};
bool Scheduler::addJob(const string &name, uint32_t default_interval,
uint32_t delay_start, const boost::function<void (int)>& func)
{
return Singleton<SchedulerImpl>::get()->addJob(name, default_interval, delay_start, func);
}
bool Scheduler::removeJob(const string &name)
{
return Singleton<SchedulerImpl>::get()->removeJob(name);
}
void Scheduler::removeAllJobs()
{
Singleton<SchedulerImpl>::get()->removeAllJobs();
}
bool Scheduler::runJobImmediatly(const std::string& name, int calltype, bool sync)
{
return Singleton<SchedulerImpl>::get()->runJobImmediatly(name, calltype, sync);
}
}
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM 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 "DeviceKey.h"
#if DEVICEKEY_ENABLED
#include "mbedtls/config.h"
#include "mbedtls/cmac.h"
#include "mbedtls/platform.h"
#include "features/storage/kvstore/include/KVStore.h"
#include "features/storage/kvstore/tdbstore/TDBStore.h"
#include "features/storage/kvstore/kv_map/KVMap.h"
#include "features/storage/kvstore/conf/kv_config.h"
#include "mbed_wait_api.h"
#include <stdlib.h>
#include "platform/mbed_error.h"
#include <string.h>
#include "entropy.h"
#include "mbed_trace.h"
#define TRACE_GROUP "DEVKEY"
#if !defined(MBEDTLS_CMAC_C)
#error [NOT_SUPPORTED] MBEDTLS_CMAC_C needs to be enabled for this driver
#else
namespace mbed {
#define DEVKEY_WRITE_UINT32_LE( dst, src ) \
do \
{ \
(dst)[0] = ( (src) >> 0 ) & 0xFF; \
(dst)[1] = ( (src) >> 8 ) & 0xFF; \
(dst)[2] = ( (src) >> 16 ) & 0xFF; \
(dst)[3] = ( (src) >> 24 ) & 0xFF; \
} while( 0 )
#define DEVKEY_WRITE_UINT8_LE( dst, src ) \
do \
{ \
(dst)[0] = (src) & 0xFF; \
} while( 0 )
DeviceKey::DeviceKey()
{
int ret = kv_init_storage_config();
if (ret != MBED_SUCCESS) {
tr_error("DeviceKey: Fail to initialize KvStore configuration.");
}
#if defined(MBEDTLS_PLATFORM_C)
ret = mbedtls_platform_setup(NULL);
if (ret != MBED_SUCCESS) {
tr_error("DeviceKey: Fail in mbedtls_platform_setup.");
}
#endif /* MBEDTLS_PLATFORM_C */
return;
}
DeviceKey::~DeviceKey()
{
#if defined(MBEDTLS_PLATFORM_C)
mbedtls_platform_teardown(NULL);
#endif /* MBEDTLS_PLATFORM_C */
return;
}
int DeviceKey::generate_derived_key(const unsigned char *salt, size_t isalt_size, unsigned char *output,
uint16_t ikey_type)
{
uint32_t key_buff[DEVICE_KEY_32BYTE / sizeof(uint32_t)];
size_t actual_size = DEVICE_KEY_32BYTE;
if (DEVICE_KEY_16BYTE != ikey_type && DEVICE_KEY_32BYTE != ikey_type) {
return DEVICEKEY_INVALID_KEY_TYPE;
}
actual_size = DEVICE_KEY_16BYTE != ikey_type ? DEVICE_KEY_32BYTE : DEVICE_KEY_16BYTE;
//First try to read the key from KVStore
int ret = read_key_from_kvstore(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret) {
return ret;
}
ret = get_derived_key(key_buff, actual_size, salt, isalt_size, output, ikey_type);
return ret;
}
int DeviceKey::device_inject_root_of_trust(uint32_t *value, size_t isize)
{
return write_key_to_kvstore(value, isize);
}
int DeviceKey::write_key_to_kvstore(uint32_t *input, size_t isize)
{
if (DEVICE_KEY_16BYTE != isize && DEVICE_KEY_32BYTE != isize) {
return DEVICEKEY_INVALID_KEY_SIZE;
}
//First we read if key exist. If it is exists, we return DEVICEKEY_ALREADY_EXIST error
uint32_t read_key[DEVICE_KEY_32BYTE / sizeof(uint32_t)] = {0};
size_t read_size = DEVICE_KEY_32BYTE;
int ret = read_key_from_kvstore(read_key, read_size);
if (DEVICEKEY_SUCCESS == ret) {
return DEVICEKEY_ALREADY_EXIST;
}
if (DEVICEKEY_NOT_FOUND != ret) {
return ret;
}
KVMap &kv_map = KVMap::get_instance();
KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);
if (inner_store == NULL) {
return DEVICEKEY_SAVE_FAILED;
}
ret = ((TDBStore *)inner_store)->reserved_data_set(input, isize);
if (MBED_ERROR_WRITE_FAILED == ret) {
return DEVICEKEY_SAVE_FAILED;
}
if (MBED_SUCCESS != ret) {
return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::read_key_from_kvstore(uint32_t *output, size_t &size)
{
if (size > (uint16_t) -1) {
return DEVICEKEY_INVALID_PARAM;
}
KVMap &kv_map = KVMap::get_instance();
KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);
if (inner_store == NULL) {
return DEVICEKEY_NOT_FOUND;
}
int kvStatus = ((TDBStore *)inner_store)->reserved_data_get(output, size, &size);
if (MBED_ERROR_ITEM_NOT_FOUND == kvStatus) {
return DEVICEKEY_NOT_FOUND;
}
if (MBED_ERROR_READ_FAILED == kvStatus || MBED_ERROR_INVALID_SIZE == kvStatus) {
return DEVICEKEY_READ_FAILED;
}
if (MBED_SUCCESS != kvStatus) {
return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::get_derived_key(uint32_t *ikey_buff, size_t ikey_size, const unsigned char *isalt,
size_t isalt_size, unsigned char *output, uint32_t ikey_type)
{
//KDF in counter mode implementation as described in Section 5.1
//of NIST SP 800-108, Recommendation for Key Derivation Using Pseudorandom Functions
int ret;
size_t counter = 0;
char separator = 0x00;
mbedtls_cipher_context_t ctx;
unsigned char output_len_enc[ 4 ] = {0};
unsigned char counter_enc[ 1 ] = {0};
DEVKEY_WRITE_UINT32_LE(output_len_enc, ikey_type);
mbedtls_cipher_type_t mbedtls_cipher_type = MBEDTLS_CIPHER_AES_128_ECB;
if (DEVICE_KEY_32BYTE == ikey_size) {
mbedtls_cipher_type = MBEDTLS_CIPHER_AES_256_ECB;
}
const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(mbedtls_cipher_type);
do {
mbedtls_cipher_init(&ctx);
ret = mbedtls_cipher_setup(&ctx, cipher_info);
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_starts(&ctx, (unsigned char *)ikey_buff, ikey_size * 8);
if (ret != 0) {
goto finish;
}
DEVKEY_WRITE_UINT8_LE(counter_enc, (counter + 1));
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)counter_enc, sizeof(counter_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, isalt, isalt_size);
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&separator, sizeof(char));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&output_len_enc, sizeof(output_len_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_finish(&ctx, output + (DEVICE_KEY_16BYTE * (counter)));
if (ret != 0) {
goto finish;
}
mbedtls_cipher_free(&ctx);
counter++;
} while (DEVICE_KEY_16BYTE * counter < ikey_type);
finish:
if (DEVICEKEY_SUCCESS != ret) {
mbedtls_cipher_free(&ctx);
return DEVICEKEY_ERR_CMAC_GENERIC_FAILURE;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::generate_root_of_trust()
{
int ret = DEVICEKEY_GENERATE_RANDOM_ERROR;
uint32_t key_buff[DEVICE_KEY_32BYTE / sizeof(uint32_t)];
size_t actual_size = DEVICE_KEY_32BYTE;
if (read_key_from_kvstore(key_buff, actual_size) == DEVICEKEY_SUCCESS) {
return DEVICEKEY_ALREADY_EXIST;
}
#if defined(DEVICE_TRNG) || defined(MBEDTLS_ENTROPY_NV_SEED) || defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
mbedtls_entropy_context *entropy = new mbedtls_entropy_context;
mbedtls_entropy_init(entropy);
memset(key_buff, 0, actual_size);
ret = mbedtls_entropy_func(entropy, (unsigned char *)key_buff, actual_size);
if (ret != MBED_SUCCESS) {
ret = DEVICEKEY_GENERATE_RANDOM_ERROR;
} else {
ret = DEVICEKEY_SUCCESS;
}
mbedtls_entropy_free(entropy);
delete entropy;
if (ret == MBED_SUCCESS) {
ret = device_inject_root_of_trust(key_buff, actual_size);
}
#endif
return ret;
}
} // namespace mbed
#endif
#endif
<commit_msg>Use correct return value.<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM 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 "DeviceKey.h"
#if DEVICEKEY_ENABLED
#include "mbedtls/config.h"
#include "mbedtls/cmac.h"
#include "mbedtls/platform.h"
#include "features/storage/kvstore/include/KVStore.h"
#include "features/storage/kvstore/tdbstore/TDBStore.h"
#include "features/storage/kvstore/kv_map/KVMap.h"
#include "features/storage/kvstore/conf/kv_config.h"
#include "mbed_wait_api.h"
#include <stdlib.h>
#include "platform/mbed_error.h"
#include <string.h>
#include "entropy.h"
#include "mbed_trace.h"
#define TRACE_GROUP "DEVKEY"
#if !defined(MBEDTLS_CMAC_C)
#error [NOT_SUPPORTED] MBEDTLS_CMAC_C needs to be enabled for this driver
#else
namespace mbed {
#define DEVKEY_WRITE_UINT32_LE( dst, src ) \
do \
{ \
(dst)[0] = ( (src) >> 0 ) & 0xFF; \
(dst)[1] = ( (src) >> 8 ) & 0xFF; \
(dst)[2] = ( (src) >> 16 ) & 0xFF; \
(dst)[3] = ( (src) >> 24 ) & 0xFF; \
} while( 0 )
#define DEVKEY_WRITE_UINT8_LE( dst, src ) \
do \
{ \
(dst)[0] = (src) & 0xFF; \
} while( 0 )
DeviceKey::DeviceKey()
{
int ret = kv_init_storage_config();
if (ret != MBED_SUCCESS) {
tr_error("DeviceKey: Fail to initialize KvStore configuration.");
}
#if defined(MBEDTLS_PLATFORM_C)
ret = mbedtls_platform_setup(NULL);
if (ret != MBED_SUCCESS) {
tr_error("DeviceKey: Fail in mbedtls_platform_setup.");
}
#endif /* MBEDTLS_PLATFORM_C */
return;
}
DeviceKey::~DeviceKey()
{
#if defined(MBEDTLS_PLATFORM_C)
mbedtls_platform_teardown(NULL);
#endif /* MBEDTLS_PLATFORM_C */
return;
}
int DeviceKey::generate_derived_key(const unsigned char *salt, size_t isalt_size, unsigned char *output,
uint16_t ikey_type)
{
uint32_t key_buff[DEVICE_KEY_32BYTE / sizeof(uint32_t)];
size_t actual_size = DEVICE_KEY_32BYTE;
if (DEVICE_KEY_16BYTE != ikey_type && DEVICE_KEY_32BYTE != ikey_type) {
return DEVICEKEY_INVALID_KEY_TYPE;
}
actual_size = DEVICE_KEY_16BYTE != ikey_type ? DEVICE_KEY_32BYTE : DEVICE_KEY_16BYTE;
//First try to read the key from KVStore
int ret = read_key_from_kvstore(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret) {
return ret;
}
ret = get_derived_key(key_buff, actual_size, salt, isalt_size, output, ikey_type);
return ret;
}
int DeviceKey::device_inject_root_of_trust(uint32_t *value, size_t isize)
{
return write_key_to_kvstore(value, isize);
}
int DeviceKey::write_key_to_kvstore(uint32_t *input, size_t isize)
{
if (DEVICE_KEY_16BYTE != isize && DEVICE_KEY_32BYTE != isize) {
return DEVICEKEY_INVALID_KEY_SIZE;
}
//First we read if key exist. If it is exists, we return DEVICEKEY_ALREADY_EXIST error
uint32_t read_key[DEVICE_KEY_32BYTE / sizeof(uint32_t)] = {0};
size_t read_size = DEVICE_KEY_32BYTE;
int ret = read_key_from_kvstore(read_key, read_size);
if (DEVICEKEY_SUCCESS == ret) {
return DEVICEKEY_ALREADY_EXIST;
}
if (DEVICEKEY_NOT_FOUND != ret) {
return ret;
}
KVMap &kv_map = KVMap::get_instance();
KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);
if (inner_store == NULL) {
return DEVICEKEY_SAVE_FAILED;
}
ret = ((TDBStore *)inner_store)->reserved_data_set(input, isize);
if (MBED_ERROR_WRITE_FAILED == ret) {
return DEVICEKEY_SAVE_FAILED;
}
if (MBED_SUCCESS != ret) {
return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::read_key_from_kvstore(uint32_t *output, size_t &size)
{
if (size > (uint16_t) -1) {
return DEVICEKEY_INVALID_PARAM;
}
KVMap &kv_map = KVMap::get_instance();
KVStore *inner_store = kv_map.get_internal_kv_instance(NULL);
if (inner_store == NULL) {
return DEVICEKEY_NOT_FOUND;
}
int kvStatus = ((TDBStore *)inner_store)->reserved_data_get(output, size, &size);
if (MBED_ERROR_ITEM_NOT_FOUND == kvStatus) {
return DEVICEKEY_NOT_FOUND;
}
if (MBED_ERROR_READ_FAILED == kvStatus || MBED_ERROR_INVALID_SIZE == kvStatus) {
return DEVICEKEY_READ_FAILED;
}
if (MBED_SUCCESS != kvStatus) {
return DEVICEKEY_KVSTORE_UNPREDICTED_ERROR;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::get_derived_key(uint32_t *ikey_buff, size_t ikey_size, const unsigned char *isalt,
size_t isalt_size, unsigned char *output, uint32_t ikey_type)
{
//KDF in counter mode implementation as described in Section 5.1
//of NIST SP 800-108, Recommendation for Key Derivation Using Pseudorandom Functions
int ret;
size_t counter = 0;
char separator = 0x00;
mbedtls_cipher_context_t ctx;
unsigned char output_len_enc[ 4 ] = {0};
unsigned char counter_enc[ 1 ] = {0};
DEVKEY_WRITE_UINT32_LE(output_len_enc, ikey_type);
mbedtls_cipher_type_t mbedtls_cipher_type = MBEDTLS_CIPHER_AES_128_ECB;
if (DEVICE_KEY_32BYTE == ikey_size) {
mbedtls_cipher_type = MBEDTLS_CIPHER_AES_256_ECB;
}
const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(mbedtls_cipher_type);
do {
mbedtls_cipher_init(&ctx);
ret = mbedtls_cipher_setup(&ctx, cipher_info);
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_starts(&ctx, (unsigned char *)ikey_buff, ikey_size * 8);
if (ret != 0) {
goto finish;
}
DEVKEY_WRITE_UINT8_LE(counter_enc, (counter + 1));
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)counter_enc, sizeof(counter_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, isalt, isalt_size);
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&separator, sizeof(char));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&output_len_enc, sizeof(output_len_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_finish(&ctx, output + (DEVICE_KEY_16BYTE * (counter)));
if (ret != 0) {
goto finish;
}
mbedtls_cipher_free(&ctx);
counter++;
} while (DEVICE_KEY_16BYTE * counter < ikey_type);
finish:
if (DEVICEKEY_SUCCESS != ret) {
mbedtls_cipher_free(&ctx);
return DEVICEKEY_ERR_CMAC_GENERIC_FAILURE;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::generate_root_of_trust()
{
int ret = DEVICEKEY_GENERATE_RANDOM_ERROR;
uint32_t key_buff[DEVICE_KEY_32BYTE / sizeof(uint32_t)];
size_t actual_size = DEVICE_KEY_32BYTE;
if (read_key_from_kvstore(key_buff, actual_size) == DEVICEKEY_SUCCESS) {
return DEVICEKEY_ALREADY_EXIST;
}
#if defined(DEVICE_TRNG) || defined(MBEDTLS_ENTROPY_NV_SEED) || defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
mbedtls_entropy_context *entropy = new mbedtls_entropy_context;
mbedtls_entropy_init(entropy);
memset(key_buff, 0, actual_size);
ret = mbedtls_entropy_func(entropy, (unsigned char *)key_buff, actual_size);
if (ret != MBED_SUCCESS) {
ret = DEVICEKEY_GENERATE_RANDOM_ERROR;
} else {
ret = DEVICEKEY_SUCCESS;
}
mbedtls_entropy_free(entropy);
delete entropy;
if (ret == DEVICEKEY_SUCCESS) {
ret = device_inject_root_of_trust(key_buff, actual_size);
}
#endif
return ret;
}
} // namespace mbed
#endif
#endif
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM 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 "DeviceKey.h"
#include "mbedtls/config.h"
#include "mbedtls/cmac.h"
#include "nvstore.h"
#include "trng_api.h"
#include "mbed_wait_api.h"
#include "stdlib.h"
#if !defined(MBEDTLS_CMAC_C)
#error [NOT_SUPPORTED] MBEDTLS_CMAC_C needs to be enabled for this driver
#else
#if NVSTORE_ENABLED
namespace mbed {
#define DEVKEY_WRITE_UINT32_LE( dst, src ) \
do \
{ \
(dst)[0] = ( (src) >> 0 ) & 0xFF; \
(dst)[1] = ( (src) >> 8 ) & 0xFF; \
(dst)[2] = ( (src) >> 16 ) & 0xFF; \
(dst)[3] = ( (src) >> 24 ) & 0xFF; \
} while( 0 )
#define DEVKEY_WRITE_UINT8_LE( dst, src ) \
do \
{ \
(dst)[0] = (src) & 0xFF; \
} while( 0 )
DeviceKey::DeviceKey()
{
return;
}
DeviceKey::~DeviceKey()
{
return;
}
int DeviceKey::generate_derived_key(const unsigned char *salt, size_t isalt_size, unsigned char *output,
uint16_t ikey_type)
{
uint32_t key_buff[DEVICE_KEY_32BYTE / sizeof(uint32_t)];
size_t actual_size = DEVICE_KEY_32BYTE;
if (DEVICE_KEY_16BYTE != ikey_type && DEVICE_KEY_32BYTE != ikey_type) {
return DEVICEKEY_INVALID_KEY_TYPE;
}
//First try to read the key from NVStore
int ret = read_key_from_nvstore(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret && DEVICEKEY_NOT_FOUND != ret) {
return ret;
}
if (DEVICE_KEY_16BYTE != actual_size && DEVICE_KEY_32BYTE != actual_size) {
return DEVICEKEY_READ_FAILED;
}
//If the key was not found in NVStore we will create it by using TRNG and then save it to NVStore
if (DEVICEKEY_NOT_FOUND == ret) {
ret = generate_key_by_trng(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret) {
return ret;
}
ret = device_inject_root_of_trust(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret) {
return ret;
}
}
ret = get_derived_key(key_buff, actual_size, salt, isalt_size, output, ikey_type);
return ret;
}
int DeviceKey::device_inject_root_of_trust(uint32_t *value, size_t isize)
{
return write_key_to_nvstore(value, isize);
}
int DeviceKey::write_key_to_nvstore(uint32_t *input, size_t isize)
{
if (DEVICE_KEY_16BYTE != isize && DEVICE_KEY_32BYTE != isize) {
return DEVICEKEY_INVALID_KEY_SIZE;
}
//First we read if key exist. If it is exists, we return DEVICEKEY_ALREADY_EXIST error
uint32_t read_key[DEVICE_KEY_32BYTE / sizeof(uint32_t)] = {0};
size_t read_size = DEVICE_KEY_32BYTE;
int ret = read_key_from_nvstore(read_key, read_size);
if (DEVICEKEY_SUCCESS == ret) {
return DEVICEKEY_ALREADY_EXIST;
}
if (DEVICEKEY_NOT_FOUND != ret) {
return ret;
}
NVStore& nvstore = NVStore::get_instance();
ret = nvstore.set(NVSTORE_DEVICEKEY_KEY, (uint16_t)isize, input);
if (NVSTORE_WRITE_ERROR == ret || NVSTORE_BUFF_TOO_SMALL == ret) {
return DEVICEKEY_SAVE_FAILED;
}
if (NVSTORE_SUCCESS != ret) {
return DEVICEKEY_NVSTORE_UNPREDICTED_ERROR;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::read_key_from_nvstore(uint32_t *output, size_t& size)
{
if (size > UINT16_MAX) {
return DEVICEKEY_INVALID_PARAM;
}
uint16_t in_size = size;
uint16_t out_size = 0;
NVStore& nvstore = NVStore::get_instance();
int nvStatus = nvstore.get(NVSTORE_DEVICEKEY_KEY, in_size, output, out_size);
if (NVSTORE_NOT_FOUND == nvStatus) {
return DEVICEKEY_NOT_FOUND;
}
if (NVSTORE_READ_ERROR == nvStatus || NVSTORE_BUFF_TOO_SMALL == nvStatus) {
return DEVICEKEY_READ_FAILED;
}
if (NVSTORE_SUCCESS != nvStatus) {
return DEVICEKEY_NVSTORE_UNPREDICTED_ERROR;
}
size = out_size;
return DEVICEKEY_SUCCESS;
}
int DeviceKey::get_derived_key(uint32_t *ikey_buff, size_t ikey_size, const unsigned char *isalt,
size_t isalt_size, unsigned char *output, uint32_t ikey_type)
{
//KDF in counter mode implementation as described in Section 5.1
//of NIST SP 800-108, Recommendation for Key Derivation Using Pseudorandom Functions
int ret;
size_t counter = 0;
char separator = 0x00;
mbedtls_cipher_context_t ctx;
unsigned char output_len_enc[ 4 ] = {0};
unsigned char counter_enc[ 1 ] = {0};
DEVKEY_WRITE_UINT32_LE(output_len_enc, ikey_type);
mbedtls_cipher_type_t mbedtls_cipher_type = MBEDTLS_CIPHER_AES_128_ECB;
if (DEVICE_KEY_32BYTE == ikey_size) {
mbedtls_cipher_type = MBEDTLS_CIPHER_AES_256_ECB;
}
const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(mbedtls_cipher_type);
mbedtls_cipher_init(&ctx);
ret = mbedtls_cipher_setup(&ctx, cipher_info);
if (ret != 0) {
goto finish;
}
do {
ret = mbedtls_cipher_cmac_starts(&ctx, (unsigned char *)ikey_buff, ikey_size * 8);
if (ret != 0) {
goto finish;
}
DEVKEY_WRITE_UINT8_LE(counter_enc, (counter+1));
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)counter_enc, sizeof(counter_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, isalt, isalt_size);
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&separator, sizeof(char));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&output_len_enc, sizeof(output_len_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_finish(&ctx, output + (DEVICE_KEY_16BYTE * (counter)));
if (ret != 0) {
goto finish;
}
counter++;
} while (DEVICE_KEY_16BYTE * counter < ikey_type);
finish:
mbedtls_cipher_free( &ctx );
if (DEVICEKEY_SUCCESS != ret) {
return DEVICEKEY_ERR_CMAC_GENERIC_FAILURE;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::generate_key_by_trng(uint32_t *output, size_t& size)
{
#if defined(DEVICE_TRNG)
size_t in_size;
size_t ongoing_size;
size_t final_size;
trng_t trng_obj;
int ret = DEVICEKEY_SUCCESS;
unsigned char *pBuffer = (unsigned char *)output;
memset(output, 0, size);
if (DEVICE_KEY_16BYTE > size) {
return DEVICEKEY_BUFFER_TOO_SMALL;
} else if (DEVICE_KEY_16BYTE <= size && DEVICE_KEY_32BYTE > size) {
size = DEVICE_KEY_16BYTE;
} else {
size = DEVICE_KEY_32BYTE;
}
trng_init(&trng_obj);
final_size = 0;
in_size = size;
while (true) {
ongoing_size = 0;
ret = trng_get_bytes(&trng_obj, (unsigned char *)pBuffer, in_size, &ongoing_size);
final_size += ongoing_size;
if (DEVICEKEY_SUCCESS != ret) {
ret = DEVICEKEY_TRNG_ERROR;
goto finish;
}
if (DEVICEKEY_SUCCESS == ret && final_size == size) {
break;
}
wait_ms(5);
pBuffer += ongoing_size;
in_size -= ongoing_size;
}
ret = DEVICEKEY_SUCCESS;
finish:
trng_free(&trng_obj);
size = final_size;
return ret;
#else
return DEVICEKEY_NO_KEY_INJECTED;
#endif
}
} // namespace mbed
#endif //NVSTORE_ENABLED
#endif
<commit_msg>Changed trng loop condition<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM 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 "DeviceKey.h"
#include "mbedtls/config.h"
#include "mbedtls/cmac.h"
#include "nvstore.h"
#include "trng_api.h"
#include "mbed_wait_api.h"
#include "stdlib.h"
#if !defined(MBEDTLS_CMAC_C)
#error [NOT_SUPPORTED] MBEDTLS_CMAC_C needs to be enabled for this driver
#else
#if NVSTORE_ENABLED
namespace mbed {
#define DEVKEY_WRITE_UINT32_LE( dst, src ) \
do \
{ \
(dst)[0] = ( (src) >> 0 ) & 0xFF; \
(dst)[1] = ( (src) >> 8 ) & 0xFF; \
(dst)[2] = ( (src) >> 16 ) & 0xFF; \
(dst)[3] = ( (src) >> 24 ) & 0xFF; \
} while( 0 )
#define DEVKEY_WRITE_UINT8_LE( dst, src ) \
do \
{ \
(dst)[0] = (src) & 0xFF; \
} while( 0 )
DeviceKey::DeviceKey()
{
return;
}
DeviceKey::~DeviceKey()
{
return;
}
int DeviceKey::generate_derived_key(const unsigned char *salt, size_t isalt_size, unsigned char *output,
uint16_t ikey_type)
{
uint32_t key_buff[DEVICE_KEY_32BYTE / sizeof(uint32_t)];
size_t actual_size = DEVICE_KEY_32BYTE;
if (DEVICE_KEY_16BYTE != ikey_type && DEVICE_KEY_32BYTE != ikey_type) {
return DEVICEKEY_INVALID_KEY_TYPE;
}
//First try to read the key from NVStore
int ret = read_key_from_nvstore(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret && DEVICEKEY_NOT_FOUND != ret) {
return ret;
}
if (DEVICE_KEY_16BYTE != actual_size && DEVICE_KEY_32BYTE != actual_size) {
return DEVICEKEY_READ_FAILED;
}
//If the key was not found in NVStore we will create it by using TRNG and then save it to NVStore
if (DEVICEKEY_NOT_FOUND == ret) {
ret = generate_key_by_trng(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret) {
return ret;
}
ret = device_inject_root_of_trust(key_buff, actual_size);
if (DEVICEKEY_SUCCESS != ret) {
return ret;
}
}
ret = get_derived_key(key_buff, actual_size, salt, isalt_size, output, ikey_type);
return ret;
}
int DeviceKey::device_inject_root_of_trust(uint32_t *value, size_t isize)
{
return write_key_to_nvstore(value, isize);
}
int DeviceKey::write_key_to_nvstore(uint32_t *input, size_t isize)
{
if (DEVICE_KEY_16BYTE != isize && DEVICE_KEY_32BYTE != isize) {
return DEVICEKEY_INVALID_KEY_SIZE;
}
//First we read if key exist. If it is exists, we return DEVICEKEY_ALREADY_EXIST error
uint32_t read_key[DEVICE_KEY_32BYTE / sizeof(uint32_t)] = {0};
size_t read_size = DEVICE_KEY_32BYTE;
int ret = read_key_from_nvstore(read_key, read_size);
if (DEVICEKEY_SUCCESS == ret) {
return DEVICEKEY_ALREADY_EXIST;
}
if (DEVICEKEY_NOT_FOUND != ret) {
return ret;
}
NVStore& nvstore = NVStore::get_instance();
ret = nvstore.set(NVSTORE_DEVICEKEY_KEY, (uint16_t)isize, input);
if (NVSTORE_WRITE_ERROR == ret || NVSTORE_BUFF_TOO_SMALL == ret) {
return DEVICEKEY_SAVE_FAILED;
}
if (NVSTORE_SUCCESS != ret) {
return DEVICEKEY_NVSTORE_UNPREDICTED_ERROR;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::read_key_from_nvstore(uint32_t *output, size_t& size)
{
if (size > UINT16_MAX) {
return DEVICEKEY_INVALID_PARAM;
}
uint16_t in_size = size;
uint16_t out_size = 0;
NVStore& nvstore = NVStore::get_instance();
int nvStatus = nvstore.get(NVSTORE_DEVICEKEY_KEY, in_size, output, out_size);
if (NVSTORE_NOT_FOUND == nvStatus) {
return DEVICEKEY_NOT_FOUND;
}
if (NVSTORE_READ_ERROR == nvStatus || NVSTORE_BUFF_TOO_SMALL == nvStatus) {
return DEVICEKEY_READ_FAILED;
}
if (NVSTORE_SUCCESS != nvStatus) {
return DEVICEKEY_NVSTORE_UNPREDICTED_ERROR;
}
size = out_size;
return DEVICEKEY_SUCCESS;
}
int DeviceKey::get_derived_key(uint32_t *ikey_buff, size_t ikey_size, const unsigned char *isalt,
size_t isalt_size, unsigned char *output, uint32_t ikey_type)
{
//KDF in counter mode implementation as described in Section 5.1
//of NIST SP 800-108, Recommendation for Key Derivation Using Pseudorandom Functions
int ret;
size_t counter = 0;
char separator = 0x00;
mbedtls_cipher_context_t ctx;
unsigned char output_len_enc[ 4 ] = {0};
unsigned char counter_enc[ 1 ] = {0};
DEVKEY_WRITE_UINT32_LE(output_len_enc, ikey_type);
mbedtls_cipher_type_t mbedtls_cipher_type = MBEDTLS_CIPHER_AES_128_ECB;
if (DEVICE_KEY_32BYTE == ikey_size) {
mbedtls_cipher_type = MBEDTLS_CIPHER_AES_256_ECB;
}
const mbedtls_cipher_info_t *cipher_info = mbedtls_cipher_info_from_type(mbedtls_cipher_type);
mbedtls_cipher_init(&ctx);
ret = mbedtls_cipher_setup(&ctx, cipher_info);
if (ret != 0) {
goto finish;
}
do {
ret = mbedtls_cipher_cmac_starts(&ctx, (unsigned char *)ikey_buff, ikey_size * 8);
if (ret != 0) {
goto finish;
}
DEVKEY_WRITE_UINT8_LE(counter_enc, (counter+1));
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)counter_enc, sizeof(counter_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, isalt, isalt_size);
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&separator, sizeof(char));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_update(&ctx, (unsigned char *)&output_len_enc, sizeof(output_len_enc));
if (ret != 0) {
goto finish;
}
ret = mbedtls_cipher_cmac_finish(&ctx, output + (DEVICE_KEY_16BYTE * (counter)));
if (ret != 0) {
goto finish;
}
counter++;
} while (DEVICE_KEY_16BYTE * counter < ikey_type);
finish:
mbedtls_cipher_free( &ctx );
if (DEVICEKEY_SUCCESS != ret) {
return DEVICEKEY_ERR_CMAC_GENERIC_FAILURE;
}
return DEVICEKEY_SUCCESS;
}
int DeviceKey::generate_key_by_trng(uint32_t *output, size_t& size)
{
#if defined(DEVICE_TRNG)
size_t in_size;
size_t ongoing_size;
size_t final_size;
trng_t trng_obj;
int ret = DEVICEKEY_SUCCESS;
unsigned char *pBuffer = (unsigned char *)output;
memset(output, 0, size);
if (DEVICE_KEY_16BYTE > size) {
return DEVICEKEY_BUFFER_TOO_SMALL;
} else if (DEVICE_KEY_16BYTE <= size && DEVICE_KEY_32BYTE > size) {
size = DEVICE_KEY_16BYTE;
} else {
size = DEVICE_KEY_32BYTE;
}
trng_init(&trng_obj);
final_size = 0;
in_size = size;
while (DEVICEKEY_SUCCESS == ret && final_size < size) {
ongoing_size = 0;
ret = trng_get_bytes(&trng_obj, (unsigned char *)pBuffer, in_size, &ongoing_size);
final_size += ongoing_size;
if (DEVICEKEY_SUCCESS != ret) {
ret = DEVICEKEY_TRNG_ERROR;
goto finish;
}
pBuffer += ongoing_size;
in_size -= ongoing_size;
}
ret = DEVICEKEY_SUCCESS;
finish:
trng_free(&trng_obj);
size = final_size;
return ret;
#else
return DEVICEKEY_NO_KEY_INJECTED;
#endif
}
} // namespace mbed
#endif //NVSTORE_ENABLED
#endif
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
// Author: [email protected] (Aaron Jacobs)
//
// 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 "gjstest/internal/cpp/test_case.h"
#include "base/callback.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/timer.h"
#include "gjstest/internal/cpp/v8_utils.h"
using v8::Arguments;
using v8::Context;
using v8::Function;
using v8::Handle;
using v8::Local;
using v8::Object;
using v8::TryCatch;
using v8::Value;
namespace gjstest {
// Get a reference to the function of the supplied name.
static Local<Function> GetFunctionNamed(const string& name) {
const Local<Value> result = ExecuteJs(name, "");
CHECK(result->IsFunction()) << "Error getting reference to " << name;
return Local<Function>::Cast(result);
}
// Log the supplied string to the test's output.
static Handle<Value> LogString(TestCase* test_case, const Arguments& args) {
CHECK_EQ(1, args.Length());
const string& message = ConvertToString(args[0]);
StringAppendF(&test_case->output, "%s\n", message.c_str());
return v8::Undefined();
}
// Record the test as having failed, and extract a failure message from the JS
// arguments and append it to the existing messages, if any.
static Handle<Value> RecordFailure(TestCase* test_case, const Arguments& args) {
CHECK_EQ(1, args.Length());
const string& message = ConvertToString(args[0]);
test_case->succeeded = false;
StringAppendF(&test_case->output, "%s\n\n", message.c_str());
StringAppendF(&test_case->failure_output, "%s\n\n", message.c_str());
return v8::Undefined();
}
TestCase::TestCase(
const Handle<Function>& test_function)
: succeeded(false),
duration_ms(kuint32max),
test_function_(test_function) {
CHECK(test_function_->IsFunction());
}
void TestCase::Run() {
CycleTimer timer;
timer.Start();
// Assume we succeeded by default.
succeeded = true;
// Grab references to runTest, getCurrentStack, and the TestEnvironment
// constructor.
const Local<Function> run_test = GetFunctionNamed("gjstest.internal.runTest");
const Local<Function> get_current_stack =
GetFunctionNamed("gjstest.internal.getCurrentStack");
const Local<Function> test_env_constructor =
GetFunctionNamed("gjstest.internal.TestEnvironment");
// Create log and reportFailure functions.
const Local<Function> log =
MakeFunction("log", NewPermanentCallback(&LogString, this));
const Local<Function> report_failure =
MakeFunction(
"reportFailure",
NewPermanentCallback(&RecordFailure, this));
// Create a test environment.
Handle<Value> test_env_args[] = { log, report_failure, get_current_stack };
const Local<Object> test_env =
test_env_constructor->NewInstance(
arraysize(test_env_args),
test_env_args);
CHECK(!test_env.IsEmpty());
// Run the test.
TryCatch try_catch;
Handle<Value> args[] = { test_function_, test_env };
const Local<Value> result =
run_test->Call(Context::GetCurrent()->Global(), arraysize(args), args);
// Was there an exception while running the test?
if (result.IsEmpty()) {
succeeded = false;
const string description = DescribeError(try_catch);
StringAppendF(&output, "%s\n", description.c_str());
StringAppendF(&failure_output, "%s\n", description.c_str());
}
// Record the test time.
timer.Stop();
duration_ms = timer.GetInMs();
}
} // namespace gjstest
<commit_msg>Fixed two memory errors.<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
// Author: [email protected] (Aaron Jacobs)
//
// 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 "gjstest/internal/cpp/test_case.h"
#include "base/callback.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/timer.h"
#include "gjstest/internal/cpp/v8_utils.h"
using v8::Arguments;
using v8::Context;
using v8::Function;
using v8::Handle;
using v8::Local;
using v8::Object;
using v8::TryCatch;
using v8::Value;
namespace gjstest {
// Get a reference to the function of the supplied name.
static Local<Function> GetFunctionNamed(const string& name) {
const Local<Value> result = ExecuteJs(name, "");
CHECK(result->IsFunction()) << "Error getting reference to " << name;
return Local<Function>::Cast(result);
}
// Log the supplied string to the test's output.
static Handle<Value> LogString(TestCase* test_case, const Arguments& args) {
CHECK_EQ(1, args.Length());
const string message = ConvertToString(args[0]);
StringAppendF(&test_case->output, "%s\n", message.c_str());
return v8::Undefined();
}
// Record the test as having failed, and extract a failure message from the JS
// arguments and append it to the existing messages, if any.
static Handle<Value> RecordFailure(TestCase* test_case, const Arguments& args) {
CHECK_EQ(1, args.Length());
const string message = ConvertToString(args[0]);
test_case->succeeded = false;
StringAppendF(&test_case->output, "%s\n\n", message.c_str());
StringAppendF(&test_case->failure_output, "%s\n\n", message.c_str());
return v8::Undefined();
}
TestCase::TestCase(
const Handle<Function>& test_function)
: succeeded(false),
duration_ms(kuint32max),
test_function_(test_function) {
CHECK(test_function_->IsFunction());
}
void TestCase::Run() {
CycleTimer timer;
timer.Start();
// Assume we succeeded by default.
succeeded = true;
// Grab references to runTest, getCurrentStack, and the TestEnvironment
// constructor.
const Local<Function> run_test = GetFunctionNamed("gjstest.internal.runTest");
const Local<Function> get_current_stack =
GetFunctionNamed("gjstest.internal.getCurrentStack");
const Local<Function> test_env_constructor =
GetFunctionNamed("gjstest.internal.TestEnvironment");
// Create log and reportFailure functions.
const Local<Function> log =
MakeFunction("log", NewPermanentCallback(&LogString, this));
const Local<Function> report_failure =
MakeFunction(
"reportFailure",
NewPermanentCallback(&RecordFailure, this));
// Create a test environment.
Handle<Value> test_env_args[] = { log, report_failure, get_current_stack };
const Local<Object> test_env =
test_env_constructor->NewInstance(
arraysize(test_env_args),
test_env_args);
CHECK(!test_env.IsEmpty());
// Run the test.
TryCatch try_catch;
Handle<Value> args[] = { test_function_, test_env };
const Local<Value> result =
run_test->Call(Context::GetCurrent()->Global(), arraysize(args), args);
// Was there an exception while running the test?
if (result.IsEmpty()) {
succeeded = false;
const string description = DescribeError(try_catch);
StringAppendF(&output, "%s\n", description.c_str());
StringAppendF(&failure_output, "%s\n", description.c_str());
}
// Record the test time.
timer.Stop();
duration_ms = timer.GetInMs();
}
} // namespace gjstest
<|endoftext|> |
<commit_before>#include <assert.h>
#include <utility>
#include "common/configmanager/configmanager.h"
#include "log/clog.h"
#include "simhub.h"
// TODO: FIX EVERYTHING
std::shared_ptr<SimHubEventController> SimHubEventController::_EventControllerInstance = NULL;
GenericTLV *AttributeToCGeneric(std::shared_ptr<Attribute> value)
{
GenericTLV *retVal = (GenericTLV *)malloc(sizeof(GenericTLV));
retVal->name = (char *)calloc(value->_name.size() + 1, 1);
strncpy(retVal->name, value->_name.c_str(), value->_name.size());
switch (value->_type) {
case BOOL_ATTRIBUTE:
retVal->type = CONFIG_BOOL;
retVal->value.bool_value = value->getValue<bool>();
break;
case FLOAT_ATTRIBUTE:
retVal->type = CONFIG_FLOAT;
retVal->value.float_value = value->getValue<float>();
break;
case INT_ATTRIBUTE:
retVal->type = CONFIG_INT;
retVal->value.int_value = value->getValue<int>();
break;
case STRING_ATTRIBUTE:
retVal->type = CONFIG_STRING;
retVal->value.string_value = (char *)calloc(value->getValue<std::string>().size() + 1, 1);
strncpy(retVal->value.string_value, value->getValue<std::string>().c_str(), value->getValue<std::string>().size());
break;
default:
assert(false);
break;
}
return retVal;
}
//! marshals the C generic struct instance into an Attribute C++ generic container
std::shared_ptr<Attribute> AttributeFromCGeneric(GenericTLV *generic)
{
std::shared_ptr<Attribute> retVal(new Attribute());
switch (generic->type) {
case CONFIG_BOOL:
retVal->setValue<bool>(generic->value.bool_value);
retVal->_type = BOOL_ATTRIBUTE;
break;
case CONFIG_FLOAT:
retVal->setValue<float>(generic->value.float_value);
retVal->_type = FLOAT_ATTRIBUTE;
break;
case CONFIG_INT:
retVal->setValue<int>(generic->value.int_value);
retVal->_type = INT_ATTRIBUTE;
break;
case CONFIG_STRING:
retVal->setValue<std::string>(generic->value.string_value);
retVal->_type = STRING_ATTRIBUTE;
break;
default:
assert(false);
break;
}
retVal->_name = generic->name;
return retVal;
}
//! static singleton accessor
std::shared_ptr<SimHubEventController> SimHubEventController::EventControllerInstance(void)
{
if (!_EventControllerInstance)
_EventControllerInstance.reset(new SimHubEventController());
return SimHubEventController::_EventControllerInstance;
}
SimHubEventController::SimHubEventController()
{
_prepare3dMethods.plugin_instance = NULL;
_pokeyMethods.plugin_instance = NULL;
_configManager = NULL;
logger.log(LOG_INFO, "Starting event controller");
}
SimHubEventController::~SimHubEventController(void)
{
terminate();
}
void SimHubEventController::setConfigManager(ConfigManager *configManager)
{
_configManager = configManager;
}
bool SimHubEventController::deliverPokeyPluginValue(std::shared_ptr<Attribute> value)
{
assert(_pokeyMethods.simplug_deliver_value);
GenericTLV *c_value = AttributeToCGeneric(value);
bool retVal = !_pokeyMethods.simplug_deliver_value(_pokeyMethods.plugin_instance, c_value);
if (c_value->type == CONFIG_STRING)
free(c_value->value.string_value);
free(c_value->name);
free(c_value);
return retVal;
}
// these callbacks will be called from the thread of the event
// generator which is assumed to not be the thread of the for
// loop below
void SimHubEventController::prepare3dEventCallback(SPHANDLE eventSource, void *eventData)
{
GenericTLV *data = static_cast<GenericTLV *>(eventData);
assert(data != NULL);
std::shared_ptr<Attribute> attribute = AttributeFromCGeneric(data);
MapEntry *mapEntry;
if (_configManager->mapManager()->find(data->name, &mapEntry)) {
// std::cout << "prepare3dEventCallback" << data->name << "--->" << mapEntry->second.c_str() << " FIND TARGET HERE" << std::endl;
_eventQueue.push(attribute);
}
}
void SimHubEventController::pokeyEventCallback(SPHANDLE eventSource, void *eventData)
{
GenericTLV *data = static_cast<GenericTLV *>(eventData);
assert(data != NULL);
std::shared_ptr<Attribute> attribute = AttributeFromCGeneric(data);
MapEntry *mapEntry;
if (_configManager->mapManager()->find(data->name, &mapEntry)) {
std::cout << "pokeyEventCallback" << data->name << "--->" << mapEntry->second.c_str() << " FIND TARGET HERE" << std::endl;
_eventQueue.push(attribute);
}
}
void SimHubEventController::LoggerWrapper(const int category, const char *msg, ...)
{
// TODO: make logger a class instance member
char buff[MAX_VA_LENGTH];
va_list args;
va_start(args, msg);
vsprintf(buff, msg, args);
va_end(args);
logger.log(category, buff);
}
simplug_vtable SimHubEventController::loadPlugin(std::string dylibName, libconfig::Config *pluginConfig, EnqueueEventHandler eventCallback)
{
SPHANDLE pluginInstance = NULL;
simplug_vtable pluginMethods;
memset(&pluginMethods, sizeof(simplug_vtable), 0);
// TODO: use correct path
std::string fullPath("plugins/");
fullPath += dylibName + LIB_EXT;
int err = simplug_bootstrap(fullPath.c_str(), &pluginMethods);
if (err == 0) {
err = pluginMethods.simplug_init(&pluginInstance, SimHubEventController::LoggerWrapper);
pluginMethods.plugin_instance = pluginInstance;
// -- temporary solution to the plugin configuration conundrom:
// - iterate over the list of libconfig::Setting instances we've
// - been given for this plugin and pass them through
pluginMethods.simplug_config_passthrough(pluginInstance, pluginConfig);
// TODO: add error checking
if (pluginMethods.simplug_preflight_complete(pluginInstance) == 0) {
// proxy the C style lambda call through to the member
// function above
pluginMethods.simplug_commence_eventing(pluginInstance, eventCallback, this);
}
else {
assert(false);
}
}
else {
assert(false);
}
return pluginMethods;
}
void SimHubEventController::loadPrepare3dPlugin(void)
{
auto prepare3dCallback = [](SPHANDLE eventSource, void *eventData, void *arg) { static_cast<SimHubEventController *>(arg)->prepare3dEventCallback(eventSource, eventData); };
_prepare3dMethods = loadPlugin("libprepare3d", _prepare3dDeviceConfig, prepare3dCallback);
}
void SimHubEventController::loadPokeyPlugin(void)
{
auto pokeyCallback = [](SPHANDLE eventSource, void *eventData, void *arg) { static_cast<SimHubEventController *>(arg)->pokeyEventCallback(eventSource, eventData); };
_pokeyMethods = loadPlugin("libpokey", _pokeyDeviceConfig, pokeyCallback);
}
//! perform shutdown ceremonies on both plugins - this unloads both plugins
void SimHubEventController::terminate(void)
{
shutdownPlugin(_prepare3dMethods);
shutdownPlugin(_pokeyMethods);
}
//! private support method - gracefully closes plugin instance represented by pluginMethods
void SimHubEventController::shutdownPlugin(simplug_vtable &pluginMethods)
{
if (pluginMethods.plugin_instance) {
pluginMethods.simplug_cease_eventing(pluginMethods.plugin_instance);
pluginMethods.simplug_release(pluginMethods.plugin_instance);
pluginMethods.plugin_instance = NULL;
}
}
<commit_msg>handle CONFIG_UINT<commit_after>#include <assert.h>
#include <utility>
#include "common/configmanager/configmanager.h"
#include "log/clog.h"
#include "simhub.h"
// TODO: FIX EVERYTHING
std::shared_ptr<SimHubEventController> SimHubEventController::_EventControllerInstance = NULL;
GenericTLV *AttributeToCGeneric(std::shared_ptr<Attribute> value)
{
GenericTLV *retVal = (GenericTLV *)malloc(sizeof(GenericTLV));
retVal->name = (char *)calloc(value->_name.size() + 1, 1);
strncpy(retVal->name, value->_name.c_str(), value->_name.size());
switch (value->_type) {
case BOOL_ATTRIBUTE:
retVal->type = CONFIG_BOOL;
retVal->value.bool_value = value->getValue<bool>();
break;
case FLOAT_ATTRIBUTE:
retVal->type = CONFIG_FLOAT;
retVal->value.float_value = value->getValue<float>();
break;
case INT_ATTRIBUTE:
retVal->type = CONFIG_INT;
retVal->value.int_value = value->getValue<int>();
break;
case STRING_ATTRIBUTE:
retVal->type = CONFIG_STRING;
retVal->value.string_value = (char *)calloc(value->getValue<std::string>().size() + 1, 1);
strncpy(retVal->value.string_value, value->getValue<std::string>().c_str(), value->getValue<std::string>().size());
break;
default:
assert(false);
break;
}
return retVal;
}
//! marshals the C generic struct instance into an Attribute C++ generic container
std::shared_ptr<Attribute> AttributeFromCGeneric(GenericTLV *generic)
{
std::shared_ptr<Attribute> retVal(new Attribute());
switch (generic->type) {
case CONFIG_BOOL:
retVal->setValue<bool>(generic->value.bool_value);
retVal->_type = BOOL_ATTRIBUTE;
break;
case CONFIG_FLOAT:
retVal->setValue<float>(generic->value.float_value);
retVal->_type = FLOAT_ATTRIBUTE;
break;
case CONFIG_INT:
retVal->setValue<int>(generic->value.int_value);
retVal->_type = INT_ATTRIBUTE;
break;
case CONFIG_UINT:
retVal->setValue<int>(generic->value.uint_value);
retVal->_type = UINT_ATTRIBUTE;
break;
case CONFIG_STRING:
retVal->setValue<std::string>(generic->value.string_value);
retVal->_type = STRING_ATTRIBUTE;
break;
default:
logger.log(LOG_ERROR, "Unknown attribute type %d %s ", (int)generic->type, generic->name);
break;
}
retVal->_name = generic->name;
return retVal;
}
//! static singleton accessor
std::shared_ptr<SimHubEventController> SimHubEventController::EventControllerInstance(void)
{
if (!_EventControllerInstance)
_EventControllerInstance.reset(new SimHubEventController());
return SimHubEventController::_EventControllerInstance;
}
SimHubEventController::SimHubEventController()
{
_prepare3dMethods.plugin_instance = NULL;
_pokeyMethods.plugin_instance = NULL;
_configManager = NULL;
logger.log(LOG_INFO, "Starting event controller");
}
SimHubEventController::~SimHubEventController(void)
{
terminate();
}
void SimHubEventController::setConfigManager(ConfigManager *configManager)
{
_configManager = configManager;
}
bool SimHubEventController::deliverPokeyPluginValue(std::shared_ptr<Attribute> value)
{
assert(_pokeyMethods.simplug_deliver_value);
GenericTLV *c_value = AttributeToCGeneric(value);
bool retVal = !_pokeyMethods.simplug_deliver_value(_pokeyMethods.plugin_instance, c_value);
if (c_value->type == CONFIG_STRING)
free(c_value->value.string_value);
free(c_value->name);
free(c_value);
return retVal;
}
// these callbacks will be called from the thread of the event
// generator which is assumed to not be the thread of the for
// loop below
void SimHubEventController::prepare3dEventCallback(SPHANDLE eventSource, void *eventData)
{
GenericTLV *data = static_cast<GenericTLV *>(eventData);
assert(data != NULL);
std::shared_ptr<Attribute> attribute = AttributeFromCGeneric(data);
MapEntry *mapEntry;
if (_configManager->mapManager()->find(data->name, &mapEntry)) {
_eventQueue.push(attribute);
}
}
void SimHubEventController::pokeyEventCallback(SPHANDLE eventSource, void *eventData)
{
GenericTLV *data = static_cast<GenericTLV *>(eventData);
assert(data != NULL);
std::shared_ptr<Attribute> attribute = AttributeFromCGeneric(data);
MapEntry *mapEntry;
if (_configManager->mapManager()->find(data->name, &mapEntry)) {
_eventQueue.push(attribute);
}
}
void SimHubEventController::LoggerWrapper(const int category, const char *msg, ...)
{
// TODO: make logger a class instance member
char buff[MAX_VA_LENGTH];
va_list args;
va_start(args, msg);
vsprintf(buff, msg, args);
va_end(args);
logger.log(category, buff);
}
simplug_vtable SimHubEventController::loadPlugin(std::string dylibName, libconfig::Config *pluginConfig, EnqueueEventHandler eventCallback)
{
SPHANDLE pluginInstance = NULL;
simplug_vtable pluginMethods;
memset(&pluginMethods, sizeof(simplug_vtable), 0);
// TODO: use correct path
std::string fullPath("plugins/");
fullPath += dylibName + LIB_EXT;
int err = simplug_bootstrap(fullPath.c_str(), &pluginMethods);
if (err == 0) {
err = pluginMethods.simplug_init(&pluginInstance, SimHubEventController::LoggerWrapper);
pluginMethods.plugin_instance = pluginInstance;
// -- temporary solution to the plugin configuration conundrom:
// - iterate over the list of libconfig::Setting instances we've
// - been given for this plugin and pass them through
pluginMethods.simplug_config_passthrough(pluginInstance, pluginConfig);
// TODO: add error checking
if (pluginMethods.simplug_preflight_complete(pluginInstance) == 0) {
// proxy the C style lambda call through to the member
// function above
pluginMethods.simplug_commence_eventing(pluginInstance, eventCallback, this);
}
else {
assert(false);
}
}
else {
assert(false);
}
return pluginMethods;
}
void SimHubEventController::loadPrepare3dPlugin(void)
{
auto prepare3dCallback = [](SPHANDLE eventSource, void *eventData, void *arg) { static_cast<SimHubEventController *>(arg)->prepare3dEventCallback(eventSource, eventData); };
_prepare3dMethods = loadPlugin("libprepare3d", _prepare3dDeviceConfig, prepare3dCallback);
}
void SimHubEventController::loadPokeyPlugin(void)
{
auto pokeyCallback = [](SPHANDLE eventSource, void *eventData, void *arg) { static_cast<SimHubEventController *>(arg)->pokeyEventCallback(eventSource, eventData); };
_pokeyMethods = loadPlugin("libpokey", _pokeyDeviceConfig, pokeyCallback);
}
//! perform shutdown ceremonies on both plugins - this unloads both plugins
void SimHubEventController::terminate(void)
{
shutdownPlugin(_prepare3dMethods);
shutdownPlugin(_pokeyMethods);
}
//! private support method - gracefully closes plugin instance represented by pluginMethods
void SimHubEventController::shutdownPlugin(simplug_vtable &pluginMethods)
{
if (pluginMethods.plugin_instance) {
pluginMethods.simplug_cease_eventing(pluginMethods.plugin_instance);
pluginMethods.simplug_release(pluginMethods.plugin_instance);
pluginMethods.plugin_instance = NULL;
}
}
<|endoftext|> |
<commit_before>//===--- lldb-moduleimport-test.cpp - LLDB moduleimport tester ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This program simulates LLDB importing modules from the __apple_ast
// section in Mach-O files. We use it to test for regressions in the
// deserialization API.
//
//===----------------------------------------------------------------------===//
#include "swift/ASTSectionImporter/ASTSectionImporter.h"
#include "swift/Frontend/Frontend.h"
#include "swift/IDE/Utils.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Serialization/Validation.h"
#include "swift/Basic/Dwarf.h"
#include "llvm/Object/ELFObjectFile.h"
#include "swift/Basic/LLVMInitialize.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ManagedStatic.h"
#include <fstream>
#include <sstream>
void anchorForGetMainExecutable() {}
using namespace llvm::MachO;
static bool
validateModule(llvm::StringRef data, bool Verbose,
swift::serialization::ValidationInfo &info,
swift::serialization::ExtendedValidationInfo &extendedInfo) {
info = swift::serialization::validateSerializedAST(data, &extendedInfo);
if (info.status != swift::serialization::Status::Valid)
return false;
swift::CompilerInvocation CI;
if (CI.loadFromSerializedAST(data) != swift::serialization::Status::Valid)
return false;
if (Verbose) {
if (!info.shortVersion.empty())
llvm::outs() << "- Swift Version: " << info.shortVersion << "\n";
llvm::outs() << "- Compatibility Version: "
<< CI.getLangOptions()
.EffectiveLanguageVersion.asAPINotesVersionString()
<< "\n";
llvm::outs() << "- Target: " << info.targetTriple << "\n";
if (!extendedInfo.getSDKPath().empty())
llvm::outs() << "- SDK path: " << extendedInfo.getSDKPath() << "\n";
if (!extendedInfo.getExtraClangImporterOptions().empty()) {
llvm::outs() << "- -Xcc options:";
for (llvm::StringRef option : extendedInfo.getExtraClangImporterOptions())
llvm::outs() << " " << option;
llvm::outs() << "\n";
}
}
return true;
}
static void resolveDeclFromMangledNameList(
swift::ASTContext &Ctx, llvm::ArrayRef<std::string> MangledNames) {
std::string Error;
for (auto &Mangled : MangledNames) {
swift::Decl *ResolvedDecl =
swift::ide::getDeclFromMangledSymbolName(Ctx, Mangled, Error);
if (!ResolvedDecl) {
llvm::errs() << "Can't resolve decl of " << Mangled << "\n";
} else {
ResolvedDecl->print(llvm::errs());
llvm::errs() << "\n";
}
}
}
static void resolveTypeFromMangledNameList(
swift::ASTContext &Ctx, llvm::ArrayRef<std::string> MangledNames) {
std::string Error;
for (auto &Mangled : MangledNames) {
swift::Type ResolvedType =
swift::ide::getTypeFromMangledSymbolname(Ctx, Mangled, Error);
if (!ResolvedType) {
llvm::errs() << "Can't resolve type of " << Mangled << "\n";
} else {
ResolvedType->print(llvm::errs());
llvm::errs() << "\n";
}
}
}
static void
collectMangledNames(const std::string &FilePath,
llvm::SmallVectorImpl<std::string> &MangledNames) {
std::string Name;
std::ifstream InputStream(FilePath);
while (std::getline(InputStream, Name)) {
if (Name.empty())
continue;
MangledNames.push_back(Name);
}
}
llvm::BumpPtrAllocator Alloc;
static bool
collectASTModules(llvm::cl::list<std::string> &InputNames,
llvm::SmallVectorImpl<std::pair<char *, uint64_t>> &Modules) {
for (auto &name : InputNames) {
auto OF = llvm::object::ObjectFile::createObjectFile(name);
if (!OF) {
llvm::outs() << "error: " << name << " "
<< errorToErrorCode(OF.takeError()).message() << "\n";
return false;
}
auto *Obj = OF->getBinary();
auto *MachO = llvm::dyn_cast<llvm::object::MachOObjectFile>(Obj);
auto *ELF = llvm::dyn_cast<llvm::object::ELFObjectFileBase>(Obj);
if (MachO) {
for (auto &Symbol : Obj->symbols()) {
auto RawSym = Symbol.getRawDataRefImpl();
llvm::MachO::nlist nlist = MachO->getSymbolTableEntry(RawSym);
if (nlist.n_type != N_AST)
continue;
auto Path = MachO->getSymbolName(RawSym);
if (!Path) {
llvm::outs() << "Cannot get symbol name\n;";
return false;
}
auto fileBuf = llvm::MemoryBuffer::getFile(*Path);
if (!fileBuf) {
llvm::outs() << "Cannot read from '" << *Path
<< "': " << fileBuf.getError().message();
return false;
}
uint64_t Size = fileBuf.get()->getBufferSize();
char *Module = Alloc.Allocate<char>(Size);
std::memcpy(Module, (void *)fileBuf.get()->getBufferStart(), Size);
Modules.push_back({Module, Size});
}
}
for (auto &Section : Obj->sections()) {
llvm::StringRef Name;
Section.getName(Name);
if ((MachO && Name == swift::MachOASTSectionName) ||
(ELF && Name == swift::ELFASTSectionName)) {
uint64_t Size = Section.getSize();
StringRef ContentsReference;
Section.getContents(ContentsReference);
char *Module = Alloc.Allocate<char>(Size);
std::memcpy(Module, (void *)ContentsReference.begin(), Size);
Modules.push_back({Module, Size});
}
}
}
return true;
}
int main(int argc, char **argv) {
PROGRAM_START(argc, argv);
INITIALIZE_LLVM();
// Command line handling.
llvm::cl::list<std::string> InputNames(
llvm::cl::Positional, llvm::cl::desc("compiled_swift_file1.o ..."),
llvm::cl::OneOrMore);
llvm::cl::opt<bool> DumpModule(
"dump-module", llvm::cl::desc(
"Dump the imported module after checking it imports just fine"));
llvm::cl::opt<bool> Verbose(
"verbose", llvm::cl::desc("Dump informations on the loaded module"));
llvm::cl::opt<std::string> ModuleCachePath(
"module-cache-path", llvm::cl::desc("Clang module cache path"));
llvm::cl::opt<std::string> DumpDeclFromMangled(
"decl-from-mangled", llvm::cl::desc("dump decl from mangled names list"));
llvm::cl::opt<std::string> DumpTypeFromMangled(
"type-from-mangled", llvm::cl::desc("dump type from mangled names list"));
llvm::cl::opt<std::string> ResourceDir("resource-dir",
llvm::cl::desc("The directory that holds the compiler resource files"));
llvm::cl::ParseCommandLineOptions(argc, argv);
// Unregister our options so they don't interfere with the command line
// parsing in CodeGen/BackendUtil.cpp.
ModuleCachePath.removeArgument();
DumpModule.removeArgument();
DumpTypeFromMangled.removeArgument();
InputNames.removeArgument();
auto validateInputFile = [](std::string Filename) {
if (Filename.empty())
return true;
if (!llvm::sys::fs::exists(llvm::Twine(Filename))) {
llvm::errs() << Filename << " does not exists, exiting.\n";
return false;
}
if (!llvm::sys::fs::is_regular_file(llvm::Twine(Filename))) {
llvm::errs() << Filename << " is not a regular file, exiting.\n";
return false;
}
return true;
};
if (!validateInputFile(DumpTypeFromMangled))
return 1;
if (!validateInputFile(DumpDeclFromMangled))
return 1;
// Fetch the serialized module bitstreams from the Mach-O files and
// register them with the module loader.
llvm::SmallVector<std::pair<char *, uint64_t>, 8> Modules;
if (!collectASTModules(InputNames, Modules))
return 1;
if (Modules.empty())
return 0;
swift::serialization::ValidationInfo info;
swift::serialization::ExtendedValidationInfo extendedInfo;
for (auto &Module : Modules) {
if (!validateModule(StringRef(Module.first, Module.second), Verbose, info,
extendedInfo)) {
llvm::errs() << "Malformed module!\n";
return 1;
}
}
// Create a Swift compiler.
llvm::SmallVector<std::string, 4> modules;
swift::CompilerInstance CI;
swift::CompilerInvocation Invocation;
Invocation.setMainExecutablePath(
llvm::sys::fs::getMainExecutable(argv[0],
reinterpret_cast<void *>(&anchorForGetMainExecutable)));
// Infer SDK and Target triple from the module.
Invocation.setSDKPath(extendedInfo.getSDKPath());
Invocation.setTargetTriple(info.targetTriple);
Invocation.setModuleName("lldbtest");
Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;
if (!ResourceDir.empty()) {
Invocation.setRuntimeResourcePath(ResourceDir);
}
if (CI.setup(Invocation))
return 1;
for (auto &Module : Modules)
if (!parseASTSection(CI.getSerializedModuleLoader(),
StringRef(Module.first, Module.second), modules))
return 1;
// Attempt to import all modules we found.
for (auto path : modules) {
if (Verbose)
llvm::outs() << "Importing " << path << "... ";
#ifdef SWIFT_SUPPORTS_SUBMODULES
std::vector<std::pair<swift::Identifier, swift::SourceLoc> > AccessPath;
for (auto i = llvm::sys::path::begin(path);
i != llvm::sys::path::end(path); ++i)
if (!llvm::sys::path::is_separator((*i)[0]))
AccessPath.push_back({ CI.getASTContext().getIdentifier(*i),
swift::SourceLoc() });
#else
std::vector<std::pair<swift::Identifier, swift::SourceLoc> > AccessPath;
AccessPath.push_back({ CI.getASTContext().getIdentifier(path),
swift::SourceLoc() });
#endif
auto Module = CI.getASTContext().getModule(AccessPath);
if (!Module) {
if (Verbose)
llvm::errs() << "FAIL!\n";
return 1;
}
if (Verbose)
llvm::outs() << "ok!\n";
if (DumpModule) {
llvm::SmallVector<swift::Decl*, 10> Decls;
Module->getTopLevelDecls(Decls);
for (auto Decl : Decls) {
Decl->dump(llvm::outs());
}
}
if (!DumpTypeFromMangled.empty()) {
llvm::SmallVector<std::string, 8> MangledNames;
collectMangledNames(DumpTypeFromMangled, MangledNames);
resolveTypeFromMangledNameList(CI.getASTContext(), MangledNames);
}
if (!DumpDeclFromMangled.empty()) {
llvm::SmallVector<std::string, 8> MangledNames;
collectMangledNames(DumpDeclFromMangled, MangledNames);
resolveDeclFromMangledNameList(CI.getASTContext(), MangledNames);
}
}
return 0;
}
<commit_msg>Hide irreleveant command line options of lldb-moduleimport-test<commit_after>//===--- lldb-moduleimport-test.cpp - LLDB moduleimport tester ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This program simulates LLDB importing modules from the __apple_ast
// section in Mach-O files. We use it to test for regressions in the
// deserialization API.
//
//===----------------------------------------------------------------------===//
#include "swift/ASTSectionImporter/ASTSectionImporter.h"
#include "swift/Frontend/Frontend.h"
#include "swift/IDE/Utils.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Serialization/Validation.h"
#include "swift/Basic/Dwarf.h"
#include "llvm/Object/ELFObjectFile.h"
#include "swift/Basic/LLVMInitialize.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/ObjectFile.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ManagedStatic.h"
#include <fstream>
#include <sstream>
void anchorForGetMainExecutable() {}
using namespace llvm::MachO;
static bool
validateModule(llvm::StringRef data, bool Verbose,
swift::serialization::ValidationInfo &info,
swift::serialization::ExtendedValidationInfo &extendedInfo) {
info = swift::serialization::validateSerializedAST(data, &extendedInfo);
if (info.status != swift::serialization::Status::Valid)
return false;
swift::CompilerInvocation CI;
if (CI.loadFromSerializedAST(data) != swift::serialization::Status::Valid)
return false;
if (Verbose) {
if (!info.shortVersion.empty())
llvm::outs() << "- Swift Version: " << info.shortVersion << "\n";
llvm::outs() << "- Compatibility Version: "
<< CI.getLangOptions()
.EffectiveLanguageVersion.asAPINotesVersionString()
<< "\n";
llvm::outs() << "- Target: " << info.targetTriple << "\n";
if (!extendedInfo.getSDKPath().empty())
llvm::outs() << "- SDK path: " << extendedInfo.getSDKPath() << "\n";
if (!extendedInfo.getExtraClangImporterOptions().empty()) {
llvm::outs() << "- -Xcc options:";
for (llvm::StringRef option : extendedInfo.getExtraClangImporterOptions())
llvm::outs() << " " << option;
llvm::outs() << "\n";
}
}
return true;
}
static void resolveDeclFromMangledNameList(
swift::ASTContext &Ctx, llvm::ArrayRef<std::string> MangledNames) {
std::string Error;
for (auto &Mangled : MangledNames) {
swift::Decl *ResolvedDecl =
swift::ide::getDeclFromMangledSymbolName(Ctx, Mangled, Error);
if (!ResolvedDecl) {
llvm::errs() << "Can't resolve decl of " << Mangled << "\n";
} else {
ResolvedDecl->print(llvm::errs());
llvm::errs() << "\n";
}
}
}
static void resolveTypeFromMangledNameList(
swift::ASTContext &Ctx, llvm::ArrayRef<std::string> MangledNames) {
std::string Error;
for (auto &Mangled : MangledNames) {
swift::Type ResolvedType =
swift::ide::getTypeFromMangledSymbolname(Ctx, Mangled, Error);
if (!ResolvedType) {
llvm::errs() << "Can't resolve type of " << Mangled << "\n";
} else {
ResolvedType->print(llvm::errs());
llvm::errs() << "\n";
}
}
}
static void
collectMangledNames(const std::string &FilePath,
llvm::SmallVectorImpl<std::string> &MangledNames) {
std::string Name;
std::ifstream InputStream(FilePath);
while (std::getline(InputStream, Name)) {
if (Name.empty())
continue;
MangledNames.push_back(Name);
}
}
llvm::BumpPtrAllocator Alloc;
static bool
collectASTModules(llvm::cl::list<std::string> &InputNames,
llvm::SmallVectorImpl<std::pair<char *, uint64_t>> &Modules) {
for (auto &name : InputNames) {
auto OF = llvm::object::ObjectFile::createObjectFile(name);
if (!OF) {
llvm::outs() << "error: " << name << " "
<< errorToErrorCode(OF.takeError()).message() << "\n";
return false;
}
auto *Obj = OF->getBinary();
auto *MachO = llvm::dyn_cast<llvm::object::MachOObjectFile>(Obj);
auto *ELF = llvm::dyn_cast<llvm::object::ELFObjectFileBase>(Obj);
if (MachO) {
for (auto &Symbol : Obj->symbols()) {
auto RawSym = Symbol.getRawDataRefImpl();
llvm::MachO::nlist nlist = MachO->getSymbolTableEntry(RawSym);
if (nlist.n_type != N_AST)
continue;
auto Path = MachO->getSymbolName(RawSym);
if (!Path) {
llvm::outs() << "Cannot get symbol name\n;";
return false;
}
auto fileBuf = llvm::MemoryBuffer::getFile(*Path);
if (!fileBuf) {
llvm::outs() << "Cannot read from '" << *Path
<< "': " << fileBuf.getError().message();
return false;
}
uint64_t Size = fileBuf.get()->getBufferSize();
char *Module = Alloc.Allocate<char>(Size);
std::memcpy(Module, (void *)fileBuf.get()->getBufferStart(), Size);
Modules.push_back({Module, Size});
}
}
for (auto &Section : Obj->sections()) {
llvm::StringRef Name;
Section.getName(Name);
if ((MachO && Name == swift::MachOASTSectionName) ||
(ELF && Name == swift::ELFASTSectionName)) {
uint64_t Size = Section.getSize();
StringRef ContentsReference;
Section.getContents(ContentsReference);
char *Module = Alloc.Allocate<char>(Size);
std::memcpy(Module, (void *)ContentsReference.begin(), Size);
Modules.push_back({Module, Size});
}
}
}
return true;
}
int main(int argc, char **argv) {
PROGRAM_START(argc, argv);
INITIALIZE_LLVM();
// Command line handling.
using namespace llvm::cl;
static OptionCategory Visible("Specific Options");
HideUnrelatedOptions({&Visible});
list<std::string> InputNames(Positional, desc("compiled_swift_file1.o ..."),
OneOrMore, cat(Visible));
opt<bool> DumpModule(
"dump-module",
desc("Dump the imported module after checking it imports just fine"),
cat(Visible));
opt<bool> Verbose("verbose", desc("Dump informations on the loaded module"),
cat(Visible));
opt<std::string> ModuleCachePath(
"module-cache-path", desc("Clang module cache path"), cat(Visible));
opt<std::string> DumpDeclFromMangled(
"decl-from-mangled", desc("dump decl from mangled names list"),
cat(Visible));
opt<std::string> DumpTypeFromMangled(
"type-from-mangled", desc("dump type from mangled names list"),
cat(Visible));
opt<std::string> ResourceDir(
"resource-dir",
desc("The directory that holds the compiler resource files"),
cat(Visible));
ParseCommandLineOptions(argc, argv);
// Unregister our options so they don't interfere with the command line
// parsing in CodeGen/BackendUtil.cpp.
ModuleCachePath.removeArgument();
DumpModule.removeArgument();
DumpTypeFromMangled.removeArgument();
InputNames.removeArgument();
auto validateInputFile = [](std::string Filename) {
if (Filename.empty())
return true;
if (!llvm::sys::fs::exists(llvm::Twine(Filename))) {
llvm::errs() << Filename << " does not exists, exiting.\n";
return false;
}
if (!llvm::sys::fs::is_regular_file(llvm::Twine(Filename))) {
llvm::errs() << Filename << " is not a regular file, exiting.\n";
return false;
}
return true;
};
if (!validateInputFile(DumpTypeFromMangled))
return 1;
if (!validateInputFile(DumpDeclFromMangled))
return 1;
// Fetch the serialized module bitstreams from the Mach-O files and
// register them with the module loader.
llvm::SmallVector<std::pair<char *, uint64_t>, 8> Modules;
if (!collectASTModules(InputNames, Modules))
return 1;
if (Modules.empty())
return 0;
swift::serialization::ValidationInfo info;
swift::serialization::ExtendedValidationInfo extendedInfo;
for (auto &Module : Modules) {
if (!validateModule(StringRef(Module.first, Module.second), Verbose, info,
extendedInfo)) {
llvm::errs() << "Malformed module!\n";
return 1;
}
}
// Create a Swift compiler.
llvm::SmallVector<std::string, 4> modules;
swift::CompilerInstance CI;
swift::CompilerInvocation Invocation;
Invocation.setMainExecutablePath(
llvm::sys::fs::getMainExecutable(argv[0],
reinterpret_cast<void *>(&anchorForGetMainExecutable)));
// Infer SDK and Target triple from the module.
Invocation.setSDKPath(extendedInfo.getSDKPath());
Invocation.setTargetTriple(info.targetTriple);
Invocation.setModuleName("lldbtest");
Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;
if (!ResourceDir.empty()) {
Invocation.setRuntimeResourcePath(ResourceDir);
}
if (CI.setup(Invocation))
return 1;
for (auto &Module : Modules)
if (!parseASTSection(CI.getSerializedModuleLoader(),
StringRef(Module.first, Module.second), modules))
return 1;
// Attempt to import all modules we found.
for (auto path : modules) {
if (Verbose)
llvm::outs() << "Importing " << path << "... ";
#ifdef SWIFT_SUPPORTS_SUBMODULES
std::vector<std::pair<swift::Identifier, swift::SourceLoc> > AccessPath;
for (auto i = llvm::sys::path::begin(path);
i != llvm::sys::path::end(path); ++i)
if (!llvm::sys::path::is_separator((*i)[0]))
AccessPath.push_back({ CI.getASTContext().getIdentifier(*i),
swift::SourceLoc() });
#else
std::vector<std::pair<swift::Identifier, swift::SourceLoc> > AccessPath;
AccessPath.push_back({ CI.getASTContext().getIdentifier(path),
swift::SourceLoc() });
#endif
auto Module = CI.getASTContext().getModule(AccessPath);
if (!Module) {
if (Verbose)
llvm::errs() << "FAIL!\n";
return 1;
}
if (Verbose)
llvm::outs() << "ok!\n";
if (DumpModule) {
llvm::SmallVector<swift::Decl*, 10> Decls;
Module->getTopLevelDecls(Decls);
for (auto Decl : Decls) {
Decl->dump(llvm::outs());
}
}
if (!DumpTypeFromMangled.empty()) {
llvm::SmallVector<std::string, 8> MangledNames;
collectMangledNames(DumpTypeFromMangled, MangledNames);
resolveTypeFromMangledNameList(CI.getASTContext(), MangledNames);
}
if (!DumpDeclFromMangled.empty()) {
llvm::SmallVector<std::string, 8> MangledNames;
collectMangledNames(DumpDeclFromMangled, MangledNames);
resolveDeclFromMangledNameList(CI.getASTContext(), MangledNames);
}
}
return 0;
}
<|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 "otbWrapperQtWidgetView.h"
#include "otbWrapperQtWidgetParameterGroup.h"
#include "otbWrapperQtWidgetParameterFactory.h"
#include "otbWrapperOutputImageParameter.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
QtWidgetView::QtWidgetView(Application* app)
{
m_Model = new QtWidgetModel(app);
m_Application = app;
//m_MainWindow = new QWidget();
//m_Application->RegisterListener( this );
}
QtWidgetView::~QtWidgetView()
{
}
void QtWidgetView::CreateGui()
{
// Create a VBoxLayout with the header, the input widgets, and the footer
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addWidget(CreateHeader());
mainLayout->addWidget(CreateInputWidgets());
mainLayout->addWidget(CreateFooter());
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(mainLayout);
// Put the main group inside a scroll area
QScrollArea *scrollArea = new QScrollArea;
scrollArea->setWidget(mainGroup);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
QVBoxLayout *scrollLayout = new QVBoxLayout();
scrollLayout->addWidget(scrollArea);
// Make the scroll layout the main layout
this->setLayout(scrollLayout);
this->setWindowIcon(QIcon( ":/otb_small.png" ));
this->setWindowTitle(QString(m_Model->GetApplication()->GetName()).append(" - version ").append(OTB_VERSION_STRING));
this->show();
}
QWidget* QtWidgetView::CreateHeader()
{
// an HLayout with the description of the application, and two icons
QHBoxLayout *headerLayout = new QHBoxLayout;
QGroupBox *headerGroup = new QGroupBox;
headerGroup->setStyleSheet("border: 1px solid gray");
headerGroup->setFixedHeight(50);
headerGroup->setContentsMargins(0,0,0,0);
headerLayout->setContentsMargins(5,5,5,5);
QLabel *iconOTBLabel = new QLabel;
iconOTBLabel->setStyleSheet("border-style: none");
//iconOTBLabel->setPixmap(QIcon( ":/otb_big.png" ).pixmap(32, QIcon::Normal, QIcon::On));
QLabel *descriptionLabel = new QLabel;
descriptionLabel->setStyleSheet("border-style: none");
QString descriptionLabelText(m_Model->GetApplication()->GetDescription());
descriptionLabel->setText(descriptionLabelText);
QLabel *iconCNESLabel = new QLabel;
iconCNESLabel->setStyleSheet("border-style: none");
//iconCNESLabel->setPixmap(QIcon( ":/cnes.png" ).pixmap(32, QIcon::Normal, QIcon::On));
headerLayout->addWidget(iconOTBLabel);
headerLayout->addStretch();
headerLayout->addWidget(descriptionLabel);
headerLayout->addStretch();
headerLayout->addWidget(iconCNESLabel);
headerGroup->setLayout(headerLayout);
return headerGroup;
}
QWidget* QtWidgetView::CreateInputWidgets()
{
QtWidgetParameterBase* params = QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model);
return params;
}
QWidget* QtWidgetView::CreateFooter()
{
// an HLayout with two buttons : Execute and Quit
QGroupBox *footerGroup = new QGroupBox;
QHBoxLayout *footerLayout = new QHBoxLayout;
footerGroup->setFixedHeight(40);
footerGroup->setContentsMargins(0,0,0,0);
footerLayout->setContentsMargins(5,5,5,5);
m_ExecButton = new QPushButton(footerGroup);
m_ExecButton->setDefault(true);
m_ExecButton->setText(QObject::tr("Execute"));
connect( m_ExecButton, SIGNAL(clicked()), this, SLOT(ExecuteAndWriteOutputSlot() ) );
m_QuitButton = new QPushButton(footerGroup);
m_QuitButton->setText(QObject::tr("Quit"));
connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) );
// Put the buttons on the right
//footerLayout->addWidget(m_ProgressLabel);
footerLayout->addStretch();
footerLayout->addWidget(m_ExecButton);
footerLayout->addWidget(m_QuitButton);
footerGroup->setLayout(footerLayout);
return footerGroup;
}
void QtWidgetView::ExecuteAndWriteOutputSlot()
{
m_Model->ExecuteAndWriteOutput();
QWidget * progWin = new QWidget();
progWin->setWindowTitle( "Progress reporting..." );
QVBoxLayout *layout = new QVBoxLayout;
std::vector< QProgressBar * > barListIntern, barListWriter;
std::vector< QLabel * > labelListIntern, labelListWriter;
if( m_Application->GetInternalProcessList().size() != m_Application->GetInternalProcessListName().size())
{
itkGenericExceptionMacro ("Internal process list and list name size mismatch...");
}
// Build the window : First internal process
for(unsigned int ii=0; ii<m_Application->GetInternalProcessList().size(); ii++)
{
QLabel *label = new QLabel(QString(m_Application->GetInternalProcessListName()[ii].c_str()));
QProgressBar * bar = new QProgressBar();
layout->addWidget(label);
layout->addWidget(bar);
barListIntern.push_back(bar);
labelListIntern.push_back(label);
}
// Build the window : then writers
unsigned int nbOutput = 0;
std::vector<std::string> paramList = m_Application->GetParametersKeys(true);
for (std::vector<std::string>::const_iterator it = paramList.begin();
it != paramList.end();
++it)
{
if ( m_Application->GetParameterType(*it) == ParameterType_OutputImage)
{
itk::OStringStream oss;
// create the label including the output description
Parameter* param = m_Application->GetParameterByKey(*it);
OutputImageParameter* outputParam = dynamic_cast<OutputImageParameter*>(param);
oss << "Writer "<< nbOutput << ": ";
oss << outputParam->GetName() <<".";
QLabel *label = new QLabel(QString(oss.str().c_str()));
QProgressBar * bar = new QProgressBar();
bar->setToolTip( QString( outputParam->GetDescription()) );
layout->addWidget(label);
layout->addWidget(bar);
barListWriter.push_back(bar);
labelListWriter.push_back(label);
nbOutput++;
}
}
// Display the window
progWin->setLayout(layout);
progWin->update();
progWin->show();
// PAY ATTENTION : launching a GUI modification in a slot is simple : you have to call the following method
// to update the general GUI
QCoreApplication::processEvents();
// Watch process
double curWriterProgress = 0;
unsigned int curWriter = 0;
unsigned int countt = 0;
while( m_Application->GetExecuteAndWriteOutputDone() == false )
{
itk::OStringStream oss;
oss.str("");
// Internal DoExecute process watcher
std::vector<double> progCount = m_Application->GetDoExecuteProgress();
for(unsigned int i=0; i<progCount.size(); i++)
{
barListIntern[i]->setValue( static_cast<int>(progCount[i]*100 ));
progWin->update();
QCoreApplication::processEvents();
}
// Writer watcher
if( nbOutput > 0)
{
double curProg = m_Application->GetExecuteProgress();
if( curProg > -1 )
{
if( curWriterProgress > curProg )
{
curWriter++;
}
barListWriter[curWriter]->setValue( static_cast<int>(curProg*100) );
curWriterProgress = curProg;
progWin->update();
QCoreApplication::processEvents();
}
}
itksys::SystemTools::sleep(1);
}
progWin->close();
}
void QtWidgetView::CloseSlot()
{
this->close();
}
}
}
<commit_msg>BUG: wrong previous commit<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 "otbWrapperQtWidgetView.h"
#include "otbWrapperQtWidgetParameterGroup.h"
#include "otbWrapperQtWidgetParameterFactory.h"
#include "otbWrapperOutputImageParameter.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
QtWidgetView::QtWidgetView(Application* app)
{
m_Model = new QtWidgetModel(app);
m_Application = app;
//m_MainWindow = new QWidget();
//m_Application->RegisterListener( this );
}
QtWidgetView::~QtWidgetView()
{
}
void QtWidgetView::CreateGui()
{
// Create a VBoxLayout with the header, the input widgets, and the footer
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addWidget(CreateHeader());
mainLayout->addWidget(CreateInputWidgets());
mainLayout->addWidget(CreateFooter());
QGroupBox *mainGroup = new QGroupBox();
mainGroup->setLayout(mainLayout);
// Put the main group inside a scroll area
QScrollArea *scrollArea = new QScrollArea;
scrollArea->setWidget(mainGroup);
scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
QVBoxLayout *scrollLayout = new QVBoxLayout();
scrollLayout->addWidget(scrollArea);
// Make the scroll layout the main layout
this->setLayout(scrollLayout);
this->setWindowIcon(QIcon( ":/otb_small.png" ));
this->setWindowTitle(QString(m_Model->GetApplication()->GetName()).append(" - version ").append(OTB_VERSION_STRING));
this->show();
}
QWidget* QtWidgetView::CreateHeader()
{
// an HLayout with the description of the application, and two icons
QHBoxLayout *headerLayout = new QHBoxLayout;
QGroupBox *headerGroup = new QGroupBox;
headerGroup->setStyleSheet("border: 1px solid gray");
headerGroup->setFixedHeight(50);
headerGroup->setContentsMargins(0,0,0,0);
headerLayout->setContentsMargins(5,5,5,5);
QLabel *iconOTBLabel = new QLabel;
iconOTBLabel->setStyleSheet("border-style: none");
//iconOTBLabel->setPixmap(QIcon( ":/otb_big.png" ).pixmap(32, QIcon::Normal, QIcon::On));
QLabel *descriptionLabel = new QLabel;
descriptionLabel->setStyleSheet("border-style: none");
QString descriptionLabelText(m_Model->GetApplication()->GetDescription());
descriptionLabel->setText(descriptionLabelText);
QLabel *iconCNESLabel = new QLabel;
iconCNESLabel->setStyleSheet("border-style: none");
//iconCNESLabel->setPixmap(QIcon( ":/cnes.png" ).pixmap(32, QIcon::Normal, QIcon::On));
headerLayout->addWidget(iconOTBLabel);
headerLayout->addStretch();
headerLayout->addWidget(descriptionLabel);
headerLayout->addStretch();
headerLayout->addWidget(iconCNESLabel);
headerGroup->setLayout(headerLayout);
return headerGroup;
}
QWidget* QtWidgetView::CreateInputWidgets()
{
QtWidgetParameterBase* params = QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model);
return params;
}
QWidget* QtWidgetView::CreateFooter()
{
// an HLayout with two buttons : Execute and Quit
QGroupBox *footerGroup = new QGroupBox;
QHBoxLayout *footerLayout = new QHBoxLayout;
footerGroup->setFixedHeight(40);
footerGroup->setContentsMargins(0,0,0,0);
footerLayout->setContentsMargins(5,5,5,5);
m_ExecButton = new QPushButton(footerGroup);
m_ExecButton->setDefault(true);
m_ExecButton->setText(QObject::tr("Execute"));
connect( m_ExecButton, SIGNAL(clicked()), this, SLOT(ExecuteAndWriteOutputSlot() ) );
m_QuitButton = new QPushButton(footerGroup);
m_QuitButton->setText(QObject::tr("Quit"));
connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) );
// Put the buttons on the right
//footerLayout->addWidget(m_ProgressLabel);
footerLayout->addStretch();
footerLayout->addWidget(m_ExecButton);
footerLayout->addWidget(m_QuitButton);
footerGroup->setLayout(footerLayout);
return footerGroup;
}
void QtWidgetView::ExecuteAndWriteOutputSlot()
{
m_Model->ExecuteAndWriteOutput();
QWidget * progWin = new QWidget();
progWin->setWindowTitle( "Progress reporting..." );
QVBoxLayout *layout = new QVBoxLayout;
std::vector< QProgressBar * > barListIntern, barListWriter;
std::vector< QLabel * > labelListIntern, labelListWriter;
if( m_Application->GetInternalProcessList().size() != m_Application->GetInternalProcessListName().size())
{
itkGenericExceptionMacro ("Internal process list and list name size mismatch...");
}
// Build the window : First internal process
for(unsigned int ii=0; ii<m_Application->GetInternalProcessList().size(); ii++)
{
QLabel *label = new QLabel(QString(m_Application->GetInternalProcessListName()[ii].c_str()));
QProgressBar * bar = new QProgressBar();
layout->addWidget(label);
layout->addWidget(bar);
barListIntern.push_back(bar);
labelListIntern.push_back(label);
}
// Build the window : then writers
unsigned int nbOutput = 0;
std::vector<std::string> paramList = m_Application->GetParametersKeys(true);
for (std::vector<std::string>::const_iterator it = paramList.begin();
it != paramList.end();
++it)
{
if ( m_Application->GetParameterType(*it) == ParameterType_OutputImage)
{
itk::OStringStream oss;
// create the label including the output description
Parameter* param = m_Application->GetParameterByKey(*it);
OutputImageParameter* outputParam = dynamic_cast<OutputImageParameter*>(param);
oss << "Writer "<< nbOutput << ": ";
oss << outputParam->GetName() <<".";
QLabel *label = new QLabel(QString(oss.str().c_str()));
QProgressBar * bar = new QProgressBar();
bar->setToolTip( QString( outputParam->GetDescription()) );
layout->addWidget(label);
layout->addWidget(bar);
barListWriter.push_back(bar);
labelListWriter.push_back(label);
nbOutput++;
}
}
// Display the window
progWin->setLayout(layout);
progWin->update();
progWin->show();
// PAY ATTENTION : launching a GUI modification in a slot is simple : you have to call the following method
// to update the general GUI
QCoreApplication::processEvents();
// Watch process
double curWriterProgress = 0;
unsigned int curWriter = 0;
unsigned int countt = 0;
while( m_Application->GetExecuteAndWriteOutputDone() == false )
{
itk::OStringStream oss;
oss.str("");
// Internal DoExecute process watcher
std::vector<double> progCount = m_Application->GetDoExecuteProgress();
for(unsigned int i=0; i<progCount.size(); i++)
{
barListIntern[i]->setValue( static_cast<int>(progCount[i]*100 ));
progWin->update();
QCoreApplication::processEvents();
}
// Writer watcher
if( nbOutput > 0)
{
double curProg = m_Application->GetExecuteProgress();
if( curProg > -1 )
{
if( curWriterProgress > curProg )
{
curWriter++;
}
barListWriter[curWriter]->setValue( static_cast<int>(curProg*100) );
curWriterProgress = curProg;
progWin->update();
QCoreApplication::processEvents();
}
}
itksys::SystemTools::Delay(1000);
}
progWin->close();
}
void QtWidgetView::CloseSlot()
{
this->close();
}
}
}
<|endoftext|> |
<commit_before>#include "calibration/Angular_Velocity_Calibration_Wizard.h"
#include <QPushButton>
#include "sz_math.hpp"
#include "sz_Calibration_Data.hpp"
#include "ui_Angular_Velocity_Calibration_Wizard_Reset.h"
#include "ui_Angular_Velocity_Calibration_Wizard_Instructions.h"
#include "ui_Angular_Velocity_Calibration_Wizard_Collect.h"
#include "ui_Angular_Velocity_Calibration_Wizard_Done.h"
constexpr std::chrono::seconds DATA_COLLECTION_DURATION(10);
Angular_Velocity_Calibration_Wizard::Angular_Velocity_Calibration_Wizard(silk::HAL& hal, silk::Comms& comms, silk::node::gs::Node_ptr node, size_t output_idx, QWidget* parent)
: QDialog(parent)
, m_hal(hal)
, m_comms(comms)
, m_node(node)
, m_output(node->outputs[output_idx])
{
m_stream = std::static_pointer_cast<silk::stream::gs::Angular_Velocity>(m_output.stream);
m_hal.set_stream_telemetry_active(m_output.stream->name, true);
m_initial_calibration = get_calibration_points();
set_calibration_points(sz::calibration::Angular_Velocity_Points());
m_step = Step::RESET;
setLayout(new QVBoxLayout(this));
layout()->setMargin(0);
layout()->setSpacing(0);
layout()->setContentsMargins(4, 4, 4, 4);
prepare_step();
}
void Angular_Velocity_Calibration_Wizard::advance()
{
if (m_step == Step::RESET)
{
m_step = Step::SHOW_INSTRUCTIONS;
}
else if (m_step == Step::SHOW_INSTRUCTIONS)
{
m_step = Step::COLLECT;
}
else if (m_step == Step::COLLECT)
{
m_connection.disconnect();
m_step = Step::DONE;
}
prepare_step();
}
void Angular_Velocity_Calibration_Wizard::cancel()
{
m_connection.disconnect();
set_calibration_points(m_initial_calibration);
close();
}
void Angular_Velocity_Calibration_Wizard::prepare_step()
{
delete m_content;
m_content = nullptr;
if (m_step == Step::RESET)
{
m_content = new QWidget(this);
layout()->addWidget(m_content);
Ui::Angular_Velocity_Calibration_Wizard_Reset ui;
ui.setupUi(m_content);
if (m_initial_calibration.points.size() > 0)
{
ui.info->setText(q::util::format2<std::string>("There are currently {} calibration points.\n"
"Do you want to clear these points or keep them?", m_initial_calibration.points.size()).c_str());
auto* clear = ui.buttonBox->addButton("Clear", QDialogButtonBox::ResetRole);
QObject::connect(clear, &QPushButton::released, [this]() { advance(); });
auto* keep = ui.buttonBox->addButton("Keep", QDialogButtonBox::AcceptRole);
QObject::connect(keep, &QPushButton::released, [this]() { m_crt_calibration = m_initial_calibration; advance(); });
}
else
{
ui.info->setText("There are no existing calibration data points.\nLet's add one");
auto* ok = ui.buttonBox->addButton("Ok", QDialogButtonBox::AcceptRole);
QObject::connect(ok, &QPushButton::released, [this]() { advance(); });
}
QObject::connect(ui.buttonBox, &QDialogButtonBox::rejected, [this]() { cancel(); });
}
else if (m_step == Step::SHOW_INSTRUCTIONS)
{
m_content = new QWidget(this);
layout()->addWidget(m_content);
Ui::Angular_Velocity_Calibration_Wizard_Instructions ui;
ui.setupUi(m_content);
ui.instructions->setText(q::util::format2<std::string>(
"Please keep the UAV perfectly still for {} seconds.\n"
"\n"
"Ready?", DATA_COLLECTION_DURATION).c_str());
QObject::connect(ui.buttonBox, &QDialogButtonBox::accepted, [this]() { advance(); });
QObject::connect(ui.buttonBox, &QDialogButtonBox::rejected, [this]() { cancel(); });
}
else if (m_step == Step::COLLECT)
{
m_content = new QWidget(this);
layout()->addWidget(m_content);
Ui::Angular_Velocity_Calibration_Wizard_Collect ui;
ui.setupUi(m_content);
auto* info = ui.info;
auto* progress = ui.progressBar;
m_samples.clear();
QObject::connect(ui.buttonBox, &QDialogButtonBox::rejected, [this]() { cancel(); });
m_connection = m_stream->samples_available_signal.connect([this, info, progress](silk::stream::gs::Angular_Velocity::Samples const& samples)
{
on_samples_received(samples);
info->setText(q::util::format2<std::string>("Collected {} samples...", m_samples.size()).c_str());
size_t needed_samples = std::chrono::seconds(DATA_COLLECTION_DURATION).count() * m_output.rate;
progress->setValue(float(m_samples.size() * 100.f) / float(needed_samples));
if (m_samples.size() >= needed_samples)
{
advance();
}
});
}
else if (m_step == Step::DONE)
{
math::vec3f bias = std::accumulate(m_samples.begin(), m_samples.end(), math::vec3f());
bias /= static_cast<float>(m_samples.size());
m_content = new QWidget(this);
layout()->addWidget(m_content);
Ui::Angular_Velocity_Calibration_Wizard_Done ui;
ui.setupUi(m_content);
ui.info->setText("Done!\n"
"The new Bias is:");
ui.bias->setText(q::util::format2<std::string>("{}", bias).c_str());
sz::calibration::Angular_Velocity point;
point.temperature = 0;
point.bias = math::vec3f(bias);
m_crt_calibration.points.push_back(point);
QObject::connect(ui.temperature, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), [this](double value)
{
m_crt_calibration.points.back().temperature = static_cast<float>(value);
});
QObject::connect(ui.buttonBox, &QDialogButtonBox::accepted, [this]()
{
set_calibration_points(m_crt_calibration);
this->accept();
});
QObject::connect(ui.buttonBox, &QDialogButtonBox::rejected, [this]() { cancel(); });
}
}
void Angular_Velocity_Calibration_Wizard::set_calibration_points(sz::calibration::Angular_Velocity_Points const& data)
{
rapidjson::Document calibrationj;
calibrationj.SetObject();
autojsoncxx::to_document(data, calibrationj);
q::Path path("Calibration");
path += m_output.name;
rapidjson::Document configj = jsonutil::clone_value(m_node->config);
if (!jsonutil::remove_value(configj, path))
{
QASSERT(0);
return;
}
if (!jsonutil::add_value(configj, path, std::move(calibrationj), configj.GetAllocator()))
{
QASSERT(0);
return;
}
m_hal.set_node_config(m_node, configj);
}
auto Angular_Velocity_Calibration_Wizard::get_calibration_points() const -> sz::calibration::Angular_Velocity_Points
{
q::Path path("Calibration");
path += m_output.name;
auto const* calibrationj = jsonutil::find_value(m_node->config, path);
if (!calibrationj)
{
QASSERT(0);
return sz::calibration::Angular_Velocity_Points();
}
sz::calibration::Angular_Velocity_Points calibration;
autojsoncxx::error::ErrorStack result;
if (!autojsoncxx::from_value(calibration, *calibrationj, result))
{
QASSERT(0);
return sz::calibration::Angular_Velocity_Points();
}
return calibration;
}
void Angular_Velocity_Calibration_Wizard::on_samples_received(silk::stream::gs::Angular_Velocity::Samples const& samples)
{
m_samples.reserve(m_samples.size() + samples.size());
for (auto const& s: samples)
{
m_samples.push_back(s.value);
}
}
<commit_msg>Fixed broken cancel<commit_after>#include "calibration/Angular_Velocity_Calibration_Wizard.h"
#include <QPushButton>
#include "sz_math.hpp"
#include "sz_Calibration_Data.hpp"
#include "ui_Angular_Velocity_Calibration_Wizard_Reset.h"
#include "ui_Angular_Velocity_Calibration_Wizard_Instructions.h"
#include "ui_Angular_Velocity_Calibration_Wizard_Collect.h"
#include "ui_Angular_Velocity_Calibration_Wizard_Done.h"
constexpr std::chrono::seconds DATA_COLLECTION_DURATION(10);
Angular_Velocity_Calibration_Wizard::Angular_Velocity_Calibration_Wizard(silk::HAL& hal, silk::Comms& comms, silk::node::gs::Node_ptr node, size_t output_idx, QWidget* parent)
: QDialog(parent)
, m_hal(hal)
, m_comms(comms)
, m_node(node)
, m_output(node->outputs[output_idx])
{
m_stream = std::static_pointer_cast<silk::stream::gs::Angular_Velocity>(m_output.stream);
m_hal.set_stream_telemetry_active(m_output.stream->name, true);
m_initial_calibration = get_calibration_points();
set_calibration_points(sz::calibration::Angular_Velocity_Points());
m_step = Step::RESET;
setLayout(new QVBoxLayout(this));
layout()->setMargin(0);
layout()->setSpacing(0);
layout()->setContentsMargins(4, 4, 4, 4);
prepare_step();
}
void Angular_Velocity_Calibration_Wizard::advance()
{
if (m_step == Step::RESET)
{
m_step = Step::SHOW_INSTRUCTIONS;
}
else if (m_step == Step::SHOW_INSTRUCTIONS)
{
m_step = Step::COLLECT;
}
else if (m_step == Step::COLLECT)
{
m_connection.disconnect();
m_step = Step::DONE;
}
prepare_step();
}
void Angular_Velocity_Calibration_Wizard::cancel()
{
m_connection.disconnect();
set_calibration_points(m_initial_calibration);
close();
}
void Angular_Velocity_Calibration_Wizard::prepare_step()
{
delete m_content;
m_content = nullptr;
if (m_step == Step::RESET)
{
m_content = new QWidget(this);
layout()->addWidget(m_content);
Ui::Angular_Velocity_Calibration_Wizard_Reset ui;
ui.setupUi(m_content);
if (m_initial_calibration.points.size() > 0)
{
ui.info->setText(q::util::format2<std::string>("There are currently {} calibration points.\n"
"Do you want to clear these points or keep them?", m_initial_calibration.points.size()).c_str());
auto* clear = ui.buttonBox->addButton("Clear", QDialogButtonBox::ResetRole);
QObject::connect(clear, &QPushButton::released, [this]() { advance(); });
auto* keep = ui.buttonBox->addButton("Keep", QDialogButtonBox::AcceptRole);
QObject::connect(keep, &QPushButton::released, [this]() { m_crt_calibration = m_initial_calibration; advance(); });
}
else
{
ui.info->setText("There are no existing calibration data points.\nLet's add one");
auto* ok = ui.buttonBox->addButton("Ok", QDialogButtonBox::AcceptRole);
QObject::connect(ok, &QPushButton::released, [this]() { advance(); });
}
QObject::connect(ui.buttonBox, &QDialogButtonBox::rejected, [this]()
{
cancel();
});
}
else if (m_step == Step::SHOW_INSTRUCTIONS)
{
m_content = new QWidget(this);
layout()->addWidget(m_content);
Ui::Angular_Velocity_Calibration_Wizard_Instructions ui;
ui.setupUi(m_content);
ui.instructions->setText(q::util::format2<std::string>(
"Please keep the UAV perfectly still for {} seconds.\n"
"\n"
"Ready?", DATA_COLLECTION_DURATION).c_str());
QObject::connect(ui.buttonBox, &QDialogButtonBox::accepted, [this]()
{
advance();
});
QObject::connect(ui.buttonBox, &QDialogButtonBox::rejected, [this]()
{
cancel();
});
}
else if (m_step == Step::COLLECT)
{
m_content = new QWidget(this);
layout()->addWidget(m_content);
Ui::Angular_Velocity_Calibration_Wizard_Collect ui;
ui.setupUi(m_content);
auto* info = ui.info;
auto* progress = ui.progressBar;
m_samples.clear();
QObject::connect(ui.buttonBox, &QDialogButtonBox::rejected, [this]() { cancel(); });
m_connection = m_stream->samples_available_signal.connect([this, info, progress](silk::stream::gs::Angular_Velocity::Samples const& samples)
{
on_samples_received(samples);
info->setText(q::util::format2<std::string>("Collected {} samples...", m_samples.size()).c_str());
size_t needed_samples = std::chrono::seconds(DATA_COLLECTION_DURATION).count() * m_output.rate;
progress->setValue(float(m_samples.size() * 100.f) / float(needed_samples));
if (m_samples.size() >= needed_samples)
{
advance();
}
});
}
else if (m_step == Step::DONE)
{
math::vec3f bias = std::accumulate(m_samples.begin(), m_samples.end(), math::vec3f());
bias /= static_cast<float>(m_samples.size());
m_content = new QWidget(this);
layout()->addWidget(m_content);
Ui::Angular_Velocity_Calibration_Wizard_Done ui;
ui.setupUi(m_content);
ui.info->setText("Done!\n"
"The new Bias is:");
ui.bias->setText(q::util::format2<std::string>("{}", bias).c_str());
sz::calibration::Angular_Velocity point;
point.temperature = 0;
point.bias = math::vec3f(bias);
m_crt_calibration.points.push_back(point);
QObject::connect(ui.temperature, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), [this](double value)
{
m_crt_calibration.points.back().temperature = static_cast<float>(value);
});
QObject::connect(ui.buttonBox, &QDialogButtonBox::accepted, [this]()
{
set_calibration_points(m_crt_calibration);
this->accept();
});
QDialogButtonBox* buttonBox = ui.buttonBox;//make a copy as the ui will go out of scope
QObject::connect(ui.buttonBox, &QDialogButtonBox::clicked, [buttonBox, this](QAbstractButton* button)
{
if (buttonBox->buttonRole(button) == QDialogButtonBox::DestructiveRole)
{
cancel();
}
});
}
}
void Angular_Velocity_Calibration_Wizard::set_calibration_points(sz::calibration::Angular_Velocity_Points const& data)
{
rapidjson::Document calibrationj;
calibrationj.SetObject();
autojsoncxx::to_document(data, calibrationj);
q::Path path("Calibration");
path += m_output.name;
rapidjson::Document configj = jsonutil::clone_value(m_node->config);
if (!jsonutil::remove_value(configj, path))
{
QASSERT(0);
return;
}
if (!jsonutil::add_value(configj, path, std::move(calibrationj), configj.GetAllocator()))
{
QASSERT(0);
return;
}
m_hal.set_node_config(m_node, configj);
}
auto Angular_Velocity_Calibration_Wizard::get_calibration_points() const -> sz::calibration::Angular_Velocity_Points
{
q::Path path("Calibration");
path += m_output.name;
auto const* calibrationj = jsonutil::find_value(m_node->config, path);
if (!calibrationj)
{
QASSERT(0);
return sz::calibration::Angular_Velocity_Points();
}
sz::calibration::Angular_Velocity_Points calibration;
autojsoncxx::error::ErrorStack result;
if (!autojsoncxx::from_value(calibration, *calibrationj, result))
{
QASSERT(0);
return sz::calibration::Angular_Velocity_Points();
}
return calibration;
}
void Angular_Velocity_Calibration_Wizard::on_samples_received(silk::stream::gs::Angular_Velocity::Samples const& samples)
{
m_samples.reserve(m_samples.size() + samples.size());
for (auto const& s: samples)
{
m_samples.push_back(s.value);
}
}
<|endoftext|> |
<commit_before>#include "imgui.h"
#include <babylon/buffers/vertex_buffer.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/core/random.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/pbr/pbr_material.h>
#include <babylon/materials/textures/hdr_cube_texture.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
#include <babylon/morph/morph_target_manager.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
namespace Samples {
using MeshPtr = std::shared_ptr<Mesh>;
using MorphTargetPtr = std::shared_ptr<MorphTarget>;
/**
* @brief Morph Targets Scene. Example demonstrating how to morph a mesh between multiple targets
* @see https://www.babylonjs-playground.com/#2JDN66#7
* @see https://doc.babylonjs.com/how_to/how_to_use_morphtargets
*/
struct MorphTargetsScene : public IRenderableSceneWithHud {
MorphTargetsScene(ICanvas* iCanvas = nullptr) : IRenderableSceneWithHud(iCanvas)
{
}
~MorphTargetsScene() override = default;
const char* getName() override
{
return "Materials Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// This creates and positions a free camera (non-mesh)
auto camera
= ArcRotateCamera::New(std::string("camera1"), 1.14f, 1.13f, 10.f, Vector3::Zero(), scene);
// This targets the camera to scene origin
camera->setTarget(Vector3::Zero());
// This attaches the camera to the canvas
camera->attachControl(canvas, true);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
auto light = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.f), scene);
// Default intensity is 1. Let's dim the light a small amount
light->intensity = 0.f;
// Our built-in 'sphere' shape. Params: name, subdivs, size, scene
auto sphere = Mesh::CreateSphere("sphere1", 16, 2.f, scene);
auto hdrTexture = HDRCubeTexture::New("/textures/room.hdr", scene, 512);
auto exposure = 0.6f;
auto contrast = 1.6f;
auto glass = PBRMaterial::New("glass", scene);
glass->reflectionTexture = hdrTexture;
glass->refractionTexture = hdrTexture;
glass->linkRefractionWithTransparency = true;
glass->indexOfRefraction = 0.52f;
glass->alpha = 0.f;
glass->cameraExposure = exposure;
glass->cameraContrast = contrast;
glass->microSurface = 1.f;
glass->reflectivityColor = Color3(0.2f, 0.2f, 0.2f);
glass->albedoColor = Color3(0.85f, 0.85f, 0.85f);
sphere->material = glass;
auto sphere2 = Mesh::CreateSphere("sphere2", 16, 2.f, scene);
sphere2->setEnabled(false);
_addSpike(sphere2);
auto sphere3 = Mesh::CreateSphere("sphere3", 16, 2.f, scene);
sphere3->setEnabled(false);
_addSpike(sphere3);
auto sphere4 = Mesh::CreateSphere("sphere4", 16, 2.f, scene);
sphere4->setEnabled(false);
_addSpike(sphere4);
auto sphere5 = Mesh::CreateSphere("sphere5", 16, 2.f, scene);
sphere5->setEnabled(false);
_addSpike(sphere5);
auto manager = MorphTargetManager::New();
sphere->morphTargetManager = manager;
_target0 = MorphTarget::FromMesh(sphere2, "sphere2", 0.25f);
manager->addTarget(_target0);
_target1 = MorphTarget::FromMesh(sphere3, "sphere3", 0.25f);
manager->addTarget(_target1);
_target2 = MorphTarget::FromMesh(sphere4, "sphere4", 0.25f);
manager->addTarget(_target2);
_target3 = MorphTarget::FromMesh(sphere5, "sphere5", 0.25f);
manager->addTarget(_target3);
// Set influences
_target0->influence = 0.25f;
_target1->influence = 0.50f;
_target2->influence = 0.75f;
_target3->influence = 1.00f;
hudGui = [=]() {
auto addSlider
= [](const std::string& label, auto& floatProperty, float min = 0.f, float max = 1.f) {
float currentValue = floatProperty;
if (ImGui::SliderFloat(label.c_str(), ¤tValue, min, max))
floatProperty = currentValue;
};
addSlider("Influence #1", _target0->influence);
addSlider("Influence #2", _target1->influence);
addSlider("Influence #3", _target2->influence);
addSlider("Influence #4", _target3->influence);
addSlider("cameraContrast", glass->cameraContrast);
addSlider("cameraExposure", glass->cameraExposure, 0., 2.);
addSlider("microSurface", glass->microSurface, 0., 2.);
addSlider("indexOfRefraction", glass->indexOfRefraction, 0., 2.);
addSlider("alpha", glass->alpha, 0., 2.);
};
}
private:
void _addSpike(const MeshPtr& mesh)
{
auto positions = mesh->getVerticesData(VertexBuffer::PositionKind);
auto normals = mesh->getVerticesData(VertexBuffer::NormalKind);
auto indices = mesh->getIndices();
for (size_t index = 0; index < 5; ++index) {
auto randomVertexID = static_cast<unsigned int>(mesh->getTotalVertices() * Math::random());
auto position = Vector3::FromArray(positions, randomVertexID * 3);
auto normal = Vector3::FromArray(normals, randomVertexID * 3);
position.addInPlace(normal);
position.toArray(positions, randomVertexID * 3);
}
VertexData::ComputeNormals(positions, indices, normals);
mesh->updateVerticesData(VertexBuffer::PositionKind, positions, false, false);
mesh->updateVerticesData(VertexBuffer::NormalKind, normals, false, false);
}
private:
using MeshPtr = std::shared_ptr<Mesh>;
using MorphTargetPtr = std::shared_ptr<MorphTarget>;
MorphTargetPtr _target0;
MorphTargetPtr _target1;
MorphTargetPtr _target2;
MorphTargetPtr _target3;
};
std::shared_ptr<BABYLON::IRenderableScene> MakeMorphTargetsScene(ICanvas* iCanvas)
{
return std::make_shared<MorphTargetsScene>(iCanvas);
}
BABYLON_REGISTER_SAMPLE("Animations", MorphTargetsScene)
} // end of namespace Samples
} // end of namespace BABYLON
<commit_msg>Using macro for forward declarations<commit_after>#include "imgui.h"
#include <babylon/babylon_fwd.h>
#include <babylon/buffers/vertex_buffer.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/core/random.h>
#include <babylon/interfaces/irenderable_scene_with_hud.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/pbr/pbr_material.h>
#include <babylon/materials/textures/hdr_cube_texture.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
#include <babylon/morph/morph_target_manager.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
namespace Samples {
FWD_CLASS_SPTR(Mesh)
FWD_CLASS_SPTR(MorphTarget)
/**
* @brief Morph Targets Scene. Example demonstrating how to morph a mesh between multiple targets
* @see https://www.babylonjs-playground.com/#2JDN66#7
* @see https://doc.babylonjs.com/how_to/how_to_use_morphtargets
*/
struct MorphTargetsScene : public IRenderableSceneWithHud {
MorphTargetsScene(ICanvas* iCanvas = nullptr) : IRenderableSceneWithHud(iCanvas)
{
}
~MorphTargetsScene() override = default;
const char* getName() override
{
return "Materials Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// This creates and positions a free camera (non-mesh)
auto camera
= ArcRotateCamera::New(std::string("camera1"), 1.14f, 1.13f, 10.f, Vector3::Zero(), scene);
// This targets the camera to scene origin
camera->setTarget(Vector3::Zero());
// This attaches the camera to the canvas
camera->attachControl(canvas, true);
// This creates a light, aiming 0,1,0 - to the sky (non-mesh)
auto light = HemisphericLight::New("light1", Vector3(0.f, 1.f, 0.f), scene);
// Default intensity is 1. Let's dim the light a small amount
light->intensity = 0.f;
// Our built-in 'sphere' shape. Params: name, subdivs, size, scene
auto sphere = Mesh::CreateSphere("sphere1", 16, 2.f, scene);
auto hdrTexture = HDRCubeTexture::New("/textures/room.hdr", scene, 512);
auto exposure = 0.6f;
auto contrast = 1.6f;
auto glass = PBRMaterial::New("glass", scene);
glass->reflectionTexture = hdrTexture;
glass->refractionTexture = hdrTexture;
glass->linkRefractionWithTransparency = true;
glass->indexOfRefraction = 0.52f;
glass->alpha = 0.f;
glass->cameraExposure = exposure;
glass->cameraContrast = contrast;
glass->microSurface = 1.f;
glass->reflectivityColor = Color3(0.2f, 0.2f, 0.2f);
glass->albedoColor = Color3(0.85f, 0.85f, 0.85f);
sphere->material = glass;
auto sphere2 = Mesh::CreateSphere("sphere2", 16, 2.f, scene);
sphere2->setEnabled(false);
_addSpike(sphere2);
auto sphere3 = Mesh::CreateSphere("sphere3", 16, 2.f, scene);
sphere3->setEnabled(false);
_addSpike(sphere3);
auto sphere4 = Mesh::CreateSphere("sphere4", 16, 2.f, scene);
sphere4->setEnabled(false);
_addSpike(sphere4);
auto sphere5 = Mesh::CreateSphere("sphere5", 16, 2.f, scene);
sphere5->setEnabled(false);
_addSpike(sphere5);
auto manager = MorphTargetManager::New();
sphere->morphTargetManager = manager;
_target0 = MorphTarget::FromMesh(sphere2, "sphere2", 0.25f);
manager->addTarget(_target0);
_target1 = MorphTarget::FromMesh(sphere3, "sphere3", 0.25f);
manager->addTarget(_target1);
_target2 = MorphTarget::FromMesh(sphere4, "sphere4", 0.25f);
manager->addTarget(_target2);
_target3 = MorphTarget::FromMesh(sphere5, "sphere5", 0.25f);
manager->addTarget(_target3);
// Set influences
_target0->influence = 0.25f;
_target1->influence = 0.50f;
_target2->influence = 0.75f;
_target3->influence = 1.00f;
hudGui = [=]() {
auto addSlider
= [](const std::string& label, auto& floatProperty, float min = 0.f, float max = 1.f) {
float currentValue = floatProperty;
if (ImGui::SliderFloat(label.c_str(), ¤tValue, min, max))
floatProperty = currentValue;
};
addSlider("Influence #1", _target0->influence);
addSlider("Influence #2", _target1->influence);
addSlider("Influence #3", _target2->influence);
addSlider("Influence #4", _target3->influence);
addSlider("cameraContrast", glass->cameraContrast);
addSlider("cameraExposure", glass->cameraExposure, 0., 2.);
addSlider("microSurface", glass->microSurface, 0., 2.);
addSlider("indexOfRefraction", glass->indexOfRefraction, 0., 2.);
addSlider("alpha", glass->alpha, 0., 2.);
};
}
private:
void _addSpike(const MeshPtr& mesh)
{
auto positions = mesh->getVerticesData(VertexBuffer::PositionKind);
auto normals = mesh->getVerticesData(VertexBuffer::NormalKind);
auto indices = mesh->getIndices();
for (size_t index = 0; index < 5; ++index) {
auto randomVertexID = static_cast<unsigned int>(mesh->getTotalVertices() * Math::random());
auto position = Vector3::FromArray(positions, randomVertexID * 3);
auto normal = Vector3::FromArray(normals, randomVertexID * 3);
position.addInPlace(normal);
position.toArray(positions, randomVertexID * 3);
}
VertexData::ComputeNormals(positions, indices, normals);
mesh->updateVerticesData(VertexBuffer::PositionKind, positions, false, false);
mesh->updateVerticesData(VertexBuffer::NormalKind, normals, false, false);
}
private:
using MeshPtr = std::shared_ptr<Mesh>;
using MorphTargetPtr = std::shared_ptr<MorphTarget>;
MorphTargetPtr _target0;
MorphTargetPtr _target1;
MorphTargetPtr _target2;
MorphTargetPtr _target3;
};
std::shared_ptr<BABYLON::IRenderableScene> MakeMorphTargetsScene(ICanvas* iCanvas)
{
return std::make_shared<MorphTargetsScene>(iCanvas);
}
BABYLON_REGISTER_SAMPLE("Animations", MorphTargetsScene)
} // end of namespace Samples
} // end of namespace BABYLON
<|endoftext|> |
<commit_before>#include "chrono_parallel/lcp/ChLcpSolverParallel.h"
#include "chrono_parallel/math/ChThrustLinearAlgebra.h"
#include "chrono_parallel/solver/ChSolverAPGD.h"
#include "chrono_parallel/solver/ChSolverAPGDREF.h"
#include "chrono_parallel/solver/ChSolverBiCG.h"
#include "chrono_parallel/solver/ChSolverBiCGStab.h"
#include "chrono_parallel/solver/ChSolverCG.h"
#include "chrono_parallel/solver/ChSolverCGS.h"
#include "chrono_parallel/solver/ChSolverMinRes.h"
#include "chrono_parallel/solver/ChSolverSD.h"
#include "chrono_parallel/solver/ChSolverGD.h"
#include "chrono_parallel/solver/ChSolverPGS.h"
#include "chrono_parallel/solver/ChSolverJacobi.h"
#include "chrono_parallel/solver/ChSolverPDIP.h"
using namespace chrono;
void ChLcpSolverParallelDVI::RunTimeStep(real step)
{
// Setup constants and other values for system
data_container->settings.step_size = step;
data_container->settings.solver.tol_speed = step * data_container->settings.solver.tolerance;
// Compute the offsets and number of constrains depending on the solver mode
if (data_container->settings.solver.solver_mode == NORMAL) {
rigid_rigid.offset = 1;
data_container->num_unilaterals = 1 * data_container->num_contacts;
} else if (data_container->settings.solver.solver_mode == SLIDING) {
rigid_rigid.offset = 3;
data_container->num_unilaterals = 3 * data_container->num_contacts;
} else if (data_container->settings.solver.solver_mode == SPINNING) {
rigid_rigid.offset = 6;
data_container->num_unilaterals = 6 * data_container->num_contacts;
}
// This is the total number of constraints
data_container->num_constraints = data_container->num_unilaterals + data_container->num_bilaterals;
// This is the total number of degrees of freedom in the system
data_container->num_dof = data_container->num_bodies * 6 + data_container->num_shafts;
// Generate the mass matrix and compute M_inv_k
ComputeMassMatrix();
data_container->host_data.gamma.resize(data_container->num_constraints);
data_container->host_data.gamma.reset();
// Perform any setup tasks for all constraint types
rigid_rigid.Setup(data_container);
bilateral.Setup(data_container);
// Clear and reset solver history data and counters
solver->current_iteration = 0;
data_container->measures.solver.total_iteration = 0;
data_container->measures.solver.maxd_hist.clear();
data_container->measures.solver.maxdeltalambda_hist.clear();
data_container->measures.solver.iter_hist.clear();
// Set pointers to constraint objects and perform setup actions for solver
solver->rigid_rigid = &rigid_rigid;
solver->bilateral = &bilateral;
solver->Setup(data_container);
ComputeD();
ComputeE();
ComputeR();
// solve for the normal
if (data_container->settings.solver.solver_mode == NORMAL || data_container->settings.solver.solver_mode == SLIDING || data_container->settings.solver.solver_mode == SPINNING) {
if (data_container->settings.solver.max_iteration_normal > 0) {
solver->SetMaxIterations(data_container->settings.solver.max_iteration_normal);
data_container->settings.solver.local_solver_mode = NORMAL;
data_container->system_timer.start("ChLcpSolverParallel_Solve");
PerformStabilization();
solver->Solve();
data_container->system_timer.stop("ChLcpSolverParallel_Solve");
}
}
if (data_container->settings.solver.solver_mode != NORMAL) {
if (data_container->settings.solver.max_iteration_sliding > 0) {
solver->SetMaxIterations(data_container->settings.solver.max_iteration_sliding);
data_container->settings.solver.local_solver_mode = SLIDING;
data_container->system_timer.start("ChLcpSolverParallel_Solve");
PerformStabilization();
solver->Solve();
data_container->system_timer.stop("ChLcpSolverParallel_Solve");
}
}
if (data_container->settings.solver.solver_mode == SPINNING) {
if (data_container->settings.solver.max_iteration_spinning > 0) {
solver->SetMaxIterations(data_container->settings.solver.max_iteration_spinning);
data_container->settings.solver.local_solver_mode = SPINNING;
data_container->system_timer.start("ChLcpSolverParallel_Solve");
PerformStabilization();
solver->Solve();
data_container->system_timer.stop("ChLcpSolverParallel_Solve");
}
}
ComputeImpulses();
for (int i = 0; i < data_container->measures.solver.iter_hist.size(); i++) {
AtIterationEnd(data_container->measures.solver.maxd_hist[i], data_container->measures.solver.maxdeltalambda_hist[i], data_container->measures.solver.iter_hist[i]);
}
tot_iterations = data_container->measures.solver.iter_hist.size();
#if PRINT_LEVEL == 2
std::cout << "Solve Done: " << residual << std::endl;
#endif
}
void ChLcpSolverParallelDVI::ComputeD()
{
uint num_constraints = data_container->num_constraints;
if (num_constraints <= 0) {
return;
}
uint num_bodies = data_container->num_bodies;
uint num_shafts = data_container->num_shafts;
uint num_dof = data_container->num_dof;
uint num_contacts = data_container->num_contacts;
uint num_bilaterals = data_container->num_bilaterals;
uint nnz_bilaterals = data_container->nnz_bilaterals;
int nnz_normal = 6 * 2 * data_container->num_contacts;
int nnz_tangential = 6 * 4 * data_container->num_contacts;
int nnz_spinning = 6 * 3 * data_container->num_contacts;
int num_normal = 1 * data_container->num_contacts;
int num_tangential = 2 * data_container->num_contacts;
int num_spinning = 3 * data_container->num_contacts;
CompressedMatrix<real>& D_n_T = data_container->host_data.D_n_T;
CompressedMatrix<real>& D_t_T = data_container->host_data.D_t_T;
CompressedMatrix<real>& D_s_T = data_container->host_data.D_s_T;
CompressedMatrix<real>& D_b_T = data_container->host_data.D_b_T;
CompressedMatrix<real>& D_n = data_container->host_data.D_n;
CompressedMatrix<real>& D_t = data_container->host_data.D_t;
CompressedMatrix<real>& D_s = data_container->host_data.D_s;
CompressedMatrix<real>& D_b = data_container->host_data.D_b;
CompressedMatrix<real>& M_invD_n = data_container->host_data.M_invD_n;
CompressedMatrix<real>& M_invD_t = data_container->host_data.M_invD_t;
CompressedMatrix<real>& M_invD_s = data_container->host_data.M_invD_s;
CompressedMatrix<real>& M_invD_b = data_container->host_data.M_invD_b;
const CompressedMatrix<real>& M_inv = data_container->host_data.M_inv;
switch (data_container->settings.solver.solver_mode) {
case NORMAL:
clear(D_n_T);
D_n_T.reserve(nnz_normal);
D_n_T.resize(num_normal, num_dof, false);
break;
case SLIDING:
clear(D_n_T);
clear(D_t_T);
D_n_T.reserve(nnz_normal);
D_t_T.reserve(nnz_tangential);
D_n_T.resize(num_normal, num_dof, false);
D_t_T.resize(num_tangential, num_dof, false);
break;
case SPINNING:
clear(D_n_T);
clear(D_t_T);
clear(D_s_T);
D_n_T.reserve(nnz_normal);
D_t_T.reserve(nnz_tangential);
D_s_T.reserve(nnz_spinning);
D_n_T.resize(num_normal, num_dof, false);
D_t_T.resize(num_tangential, num_dof, false);
D_s_T.resize(num_spinning, num_dof, false);
break;
}
clear(D_b_T);
D_b_T.reserve(nnz_bilaterals);
rigid_rigid.GenerateSparsity();
bilateral.GenerateSparsity();
rigid_rigid.Build_D();
bilateral.Build_D();
D_n = trans(D_n_T);
D_t = trans(D_t_T);
D_s = trans(D_s_T);
D_b = trans(D_b_T);
M_invD_n = M_inv * D_n;
M_invD_t = M_inv * D_t;
M_invD_s = M_inv * D_s;
M_invD_b = M_inv * D_b;
}
void ChLcpSolverParallelDVI::ComputeE()
{
if (data_container->num_constraints <= 0) {
return;
}
data_container->host_data.E.resize(data_container->num_constraints);
reset(data_container->host_data.E);
rigid_rigid.Build_E();
bilateral.Build_E();
}
void ChLcpSolverParallelDVI::ComputeR()
{
if (data_container->num_constraints <= 0) {
return;
}
data_container->host_data.b.resize(data_container->num_constraints);
reset(data_container->host_data.b);
rigid_rigid.Build_b();
bilateral.Build_b();
data_container->host_data.R = -data_container->host_data.b - data_container->host_data.D_T * data_container->host_data.M_invk;
}
void ChLcpSolverParallelDVI::ChangeSolverType(SOLVERTYPE type) {
data_container->settings.solver.solver_type = type;
if (this->solver) {
delete (this->solver);
}
if (type == STEEPEST_DESCENT) {
solver = new ChSolverSD();
} else if (type == GRADIENT_DESCENT) {
solver = new ChSolverGD();
} else if (type == CONJUGATE_GRADIENT) {
solver = new ChSolverCG();
} else if (type == CONJUGATE_GRADIENT_SQUARED) {
solver = new ChSolverCGS();
} else if (type == BICONJUGATE_GRADIENT) {
solver = new ChSolverBiCG();
} else if (type == BICONJUGATE_GRADIENT_STAB) {
solver = new ChSolverBiCGStab();
} else if (type == MINIMUM_RESIDUAL) {
solver = new ChSolverMinRes();
} else if (type == QUASAI_MINIMUM_RESIDUAL) {
// // This solver has not been implemented yet
// //SolveQMR(data_container->gpu_data.device_gam_data, rhs, max_iteration);
} else if (type == APGD) {
solver = new ChSolverAPGD();
} else if (type == APGDREF) {
solver = new ChSolverAPGDREF();
} else if (type == JACOBI) {
solver = new ChSolverJacobi();
} else if (type == GAUSS_SEIDEL) {
solver = new ChSolverPGS();
} else if (type == PDIP) {
solver = new ChSolverPDIP();
}
}
<commit_msg>Update the ComputeR function with the new split jacobians<commit_after>#include "chrono_parallel/lcp/ChLcpSolverParallel.h"
#include "chrono_parallel/math/ChThrustLinearAlgebra.h"
#include "chrono_parallel/solver/ChSolverAPGD.h"
#include "chrono_parallel/solver/ChSolverAPGDREF.h"
#include "chrono_parallel/solver/ChSolverBiCG.h"
#include "chrono_parallel/solver/ChSolverBiCGStab.h"
#include "chrono_parallel/solver/ChSolverCG.h"
#include "chrono_parallel/solver/ChSolverCGS.h"
#include "chrono_parallel/solver/ChSolverMinRes.h"
#include "chrono_parallel/solver/ChSolverSD.h"
#include "chrono_parallel/solver/ChSolverGD.h"
#include "chrono_parallel/solver/ChSolverPGS.h"
#include "chrono_parallel/solver/ChSolverJacobi.h"
#include "chrono_parallel/solver/ChSolverPDIP.h"
using namespace chrono;
void ChLcpSolverParallelDVI::RunTimeStep(real step)
{
// Setup constants and other values for system
data_container->settings.step_size = step;
data_container->settings.solver.tol_speed = step * data_container->settings.solver.tolerance;
// Compute the offsets and number of constrains depending on the solver mode
if (data_container->settings.solver.solver_mode == NORMAL) {
rigid_rigid.offset = 1;
data_container->num_unilaterals = 1 * data_container->num_contacts;
} else if (data_container->settings.solver.solver_mode == SLIDING) {
rigid_rigid.offset = 3;
data_container->num_unilaterals = 3 * data_container->num_contacts;
} else if (data_container->settings.solver.solver_mode == SPINNING) {
rigid_rigid.offset = 6;
data_container->num_unilaterals = 6 * data_container->num_contacts;
}
// This is the total number of constraints
data_container->num_constraints = data_container->num_unilaterals + data_container->num_bilaterals;
// This is the total number of degrees of freedom in the system
data_container->num_dof = data_container->num_bodies * 6 + data_container->num_shafts;
// Generate the mass matrix and compute M_inv_k
ComputeMassMatrix();
data_container->host_data.gamma.resize(data_container->num_constraints);
data_container->host_data.gamma.reset();
// Perform any setup tasks for all constraint types
rigid_rigid.Setup(data_container);
bilateral.Setup(data_container);
// Clear and reset solver history data and counters
solver->current_iteration = 0;
data_container->measures.solver.total_iteration = 0;
data_container->measures.solver.maxd_hist.clear();
data_container->measures.solver.maxdeltalambda_hist.clear();
data_container->measures.solver.iter_hist.clear();
// Set pointers to constraint objects and perform setup actions for solver
solver->rigid_rigid = &rigid_rigid;
solver->bilateral = &bilateral;
solver->Setup(data_container);
ComputeD();
ComputeE();
ComputeR();
// solve for the normal
if (data_container->settings.solver.solver_mode == NORMAL || data_container->settings.solver.solver_mode == SLIDING || data_container->settings.solver.solver_mode == SPINNING) {
if (data_container->settings.solver.max_iteration_normal > 0) {
solver->SetMaxIterations(data_container->settings.solver.max_iteration_normal);
data_container->settings.solver.local_solver_mode = NORMAL;
data_container->system_timer.start("ChLcpSolverParallel_Solve");
PerformStabilization();
solver->Solve();
data_container->system_timer.stop("ChLcpSolverParallel_Solve");
}
}
if (data_container->settings.solver.solver_mode != NORMAL) {
if (data_container->settings.solver.max_iteration_sliding > 0) {
solver->SetMaxIterations(data_container->settings.solver.max_iteration_sliding);
data_container->settings.solver.local_solver_mode = SLIDING;
data_container->system_timer.start("ChLcpSolverParallel_Solve");
PerformStabilization();
solver->Solve();
data_container->system_timer.stop("ChLcpSolverParallel_Solve");
}
}
if (data_container->settings.solver.solver_mode == SPINNING) {
if (data_container->settings.solver.max_iteration_spinning > 0) {
solver->SetMaxIterations(data_container->settings.solver.max_iteration_spinning);
data_container->settings.solver.local_solver_mode = SPINNING;
data_container->system_timer.start("ChLcpSolverParallel_Solve");
PerformStabilization();
solver->Solve();
data_container->system_timer.stop("ChLcpSolverParallel_Solve");
}
}
ComputeImpulses();
for (int i = 0; i < data_container->measures.solver.iter_hist.size(); i++) {
AtIterationEnd(data_container->measures.solver.maxd_hist[i], data_container->measures.solver.maxdeltalambda_hist[i], data_container->measures.solver.iter_hist[i]);
}
tot_iterations = data_container->measures.solver.iter_hist.size();
#if PRINT_LEVEL == 2
std::cout << "Solve Done: " << residual << std::endl;
#endif
}
void ChLcpSolverParallelDVI::ComputeD()
{
uint num_constraints = data_container->num_constraints;
if (num_constraints <= 0) {
return;
}
uint num_bodies = data_container->num_bodies;
uint num_shafts = data_container->num_shafts;
uint num_dof = data_container->num_dof;
uint num_contacts = data_container->num_contacts;
uint num_bilaterals = data_container->num_bilaterals;
uint nnz_bilaterals = data_container->nnz_bilaterals;
int nnz_normal = 6 * 2 * data_container->num_contacts;
int nnz_tangential = 6 * 4 * data_container->num_contacts;
int nnz_spinning = 6 * 3 * data_container->num_contacts;
int num_normal = 1 * data_container->num_contacts;
int num_tangential = 2 * data_container->num_contacts;
int num_spinning = 3 * data_container->num_contacts;
CompressedMatrix<real>& D_n_T = data_container->host_data.D_n_T;
CompressedMatrix<real>& D_t_T = data_container->host_data.D_t_T;
CompressedMatrix<real>& D_s_T = data_container->host_data.D_s_T;
CompressedMatrix<real>& D_b_T = data_container->host_data.D_b_T;
CompressedMatrix<real>& D_n = data_container->host_data.D_n;
CompressedMatrix<real>& D_t = data_container->host_data.D_t;
CompressedMatrix<real>& D_s = data_container->host_data.D_s;
CompressedMatrix<real>& D_b = data_container->host_data.D_b;
CompressedMatrix<real>& M_invD_n = data_container->host_data.M_invD_n;
CompressedMatrix<real>& M_invD_t = data_container->host_data.M_invD_t;
CompressedMatrix<real>& M_invD_s = data_container->host_data.M_invD_s;
CompressedMatrix<real>& M_invD_b = data_container->host_data.M_invD_b;
const CompressedMatrix<real>& M_inv = data_container->host_data.M_inv;
switch (data_container->settings.solver.solver_mode) {
case NORMAL:
clear(D_n_T);
D_n_T.reserve(nnz_normal);
D_n_T.resize(num_normal, num_dof, false);
break;
case SLIDING:
clear(D_n_T);
clear(D_t_T);
D_n_T.reserve(nnz_normal);
D_t_T.reserve(nnz_tangential);
D_n_T.resize(num_normal, num_dof, false);
D_t_T.resize(num_tangential, num_dof, false);
break;
case SPINNING:
clear(D_n_T);
clear(D_t_T);
clear(D_s_T);
D_n_T.reserve(nnz_normal);
D_t_T.reserve(nnz_tangential);
D_s_T.reserve(nnz_spinning);
D_n_T.resize(num_normal, num_dof, false);
D_t_T.resize(num_tangential, num_dof, false);
D_s_T.resize(num_spinning, num_dof, false);
break;
}
clear(D_b_T);
D_b_T.reserve(nnz_bilaterals);
rigid_rigid.GenerateSparsity();
bilateral.GenerateSparsity();
rigid_rigid.Build_D();
bilateral.Build_D();
D_n = trans(D_n_T);
D_t = trans(D_t_T);
D_s = trans(D_s_T);
D_b = trans(D_b_T);
M_invD_n = M_inv * D_n;
M_invD_t = M_inv * D_t;
M_invD_s = M_inv * D_s;
M_invD_b = M_inv * D_b;
}
void ChLcpSolverParallelDVI::ComputeE()
{
if (data_container->num_constraints <= 0) {
return;
}
data_container->host_data.E.resize(data_container->num_constraints);
reset(data_container->host_data.E);
rigid_rigid.Build_E();
bilateral.Build_E();
}
void ChLcpSolverParallelDVI::ComputeR()
{
if (data_container->num_constraints <= 0) {
return;
}
const CompressedMatrix<real>& D_n_T = data_container->host_data.D_n_T;
const CompressedMatrix<real>& D_t_T = data_container->host_data.D_t_T;
const CompressedMatrix<real>& D_s_T = data_container->host_data.D_s_T;
const CompressedMatrix<real>& D_b_T = data_container->host_data.D_b_T;
const DynamicVector<real>& M_invk = data_container->host_data.M_invk;
DynamicVector<real>& R = data_container->host_data.R;
DynamicVector<real>& b = data_container->host_data.b;
b.resize(data_container->num_constraints);
reset(b);
rigid_rigid.Build_b();
bilateral.Build_b();
switch (data_container->settings.solver.solver_mode) {
case NORMAL: {
R = -b - D_n_T * M_invk;
} break;
case SLIDING: {
R = -b - D_n_T * M_invk - D_t_T * M_invk;
} break;
case SPINNING: {
R = -b - D_n_T * M_invk - D_t_T * M_invk - D_s_T * M_invk;
} break;
}
}
void ChLcpSolverParallelDVI::ChangeSolverType(SOLVERTYPE type) {
data_container->settings.solver.solver_type = type;
if (this->solver) {
delete (this->solver);
}
if (type == STEEPEST_DESCENT) {
solver = new ChSolverSD();
} else if (type == GRADIENT_DESCENT) {
solver = new ChSolverGD();
} else if (type == CONJUGATE_GRADIENT) {
solver = new ChSolverCG();
} else if (type == CONJUGATE_GRADIENT_SQUARED) {
solver = new ChSolverCGS();
} else if (type == BICONJUGATE_GRADIENT) {
solver = new ChSolverBiCG();
} else if (type == BICONJUGATE_GRADIENT_STAB) {
solver = new ChSolverBiCGStab();
} else if (type == MINIMUM_RESIDUAL) {
solver = new ChSolverMinRes();
} else if (type == QUASAI_MINIMUM_RESIDUAL) {
// // This solver has not been implemented yet
// //SolveQMR(data_container->gpu_data.device_gam_data, rhs, max_iteration);
} else if (type == APGD) {
solver = new ChSolverAPGD();
} else if (type == APGDREF) {
solver = new ChSolverAPGDREF();
} else if (type == JACOBI) {
solver = new ChSolverJacobi();
} else if (type == GAUSS_SEIDEL) {
solver = new ChSolverPGS();
} else if (type == PDIP) {
solver = new ChSolverPDIP();
}
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
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.
author: Moritz Dannhauer
last change: 04/14/14
TODO: improve the pointer arithmetic (from SCIRun4) in template class
*/
#include <Core/Algorithms/Legacy/Fields/Mapping/ApplyMappingMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/SparseRowMatrixFromMap.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/Mesh.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Core/GeometryPrimitives/Point.h>
#include <Core/GeometryPrimitives/Tensor.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
//namespace SCIRunAlgo {
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Geometry;
<<<<<<< HEAD
//! Internal function to this algorithm: no need for this function to be
//! public. It is called from the algorithm class only.
=======
/// Internal function to this algorithm: no need for this function to be
/// public. It is called from the algorithm class only.
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
template <class DATA>
/*bool
ApplyMappingMatrixT(const ApplyMappingMatrixAlgo* algo,
VField* input, VField* output,
<<<<<<< HEAD
SparseRowMatrix* mapping);*/
bool
ApplyMappingMatrixT(const ApplyMappingMatrixAlgo* algo,
const VField* input, VField* output,
SparseRowMatrixHandle mapping);
//! This is the basic algorithm behind the mapping algorithm
=======
SparseRowMatrix* mapping);
/// This is the basic algorithm behind the mapping algorithm
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
template <class DATA>
bool
ApplyMappingMatrixT(const ApplyMappingMatrixAlgo* algo,
const VField* input, VField* output,
SparseRowMatrixHandle mapping)
/*bool
ApplyMappingMatrixT(const ApplyMappingMatrixAlgo* algo,
VField* input, VField* output,
SparseRowMatrix* mapping)*/
{
double* vals = mapping->valuePtr();
const index_type* rows = mapping->get_rows();
const index_type* columns = mapping->get_cols();
const size_type m = mapping->nrows();
index_type cnt=0;
for (index_type idx=0; idx<m; idx++)
{
DATA val(0);
index_type rr = rows[idx];
size_type ss = rows[idx+1]-rows[idx];
input->get_weighted_value(val,&(columns[rr]),&(vals[rr]),ss);
<<<<<<< HEAD
output->set_value(val,idx);
cnt++; if (cnt==400) {algo->update_progress((double)idx/m); cnt=0;}
}
return true;
=======
/// Algorithm succeeded
algo->algo_end(); return (true);
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
}
/// Actual Algorithm class
ApplyMappingMatrixAlgo::ApplyMappingMatrixAlgo()
{
<<<<<<< HEAD
}
FieldHandle ApplyMappingMatrixAlgo::run(FieldHandle& isrc, FieldHandle& idst, MatrixHandle& mapping) const
{
FieldHandle output;
if (!isrc)
=======
#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER
algo_start("ApplyMappingMatrix");
/// safety check
if (isrc.get_rep() == 0)
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
{
THROW_ALGORITHM_INPUT_ERROR("No input source field");
return FieldHandle();
}
<<<<<<< HEAD
if (!isrc)
=======
/// safety check
if (idst.get_rep() == 0)
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
{
THROW_ALGORITHM_INPUT_ERROR("No input destination field");
return FieldHandle();
}
if (!isrc)
{
THROW_ALGORITHM_INPUT_ERROR("No input mapping field");
return FieldHandle();
}
auto matrix = matrix_cast::as_sparse(mapping);
if (!matrix)
{
THROW_ALGORITHM_INPUT_ERROR("Mapping matrix needs to be sparse");
return FieldHandle();
}
VField* ifsrc = isrc->vfield();
VField* ifdst = idst->vfield();
VMesh* imdst = idst->vmesh();
<<<<<<< HEAD
//! Get information about field types
=======
/// Get information about field types
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
FieldInformation fi(isrc);
FieldInformation fo(idst);
fo.set_data_type(fi.get_data_type());
size_type m = mapping->nrows();
size_type n = mapping->ncols();
size_type dst_num_nodes = imdst->num_nodes();
size_type dst_num_elems = imdst->num_elems();
size_type dst_num_values = ifdst->num_values();
size_type src_num_values = ifsrc->num_values();
if (dst_num_values == m)
{
// do nothing
}
if (m == dst_num_nodes)
{
fo.make_lineardata();
}
else if (m == dst_num_elems)
{
fo.make_constantdata();
}
else
{
THROW_ALGORITHM_INPUT_ERROR("The number of columns in the matrix does not match number of nodes or elements in the destination field");
return FieldHandle();
}
if (src_num_values != n)
{
std::cerr << "n="<<n<<"\n";
std::cerr << "num_values="<<src_num_values<<"\n";
THROW_ALGORITHM_INPUT_ERROR("The number of columns in the matrix does not match number of values in the source field");
return FieldHandle();
}
<<<<<<< HEAD
//! Create output field
=======
/// Create output field
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
output = CreateField(fo,idst->mesh());
VField* ofield = output->vfield();
ofield->resize_values();
<<<<<<< HEAD
if (!output)
=======
/// Check whether output field was created
if (output.get_rep() == 0)
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
{
THROW_ALGORITHM_INPUT_ERROR("Could not create output field");
return FieldHandle();
}
<<<<<<< HEAD
//! Simple table to deal with the various data type formats
//! Note that not every data type is handled, all char, shorts etc,
//! are automatically handled by the int, and unsigned int case, by
//! casting the data on input (these should be the less frequently
//! used datatypes and hence have no specific algorithm in place).
//! Similarly floats are casted to doubles.
=======
/// Simple table to deal with the various data type formats
/// Note that not every data type is handled, all char, shorts etc,
/// are automatically handled by the int, and unsigned int case, by
/// casting the data on input (these should be the less frequently
/// used datatypes and hence have no specific algorithm in place).
/// Similarly floats are casted to doubles.
>>>>>>> c2521af3852c84caa0e1e82b864408ff78ca7429
if (isrc->vfield()->is_char())
if (ApplyMappingMatrixT<char>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_unsigned_char())
if (ApplyMappingMatrixT<unsigned char>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_short())
if (ApplyMappingMatrixT<short>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_unsigned_short())
if (ApplyMappingMatrixT<unsigned short>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_int())
if (ApplyMappingMatrixT<int>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_unsigned_int())
if (ApplyMappingMatrixT<unsigned int>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_longlong())
if (ApplyMappingMatrixT<long long>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_unsigned_longlong())
if (ApplyMappingMatrixT<unsigned long long>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_float())
if (ApplyMappingMatrixT<float>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_double())
if (ApplyMappingMatrixT<double>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_vector())
if (ApplyMappingMatrixT<Vector>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_tensor())
if (ApplyMappingMatrixT<Tensor>(this,ifsrc,ofield,matrix))
return output;
return output;
}
AlgorithmInputName ApplyMappingMatrixAlgo::Source("Source");
AlgorithmInputName ApplyMappingMatrixAlgo::Destination("Destination");
AlgorithmInputName ApplyMappingMatrixAlgo::Mapping("Mapping");
AlgorithmOutputName ApplyMappingMatrixAlgo::Output("Output");
AlgorithmOutput ApplyMappingMatrixAlgo::run_generic(const AlgorithmInput & input) const
{
AlgorithmOutput output;
auto src = input.get<Field>(Source);
auto dest = input.get<Field>(Destination);
auto mapp = input.get<Matrix>(Mapping);
FieldHandle output_field;
output_field = run(src,dest,mapp);
output[Output] = output_field;
return output;
}
//ApplyMappingMatrixAlgo::~ApplyMappingMatrixAlgo() {}
//} // namespace SCIRunAlgo
<commit_msg>changes to make ApplyMappingMatrix to work<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
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.
author: Moritz Dannhauer
last change: 04/14/14
TODO: improve the pointer arithmetic (from SCIRun4) in template class
*/
#include <Core/Algorithms/Legacy/Fields/Mapping/ApplyMappingMatrix.h>
#include <Core/Datatypes/SparseRowMatrix.h>
#include <Core/Datatypes/SparseRowMatrixFromMap.h>
#include <Core/Algorithms/Base/AlgorithmPreconditions.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/Mesh.h>
#include <Core/Datatypes/MatrixTypeConversions.h>
#include <Core/GeometryPrimitives/Point.h>
#include <Core/GeometryPrimitives/Tensor.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Geometry;
/// Internal function to this algorithm: no need for this function to be
/// public. It is called from the algorithm class only.
template <class DATA>
bool
ApplyMappingMatrixT(const ApplyMappingMatrixAlgo* algo,
const VField* input, VField* output,
SparseRowMatrixHandle mapping);
//! This is the basic algorithm behind the mapping algorithm
template <class DATA>
bool
ApplyMappingMatrixT(const ApplyMappingMatrixAlgo* algo,
const VField* input, VField* output,
SparseRowMatrixHandle mapping)
{
double* vals = mapping->valuePtr();
const index_type* rows = mapping->get_rows();
const index_type* columns = mapping->get_cols();
const size_type m = mapping->nrows();
index_type cnt=0;
for (index_type idx=0; idx<m; idx++)
{
DATA val(0);
index_type rr = rows[idx];
size_type ss = rows[idx+1]-rows[idx];
input->get_weighted_value(val,&(columns[rr]),&(vals[rr]),ss);
output->set_value(val,idx);
cnt++; if (cnt==400) {algo->update_progress((double)idx/m); cnt=0;}
}
return true;
}
/// Actual Algorithm class
ApplyMappingMatrixAlgo::ApplyMappingMatrixAlgo()
{
}
FieldHandle ApplyMappingMatrixAlgo::run(FieldHandle& isrc, FieldHandle& idst, MatrixHandle& mapping) const
{
FieldHandle output;
if (!isrc)
{
THROW_ALGORITHM_INPUT_ERROR("No input source field");
return FieldHandle();
}
if (!isrc)
{
THROW_ALGORITHM_INPUT_ERROR("No input destination field");
return FieldHandle();
}
if (!isrc)
{
THROW_ALGORITHM_INPUT_ERROR("No input mapping field");
return FieldHandle();
}
auto matrix = matrix_cast::as_sparse(mapping);
if (!matrix)
{
THROW_ALGORITHM_INPUT_ERROR("Mapping matrix needs to be sparse");
return FieldHandle();
}
VField* ifsrc = isrc->vfield();
VField* ifdst = idst->vfield();
VMesh* imdst = idst->vmesh();
/// Get information about field types
FieldInformation fi(isrc);
FieldInformation fo(idst);
fo.set_data_type(fi.get_data_type());
size_type m = mapping->nrows();
size_type n = mapping->ncols();
size_type dst_num_nodes = imdst->num_nodes();
size_type dst_num_elems = imdst->num_elems();
size_type dst_num_values = ifdst->num_values();
size_type src_num_values = ifsrc->num_values();
if (dst_num_values == m)
{
// do nothing
}
if (m == dst_num_nodes)
{
fo.make_lineardata();
}
else if (m == dst_num_elems)
{
fo.make_constantdata();
}
else
{
THROW_ALGORITHM_INPUT_ERROR("The number of columns in the matrix does not match number of nodes or elements in the destination field");
return FieldHandle();
}
if (src_num_values != n)
{
std::cerr << "n="<<n<<"\n";
std::cerr << "num_values="<<src_num_values<<"\n";
THROW_ALGORITHM_INPUT_ERROR("The number of columns in the matrix does not match number of values in the source field");
return FieldHandle();
}
/// Create output field
output = CreateField(fo,idst->mesh());
VField* ofield = output->vfield();
ofield->resize_values();
if (!output)
{
THROW_ALGORITHM_INPUT_ERROR("Could not create output field");
return FieldHandle();
}
/// Simple table to deal with the various data type formats
/// Note that not every data type is handled, all char, shorts etc,
/// are automatically handled by the int, and unsigned int case, by
/// casting the data on input (these should be the less frequently
/// used datatypes and hence have no specific algorithm in place).
/// Similarly floats are casted to doubles.
if (isrc->vfield()->is_char())
if (ApplyMappingMatrixT<char>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_unsigned_char())
if (ApplyMappingMatrixT<unsigned char>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_short())
if (ApplyMappingMatrixT<short>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_unsigned_short())
if (ApplyMappingMatrixT<unsigned short>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_int())
if (ApplyMappingMatrixT<int>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_unsigned_int())
if (ApplyMappingMatrixT<unsigned int>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_longlong())
if (ApplyMappingMatrixT<long long>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_unsigned_longlong())
if (ApplyMappingMatrixT<unsigned long long>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_float())
if (ApplyMappingMatrixT<float>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_double())
if (ApplyMappingMatrixT<double>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_vector())
if (ApplyMappingMatrixT<Vector>(this,ifsrc,ofield,matrix))
return output;
if (isrc->vfield()->is_tensor())
if (ApplyMappingMatrixT<Tensor>(this,ifsrc,ofield,matrix))
return output;
return output;
}
AlgorithmInputName ApplyMappingMatrixAlgo::Source("Source");
AlgorithmInputName ApplyMappingMatrixAlgo::Destination("Destination");
AlgorithmInputName ApplyMappingMatrixAlgo::Mapping("Mapping");
AlgorithmOutputName ApplyMappingMatrixAlgo::Output("Output");
AlgorithmOutput ApplyMappingMatrixAlgo::run_generic(const AlgorithmInput & input) const
{
AlgorithmOutput output;
auto src = input.get<Field>(Source);
auto dest = input.get<Field>(Destination);
auto mapp = input.get<Matrix>(Mapping);
FieldHandle output_field;
output_field = run(src,dest,mapp);
output[Output] = output_field;
return output;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
// SYSCOIN for auxpow
#include "main.h"
using namespace std;
// SYSCOIN moved and added auxpow check
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
/* The CBlockIndex object's block header is missing the auxpow.
So if this is an auxpow block, read it from disk instead. We only
have to read the actual *header*, not the full block. */
if (nVersion.IsAuxpow())
{
ReadBlockHeaderFromDisk(block, this, consensusParams);
return block;
}
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex *pindex) {
if (pindex == NULL) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
if (pindex == NULL) {
return NULL;
}
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height) {
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (pindexWalk->pskip != NULL &&
(heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
heightSkipPrev >= height)))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
<commit_msg>auxpow<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
// SYSCOIN for auxpow
#include "main.h"
using namespace std;
// SYSCOIN moved and added auxpow check
CBlockHeader CBlockIndex::GetBlockHeader() const
{
CBlockHeader block;
/* The CBlockIndex object's block header is missing the auxpow.
So if this is an auxpow block, read it from disk instead. We only
have to read the actual *header*, not the full block. */
if (nVersion.IsAuxpow())
{
ReadBlockHeaderFromDisk(block, this, consensusParams);
return block;
}
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
/**
* CChain implementation
*/
void CChain::SetTip(CBlockIndex *pindex) {
if (pindex == NULL) {
vChain.clear();
return;
}
vChain.resize(pindex->nHeight + 1);
while (pindex && vChain[pindex->nHeight] != pindex) {
vChain[pindex->nHeight] = pindex;
pindex = pindex->pprev;
}
}
CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const {
int nStep = 1;
std::vector<uint256> vHave;
vHave.reserve(32);
if (!pindex)
pindex = Tip();
while (pindex) {
vHave.push_back(pindex->GetBlockHash());
// Stop when we have added the genesis block.
if (pindex->nHeight == 0)
break;
// Exponentially larger steps back, plus the genesis block.
int nHeight = std::max(pindex->nHeight - nStep, 0);
if (Contains(pindex)) {
// Use O(1) CChain index if possible.
pindex = (*this)[nHeight];
} else {
// Otherwise, use O(log n) skiplist.
pindex = pindex->GetAncestor(nHeight);
}
if (vHave.size() > 10)
nStep *= 2;
}
return CBlockLocator(vHave);
}
const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const {
if (pindex == NULL) {
return NULL;
}
if (pindex->nHeight > Height())
pindex = pindex->GetAncestor(Height());
while (pindex && !Contains(pindex))
pindex = pindex->pprev;
return pindex;
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height) {
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (pindexWalk->pskip != NULL &&
(heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 &&
heightSkipPrev >= height)))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2018 Alexandr Akulich <[email protected]>
This file is a part of TelegramQt library.
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.
*/
#include "ClientRpcLayer.hpp"
#include "ClientRpcUpdatesLayer.hpp"
#include "IgnoredMessageNotification.hpp"
#include "SendPackageHelper.hpp"
#include "Debug_p.hpp"
#include "CAppInformation.hpp"
#include "PendingRpcOperation.hpp"
#include "RandomGenerator.hpp"
#include "UpdatesLayer.hpp"
#include "MTProto/MessageHeader.hpp"
#include "MTProto/Stream.hpp"
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_clientRpcLayerCategory, "telegram.client.rpclayer", QtWarningMsg)
Q_LOGGING_CATEGORY(c_clientRpcDumpPackageCategory, "telegram.client.rpclayer.dump", QtWarningMsg)
namespace Telegram {
namespace Client {
RpcLayer::RpcLayer(QObject *parent) :
BaseRpcLayer(parent)
{
}
RpcLayer::~RpcLayer()
{
qDeleteAll(m_messages);
}
void RpcLayer::setAppInformation(AppInformation *appInfo)
{
m_appInfo = appInfo;
}
void RpcLayer::installUpdatesHandler(UpdatesInternalApi *updatesHandler)
{
m_UpdatesInternalApi = updatesHandler;
}
void RpcLayer::setSessionData(quint64 sessionId, quint32 contentRelatedMessagesNumber)
{
m_sessionId = sessionId;
m_contentRelatedMessages = contentRelatedMessagesNumber;
}
void RpcLayer::setServerSalt(quint64 serverSalt)
{
m_serverSalt = serverSalt;
}
void RpcLayer::startNewSession()
{
m_sessionId = RandomGenerator::instance()->generate<quint64>();
m_contentRelatedMessages = 0;
}
bool RpcLayer::processMTProtoMessage(const MTProto::Message &message)
{
if (message.sequenceNumber & 1) {
addMessageToAck(message.messageId);
}
const TLValue firstValue = message.firstValue();
if (firstValue.isTypeOf<TLUpdates>()) {
return processUpdates(message);
}
bool result = false;
switch (firstValue) {
case TLValue::NewSessionCreated:
result = processSessionCreated(message.skipTLValue());
break;
case TLValue::MsgContainer:
result = processMsgContainer(message.skipTLValue());
break;
case TLValue::RpcResult:
result = processRpcResult(message.skipTLValue());
break;
case TLValue::MsgsAck:
result = processMessageAck(message.skipTLValue());
break;
case TLValue::BadMsgNotification:
case TLValue::BadServerSalt:
result = processIgnoredMessageNotification(message);
break;
case TLValue::GzipPacked:
qCWarning(c_clientRpcLayerCategory) << CALL_INFO
<< "GzipPacked should be processed in the base class";
break;
case TLValue::Pong:
{
MTProto::Stream stream(message.data);
TLPong pong;
stream >> pong;
PendingRpcOperation *op = m_operations.take(pong.msgId);
if (op) {
op->setFinishedWithReplyData(message.data);
result = true;
} else {
qCWarning(c_clientRpcLayerCategory) << "Unexpected pong?!" << pong.msgId << pong.pingId;
}
}
break;
default:
qCDebug(c_clientRpcLayerCategory) << Q_FUNC_INFO << "value:" << message.firstValue();
break;
}
if (!result) {
qCWarning(c_clientRpcLayerCategory) << CALL_INFO << "Unable to process" << message.firstValue();
}
return result;
}
bool RpcLayer::processRpcResult(const MTProto::Message &message)
{
qCDebug(c_clientRpcLayerCategory) << "processRpcQuery(stream);";
MTProto::Stream stream(message.data);
quint64 messageId = 0;
stream >> messageId;
PendingRpcOperation *op = m_operations.take(messageId);
if (!op) {
qCWarning(c_clientRpcLayerCategory) << "processRpcQuery():"
<< "Unhandled RPC result for messageId"
<< hex << showbase << messageId;
return false;
}
op->setFinishedWithReplyData(stream.readAll());
#define DUMP_CLIENT_RPC_PACKETS
#ifdef DUMP_CLIENT_RPC_PACKETS
qCDebug(c_clientRpcLayerCategory) << "Client: Answer for message"
<< messageId << "op:" << op;
qCDebug(c_clientRpcLayerCategory).noquote() << "Client: RPC Reply bytes:"
<< op->replyData().size() << op->replyData().toHex();
#endif
qCDebug(c_clientRpcLayerCategory) << "processRpcQuery():" << "Set finished op" << op
<< "messageId:" << hex << showbase << messageId
<< "error:" << op->errorDetails();
return true;
}
bool RpcLayer::processUpdates(const MTProto::Message &message)
{
qCDebug(c_clientRpcLayerCategory) << "processUpdates()" << message.firstValue();
MTProto::Stream stream(message.data);
TLUpdates updates;
stream >> updates;
return m_UpdatesInternalApi->processUpdates(updates);
}
bool RpcLayer::processMessageAck(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
TLVector<quint64> idsVector;
stream >> idsVector;
qCDebug(c_clientRpcLayerCategory) << "processMessageAck():" << idsVector;
return true;
}
bool RpcLayer::processSessionCreated(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
// https://core.telegram.org/mtproto/service_messages#new-session-creation-notification
quint64 firstMsgId;
quint64 uniqueId;
quint64 serverSalt;
stream >> firstMsgId;
stream >> uniqueId;
stream >> serverSalt;
qCDebug(c_clientRpcLayerCategory) << "processSessionCreated(stream) {"
<< hex << showbase
<< " firstMsgId:" << firstMsgId
<< " uniqueId:" << uniqueId
<< " serverSalt:" << serverSalt;
return true;
}
bool RpcLayer::processIgnoredMessageNotification(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
TLBadMsgNotification tlNotification;
stream >> tlNotification;
// https://core.telegram.org/mtproto/service_messages_about_messages#notice-of-ignored-error-message
MTProto::IgnoredMessageNotification notification(tlNotification);
qCDebug(c_clientRpcLayerCategory) << CALL_INFO << notification.toString();
MTProto::Message *m = m_messages.value(notification.messageId);
if (!m) {
qCWarning(c_clientRpcLayerCategory) << CALL_INFO
<< notification.toString() << "for unknown message id"
<< hex << showbase << notification.messageId;
return false;
}
switch (notification.errorCode) {
case MTProto::IgnoredMessageNotification::IncorrectServerSalt:
// We sync local serverSalt value in processDecryptedMessageHeader().
// Resend message will automatically apply the new salt
return resendIgnoredMessage(notification.messageId);
case MTProto::IgnoredMessageNotification::MessageIdTooOld:
return resendIgnoredMessage(notification.messageId);
case MTProto::IgnoredMessageNotification::SequenceNumberTooHigh:
qCDebug(c_clientRpcLayerCategory) << "processIgnoredMessageNotification(SequenceNumberTooHigh):"
" reduce seq num"
<< hex << showbase
<< " from" << m->sequenceNumber
<< " to" << (m->sequenceNumber - 2);
m->sequenceNumber -= 2;
return resendIgnoredMessage(notification.messageId);
case MTProto::IgnoredMessageNotification::SequenceNumberTooLow:
qCDebug(c_clientRpcLayerCategory) << "processIgnoredMessageNotification(SequenceNumberTooLow):"
" increase seq num"
<< hex << showbase
<< " from" << m->sequenceNumber
<< " to" << (m->sequenceNumber + 2);
m->sequenceNumber += 2;
{
quint32 messageContentNumber = m->sequenceNumber / 2;
if (m_contentRelatedMessages <= messageContentNumber) {
m_contentRelatedMessages = messageContentNumber + 1;
}
}
return resendIgnoredMessage(notification.messageId);
case MTProto::IgnoredMessageNotification::IncorrectTwoLowerOrderMessageIdBits:
qCCritical(c_clientRpcLayerCategory) << "How we ever managed to mess with"
" the lower messageId bytes?!";
// Just resend the message. We regenerate message id, so it can help.
return resendIgnoredMessage(notification.messageId);
default:
break;
}
qCWarning(c_clientRpcLayerCategory) << "Unhandled error:" << notification.toString();
return false;
}
bool RpcLayer::processMessageHeader(const MTProto::FullMessageHeader &header)
{
if (serverSalt() != header.serverSalt) {
qCDebug(c_clientRpcLayerCategory).noquote()
<< QStringLiteral("Received different server salt: %1 (remote) vs %2 (local)."
" Fix local to remote.")
.arg(toHex(header.serverSalt))
.arg(toHex(serverSalt()));
setServerSalt(header.serverSalt);
}
if (m_sessionId != header.sessionId) {
qCWarning(c_clientRpcLayerCategory) << CALL_INFO << "Session Id is wrong.";
return false;
}
return true;
}
QByteArray RpcLayer::getEncryptionKeyPart() const
{
return m_sendHelper->getClientKeyPart();
}
QByteArray RpcLayer::getVerificationKeyPart() const
{
return m_sendHelper->getServerKeyPart();
}
quint64 RpcLayer::sendRpc(PendingRpcOperation *operation)
{
operation->setConnection(m_sendHelper->getConnection());
MTProto::Message *message = new MTProto::Message();
message->messageId = m_sendHelper->newMessageId(SendMode::Client);
if (operation->isContentRelated()) {
message->sequenceNumber = m_contentRelatedMessages * 2 + 1;
++m_contentRelatedMessages;
} else {
if (m_contentRelatedMessages == 0) {
qCCritical(c_clientRpcLayerCategory) << CALL_INFO
<< "First message should be content related!";
}
message->sequenceNumber = m_contentRelatedMessages * 2;
}
// We have to add InitConnection here because
// sendPackage() implementation is shared with server
if (message->sequenceNumber == 1) {
message->setData(getInitConnection() + operation->requestData());
} else {
message->setData(operation->requestData());
}
m_operations.insert(message->messageId, operation);
m_messages.insert(message->messageId, message);
sendPacket(*message);
return message->messageId;
}
bool RpcLayer::resendIgnoredMessage(quint64 messageId)
{
MTProto::Message *message = m_messages.take(messageId);
PendingRpcOperation *operation = m_operations.take(messageId);
if (!operation) {
qCCritical(c_clientRpcLayerCategory) << CALL_INFO
<< "Unable to find the message to resend"
<< hex << messageId;
delete message;
return false;
}
qCDebug(c_clientRpcLayerCategory) << "Resend message"
<< hex << messageId
<< message->firstValue();
message->messageId = m_sendHelper->newMessageId(SendMode::Client);
m_operations.insert(message->messageId, operation);
m_messages.insert(message->messageId, message);
sendPacket(*message);
emit operation->resent(messageId, message->messageId);
return message->messageId;
}
void RpcLayer::acknowledgeMessages()
{
MTProto::Stream outputStream(MTProto::Stream::WriteOnly);
TLVector<quint64> idsVector = m_messagesToAck;
m_messagesToAck.clear();
outputStream << TLValue::MsgsAck;
outputStream << idsVector;
MTProto::Message *message = new MTProto::Message();
message->messageId = m_sendHelper->newMessageId(SendMode::Client);
message->sequenceNumber = m_contentRelatedMessages * 2;
message->setData(outputStream.getData());
m_messages.insert(message->messageId, message);
sendPacket(*message);
}
void RpcLayer::onConnectionFailed()
{
for (PendingRpcOperation *op : m_operations) {
if (!op->isFinished()) {
op->setFinishedWithTextError(QLatin1String("Connection failed"));
}
}
m_operations.clear();
qDeleteAll(m_messages);
m_messages.clear();
}
QByteArray RpcLayer::getInitConnection() const
{
#ifdef DEVELOPER_BUILD
qCDebug(c_clientRpcLayerCategory) << CALL_INFO << "layer" << TLValue::CurrentLayer;
#endif
MTProto::Stream outputStream(MTProto::Stream::WriteOnly);
outputStream << TLValue::InvokeWithLayer;
outputStream << TLValue::CurrentLayer;
outputStream << TLValue::InitConnection;
outputStream << m_appInfo->appId();
outputStream << m_appInfo->deviceInfo();
outputStream << m_appInfo->osInfo();
outputStream << m_appInfo->appVersion();
#if TELEGRAMQT_LAYER >= 67
outputStream << m_appInfo->languageCode(); // System language
outputStream << QString(); // Langpack
#endif
outputStream << m_appInfo->languageCode(); // Lang code
return outputStream.getData();
}
void RpcLayer::addMessageToAck(quint64 messageId)
{
if (m_messagesToAck.isEmpty()) {
QMetaObject::invokeMethod(this, "acknowledgeMessages", Qt::QueuedConnection);
}
m_messagesToAck.append(messageId);
}
} // Client namespace
} // Telegram namespace
<commit_msg>ClientRpcLayer: Use invokeMethod(Functor) if available<commit_after>/*
Copyright (C) 2018 Alexandr Akulich <[email protected]>
This file is a part of TelegramQt library.
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.
*/
#include "ClientRpcLayer.hpp"
#include "ClientRpcUpdatesLayer.hpp"
#include "IgnoredMessageNotification.hpp"
#include "SendPackageHelper.hpp"
#include "Debug_p.hpp"
#include "CAppInformation.hpp"
#include "PendingRpcOperation.hpp"
#include "RandomGenerator.hpp"
#include "UpdatesLayer.hpp"
#include "MTProto/MessageHeader.hpp"
#include "MTProto/Stream.hpp"
#include <QLoggingCategory>
Q_LOGGING_CATEGORY(c_clientRpcLayerCategory, "telegram.client.rpclayer", QtWarningMsg)
Q_LOGGING_CATEGORY(c_clientRpcDumpPackageCategory, "telegram.client.rpclayer.dump", QtWarningMsg)
namespace Telegram {
namespace Client {
RpcLayer::RpcLayer(QObject *parent) :
BaseRpcLayer(parent)
{
}
RpcLayer::~RpcLayer()
{
qDeleteAll(m_messages);
}
void RpcLayer::setAppInformation(AppInformation *appInfo)
{
m_appInfo = appInfo;
}
void RpcLayer::installUpdatesHandler(UpdatesInternalApi *updatesHandler)
{
m_UpdatesInternalApi = updatesHandler;
}
void RpcLayer::setSessionData(quint64 sessionId, quint32 contentRelatedMessagesNumber)
{
m_sessionId = sessionId;
m_contentRelatedMessages = contentRelatedMessagesNumber;
}
void RpcLayer::setServerSalt(quint64 serverSalt)
{
m_serverSalt = serverSalt;
}
void RpcLayer::startNewSession()
{
m_sessionId = RandomGenerator::instance()->generate<quint64>();
m_contentRelatedMessages = 0;
}
bool RpcLayer::processMTProtoMessage(const MTProto::Message &message)
{
if (message.sequenceNumber & 1) {
addMessageToAck(message.messageId);
}
const TLValue firstValue = message.firstValue();
if (firstValue.isTypeOf<TLUpdates>()) {
return processUpdates(message);
}
bool result = false;
switch (firstValue) {
case TLValue::NewSessionCreated:
result = processSessionCreated(message.skipTLValue());
break;
case TLValue::MsgContainer:
result = processMsgContainer(message.skipTLValue());
break;
case TLValue::RpcResult:
result = processRpcResult(message.skipTLValue());
break;
case TLValue::MsgsAck:
result = processMessageAck(message.skipTLValue());
break;
case TLValue::BadMsgNotification:
case TLValue::BadServerSalt:
result = processIgnoredMessageNotification(message);
break;
case TLValue::GzipPacked:
qCWarning(c_clientRpcLayerCategory) << CALL_INFO
<< "GzipPacked should be processed in the base class";
break;
case TLValue::Pong:
{
MTProto::Stream stream(message.data);
TLPong pong;
stream >> pong;
PendingRpcOperation *op = m_operations.take(pong.msgId);
if (op) {
op->setFinishedWithReplyData(message.data);
result = true;
} else {
qCWarning(c_clientRpcLayerCategory) << "Unexpected pong?!" << pong.msgId << pong.pingId;
}
}
break;
default:
qCDebug(c_clientRpcLayerCategory) << Q_FUNC_INFO << "value:" << message.firstValue();
break;
}
if (!result) {
qCWarning(c_clientRpcLayerCategory) << CALL_INFO << "Unable to process" << message.firstValue();
}
return result;
}
bool RpcLayer::processRpcResult(const MTProto::Message &message)
{
qCDebug(c_clientRpcLayerCategory) << "processRpcQuery(stream);";
MTProto::Stream stream(message.data);
quint64 messageId = 0;
stream >> messageId;
PendingRpcOperation *op = m_operations.take(messageId);
if (!op) {
qCWarning(c_clientRpcLayerCategory) << "processRpcQuery():"
<< "Unhandled RPC result for messageId"
<< hex << showbase << messageId;
return false;
}
op->setFinishedWithReplyData(stream.readAll());
#define DUMP_CLIENT_RPC_PACKETS
#ifdef DUMP_CLIENT_RPC_PACKETS
qCDebug(c_clientRpcLayerCategory) << "Client: Answer for message"
<< messageId << "op:" << op;
qCDebug(c_clientRpcLayerCategory).noquote() << "Client: RPC Reply bytes:"
<< op->replyData().size() << op->replyData().toHex();
#endif
qCDebug(c_clientRpcLayerCategory) << "processRpcQuery():" << "Set finished op" << op
<< "messageId:" << hex << showbase << messageId
<< "error:" << op->errorDetails();
return true;
}
bool RpcLayer::processUpdates(const MTProto::Message &message)
{
qCDebug(c_clientRpcLayerCategory) << "processUpdates()" << message.firstValue();
MTProto::Stream stream(message.data);
TLUpdates updates;
stream >> updates;
return m_UpdatesInternalApi->processUpdates(updates);
}
bool RpcLayer::processMessageAck(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
TLVector<quint64> idsVector;
stream >> idsVector;
qCDebug(c_clientRpcLayerCategory) << "processMessageAck():" << idsVector;
return true;
}
bool RpcLayer::processSessionCreated(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
// https://core.telegram.org/mtproto/service_messages#new-session-creation-notification
quint64 firstMsgId;
quint64 uniqueId;
quint64 serverSalt;
stream >> firstMsgId;
stream >> uniqueId;
stream >> serverSalt;
qCDebug(c_clientRpcLayerCategory) << "processSessionCreated(stream) {"
<< hex << showbase
<< " firstMsgId:" << firstMsgId
<< " uniqueId:" << uniqueId
<< " serverSalt:" << serverSalt;
return true;
}
bool RpcLayer::processIgnoredMessageNotification(const MTProto::Message &message)
{
MTProto::Stream stream(message.data);
TLBadMsgNotification tlNotification;
stream >> tlNotification;
// https://core.telegram.org/mtproto/service_messages_about_messages#notice-of-ignored-error-message
MTProto::IgnoredMessageNotification notification(tlNotification);
qCDebug(c_clientRpcLayerCategory) << CALL_INFO << notification.toString();
MTProto::Message *m = m_messages.value(notification.messageId);
if (!m) {
qCWarning(c_clientRpcLayerCategory) << CALL_INFO
<< notification.toString() << "for unknown message id"
<< hex << showbase << notification.messageId;
return false;
}
switch (notification.errorCode) {
case MTProto::IgnoredMessageNotification::IncorrectServerSalt:
// We sync local serverSalt value in processDecryptedMessageHeader().
// Resend message will automatically apply the new salt
return resendIgnoredMessage(notification.messageId);
case MTProto::IgnoredMessageNotification::MessageIdTooOld:
return resendIgnoredMessage(notification.messageId);
case MTProto::IgnoredMessageNotification::SequenceNumberTooHigh:
qCDebug(c_clientRpcLayerCategory) << "processIgnoredMessageNotification(SequenceNumberTooHigh):"
" reduce seq num"
<< hex << showbase
<< " from" << m->sequenceNumber
<< " to" << (m->sequenceNumber - 2);
m->sequenceNumber -= 2;
return resendIgnoredMessage(notification.messageId);
case MTProto::IgnoredMessageNotification::SequenceNumberTooLow:
qCDebug(c_clientRpcLayerCategory) << "processIgnoredMessageNotification(SequenceNumberTooLow):"
" increase seq num"
<< hex << showbase
<< " from" << m->sequenceNumber
<< " to" << (m->sequenceNumber + 2);
m->sequenceNumber += 2;
{
quint32 messageContentNumber = m->sequenceNumber / 2;
if (m_contentRelatedMessages <= messageContentNumber) {
m_contentRelatedMessages = messageContentNumber + 1;
}
}
return resendIgnoredMessage(notification.messageId);
case MTProto::IgnoredMessageNotification::IncorrectTwoLowerOrderMessageIdBits:
qCCritical(c_clientRpcLayerCategory) << "How we ever managed to mess with"
" the lower messageId bytes?!";
// Just resend the message. We regenerate message id, so it can help.
return resendIgnoredMessage(notification.messageId);
default:
break;
}
qCWarning(c_clientRpcLayerCategory) << "Unhandled error:" << notification.toString();
return false;
}
bool RpcLayer::processMessageHeader(const MTProto::FullMessageHeader &header)
{
if (serverSalt() != header.serverSalt) {
qCDebug(c_clientRpcLayerCategory).noquote()
<< QStringLiteral("Received different server salt: %1 (remote) vs %2 (local)."
" Fix local to remote.")
.arg(toHex(header.serverSalt))
.arg(toHex(serverSalt()));
setServerSalt(header.serverSalt);
}
if (m_sessionId != header.sessionId) {
qCWarning(c_clientRpcLayerCategory) << CALL_INFO << "Session Id is wrong.";
return false;
}
return true;
}
QByteArray RpcLayer::getEncryptionKeyPart() const
{
return m_sendHelper->getClientKeyPart();
}
QByteArray RpcLayer::getVerificationKeyPart() const
{
return m_sendHelper->getServerKeyPart();
}
quint64 RpcLayer::sendRpc(PendingRpcOperation *operation)
{
operation->setConnection(m_sendHelper->getConnection());
MTProto::Message *message = new MTProto::Message();
message->messageId = m_sendHelper->newMessageId(SendMode::Client);
if (operation->isContentRelated()) {
message->sequenceNumber = m_contentRelatedMessages * 2 + 1;
++m_contentRelatedMessages;
} else {
if (m_contentRelatedMessages == 0) {
qCCritical(c_clientRpcLayerCategory) << CALL_INFO
<< "First message should be content related!";
}
message->sequenceNumber = m_contentRelatedMessages * 2;
}
// We have to add InitConnection here because
// sendPackage() implementation is shared with server
if (message->sequenceNumber == 1) {
message->setData(getInitConnection() + operation->requestData());
} else {
message->setData(operation->requestData());
}
m_operations.insert(message->messageId, operation);
m_messages.insert(message->messageId, message);
sendPacket(*message);
return message->messageId;
}
bool RpcLayer::resendIgnoredMessage(quint64 messageId)
{
MTProto::Message *message = m_messages.take(messageId);
PendingRpcOperation *operation = m_operations.take(messageId);
if (!operation) {
qCCritical(c_clientRpcLayerCategory) << CALL_INFO
<< "Unable to find the message to resend"
<< hex << messageId;
delete message;
return false;
}
qCDebug(c_clientRpcLayerCategory) << "Resend message"
<< hex << messageId
<< message->firstValue();
message->messageId = m_sendHelper->newMessageId(SendMode::Client);
m_operations.insert(message->messageId, operation);
m_messages.insert(message->messageId, message);
sendPacket(*message);
emit operation->resent(messageId, message->messageId);
return message->messageId;
}
void RpcLayer::acknowledgeMessages()
{
MTProto::Stream outputStream(MTProto::Stream::WriteOnly);
TLVector<quint64> idsVector = m_messagesToAck;
m_messagesToAck.clear();
outputStream << TLValue::MsgsAck;
outputStream << idsVector;
MTProto::Message *message = new MTProto::Message();
message->messageId = m_sendHelper->newMessageId(SendMode::Client);
message->sequenceNumber = m_contentRelatedMessages * 2;
message->setData(outputStream.getData());
m_messages.insert(message->messageId, message);
sendPacket(*message);
}
void RpcLayer::onConnectionFailed()
{
for (PendingRpcOperation *op : m_operations) {
if (!op->isFinished()) {
op->setFinishedWithTextError(QLatin1String("Connection failed"));
}
}
m_operations.clear();
qDeleteAll(m_messages);
m_messages.clear();
}
QByteArray RpcLayer::getInitConnection() const
{
#ifdef DEVELOPER_BUILD
qCDebug(c_clientRpcLayerCategory) << CALL_INFO << "layer" << TLValue::CurrentLayer;
#endif
MTProto::Stream outputStream(MTProto::Stream::WriteOnly);
outputStream << TLValue::InvokeWithLayer;
outputStream << TLValue::CurrentLayer;
outputStream << TLValue::InitConnection;
outputStream << m_appInfo->appId();
outputStream << m_appInfo->deviceInfo();
outputStream << m_appInfo->osInfo();
outputStream << m_appInfo->appVersion();
#if TELEGRAMQT_LAYER >= 67
outputStream << m_appInfo->languageCode(); // System language
outputStream << QString(); // Langpack
#endif
outputStream << m_appInfo->languageCode(); // Lang code
return outputStream.getData();
}
void RpcLayer::addMessageToAck(quint64 messageId)
{
if (m_messagesToAck.isEmpty()) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
QMetaObject::invokeMethod(this, &RpcLayer::acknowledgeMessages, Qt::QueuedConnection);
#else
QMetaObject::invokeMethod(this, "acknowledgeMessages", Qt::QueuedConnection);
#endif
}
m_messagesToAck.append(messageId);
}
} // Client namespace
} // Telegram namespace
<|endoftext|> |
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2007 Frank Osterfeld <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "subscriptionlistview.h"
#include "subscriptionlistmodel.h"
#include "subscriptionlistdelegate.h"
#include "akregatorconfig.h"
#include <QHeaderView>
#include <QStack>
#include <QPointer>
#include <KMenu>
#include <KLocale>
#include <KDebug>
#include <KConfigGroup>
#include <cassert>
using namespace Akregator;
namespace {
QModelIndex prevIndex( const QModelIndex& idx )
{
if ( !idx.isValid() )
return QModelIndex();
const QAbstractItemModel* const model = idx.model();
assert( model );
if ( idx.row() > 0 )
{
QModelIndex i = idx.sibling( idx.row() - 1, idx.column() );
while ( model->hasChildren( i ) )
i = i.child( model->rowCount( i ) - 1, i.column() );
return i;
}
else
return idx.parent();
}
QModelIndex prevFeedIndex( const QModelIndex& idx, bool allowPassed = false )
{
QModelIndex prev = allowPassed ? idx : prevIndex( idx );
while ( prev.isValid() && prev.data( SubscriptionListModel::IsAggregationRole ).toBool() )
prev = prevIndex( prev );
return prev;
}
QModelIndex prevUnreadFeedIndex( const QModelIndex& idx, bool allowPassed = false )
{
QModelIndex prev = allowPassed ? idx : prevIndex( idx );
while ( prev.isValid() && ( prev.data( SubscriptionListModel::IsAggregationRole ).toBool() || prev.sibling( prev.row(), SubscriptionListModel::UnreadCountColumn ).data().toInt() == 0 ) )
prev = prevIndex( prev );
return prev;
}
QModelIndex lastLeaveChild( const QAbstractItemModel* const model )
{
assert( model );
if ( model->rowCount() == 0 )
return QModelIndex();
QModelIndex idx = model->index( model->rowCount() - 1, 0 );
while ( model->hasChildren( idx ) )
idx = idx.child( model->rowCount( idx ) - 1, idx.column() );
return idx;
}
QModelIndex nextIndex( const QModelIndex& idx )
{
if ( !idx.isValid() )
return QModelIndex();
const QAbstractItemModel* const model = idx.model();
assert( model );
if ( model->hasChildren( idx ) )
return idx.child( 0, idx.column() );
QModelIndex i = idx;
while ( true )
{
if ( !i.isValid() )
return i;
const int siblings = model->rowCount( i.parent() );
if ( i.row() + 1 < siblings )
return i.sibling( i.row() + 1, i.column() );
i = i.parent();
}
}
QModelIndex nextFeedIndex( const QModelIndex& idx )
{
QModelIndex next = nextIndex( idx );
while ( next.isValid() && next.data( SubscriptionListModel::IsAggregationRole ).toBool() )
next = nextIndex( next );
return next;
}
QModelIndex nextUnreadFeedIndex( const QModelIndex& idx )
{
QModelIndex next = nextIndex( idx );
while ( next.isValid() && ( next.data( SubscriptionListModel::IsAggregationRole ).toBool() || next.sibling( next.row(), SubscriptionListModel::UnreadCountColumn ).data().toInt() == 0 ) )
next = nextIndex( next );
return next;
}
}
Akregator::SubscriptionListView::SubscriptionListView( QWidget* parent ) : QTreeView( parent )
{
setFocusPolicy( Qt::NoFocus );
setSelectionMode( QAbstractItemView::SingleSelection );
setRootIsDecorated( false );
setAlternatingRowColors( true );
setContextMenuPolicy( Qt::CustomContextMenu );
setDragDropMode( QAbstractItemView::DragDrop );
setDropIndicatorShown( true );
setAcceptDrops( true );
setUniformRowHeights( true );
setItemDelegate( new SubscriptionListDelegate( this ) );
connect( header(), SIGNAL( customContextMenuRequested( const QPoint & ) ), this, SLOT( showHeaderMenu( const QPoint& ) ) );
loadHeaderSettings();
}
Akregator::SubscriptionListView::~SubscriptionListView()
{
saveHeaderSettings();
}
void Akregator::SubscriptionListView::setModel( QAbstractItemModel* m )
{
if ( model() )
m_headerState = header()->saveState();
QTreeView::setModel( m );
if ( m )
header()->restoreState( m_headerState );
QStack<QModelIndex> stack;
stack.push( rootIndex() );
while ( !stack.isEmpty() )
{
const QModelIndex i = stack.pop();
const int childCount = m->rowCount( i );
for ( int j = 0; j < childCount; ++j )
{
const QModelIndex child = m->index( j, 0, i );
if ( child.isValid() )
stack.push( child );
}
setExpanded( i, i.data( Akregator::SubscriptionListModel::IsOpenRole ).toBool() );
}
header()->setContextMenuPolicy( Qt::CustomContextMenu );
}
void Akregator::SubscriptionListView::showHeaderMenu( const QPoint& pos )
{
if( ! model() )
return;
QPointer<KMenu> menu = new KMenu( this );
menu->addTitle( i18n( "Columns" ) );
menu->setAttribute( Qt::WA_DeleteOnClose );
connect(menu, SIGNAL( triggered( QAction* ) ), this, SLOT( headerMenuItemTriggered( QAction* ) ) );
for (int i = 0; i < model()->columnCount(); i++)
{
QString col = model()->headerData( i, Qt::Horizontal, Qt::DisplayRole ).toString();
QAction* act = menu->addAction( col );
act->setCheckable( true );
act->setChecked( !header()->isSectionHidden( i ) );
act->setData( i );
}
menu->popup( header()->mapToGlobal( pos ) );
}
void Akregator::SubscriptionListView::headerMenuItemTriggered( QAction* act )
{
assert( act );
const int col = act->data().toInt();
if ( act->isChecked() )
header()->showSection( col );
else
header()->hideSection( col );
}
void Akregator::SubscriptionListView::saveHeaderSettings()
{
if ( model() )
m_headerState = header()->saveState();
KConfigGroup conf( Settings::self()->config(), "General" );
conf.writeEntry( "SubscriptionListHeaders", m_headerState.toBase64() );
}
void Akregator::SubscriptionListView::loadHeaderSettings()
{
const KConfigGroup conf( Settings::self()->config(), "General" );
m_headerState = QByteArray::fromBase64( conf.readEntry( "SubscriptionListHeaders" ).toAscii() );
header()->restoreState( m_headerState ); // needed, even with Qt 4.5
}
void Akregator::SubscriptionListView::slotPrevFeed()
{
if ( !model() )
return;
const QModelIndex current = currentIndex();
QModelIndex prev = prevFeedIndex( current );
if ( !prev.isValid() )
{
prev = prevFeedIndex( lastLeaveChild( model() ), true );
}
if ( prev.isValid() )
setCurrentIndex( prev );
}
void Akregator::SubscriptionListView::slotNextFeed()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
QModelIndex next = nextFeedIndex( current );
if ( !next.isValid() )
next = nextFeedIndex( model()->index( 0, 0 ) );
if ( next.isValid() )
setCurrentIndex( next );
}
void Akregator::SubscriptionListView::slotPrevUnreadFeed()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
QModelIndex prev = prevUnreadFeedIndex( current );
if ( !prev.isValid() )
prev = prevUnreadFeedIndex( lastLeaveChild( model() ), true );
if ( prev.isValid() )
setCurrentIndex( prev );
}
void Akregator::SubscriptionListView::slotNextUnreadFeed()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
QModelIndex next = nextUnreadFeedIndex( current );
if ( !next.isValid() )
next = nextUnreadFeedIndex( model()->index( 0, 0 ) );
if ( next.isValid() )
setCurrentIndex( next );
}
void SubscriptionListView::slotItemBegin()
{
}
void SubscriptionListView::slotItemEnd()
{
}
void SubscriptionListView::slotItemLeft()
{
}
void SubscriptionListView::slotItemRight()
{
}
void SubscriptionListView::slotItemUp()
{
}
void SubscriptionListView::slotItemDown()
{
}
void Akregator::SubscriptionListView::ensureNodeVisible( Akregator::TreeNode* )
{
}
void Akregator::SubscriptionListView::startNodeRenaming( Akregator::TreeNode* node )
{
Q_UNUSED( node );
const QModelIndex current = currentIndex();
if ( !current.isValid() )
return;
edit( current );
}
#include "subscriptionlistview.moc"
<commit_msg>bring back keyboard navigation for the feed list (up, down, left, right, top, bottom)<commit_after>/*
This file is part of Akregator.
Copyright (C) 2007 Frank Osterfeld <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "subscriptionlistview.h"
#include "subscriptionlistmodel.h"
#include "subscriptionlistdelegate.h"
#include "akregatorconfig.h"
#include <QHeaderView>
#include <QStack>
#include <QPointer>
#include <KMenu>
#include <KLocale>
#include <KDebug>
#include <KConfigGroup>
#include <cassert>
using namespace Akregator;
static QModelIndex prevIndex( const QModelIndex& idx )
{
if ( !idx.isValid() )
return QModelIndex();
const QAbstractItemModel* const model = idx.model();
assert( model );
if ( idx.row() > 0 )
{
QModelIndex i = idx.sibling( idx.row() - 1, idx.column() );
while ( model->hasChildren( i ) )
i = i.child( model->rowCount( i ) - 1, i.column() );
return i;
}
else
return idx.parent();
}
static QModelIndex prevFeedIndex( const QModelIndex& idx, bool allowPassed = false )
{
QModelIndex prev = allowPassed ? idx : prevIndex( idx );
while ( prev.isValid() && prev.data( SubscriptionListModel::IsAggregationRole ).toBool() )
prev = prevIndex( prev );
return prev;
}
static QModelIndex prevUnreadFeedIndex( const QModelIndex& idx, bool allowPassed = false )
{
QModelIndex prev = allowPassed ? idx : prevIndex( idx );
while ( prev.isValid() && ( prev.data( SubscriptionListModel::IsAggregationRole ).toBool() || prev.sibling( prev.row(), SubscriptionListModel::UnreadCountColumn ).data().toInt() == 0 ) )
prev = prevIndex( prev );
return prev;
}
static QModelIndex lastLeaveChild( const QAbstractItemModel* const model )
{
assert( model );
if ( model->rowCount() == 0 )
return QModelIndex();
QModelIndex idx = model->index( model->rowCount() - 1, 0 );
while ( model->hasChildren( idx ) )
idx = idx.child( model->rowCount( idx ) - 1, idx.column() );
return idx;
}
static QModelIndex nextIndex( const QModelIndex& idx )
{
if ( !idx.isValid() )
return QModelIndex();
const QAbstractItemModel* const model = idx.model();
assert( model );
if ( model->hasChildren( idx ) )
return idx.child( 0, idx.column() );
QModelIndex i = idx;
while ( true )
{
if ( !i.isValid() )
return i;
const int siblings = model->rowCount( i.parent() );
if ( i.row() + 1 < siblings )
return i.sibling( i.row() + 1, i.column() );
i = i.parent();
}
}
static QModelIndex nextFeedIndex( const QModelIndex& idx )
{
QModelIndex next = nextIndex( idx );
while ( next.isValid() && next.data( SubscriptionListModel::IsAggregationRole ).toBool() )
next = nextIndex( next );
return next;
}
static QModelIndex nextUnreadFeedIndex( const QModelIndex& idx )
{
QModelIndex next = nextIndex( idx );
while ( next.isValid() && ( next.data( SubscriptionListModel::IsAggregationRole ).toBool() || next.sibling( next.row(), SubscriptionListModel::UnreadCountColumn ).data().toInt() == 0 ) )
next = nextIndex( next );
return next;
}
Akregator::SubscriptionListView::SubscriptionListView( QWidget* parent ) : QTreeView( parent )
{
setFocusPolicy( Qt::NoFocus );
setSelectionMode( QAbstractItemView::SingleSelection );
setRootIsDecorated( false );
setAlternatingRowColors( true );
setContextMenuPolicy( Qt::CustomContextMenu );
setDragDropMode( QAbstractItemView::DragDrop );
setDropIndicatorShown( true );
setAcceptDrops( true );
setUniformRowHeights( true );
setItemDelegate( new SubscriptionListDelegate( this ) );
connect( header(), SIGNAL( customContextMenuRequested( const QPoint & ) ), this, SLOT( showHeaderMenu( const QPoint& ) ) );
loadHeaderSettings();
}
Akregator::SubscriptionListView::~SubscriptionListView()
{
saveHeaderSettings();
}
void Akregator::SubscriptionListView::setModel( QAbstractItemModel* m )
{
if ( model() )
m_headerState = header()->saveState();
QTreeView::setModel( m );
if ( m )
header()->restoreState( m_headerState );
QStack<QModelIndex> stack;
stack.push( rootIndex() );
while ( !stack.isEmpty() )
{
const QModelIndex i = stack.pop();
const int childCount = m->rowCount( i );
for ( int j = 0; j < childCount; ++j )
{
const QModelIndex child = m->index( j, 0, i );
if ( child.isValid() )
stack.push( child );
}
setExpanded( i, i.data( Akregator::SubscriptionListModel::IsOpenRole ).toBool() );
}
header()->setContextMenuPolicy( Qt::CustomContextMenu );
}
void Akregator::SubscriptionListView::showHeaderMenu( const QPoint& pos )
{
if( ! model() )
return;
QPointer<KMenu> menu = new KMenu( this );
menu->addTitle( i18n( "Columns" ) );
menu->setAttribute( Qt::WA_DeleteOnClose );
connect(menu, SIGNAL( triggered( QAction* ) ), this, SLOT( headerMenuItemTriggered( QAction* ) ) );
for (int i = 0; i < model()->columnCount(); i++)
{
QString col = model()->headerData( i, Qt::Horizontal, Qt::DisplayRole ).toString();
QAction* act = menu->addAction( col );
act->setCheckable( true );
act->setChecked( !header()->isSectionHidden( i ) );
act->setData( i );
}
menu->popup( header()->mapToGlobal( pos ) );
}
void Akregator::SubscriptionListView::headerMenuItemTriggered( QAction* act )
{
assert( act );
const int col = act->data().toInt();
if ( act->isChecked() )
header()->showSection( col );
else
header()->hideSection( col );
}
void Akregator::SubscriptionListView::saveHeaderSettings()
{
if ( model() )
m_headerState = header()->saveState();
KConfigGroup conf( Settings::self()->config(), "General" );
conf.writeEntry( "SubscriptionListHeaders", m_headerState.toBase64() );
}
void Akregator::SubscriptionListView::loadHeaderSettings()
{
const KConfigGroup conf( Settings::self()->config(), "General" );
m_headerState = QByteArray::fromBase64( conf.readEntry( "SubscriptionListHeaders" ).toAscii() );
header()->restoreState( m_headerState ); // needed, even with Qt 4.5
}
void Akregator::SubscriptionListView::slotPrevFeed()
{
if ( !model() )
return;
const QModelIndex current = currentIndex();
QModelIndex prev = prevFeedIndex( current );
if ( !prev.isValid() )
{
prev = prevFeedIndex( lastLeaveChild( model() ), true );
}
if ( prev.isValid() )
setCurrentIndex( prev );
}
void Akregator::SubscriptionListView::slotNextFeed()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
QModelIndex next = nextFeedIndex( current );
if ( !next.isValid() )
next = nextFeedIndex( model()->index( 0, 0 ) );
if ( next.isValid() )
setCurrentIndex( next );
}
void Akregator::SubscriptionListView::slotPrevUnreadFeed()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
QModelIndex prev = prevUnreadFeedIndex( current );
if ( !prev.isValid() )
prev = prevUnreadFeedIndex( lastLeaveChild( model() ), true );
if ( prev.isValid() )
setCurrentIndex( prev );
}
void Akregator::SubscriptionListView::slotNextUnreadFeed()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
QModelIndex next = nextUnreadFeedIndex( current );
if ( !next.isValid() )
next = nextUnreadFeedIndex( model()->index( 0, 0 ) );
if ( next.isValid() )
setCurrentIndex( next );
}
void SubscriptionListView::slotItemBegin()
{
if ( !model() )
return;
emit userActionTakingPlace();
setCurrentIndex( nextFeedIndex( model()->index( 0, 0 ) ) );
}
void SubscriptionListView::slotItemEnd()
{
if ( !model() )
return;
emit userActionTakingPlace();
setCurrentIndex( lastLeaveChild( model() ) );
}
void SubscriptionListView::slotItemLeft()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
if ( !current.isValid() ) {
setCurrentIndex( nextFeedIndex( model()->index( 0, 0 ) ) );
return;
}
if ( current.parent().isValid() )
setCurrentIndex( current.parent() );
}
void SubscriptionListView::slotItemRight()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
if ( !current.isValid() ) {
setCurrentIndex( nextFeedIndex( model()->index( 0, 0 ) ) );
return;
}
if ( model()->rowCount( current ) > 0 )
setCurrentIndex( current.child( 0, 0 ) );
}
void SubscriptionListView::slotItemUp()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
QModelIndex prev = current.row() > 0 ? current.sibling( current.row() - 1, current.column() ) : current.parent();
if ( !prev.isValid() )
prev = lastLeaveChild( model() );
if ( prev.isValid() )
setCurrentIndex( prev );
}
void SubscriptionListView::slotItemDown()
{
if ( !model() )
return;
emit userActionTakingPlace();
const QModelIndex current = currentIndex();
if ( current.row() >= model()->rowCount( current.parent() ) )
return;
setCurrentIndex( current.sibling( current.row() + 1, current.column() ) );
}
void Akregator::SubscriptionListView::ensureNodeVisible( Akregator::TreeNode* )
{
}
void Akregator::SubscriptionListView::startNodeRenaming( Akregator::TreeNode* node )
{
Q_UNUSED( node );
const QModelIndex current = currentIndex();
if ( !current.isValid() )
return;
edit( current );
}
#include "subscriptionlistview.moc"
<|endoftext|> |
<commit_before>//
// Created by cheyulin on 8/4/16.
//
#include <functional>
#include <iostream>
using namespace std;
struct MyClass {
void PrintHello() {
//function_object() is ret_function, then we call ret_function()
cout << "Ret:" << function_object()(1) << endl;
//Directly call function_object2
function_object2();
function_object3();
}
//function_object hold ret_function, whole type is function<void(void)> object
//functional programming:
function<int(int)> function_object() {
function<int(int)> ret_function;
ret_function = [](int integer) -> int {
cout << "Hello World:" << integer << endl;
return -1;
};
return ret_function;
}
function<void()> function_object2 = []() {
cout << "Hello World 2" << endl;
};
function<void()> function_object3() {
cout << "Hello World 3" << endl;
return [] {};
}
};
int main() {
MyClass().PrintHello();
function<void(void)> function_object4 = []() {
cout << "Hello World 4" << endl;
};
function_object4();
}<commit_msg>add more examples<commit_after>//
// Created by cheyulin on 8/4/16.
//
#include <functional>
#include <iostream>
using namespace std;
struct MyClass {
void PrintHello() {
//function_object() is ret_function, then we call ret_function()
cout << "Ret:" << function_object()(111) << endl;
cout << "Ret:" << function_object0(2.0)(222)<<endl;
//Directly call function_object2
function_object2();
function_object3();
}
//function_object hold ret_function, whole type is function<void(void)> object
//functional programming:
function<int(int)> function_object() {
function<int(int)> ret_function;
ret_function = [](int integer) -> int {
cout << "Hello World:" << integer << endl;
return -1;
};
return ret_function;
}
function<int(int)> function_object0(float my_float) {
cout << "function_object0, my float:" << my_float << endl;
function<int(int)> ret_function;
ret_function = [](int integer) -> int {
cout << "Hello World:" << integer << endl;
return -2;
};
return ret_function;
}
function<void()> function_object2 = []() {
cout << "Hello World 2" << endl;
};
function<void()> function_object3() {
cout << "Hello World 3" << endl;
return [] {};
}
};
int main() {
MyClass().PrintHello();
function<void(void)> function_object4 = []() {
cout << "Hello World 4" << endl;
};
function_object4();
}<|endoftext|> |
<commit_before>//
// XYO Build
//
// Copyright (c) 2014 Grigore Stefan, <[email protected]>
// Created by Grigore Stefan <[email protected]>
//
// The MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef XYO_OS_TYPE_WIN
#include <windows.h>
#endif
#ifdef XYO_OS_TYPE_WIN
#ifdef XYO_MEMORY_LEAK_DETECTOR
#include "vld.h"
#endif
#endif
#include "libquantum-script.hpp"
#include "xyo-build-licence.hpp"
#include "xyo-build-copyright.hpp"
#ifndef XYO_BUILD_NO_VERSION
#include "xyo-build-version.hpp"
#endif
//#define QUANTUM_SCRIPT_VM_DEBUG_RUNTIME
using namespace XYO;
using namespace XYO::XY;
using namespace XYO::XO;
using namespace Quantum::Script;
bool isError;
QUANTUM_SCRIPT_INSTRUCTION_DEFINE(Build_isError);
QUANTUM_SCRIPT_INSTRUCTION_IMPLEMENT(Build_isError) {
#ifdef QUANTUM_SCRIPT_DEBUG_RUNTIME
printf("#%p build-is-error\n", context->currentProgramCounter);
#endif
TPointer<Variable> operand1;
operand1 = context->getArgument(0);
if (operand1) {
isError=Process::toBoolean(operand1);
};
return;
};
class Application :
public virtual IMain {
XYO_XY_DEFINE_PRIVATE_COPY(Application);
protected:
static bool initExecutive(Executive *);
void showUsage();
void showLicence();
public:
inline Application() {
};
int main(int cmdN, char *cmdS[]);
};
bool Application::initExecutive(Executive *executive) {
//executive->configPrintStackTraceLimit=1;
if (executive->compileString(
"\n"
"function With(this_,proc_){\n"
"\tproc_.call(this_);\n"
"};\n"
"function ForEach(what_,proc_,this_){\n"
"\tfor(var key in what_){\n"
"\t\tproc_.call(this_,key,what_[key]);\n"
"\t};\n"
"};\n"
) != 0) {
return false;
};
if (executive->compileString("Script.include(\"xyo-build.include/shell.js\");") != 0) {
return false;
};
if (executive->compileString("var Build={};") != 0) {
return false;
};
if (!executive->setVmFunction("Build.isError(flag)", InstructionBuild_isError, NULL)) {
return false;
};
return true;
};
void Application::showUsage() {
#ifdef XYO_BUILD_NO_VERSION
printf("XYO Build\n");
#else
printf("XYO Build - version %s build %s [%s]\n", XYO::Build::Version::getVersion(), XYO::Build::Version::getBuild(), XYO::Build::Version::getDatetime());
#endif
printf("%s\n\n", XYO::Build::Copyright::fullCopyright());
printf("%s\n",
"options:\n"
" --licence show licence\n"
" --help this help\n"
" --script script.js execute script file [default is workspace.xyo-build.js]\n"
);
};
void Application::showLicence() {
printf("%s", XYO::Build::Licence::content());
};
int Application::main(int cmdN, char *cmdS[]) {
int i;
char *opt;
const char *script_;
for (i = 1; i < cmdN; ++i) {
if (strncmp(cmdS[i], "--", 2) == 0) {
opt = &cmdS[i][2];
if (strcmp(opt, "help") == 0) {
showUsage();
return 0;
};
if (strcmp(opt, "licence") == 0) {
showLicence();
if (cmdN == 2) {
return 0;
};
};
continue;
};
};
script_ = "workspace.xyo-build.js";
for (i = 1; i < cmdN; ++i) {
if (i == 1) {
if (strlen(cmdS[i]) >= 3) {
if (strcmp(&cmdS[i][strlen(cmdS[i]) - 3], ".js") == 0) {
if (strncmp(cmdS[i], "--", 2) != 0) {
script_ = cmdS[i];
continue;
};
};
};
};
if (strcmp(cmdS[i], "--script") == 0) {
++i;
if (i < cmdN) {
script_ = cmdS[i];
};
continue;
};
};
String scriptConfig=(ExecutiveX::getExecutive()).pathExecutable;
scriptConfig<<"/xyo-build.config.js";
scriptConfig=StringX::replace(scriptConfig,"\\","/");
String script;
script << "\n"
"function BuildError(message){\n"
"\tthis.message=message;\n"
"\tthis.name=\"Build\";\n"
"};\n"
"BuildError.prototype=new Error();\n"
"function ___main(){\n"
"\tScript.include(\"xyo-build.include/build.js\");\n"
"\tif(Shell.fileExists(\""<<scriptConfig<<"\")){\n"
"\t\tScript.include(\""<<scriptConfig<<"\");\n"
"\t};\n"
"\tScript.include(\"xyo-build.include/make.js\");\n"
"\tScript.include(\"xyo-build.include/project.js\");\n"
"\tScript.include(\"xyo-build.include/solution.js\");\n"
"\tScript.include(\"xyo-build.include/platform.js\");\n"
"\tBuild.parseCommandLine();\n"
"\tif(Build.cmdMode()){\n"
"\t}else{\n"
"\t\tBuild.includeScript(\"" << script_ << "\");\n"
"\t\tPlatform.build(Build.mode_);\n"
"\t};\n"
"};\n"
"function ___exec(){\n"
"\ttry{\n"
"\t\t___main();\n"
"\t}catch(e){\n"
"\t\tBuild.isError(true);\n"
"\t\tConsole.writeLn(e.toString());\n"
"\t\tif(e instanceof BuildError){}else{\n"
"\t\t\tConsole.write(e.stackTrace);\n"
"\t\t};\n"
"\t};\n"
"};\n"
"___exec();\n";
if(ExecutiveX::initExecutive(cmdN,cmdS,initExecutive)) {
if(ExecutiveX::executeString(script)) {
ExecutiveX::executeEnd();
return 0;
};
};
fflush(stdout);
printf("%s\n",(ExecutiveX::getError()).value());
printf("%s",(ExecutiveX::getStackTrace()).value());
fflush(stdout);
ExecutiveX::executeEnd();
return -1;
};
XYO_XY_MAIN_STD(Application);
#ifdef QUANTUM_SCRIPT_AMALGAM
#include "quantum-script-amalgam.cpp"
#endif
<commit_msg>update<commit_after>//
// XYO Build
//
// Copyright (c) 2014 Grigore Stefan, <[email protected]>
// Created by Grigore Stefan <[email protected]>
//
// The MIT License (MIT) <http://opensource.org/licenses/MIT>
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef XYO_OS_TYPE_WIN
#include <windows.h>
#endif
#ifdef XYO_OS_TYPE_WIN
#ifdef XYO_MEMORY_LEAK_DETECTOR
#include "vld.h"
#endif
#endif
#include "libquantum-script.hpp"
#include "xyo-build-licence.hpp"
#include "xyo-build-copyright.hpp"
#ifndef XYO_BUILD_NO_VERSION
#include "xyo-build-version.hpp"
#endif
//#define QUANTUM_SCRIPT_VM_DEBUG_RUNTIME
using namespace XYO;
using namespace XYO::XY;
using namespace XYO::XO;
using namespace Quantum::Script;
bool isError;
QUANTUM_SCRIPT_INSTRUCTION_DEFINE(Build_isError);
QUANTUM_SCRIPT_INSTRUCTION_IMPLEMENT(Build_isError) {
#ifdef QUANTUM_SCRIPT_DEBUG_RUNTIME
printf("#%p build-is-error\n", context->currentProgramCounter);
#endif
TPointer<Variable> operand1;
operand1 = context->getArgument(0);
if (operand1) {
isError=operand1->toBoolean();
};
return;
};
class Application :
public virtual IMain {
XYO_XY_DEFINE_PRIVATE_COPY(Application);
protected:
static bool initExecutive(Executive *);
void showUsage();
void showLicence();
public:
inline Application() {
};
int main(int cmdN, char *cmdS[]);
};
bool Application::initExecutive(Executive *executive) {
//executive->configPrintStackTraceLimit=1;
if (executive->compileString(
"\n"
"function With(this_,proc_){\n"
"\tproc_.call(this_);\n"
"};\n"
"function ForEach(what_,proc_,this_){\n"
"\tfor(var key in what_){\n"
"\t\tproc_.call(this_,key,what_[key]);\n"
"\t};\n"
"};\n"
) != 0) {
return false;
};
if (executive->compileString("Script.include(\"xyo-build.include/shell.js\");") != 0) {
return false;
};
if (executive->compileString("var Build={};") != 0) {
return false;
};
if (!executive->setVmFunction("Build.isError(flag)", InstructionBuild_isError, NULL)) {
return false;
};
return true;
};
void Application::showUsage() {
#ifdef XYO_BUILD_NO_VERSION
printf("XYO Build\n");
#else
printf("XYO Build - version %s build %s [%s]\n", XYO::Build::Version::getVersion(), XYO::Build::Version::getBuild(), XYO::Build::Version::getDatetime());
#endif
printf("%s\n\n", XYO::Build::Copyright::fullCopyright());
printf("%s\n",
"options:\n"
" --licence show licence\n"
" --help this help\n"
" --script script.js execute script file [default is workspace.xyo-build.js]\n"
);
};
void Application::showLicence() {
printf("%s", XYO::Build::Licence::content());
};
int Application::main(int cmdN, char *cmdS[]) {
int i;
char *opt;
const char *script_;
for (i = 1; i < cmdN; ++i) {
if (strncmp(cmdS[i], "--", 2) == 0) {
opt = &cmdS[i][2];
if (strcmp(opt, "help") == 0) {
showUsage();
return 0;
};
if (strcmp(opt, "licence") == 0) {
showLicence();
if (cmdN == 2) {
return 0;
};
};
continue;
};
};
script_ = "workspace.xyo-build.js";
for (i = 1; i < cmdN; ++i) {
if (i == 1) {
if (strlen(cmdS[i]) >= 3) {
if (strcmp(&cmdS[i][strlen(cmdS[i]) - 3], ".js") == 0) {
if (strncmp(cmdS[i], "--", 2) != 0) {
script_ = cmdS[i];
continue;
};
};
};
};
if (strcmp(cmdS[i], "--script") == 0) {
++i;
if (i < cmdN) {
script_ = cmdS[i];
};
continue;
};
};
String scriptConfig=(ExecutiveX::getExecutive()).pathExecutable;
scriptConfig<<"/xyo-build.config.js";
scriptConfig=StringX::replace(scriptConfig,"\\","/");
String script;
script << "\n"
"function BuildError(message){\n"
"\tthis.message=message;\n"
"\tthis.name=\"Build\";\n"
"};\n"
"BuildError.prototype=new Error();\n"
"function ___main(){\n"
"\tScript.include(\"xyo-build.include/build.js\");\n"
"\tif(Shell.fileExists(\""<<scriptConfig<<"\")){\n"
"\t\tScript.include(\""<<scriptConfig<<"\");\n"
"\t};\n"
"\tScript.include(\"xyo-build.include/make.js\");\n"
"\tScript.include(\"xyo-build.include/project.js\");\n"
"\tScript.include(\"xyo-build.include/solution.js\");\n"
"\tScript.include(\"xyo-build.include/platform.js\");\n"
"\tBuild.parseCommandLine();\n"
"\tif(Build.cmdMode()){\n"
"\t}else{\n"
"\t\tBuild.includeScript(\"" << script_ << "\");\n"
"\t\tPlatform.build(Build.mode_);\n"
"\t};\n"
"};\n"
"function ___exec(){\n"
"\ttry{\n"
"\t\t___main();\n"
"\t}catch(e){\n"
"\t\tBuild.isError(true);\n"
"\t\tConsole.writeLn(e.toString());\n"
"\t\tif(e instanceof BuildError){}else{\n"
"\t\t\tConsole.write(e.stackTrace);\n"
"\t\t};\n"
"\t};\n"
"};\n"
"___exec();\n";
if(ExecutiveX::initExecutive(cmdN,cmdS,initExecutive)) {
if(ExecutiveX::executeString(script)) {
ExecutiveX::executeEnd();
return 0;
};
};
fflush(stdout);
printf("%s\n",(ExecutiveX::getError()).value());
printf("%s",(ExecutiveX::getStackTrace()).value());
fflush(stdout);
ExecutiveX::executeEnd();
return -1;
};
XYO_XY_MAIN_STD(Application);
#ifdef QUANTUM_SCRIPT_AMALGAM
#include "quantum-script-amalgam.cpp"
#endif
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_NETWORK_CONNECTIONS_HPP
#define LIBBITCOIN_NETWORK_CONNECTIONS_HPP
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/network/channel.hpp>
#include <bitcoin/network/define.hpp>
#include <bitcoin/bitcoin/message/address.hpp>
namespace libbitcoin {
namespace network {
/// Pool of active connections, thread and lock safe.
class BCT_API connections
: public enable_shared_from_base<connections>
{
public:
typedef std::shared_ptr<connections> ptr;
typedef std::function<void(bool)> truth_handler;
typedef std::function<void(size_t)> count_handler;
typedef std::function<void(const code&)> result_handler;
typedef std::function<void(const code&, channel::ptr)> channel_handler;
/// Construct an instance.
connections();
/// Validate connections stopped.
~connections();
/// This class is not copyable.
connections(const connections&) = delete;
void operator=(const connections&) = delete;
/// Send a message to all channels, with completion handlers.
/// Complete always returns success, use channel handler for failure codes.
template <typename Message>
void broadcast(const Message& message, channel_handler handle_channel,
result_handler handle_complete)
{
// We cannot use a synchronizer here because handler closure in loop.
auto counter = std::make_shared<std::atomic<size_t>>(channels_.size());
for (const auto channel: safe_copy())
{
const auto handle_send = [=](code ec)
{
handle_channel(ec, channel);
if (counter->fetch_sub(1) == 1)
handle_complete(error::success);
};
// No pre-serialize, channels may have different protocol versions.
channel->send(message, handle_send);
}
}
/// Subscribe to all incoming messages of a type.
template <class Message>
void subscribe(message_handler<Message>&& handler)
{
for (const auto channel: safe_copy())
channel->subscribe(
std::forward<message_handler<Message>>(handler));
}
virtual void stop(const code& ec);
virtual void count(count_handler handler) const;
virtual void store(channel::ptr channel, result_handler handler);
virtual void remove(channel::ptr channel, result_handler handler);
virtual void exists(const config::authority& authority,
truth_handler handler) const;
config::authority::list authority_list();
private:
typedef std::vector<channel::ptr> list;
list safe_copy() const;
size_t safe_count() const;
code safe_store(channel::ptr channel);
bool safe_remove(channel::ptr channel);
bool safe_exists(const config::authority& address) const;
list channels_;
std::atomic<bool> stopped_;
mutable upgrade_mutex mutex_;
};
} // namespace network
} // namespace libbitcoin
#endif
<commit_msg>fix nullptr handler<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* 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 <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_NETWORK_CONNECTIONS_HPP
#define LIBBITCOIN_NETWORK_CONNECTIONS_HPP
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/network/channel.hpp>
#include <bitcoin/network/define.hpp>
#include <bitcoin/bitcoin/message/address.hpp>
namespace libbitcoin {
namespace network {
/// Pool of active connections, thread and lock safe.
class BCT_API connections
: public enable_shared_from_base<connections>
{
public:
typedef std::shared_ptr<connections> ptr;
typedef std::function<void(bool)> truth_handler;
typedef std::function<void(size_t)> count_handler;
typedef std::function<void(const code&)> result_handler;
typedef std::function<void(const code&, channel::ptr)> channel_handler;
/// Construct an instance.
connections();
/// Validate connections stopped.
~connections();
/// This class is not copyable.
connections(const connections&) = delete;
void operator=(const connections&) = delete;
/// Send a message to all channels, with completion handlers.
/// Complete always returns success, use channel handler for failure codes.
template <typename Message>
void broadcast(const Message& message, channel_handler handle_channel,
result_handler handle_complete)
{
// We cannot use a synchronizer here because handler closure in loop.
auto counter = std::make_shared<std::atomic<size_t>>(channels_.size());
for (const auto channel: safe_copy())
{
const auto handle_send = [=](code ec)
{
handle_channel(ec, channel);
if (counter->fetch_sub(1) == 1)
handle_complete(error::success);
};
// No pre-serialize, channels may have different protocol versions.
channel->send(message, handle_send);
}
}
/// Subscribe to all incoming messages of a type.
template <class Message>
void subscribe(message_handler<Message>&& handler)
{
for (const auto channel: safe_copy())
{
auto handler_copy = handler;
channel->subscribe(std::move(handler_copy));//by jianglh
// channel->subscribe(
// std::forward<message_handler<Message>>(handler));
}
}
virtual void stop(const code& ec);
virtual void count(count_handler handler) const;
virtual void store(channel::ptr channel, result_handler handler);
virtual void remove(channel::ptr channel, result_handler handler);
virtual void exists(const config::authority& authority,
truth_handler handler) const;
config::authority::list authority_list();
private:
typedef std::vector<channel::ptr> list;
list safe_copy() const;
size_t safe_count() const;
code safe_store(channel::ptr channel);
bool safe_remove(channel::ptr channel);
bool safe_exists(const config::authority& address) const;
list channels_;
std::atomic<bool> stopped_;
mutable upgrade_mutex mutex_;
};
} // namespace network
} // namespace libbitcoin
#endif
<|endoftext|> |
<commit_before>#include "ToggleButton.h"
#include "Timer.h"
#include "Arduino.h"
const bool ToggleButton::IS_POS_LOGIC = false;
const bool ToggleButton::IS_NEG_LOGIC = true;
const int ToggleButton::BTN_NC = -1;
const int ToggleButton::IND_NC = -1;
const int ToggleButton::s_defaultKeyPollTime = 50;
//-----------------------------------------------------------------------------
class MyDebounceTimerAdatper : public TimerAdapter
{
private:
ToggleButton* m_toggleButton;
bool m_lastWasButtonPressed;
public:
MyDebounceTimerAdatper(ToggleButton* toggleButton)
: m_toggleButton(toggleButton)
, m_lastWasButtonPressed(false)
{ }
void timeExpired()
{
if (0 != m_toggleButton)
{
bool currentIsButtonPressed = m_toggleButton->isButtonPressed();
if (m_lastWasButtonPressed != currentIsButtonPressed)
{
m_lastWasButtonPressed = currentIsButtonPressed;
if (currentIsButtonPressed)
{
m_toggleButton->toggle();
}
}
}
}
};
//-----------------------------------------------------------------------------
ToggleButton::ToggleButton(int buttonPin, int indicatorPin, bool isButtonNegativeLogic, ToggleButtonAdapter* adapter)
: m_debounceTimer(new Timer(new MyDebounceTimerAdatper(this), Timer::IS_RECURRING, s_defaultKeyPollTime))
, m_adapter(adapter)
, m_isButtonNegativeLogic(isButtonNegativeLogic)
, m_isActive(false)
, m_buttonPin(buttonPin)
, m_indicatorPin(indicatorPin)
{
if (0 <= m_buttonPin)
{
pinMode(m_buttonPin, INPUT);
digitalWrite(m_buttonPin, m_isButtonNegativeLogic ? HIGH : LOW); // pull
}
if (0 <= m_indicatorPin)
{
pinMode(m_indicatorPin, OUTPUT);
digitalWrite(m_indicatorPin, m_isActive);
}
}
ToggleButton::~ToggleButton()
{
delete m_debounceTimer->adapter();
delete m_debounceTimer; m_debounceTimer = 0;
}
ToggleButtonAdapter* ToggleButton::adapter()
{
return m_adapter;
}
void ToggleButton::attachAdapter(ToggleButtonAdapter* adapter)
{
m_adapter = adapter;
}
bool ToggleButton::isActive()
{
return m_isActive;
}
void ToggleButton::setIsActive(bool isActive)
{
bool changed = (isActive != m_isActive);
m_isActive = isActive;
if (0 <= m_indicatorPin)
{
digitalWrite(m_indicatorPin, m_isActive);
}
if ((0 != m_adapter) && (changed))
{
m_adapter->notifyStatusChanged(m_isActive);
}
}
void ToggleButton::toggle()
{
m_isActive = !m_isActive;
digitalWrite(m_indicatorPin, m_isActive);
if (0 != m_adapter)
{
m_adapter->notifyStatusChanged(m_isActive);
}
}
bool ToggleButton::isButtonPressed()
{
bool pressed = false;
if (0 <= m_buttonPin)
{
pressed = digitalRead(m_buttonPin);
pressed = (m_isButtonNegativeLogic ? !pressed : pressed);
}
return pressed;
}
<commit_msg>Bug fix: toggle() avoid writing status to pin when not real indicator pin is configured.<commit_after>#include "ToggleButton.h"
#include "Timer.h"
#include "Arduino.h"
const bool ToggleButton::IS_POS_LOGIC = false;
const bool ToggleButton::IS_NEG_LOGIC = true;
const int ToggleButton::BTN_NC = -1;
const int ToggleButton::IND_NC = -1;
const int ToggleButton::s_defaultKeyPollTime = 50;
//-----------------------------------------------------------------------------
class MyDebounceTimerAdatper : public TimerAdapter
{
private:
ToggleButton* m_toggleButton;
bool m_lastWasButtonPressed;
public:
MyDebounceTimerAdatper(ToggleButton* toggleButton)
: m_toggleButton(toggleButton)
, m_lastWasButtonPressed(false)
{ }
void timeExpired()
{
if (0 != m_toggleButton)
{
bool currentIsButtonPressed = m_toggleButton->isButtonPressed();
if (m_lastWasButtonPressed != currentIsButtonPressed)
{
m_lastWasButtonPressed = currentIsButtonPressed;
if (currentIsButtonPressed)
{
m_toggleButton->toggle();
}
}
}
}
};
//-----------------------------------------------------------------------------
ToggleButton::ToggleButton(int buttonPin, int indicatorPin, bool isButtonNegativeLogic, ToggleButtonAdapter* adapter)
: m_debounceTimer(new Timer(new MyDebounceTimerAdatper(this), Timer::IS_RECURRING, s_defaultKeyPollTime))
, m_adapter(adapter)
, m_isButtonNegativeLogic(isButtonNegativeLogic)
, m_isActive(false)
, m_buttonPin(buttonPin)
, m_indicatorPin(indicatorPin)
{
if (0 <= m_buttonPin)
{
pinMode(m_buttonPin, INPUT);
digitalWrite(m_buttonPin, m_isButtonNegativeLogic ? HIGH : LOW); // pull
}
if (0 <= m_indicatorPin)
{
pinMode(m_indicatorPin, OUTPUT);
digitalWrite(m_indicatorPin, m_isActive);
}
}
ToggleButton::~ToggleButton()
{
delete m_debounceTimer->adapter();
delete m_debounceTimer; m_debounceTimer = 0;
}
ToggleButtonAdapter* ToggleButton::adapter()
{
return m_adapter;
}
void ToggleButton::attachAdapter(ToggleButtonAdapter* adapter)
{
m_adapter = adapter;
}
bool ToggleButton::isActive()
{
return m_isActive;
}
void ToggleButton::setIsActive(bool isActive)
{
bool changed = (isActive != m_isActive);
m_isActive = isActive;
if (0 <= m_indicatorPin)
{
digitalWrite(m_indicatorPin, m_isActive);
}
if ((0 != m_adapter) && (changed))
{
m_adapter->notifyStatusChanged(m_isActive);
}
}
void ToggleButton::toggle()
{
m_isActive = !m_isActive;
if (0 <= m_indicatorPin)
{
digitalWrite(m_indicatorPin, m_isActive);
}
if (0 != m_adapter)
{
m_adapter->notifyStatusChanged(m_isActive);
}
}
bool ToggleButton::isButtonPressed()
{
bool pressed = false;
if (0 <= m_buttonPin)
{
pressed = digitalRead(m_buttonPin);
pressed = (m_isButtonNegativeLogic ? !pressed : pressed);
}
return pressed;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef ELEM_LAPACK_QR_TS_HPP
#define ELEM_LAPACK_QR_TS_HPP
#include "elemental/blas-like/level1/MakeTriangular.hpp"
#include "elemental/lapack-like/ExpandPackedReflectors.hpp"
#include "elemental/lapack-like/QR.hpp"
namespace elem {
namespace qr {
namespace ts {
template<typename F>
struct TreeData
{
Matrix<F> QR0, t0;
std::vector<Matrix<F>> QRList;
std::vector<Matrix<F>> tList;
TreeData( Int numStages=0 )
: QRList(numStages), tList(numStages)
{ }
TreeData( TreeData<F>&& treeData )
: QR0(std::move(treeData.QR0)),
t0(std::move(treeData.t0)),
QRList(std::move(treeData.QRList)),
tList(std::move(treeData.tList))
{ }
TreeData<F>& operator=( TreeData<F>&& treeData )
{
QR0 = std::move(treeData.QR0);
t0 = std::move(treeData.t0);
QRList = std::move(treeData.QRList);
tList = std::move(treeData.tList);
return *this;
}
};
template<typename F,Distribution U>
inline void
Reduce( const DistMatrix<F,U,STAR>& A, TreeData<F>& treeData )
{
#ifndef RELEASE
CallStackEntry cse("qr::ts::Reduce");
#endif
const Int m = A.Height();
const Int n = A.Width();
const mpi::Comm colComm = A.ColComm();
const Int p = mpi::CommSize( colComm );
if( p == 1 )
return;
const Int rank = mpi::CommRank( colComm );
if( m < p*n )
LogicError("TSQR currently assumes height >= width*numProcesses");
if( !PowerOfTwo(p) )
LogicError("TSQR currently requires power-of-two number of processes");
const Int logp = Log2(p);
auto lastZ = LockedView( treeData.QR0, 0, 0, n, n );
treeData.QRList.resize( logp );
treeData.tList.resize( logp );
// Run the binary tree reduction
Matrix<F> ZTop(n,n,n), ZBot(n,n,n);
for( Int stage=0; stage<logp; ++stage )
{
// Pack, then send and receive n x n matrices
const Int partner = Unsigned(rank) ^ (Unsigned(1)<<stage);
const bool top = rank < partner;
if( top )
{
ZTop = lastZ;
MakeTriangular( UPPER, ZTop );
mpi::Recv( ZBot.Buffer(), n*n, partner, colComm );
}
else
{
ZBot = lastZ;
MakeTriangular( UPPER, ZBot );
mpi::Send( ZBot.LockedBuffer(), n*n, partner, colComm );
break;
}
auto& Q = treeData.QRList[stage];
auto& t = treeData.tList[stage];
Q.ResizeTo( 2*n, n, 2*n );
t.ResizeTo( n, 1 );
auto QTop = View( Q, 0, 0, n, n );
auto QBot = View( Q, n, 0, n, n );
QTop = ZTop;
QBot = ZBot;
// Note that the last QR is not performed by this routine, as many
// higher-level routines, such as TS-SVT, are simplified if the final
// small matrix is left alone.
if( stage < logp-1 )
{
// TODO: Exploit double-triangular structure
QR( Q, t );
lastZ = LockedView( Q, 0, 0, n, n );
}
}
}
template<typename F,Distribution U>
inline Matrix<F>&
RootQR( const DistMatrix<F,U,STAR>& A, TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
const Int rank = mpi::CommRank( A.ColComm() );
if( rank != 0 )
LogicError("This process does not have access to the root QR");
if( p == 1 )
return treeData.QR0;
else
return treeData.QRList.back();
}
template<typename F,Distribution U>
inline const Matrix<F>&
RootQR( const DistMatrix<F,U,STAR>& A, const TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
const Int rank = mpi::CommRank( A.ColComm() );
if( rank != 0 )
LogicError("This process does not have access to the root QR");
if( p == 1 )
return treeData.QR0;
else
return treeData.QRList.back();
}
template<typename F,Distribution U>
inline Matrix<F>&
RootPhases( const DistMatrix<F,U,STAR>& A, TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
const Int rank = mpi::CommRank( A.ColComm() );
if( rank != 0 )
LogicError("This process does not have access to the root phases");
if( p == 1 )
return treeData.t0;
else
return treeData.tList.back();
}
template<typename F,Distribution U>
inline const Matrix<F>&
RootPhases( const DistMatrix<F,U,STAR>& A, const TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
const Int rank = mpi::CommRank( A.ColComm() );
if( rank != 0 )
LogicError("This process does not have access to the root phases");
if( p == 1 )
return treeData.t0;
else
return treeData.tList.back();
}
template<typename F,Distribution U>
inline void
Scatter( DistMatrix<F,U,STAR>& A, const TreeData<F>& treeData )
{
#ifndef RELEASE
CallStackEntry cse("qr::ts::Scatter");
#endif
const Int m = A.Height();
const Int n = A.Width();
const mpi::Comm colComm = A.ColComm();
const Int p = mpi::CommSize( colComm );
if( p == 1 )
return;
const Int rank = mpi::CommRank( colComm );
if( m < p*n )
LogicError("TSQR currently assumes height >= width*numProcesses");
if( !PowerOfTwo(p) )
LogicError("TSQR currently requires power-of-two number of processes");
const Int logp = Log2(p);
// Run the binary tree scatter
Matrix<F> Z(2*n,n,2*n), ZHalf(n,n,n);
if( rank == 0 )
Z = RootQR( A, treeData );
auto ZTop = View( Z, 0, 0, n, n );
auto ZBot = View( Z, n, 0, n, n );
for( Int revStage=0; revStage<logp; ++revStage )
{
const Int stage = (logp-1)-revStage;
// Skip this stage if the first stage bits of our rank are not zero
if( stage>0 && (Unsigned(rank) & ((Unsigned(1)<<stage)-1)) )
continue;
const Int partner = rank ^ (1u<<stage);
const bool top = rank < partner;
if( top )
{
if( stage < logp-1 )
{
// Multiply by the current Q
ZTop = ZHalf;
MakeZeros( ZBot );
// TODO: Exploit sparsity?
ApplyQ
( LEFT, NORMAL,
treeData.QRList[stage], treeData.tList[stage], Z );
}
// Send bottom-half to partner and keep top half
ZHalf = ZBot;
mpi::Send( ZHalf.LockedBuffer(), n*n, partner, colComm );
ZHalf = ZTop;
}
else
{
// Recv top half from partner
mpi::Recv( ZHalf.Buffer(), n*n, partner, colComm );
}
}
// Apply the initial Q
MakeZeros( A.Matrix() );
auto ATop = View( A.Matrix(), 0, 0, n, n );
ATop = ZHalf;
// TODO: Exploit sparsity
ApplyQ( LEFT, NORMAL, treeData.QR0, treeData.t0, A.Matrix() );
}
template<typename F,Distribution U>
inline DistMatrix<F,STAR,STAR>
FormR( const DistMatrix<F,U,STAR>& A, const TreeData<F>& treeData )
{
const Grid& g = A.Grid();
DistMatrix<F,CIRC,CIRC> RRoot(g);
if( A.ColRank() == 0 )
{
const Int n = A.Width();
auto RTop = LockedView( RootQR(A,treeData), 0, 0, n, n );
RRoot.CopyFromRoot( RTop );
MakeTriangular( UPPER, RRoot );
}
else
RRoot.CopyFromNonRoot();
DistMatrix<F,STAR,STAR> R(g);
R = RRoot;
return R;
}
// NOTE: This is destructive
template<typename F,Distribution U>
inline void
FormQ( DistMatrix<F,U,STAR>& A, TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
if( p == 1 )
{
A.Matrix() = treeData.QR0;
ExpandPackedReflectors
( LOWER, VERTICAL, UNCONJUGATED, 0,
A.Matrix(), RootPhases(A,treeData) );
}
else
{
if( A.ColRank() == 0 )
ExpandPackedReflectors
( LOWER, VERTICAL, UNCONJUGATED, 0,
RootQR(A,treeData), RootPhases(A,treeData) );
Scatter( A, treeData );
}
}
} // namespace ts
template<typename F,Distribution U>
inline ts::TreeData<F>
TS( const DistMatrix<F,U,STAR>& A )
{
ts::TreeData<F> treeData;
treeData.QR0 = A.LockedMatrix();
QR( treeData.QR0, treeData.t0 );
const Int p = mpi::CommSize( A.ColComm() );
if( p != 1 )
{
ts::Reduce( A, treeData );
if( A.ColRank() == 0 )
QR( RootQR(A,treeData), RootPhases(A,treeData) );
}
return treeData;
}
template<typename F,Distribution U>
inline void
ExplicitTS( DistMatrix<F,U,STAR>& A, DistMatrix<F,STAR,STAR>& R )
{
auto treeData = TS( A );
R = ts::FormR( A, treeData );
ts::FormQ( A, treeData );
}
} // namespace qr
} // namespace elem
#endif // ifndef ELEM_LAPACK_QR_TS_HPP
<commit_msg>Fixing a few details in TSQR<commit_after>/*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef ELEM_LAPACK_QR_TS_HPP
#define ELEM_LAPACK_QR_TS_HPP
#include "elemental/blas-like/level1/MakeTriangular.hpp"
#include "elemental/lapack-like/ExpandPackedReflectors.hpp"
#include "elemental/lapack-like/QR.hpp"
namespace elem {
namespace qr {
template<typename F>
struct TreeData
{
Matrix<F> QR0, t0;
std::vector<Matrix<F>> QRList;
std::vector<Matrix<F>> tList;
TreeData( Int numStages=0 )
: QRList(numStages), tList(numStages)
{ }
TreeData( TreeData<F>&& treeData )
: QR0(std::move(treeData.QR0)),
t0(std::move(treeData.t0)),
QRList(std::move(treeData.QRList)),
tList(std::move(treeData.tList))
{ }
TreeData<F>& operator=( TreeData<F>&& treeData )
{
QR0 = std::move(treeData.QR0);
t0 = std::move(treeData.t0);
QRList = std::move(treeData.QRList);
tList = std::move(treeData.tList);
return *this;
}
};
namespace ts {
template<typename F,Distribution U>
inline void
Reduce( const DistMatrix<F,U,STAR>& A, TreeData<F>& treeData )
{
#ifndef RELEASE
CallStackEntry cse("qr::ts::Reduce");
#endif
const Int m = A.Height();
const Int n = A.Width();
const mpi::Comm colComm = A.ColComm();
const Int p = mpi::CommSize( colComm );
if( p == 1 )
return;
const Int rank = mpi::CommRank( colComm );
if( m < p*n )
LogicError("TSQR currently assumes height >= width*numProcesses");
if( !PowerOfTwo(p) )
LogicError("TSQR currently requires power-of-two number of processes");
const Int logp = Log2(p);
auto lastZ = LockedView( treeData.QR0, 0, 0, n, n );
treeData.QRList.resize( logp );
treeData.tList.resize( logp );
// Run the binary tree reduction
Matrix<F> ZTop(n,n,n), ZBot(n,n,n);
for( Int stage=0; stage<logp; ++stage )
{
// Pack, then send and receive n x n matrices
const Int partner = Unsigned(rank) ^ (Unsigned(1)<<stage);
const bool top = rank < partner;
if( top )
{
ZTop = lastZ;
MakeTriangular( UPPER, ZTop );
mpi::Recv( ZBot.Buffer(), n*n, partner, colComm );
}
else
{
ZBot = lastZ;
MakeTriangular( UPPER, ZBot );
mpi::Send( ZBot.LockedBuffer(), n*n, partner, colComm );
break;
}
auto& Q = treeData.QRList[stage];
auto& t = treeData.tList[stage];
Q.ResizeTo( 2*n, n, 2*n );
t.ResizeTo( n, 1 );
auto QTop = View( Q, 0, 0, n, n );
auto QBot = View( Q, n, 0, n, n );
QTop = ZTop;
QBot = ZBot;
// Note that the last QR is not performed by this routine, as many
// higher-level routines, such as TS-SVT, are simplified if the final
// small matrix is left alone.
if( stage < logp-1 )
{
// TODO: Exploit double-triangular structure
QR( Q, t );
lastZ = LockedView( Q, 0, 0, n, n );
}
}
}
template<typename F,Distribution U>
inline Matrix<F>&
RootQR( const DistMatrix<F,U,STAR>& A, TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
const Int rank = mpi::CommRank( A.ColComm() );
if( rank != 0 )
LogicError("This process does not have access to the root QR");
if( p == 1 )
return treeData.QR0;
else
return treeData.QRList.back();
}
template<typename F,Distribution U>
inline const Matrix<F>&
RootQR( const DistMatrix<F,U,STAR>& A, const TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
const Int rank = mpi::CommRank( A.ColComm() );
if( rank != 0 )
LogicError("This process does not have access to the root QR");
if( p == 1 )
return treeData.QR0;
else
return treeData.QRList.back();
}
template<typename F,Distribution U>
inline Matrix<F>&
RootPhases( const DistMatrix<F,U,STAR>& A, TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
const Int rank = mpi::CommRank( A.ColComm() );
if( rank != 0 )
LogicError("This process does not have access to the root phases");
if( p == 1 )
return treeData.t0;
else
return treeData.tList.back();
}
template<typename F,Distribution U>
inline const Matrix<F>&
RootPhases( const DistMatrix<F,U,STAR>& A, const TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
const Int rank = mpi::CommRank( A.ColComm() );
if( rank != 0 )
LogicError("This process does not have access to the root phases");
if( p == 1 )
return treeData.t0;
else
return treeData.tList.back();
}
template<typename F,Distribution U>
inline void
Scatter( DistMatrix<F,U,STAR>& A, const TreeData<F>& treeData )
{
#ifndef RELEASE
CallStackEntry cse("qr::ts::Scatter");
#endif
const Int m = A.Height();
const Int n = A.Width();
const mpi::Comm colComm = A.ColComm();
const Int p = mpi::CommSize( colComm );
if( p == 1 )
return;
const Int rank = mpi::CommRank( colComm );
if( m < p*n )
LogicError("TSQR currently assumes height >= width*numProcesses");
if( !PowerOfTwo(p) )
LogicError("TSQR currently requires power-of-two number of processes");
const Int logp = Log2(p);
// Run the binary tree scatter
Matrix<F> Z(2*n,n,2*n), ZHalf(n,n,n);
if( rank == 0 )
Z = RootQR( A, treeData );
auto ZTop = View( Z, 0, 0, n, n );
auto ZBot = View( Z, n, 0, n, n );
for( Int revStage=0; revStage<logp; ++revStage )
{
const Int stage = (logp-1)-revStage;
// Skip this stage if the first stage bits of our rank are not zero
if( stage>0 && (Unsigned(rank) & ((Unsigned(1)<<stage)-1)) )
continue;
const Int partner = rank ^ (1u<<stage);
const bool top = rank < partner;
if( top )
{
if( stage < logp-1 )
{
// Multiply by the current Q
ZTop = ZHalf;
MakeZeros( ZBot );
// TODO: Exploit sparsity?
ApplyQ
( LEFT, NORMAL,
treeData.QRList[stage], treeData.tList[stage], Z );
}
// Send bottom-half to partner and keep top half
ZHalf = ZBot;
mpi::Send( ZHalf.LockedBuffer(), n*n, partner, colComm );
ZHalf = ZTop;
}
else
{
// Recv top half from partner
mpi::Recv( ZHalf.Buffer(), n*n, partner, colComm );
}
}
// Apply the initial Q
MakeZeros( A.Matrix() );
auto ATop = View( A.Matrix(), 0, 0, n, n );
ATop = ZHalf;
// TODO: Exploit sparsity
ApplyQ( LEFT, NORMAL, treeData.QR0, treeData.t0, A.Matrix() );
}
template<typename F,Distribution U>
inline DistMatrix<F,STAR,STAR>
FormR( const DistMatrix<F,U,STAR>& A, const TreeData<F>& treeData )
{
const Grid& g = A.Grid();
DistMatrix<F,CIRC,CIRC> RRoot(g);
if( A.ColRank() == 0 )
{
const Int n = A.Width();
auto RTop = LockedView( RootQR(A,treeData), 0, 0, n, n );
RRoot.CopyFromRoot( RTop );
MakeTriangular( UPPER, RRoot );
}
else
RRoot.CopyFromNonRoot();
DistMatrix<F,STAR,STAR> R(g);
R = RRoot;
return R;
}
// NOTE: This is destructive
template<typename F,Distribution U>
inline void
FormQ( DistMatrix<F,U,STAR>& A, TreeData<F>& treeData )
{
const Int p = mpi::CommSize( A.ColComm() );
if( p == 1 )
{
A.Matrix() = treeData.QR0;
ExpandPackedReflectors
( LOWER, VERTICAL, UNCONJUGATED, 0,
A.Matrix(), RootPhases(A,treeData) );
}
else
{
if( A.ColRank() == 0 )
ExpandPackedReflectors
( LOWER, VERTICAL, UNCONJUGATED, 0,
RootQR(A,treeData), RootPhases(A,treeData) );
Scatter( A, treeData );
}
}
} // namespace ts
template<typename F,Distribution U>
inline TreeData<F>
TS( const DistMatrix<F,U,STAR>& A )
{
TreeData<F> treeData;
treeData.QR0 = A.LockedMatrix();
QR( treeData.QR0, treeData.t0 );
const Int p = mpi::CommSize( A.ColComm() );
if( p != 1 )
{
ts::Reduce( A, treeData );
if( A.ColRank() == 0 )
QR( ts::RootQR(A,treeData), ts::RootPhases(A,treeData) );
}
return treeData;
}
template<typename F,Distribution U>
inline void
ExplicitTS( DistMatrix<F,U,STAR>& A, DistMatrix<F,STAR,STAR>& R )
{
auto treeData = TS( A );
R = ts::FormR( A, treeData );
ts::FormQ( A, treeData );
}
} // namespace qr
} // namespace elem
#endif // ifndef ELEM_LAPACK_QR_TS_HPP
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/exp_omi_setup.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_omi_setup.C
/// @brief Contains the explorer OMI setup
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Stephen Glancy <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: Memory
#include <fapi2.H>
#include <generic/memory/lib/utils/c_str.H>
#include <lib/exp_attribute_accessors_manual.H>
#include <lib/omi/exp_omi_utils.H>
#include <lib/workarounds/exp_omi_workarounds.H>
#include <lib/i2c/exp_i2c.H>
#include <generic/memory/mss_git_data_helper.H>
#include <generic/memory/lib/mss_generic_attribute_getters.H>
#include <generic/memory/lib/mss_generic_system_attribute_getters.H>
extern "C"
{
///
/// @brief Setup the OCMB for enterprise and half-DIMM modes as desired
/// @param[in] i_target the OCMB target to operate on
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode exp_omi_setup( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target)
{
mss::display_git_commit_info("exp_omi_setup");
// Declares variables
fapi2::buffer<uint64_t> l_data;
fapi2::buffer<uint64_t> dlx_config1_data;
uint8_t l_edpl_disable = 0;
bool l_is_enterprise = false;
bool l_is_half_dimm = false;
bool l_workaround_required = false;
std::vector<uint8_t> l_boot_config_data;
uint8_t l_dl_layer_boot_mode = fapi2::ENUM_ATTR_MSS_OCMB_EXP_BOOT_CONFIG_DL_LAYER_BOOT_MODE_NON_DL_TRAINING;
// Gets the data setup
FAPI_TRY(mss::exp::omi::train::setup_fw_boot_config(i_target, l_boot_config_data));
// Sanity check: set dl_layer_boot_mode to NON DL TRAINING (0b00 == default)
FAPI_TRY(mss::exp::i2c::boot_cfg::set_dl_layer_boot_mode( i_target, l_boot_config_data, l_dl_layer_boot_mode ));
// Issues the command and checks for completion
// Note: This does not kick off OMI training
FAPI_TRY(mss::exp::i2c::boot_config(i_target, l_boot_config_data));
// Gets the configuration information from attributes
FAPI_TRY(mss::enterprise_mode(i_target, l_is_enterprise));
FAPI_TRY(mss::half_dimm_mode(i_target, l_is_half_dimm));
FAPI_TRY(mss::attr::get_mss_omi_edpl_disable(l_edpl_disable));
// Prints out the data
FAPI_INF("%s is %s enterprise mode, and %s-DIMM mode", mss::c_str(i_target), l_is_enterprise ? "" : "non",
l_is_half_dimm ? "half" : "full");
// Sets up the register
mss::exp::omi::set_enterprise_set_bit(l_data, l_is_enterprise);
mss::exp::omi::set_half_dimm_mode(l_data, l_is_half_dimm);
// Writes the data to the register
FAPI_TRY(mss::exp::omi::write_enterprise_config(i_target, l_data));
// Checks that the chip is configured correctly
FAPI_TRY(mss::exp::omi::read_enterprise_config(i_target, l_data));
FAPI_TRY(mss::exp::omi::check_enterprise_mode(i_target, l_is_enterprise, l_data));
// Set the EDPL according the attribute
FAPI_TRY(mss::exp::omi::read_dlx_config1(i_target, dlx_config1_data));
mss::exp::omi::set_edpl_enable_bit(dlx_config1_data, l_edpl_disable);
FAPI_TRY(mss::exp::omi::write_dlx_config1(i_target, dlx_config1_data));
FAPI_INF("%s EDPL enable: ", mss::c_str(i_target), l_edpl_disable ? "false" : "true");
// Run the workaround if it's needed
FAPI_TRY(mss::exp::workarounds::omi::is_prbs_ocmb_required(i_target, l_workaround_required));
if (l_workaround_required)
{
uint8_t l_dl_x4_backoff_en = 0;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_OMI_DL_X4_BACKOFF_ENABLE, i_target, l_dl_x4_backoff_en),
"Error getting ATTR_CHIP_EC_FEATURE_OMI_DL_X4_BACKOFF_ENABLE");
FAPI_TRY(mss::exp::workarounds::omi::prbs_ocmb(i_target, l_dl_x4_backoff_en));
}
fapi_try_exit:
return fapi2::current_err;
}
}
<commit_msg>Fix FAPI_INF segfault in exp_omi_setup<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/exp_omi_setup.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file exp_omi_setup.C
/// @brief Contains the explorer OMI setup
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Stephen Glancy <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: Memory
#include <fapi2.H>
#include <generic/memory/lib/utils/c_str.H>
#include <lib/exp_attribute_accessors_manual.H>
#include <lib/omi/exp_omi_utils.H>
#include <lib/workarounds/exp_omi_workarounds.H>
#include <lib/i2c/exp_i2c.H>
#include <generic/memory/mss_git_data_helper.H>
#include <generic/memory/lib/mss_generic_attribute_getters.H>
#include <generic/memory/lib/mss_generic_system_attribute_getters.H>
extern "C"
{
///
/// @brief Setup the OCMB for enterprise and half-DIMM modes as desired
/// @param[in] i_target the OCMB target to operate on
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode exp_omi_setup( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target)
{
mss::display_git_commit_info("exp_omi_setup");
// Declares variables
fapi2::buffer<uint64_t> l_data;
fapi2::buffer<uint64_t> dlx_config1_data;
uint8_t l_edpl_disable = 0;
bool l_is_enterprise = false;
bool l_is_half_dimm = false;
bool l_workaround_required = false;
std::vector<uint8_t> l_boot_config_data;
uint8_t l_dl_layer_boot_mode = fapi2::ENUM_ATTR_MSS_OCMB_EXP_BOOT_CONFIG_DL_LAYER_BOOT_MODE_NON_DL_TRAINING;
// Gets the data setup
FAPI_TRY(mss::exp::omi::train::setup_fw_boot_config(i_target, l_boot_config_data));
// Sanity check: set dl_layer_boot_mode to NON DL TRAINING (0b00 == default)
FAPI_TRY(mss::exp::i2c::boot_cfg::set_dl_layer_boot_mode( i_target, l_boot_config_data, l_dl_layer_boot_mode ));
// Issues the command and checks for completion
// Note: This does not kick off OMI training
FAPI_TRY(mss::exp::i2c::boot_config(i_target, l_boot_config_data));
// Gets the configuration information from attributes
FAPI_TRY(mss::enterprise_mode(i_target, l_is_enterprise));
FAPI_TRY(mss::half_dimm_mode(i_target, l_is_half_dimm));
FAPI_TRY(mss::attr::get_mss_omi_edpl_disable(l_edpl_disable));
// Prints out the data
FAPI_INF("%s is %s enterprise mode, and %s-DIMM mode", mss::c_str(i_target), l_is_enterprise ? "" : "non",
l_is_half_dimm ? "half" : "full");
// Sets up the register
mss::exp::omi::set_enterprise_set_bit(l_data, l_is_enterprise);
mss::exp::omi::set_half_dimm_mode(l_data, l_is_half_dimm);
// Writes the data to the register
FAPI_TRY(mss::exp::omi::write_enterprise_config(i_target, l_data));
// Checks that the chip is configured correctly
FAPI_TRY(mss::exp::omi::read_enterprise_config(i_target, l_data));
FAPI_TRY(mss::exp::omi::check_enterprise_mode(i_target, l_is_enterprise, l_data));
// Set the EDPL according the attribute
FAPI_TRY(mss::exp::omi::read_dlx_config1(i_target, dlx_config1_data));
mss::exp::omi::set_edpl_enable_bit(dlx_config1_data, l_edpl_disable);
FAPI_TRY(mss::exp::omi::write_dlx_config1(i_target, dlx_config1_data));
FAPI_INF("%s EDPL enable: %s", mss::c_str(i_target), (l_edpl_disable ? "false" : "true"));
// Run the workaround if it's needed
FAPI_TRY(mss::exp::workarounds::omi::is_prbs_ocmb_required(i_target, l_workaround_required));
if (l_workaround_required)
{
uint8_t l_dl_x4_backoff_en = 0;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_OMI_DL_X4_BACKOFF_ENABLE, i_target, l_dl_x4_backoff_en),
"Error getting ATTR_CHIP_EC_FEATURE_OMI_DL_X4_BACKOFF_ENABLE");
FAPI_TRY(mss::exp::workarounds::omi::prbs_ocmb(i_target, l_dl_x4_backoff_en));
}
fapi_try_exit:
return fapi2::current_err;
}
}
<|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.
*/
#ifndef FLUSSPFERD_FUNCTION_ADAPTER_HPP
#define FLUSSPFERD_FUNCTION_ADAPTER_HPP
#include "convert.hpp"
#include "call_context.hpp"
#include <boost/type_traits/is_convertible.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/function.hpp>
namespace flusspferd {
namespace detail {
template<typename T>
struct is_native_object_type {
typedef typename boost::remove_reference<T>::type T2;
typedef typename boost::remove_pointer<T2>::type native_object_type;
typedef typename boost::is_convertible<T2, native_object_base>::type type;
};
template<typename T, typename Condition = void>
struct ptr_to_native_object_type {
static T get(native_object_base *self_native) {
return self_native;
}
};
template<typename T>
struct ptr_to_native_object_type<
T, typename boost::enable_if<typename boost::is_pointer<T>::type>::type>
{
static T get(native_object_base *self_native) {
return *self_native;
}
};
native_object_base *
get_native_object_parameter(call_context &x, std::size_t &offset) {
native_object_base *p = x.self_native;
if (p)
return p;
convert<native_object_base *>::from_value from_value;
p = from_value.perform(x.arg[offset++]);
return p;
}
template<
typename T,
typename R = typename T::result_type,
std::size_t A = T::arity,
typename Condition = void>
struct function_adapter;
template<typename T, typename R>
struct function_adapter<T, R, 0> {
typename convert<R>::to_value to_value;
void action(T const &function, call_context &x) {
x.result = to_value.perform(function());
}
};
template<typename T>
struct function_adapter<T, void, 0> {
void action(T const &function, call_context &) {
function();
}
};
template<typename T, typename R>
struct function_adapter<
T, R, 1,
typename boost::enable_if<
typename is_native_object_type<typename T::arg1_type>::type
>::type
>
{
typename convert<R>::to_value to_value;
typedef typename T::arg1_type arg1_type;
void action(T const &function, call_context &x) {
std::size_t offset = 0;
native_object_base *obj = get_native_object_parameter(x, offset);
arg1_type arg1 = ptr_to_native_object_type<arg1_type>::get(obj);
x.result = to_value.perform(function(arg1));
}
};
template<typename T>
struct function_adapter<
T, void, 1,
typename boost::enable_if<
typename is_native_object_type<typename T::arg1_type>::type
>::type
>
{
typedef typename T::arg1_type arg1_type;
void action(T const &function, call_context &x) {
std::size_t offset = 0;
native_object_base *obj = get_native_object_parameter(x, offset);
arg1_type arg1 = ptr_to_native_object_type<arg1_type>::get(obj);
function(arg1);
}
};
template<typename T, typename R>
struct function_adapter<
T, R, 1,
typename boost::enable_if<
typename boost::is_convertible<typename T::arg1_type, object>::type
>::type
>
{
typename convert<R>::to_value to_value;
void action(T const &function, call_context &x) {
x.result = to_value.perform(function(x.self));
}
};
template<typename T>
struct function_adapter<
T, void, 1,
typename boost::enable_if<
typename boost::is_convertible<typename T::arg1_type, object>::type
>::type
>
{
void action(T const &function, call_context &x) {
function(x.self);
}
};
template<typename T, typename R, typename C>
struct function_adapter<T, R, 1, C> {
typename convert<R>::to_value to_value;
typedef typename T::arg1_type arg1_type;
typename convert<arg1_type>::from_value arg1_from_value;
void action(T const &function, call_context &x) {
x.result = to_value.perform(function(arg1_from_value.perform(x.arg[0])));
}
};
template<typename T, typename C>
struct function_adapter<T, void, 1, C> {
typedef typename T::arg1_type arg1_type;
typename convert<arg1_type>::from_value arg1_from_value;
void action(T const &function, call_context &x) {
function(arg1_from_value.perform(x.arg[0]));
}
};
}
template<typename T>
class function_adapter {
public:
typedef T spec_type;
typedef boost::function<spec_type> function_type;
function_adapter(function_type const &function)
: function(function)
{}
void operator() (call_context &x) {
detail::function_adapter<function_type> function_adapter_implementation;
function_adapter_implementation.action(function, x);
}
private:
function_type function;
};
}
#endif
<commit_msg>macro abstractions<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.
*/
#ifndef FLUSSPFERD_FUNCTION_ADAPTER_HPP
#define FLUSSPFERD_FUNCTION_ADAPTER_HPP
#if 1
#include "convert.hpp"
#include "call_context.hpp"
#include <boost/type_traits/is_convertible.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/function.hpp>
#endif
#include <boost/preprocessor.hpp>
namespace flusspferd {
namespace detail {
template<typename T>
struct is_native_object_type {
typedef typename boost::remove_reference<T>::type T2;
typedef typename boost::remove_pointer<T2>::type native_object_type;
typedef typename boost::is_convertible<T2, native_object_base>::type type;
};
template<typename T, typename Condition = void>
struct ptr_to_native_object_type {
static T get(native_object_base *self_native) {
return self_native;
}
};
template<typename T>
struct ptr_to_native_object_type<
T, typename boost::enable_if<typename boost::is_pointer<T>::type>::type>
{
static T get(native_object_base *self_native) {
return *self_native;
}
};
native_object_base *
get_native_object_parameter(call_context &x, std::size_t &offset) {
native_object_base *p = x.self_native;
if (p)
return p;
convert<native_object_base *>::from_value from_value;
p = from_value.perform(x.arg[offset++]);
return p;
}
template<
typename T,
typename R = typename T::result_type,
std::size_t A = T::arity,
typename Condition = void>
struct function_adapter;
template<typename T, typename R>
struct function_adapter<T, R, 0> {
typename convert<R>::to_value to_value;
void action(T const &function, call_context &x) {
x.result = to_value.perform(function());
}
};
template<typename T>
struct function_adapter<T, void, 0> {
void action(T const &function, call_context &) {
function();
}
};
template<typename T, typename R>
struct function_adapter<
T, R, 1,
typename boost::enable_if<
typename is_native_object_type<typename T::arg1_type>::type
>::type
>
{
typename convert<R>::to_value to_value;
typedef typename T::arg1_type arg1_type;
void action(T const &function, call_context &x) {
std::size_t offset = 0;
native_object_base *obj = get_native_object_parameter(x, offset);
arg1_type arg1 = ptr_to_native_object_type<arg1_type>::get(obj);
x.result = to_value.perform(function(arg1));
}
};
template<typename T>
struct function_adapter<
T, void, 1,
typename boost::enable_if<
typename is_native_object_type<typename T::arg1_type>::type
>::type
>
{
typedef typename T::arg1_type arg1_type;
void action(T const &function, call_context &x) {
std::size_t offset = 0;
native_object_base *obj = get_native_object_parameter(x, offset);
arg1_type arg1 = ptr_to_native_object_type<arg1_type>::get(obj);
function(arg1);
}
};
template<typename T, typename R>
struct function_adapter<
T, R, 1,
typename boost::enable_if<
typename boost::is_convertible<typename T::arg1_type, object>::type
>::type
>
{
typename convert<R>::to_value to_value;
void action(T const &function, call_context &x) {
x.result = to_value.perform(function(x.self));
}
};
template<typename T>
struct function_adapter<
T, void, 1,
typename boost::enable_if<
typename boost::is_convertible<typename T::arg1_type, object>::type
>::type
>
{
void action(T const &function, call_context &x) {
function(x.self);
}
};
#define FLUSSPFERD_DECLARE_ARG_CONVERTER(z, i, T) \
typename convert<typename T::BOOST_PP_CAT(BOOST_PP_CAT(arg, i), _type)>::from_value \
BOOST_PP_CAT(BOOST_PP_CAT(arg, i), _from_value); \
/**/
#define FLUSSPFERD_DECLARE_ARG_CONVERTERS(n, T) \
BOOST_PP_REPEAT_FROM_TO( \
1, \
BOOST_PP_INC(n), \
FLUSSPFERD_DECLARE_ARG_CONVERTER, \
T) \
/**/
#define FLUSSPFERD_CONVERT_ARG(z, i, x) \
BOOST_PP_COMMA_IF(BOOST_PP_GREATER(i, 1)) \
BOOST_PP_CAT(BOOST_PP_CAT(arg, i), _from_value) \
.perform((x).arg[BOOST_PP_DEC(i)]) \
/**/
#define FLUSSPFERD_CONVERT_ARGS(n, x) \
BOOST_PP_REPEAT_FROM_TO( \
1, \
BOOST_PP_INC(n), \
FLUSSPFERD_CONVERT_ARG, \
x) \
/**/
template<typename T, typename R, typename C>
struct function_adapter<T, R, 1, C> {
typename convert<R>::to_value to_value;
FLUSSPFERD_DECLARE_ARG_CONVERTERS(1, T)
void action(T const &function, call_context &x) {
x.result = to_value.perform(FLUSSPFERD_CONVERT_ARGS(1, x));
}
};
template<typename T, typename C>
struct function_adapter<T, void, 1, C> {
FLUSSPFERD_DECLARE_ARG_CONVERTERS(1, T)
void action(T const &function, call_context &x) {
function(FLUSSPFERD_CONVERT_ARGS(1, x));
}
};
}
template<typename T>
class function_adapter {
public:
typedef T spec_type;
typedef boost::function<spec_type> function_type;
function_adapter(function_type const &function)
: function(function)
{}
void operator() (call_context &x) {
detail::function_adapter<function_type> function_adapter_implementation;
function_adapter_implementation.action(function, x);
}
private:
function_type function;
};
}
#endif
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2017 Intel Corporation. All Rights Reserved.
#ifndef LIBREALSENSE_RS2_EXPORT_HPP
#define LIBREALSENSE_RS2_EXPORT_HPP
#include <map>
#include <fstream>
#include <cmath>
#include <sstream>
#include <cassert>
#include "rs_processing.hpp"
#include "rs_internal.hpp"
namespace rs2
{
class save_to_ply : public filter
{
public:
save_to_ply(std::string filename = "RealSense Pointcloud ", pointcloud pc = pointcloud())
: filter([this](frame f, frame_source& s) { func(f, s); }),
_pc(std::move(pc)), fname(filename)
{
register_simple_option(OPTION_IGNORE_COLOR, option_range{ 0, 1, 0, 1 });
}
DECLARE_PB_OPTION(OPTION_IGNORE_COLOR, 1);
private:
void func(frame data, frame_source& source)
{
frame depth, color;
if (auto fs = data.as<frameset>()) {
for (auto f : fs) {
if (f.is<points>()) depth = f;
else if (!depth && f.is<depth_frame>()) depth = f;
else if (!color && f.is<video_frame>()) color = f;
}
} else if (data.is<depth_frame>() || data.is<points>()) {
depth = data;
}
if (!depth) throw std::runtime_error("Need depth data to save PLY");
if (!depth.is<points>()) {
if (color) _pc.map_to(color);
depth = _pc.calculate(depth);
}
export_to_ply(depth, color);
source.frame_ready(data); // passthrough filter because processing_block::process doesn't support sinks
}
void export_to_ply(points p, video_frame color) {
const bool use_texcoords = color && get_option(OPTION_IGNORE_COLOR);
const auto verts = p.get_vertices();
const auto texcoords = p.get_texture_coordinates();
std::vector<rs2::vertex> new_verts;
std::vector<std::array<uint8_t, 3>> new_tex;
std::map<int, int> idx_map;
new_verts.reserve(p.size());
if (use_texcoords) new_tex.reserve(p.size());
static const auto min_distance = 1e-6;
for (size_t i = 0; i < p.size(); ++i) {
if (fabs(verts[i].x) >= min_distance || fabs(verts[i].y) >= min_distance ||
fabs(verts[i].z) >= min_distance)
{
idx_map[i] = new_verts.size();
new_verts.push_back(verts[i]);
if (use_texcoords)
{
auto rgb = get_texcolor(color, texcoords[i].u, texcoords[i].v);
new_tex.push_back(rgb);
}
}
}
auto profile = p.get_profile().as<video_stream_profile>();
auto width = profile.width(), height = profile.height();
static const auto threshold = 0.05f;
std::vector<std::array<int, 3>> faces;
for (int x = 0; x < width - 1; ++x) {
for (int y = 0; y < height - 1; ++y) {
auto a = y * width + x, b = y * width + x + 1, c = (y + 1)*width + x, d = (y + 1)*width + x + 1;
if (verts[a].z && verts[b].z && verts[c].z && verts[d].z
&& fabs(verts[a].z - verts[b].z) < threshold && fabs(verts[a].z - verts[c].z) < threshold
&& fabs(verts[b].z - verts[d].z) < threshold && fabs(verts[c].z - verts[d].z) < threshold)
{
if (idx_map.count(a) == 0 || idx_map.count(b) == 0 || idx_map.count(c) == 0 ||
idx_map.count(d) == 0)
continue;
faces.push_back({ idx_map[a], idx_map[b], idx_map[d] });
faces.push_back({ idx_map[d], idx_map[c], idx_map[a] });
}
}
}
std::stringstream name;
name << fname << p.get_frame_number() << ".ply";
std::ofstream out(name.str());
out << "ply\n";
out << "format binary_little_endian 1.0\n";
out << "comment pointcloud saved from Realsense Viewer\n";
out << "element vertex " << new_verts.size() << "\n";
out << "property float" << sizeof(float) * 8 << " x\n";
out << "property float" << sizeof(float) * 8 << " y\n";
out << "property float" << sizeof(float) * 8 << " z\n";
if (use_texcoords)
{
out << "property uchar red\n";
out << "property uchar green\n";
out << "property uchar blue\n";
}
out << "element face " << faces.size() << "\n";
out << "property list uchar int vertex_indices\n";
out << "end_header\n";
out.close();
out.open(name.str(), std::ios_base::app | std::ios_base::binary);
for (int i = 0; i < new_verts.size(); ++i)
{
// we assume little endian architecture on your device
out.write(reinterpret_cast<const char*>(&(new_verts[i].x)), sizeof(float));
out.write(reinterpret_cast<const char*>(&(new_verts[i].y)), sizeof(float));
out.write(reinterpret_cast<const char*>(&(new_verts[i].z)), sizeof(float));
if (use_texcoords)
{
out.write(reinterpret_cast<const char*>(&(new_tex[i][0])), sizeof(uint8_t));
out.write(reinterpret_cast<const char*>(&(new_tex[i][1])), sizeof(uint8_t));
out.write(reinterpret_cast<const char*>(&(new_tex[i][2])), sizeof(uint8_t));
}
}
auto size = faces.size();
for (int i = 0; i < size; ++i) {
static const int three = 3;
out.write(reinterpret_cast<const char*>(&three), sizeof(uint8_t));
out.write(reinterpret_cast<const char*>(&(faces[i][0])), sizeof(int));
out.write(reinterpret_cast<const char*>(&(faces[i][1])), sizeof(int));
out.write(reinterpret_cast<const char*>(&(faces[i][2])), sizeof(int));
}
}
// TODO: get_texcolor, options API
std::array<uint8_t, 3> get_texcolor(const video_frame& texture, float u, float v)
{
const int w = texture.get_width(), h = texture.get_height();
int x = std::min(std::max(int(u*w + .5f), 0), w - 1);
int y = std::min(std::max(int(v*h + .5f), 0), h - 1);
int idx = x * texture.get_bytes_per_pixel() + y * texture.get_stride_in_bytes();
const auto texture_data = reinterpret_cast<const uint8_t*>(texture.get_data());
return { texture_data[idx], texture_data[idx + 1], texture_data[idx + 2] };
}
std::string fname;
pointcloud _pc;
};
class save_single_frameset : public filter {
public:
save_single_frameset(std::string filename = "RealSense Frameset ")
: filter([this](frame f, frame_source& s) { save(f, s); }), fname(filename)
{}
private:
void save(frame data, frame_source& source, bool do_signal=true)
{
software_device dev;
std::vector<std::tuple<software_sensor, stream_profile, int>> sensors;
if (auto fs = data.as<frameset>()) {
int uid = 0;
for (int i = 0; i < fs.size(); ++i) {
frame f = fs[i];
auto profile = f.get_profile();
auto s = dev.add_sensor(profile.stream_name() + "Sensor (" + std::to_string(uid) + ")");
stream_profile software_profile;
if (auto vf = f.as<video_frame>()) {
auto vp = profile.as<video_stream_profile>();
rs2_video_stream stream{ vp.stream_type(), vp.stream_index(), uid++, vp.width(), vp.height(), vp.fps(), vf.get_bytes_per_pixel(), vp.format(), vp.get_intrinsics() };
software_profile = s.add_video_stream(stream);
} else if (f.is<motion_frame>()) {
auto mp = profile.as<motion_stream_profile>();
rs2_motion_stream stream{ mp.stream_type(), mp.stream_index(), uid++, mp.fps(), mp.format(), mp.get_motion_intrinsics() };
software_profile = s.add_motion_stream(stream);
} else if (f.is<pose_frame>()) {
rs2_pose_stream stream{ profile.stream_type(), profile.stream_index(), uid++, profile.fps(), profile.format() };
software_profile = s.add_pose_stream(stream);
} else {
// TODO: How to handle other frame types? (e.g. points)
assert(false);
}
sensors.emplace_back(s, software_profile, i);
}
// Recorder needs sensors to already exist when its created
recorder rec(fname + std::to_string(data.get_frame_number()) + ".bag", dev);
for (auto group : sensors) {
auto s = std::get<software_sensor>(group);
auto profile = std::get<stream_profile>(group);
s.open(profile);
s.start([](frame) {});
frame f = fs[std::get<int>(group)];
if (auto vf = f.as<video_frame>()) {
s.on_video_frame({ const_cast<void*>(vf.get_data()), [](void*) {}, vf.get_stride_in_bytes(), vf.get_bytes_per_pixel(),
vf.get_timestamp(), vf.get_frame_timestamp_domain(), static_cast<int>(vf.get_frame_number()), profile });
} else if (f.is<motion_frame>()) {
s.on_motion_frame({ const_cast<void*>(f.get_data()), [](void*) {}, f.get_timestamp(),
f.get_frame_timestamp_domain(), static_cast<int>(f.get_frame_number()), profile });
} else if (f.is<pose_frame>()) {
s.on_pose_frame({ const_cast<void*>(f.get_data()), [](void*) {}, f.get_timestamp(),
f.get_frame_timestamp_domain(), static_cast<int>(f.get_frame_number()), profile });
}
}
} else {
// single frame
auto set = source.allocate_composite_frame({ data });
save(set, source, false);
}
if (do_signal)
source.frame_ready(data);
}
std::string fname;
};
}
#endif<commit_msg>Android fix<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2017 Intel Corporation. All Rights Reserved.
#ifndef LIBREALSENSE_RS2_EXPORT_HPP
#define LIBREALSENSE_RS2_EXPORT_HPP
#include <map>
#include <fstream>
#include <cmath>
#include <sstream>
#include <cassert>
#include "rs_processing.hpp"
#include "rs_internal.hpp"
namespace rs2
{
class save_to_ply : public filter
{
public:
save_to_ply(std::string filename = "RealSense Pointcloud ", pointcloud pc = pointcloud())
: filter([this](frame f, frame_source& s) { func(f, s); }),
_pc(std::move(pc)), fname(filename)
{
register_simple_option(OPTION_IGNORE_COLOR, option_range{ 0, 1, 0, 1 });
}
DECLARE_PB_OPTION(OPTION_IGNORE_COLOR, 1);
private:
void func(frame data, frame_source& source)
{
frame depth, color;
if (auto fs = data.as<frameset>()) {
for (auto f : fs) {
if (f.is<points>()) depth = f;
else if (!depth && f.is<depth_frame>()) depth = f;
else if (!color && f.is<video_frame>()) color = f;
}
} else if (data.is<depth_frame>() || data.is<points>()) {
depth = data;
}
if (!depth) throw std::runtime_error("Need depth data to save PLY");
if (!depth.is<points>()) {
if (color) _pc.map_to(color);
depth = _pc.calculate(depth);
}
export_to_ply(depth, color);
source.frame_ready(data); // passthrough filter because processing_block::process doesn't support sinks
}
void export_to_ply(points p, video_frame color) {
const bool use_texcoords = color && get_option(OPTION_IGNORE_COLOR);
const auto verts = p.get_vertices();
const auto texcoords = p.get_texture_coordinates();
std::vector<rs2::vertex> new_verts;
std::vector<std::array<uint8_t, 3>> new_tex;
std::map<int, int> idx_map;
new_verts.reserve(p.size());
if (use_texcoords) new_tex.reserve(p.size());
static const auto min_distance = 1e-6;
for (size_t i = 0; i < p.size(); ++i) {
if (fabs(verts[i].x) >= min_distance || fabs(verts[i].y) >= min_distance ||
fabs(verts[i].z) >= min_distance)
{
idx_map[i] = new_verts.size();
new_verts.push_back(verts[i]);
if (use_texcoords)
{
auto rgb = get_texcolor(color, texcoords[i].u, texcoords[i].v);
new_tex.push_back(rgb);
}
}
}
auto profile = p.get_profile().as<video_stream_profile>();
auto width = profile.width(), height = profile.height();
static const auto threshold = 0.05f;
std::vector<std::array<int, 3>> faces;
for (int x = 0; x < width - 1; ++x) {
for (int y = 0; y < height - 1; ++y) {
auto a = y * width + x, b = y * width + x + 1, c = (y + 1)*width + x, d = (y + 1)*width + x + 1;
if (verts[a].z && verts[b].z && verts[c].z && verts[d].z
&& fabs(verts[a].z - verts[b].z) < threshold && fabs(verts[a].z - verts[c].z) < threshold
&& fabs(verts[b].z - verts[d].z) < threshold && fabs(verts[c].z - verts[d].z) < threshold)
{
if (idx_map.count(a) == 0 || idx_map.count(b) == 0 || idx_map.count(c) == 0 ||
idx_map.count(d) == 0)
continue;
faces.push_back({ idx_map[a], idx_map[b], idx_map[d] });
faces.push_back({ idx_map[d], idx_map[c], idx_map[a] });
}
}
}
std::stringstream name;
name << fname << p.get_frame_number() << ".ply";
std::ofstream out(name.str());
out << "ply\n";
out << "format binary_little_endian 1.0\n";
out << "comment pointcloud saved from Realsense Viewer\n";
out << "element vertex " << new_verts.size() << "\n";
out << "property float" << sizeof(float) * 8 << " x\n";
out << "property float" << sizeof(float) * 8 << " y\n";
out << "property float" << sizeof(float) * 8 << " z\n";
if (use_texcoords)
{
out << "property uchar red\n";
out << "property uchar green\n";
out << "property uchar blue\n";
}
out << "element face " << faces.size() << "\n";
out << "property list uchar int vertex_indices\n";
out << "end_header\n";
out.close();
out.open(name.str(), std::ios_base::app | std::ios_base::binary);
for (int i = 0; i < new_verts.size(); ++i)
{
// we assume little endian architecture on your device
out.write(reinterpret_cast<const char*>(&(new_verts[i].x)), sizeof(float));
out.write(reinterpret_cast<const char*>(&(new_verts[i].y)), sizeof(float));
out.write(reinterpret_cast<const char*>(&(new_verts[i].z)), sizeof(float));
if (use_texcoords)
{
out.write(reinterpret_cast<const char*>(&(new_tex[i][0])), sizeof(uint8_t));
out.write(reinterpret_cast<const char*>(&(new_tex[i][1])), sizeof(uint8_t));
out.write(reinterpret_cast<const char*>(&(new_tex[i][2])), sizeof(uint8_t));
}
}
auto size = faces.size();
for (int i = 0; i < size; ++i) {
static const int three = 3;
out.write(reinterpret_cast<const char*>(&three), sizeof(uint8_t));
out.write(reinterpret_cast<const char*>(&(faces[i][0])), sizeof(int));
out.write(reinterpret_cast<const char*>(&(faces[i][1])), sizeof(int));
out.write(reinterpret_cast<const char*>(&(faces[i][2])), sizeof(int));
}
}
// TODO: get_texcolor, options API
std::array<uint8_t, 3> get_texcolor(const video_frame& texture, float u, float v)
{
const int w = texture.get_width(), h = texture.get_height();
int x = std::min(std::max(int(u*w + .5f), 0), w - 1);
int y = std::min(std::max(int(v*h + .5f), 0), h - 1);
int idx = x * texture.get_bytes_per_pixel() + y * texture.get_stride_in_bytes();
const auto texture_data = reinterpret_cast<const uint8_t*>(texture.get_data());
return { texture_data[idx], texture_data[idx + 1], texture_data[idx + 2] };
}
std::string fname;
pointcloud _pc;
};
class save_single_frameset : public filter {
public:
save_single_frameset(std::string filename = "RealSense Frameset ")
: filter([this](frame f, frame_source& s) { save(f, s); }), fname(filename)
{}
private:
void save(frame data, frame_source& source, bool do_signal=true)
{
software_device dev;
std::vector<std::tuple<software_sensor, stream_profile, int>> sensors;
if (auto fs = data.as<frameset>()) {
int uid = 0;
for (int i = 0; i < fs.size(); ++i) {
frame f = fs[i];
auto profile = f.get_profile();
std::stringstream sname;
sname << "Sensor (" << uid << ")";
auto s = dev.add_sensor(sname.str());
stream_profile software_profile;
if (auto vf = f.as<video_frame>()) {
auto vp = profile.as<video_stream_profile>();
rs2_video_stream stream{ vp.stream_type(), vp.stream_index(), uid++, vp.width(), vp.height(), vp.fps(), vf.get_bytes_per_pixel(), vp.format(), vp.get_intrinsics() };
software_profile = s.add_video_stream(stream);
} else if (f.is<motion_frame>()) {
auto mp = profile.as<motion_stream_profile>();
rs2_motion_stream stream{ mp.stream_type(), mp.stream_index(), uid++, mp.fps(), mp.format(), mp.get_motion_intrinsics() };
software_profile = s.add_motion_stream(stream);
} else if (f.is<pose_frame>()) {
rs2_pose_stream stream{ profile.stream_type(), profile.stream_index(), uid++, profile.fps(), profile.format() };
software_profile = s.add_pose_stream(stream);
} else {
// TODO: How to handle other frame types? (e.g. points)
assert(false);
}
sensors.emplace_back(s, software_profile, i);
}
// Recorder needs sensors to already exist when its created
std::stringstream name;
name << fname << data.get_frame_number() << ".bag";
recorder rec(name.str(), dev);
for (auto group : sensors) {
auto s = std::get<software_sensor>(group);
auto profile = std::get<stream_profile>(group);
s.open(profile);
s.start([](frame) {});
frame f = fs[std::get<int>(group)];
if (auto vf = f.as<video_frame>()) {
s.on_video_frame({ const_cast<void*>(vf.get_data()), [](void*) {}, vf.get_stride_in_bytes(), vf.get_bytes_per_pixel(),
vf.get_timestamp(), vf.get_frame_timestamp_domain(), static_cast<int>(vf.get_frame_number()), profile });
} else if (f.is<motion_frame>()) {
s.on_motion_frame({ const_cast<void*>(f.get_data()), [](void*) {}, f.get_timestamp(),
f.get_frame_timestamp_domain(), static_cast<int>(f.get_frame_number()), profile });
} else if (f.is<pose_frame>()) {
s.on_pose_frame({ const_cast<void*>(f.get_data()), [](void*) {}, f.get_timestamp(),
f.get_frame_timestamp_domain(), static_cast<int>(f.get_frame_number()), profile });
}
}
} else {
// single frame
auto set = source.allocate_composite_frame({ data });
save(set, source, false);
}
if (do_signal)
source.frame_ready(data);
}
std::string fname;
};
}
#endif<|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.
*/
#ifndef TORRENT_BROADCAST_SOCKET_HPP_INCLUDED
#define TORRENT_BROADCAST_SOCKET_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <list>
namespace libtorrent
{
bool is_local(address const& a);
bool is_loopback(address const& addr);
bool is_multicast(address const& addr);
bool is_any(address const& addr);
address guess_local_address(asio::io_service&);
typedef boost::function<void(udp::endpoint const& from
, char* buffer, int size)> receive_handler_t;
class broadcast_socket
{
public:
broadcast_socket(asio::io_service& ios, udp::endpoint const& multicast_endpoint
, receive_handler_t const& handler, bool loopback = true);
~broadcast_socket() { close(); }
void send(char const* buffer, int size, asio::error_code& ec);
void close();
private:
struct socket_entry
{
socket_entry(boost::shared_ptr<datagram_socket> const& s): socket(s) {}
boost::shared_ptr<datagram_socket> socket;
char buffer[1024];
udp::endpoint remote;
void close() { socket->close(); }
};
void on_receive(socket_entry* s, asio::error_code const& ec
, std::size_t bytes_transferred);
void open_unicast_socket(io_service& ios, address const& addr);
// these sockets are used to
// join the multicast group (on each interface)
// and receive multicast messages
std::list<socket_entry> m_sockets;
// these sockets are not bound to any
// specific port and are used to
// send messages to the multicast group
// and receive unicast responses
std::list<socket_entry> m_unicast_sockets;
udp::endpoint m_multicast_endpoint;
receive_handler_t m_on_receive;
};
}
#endif
<commit_msg>support in broadcast_socket to be built without exception support<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.
*/
#ifndef TORRENT_BROADCAST_SOCKET_HPP_INCLUDED
#define TORRENT_BROADCAST_SOCKET_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <list>
namespace libtorrent
{
bool is_local(address const& a);
bool is_loopback(address const& addr);
bool is_multicast(address const& addr);
bool is_any(address const& addr);
address guess_local_address(asio::io_service&);
typedef boost::function<void(udp::endpoint const& from
, char* buffer, int size)> receive_handler_t;
class broadcast_socket
{
public:
broadcast_socket(asio::io_service& ios, udp::endpoint const& multicast_endpoint
, receive_handler_t const& handler, bool loopback = true);
~broadcast_socket() { close(); }
void send(char const* buffer, int size, asio::error_code& ec);
void close();
private:
struct socket_entry
{
socket_entry(boost::shared_ptr<datagram_socket> const& s): socket(s) {}
boost::shared_ptr<datagram_socket> socket;
char buffer[1024];
udp::endpoint remote;
void close()
{
asio::error_code ec;
socket->close(ec);
}
};
void on_receive(socket_entry* s, asio::error_code const& ec
, std::size_t bytes_transferred);
void open_unicast_socket(io_service& ios, address const& addr);
// these sockets are used to
// join the multicast group (on each interface)
// and receive multicast messages
std::list<socket_entry> m_sockets;
// these sockets are not bound to any
// specific port and are used to
// send messages to the multicast group
// and receive unicast responses
std::list<socket_entry> m_unicast_sockets;
udp::endpoint m_multicast_endpoint;
receive_handler_t m_on_receive;
};
}
#endif
<|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.
*/
#ifndef TORRENT_BROADCAST_SOCKET_HPP_INCLUDED
#define TORRENT_BROADCAST_SOCKET_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <list>
namespace libtorrent
{
bool is_local(address const& a);
bool is_loopback(address const& addr);
bool is_multicast(address const& addr);
bool is_any(address const& addr);
address guess_local_address(asio::io_service&);
typedef boost::function<void(udp::endpoint const& from
, char* buffer, int size)> receive_handler_t;
class broadcast_socket
{
public:
broadcast_socket(asio::io_service& ios, udp::endpoint const& multicast_endpoint
, receive_handler_t const& handler, bool loopback = true);
~broadcast_socket() { close(); }
void send(char const* buffer, int size, asio::error_code& ec);
void close();
private:
struct socket_entry
{
socket_entry(boost::shared_ptr<datagram_socket> const& s): socket(s) {}
boost::shared_ptr<datagram_socket> socket;
char buffer[1024];
udp::endpoint remote;
void close() { socket->close(); }
};
void on_receive(socket_entry* s, asio::error_code const& ec
, std::size_t bytes_transferred);
void open_unicast_socket(io_service& ios, address const& addr);
// these sockets are used to
// join the multicast group (on each interface)
// and receive multicast messages
std::list<socket_entry> m_sockets;
// these sockets are not bound to any
// specific port and are used to
// send messages to the multicast group
// and receive unicast responses
std::list<socket_entry> m_unicast_sockets;
udp::endpoint m_multicast_endpoint;
receive_handler_t m_on_receive;
};
}
#endif
<commit_msg>support in broadcast_socket to be built without exception support<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.
*/
#ifndef TORRENT_BROADCAST_SOCKET_HPP_INCLUDED
#define TORRENT_BROADCAST_SOCKET_HPP_INCLUDED
#include "libtorrent/socket.hpp"
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>
#include <list>
namespace libtorrent
{
bool is_local(address const& a);
bool is_loopback(address const& addr);
bool is_multicast(address const& addr);
bool is_any(address const& addr);
address guess_local_address(asio::io_service&);
typedef boost::function<void(udp::endpoint const& from
, char* buffer, int size)> receive_handler_t;
class broadcast_socket
{
public:
broadcast_socket(asio::io_service& ios, udp::endpoint const& multicast_endpoint
, receive_handler_t const& handler, bool loopback = true);
~broadcast_socket() { close(); }
void send(char const* buffer, int size, asio::error_code& ec);
void close();
private:
struct socket_entry
{
socket_entry(boost::shared_ptr<datagram_socket> const& s): socket(s) {}
boost::shared_ptr<datagram_socket> socket;
char buffer[1024];
udp::endpoint remote;
void close()
{
asio::error_code ec;
socket->close(ec);
}
};
void on_receive(socket_entry* s, asio::error_code const& ec
, std::size_t bytes_transferred);
void open_unicast_socket(io_service& ios, address const& addr);
// these sockets are used to
// join the multicast group (on each interface)
// and receive multicast messages
std::list<socket_entry> m_sockets;
// these sockets are not bound to any
// specific port and are used to
// send messages to the multicast group
// and receive unicast responses
std::list<socket_entry> m_unicast_sockets;
udp::endpoint m_multicast_endpoint;
receive_handler_t m_on_receive;
};
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_HARFBUZZ_SHAPER_HPP
#define MAPNIK_HARFBUZZ_SHAPER_HPP
// mapnik
#include <mapnik/text/text_properties.hpp>
#include <mapnik/text/text_line.hpp>
#include <mapnik/text/face.hpp>
#include <mapnik/text/font_feature_settings.hpp>
#include <mapnik/text/itemizer.hpp>
#include <mapnik/safe_cast.hpp>
#include <mapnik/font_engine_freetype.hpp>
// stl
#include <list>
#include <type_traits>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <harfbuzz/hb.h>
#include <harfbuzz/hb-ft.h>
#include <unicode/uscript.h>
#pragma GCC diagnostic pop
namespace mapnik { namespace detail {
static inline hb_script_t _icu_script_to_script(UScriptCode script)
{
if (script == USCRIPT_INVALID_CODE) return HB_SCRIPT_INVALID;
return hb_script_from_string(uscript_getShortName(script), -1);
}
static inline const uint16_t * uchar_to_utf16(const UChar* src)
{
static_assert(sizeof(UChar) == sizeof(uint16_t),"UChar is eq size to uint16_t");
#if defined(_MSC_VER)
return reinterpret_cast<const uint16_t *>(src);
#else
return src;
#endif
}
static hb_language_t script_to_language(hb_script_t script)
{
switch (script)
{
// Unicode 1.1
case HB_SCRIPT_ARABIC: return hb_language_from_string("ar", -1); break;
case HB_SCRIPT_ARMENIAN: return hb_language_from_string("hy", -1); break;
case HB_SCRIPT_BENGALI: return hb_language_from_string("bn", -1); break;
case HB_SCRIPT_CANADIAN_ABORIGINAL: return hb_language_from_string("iu", -1); break;
case HB_SCRIPT_CHEROKEE: return hb_language_from_string("chr", -1); break;
case HB_SCRIPT_COPTIC: return hb_language_from_string("cop", -1); break;
case HB_SCRIPT_CYRILLIC: return hb_language_from_string("ru", -1); break;
case HB_SCRIPT_DEVANAGARI: return hb_language_from_string("hi", -1); break;
case HB_SCRIPT_GEORGIAN: return hb_language_from_string("ka", -1); break;
case HB_SCRIPT_GREEK: return hb_language_from_string("el", -1); break;
case HB_SCRIPT_GUJARATI: return hb_language_from_string("gu", -1); break;
case HB_SCRIPT_GURMUKHI: return hb_language_from_string("pa", -1); break;
case HB_SCRIPT_HANGUL: return hb_language_from_string("ko", -1); break;
case HB_SCRIPT_HAN: return hb_language_from_string("zh-Hans", -1); break;
case HB_SCRIPT_HEBREW: return hb_language_from_string("he", -1); break;
case HB_SCRIPT_HIRAGANA: return hb_language_from_string("ja", -1); break;
case HB_SCRIPT_KANNADA: return hb_language_from_string("kn", -1); break;
case HB_SCRIPT_KATAKANA: return hb_language_from_string("ja", -1); break;
case HB_SCRIPT_LAO: return hb_language_from_string("lo", -1); break;
case HB_SCRIPT_LATIN: return hb_language_from_string("en", -1); break;
case HB_SCRIPT_MALAYALAM: return hb_language_from_string("ml", -1); break;
case HB_SCRIPT_MONGOLIAN: return hb_language_from_string("mn", -1); break;
case HB_SCRIPT_ORIYA: return hb_language_from_string("or", -1); break;
case HB_SCRIPT_SYRIAC: return hb_language_from_string("syr", -1); break;
case HB_SCRIPT_TAMIL: return hb_language_from_string("ta", -1); break;
case HB_SCRIPT_TELUGU: return hb_language_from_string("te", -1); break;
case HB_SCRIPT_THAI: return hb_language_from_string("th", -1); break;
// Unicode 2.0
case HB_SCRIPT_TIBETAN: return hb_language_from_string("bo", -1); break;
// Unicode 3.0
case HB_SCRIPT_ETHIOPIC: return hb_language_from_string("am", -1); break;
case HB_SCRIPT_KHMER: return hb_language_from_string("km", -1); break;
case HB_SCRIPT_MYANMAR: return hb_language_from_string("my", -1); break;
case HB_SCRIPT_SINHALA: return hb_language_from_string("si", -1); break;
case HB_SCRIPT_THAANA: return hb_language_from_string("dv", -1); break;
// Unicode 3.2
case HB_SCRIPT_BUHID: return hb_language_from_string("bku", -1); break;
case HB_SCRIPT_HANUNOO: return hb_language_from_string("hnn", -1); break;
case HB_SCRIPT_TAGALOG: return hb_language_from_string("tl", -1); break;
case HB_SCRIPT_TAGBANWA: return hb_language_from_string("tbw", -1); break;
// Unicode 4.0
case HB_SCRIPT_UGARITIC: return hb_language_from_string("uga", -1); break;
// Unicode 4.1
case HB_SCRIPT_BUGINESE: return hb_language_from_string("bug", -1); break;
case HB_SCRIPT_OLD_PERSIAN: return hb_language_from_string("peo", -1); break;
case HB_SCRIPT_SYLOTI_NAGRI: return hb_language_from_string("syl", -1); break;
// Unicode 5.0
case HB_SCRIPT_NKO: return hb_language_from_string("nko", -1); break;
// no representative language exists
default: return HB_LANGUAGE_INVALID; break;
}
}
} // ns detail
struct harfbuzz_shaper
{
static void shape_text(text_line & line,
text_itemizer & itemizer,
std::map<unsigned,double> & width_map,
face_manager_freetype & font_manager,
double scale_factor)
{
unsigned start = line.first_char();
unsigned end = line.last_char();
std::size_t length = end - start;
if (!length) return;
std::list<text_item> const& list = itemizer.itemize(start, end);
line.reserve(length);
auto hb_buffer_deleter = [](hb_buffer_t * buffer) { hb_buffer_destroy(buffer);};
const std::unique_ptr<hb_buffer_t, decltype(hb_buffer_deleter)> buffer(hb_buffer_create(), hb_buffer_deleter);
hb_buffer_pre_allocate(buffer.get(), safe_cast<int>(length));
mapnik::value_unicode_string const& text = itemizer.text();
for (auto const& text_item : list)
{
face_set_ptr face_set = font_manager.get_face_set(text_item.format_->face_name, text_item.format_->fontset);
double size = text_item.format_->text_size * scale_factor;
face_set->set_unscaled_character_sizes();
std::size_t num_faces = face_set->size();
font_feature_settings const& ff_settings = text_item.format_->ff_settings;
int ff_count = safe_cast<int>(ff_settings.count());
// rendering information for a single glyph
struct glyph_face_info
{
face_ptr face;
hb_glyph_info_t glyph;
hb_glyph_position_t position;
};
// this table is filled with information for rendering each glyph, so that
// several font faces can be used in a single text_item
std::size_t pos = 0;
std::vector<std::vector<glyph_face_info>> glyphinfos;
glyphinfos.resize(text.length());
for (auto const& face : *face_set)
{
++pos;
hb_buffer_clear_contents(buffer.get());
hb_buffer_add_utf16(buffer.get(), detail::uchar_to_utf16(text.getBuffer()), text.length(), text_item.start, static_cast<int>(text_item.end - text_item.start));
hb_buffer_set_direction(buffer.get(), (text_item.dir == UBIDI_RTL) ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
hb_font_t *font(hb_ft_font_create(face->get_face(), nullptr));
auto script = detail::_icu_script_to_script(text_item.script);
auto language = detail::script_to_language(script);
if (language != HB_LANGUAGE_INVALID)
{
hb_buffer_set_language(buffer.get(), language); // set most common language for the run based script
}
hb_buffer_set_script(buffer.get(), script);
// https://github.com/mapnik/test-data-visual/pull/25
#if HB_VERSION_MAJOR > 0
#if HB_VERSION_ATLEAST(1, 0 , 5)
hb_ft_font_set_load_flags(font,FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING);
#endif
#endif
hb_shape(font, buffer.get(), ff_settings.get_features(), ff_count);
hb_font_destroy(font);
unsigned num_glyphs = hb_buffer_get_length(buffer.get());
hb_glyph_info_t *glyphs = hb_buffer_get_glyph_infos(buffer.get(), &num_glyphs);
hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer.get(), &num_glyphs);
unsigned cluster = 0;
bool in_cluster = false;
std::vector<unsigned> clusters;
for (unsigned i = 0; i < num_glyphs; ++i)
{
if (i == 0)
{
cluster = glyphs[0].cluster;
clusters.push_back(cluster);
}
if (cluster != glyphs[i].cluster)
{
cluster = glyphs[i].cluster;
clusters.push_back(cluster);
in_cluster = false;
}
else if (i != 0)
{
in_cluster = true;
}
if (glyphinfos.size() <= cluster)
{
glyphinfos.resize(cluster + 1);
}
auto & c = glyphinfos[cluster];
if (c.empty())
{
c.push_back({face, glyphs[i], positions[i]});
}
else if (c.front().glyph.codepoint == 0)
{
c.front() = { face, glyphs[i], positions[i] };
}
else if (in_cluster)
{
c.push_back({ face, glyphs[i], positions[i] });
}
}
bool all_set = true;
for (auto c_id : clusters)
{
auto const& c = glyphinfos[c_id];
if (c.empty() || c.front().glyph.codepoint == 0)
{
all_set = false;
break;
}
}
if (!all_set && (pos < num_faces))
{
//Try next font in fontset
continue;
}
double max_glyph_height = 0;
for (auto const& c_id : clusters)
{
auto const& c = glyphinfos[c_id];
for (auto const& info : c)
{
auto const& gpos = info.position;
auto const& glyph = info.glyph;
unsigned char_index = glyph.cluster;
glyph_info g(glyph.codepoint,char_index,text_item.format_);
if (info.glyph.codepoint != 0) g.face = info.face;
else g.face = face;
if (g.face->glyph_dimensions(g))
{
g.scale_multiplier = g.face->get_face()->units_per_EM > 0 ?
(size / g.face->get_face()->units_per_EM) : (size / 2048.0) ;
//Overwrite default advance with better value provided by HarfBuzz
g.unscaled_advance = gpos.x_advance;
g.offset.set(gpos.x_offset * g.scale_multiplier, gpos.y_offset * g.scale_multiplier);
double tmp_height = g.height();
if (g.face->is_color())
{
tmp_height = size;
}
if (tmp_height > max_glyph_height) max_glyph_height = tmp_height;
width_map[char_index] += g.advance();
line.add_glyph(std::move(g), scale_factor);
}
}
}
line.update_max_char_height(max_glyph_height);
break; //When we reach this point the current font had all glyphs.
}
}
}
};
} // namespace mapnik
#endif // MAPNIK_HARFBUZZ_SHAPER_HPP
<commit_msg>add debug log<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2016 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_HARFBUZZ_SHAPER_HPP
#define MAPNIK_HARFBUZZ_SHAPER_HPP
// mapnik
#include <mapnik/text/text_properties.hpp>
#include <mapnik/text/text_line.hpp>
#include <mapnik/text/face.hpp>
#include <mapnik/text/font_feature_settings.hpp>
#include <mapnik/text/itemizer.hpp>
#include <mapnik/safe_cast.hpp>
#include <mapnik/font_engine_freetype.hpp>
// stl
#include <list>
#include <type_traits>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <harfbuzz/hb.h>
#include <harfbuzz/hb-ft.h>
#include <unicode/uscript.h>
#pragma GCC diagnostic pop
namespace mapnik { namespace detail {
static inline hb_script_t _icu_script_to_script(UScriptCode script)
{
if (script == USCRIPT_INVALID_CODE) return HB_SCRIPT_INVALID;
return hb_script_from_string(uscript_getShortName(script), -1);
}
static inline const uint16_t * uchar_to_utf16(const UChar* src)
{
static_assert(sizeof(UChar) == sizeof(uint16_t),"UChar is eq size to uint16_t");
#if defined(_MSC_VER)
return reinterpret_cast<const uint16_t *>(src);
#else
return src;
#endif
}
static hb_language_t script_to_language(hb_script_t script)
{
switch (script)
{
// Unicode 1.1
case HB_SCRIPT_ARABIC: return hb_language_from_string("ar", -1); break;
case HB_SCRIPT_ARMENIAN: return hb_language_from_string("hy", -1); break;
case HB_SCRIPT_BENGALI: return hb_language_from_string("bn", -1); break;
case HB_SCRIPT_CANADIAN_ABORIGINAL: return hb_language_from_string("iu", -1); break;
case HB_SCRIPT_CHEROKEE: return hb_language_from_string("chr", -1); break;
case HB_SCRIPT_COPTIC: return hb_language_from_string("cop", -1); break;
case HB_SCRIPT_CYRILLIC: return hb_language_from_string("ru", -1); break;
case HB_SCRIPT_DEVANAGARI: return hb_language_from_string("hi", -1); break;
case HB_SCRIPT_GEORGIAN: return hb_language_from_string("ka", -1); break;
case HB_SCRIPT_GREEK: return hb_language_from_string("el", -1); break;
case HB_SCRIPT_GUJARATI: return hb_language_from_string("gu", -1); break;
case HB_SCRIPT_GURMUKHI: return hb_language_from_string("pa", -1); break;
case HB_SCRIPT_HANGUL: return hb_language_from_string("ko", -1); break;
case HB_SCRIPT_HAN: return hb_language_from_string("zh-hans", -1); break;
case HB_SCRIPT_HEBREW: return hb_language_from_string("he", -1); break;
case HB_SCRIPT_HIRAGANA: return hb_language_from_string("ja", -1); break;
case HB_SCRIPT_KANNADA: return hb_language_from_string("kn", -1); break;
case HB_SCRIPT_KATAKANA: return hb_language_from_string("ja", -1); break;
case HB_SCRIPT_LAO: return hb_language_from_string("lo", -1); break;
case HB_SCRIPT_LATIN: return hb_language_from_string("en", -1); break;
case HB_SCRIPT_MALAYALAM: return hb_language_from_string("ml", -1); break;
case HB_SCRIPT_MONGOLIAN: return hb_language_from_string("mn", -1); break;
case HB_SCRIPT_ORIYA: return hb_language_from_string("or", -1); break;
case HB_SCRIPT_SYRIAC: return hb_language_from_string("syr", -1); break;
case HB_SCRIPT_TAMIL: return hb_language_from_string("ta", -1); break;
case HB_SCRIPT_TELUGU: return hb_language_from_string("te", -1); break;
case HB_SCRIPT_THAI: return hb_language_from_string("th", -1); break;
// Unicode 2.0
case HB_SCRIPT_TIBETAN: return hb_language_from_string("bo", -1); break;
// Unicode 3.0
case HB_SCRIPT_ETHIOPIC: return hb_language_from_string("am", -1); break;
case HB_SCRIPT_KHMER: return hb_language_from_string("km", -1); break;
case HB_SCRIPT_MYANMAR: return hb_language_from_string("my", -1); break;
case HB_SCRIPT_SINHALA: return hb_language_from_string("si", -1); break;
case HB_SCRIPT_THAANA: return hb_language_from_string("dv", -1); break;
// Unicode 3.2
case HB_SCRIPT_BUHID: return hb_language_from_string("bku", -1); break;
case HB_SCRIPT_HANUNOO: return hb_language_from_string("hnn", -1); break;
case HB_SCRIPT_TAGALOG: return hb_language_from_string("tl", -1); break;
case HB_SCRIPT_TAGBANWA: return hb_language_from_string("tbw", -1); break;
// Unicode 4.0
case HB_SCRIPT_UGARITIC: return hb_language_from_string("uga", -1); break;
// Unicode 4.1
case HB_SCRIPT_BUGINESE: return hb_language_from_string("bug", -1); break;
case HB_SCRIPT_OLD_PERSIAN: return hb_language_from_string("peo", -1); break;
case HB_SCRIPT_SYLOTI_NAGRI: return hb_language_from_string("syl", -1); break;
// Unicode 5.0
case HB_SCRIPT_NKO: return hb_language_from_string("nko", -1); break;
// no representative language exists
default: return HB_LANGUAGE_INVALID; break;
}
}
} // ns detail
struct harfbuzz_shaper
{
static void shape_text(text_line & line,
text_itemizer & itemizer,
std::map<unsigned,double> & width_map,
face_manager_freetype & font_manager,
double scale_factor)
{
unsigned start = line.first_char();
unsigned end = line.last_char();
std::size_t length = end - start;
if (!length) return;
std::list<text_item> const& list = itemizer.itemize(start, end);
line.reserve(length);
auto hb_buffer_deleter = [](hb_buffer_t * buffer) { hb_buffer_destroy(buffer);};
const std::unique_ptr<hb_buffer_t, decltype(hb_buffer_deleter)> buffer(hb_buffer_create(), hb_buffer_deleter);
hb_buffer_pre_allocate(buffer.get(), safe_cast<int>(length));
mapnik::value_unicode_string const& text = itemizer.text();
for (auto const& text_item : list)
{
face_set_ptr face_set = font_manager.get_face_set(text_item.format_->face_name, text_item.format_->fontset);
double size = text_item.format_->text_size * scale_factor;
face_set->set_unscaled_character_sizes();
std::size_t num_faces = face_set->size();
font_feature_settings const& ff_settings = text_item.format_->ff_settings;
int ff_count = safe_cast<int>(ff_settings.count());
// rendering information for a single glyph
struct glyph_face_info
{
face_ptr face;
hb_glyph_info_t glyph;
hb_glyph_position_t position;
};
// this table is filled with information for rendering each glyph, so that
// several font faces can be used in a single text_item
std::size_t pos = 0;
std::vector<std::vector<glyph_face_info>> glyphinfos;
glyphinfos.resize(text.length());
for (auto const& face : *face_set)
{
++pos;
hb_buffer_clear_contents(buffer.get());
hb_buffer_add_utf16(buffer.get(), detail::uchar_to_utf16(text.getBuffer()), text.length(), text_item.start, static_cast<int>(text_item.end - text_item.start));
hb_buffer_set_direction(buffer.get(), (text_item.dir == UBIDI_RTL) ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
hb_font_t *font(hb_ft_font_create(face->get_face(), nullptr));
auto script = detail::_icu_script_to_script(text_item.script);
auto language = detail::script_to_language(script);
MAPNIK_LOG_DEBUG(harfbuzz_shaper) << "RUN:[" << text_item.start << "," << text_item.end << "]"
<< " LANGUAGE:" << hb_language_to_string(language)
<< " SCRIPT:" << script << "(" << text_item.script << ") " << uscript_getShortName(text_item.script)
<< " FONT:" << face->family_name();
if (language != HB_LANGUAGE_INVALID)
{
hb_buffer_set_language(buffer.get(), language); // set most common language for the run based script
}
hb_buffer_set_script(buffer.get(), script);
// https://github.com/mapnik/test-data-visual/pull/25
#if HB_VERSION_MAJOR > 0
#if HB_VERSION_ATLEAST(1, 0 , 5)
hb_ft_font_set_load_flags(font,FT_LOAD_DEFAULT | FT_LOAD_NO_HINTING);
#endif
#endif
hb_shape(font, buffer.get(), ff_settings.get_features(), ff_count);
hb_font_destroy(font);
unsigned num_glyphs = hb_buffer_get_length(buffer.get());
hb_glyph_info_t *glyphs = hb_buffer_get_glyph_infos(buffer.get(), &num_glyphs);
hb_glyph_position_t *positions = hb_buffer_get_glyph_positions(buffer.get(), &num_glyphs);
unsigned cluster = 0;
bool in_cluster = false;
std::vector<unsigned> clusters;
for (unsigned i = 0; i < num_glyphs; ++i)
{
if (i == 0)
{
cluster = glyphs[0].cluster;
clusters.push_back(cluster);
}
if (cluster != glyphs[i].cluster)
{
cluster = glyphs[i].cluster;
clusters.push_back(cluster);
in_cluster = false;
}
else if (i != 0)
{
in_cluster = true;
}
if (glyphinfos.size() <= cluster)
{
glyphinfos.resize(cluster + 1);
}
auto & c = glyphinfos[cluster];
if (c.empty())
{
c.push_back({face, glyphs[i], positions[i]});
}
else if (c.front().glyph.codepoint == 0)
{
c.front() = { face, glyphs[i], positions[i] };
}
else if (in_cluster)
{
c.push_back({ face, glyphs[i], positions[i] });
}
}
bool all_set = true;
for (auto c_id : clusters)
{
auto const& c = glyphinfos[c_id];
if (c.empty() || c.front().glyph.codepoint == 0)
{
all_set = false;
break;
}
}
if (!all_set && (pos < num_faces))
{
//Try next font in fontset
continue;
}
double max_glyph_height = 0;
for (auto const& c_id : clusters)
{
auto const& c = glyphinfos[c_id];
for (auto const& info : c)
{
auto const& gpos = info.position;
auto const& glyph = info.glyph;
unsigned char_index = glyph.cluster;
glyph_info g(glyph.codepoint,char_index,text_item.format_);
if (info.glyph.codepoint != 0) g.face = info.face;
else g.face = face;
if (g.face->glyph_dimensions(g))
{
g.scale_multiplier = g.face->get_face()->units_per_EM > 0 ?
(size / g.face->get_face()->units_per_EM) : (size / 2048.0) ;
//Overwrite default advance with better value provided by HarfBuzz
g.unscaled_advance = gpos.x_advance;
g.offset.set(gpos.x_offset * g.scale_multiplier, gpos.y_offset * g.scale_multiplier);
double tmp_height = g.height();
if (g.face->is_color())
{
tmp_height = size;
}
if (tmp_height > max_glyph_height) max_glyph_height = tmp_height;
width_map[char_index] += g.advance();
line.add_glyph(std::move(g), scale_factor);
}
}
}
line.update_max_char_height(max_glyph_height);
break; //When we reach this point the current font had all glyphs.
}
}
}
};
} // namespace mapnik
#endif // MAPNIK_HARFBUZZ_SHAPER_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <microscopes/common/type_helper.hpp>
#include <microscopes/common/random_fwd.hpp>
#include <microscopes/common/macros.hpp>
#include <microscopes/common/assert.hpp>
#include <vector>
#include <cstring>
#include <iostream>
namespace microscopes {
namespace common {
class row_accessor {
friend class row_mutator;
public:
row_accessor()
: data_(), mask_(), types_(),
cursor_(), mask_cursor_(), pos_() {}
row_accessor(const uint8_t *data,
const bool *mask,
const std::vector<runtime_type> *types)
: data_(data), mask_(mask), types_(types),
cursor_(data), mask_cursor_(mask), pos_()
{
MICROSCOPES_ASSERT(data);
MICROSCOPES_ASSERT(types);
}
inline size_t tell() const { return pos_; }
inline size_t nfeatures() const { return types_->size(); }
inline const runtime_type & curtype() const { return (*types_)[pos_]; }
inline unsigned curshape() const { return curtype().n(); }
inline bool
ismasked(size_t idx) const
{
MICROSCOPES_ASSERT(idx < curshape());
return !mask_ ? false : *(mask_cursor_ + idx);
}
template <typename T>
inline T
get(size_t idx) const
{
MICROSCOPES_ASSERT(pos_ < nfeatures());
MICROSCOPES_ASSERT(cursor_);
MICROSCOPES_ASSERT(idx < curshape());
const size_t s = runtime_type_traits::PrimitiveTypeSize(curtype().t());
return runtime_cast::cast<T>(cursor_ + idx * s, curtype().t());
}
inline void
bump()
{
MICROSCOPES_ASSERT(pos_ <= nfeatures());
cursor_ += runtime_type_traits::RuntimeTypeSize(curtype());
mask_cursor_ += curtype().n();
pos_++;
}
inline bool end() const { return pos_ == nfeatures(); }
inline void
reset()
{
cursor_ = data_;
mask_cursor_ = mask_;
pos_ = 0;
}
std::string debug_str() const;
protected:
inline const uint8_t * cursor() const { return cursor_; }
private:
const uint8_t *data_;
const bool *mask_;
const std::vector<runtime_type> *types_;
const uint8_t *cursor_;
const bool *mask_cursor_;
size_t pos_;
};
class row_mutator {
public:
row_mutator()
: data_(), types_(), cursor_(), pos_() {}
row_mutator(uint8_t *data,
const std::vector<runtime_type> *types)
: data_(data), types_(types),
cursor_(data), pos_()
{
MICROSCOPES_ASSERT(data);
MICROSCOPES_ASSERT(types);
}
inline size_t tell() const { return pos_; }
inline size_t nfeatures() const { return types_->size(); }
inline const runtime_type & curtype() const { return (*types_)[pos_]; }
inline unsigned curshape() const { return curtype().n(); }
template <typename T>
inline void
set(T t, size_t idx)
{
MICROSCOPES_ASSERT(pos_ < nfeatures());
MICROSCOPES_ASSERT(cursor_);
MICROSCOPES_ASSERT(idx < curshape());
const size_t s = runtime_type_traits::PrimitiveTypeSize(curtype().t());
runtime_cast::uncast<T>(cursor_ + idx * s, curtype().t(), t);
}
void
set(const row_accessor &acc)
{
MICROSCOPES_DCHECK(curshape() == acc.curshape(), "shapes do not match");
MICROSCOPES_ASSERT(cursor_);
MICROSCOPES_ASSERT(acc.cursor());
const size_t s0 = runtime_type_traits::PrimitiveTypeSize(curtype().t());
const size_t s1 = runtime_type_traits::PrimitiveTypeSize(acc.curtype().t());
for (unsigned i = 0; i < curshape(); i++)
runtime_cast::copy(
cursor_ + i * s0, curtype().t(),
acc.cursor() + i * s1, acc.curtype().t());
}
inline void
bump()
{
MICROSCOPES_ASSERT(pos_ <= nfeatures());
cursor_ += runtime_type_traits::RuntimeTypeSize(curtype());
pos_++;
}
inline bool end() const { return pos_ == nfeatures(); }
inline void
reset()
{
cursor_ = data_;
pos_ = 0;
}
std::string debug_str() const;
private:
uint8_t *data_;
const std::vector<runtime_type> *types_;
uint8_t *cursor_;
size_t pos_;
};
class dataview {
protected:
dataview(size_t n, const std::vector<runtime_type> &types);
inline const std::vector<size_t> & offsets() const { return offsets_; }
// in bytes
inline size_t rowsize() const { return rowsize_; }
inline size_t maskrowsize() const { return maskrowsize_; }
public:
virtual ~dataview() {}
// implementations need to provide the following API
virtual row_accessor get() const = 0;
virtual size_t index() const = 0;
virtual void next() = 0;
virtual void reset() = 0;
virtual bool end() const = 0;
inline size_t size() const { return n_; }
inline const std::vector<runtime_type> & types() const { return types_; }
private:
size_t n_;
std::vector<runtime_type> types_;
std::vector<size_t> offsets_;
size_t rowsize_;
size_t maskrowsize_;
};
class row_major_dataview : public dataview {
public:
row_major_dataview(const uint8_t *data,
const bool *mask,
size_t n,
const std::vector<runtime_type> &types);
row_accessor get() const override;
size_t index() const override;
void next() override;
void reset() override;
bool end() const override;
inline void reset_permutation() { pi_.clear(); }
void permute(rng_t &rng);
private:
const uint8_t *data_;
const bool *mask_;
size_t pos_;
std::vector<size_t> pi_;
};
} // namespace common
} // namespace microscopes
<commit_msg>helper function anymasked()<commit_after>#pragma once
#include <microscopes/common/type_helper.hpp>
#include <microscopes/common/random_fwd.hpp>
#include <microscopes/common/macros.hpp>
#include <microscopes/common/assert.hpp>
#include <vector>
#include <cstring>
#include <iostream>
namespace microscopes {
namespace common {
class row_accessor {
friend class row_mutator;
public:
row_accessor()
: data_(), mask_(), types_(),
cursor_(), mask_cursor_(), pos_() {}
row_accessor(const uint8_t *data,
const bool *mask,
const std::vector<runtime_type> *types)
: data_(data), mask_(mask), types_(types),
cursor_(data), mask_cursor_(mask), pos_()
{
MICROSCOPES_ASSERT(data);
MICROSCOPES_ASSERT(types);
}
inline size_t tell() const { return pos_; }
inline size_t nfeatures() const { return types_->size(); }
inline const runtime_type & curtype() const { return (*types_)[pos_]; }
inline unsigned curshape() const { return curtype().n(); }
inline bool
ismasked(size_t idx) const
{
MICROSCOPES_ASSERT(idx < curshape());
return !mask_ ? false : *(mask_cursor_ + idx);
}
inline bool
anymasked() const
{
if (!mask_)
return false;
// XXX: more efficient ways to do this!
for (size_t i = 0; i < curshape(); i++)
if (ismasked(i))
return true;
return false;
}
template <typename T>
inline T
get(size_t idx) const
{
MICROSCOPES_ASSERT(pos_ < nfeatures());
MICROSCOPES_ASSERT(cursor_);
MICROSCOPES_ASSERT(idx < curshape());
const size_t s = runtime_type_traits::PrimitiveTypeSize(curtype().t());
return runtime_cast::cast<T>(cursor_ + idx * s, curtype().t());
}
inline void
bump()
{
MICROSCOPES_ASSERT(pos_ <= nfeatures());
cursor_ += runtime_type_traits::RuntimeTypeSize(curtype());
mask_cursor_ += curtype().n();
pos_++;
}
inline bool end() const { return pos_ == nfeatures(); }
inline void
reset()
{
cursor_ = data_;
mask_cursor_ = mask_;
pos_ = 0;
}
std::string debug_str() const;
protected:
inline const uint8_t * cursor() const { return cursor_; }
private:
const uint8_t *data_;
const bool *mask_;
const std::vector<runtime_type> *types_;
const uint8_t *cursor_;
const bool *mask_cursor_;
size_t pos_;
};
class row_mutator {
public:
row_mutator()
: data_(), types_(), cursor_(), pos_() {}
row_mutator(uint8_t *data,
const std::vector<runtime_type> *types)
: data_(data), types_(types),
cursor_(data), pos_()
{
MICROSCOPES_ASSERT(data);
MICROSCOPES_ASSERT(types);
}
inline size_t tell() const { return pos_; }
inline size_t nfeatures() const { return types_->size(); }
inline const runtime_type & curtype() const { return (*types_)[pos_]; }
inline unsigned curshape() const { return curtype().n(); }
template <typename T>
inline void
set(T t, size_t idx)
{
MICROSCOPES_ASSERT(pos_ < nfeatures());
MICROSCOPES_ASSERT(cursor_);
MICROSCOPES_ASSERT(idx < curshape());
const size_t s = runtime_type_traits::PrimitiveTypeSize(curtype().t());
runtime_cast::uncast<T>(cursor_ + idx * s, curtype().t(), t);
}
void
set(const row_accessor &acc)
{
MICROSCOPES_DCHECK(curshape() == acc.curshape(), "shapes do not match");
MICROSCOPES_ASSERT(cursor_);
MICROSCOPES_ASSERT(acc.cursor());
const size_t s0 = runtime_type_traits::PrimitiveTypeSize(curtype().t());
const size_t s1 = runtime_type_traits::PrimitiveTypeSize(acc.curtype().t());
for (unsigned i = 0; i < curshape(); i++)
runtime_cast::copy(
cursor_ + i * s0, curtype().t(),
acc.cursor() + i * s1, acc.curtype().t());
}
inline void
bump()
{
MICROSCOPES_ASSERT(pos_ <= nfeatures());
cursor_ += runtime_type_traits::RuntimeTypeSize(curtype());
pos_++;
}
inline bool end() const { return pos_ == nfeatures(); }
inline void
reset()
{
cursor_ = data_;
pos_ = 0;
}
std::string debug_str() const;
private:
uint8_t *data_;
const std::vector<runtime_type> *types_;
uint8_t *cursor_;
size_t pos_;
};
class dataview {
protected:
dataview(size_t n, const std::vector<runtime_type> &types);
inline const std::vector<size_t> & offsets() const { return offsets_; }
// in bytes
inline size_t rowsize() const { return rowsize_; }
inline size_t maskrowsize() const { return maskrowsize_; }
public:
virtual ~dataview() {}
// implementations need to provide the following API
virtual row_accessor get() const = 0;
virtual size_t index() const = 0;
virtual void next() = 0;
virtual void reset() = 0;
virtual bool end() const = 0;
inline size_t size() const { return n_; }
inline const std::vector<runtime_type> & types() const { return types_; }
private:
size_t n_;
std::vector<runtime_type> types_;
std::vector<size_t> offsets_;
size_t rowsize_;
size_t maskrowsize_;
};
class row_major_dataview : public dataview {
public:
row_major_dataview(const uint8_t *data,
const bool *mask,
size_t n,
const std::vector<runtime_type> &types);
row_accessor get() const override;
size_t index() const override;
void next() override;
void reset() override;
bool end() const override;
inline void reset_permutation() { pi_.clear(); }
void permute(rng_t &rng);
private:
const uint8_t *data_;
const bool *mask_;
size_t pos_;
std::vector<size_t> pi_;
};
} // namespace common
} // namespace microscopes
<|endoftext|> |
<commit_before>//
// Copyright Antoine Leblanc 2010 - 2015
// Distributed under the MIT license.
//
// http://nauths.fr
// http://github.com/nicuveo
// mailto://[email protected]
//
#ifndef TOOLS_DUAL_ITERATOR_HH_
# define TOOLS_DUAL_ITERATOR_HH_
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Includes
# include <boost/iterator/iterator_adaptor.hpp>
# include <boost/tuple/tuple.hpp>
# include <boost/call_traits.hpp>
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Declarations
namespace tools
{
namespace il
{
template <typename C>
struct DualTrait
{
public:
typedef C ContainerType;
typedef typename ContainerType::value_type ValueType;
typedef typename ContainerType::const_iterator IteratorType;
typedef typename boost::call_traits<ValueType>::param_type RefType;
typedef boost::tuple<RefType, RefType> DualType;
};
template <typename E, typename C>
struct AdaptorTrait
{
public:
typedef boost::iterator_adaptor<
E,
typename DualTrait<C>::IteratorType,
typename DualTrait<C>::DualType,
boost::use_default,
typename DualTrait<C>::DualType> AdaptorType;
};
}
template <typename C>
class DualIterator : public il::AdaptorTrait<DualIterator<C>, C>::AdaptorType
{
public:
// types
typedef DualIterator<C> SelfType;
typedef il::DualTrait<C> TraitType;
typedef typename il::AdaptorTrait<SelfType, C>::AdaptorType AdaptorType;
typedef typename TraitType::IteratorType IteratorType;
typedef typename TraitType::DualType DualType;
typedef typename TraitType::RefType RefType;
// constructors
DualIterator()
{
}
template <typename I>
DualIterator(I const& other)
: AdaptorType(other), b_(other.b_), e_(other.e_)
{
}
template <typename I>
DualIterator(I const& b, I const& e, I const& i)
: AdaptorType(i), b_(b), e_(e)
{
}
private:
friend class boost::iterator_core_access;
// data
IteratorType b_;
IteratorType e_;
// internal operations
DualType dereference() const
{
IteratorType i1 = this->base_reference();
IteratorType i2 = i1;
if (++i2 == e_)
i2 = b_;
return boost::tie(*i1, *i2);
}
};
template <typename C>
struct DualType
{
public:
typedef typename DualIterator<C>::DualType Type;
};
template <typename C>
inline DualIterator<C> begin(C const& c)
{
return DualIterator<C>(c.begin(), c.end(), c.begin());
}
template <typename C>
inline DualIterator<C> end(C const& c)
{
return DualIterator<C>(c.begin(), c.end(), c.end());
}
template <typename C>
inline std::pair<DualIterator<C>, DualIterator<C> > range(C const& c)
{
return std::make_pair(begin(c), end(c));
}
template <typename T1, typename T2>
inline typename boost::call_traits<T1>::const_reference
first(boost::tuple<T1, T2> const& dt)
{
return dt.template get<0>();
}
template <typename T1, typename T2>
inline typename boost::call_traits<T2>::const_reference
second(boost::tuple<T1, T2> const& dt)
{
return dt.template get<1>();
}
}
#endif /* !TOOLS_DUAL_ITERATOR_HH_ */
<commit_msg>Removed unused file.<commit_after><|endoftext|> |
<commit_before>#include "ros/ros.h"
#include "std_msgs/String.h"
#include <uranus_dp/JoystickUranus.h>
#include <iostream>
#include <string.h>
#include "geometry_msgs/Twist.h"
class SetpointProcessing{
public:
SetpointProcessing(){
pub = n.advertise<std_msgs::String>("s1", 1);
sub = n.subscribe("joy_input", 1, &SetpointProcessing::callback, this);
}
void callback(const uranus_dp::JoystickUranus& input)
{
geometry_msgs::Twist output;
output.linear.x = input.surge;
output.linear.y = input.sway;
output.linear.z = input.heave;
output.angular.x = input.roll;
output.angular.y = input.pitch;
output.angular.z = input.yaw;
}
private:
ros::NodeHandle n;
ros::Publisher pub;
ros::Subscriber sub;
};
int main(int argc, char** argv){
ros::init(argc, argv, "setpoint_processing");
SetpointProcessing f;
ros::spin();
return 0;
}
<commit_msg>Add code for processing movement joystick input<commit_after>#include "ros/ros.h"
#include "std_msgs/String.h"
#include <uranus_dp/JoystickUranus.h>
#include <iostream>
#include <string.h>
#include "geometry_msgs/Twist.h"
#include <joystick/directional_input.h>
// Delivers twist.msg
class SetpointProcessing{
public:
SetpointProcessing(){
pub = n.advertise<geometry_msgs::Twist>("temp", 1);
sub = n.subscribe("joy_input", 1, &SetpointProcessing::callback, this);
}
void callback(const joystick::directional_input& input)
{
geometry_msgs::Twist output;
output.linear.x = (input.strafe_X/STRAFE_RANGE)*MAX_LINEAR_X;
output.linear.y = (input.strafe_Y/STRAFE_RANGE)*MAX_LINEAR_Y;
output.linear.z = (input.ascend/ASCEND_RANGE)*MAX_LINEAR_Z;
output.angular.x = 0.0;
output.angular.y = (input.turn_Y/TURN_RANGE)*MAX_ANGULAR_X;
output.angular.z = (input.turn_X/TURN_RANGE)*MAX_ANGULAR_Z;
pub.publish(output);
}
private:
ros::NodeHandle n;
ros::Publisher pub;
ros::Subscriber sub;
static const double MAX_LINEAR_X = 1.0;
static const double MAX_LINEAR_Y = 1.0;
static const double MAX_LINEAR_Z = 1.0;
static const double MAX_ANGULAR_X = 1.0;
static const double MAX_ANGULAR_Y = 1.0;
static const double MAX_ANGULAR_Z = 1.0;
static const int STRAFE_RANGE = (2 << 16);
static const int TURN_RANGE = (2 << 16);
static const int ASCEND_RANGE = (2 << 16);
};
int main(int argc, char** argv){
ros::init(argc, argv, "setpoint_processing");
SetpointProcessing f;
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <tacopie/typedefs.hpp>
namespace tacopie {
class tcp_socket {
public:
//! possible types of a TCP socket, either a client or a server
//! type is used to prevent the used of client specific operations on a server socket (and vice-versa)
//!
//! UNKNOWN is used when socket type could not be determined for now
//! for example, when
enum class type {
CLIENT,
SERVER,
UNKNOWN
};
public:
//! ctor & dtor
tcp_socket(void);
~tcp_socket(void) = default;
//! custom ctor
//! build socket from existing file descriptor
tcp_socket(fd_t fd, const std::string& host, std::uint32_t port, type t);
//! move ctor
tcp_socket(tcp_socket&&);
//! copy ctor & assignment operator
tcp_socket(const tcp_socket&) = delete;
tcp_socket& operator=(const tcp_socket&) = delete;
public:
//! comparison operator
bool operator==(const tcp_socket& rhs) const;
bool operator!=(const tcp_socket& rhs) const;
public:
//! client socket operations
std::vector<char> recv(std::size_t size_to_read);
std::size_t send(const std::vector<char>& data, std::size_t size_to_write);
void connect(const std::string& host, std::uint32_t port);
//! server socket operations
void bind(const std::string& host, std::uint32_t port);
void listen(std::size_t max_connection_queue);
tcp_socket accept(void);
//! general socket operations
void close(void);
public:
//! get socket name information
const std::string& get_host(void) const;
std::uint32_t get_port(void) const;
//! get socket type
type get_type(void) const;
//! set type, should be used if some operations determining socket type
//! have been done on the behalf of the tcp_socket instance
void set_type(type t);
//! direct access to the underlying fd
fd_t get_fd(void) const;
private:
//! create a new socket if no socket has been initialized yet
void create_socket_if_necessary(void);
//! check whether the current socket has an approriate type for that kind of operation
//! if current type is UNKNOWN, update internal type with given type
void check_or_set_type(type t);
private:
//! fd associated to the socket
fd_t m_fd;
//! socket name information
std::string m_host;
std::uint32_t m_port;
//! type of the socket
type m_type;
};
} //! tacopie
<commit_msg>comment typo<commit_after>#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <tacopie/typedefs.hpp>
namespace tacopie {
class tcp_socket {
public:
//! possible types of a TCP socket, either a client or a server
//! type is used to prevent the used of client specific operations on a server socket (and vice-versa)
//!
//! UNKNOWN is used when socket type could not be determined for now
enum class type {
CLIENT,
SERVER,
UNKNOWN
};
public:
//! ctor & dtor
tcp_socket(void);
~tcp_socket(void) = default;
//! custom ctor
//! build socket from existing file descriptor
tcp_socket(fd_t fd, const std::string& host, std::uint32_t port, type t);
//! move ctor
tcp_socket(tcp_socket&&);
//! copy ctor & assignment operator
tcp_socket(const tcp_socket&) = delete;
tcp_socket& operator=(const tcp_socket&) = delete;
public:
//! comparison operator
bool operator==(const tcp_socket& rhs) const;
bool operator!=(const tcp_socket& rhs) const;
public:
//! client socket operations
std::vector<char> recv(std::size_t size_to_read);
std::size_t send(const std::vector<char>& data, std::size_t size_to_write);
void connect(const std::string& host, std::uint32_t port);
//! server socket operations
void bind(const std::string& host, std::uint32_t port);
void listen(std::size_t max_connection_queue);
tcp_socket accept(void);
//! general socket operations
void close(void);
public:
//! get socket name information
const std::string& get_host(void) const;
std::uint32_t get_port(void) const;
//! get socket type
type get_type(void) const;
//! set type, should be used if some operations determining socket type
//! have been done on the behalf of the tcp_socket instance
void set_type(type t);
//! direct access to the underlying fd
fd_t get_fd(void) const;
private:
//! create a new socket if no socket has been initialized yet
void create_socket_if_necessary(void);
//! check whether the current socket has an approriate type for that kind of operation
//! if current type is UNKNOWN, update internal type with given type
void check_or_set_type(type t);
private:
//! fd associated to the socket
fd_t m_fd;
//! socket name information
std::string m_host;
std::uint32_t m_port;
//! type of the socket
type m_type;
};
} //! tacopie
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ClangInternalState.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <cstdio>
#include <string>
#include <time.h>
using namespace clang;
namespace cling {
ClangInternalState::ClangInternalState(ASTContext& C, llvm::Module& M,
const std::string& name)
: m_ASTContext(C), m_Module(M), m_DiffCommand("diff -u "), m_Name(name) {
store();
}
ClangInternalState::~ClangInternalState() {
// cleanup the temporary files:
remove(m_LookupTablesFile.c_str());
remove(m_IncludedFilesFile.c_str());
remove(m_ASTFile.c_str());
remove(m_LLVMModuleFile.c_str());
}
void ClangInternalState::store() {
m_LookupTablesOS.reset(createOutputFile("lookup", &m_LookupTablesFile));
m_IncludedFilesOS.reset(createOutputFile("included", &m_IncludedFilesFile));
m_ASTOS.reset(createOutputFile("ast", &m_ASTFile));
m_LLVMModuleOS.reset(createOutputFile("module", &m_LLVMModuleFile));
printLookupTables(*m_LookupTablesOS.get(), m_ASTContext);
printIncludedFiles(*m_IncludedFilesOS.get(),
m_ASTContext.getSourceManager());
printAST(*m_ASTOS.get(), m_ASTContext);
printLLVMModule(*m_LLVMModuleOS.get(), m_Module);
}
namespace {
std::string getCurrentTimeAsString() {
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer, 80, "%I_%M_%S", timeinfo);
return buffer;
}
}
// Copied with modifications from CompilerInstance.cpp
llvm::raw_fd_ostream*
ClangInternalState::createOutputFile(llvm::StringRef OutFile,
std::string *TempPathName/*=0*/,
bool RemoveFileOnSignal/*=true*/) {
llvm::OwningPtr<llvm::raw_fd_ostream> OS;
std::string OSFile;
llvm::SmallString<256> OutputPath;
llvm::sys::path::system_temp_directory(/*erasedOnReboot*/false, OutputPath);
// Only create the temporary if the parent directory exists (or create
// missing directories is true) and we can actually write to OutPath,
// otherwise we want to fail early.
llvm::SmallString<256> TempPath(OutputPath);
llvm::sys::fs::make_absolute(TempPath);
assert(llvm::sys::fs::is_directory(TempPath.str()) && "Must be a folder.");
// Create a temporary file.
llvm::sys::path::append(TempPath, OutFile);
TempPath += "-" + getCurrentTimeAsString();
TempPath += "-%%%%%%%%";
int fd;
if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)
== llvm::errc::success) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempPath.str();
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (TempPathName)
*TempPathName = OSFile;
return OS.take();
}
void ClangInternalState::compare(ClangInternalState& other) {
std::string differences = "";
if (differentContent(m_LookupTablesFile, other.m_LookupTablesFile,
differences)) {
llvm::errs() << "Differences in the lookup tablse\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_IncludedFilesFile, other.m_IncludedFilesFile,
differences)) {
llvm::errs() << "Differences in the included files\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_ASTFile, other.m_ASTFile, differences)) {
llvm::errs() << "Differences in the AST \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_LLVMModuleFile, other.m_LLVMModuleFile, differences)){
llvm::errs() << "Differences in the llvm Module \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
bool ClangInternalState::differentContent(const std::string& file1,
const std::string& file2,
std::string& differences) const {
FILE* pipe = popen((m_DiffCommand + file1 + " " + file2).c_str() , "r");
assert(pipe && "Error creating the pipe");
assert(differences.empty() && "Must be empty");
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
differences += buffer;
}
pclose(pipe);
return !differences.empty();
}
class DumpLookupTables : public RecursiveASTVisitor<DumpLookupTables> {
private:
//llvm::raw_ostream& m_OS;
public:
//DumpLookupTables(llvm::raw_ostream& OS) : m_OS(OS) { }
DumpLookupTables(llvm::raw_ostream&) { }
bool VisitDeclContext(DeclContext* DC) {
//DC->dumpLookups(m_OS);
return true;
}
};
void ClangInternalState::printLookupTables(llvm::raw_ostream& Out,
ASTContext& C) {
DumpLookupTables dumper(Out);
dumper.TraverseDecl(C.getTranslationUnitDecl());
}
void ClangInternalState::printIncludedFiles(llvm::raw_ostream& Out,
SourceManager& SM) {
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
const clang::SrcMgr::ContentCache &C = *I->second;
const clang::FileEntry *FE = C.OrigEntry;
// Our error recovery purges the cache of the FileEntry, but keeps
// the FileEntry's pointer so that if it was used by smb (like the
// SourceManager) it wouldn't be dangling. In that case we shouldn't
// print the FileName, because semantically it is not there.
if (!FE->getSize() && !FE->getModificationTime())
continue;
std::string fileName(FE->getName());
if (!(fileName.compare(0, 5, "/usr/") == 0 &&
fileName.find("/bits/") != std::string::npos)) {
Out << fileName << '\n';
}
}
}
void ClangInternalState::printAST(llvm::raw_ostream& Out, ASTContext& C) {
TranslationUnitDecl* TU = C.getTranslationUnitDecl();
unsigned Indentation = 0;
bool PrintInstantiation = false;
std::string ErrMsg;
clang::PrintingPolicy policy = C.getPrintingPolicy();
TU->print(Out, policy, Indentation, PrintInstantiation);
Out.flush();
}
void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
llvm::Module& M) {
M.print(Out, /*AssemblyAnnotationWriter*/ 0);
}
} // end namespace cling
<commit_msg>Add future wanna-track property.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <[email protected]>
//------------------------------------------------------------------------------
#include "cling/Interpreter/ClangInternalState.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"
#include <cstdio>
#include <string>
#include <time.h>
using namespace clang;
namespace cling {
ClangInternalState::ClangInternalState(ASTContext& C, llvm::Module& M,
const std::string& name)
: m_ASTContext(C), m_Module(M), m_DiffCommand("diff -u "), m_Name(name) {
store();
}
ClangInternalState::~ClangInternalState() {
// cleanup the temporary files:
remove(m_LookupTablesFile.c_str());
remove(m_IncludedFilesFile.c_str());
remove(m_ASTFile.c_str());
remove(m_LLVMModuleFile.c_str());
}
void ClangInternalState::store() {
m_LookupTablesOS.reset(createOutputFile("lookup", &m_LookupTablesFile));
m_IncludedFilesOS.reset(createOutputFile("included", &m_IncludedFilesFile));
m_ASTOS.reset(createOutputFile("ast", &m_ASTFile));
m_LLVMModuleOS.reset(createOutputFile("module", &m_LLVMModuleFile));
printLookupTables(*m_LookupTablesOS.get(), m_ASTContext);
printIncludedFiles(*m_IncludedFilesOS.get(),
m_ASTContext.getSourceManager());
printAST(*m_ASTOS.get(), m_ASTContext);
printLLVMModule(*m_LLVMModuleOS.get(), m_Module);
}
namespace {
std::string getCurrentTimeAsString() {
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer, 80, "%I_%M_%S", timeinfo);
return buffer;
}
}
// Copied with modifications from CompilerInstance.cpp
llvm::raw_fd_ostream*
ClangInternalState::createOutputFile(llvm::StringRef OutFile,
std::string *TempPathName/*=0*/,
bool RemoveFileOnSignal/*=true*/) {
llvm::OwningPtr<llvm::raw_fd_ostream> OS;
std::string OSFile;
llvm::SmallString<256> OutputPath;
llvm::sys::path::system_temp_directory(/*erasedOnReboot*/false, OutputPath);
// Only create the temporary if the parent directory exists (or create
// missing directories is true) and we can actually write to OutPath,
// otherwise we want to fail early.
llvm::SmallString<256> TempPath(OutputPath);
llvm::sys::fs::make_absolute(TempPath);
assert(llvm::sys::fs::is_directory(TempPath.str()) && "Must be a folder.");
// Create a temporary file.
llvm::sys::path::append(TempPath, OutFile);
TempPath += "-" + getCurrentTimeAsString();
TempPath += "-%%%%%%%%";
int fd;
if (llvm::sys::fs::createUniqueFile(TempPath.str(), fd, TempPath)
== llvm::errc::success) {
OS.reset(new llvm::raw_fd_ostream(fd, /*shouldClose=*/true));
OSFile = TempPath.str();
}
// Make sure the out stream file gets removed if we crash.
if (RemoveFileOnSignal)
llvm::sys::RemoveFileOnSignal(OSFile);
if (TempPathName)
*TempPathName = OSFile;
return OS.take();
}
void ClangInternalState::compare(ClangInternalState& other) {
std::string differences = "";
if (differentContent(m_LookupTablesFile, other.m_LookupTablesFile,
differences)) {
llvm::errs() << "Differences in the lookup tablse\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_IncludedFilesFile, other.m_IncludedFilesFile,
differences)) {
llvm::errs() << "Differences in the included files\n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_ASTFile, other.m_ASTFile, differences)) {
llvm::errs() << "Differences in the AST \n";
llvm::errs() << differences << "\n";
differences = "";
}
if (differentContent(m_LLVMModuleFile, other.m_LLVMModuleFile, differences)){
llvm::errs() << "Differences in the llvm Module \n";
llvm::errs() << differences << "\n";
differences = "";
}
}
bool ClangInternalState::differentContent(const std::string& file1,
const std::string& file2,
std::string& differences) const {
FILE* pipe = popen((m_DiffCommand + file1 + " " + file2).c_str() , "r");
assert(pipe && "Error creating the pipe");
assert(differences.empty() && "Must be empty");
char buffer[128];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
differences += buffer;
}
pclose(pipe);
return !differences.empty();
}
class DumpLookupTables : public RecursiveASTVisitor<DumpLookupTables> {
private:
//llvm::raw_ostream& m_OS;
public:
//DumpLookupTables(llvm::raw_ostream& OS) : m_OS(OS) { }
DumpLookupTables(llvm::raw_ostream&) { }
bool VisitDeclContext(DeclContext* DC) {
//DC->dumpLookups(m_OS);
return true;
}
};
void ClangInternalState::printLookupTables(llvm::raw_ostream& Out,
ASTContext& C) {
DumpLookupTables dumper(Out);
dumper.TraverseDecl(C.getTranslationUnitDecl());
}
void ClangInternalState::printIncludedFiles(llvm::raw_ostream& Out,
SourceManager& SM) {
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
const clang::SrcMgr::ContentCache &C = *I->second;
const clang::FileEntry *FE = C.OrigEntry;
// Our error recovery purges the cache of the FileEntry, but keeps
// the FileEntry's pointer so that if it was used by smb (like the
// SourceManager) it wouldn't be dangling. In that case we shouldn't
// print the FileName, because semantically it is not there.
if (!FE->getSize() && !FE->getModificationTime())
continue;
std::string fileName(FE->getName());
if (!(fileName.compare(0, 5, "/usr/") == 0 &&
fileName.find("/bits/") != std::string::npos)) {
Out << fileName << '\n';
}
}
}
void ClangInternalState::printAST(llvm::raw_ostream& Out, ASTContext& C) {
TranslationUnitDecl* TU = C.getTranslationUnitDecl();
unsigned Indentation = 0;
bool PrintInstantiation = false;
std::string ErrMsg;
clang::PrintingPolicy policy = C.getPrintingPolicy();
TU->print(Out, policy, Indentation, PrintInstantiation);
// TODO: For future when we relpace the bump allocation with slab.
//
//Out << "Allocated memory: " << C.getAllocatedMemory();
//Out << "Side table allocated memory: " << C.getSideTableAllocatedMemory();
Out.flush();
}
void ClangInternalState::printLLVMModule(llvm::raw_ostream& Out,
llvm::Module& M) {
M.print(Out, /*AssemblyAnnotationWriter*/ 0);
}
} // end namespace cling
<|endoftext|> |
<commit_before>#include "binaryninjaapi.h"
using namespace BinaryNinja;
using namespace std;
ScriptingOutputListener::ScriptingOutputListener()
{
m_callbacks.context = this;
m_callbacks.output = OutputCallback;
m_callbacks.error = ErrorCallback;
m_callbacks.inputReadyStateChanged = InputReadyStateChangedCallback;
}
void ScriptingOutputListener::OutputCallback(void* ctxt, const char* text)
{
ScriptingOutputListener* listener = (ScriptingOutputListener*)ctxt;
listener->NotifyOutput(text);
}
void ScriptingOutputListener::ErrorCallback(void* ctxt, const char* text)
{
ScriptingOutputListener* listener = (ScriptingOutputListener*)ctxt;
listener->NotifyError(text);
}
void ScriptingOutputListener::InputReadyStateChangedCallback(void* ctxt, BNScriptingProviderInputReadyState state)
{
ScriptingOutputListener* listener = (ScriptingOutputListener*)ctxt;
listener->NotifyInputReadyStateChanged(state);
}
void ScriptingOutputListener::NotifyOutput(const string&) {}
void ScriptingOutputListener::NotifyError(const string&) {}
void ScriptingOutputListener::NotifyInputReadyStateChanged(BNScriptingProviderInputReadyState) {}
ScriptingInstance::ScriptingInstance(ScriptingProvider* provider)
{
BNScriptingInstanceCallbacks cb;
cb.context = this;
cb.destroyInstance = DestroyInstanceCallback;
cb.externalRefTaken = nullptr;
cb.externalRefReleased = nullptr;
cb.executeScriptInput = ExecuteScriptInputCallback;
cb.cancelScriptInput = CancelScriptInputCallback;
cb.setCurrentBinaryView = SetCurrentBinaryViewCallback;
cb.setCurrentFunction = SetCurrentFunctionCallback;
cb.setCurrentBasicBlock = SetCurrentBasicBlockCallback;
cb.setCurrentAddress = SetCurrentAddressCallback;
cb.setCurrentSelection = SetCurrentSelectionCallback;
cb.completeInput = CompleteInputCallback;
cb.stop = StopCallback;
AddRefForRegistration();
m_object = BNInitScriptingInstance(provider->GetObject(), &cb);
}
ScriptingInstance::ScriptingInstance(BNScriptingInstance* instance)
{
m_object = instance;
}
void ScriptingInstance::DestroyInstanceCallback(void* ctxt)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->DestroyInstance();
}
BNScriptingProviderExecuteResult ScriptingInstance::ExecuteScriptInputCallback(void* ctxt, const char* input)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
return instance->ExecuteScriptInput(input);
}
void ScriptingInstance::CancelScriptInputCallback(void* ctxt)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->CancelScriptInput();
}
void ScriptingInstance::SetCurrentBinaryViewCallback(void* ctxt, BNBinaryView* view)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->SetCurrentBinaryView(view ? new BinaryView(BNNewViewReference(view)) : nullptr);
}
void ScriptingInstance::SetCurrentFunctionCallback(void* ctxt, BNFunction* func)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->SetCurrentFunction(func ? new Function(BNNewFunctionReference(func)) : nullptr);
}
void ScriptingInstance::SetCurrentBasicBlockCallback(void* ctxt, BNBasicBlock* block)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->SetCurrentBasicBlock(block ? new BasicBlock(BNNewBasicBlockReference(block)) : nullptr);
}
void ScriptingInstance::SetCurrentAddressCallback(void* ctxt, uint64_t addr)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->SetCurrentAddress(addr);
}
void ScriptingInstance::SetCurrentSelectionCallback(void* ctxt, uint64_t begin, uint64_t end)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->SetCurrentSelection(begin, end);
}
char* ScriptingInstance::CompleteInputCallback(void* ctxt, const char* text, uint64_t state)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
std::string completed = instance->CompleteInput(text, state);
if (completed.c_str() == nullptr)
{
LogWarn("ScriptingInstance::CompleteInput returned nullptr; replacing with empty string.");
completed = "";
}
return BNAllocString(completed.c_str());
}
void ScriptingInstance::StopCallback(void* ctxt)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->Stop();
}
void ScriptingInstance::DestroyInstance()
{
ReleaseForRegistration();
}
void ScriptingInstance::CancelScriptInput() {}
void ScriptingInstance::SetCurrentBinaryView(BinaryView*) {}
void ScriptingInstance::SetCurrentFunction(Function*) {}
void ScriptingInstance::SetCurrentBasicBlock(BasicBlock*) {}
void ScriptingInstance::SetCurrentAddress(uint64_t) {}
void ScriptingInstance::SetCurrentSelection(uint64_t, uint64_t) {}
std::string ScriptingInstance::CompleteInput(const std::string&, uint64_t)
{
return "";
}
void ScriptingInstance::Output(const string& text)
{
BNNotifyOutputForScriptingInstance(m_object, text.c_str());
}
void ScriptingInstance::Error(const string& text)
{
BNNotifyErrorForScriptingInstance(m_object, text.c_str());
}
void ScriptingInstance::InputReadyStateChanged(BNScriptingProviderInputReadyState state)
{
BNNotifyInputReadyStateForScriptingInstance(m_object, state);
}
BNScriptingProviderInputReadyState ScriptingInstance::GetInputReadyState()
{
return BNGetScriptingInstanceInputReadyState(m_object);
}
void ScriptingInstance::RegisterOutputListener(ScriptingOutputListener* listener)
{
BNRegisterScriptingInstanceOutputListener(m_object, &listener->GetCallbacks());
}
void ScriptingInstance::UnregisterOutputListener(ScriptingOutputListener* listener)
{
BNUnregisterScriptingInstanceOutputListener(m_object, &listener->GetCallbacks());
}
std::string ScriptingInstance::GetDelimiters()
{
return BNGetScriptingInstanceDelimiters(m_object);
}
void ScriptingInstance::SetDelimiters(const std::string& delimiters)
{
BNSetScriptingInstanceDelimiters(m_object, delimiters.c_str());
}
void ScriptingInstance::Stop() {}
CoreScriptingInstance::CoreScriptingInstance(BNScriptingInstance* instance) : ScriptingInstance(instance) {}
BNScriptingProviderExecuteResult CoreScriptingInstance::ExecuteScriptInput(const string& input)
{
return BNExecuteScriptInput(m_object, input.c_str());
}
BNScriptingProviderExecuteResult CoreScriptingInstance::ExecuteScriptInputFromFilename(const string& filename)
{
return BNExecuteScriptInputFromFilename(m_object, filename.c_str());
}
void CoreScriptingInstance::CancelScriptInput()
{
BNCancelScriptInput(m_object);
}
void CoreScriptingInstance::SetCurrentBinaryView(BinaryView* view)
{
BNSetScriptingInstanceCurrentBinaryView(m_object, view ? view->GetObject() : nullptr);
}
void CoreScriptingInstance::SetCurrentFunction(Function* func)
{
BNSetScriptingInstanceCurrentFunction(m_object, func ? func->GetObject() : nullptr);
}
void CoreScriptingInstance::SetCurrentBasicBlock(BasicBlock* block)
{
BNSetScriptingInstanceCurrentBasicBlock(m_object, block ? block->GetObject() : nullptr);
}
void CoreScriptingInstance::SetCurrentAddress(uint64_t addr)
{
BNSetScriptingInstanceCurrentAddress(m_object, addr);
}
void CoreScriptingInstance::SetCurrentSelection(uint64_t begin, uint64_t end)
{
BNSetScriptingInstanceCurrentSelection(m_object, begin, end);
}
std::string CoreScriptingInstance::CompleteInput(const std::string& text, uint64_t state)
{
char* result = BNScriptingInstanceCompleteInput(m_object, text.c_str(), state);
std::string ret = result;
BNFreeString(result);
return ret;
}
void CoreScriptingInstance::Stop()
{
BNStopScriptingInstance(m_object);
}
ScriptingProvider::ScriptingProvider(const string& name, const string& apiName) :
m_nameForRegister(name), m_apiNameForRegister(apiName)
{}
ScriptingProvider::ScriptingProvider(BNScriptingProvider* provider)
{
m_object = provider;
}
BNScriptingInstance* ScriptingProvider::CreateInstanceCallback(void* ctxt)
{
ScriptingProvider* provider = (ScriptingProvider*)ctxt;
Ref<ScriptingInstance> instance = provider->CreateNewInstance();
return instance ? BNNewScriptingInstanceReference(instance->GetObject()) : nullptr;
}
bool ScriptingProvider::LoadModuleCallback(void* ctxt, const char* repository, const char* module, bool force)
{
ScriptingProvider* provider = (ScriptingProvider*)ctxt;
return BNLoadScriptingProviderModule(provider->GetObject(), repository, module, force);
}
bool ScriptingProvider::InstallModulesCallback(void* ctxt, const char* modules)
{
ScriptingProvider* provider = (ScriptingProvider*)ctxt;
return BNInstallScriptingProviderModules(provider->GetObject(), modules);
}
string ScriptingProvider::GetName()
{
char* providerNameRaw = BNGetScriptingProviderName(m_object);
string providerName(providerNameRaw);
BNFreeString(providerNameRaw);
return providerName;
}
string ScriptingProvider::GetAPIName()
{
char* providerNameRaw = BNGetScriptingProviderAPIName(m_object);
string providerName(providerNameRaw);
BNFreeString(providerNameRaw);
return providerName;
}
vector<Ref<ScriptingProvider>> ScriptingProvider::GetList()
{
size_t count;
BNScriptingProvider** list = BNGetScriptingProviderList(&count);
vector<Ref<ScriptingProvider>> result;
for (size_t i = 0; i < count; i++)
result.push_back(new CoreScriptingProvider(list[i]));
BNFreeScriptingProviderList(list);
return result;
}
Ref<ScriptingProvider> ScriptingProvider::GetByName(const string& name)
{
BNScriptingProvider* result = BNGetScriptingProviderByName(name.c_str());
if (!result)
return nullptr;
return new CoreScriptingProvider(result);
}
Ref<ScriptingProvider> ScriptingProvider::GetByAPIName(const string& name)
{
BNScriptingProvider* result = BNGetScriptingProviderByAPIName(name.c_str());
if (!result)
return nullptr;
return new CoreScriptingProvider(result);
}
void ScriptingProvider::Register(ScriptingProvider* provider)
{
BNScriptingProviderCallbacks cb;
cb.context = provider;
cb.createInstance = CreateInstanceCallback;
cb.loadModule = LoadModuleCallback;
cb.installModules = InstallModulesCallback;
provider->m_object =
BNRegisterScriptingProvider(provider->m_nameForRegister.c_str(), provider->m_apiNameForRegister.c_str(), &cb);
}
CoreScriptingProvider::CoreScriptingProvider(BNScriptingProvider* provider) : ScriptingProvider(provider) {}
Ref<ScriptingInstance> CoreScriptingProvider::CreateNewInstance()
{
BNScriptingInstance* result = BNCreateScriptingProviderInstance(m_object);
if (!result)
return nullptr;
return new CoreScriptingInstance(result);
}
bool CoreScriptingProvider::LoadModule(const std::string& repository, const std::string& module, bool force)
{
return BNLoadScriptingProviderModule(m_object, repository.c_str(), module.c_str(), force);
}
bool CoreScriptingProvider::InstallModules(const std::string& modules)
{
return BNInstallScriptingProviderModules(m_object, modules.c_str());
}
<commit_msg>Fix memory leak issue related to ScriptingInstance. Close https://github.com/Vector35/binaryninja-api/issues/3461.<commit_after>#include "binaryninjaapi.h"
using namespace BinaryNinja;
using namespace std;
ScriptingOutputListener::ScriptingOutputListener()
{
m_callbacks.context = this;
m_callbacks.output = OutputCallback;
m_callbacks.error = ErrorCallback;
m_callbacks.inputReadyStateChanged = InputReadyStateChangedCallback;
}
void ScriptingOutputListener::OutputCallback(void* ctxt, const char* text)
{
ScriptingOutputListener* listener = (ScriptingOutputListener*)ctxt;
listener->NotifyOutput(text);
}
void ScriptingOutputListener::ErrorCallback(void* ctxt, const char* text)
{
ScriptingOutputListener* listener = (ScriptingOutputListener*)ctxt;
listener->NotifyError(text);
}
void ScriptingOutputListener::InputReadyStateChangedCallback(void* ctxt, BNScriptingProviderInputReadyState state)
{
ScriptingOutputListener* listener = (ScriptingOutputListener*)ctxt;
listener->NotifyInputReadyStateChanged(state);
}
void ScriptingOutputListener::NotifyOutput(const string&) {}
void ScriptingOutputListener::NotifyError(const string&) {}
void ScriptingOutputListener::NotifyInputReadyStateChanged(BNScriptingProviderInputReadyState) {}
ScriptingInstance::ScriptingInstance(ScriptingProvider* provider)
{
BNScriptingInstanceCallbacks cb;
cb.context = this;
cb.destroyInstance = DestroyInstanceCallback;
cb.externalRefTaken = nullptr;
cb.externalRefReleased = nullptr;
cb.executeScriptInput = ExecuteScriptInputCallback;
cb.cancelScriptInput = CancelScriptInputCallback;
cb.setCurrentBinaryView = SetCurrentBinaryViewCallback;
cb.setCurrentFunction = SetCurrentFunctionCallback;
cb.setCurrentBasicBlock = SetCurrentBasicBlockCallback;
cb.setCurrentAddress = SetCurrentAddressCallback;
cb.setCurrentSelection = SetCurrentSelectionCallback;
cb.completeInput = CompleteInputCallback;
cb.stop = StopCallback;
AddRefForRegistration();
m_object = BNInitScriptingInstance(provider->GetObject(), &cb);
}
ScriptingInstance::ScriptingInstance(BNScriptingInstance* instance)
{
m_object = instance;
}
void ScriptingInstance::DestroyInstanceCallback(void* ctxt)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->DestroyInstance();
}
BNScriptingProviderExecuteResult ScriptingInstance::ExecuteScriptInputCallback(void* ctxt, const char* input)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
return instance->ExecuteScriptInput(input);
}
void ScriptingInstance::CancelScriptInputCallback(void* ctxt)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->CancelScriptInput();
}
void ScriptingInstance::SetCurrentBinaryViewCallback(void* ctxt, BNBinaryView* view)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
Ref<BinaryView> object = view ? new BinaryView(BNNewViewReference(view)) : nullptr;
instance->SetCurrentBinaryView(object);
}
void ScriptingInstance::SetCurrentFunctionCallback(void* ctxt, BNFunction* func)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
Ref<Function> object = func ? new Function(BNNewFunctionReference(func)) : nullptr;
instance->SetCurrentFunction(object);
}
void ScriptingInstance::SetCurrentBasicBlockCallback(void* ctxt, BNBasicBlock* block)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
Ref<BasicBlock> object = block ? new BasicBlock(BNNewBasicBlockReference(block)) : nullptr;
instance->SetCurrentBasicBlock(object);
}
void ScriptingInstance::SetCurrentAddressCallback(void* ctxt, uint64_t addr)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->SetCurrentAddress(addr);
}
void ScriptingInstance::SetCurrentSelectionCallback(void* ctxt, uint64_t begin, uint64_t end)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->SetCurrentSelection(begin, end);
}
char* ScriptingInstance::CompleteInputCallback(void* ctxt, const char* text, uint64_t state)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
std::string completed = instance->CompleteInput(text, state);
if (completed.c_str() == nullptr)
{
LogWarn("ScriptingInstance::CompleteInput returned nullptr; replacing with empty string.");
completed = "";
}
return BNAllocString(completed.c_str());
}
void ScriptingInstance::StopCallback(void* ctxt)
{
ScriptingInstance* instance = (ScriptingInstance*)ctxt;
instance->Stop();
}
void ScriptingInstance::DestroyInstance()
{
ReleaseForRegistration();
}
void ScriptingInstance::CancelScriptInput() {}
void ScriptingInstance::SetCurrentBinaryView(BinaryView*) {}
void ScriptingInstance::SetCurrentFunction(Function*) {}
void ScriptingInstance::SetCurrentBasicBlock(BasicBlock*) {}
void ScriptingInstance::SetCurrentAddress(uint64_t) {}
void ScriptingInstance::SetCurrentSelection(uint64_t, uint64_t) {}
std::string ScriptingInstance::CompleteInput(const std::string&, uint64_t)
{
return "";
}
void ScriptingInstance::Output(const string& text)
{
BNNotifyOutputForScriptingInstance(m_object, text.c_str());
}
void ScriptingInstance::Error(const string& text)
{
BNNotifyErrorForScriptingInstance(m_object, text.c_str());
}
void ScriptingInstance::InputReadyStateChanged(BNScriptingProviderInputReadyState state)
{
BNNotifyInputReadyStateForScriptingInstance(m_object, state);
}
BNScriptingProviderInputReadyState ScriptingInstance::GetInputReadyState()
{
return BNGetScriptingInstanceInputReadyState(m_object);
}
void ScriptingInstance::RegisterOutputListener(ScriptingOutputListener* listener)
{
BNRegisterScriptingInstanceOutputListener(m_object, &listener->GetCallbacks());
}
void ScriptingInstance::UnregisterOutputListener(ScriptingOutputListener* listener)
{
BNUnregisterScriptingInstanceOutputListener(m_object, &listener->GetCallbacks());
}
std::string ScriptingInstance::GetDelimiters()
{
return BNGetScriptingInstanceDelimiters(m_object);
}
void ScriptingInstance::SetDelimiters(const std::string& delimiters)
{
BNSetScriptingInstanceDelimiters(m_object, delimiters.c_str());
}
void ScriptingInstance::Stop() {}
CoreScriptingInstance::CoreScriptingInstance(BNScriptingInstance* instance) : ScriptingInstance(instance) {}
BNScriptingProviderExecuteResult CoreScriptingInstance::ExecuteScriptInput(const string& input)
{
return BNExecuteScriptInput(m_object, input.c_str());
}
BNScriptingProviderExecuteResult CoreScriptingInstance::ExecuteScriptInputFromFilename(const string& filename)
{
return BNExecuteScriptInputFromFilename(m_object, filename.c_str());
}
void CoreScriptingInstance::CancelScriptInput()
{
BNCancelScriptInput(m_object);
}
void CoreScriptingInstance::SetCurrentBinaryView(BinaryView* view)
{
BNSetScriptingInstanceCurrentBinaryView(m_object, view ? view->GetObject() : nullptr);
}
void CoreScriptingInstance::SetCurrentFunction(Function* func)
{
BNSetScriptingInstanceCurrentFunction(m_object, func ? func->GetObject() : nullptr);
}
void CoreScriptingInstance::SetCurrentBasicBlock(BasicBlock* block)
{
BNSetScriptingInstanceCurrentBasicBlock(m_object, block ? block->GetObject() : nullptr);
}
void CoreScriptingInstance::SetCurrentAddress(uint64_t addr)
{
BNSetScriptingInstanceCurrentAddress(m_object, addr);
}
void CoreScriptingInstance::SetCurrentSelection(uint64_t begin, uint64_t end)
{
BNSetScriptingInstanceCurrentSelection(m_object, begin, end);
}
std::string CoreScriptingInstance::CompleteInput(const std::string& text, uint64_t state)
{
char* result = BNScriptingInstanceCompleteInput(m_object, text.c_str(), state);
std::string ret = result;
BNFreeString(result);
return ret;
}
void CoreScriptingInstance::Stop()
{
BNStopScriptingInstance(m_object);
}
ScriptingProvider::ScriptingProvider(const string& name, const string& apiName) :
m_nameForRegister(name), m_apiNameForRegister(apiName)
{}
ScriptingProvider::ScriptingProvider(BNScriptingProvider* provider)
{
m_object = provider;
}
BNScriptingInstance* ScriptingProvider::CreateInstanceCallback(void* ctxt)
{
ScriptingProvider* provider = (ScriptingProvider*)ctxt;
Ref<ScriptingInstance> instance = provider->CreateNewInstance();
return instance ? BNNewScriptingInstanceReference(instance->GetObject()) : nullptr;
}
bool ScriptingProvider::LoadModuleCallback(void* ctxt, const char* repository, const char* module, bool force)
{
ScriptingProvider* provider = (ScriptingProvider*)ctxt;
return BNLoadScriptingProviderModule(provider->GetObject(), repository, module, force);
}
bool ScriptingProvider::InstallModulesCallback(void* ctxt, const char* modules)
{
ScriptingProvider* provider = (ScriptingProvider*)ctxt;
return BNInstallScriptingProviderModules(provider->GetObject(), modules);
}
string ScriptingProvider::GetName()
{
char* providerNameRaw = BNGetScriptingProviderName(m_object);
string providerName(providerNameRaw);
BNFreeString(providerNameRaw);
return providerName;
}
string ScriptingProvider::GetAPIName()
{
char* providerNameRaw = BNGetScriptingProviderAPIName(m_object);
string providerName(providerNameRaw);
BNFreeString(providerNameRaw);
return providerName;
}
vector<Ref<ScriptingProvider>> ScriptingProvider::GetList()
{
size_t count;
BNScriptingProvider** list = BNGetScriptingProviderList(&count);
vector<Ref<ScriptingProvider>> result;
for (size_t i = 0; i < count; i++)
result.push_back(new CoreScriptingProvider(list[i]));
BNFreeScriptingProviderList(list);
return result;
}
Ref<ScriptingProvider> ScriptingProvider::GetByName(const string& name)
{
BNScriptingProvider* result = BNGetScriptingProviderByName(name.c_str());
if (!result)
return nullptr;
return new CoreScriptingProvider(result);
}
Ref<ScriptingProvider> ScriptingProvider::GetByAPIName(const string& name)
{
BNScriptingProvider* result = BNGetScriptingProviderByAPIName(name.c_str());
if (!result)
return nullptr;
return new CoreScriptingProvider(result);
}
void ScriptingProvider::Register(ScriptingProvider* provider)
{
BNScriptingProviderCallbacks cb;
cb.context = provider;
cb.createInstance = CreateInstanceCallback;
cb.loadModule = LoadModuleCallback;
cb.installModules = InstallModulesCallback;
provider->m_object =
BNRegisterScriptingProvider(provider->m_nameForRegister.c_str(), provider->m_apiNameForRegister.c_str(), &cb);
}
CoreScriptingProvider::CoreScriptingProvider(BNScriptingProvider* provider) : ScriptingProvider(provider) {}
Ref<ScriptingInstance> CoreScriptingProvider::CreateNewInstance()
{
BNScriptingInstance* result = BNCreateScriptingProviderInstance(m_object);
if (!result)
return nullptr;
return new CoreScriptingInstance(result);
}
bool CoreScriptingProvider::LoadModule(const std::string& repository, const std::string& module, bool force)
{
return BNLoadScriptingProviderModule(m_object, repository.c_str(), module.c_str(), force);
}
bool CoreScriptingProvider::InstallModules(const std::string& modules)
{
return BNInstallScriptingProviderModules(m_object, modules.c_str());
}
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2020 Google LLC.
* 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 <map>
#include <limits>
#include <Weave/Profiles/data-management/Current/WdmManagedNamespace.h>
#include <Weave/Profiles/data-management/Current/GenericTraitCatalogImpl.h>
#include <Weave/Profiles/data-management/Current/GenericTraitCatalogImpl.ipp>
namespace nl {
namespace Weave {
namespace Profiles {
namespace WeaveMakeManagedNamespaceIdentifier(DataManagement, kWeaveManagedNamespaceDesignation_Current) {
template class GenericTraitCatalogImpl<TraitDataSink>;
template class GenericTraitCatalogImpl<TraitDataSource>;
}; // namespace WeaveMakeManagedNamespaceIdentifier(DataManagement, kWeaveManagedNamespaceDesignation_Current)
}; // namespace Profiles
}; // namespace Weave
}; // namespace nl
<commit_msg>Guard the template instantiation for generictraitcatalogimpl<commit_after>/*
*
* Copyright (c) 2020 Google LLC.
* 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.
*/
#if WEAVE_CONFIG_DATA_MANAGEMENT_CLIENT_EXPERIMENTAL
#include <map>
#include <limits>
#include <Weave/Profiles/data-management/Current/WdmManagedNamespace.h>
#include <Weave/Profiles/data-management/Current/GenericTraitCatalogImpl.h>
#include <Weave/Profiles/data-management/Current/GenericTraitCatalogImpl.ipp>
namespace nl {
namespace Weave {
namespace Profiles {
namespace WeaveMakeManagedNamespaceIdentifier(DataManagement, kWeaveManagedNamespaceDesignation_Current) {
template class GenericTraitCatalogImpl<TraitDataSink>;
template class GenericTraitCatalogImpl<TraitDataSource>;
}; // namespace WeaveMakeManagedNamespaceIdentifier(DataManagement, kWeaveManagedNamespaceDesignation_Current)
}; // namespace Profiles
}; // namespace Weave
}; // namespace nl
#endif
<|endoftext|> |
<commit_before>/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "pluginproxy.h"
#include <sys/types.h>
#include <pwd.h>
#include <QStringList>
#include <QThreadStorage>
#include <QThread>
#include "SignOn/uisessiondata_priv.h"
#include "SignOn/signonplugincommon.h"
/*
* TODO: remove the "SignOn/authpluginif.h" include below after the removal
* of the deprecated error handling (needed here only for the deprecated
* AuthPluginError::PLUGIN_ERROR_GENERAL).
*/
#include "SignOn/authpluginif.h"
using namespace SignOn;
//TODO get this from config
#define REMOTEPLUGIN_BIN_PATH QLatin1String("/usr/bin/signonpluginprocess")
#define PLUGINPROCESS_START_TIMEOUT 5000
#define PLUGINPROCESS_STOP_TIMEOUT 1000
namespace SignonDaemonNS {
PluginProcess::PluginProcess(QObject *parent) : QProcess(parent)
{
}
PluginProcess::~PluginProcess()
{
}
void PluginProcess::setupChildProcess()
{
// Drop all root privileges in the child process and switch to signon user
#ifndef NO_SIGNON_USER
//get uid and gid
struct passwd *passwdRecord = getpwnam("signon");
if ( !passwdRecord ){
fprintf(stderr, "failed to get user: signon\n");
emit QProcess::finished(2, QProcess::NormalExit);
exit(2);
}
#ifdef SIGNOND_TRACE
//this is run in remote plugin process, so trace should go to stderr
fprintf(stderr, "got user: %s with uid: %d\n", passwdRecord->pw_name, passwdRecord->pw_uid);
#endif
if (( ::setgid(passwdRecord->pw_gid))
|| (::setuid(passwdRecord->pw_uid))
|| (::getuid() != passwdRecord->pw_uid)
) {
fprintf(stderr, "failed to set user: %s with uid: %d", passwdRecord->pw_name, passwdRecord->pw_uid);
emit QProcess::finished(2, QProcess::NormalExit);
exit(2);
}
#endif
}
PluginProxy::PluginProxy(QString type, QObject *parent)
: QObject(parent)
{
TRACE();
m_type = type;
m_isProcessing = false;
m_process = new PluginProcess(this);
connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(onReadStandardError()));
/*
* TODO: some error handling should be added here, at least remove of current
* request data from the top of the queue and reply an error code
* */
connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onExit(int, QProcess::ExitStatus)));
connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onError(QProcess::ProcessError)));
}
PluginProxy::~PluginProxy()
{
if (m_process != NULL &&
m_process->state() != QProcess::NotRunning)
{
if (m_isProcessing)
cancel();
stop();
if (!m_process->waitForFinished(PLUGINPROCESS_STOP_TIMEOUT)) {
qCritical() << "The signon plugin does not react on demand to stop: need to kill it!!!";
m_process->kill();
if (!m_process->waitForFinished(PLUGINPROCESS_STOP_TIMEOUT))
{
if (m_process->pid()) {
qCritical() << "The signon plugin seems to ignore kill(), killing it from command line";
QString killProcessCommand(QString::fromLatin1("kill -9 %1").arg(m_process->pid()));
QProcess::execute(killProcessCommand);
}
}
}
}
}
PluginProxy* PluginProxy::createNewPluginProxy(const QString &type)
{
PluginProxy *pp = new PluginProxy(type);
QStringList args = QStringList() << pp->m_type;
pp->m_process->start(REMOTEPLUGIN_BIN_PATH, args);
QByteArray tmp;
if (!pp->waitForStarted(PLUGINPROCESS_START_TIMEOUT)) {
TRACE() << "The process cannot be started";
delete pp;
return NULL;
}
if (!pp->readOnReady(tmp, PLUGINPROCESS_START_TIMEOUT)) {
TRACE() << "The process cannot load plugin";
delete pp;
return NULL;
}
pp->m_type = pp->queryType();
pp->m_mechanisms = pp->queryMechanisms();
connect(pp->m_process, SIGNAL(readyReadStandardOutput()), pp, SLOT(onReadStandardOutput()));
TRACE() << "The process is started";
return pp;
}
bool PluginProxy::process(const QString &cancelKey, const QVariantMap &inData, const QString &mechanism)
{
TRACE();
if (!restartIfRequired())
return false;
m_cancelKey = cancelKey;
QVariant value = inData.value(SSOUI_KEY_UIPOLICY);
m_uiPolicy = value.toInt();
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_PROCESS;
in << QVariant(inData);
in << QVariant(mechanism);
m_isProcessing = true;
return true;
}
bool PluginProxy::processUi(const QString &cancelKey, const QVariantMap &inData)
{
TRACE() << inData;
if (!restartIfRequired())
return false;
m_cancelKey = cancelKey;
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_PROCESS_UI;
in << QVariant(inData);
m_isProcessing = true;
return true;
}
bool PluginProxy::processRefresh(const QString &cancelKey, const QVariantMap &inData)
{
TRACE() << inData;
if (!restartIfRequired())
return false;
m_cancelKey = cancelKey;
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_REFRESH;
in << QVariant(inData);
m_isProcessing = true;
return true;
}
void PluginProxy::cancel()
{
TRACE();
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_CANCEL;
}
void PluginProxy::stop()
{
TRACE();
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_STOP;
}
bool PluginProxy::readOnReady(QByteArray &buffer, int timeout)
{
bool ready = m_process->waitForReadyRead(timeout);
if (ready) {
if (!m_process->bytesAvailable())
return false;
while (m_process->bytesAvailable())
buffer += m_process->readAllStandardOutput();
}
return ready;
}
bool PluginProxy::isProcessing()
{
return m_isProcessing;
}
void PluginProxy::onReadStandardOutput()
{
disconnect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadStandardOutput()));
QByteArray token;
QVariant infoVa;
QVariantMap info;
if (!m_process->bytesAvailable()) {
qCritical() << "No information available on process";
m_isProcessing = false;
emit processError(m_cancelKey, Error::InternalServer, QString());
return;
}
QByteArray buffer;
while (m_process->bytesAvailable())
buffer += m_process->readAllStandardOutput();
/*
* we need to analyze the whole buffer
* and if it contains error then emit only error
* otherwise process/emit the incoming information
* one by one
* */
QDataStream out(buffer);
bool isResultObtained = false;
while (out.status() == QDataStream::Ok) {
quint32 opres;
out >> opres; //result of operation: error code
TRACE() << opres;
if (opres == PLUGIN_RESPONSE_RESULT) {
TRACE() << "PLUGIN_RESPONSE_RESULT";
out >> infoVa; //SessionData in QVariant
info = infoVa.toMap();
m_isProcessing = false;
if (!isResultObtained)
emit processResultReply(m_cancelKey, info);
else
BLAME() << "Unexpected plugin response: " << info;
isResultObtained = true;
} else if (opres == PLUGIN_RESPONSE_STORE) {
TRACE() << "PLUGIN_RESPONSE_STORE";
out >> infoVa; //SessionData in QVariant
info = infoVa.toMap();
if (!isResultObtained)
emit processStore(m_cancelKey, info);
else
BLAME() << "Unexpected plugin store: " << info;
} else if (opres == PLUGIN_RESPONSE_UI) {
TRACE() << "PLUGIN_RESPONSE_UI";
out >> infoVa; //UiSessionData in QVariant
info = infoVa.toMap();
if (!isResultObtained) {
bool allowed = true;
if (m_uiPolicy == NoUserInteractionPolicy)
allowed = false;
if (m_uiPolicy == ValidationPolicy) {
bool credentialsQueried =
(info.contains(SSOUI_KEY_QUERYUSERNAME)
|| info.contains(SSOUI_KEY_QUERYPASSWORD));
bool captchaQueried =
(info.contains(SSOUI_KEY_CAPTCHAIMG)
|| info.contains(SSOUI_KEY_CAPTCHAURL));
if (credentialsQueried && !captchaQueried)
allowed = false;
}
if (!allowed) {
//set error and return;
TRACE() << "ui policy prevented ui launch";
info.insert(SSOUI_KEY_ERROR, QUERY_ERROR_FORBIDDEN);
processUi(m_cancelKey, info);
} else {
TRACE() << "open ui";
emit processUiRequest(m_cancelKey, info);
}
} else {
BLAME() << "Unexpected plugin ui response: " << info;
}
} else if (opres == PLUGIN_RESPONSE_REFRESHED) {
TRACE() << "PLUGIN_RESPONSE_REFRESHED";
out >> infoVa; //UiSessionData in QVariant
info = infoVa.toMap();
if (!isResultObtained)
emit processRefreshRequest(m_cancelKey, info);
else
BLAME() << "Unexpected plugin ui response: " << info;
} else if (opres == PLUGIN_RESPONSE_ERROR) {
TRACE() << "PLUGIN_RESPONSE_ERROR";
quint32 err;
QString errorMessage;
out >> err;
out >> errorMessage;
m_isProcessing = false;
if (!isResultObtained)
emit processError(m_cancelKey, (int)err, errorMessage);
else
BLAME() << "Unexpected plugin error: " << errorMessage;
isResultObtained = true;
} else if (opres == PLUGIN_RESPONSE_SIGNAL) {
TRACE() << "PLUGIN_RESPONSE_SIGNAL";
quint32 state;
QString message;
out >> state;
out >> message;
if (!isResultObtained)
emit stateChanged(m_cancelKey, (int)state, message);
else
BLAME() << "Unexpected plugin signal: " << state << " " << message;
}
}
connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadStandardOutput()));
}
void PluginProxy::onReadStandardError()
{
QString ba = QString::fromLatin1(m_process->readAllStandardError());
TRACE() << ba;
}
void PluginProxy::onExit(int exitCode, QProcess::ExitStatus exitStatus)
{
TRACE() << "Plugin process exit with code " << exitCode << " : " << exitStatus;
if (m_isProcessing || exitStatus == QProcess::CrashExit) {
qCritical() << "Challenge produces CRASH!";
emit processError(m_cancelKey, Error::InternalServer, QLatin1String("plugin processed crashed"));
}
if (exitCode == 2) {
TRACE() << "plugin process terminated because cannot change user";
}
m_isProcessing = false;
}
void PluginProxy::onError(QProcess::ProcessError err)
{
TRACE() << "Error: " << err;
}
QString PluginProxy::queryType()
{
TRACE();
if (!restartIfRequired())
return QString();
QDataStream ds(m_process);
ds << (quint32)PLUGIN_OP_TYPE;
QByteArray typeBa, buffer;
bool result;
if ((result = readOnReady(buffer, PLUGINPROCESS_START_TIMEOUT))) {
QDataStream out(buffer);
out >> typeBa;
} else
qCritical("PluginProxy returned NULL result");
return QString::fromLatin1(typeBa);
}
QStringList PluginProxy::queryMechanisms()
{
TRACE();
if (!restartIfRequired())
return QStringList();
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_MECHANISMS;
QByteArray buffer;
QStringList strList;
bool result;
if ((result = readOnReady(buffer, PLUGINPROCESS_START_TIMEOUT))) {
QVariant mechanismsVar;
QDataStream out(buffer);
out >> mechanismsVar;
QVariantList varList = mechanismsVar.toList();
for (int i = 0; i < varList.count(); i++)
strList << varList.at(i).toString();
TRACE() << strList;
} else
qCritical("PluginProxy returned NULL result");
return strList;
}
bool PluginProxy::waitForStarted(int timeout)
{
return m_process->waitForStarted(timeout);
}
bool PluginProxy::waitForFinished(int timeout)
{
return m_process->waitForFinished(timeout);
}
bool PluginProxy::restartIfRequired()
{
if (m_process->state() == QProcess::NotRunning) {
TRACE() << "RESTART REQUIRED";
m_process->start(REMOTEPLUGIN_BIN_PATH, QStringList(m_type));
QByteArray tmp;
if (!waitForStarted(PLUGINPROCESS_START_TIMEOUT) || !readOnReady(tmp, PLUGINPROCESS_START_TIMEOUT))
return false;
}
return true;
}
} //namespace SignonDaemonNS
<commit_msg>Included common header.<commit_after>/*
* This file is part of signon
*
* Copyright (C) 2009-2010 Nokia Corporation.
*
* Contact: Alberto Mardegan <[email protected]>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "pluginproxy.h"
#include <sys/types.h>
#include <pwd.h>
#include <QStringList>
#include <QThreadStorage>
#include <QThread>
#include "signond-common.h"
#include "SignOn/uisessiondata_priv.h"
#include "SignOn/signonplugincommon.h"
/*
* TODO: remove the "SignOn/authpluginif.h" include below after the removal
* of the deprecated error handling (needed here only for the deprecated
* AuthPluginError::PLUGIN_ERROR_GENERAL).
*/
#include "SignOn/authpluginif.h"
using namespace SignOn;
//TODO get this from config
#define REMOTEPLUGIN_BIN_PATH QLatin1String("/usr/bin/signonpluginprocess")
#define PLUGINPROCESS_START_TIMEOUT 5000
#define PLUGINPROCESS_STOP_TIMEOUT 1000
namespace SignonDaemonNS {
PluginProcess::PluginProcess(QObject *parent) : QProcess(parent)
{
}
PluginProcess::~PluginProcess()
{
}
void PluginProcess::setupChildProcess()
{
// Drop all root privileges in the child process and switch to signon user
#ifndef NO_SIGNON_USER
//get uid and gid
struct passwd *passwdRecord = getpwnam("signon");
if ( !passwdRecord ){
fprintf(stderr, "failed to get user: signon\n");
emit QProcess::finished(2, QProcess::NormalExit);
exit(2);
}
#ifdef SIGNOND_TRACE
//this is run in remote plugin process, so trace should go to stderr
fprintf(stderr, "got user: %s with uid: %d\n", passwdRecord->pw_name, passwdRecord->pw_uid);
#endif
if (( ::setgid(passwdRecord->pw_gid))
|| (::setuid(passwdRecord->pw_uid))
|| (::getuid() != passwdRecord->pw_uid)
) {
fprintf(stderr, "failed to set user: %s with uid: %d", passwdRecord->pw_name, passwdRecord->pw_uid);
emit QProcess::finished(2, QProcess::NormalExit);
exit(2);
}
#endif
}
PluginProxy::PluginProxy(QString type, QObject *parent)
: QObject(parent)
{
TRACE();
m_type = type;
m_isProcessing = false;
m_process = new PluginProcess(this);
connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(onReadStandardError()));
/*
* TODO: some error handling should be added here, at least remove of current
* request data from the top of the queue and reply an error code
* */
connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onExit(int, QProcess::ExitStatus)));
connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onError(QProcess::ProcessError)));
}
PluginProxy::~PluginProxy()
{
if (m_process != NULL &&
m_process->state() != QProcess::NotRunning)
{
if (m_isProcessing)
cancel();
stop();
if (!m_process->waitForFinished(PLUGINPROCESS_STOP_TIMEOUT)) {
qCritical() << "The signon plugin does not react on demand to stop: need to kill it!!!";
m_process->kill();
if (!m_process->waitForFinished(PLUGINPROCESS_STOP_TIMEOUT))
{
if (m_process->pid()) {
qCritical() << "The signon plugin seems to ignore kill(), killing it from command line";
QString killProcessCommand(QString::fromLatin1("kill -9 %1").arg(m_process->pid()));
QProcess::execute(killProcessCommand);
}
}
}
}
}
PluginProxy* PluginProxy::createNewPluginProxy(const QString &type)
{
PluginProxy *pp = new PluginProxy(type);
QStringList args = QStringList() << pp->m_type;
pp->m_process->start(REMOTEPLUGIN_BIN_PATH, args);
QByteArray tmp;
if (!pp->waitForStarted(PLUGINPROCESS_START_TIMEOUT)) {
TRACE() << "The process cannot be started";
delete pp;
return NULL;
}
if (!pp->readOnReady(tmp, PLUGINPROCESS_START_TIMEOUT)) {
TRACE() << "The process cannot load plugin";
delete pp;
return NULL;
}
pp->m_type = pp->queryType();
pp->m_mechanisms = pp->queryMechanisms();
connect(pp->m_process, SIGNAL(readyReadStandardOutput()), pp, SLOT(onReadStandardOutput()));
TRACE() << "The process is started";
return pp;
}
bool PluginProxy::process(const QString &cancelKey, const QVariantMap &inData, const QString &mechanism)
{
TRACE();
if (!restartIfRequired())
return false;
m_cancelKey = cancelKey;
QVariant value = inData.value(SSOUI_KEY_UIPOLICY);
m_uiPolicy = value.toInt();
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_PROCESS;
in << QVariant(inData);
in << QVariant(mechanism);
m_isProcessing = true;
return true;
}
bool PluginProxy::processUi(const QString &cancelKey, const QVariantMap &inData)
{
TRACE() << inData;
if (!restartIfRequired())
return false;
m_cancelKey = cancelKey;
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_PROCESS_UI;
in << QVariant(inData);
m_isProcessing = true;
return true;
}
bool PluginProxy::processRefresh(const QString &cancelKey, const QVariantMap &inData)
{
TRACE() << inData;
if (!restartIfRequired())
return false;
m_cancelKey = cancelKey;
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_REFRESH;
in << QVariant(inData);
m_isProcessing = true;
return true;
}
void PluginProxy::cancel()
{
TRACE();
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_CANCEL;
}
void PluginProxy::stop()
{
TRACE();
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_STOP;
}
bool PluginProxy::readOnReady(QByteArray &buffer, int timeout)
{
bool ready = m_process->waitForReadyRead(timeout);
if (ready) {
if (!m_process->bytesAvailable())
return false;
while (m_process->bytesAvailable())
buffer += m_process->readAllStandardOutput();
}
return ready;
}
bool PluginProxy::isProcessing()
{
return m_isProcessing;
}
void PluginProxy::onReadStandardOutput()
{
disconnect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadStandardOutput()));
QByteArray token;
QVariant infoVa;
QVariantMap info;
if (!m_process->bytesAvailable()) {
qCritical() << "No information available on process";
m_isProcessing = false;
emit processError(m_cancelKey, Error::InternalServer, QString());
return;
}
QByteArray buffer;
while (m_process->bytesAvailable())
buffer += m_process->readAllStandardOutput();
/*
* we need to analyze the whole buffer
* and if it contains error then emit only error
* otherwise process/emit the incoming information
* one by one
* */
QDataStream out(buffer);
bool isResultObtained = false;
while (out.status() == QDataStream::Ok) {
quint32 opres;
out >> opres; //result of operation: error code
TRACE() << opres;
if (opres == PLUGIN_RESPONSE_RESULT) {
TRACE() << "PLUGIN_RESPONSE_RESULT";
out >> infoVa; //SessionData in QVariant
info = infoVa.toMap();
m_isProcessing = false;
if (!isResultObtained)
emit processResultReply(m_cancelKey, info);
else
BLAME() << "Unexpected plugin response: " << info;
isResultObtained = true;
} else if (opres == PLUGIN_RESPONSE_STORE) {
TRACE() << "PLUGIN_RESPONSE_STORE";
out >> infoVa; //SessionData in QVariant
info = infoVa.toMap();
if (!isResultObtained)
emit processStore(m_cancelKey, info);
else
BLAME() << "Unexpected plugin store: " << info;
} else if (opres == PLUGIN_RESPONSE_UI) {
TRACE() << "PLUGIN_RESPONSE_UI";
out >> infoVa; //UiSessionData in QVariant
info = infoVa.toMap();
if (!isResultObtained) {
bool allowed = true;
if (m_uiPolicy == NoUserInteractionPolicy)
allowed = false;
if (m_uiPolicy == ValidationPolicy) {
bool credentialsQueried =
(info.contains(SSOUI_KEY_QUERYUSERNAME)
|| info.contains(SSOUI_KEY_QUERYPASSWORD));
bool captchaQueried =
(info.contains(SSOUI_KEY_CAPTCHAIMG)
|| info.contains(SSOUI_KEY_CAPTCHAURL));
if (credentialsQueried && !captchaQueried)
allowed = false;
}
if (!allowed) {
//set error and return;
TRACE() << "ui policy prevented ui launch";
info.insert(SSOUI_KEY_ERROR, QUERY_ERROR_FORBIDDEN);
processUi(m_cancelKey, info);
} else {
TRACE() << "open ui";
emit processUiRequest(m_cancelKey, info);
}
} else {
BLAME() << "Unexpected plugin ui response: " << info;
}
} else if (opres == PLUGIN_RESPONSE_REFRESHED) {
TRACE() << "PLUGIN_RESPONSE_REFRESHED";
out >> infoVa; //UiSessionData in QVariant
info = infoVa.toMap();
if (!isResultObtained)
emit processRefreshRequest(m_cancelKey, info);
else
BLAME() << "Unexpected plugin ui response: " << info;
} else if (opres == PLUGIN_RESPONSE_ERROR) {
TRACE() << "PLUGIN_RESPONSE_ERROR";
quint32 err;
QString errorMessage;
out >> err;
out >> errorMessage;
m_isProcessing = false;
if (!isResultObtained)
emit processError(m_cancelKey, (int)err, errorMessage);
else
BLAME() << "Unexpected plugin error: " << errorMessage;
isResultObtained = true;
} else if (opres == PLUGIN_RESPONSE_SIGNAL) {
TRACE() << "PLUGIN_RESPONSE_SIGNAL";
quint32 state;
QString message;
out >> state;
out >> message;
if (!isResultObtained)
emit stateChanged(m_cancelKey, (int)state, message);
else
BLAME() << "Unexpected plugin signal: " << state << " " << message;
}
}
connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(onReadStandardOutput()));
}
void PluginProxy::onReadStandardError()
{
QString ba = QString::fromLatin1(m_process->readAllStandardError());
TRACE() << ba;
}
void PluginProxy::onExit(int exitCode, QProcess::ExitStatus exitStatus)
{
TRACE() << "Plugin process exit with code " << exitCode << " : " << exitStatus;
if (m_isProcessing || exitStatus == QProcess::CrashExit) {
qCritical() << "Challenge produces CRASH!";
emit processError(m_cancelKey, Error::InternalServer, QLatin1String("plugin processed crashed"));
}
if (exitCode == 2) {
TRACE() << "plugin process terminated because cannot change user";
}
m_isProcessing = false;
}
void PluginProxy::onError(QProcess::ProcessError err)
{
TRACE() << "Error: " << err;
}
QString PluginProxy::queryType()
{
TRACE();
if (!restartIfRequired())
return QString();
QDataStream ds(m_process);
ds << (quint32)PLUGIN_OP_TYPE;
QByteArray typeBa, buffer;
bool result;
if ((result = readOnReady(buffer, PLUGINPROCESS_START_TIMEOUT))) {
QDataStream out(buffer);
out >> typeBa;
} else
qCritical("PluginProxy returned NULL result");
return QString::fromLatin1(typeBa);
}
QStringList PluginProxy::queryMechanisms()
{
TRACE();
if (!restartIfRequired())
return QStringList();
QDataStream in(m_process);
in << (quint32)PLUGIN_OP_MECHANISMS;
QByteArray buffer;
QStringList strList;
bool result;
if ((result = readOnReady(buffer, PLUGINPROCESS_START_TIMEOUT))) {
QVariant mechanismsVar;
QDataStream out(buffer);
out >> mechanismsVar;
QVariantList varList = mechanismsVar.toList();
for (int i = 0; i < varList.count(); i++)
strList << varList.at(i).toString();
TRACE() << strList;
} else
qCritical("PluginProxy returned NULL result");
return strList;
}
bool PluginProxy::waitForStarted(int timeout)
{
return m_process->waitForStarted(timeout);
}
bool PluginProxy::waitForFinished(int timeout)
{
return m_process->waitForFinished(timeout);
}
bool PluginProxy::restartIfRequired()
{
if (m_process->state() == QProcess::NotRunning) {
TRACE() << "RESTART REQUIRED";
m_process->start(REMOTEPLUGIN_BIN_PATH, QStringList(m_type));
QByteArray tmp;
if (!waitForStarted(PLUGINPROCESS_START_TIMEOUT) || !readOnReady(tmp, PLUGINPROCESS_START_TIMEOUT))
return false;
}
return true;
}
} //namespace SignonDaemonNS
<|endoftext|> |
<commit_before>// RUN: cat %s | %cling -I%p | FileCheck %s
// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here
// PR #93092
// Don't remove the spaces and tabs
.L cling/Interpreter/Interpreter.h
.x ./DotXable.h(5)
// CHECK: 5
// End PR #93092
.X ./DotXable(10)
// CHECK: 10
<commit_msg>Add sane test case testing capital x.<commit_after>// RUN: cat %s | %cling -I%p | FileCheck %s
// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here
// PR #93092
// Don't remove the spaces and tabs
.L cling/Interpreter/Interpreter.h
.X ./DotXable.h(5)
// CHECK: 5
// End PR #93092
<|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 "sync/test/fake_server/fake_server_verifier.h"
#include "base/memory/scoped_ptr.h"
#include "base/values.h"
#include "sync/internal_api/public/base/model_type.h"
#include "sync/test/fake_server/fake_server.h"
#include "testing/gtest/include/gtest/gtest.h"
using std::string;
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;
namespace {
AssertionResult DictionaryCreationAssertionFailure() {
return AssertionFailure() << "FakeServer failed to create an entities "
<< "dictionary.";
}
AssertionResult VerificationCountAssertionFailure(size_t actual_count,
size_t expected_count) {
return AssertionFailure() << "Actual count: " << actual_count << "; "
<< "Expected count: " << expected_count;
}
AssertionResult UnknownTypeAssertionFailure(const string& model_type) {
return AssertionFailure() << "Verification not attempted. Unknown ModelType: "
<< model_type;
}
} // namespace
namespace fake_server {
FakeServerVerifier::FakeServerVerifier(FakeServer* fake_server)
: fake_server_(fake_server) { }
FakeServerVerifier::~FakeServerVerifier() {}
AssertionResult FakeServerVerifier::VerifyEntityCountByType(
size_t expected_count,
syncer::ModelType model_type) const {
scoped_ptr<base::DictionaryValue> entities =
fake_server_->GetEntitiesAsDictionaryValue();
if (!entities.get()) {
return DictionaryCreationAssertionFailure();
}
string model_type_string = ModelTypeToString(model_type);
base::ListValue* entity_list = NULL;
if (!entities->GetList(model_type_string, &entity_list)) {
return UnknownTypeAssertionFailure(model_type_string);
} else if (expected_count != entity_list->GetSize()) {
return VerificationCountAssertionFailure(entity_list->GetSize(),
expected_count);
}
return AssertionSuccess();
}
AssertionResult FakeServerVerifier::VerifyEntityCountByTypeAndName(
size_t expected_count,
syncer::ModelType model_type,
const string& name) const {
scoped_ptr<base::DictionaryValue> entities =
fake_server_->GetEntitiesAsDictionaryValue();
if (!entities.get()) {
return DictionaryCreationAssertionFailure();
}
string model_type_string = ModelTypeToString(model_type);
base::ListValue* entity_list = NULL;
size_t actual_count = 0;
if (entities->GetList(model_type_string, &entity_list)) {
scoped_ptr<base::Value> name_value(new base::StringValue(name));
for (base::ListValue::const_iterator it = entity_list->begin();
it != entity_list->end(); ++it) {
if (name_value->Equals(*it)) {
actual_count++;
}
}
}
if (!entity_list) {
return UnknownTypeAssertionFailure(model_type_string);
} else if (actual_count != expected_count) {
return VerificationCountAssertionFailure(actual_count, expected_count)
<< "; Name: " << name;
}
return AssertionSuccess();
}
} // namespace fake_server
<commit_msg>Sync: Print FakeServer contents on test failure<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 "sync/test/fake_server/fake_server_verifier.h"
#include "base/json/json_writer.h"
#include "base/memory/scoped_ptr.h"
#include "base/values.h"
#include "sync/internal_api/public/base/model_type.h"
#include "sync/test/fake_server/fake_server.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::JSONWriter;
using std::string;
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;
namespace {
AssertionResult DictionaryCreationAssertionFailure() {
return AssertionFailure() << "FakeServer failed to create an entities "
<< "dictionary.";
}
AssertionResult VerificationCountAssertionFailure(size_t actual_count,
size_t expected_count) {
return AssertionFailure() << "Actual count: " << actual_count << "; "
<< "Expected count: " << expected_count;
}
AssertionResult UnknownTypeAssertionFailure(const string& model_type) {
return AssertionFailure() << "Verification not attempted. Unknown ModelType: "
<< model_type;
}
// Caller maintains ownership of |entities|.
string ConvertFakeServerContentsToString(
const base::DictionaryValue& entities) {
string entities_str;
if (!JSONWriter::WriteWithOptions(&entities,
JSONWriter::OPTIONS_PRETTY_PRINT,
&entities_str)) {
entities_str = "Could not convert FakeServer contents to string.";
}
return "FakeServer contents:\n" + entities_str;
}
} // namespace
namespace fake_server {
FakeServerVerifier::FakeServerVerifier(FakeServer* fake_server)
: fake_server_(fake_server) { }
FakeServerVerifier::~FakeServerVerifier() {}
AssertionResult FakeServerVerifier::VerifyEntityCountByType(
size_t expected_count,
syncer::ModelType model_type) const {
scoped_ptr<base::DictionaryValue> entities =
fake_server_->GetEntitiesAsDictionaryValue();
if (!entities.get()) {
return DictionaryCreationAssertionFailure();
}
string model_type_string = ModelTypeToString(model_type);
base::ListValue* entity_list = NULL;
if (!entities->GetList(model_type_string, &entity_list)) {
return UnknownTypeAssertionFailure(model_type_string);
} else if (expected_count != entity_list->GetSize()) {
return VerificationCountAssertionFailure(entity_list->GetSize(),
expected_count)
<< "\n\n"
<< ConvertFakeServerContentsToString(*entities);
}
return AssertionSuccess();
}
AssertionResult FakeServerVerifier::VerifyEntityCountByTypeAndName(
size_t expected_count,
syncer::ModelType model_type,
const string& name) const {
scoped_ptr<base::DictionaryValue> entities =
fake_server_->GetEntitiesAsDictionaryValue();
if (!entities.get()) {
return DictionaryCreationAssertionFailure();
}
string model_type_string = ModelTypeToString(model_type);
base::ListValue* entity_list = NULL;
size_t actual_count = 0;
if (entities->GetList(model_type_string, &entity_list)) {
scoped_ptr<base::Value> name_value(new base::StringValue(name));
for (base::ListValue::const_iterator it = entity_list->begin();
it != entity_list->end(); ++it) {
if (name_value->Equals(*it)) {
actual_count++;
}
}
}
if (!entity_list) {
return UnknownTypeAssertionFailure(model_type_string);
} else if (actual_count != expected_count) {
return VerificationCountAssertionFailure(actual_count, expected_count)
<< "; Name: "
<< name
<< "\n\n"
<< ConvertFakeServerContentsToString(*entities);
}
return AssertionSuccess();
}
} // namespace fake_server
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//TESTED_COMPONENT=src/serviceframework
#include <QCoreApplication>
#include "qservicemanager.h"
#include "qservicefilter.h"
#include "service.h"
#include <QTimer>
#include <QMetaObject>
#include <QMetaMethod>
#include <QtTest/QtTest>
#include <qservice.h>
#include <qremoteserviceregister.h>
#include <QDebug>
#include <QByteArray>
#include <QDataStream>
#define QTRY_VERIFY(a) \
for (int _i = 0; _i < 5000; _i += 100) { \
if (a) break; \
QTest::qWait(100); \
} \
QVERIFY(a)
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QServiceFilter);
Q_DECLARE_METATYPE(QVariant);
Q_DECLARE_METATYPE(QList<QString>);
class tst_QServiceManager_IPC: public QObject
{
Q_OBJECT
public:
private slots:
void initTestCase();
void cleanupTestCase();
void checkCreateEntryWithEmptyServiceName();
void checkOperators();
void checkPublish();
private:
QRemoteServiceRegister* serviceRegister;
QRemoteServiceRegister::Entry uniqueEntry;
QRemoteServiceRegister::Entry uniqueEntry2;
};
bool mySecurityFilterFunction(const void *p)
{
const QRemoteServiceRegisterCredentials *cred = (const struct QRemoteServiceRegisterCredentials *)p;
// allow the superuser
if (cred->uid == 0)
return true;
return false;
}
void tst_QServiceManager_IPC::initTestCase()
{
qRegisterMetaType<QServiceFilter>("QServiceFilter");
qRegisterMetaTypeStreamOperators<QServiceFilter>("QServiceFilter");
qRegisterMetaType<QList<QString> >("QList<QString>");
qRegisterMetaTypeStreamOperators<QList<QString> >("QList<QString>");
serviceRegister = new QRemoteServiceRegister();
//Check setting of close on last instance
// serviceRegister->setQuitOnLastInstanceClosed(false);
// QVERIFY(serviceRegister->quitOnLastInstanceClosed() == false);
serviceRegister->setQuitOnLastInstanceClosed(true);
QVERIFY(serviceRegister->quitOnLastInstanceClosed() == true);
//check setting a security filter
serviceRegister->setSecurityFilter(mySecurityFilterFunction);
QServiceManager* manager = new QServiceManager(this);
// Symbian has auto registration
#ifndef Q_OS_SYMBIAN
const QString path = QCoreApplication::applicationDirPath() + "/xmldata/rsrexampleservice.xml";
bool r = manager->addService(path);
if (!r)
qWarning() << "Cannot register RSRExampleService" << path;
#endif
// D-Bus auto registration
#ifndef QT_NO_DBUS
const QString &file = QDir::homePath() + "/.local/share/dbus-1/services/" +
"com.nokia.qt.rsrunittest.service";
QFile data(file);
if (data.open(QFile::WriteOnly)) {
QTextStream out(&data);
out << "[D-BUS Service]\n"
<< "Name=com.nokia.qtmobility.sfw.RSRExampleService" << '\n'
<< "Exec=" << QFileInfo("./qt_sfw_example_rsr_unittest").absoluteFilePath();
data.close();
}
#endif
//register the unique service
uniqueEntry = serviceRegister->createEntry<QRemoteServiceRegisterService>(
"RSRExampleService", "com.nokia.qt.rsrunittest", "1.0");
bool valid = uniqueEntry.isValid();
QVERIFY(valid == true);
uniqueEntry2 = serviceRegister->createEntry<QRemoteServiceRegisterService>(
"RSRExampleService", "com.nokia.qt.rsrunittest", "1.0");
valid = uniqueEntry2.isValid();
QVERIFY(valid == true);
}
void tst_QServiceManager_IPC::cleanupTestCase()
{
#ifndef QT_NO_DBUS
const QString &file = QDir::homePath() + "/.local/share/dbus-1/services/" +
"com.nokia.qt.rsrunittest.service";
QFile::remove(file);
#endif
// clean up the unit, don't leave it registered
QServiceManager m;
m.removeService("RSRExampleService");
delete serviceRegister;
}
void tst_QServiceManager_IPC::checkCreateEntryWithEmptyServiceName()
{
QRemoteServiceRegister::Entry emptyservicename =
serviceRegister->createEntry<QRemoteServiceRegisterService>(
"", "", "");
QVERIFY(emptyservicename.serviceName() == "");
bool valid = emptyservicename.isValid();
QVERIFY(valid == false);
}
void tst_QServiceManager_IPC::checkOperators()
{
//== operator
bool equal = (uniqueEntry == uniqueEntry2 ? true : false);
QVERIFY(equal == true);
//!= operator
bool notequal = (uniqueEntry != uniqueEntry2 ? true : false);
QVERIFY(notequal == false);
//= operator
QRemoteServiceRegister::Entry assignval;
assignval = uniqueEntry;
equal = (assignval == uniqueEntry ? true : false);
QVERIFY(equal == true);
//QDataStream << >>
#ifndef QT_NO_DATASTREAM
QByteArray barray = QByteArray();
QDataStream streamOut(&barray, QIODevice::WriteOnly);
streamOut.setVersion(QDataStream::Qt_4_6);
streamOut << uniqueEntry;
QDataStream streamIn(&barray, QIODevice::ReadOnly);
streamOut.setVersion(QDataStream::Qt_4_6);
QRemoteServiceRegister::Entry streamedentry;
streamIn >> streamedentry;
QVERIFY(uniqueEntry.serviceName() == streamedentry.serviceName());
QVERIFY(uniqueEntry.interfaceName() == streamedentry.interfaceName());
QVERIFY(uniqueEntry.version() == streamedentry.version());
#endif
}
void tst_QServiceManager_IPC::checkPublish()
{
//publish the registered services
serviceRegister->publishEntries("qt_sfw_example_rsr_unittest");
//check instantiation type
//- default value
QRemoteServiceRegister::InstanceType type = uniqueEntry.instantiationType();
QRemoteServiceRegister::InstanceType type2 = uniqueEntry2.instantiationType();
QVERIFY(type == QRemoteServiceRegister::InstanceType::PrivateInstance);
QVERIFY(type2 == QRemoteServiceRegister::InstanceType::PrivateInstance);
//check setting the type
uniqueEntry2.setInstantiationType(QRemoteServiceRegister::InstanceType::GlobalInstance);
type2 = uniqueEntry2.instantiationType();
QVERIFY(type2 == QRemoteServiceRegister::InstanceType::GlobalInstance);
}
QTEST_MAIN(tst_QServiceManager_IPC);
#include "tst_qremoteserviceregister.moc"
<commit_msg>MOBILITY-2161 fix linux build.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//TESTED_COMPONENT=src/serviceframework
#include <QCoreApplication>
#include "qservicemanager.h"
#include "qservicefilter.h"
#include "service.h"
#include <QTimer>
#include <QMetaObject>
#include <QMetaMethod>
#include <QtTest/QtTest>
#include <qservice.h>
#include <qremoteserviceregister.h>
#include <QDebug>
#include <QByteArray>
#include <QDataStream>
#define QTRY_VERIFY(a) \
for (int _i = 0; _i < 5000; _i += 100) { \
if (a) break; \
QTest::qWait(100); \
} \
QVERIFY(a)
QTM_USE_NAMESPACE
Q_DECLARE_METATYPE(QServiceFilter);
Q_DECLARE_METATYPE(QVariant);
Q_DECLARE_METATYPE(QList<QString>);
class tst_QServiceManager_IPC: public QObject
{
Q_OBJECT
public:
private slots:
void initTestCase();
void cleanupTestCase();
void checkCreateEntryWithEmptyServiceName();
void checkOperators();
void checkPublish();
private:
QRemoteServiceRegister* serviceRegister;
QRemoteServiceRegister::Entry uniqueEntry;
QRemoteServiceRegister::Entry uniqueEntry2;
};
bool mySecurityFilterFunction(const void *p)
{
const QRemoteServiceRegisterCredentials *cred = (const struct QRemoteServiceRegisterCredentials *)p;
// allow the superuser
if (cred->uid == 0)
return true;
return false;
}
void tst_QServiceManager_IPC::initTestCase()
{
qRegisterMetaType<QServiceFilter>("QServiceFilter");
qRegisterMetaTypeStreamOperators<QServiceFilter>("QServiceFilter");
qRegisterMetaType<QList<QString> >("QList<QString>");
qRegisterMetaTypeStreamOperators<QList<QString> >("QList<QString>");
serviceRegister = new QRemoteServiceRegister();
//Check setting of close on last instance
// serviceRegister->setQuitOnLastInstanceClosed(false);
// QVERIFY(serviceRegister->quitOnLastInstanceClosed() == false);
serviceRegister->setQuitOnLastInstanceClosed(true);
QVERIFY(serviceRegister->quitOnLastInstanceClosed() == true);
//check setting a security filter
serviceRegister->setSecurityFilter(mySecurityFilterFunction);
QServiceManager* manager = new QServiceManager(this);
// Symbian has auto registration
#ifndef Q_OS_SYMBIAN
const QString path = QCoreApplication::applicationDirPath() + "/xmldata/rsrexampleservice.xml";
bool r = manager->addService(path);
if (!r)
qWarning() << "Cannot register RSRExampleService" << path;
#endif
// D-Bus auto registration
#ifndef QT_NO_DBUS
const QString &file = QDir::homePath() + "/.local/share/dbus-1/services/" +
"com.nokia.qt.rsrunittest.service";
QFile data(file);
if (data.open(QFile::WriteOnly)) {
QTextStream out(&data);
out << "[D-BUS Service]\n"
<< "Name=com.nokia.qtmobility.sfw.RSRExampleService" << '\n'
<< "Exec=" << QFileInfo("./qt_sfw_example_rsr_unittest").absoluteFilePath();
data.close();
}
#endif
//register the unique service
uniqueEntry = serviceRegister->createEntry<QRemoteServiceRegisterService>(
"RSRExampleService", "com.nokia.qt.rsrunittest", "1.0");
bool valid = uniqueEntry.isValid();
QVERIFY(valid == true);
uniqueEntry2 = serviceRegister->createEntry<QRemoteServiceRegisterService>(
"RSRExampleService", "com.nokia.qt.rsrunittest", "1.0");
valid = uniqueEntry2.isValid();
QVERIFY(valid == true);
}
void tst_QServiceManager_IPC::cleanupTestCase()
{
#ifndef QT_NO_DBUS
const QString &file = QDir::homePath() + "/.local/share/dbus-1/services/" +
"com.nokia.qt.rsrunittest.service";
QFile::remove(file);
#endif
// clean up the unit, don't leave it registered
QServiceManager m;
m.removeService("RSRExampleService");
delete serviceRegister;
}
void tst_QServiceManager_IPC::checkCreateEntryWithEmptyServiceName()
{
QRemoteServiceRegister::Entry emptyservicename =
serviceRegister->createEntry<QRemoteServiceRegisterService>(
"", "", "");
QVERIFY(emptyservicename.serviceName() == "");
bool valid = emptyservicename.isValid();
QVERIFY(valid == false);
}
void tst_QServiceManager_IPC::checkOperators()
{
//== operator
bool equal = (uniqueEntry == uniqueEntry2 ? true : false);
QVERIFY(equal == true);
//!= operator
bool notequal = (uniqueEntry != uniqueEntry2 ? true : false);
QVERIFY(notequal == false);
//= operator
QRemoteServiceRegister::Entry assignval;
assignval = uniqueEntry;
equal = (assignval == uniqueEntry ? true : false);
QVERIFY(equal == true);
//QDataStream << >>
#ifndef QT_NO_DATASTREAM
QByteArray barray = QByteArray();
QDataStream streamOut(&barray, QIODevice::WriteOnly);
streamOut.setVersion(QDataStream::Qt_4_6);
streamOut << uniqueEntry;
QDataStream streamIn(&barray, QIODevice::ReadOnly);
streamOut.setVersion(QDataStream::Qt_4_6);
QRemoteServiceRegister::Entry streamedentry;
streamIn >> streamedentry;
QVERIFY(uniqueEntry.serviceName() == streamedentry.serviceName());
QVERIFY(uniqueEntry.interfaceName() == streamedentry.interfaceName());
QVERIFY(uniqueEntry.version() == streamedentry.version());
#endif
}
void tst_QServiceManager_IPC::checkPublish()
{
//publish the registered services
serviceRegister->publishEntries("qt_sfw_example_rsr_unittest");
//check instantiation type
//- default value
QRemoteServiceRegister::InstanceType type = uniqueEntry.instantiationType();
QRemoteServiceRegister::InstanceType type2 = uniqueEntry2.instantiationType();
QVERIFY(type == QRemoteServiceRegister::PrivateInstance);
QVERIFY(type2 == QRemoteServiceRegister::PrivateInstance);
//check setting the type
uniqueEntry2.setInstantiationType(QRemoteServiceRegister::GlobalInstance);
type2 = uniqueEntry2.instantiationType();
QVERIFY(type2 == QRemoteServiceRegister::GlobalInstance);
}
QTEST_MAIN(tst_QServiceManager_IPC);
#include "tst_qremoteserviceregister.moc"
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QDebug>
#include <QDir>
#include <QStringList>
#include <QFile>
#include <QTextStream>
#include <QDomDocument>
#include <QDomNode>
#include <QDomNodeList>
QString makeTable(QHash<QString, QStringList> &results, QString fileName,
QString testName1, QString testName2)
{
if(results[fileName+testName1].count()<2 || results[fileName+testName2].count()<2)
return QString("No valid data<br>");
int test1Total = results[fileName+testName1].at(2).toInt();
int test2Total = results[fileName+testName2].at(2).toInt();
int fasterTime, slowerTime;
if(test1Total<test2Total)
{
fasterTime=test1Total;
slowerTime=test2Total;
}
else
{
fasterTime=test2Total;
slowerTime=test1Total;
}
bool isFirstFaster=(test1Total < test2Total ? true:false);
QString table("<table style=\"border: 1px solid blue;\"><tr><td style=\"width:80px;\"></td>"
"<td class=\"%1\">%3</td><td class=\"%2\">%4</td></tr><tr><td>median<br>mean<br>total</td>"
"<td class=\"%1\">%5</td><td class=\"%2\">%6</td><td class=\"w\">%7 is faster by <b>%8%</b></td>"
"</tr></table><br />");
return table.arg(QString(isFirstFaster?"g":"w")).arg(QString((isFirstFaster?"w":"g"))).
arg(testName1).arg(testName2).arg(results[fileName+testName1].join("<br>")).
arg(results[fileName+testName2].join("<br>")).arg((isFirstFaster?testName1:testName2)).
arg(((slowerTime-fasterTime)*100)/slowerTime);
}
QString makeTableCombined(QHash<QString, QStringList> &results, QString fileName,
QStringList testNames1, QStringList testNames2)
{
for(int i=0; i<testNames1.count(); i++)
if(results[fileName+testNames1[i]].count()<2)
return QString("No valid data<br>");
int test1Total = 0;
for(int i=0; i<testNames1.count(); i++)
test1Total+= results[fileName+testNames1[i]].at(2).toInt();
int test2Total = 0;
for(int i=0; i<testNames2.count(); i++)
test2Total+= results[fileName+testNames2[i]].at(2).toInt();
int fasterTime, slowerTime;
if(test1Total<test2Total)
{
fasterTime=test1Total;
slowerTime=test2Total;
}
else
{
fasterTime=test2Total;
slowerTime=test1Total;
}
bool isFirstFaster=(test1Total < test2Total ? true:false);
QString table("<table style=\"border: 1px solid blue;\"><tr><td style=\"width:80px;\"></td>"
"<td class=\"%1\">%3</td><td class=\"%2\">%4</td></tr><tr><td>total</td>"
"<td class=\"%1\">%5</td><td class=\"%2\">%6</td><td class=\"w\">%7 is faster by <b>%8%</b>"
"</td></tr></table><br />");
return table.arg(QString(isFirstFaster?"g":"w")).arg((isFirstFaster?"w":"g")).arg(testNames1.join(" + ")).
arg(testNames2.join(" + ")).arg(test1Total).arg(test2Total).arg((isFirstFaster?testNames1:testNames2)
.join(" + ")).arg(((slowerTime-fasterTime)*100)/slowerTime);
}
int main(int argc, char *argv[])
{
Q_UNUSED(argc);
Q_UNUSED(argv);
QString dirPath = QDir::homePath() + QDir::separator();
QDir myDir(dirPath);
QStringList fileList = myDir.entryList(QStringList() << "benchmark-*.xml");
QString pageOutput;
pageOutput = "<html>"
"<head>"
"<title>Benchmark result comparison</title>"
"</head>"
"<style>body, table {font-size:12px;}"
"td.row1{ background-color:#FFFFFF;}"
"td.row2{ background-color:#E8E8E8;}"
"sup.t1{color:red;}"
"sup.t2{color:green;}"
".b{color:#006699;}"
".o{color:#CC6633;}"
"td.g{background-color:#99FF66; width:250px;}"
"td.w{background-color:#FFFFFF; width:250px;}"
"</style>"
"<body><h1>Report generated by Benchmark Comparison Tool (part of QSparql test library)</h1>";
QHash<QString, QStringList> results;
QHash<QString, QString> tracker_ver;
QHash<QString, QString> qsparql_ver;
QStringList testNames;
QString pageOutput2(pageOutput);
//lets iterate through files, read them and parse
for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
{
QString filename(dirPath+fileList.at(dirIterator));
QDomDocument doc("xmlResult");
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
{
qDebug() << "Couldn't open file "<< filename;
pageOutput.append("Error: Couldn't open file "+filename);
}
else
if (!doc.setContent(&file)) {
file.close();
qDebug() << "Couldn't set file content for QDomDocument "<< filename;
pageOutput.append("Couldn't set file content for QDomDocument "+filename);
}
else
{
file.close();
QDomNode asset = doc.elementsByTagName("benchmark").at(0).firstChild();
QDomNode assetIterator = asset.firstChild();
QString tracker, qsparql, created;
for(QDomNode assetIterator = asset.firstChild(); !assetIterator.isNull();
assetIterator = assetIterator.nextSibling())
{
QString tagName = assetIterator.toElement().tagName();
if(tagName == "tracker")
tracker = assetIterator.toElement().text();
else if(tagName == "qsparql")
qsparql = assetIterator.toElement().text();
else if(tagName == "created")
created = assetIterator.toElement().text();
}
//QString description = assetIterator.toElement().text();
tracker_ver[fileList.at(dirIterator)]=tracker;
qsparql_ver[fileList.at(dirIterator)]=qsparql;
QDomNodeList testList = doc.elementsByTagName("benchmark").at(0).lastChild().
toElement().elementsByTagName("test");
for(int i=0; i< testList.count(); i++)
{
QString name = testList.at(i).toElement().attribute("name");
if(!testNames.contains(name))
testNames << name;
QDomNode median = testList.at(i).toElement().firstChild();
QString medianValue = median.toElement().attribute("value");
QDomNode mean = median.nextSibling();
QString meanValue = mean.toElement().attribute("value");
QDomNode total = mean.nextSibling();
QString totalValue = total.toElement().attribute("value");
QStringList runResults;
runResults << medianValue << meanValue << totalValue;
results[fileList.at(dirIterator)+name] = runResults;
}
}
}
//overall comparison html page
pageOutput.append("<br /><table><tr><td>Test name</td>");
for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
{
QStringList nameparts = fileList.at(dirIterator).split(".");
pageOutput.append("<td>" + nameparts[0] + "<br>" +nameparts[1] + "<br><span class=\"b\">"+
qsparql_ver[fileList.at(dirIterator)]+"</span><br>"+
"<span class=\"o\">"+tracker_ver[fileList.at(dirIterator)]+"</span>" +
"<br /><a href=\"tests-comparison.html#" + nameparts[0]+ "." + nameparts[1] +
"\">tests comaprison</a></td>");
}
pageOutput.append("</tr>\n");
QStringList previousResult;
for(int testIterator=0; testIterator < testNames.count(); testIterator++)
{
previousResult.clear();
pageOutput.append(QString("<tr><td class=\"row%1").arg(testIterator%2+1)+
"\" style=\"width:230px;\"><b>"+testNames[testIterator].remove(".xml")+
"</b><br /><small>median<br />mean<br />total</small></td>");
for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
{
pageOutput.append("<td class=\"row"+QString("%1").arg(testIterator%2+1)+"\">");
for(int partResultIterator=0; partResultIterator < results[fileList.at(dirIterator)+
testNames[testIterator]].count(); partResultIterator++)
{
int currentValue=results[fileList.at(dirIterator)+testNames[testIterator]].
at(partResultIterator).toInt();
pageOutput.append(QString("%1").arg(currentValue));
if(previousResult.count() == results[fileList.at(dirIterator)+
testNames[testIterator]].count() && previousResult.count()-1 == partResultIterator)
{
int previousValue=previousResult[partResultIterator].toInt();
int diff = (previousValue?(((previousValue-currentValue)*100)/previousValue):100);
pageOutput.append(QString(" <sup class=\"t%2\">%1%</sup>").arg(diff*-1).
arg(diff<0?"1":"2"));
}
pageOutput.append("<br />");
}
pageOutput.append("</td>\n");
previousResult = results[fileList.at(dirIterator)+testNames[testIterator]];
}
pageOutput.append("</tr>\n\n");
}
pageOutput.append("</tr></table>");
pageOutput.append("</body></html>");
//between-tests-comparison html page
pageOutput2.append("<h2>In-between tests comaprison</h2><a href=\"index.html\">Back to the mainpage</a><br><br>");
for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
{
QStringList nameparts = fileList.at(dirIterator).split(".");
pageOutput2.append("<br /><a name=\"" + nameparts[0]+ "." + nameparts[1] + "\"></a>" +
"<hr><h4>"+ nameparts[0]+ "." + nameparts[1] +"</h4>" + "<span class=\"b\">"+
qsparql_ver[fileList.at(dirIterator)]+"</span><br>"+
"<span class=\"o\">"+tracker_ver[fileList.at(dirIterator)]+"</span><br /><br />" +
makeTable(results, fileList.at(dirIterator), "read-music-Async-fin", "read-music-Sync-fin")+
makeTable(results, fileList.at(dirIterator), "read-music-Async-read", "read-music-Sync-read")+
makeTable(results, fileList.at(dirIterator), "read-music-Async-ForwardOnly-fin", "read-music-Async-fin")+
makeTable(results, fileList.at(dirIterator), "read-music-Async-ForwardOnly-read", "read-music-Async-read")+
makeTableCombined(results, fileList.at(dirIterator), QStringList() << "read-music-Async-fin"
<< "read-music-Async-read", QStringList() << "read-music-Sync-fin" << "read-music-Sync-read")+
makeTableCombined(results, fileList.at(dirIterator), QStringList() << "read-music-Async-fin"
<< "read-music-Async-read", QStringList() << "read-music-Async-ForwardOnly-fin"
<< "read-music-Async-ForwardOnly-read"));
}
pageOutput2.append("</body></html>");
QFile data(dirPath+"index.html");
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&data);
out << pageOutput;
qDebug() << "Report saved in " << dirPath;
data.close();
}
else
qDebug() << "Couldn't save report in " << dirPath << "Check writing permissions!";
data.setFileName(dirPath+"tests-comparison.html");
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&data);
out << pageOutput2;
qDebug() << "Report saved in " << dirPath;
}
else
qDebug() << "Couldn't save report in " << dirPath << "Check writing permissions!";
return 0;
}<commit_msg>Fix for crash when generating comparison report with old xml format<commit_after>/****************************************************************************
**
** Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QDebug>
#include <QDir>
#include <QStringList>
#include <QFile>
#include <QTextStream>
#include <QDomDocument>
#include <QDomNode>
#include <QDomNodeList>
QString makeTable(QHash<QString, QStringList> &results, QString fileName,
QString testName1, QString testName2)
{
if(results[fileName+testName1].count()<2 || results[fileName+testName2].count()<2)
return QString("No valid data<br>");
int test1Total = results[fileName+testName1].at(2).toInt();
int test2Total = results[fileName+testName2].at(2).toInt();
int fasterTime, slowerTime;
if(test1Total<test2Total)
{
fasterTime=test1Total;
slowerTime=test2Total;
}
else
{
fasterTime=test2Total;
slowerTime=test1Total;
}
bool isFirstFaster=(test1Total < test2Total ? true:false);
QString table("<table style=\"border: 1px solid blue;\"><tr><td style=\"width:80px;\"></td>"
"<td class=\"%1\">%3</td><td class=\"%2\">%4</td></tr><tr><td>median<br>mean<br>total</td>"
"<td class=\"%1\">%5</td><td class=\"%2\">%6</td><td class=\"w\">%7 is faster by <b>%8%</b></td>"
"</tr></table><br />");
return table.arg(QString(isFirstFaster?"g":"w")).arg(QString((isFirstFaster?"w":"g"))).
arg(testName1).arg(testName2).arg(results[fileName+testName1].join("<br>")).
arg(results[fileName+testName2].join("<br>")).arg((isFirstFaster?testName1:testName2)).
arg(((slowerTime-fasterTime)*100)/slowerTime);
}
QString makeTableCombined(QHash<QString, QStringList> &results, QString fileName,
QStringList testNames1, QStringList testNames2)
{
for(int i=0; i<testNames1.count(); i++)
if(results[fileName+testNames1[i]].count()<2 || results[fileName+testNames2[i]].count()<2)
return QString("No valid data<br>");
int test1Total = 0;
for(int i=0; i<testNames1.count(); i++)
test1Total+= results[fileName+testNames1[i]].at(2).toInt();
int test2Total = 0;
for(int i=0; i<testNames2.count(); i++)
test2Total+= results[fileName+testNames2[i]].at(2).toInt();
int fasterTime, slowerTime;
if(test1Total<test2Total)
{
fasterTime=test1Total;
slowerTime=test2Total;
}
else
{
fasterTime=test2Total;
slowerTime=test1Total;
}
bool isFirstFaster=(test1Total < test2Total ? true:false);
QString table("<table style=\"border: 1px solid blue;\"><tr><td style=\"width:80px;\"></td>"
"<td class=\"%1\">%3</td><td class=\"%2\">%4</td></tr><tr><td>total</td>"
"<td class=\"%1\">%5</td><td class=\"%2\">%6</td><td class=\"w\">%7 is faster by <b>%8%</b>"
"</td></tr></table><br />");
return table.arg(QString(isFirstFaster?"g":"w")).arg((isFirstFaster?"w":"g")).arg(testNames1.join(" + ")).
arg(testNames2.join(" + ")).arg(test1Total).arg(test2Total).arg((isFirstFaster?testNames1:testNames2)
.join(" + ")).arg(((slowerTime-fasterTime)*100)/slowerTime);
}
int main(int argc, char *argv[])
{
Q_UNUSED(argc);
Q_UNUSED(argv);
QString dirPath = QDir::homePath() + QDir::separator();
QDir myDir(dirPath);
QStringList fileList = myDir.entryList(QStringList() << "benchmark-*.xml");
QString pageOutput;
pageOutput = "<html>"
"<head>"
"<title>Benchmark result comparison</title>"
"</head>"
"<style>body, table {font-size:12px;}"
"td.row1{ background-color:#FFFFFF;}"
"td.row2{ background-color:#E8E8E8;}"
"sup.t1{color:red;}"
"sup.t2{color:green;}"
".b{color:#006699;}"
".o{color:#CC6633;}"
"td.g{background-color:#99FF66; width:250px;}"
"td.w{background-color:#FFFFFF; width:250px;}"
"</style>"
"<body><h1>Report generated by Benchmark Comparison Tool (part of QSparql test library)</h1>";
QHash<QString, QStringList> results;
QHash<QString, QString> tracker_ver;
QHash<QString, QString> qsparql_ver;
QStringList testNames;
QString pageOutput2(pageOutput);
//lets iterate through files, read them and parse
for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
{
QString filename(dirPath+fileList.at(dirIterator));
QDomDocument doc("xmlResult");
QFile file(filename);
if (!file.open(QIODevice::ReadOnly))
{
qDebug() << "Couldn't open file "<< filename;
pageOutput.append("Error: Couldn't open file "+filename);
}
else
if (!doc.setContent(&file)) {
file.close();
qDebug() << "Couldn't set file content for QDomDocument "<< filename;
pageOutput.append("Couldn't set file content for QDomDocument "+filename);
}
else
{
file.close();
QDomNode asset = doc.elementsByTagName("benchmark").at(0).firstChild();
QDomNode assetIterator = asset.firstChild();
QString tracker, qsparql, created;
for(QDomNode assetIterator = asset.firstChild(); !assetIterator.isNull();
assetIterator = assetIterator.nextSibling())
{
QString tagName = assetIterator.toElement().tagName();
if(tagName == "tracker")
tracker = assetIterator.toElement().text();
else if(tagName == "qsparql")
qsparql = assetIterator.toElement().text();
else if(tagName == "created")
created = assetIterator.toElement().text();
}
//QString description = assetIterator.toElement().text();
tracker_ver[fileList.at(dirIterator)]=tracker;
qsparql_ver[fileList.at(dirIterator)]=qsparql;
QDomNodeList testList = doc.elementsByTagName("benchmark").at(0).lastChild().
toElement().elementsByTagName("test");
for(int i=0; i< testList.count(); i++)
{
QString name = testList.at(i).toElement().attribute("name");
if(!testNames.contains(name))
testNames << name;
QDomNode median = testList.at(i).toElement().firstChild();
QString medianValue = median.toElement().attribute("value");
QDomNode mean = median.nextSibling();
QString meanValue = mean.toElement().attribute("value");
QDomNode total = mean.nextSibling();
QString totalValue = total.toElement().attribute("value");
QStringList runResults;
runResults << medianValue << meanValue << totalValue;
results[fileList.at(dirIterator)+name] = runResults;
}
}
}
//overall comparison html page
pageOutput.append("<br /><table><tr><td>Test name</td>");
for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
{
QStringList nameparts = fileList.at(dirIterator).split(".");
pageOutput.append("<td>" + nameparts[0] + "<br>" +nameparts[1] + "<br><span class=\"b\">"+
qsparql_ver[fileList.at(dirIterator)]+"</span><br>"+
"<span class=\"o\">"+tracker_ver[fileList.at(dirIterator)]+"</span>" +
"<br /><a href=\"tests-comparison.html#" + nameparts[0]+ "." + nameparts[1] +
"\">tests comaprison</a></td>");
}
pageOutput.append("</tr>\n");
QStringList previousResult;
for(int testIterator=0; testIterator < testNames.count(); testIterator++)
{
previousResult.clear();
pageOutput.append(QString("<tr><td class=\"row%1").arg(testIterator%2+1)+
"\" style=\"width:230px;\"><b>"+testNames[testIterator].remove(".xml")+
"</b><br /><small>median<br />mean<br />total</small></td>");
for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
{
pageOutput.append("<td class=\"row"+QString("%1").arg(testIterator%2+1)+"\">");
for(int partResultIterator=0; partResultIterator < results[fileList.at(dirIterator)+
testNames[testIterator]].count(); partResultIterator++)
{
int currentValue=results[fileList.at(dirIterator)+testNames[testIterator]].
at(partResultIterator).toInt();
pageOutput.append(QString("%1").arg(currentValue));
if(previousResult.count() == results[fileList.at(dirIterator)+
testNames[testIterator]].count() && previousResult.count()-1 == partResultIterator)
{
int previousValue=previousResult[partResultIterator].toInt();
int diff = (previousValue?(((previousValue-currentValue)*100)/previousValue):100);
pageOutput.append(QString(" <sup class=\"t%2\">%1%</sup>").arg(diff*-1).
arg(diff<0?"1":"2"));
}
pageOutput.append("<br />");
}
pageOutput.append("</td>\n");
previousResult = results[fileList.at(dirIterator)+testNames[testIterator]];
}
pageOutput.append("</tr>\n\n");
}
pageOutput.append("</tr></table>");
pageOutput.append("</body></html>");
//between-tests-comparison html page
pageOutput2.append("<h2>In-between tests comaprison</h2><a href=\"index.html\">Back to the mainpage</a><br><br>");
for(int dirIterator=0; dirIterator < fileList.count(); dirIterator++)
{
QStringList nameparts = fileList.at(dirIterator).split(".");
pageOutput2.append("<br /><a name=\"" + nameparts[0]+ "." + nameparts[1] + "\"></a>" +
"<hr><h4>"+ nameparts[0]+ "." + nameparts[1] +"</h4>" + "<span class=\"b\">"+
qsparql_ver[fileList.at(dirIterator)]+"</span><br>"+
"<span class=\"o\">"+tracker_ver[fileList.at(dirIterator)]+"</span><br /><br />" +
makeTable(results, fileList.at(dirIterator), "read-music-Async-fin", "read-music-Sync-fin")+
makeTable(results, fileList.at(dirIterator), "read-music-Async-read", "read-music-Sync-read")+
makeTable(results, fileList.at(dirIterator), "read-music-Async-ForwardOnly-fin", "read-music-Async-fin")+
makeTable(results, fileList.at(dirIterator), "read-music-Async-ForwardOnly-read", "read-music-Async-read")+
makeTableCombined(results, fileList.at(dirIterator), QStringList() << "read-music-Async-fin"
<< "read-music-Async-read", QStringList() << "read-music-Sync-fin" << "read-music-Sync-read")+
makeTableCombined(results, fileList.at(dirIterator), QStringList() << "read-music-Async-fin"
<< "read-music-Async-read", QStringList() << "read-music-Async-ForwardOnly-fin"
<< "read-music-Async-ForwardOnly-read"));
}
pageOutput2.append("</body></html>");
QFile data(dirPath+"index.html");
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&data);
out << pageOutput;
qDebug() << "Report saved in " << dirPath;
data.close();
}
else
qDebug() << "Couldn't save report in " << dirPath << "Check writing permissions!";
data.setFileName(dirPath+"tests-comparison.html");
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&data);
out << pageOutput2;
qDebug() << "Report saved in " << dirPath;
}
else
qDebug() << "Couldn't save report in " << dirPath << "Check writing permissions!";
return 0;
}<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (c) FFLAS-FFPACK
* Written by Clement Pernet <[email protected]>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
#define __FFLASFFPACK_FORCE_SEQ
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"
using namespace std;
int main(int argc, char** argv) {
size_t iter = 1;
size_t n = 500;
std::string file = "";
static int variant =0;
size_t b = 150;
Argument as[] = {
{ 'b', "-b B", "Set the bitsize of the random characteristic.", TYPE_INT , &b },
{ 'n', "-n N", "Set the dimension of the matrix.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'f', "-f FILE", "Set the input file (empty for random).", TYPE_STR , &file },
{ 'a', "-a algorithm", "Set the algorithmic variant", TYPE_INT, &variant },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
typedef Givaro::ZRing<Givaro::Integer> Field;
FFPACK::FFPACK_CHARPOLY_TAG CT;
switch (variant){
case 0: CT = FFPACK::FfpackAuto; break;
case 1: CT = FFPACK::FfpackLUK; break;
case 2: CT = FFPACK::FfpackDanilevski; break;
case 3: CT = FFPACK::FfpackArithProg; break;
case 4: CT = FFPACK::FfpackKG; break;
case 5: CT = FFPACK::FfpackKGFast; break;
case 6: CT = FFPACK::FfpackHybrid; break;
case 7: CT = FFPACK::FfpackKGFastG; break;
default: CT = FFPACK::FfpackAuto; break;
}
typedef Field::Element Element;
Field F;
FFLAS::Timer chrono;
double time=0.0;
Element *A;
size_t bs=1;
size_t size=b;
for (size_t i=0;i<iter;++i){
if (!file.empty()){
A = read_field (F, file.c_str(), &n, &n);
}
else{
A = FFLAS::fflas_new<Element>(n*n);
Field::RandIter G(F,size);
for (size_t j=0; j< (size_t)n*n; ++j)
G.random(*(A+j));
}
typedef Givaro::Poly1Dom<Field> PolRing;
PolRing R(F);
PolRing::Element cpol;
chrono.clear();
chrono.start();
FFPACK::CharPoly (R, cpol, n, A, n, CT);
chrono.stop();
time+=chrono.usertime();
bs = FFLAS::bitsize (F,n,n,A,n);
FFLAS::fflas_delete( A);
}
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
std::cerr << "n: "<<n<<" bitsize: "<<bs<<" Time: " << time / double(iter)
<< " Gflops: " << (2.*double(n)/1000.*double(n)/1000.*double(n)/1000.0) / time * double(iter);
FFLAS::writeCommandString(std::cerr, as) << std::endl;
return 0;
}
<commit_msg>smaller default bench<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/* Copyright (c) FFLAS-FFPACK
* Written by Clement Pernet <[email protected]>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*/
#define __FFLASFFPACK_FORCE_SEQ
#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"
using namespace std;
int main(int argc, char** argv) {
size_t iter = 1;
size_t n = 100;
std::string file = "";
static int variant =0;
size_t b = 150;
Argument as[] = {
{ 'b', "-b B", "Set the bitsize of the random characteristic.", TYPE_INT , &b },
{ 'n', "-n N", "Set the dimension of the matrix.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 'f', "-f FILE", "Set the input file (empty for random).", TYPE_STR , &file },
{ 'a', "-a algorithm", "Set the algorithmic variant", TYPE_INT, &variant },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
typedef Givaro::ZRing<Givaro::Integer> Field;
FFPACK::FFPACK_CHARPOLY_TAG CT;
switch (variant){
case 0: CT = FFPACK::FfpackAuto; break;
case 1: CT = FFPACK::FfpackLUK; break;
case 2: CT = FFPACK::FfpackDanilevski; break;
case 3: CT = FFPACK::FfpackArithProg; break;
case 4: CT = FFPACK::FfpackKG; break;
case 5: CT = FFPACK::FfpackKGFast; break;
case 6: CT = FFPACK::FfpackHybrid; break;
case 7: CT = FFPACK::FfpackKGFastG; break;
default: CT = FFPACK::FfpackAuto; break;
}
typedef Field::Element Element;
Field F;
FFLAS::Timer chrono;
double time=0.0;
Element *A;
size_t bs=1;
size_t size=b;
for (size_t i=0;i<iter;++i){
if (!file.empty()){
A = read_field (F, file.c_str(), &n, &n);
}
else{
A = FFLAS::fflas_new<Element>(n*n);
Field::RandIter G(F,size);
for (size_t j=0; j< (size_t)n*n; ++j)
G.random(*(A+j));
}
typedef Givaro::Poly1Dom<Field> PolRing;
PolRing R(F);
PolRing::Element cpol;
chrono.clear();
chrono.start();
FFPACK::CharPoly (R, cpol, n, A, n, CT);
chrono.stop();
time+=chrono.usertime();
bs = FFLAS::bitsize (F,n,n,A,n);
FFLAS::fflas_delete( A);
}
// -----------
// Standard output for benchmark - Alexis Breust 2014/11/14
std::cerr << "n: "<<n<<" bitsize: "<<bs<<" Time: " << time / double(iter)
<< " Gflops: " << (2.*double(n)/1000.*double(n)/1000.*double(n)/1000.0) / time * double(iter);
FFLAS::writeCommandString(std::cerr, as) << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h> /* ROS */
#include <geometry_msgs/Twist.h> /* ROS Twist message */
#include <base_controller/encoders.h> /* Custom message /encoders */
#include <base_controller/md49data.h> /* Custom message /encoders */
#include <serialport/serialport.h>
#define REPLY_SIZE 18
#define TIMEOUT 1000
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
char reply[REPLY_SIZE];
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4; /* Base width in meters */
//unsigned char serialBuffer[18]; /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
using namespace std;
cereal::CerealPort device;
base_controller::encoders encoders;
base_controller::md49data md49data;
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
if (vel_cmd.linear.x>0){
speed_l = 255;
speed_r = 255;
}
if (vel_cmd.linear.x<0){
speed_l = 0;
speed_r = 0;
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
speed_l = 128;
speed_r = 128;
}
if (vel_cmd.angular.z>0){
speed_l = 0;
speed_r = 255;
}
if (vel_cmd.angular.z<0){
speed_l = 255;
speed_r = 0;
}
if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
//set_MD49_speed(speed_l,speed_r);
last_speed_l=speed_l;
last_speed_r=speed_r;
}
/*
//ANFANG Alternative
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
else if(vel_cmd.linear.x == 0){
// turning
vr = vel_cmd.angular.z * base_width / 2.0;
vl = (-1) * vr;
}
else if(vel_cmd.angular.z == 0){
// forward / backward
vl = vr = vel_cmd.linear.x;
}
else{
// moving doing arcs
vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
if (vl > max_vl) {vl=max_vl;}
if (vl < min_vl) {vl=min_vl;}
vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
if (vr > max_vr) {vr=max_vr;}
if (vr < min_vr) {vr=min_vr;}
}
//ENDE Alternative
*/
}
int main( int argc, char* argv[] ){
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);
// Init node
// *********
ros::Rate loop_rate(10);
ROS_INFO("base_controller running...");
ROS_INFO("=============================");
ROS_INFO("Subscribing to topic /cmd_vel");
ROS_INFO("Publishing to topic /encoders");
ROS_INFO("Publishing to topic /md49data");
// Open serial port
// ****************
try{ device.open("/dev/ttyAMA0", 38400); }
catch(cereal::Exception& e)
{
ROS_FATAL("Failed to open the serial port!!!");
ROS_BREAK();
}
ROS_INFO("The serial port is opened.");
while(n.ok())
{
// Read encoder and other data from MD49
// (data is read from serial_controller_node
// and avaiable through md49_data.txt)
// *****************************************
read_MD49_Data();
// Publish encoder values to topic /encoders (custom message)
// **********************************************************
encoders.encoder_l=EncoderL;
encoders.encoder_r=EncoderR;
encoders_pub.publish(encoders);
// Publish MD49 data to topic /md49data (custom message)
// *****************************************************
md49data.speed_l = reply[8];
md49data.speed_r = reply[9];
md49data.volt = reply[10];
md49data.current_l = reply[11];
md49data.current_r = reply[12];
md49data.error = reply[13];
md49data.acceleration = reply[14];
md49data.mode = reply[15];
md49data.regulator = reply[16];
md49data.timeout = reply[17];
md49data_pub.publish(md49data);
// ****
ros::spinOnce();
loop_rate.sleep();
}// end.mainloop
return 1;
} // end.main
void read_MD49_Data (void){
// Send 'R' over the serial port
device.write("R");
// Get the reply, the last value is the timeout in ms
try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
catch(cereal::TimeoutException& e)
{
ROS_ERROR("Timeout on serialport! No data read");
}
//ROS_INFO("Received MD49 data");
// Put toghether new encodervalues
// *******************************
EncoderL = reply[0] << 24; // Put together first encoder value
EncoderL |= (reply[1] << 16);
EncoderL |= (reply[2] << 8);
EncoderL |= (reply[3]);
EncoderR = reply[4] << 24; // Put together second encoder value
EncoderR |= (reply[5] << 16);
EncoderR |= (reply[6] << 8);
EncoderR |= (reply[7]);
/*
// Output MD49 data on screen
// **************************
printf("\033[2J"); // clear the screen
printf("\033[H"); // position cursor at top-left corner
printf ("MD49-Data read from AVR-Master: \n");
printf("========================================\n");
printf("Encoder1 Byte1: %i ",reply[0]);
printf("Byte2: %i ",reply[1]);
printf("Byte3: % i ",reply[2]);
printf("Byte4: %i \n",reply[3]);
printf("Encoder2 Byte1: %i ",reply[4]);
printf("Byte2: %i ",reply[5]);
printf("Byte3: %i ",reply[6]);
printf("Byte4: %i \n",reply[7]);
printf("EncoderL: %i ",EncoderL);
printf("EncoderR: %i \n",EncoderR);
printf("========================================\n");
printf("Speed1: %i ",reply[8]);
printf("Speed2: %i \n",reply[9]);
printf("Volts: %i \n",reply[10]);
printf("Current1: %i ",reply[11]);
printf("Current2: %i \n",reply[12]);
printf("Error: %i \n",reply[13]);
printf("Acceleration: %i \n",reply[14]);
printf("Mode: %i \n",reply[15]);
printf("Regulator: %i \n",reply[16]);
printf("Timeout: %i \n",reply[17]);
*/
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
/*
char buffer[33];
ofstream myfile;
myfile.open ("md49_commands.txt");
//myfile << "Writing this to a file.\n";
if (speed_l==0){
myfile << "000";
myfile << "\n";
}
else if (speed_l<10){
myfile << "00";
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
else if (speed_l<100){
myfile << "0";
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
else{
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
if (speed_r==0){
myfile << "000";
myfile << "\n";
}
else if (speed_r<10){
myfile << "00";
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
else if (speed_r<100){
myfile << "0";
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
else{
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
myfile.close();
*/
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h> /* ROS */
#include <geometry_msgs/Twist.h> /* ROS Twist message */
#include <base_controller/encoders.h> /* Custom message /encoders */
#include <base_controller/md49data.h> /* Custom message /encoders */
#include <serialport/serialport.h>
#define REPLY_SIZE 18
#define TIMEOUT 1000
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
char reply[REPLY_SIZE];
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4; /* Base width in meters */
//unsigned char serialBuffer[18]; /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
using namespace std;
cereal::CerealPort device;
base_controller::encoders encoders;
base_controller::md49data md49data;
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
if (vel_cmd.linear.x>0){
speed_l = 255;
speed_r = 255;
}
if (vel_cmd.linear.x<0){
speed_l = 0;
speed_r = 0;
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
speed_l = 128;
speed_r = 128;
}
if (vel_cmd.angular.z>0){
speed_l = 0;
speed_r = 255;
}
if (vel_cmd.angular.z<0){
speed_l = 255;
speed_r = 0;
}
//if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
//set_MD49_speed(speed_l,speed_r);
//last_speed_l=speed_l;
//last_speed_r=speed_r;
//}
/*
//ANFANG Alternative
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
else if(vel_cmd.linear.x == 0){
// turning
vr = vel_cmd.angular.z * base_width / 2.0;
vl = (-1) * vr;
}
else if(vel_cmd.angular.z == 0){
// forward / backward
vl = vr = vel_cmd.linear.x;
}
else{
// moving doing arcs
vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
if (vl > max_vl) {vl=max_vl;}
if (vl < min_vl) {vl=min_vl;}
vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
if (vr > max_vr) {vr=max_vr;}
if (vr < min_vr) {vr=min_vr;}
}
//ENDE Alternative
*/
}
int main( int argc, char* argv[] ){
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10);
// Init node
// *********
ros::Rate loop_rate(10);
ROS_INFO("base_controller running...");
ROS_INFO("=============================");
ROS_INFO("Subscribing to topic /cmd_vel");
ROS_INFO("Publishing to topic /encoders");
ROS_INFO("Publishing to topic /md49data");
// Open serial port
// ****************
try{ device.open("/dev/ttyAMA0", 38400); }
catch(cereal::Exception& e)
{
ROS_FATAL("Failed to open the serial port!!!");
ROS_BREAK();
}
ROS_INFO("The serial port is opened.");
while(n.ok())
{
// Read encoder and other data from MD49
// (data is read from serial_controller_node
// and avaiable through md49_data.txt)
// *****************************************
read_MD49_Data();
// Publish encoder values to topic /encoders (custom message)
// **********************************************************
encoders.encoder_l=EncoderL;
encoders.encoder_r=EncoderR;
encoders_pub.publish(encoders);
// Publish MD49 data to topic /md49data (custom message)
// *****************************************************
md49data.speed_l = reply[8];
md49data.speed_r = reply[9];
md49data.volt = reply[10];
md49data.current_l = reply[11];
md49data.current_r = reply[12];
md49data.error = reply[13];
md49data.acceleration = reply[14];
md49data.mode = reply[15];
md49data.regulator = reply[16];
md49data.timeout = reply[17];
md49data_pub.publish(md49data);
// ****
ros::spinOnce();
loop_rate.sleep();
}// end.mainloop
return 1;
} // end.main
void read_MD49_Data (void){
// Send 'R' over the serial port
device.write("R");
// Get the reply, the last value is the timeout in ms
try{ device.read(reply, REPLY_SIZE, TIMEOUT); }
catch(cereal::TimeoutException& e)
{
ROS_ERROR("Timeout on serialport! No data read");
}
//ROS_INFO("Received MD49 data");
// Put toghether new encodervalues
// *******************************
EncoderL = reply[0] << 24; // Put together first encoder value
EncoderL |= (reply[1] << 16);
EncoderL |= (reply[2] << 8);
EncoderL |= (reply[3]);
EncoderR = reply[4] << 24; // Put together second encoder value
EncoderR |= (reply[5] << 16);
EncoderR |= (reply[6] << 8);
EncoderR |= (reply[7]);
/*
// Output MD49 data on screen
// **************************
printf("\033[2J"); // clear the screen
printf("\033[H"); // position cursor at top-left corner
printf ("MD49-Data read from AVR-Master: \n");
printf("========================================\n");
printf("Encoder1 Byte1: %i ",reply[0]);
printf("Byte2: %i ",reply[1]);
printf("Byte3: % i ",reply[2]);
printf("Byte4: %i \n",reply[3]);
printf("Encoder2 Byte1: %i ",reply[4]);
printf("Byte2: %i ",reply[5]);
printf("Byte3: %i ",reply[6]);
printf("Byte4: %i \n",reply[7]);
printf("EncoderL: %i ",EncoderL);
printf("EncoderR: %i \n",EncoderR);
printf("========================================\n");
printf("Speed1: %i ",reply[8]);
printf("Speed2: %i \n",reply[9]);
printf("Volts: %i \n",reply[10]);
printf("Current1: %i ",reply[11]);
printf("Current2: %i \n",reply[12]);
printf("Error: %i \n",reply[13]);
printf("Acceleration: %i \n",reply[14]);
printf("Mode: %i \n",reply[15]);
printf("Regulator: %i \n",reply[16]);
printf("Timeout: %i \n",reply[17]);
*/
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
const char* command;
//command=("Xs%i%i",speed_l,speed_r);
device.write("Xs",2);
device.write(command,1);
//device.write(speed_r,1);
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_
#include <vector>
#include "clustering/administration/issues/local.hpp"
#include "concurrency/watchable.hpp"
#include "containers/clone_ptr.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/serialize_macros.hpp"
// All local issue types are declared here to avoid circular dependencies
class log_write_issue_t : public local_issue_t {
public:
log_write_issue_t();
explicit log_write_issue_t(const std::string &_message);
const datum_string_t &get_name() const { return log_write_issue_type; }
bool is_critical() const { return false; }
std::string message;
private:
ql::datum_t build_info(const metadata_t &metadata) const;
datum_string_t build_description(const ql::datum_t &info) const;
static const datum_string_t log_write_issue_type;
static const uuid_u base_issue_id;
};
RDB_DECLARE_SERIALIZABLE(log_write_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(log_write_issue_t);
class outdated_index_issue_t : public local_issue_t {
public:
typedef std::map<namespace_id_t, std::set<std::string> > index_map_t;
outdated_index_issue_t();
explicit outdated_index_issue_t(const index_map_t &indexes);
const datum_string_t &get_name() const { return outdated_index_issue_type; }
bool is_critical() const { return false; }
index_map_t indexes;
private:
ql::datum_t build_info(const metadata_t &metadata) const;
datum_string_t build_description(const ql::datum_t &info) const;
static const datum_string_t outdated_index_issue_type;
static const uuid_u base_issue_id;
};
RDB_DECLARE_SERIALIZABLE(outdated_index_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(outdated_index_issue_t);
class server_down_issue_t : public local_issue_t {
public:
server_down_issue_t();
explicit server_down_issue_t(const machine_id_t &_down_server_id);
const datum_string_t &get_name() const { return server_down_issue_type; }
bool is_critical() const { return true; }
machine_id_t down_server_id;
private:
ql::datum_t build_info(const metadata_t &metadata) const;
datum_string_t build_description(const ql::datum_t &info) const;
static const datum_string_t server_down_issue_type;
static const issue_id_t base_issue_id;
};
RDB_DECLARE_SERIALIZABLE(server_down_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(server_down_issue_t);
class server_ghost_issue_t : public local_issue_t {
public:
server_ghost_issue_t();
explicit server_ghost_issue_t(const machine_id_t &_ghost_server_id);
const datum_string_t &get_name() const { return server_ghost_issue_type; }
bool is_critical() const { return false; }
machine_id_t ghost_server_id;
private:
ql::datum_t build_info(const metadata_t &metadata) const;
datum_string_t build_description(const ql::datum_t &info) const;
static const datum_string_t server_ghost_issue_type;
static const issue_id_t base_issue_id;
};
RDB_DECLARE_SERIALIZABLE(server_ghost_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(server_ghost_issue_t);
// Every local issue type should have the following:
// - an entry in the local_issues_t
// - a local_issue_t::make_*_issue function for the local issue type
struct local_issues_t {
std::vector<log_write_issue_t> log_write_issues;
std::vector<server_down_issue_t> server_down_issues;
std::vector<server_ghost_issue_t> server_ghost_issues;
std::vector<outdated_index_issue_t> outdated_index_issues;
};
RDB_DECLARE_SERIALIZABLE(local_issues_t);
RDB_DECLARE_EQUALITY_COMPARABLE(local_issues_t);
class local_issue_aggregator_t : public home_thread_mixin_t {
public:
local_issue_aggregator_t();
clone_ptr_t<watchable_t<local_issues_t> > get_issues_watchable();
private:
friend class local_issue_tracker_t;
watchable_variable_t<local_issues_t> issues_watchable;
DISABLE_COPYING(local_issue_aggregator_t);
};
#endif /* CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_ */
<commit_msg>updating comments<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_
#include <vector>
#include "clustering/administration/issues/local.hpp"
#include "concurrency/watchable.hpp"
#include "containers/clone_ptr.hpp"
#include "rpc/semilattice/joins/macros.hpp"
#include "rpc/serialize_macros.hpp"
// All local issue types are declared here to avoid circular dependencies
// This is because local issue trackers require definitions for the metadata,
// but the metadata requires definitions of all local issue types.
//
// Every local issue type should have the following:
// - an issue_t subclass defined in this file
// - an entry in the local_issues_t for that issue_t subclass
// - handling in remote_issue_tracker_t
// - a combine() method in the issue tracker
class log_write_issue_t : public local_issue_t {
public:
log_write_issue_t();
explicit log_write_issue_t(const std::string &_message);
const datum_string_t &get_name() const { return log_write_issue_type; }
bool is_critical() const { return false; }
std::string message;
private:
ql::datum_t build_info(const metadata_t &metadata) const;
datum_string_t build_description(const ql::datum_t &info) const;
static const datum_string_t log_write_issue_type;
static const uuid_u base_issue_id;
};
RDB_DECLARE_SERIALIZABLE(log_write_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(log_write_issue_t);
class outdated_index_issue_t : public local_issue_t {
public:
typedef std::map<namespace_id_t, std::set<std::string> > index_map_t;
outdated_index_issue_t();
explicit outdated_index_issue_t(const index_map_t &indexes);
const datum_string_t &get_name() const { return outdated_index_issue_type; }
bool is_critical() const { return false; }
index_map_t indexes;
private:
ql::datum_t build_info(const metadata_t &metadata) const;
datum_string_t build_description(const ql::datum_t &info) const;
static const datum_string_t outdated_index_issue_type;
static const uuid_u base_issue_id;
};
RDB_DECLARE_SERIALIZABLE(outdated_index_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(outdated_index_issue_t);
class server_down_issue_t : public local_issue_t {
public:
server_down_issue_t();
explicit server_down_issue_t(const machine_id_t &_down_server_id);
const datum_string_t &get_name() const { return server_down_issue_type; }
bool is_critical() const { return true; }
machine_id_t down_server_id;
private:
ql::datum_t build_info(const metadata_t &metadata) const;
datum_string_t build_description(const ql::datum_t &info) const;
static const datum_string_t server_down_issue_type;
static const issue_id_t base_issue_id;
};
RDB_DECLARE_SERIALIZABLE(server_down_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(server_down_issue_t);
class server_ghost_issue_t : public local_issue_t {
public:
server_ghost_issue_t();
explicit server_ghost_issue_t(const machine_id_t &_ghost_server_id);
const datum_string_t &get_name() const { return server_ghost_issue_type; }
bool is_critical() const { return false; }
machine_id_t ghost_server_id;
private:
ql::datum_t build_info(const metadata_t &metadata) const;
datum_string_t build_description(const ql::datum_t &info) const;
static const datum_string_t server_ghost_issue_type;
static const issue_id_t base_issue_id;
};
RDB_DECLARE_SERIALIZABLE(server_ghost_issue_t);
RDB_DECLARE_EQUALITY_COMPARABLE(server_ghost_issue_t);
struct local_issues_t {
std::vector<log_write_issue_t> log_write_issues;
std::vector<server_down_issue_t> server_down_issues;
std::vector<server_ghost_issue_t> server_ghost_issues;
std::vector<outdated_index_issue_t> outdated_index_issues;
};
RDB_DECLARE_SERIALIZABLE(local_issues_t);
RDB_DECLARE_EQUALITY_COMPARABLE(local_issues_t);
class local_issue_aggregator_t : public home_thread_mixin_t {
public:
local_issue_aggregator_t();
clone_ptr_t<watchable_t<local_issues_t> > get_issues_watchable();
private:
friend class local_issue_tracker_t;
watchable_variable_t<local_issues_t> issues_watchable;
DISABLE_COPYING(local_issue_aggregator_t);
};
#endif /* CLUSTERING_ADMINISTRATION_ISSUES_LOCAL_ISSUE_AGGREGATOR_HPP_ */
<|endoftext|> |
<commit_before>// Copyright (C) 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "fake_downloader.h"
#include <cassert>
#include <fstream>
#include <map>
#include <string>
#include <utility>
namespace i18n {
namespace addressinput {
// static
const char FakeDownloader::kFakeDataUrl[] = "test:///";
namespace {
// The name of the test data file.
const char kDataFileName[] = TEST_DATA_DIR "/countryinfo.txt";
// The number of characters in the fake data URL prefix.
const size_t kFakeDataUrlLength = sizeof FakeDownloader::kFakeDataUrl - 1;
std::string CCKey(const std::string& key) {
const char kSplitChar = '/';
std::string::size_type split = key.find(kSplitChar);
if (split == std::string::npos) {
return key;
}
split = key.find(kSplitChar, split + 1);
if (split == std::string::npos) {
return key;
}
return key.substr(0, split);
}
std::map<std::string, std::string> InitData() {
std::map<std::string, std::string> data;
std::ifstream file(kDataFileName);
assert(file.is_open());
std::string line;
while (file.good()) {
std::getline(file, line);
std::string::size_type divider = line.find('=');
if (divider == std::string::npos) {
continue;
}
std::string key = line.substr(0, divider);
std::string cc_key = CCKey(key);
std::string value = line.substr(divider + 1);
std::string url = FakeDownloader::kFakeDataUrl + cc_key;
std::map<std::string, std::string>::iterator data_it = data.find(url);
if (data_it != data.end()) {
data_it->second += ", \"" + key + "\": " + value;
} else {
data.insert(std::make_pair(url, "{\"" + key + "\": " + value));
}
}
file.close();
for (std::map<std::string, std::string>::iterator data_it = data.begin();
data_it != data.end(); ++data_it) {
data_it->second += "}";
}
return data;
}
const std::map<std::string, std::string>& GetData() {
static const std::map<std::string, std::string> kData(InitData());
return kData;
}
} // namespace
FakeDownloader::FakeDownloader() {}
FakeDownloader::~FakeDownloader() {}
void FakeDownloader::Download(const std::string& url,
scoped_ptr<Callback> downloaded) {
std::map<std::string, std::string>::const_iterator data_it =
GetData().find(url);
bool success = data_it != GetData().end();
std::string data = success ? data_it->second : std::string();
if (!success &&
url.compare(
0, kFakeDataUrlLength, kFakeDataUrl, kFakeDataUrlLength) == 0) {
// URLs that start with
// "https://i18napis.appspot.com/ssl-aggregate-address/" prefix, but do not
// have associated data will always return "{}" with status code 200.
// FakeDownloader imitates this behavior for URLs that start with "test:///"
// prefix.
success = true;
data = "{}";
}
(*downloaded)(success, url, make_scoped_ptr(new std::string(data)));
}
} // namespace addressinput
} // namespace i18n
<commit_msg>Include language-specific rules in fake downloader for libaddressinput.<commit_after>// Copyright (C) 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "fake_downloader.h"
#include <cassert>
#include <fstream>
#include <map>
#include <string>
#include <utility>
namespace i18n {
namespace addressinput {
// static
const char FakeDownloader::kFakeDataUrl[] = "test:///";
namespace {
// The name of the test data file.
const char kDataFileName[] = TEST_DATA_DIR "/countryinfo.txt";
// The number of characters in the fake data URL prefix.
const size_t kFakeDataUrlLength = sizeof FakeDownloader::kFakeDataUrl - 1;
// Returns "data/HK" for "data/HK--en".
std::string RemoveLanguageCode(const std::string& key) {
std::string::size_type language_code_pos = key.find("--");
return language_code_pos == std::string::npos
? key
: key.substr(0, language_code_pos);
}
std::string CCKey(const std::string& key) {
const char kSplitChar = '/';
std::string::size_type split = key.find(kSplitChar);
if (split == std::string::npos) {
return key;
}
split = key.find(kSplitChar, split + 1);
if (split == std::string::npos) {
return key;
}
return key.substr(0, split);
}
std::map<std::string, std::string> InitData() {
std::map<std::string, std::string> data;
std::ifstream file(kDataFileName);
assert(file.is_open());
std::string line;
while (file.good()) {
std::getline(file, line);
std::string::size_type divider = line.find('=');
if (divider == std::string::npos) {
continue;
}
std::string key = line.substr(0, divider);
std::string cc_key = RemoveLanguageCode(CCKey(key));
std::string value = line.substr(divider + 1);
std::string url = FakeDownloader::kFakeDataUrl + cc_key;
std::map<std::string, std::string>::iterator data_it = data.find(url);
if (data_it != data.end()) {
data_it->second += ", \"" + key + "\": " + value;
} else {
data.insert(std::make_pair(url, "{\"" + key + "\": " + value));
}
}
file.close();
for (std::map<std::string, std::string>::iterator data_it = data.begin();
data_it != data.end(); ++data_it) {
data_it->second += "}";
}
return data;
}
const std::map<std::string, std::string>& GetData() {
static const std::map<std::string, std::string> kData(InitData());
return kData;
}
} // namespace
FakeDownloader::FakeDownloader() {}
FakeDownloader::~FakeDownloader() {}
void FakeDownloader::Download(const std::string& url,
scoped_ptr<Callback> downloaded) {
std::map<std::string, std::string>::const_iterator data_it =
GetData().find(url);
bool success = data_it != GetData().end();
std::string data = success ? data_it->second : std::string();
if (!success &&
url.compare(
0, kFakeDataUrlLength, kFakeDataUrl, kFakeDataUrlLength) == 0) {
// URLs that start with
// "https://i18napis.appspot.com/ssl-aggregate-address/" prefix, but do not
// have associated data will always return "{}" with status code 200.
// FakeDownloader imitates this behavior for URLs that start with "test:///"
// prefix.
success = true;
data = "{}";
}
(*downloaded)(success, url, make_scoped_ptr(new std::string(data)));
}
} // namespace addressinput
} // namespace i18n
<|endoftext|> |
<commit_before>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
#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 */
#include <ctype.h> /* isxxx() */
const char* serialport="/dev/ttyAMA0"; /* defines used serialport */
int serialport_bps=B38400; /* defines baudrate od serialport */
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
int filedesc; // File descriptor of serial port we will talk to
int fd; /* serial port file descriptor */
unsigned char serialBuffer[16]; /* Serial buffer to store uart data */
struct termios orig; // Port options
using namespace std;
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
unsigned char md49_data[18];
int main( int argc, char* argv[] ){
// Open serial port
// ****************
filedesc = openSerialPort("/dev/ttyAMA0", serialport_bps);
if (filedesc == -1) exit(1);
usleep(10000); // Sleep for UART to power up and set options
while( 1 )
{
// Read encoder and other data from MD49
// and put into sqlite db
// *************************************
read_MD49_Data();
usleep(200000);
// Read commands from sqlite db and
// set speed and other commands to MD49
// ************************************
string line;
ifstream myfile ("md49_commands.txt");
if (myfile.is_open())
{
int i=0;
while ( getline (myfile,line) )
{
//cout << line << '\n';
char data[10];
std::copy(line.begin(), line.end(), data);
md49_data[i]=atoi(data);
i =i++;
}
myfile.close();
speed_l=md49_data[0];
speed_r=md49_data[1];
}
else cout << "Unable to open file";
set_MD49_speed(speed_l, speed_r);
usleep(200000);
}// end.mainloop
return 1;
} // end.main
int openSerialPort(const char * device, int bps){
struct termios neu;
char buf[128];
//fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1)
{
sprintf(buf, "openSerialPort %s error", device);
perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
//fprintf(stderr, "speed=%d\n", bps);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void read_MD49_Data (void){
serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
writeBytes(fd, 1);
//Daten lesen und in Array schreiben
readBytes(fd, 18);
ofstream myfile;
myfile.open ("md49_data.txt");
//myfile << "Writing this to a file.\n";
char buffer[33];
EncoderL = serialBuffer[0] << 24; // Put together first encoder value
EncoderL |= (serialBuffer[1] << 16);
EncoderL |= (serialBuffer[2] << 8);
EncoderL |= (serialBuffer[3]);
EncoderR = serialBuffer[4] << 24; // Put together second encoder value
EncoderR |= (serialBuffer[5] << 16);
EncoderR |= (serialBuffer[6] << 8);
EncoderR |= (serialBuffer[7]);
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
printf("Encoder1 Byte1: %i ",serialBuffer[0]);
if (serialBuffer[0]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[0],buffer,10);
}
myfile << "\n";
printf("Byte2: %i ",serialBuffer[1]);
if (serialBuffer[1]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[1],buffer,10);
}
myfile << "\n";
printf("Byte3: % i ",serialBuffer[2]);
if (serialBuffer[2]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[2],buffer,10);
}
myfile << "\n";
printf("Byte4: %i \n",serialBuffer[3]);
if (serialBuffer[3]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[3],buffer,10);
}
myfile << "\n";
printf("Encoder2 Byte1: %i ",serialBuffer[4]);
if (serialBuffer[4]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[4],buffer,10);
}
myfile << "\n";
printf("Byte2: %i ",serialBuffer[5]);
if (serialBuffer[5]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[5],buffer,10);
}
myfile << "\n";
printf("Byte3: %i ",serialBuffer[6]);
if (serialBuffer[6]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[6],buffer,10);
}
myfile << "\n";
printf("Byte4: %i \n",serialBuffer[7]);
if (serialBuffer[7]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[7],buffer,10);
}
myfile << "\n";
printf("EncoderL: %i ",EncoderL);
// myfile << itoa(EncoderL,buffer,10);
//myfile << "\n";
printf("EncoderR: %i \n",EncoderR);
//myfile << itoa(EncoderR,buffer,10);
//myfile << "\n";
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
if (serialBuffer[8]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[8],buffer,10);
}
myfile << "\n";
printf("Speed2: %i \n",serialBuffer[9]);
if (serialBuffer[9]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[9],buffer,10);
}
myfile << "\n";
printf("Volts: %i \n",serialBuffer[10]);
if (serialBuffer[10]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[10],buffer,10);
}
myfile << "\n";
printf("Current1: %i ",serialBuffer[11]);
if (serialBuffer[11]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[11],buffer,10);
}
myfile << "\n";
printf("Current2: %i \n",serialBuffer[12]);
if (serialBuffer[12]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[12],buffer,10);
}
myfile << "\n";
printf("Error: %i \n",serialBuffer[13]);
if (serialBuffer[13]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[13],buffer,10);
}
myfile << "\n";
printf("Acceleration: %i \n",serialBuffer[14]);
if (serialBuffer[14]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[14],buffer,10);
}
myfile << "\n";
printf("Mode: %i \n",serialBuffer[15]);
if (serialBuffer[15]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[15],buffer,10);
}
myfile << "\n";
printf("Regulator: %i \n",serialBuffer[16]);
if (serialBuffer[16]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[16],buffer,10);
}
myfile << "\n";
printf("Timeout: %i \n",serialBuffer[17]);
if (serialBuffer[17]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[17],buffer,10);
}
myfile << "\n";
printf("speed_l = %i \n",speed_l);
printf("speed_r = %i \n",speed_r);
myfile.close();
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = speed_l; // speed1
serialBuffer[3] = speed_r; // speed2
writeBytes(fd, 4);
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
#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 */
#include <ctype.h> /* isxxx() */
const char* serialport="/dev/ttyAMA0"; /* defines used serialport */
int serialport_bps=B38400; /* defines baudrate od serialport */
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
int filedesc; // File descriptor of serial port we will talk to
int fd; /* serial port file descriptor */
unsigned char serialBuffer[16]; /* Serial buffer to store uart data */
struct termios orig; // Port options
using namespace std;
int openSerialPort(const char * device, int bps);
void writeBytes(int descriptor, int count);
void readBytes(int descriptor, int count);
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
unsigned char md49_data[18];
int main( int argc, char* argv[] ){
// Open serial port
// ****************
filedesc = openSerialPort("/dev/ttyAMA0", serialport_bps);
if (filedesc == -1) exit(1);
usleep(10000); // Sleep for UART to power up and set options
while( 1 )
{
// Read encoder and other data from MD49
// and put into sqlite db
// *************************************
read_MD49_Data();
usleep(200000);
// Read commands from sqlite db and
// set speed and other commands to MD49
// ************************************
string line;
ifstream myfile ("md49_commands.txt");
if (myfile.is_open())
{
int i=0;
while ( getline (myfile,line) )
{
//cout << line << '\n';
char data[10];
std::copy(line.begin(), line.end(), data);
md49_data[i]=atoi(data);
i =i++;
}
myfile.close();
speed_l=md49_data[0];
speed_r=md49_data[1];
}
else cout << "Unable to open file";
set_MD49_speed(speed_l, speed_r);
usleep(200000);
}// end.mainloop
return 1;
} // end.main
int openSerialPort(const char * device, int bps){
struct termios neu;
char buf[128];
//fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1)
{
sprintf(buf, "openSerialPort %s error", device);
perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
//fprintf(stderr, "speed=%d\n", bps);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void read_MD49_Data (void){
serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
writeBytes(fd, 1);
//Daten lesen und in Array schreiben
readBytes(fd, 18);
ofstream myfile;
myfile.open ("md49_data.txt");
//myfile << "Writing this to a file.\n";
char buffer[33];
EncoderL = serialBuffer[0] << 24; // Put together first encoder value
EncoderL |= (serialBuffer[1] << 16);
EncoderL |= (serialBuffer[2] << 8);
EncoderL |= (serialBuffer[3]);
EncoderR = serialBuffer[4] << 24; // Put together second encoder value
EncoderR |= (serialBuffer[5] << 16);
EncoderR |= (serialBuffer[6] << 8);
EncoderR |= (serialBuffer[7]);
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
printf("Encoder1 Byte1: %i ",serialBuffer[0]);
if (serialBuffer[0]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[0],buffer,10);
}
myfile << "\n";
printf("Byte2: %i ",serialBuffer[1]);
if (serialBuffer[1]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[1],buffer,10);
}
myfile << "\n";
printf("Byte3: % i ",serialBuffer[2]);
if (serialBuffer[2]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[2],buffer,10);
}
myfile << "\n";
printf("Byte4: %i \n",serialBuffer[3]);
if (serialBuffer[3]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[3],buffer,10);
}
myfile << "\n";
printf("Encoder2 Byte1: %i ",serialBuffer[4]);
if (serialBuffer[4]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[4],buffer,10);
}
myfile << "\n";
printf("Byte2: %i ",serialBuffer[5]);
if (serialBuffer[5]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[5],buffer,10);
}
myfile << "\n";
printf("Byte3: %i ",serialBuffer[6]);
if (serialBuffer[6]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[6],buffer,10);
}
myfile << "\n";
printf("Byte4: %i \n",serialBuffer[7]);
if (serialBuffer[7]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[7],buffer,10);
}
myfile << "\n";
printf("EncoderL: %i ",EncoderL);
// myfile << itoa(EncoderL,buffer,10);
//myfile << "\n";
printf("EncoderR: %i \n",EncoderR);
//myfile << itoa(EncoderR,buffer,10);
//myfile << "\n";
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
if (serialBuffer[8]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[8],buffer,10);
}
myfile << "\n";
printf("Speed2: %i \n",serialBuffer[9]);
if (serialBuffer[9]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[9],buffer,10);
}
myfile << "\n";
printf("Volts: %i \n",serialBuffer[10]);
if (serialBuffer[10]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[10],buffer,10);
}
myfile << "\n";
printf("Current1: %i ",serialBuffer[11]);
if (serialBuffer[11]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[11],buffer,10);
}
myfile << "\n";
printf("Current2: %i \n",serialBuffer[12]);
if (serialBuffer[12]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[12],buffer,10);
}
myfile << "\n";
printf("Error: %i \n",serialBuffer[13]);
if (serialBuffer[13]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[13],buffer,10);
}
myfile << "\n";
printf("Acceleration: %i \n",serialBuffer[14]);
if (serialBuffer[14]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[14],buffer,10);
}
myfile << "\n";
printf("Mode: %i \n",serialBuffer[15]);
if (serialBuffer[15]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[15],buffer,10);
}
myfile << "\n";
printf("Regulator: %i \n",serialBuffer[16]);
if (serialBuffer[16]==0){
myfile << "000";
}
else{
if (serialBuffer[16]<10){
myfile << "00";
myfile << itoa(serialBuffer[16],buffer,10);
}
else{
myfile << itoa(serialBuffer[16],buffer,10);
}
}
myfile << "\n";
printf("Timeout: %i \n",serialBuffer[17]);
if (serialBuffer[17]==0){
myfile << "000";
}
else{
myfile << itoa(serialBuffer[17],buffer,10);
}
myfile << "\n";
printf("speed_l = %i \n",speed_l);
printf("speed_r = %i \n",speed_r);
myfile.close();
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden
serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed
serialBuffer[2] = speed_l; // speed1
serialBuffer[3] = speed_r; // speed2
writeBytes(fd, 4);
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019-2020 Inviwo 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.
*
* 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 <ivwdataframe/pydataframe.h>
#include <warn/push>
#include <warn/ignore/shadow>
#include <pybind11/functional.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <warn/pop>
#include <inviwo/dataframe/datastructures/column.h>
#include <inviwo/dataframe/datastructures/dataframe.h>
#include <inviwo/dataframe/datastructures/datapoint.h>
#include <inviwo/core/util/defaultvalues.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <modules/python3/pyportutils.h>
#include <fmt/format.h>
namespace py = pybind11;
namespace inviwo {
namespace {
struct DataFrameAddColumnReg {
template <typename T>
auto operator()(py::class_<DataFrame, std::shared_ptr<DataFrame>>& d) {
auto classname = Defaultvalues<T>::getName();
d.def(fmt::format("add{}Column", classname).c_str(),
[](DataFrame& d, const std::string& header, const size_t size = 0) {
return d.addColumn<T>(header, size);
},
py::arg("header"), py::arg("size") = 0);
d.def(fmt::format("add{}Column", classname).c_str(),
[](DataFrame& d, std::string header, std::vector<T> data) {
return d.addColumn(std::move(header), std::move(data));
},
py::arg("header"), py::arg("data"));
}
};
struct DataPointReg {
template <typename T>
auto operator()(pybind11::module& m) {
using D = DataPoint<T>;
auto classname = Defaultvalues<T>::getName() + "DataPoint";
py::class_<D, DataPointBase, std::shared_ptr<D>> data(m, classname.c_str());
data.def_property_readonly("data", &D::getData)
.def_property_readonly("str", &D::toString)
.def("__repr__",
[classname](D& p) { return fmt::format("<{}: '{}'>", classname, p.toString()); });
}
};
struct TemplateColumnReg {
template <typename T>
auto operator()(pybind11::module& m) {
using C = TemplateColumn<T>;
auto classname = Defaultvalues<T>::getName() + "Column";
py::class_<C, Column, std::shared_ptr<C>> col(m, classname.c_str());
col.def_property_readonly("buffer", [](C& c) { return c.getTypedBuffer(); })
.def(py::init<const std::string&>())
.def("add", py::overload_cast<const T&>(&C::add))
.def("add", py::overload_cast<const std::string&>(&C::add))
.def("append", [](C& c, C& src) { c.append(src); })
.def("set", &C::set)
.def("get",
[](const C& c, size_t i) {
if (i >= c.getSize()) throw py::index_error();
return c.get(i);
},
py::arg("i"))
.def("get",
[](const C& c, size_t i, bool asString) {
if (i >= c.getSize()) throw py::index_error();
return c.get(i, asString);
},
py::arg("i"), py::arg("asString"))
.def("__repr__", [classname](C& c) {
return fmt::format("<{}: '{}', {}, {}>", classname, c.getHeader(), c.getSize(),
c.getBuffer()->getDataFormat()->getString());
});
}
};
} // namespace
void exposeDataFrame(pybind11::module& m) {
py::class_<DataPointBase, std::shared_ptr<DataPointBase>>(m, "DataPointBase")
.def("__repr__",
[](DataPointBase& p) { return fmt::format("<DataPoint: '{}'>", p.toString()); });
py::class_<Column, std::shared_ptr<Column>>(m, "Column")
.def_property("header", &Column::getHeader, &Column::setHeader)
.def_property_readonly("buffer", [](Column& self) { return self.getBuffer(); })
.def_property_readonly("size", &Column::getSize)
.def("__repr__", [](Column& c) {
return fmt::format("<Column: '{}', {}, {}>", c.getHeader(), c.getSize(),
c.getBuffer()->getDataFormat()->getString());
});
using Scalars = std::tuple<float, double, int, glm::i64, size_t, std::uint32_t>;
util::for_each_type<Scalars>{}(DataPointReg{}, m);
util::for_each_type<Scalars>{}(TemplateColumnReg{}, m);
py::class_<CategoricalColumn, TemplateColumn<std::uint32_t>,
std::shared_ptr<CategoricalColumn>>(m, "CategoricalColumn")
.def(py::init<const std::string&>())
.def_property_readonly("categories", &CategoricalColumn::getCategories,
py::return_value_policy::copy)
.def("add", [](CategoricalColumn& c, const std::string& str) { c.add(str); })
.def("append", [](CategoricalColumn& c, CategoricalColumn& src) { c.append(src); })
.def("set", [](CategoricalColumn& c, size_t idx, const std::uint32_t& v) { c.set(idx, v); })
.def("set", py::overload_cast<size_t, const std::string&>(&CategoricalColumn::set))
.def("get",
[](const CategoricalColumn& c, size_t i, bool asString) {
if (i >= c.getSize()) throw py::index_error();
return c.get(i, asString);
},
py::arg("i"), py::arg("asString") = true)
.def("__repr__", [](CategoricalColumn& c) {
return fmt::format("<CategoricalColumn: '{}', {}, {} categories>", c.getHeader(),
c.getSize(), c.getCategories().size());
});
py::class_<DataFrame, std::shared_ptr<DataFrame>> dataframe(m, "DataFrame");
dataframe.def(py::init<std::uint32_t>(), py::arg("size") = 0)
.def_property_readonly("cols", &DataFrame::getNumberOfColumns)
.def_property_readonly("rows", &DataFrame::getNumberOfRows)
.def("indexcol", [](DataFrame& d) { return d.getIndexColumn(); })
.def("column", [](DataFrame& self, size_t index) { return self.getColumn(index); })
.def("addColumnFromBuffer", &DataFrame::addColumnFromBuffer)
.def("addCategoricalColumn", &DataFrame::addCategoricalColumn, py::arg("header"),
py::arg("size") = 0)
.def("getRow", &DataFrame::getDataItem, py::arg("index"), py::arg("asString") = false)
.def("updateIndex", [](DataFrame& d) { d.updateIndexBuffer(); })
// interface for operator[]
.def("__getitem__",
[](const DataFrame& d, size_t i) {
if (i >= d.getNumberOfColumns()) throw py::index_error();
return *(d.begin() + i);
},
py::return_value_policy::reference_internal)
// sequence protocol operations
.def("__iter__", [](const DataFrame& d) { return py::make_iterator(d.begin(), d.end()); },
py::keep_alive<0, 1>() /* Essential: keep object alive while iterator exists */)
.def("__repr__", [](const DataFrame& d) {
std::string str = fmt::format("<DataFrame: {} column(s), {} rows",
d.getNumberOfColumns(), d.getNumberOfRows());
size_t i = 0;
for (auto c : d) {
++i;
str += fmt::format("\n {:>3}: '{}', {}, {}", i, c->getHeader(), c->getSize(),
c->getBuffer()->getDataFormat()->getString());
}
return str + ">";
});
util::for_each_type<Scalars>{}(DataFrameAddColumnReg{}, dataframe);
m.def("createDataFrame", createDataFrame, py::arg("exampleRows"),
py::arg("colheaders") = std::vector<std::string>{},
R"delim(
Create a new DataFrame by guessing the column types from a number of rows.
Parameters
----------
exampleRows Rows for guessing data type of each column.
colHeaders Name of each column. If none are given, "Column 1", "Column 2", ... is used
)delim");
exposeStandardDataPorts<DataFrame>(m, "DataFrame");
}
} // namespace inviwo
<commit_msg>DataFramePython: exposed DataFrame joins<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2019-2020 Inviwo 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.
*
* 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 <ivwdataframe/pydataframe.h>
#include <warn/push>
#include <warn/ignore/shadow>
#include <pybind11/functional.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <warn/pop>
#include <inviwo/dataframe/datastructures/column.h>
#include <inviwo/dataframe/datastructures/dataframe.h>
#include <inviwo/dataframe/datastructures/datapoint.h>
#include <inviwo/dataframe/util/dataframeutils.h>
#include <inviwo/core/util/defaultvalues.h>
#include <inviwo/core/datastructures/buffer/buffer.h>
#include <modules/python3/pyportutils.h>
#include <fmt/format.h>
namespace py = pybind11;
namespace inviwo {
namespace {
struct DataFrameAddColumnReg {
template <typename T>
auto operator()(py::class_<DataFrame, std::shared_ptr<DataFrame>>& d) {
auto classname = Defaultvalues<T>::getName();
d.def(
fmt::format("add{}Column", classname).c_str(),
[](DataFrame& d, const std::string& header, const size_t size = 0) {
return d.addColumn<T>(header, size);
},
py::arg("header"), py::arg("size") = 0);
d.def(
fmt::format("add{}Column", classname).c_str(),
[](DataFrame& d, std::string header, std::vector<T> data) {
return d.addColumn(std::move(header), std::move(data));
},
py::arg("header"), py::arg("data"));
}
};
struct DataPointReg {
template <typename T>
auto operator()(pybind11::module& m) {
using D = DataPoint<T>;
auto classname = Defaultvalues<T>::getName() + "DataPoint";
py::class_<D, DataPointBase, std::shared_ptr<D>> data(m, classname.c_str());
data.def_property_readonly("data", &D::getData)
.def_property_readonly("str", &D::toString)
.def("__repr__",
[classname](D& p) { return fmt::format("<{}: '{}'>", classname, p.toString()); });
}
};
struct TemplateColumnReg {
template <typename T>
auto operator()(pybind11::module& m) {
using C = TemplateColumn<T>;
auto classname = Defaultvalues<T>::getName() + "Column";
py::class_<C, Column, std::shared_ptr<C>> col(m, classname.c_str());
col.def_property_readonly("buffer", [](C& c) { return c.getTypedBuffer(); })
.def(py::init<const std::string&>())
.def("add", py::overload_cast<const T&>(&C::add))
.def("add", py::overload_cast<const std::string&>(&C::add))
.def("append", [](C& c, C& src) { c.append(src); })
.def("set", &C::set)
.def(
"get",
[](const C& c, size_t i) {
if (i >= c.getSize()) throw py::index_error();
return c.get(i);
},
py::arg("i"))
.def(
"get",
[](const C& c, size_t i, bool asString) {
if (i >= c.getSize()) throw py::index_error();
return c.get(i, asString);
},
py::arg("i"), py::arg("asString"))
.def("__repr__", [classname](C& c) {
return fmt::format("<{}: '{}', {}, {}>", classname, c.getHeader(), c.getSize(),
c.getBuffer()->getDataFormat()->getString());
});
}
};
} // namespace
void exposeDataFrame(pybind11::module& m) {
py::class_<DataPointBase, std::shared_ptr<DataPointBase>>(m, "DataPointBase")
.def("__repr__",
[](DataPointBase& p) { return fmt::format("<DataPoint: '{}'>", p.toString()); });
py::class_<Column, std::shared_ptr<Column>>(m, "Column")
.def_property("header", &Column::getHeader, &Column::setHeader)
.def_property_readonly("buffer", [](Column& self) { return self.getBuffer(); })
.def_property_readonly("size", &Column::getSize)
.def("__repr__", [](Column& c) {
return fmt::format("<Column: '{}', {}, {}>", c.getHeader(), c.getSize(),
c.getBuffer()->getDataFormat()->getString());
});
using Scalars = std::tuple<float, double, int, glm::i64, size_t, std::uint32_t>;
util::for_each_type<Scalars>{}(DataPointReg{}, m);
util::for_each_type<Scalars>{}(TemplateColumnReg{}, m);
py::class_<CategoricalColumn, TemplateColumn<std::uint32_t>,
std::shared_ptr<CategoricalColumn>>(m, "CategoricalColumn")
.def(py::init<const std::string&>())
.def_property_readonly("categories", &CategoricalColumn::getCategories,
py::return_value_policy::copy)
.def("add", [](CategoricalColumn& c, const std::string& str) { c.add(str); })
.def("append", [](CategoricalColumn& c, CategoricalColumn& src) { c.append(src); })
.def("set", [](CategoricalColumn& c, size_t idx, const std::uint32_t& v) { c.set(idx, v); })
.def("set", py::overload_cast<size_t, const std::string&>(&CategoricalColumn::set))
.def(
"get",
[](const CategoricalColumn& c, size_t i, bool asString) {
if (i >= c.getSize()) throw py::index_error();
return c.get(i, asString);
},
py::arg("i"), py::arg("asString") = true)
.def("__repr__", [](CategoricalColumn& c) {
return fmt::format("<CategoricalColumn: '{}', {}, {} categories>", c.getHeader(),
c.getSize(), c.getCategories().size());
});
py::class_<DataFrame, std::shared_ptr<DataFrame>> dataframe(m, "DataFrame");
dataframe.def(py::init<std::uint32_t>(), py::arg("size") = 0)
.def_property_readonly("cols", &DataFrame::getNumberOfColumns)
.def_property_readonly("rows", &DataFrame::getNumberOfRows)
.def("indexcol", [](DataFrame& d) { return d.getIndexColumn(); })
.def("column", [](DataFrame& self, size_t index) { return self.getColumn(index); })
.def("addColumnFromBuffer", &DataFrame::addColumnFromBuffer)
.def("addCategoricalColumn", &DataFrame::addCategoricalColumn, py::arg("header"),
py::arg("size") = 0)
.def("getRow", &DataFrame::getDataItem, py::arg("index"), py::arg("asString") = false)
.def("updateIndex", [](DataFrame& d) { d.updateIndexBuffer(); })
// interface for operator[]
.def(
"__getitem__",
[](const DataFrame& d, size_t i) {
if (i >= d.getNumberOfColumns()) throw py::index_error();
return *(d.begin() + i);
},
py::return_value_policy::reference_internal)
// sequence protocol operations
.def(
"__iter__", [](const DataFrame& d) { return py::make_iterator(d.begin(), d.end()); },
py::keep_alive<0, 1>() /* Essential: keep object alive while iterator exists */)
.def("__repr__", [](const DataFrame& d) {
std::string str = fmt::format("<DataFrame: {} column(s), {} rows",
d.getNumberOfColumns(), d.getNumberOfRows());
size_t i = 0;
for (auto c : d) {
++i;
str += fmt::format("\n {:>3}: '{}', {}, {}", i, c->getHeader(), c->getSize(),
c->getBuffer()->getDataFormat()->getString());
}
return str + ">";
});
util::for_each_type<Scalars>{}(DataFrameAddColumnReg{}, dataframe);
m.def("createDataFrame", createDataFrame, py::arg("exampleRows"),
py::arg("colheaders") = std::vector<std::string>{},
R"delim(
Create a new DataFrame by guessing the column types from a number of rows.
Parameters
----------
exampleRows Rows for guessing data type of each column.
colHeaders Name of each column. If none are given, "Column 1", "Column 2", ... is used
)delim")
.def("appendColumns", dataframeutils::appendColumns, py::arg("left"), py::arg("right"),
py::arg("ignoreduplicates") = false, py::arg("fillmissingrows") = false,
R"delim(
Create a new DataFrame by appending the columns of DataFrame right to DataFrame left
Parameters
----------
ignoreduplicates duplicate columns, i.e. same column header, are ignored if true
fillmissingrows if true, missing rows in either DataFrame are filled with 0 or
"undefined" (for categorical columns)
)delim")
.def("appendRows", dataframeutils::appendRows, py::arg("top"), py::arg("bottom"),
py::arg("matchbyname") = false,
R"delim(
Create a new DataFrame by appending the rows of DataFrame bottom to DataFrame top
Parameters
----------
matchByName if true, column headers are used for matching columns. Otherwise columns
are matched by order (default)
)delim")
.def("innerJoin", dataframeutils::innerJoin, py::arg("left"), py::arg("right"),
py::arg("keycolumn") = "index",
R"delim(
Create a new DataFrame by using an inner join of DataFrame left and DataFrame right.
That is only rows with matching keys are kept.
It is assumed that the entries in the key columns are unique. Otherwise results are undefined.
Parameters
----------
keycolumn header of the column used as key for the join operation (default: index column)
)delim");
exposeStandardDataPorts<DataFrame>(m, "DataFrame");
}
} // namespace inviwo
<|endoftext|> |
<commit_before>#include <wayfire/singleton-plugin.hpp>
#include <wayfire/view.hpp>
#include <wayfire/matcher.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/output.hpp>
#include <wayfire/signal-definitions.hpp>
#include "deco-subsurface.hpp"
struct wayfire_decoration_global_cleanup_t
{
~wayfire_decoration_global_cleanup_t()
{
for (auto view : wf::get_core().get_all_views())
{
deinit_view(view);
}
}
};
class wayfire_decoration :
public wf::singleton_plugin_t<wayfire_decoration_global_cleanup_t, true>
{
wf::view_matcher_t ignore_views{"decoration/ignore_views"};
wf::signal_connection_t view_updated{
[=] (wf::signal_data_t *data)
{
update_view_decoration(get_signaled_view(data));
}
};
public:
void init() override
{
singleton_plugin_t::init();
grab_interface->name = "simple-decoration";
grab_interface->capabilities = wf::CAPABILITY_VIEW_DECORATOR;
output->connect_signal("view-mapped", &view_updated);
output->connect_signal("view-decoration-state-updated", &view_updated);
}
/**
* Uses view_matcher_t to match whether the given view needs to be
* ignored for decoration
*
* @param view The view to match
* @return Whether the given view should be decorated?
*/
bool ignore_decoration_of_view(wayfire_view view)
{
return ignore_views.matches(view);
}
wf::wl_idle_call idle_deactivate;
void update_view_decoration(wayfire_view view)
{
if (view->should_be_decorated() && !ignore_decoration_of_view(view))
{
if (output->activate_plugin(grab_interface))
{
init_view(view);
idle_deactivate.run_once([this] ()
{
output->deactivate_plugin(grab_interface);
});
}
} else
{
deinit_view(view);
}
}
void fini() override
{
for (auto& view : output->workspace->get_views_in_layer(wf::ALL_LAYERS))
{
deinit_view(view);
}
singleton_plugin_t::fini();
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_decoration);
<commit_msg>decoration: Add decorations to views on init<commit_after>#include <wayfire/singleton-plugin.hpp>
#include <wayfire/view.hpp>
#include <wayfire/matcher.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/output.hpp>
#include <wayfire/signal-definitions.hpp>
#include "deco-subsurface.hpp"
struct wayfire_decoration_global_cleanup_t
{
~wayfire_decoration_global_cleanup_t()
{
for (auto view : wf::get_core().get_all_views())
{
deinit_view(view);
}
}
};
class wayfire_decoration :
public wf::singleton_plugin_t<wayfire_decoration_global_cleanup_t, true>
{
wf::view_matcher_t ignore_views{"decoration/ignore_views"};
wf::signal_connection_t view_updated{
[=] (wf::signal_data_t *data)
{
update_view_decoration(get_signaled_view(data));
}
};
public:
void init() override
{
singleton_plugin_t::init();
grab_interface->name = "simple-decoration";
grab_interface->capabilities = wf::CAPABILITY_VIEW_DECORATOR;
output->connect_signal("view-mapped", &view_updated);
output->connect_signal("view-decoration-state-updated", &view_updated);
for (auto& view :
output->workspace->get_views_in_layer(wf::ALL_LAYERS))
{
update_view_decoration(view);
}
}
/**
* Uses view_matcher_t to match whether the given view needs to be
* ignored for decoration
*
* @param view The view to match
* @return Whether the given view should be decorated?
*/
bool ignore_decoration_of_view(wayfire_view view)
{
return ignore_views.matches(view);
}
wf::wl_idle_call idle_deactivate;
void update_view_decoration(wayfire_view view)
{
if (view->should_be_decorated() && !ignore_decoration_of_view(view))
{
if (output->activate_plugin(grab_interface))
{
init_view(view);
idle_deactivate.run_once([this] ()
{
output->deactivate_plugin(grab_interface);
});
}
} else
{
deinit_view(view);
}
}
void fini() override
{
for (auto& view : output->workspace->get_views_in_layer(wf::ALL_LAYERS))
{
deinit_view(view);
}
singleton_plugin_t::fini();
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_decoration);
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/vespalib/objects/hexdump.h>
#include <vespa/vespalib/test/insertion_operators.h>
#include <ostream>
using vespalib::nbostream;
using ExpBuffer = std::vector<uint8_t>;
namespace std
{
bool operator==(const std::vector<uint8_t> &exp, const nbostream &stream)
{
return ((exp.size() == stream.size()) &&
(memcmp(&exp[0], stream.peek(), exp.size()) == 0));
}
std::ostream &operator<<(std::ostream &out, const std::vector<uint8_t> &rhs)
{
out << vespalib::HexDump(&rhs[0], rhs.size());
return out;
}
template <typename T, typename U>
std::ostream &operator<<(std::ostream &out, const std::pair<T, U> &rhs)
{
out << "{ " << rhs.first << ", " << rhs.second << " }";
return out;
}
template <typename T>
std::ostream &
operator<<(std::ostream &os, const vespalib::Array<T> &set)
{
os << "{";
bool first = true;
for (const auto &entry : set) {
if (!first) {
os << ",";
}
os << entry;
first = false;
}
os << "}";
return os;
}
} // namespace std
struct Fixture
{
nbostream _stream;
template <typename T>
void
assertSerialize(const ExpBuffer &exp, const T &val)
{
_stream << val;
EXPECT_EQUAL(exp, _stream);
T checkVal = T();
_stream >> checkVal;
EXPECT_EQUAL(val, checkVal);
}
};
TEST_F("test serializing 64-bit signed integers", Fixture)
{
int64_t val = 0x0123456789ABCDEF;
f.assertSerialize({ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }, val);
}
TEST_F("test serializing 64-bit unsigned integers", Fixture)
{
uint64_t val = 0x0123456789ABCDEF;
f.assertSerialize({ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }, val);
}
TEST_F("test serializing 32-bit signed integers", Fixture)
{
int32_t val = 0x01234567;
f.assertSerialize({ 0x01, 0x23, 0x45, 0x67 }, val);
}
TEST_F("test serializing 32-bit unsigned integers", Fixture)
{
uint32_t val = 0x01234567;
f.assertSerialize({ 0x01, 0x23, 0x45, 0x67 }, val);
}
TEST_F("test serializing 16-bit signed integers", Fixture)
{
int16_t val = 0x0123;
f.assertSerialize({ 0x01, 0x23 }, val);
}
TEST_F("test serializing 16-bit unsigned integers", Fixture)
{
uint16_t val = 0x0123;
f.assertSerialize({ 0x01, 0x23 }, val);
}
TEST_F("test serializing 8-bit signed integers", Fixture)
{
int8_t val = 0x23;
f.assertSerialize({ 0x23 }, val);
}
TEST_F("test serializing 8-bit unsigned integers", Fixture)
{
uint8_t val = 0x23;
f.assertSerialize({ 0x23 }, val);
}
TEST_F("test serializing char", Fixture)
{
char val('A');
f.assertSerialize({ 0x41 }, val);
}
TEST_F("test serializing bool", Fixture)
{
bool myfalse = false;
bool mytrue = true;
ExpBuffer exp({ 0x00, 0x01 });
f._stream << myfalse << mytrue;
EXPECT_EQUAL(exp, f._stream);
bool checkFalse = true;
bool checkTrue = false;
f._stream >> checkFalse >> checkTrue;
EXPECT_FALSE(checkFalse);
EXPECT_TRUE(checkTrue);
}
TEST_F("test serializing double", Fixture)
{
double val = 1.5;
f.assertSerialize({ 0x3F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, val);
}
TEST_F("test serializing float", Fixture)
{
float val = -1.5;
f.assertSerialize({ 0xBF, 0xC0, 0x00, 0x00 }, val);
}
TEST_F("Test serializing c string", Fixture)
{
const char *cstr = "Hello";
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
f._stream << cstr;
EXPECT_EQUAL(exp, f._stream);
}
TEST_F("Test serializing stringref", Fixture)
{
vespalib::stringref val("Hello");
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
f._stream << val;
EXPECT_EQUAL(exp, f._stream);
}
TEST_F("Test serializing std::string", Fixture)
{
std::string val("Hello");
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
f.assertSerialize(exp, val);
}
TEST_F("Test serializing vespalib::string", Fixture)
{
vespalib::string val("Hello");
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
f.assertSerialize(exp, val);
}
TEST_F("Test serializing vespalib::Array", Fixture)
{
vespalib::Array<int16_t> val;
val.resize(2);
val[0] = 0x0123;
val[1] = 0x4567;
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x02, 0x01, 0x23, 0x45, 0x67 });
f.assertSerialize(exp, val);
}
TEST_F("Test serializing std::vector", Fixture)
{
std::vector<int16_t> val({ 0x0123, 0x4567 });
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x02, 0x01, 0x23, 0x45, 0x67 });
f.assertSerialize(exp, val);
}
TEST_F("Test serializing std::pair", Fixture)
{
std::pair<int16_t, int16_t> val({ 0x0123, 0x4567 });
ExpBuffer exp({ 0x01, 0x23, 0x45, 0x67 });
f.assertSerialize(exp, val);
}
TEST_F("Test saveVector", Fixture)
{
std::vector<int16_t> val({ 0x0123, 0x4567 });
val.reserve(16);
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
0x01, 0x23, 0x45, 0x67 });
f._stream.saveVector(val);
EXPECT_EQUAL(exp, f._stream);
std::vector<int16_t> checkVal;
f._stream.restoreVector(checkVal);
EXPECT_EQUAL(val, checkVal);
EXPECT_EQUAL(val.capacity(), checkVal.capacity());
}
TEST_F("Test write", Fixture)
{
f._stream.write("Hello", 5);
ExpBuffer exp({ 0x48, 0x65, 0x6c, 0x6c, 0x6f });
EXPECT_EQUAL(exp, f._stream);
EXPECT_EQUAL(5u, f._stream.size());
ExpBuffer rval(5);
f._stream.read(&rval[0], 5);
EXPECT_EQUAL(exp, rval);
}
TEST_F("Test putInt1_4", Fixture)
{
f._stream.putInt1_4Bytes(5);
EXPECT_EQUAL(ExpBuffer({ 0x05 }), f._stream);
uint32_t checkInt = f._stream.getInt1_4Bytes();
EXPECT_EQUAL(5u, checkInt);
EXPECT_EQUAL(0u, f._stream.size());
f._stream.clear();
f._stream.putInt1_4Bytes(1000);
EXPECT_EQUAL(ExpBuffer({ 0x80, 0x00, 0x03, 0xe8 }), f._stream);
checkInt = f._stream.getInt1_4Bytes();
EXPECT_EQUAL(1000u, checkInt);
EXPECT_EQUAL(0u, f._stream.size());
}
TEST_F("Test writeSmallString", Fixture)
{
f._stream.writeSmallString("Hello");
ExpBuffer exp({ 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
EXPECT_EQUAL(exp, f._stream);
vespalib::string checkString;
f._stream.readSmallString(checkString);
EXPECT_EQUAL("Hello", checkString);
EXPECT_EQUAL(0u, f._stream.size());
}
TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>Unbreak factory (vespalib)<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/vespalib/objects/nbostream.h>
#include <vespa/vespalib/objects/hexdump.h>
#include <vespa/vespalib/test/insertion_operators.h>
#include <ostream>
using vespalib::nbostream;
using ExpBuffer = std::vector<uint8_t>;
namespace std
{
bool operator==(const std::vector<uint8_t> &exp, const nbostream &stream)
{
return ((exp.size() == stream.size()) &&
(memcmp(&exp[0], stream.peek(), exp.size()) == 0));
}
std::ostream &operator<<(std::ostream &out, const std::vector<uint8_t> &rhs)
{
out << vespalib::HexDump(&rhs[0], rhs.size());
return out;
}
template <typename T>
std::ostream &
operator<<(std::ostream &os, const vespalib::Array<T> &set)
{
os << "{";
bool first = true;
for (const auto &entry : set) {
if (!first) {
os << ",";
}
os << entry;
first = false;
}
os << "}";
return os;
}
} // namespace std
struct Fixture
{
nbostream _stream;
template <typename T>
void
assertSerialize(const ExpBuffer &exp, const T &val)
{
_stream << val;
EXPECT_EQUAL(exp, _stream);
T checkVal = T();
_stream >> checkVal;
EXPECT_EQUAL(val, checkVal);
}
};
TEST_F("test serializing 64-bit signed integers", Fixture)
{
int64_t val = 0x0123456789ABCDEF;
f.assertSerialize({ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }, val);
}
TEST_F("test serializing 64-bit unsigned integers", Fixture)
{
uint64_t val = 0x0123456789ABCDEF;
f.assertSerialize({ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF }, val);
}
TEST_F("test serializing 32-bit signed integers", Fixture)
{
int32_t val = 0x01234567;
f.assertSerialize({ 0x01, 0x23, 0x45, 0x67 }, val);
}
TEST_F("test serializing 32-bit unsigned integers", Fixture)
{
uint32_t val = 0x01234567;
f.assertSerialize({ 0x01, 0x23, 0x45, 0x67 }, val);
}
TEST_F("test serializing 16-bit signed integers", Fixture)
{
int16_t val = 0x0123;
f.assertSerialize({ 0x01, 0x23 }, val);
}
TEST_F("test serializing 16-bit unsigned integers", Fixture)
{
uint16_t val = 0x0123;
f.assertSerialize({ 0x01, 0x23 }, val);
}
TEST_F("test serializing 8-bit signed integers", Fixture)
{
int8_t val = 0x23;
f.assertSerialize({ 0x23 }, val);
}
TEST_F("test serializing 8-bit unsigned integers", Fixture)
{
uint8_t val = 0x23;
f.assertSerialize({ 0x23 }, val);
}
TEST_F("test serializing char", Fixture)
{
char val('A');
f.assertSerialize({ 0x41 }, val);
}
TEST_F("test serializing bool", Fixture)
{
bool myfalse = false;
bool mytrue = true;
ExpBuffer exp({ 0x00, 0x01 });
f._stream << myfalse << mytrue;
EXPECT_EQUAL(exp, f._stream);
bool checkFalse = true;
bool checkTrue = false;
f._stream >> checkFalse >> checkTrue;
EXPECT_FALSE(checkFalse);
EXPECT_TRUE(checkTrue);
}
TEST_F("test serializing double", Fixture)
{
double val = 1.5;
f.assertSerialize({ 0x3F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, val);
}
TEST_F("test serializing float", Fixture)
{
float val = -1.5;
f.assertSerialize({ 0xBF, 0xC0, 0x00, 0x00 }, val);
}
TEST_F("Test serializing c string", Fixture)
{
const char *cstr = "Hello";
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
f._stream << cstr;
EXPECT_EQUAL(exp, f._stream);
}
TEST_F("Test serializing stringref", Fixture)
{
vespalib::stringref val("Hello");
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
f._stream << val;
EXPECT_EQUAL(exp, f._stream);
}
TEST_F("Test serializing std::string", Fixture)
{
std::string val("Hello");
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
f.assertSerialize(exp, val);
}
TEST_F("Test serializing vespalib::string", Fixture)
{
vespalib::string val("Hello");
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
f.assertSerialize(exp, val);
}
TEST_F("Test serializing vespalib::Array", Fixture)
{
vespalib::Array<int16_t> val;
val.resize(2);
val[0] = 0x0123;
val[1] = 0x4567;
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x02, 0x01, 0x23, 0x45, 0x67 });
f.assertSerialize(exp, val);
}
TEST_F("Test serializing std::vector", Fixture)
{
std::vector<int16_t> val({ 0x0123, 0x4567 });
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x02, 0x01, 0x23, 0x45, 0x67 });
f.assertSerialize(exp, val);
}
TEST_F("Test serializing std::pair", Fixture)
{
std::pair<int16_t, int16_t> val({ 0x0123, 0x4567 });
ExpBuffer exp({ 0x01, 0x23, 0x45, 0x67 });
f.assertSerialize(exp, val);
}
TEST_F("Test saveVector", Fixture)
{
std::vector<int16_t> val({ 0x0123, 0x4567 });
val.reserve(16);
ExpBuffer exp({ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
0x01, 0x23, 0x45, 0x67 });
f._stream.saveVector(val);
EXPECT_EQUAL(exp, f._stream);
std::vector<int16_t> checkVal;
f._stream.restoreVector(checkVal);
EXPECT_EQUAL(val, checkVal);
EXPECT_EQUAL(val.capacity(), checkVal.capacity());
}
TEST_F("Test write", Fixture)
{
f._stream.write("Hello", 5);
ExpBuffer exp({ 0x48, 0x65, 0x6c, 0x6c, 0x6f });
EXPECT_EQUAL(exp, f._stream);
EXPECT_EQUAL(5u, f._stream.size());
ExpBuffer rval(5);
f._stream.read(&rval[0], 5);
EXPECT_EQUAL(exp, rval);
}
TEST_F("Test putInt1_4", Fixture)
{
f._stream.putInt1_4Bytes(5);
EXPECT_EQUAL(ExpBuffer({ 0x05 }), f._stream);
uint32_t checkInt = f._stream.getInt1_4Bytes();
EXPECT_EQUAL(5u, checkInt);
EXPECT_EQUAL(0u, f._stream.size());
f._stream.clear();
f._stream.putInt1_4Bytes(1000);
EXPECT_EQUAL(ExpBuffer({ 0x80, 0x00, 0x03, 0xe8 }), f._stream);
checkInt = f._stream.getInt1_4Bytes();
EXPECT_EQUAL(1000u, checkInt);
EXPECT_EQUAL(0u, f._stream.size());
}
TEST_F("Test writeSmallString", Fixture)
{
f._stream.writeSmallString("Hello");
ExpBuffer exp({ 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f });
EXPECT_EQUAL(exp, f._stream);
vespalib::string checkString;
f._stream.readSmallString(checkString);
EXPECT_EQUAL("Hello", checkString);
EXPECT_EQUAL(0u, f._stream.size());
}
TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|> |
<commit_before>#include <errno.h>
#include <stdlib.h>
#include <getopt.h>
#include <boost/foreach.hpp>
#include <boost/asio/ip/address.hpp>
#include <libwatcher/connectivityMessage.h>
#include "logger.h"
#include "client.h"
#include "sendMessageHandler.h"
using namespace std;
using namespace watcher;
using namespace watcher::event;
void usage(const char *progName)
{
fprintf(stderr, "Usage: %s -s|--servername server [-l|--logProps log.propertiesFile] [-f|--fromNode fromNodeAddr] nbr1 nbr2 ... nbrN\n", basename(progName));
fprintf(stderr, "Where:\n");
fprintf(stderr, "\tnbr1 nbr2 ... nbrN is a list of ip addresses that the node is connected to.\n");
fprintf(stderr, "\tserver is the server address or hostname\n");
fprintf(stderr, "\tfromNodeAddr is the address of the node the neighbors are attached to.\n");
exit(1);
}
int main(int argc, char **argv)
{
int c;
char *serverName=NULL;
char *logProps=NULL;
boost::asio::ip::address_v4 fromNodeAddr;
while (true)
{
int option_index = 0;
static struct option long_options[] = {
{"logProps", required_argument, 0, 'l'},
{"servername", required_argument, 0, 's'},
{"fromNode", required_argument, 0, 'f'},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "l:s:f:hH?", long_options, &option_index);
if (c == -1)
break;
switch(c)
{
case 'l':
logProps = strdup(optarg); // buffer overflow here. :)
break;
case 's':
serverName = strdup(optarg); // buffer overflow here :)
break;
case 'f':
fromNodeAddr=boost::asio::ip::address_v4::from_string(optarg);
break;
case 'h':
case 'H':
case '?':
default:
usage(argv[0]);
break;
}
}
if (!serverName)
{
usage(argv[0]);
if (serverName)
free(serverName);
if (logProps)
free(logProps);
exit(1);
}
//
// Now do some actual work.
//
printf("Initializing logging system\n");
LOAD_LOG_PROPS(logProps ? logProps : "sendMessage.log.properties");
LOG_DEBUG("Args: server: " << serverName << " fromAddr: " << fromNodeAddr << " logProps: " << logProps);
watcher::Client client(serverName);
client.addMessageHandler(SendMessageHandler::create());
printf("Connecting to %s and sending message.\n", serverName);
ConnectivityMessagePtr cm(new ConnectivityMessage);
if(fromNodeAddr!=boost::asio::ip::address_v4())
{
LOG_DEBUG("Setting from address on message to " << fromNodeAddr);
cm->fromNodeID=fromNodeAddr;
}
for(int i=optind; i<argc; i++)
{
boost::system::error_code ec;
NodeIdentifier addr=NodeIdentifier::from_string(argv[i], ec);
if(!ec)
cm->neighbors.push_back(addr);
else
LOG_ERROR("Ignoring non address arguement: " << argv[i]);
}
LOG_DEBUG("Sending Message: " << *cm);
if(!client.sendMessage(cm))
{
LOG_ERROR("Error sending gps message: " << *cm);
free(serverName);
if (logProps)
free(logProps);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
client.wait();
free(serverName);
if (logProps)
free(logProps);
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
}
<commit_msg>Allow layer to be specified on the command line for sendConnectivityMesssage.<commit_after>#include <errno.h>
#include <stdlib.h>
#include <getopt.h>
#include <boost/foreach.hpp>
#include <boost/asio/ip/address.hpp>
#include <libwatcher/connectivityMessage.h>
#include "logger.h"
#include "client.h"
#include "sendMessageHandler.h"
using namespace std;
using namespace watcher;
using namespace watcher::event;
void usage(const char *progName)
{
fprintf(stderr, "Usage: %s -s|--servername server [-l|--logProps log.propertiesFile] [-f|--fromNode fromNodeAddr] nbr1 nbr2 ... nbrN\n", basename(progName));
fprintf(stderr, "Where:\n");
fprintf(stderr, "\tnbr1 nbr2 ... nbrN is a list of ip addresses that the node is connected to.\n");
fprintf(stderr, "\tserver is the server address or hostname\n");
fprintf(stderr, "\tfromNodeAddr is the address of the node the neighbors are attached to.\n");
exit(1);
}
int main(int argc, char **argv)
{
int c;
char *serverName=NULL;
char *logProps=NULL;
GUILayer layer(PHYSICAL_LAYER);
boost::asio::ip::address_v4 fromNodeAddr;
while (true)
{
int option_index = 0;
static struct option long_options[] = {
{"logProps", required_argument, 0, 'p'},
{"servername", required_argument, 0, 's'},
{"fromNode", required_argument, 0, 'f'},
{"layer", required_argument, 0, 'l'},
{0, 0, 0, 0}
};
c = getopt_long(argc, argv, "p:s:f:l:hH?", long_options, &option_index);
if (c == -1)
break;
switch(c)
{
case 'p':
logProps = strdup(optarg); // buffer overflow here. :)
break;
case 's':
serverName = strdup(optarg); // buffer overflow here :)
break;
case 'f':
fromNodeAddr=boost::asio::ip::address_v4::from_string(optarg);
break;
case 'l':
layer = strdup(optarg);
break;
case 'h':
case 'H':
case '?':
default:
usage(argv[0]);
break;
}
}
if (!serverName)
{
usage(argv[0]);
if (serverName)
free(serverName);
if (logProps)
free(logProps);
exit(1);
}
//
// Now do some actual work.
//
printf("Initializing logging system\n");
LOAD_LOG_PROPS(logProps ? logProps : "sendMessage.log.properties");
LOG_DEBUG("Args: server: " << serverName << " fromAddr: " << fromNodeAddr << " logProps: " << logProps);
watcher::Client client(serverName);
client.addMessageHandler(SendMessageHandler::create());
printf("Connecting to %s and sending message.\n", serverName);
ConnectivityMessagePtr cm(new ConnectivityMessage);
if(fromNodeAddr!=boost::asio::ip::address_v4())
{
LOG_DEBUG("Setting from address on message to " << fromNodeAddr);
cm->fromNodeID=fromNodeAddr;
}
cm->layer=layer;
for(int i=optind; i<argc; i++)
{
boost::system::error_code ec;
NodeIdentifier addr=NodeIdentifier::from_string(argv[i], ec);
if(!ec)
cm->neighbors.push_back(addr);
else
LOG_ERROR("Ignoring non address arguement: " << argv[i]);
}
LOG_DEBUG("Sending Message: " << *cm);
if(!client.sendMessage(cm))
{
LOG_ERROR("Error sending gps message: " << *cm);
free(serverName);
if (logProps)
free(logProps);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
client.wait();
free(serverName);
if (logProps)
free(logProps);
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "vie_autotest.h"
#include "base_primitives.h"
#include "general_primitives.h"
#include "tb_interfaces.h"
#include "vie_autotest_defines.h"
#include "video_capture_factory.h"
class BaseObserver : public webrtc::ViEBaseObserver {
public:
BaseObserver()
: cpu_load_(0) {}
virtual void PerformanceAlarm(const unsigned int cpu_load) {
cpu_load_ = cpu_load;
}
unsigned int cpu_load_;
};
void ViEAutoTest::ViEBaseStandardTest() {
// ***************************************************************
// Begin create/initialize WebRTC Video Engine for testing
// ***************************************************************
TbInterfaces interfaces("ViEBaseStandardTest");
// ***************************************************************
// Engine ready. Set up the test case:
// ***************************************************************
int video_channel = -1;
EXPECT_EQ(0, interfaces.base->CreateChannel(video_channel));
webrtc::VideoCaptureModule* video_capture_module(NULL);
const unsigned int kMaxDeviceNameLength = 128;
char device_name[kMaxDeviceNameLength];
memset(device_name, 0, kMaxDeviceNameLength);
int capture_id;
webrtc::ViEBase *base_interface = interfaces.base;
webrtc::ViERender *render_interface = interfaces.render;
webrtc::ViECapture *capture_interface = interfaces.capture;
FindCaptureDeviceOnSystem(capture_interface,
device_name,
kMaxDeviceNameLength,
&capture_id,
&video_capture_module);
EXPECT_EQ(0, capture_interface->ConnectCaptureDevice(capture_id,
video_channel));
EXPECT_EQ(0, capture_interface->StartCapture(capture_id));
ConfigureRtpRtcp(interfaces.rtp_rtcp, video_channel);
EXPECT_EQ(0, render_interface->RegisterVideoRenderModule(*_vrm1));
EXPECT_EQ(0, render_interface->RegisterVideoRenderModule(*_vrm2));
RenderInWindow(render_interface, capture_id, _window1, 0);
RenderInWindow(render_interface, video_channel, _window2, 1);
// ***************************************************************
// Run the actual test:
// ***************************************************************
ViETest::Log("You should shortly see a local preview from camera %s"
" in window 1 and the remote video in window 2.", device_name);
::TestI420CallSetup(interfaces.codec, interfaces.video_engine,
base_interface, interfaces.network, video_channel,
device_name);
// ***************************************************************
// Testing finished. Tear down Video Engine
// ***************************************************************
EXPECT_EQ(0, capture_interface->StopCapture(capture_id));
EXPECT_EQ(0, base_interface->StopReceive(video_channel));
StopAndRemoveRenderers(base_interface, render_interface, video_channel,
capture_id);
EXPECT_EQ(0, render_interface->DeRegisterVideoRenderModule(*_vrm1));
EXPECT_EQ(0, render_interface->DeRegisterVideoRenderModule(*_vrm2));
EXPECT_EQ(0, capture_interface->ReleaseCaptureDevice(capture_id));
video_capture_module->Release();
video_capture_module = NULL;
EXPECT_EQ(0, base_interface->DeleteChannel(video_channel));
}
void ViEAutoTest::ViEBaseExtendedTest() {
// Start with standard test
ViEBaseAPITest();
ViEBaseStandardTest();
// ***************************************************************
// Test BaseObserver
// ***************************************************************
// TODO(mflodman) Add test for base observer. Cpu load must be over 75%.
// BaseObserver base_observer;
// EXPECT_EQ(ptrViEBase->RegisterObserver(base_observer), 0);
//
// AutoTestSleep(KAutoTestSleepTimeMs);
//
// EXPECT_EQ(ptrViEBase->DeregisterObserver(), 0);
// EXPECT_GT(base_observer.cpu_load, 0);
}
void ViEAutoTest::ViEBaseAPITest() {
// ***************************************************************
// Begin create/initialize WebRTC Video Engine for testing
// ***************************************************************
// Get the ViEBase API
webrtc::ViEBase* ptrViEBase = webrtc::ViEBase::GetInterface(NULL);
EXPECT_EQ(NULL, ptrViEBase) << "Should return null for a bad ViE pointer";
webrtc::VideoEngine* ptrViE = webrtc::VideoEngine::Create();
EXPECT_TRUE(NULL != ptrViE);
std::string trace_file_path =
ViETest::GetResultOutputPath() + "ViEBaseAPI_trace.txt";
EXPECT_EQ(0, ptrViE->SetTraceFile(trace_file_path.c_str()));
ptrViEBase = webrtc::ViEBase::GetInterface(ptrViE);
EXPECT_TRUE(NULL != ptrViEBase);
// ***************************************************************
// Engine ready. Begin testing class
// ***************************************************************
char version[1024] = "";
EXPECT_EQ(0, ptrViEBase->GetVersion(version));
EXPECT_EQ(0, ptrViEBase->LastError());
// Create without init
int videoChannel = -1;
EXPECT_NE(0, ptrViEBase->CreateChannel(videoChannel)) <<
"Should fail since Init has not been called yet";
EXPECT_EQ(0, ptrViEBase->Init());
EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel));
int videoChannel2 = -1;
EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel2));
EXPECT_NE(videoChannel, videoChannel2) <<
"Should allocate new number for independent channel";
EXPECT_EQ(0, ptrViEBase->DeleteChannel(videoChannel2));
EXPECT_EQ(-1, ptrViEBase->CreateChannel(videoChannel2, videoChannel + 1)) <<
"Should fail since neither channel exists (the second must)";
EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel2, videoChannel));
// Test Voice Engine integration with Video Engine.
webrtc::VoiceEngine* ptrVoE = NULL;
webrtc::VoEBase* ptrVoEBase = NULL;
int audioChannel = -1;
ptrVoE = webrtc::VoiceEngine::Create();
EXPECT_TRUE(NULL != ptrVoE);
ptrVoEBase = webrtc::VoEBase::GetInterface(ptrVoE);
EXPECT_TRUE(NULL != ptrVoEBase);
EXPECT_EQ(0, ptrVoEBase->Init());
audioChannel = ptrVoEBase->CreateChannel();
EXPECT_NE(-1, audioChannel);
// Connect before setting VoE.
EXPECT_NE(0, ptrViEBase->ConnectAudioChannel(videoChannel, audioChannel)) <<
"Should fail since Voice Engine is not set yet.";
// Then do it right.
EXPECT_EQ(0, ptrViEBase->SetVoiceEngine(ptrVoE));
EXPECT_EQ(0, ptrViEBase->ConnectAudioChannel(videoChannel, audioChannel));
// ***************************************************************
// Testing finished. Tear down Video Engine
// ***************************************************************
EXPECT_NE(0, ptrViEBase->DisconnectAudioChannel(videoChannel + 5)) <<
"Should fail: disconnecting bogus channel";
EXPECT_EQ(0, ptrViEBase->DisconnectAudioChannel(videoChannel));
// Clean up voice engine
EXPECT_EQ(0, ptrViEBase->SetVoiceEngine(NULL));
EXPECT_EQ(0, ptrVoEBase->Release());
EXPECT_TRUE(webrtc::VoiceEngine::Delete(ptrVoE));
webrtc::ViEBase* ptrViEBase2 = webrtc::ViEBase::GetInterface(ptrViE);
EXPECT_TRUE(NULL != ptrViEBase2);
EXPECT_EQ(1, ptrViEBase->Release()) << "There should be one interface left.";
EXPECT_FALSE(webrtc::VideoEngine::Delete(ptrViE)) <<
"Should fail since there are interfaces left.";
EXPECT_EQ(0, ptrViEBase->Release());
EXPECT_TRUE(webrtc::VideoEngine::Delete(ptrViE));
}
<commit_msg>nits<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "vie_autotest.h"
#include "base_primitives.h"
#include "general_primitives.h"
#include "tb_interfaces.h"
#include "vie_autotest_defines.h"
#include "video_capture_factory.h"
class BaseObserver : public webrtc::ViEBaseObserver {
public:
BaseObserver()
: cpu_load_(0) {}
virtual void PerformanceAlarm(const unsigned int cpu_load) {
cpu_load_ = cpu_load;
}
unsigned int cpu_load_;
};
void ViEAutoTest::ViEBaseStandardTest() {
// ***************************************************************
// Begin create/initialize WebRTC Video Engine for testing
// ***************************************************************
TbInterfaces interfaces("ViEBaseStandardTest");
// ***************************************************************
// Engine ready. Set up the test case:
// ***************************************************************
int video_channel = -1;
EXPECT_EQ(0, interfaces.base->CreateChannel(video_channel));
webrtc::VideoCaptureModule* video_capture_module(NULL);
const unsigned int kMaxDeviceNameLength = 128;
char device_name[kMaxDeviceNameLength];
memset(device_name, 0, kMaxDeviceNameLength);
int capture_id;
webrtc::ViEBase *base_interface = interfaces.base;
webrtc::ViERender *render_interface = interfaces.render;
webrtc::ViECapture *capture_interface = interfaces.capture;
FindCaptureDeviceOnSystem(capture_interface,
device_name,
kMaxDeviceNameLength,
&capture_id,
&video_capture_module);
EXPECT_EQ(0, capture_interface->ConnectCaptureDevice(capture_id,
video_channel));
EXPECT_EQ(0, capture_interface->StartCapture(capture_id));
ConfigureRtpRtcp(interfaces.rtp_rtcp, video_channel);
EXPECT_EQ(0, render_interface->RegisterVideoRenderModule(*_vrm1));
EXPECT_EQ(0, render_interface->RegisterVideoRenderModule(*_vrm2));
RenderInWindow(render_interface, capture_id, _window1, 0);
RenderInWindow(render_interface, video_channel, _window2, 1);
// ***************************************************************
// Run the actual test:
// ***************************************************************
ViETest::Log("You should shortly see a local preview from camera %s"
" in window 1 and the remote video in window 2.", device_name);
::TestI420CallSetup(interfaces.codec, interfaces.video_engine,
base_interface, interfaces.network, video_channel,
device_name);
// ***************************************************************
// Testing finished. Tear down Video Engine
// ***************************************************************
EXPECT_EQ(0, capture_interface->StopCapture(capture_id));
EXPECT_EQ(0, base_interface->StopReceive(video_channel));
StopAndRemoveRenderers(base_interface, render_interface, video_channel,
capture_id);
EXPECT_EQ(0, render_interface->DeRegisterVideoRenderModule(*_vrm1));
EXPECT_EQ(0, render_interface->DeRegisterVideoRenderModule(*_vrm2));
EXPECT_EQ(0, capture_interface->ReleaseCaptureDevice(capture_id));
video_capture_module->Release();
video_capture_module = NULL;
EXPECT_EQ(0, base_interface->DeleteChannel(video_channel));
}
void ViEAutoTest::ViEBaseExtendedTest() {
// Start with standard test
ViEBaseAPITest();
ViEBaseStandardTest();
// ***************************************************************
// Test BaseObserver
// ***************************************************************
// TODO(mflodman) Add test for base observer. Cpu load must be over 75%.
// BaseObserver base_observer;
// EXPECT_EQ(ptrViEBase->RegisterObserver(base_observer), 0);
//
// AutoTestSleep(KAutoTestSleepTimeMs);
//
// EXPECT_EQ(ptrViEBase->DeregisterObserver(), 0);
// EXPECT_GT(base_observer.cpu_load, 0);
}
void ViEAutoTest::ViEBaseAPITest() {
// ***************************************************************
// Begin create/initialize WebRTC Video Engine for testing
// ***************************************************************
// Get the ViEBase API
webrtc::ViEBase* ptrViEBase = webrtc::ViEBase::GetInterface(NULL);
EXPECT_EQ(NULL, ptrViEBase) << "Should return null for a bad ViE pointer";
webrtc::VideoEngine* ptrViE = webrtc::VideoEngine::Create();
EXPECT_TRUE(NULL != ptrViE);
std::string trace_file_path =
ViETest::GetResultOutputPath() + "ViEBaseAPI_trace.txt";
EXPECT_EQ(0, ptrViE->SetTraceFile(trace_file_path.c_str()));
ptrViEBase = webrtc::ViEBase::GetInterface(ptrViE);
EXPECT_TRUE(NULL != ptrViEBase);
// ***************************************************************
// Engine ready. Begin testing class
// ***************************************************************
char version[1024] = "";
EXPECT_EQ(0, ptrViEBase->GetVersion(version));
EXPECT_EQ(0, ptrViEBase->LastError());
// Create without init
int videoChannel = -1;
EXPECT_NE(0, ptrViEBase->CreateChannel(videoChannel)) <<
"Should fail since Init has not been called yet";
EXPECT_EQ(0, ptrViEBase->Init());
EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel));
int videoChannel2 = -1;
EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel2));
EXPECT_NE(videoChannel, videoChannel2) <<
"Should allocate new number for independent channel";
EXPECT_EQ(0, ptrViEBase->DeleteChannel(videoChannel2));
EXPECT_EQ(-1, ptrViEBase->CreateChannel(videoChannel2, videoChannel + 1)) <<
"Should fail since neither channel exists (the second must)";
EXPECT_EQ(0, ptrViEBase->CreateChannel(videoChannel2, videoChannel));
// Test Voice Engine integration with Video Engine.
webrtc::VoiceEngine* ptrVoE = NULL;
webrtc::VoEBase* ptrVoEBase = NULL;
int audioChannel = -1;
ptrVoE = webrtc::VoiceEngine::Create();
EXPECT_TRUE(NULL != ptrVoE);
ptrVoEBase = webrtc::VoEBase::GetInterface(ptrVoE);
EXPECT_TRUE(NULL != ptrVoEBase);
EXPECT_EQ(0, ptrVoEBase->Init());
audioChannel = ptrVoEBase->CreateChannel();
EXPECT_NE(-1, audioChannel);
// Connect before setting VoE.
EXPECT_NE(0, ptrViEBase->ConnectAudioChannel(videoChannel, audioChannel)) <<
"Should fail since Voice Engine is not set yet.";
// Then do it right.
EXPECT_EQ(0, ptrViEBase->SetVoiceEngine(ptrVoE));
EXPECT_EQ(0, ptrViEBase->ConnectAudioChannel(videoChannel, audioChannel));
// ***************************************************************
// Testing finished. Tear down Video Engine
// ***************************************************************
EXPECT_NE(0, ptrViEBase->DisconnectAudioChannel(videoChannel + 5)) <<
"Should fail: disconnecting bogus channel";
EXPECT_EQ(0, ptrViEBase->DisconnectAudioChannel(videoChannel));
// Clean up voice engine
EXPECT_EQ(0, ptrViEBase->SetVoiceEngine(NULL));
EXPECT_EQ(0, ptrVoEBase->Release());
EXPECT_TRUE(webrtc::VoiceEngine::Delete(ptrVoE));
webrtc::ViEBase* ptrViEBase2 = webrtc::ViEBase::GetInterface(ptrViE);
EXPECT_TRUE(NULL != ptrViEBase2);
EXPECT_EQ(1, ptrViEBase->Release()) << "There should be one interface left.";
EXPECT_FALSE(webrtc::VideoEngine::Delete(ptrViE)) <<
"Should fail since there are interfaces left.";
EXPECT_EQ(0, ptrViEBase->Release());
EXPECT_TRUE(webrtc::VideoEngine::Delete(ptrViE));
}
<|endoftext|> |
<commit_before><commit_msg>loplugin:stringconstant: handle OUString+=OUString(literal)<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2007 Kevin Ollivier <[email protected]>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "PlatformWheelEvent.h"
#include <wx/defs.h>
#include <wx/event.h>
namespace WebCore {
PlatformWheelEvent::PlatformWheelEvent(const wxMouseEvent& event, const wxPoint& globalPoint)
: m_position(event.GetPosition())
, m_globalPosition(globalPoint)
, m_shiftKey(event.ShiftDown())
, m_ctrlKey(event.ControlDown())
, m_altKey(event.AltDown())
, m_metaKey(event.MetaDown()) // FIXME: We'll have to test other browsers
, m_deltaX(0) // wx doesn't support horizontal mouse wheel scrolling
, m_deltaY(event.GetWheelRotation() / event.GetWheelDelta())
, m_isAccepted(false)
, m_isContinuous(false)
, m_continuousDeltaX(0)
, m_continuousDeltaY(0)
{
// FIXME: retrieve the user setting for the number of lines to scroll on each wheel event
m_charsToScrollPerDelta = 1;
m_linesToScrollPerDelta = 1;
m_pageXScrollMode = false;
m_pageYScrollMode = false;
}
}
<commit_msg>Fix wx bustage.<commit_after>/*
* Copyright (C) 2007 Kevin Ollivier <[email protected]>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "PlatformWheelEvent.h"
#include <wx/defs.h>
#include <wx/event.h>
namespace WebCore {
PlatformWheelEvent::PlatformWheelEvent(const wxMouseEvent& event, const wxPoint& globalPoint)
: m_position(event.GetPosition())
, m_globalPosition(globalPoint)
, m_granularity(ScrollByLineWheelEvent)
, m_shiftKey(event.ShiftDown())
, m_ctrlKey(event.ControlDown())
, m_altKey(event.AltDown())
, m_metaKey(event.MetaDown()) // FIXME: We'll have to test other browsers
, m_deltaX(0) // wx doesn't support horizontal mouse wheel scrolling
, m_deltaY(event.GetWheelRotation() / event.GetWheelDelta())
, m_isAccepted(false)
{
// FIXME: retrieve the user setting for the number of lines to scroll on each wheel event
m_deltaY *= horizontalLineMultiplier();
}
}
<|endoftext|> |
<commit_before>/*
* TableFlagFilter.cpp
*
* Copyright (C) 2020 by VISUS (University of Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "TableFlagFilter.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/utility/log/Log.h"
using namespace megamol::stdplugin::datatools;
using namespace megamol::stdplugin::datatools::table;
using namespace megamol;
TableFlagFilter::TableFlagFilter()
: core::Module()
, tableInSlot("getDataIn", "Float table input")
, flagStorageInSlot("readFlagStorage", "Flag storage read input")
, tableOutSlot("getDataOut", "Float table output")
, filterModeParam("filterMode", "filter mode")
, tableInFrameCount(0)
, tableInDataHash(0)
, tableInColCount(0)
, dataHash(0)
, rowCount(0) {
this->tableInSlot.SetCompatibleCall<TableDataCallDescription>();
this->MakeSlotAvailable(&this->tableInSlot);
this->flagStorageInSlot.SetCompatibleCall<core::FlagCallRead_GLDescription>();
this->MakeSlotAvailable(&this->flagStorageInSlot);
this->tableOutSlot.SetCallback(TableDataCall::ClassName(),
TableDataCall::FunctionName(0),
&TableFlagFilter::getData);
this->tableOutSlot.SetCallback(TableDataCall::ClassName(),
TableDataCall::FunctionName(1),
&TableFlagFilter::getHash);
this->MakeSlotAvailable(&this->tableOutSlot);
auto* fmp = new core::param::EnumParam(FilterMode::FILTERED);
fmp->SetTypePair(FilterMode::FILTERED, "Filtered");
fmp->SetTypePair(FilterMode::SELECTED, "Selected");
this->filterModeParam << fmp;
this->MakeSlotAvailable(&this->filterModeParam);
}
TableFlagFilter::~TableFlagFilter() {
this->Release();
}
bool TableFlagFilter::create() {
return true;
}
void TableFlagFilter::release() {
}
bool TableFlagFilter::getData(core::Call &call) {
if (!this->handleCall(call)) {
return false;
}
auto *tableOutCall = dynamic_cast<TableDataCall *>(&call);
tableOutCall->SetFrameCount(this->tableInFrameCount);
tableOutCall->SetDataHash(this->dataHash);
tableOutCall->Set(this->tableInColCount, this->rowCount, this->colInfos.data(), this->data.data());
return true;
}
bool TableFlagFilter::getHash(core::Call &call) {
if (!this->handleCall(call)) {
return false;
}
auto *tableOutCall = dynamic_cast<TableDataCall *>(&call);
tableOutCall->SetFrameCount(this->tableInFrameCount);
tableOutCall->SetDataHash(this->dataHash);
return true;
}
bool TableFlagFilter::handleCall(core::Call &call) {
auto *tableOutCall = dynamic_cast<TableDataCall *>(&call);
auto *tableInCall = this->tableInSlot.CallAs<TableDataCall>();
auto *flagsInCall = this->flagStorageInSlot.CallAs<core::FlagCallRead_GL>();
if (tableOutCall == nullptr) {
return false;
}
if (tableInCall == nullptr) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(
megamol::core::utility::log::Log::LEVEL_ERROR, "TableFlagFilter requires a table!");
return false;
}
if (flagsInCall == nullptr) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(
megamol::core::utility::log::Log::LEVEL_ERROR, "TableFlagFilter requires a flag storage!");
return false;
}
tableInCall->SetFrameID(tableOutCall->GetFrameID());
(*tableInCall)(1);
(*tableInCall)(0);
(*flagsInCall)(core::FlagCallRead_GL::CallGetData);
if (this->tableInFrameCount != tableInCall->GetFrameCount() || this->tableInDataHash != tableInCall->DataHash() || flagsInCall->hasUpdate()) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_INFO, "TableFlagFilter: Filter table.");
this->dataHash++;
this->tableInFrameCount = tableInCall->GetFrameCount();
this->tableInDataHash = tableInCall->DataHash();
this->tableInColCount = tableInCall->GetColumnsCount();
size_t tableInRowCount = tableInCall->GetRowsCount();
// download flags
flagsInCall->getData()->validateFlagCount(tableInRowCount);
auto flags = flagsInCall->getData()->flags;
uint32_t *flagsData = new uint32_t[flags->getByteSize() / sizeof(uint32_t)];
flags->bind();
glGetBufferSubData(flags->getTarget(), 0, flags->getByteSize(), flagsData);
// copy column infos
this->colInfos.resize(this->tableInColCount);
for (size_t i = 0; i < this->tableInColCount; ++i) {
this->colInfos[i] = tableInCall->GetColumnsInfos()[i];
this->colInfos[i].SetMinimumValue(std::numeric_limits<float>::max());
this->colInfos[i].SetMaximumValue(std::numeric_limits<float>::lowest());
}
core::FlagStorage::FlagItemType testMask = core::FlagStorage::ENABLED | core::FlagStorage::FILTERED;
core::FlagStorage::FlagItemType passMask = core::FlagStorage::ENABLED;;
if (static_cast<FilterMode>(this->filterModeParam.Param<core::param::EnumParam>()->Value()) == FilterMode::SELECTED) {
testMask = core::FlagStorage::ENABLED | core::FlagStorage::SELECTED | core::FlagStorage::FILTERED;
passMask = core::FlagStorage::ENABLED | core::FlagStorage::SELECTED;
}
// Resize data to size of input table. With this we only need to allocate memory once.
this->data.resize(this->tableInColCount * tableInRowCount);
this->rowCount = 0;
const float *tableInData = tableInCall->GetData();
for (size_t r = 0; r < tableInRowCount; ++r) {
if ((flagsData[r] & testMask) == passMask) {
for (size_t c = 0; c < this->tableInColCount; ++c) {
float val = tableInData[this->tableInColCount * r + c];
this->data[this->tableInColCount * this->rowCount + c] = val;
if (val < this->colInfos[c].MinimumValue()) {
this->colInfos[c].SetMinimumValue(val);
}
if (val > this->colInfos[c].MaximumValue()) {
this->colInfos[c].SetMaximumValue(val);
}
}
this->rowCount++;
}
}
// delete memory of filtered rows
this->data.resize(this->tableInColCount * this->rowCount);
delete[] flagsData;
// nicer output
if (this->rowCount == 0) {
for (size_t i = 0; i < this->tableInColCount; ++i) {
this->colInfos[i].SetMinimumValue(0.0);
this->colInfos[i].SetMaximumValue(0.0);
}
}
}
return true;
}
<commit_msg>less verbose table flag filter<commit_after>/*
* TableFlagFilter.cpp
*
* Copyright (C) 2020 by VISUS (University of Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "TableFlagFilter.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/utility/log/Log.h"
using namespace megamol::stdplugin::datatools;
using namespace megamol::stdplugin::datatools::table;
using namespace megamol;
TableFlagFilter::TableFlagFilter()
: core::Module()
, tableInSlot("getDataIn", "Float table input")
, flagStorageInSlot("readFlagStorage", "Flag storage read input")
, tableOutSlot("getDataOut", "Float table output")
, filterModeParam("filterMode", "filter mode")
, tableInFrameCount(0)
, tableInDataHash(0)
, tableInColCount(0)
, dataHash(0)
, rowCount(0) {
this->tableInSlot.SetCompatibleCall<TableDataCallDescription>();
this->MakeSlotAvailable(&this->tableInSlot);
this->flagStorageInSlot.SetCompatibleCall<core::FlagCallRead_GLDescription>();
this->MakeSlotAvailable(&this->flagStorageInSlot);
this->tableOutSlot.SetCallback(TableDataCall::ClassName(),
TableDataCall::FunctionName(0),
&TableFlagFilter::getData);
this->tableOutSlot.SetCallback(TableDataCall::ClassName(),
TableDataCall::FunctionName(1),
&TableFlagFilter::getHash);
this->MakeSlotAvailable(&this->tableOutSlot);
auto* fmp = new core::param::EnumParam(FilterMode::FILTERED);
fmp->SetTypePair(FilterMode::FILTERED, "Filtered");
fmp->SetTypePair(FilterMode::SELECTED, "Selected");
this->filterModeParam << fmp;
this->MakeSlotAvailable(&this->filterModeParam);
}
TableFlagFilter::~TableFlagFilter() {
this->Release();
}
bool TableFlagFilter::create() {
return true;
}
void TableFlagFilter::release() {
}
bool TableFlagFilter::getData(core::Call &call) {
if (!this->handleCall(call)) {
return false;
}
auto *tableOutCall = dynamic_cast<TableDataCall *>(&call);
tableOutCall->SetFrameCount(this->tableInFrameCount);
tableOutCall->SetDataHash(this->dataHash);
tableOutCall->Set(this->tableInColCount, this->rowCount, this->colInfos.data(), this->data.data());
return true;
}
bool TableFlagFilter::getHash(core::Call &call) {
if (!this->handleCall(call)) {
return false;
}
auto *tableOutCall = dynamic_cast<TableDataCall *>(&call);
tableOutCall->SetFrameCount(this->tableInFrameCount);
tableOutCall->SetDataHash(this->dataHash);
return true;
}
bool TableFlagFilter::handleCall(core::Call &call) {
auto *tableOutCall = dynamic_cast<TableDataCall *>(&call);
auto *tableInCall = this->tableInSlot.CallAs<TableDataCall>();
auto *flagsInCall = this->flagStorageInSlot.CallAs<core::FlagCallRead_GL>();
if (tableOutCall == nullptr) {
return false;
}
if (tableInCall == nullptr) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(
megamol::core::utility::log::Log::LEVEL_ERROR, "TableFlagFilter requires a table!");
return false;
}
if (flagsInCall == nullptr) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(
megamol::core::utility::log::Log::LEVEL_ERROR, "TableFlagFilter requires a flag storage!");
return false;
}
tableInCall->SetFrameID(tableOutCall->GetFrameID());
(*tableInCall)(1);
(*tableInCall)(0);
(*flagsInCall)(core::FlagCallRead_GL::CallGetData);
if (this->tableInFrameCount != tableInCall->GetFrameCount() || this->tableInDataHash != tableInCall->DataHash() || flagsInCall->hasUpdate()) {
// megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_INFO, "TableFlagFilter: Filter table.");
this->dataHash++;
this->tableInFrameCount = tableInCall->GetFrameCount();
this->tableInDataHash = tableInCall->DataHash();
this->tableInColCount = tableInCall->GetColumnsCount();
size_t tableInRowCount = tableInCall->GetRowsCount();
// download flags
flagsInCall->getData()->validateFlagCount(tableInRowCount);
auto flags = flagsInCall->getData()->flags;
uint32_t *flagsData = new uint32_t[flags->getByteSize() / sizeof(uint32_t)];
flags->bind();
glGetBufferSubData(flags->getTarget(), 0, flags->getByteSize(), flagsData);
// copy column infos
this->colInfos.resize(this->tableInColCount);
for (size_t i = 0; i < this->tableInColCount; ++i) {
this->colInfos[i] = tableInCall->GetColumnsInfos()[i];
this->colInfos[i].SetMinimumValue(std::numeric_limits<float>::max());
this->colInfos[i].SetMaximumValue(std::numeric_limits<float>::lowest());
}
core::FlagStorage::FlagItemType testMask = core::FlagStorage::ENABLED | core::FlagStorage::FILTERED;
core::FlagStorage::FlagItemType passMask = core::FlagStorage::ENABLED;;
if (static_cast<FilterMode>(this->filterModeParam.Param<core::param::EnumParam>()->Value()) == FilterMode::SELECTED) {
testMask = core::FlagStorage::ENABLED | core::FlagStorage::SELECTED | core::FlagStorage::FILTERED;
passMask = core::FlagStorage::ENABLED | core::FlagStorage::SELECTED;
}
// Resize data to size of input table. With this we only need to allocate memory once.
this->data.resize(this->tableInColCount * tableInRowCount);
this->rowCount = 0;
const float *tableInData = tableInCall->GetData();
for (size_t r = 0; r < tableInRowCount; ++r) {
if ((flagsData[r] & testMask) == passMask) {
for (size_t c = 0; c < this->tableInColCount; ++c) {
float val = tableInData[this->tableInColCount * r + c];
this->data[this->tableInColCount * this->rowCount + c] = val;
if (val < this->colInfos[c].MinimumValue()) {
this->colInfos[c].SetMinimumValue(val);
}
if (val > this->colInfos[c].MaximumValue()) {
this->colInfos[c].SetMaximumValue(val);
}
}
this->rowCount++;
}
}
// delete memory of filtered rows
this->data.resize(this->tableInColCount * this->rowCount);
delete[] flagsData;
// nicer output
if (this->rowCount == 0) {
for (size_t i = 0; i < this->tableInColCount; ++i) {
this->colInfos[i].SetMinimumValue(0.0);
this->colInfos[i].SetMaximumValue(0.0);
}
}
}
return true;
}
<|endoftext|> |
<commit_before>/* Copyright 2018 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/compiler/xla/client/lib/slicing.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/util.h"
namespace xla {
XlaOp SliceInMinorDims(XlaOp x, absl::Span<const int64> start,
absl::Span<const int64> end) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_RET_CHECK(start.size() == end.size());
int64 n_minor_dims = start.size();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
TF_RET_CHECK(n_minor_dims <= n_dims);
auto major_dims = AsInt64Slice(shape.dimensions())
.subspan(
/*pos=*/0,
/*len=*/n_dims - n_minor_dims);
// Prepends 0s in the major dim
std::vector<int64> padded_start(n_dims, 0);
std::copy(start.begin(), start.end(),
padded_start.begin() + major_dims.size());
// Prepends the shape of the major dims.
std::vector<int64> padded_end(n_dims);
std::copy(major_dims.begin(), major_dims.end(), padded_end.begin());
std::copy(end.begin(), end.end(), padded_end.begin() + major_dims.size());
std::vector<int64> strides(n_dims, 1);
return Slice(x, padded_start, padded_end, strides);
});
}
XlaOp UpdateSlice(XlaOp x, XlaOp update, absl::Span<const int64> start) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
TF_RET_CHECK(start.size() == n_dims);
// TODO(phawkins): make int64 work on all backends, remove the int32 cast.
std::vector<int32> start_as_int32(start.begin(), start.end());
std::vector<XlaOp> start_ops(start.size());
for (int i = 0; i < start.size(); ++i) {
start_ops[i] = ConstantR0(builder, start_as_int32[i]);
}
return DynamicUpdateSlice(x, update, start_ops);
});
}
XlaOp UpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const int64> start) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
const int64 n_minor_dims = start.size();
TF_RET_CHECK(n_minor_dims <= n_dims);
std::vector<int64> padded_start(n_dims, 0);
std::copy(start.begin(), start.end(),
padded_start.begin() + (n_dims - n_minor_dims));
return UpdateSlice(x, update, padded_start);
});
}
namespace {
std::vector<int64> ConcatVectors(absl::Span<const int64> xs,
absl::Span<const int64> ys) {
std::vector<int64> output(xs.size() + ys.size());
std::copy(xs.begin(), xs.end(), output.begin());
std::copy(ys.begin(), ys.end(), output.begin() + xs.size());
return output;
}
StatusOr<std::vector<XlaOp>> PrependZerosInMajorDims(
XlaOp x, absl::Span<const XlaOp> starts) {
XlaBuilder* builder = x.builder();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
auto zero = ConstantR0<int32>(builder, 0);
std::vector<XlaOp> padded_starts(n_dims, zero);
for (int i = 0; i < starts.size(); ++i) {
padded_starts[n_dims - starts.size() + i] = starts[i];
}
return padded_starts;
}
} // namespace
XlaOp DynamicSliceInMinorDims(XlaOp x, absl::Span<const XlaOp> starts,
absl::Span<const int64> sizes) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
int64 n_minor_dims = starts.size();
TF_RET_CHECK(n_minor_dims == sizes.size());
TF_RET_CHECK(n_minor_dims <= n_dims);
auto major_dims = AsInt64Slice(shape.dimensions())
.subspan(
/*pos=*/0,
/*len=*/n_dims - sizes.size());
TF_ASSIGN_OR_RETURN(auto padded_starts, PrependZerosInMajorDims(x, starts));
auto padded_sizes = ConcatVectors(major_dims, sizes);
return DynamicSlice(x, padded_starts, padded_sizes);
});
}
XlaOp DynamicUpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const XlaOp> starts) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(auto padded_starts, PrependZerosInMajorDims(x, starts));
return DynamicUpdateSlice(x, update, padded_starts);
});
}
XlaOp TorchGather(XlaOp input, XlaOp index, int64 dim) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
ShapeUtil::AppendMajorDimension(1, &index_shape);
std::vector<XlaOp> to_concat;
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
to_concat.reserve(input_shape.rank());
for (int64 i = 0; i < input_shape.rank(); ++i) {
if (i == dim) {
to_concat.push_back(Reshape(index, index_shape.dimensions()));
} else {
to_concat.push_back(Iota(builder, index_shape, i));
}
}
XlaOp gather_indices = ConcatInDim(builder, to_concat, input_shape.rank());
std::vector<int64> slice_sizes(input_shape.rank(), 1);
GatherDimensionNumbers gather_dnums;
gather_dnums.set_index_vector_dim(input_shape.rank());
for (int64 i = 0; i < input_shape.rank(); ++i) {
gather_dnums.add_collapsed_slice_dims(i);
gather_dnums.add_start_index_map(i);
}
return Gather(input, gather_indices, gather_dnums, slice_sizes);
});
}
XlaOp TorchIndexSelect(XlaOp input, XlaOp index, int64 dim, int64 batch_dims) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
if (dim < batch_dims) {
return InvalidArgument(
"Gather dim must be greater than or equal to the number of batch "
"dims");
}
std::vector<int64> slice_sizes = input_shape.dimensions();
GatherDimensionNumbers gather_dnums;
gather_dnums.set_index_vector_dim(index_shape.rank());
if (batch_dims > 0) {
ShapeUtil::AppendMajorDimension(1, &index_shape);
std::vector<XlaOp> to_concat;
to_concat.reserve(batch_dims + 1);
for (int64 batch_dim = 0; batch_dim < batch_dims; ++batch_dim) {
to_concat.push_back(Iota(builder, index_shape, batch_dim));
}
to_concat.push_back(Reshape(index, index_shape.dimensions()));
index = ConcatInDim(builder, to_concat, gather_dnums.index_vector_dim());
}
for (int64 i = 0; i < input_shape.rank(); ++i) {
if (i < batch_dims || i == dim) {
if (slice_sizes[i] != 0) {
slice_sizes[i] = 1;
gather_dnums.add_collapsed_slice_dims(i);
}
gather_dnums.add_start_index_map(i);
} else {
if (i < dim) {
gather_dnums.add_offset_dims(i);
} else {
gather_dnums.add_offset_dims(i + gather_dnums.index_vector_dim() -
(1 + batch_dims));
}
}
}
return Gather(input, index, gather_dnums, slice_sizes);
});
}
} // namespace xla
<commit_msg>[XLA:CLIENT] Use U32 instead of 64 bit types for gathers against dimensions smaller than 2^32.<commit_after>/* Copyright 2018 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/compiler/xla/client/lib/slicing.h"
#include <limits>
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/util.h"
namespace xla {
XlaOp SliceInMinorDims(XlaOp x, absl::Span<const int64> start,
absl::Span<const int64> end) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_RET_CHECK(start.size() == end.size());
int64 n_minor_dims = start.size();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
TF_RET_CHECK(n_minor_dims <= n_dims);
auto major_dims = AsInt64Slice(shape.dimensions())
.subspan(
/*pos=*/0,
/*len=*/n_dims - n_minor_dims);
// Prepends 0s in the major dim
std::vector<int64> padded_start(n_dims, 0);
std::copy(start.begin(), start.end(),
padded_start.begin() + major_dims.size());
// Prepends the shape of the major dims.
std::vector<int64> padded_end(n_dims);
std::copy(major_dims.begin(), major_dims.end(), padded_end.begin());
std::copy(end.begin(), end.end(), padded_end.begin() + major_dims.size());
std::vector<int64> strides(n_dims, 1);
return Slice(x, padded_start, padded_end, strides);
});
}
XlaOp UpdateSlice(XlaOp x, XlaOp update, absl::Span<const int64> start) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
TF_RET_CHECK(start.size() == n_dims);
// TODO(phawkins): make int64 work on all backends, remove the int32 cast.
std::vector<int32> start_as_int32(start.begin(), start.end());
std::vector<XlaOp> start_ops(start.size());
for (int i = 0; i < start.size(); ++i) {
start_ops[i] = ConstantR0(builder, start_as_int32[i]);
}
return DynamicUpdateSlice(x, update, start_ops);
});
}
XlaOp UpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const int64> start) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
const int64 n_minor_dims = start.size();
TF_RET_CHECK(n_minor_dims <= n_dims);
std::vector<int64> padded_start(n_dims, 0);
std::copy(start.begin(), start.end(),
padded_start.begin() + (n_dims - n_minor_dims));
return UpdateSlice(x, update, padded_start);
});
}
namespace {
std::vector<int64> ConcatVectors(absl::Span<const int64> xs,
absl::Span<const int64> ys) {
std::vector<int64> output(xs.size() + ys.size());
std::copy(xs.begin(), xs.end(), output.begin());
std::copy(ys.begin(), ys.end(), output.begin() + xs.size());
return output;
}
StatusOr<std::vector<XlaOp>> PrependZerosInMajorDims(
XlaOp x, absl::Span<const XlaOp> starts) {
XlaBuilder* builder = x.builder();
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
auto zero = ConstantR0<int32>(builder, 0);
std::vector<XlaOp> padded_starts(n_dims, zero);
for (int i = 0; i < starts.size(); ++i) {
padded_starts[n_dims - starts.size() + i] = starts[i];
}
return padded_starts;
}
} // namespace
XlaOp DynamicSliceInMinorDims(XlaOp x, absl::Span<const XlaOp> starts,
absl::Span<const int64> sizes) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape shape, builder->GetShape(x));
const int64 n_dims = shape.rank();
int64 n_minor_dims = starts.size();
TF_RET_CHECK(n_minor_dims == sizes.size());
TF_RET_CHECK(n_minor_dims <= n_dims);
auto major_dims = AsInt64Slice(shape.dimensions())
.subspan(
/*pos=*/0,
/*len=*/n_dims - sizes.size());
TF_ASSIGN_OR_RETURN(auto padded_starts, PrependZerosInMajorDims(x, starts));
auto padded_sizes = ConcatVectors(major_dims, sizes);
return DynamicSlice(x, padded_starts, padded_sizes);
});
}
XlaOp DynamicUpdateSliceInMinorDims(XlaOp x, XlaOp update,
absl::Span<const XlaOp> starts) {
XlaBuilder* builder = x.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(auto padded_starts, PrependZerosInMajorDims(x, starts));
return DynamicUpdateSlice(x, update, padded_starts);
});
}
XlaOp TorchGather(XlaOp input, XlaOp index, int64 dim) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
ShapeUtil::AppendMajorDimension(1, &index_shape);
std::vector<XlaOp> to_concat;
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
if (ShapeUtil::ElementHasBitWidth(index_shape, 64) &&
input_shape.dimensions(dim) < std::numeric_limits<uint32>::max()) {
index = ConvertElementType(index, U32);
index_shape.set_element_type(U32);
}
to_concat.reserve(input_shape.rank());
for (int64 i = 0; i < input_shape.rank(); ++i) {
if (i == dim) {
to_concat.push_back(Reshape(index, index_shape.dimensions()));
} else {
to_concat.push_back(Iota(builder, index_shape, i));
}
}
XlaOp gather_indices = ConcatInDim(builder, to_concat, input_shape.rank());
std::vector<int64> slice_sizes(input_shape.rank(), 1);
GatherDimensionNumbers gather_dnums;
gather_dnums.set_index_vector_dim(input_shape.rank());
for (int64 i = 0; i < input_shape.rank(); ++i) {
gather_dnums.add_collapsed_slice_dims(i);
gather_dnums.add_start_index_map(i);
}
return Gather(input, gather_indices, gather_dnums, slice_sizes);
});
}
XlaOp TorchIndexSelect(XlaOp input, XlaOp index, int64 dim, int64 batch_dims) {
XlaBuilder* builder = input.builder();
return builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
TF_ASSIGN_OR_RETURN(Shape input_shape, builder->GetShape(input));
TF_ASSIGN_OR_RETURN(Shape index_shape, builder->GetShape(index));
if (dim < batch_dims) {
return InvalidArgument(
"Gather dim must be greater than or equal to the number of batch "
"dims");
}
if (ShapeUtil::ElementHasBitWidth(index_shape, 64) &&
input_shape.dimensions(dim) < std::numeric_limits<uint32>::max()) {
index = ConvertElementType(index, U32);
index_shape.set_element_type(U32);
}
std::vector<int64> slice_sizes = input_shape.dimensions();
GatherDimensionNumbers gather_dnums;
gather_dnums.set_index_vector_dim(index_shape.rank());
if (batch_dims > 0) {
ShapeUtil::AppendMajorDimension(1, &index_shape);
std::vector<XlaOp> to_concat;
to_concat.reserve(batch_dims + 1);
for (int64 batch_dim = 0; batch_dim < batch_dims; ++batch_dim) {
to_concat.push_back(Iota(builder, index_shape, batch_dim));
}
to_concat.push_back(Reshape(index, index_shape.dimensions()));
index = ConcatInDim(builder, to_concat, gather_dnums.index_vector_dim());
}
for (int64 i = 0; i < input_shape.rank(); ++i) {
if (i < batch_dims || i == dim) {
if (slice_sizes[i] != 0) {
slice_sizes[i] = 1;
gather_dnums.add_collapsed_slice_dims(i);
}
gather_dnums.add_start_index_map(i);
} else {
if (i < dim) {
gather_dnums.add_offset_dims(i);
} else {
gather_dnums.add_offset_dims(i + gather_dnums.index_vector_dim() -
(1 + batch_dims));
}
}
}
return Gather(input, index, gather_dnums, slice_sizes);
});
}
} // namespace xla
<|endoftext|> |
<commit_before>/**
* @file seaicing.cpp
*
* Created on: Jan 03, 2013
* @author aaltom
*/
#include "seaicing.h"
#include "logger_factory.h"
#include <boost/lexical_cast.hpp>
#include "level.h"
#include "forecast_time.h"
using namespace std;
using namespace himan::plugin;
seaicing::seaicing()
: global(false)
{
itsClearTextFormula = "SeaIcing = FF * ( -sIndex -T2m ) / ( 1 + 0.3 * ( T0 + sIndex ))";
itsLogger = logger_factory::Instance()->GetLog("seaicing");
}
void seaicing::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
if (itsConfiguration->Exists("global") && itsConfiguration->GetValue("global") == "true")
{
SetParams({param("SSICING-N", 10059, 0, 0, 2)});
global = true;
}
else
{
// By default baltic sea
SetParams({param("ICING-N", 480, 0, 0, 2)});
global = false;
}
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void seaicing::Calculate(shared_ptr<info> myTargetInfo, unsigned short theThreadIndex)
{
const params TParam = {param("T-K"), param("TG-K")};
const level TLevel(himan::kHeight, 2, "HEIGHT");
const param FfParam("FF-MS"); // 10 meter wind
const level FfLevel(himan::kHeight, 10, "HEIGHT");
level ground;
double saltinessIndex = 0.35;
if (global)
{
saltinessIndex = 1.5;
}
// this will come back to us
if ( itsConfiguration->SourceProducer().Id() == 131)
{
ground = level(himan::kGndLayer, 0, "GNDLAYER");
}
else
{
ground = level(himan::kHeight, 0, "HEIGHT");
}
auto myThreadedLogger = logger_factory::Instance()->GetLog("seaicingThread #" + boost::lexical_cast<string> (theThreadIndex));
forecast_time forecastTime = myTargetInfo->Time();
level forecastLevel = myTargetInfo->Level();
myThreadedLogger->Info("Calculating time " + static_cast<string>(*forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel));
info_t TInfo = Fetch(forecastTime, TLevel, TParam, false);
info_t TgInfo = Fetch(forecastTime, ground, TParam, false);
info_t FfInfo = Fetch(forecastTime, FfLevel, FfParam, false);
if (!TInfo || !TgInfo || !FfInfo)
{
myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel));
return;
}
string deviceType = "CPU";
LOCKSTEP(myTargetInfo, TInfo, TgInfo, FfInfo)
{
double T = TInfo->Value();
double Tg = TgInfo->Value();
double Ff = FfInfo->Value();
if (T == kFloatMissing || Tg == kFloatMissing || Ff == kFloatMissing)
{
myTargetInfo->Value(-10);
continue;
}
double seaIcing;
double TBase = 273.15;
T = T - TBase;
Tg = Tg - TBase;
if (Tg < -2 )
{
seaIcing = -10;
}
else
{
seaIcing = Ff * ( -saltinessIndex -T ) / ( 1 + 0.3 * ( Tg + saltinessIndex ));
if (seaIcing > 100)
{
seaIcing = 100;
}
}
myTargetInfo->Value(seaIcing);
}
myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data()->MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data()->Size()));
}
<commit_msg>Calculate index instead of values.<commit_after>/**
* @file seaicing.cpp
*
* Created on: Jan 03, 2013
* @author aaltom
*/
#include "seaicing.h"
#include "logger_factory.h"
#include <boost/lexical_cast.hpp>
#include "level.h"
#include "forecast_time.h"
using namespace std;
using namespace himan::plugin;
seaicing::seaicing()
: global(false)
{
itsClearTextFormula = "SeaIcing = FF * ( -sIndex -T2m ) / ( 1 + 0.3 * ( T0 + sIndex ))";
itsLogger = logger_factory::Instance()->GetLog("seaicing");
}
void seaicing::Process(std::shared_ptr<const plugin_configuration> conf)
{
Init(conf);
if (itsConfiguration->Exists("global") && itsConfiguration->GetValue("global") == "true")
{
SetParams({param("SSICING-N", 10059, 0, 0, 2)});
global = true;
}
else
{
// By default baltic sea
SetParams({param("ICING-N", 480, 0, 0, 2)});
global = false;
}
Start();
}
/*
* Calculate()
*
* This function does the actual calculation.
*/
void seaicing::Calculate(shared_ptr<info> myTargetInfo, unsigned short theThreadIndex)
{
const params TParam = {param("T-K"), param("TG-K")};
const level TLevel(himan::kHeight, 2, "HEIGHT");
const param FfParam("FF-MS"); // 10 meter wind
const level FfLevel(himan::kHeight, 10, "HEIGHT");
level ground;
double saltinessIndex = 0.35;
if (global)
{
saltinessIndex = 1.5;
}
// this will come back to us
if ( itsConfiguration->SourceProducer().Id() == 131)
{
ground = level(himan::kGndLayer, 0, "GNDLAYER");
}
else
{
ground = level(himan::kHeight, 0, "HEIGHT");
}
auto myThreadedLogger = logger_factory::Instance()->GetLog("seaicingThread #" + boost::lexical_cast<string> (theThreadIndex));
forecast_time forecastTime = myTargetInfo->Time();
level forecastLevel = myTargetInfo->Level();
myThreadedLogger->Info("Calculating time " + static_cast<string>(*forecastTime.ValidDateTime()) + " level " + static_cast<string> (forecastLevel));
info_t TInfo = Fetch(forecastTime, TLevel, TParam, false);
info_t TgInfo = Fetch(forecastTime, ground, TParam, false);
info_t FfInfo = Fetch(forecastTime, FfLevel, FfParam, false);
if (!TInfo || !TgInfo || !FfInfo)
{
myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string> (forecastTime.Step()) + ", level " + static_cast<string> (forecastLevel));
return;
}
string deviceType = "CPU";
LOCKSTEP(myTargetInfo, TInfo, TgInfo, FfInfo)
{
double T = TInfo->Value();
double Tg = TgInfo->Value();
double Ff = FfInfo->Value();
if (T == kFloatMissing || Tg == kFloatMissing || Ff == kFloatMissing)
{
myTargetInfo->Value(-10);
continue;
}
double seaIcing;
double TBase = 273.15;
T = T - TBase;
Tg = Tg - TBase;
if (Tg < -2 )
{
seaIcing = -10;
}
else
{
seaIcing = Ff * ( -saltinessIndex -T ) / ( 1 + 0.3 * ( Tg + saltinessIndex ));
if (seaIcing > 100)
{
seaIcing = 100;
}
}
// Change values to index
// Index by Antonios Niros: Vessel icing forecast and services: further development and perspectives.
if (seaIcing <= 0)
{ // No icing
seaIcing = 1;
}
else if (seaIcing > 0 && seaIcing < 22.4)
{ // Light icing ja icing rate <0.7cm/h
seaIcing = 2;
}
else if (seaIcing >= 22.4 && seaIcing < 53.3)
{ // Moderate icing ja icing rate between 0.7cm/h-2cm/h
seaIcing = 3;
}
else if (seaIcing >= 53.3 && seaIcing < 83)
{ // Heavy icing ja icing rate between 2.0cm/h-4.0cm/h
seaIcing = 4;
}
else if (seaIcing >= 83)
{ // Extreme icing ja icing rate >4cm/h
seaIcing = 5;
}
myTargetInfo->Value(seaIcing);
}
myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string> (myTargetInfo->Data()->MissingCount()) + "/" + boost::lexical_cast<string> (myTargetInfo->Data()->Size()));
}
<|endoftext|> |
<commit_before>/* Copyright 2015 Google Inc. 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.
==============================================================================*/
// See docs in ../ops/data_flow_ops.cc.
#include <deque>
#include <vector>
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/padding_fifo_queue.h"
#include "tensorflow/core/kernels/queue_base.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/port.h"
#include "tensorflow/core/public/tensor.h"
#include "tensorflow/core/public/tensor_shape.h"
namespace tensorflow {
PaddingFIFOQueue::PaddingFIFOQueue(
int capacity, const DataTypeVector& component_dtypes,
const std::vector<PartialTensorShape>& partial_shapes, const string& name)
: FIFOQueue(capacity, component_dtypes,
ConvertShapesPartialDimensionsToZero(partial_shapes), name),
partial_shapes_(partial_shapes) {}
Status PaddingFIFOQueue::Initialize() {
Status s = FIFOQueue::Initialize();
if (!s.ok()) return s;
if (component_dtypes_.size() != partial_shapes_.size()) {
return errors::InvalidArgument(
"Shapes must be provided for all components, but received ",
component_dtypes_.size(), " dtypes and ", partial_shapes_.size(),
" shapes.");
}
return Status::OK();
}
/* static */
Status PaddingFIFOQueue::GetElementComponent(
const PaddingFIFOQueue::Tuple& tuple, int component, OpKernelContext* ctx,
PersistentTensor* out_tensor) {
TensorShape element_shape(tuple[component].shape());
Tensor* element_access = nullptr;
TF_RETURN_IF_ERROR(ctx->allocate_persistent(
tuple[component].dtype(), element_shape, out_tensor, &element_access));
*element_access = tuple[component];
return Status::OK();
}
void PaddingFIFOQueue::TryDequeueMany(int num_elements, OpKernelContext* ctx,
CallbackWithTuple callback) {
if (num_elements == 0) {
Tuple tuple;
tuple.reserve(num_components());
for (int i = 0; i < num_components(); ++i) {
// TODO(josh11b,misard): Switch to allocate_output().
// See similar comment in fifo_queue.cc
Tensor element;
// Here, ManyOutShape returns zeros for undetermined shapes,
// which is exactly what we want to use.
ctx->allocate_temp(component_dtypes_[i], ManyOutShape(i, 0), &element);
tuple.emplace_back(element);
}
callback(tuple);
return;
}
CancellationManager* cm = ctx->cancellation_manager();
CancellationToken token = cm->get_cancellation_token();
bool already_cancelled;
{
mutex_lock l(mu_);
already_cancelled = !cm->RegisterCallback(
token, [this, token]() { Cancel(kDequeue, token); });
if (!already_cancelled) {
// TODO(josh11b): This makes two copies of callback, avoid this if possible.
dequeue_attempts_.emplace_back(
num_elements, [callback]() { callback(Tuple()); }, ctx, token,
[callback, this](Attempt* attempt) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
int32 s = queues_[0].size();
if (closed_ && s < attempt->elements_requested) {
attempt->context->SetStatus(errors::OutOfRange(
"PaddingFIFOQueue '", name_, "' is closed and has ",
"insufficient elements (requested ",
attempt->elements_requested, ", current size ", s, ")"));
// TODO(mrry): Add support for producing a partial batch as
// output when the queue is closed.
if (!attempt->tuples.empty()) {
// Restore already-dequeued elements to the front of the queue.
for (int64 i = attempt->tuples.size() - 1; i >= 0; --i) {
for (int j = 0; j < num_components(); ++j) {
PersistentTensor element;
Status s = GetElementComponent(attempt->tuples[i], j,
attempt->context, &element);
if (!s.ok()) {
attempt->context->SetStatus(
errors::DataLoss("Failed to restore element from "
"partially-dequeued batch "
"to PaddingFIFOQueue: ",
s.error_message()));
}
queues_[j].push_front(element);
}
}
}
return kComplete;
}
RunResult result = kNoProgress;
for (; s > 0; --s) {
result = kProgress;
Tuple tuple;
DequeueLocked(attempt->context, &tuple);
attempt->tuples.push_back(tuple);
tuple.clear();
--attempt->elements_requested;
if (attempt->elements_requested == 0) {
// Finished. Allocate attempt->tuple and
// copy from attempt->tuples to attempt->tuple.
attempt->tuple.reserve(num_components());
const std::vector<Tuple>& tuples = attempt->tuples;
std::vector<bool> dynamic_shape;
const int64 batch_size = tuples.size();
for (int i = 0; i < num_components(); ++i) {
const PartialTensorShape partial_shape =
PartialTensorShape({batch_size})
.Concatenate(partial_shapes_[i]);
TensorShape shape({batch_size});
for (int j = 0; j < partial_shape.dims() - 1; ++j) {
if (partial_shape.dim_size(j + 1) > -1) {
shape.AddDim(partial_shape.dim_size(j + 1));
} else {
// Expand sizes to match.
int64 max_val = 0;
for (const Tuple& t : tuples) {
max_val = max(max_val, t[i].shape().dim_size(j));
}
shape.AddDim(max_val);
}
}
Tensor element;
attempt->context->allocate_temp(component_dtypes_[i], shape,
&element);
bool has_dynamic_shape = !partial_shape.IsFullyDefined();
if (has_dynamic_shape) {
// Set all values to zero because not all values
// will get written over.
attempt->context->SetStatus(SetElementZero(&element));
if (!attempt->context->status().ok()) return kComplete;
}
dynamic_shape.push_back(has_dynamic_shape);
// TODO(ebrevdo): should this be a persistent tensor?
attempt->tuple.emplace_back(element);
}
for (int index = 0; index < tuples.size(); ++index) {
for (int i = 0; i < num_components(); ++i) {
if (dynamic_shape[i]) {
// Slightly slower copy operation
attempt->context->SetStatus(CopyElementToLargerSlice(
tuples[index][i], &attempt->tuple[i], index));
} else {
attempt->context->SetStatus(CopyElementToSlice(
tuples[index][i], &attempt->tuple[i], index));
}
if (!attempt->context->status().ok()) return kComplete;
}
}
tuple = attempt->tuple;
attempt->tuples.clear();
attempt->done_callback = [callback, tuple]() {
callback(tuple);
};
return kComplete;
}
}
return result;
});
}
}
if (!already_cancelled) {
FlushUnlocked();
} else {
ctx->SetStatus(errors::Cancelled("Dequeue operation was cancelled"));
callback(Tuple());
}
}
Status PaddingFIFOQueue::ValidateTuple(const Tuple& tuple) {
TF_RETURN_IF_ERROR(ValidateTupleCommon(tuple));
for (size_t i = 0; i < tuple.size(); ++i) {
if (!partial_shapes_[i].IsCompatibleWith(tuple[i].shape())) {
return errors::InvalidArgument("Shape mismatch in tuple component ", i,
". Expected ",
partial_shapes_[i].DebugString(), ", got ",
tuple[i].shape().ShortDebugString());
}
}
return Status::OK();
}
Status PaddingFIFOQueue::ValidateManyTuple(const Tuple& tuple) {
TF_RETURN_IF_ERROR(ValidateTupleCommon(tuple));
const int64 batch_size = tuple[0].dim_size(0);
for (size_t i = 0; i < tuple.size(); ++i) {
// Expected shape is [batch_size] + partial_shapes_[i]
const PartialTensorShape expected_shape =
PartialTensorShape({batch_size}).Concatenate(partial_shapes_[i]);
if (!expected_shape.IsCompatibleWith(tuple[i].shape())) {
return errors::InvalidArgument("Shape mismatch in tuple component ", i,
". Expected ",
expected_shape.DebugString(), ", got ",
tuple[i].shape().ShortDebugString());
}
}
return Status::OK();
}
Status PaddingFIFOQueue::CompatibleNodeDefShapes(
const NodeDef& node_def) const {
std::vector<PartialTensorShape> requested_shapes;
TF_RETURN_IF_ERROR(GetNodeAttr(node_def, "shapes", &requested_shapes));
if (!PartialTensorShapeUtils::AreCompatible(requested_shapes,
partial_shapes_)) {
return errors::InvalidArgument(
"Shared queue '", name_, "' has component shapes ",
PartialTensorShapeUtils::PartialShapeListString(partial_shapes_),
" but requested component shapes were ",
PartialTensorShapeUtils::PartialShapeListString(requested_shapes));
} else {
return Status::OK();
}
}
Status PaddingFIFOQueue::MatchesNodeDef(const NodeDef& node_def) {
TF_RETURN_IF_ERROR(MatchesNodeDefOp(node_def, "PaddingFIFOQueue"));
TF_RETURN_IF_ERROR(MatchesNodeDefCapacity(node_def, capacity_));
TF_RETURN_IF_ERROR(MatchesNodeDefTypes(node_def));
TF_RETURN_IF_ERROR(CompatibleNodeDefShapes(node_def));
return Status::OK();
}
template <typename T, int NDIMS>
Status HandleElementToLargerSlice(const Tensor& element, Tensor* parent,
int index) {
DCHECK_NE(parent->dim_size(0), 0);
if (element.NumElements() > (parent->NumElements() / parent->dim_size(0))) {
TensorShape chip_shape = parent->shape();
chip_shape.RemoveDim(0);
return errors::Internal(
"HandleElementToLargerSlice Cannot copy slice: number of entries in "
"element is greater than number of elements in parent slice. ",
"Shapes are: [element]: ", element.shape().DebugString(),
", [parent slice]: ", chip_shape.DebugString());
}
auto element_t = element.tensor<T, NDIMS>();
auto parent_t = parent->tensor<T, NDIMS + 1>();
Eigen::DSizes<Eigen::DenseIndex, NDIMS + 1> slice_indices;
slice_indices[0] = index;
Eigen::DSizes<Eigen::DenseIndex, NDIMS + 1> slice_size;
slice_size[0] = 1;
for (int i = 1; i < slice_size.size(); ++i) {
slice_size[i] = element_t.dimension(i - 1);
}
parent_t.slice(slice_indices, slice_size) = element_t.reshape(slice_size);
return Status::OK();
}
namespace {
template <int NDIMS>
Status HandleElementToLargerSliceWithRank(const Tensor& element, Tensor* parent,
int index) {
#define HANDLE_TYPE(T) \
case DataTypeToEnum<T>::value: { \
return HandleElementToLargerSlice<T, NDIMS>(element, parent, index); \
}
switch (element.dtype()) {
TF_CALL_ALL_TYPES(HANDLE_TYPE);
#undef HANDLE_TYPE
default:
return errors::Unimplemented(
"HandleElementToLargerSliceWithRank Unhandled data type: ",
element.dtype());
}
}
} // namespace
Status PaddingFIFOQueue::CopyElementToLargerSlice(const Tensor& element,
Tensor* parent, int index) {
if (parent->dims() != element.dims() + 1) {
return errors::Internal(
"Mismatched ranks. Element's rank is: ", element.dims(),
" but element is meant to be a slice in output Tensor having rank: ",
parent->dims(), " (should be: ", element.dims() + 1, ")");
}
#define HANDLE_DIMS(NDIMS) \
case NDIMS: { \
TF_RETURN_IF_ERROR( \
HandleElementToLargerSliceWithRank<NDIMS>(element, parent, index)); \
return Status::OK(); \
}
switch (element.dims()) {
HANDLE_DIMS(0);
HANDLE_DIMS(1);
HANDLE_DIMS(2);
HANDLE_DIMS(3);
HANDLE_DIMS(4);
#undef HANDLE_DIMS
default:
return errors::Unimplemented("CopyElementToLargerSlice Unhandled rank: ",
element.dims());
}
}
// Static method
Status PaddingFIFOQueue::SetElementZero(Tensor* element) {
#define HANDLE_TYPE(T) \
if (element->dtype() == DataTypeToEnum<T>::value) { \
element->flat<T>().setConstant(T()); \
return Status::OK(); \
}
TF_CALL_ALL_TYPES(HANDLE_TYPE);
#undef HANDLE_TYPE
return errors::Unimplemented("SetElementZero Unhandled data type: ",
element->dtype());
}
std::vector<TensorShape> PaddingFIFOQueue::ConvertShapesPartialDimensionsToZero(
const gtl::ArraySlice<PartialTensorShape>& partial_shapes) {
std::vector<TensorShape> shapes(partial_shapes.size());
for (int i = 0; i < shapes.size(); ++i) {
const PartialTensorShape& partial = partial_shapes[i];
TensorShape& shape = shapes[i];
for (int64 s : partial.dim_sizes()) shape.AddDim(s < 0 ? 0 : s);
}
return shapes;
}
} // namespace tensorflow
<commit_msg>Change: 112640197<commit_after>/* Copyright 2015 Google Inc. 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.
==============================================================================*/
// See docs in ../ops/data_flow_ops.cc.
#include <deque>
#include <vector>
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/padding_fifo_queue.h"
#include "tensorflow/core/kernels/queue_base.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/port.h"
#include "tensorflow/core/public/tensor.h"
#include "tensorflow/core/public/tensor_shape.h"
namespace tensorflow {
PaddingFIFOQueue::PaddingFIFOQueue(
int capacity, const DataTypeVector& component_dtypes,
const std::vector<PartialTensorShape>& partial_shapes, const string& name)
: FIFOQueue(capacity, component_dtypes,
ConvertShapesPartialDimensionsToZero(partial_shapes), name),
partial_shapes_(partial_shapes) {}
Status PaddingFIFOQueue::Initialize() {
Status s = FIFOQueue::Initialize();
if (!s.ok()) return s;
if (component_dtypes_.size() != partial_shapes_.size()) {
return errors::InvalidArgument(
"Shapes must be provided for all components, but received ",
component_dtypes_.size(), " dtypes and ", partial_shapes_.size(),
" shapes.");
}
return Status::OK();
}
/* static */
Status PaddingFIFOQueue::GetElementComponent(
const PaddingFIFOQueue::Tuple& tuple, int component, OpKernelContext* ctx,
PersistentTensor* out_tensor) {
TensorShape element_shape(tuple[component].shape());
Tensor* element_access = nullptr;
TF_RETURN_IF_ERROR(ctx->allocate_persistent(
tuple[component].dtype(), element_shape, out_tensor, &element_access));
*element_access = tuple[component];
return Status::OK();
}
void PaddingFIFOQueue::TryDequeueMany(int num_elements, OpKernelContext* ctx,
CallbackWithTuple callback) {
if (num_elements == 0) {
Tuple tuple;
tuple.reserve(num_components());
for (int i = 0; i < num_components(); ++i) {
// TODO(josh11b,misard): Switch to allocate_output().
// See similar comment in fifo_queue.cc
Tensor element;
// Here, ManyOutShape returns zeros for undetermined shapes,
// which is exactly what we want to use.
ctx->allocate_temp(component_dtypes_[i], ManyOutShape(i, 0), &element);
tuple.emplace_back(element);
}
callback(tuple);
return;
}
CancellationManager* cm = ctx->cancellation_manager();
CancellationToken token = cm->get_cancellation_token();
bool already_cancelled;
{
mutex_lock l(mu_);
already_cancelled = !cm->RegisterCallback(
token, [this, token]() { Cancel(kDequeue, token); });
if (!already_cancelled) {
// TODO(josh11b): This makes two copies of callback, avoid this if possible.
dequeue_attempts_.emplace_back(
num_elements, [callback]() { callback(Tuple()); }, ctx, token,
[callback, this](Attempt* attempt) EXCLUSIVE_LOCKS_REQUIRED(mu_) {
int32 s = queues_[0].size();
if (closed_ && s < attempt->elements_requested) {
attempt->context->SetStatus(errors::OutOfRange(
"PaddingFIFOQueue '", name_, "' is closed and has ",
"insufficient elements (requested ",
attempt->elements_requested, ", current size ", s, ")"));
// TODO(mrry): Add support for producing a partial batch as
// output when the queue is closed.
if (!attempt->tuples.empty()) {
// Restore already-dequeued elements to the front of the queue.
for (int64 i = attempt->tuples.size() - 1; i >= 0; --i) {
for (int j = 0; j < num_components(); ++j) {
PersistentTensor element;
Status s = GetElementComponent(attempt->tuples[i], j,
attempt->context, &element);
if (!s.ok()) {
attempt->context->SetStatus(
errors::DataLoss("Failed to restore element from "
"partially-dequeued batch "
"to PaddingFIFOQueue: ",
s.error_message()));
}
queues_[j].push_front(element);
}
}
}
return kComplete;
}
RunResult result = kNoProgress;
for (; s > 0; --s) {
result = kProgress;
Tuple tuple;
DequeueLocked(attempt->context, &tuple);
attempt->tuples.push_back(tuple);
tuple.clear();
--attempt->elements_requested;
if (attempt->elements_requested == 0) {
// Finished. Allocate attempt->tuple and
// copy from attempt->tuples to attempt->tuple.
attempt->tuple.reserve(num_components());
const std::vector<Tuple>& tuples = attempt->tuples;
std::vector<bool> dynamic_shape;
const int64 batch_size = tuples.size();
for (int i = 0; i < num_components(); ++i) {
const PartialTensorShape partial_shape =
PartialTensorShape({batch_size})
.Concatenate(partial_shapes_[i]);
TensorShape shape({batch_size});
for (int j = 0; j < partial_shape.dims() - 1; ++j) {
if (partial_shape.dim_size(j + 1) > -1) {
shape.AddDim(partial_shape.dim_size(j + 1));
} else {
// Expand sizes to match.
int64 max_val = 0;
for (const Tuple& t : tuples) {
max_val = std::max(max_val, t[i].shape().dim_size(j));
}
shape.AddDim(max_val);
}
}
Tensor element;
attempt->context->allocate_temp(component_dtypes_[i], shape,
&element);
bool has_dynamic_shape = !partial_shape.IsFullyDefined();
if (has_dynamic_shape) {
// Set all values to zero because not all values
// will get written over.
attempt->context->SetStatus(SetElementZero(&element));
if (!attempt->context->status().ok()) return kComplete;
}
dynamic_shape.push_back(has_dynamic_shape);
// TODO(ebrevdo): should this be a persistent tensor?
attempt->tuple.emplace_back(element);
}
for (int index = 0; index < tuples.size(); ++index) {
for (int i = 0; i < num_components(); ++i) {
if (dynamic_shape[i]) {
// Slightly slower copy operation
attempt->context->SetStatus(CopyElementToLargerSlice(
tuples[index][i], &attempt->tuple[i], index));
} else {
attempt->context->SetStatus(CopyElementToSlice(
tuples[index][i], &attempt->tuple[i], index));
}
if (!attempt->context->status().ok()) return kComplete;
}
}
tuple = attempt->tuple;
attempt->tuples.clear();
attempt->done_callback = [callback, tuple]() {
callback(tuple);
};
return kComplete;
}
}
return result;
});
}
}
if (!already_cancelled) {
FlushUnlocked();
} else {
ctx->SetStatus(errors::Cancelled("Dequeue operation was cancelled"));
callback(Tuple());
}
}
Status PaddingFIFOQueue::ValidateTuple(const Tuple& tuple) {
TF_RETURN_IF_ERROR(ValidateTupleCommon(tuple));
for (size_t i = 0; i < tuple.size(); ++i) {
if (!partial_shapes_[i].IsCompatibleWith(tuple[i].shape())) {
return errors::InvalidArgument("Shape mismatch in tuple component ", i,
". Expected ",
partial_shapes_[i].DebugString(), ", got ",
tuple[i].shape().ShortDebugString());
}
}
return Status::OK();
}
Status PaddingFIFOQueue::ValidateManyTuple(const Tuple& tuple) {
TF_RETURN_IF_ERROR(ValidateTupleCommon(tuple));
const int64 batch_size = tuple[0].dim_size(0);
for (size_t i = 0; i < tuple.size(); ++i) {
// Expected shape is [batch_size] + partial_shapes_[i]
const PartialTensorShape expected_shape =
PartialTensorShape({batch_size}).Concatenate(partial_shapes_[i]);
if (!expected_shape.IsCompatibleWith(tuple[i].shape())) {
return errors::InvalidArgument("Shape mismatch in tuple component ", i,
". Expected ",
expected_shape.DebugString(), ", got ",
tuple[i].shape().ShortDebugString());
}
}
return Status::OK();
}
Status PaddingFIFOQueue::CompatibleNodeDefShapes(
const NodeDef& node_def) const {
std::vector<PartialTensorShape> requested_shapes;
TF_RETURN_IF_ERROR(GetNodeAttr(node_def, "shapes", &requested_shapes));
if (!PartialTensorShapeUtils::AreCompatible(requested_shapes,
partial_shapes_)) {
return errors::InvalidArgument(
"Shared queue '", name_, "' has component shapes ",
PartialTensorShapeUtils::PartialShapeListString(partial_shapes_),
" but requested component shapes were ",
PartialTensorShapeUtils::PartialShapeListString(requested_shapes));
} else {
return Status::OK();
}
}
Status PaddingFIFOQueue::MatchesNodeDef(const NodeDef& node_def) {
TF_RETURN_IF_ERROR(MatchesNodeDefOp(node_def, "PaddingFIFOQueue"));
TF_RETURN_IF_ERROR(MatchesNodeDefCapacity(node_def, capacity_));
TF_RETURN_IF_ERROR(MatchesNodeDefTypes(node_def));
TF_RETURN_IF_ERROR(CompatibleNodeDefShapes(node_def));
return Status::OK();
}
template <typename T, int NDIMS>
Status HandleElementToLargerSlice(const Tensor& element, Tensor* parent,
int index) {
DCHECK_NE(parent->dim_size(0), 0);
if (element.NumElements() > (parent->NumElements() / parent->dim_size(0))) {
TensorShape chip_shape = parent->shape();
chip_shape.RemoveDim(0);
return errors::Internal(
"HandleElementToLargerSlice Cannot copy slice: number of entries in "
"element is greater than number of elements in parent slice. ",
"Shapes are: [element]: ", element.shape().DebugString(),
", [parent slice]: ", chip_shape.DebugString());
}
auto element_t = element.tensor<T, NDIMS>();
auto parent_t = parent->tensor<T, NDIMS + 1>();
Eigen::DSizes<Eigen::DenseIndex, NDIMS + 1> slice_indices;
slice_indices[0] = index;
Eigen::DSizes<Eigen::DenseIndex, NDIMS + 1> slice_size;
slice_size[0] = 1;
for (int i = 1; i < slice_size.size(); ++i) {
slice_size[i] = element_t.dimension(i - 1);
}
parent_t.slice(slice_indices, slice_size) = element_t.reshape(slice_size);
return Status::OK();
}
namespace {
template <int NDIMS>
Status HandleElementToLargerSliceWithRank(const Tensor& element, Tensor* parent,
int index) {
#define HANDLE_TYPE(T) \
case DataTypeToEnum<T>::value: { \
return HandleElementToLargerSlice<T, NDIMS>(element, parent, index); \
}
switch (element.dtype()) {
TF_CALL_ALL_TYPES(HANDLE_TYPE);
#undef HANDLE_TYPE
default:
return errors::Unimplemented(
"HandleElementToLargerSliceWithRank Unhandled data type: ",
element.dtype());
}
}
} // namespace
Status PaddingFIFOQueue::CopyElementToLargerSlice(const Tensor& element,
Tensor* parent, int index) {
if (parent->dims() != element.dims() + 1) {
return errors::Internal(
"Mismatched ranks. Element's rank is: ", element.dims(),
" but element is meant to be a slice in output Tensor having rank: ",
parent->dims(), " (should be: ", element.dims() + 1, ")");
}
#define HANDLE_DIMS(NDIMS) \
case NDIMS: { \
TF_RETURN_IF_ERROR( \
HandleElementToLargerSliceWithRank<NDIMS>(element, parent, index)); \
return Status::OK(); \
}
switch (element.dims()) {
HANDLE_DIMS(0);
HANDLE_DIMS(1);
HANDLE_DIMS(2);
HANDLE_DIMS(3);
HANDLE_DIMS(4);
#undef HANDLE_DIMS
default:
return errors::Unimplemented("CopyElementToLargerSlice Unhandled rank: ",
element.dims());
}
}
// Static method
Status PaddingFIFOQueue::SetElementZero(Tensor* element) {
#define HANDLE_TYPE(T) \
if (element->dtype() == DataTypeToEnum<T>::value) { \
element->flat<T>().setConstant(T()); \
return Status::OK(); \
}
TF_CALL_ALL_TYPES(HANDLE_TYPE);
#undef HANDLE_TYPE
return errors::Unimplemented("SetElementZero Unhandled data type: ",
element->dtype());
}
std::vector<TensorShape> PaddingFIFOQueue::ConvertShapesPartialDimensionsToZero(
const gtl::ArraySlice<PartialTensorShape>& partial_shapes) {
std::vector<TensorShape> shapes(partial_shapes.size());
for (int i = 0; i < shapes.size(); ++i) {
const PartialTensorShape& partial = partial_shapes[i];
TensorShape& shape = shapes[i];
for (int64 s : partial.dim_sizes()) shape.AddDim(s < 0 ? 0 : s);
}
return shapes;
}
} // namespace tensorflow
<|endoftext|> |
<commit_before>
#include <iostream>
#include <boost/test/included/unit_test.hpp>
#include "protocol_module_control.h"
//#include "../../src/protocol_module_control.cpp"
#define PM1 "test1"
#define PM2 "test2"
class l7vs::protocol_module_control;
using namespace boost::unit_test;
//test case1.
void protocol_module_control_test(){
l7vs::protocol_module_base* protomod = NULL;
l7vs::protocol_module_control& control = l7vs::protocol_module_control::getInstance();
//call load_module before initialize
try{
protomod = control.load_module( PM1 );
}
// catch( l7vs::module_control_error& err ){
// std::cout << err.message << std::endl;
// }
catch(...){
}
//test initialize and finalize
control.initialize( "./" );
control.finalize();
}
test_suite* init_unit_test_suite( int argc, char* argv[] ){
// create unit test suite
test_suite* ts = BOOST_TEST_SUITE( "protocol_module_control" );
ts->add( BOOST_TEST_CASE( &protocol_module_control_test ) );
framework::master_test_suite().add( ts );
return 0;
}
<commit_msg>テスト項目追加<commit_after>
#include <iostream>
#include <boost/test/included/unit_test.hpp>
#include "protocol_module_control.h"
//#include "../../src/protocol_module_control.cpp"
#define PM1 "test1"
#define PM2 "test2"
class l7vs::protocol_module_control;
using namespace boost::unit_test;
//test case1.
void protocol_module_control_test(){
//============================================
//protocol_module_control
//1
//getInstanceメソッドのテスト
//getInstanceによって取得したcontrolとcontrol_2のインスタンスが同一であることを確認する。
//============================================
l7vs::protocol_module_control& control = l7vs::protocol_module_control::getInstance();
l7vs::protocol_module_control& control_2 = l7vs::protocol_module_control::getInstance();
BOOST_CHECK_EQUAL( &control, &control_2 );
//test initialize and finalize
control.initialize( "./" );
control.finalize();
//============================================
//protocol_module_control
//2
//load_moduleメソッドのテスト(正常系その1)
//ProtocolModuleクラスのインスタンスが取得できること
//例外が発生しないこと
//指定したモジュール名と取得したモジュール名が同じこと
//============================================
control.initialize( "./" );
l7vs::protocol_module_base* protomod = NULL;
try{
protomod = control.load_module( PM1 );
}
catch(...){
BOOST_ERROR( "exception : load_module" );
}
BOOST_CHECK( NULL != protomod );
// BOOST_CHECK_EQUAL( PM1, protomod.get_name() );
}
//test case2
void protocol_module_control_test_thread(){
}
test_suite* init_unit_test_suite( int argc, char* argv[] ){
// create unit test suite
test_suite* ts = BOOST_TEST_SUITE( "protocol_module_control" );
// add test case to test suite
ts->add( BOOST_TEST_CASE( &protocol_module_control_test ) );
ts->add( BOOST_TEST_CASE( &protocol_module_control_test_thread ) );
framework::master_test_suite().add( ts );
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017, Andrej Kislovskij
*
* This is PUBLIC DOMAIN software so use at your own risk as it comes
* with no warranties. This code is yours to share, use and modify without
* any restrictions or obligations.
*
* For more information see conwrap/LICENSE or refer refer to http://unlicense.org
*
* Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)
*/
#pragma once
#include <algorithm>
#include <atomic>
#include <chrono>
#include <conwrap/ProcessorProxy.hpp>
#include <cstddef> // std::size_t
#include <functional>
#include <memory>
#include <optional>
#include <sstream> // std::stringstream
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include "slim/Chunk.hpp"
#include "slim/Consumer.hpp"
#include "slim/ContainerBase.hpp"
#include "slim/EncoderBuilder.hpp"
#include "slim/Exception.hpp"
#include "slim/log/log.hpp"
#include "slim/proto/Command.hpp"
#include "slim/proto/CommandSession.hpp"
#include "slim/proto/StreamingSession.hpp"
namespace slim
{
namespace proto
{
template<typename ConnectionType>
class Streamer : public Consumer
{
template<typename SessionType>
using SessionsMap = std::unordered_map<ConnectionType*, std::unique_ptr<SessionType>>;
using TimePoint = std::chrono::time_point<std::chrono::steady_clock>;
using CommandSessionType = CommandSession<ConnectionType>;
using StreamingSessionType = StreamingSession<ConnectionType>;
public:
Streamer(unsigned int sp, EncoderBuilder eb, std::optional<unsigned int> g)
: streamingPort{sp}
, encoderBuilder{eb}
, gain{g}
, monitorThread{[&]
{
LOG(DEBUG) << LABELS{"proto"} << "Monitor thread was started (id=" << std::this_thread::get_id() << ")";
for(unsigned int counter{0}; !monitorFinish; counter++, std::this_thread::sleep_for(std::chrono::milliseconds{200}))
{
// TODO: make configurable
if (counter > 24)
{
auto processorProxyPtr{getProcessorProxy()};
if (processorProxyPtr)
{
processorProxyPtr->process([&]
{
// sending ping command to measure round-trip latency
for (auto& entry : commandSessions)
{
entry.second->ping();
}
});
}
counter = 0;
}
}
LOG(DEBUG) << LABELS{"proto"} << "Monitor thread was stopped (id=" << std::this_thread::get_id() << ")";
}}
{
LOG(DEBUG) << LABELS{"proto"} << "Streamer object was created (id=" << this << ")";
}
virtual ~Streamer()
{
// stopping monitor thread
monitorFinish = true;
if (monitorThread.joinable())
{
monitorThread.join();
}
LOG(DEBUG) << LABELS{"proto"} << "Streamer object was deleted (id=" << this << ")";
}
// TODO: non-movable is required due to usage in server callbacks; consider refactoring
Streamer(const Streamer&) = delete; // non-copyable
Streamer& operator=(const Streamer&) = delete; // non-assignable
Streamer(Streamer&& rhs) = delete; // non-movable
Streamer& operator=(Streamer&& rhs) = delete; // non-movable-assinable
virtual bool consumeChunk(Chunk& chunk) override
{
auto result{false};
auto chunkSamplingRate{chunk.getSamplingRate()};
if (samplingRate != chunkSamplingRate)
{
if (samplingRate)
{
// propogating end-of-stream to all the clients
stop();
// changing state to not streaming
streaming = false;
}
// assigning new sampling rate
samplingRate = chunkSamplingRate;
// if this is the beginning of a stream
if (chunkSamplingRate)
{
start();
}
}
else if (samplingRate)
{
if (!streaming)
{
// checking if all conditions for streaming were met
streaming = isReadyToStream();
}
if (streaming)
{
// sending out Chunk to all the clients
distributeChunk(chunk);
// it will make Chunk to be consumed
result = true;
}
}
else
{
// consuming Chunk in case when samplingRate == chunkSamplingRate == 0
result = true;
}
return result;
}
void onHTTPClose(ConnectionType& connection)
{
LOG(INFO) << LABELS{"proto"} << "HTTP close callback (connection=" << &connection << ")";
auto streamingSessionPtr{removeSession(streamingSessions, connection)};
if (streamingSessionPtr)
{
// if there is a relevant SlimProto connection found
auto clientID{streamingSessionPtr->getClientID()};
auto commandSession{findSessionByID(commandSessions, clientID)};
if (commandSession.has_value())
{
// resetting HTTP session in its relevant SlimProto session
commandSession.value()->setStreamingSession(nullptr);
}
else
{
LOG(WARNING) << LABELS{"proto"} << "Could not find SlimProto session by client ID (clientID=" << clientID << ")";
}
}
else
{
LOG(WARNING) << LABELS{"proto"} << "Could not find HTTP session object";
}
}
void onHTTPData(ConnectionType& connection, unsigned char* buffer, std::size_t receivedSize)
{
if (!applyToSession(streamingSessions, connection, [&](StreamingSessionType& session)
{
// processing request by a proper Streaming session mapped to this connection
session.onRequest(buffer, receivedSize);
}))
{
// parsing client ID
auto clientID = StreamingSessionType::parseClientID(std::string{(char*)buffer, receivedSize});
if (!clientID.has_value())
{
throw slim::Exception("Missing client ID in streaming session request");
}
LOG(INFO) << LABELS{"proto"} << "Client ID was parsed (clientID=" << clientID.value() << ")";
// configuring an encoder builder
encoderBuilder.setSamplingRate(samplingRate);
encoderBuilder.setWriter(&connection);
// creating streaming session object
auto streamingSessionPtr{std::make_unique<StreamingSessionType>(std::ref<ConnectionType>(connection), std::move(encoderBuilder.build()), samplingRate, clientID.value())};
// saving Streaming session reference in the relevant Command session
auto commandSessionPtr{findSessionByID(commandSessions, clientID.value())};
if (!commandSessionPtr.has_value())
{
throw slim::Exception("Could not correlate provided client ID with a valid SlimProto session");
}
commandSessionPtr.value()->setStreamingSession(streamingSessionPtr.get());
// processing request by a proper Streaming session mapped to this connection
streamingSessionPtr->onRequest(buffer, receivedSize);
// saving Streaming session as a part of this Streamer
addSession(streamingSessions, connection, std::move(streamingSessionPtr));
}
}
void onHTTPOpen(ConnectionType& connection)
{
LOG(INFO) << LABELS{"proto"} << "New HTTP session request received (connection=" << &connection << ")";
}
void onSlimProtoClose(ConnectionType& connection)
{
removeSession(commandSessions, connection);
}
void onSlimProtoData(ConnectionType& connection, unsigned char* buffer, std::size_t size)
{
try
{
if (!applyToSession(commandSessions, connection, [&](CommandSessionType& session)
{
session.onRequest(buffer, size);
}))
{
throw slim::Exception("Could not find SlimProto session object");
}
}
catch (const slim::Exception& error)
{
LOG(ERROR) << LABELS{"proto"} << "Error while processing SlimProto command: " << error.what();
connection.stop();
}
}
void onSlimProtoOpen(ConnectionType& connection)
{
// using regular counter for session ID's instead of MAC's; it allows running multiple players on one host
std::stringstream ss;
ss << (++nextID);
// creating command session object
auto commandSessionPtr{std::make_unique<CommandSessionType>(std::ref<ConnectionType>(connection), ss.str(), streamingPort, encoderBuilder.getFormat(), gain)};
// enable streaming for this session if required
if (streaming)
{
// TODO: this is temporary solution
commandSessionPtr->setSamplingRate(samplingRate);
commandSessionPtr->start();
}
// saving command session in the map
addSession(commandSessions, connection, std::move(commandSessionPtr));
}
virtual void start() override
{
for (auto& entry : commandSessions)
{
// TODO: this is a temporary solution
entry.second->setSamplingRate(samplingRate);
entry.second->start();
}
startedAt = std::chrono::steady_clock::now();
}
virtual void stop(bool gracefully = true) override
{
// stopping SlimProto session will send end-of-stream command which normally triggers close of HTTP connection
// TODO: implement 'safety' logic to close HTTP connection in case client does not
for (auto& entry : commandSessions)
{
entry.second->stop();
}
}
protected:
template<typename SessionType>
inline auto& addSession(SessionsMap<SessionType>& sessions, ConnectionType& connection, std::unique_ptr<SessionType> sessionPtr)
{
auto found{sessions.find(&connection)};
SessionType* s{nullptr};
if (found == sessions.end())
{
s = sessionPtr.get();
// saving session in a map; using pointer to a relevant connection as an ID
sessions[&connection] = std::move(sessionPtr);
LOG(DEBUG) << LABELS{"proto"} << "New session was added (id=" << s << ", sessions=" << sessions.size() << ")";
}
else
{
s = (*found).second.get();
LOG(WARNING) << LABELS{"proto"} << "Session already exists";
}
return *s;
}
template<typename SessionType, typename FunctionType>
inline bool applyToSession(SessionsMap<SessionType>& sessions, ConnectionType& connection, FunctionType fun)
{
auto found{sessions.find(&connection)};
if (found != sessions.end())
{
fun(*(*found).second);
}
return (found != sessions.end());
}
inline void distributeChunk(Chunk& chunk)
{
// sending chunk to all HTTP sessions
auto counter{commandSessions.size()};
for (auto& entry : commandSessions)
{
auto streamingSessionPtr{entry.second->getStreamingSession()};
if (streamingSessionPtr)
{
streamingSessionPtr->onChunk(chunk);
counter--;
}
}
// if there are command sessions without relevant HTTP session
if (counter > 0)
{
LOG(WARNING) << LABELS{"proto"} << "A chunk was not delivered to all clients (clients=" << commandSessions.size() << ", skipped=" << counter << ", size=" << chunk.getSize() << ")";
}
else
{
LOG(DEBUG) << LABELS{"proto"} << "A chunk was delivered (clients=" << commandSessions.size() << ", size=" << chunk.getSize() << ")";
}
}
template<typename SessionType>
auto findSessionByID(SessionsMap<SessionType>& sessions, std::string clientID)
{
auto result{std::optional<SessionType*>{std::nullopt}};
auto found{std::find_if(sessions.begin(), sessions.end(), [&](auto& entry) -> bool
{
auto found{false};
if (entry.second->getClientID() == clientID)
{
found = true;
}
return found;
})};
if (found != sessions.end())
{
result = (*found).second.get();
}
return result;
}
inline auto isReadyToStream()
{
// TODO: deferring time-out should be configurable
auto result{500 < std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startedAt).count()};
auto missingSessionsTotal{std::count_if(commandSessions.begin(), commandSessions.end(), [&](auto& entry)
{
auto streamingSessionPtr{entry.second->getStreamingSession()};
return !(streamingSessionPtr && samplingRate == streamingSessionPtr->getSamplingRate());
})};
// if deferring time-out has expired
if (result && missingSessionsTotal)
{
LOG(WARNING) << LABELS{"proto"} << "Could not defer chunk processing due to reached threashold";
}
else if (!result)
{
// if all HTTP sessions were established
if (!missingSessionsTotal)
{
result = true;
}
else
{
LOG(DEBUG) << LABELS{"proto"} << "Deferring chunk transmition due to missing HTTP sessions";
// TODO: implement cruise control; for now sleep is good enough
// this sleep prevents from busy spinning until all HTTP sessions reconnect
std::this_thread::sleep_for(std::chrono::milliseconds{20});
}
}
return result;
}
template<typename SessionType>
inline auto removeSession(SessionsMap<SessionType>& sessions, ConnectionType& connection)
{
std::unique_ptr<SessionType> sessionPtr{};
auto found{sessions.find(&connection)};
if (found != sessions.end())
{
sessionPtr = std::move((*found).second);
sessions.erase(found);
LOG(DEBUG) << LABELS{"proto"} << "Session was removed (id=" << sessionPtr.get() << ", sessions=" << sessions.size() << ")";
}
return std::move(sessionPtr);
}
private:
unsigned int streamingPort;
EncoderBuilder encoderBuilder;
std::optional<unsigned int> gain;
SessionsMap<CommandSessionType> commandSessions;
SessionsMap<StreamingSessionType> streamingSessions;
bool streaming{false};
unsigned int samplingRate{0};
unsigned long nextID{0};
std::atomic<bool> monitorFinish{false};
std::thread monitorThread;
TimePoint startedAt;
};
}
}
<commit_msg>Minor changes<commit_after>/*
* Copyright 2017, Andrej Kislovskij
*
* This is PUBLIC DOMAIN software so use at your own risk as it comes
* with no warranties. This code is yours to share, use and modify without
* any restrictions or obligations.
*
* For more information see conwrap/LICENSE or refer refer to http://unlicense.org
*
* Author: gimesketvirtadieni at gmail dot com (Andrej Kislovskij)
*/
#pragma once
#include <algorithm>
#include <atomic>
#include <chrono>
#include <conwrap/ProcessorProxy.hpp>
#include <cstddef> // std::size_t
#include <functional>
#include <memory>
#include <optional>
#include <sstream> // std::stringstream
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
#include "slim/Chunk.hpp"
#include "slim/Consumer.hpp"
#include "slim/ContainerBase.hpp"
#include "slim/EncoderBuilder.hpp"
#include "slim/Exception.hpp"
#include "slim/log/log.hpp"
#include "slim/proto/Command.hpp"
#include "slim/proto/CommandSession.hpp"
#include "slim/proto/StreamingSession.hpp"
namespace slim
{
namespace proto
{
template<typename ConnectionType>
class Streamer : public Consumer
{
template<typename SessionType>
using SessionsMap = std::unordered_map<ConnectionType*, std::unique_ptr<SessionType>>;
using TimePoint = std::chrono::time_point<std::chrono::steady_clock>;
using CommandSessionType = CommandSession<ConnectionType>;
using StreamingSessionType = StreamingSession<ConnectionType>;
public:
Streamer(unsigned int sp, EncoderBuilder eb, std::optional<unsigned int> g)
: streamingPort{sp}
, encoderBuilder{eb}
, gain{g}
, monitorThread{[&]
{
LOG(DEBUG) << LABELS{"proto"} << "Monitor thread was started (id=" << std::this_thread::get_id() << ")";
for(unsigned int counter{0}; !monitorFinish; counter++, std::this_thread::sleep_for(std::chrono::milliseconds{200}))
{
// TODO: make configurable
if (counter > 24)
{
auto processorProxyPtr{getProcessorProxy()};
if (processorProxyPtr)
{
processorProxyPtr->process([&]
{
// sending ping command to measure round-trip latency
for (auto& entry : commandSessions)
{
entry.second->ping();
}
});
}
counter = 0;
}
}
LOG(DEBUG) << LABELS{"proto"} << "Monitor thread was stopped (id=" << std::this_thread::get_id() << ")";
}}
{
LOG(DEBUG) << LABELS{"proto"} << "Streamer object was created (id=" << this << ")";
}
virtual ~Streamer()
{
// stopping monitor thread
monitorFinish = true;
if (monitorThread.joinable())
{
monitorThread.join();
}
LOG(DEBUG) << LABELS{"proto"} << "Streamer object was deleted (id=" << this << ")";
}
// TODO: non-movable is required due to usage in server callbacks; consider refactoring
Streamer(const Streamer&) = delete; // non-copyable
Streamer& operator=(const Streamer&) = delete; // non-assignable
Streamer(Streamer&& rhs) = delete; // non-movable
Streamer& operator=(Streamer&& rhs) = delete; // non-movable-assinable
virtual bool consumeChunk(Chunk& chunk) override
{
auto result{false};
auto chunkSamplingRate{chunk.getSamplingRate()};
if (samplingRate != chunkSamplingRate)
{
if (samplingRate)
{
// propogating end-of-stream to all the clients
stop();
// changing state to not streaming
streaming = false;
}
// assigning new sampling rate
samplingRate = chunkSamplingRate;
// if this is the beginning of a stream
if (chunkSamplingRate)
{
start();
}
}
else if (samplingRate)
{
if (!streaming)
{
// checking if all conditions for streaming were met
streaming = isReadyToStream();
}
if (streaming)
{
// sending out Chunk to all the clients
distributeChunk(chunk);
// it will make Chunk to be consumed
result = true;
}
}
else
{
// consuming Chunk in case when samplingRate == chunkSamplingRate == 0
result = true;
}
return result;
}
void onHTTPClose(ConnectionType& connection)
{
LOG(INFO) << LABELS{"proto"} << "HTTP close callback (connection=" << &connection << ")";
auto streamingSessionPtr{removeSession(streamingSessions, connection)};
if (streamingSessionPtr)
{
// if there is a relevant SlimProto connection found
auto clientID{streamingSessionPtr->getClientID()};
auto commandSession{findSessionByID(commandSessions, clientID)};
if (commandSession.has_value())
{
// resetting HTTP session in its relevant SlimProto session
commandSession.value()->setStreamingSession(nullptr);
}
else
{
LOG(WARNING) << LABELS{"proto"} << "Could not find SlimProto session by client ID (clientID=" << clientID << ")";
}
}
else
{
LOG(WARNING) << LABELS{"proto"} << "Could not find HTTP session object";
}
}
void onHTTPData(ConnectionType& connection, unsigned char* buffer, std::size_t receivedSize)
{
if (!applyToSession(streamingSessions, connection, [&](StreamingSessionType& session)
{
// processing request by a proper Streaming session mapped to this connection
session.onRequest(buffer, receivedSize);
}))
{
// parsing client ID
auto clientID = StreamingSessionType::parseClientID(std::string{(char*)buffer, receivedSize});
if (!clientID.has_value())
{
throw slim::Exception("Missing client ID in streaming session request");
}
LOG(INFO) << LABELS{"proto"} << "Client ID was parsed (clientID=" << clientID.value() << ")";
// configuring an encoder builder
encoderBuilder.setSamplingRate(samplingRate);
encoderBuilder.setWriter(&connection);
// creating streaming session object
auto streamingSessionPtr{std::make_unique<StreamingSessionType>(std::ref<ConnectionType>(connection), std::move(encoderBuilder.build()), samplingRate, clientID.value())};
// saving Streaming session reference in the relevant Command session
auto commandSessionPtr{findSessionByID(commandSessions, clientID.value())};
if (!commandSessionPtr.has_value())
{
throw slim::Exception("Could not correlate provided client ID with a valid SlimProto session");
}
commandSessionPtr.value()->setStreamingSession(streamingSessionPtr.get());
// processing request by a proper Streaming session mapped to this connection
streamingSessionPtr->onRequest(buffer, receivedSize);
// saving Streaming session as a part of this Streamer
addSession(streamingSessions, connection, std::move(streamingSessionPtr));
}
}
void onHTTPOpen(ConnectionType& connection)
{
LOG(INFO) << LABELS{"proto"} << "New HTTP session request received (connection=" << &connection << ")";
}
void onSlimProtoClose(ConnectionType& connection)
{
removeSession(commandSessions, connection);
}
void onSlimProtoData(ConnectionType& connection, unsigned char* buffer, std::size_t size)
{
try
{
if (!applyToSession(commandSessions, connection, [&](CommandSessionType& session)
{
session.onRequest(buffer, size);
}))
{
throw slim::Exception("Could not find SlimProto session object");
}
}
catch (const slim::Exception& error)
{
LOG(ERROR) << LABELS{"proto"} << "Error while processing SlimProto command: " << error.what();
connection.stop();
}
}
void onSlimProtoOpen(ConnectionType& connection)
{
// using regular counter for session ID's instead of MAC's; it allows running multiple players on one host
std::stringstream ss;
ss << (++nextID);
// creating command session object
auto commandSessionPtr{std::make_unique<CommandSessionType>(std::ref<ConnectionType>(connection), ss.str(), streamingPort, encoderBuilder.getFormat(), gain)};
// enable streaming for this session if required
if (streaming)
{
commandSessionPtr->setSamplingRate(samplingRate);
commandSessionPtr->start();
}
// saving command session in the map
addSession(commandSessions, connection, std::move(commandSessionPtr));
}
virtual void start() override
{
for (auto& entry : commandSessions)
{
// TODO: this is a temporary solution
entry.second->setSamplingRate(samplingRate);
entry.second->start();
}
// saving when streaming was started - required for calculating defer time-out
startedAt = std::chrono::steady_clock::now();
}
virtual void stop(bool gracefully = true) override
{
// stopping SlimProto session will send end-of-stream command which normally triggers close of HTTP connection
// TODO: implement 'safety' logic to close HTTP connection in case client does not
for (auto& entry : commandSessions)
{
entry.second->stop();
}
}
protected:
template<typename SessionType>
inline auto& addSession(SessionsMap<SessionType>& sessions, ConnectionType& connection, std::unique_ptr<SessionType> sessionPtr)
{
auto found{sessions.find(&connection)};
SessionType* s{nullptr};
if (found == sessions.end())
{
s = sessionPtr.get();
// saving session in a map; using pointer to a relevant connection as an ID
sessions[&connection] = std::move(sessionPtr);
LOG(DEBUG) << LABELS{"proto"} << "New session was added (id=" << s << ", sessions=" << sessions.size() << ")";
}
else
{
s = (*found).second.get();
LOG(WARNING) << LABELS{"proto"} << "Session already exists";
}
return *s;
}
template<typename SessionType, typename FunctionType>
inline bool applyToSession(SessionsMap<SessionType>& sessions, ConnectionType& connection, FunctionType fun)
{
auto found{sessions.find(&connection)};
if (found != sessions.end())
{
fun(*(*found).second);
}
return (found != sessions.end());
}
inline void distributeChunk(Chunk& chunk)
{
// sending chunk to all HTTP sessions
auto counter{commandSessions.size()};
for (auto& entry : commandSessions)
{
auto streamingSessionPtr{entry.second->getStreamingSession()};
if (streamingSessionPtr)
{
streamingSessionPtr->onChunk(chunk);
counter--;
}
}
// if there are command sessions without relevant HTTP session
if (counter > 0)
{
LOG(WARNING) << LABELS{"proto"} << "A chunk was not delivered to all clients (clients=" << commandSessions.size() << ", skipped=" << counter << ", size=" << chunk.getSize() << ")";
}
else
{
LOG(DEBUG) << LABELS{"proto"} << "A chunk was delivered (clients=" << commandSessions.size() << ", size=" << chunk.getSize() << ")";
}
}
template<typename SessionType>
auto findSessionByID(SessionsMap<SessionType>& sessions, std::string clientID)
{
auto result{std::optional<SessionType*>{std::nullopt}};
auto found{std::find_if(sessions.begin(), sessions.end(), [&](auto& entry) -> bool
{
auto found{false};
if (entry.second->getClientID() == clientID)
{
found = true;
}
return found;
})};
if (found != sessions.end())
{
result = (*found).second.get();
}
return result;
}
inline auto isReadyToStream()
{
// TODO: deferring time-out should be configurable
auto result{500 < std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startedAt).count()};
auto missingSessionsTotal{std::count_if(commandSessions.begin(), commandSessions.end(), [&](auto& entry)
{
auto streamingSessionPtr{entry.second->getStreamingSession()};
return !(streamingSessionPtr && samplingRate == streamingSessionPtr->getSamplingRate());
})};
// if deferring time-out has expired
if (result && missingSessionsTotal)
{
LOG(WARNING) << LABELS{"proto"} << "Could not defer chunk processing due to reached threashold";
}
else if (!result)
{
// if all HTTP sessions were established
if (!missingSessionsTotal)
{
result = true;
}
else
{
LOG(DEBUG) << LABELS{"proto"} << "Deferring chunk transmition due to missing HTTP sessions";
// TODO: implement cruise control; for now sleep is good enough
// this sleep prevents from busy spinning until all HTTP sessions reconnect
std::this_thread::sleep_for(std::chrono::milliseconds{20});
}
}
return result;
}
template<typename SessionType>
inline auto removeSession(SessionsMap<SessionType>& sessions, ConnectionType& connection)
{
std::unique_ptr<SessionType> sessionPtr{};
auto found{sessions.find(&connection)};
if (found != sessions.end())
{
sessionPtr = std::move((*found).second);
sessions.erase(found);
LOG(DEBUG) << LABELS{"proto"} << "Session was removed (id=" << sessionPtr.get() << ", sessions=" << sessions.size() << ")";
}
return std::move(sessionPtr);
}
private:
unsigned int streamingPort;
EncoderBuilder encoderBuilder;
std::optional<unsigned int> gain;
SessionsMap<CommandSessionType> commandSessions;
SessionsMap<StreamingSessionType> streamingSessions;
bool streaming{false};
unsigned int samplingRate{0};
unsigned long nextID{0};
std::atomic<bool> monitorFinish{false};
std::thread monitorThread;
TimePoint startedAt;
};
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <eos/chain/block.hpp>
#include <eos/chain/types.hpp>
namespace eos {
using namespace chain;
using namespace fc;
struct handshake_message {
int16_t network_version = 0;
chain_id_type chain_id; ///< used to identify chain
fc::sha256 node_id; ///< used to identify peers and prevent self-connect
string p2p_address;
uint32_t last_irreversible_block_num = 0;
block_id_type last_irreversible_block_id;
uint32_t head_num = 0;
block_id_type head_id;
string os;
string agent;
};
struct notice_message {
vector<transaction_id_type> known_trx;
vector<block_id_type> known_blocks;
};
struct request_message {
vector<transaction_id_type> req_trx;
vector<block_id_type> req_blocks;
};
struct block_summary_message {
signed_block block;
vector<transaction_id_type> trx_ids;
};
struct sync_request_message {
uint32_t start_block;
uint32_t end_block;
};
struct peer_message {
vector<fc::ip::endpoint> peers;
};
using net_message = static_variant<handshake_message,
peer_message,
notice_message,
request_message,
sync_request_message,
block_summary_message,
SignedTransaction,
signed_block>;
} // namespace eos
FC_REFLECT( eos::handshake_message,
(network_version)(chain_id)(node_id)
(p2p_address)
(last_irreversible_block_num)(last_irreversible_block_id)
(head_num)(head_id)
(os)(agent) )
FC_REFLECT( eos::block_summary_message, (block)(trx_ids) )
FC_REFLECT( eos::notice_message, (known_trx)(known_blocks) )
FC_REFLECT( eos::request_message, (req_trx)(req_blocks) )
FC_REFLECT( eos::sync_request_message, (start_block)(end_block) )
FC_REFLECT( eos::peer_message, (peers) )
/**
*
Goals of Network Code
1. low latency to minimize missed blocks and potentially reduce block interval
2. minimize redundant data between blocks and transactions.
3. enable rapid sync of a new node
4. update to new boost / fc
State:
All nodes know which blocks and transactions they have
All nodes know which blocks and transactions their peers have
A node knows which blocks and transactions it has requested
All nodes know when they learned of a transaction
send hello message
write loop (true)
if peer knows the last irreversible block {
if peer does not know you know a block or transactions
send the ids you know (so they don't send it to you)
yield continue
if peer does not know about a block
send transactions in block peer doesn't know then send block summary
yield continue
if peer does not know about new public endpoints that you have verified
relay new endpoints to peer
yield continue
if peer does not know about transactions
sends the oldest transactions that is not known by the remote peer
yield continue
wait for new validated block, transaction, or peer signal from network fiber
} else {
we assume peer is in sync mode in which case it is operating on a
request / response basis
wait for notice of sync from the read loop
}
read loop
if hello message
verify that peers Last Ir Block is in our state or disconnect, they are on fork
verify peer network protocol
if notice message update list of transactions known by remote peer
if trx message then insert into global state as unvalidated
if blk summary message then insert into global state *if* we know of all dependent transactions
else close connection
if my head block < the LIB of a peer and my head block age > block interval * round_size/2 then
enter sync mode...
divide the block numbers you need to fetch among peers and send fetch request
if peer does not respond to request in a timely manner then make request to another peer
ensure that there is a constant queue of requests in flight and everytime a request is filled
send of another request.
Once you have caught up to all peers, notify all peers of your head block so they know that you
know the LIB and will start sending you real time tranasctions
parallel fetches, request in groups
only relay transactions to peers if we don't already know about it.
send a notification rather than a transaaction if the txn is > 3mtu size.
*/
<commit_msg>Update protocol.hpp<commit_after>#pragma once
#include <eos/chain/block.hpp>
#include <eos/chain/types.hpp>
namespace eos {
using namespace chain;
using namespace fc;
struct handshake_message {
int16_t network_version = 0;
chain_id_type chain_id; ///< used to identify chain
fc::sha256 node_id; ///< used to identify peers and prevent self-connect
string p2p_address;
uint32_t last_irreversible_block_num = 0;
block_id_type last_irreversible_block_id;
uint32_t head_num = 0;
block_id_type head_id;
string os;
string agent;
};
struct notice_message {
vector<transaction_id_type> known_trx;
vector<block_id_type> known_blocks;
};
struct request_message {
vector<transaction_id_type> req_trx;
vector<block_id_type> req_blocks;
};
struct block_summary_message {
signed_block block;
vector<transaction_id_type> trx_ids;
};
struct sync_request_message {
uint32_t start_block;
uint32_t end_block;
};
struct peer_message {
vector<fc::ip::endpoint> peers;
};
using net_message = static_variant<handshake_message,
peer_message,
notice_message,
request_message,
sync_request_message,
block_summary_message,
SignedTransaction,
signed_block>;
} // namespace eos
FC_REFLECT( eos::handshake_message,
(network_version)(chain_id)(node_id)
(p2p_address)
(last_irreversible_block_num)(last_irreversible_block_id)
(head_num)(head_id)
(os)(agent) )
FC_REFLECT( eos::block_summary_message, (block)(trx_ids) )
FC_REFLECT( eos::notice_message, (known_trx)(known_blocks) )
FC_REFLECT( eos::request_message, (req_trx)(req_blocks) )
FC_REFLECT( eos::sync_request_message, (start_block)(end_block) )
FC_REFLECT( eos::peer_message, (peers) )
/**
*
Goals of Network Code
1. low latency to minimize missed blocks and potentially reduce block interval
2. minimize redundant data between blocks and transactions.
3. enable rapid sync of a new node
4. update to new boost / fc
State:
All nodes know which blocks and transactions they have
All nodes know which blocks and transactions their peers have
A node knows which blocks and transactions it has requested
All nodes know when they learned of a transaction
send hello message
write loop (true)
if peer knows the last irreversible block {
if peer does not know you know a block or transactions
send the ids you know (so they don't send it to you)
yield continue
if peer does not know about a block
send transactions in block peer doesn't know then send block summary
yield continue
if peer does not know about new public endpoints that you have verified
relay new endpoints to peer
yield continue
if peer does not know about transactions
sends the oldest transactions that is not known by the remote peer
yield continue
wait for new validated block, transaction, or peer signal from network fiber
} else {
we assume peer is in sync mode in which case it is operating on a
request / response basis
wait for notice of sync from the read loop
}
read loop
if hello message
verify that peers Last Ir Block is in our state or disconnect, they are on fork
verify peer network protocol
if notice message update list of transactions known by remote peer
if trx message then insert into global state as unvalidated
if blk summary message then insert into global state *if* we know of all dependent transactions
else close connection
if my head block < the LIB of a peer and my head block age > block interval * round_size/2 then
enter sync mode...
divide the block numbers you need to fetch among peers and send fetch request
if peer does not respond to request in a timely manner then make request to another peer
ensure that there is a constant queue of requests in flight and everytime a request is filled
send of another request.
Once you have caught up to all peers, notify all peers of your head block so they know that you
know the LIB and will start sending you real time tranasctions
parallel fetches, request in groups
only relay transactions to peers if we don't already know about it.
send a notification rather than a transaction if the txn is > 3mtu size.
*/
<|endoftext|> |
<commit_before>#include "KickEvaluator.hpp"
#include <algorithm>
#include <vector>
#include <math.h>
#include <cmath>
REGISTER_CONFIGURABLE(KickEvaluator)
using namespace std;
using namespace Geometry2d;
ConfigDouble* KickEvaluator::kick_std_dev;
ConfigDouble* KickEvaluator::kick_mean;
ConfigDouble* KickEvaluator::robot_std_dev;
ConfigDouble* KickEvaluator::start_x_offset;
void KickEvaluator::createConfiguration(Configuration* cfg) {
kick_std_dev = new ConfigDouble(cfg,
"KickEvaluator/kick_std_dev", 0.08);
kick_mean = new ConfigDouble(cfg,
"KickEvaluator/kick_mean", 0);
robot_std_dev = new ConfigDouble(cfg,
"KickEvaluator/robot_std_dev", 0.3);
start_x_offset = new ConfigDouble(cfg,
"KickEvaluator/start_x_offset", 0.1);
}
KickEvaluator::KickEvaluator(SystemState* systemState) : system(systemState) {}
KickResults KickEvaluator::eval_pt_to_pt(Point origin, Point target,
float targetWidth) {
Point dir = (target - origin).perpCCW().normalized();
Segment seg = Segment{target + dir * (targetWidth / 2),
target - dir * (targetWidth / 2)};
return eval_pt_to_seg(origin, seg);
}
KickResults KickEvaluator::eval_pt_to_robot(Point origin, Point target) {
return eval_pt_to_pt(origin, target, 2* Robot_Radius);
}
KickResults KickEvaluator::eval_pt_to_opp_goal(Point origin) {
Segment their_goal{
Point{-Field_Dimensions::Current_Dimensions.GoalWidth() / 2,
Field_Dimensions::Current_Dimensions.Length()},
Point{Field_Dimensions::Current_Dimensions.GoalWidth() / 2,
Field_Dimensions::Current_Dimensions.Length()}
};
return eval_pt_to_seg(origin, their_goal);
}
KickResults KickEvaluator::eval_pt_to_our_goal(Point origin) {
Segment our_goal{
Point{-Field_Dimensions::Current_Dimensions.GoalWidth() / 2, 0},
Point{Field_Dimensions::Current_Dimensions.GoalWidth() / 2, 0}
};
return eval_pt_to_seg(origin, our_goal);
}
KickResults KickEvaluator::eval_pt_to_seg(Point origin, Segment target) {
Point center = target.center();
double targetWidth = get_target_angle(origin, target);
// Polar bot locations
// <Dist, Angle>
vector< tuple<double, double> > botLocations =
convert_robots_to_polar(origin, center);
// Convert polar to mean / std_dev / Vertical Scales
vector<double> botMeans;
vector<double> botStDevs;
vector<double> botVertScales;
for (tuple<double, double>& loc : botLocations){
botMeans.push_back(get<1>(loc));
// Want std_dev in radians, not XY distance
botStDevs.push_back(atan(*robot_std_dev / get<0>(loc)));
// Robot Past Target
double distPastTarget = get<0>(loc) - (origin - center).mag();
// If robot is past target, only use the chance at the target segment
if (distPastTarget > 0 && fabs(get<1>(loc)) < M_PI / 2) {
// Evaluate a normal distribution at dist away and scale
double stdev2 = pow(*robot_std_dev, 2);
botVertScales.push_back(1 / stdev2 * exp(-0.5 * pow(distPastTarget, 2) / stdev2));
} else {
botVertScales.push_back(1);
}
}
// No opponent robots on the field
if (botMeans.size() == 0) {
botMeans.push_back(0);
// Must be non-zero as 1 / botStDev is used
botStDevs.push_back(1);
botVertScales.push_back(0);
}
// Create KickEvaluator Function parameters
unique_ptr<KickEvaluatorArgs> keArgs(
new KickEvaluatorArgs(*kick_mean, *kick_std_dev,
botMeans, botStDevs, botVertScales,
targetWidth / -2, targetWidth / 2));
ParallelGradient1DConfig parallelConfig = init_gradient_configs(keArgs.get());
// Create Gradient Ascent Optimizer and run it
ParallelGradientAscent1D optimizer(parallelConfig);
optimizer.execute();
// Grab the lcoal max values and their X location
vector<double> maxXValues = optimizer.getMaxXValues();
vector<double> maxValues = optimizer.getMaxValues();
// Find the segment out of the list
double maxX;
double maxChance;
// More than one local max
if (maxXValues.size() > 1) {
// This happens when there is a "flat" top
// Find the highest average between the two
maxX = 0;
maxChance = 0;
for (int i = 0; i < maxXValues.size() - 1; i++) {
double midPoint = (maxXValues.at(i + 1) + maxXValues.at(i)) / 2;
double chance = get<0>(eval_calculation(midPoint, keArgs.get()));
if (chance > maxChance) {
maxX = midPoint;
maxChance = chance;
}
}
} else {
maxX = maxXValues.at(0);
maxChance = maxValues.at(0);
}
// Angle in reference to the field
double realMaxAngle = maxX + (center - origin).angle();
Line bestKickLine(origin, Point{cos(realMaxAngle), sin(realMaxAngle)});
// Return point on target segment and chance
return pair<Point, double>(target.nearestPoint(bestKickLine), maxChance);
}
tuple<double, double> KickEvaluator::eval_calculation(double x, FunctionArgs* fArgs) {
// 3 Main distribution sets
// Set #1 : A set of each normal distribution for the obstacles
// Set #2 : A band pass style distribution that represents a valid target kick
// Set #3 : A normal distribution representing a kick
// Set #1 and #2 are combined. To keep the convolution simple, Set #2 is represented using
// a Unit step function and just added/subtracted to/from Set #1
// This will cause problems along the edges when a robot is near since it will go negative
// But it is not /super/ significant
// The resulting F(X) represents the convolution of Set #12 and Set #3
// All of this is calculated with Mathematica
KickEvaluatorArgs* args = static_cast<KickEvaluatorArgs*>(fArgs);
// We want the worst chance of success
double minResults = 1;
double minIndex = 0;
// Shortcuts for repeated operations
double sqrt2pi = sqrt(2*M_PI);
double sqrtpi_2 = sqrt(M_PI / 2);
double kmean = args->kickMean;
double kstdev = args->kickStDev;
double kstdev2 = pow(kstdev, 2);
double rmean;
double rstdev;
double rstdev2;
double robotV;
double kx = kmean - x;
double fterm; // First term, Robot normal distribution
double sterm; // Second term, Left boundary
double tterm; // Third term, Right Boundary
// For each robot distribution in Set #1
for (int i = 0; i < args->robotMeans.size(); i++) {
rmean = args->robotMeans.at(i);
rstdev = args->robotStDevs.at(i);
rstdev2 = pow(rstdev, 2);
robotV = args->robotVertScales.at(i);
fterm = -1 * exp(-0.5 * pow(kx + rmean, 2) / (kstdev2 + rstdev2)) * robotV * sqrt2pi;
fterm = fterm / sqrt(1 / kstdev2 + 1 / rstdev2);
sterm = 1 / sqrt(1 / kstdev2) - kstdev * erf((kx + args->boundaryLower) / (sqrt(2) * kstdev));
sterm *= sqrtpi_2;
tterm = 1 / sqrt(1 / kstdev2) - kstdev * erf((kx + args->boundaryUpper) / (sqrt(2) * kstdev));
tterm *= sqrtpi_2;
double results = 1 / (kstdev * sqrt2pi) * (fterm + sterm - tterm);
if (results < minResults) {
minResults = results;
minIndex = i;
}
}
// Calculate derivative of the convolution
rmean = args->robotMeans.at(minIndex);
rstdev = args->robotStDevs.at(minIndex);
rstdev2 = pow(rstdev, 2);
robotV = args->robotVertScales.at(minIndex);
fterm = exp(-0.5 * pow(kx + rmean, 2) / (kstdev2 + rstdev2)) * robotV * sqrt2pi * (kx + rmean);
fterm = fterm / (sqrt(1 / kstdev2 + 1 / rstdev2) * (kstdev2 + rstdev2));
sterm = exp(-0.5 * pow(kx + args->boundaryLower, 2) / kstdev2);
tterm = exp(-0.5 * pow(kx + args->boundaryUpper, 2) / kstdev2);
double derivative = 1 / (kstdev * sqrt2pi) * (sterm - tterm - fterm);
return make_tuple(minResults, derivative);
}
double KickEvaluator::get_target_angle(Point origin, Segment target) {
Point left = target.pt[0] - origin;
Point right = target.pt[1] - origin;
return abs(left.angle() - right.angle());
}
vector<Robot*> KickEvaluator::get_valid_robots() {
vector<Robot*> bots(system->self.size() + system->opp.size());
auto filter_predicate = [&](const Robot* bot) -> bool {
return bot != nullptr && bot->visible &&
find(excluded_robots.begin(), excluded_robots.end(), bot) ==
excluded_robots.end();
};
auto end_it = copy_if(system->self.begin(), system->self.end(),
bots.begin(), filter_predicate);
end_it = copy_if(system->opp.begin(), system->opp.end(),
end_it, filter_predicate);
bots.resize(distance(bots.begin(), end_it));
return bots;
}
tuple<double, double> KickEvaluator::rect_to_polar(Point origin,
Point target,
Point obstacle) {
Point obstacleDir = obstacle - origin;
Point targetDir = target - origin;
double angle = obstacleDir.angle() - targetDir.angle();
// Force between -pi and pi
angle = atan2(sin(angle), cos(angle));
return make_tuple(obstacleDir.mag(), angle);
}
vector< tuple<double, double> > KickEvaluator::convert_robots_to_polar(Point origin, Point target) {
vector<Robot*> bots = get_valid_robots();
vector< tuple<double, double> > botLocations;
// Convert each bot position to polar
for_each(bots.begin(), bots.end(),
[&botLocations, target, origin, this](Robot* bot) {
botLocations.push_back(rect_to_polar(origin,
target,
bot->pos));
});
// Convert imaginary obstacles to polar
for_each(hypothetical_robot_locations.begin(),
hypothetical_robot_locations.end(),
[&botLocations, target, origin, this](Point obstacle) {
botLocations.push_back(rect_to_polar(origin,
target,
obstacle));
});
return botLocations;
}
ParallelGradient1DConfig KickEvaluator::init_gradient_configs(KickEvaluatorArgs* keArgs) {
// Create list of single configs
vector<Gradient1DConfig> singleGradientConfigs;
// Standard Gradient Configs
double dxError = 0.01;
double maxXMovement = *min_element(keArgs->robotStDevs.begin(), keArgs->robotStDevs.end()) / 5;
double temperatureDescent = 0.5;
double temperatureMin = 0.01;
int maxIterations = 100;
double maxValue = 1;
double maxThresh = 0.01;
double boundaryLower = keArgs->boundaryLower;
double boundaryUpper = keArgs->boundaryUpper;
// PrevStart, Start
vector< tuple<double, double> > xStarts;
double startX = boundaryLower + *start_x_offset * keArgs->kickStDev;
xStarts.push_back(make_tuple(boundaryLower, startX));
startX = boundaryUpper - *start_x_offset * keArgs->kickStDev;
xStarts.push_back(make_tuple(boundaryUpper, startX));
// For each robot
for (int i = 0; i < keArgs->robotMeans.size(); i++) {
// -1 or 1
for (int side = -1; side <= 1; side += 2) {
startX = keArgs->robotMeans.at(i) + side * *start_x_offset * keArgs->robotStDevs.at(i);
xStarts.push_back(make_tuple(keArgs->robotMeans.at(i), startX));
}
}
// Force into ascending order to make things simpler
sort(xStarts.begin(), xStarts.end(), [&](tuple<double, double> a, tuple<double, double> b) {
return get<1>(a) < get<1>(b);
});
// Create list of configs
for (tuple<double, double> xStart : xStarts) {
singleGradientConfigs.push_back(
Gradient1DConfig(&eval_calculation, keArgs,
get<1>(xStart), get<0>(xStart),
dxError, maxXMovement,
temperatureDescent, temperatureMin,
maxIterations, maxValue, maxThresh));
}
// Create config from all the singles and the min std_dev
double xCombineThresh = *min_element(keArgs->robotStDevs.begin(), keArgs->robotStDevs.end()) * *start_x_offset / 2;
return ParallelGradient1DConfig(singleGradientConfigs, xCombineThresh);
}<commit_msg>Fixed case where there is only one local max Switched some stuff to the utils functions<commit_after>#include "KickEvaluator.hpp"
#include <Utils.hpp>
#include <Geometry2d/Util.hpp>
#include <algorithm>
#include <vector>
#include <math.h>
#include <cmath>
REGISTER_CONFIGURABLE(KickEvaluator)
using namespace std;
using namespace Geometry2d;
ConfigDouble* KickEvaluator::kick_std_dev;
ConfigDouble* KickEvaluator::kick_mean;
ConfigDouble* KickEvaluator::robot_std_dev;
ConfigDouble* KickEvaluator::start_x_offset;
void KickEvaluator::createConfiguration(Configuration* cfg) {
kick_std_dev = new ConfigDouble(cfg,
"KickEvaluator/kick_std_dev", 0.08);
kick_mean = new ConfigDouble(cfg,
"KickEvaluator/kick_mean", 0);
robot_std_dev = new ConfigDouble(cfg,
"KickEvaluator/robot_std_dev", 0.3);
start_x_offset = new ConfigDouble(cfg,
"KickEvaluator/start_x_offset", 0.1);
}
KickEvaluator::KickEvaluator(SystemState* systemState) : system(systemState) {}
KickResults KickEvaluator::eval_pt_to_pt(Point origin, Point target,
float targetWidth) {
Point dir = (target - origin).perpCCW().normalized();
Segment seg = Segment{target + dir * (targetWidth / 2),
target - dir * (targetWidth / 2)};
return eval_pt_to_seg(origin, seg);
}
KickResults KickEvaluator::eval_pt_to_robot(Point origin, Point target) {
return eval_pt_to_pt(origin, target, 2* Robot_Radius);
}
KickResults KickEvaluator::eval_pt_to_opp_goal(Point origin) {
Segment their_goal{
Point{-Field_Dimensions::Current_Dimensions.GoalWidth() / 2,
Field_Dimensions::Current_Dimensions.Length()},
Point{Field_Dimensions::Current_Dimensions.GoalWidth() / 2,
Field_Dimensions::Current_Dimensions.Length()}
};
return eval_pt_to_seg(origin, their_goal);
}
KickResults KickEvaluator::eval_pt_to_our_goal(Point origin) {
Segment our_goal{
Point{-Field_Dimensions::Current_Dimensions.GoalWidth() / 2, 0},
Point{Field_Dimensions::Current_Dimensions.GoalWidth() / 2, 0}
};
return eval_pt_to_seg(origin, our_goal);
}
KickResults KickEvaluator::eval_pt_to_seg(Point origin, Segment target) {
Point center = target.center();
double targetWidth = get_target_angle(origin, target);
// Polar bot locations
// <Dist, Angle>
vector< tuple<double, double> > botLocations =
convert_robots_to_polar(origin, center);
// Convert polar to mean / std_dev / Vertical Scales
vector<double> botMeans;
vector<double> botStDevs;
vector<double> botVertScales;
for (tuple<double, double>& loc : botLocations){
botMeans.push_back(get<1>(loc));
// Want std_dev in radians, not XY distance
botStDevs.push_back(atan(*robot_std_dev / get<0>(loc)));
// Robot Past Target
double distPastTarget = get<0>(loc) - (origin - center).mag();
// If robot is past target, only use the chance at the target segment
if (distPastTarget > 0 && fabs(get<1>(loc)) < M_PI / 2) {
// Evaluate a normal distribution at dist away and scale
double stdev2 = pow(*robot_std_dev, 2);
botVertScales.push_back(1 / stdev2 * exp(-0.5 * pow(distPastTarget, 2) / stdev2));
} else {
botVertScales.push_back(1);
}
}
// No opponent robots on the field
if (botMeans.size() == 0) {
botMeans.push_back(0);
// Must be non-zero as 1 / botStDev is used
botStDevs.push_back(1);
botVertScales.push_back(0);
}
// Create KickEvaluator Function parameters
unique_ptr<KickEvaluatorArgs> keArgs(
new KickEvaluatorArgs(*kick_mean, *kick_std_dev,
botMeans, botStDevs, botVertScales,
targetWidth / -2, targetWidth / 2));
ParallelGradient1DConfig parallelConfig = init_gradient_configs(keArgs.get());
// Create Gradient Ascent Optimizer and run it
ParallelGradientAscent1D optimizer(parallelConfig);
optimizer.execute();
// Grab the lcoal max values and their X location
vector<double> maxXValues = optimizer.getMaxXValues();
vector<double> maxValues = optimizer.getMaxValues();
// Default to a local max
int index = distance(maxValues.begin(), max_element(maxValues.begin(), maxValues.end()));
double maxX = maxXValues.at(index);
double maxChance = maxValues.at(index);
// See if there is a segment which is longer
// Since local maxes stop on either side of the segment
if (maxXValues.size() > 1) {
for (int i = 0; i < maxXValues.size() - 1; i++) {
// Finds the score at the average between two local maxes
double midPoint = (maxXValues.at(i) + maxXValues.at(i + 1)) / 2;
double chance = get<0>(eval_calculation(midPoint, keArgs.get()));
if (chance > maxChance || nearlyEqual(chance, maxChance)) {
maxX = midPoint;
maxChance = chance;
}
}
}
// Angle in reference to the field
double realMaxAngle = maxX + (center - origin).angle();
Line bestKickLine(origin, Point{cos(realMaxAngle), sin(realMaxAngle)});
// Return point on target segment and chance
return pair<Point, double>(target.nearestPoint(bestKickLine), maxChance);
}
tuple<double, double> KickEvaluator::eval_calculation(double x, FunctionArgs* fArgs) {
// 3 Main distribution sets
// Set #1 : A set of each normal distribution for the obstacles
// Set #2 : A band pass style distribution that represents a valid target kick
// Set #3 : A normal distribution representing a kick
// Set #1 and #2 are combined. To keep the convolution simple, Set #2 is represented using
// a Unit step function and just added/subtracted to/from Set #1
// This will cause problems along the edges when a robot is near since it will go negative
// But it is not /super/ significant
// The resulting F(X) represents the convolution of Set #12 and Set #3
// All of this is calculated with Mathematica
KickEvaluatorArgs* args = static_cast<KickEvaluatorArgs*>(fArgs);
// We want the worst chance of success
double minResults = 1;
double minIndex = 0;
// Shortcuts for repeated operations
double sqrt2pi = sqrt(2*M_PI);
double sqrtpi_2 = sqrt(M_PI / 2);
double kmean = args->kickMean;
double kstdev = args->kickStDev;
double kstdev2 = pow(kstdev, 2);
double rmean;
double rstdev;
double rstdev2;
double robotV;
double kx = kmean - x;
double fterm; // First term, Robot normal distribution
double sterm; // Second term, Left boundary
double tterm; // Third term, Right Boundary
// For each robot distribution in Set #1
for (int i = 0; i < args->robotMeans.size(); i++) {
rmean = args->robotMeans.at(i);
rstdev = args->robotStDevs.at(i);
rstdev2 = pow(rstdev, 2);
robotV = args->robotVertScales.at(i);
fterm = -1 * exp(-0.5 * pow(kx + rmean, 2) / (kstdev2 + rstdev2)) * robotV * sqrt2pi;
fterm = fterm / sqrt(1 / kstdev2 + 1 / rstdev2);
sterm = 1 / sqrt(1 / kstdev2) - kstdev * erf((kx + args->boundaryLower) / (sqrt(2) * kstdev));
sterm *= sqrtpi_2;
tterm = 1 / sqrt(1 / kstdev2) - kstdev * erf((kx + args->boundaryUpper) / (sqrt(2) * kstdev));
tterm *= sqrtpi_2;
double results = 1 / (kstdev * sqrt2pi) * (fterm + sterm - tterm);
if (results < minResults) {
minResults = results;
minIndex = i;
}
}
// Calculate derivative of the convolution
rmean = args->robotMeans.at(minIndex);
rstdev = args->robotStDevs.at(minIndex);
rstdev2 = pow(rstdev, 2);
robotV = args->robotVertScales.at(minIndex);
fterm = exp(-0.5 * pow(kx + rmean, 2) / (kstdev2 + rstdev2)) * robotV * sqrt2pi * (kx + rmean);
fterm = fterm / (sqrt(1 / kstdev2 + 1 / rstdev2) * (kstdev2 + rstdev2));
sterm = exp(-0.5 * pow(kx + args->boundaryLower, 2) / kstdev2);
tterm = exp(-0.5 * pow(kx + args->boundaryUpper, 2) / kstdev2);
double derivative = 1 / (kstdev * sqrt2pi) * (sterm - tterm - fterm);
return make_tuple(minResults, derivative);
}
double KickEvaluator::get_target_angle(Point origin, Segment target) {
Point left = target.pt[0] - origin;
Point right = target.pt[1] - origin;
return abs(left.angle() - right.angle());
}
vector<Robot*> KickEvaluator::get_valid_robots() {
vector<Robot*> bots(system->self.size() + system->opp.size());
auto filter_predicate = [&](const Robot* bot) -> bool {
return bot != nullptr && bot->visible &&
find(excluded_robots.begin(), excluded_robots.end(), bot) ==
excluded_robots.end();
};
auto end_it = copy_if(system->self.begin(), system->self.end(),
bots.begin(), filter_predicate);
end_it = copy_if(system->opp.begin(), system->opp.end(),
end_it, filter_predicate);
bots.resize(distance(bots.begin(), end_it));
return bots;
}
tuple<double, double> KickEvaluator::rect_to_polar(Point origin,
Point target,
Point obstacle) {
Point obstacleDir = obstacle - origin;
Point targetDir = target - origin;
double angle = obstacleDir.angle() - targetDir.angle();
return make_tuple(obstacleDir.mag(), fixAngleRadians(angle));
}
vector< tuple<double, double> > KickEvaluator::convert_robots_to_polar(Point origin, Point target) {
vector<Robot*> bots = get_valid_robots();
vector< tuple<double, double> > botLocations;
// Convert each bot position to polar
for_each(bots.begin(), bots.end(),
[&botLocations, target, origin, this](Robot* bot) {
botLocations.push_back(rect_to_polar(origin,
target,
bot->pos));
});
// Convert imaginary obstacles to polar
for_each(hypothetical_robot_locations.begin(),
hypothetical_robot_locations.end(),
[&botLocations, target, origin, this](Point obstacle) {
botLocations.push_back(rect_to_polar(origin,
target,
obstacle));
});
return botLocations;
}
ParallelGradient1DConfig KickEvaluator::init_gradient_configs(KickEvaluatorArgs* keArgs) {
// Create list of single configs
vector<Gradient1DConfig> singleGradientConfigs;
// Standard Gradient Configs
double dxError = 0.01;
double maxXMovement = *min_element(keArgs->robotStDevs.begin(), keArgs->robotStDevs.end()) / 5;
double temperatureDescent = 0.5;
double temperatureMin = 0.01;
int maxIterations = 100;
double maxValue = 1;
double maxThresh = 0.01;
double boundaryLower = keArgs->boundaryLower;
double boundaryUpper = keArgs->boundaryUpper;
// PrevStart, Start
vector< tuple<double, double> > xStarts;
double startX = boundaryLower + *start_x_offset * keArgs->kickStDev;
xStarts.push_back(make_tuple(boundaryLower, startX));
startX = boundaryUpper - *start_x_offset * keArgs->kickStDev;
xStarts.push_back(make_tuple(boundaryUpper, startX));
// For each robot
for (int i = 0; i < keArgs->robotMeans.size(); i++) {
// -1 or 1
for (int side = -1; side <= 1; side += 2) {
startX = keArgs->robotMeans.at(i) + side * *start_x_offset * keArgs->robotStDevs.at(i);
xStarts.push_back(make_tuple(keArgs->robotMeans.at(i), startX));
}
}
// Force into ascending order to make things simpler
sort(xStarts.begin(), xStarts.end(), [&](tuple<double, double> a, tuple<double, double> b) {
return get<1>(a) < get<1>(b);
});
// Create list of configs
for (tuple<double, double> xStart : xStarts) {
singleGradientConfigs.push_back(
Gradient1DConfig(&eval_calculation, keArgs,
get<1>(xStart), get<0>(xStart),
dxError, maxXMovement,
temperatureDescent, temperatureMin,
maxIterations, maxValue, maxThresh));
}
// Create config from all the singles and the min std_dev
double xCombineThresh = *min_element(keArgs->robotStDevs.begin(), keArgs->robotStDevs.end()) * *start_x_offset / 2;
return ParallelGradient1DConfig(singleGradientConfigs, xCombineThresh);
}<|endoftext|> |
<commit_before><commit_msg>ZedPlugin color issue solved<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2009-2018 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
// Maintainer: jglaser
#include "MolecularForceCompute.h"
#include "hoomd/CachedAllocator.h"
#include "hoomd/Autotuner.h"
#ifdef ENABLE_CUDA
#include "MolecularForceCompute.cuh"
#endif
#include <string.h>
#include <map>
namespace py = pybind11;
/*! \file MolecularForceCompute.cc
\brief Contains code for the MolecularForceCompute class
*/
/*! \param sysdef SystemDefinition containing the ParticleData to compute forces on
*/
MolecularForceCompute::MolecularForceCompute(std::shared_ptr<SystemDefinition> sysdef)
: ForceConstraint(sysdef), m_molecule_tag(m_exec_conf), m_n_molecules_global(0), m_dirty(true),
m_molecule_list(m_exec_conf), m_molecule_length(m_exec_conf), m_molecule_order(m_exec_conf),
m_molecule_idx(m_exec_conf)
{
// connect to the ParticleData to recieve notifications when particles change order in memory
m_pdata->getParticleSortSignal().connect<MolecularForceCompute, &MolecularForceCompute::setDirty>(this);
TAG_ALLOCATION(m_molecule_tag);
TAG_ALLOCATION(m_molecule_list);
TAG_ALLOCATION(m_molecule_length);
TAG_ALLOCATION(m_molecule_order);
TAG_ALLOCATION(m_molecule_idx);
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
// initialize autotuner
std::vector<unsigned int> valid_params;
for (unsigned int block_size = 32; block_size <= 1024; block_size += 32)
valid_params.push_back(block_size);
m_tuner_fill.reset(new Autotuner(valid_params, 5, 100000, "fill_molecule_table", this->m_exec_conf));
}
#endif
}
//! Destructor
MolecularForceCompute::~MolecularForceCompute()
{
m_pdata->getParticleSortSignal().disconnect<MolecularForceCompute, &MolecularForceCompute::setDirty>(this);
}
#ifdef ENABLE_CUDA
void MolecularForceCompute::initMoleculesGPU()
{
if (m_prof) m_prof->push(m_exec_conf,"init molecules");
unsigned int nptl_local = m_pdata->getN() + m_pdata->getNGhosts();
unsigned int n_local_molecules = 0;
// maximum molecule length
unsigned int nmax = 0;
// number of local particles that are part of molecules
unsigned int n_local_ptls_in_molecules = 0;
// resize to maximum possible number of local molecules
m_molecule_length.resize(nptl_local);
m_molecule_idx.resize(nptl_local);
ScopedAllocation<unsigned int> d_idx_sorted_by_tag(m_exec_conf->getCachedAllocator(), nptl_local);
ScopedAllocation<unsigned int> d_local_molecule_tags(m_exec_conf->getCachedAllocator(), nptl_local);
{
ArrayHandle<unsigned int> d_molecule_tag(m_molecule_tag, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_molecule_length(m_molecule_length, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_idx(m_molecule_idx, access_location::device, access_mode::overwrite);
// temporary buffers
ScopedAllocation<unsigned int> d_local_unique_molecule_tags(m_exec_conf->getCachedAllocator(), m_n_molecules_global);
ScopedAllocation<unsigned int> d_sorted_by_tag(m_exec_conf->getCachedAllocator(), nptl_local);
gpu_sort_by_molecule(nptl_local,
d_tag.data,
d_molecule_tag.data,
d_local_molecule_tags.data,
d_local_unique_molecule_tags.data,
d_molecule_idx.data,
d_sorted_by_tag.data,
d_idx_sorted_by_tag.data,
d_molecule_length.data,
n_local_molecules,
nmax,
n_local_ptls_in_molecules,
m_exec_conf->getCachedAllocator());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
}
// set up indexer
m_molecule_indexer = Index2D(nmax, n_local_molecules);
m_exec_conf->msg->notice(7) << "MolecularForceCompute: " << n_local_molecules << " molecules, "
<< n_local_ptls_in_molecules << " particles in molecules " << std::endl;
// resize molecule list
m_molecule_list.resize(m_molecule_indexer.getNumElements());
// resize molecule lookup to size of local particle data
m_molecule_order.resize(m_pdata->getMaxN());
{
// write out molecule list and order
ArrayHandle<unsigned int> d_molecule_list(m_molecule_list, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_order(m_molecule_order, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_idx(m_molecule_idx, access_location::device, access_mode::read);
m_tuner_fill->begin();
unsigned int block_size = m_tuner_fill->getParam();
gpu_fill_molecule_table(nptl_local,
n_local_ptls_in_molecules,
m_molecule_indexer,
d_molecule_idx.data,
d_local_molecule_tags.data,
d_idx_sorted_by_tag.data,
d_molecule_list.data,
d_molecule_order.data,
block_size,
m_exec_conf->getCachedAllocator());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_fill->end();
}
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
auto gpu_map = m_exec_conf->getGPUIds();
if (m_exec_conf->getNumActiveGPUs() > 1)
{
for (unsigned int idev = 0; idev < m_exec_conf->getNumActiveGPUs(); ++idev)
{
auto range = m_pdata->getGPUPartition().getRange(idev);
unsigned int nelem = range.second - range.first;
// skip if no hint set
if (!nelem)
continue;
cudaMemAdvise(m_molecule_idx.get()+range.first, sizeof(unsigned int)*nelem, cudaMemAdviseSetPreferredLocation, gpu_map[idev]);
cudaMemPrefetchAsync(m_molecule_idx.get()+range.first, sizeof(unsigned int)*nelem, gpu_map[idev]);
}
CHECK_CUDA_ERROR();
}
}
#endif
if (m_prof) m_prof->pop(m_exec_conf);
}
#endif
void MolecularForceCompute::initMolecules()
{
// return early if no molecules are defined
if (!m_n_molecules_global) return;
m_exec_conf->msg->notice(7) << "MolecularForceCompute initializing molecule table" << std::endl;
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
initMoleculesGPU();
return;
}
#endif
if (m_prof) m_prof->push("init molecules");
// construct local molecule table
unsigned int nptl_local = m_pdata->getN() + m_pdata->getNGhosts();
ArrayHandle<unsigned int> h_molecule_tag(m_molecule_tag, access_location::host, access_mode::read);
ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read);
std::set<unsigned int> local_molecule_tags;
unsigned int n_local_molecules = 0;
std::vector<unsigned int> local_molecule_idx(nptl_local, NO_MOLECULE);
// resize molecule lookup to size of local particle data
m_molecule_order.resize(m_pdata->getMaxN());
// sort local molecules by molecule tag, and inside the molecule by ptl tag
std::map<unsigned int, std::set<unsigned int> > local_molecules_sorted;
for (unsigned int iptl = 0; iptl < nptl_local; ++iptl)
{
unsigned int tag = h_tag.data[iptl];
assert(tag < m_molecule_tag.getNumElements());
unsigned int mol_tag = h_molecule_tag.data[tag];
if (mol_tag == NO_MOLECULE) continue;
auto it = local_molecules_sorted.find(mol_tag);
if (it == local_molecules_sorted.end())
{
auto res = local_molecules_sorted.insert(std::make_pair(mol_tag,std::set<unsigned int>()));
assert(res.second);
it = res.first;
}
it->second.insert(tag);
}
n_local_molecules = local_molecules_sorted.size();
m_exec_conf->msg->notice(7) << "MolecularForceCompute: " << n_local_molecules << " molecules" << std::endl;
m_molecule_length.resize(n_local_molecules);
ArrayHandle<unsigned int> h_molecule_length(m_molecule_length, access_location::host, access_mode::overwrite);
// reset lengths
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
h_molecule_length.data[imol] = 0;
}
// count molecule lengths
unsigned int i = 0;
for (auto it = local_molecules_sorted.begin(); it != local_molecules_sorted.end(); ++it)
{
h_molecule_length.data[i++] = it->second.size();
}
// find maximum length
unsigned nmax = 0;
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
if (h_molecule_length.data[imol] > nmax)
{
nmax = h_molecule_length.data[imol];
}
}
// set up indexer
m_molecule_indexer = Index2D(nmax, n_local_molecules);
// resize molecule list
m_molecule_list.resize(m_molecule_indexer.getNumElements());
// reset lengths again
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
h_molecule_length.data[imol] = 0;
}
// reset molecule order
ArrayHandle<unsigned int> h_molecule_order(m_molecule_order, access_location::host, access_mode::overwrite);
memset(h_molecule_order.data, 0, sizeof(unsigned int)*(m_pdata->getN() + m_pdata->getNGhosts()));
// resize reverse-lookup
m_molecule_idx.resize(nptl_local);
// fill molecule list
ArrayHandle<unsigned int> h_molecule_list(m_molecule_list, access_location::host, access_mode::overwrite);
ArrayHandle<unsigned int> h_molecule_idx(m_molecule_idx, access_location::host, access_mode::overwrite);
ArrayHandle<unsigned int> h_rtag(m_pdata->getRTags(), access_location::host, access_mode::read);
// reset reverse lookup
memset(h_molecule_idx.data, 0, sizeof(unsigned int)*nptl_local);
unsigned int i_mol = 0;
for (auto it_mol = local_molecules_sorted.begin(); it_mol != local_molecules_sorted.end(); ++it_mol)
{
for (std::set<unsigned int>::iterator it_tag = it_mol->second.begin(); it_tag != it_mol->second.end(); ++it_tag)
{
unsigned int n = h_molecule_length.data[i_mol]++;
unsigned int ptl_idx = h_rtag.data[*it_tag];
assert(ptl_idx < m_pdata->getN() + m_pdata->getNGhosts());
h_molecule_list.data[m_molecule_indexer(n, i_mol)] = ptl_idx;
h_molecule_idx.data[ptl_idx] = i_mol;
h_molecule_order.data[ptl_idx] = n;
}
i_mol ++;
}
if (m_prof) m_prof->pop(m_exec_conf);
}
void export_MolecularForceCompute(py::module& m)
{
py::class_< MolecularForceCompute, std::shared_ptr<MolecularForceCompute> >(m, "MolecularForceCompute", py::base<ForceConstraint>())
.def(py::init< std::shared_ptr<SystemDefinition> >())
;
}
<commit_msg>setAccessedBy memory hint on molecule tables<commit_after>// Copyright (c) 2009-2018 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
// Maintainer: jglaser
#include "MolecularForceCompute.h"
#include "hoomd/CachedAllocator.h"
#include "hoomd/Autotuner.h"
#ifdef ENABLE_CUDA
#include "MolecularForceCompute.cuh"
#endif
#include <string.h>
#include <map>
namespace py = pybind11;
/*! \file MolecularForceCompute.cc
\brief Contains code for the MolecularForceCompute class
*/
/*! \param sysdef SystemDefinition containing the ParticleData to compute forces on
*/
MolecularForceCompute::MolecularForceCompute(std::shared_ptr<SystemDefinition> sysdef)
: ForceConstraint(sysdef), m_molecule_tag(m_exec_conf), m_n_molecules_global(0), m_dirty(true),
m_molecule_list(m_exec_conf), m_molecule_length(m_exec_conf), m_molecule_order(m_exec_conf),
m_molecule_idx(m_exec_conf)
{
// connect to the ParticleData to recieve notifications when particles change order in memory
m_pdata->getParticleSortSignal().connect<MolecularForceCompute, &MolecularForceCompute::setDirty>(this);
TAG_ALLOCATION(m_molecule_tag);
TAG_ALLOCATION(m_molecule_list);
TAG_ALLOCATION(m_molecule_length);
TAG_ALLOCATION(m_molecule_order);
TAG_ALLOCATION(m_molecule_idx);
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
// initialize autotuner
std::vector<unsigned int> valid_params;
for (unsigned int block_size = 32; block_size <= 1024; block_size += 32)
valid_params.push_back(block_size);
m_tuner_fill.reset(new Autotuner(valid_params, 5, 100000, "fill_molecule_table", this->m_exec_conf));
}
#endif
}
//! Destructor
MolecularForceCompute::~MolecularForceCompute()
{
m_pdata->getParticleSortSignal().disconnect<MolecularForceCompute, &MolecularForceCompute::setDirty>(this);
}
#ifdef ENABLE_CUDA
void MolecularForceCompute::initMoleculesGPU()
{
if (m_prof) m_prof->push(m_exec_conf,"init molecules");
unsigned int nptl_local = m_pdata->getN() + m_pdata->getNGhosts();
unsigned int n_local_molecules = 0;
// maximum molecule length
unsigned int nmax = 0;
// number of local particles that are part of molecules
unsigned int n_local_ptls_in_molecules = 0;
// resize to maximum possible number of local molecules
m_molecule_length.resize(nptl_local);
m_molecule_idx.resize(nptl_local);
ScopedAllocation<unsigned int> d_idx_sorted_by_tag(m_exec_conf->getCachedAllocator(), nptl_local);
ScopedAllocation<unsigned int> d_local_molecule_tags(m_exec_conf->getCachedAllocator(), nptl_local);
{
ArrayHandle<unsigned int> d_molecule_tag(m_molecule_tag, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_molecule_length(m_molecule_length, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_idx(m_molecule_idx, access_location::device, access_mode::overwrite);
// temporary buffers
ScopedAllocation<unsigned int> d_local_unique_molecule_tags(m_exec_conf->getCachedAllocator(), m_n_molecules_global);
ScopedAllocation<unsigned int> d_sorted_by_tag(m_exec_conf->getCachedAllocator(), nptl_local);
gpu_sort_by_molecule(nptl_local,
d_tag.data,
d_molecule_tag.data,
d_local_molecule_tags.data,
d_local_unique_molecule_tags.data,
d_molecule_idx.data,
d_sorted_by_tag.data,
d_idx_sorted_by_tag.data,
d_molecule_length.data,
n_local_molecules,
nmax,
n_local_ptls_in_molecules,
m_exec_conf->getCachedAllocator());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
}
// set up indexer
m_molecule_indexer = Index2D(nmax, n_local_molecules);
m_exec_conf->msg->notice(7) << "MolecularForceCompute: " << n_local_molecules << " molecules, "
<< n_local_ptls_in_molecules << " particles in molecules " << std::endl;
// resize molecule list
m_molecule_list.resize(m_molecule_indexer.getNumElements());
// resize molecule lookup to size of local particle data
m_molecule_order.resize(m_pdata->getMaxN());
{
// write out molecule list and order
ArrayHandle<unsigned int> d_molecule_list(m_molecule_list, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_order(m_molecule_order, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_idx(m_molecule_idx, access_location::device, access_mode::read);
m_tuner_fill->begin();
unsigned int block_size = m_tuner_fill->getParam();
gpu_fill_molecule_table(nptl_local,
n_local_ptls_in_molecules,
m_molecule_indexer,
d_molecule_idx.data,
d_local_molecule_tags.data,
d_idx_sorted_by_tag.data,
d_molecule_list.data,
d_molecule_order.data,
block_size,
m_exec_conf->getCachedAllocator());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_fill->end();
}
if (m_exec_conf->getNumActiveGPUs() > 1)
{
auto gpu_map = m_exec_conf->getGPUIds();
for (unsigned int idev = 0; idev < m_exec_conf->getNumActiveGPUs(); ++idev)
{
cudaMemAdvise(m_molecule_list.get(), sizeof(unsigned int)*m_molecule_list.getNumElements(), cudaMemAdviseSetAccessedBy, gpu_map[idev]);
cudaMemAdvise(m_molecule_length.get(), sizeof(unsigned int)*m_molecule_length.getNumElements(), cudaMemAdviseSetAccessedBy, gpu_map[idev]);
}
for (unsigned int idev = 0; idev < m_exec_conf->getNumActiveGPUs(); ++idev)
{
auto range = m_pdata->getGPUPartition().getRange(idev);
unsigned int nelem = range.second - range.first;
// skip if no hint set
if (!nelem)
continue;
cudaMemAdvise(m_molecule_idx.get()+range.first, sizeof(unsigned int)*nelem, cudaMemAdviseSetPreferredLocation, gpu_map[idev]);
cudaMemPrefetchAsync(m_molecule_idx.get()+range.first, sizeof(unsigned int)*nelem, gpu_map[idev]);
}
CHECK_CUDA_ERROR();
}
if (m_prof) m_prof->pop(m_exec_conf);
}
#endif
void MolecularForceCompute::initMolecules()
{
// return early if no molecules are defined
if (!m_n_molecules_global) return;
m_exec_conf->msg->notice(7) << "MolecularForceCompute initializing molecule table" << std::endl;
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
initMoleculesGPU();
return;
}
#endif
if (m_prof) m_prof->push("init molecules");
// construct local molecule table
unsigned int nptl_local = m_pdata->getN() + m_pdata->getNGhosts();
ArrayHandle<unsigned int> h_molecule_tag(m_molecule_tag, access_location::host, access_mode::read);
ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read);
std::set<unsigned int> local_molecule_tags;
unsigned int n_local_molecules = 0;
std::vector<unsigned int> local_molecule_idx(nptl_local, NO_MOLECULE);
// resize molecule lookup to size of local particle data
m_molecule_order.resize(m_pdata->getMaxN());
// sort local molecules by molecule tag, and inside the molecule by ptl tag
std::map<unsigned int, std::set<unsigned int> > local_molecules_sorted;
for (unsigned int iptl = 0; iptl < nptl_local; ++iptl)
{
unsigned int tag = h_tag.data[iptl];
assert(tag < m_molecule_tag.getNumElements());
unsigned int mol_tag = h_molecule_tag.data[tag];
if (mol_tag == NO_MOLECULE) continue;
auto it = local_molecules_sorted.find(mol_tag);
if (it == local_molecules_sorted.end())
{
auto res = local_molecules_sorted.insert(std::make_pair(mol_tag,std::set<unsigned int>()));
assert(res.second);
it = res.first;
}
it->second.insert(tag);
}
n_local_molecules = local_molecules_sorted.size();
m_exec_conf->msg->notice(7) << "MolecularForceCompute: " << n_local_molecules << " molecules" << std::endl;
m_molecule_length.resize(n_local_molecules);
ArrayHandle<unsigned int> h_molecule_length(m_molecule_length, access_location::host, access_mode::overwrite);
// reset lengths
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
h_molecule_length.data[imol] = 0;
}
// count molecule lengths
unsigned int i = 0;
for (auto it = local_molecules_sorted.begin(); it != local_molecules_sorted.end(); ++it)
{
h_molecule_length.data[i++] = it->second.size();
}
// find maximum length
unsigned nmax = 0;
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
if (h_molecule_length.data[imol] > nmax)
{
nmax = h_molecule_length.data[imol];
}
}
// set up indexer
m_molecule_indexer = Index2D(nmax, n_local_molecules);
// resize molecule list
m_molecule_list.resize(m_molecule_indexer.getNumElements());
// reset lengths again
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
h_molecule_length.data[imol] = 0;
}
// reset molecule order
ArrayHandle<unsigned int> h_molecule_order(m_molecule_order, access_location::host, access_mode::overwrite);
memset(h_molecule_order.data, 0, sizeof(unsigned int)*(m_pdata->getN() + m_pdata->getNGhosts()));
// resize reverse-lookup
m_molecule_idx.resize(nptl_local);
// fill molecule list
ArrayHandle<unsigned int> h_molecule_list(m_molecule_list, access_location::host, access_mode::overwrite);
ArrayHandle<unsigned int> h_molecule_idx(m_molecule_idx, access_location::host, access_mode::overwrite);
ArrayHandle<unsigned int> h_rtag(m_pdata->getRTags(), access_location::host, access_mode::read);
// reset reverse lookup
memset(h_molecule_idx.data, 0, sizeof(unsigned int)*nptl_local);
unsigned int i_mol = 0;
for (auto it_mol = local_molecules_sorted.begin(); it_mol != local_molecules_sorted.end(); ++it_mol)
{
for (std::set<unsigned int>::iterator it_tag = it_mol->second.begin(); it_tag != it_mol->second.end(); ++it_tag)
{
unsigned int n = h_molecule_length.data[i_mol]++;
unsigned int ptl_idx = h_rtag.data[*it_tag];
assert(ptl_idx < m_pdata->getN() + m_pdata->getNGhosts());
h_molecule_list.data[m_molecule_indexer(n, i_mol)] = ptl_idx;
h_molecule_idx.data[ptl_idx] = i_mol;
h_molecule_order.data[ptl_idx] = n;
}
i_mol ++;
}
if (m_prof) m_prof->pop(m_exec_conf);
}
void export_MolecularForceCompute(py::module& m)
{
py::class_< MolecularForceCompute, std::shared_ptr<MolecularForceCompute> >(m, "MolecularForceCompute", py::base<ForceConstraint>())
.def(py::init< std::shared_ptr<SystemDefinition> >())
;
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2018 gRPC 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 <grpc/support/port_platform.h>
#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
const size_t kBiosDataBufferSize = 256;
static char* trim(const char* src) {
if (src == nullptr || *src == '\0') {
return nullptr;
}
char* des = nullptr;
size_t start = 0, end = strlen(src) - 1;
/* find the last character that is not a whitespace. */
while (end != 0 && isspace(src[end])) {
end--;
}
/* find the first character that is not a whitespace. */
while (start < strlen(src) && isspace(src[start])) {
start++;
}
if (start <= end) {
des = static_cast<char*>(
gpr_zalloc(sizeof(char) * (end - start + 2 /* '\0' */)));
memcpy(des, src + start, end - start + 1);
}
return des;
}
namespace grpc_core {
namespace internal {
char* read_bios_file(const char* bios_file) {
FILE* fp = fopen(bios_file, "r");
if (!fp) {
gpr_log(GPR_ERROR, "BIOS data file cannot be opened.");
return nullptr;
}
char buf[kBiosDataBufferSize + 1];
size_t ret = fread(buf, sizeof(char), kBiosDataBufferSize, fp);
buf[ret] = '\0';
char* trimmed_buf = trim(buf);
fclose(fp);
return trimmed_buf;
}
} // namespace internal
} // namespace grpc_core
<commit_msg>silent log when bios data file does not exist<commit_after>/*
*
* Copyright 2018 gRPC 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 <grpc/support/port_platform.h>
#include "src/core/lib/security/credentials/alts/check_gcp_environment.h"
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
const size_t kBiosDataBufferSize = 256;
static char* trim(const char* src) {
if (src == nullptr || *src == '\0') {
return nullptr;
}
char* des = nullptr;
size_t start = 0, end = strlen(src) - 1;
/* find the last character that is not a whitespace. */
while (end != 0 && isspace(src[end])) {
end--;
}
/* find the first character that is not a whitespace. */
while (start < strlen(src) && isspace(src[start])) {
start++;
}
if (start <= end) {
des = static_cast<char*>(
gpr_zalloc(sizeof(char) * (end - start + 2 /* '\0' */)));
memcpy(des, src + start, end - start + 1);
}
return des;
}
namespace grpc_core {
namespace internal {
char* read_bios_file(const char* bios_file) {
FILE* fp = fopen(bios_file, "r");
if (!fp) {
gpr_log(GPR_INFO, "BIOS data file does not exist or cannot be opened.");
return nullptr;
}
char buf[kBiosDataBufferSize + 1];
size_t ret = fread(buf, sizeof(char), kBiosDataBufferSize, fp);
buf[ret] = '\0';
char* trimmed_buf = trim(buf);
fclose(fp);
return trimmed_buf;
}
} // namespace internal
} // namespace grpc_core
<|endoftext|> |
<commit_before>#include <malloc.h>
#include <cstring>
#include "SystemMessagePacket.h"
#include "Poco/BinaryWriter.h"
#include "Poco/MemoryStream.h"
#include "../data/PSO2String.h"
SystemMessagePacket::SystemMessagePacket(std::string message, uint32_t messageType){
this->message = message;
this->messageType = messageType;
}
SystemMessagePacket::~SystemMessagePacket() {
}
PacketData SystemMessagePacket::build() {
// Convert the sting to a PSO2String.
Polaris::Data::PSO2String theString = Polaris::Data::CreatePSO2String(message, 0xA2, 0x78F7);
PacketHeader header((uint32_t) (sizeof(PacketHeader) + theString.dataLength + sizeof(uint32_t)), 0x19, 0x01, 0x04, 0x00);
PacketData data(header.length);
data.appendData(&header, sizeof(header));
data.appendData(&theString.magicValue, 4);
data.appendData(theString.utf16string.data(), theString.dataLength - 4);
return data;
}
<commit_msg>Insert message type<commit_after>#include <malloc.h>
#include <cstring>
#include "SystemMessagePacket.h"
#include "Poco/BinaryWriter.h"
#include "Poco/MemoryStream.h"
#include "../data/PSO2String.h"
SystemMessagePacket::SystemMessagePacket(std::string message, uint32_t messageType){
this->message = message;
this->messageType = messageType;
}
SystemMessagePacket::~SystemMessagePacket() {
}
PacketData SystemMessagePacket::build() {
// Convert the sting to a PSO2String.
Polaris::Data::PSO2String theString = Polaris::Data::CreatePSO2String(message, 0xA2, 0x78F7);
PacketHeader header((uint32_t) (sizeof(PacketHeader) + theString.dataLength + sizeof(uint32_t)), 0x19, 0x01, 0x04, 0x00);
PacketData data(header.length);
data.appendData(&header, sizeof(header));
data.appendData(&theString.magicValue, 4);
data.appendData(theString.utf16string.data(), theString.dataLength - 4);
data.appendData(&messageType, 4);
return data;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_utils_to_throttle.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_utils_to_throttle.H
/// @brief Sets throttles
/// TMGT will call this procedure to set the N address operations (commands)
/// allowed within a window of M DRAM clocks given the minimum dram data bus utilization.
///
// *HWP HWP Owner: Jacob Harvey <[email protected]>
// *HWP HWP Backup: Brian Silver <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#ifndef __P9_MSS_UTILS_TO_THROTTLE__
#define __P9_MSS_UTILS_TO_THROTTLE__
#include <fapi2.H>
#include <vector>
typedef fapi2::ReturnCode (*p9_mss_utils_to_throttle_FP_t) (const
std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >&);
extern "C"
{
///
/// @brief Set the N throttle attributes for a given dram data bus utilization.
/// @param[in] i_targets vector of MCS on the same VDDR domain
/// @return FAPI2_RC_SUCCESS iff ok
/// @note throttle_per_slot will be equalized so all throttles coming out will be equal to worst case
fapi2::ReturnCode p9_mss_utils_to_throttle( const std::vector <fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_targets );
}
#endif
<commit_msg>Cleaning up and implementing L3 eff_config_thermal<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_utils_to_throttle.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_utils_to_throttle.H
/// @brief Sets throttles
/// TMGT will call this procedure to set the N address operations (commands)
/// allowed within a window of M DRAM clocks given the minimum dram data bus utilization.
///
// *HWP HWP Owner: Jacob Harvey <[email protected]>
// *HWP HWP Backup: Andre A. Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#ifndef __P9_MSS_UTILS_TO_THROTTLE__
#define __P9_MSS_UTILS_TO_THROTTLE__
#include <fapi2.H>
#include <vector>
typedef fapi2::ReturnCode (*p9_mss_utils_to_throttle_FP_t) (const
std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >&);
extern "C"
{
///
/// @brief Sets number commands allowed within a given port databus utilization.
/// @param[in] i_targets vector of MCS to set throttle attributes on
/// @return FAPI2_RC_SUCCESS iff ok
/// @note ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT will be set to worst case of all slots passed in
/// @note output ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_SLOT, ATTR_MSS_MEM_THROTTLED_N_COMMANDS_PER_PORT, and ATTR_MSS_PORT_MAXPOWER
///
fapi2::ReturnCode p9_mss_utils_to_throttle( const std::vector <fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_targets );
}
#endif
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket_attr.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_pm_get_poundv_bucket_attr.C
/// @brief Grab PM data from certain bucket in #V keyword in LRPX record
///
/// *HWP HW Owner : N/A (This is a FW delivered function)
/// *HWP FW Owner : Thi Tran <[email protected]>
/// *HWP Team : PM - Calling this function.
/// *HWP Consumed by : FSP
/// *HWP Level : 3
///
// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_pm_get_poundv_bucket_attr.H>
#include <p9_pm_get_poundv_bucket.H>
#include <mvpd_access_defs.H>
#include <attribute_ids.H>
fapi2::ReturnCode p9_pm_get_poundv_bucket_attr(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
uint8_t* o_data)
{
FAPI_DBG("Entering p9_pm_get_poundv_bucket_attr ....");
uint8_t* l_prDataPtr = NULL;
uint8_t* l_fullVpdData = NULL;
uint8_t l_overridePresent = 0;
uint32_t l_tempVpdSize = 0;
uint32_t l_vpdSize = 0;
uint8_t l_eqChipUnitPos = 0;
uint8_t l_bucketId = 0xFF;
uint8_t l_bucketSize = 0;
uint32_t l_sysNestFreq = 0;
uint32_t l_fallbackNestFreq = 0;
fapi2::voltageBucketData_t* l_currentBucket = NULL;
fapi2::voltageBucketData_t* l_fallbackBucket = NULL;
uint8_t l_numMatches = 0;
uint8_t l_numMatchesFallback = 0;
uint16_t l_pbFreq = 0;
fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;
//To read MVPD we will need the proc parent of the inputted EQ target
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =
i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
//Need to determine which LRP record to read from depending on which
//bucket we are getting the power management data from. FapiPos will
//tell us which LRP record to use.
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,
i_target,
l_eqChipUnitPos));
FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,
fapi2::INVALID_EQ_CHIP_POS().
set_EQ_POSITION( l_eqChipUnitPos ),
"Invalid EQ chip unit position = 0x%X",
l_eqChipUnitPos);
//The enumeration for the LRPx records are just 3 more
//than the EQ chip unit pos. See mvpd_access_defs.H
lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +
fapi2::MVPD_RECORD_LRP0 );
//check if bucket num has been overriden
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,
i_target,
l_overridePresent));
if(l_overridePresent != 0)
{
//If it has been overriden then get the override
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,
i_target,
l_bucketId));
}
else
{
//First read is to get size of vpd record, note the o_buffer is NULL
FAPI_TRY( getMvpdField(lrpRecord,
fapi2::MVPD_KEYWORD_PDV,
l_procParent,
NULL,
l_tempVpdSize) );
//save off the actual vpd size
l_vpdSize = l_tempVpdSize;
//Allocate memory for vpd data
l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));
//Second read is to get data of vpd record
FAPI_TRY( getMvpdField(lrpRecord,
fapi2::MVPD_KEYWORD_PDV,
l_procParent,
l_fullVpdData,
l_tempVpdSize) );
//Version 2:
//#V record is laid out as follows:
//Name: 0x2 byte
//Length: 0x2 byte
//Version: 0x1 byte **buffer starts here
//PNP: 0x3 byte
//bucket a: 0x33 byte
//bucket b: 0x33 byte
//bucket c: 0x33 byte
//bucket d: 0x33 byte
//bucket e: 0x33 byte
//bucket f: 0x33 byte
if( *l_fullVpdData == POUNDV_VERSION_2)
{
//Set the size of the bucket
l_bucketSize = VERSION_2_BUCKET_SIZE;
//Reset VPD size because we want to find size of another VPD record
l_tempVpdSize = 0;
//First read is to get size of vpd record, note the o_buffer is NULL
FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
fapi2::MVPD_KEYWORD_PR,
l_procParent,
NULL,
l_tempVpdSize) );
l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));
//Second read is to get data of vpd record
FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
fapi2::MVPD_KEYWORD_PR,
l_procParent,
l_prDataPtr,
l_tempVpdSize) );
//Bucket ID is byte[4] of the PR keyword
memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));
}
//Version 3:
//#V record is laid out as follows:
//Name: 0x2 byte
//Length: 0x2 byte
//Version: 0x1 byte **buffer starts here
//PNP: 0x3 byte
//bucket a: 0x3D byte
//bucket b: 0x3D byte
//bucket c: 0x3D byte
//bucket d: 0x3D byte
//bucket e: 0x3D byte
//bucket f: 0x3D byte
else if( *l_fullVpdData == POUNDV_VERSION_3 )
{
// Set the size of the bucket
l_bucketSize = VERSION_3_BUCKET_SIZE;
//Save off some FFDC data about the #V data itself
uint16_t l_bucketNestFreqs[NUM_BUCKETS] = { 0, 0, 0, 0, 0, 0 };
// Version 3 uses the nest frequency to choose the bucket Id
// get the system target to find the NEST_FREQ_MHZ
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,
l_sysParent,
l_sysNestFreq));
//cast the voltage data into an array of buckets
fapi2::voltageBucketData_t* l_buckets = reinterpret_cast
<fapi2::voltageBucketData_t*>
(l_fullVpdData + POUNDV_BUCKET_OFFSET);
//see if we have a fall-back frequency to use if we don't
// get a match
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ_POUNDV_FALLBACK,
l_sysParent,
l_fallbackNestFreq));
for(int i = 0; i < NUM_BUCKETS; i++)
{
#ifndef _BIG_ENDIAN
l_pbFreq = ( (((l_buckets[i].pbFreq) >> 8) & 0x00FF) | (((l_buckets[i].pbFreq) << 8) & 0xFF00) );
#else
l_pbFreq = l_buckets[i].pbFreq;
#endif
if(l_pbFreq == l_sysNestFreq)
{
l_numMatches++;
if(l_numMatches > 1)
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::"
" Multiple buckets (%d) reporting the same nest frequency"
" Bucket Nest = %d Bucket ID = %d, First Bucket = %d",
l_numMatches,
l_pbFreq,
(i + 1),
l_currentBucket);
}
else
{
l_currentBucket = &l_buckets[i];
}
}
else if(l_pbFreq == l_fallbackNestFreq)
{
l_numMatchesFallback++;
if(l_numMatchesFallback > 1)
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::"
" Multiple buckets (%d) reporting the same nest frequency"
" Fallback Nest = %d Bucket ID = %d, First Bucket = %d",
l_numMatchesFallback,
l_fallbackNestFreq,
(i + 1),
l_fallbackBucket);
}
else
{
l_fallbackBucket = &l_buckets[i];
}
}
//save FFDC in case we fail
l_bucketNestFreqs[i] = l_pbFreq;
}
if(l_numMatches == 1)
{
l_bucketId = l_currentBucket->bucketId;
}
else if(l_numMatchesFallback == 1)
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid number of matching "
"nest freqs found for PBFreq=%d. Matches found = %d. But "
"did find a fallback match for Freq=%d",
l_sysNestFreq, l_numMatches, l_fallbackNestFreq );
l_bucketId = l_fallbackBucket->bucketId;
}
else
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid number of matching "
"nest freqs found for PBFreq=%d. Matches found = %d",
l_sysNestFreq, l_numMatches );
FAPI_ASSERT(false,
fapi2::INVALID_MATCHING_FREQ_NUMBER().
set_EQ_TARGET(i_target).
set_MATCHES_FOUND(l_numMatches).
set_DESIRED_FREQPB(l_sysNestFreq).
set_LRPREC(lrpRecord).
set_BUCKETA_FREQPB(l_bucketNestFreqs[0]).
set_BUCKETB_FREQPB(l_bucketNestFreqs[1]).
set_BUCKETC_FREQPB(l_bucketNestFreqs[2]).
set_BUCKETD_FREQPB(l_bucketNestFreqs[3]).
set_BUCKETE_FREQPB(l_bucketNestFreqs[4]).
set_BUCKETF_FREQPB(l_bucketNestFreqs[5]),
"Matches found is NOT 1" );
}
}
else
{
FAPI_ASSERT( false,
fapi2::INVALID_POUNDV_VERSION()
.set_EQ_TARGET(i_target)
.set_POUNDV_VERSION(*l_fullVpdData),
"p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x",
*l_fullVpdData);
}
// This assert ensures the size of the calculated data is correct
FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *
l_bucketSize) >= l_bucketSize,
fapi2::BAD_VPD_READ()
.set_EQ_TARGET(i_target)
.set_EXPECTED_SIZE(sizeof(l_bucketSize))
.set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -
((l_bucketId - 1) * l_bucketSize)),
"#V data read was too small!" );
}// else no override
// Ensure we got a valid bucket id
// NOTE: Bucket IDs range from 1-6
FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),
fapi2::INVALID_BUCKET_ID()
.set_EQ_TARGET(i_target)
.set_BUCKET_ID(l_bucketId),
"Invalid Bucket Id = %d",
l_bucketId );
// Use the selected bucket id to populate the output data
memcpy(o_data,
l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,
l_bucketSize);
fapi_try_exit:
if(l_fullVpdData != NULL)
{
free(l_fullVpdData);
l_fullVpdData = NULL;
}
if(l_prDataPtr != NULL)
{
free(l_prDataPtr);
l_prDataPtr = NULL;
}
FAPI_DBG("Exiting p9_pm_get_poundv_bucket_attr ....");
return fapi2::current_err;
}
<commit_msg>Remove distracting error message for fallback #V freq<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_get_poundv_bucket_attr.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_pm_get_poundv_bucket_attr.C
/// @brief Grab PM data from certain bucket in #V keyword in LRPX record
///
/// *HWP HW Owner : N/A (This is a FW delivered function)
/// *HWP FW Owner : Thi Tran <[email protected]>
/// *HWP Team : PM - Calling this function.
/// *HWP Consumed by : FSP
/// *HWP Level : 3
///
// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_pm_get_poundv_bucket_attr.H>
#include <p9_pm_get_poundv_bucket.H>
#include <mvpd_access_defs.H>
#include <attribute_ids.H>
fapi2::ReturnCode p9_pm_get_poundv_bucket_attr(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
uint8_t* o_data)
{
FAPI_DBG("Entering p9_pm_get_poundv_bucket_attr ....");
uint8_t* l_prDataPtr = NULL;
uint8_t* l_fullVpdData = NULL;
uint8_t l_overridePresent = 0;
uint32_t l_tempVpdSize = 0;
uint32_t l_vpdSize = 0;
uint8_t l_eqChipUnitPos = 0;
uint8_t l_bucketId = 0xFF;
uint8_t l_bucketSize = 0;
uint32_t l_sysNestFreq = 0;
uint32_t l_fallbackNestFreq = 0;
fapi2::voltageBucketData_t* l_currentBucket = NULL;
fapi2::voltageBucketData_t* l_fallbackBucket = NULL;
uint8_t l_numMatches = 0;
uint8_t l_numMatchesFallback = 0;
uint16_t l_pbFreq = 0;
fapi2::MvpdRecord lrpRecord = fapi2::MVPD_RECORD_LAST;
//To read MVPD we will need the proc parent of the inputted EQ target
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_procParent =
i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
//Need to determine which LRP record to read from depending on which
//bucket we are getting the power management data from. FapiPos will
//tell us which LRP record to use.
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS,
i_target,
l_eqChipUnitPos));
FAPI_ASSERT( l_eqChipUnitPos < NUM_BUCKETS ,
fapi2::INVALID_EQ_CHIP_POS().
set_EQ_POSITION( l_eqChipUnitPos ),
"Invalid EQ chip unit position = 0x%X",
l_eqChipUnitPos);
//The enumeration for the LRPx records are just 3 more
//than the EQ chip unit pos. See mvpd_access_defs.H
lrpRecord = static_cast<fapi2::MvpdRecord>(l_eqChipUnitPos +
fapi2::MVPD_RECORD_LRP0 );
//check if bucket num has been overriden
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM_OVERRIDE,
i_target,
l_overridePresent));
if(l_overridePresent != 0)
{
//If it has been overriden then get the override
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_POUNDV_BUCKET_NUM,
i_target,
l_bucketId));
}
else
{
//First read is to get size of vpd record, note the o_buffer is NULL
FAPI_TRY( getMvpdField(lrpRecord,
fapi2::MVPD_KEYWORD_PDV,
l_procParent,
NULL,
l_tempVpdSize) );
//save off the actual vpd size
l_vpdSize = l_tempVpdSize;
//Allocate memory for vpd data
l_fullVpdData = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));
//Second read is to get data of vpd record
FAPI_TRY( getMvpdField(lrpRecord,
fapi2::MVPD_KEYWORD_PDV,
l_procParent,
l_fullVpdData,
l_tempVpdSize) );
//Version 2:
//#V record is laid out as follows:
//Name: 0x2 byte
//Length: 0x2 byte
//Version: 0x1 byte **buffer starts here
//PNP: 0x3 byte
//bucket a: 0x33 byte
//bucket b: 0x33 byte
//bucket c: 0x33 byte
//bucket d: 0x33 byte
//bucket e: 0x33 byte
//bucket f: 0x33 byte
if( *l_fullVpdData == POUNDV_VERSION_2)
{
//Set the size of the bucket
l_bucketSize = VERSION_2_BUCKET_SIZE;
//Reset VPD size because we want to find size of another VPD record
l_tempVpdSize = 0;
//First read is to get size of vpd record, note the o_buffer is NULL
FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
fapi2::MVPD_KEYWORD_PR,
l_procParent,
NULL,
l_tempVpdSize) );
l_prDataPtr = reinterpret_cast<uint8_t*>(malloc(l_tempVpdSize));
//Second read is to get data of vpd record
FAPI_TRY( getMvpdField(fapi2::MVPD_RECORD_VINI,
fapi2::MVPD_KEYWORD_PR,
l_procParent,
l_prDataPtr,
l_tempVpdSize) );
//Bucket ID is byte[4] of the PR keyword
memcpy(&l_bucketId, (l_prDataPtr + 4), sizeof(uint8_t));
}
//Version 3:
//#V record is laid out as follows:
//Name: 0x2 byte
//Length: 0x2 byte
//Version: 0x1 byte **buffer starts here
//PNP: 0x3 byte
//bucket a: 0x3D byte
//bucket b: 0x3D byte
//bucket c: 0x3D byte
//bucket d: 0x3D byte
//bucket e: 0x3D byte
//bucket f: 0x3D byte
else if( *l_fullVpdData == POUNDV_VERSION_3 )
{
// Set the size of the bucket
l_bucketSize = VERSION_3_BUCKET_SIZE;
//Save off some FFDC data about the #V data itself
uint16_t l_bucketNestFreqs[NUM_BUCKETS] = { 0, 0, 0, 0, 0, 0 };
// Version 3 uses the nest frequency to choose the bucket Id
// get the system target to find the NEST_FREQ_MHZ
fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sysParent;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ,
l_sysParent,
l_sysNestFreq));
//cast the voltage data into an array of buckets
fapi2::voltageBucketData_t* l_buckets = reinterpret_cast
<fapi2::voltageBucketData_t*>
(l_fullVpdData + POUNDV_BUCKET_OFFSET);
//see if we have a fall-back frequency to use if we don't
// get a match
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ_POUNDV_FALLBACK,
l_sysParent,
l_fallbackNestFreq));
for(int i = 0; i < NUM_BUCKETS; i++)
{
#ifndef _BIG_ENDIAN
l_pbFreq = ( (((l_buckets[i].pbFreq) >> 8) & 0x00FF) | (((l_buckets[i].pbFreq) << 8) & 0xFF00) );
#else
l_pbFreq = l_buckets[i].pbFreq;
#endif
if(l_pbFreq == l_sysNestFreq)
{
l_numMatches++;
if(l_numMatches > 1)
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::"
" Multiple buckets (%d) reporting the same nest frequency"
" Bucket Nest = %d Bucket ID = %d, First Bucket = %d",
l_numMatches,
l_pbFreq,
(i + 1),
l_currentBucket);
}
else
{
l_currentBucket = &l_buckets[i];
}
}
else if( (l_pbFreq == l_fallbackNestFreq)
&& (l_pbFreq != 0) )
{
l_numMatchesFallback++;
if(l_numMatchesFallback > 1)
{
FAPI_INF("p9_pm_get_poundv_bucket_attr::"
" Multiple buckets (%d) reporting the same nest frequency"
" Fallback Nest = %d Bucket ID = %d, First Bucket = %d",
l_numMatchesFallback,
l_fallbackNestFreq,
(i + 1),
l_fallbackBucket);
}
else
{
l_fallbackBucket = &l_buckets[i];
}
}
//save FFDC in case we fail
l_bucketNestFreqs[i] = l_pbFreq;
}
if(l_numMatches == 1)
{
l_bucketId = l_currentBucket->bucketId;
}
else if(l_numMatchesFallback == 1)
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid number of matching "
"nest freqs found for PBFreq=%d. Matches found = %d. But "
"did find a fallback match for Freq=%d",
l_sysNestFreq, l_numMatches, l_fallbackNestFreq );
l_bucketId = l_fallbackBucket->bucketId;
}
else
{
FAPI_ERR("p9_pm_get_poundv_bucket_attr::Invalid number of matching "
"nest freqs found for PBFreq=%d. Matches found = %d",
l_sysNestFreq, l_numMatches );
FAPI_ASSERT(false,
fapi2::INVALID_MATCHING_FREQ_NUMBER().
set_EQ_TARGET(i_target).
set_MATCHES_FOUND(l_numMatches).
set_DESIRED_FREQPB(l_sysNestFreq).
set_LRPREC(lrpRecord).
set_BUCKETA_FREQPB(l_bucketNestFreqs[0]).
set_BUCKETB_FREQPB(l_bucketNestFreqs[1]).
set_BUCKETC_FREQPB(l_bucketNestFreqs[2]).
set_BUCKETD_FREQPB(l_bucketNestFreqs[3]).
set_BUCKETE_FREQPB(l_bucketNestFreqs[4]).
set_BUCKETF_FREQPB(l_bucketNestFreqs[5]),
"Matches found is NOT 1" );
}
}
else
{
FAPI_ASSERT( false,
fapi2::INVALID_POUNDV_VERSION()
.set_EQ_TARGET(i_target)
.set_POUNDV_VERSION(*l_fullVpdData),
"p9_pm_get_poundv_bucket_attr::Invalid #V record version: 0x%x",
*l_fullVpdData);
}
// This assert ensures the size of the calculated data is correct
FAPI_ASSERT(l_vpdSize - POUNDV_BUCKET_OFFSET - ((l_bucketId - 1) *
l_bucketSize) >= l_bucketSize,
fapi2::BAD_VPD_READ()
.set_EQ_TARGET(i_target)
.set_EXPECTED_SIZE(sizeof(l_bucketSize))
.set_ACTUAL_SIZE(l_vpdSize - POUNDV_BUCKET_OFFSET -
((l_bucketId - 1) * l_bucketSize)),
"#V data read was too small!" );
}// else no override
// Ensure we got a valid bucket id
// NOTE: Bucket IDs range from 1-6
FAPI_ASSERT( (l_bucketId <= NUM_BUCKETS) && (l_bucketId != 0),
fapi2::INVALID_BUCKET_ID()
.set_EQ_TARGET(i_target)
.set_BUCKET_ID(l_bucketId),
"Invalid Bucket Id = %d",
l_bucketId );
// Use the selected bucket id to populate the output data
memcpy(o_data,
l_fullVpdData + POUNDV_BUCKET_OFFSET + (l_bucketId - 1) * l_bucketSize,
l_bucketSize);
fapi_try_exit:
if(l_fullVpdData != NULL)
{
free(l_fullVpdData);
l_fullVpdData = NULL;
}
if(l_prDataPtr != NULL)
{
free(l_prDataPtr);
l_prDataPtr = NULL;
}
FAPI_DBG("Exiting p9_pm_get_poundv_bucket_attr ....");
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>#ifndef ATL_GC_GC_HPP
#define ATL_GC_GC_HPP
// @file /home/ryan/programming/atl/gc.hpp
// @author Ryan Domigan <ryan_domigan@[email protected]>
// Created on Jan 08, 2014
//
// A garbage collected environment.
#include <limits>
#include <algorithm>
#include <functional>
#include <list>
#include <memory>
#include <iterator>
#include <boost/mpl/map.hpp>
#include <boost/mpl/lambda.hpp>
#include <boost/mpl/value_type.hpp>
#include "./debug.hpp"
#include "./byte_code.hpp"
#include <gc/ast_pool.hpp>
#include <gc/pool.hpp>
#include <gc/ast_builder.hpp>
#include <gc/marked.hpp>
#include <gc/vm_closure.hpp>
namespace atl
{
/*****************/
/* ____ ____ */
/* / ___|/ ___| */
/* | | _| | */
/* | |_| | |___ */
/* \____|\____| */
/*****************/
struct GC;
namespace gc_detail
{
struct Counter
{
size_t& count;
GC* gc;
Counter(GC *gc_, size_t& count_) : count(count_), gc(gc_) {}
template<class Mem>
void operator()(Mem const&)
{
auto &mem = gc->*Mem::value;
count += mem.num_allocated();
}
};
struct Sweeper
{
GC* gc;
Sweeper(GC *gc_) : gc(gc_) {}
template<class Mem>
void operator()(Mem const&)
{
auto &mem = gc->*Mem::value;
mem.sweep();
}
};
// Class needs to implement MarkBase to get marked by the GC
template<class GC>
struct MarkBase;
// Manage the lifespan of the GC's reference to a MarkBase
// instance.
template<class GC>
struct ManageMarking
{
MarkBase<GC>* container;
GC* gc;
typename GC::MarkBaseList::iterator itr;
ManageMarking(GC* gc_, MarkBase<GC>* container_)
: container(container_),
gc(gc_)
{ itr = gc->add_mark_base(container); }
void drop()
{
if(gc) { gc->remove_mark_base(itr); }
}
void take(ManageMarking&& other, MarkBase<GC>* container_)
{
container = container_;
gc = other.gc;
itr = other.itr;
*itr = container;
other.gc = nullptr;
}
ManageMarking(ManageMarking&& other, MarkBase<GC>* container_)
{ take(std::move(other), container_); }
ManageMarking()=delete;
ManageMarking(ManageMarking const&)=delete;
ManageMarking(ManageMarking&&)=delete;
~ManageMarking()
{ drop(); }
};
template<class GC>
struct MarkBase
{
ManageMarking<GC> manage_marking;
MarkBase(GC& gc)
: manage_marking(&gc, this)
{}
MarkBase(MarkBase const& other)
: manage_marking(other.manage_marking.gc, this)
{}
MarkBase(MarkBase&& other)
: manage_marking(std::move(other.manage_marking), this)
{}
MarkBase& operator=(MarkBase&& other)
{
manage_marking.drop();
manage_marking.take(std::move(other.manage_marking), this);
return *this;
}
virtual void mark()=0;
};
}
struct GC
{
typedef ::atl::gc_detail::MarkBase<GC> MarkBase;
typedef std::function<void (GC&)> MarkCallback;
typedef std::list<MarkCallback> RootsType;
typedef std::list<MarkBase*> MarkBaseList;
typedef ::atl::AstPool<GC> AstPool;
typedef ::atl::ast_builder::AstBuilder<AstPool> AstBuilder;
typedef std::function<void (AstBuilder&)> ast_composer;
RootsType _roots;
MarkBaseList _mark_bases;
Marked<Any> *_cxx_stack;
// Adds callbacks which will be invoked during the mark phase of the GC.
// @param fn: the callback
RootsType::iterator add_marker(MarkCallback const& fn)
{
_roots.push_front(fn);
return _roots.begin();
}
void remove_marker(RootsType::iterator itr) { _roots.erase(itr); }
MarkBaseList::iterator add_mark_base(MarkBase* item)
{
_mark_bases.push_front(item);
return _mark_bases.begin();
}
void remove_mark_base(MarkBaseList::iterator itr) { _mark_bases.erase(itr); }
AstPool _ast_pool;
ClosurePool _closure_pool;
memory_pool::Pool< LambdaMetadata > _lambda_metadata_heap;
memory_pool::Pool< String > _string_heap;
memory_pool::Pool< CxxFunctor > _primitive_recursive_heap;
memory_pool::Pool< Symbol > _symbol_heap;
memory_pool::Pool< Scheme > _scheme_heap;
bool _gc_in_progress;
template< class T, memory_pool::Pool<T> GC::*member >
struct MemberPtr {
typedef memory_pool::Pool<T> GC::* PoolType;
/* man this would be easier with inline definitions. */
const static PoolType value;
};
typedef mpl::map< mpl::pair< LambdaMetadata , MemberPtr<LambdaMetadata, &GC::_lambda_metadata_heap > >
, mpl::pair< String , MemberPtr<String, &GC::_string_heap > >
, mpl::pair< CxxFunctor,
MemberPtr<CxxFunctor, &GC::_primitive_recursive_heap > >
, mpl::pair< Symbol, MemberPtr<Symbol, &GC::_symbol_heap > >
, mpl::pair< Scheme, MemberPtr<Scheme, &GC::_scheme_heap > >
> PoolMap;
template<class T>
T* alloc_from(memory_pool::Pool<T> &pool)
{
auto result = pool.alloc();
if(result == nullptr) {
gc();
result = pool.alloc();
if(result == nullptr)
{ throw std::string("out of memory"); }
}
return result;
}
GC() : _cxx_stack(nullptr), _ast_pool(*this), _gc_in_progress(false) {}
// Mark everything the GC knows about. This method was broken
// out for testing; use the 'gc()' method.
void _mark()
{
_ast_pool.gc_start();
_ast_pool.mark();
for(auto& i : _roots) { i(*this); }
for(auto& i : _mark_bases) { i->mark(); }
auto marked = _cxx_stack;
while(marked)
{
mark(marked->any);
marked = marked->_up;
}
}
// Sweep marked objects. This method was broken out for
// testing; use the gc() method.
void _sweep()
{
auto sweeper = gc_detail::Sweeper(this);
mpl::for_each
<PoolMap,
typename mpl::lambda< mpl::value_type<PoolMap, mpl::_1 > >::type
>(sweeper);
_ast_pool.gc_finish();
}
void gc()
{
assert(!_gc_in_progress);
_gc_in_progress = true;
_mark();
_sweep();
_gc_in_progress = false;
}
void mark(String& str)
{ _string_heap.mark(&str); }
void mark(CxxFunctor& functor)
{
_primitive_recursive_heap.mark(&functor);
mark(functor.type);
}
void mark(Scheme& scheme)
{
_scheme_heap.mark(&scheme);
mark(scheme.type);
}
void mark(Symbol& sym)
{
_symbol_heap.mark(&sym);
mark(sym.value);
// The Scheme is on the Symbol, not the Scheme heap, so
// just check its type part.
mark(sym.scheme.type);
}
void mark(LambdaMetadata& metadata)
{
_lambda_metadata_heap.mark(&metadata);
if(metadata.has_closure_values)
{ mark(metadata.closure_values); }
for(auto sym : metadata.closure)
{ mark(*sym); }
mark(metadata.formals);
mark(metadata.return_type);
}
void mark(Ast& ast)
{ ast = _ast_pool.move(ast); }
void mark(Any& aa)
{
switch(aa._tag)
{
case tag<Lambda>::value:
if(aa.value) { mark(*unwrap<Lambda>(aa).value); }
break;
case tag<LambdaMetadata>::value:
mark(unwrap<LambdaMetadata>(aa));
break;
case tag<String>::value:
mark(unwrap<String>(aa));
break;
case tag<CxxFunctor>::value:
mark(unwrap<CxxFunctor>(aa));
break;
case tag<Symbol>::value:
mark(unwrap<Symbol>(aa));
break;
case tag<Scheme>::value:
mark(unwrap<Scheme>(aa));
break;
case tag<Ast>::value:
mark(unwrap<Ast>(aa));
break;
default:
break;
}
}
/*****************************/
/** __ __ _ **/
/** | \/ | __ _| | _____ **/
/** | |\/| |/ _` | |/ / _ \ **/
/** | | | | (_| | < __/ **/
/** |_| |_|\__,_|_|\_\___| **/
/*****************************/
template<class T>
T* alloc()
{
static_assert( mpl::has_key<PoolMap, T>::value,
"GC::Type does not have corrosponding pool." );
return alloc_from( (this->*mpl::at<PoolMap,T>::type::value) );
}
template<class Type, class ... Types>
Type* raw_make(Types ... args)
{ return new (alloc<Type>()) Type (args...); }
template<class Type, class ... Types>
Any amake(Types ... args)
{ return Any(tag<Type>::value , raw_make<Type>(args...)); }
// Unpacks any of the `args` which are of Marked type before
// passing them to the constructor
template<class Type, class ... Types>
Marked<Type> make(Types ... args)
{
return Marked<Type>(_cxx_stack,
Any(tag<Type>::value,
raw_make<Type>(unpack_marked(args)...)));
}
template<class T>
Marked<T> marked(T& thing)
{ return Marked<T>(_cxx_stack, thing); }
Marked<Ast> marked(Ast thing)
{ return Marked<Ast>(_cxx_stack, wrap(thing)); }
Marked<Any> marked(Any thing)
{ return Marked<Any>(_cxx_stack, thing); }
AstBuilder ast_builder()
{ return AstBuilder(_ast_pool, _ast_pool.ast_backer()); }
AstBuilder ast_builder(size_t nn)
{ return AstBuilder(_ast_pool, _ast_pool.ast_backer(nn)); }
Ast raw_ast(ast_composer const& func)
{
auto ast = ast_builder();
func(ast);
return ast.root();
}
Marked<Ast> operator()(ast_composer const& func)
{
auto ast = ast_builder();
func(ast);
return Marked<Ast>(_cxx_stack, wrap(ast.root()));
}
size_t cells_allocated()
{
size_t count = 0;
auto counter = gc_detail::Counter(this, count);
mpl::for_each
<PoolMap,
typename mpl::lambda< mpl::value_type<PoolMap, mpl::_1 > >::type
>(counter);
return count + _ast_pool.size();
}
pcode::value_type* closure(pcode::value_type body_location,
size_t formals,
size_t captures)
{ return _closure_pool.closure(body_location, formals, captures); }
};
template< class T, memory_pool::Pool<T> GC::*member >
const typename GC::MemberPtr<T,member>::PoolType GC::MemberPtr<T,member>::value = member;
typedef GC::AstBuilder AstBuilder;
typedef ast_builder::NestAst<AstBuilder> NestAst;
typedef GC::ast_composer ast_composer;
typedef GC::MarkBase MarkBase;
}
#endif
<commit_msg>gc: Keep a compile-time set of the types which require marking<commit_after>#ifndef ATL_GC_GC_HPP
#define ATL_GC_GC_HPP
// @file /home/ryan/programming/atl/gc.hpp
// @author Ryan Domigan <ryan_domigan@[email protected]>
// Created on Jan 08, 2014
//
// A garbage collected environment.
#include <limits>
#include <algorithm>
#include <functional>
#include <list>
#include <memory>
#include <iterator>
#include <boost/mpl/map.hpp>
#include <boost/mpl/set.hpp>
#include <boost/mpl/lambda.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/value_type.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/insert.hpp>
#include <boost/mpl/apply.hpp>
#include "./debug.hpp"
#include "./byte_code.hpp"
#include <gc/ast_pool.hpp>
#include <gc/pool.hpp>
#include <gc/ast_builder.hpp>
#include <gc/marked.hpp>
#include <gc/vm_closure.hpp>
namespace atl
{
/*****************/
/* ____ ____ */
/* / ___|/ ___| */
/* | | _| | */
/* | |_| | |___ */
/* \____|\____| */
/*****************/
struct GC;
namespace gc_detail
{
struct Counter
{
size_t& count;
GC* gc;
Counter(GC *gc_, size_t& count_) : count(count_), gc(gc_) {}
template<class Mem>
void operator()(Mem const&)
{
auto &mem = gc->*Mem::value;
count += mem.num_allocated();
}
};
struct Sweeper
{
GC* gc;
Sweeper(GC *gc_) : gc(gc_) {}
template<class Mem>
void operator()(Mem const&)
{
auto &mem = gc->*Mem::value;
mem.sweep();
}
};
// Class needs to implement MarkBase to get marked by the GC
template<class GC>
struct MarkBase;
// Manage the lifespan of the GC's reference to a MarkBase
// instance.
template<class GC>
struct ManageMarking
{
MarkBase<GC>* container;
GC* gc;
typename GC::MarkBaseList::iterator itr;
ManageMarking(GC* gc_, MarkBase<GC>* container_)
: container(container_),
gc(gc_)
{ itr = gc->add_mark_base(container); }
void drop()
{
if(gc) { gc->remove_mark_base(itr); }
}
void take(ManageMarking&& other, MarkBase<GC>* container_)
{
container = container_;
gc = other.gc;
itr = other.itr;
*itr = container;
other.gc = nullptr;
}
ManageMarking(ManageMarking&& other, MarkBase<GC>* container_)
{ take(std::move(other), container_); }
ManageMarking()=delete;
ManageMarking(ManageMarking const&)=delete;
ManageMarking(ManageMarking&&)=delete;
~ManageMarking()
{ drop(); }
};
template<class GC>
struct MarkBase
{
ManageMarking<GC> manage_marking;
MarkBase(GC& gc)
: manage_marking(&gc, this)
{}
MarkBase(MarkBase const& other)
: manage_marking(other.manage_marking.gc, this)
{}
MarkBase(MarkBase&& other)
: manage_marking(std::move(other.manage_marking), this)
{}
MarkBase& operator=(MarkBase&& other)
{
manage_marking.drop();
manage_marking.take(std::move(other.manage_marking), this);
return *this;
}
virtual void mark()=0;
};
}
namespace pl = ::boost::mpl::placeholders;
struct GC
{
typedef ::atl::gc_detail::MarkBase<GC> MarkBase;
typedef std::function<void (GC&)> MarkCallback;
typedef std::list<MarkCallback> RootsType;
typedef std::list<MarkBase*> MarkBaseList;
typedef ::atl::AstPool<GC> AstPool;
typedef ::atl::ast_builder::AstBuilder<AstPool> AstBuilder;
typedef std::function<void (AstBuilder&)> ast_composer;
RootsType _roots;
MarkBaseList _mark_bases;
Marked<Any> *_cxx_stack;
// Adds callbacks which will be invoked during the mark phase of the GC.
// @param fn: the callback
RootsType::iterator add_marker(MarkCallback const& fn)
{
_roots.push_front(fn);
return _roots.begin();
}
void remove_marker(RootsType::iterator itr) { _roots.erase(itr); }
MarkBaseList::iterator add_mark_base(MarkBase* item)
{
_mark_bases.push_front(item);
return _mark_bases.begin();
}
void remove_mark_base(MarkBaseList::iterator itr) { _mark_bases.erase(itr); }
AstPool _ast_pool;
ClosurePool _closure_pool;
memory_pool::Pool< LambdaMetadata > _lambda_metadata_heap;
memory_pool::Pool< String > _string_heap;
memory_pool::Pool< CxxFunctor > _primitive_recursive_heap;
memory_pool::Pool< Symbol > _symbol_heap;
memory_pool::Pool< Scheme > _scheme_heap;
bool _gc_in_progress;
template< class T, memory_pool::Pool<T> GC::*member >
struct MemberPtr {
typedef memory_pool::Pool<T> GC::* PoolType;
/* man this would be easier with inline definitions. */
const static PoolType value;
};
typedef mpl::map< mpl::pair< LambdaMetadata , MemberPtr<LambdaMetadata, &GC::_lambda_metadata_heap > >
, mpl::pair< String , MemberPtr<String, &GC::_string_heap > >
, mpl::pair< CxxFunctor,
MemberPtr<CxxFunctor, &GC::_primitive_recursive_heap > >
, mpl::pair< Symbol, MemberPtr<Symbol, &GC::_symbol_heap > >
, mpl::pair< Scheme, MemberPtr<Scheme, &GC::_scheme_heap > >
> PoolMap;
typedef typename mpl::fold<PoolMap,
mpl::set<>,
mpl::lambda< mpl::insert<pl::_1, mpl::first<pl::_2> > >
>::type BasicPoolTypes;
typedef typename tmpl::Apply<mpl::insert,
mpl::insert<BasicPoolTypes, Ast>,
tmpl::Identity<Any> >::type MarkableTypes;
template<class T>
T* alloc_from(memory_pool::Pool<T> &pool)
{
auto result = pool.alloc();
if(result == nullptr) {
gc();
result = pool.alloc();
if(result == nullptr)
{ throw std::string("out of memory"); }
}
return result;
}
GC() : _cxx_stack(nullptr), _ast_pool(*this), _gc_in_progress(false) {}
// Mark everything the GC knows about. This method was broken
// out for testing; use the 'gc()' method.
void _mark()
{
_ast_pool.gc_start();
_ast_pool.mark();
for(auto& i : _roots) { i(*this); }
for(auto& i : _mark_bases) { i->mark(); }
auto marked = _cxx_stack;
while(marked)
{
mark(marked->any);
marked = marked->_up;
}
}
// Sweep marked objects. This method was broken out for
// testing; use the gc() method.
void _sweep()
{
auto sweeper = gc_detail::Sweeper(this);
mpl::for_each
<PoolMap,
typename mpl::lambda< mpl::value_type<PoolMap, mpl::_1 > >::type
>(sweeper);
_ast_pool.gc_finish();
}
void gc()
{
assert(!_gc_in_progress);
_gc_in_progress = true;
_mark();
_sweep();
_gc_in_progress = false;
}
void mark(String& str)
{ _string_heap.mark(&str); }
void mark(CxxFunctor& functor)
{
_primitive_recursive_heap.mark(&functor);
mark(functor.type);
}
void mark(Scheme& scheme)
{
_scheme_heap.mark(&scheme);
mark(scheme.type);
}
void mark(Symbol& sym)
{
_symbol_heap.mark(&sym);
mark(sym.value);
// The Scheme is on the Symbol, not the Scheme heap, so
// just check its type part.
mark(sym.scheme.type);
}
void mark(LambdaMetadata& metadata)
{
_lambda_metadata_heap.mark(&metadata);
if(metadata.has_closure_values)
{ mark(metadata.closure_values); }
for(auto sym : metadata.closure)
{ mark(*sym); }
mark(metadata.formals);
mark(metadata.return_type);
}
void mark(Ast& ast)
{ ast = _ast_pool.move(ast); }
void mark(Any& aa)
{
switch(aa._tag)
{
case tag<Lambda>::value:
if(aa.value) { mark(*unwrap<Lambda>(aa).value); }
break;
case tag<LambdaMetadata>::value:
mark(unwrap<LambdaMetadata>(aa));
break;
case tag<String>::value:
mark(unwrap<String>(aa));
break;
case tag<CxxFunctor>::value:
mark(unwrap<CxxFunctor>(aa));
break;
case tag<Symbol>::value:
mark(unwrap<Symbol>(aa));
break;
case tag<Scheme>::value:
mark(unwrap<Scheme>(aa));
break;
case tag<Ast>::value:
mark(unwrap<Ast>(aa));
break;
default:
break;
}
}
/*****************************/
/** __ __ _ **/
/** | \/ | __ _| | _____ **/
/** | |\/| |/ _` | |/ / _ \ **/
/** | | | | (_| | < __/ **/
/** |_| |_|\__,_|_|\_\___| **/
/*****************************/
template<class T>
T* alloc()
{
static_assert( mpl::has_key<PoolMap, T>::value,
"GC::Type does not have corrosponding pool." );
return alloc_from( (this->*mpl::at<PoolMap,T>::type::value) );
}
template<class Type, class ... Types>
Type* raw_make(Types ... args)
{ return new (alloc<Type>()) Type (args...); }
template<class Type, class ... Types>
Any amake(Types ... args)
{ return Any(tag<Type>::value , raw_make<Type>(args...)); }
// Unpacks any of the `args` which are of Marked type before
// passing them to the constructor
template<class Type, class ... Types>
Marked<Type> make(Types ... args)
{
return Marked<Type>(_cxx_stack,
Any(tag<Type>::value,
raw_make<Type>(unpack_marked(args)...)));
}
template<class T>
Marked<T> marked(T& thing)
{ return Marked<T>(_cxx_stack, thing); }
Marked<Ast> marked(Ast thing)
{ return Marked<Ast>(_cxx_stack, wrap(thing)); }
Marked<Any> marked(Any thing)
{ return Marked<Any>(_cxx_stack, thing); }
AstBuilder ast_builder()
{ return AstBuilder(_ast_pool, _ast_pool.ast_backer()); }
AstBuilder ast_builder(size_t nn)
{ return AstBuilder(_ast_pool, _ast_pool.ast_backer(nn)); }
Ast raw_ast(ast_composer const& func)
{
auto ast = ast_builder();
func(ast);
return ast.root();
}
Marked<Ast> operator()(ast_composer const& func)
{
auto ast = ast_builder();
func(ast);
return Marked<Ast>(_cxx_stack, wrap(ast.root()));
}
size_t cells_allocated()
{
size_t count = 0;
auto counter = gc_detail::Counter(this, count);
mpl::for_each
<PoolMap,
typename mpl::lambda< mpl::value_type<PoolMap, mpl::_1 > >::type
>(counter);
return count + _ast_pool.size();
}
pcode::value_type* closure(pcode::value_type body_location,
size_t formals,
size_t captures)
{ return _closure_pool.closure(body_location, formals, captures); }
};
template< class T, memory_pool::Pool<T> GC::*member >
const typename GC::MemberPtr<T,member>::PoolType GC::MemberPtr<T,member>::value = member;
typedef GC::AstBuilder AstBuilder;
typedef ast_builder::NestAst<AstBuilder> NestAst;
typedef GC::ast_composer ast_composer;
typedef GC::MarkBase MarkBase;
}
#endif
<|endoftext|> |
<commit_before>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2009-2012 Yuvraaj Kelkar
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 Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: [email protected]
*/
#include "QGVConnection.h"
#include "gen/connection_adapter.h"
#include "QGVTextChannel.h"
QGVConnection::QGVConnection(const QString &u, const QString &p,
QObject *parent /*= NULL*/)
: QObject(parent)
, m_user(u)
, m_pass(p)
, m_hasImmortalHandle(false)
, m_channelNumber(0)
, m_connStatus(QGVConnection::Disconnected)
{
Q_DEBUG("Here");
}//QGVConnection::QGVConnection
QGVConnection::~QGVConnection()
{
Q_DEBUG("Here");
}//QGVConnection::~QGVConnection
void
QGVConnection::AddClientInterest(const QStringList & /*Tokens*/)
{
Q_DEBUG("Not implemented");
}//QGVConnection::AddClientInterest
void
QGVConnection::Connect()
{
if (m_connStatus != QGVConnection::Connected) {
m_connStatus = QGVConnection::Connected;
emit StatusChanged (m_connStatus, QGVConnection::Requested);
Q_DEBUG(QString("Connect requested for user %1").arg(m_user));
} else {
Q_WARN(QString("Duplicate connect for user %1").arg(m_user));
}
}//QGVConnection::Connect
void
QGVConnection::Disconnect()
{
if (m_connStatus != QGVConnection::Disconnected) {
m_connStatus = QGVConnection::Disconnected;
emit StatusChanged (m_connStatus, QGVConnection::Requested);
Q_DEBUG(QString("Disconnect requested for user %1").arg(m_user));
} else {
Q_WARN(QString("Duplicate disconnect for user %1").arg(m_user));
}
}//QGVConnection::Disconnect
QStringList
QGVConnection::GetInterfaces()
{
QStringList rv;
rv << ofdT_Conn_Iface_Requests;
Q_DEBUG(QString("Returning interfaces: [%1]").arg(rv.join (", ")));
return rv;
}//QGVConnection::GetInterfaces
QString
QGVConnection::GetProtocol()
{
Q_DEBUG("Requested protocol");
return QGV_ProtocolName;
}//QGVConnection::GetProtocol
uint
QGVConnection::GetSelfHandle()
{
if (m_connStatus != QGVConnection::Connected) {
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
Q_WARN("Not connected");
} else {
Q_DEBUG(QString("Returning self handle %1").arg(m_selfHandle));
}
return m_selfHandle;
}//QGVConnection::GetSelfHandle
uint
QGVConnection::GetStatus()
{
Q_DEBUG(QString("Returning connection status %1").arg(m_connStatus));
return m_connStatus;
}//QGVConnection::GetStatus
void
QGVConnection::HoldHandles(uint /*Handle_Type*/, const Qt_Type_au & /*Handles*/)
{
if (m_connStatus != QGVConnection::Connected) {
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
Q_WARN("Not connected");
return;
}
// There's nothing really to "hold"
Q_DEBUG("Not implemented");
}//QGVConnection::HoldHandles
QStringList
QGVConnection::InspectHandles(uint /*Handle_Type*/, const Qt_Type_au & /*Handles*/)
{
QStringList rv;
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("Inspect handles. I don't really know what to do here.");
} while (0);
return rv;
}//QGVConnection::InspectHandles
Qt_Type_a_osuu
QGVConnection::ListChannels()
{
Qt_Type_a_osuu rv;
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("No channels to list.");
} while (0);
return rv;
}//QGVConnection::ListChannels
void
QGVConnection::ReleaseHandles(uint /*Handle_Type*/, const Qt_Type_au & /*Handles*/)
{
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("Release handles. I don't really know what to do here.");
} while (0);
}//QGVConnection::ReleaseHandles
void
QGVConnection::RemoveClientInterest(const QStringList & /*Tokens*/)
{
Q_DEBUG("Not implemented");
}//QGVConnection::RemoveClientInterest
QDBusObjectPath
QGVConnection::RequestChannel(const QString & /*Type*/, uint /*Handle_Type*/,
uint /*Handle*/, bool /*Suppress_Handler*/)
{
QDBusObjectPath rv;
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("Request channel. I don't really know what to do here.");
sendErrorReply (ofdT_Err_NotImplemented, "Don't know how");
} while (0);
return rv;
}//QGVConnection::RequestChannel
Qt_Type_au
QGVConnection::RequestHandles(uint /*Handle_Type*/,
const QStringList & /*Identifiers*/)
{
Qt_Type_au rv;
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("Request handles. I don't really know what to do here.");
sendErrorReply (ofdT_Err_NotImplemented, "Don't know how");
} while (0);
return rv;
}//QGVConnection::RequestHandles
void
QGVConnection::setSelfHandle(uint h)
{
Q_DEBUG("Here");
m_selfHandle = h;
}//QGVConnection::SetSelfHandle
int
QGVConnection::getSelfHandle()
{
Q_DEBUG("Here");
return m_selfHandle;
}//QGVConnection::getSelfHandle
QString
QGVConnection::getDBusObjectPath()
{
return m_dbusObjectPath;
}//QGVConnection::getDBusObjectPath
QString
QGVConnection::getDBusBusName()
{
return m_dbusBusName;
}//QGVConnection::getDBusBusName
bool
QGVConnection::registerObject()
{
ConnectionAdaptor *ca = new ConnectionAdaptor(this);
if (NULL == ca) {
Q_WARN("Failed to create connection adapter object");
return false;
}
RequestsAdaptor *ra = new RequestsAdaptor(this);
if (NULL == ra) {
Q_WARN("Failed to create connection adapter object");
delete ca;
return false;
}
bool connObjReg = false, connSrvReg = false;
QString noAmpUser = m_user;
noAmpUser.replace('@', '_');
noAmpUser.replace('.', '_');
m_dbusObjectPath = QGV_CONN_OP + noAmpUser;
m_dbusBusName = QGV_CONN_SP "." + noAmpUser;
QDBusConnection sessionBus = QDBusConnection::sessionBus();
bool rv = false;
do { // Begin cleanup block (not a loop)
rv = sessionBus.registerObject(m_dbusObjectPath, this);
if (!rv) {
Q_WARN(QString("Couldn't register Connection object for user %1")
.arg(m_user));
break;
}
connObjReg = true;
rv = sessionBus.registerService (m_dbusBusName);
if (!rv) {
Q_WARN(QString("Couldn't register Connection bus for user %1")
.arg(m_user));
break;
}
connSrvReg = true;
Q_DEBUG(QString("Connection registered for user %1").arg(m_user));
} while (0); // End cleanup block (not a loop)
if (!rv) {
if (connObjReg) {
sessionBus.unregisterObject(m_dbusObjectPath);
}
if (connSrvReg) {
sessionBus.unregisterService (m_dbusBusName);
}
m_dbusObjectPath.clear ();
m_dbusBusName.clear ();
}
return rv;
}//QGVConnection::registerObject
void
QGVConnection::unregisterObject()
{
QDBusConnection sessionBus = QDBusConnection::sessionBus();
sessionBus.unregisterObject (m_dbusObjectPath);
sessionBus.unregisterService (m_dbusBusName);
}//QGVConnection::unregisterObject
bool
QGVConnection::hasImmortalHandles() const
{
Q_DEBUG("Here");
return m_hasImmortalHandle;
}//QGVConnection::hasImmortalHandles
bool
QGVConnection::processChannel(const QVariantMap &request,
QDBusObjectPath &objPath)
{
QVariant val;
if (!request.contains (ofdT_Channel_TargetID)) {
sendErrorReply (ofdT_Err_InvalidArgument,
"Target ID not present in request");
Q_WARN("Target ID not present in request");
return false;
}
val = request[ofdT_Channel_TargetID];
QString strNum = val.toString ();
if ((!val.isValid ()) || (strNum.isEmpty ())) {
sendErrorReply (ofdT_Err_InvalidArgument,
"Target ID in request is not valid");
Q_WARN("Target ID in request is not valid");
return false;
}
if (!request.contains (ofdT_Channel_ChannelType)) {
sendErrorReply (ofdT_Err_InvalidArgument,
"Channel type not present in request");
Q_WARN("Target ID not present in request");
return false;
}
val = request[ofdT_Channel_ChannelType];
QString strType = val.toString ();
if ((!val.isValid ()) || (strType.isEmpty ())) {
sendErrorReply (ofdT_Err_InvalidArgument,
"Channel type in request is not valid");
Q_WARN("Target ID in request is not valid");
return false;
}
QStringList keys = request.keys ();
foreach (QString key, keys) {
Q_DEBUG(QString("[%1] = %2").arg(key, request[key].toString()));
}
bool success = false;
if (strType == ofdT_ChannelType_StreamedMedia) {
Q_DEBUG(QString("Call to %1").arg(strNum));
QDBusInterface iface("org.QGVDial.APIServer", "/org/QGVDial/CallServer",
"", QDBusConnection::sessionBus());
if (!iface.isValid()) {
sendErrorReply(ofdT_Err_NetworkError,
"qgvtp - QGVDial call interface is not ready");
Q_WARN("QGVDial call interface is not ready");
return false;
}
iface.call("Call", strNum);
Q_DEBUG("Call started successfully");
sendErrorReply (ofdT_Err_NetworkError, "Channel created successfully");
success = true;
} else if (strType == ofdT_ChannelType_Text) {
Q_DEBUG(QString("Text to %1.").arg(strNum));
QString objName = m_dbusObjectPath
+ QString("/%1").arg(++m_channelNumber);
QGVTextChannel *textChan = new QGVTextChannel(objName, strNum, this);
bool rv = textChan->registerObject ();
if (rv) {
objPath.setPath (objName);
connect(textChan,
SIGNAL(pingNewChannel(QDBusObjectPath,QString,uint,uint,bool)),
this,
SLOT(onNewChannel(QDBusObjectPath,QString,uint,uint,bool)));
Q_DEBUG("Text channel created.");
success = true;
} else {
delete textChan;
Q_WARN("Failed to create text channel");
success = false;
}
/*
QDBusInterface iface("org.QGVDial.APIServer", "/org/QGVDial/TextServer",
"", QDBusConnection::sessionBus());
if (!iface.isValid()) {
sendErrorReply(ofdT_Err_NotAvailable,
"qgvtp - QGVDial text interface is not ready");
Q_WARN("QGVDial text interface is not ready");
return false;
}
QStringList listNumbers;
listNumbers += strNum;
iface.call("TextWithoutData", listNumbers);
Q_DEBUG("Text initiated successfully");
sendErrorReply (ofdT_Err_NetworkError, "Channel created successfully");
success = true;
*/
} else {
sendErrorReply (ofdT_Err_UnsupportedMedia,
"Channel type in request is not valid");
Q_WARN(QString("Unsupported channel type %1").arg(strType));
return false;
}
return success;
}//QGVConnection::processChannel
void
QGVConnection::onNewChannel(const QDBusObjectPath &Object_Path,
const QString &Channel_Type, uint Handle_Type,
uint Handle, bool Suppress_Handler)
{
Qt_Type_a_o_dict_sv chanInfoList;
Struct_o_dict_sv chanInfo;
Q_DEBUG("Time for a new channel");
chanInfo.o = Object_Path;
chanInfo.vmap[ofdT_Channel_ChannelType] = Channel_Type;
chanInfo.vmap[ofdT_Channel_TargetHandleType] = Handle_Type;
chanInfo.vmap[ofdT_Channel_TargetHandle] = Handle;
chanInfo.vmap[ofdT_Channel_TargetID] = "";
chanInfo.vmap[ofdT_Channel_Requested] = Suppress_Handler;
chanInfoList << chanInfo;
emit NewChannels (chanInfoList);
emit NewChannel (Object_Path, Channel_Type, Handle_Type, Handle,
Suppress_Handler);
}//QGVConnection::onNewChannel
QDBusObjectPath
QGVConnection::CreateChannel(const QVariantMap &Request, // IN
QVariantMap & /*Properties*/) // OUT
{
Q_DEBUG("Here");
QDBusObjectPath objPath;
bool success = processChannel (Request, objPath);
return objPath;
}//QGVConnection::CreateChannel
bool
QGVConnection::EnsureChannel(const QVariantMap &Request, // IN
QDBusObjectPath & Channel, // OUT
QVariantMap & /*Properties*/) // OUT
{
Q_DEBUG("Here");
QDBusObjectPath objPath;
bool success = processChannel (Request, objPath);
if (success) {
Channel = objPath;
}
return success;
}//QGVConnection::EnsureChannel
Qt_Type_a_o_dict_sv
QGVConnection::channels() const
{
Qt_Type_a_o_dict_sv rv;
// Always return an empty channels list
Q_DEBUG("Returning empty channels list");
return rv;
}//QGVConnection::channels
Qt_Type_a_dict_sv_as
QGVConnection::requestableChannelClasses() const
{
Q_DEBUG("Here");
uint hType(1); // Handle type : Contact
Struct_dict_sv_as r1, r2;
r1.sv.insert (ofdT_Channel_TargetHandleType, hType);
r1.sv.insert (ofdT_Channel_ChannelType, ofdT_ChannelType_StreamedMedia);
r1.as.append (ofdT_Channel_TargetHandle);
r1.as.append (ofdT_StreamedMedia_InitialAudio);
r2.sv.insert (ofdT_Channel_TargetHandleType, hType);
r2.sv.insert (ofdT_Channel_ChannelType, ofdT_ChannelType_Text);
r2.as.append (ofdT_Channel_TargetHandle);
Qt_Type_a_dict_sv_as rv;
rv.append (r1);
rv.append (r2);
return rv;
}//QGVConnection::requestableChannelClasses
<commit_msg>maybe the immortal handles had something to do with it<commit_after>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2009-2012 Yuvraaj Kelkar
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 Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: [email protected]
*/
#include "QGVConnection.h"
#include "gen/connection_adapter.h"
#include "QGVTextChannel.h"
QGVConnection::QGVConnection(const QString &u, const QString &p,
QObject *parent /*= NULL*/)
: QObject(parent)
, m_user(u)
, m_pass(p)
, m_hasImmortalHandle(true)
, m_channelNumber(0)
, m_connStatus(QGVConnection::Disconnected)
{
Q_DEBUG("Here");
}//QGVConnection::QGVConnection
QGVConnection::~QGVConnection()
{
Q_DEBUG("Here");
}//QGVConnection::~QGVConnection
bool
QGVConnection::registerObject()
{
ConnectionAdaptor *ca = new ConnectionAdaptor(this);
if (NULL == ca) {
Q_WARN("Failed to create connection adapter object");
return false;
}
RequestsAdaptor *ra = new RequestsAdaptor(this);
if (NULL == ra) {
Q_WARN("Failed to create connection adapter object");
delete ca;
return false;
}
bool connObjReg = false, connSrvReg = false;
QString noAmpUser = m_user;
noAmpUser.replace('@', '_');
noAmpUser.replace('.', '_');
m_dbusObjectPath = QGV_CONN_OP + noAmpUser;
m_dbusBusName = QGV_CONN_SP "." + noAmpUser;
QDBusConnection sessionBus = QDBusConnection::sessionBus();
bool rv = false;
do { // Begin cleanup block (not a loop)
rv = sessionBus.registerObject(m_dbusObjectPath, this);
if (!rv) {
Q_WARN(QString("Couldn't register Connection object for user %1")
.arg(m_user));
break;
}
connObjReg = true;
rv = sessionBus.registerService (m_dbusBusName);
if (!rv) {
Q_WARN(QString("Couldn't register Connection bus for user %1")
.arg(m_user));
break;
}
connSrvReg = true;
Q_DEBUG(QString("Connection registered for user %1").arg(m_user));
} while (0); // End cleanup block (not a loop)
if (!rv) {
if (connObjReg) {
sessionBus.unregisterObject(m_dbusObjectPath);
}
if (connSrvReg) {
sessionBus.unregisterService (m_dbusBusName);
}
m_dbusObjectPath.clear ();
m_dbusBusName.clear ();
}
return rv;
}//QGVConnection::registerObject
void
QGVConnection::unregisterObject()
{
QDBusConnection sessionBus = QDBusConnection::sessionBus();
sessionBus.unregisterObject (m_dbusObjectPath);
sessionBus.unregisterService (m_dbusBusName);
}//QGVConnection::unregisterObject
void
QGVConnection::AddClientInterest(const QStringList & /*Tokens*/)
{
Q_DEBUG("Not implemented");
}//QGVConnection::AddClientInterest
void
QGVConnection::Connect()
{
if (m_connStatus != QGVConnection::Connected) {
m_connStatus = QGVConnection::Connected;
emit StatusChanged (m_connStatus, QGVConnection::Requested);
Q_DEBUG(QString("Connect requested for user %1").arg(m_user));
} else {
Q_WARN(QString("Duplicate connect for user %1").arg(m_user));
}
}//QGVConnection::Connect
void
QGVConnection::Disconnect()
{
if (m_connStatus != QGVConnection::Disconnected) {
m_connStatus = QGVConnection::Disconnected;
emit StatusChanged (m_connStatus, QGVConnection::Requested);
Q_DEBUG(QString("Disconnect requested for user %1").arg(m_user));
} else {
Q_WARN(QString("Duplicate disconnect for user %1").arg(m_user));
}
}//QGVConnection::Disconnect
QStringList
QGVConnection::GetInterfaces()
{
QStringList rv;
rv << ofdT_Conn_Iface_Requests;
Q_DEBUG(QString("Returning interfaces: [%1]").arg(rv.join (", ")));
return rv;
}//QGVConnection::GetInterfaces
QString
QGVConnection::GetProtocol()
{
Q_DEBUG("Requested protocol");
return QGV_ProtocolName;
}//QGVConnection::GetProtocol
uint
QGVConnection::GetSelfHandle()
{
if (m_connStatus != QGVConnection::Connected) {
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
Q_WARN("Not connected");
} else {
Q_DEBUG(QString("Returning self handle %1").arg(m_selfHandle));
}
return m_selfHandle;
}//QGVConnection::GetSelfHandle
uint
QGVConnection::GetStatus()
{
Q_DEBUG(QString("Returning connection status %1").arg(m_connStatus));
return m_connStatus;
}//QGVConnection::GetStatus
void
QGVConnection::HoldHandles(uint /*Handle_Type*/, const Qt_Type_au & /*Handles*/)
{
if (m_connStatus != QGVConnection::Connected) {
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
Q_WARN("Not connected");
return;
}
// There's nothing really to "hold"
Q_DEBUG("Not implemented");
}//QGVConnection::HoldHandles
QStringList
QGVConnection::InspectHandles(uint /*Handle_Type*/, const Qt_Type_au & /*Handles*/)
{
QStringList rv;
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("Inspect handles. I don't really know what to do here.");
} while (0);
return rv;
}//QGVConnection::InspectHandles
Qt_Type_a_osuu
QGVConnection::ListChannels()
{
Qt_Type_a_osuu rv;
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("No channels to list.");
} while (0);
return rv;
}//QGVConnection::ListChannels
void
QGVConnection::ReleaseHandles(uint /*Handle_Type*/, const Qt_Type_au & /*Handles*/)
{
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("Release handles. I don't really know what to do here.");
} while (0);
}//QGVConnection::ReleaseHandles
void
QGVConnection::RemoveClientInterest(const QStringList & /*Tokens*/)
{
Q_DEBUG("Not implemented");
}//QGVConnection::RemoveClientInterest
QDBusObjectPath
QGVConnection::RequestChannel(const QString & /*Type*/, uint /*Handle_Type*/,
uint /*Handle*/, bool /*Suppress_Handler*/)
{
QDBusObjectPath rv;
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("Request channel. I don't really know what to do here.");
sendErrorReply (ofdT_Err_NotImplemented, "Don't know how");
} while (0);
return rv;
}//QGVConnection::RequestChannel
Qt_Type_au
QGVConnection::RequestHandles(uint /*Handle_Type*/,
const QStringList & /*Identifiers*/)
{
Qt_Type_au rv;
do {
if (m_connStatus != QGVConnection::Connected) {
Q_WARN("Not connected");
sendErrorReply (ofdT_Err_Disconnected,
"Connection object not connected");
break;
}
Q_DEBUG("Request handles. I don't really know what to do here.");
sendErrorReply (ofdT_Err_NotImplemented, "Don't know how");
} while (0);
return rv;
}//QGVConnection::RequestHandles
void
QGVConnection::setSelfHandle(uint h)
{
Q_DEBUG("Here");
m_selfHandle = h;
}//QGVConnection::SetSelfHandle
int
QGVConnection::getSelfHandle()
{
Q_DEBUG("Here");
return m_selfHandle;
}//QGVConnection::getSelfHandle
QString
QGVConnection::getDBusObjectPath()
{
return m_dbusObjectPath;
}//QGVConnection::getDBusObjectPath
QString
QGVConnection::getDBusBusName()
{
return m_dbusBusName;
}//QGVConnection::getDBusBusName
bool
QGVConnection::hasImmortalHandles() const
{
Q_DEBUG("Here");
return m_hasImmortalHandle;
}//QGVConnection::hasImmortalHandles
bool
QGVConnection::processChannel(const QVariantMap &request,
QDBusObjectPath &objPath)
{
QVariant val;
if (!request.contains (ofdT_Channel_TargetID)) {
sendErrorReply (ofdT_Err_InvalidArgument,
"Target ID not present in request");
Q_WARN("Target ID not present in request");
return false;
}
val = request[ofdT_Channel_TargetID];
QString strNum = val.toString ();
if ((!val.isValid ()) || (strNum.isEmpty ())) {
sendErrorReply (ofdT_Err_InvalidArgument,
"Target ID in request is not valid");
Q_WARN("Target ID in request is not valid");
return false;
}
if (!request.contains (ofdT_Channel_ChannelType)) {
sendErrorReply (ofdT_Err_InvalidArgument,
"Channel type not present in request");
Q_WARN("Target ID not present in request");
return false;
}
val = request[ofdT_Channel_ChannelType];
QString strType = val.toString ();
if ((!val.isValid ()) || (strType.isEmpty ())) {
sendErrorReply (ofdT_Err_InvalidArgument,
"Channel type in request is not valid");
Q_WARN("Target ID in request is not valid");
return false;
}
QStringList keys = request.keys ();
foreach (QString key, keys) {
Q_DEBUG(QString("[%1] = %2").arg(key, request[key].toString()));
}
bool success = false;
if (strType == ofdT_ChannelType_StreamedMedia) {
Q_DEBUG(QString("Call to %1").arg(strNum));
QDBusInterface iface("org.QGVDial.APIServer", "/org/QGVDial/CallServer",
"", QDBusConnection::sessionBus());
if (!iface.isValid()) {
sendErrorReply(ofdT_Err_NetworkError,
"qgvtp - QGVDial call interface is not ready");
Q_WARN("QGVDial call interface is not ready");
return false;
}
iface.call("Call", strNum);
Q_DEBUG("Call started successfully");
sendErrorReply (ofdT_Err_NetworkError, "Channel created successfully");
success = true;
} else if (strType == ofdT_ChannelType_Text) {
Q_DEBUG(QString("Text to %1.").arg(strNum));
QString objName = m_dbusObjectPath
+ QString("/%1").arg(++m_channelNumber);
QGVTextChannel *textChan = new QGVTextChannel(objName, strNum, this);
bool rv = textChan->registerObject ();
if (rv) {
objPath.setPath (objName);
connect(textChan,
SIGNAL(pingNewChannel(QDBusObjectPath,QString,uint,uint,bool)),
this,
SLOT(onNewChannel(QDBusObjectPath,QString,uint,uint,bool)));
Q_DEBUG("Text channel created.");
success = true;
} else {
delete textChan;
Q_WARN("Failed to create text channel");
success = false;
}
/*
QDBusInterface iface("org.QGVDial.APIServer", "/org/QGVDial/TextServer",
"", QDBusConnection::sessionBus());
if (!iface.isValid()) {
sendErrorReply(ofdT_Err_NotAvailable,
"qgvtp - QGVDial text interface is not ready");
Q_WARN("QGVDial text interface is not ready");
return false;
}
QStringList listNumbers;
listNumbers += strNum;
iface.call("TextWithoutData", listNumbers);
Q_DEBUG("Text initiated successfully");
sendErrorReply (ofdT_Err_NetworkError, "Channel created successfully");
success = true;
*/
} else {
sendErrorReply (ofdT_Err_UnsupportedMedia,
"Channel type in request is not valid");
Q_WARN(QString("Unsupported channel type %1").arg(strType));
return false;
}
return success;
}//QGVConnection::processChannel
void
QGVConnection::onNewChannel(const QDBusObjectPath &Object_Path,
const QString &Channel_Type, uint Handle_Type,
uint Handle, bool Suppress_Handler)
{
Qt_Type_a_o_dict_sv chanInfoList;
Struct_o_dict_sv chanInfo;
Q_DEBUG("Time for a new channel");
chanInfo.o = Object_Path;
chanInfo.vmap[ofdT_Channel_ChannelType] = Channel_Type;
chanInfo.vmap[ofdT_Channel_TargetHandleType] = Handle_Type;
chanInfo.vmap[ofdT_Channel_TargetHandle] = Handle;
chanInfo.vmap[ofdT_Channel_TargetID] = "";
chanInfo.vmap[ofdT_Channel_Requested] = Suppress_Handler;
chanInfoList << chanInfo;
emit NewChannels (chanInfoList);
emit NewChannel (Object_Path, Channel_Type, Handle_Type, Handle,
Suppress_Handler);
}//QGVConnection::onNewChannel
QDBusObjectPath
QGVConnection::CreateChannel(const QVariantMap &Request, // IN
QVariantMap & /*Properties*/) // OUT
{
Q_DEBUG("Here");
QDBusObjectPath objPath;
bool success = processChannel (Request, objPath);
return objPath;
}//QGVConnection::CreateChannel
bool
QGVConnection::EnsureChannel(const QVariantMap &Request, // IN
QDBusObjectPath & Channel, // OUT
QVariantMap & /*Properties*/) // OUT
{
Q_DEBUG("Here");
QDBusObjectPath objPath;
bool success = processChannel (Request, objPath);
if (success) {
Channel = objPath;
}
return success;
}//QGVConnection::EnsureChannel
Qt_Type_a_o_dict_sv
QGVConnection::channels() const
{
Qt_Type_a_o_dict_sv rv;
// Always return an empty channels list
Q_DEBUG("Returning empty channels list");
return rv;
}//QGVConnection::channels
Qt_Type_a_dict_sv_as
QGVConnection::requestableChannelClasses() const
{
Q_DEBUG("Here");
uint hType(1); // Handle type : Contact
Struct_dict_sv_as r1, r2;
r1.sv.insert (ofdT_Channel_TargetHandleType, hType);
r1.sv.insert (ofdT_Channel_ChannelType, ofdT_ChannelType_StreamedMedia);
r1.as.append (ofdT_Channel_TargetHandle);
r1.as.append (ofdT_StreamedMedia_InitialAudio);
r2.sv.insert (ofdT_Channel_TargetHandleType, hType);
r2.sv.insert (ofdT_Channel_ChannelType, ofdT_ChannelType_Text);
r2.as.append (ofdT_Channel_TargetHandle);
Qt_Type_a_dict_sv_as rv;
rv.append (r1);
rv.append (r2);
return rv;
}//QGVConnection::requestableChannelClasses
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlencryption_nssimpl.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 17:35:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SAL_CONFIG_H_
#include <sal/config.h>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _XMLENCRYPTION_NSSIMPL_HXX_
#include "xmlencryption_nssimpl.hxx"
#endif
#ifndef _XMLDOCUMENTWRAPPER_XMLSECIMPL_HXX_
#include "xmldocumentwrapper_xmlsecimpl.hxx"
#endif
#ifndef _XMLELEMENTWRAPPER_XMLSECIMPL_HXX_
#include "xmlelementwrapper_xmlsecimpl.hxx"
#endif
#ifndef _SECURITYENVIRONMENT_NSSIMPL_HXX_
#include "securityenvironment_nssimpl.hxx"
#endif
#ifndef _ERRORCALLBACK_XMLSECIMPL_HXX_
#include "errorcallback.hxx"
#endif
#include "xmlsec/xmlsec.h"
#include "xmlsec/xmltree.h"
#include "xmlsec/xmlenc.h"
#include "xmlsec/crypto.h"
#ifdef UNX
#define stricmp strcasecmp
#endif
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using ::com::sun::star::lang::XMultiServiceFactory ;
using ::com::sun::star::lang::XSingleServiceFactory ;
using ::rtl::OUString ;
using ::com::sun::star::xml::wrapper::XXMLElementWrapper ;
using ::com::sun::star::xml::wrapper::XXMLDocumentWrapper ;
using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
using ::com::sun::star::xml::crypto::XXMLEncryption ;
using ::com::sun::star::xml::crypto::XXMLEncryptionTemplate ;
using ::com::sun::star::xml::crypto::XXMLSecurityContext ;
using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
using ::com::sun::star::xml::crypto::XMLEncryptionException ;
XMLEncryption_NssImpl :: XMLEncryption_NssImpl( const Reference< XMultiServiceFactory >& aFactory ) : m_xServiceManager( aFactory ) {
}
XMLEncryption_NssImpl :: ~XMLEncryption_NssImpl() {
}
/* XXMLEncryption */
Reference< XXMLEncryptionTemplate >
SAL_CALL XMLEncryption_NssImpl :: encrypt(
const Reference< XXMLEncryptionTemplate >& aTemplate ,
const Reference< XSecurityEnvironment >& aEnvironment
) throw( com::sun::star::xml::crypto::XMLEncryptionException,
com::sun::star::uno::SecurityException )
{
xmlSecKeysMngrPtr pMngr = NULL ;
xmlSecEncCtxPtr pEncCtx = NULL ;
xmlNodePtr pEncryptedData = NULL ;
xmlNodePtr pEncryptedKey = NULL ;
xmlNodePtr pContent = NULL ;
if( !aTemplate.is() )
throw RuntimeException() ;
if( !aEnvironment.is() )
throw RuntimeException() ;
//Get Keys Manager
Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ;
if( !xSecTunnel.is() ) {
throw RuntimeException() ;
}
#if 0
XMLSecurityContext_NssImpl* pSecCtxt = ( XMLSecurityContext_NssImpl* )xSecTunnel->getSomething( XMLSecurityContext_NssImpl::getUnoTunnelId() ) ;
if( pSecCtxt == NULL )
throw RuntimeException() ;
#endif
SecurityEnvironment_NssImpl* pSecEnv = ( SecurityEnvironment_NssImpl* )xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ) ;
if( pSecEnv == NULL )
throw RuntimeException() ;
//Get the encryption template
Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ;
if( !xTemplate.is() ) {
throw RuntimeException() ;
}
Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ;
if( !xTplTunnel.is() ) {
throw RuntimeException() ;
}
XMLElementWrapper_XmlSecImpl* pTemplate = ( XMLElementWrapper_XmlSecImpl* )xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ;
if( pTemplate == NULL ) {
throw RuntimeException() ;
}
//MM : Get the element to be encrypted
Reference< XXMLElementWrapper > xTarget = aTemplate->getTarget() ;
if( !xTarget.is() ) {
throw XMLEncryptionException() ;
}
Reference< XUnoTunnel > xTgtTunnel( xTarget , UNO_QUERY ) ;
if( !xTgtTunnel.is() ) {
throw XMLEncryptionException() ;
}
XMLElementWrapper_XmlSecImpl* pTarget = ( XMLElementWrapper_XmlSecImpl* )xTgtTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ;
if( pTarget == NULL ) {
throw RuntimeException() ;
}
pContent = pTarget->getNativeElement() ;
//MM : end
if( pContent == NULL ) {
throw XMLEncryptionException() ;
}
/* MM : remove the following 2 lines
xmlUnlinkNode(pContent);
xmlAddNextSibling(pEncryptedData, pContent);
*/
//remember the position of the element to be signed
sal_Bool isParentRef = sal_True;
xmlNodePtr pParent = pEncryptedData->parent;
xmlNodePtr referenceNode;
if (pEncryptedData == pParent->children)
{
referenceNode = pParent;
}
else
{
referenceNode = pEncryptedData->prev;
isParentRef = sal_False;
}
setErrorRecorder( aTemplate );
pMngr = pSecEnv->createKeysManager() ; //i39448
if( !pMngr ) {
throw RuntimeException() ;
}
//Create Encryption context
pEncCtx = xmlSecEncCtxCreate( pMngr ) ;
if( pEncCtx == NULL )
{
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//throw XMLEncryptionException() ;
clearErrorRecorder();
return aTemplate;
}
pEncryptedData = pTemplate->getNativeElement() ;
//Find the element to be encrypted.
/* MM : remove the old method to get the target element
//This element is wrapped in the CipherValue sub-element.
xmlNodePtr pCipherData = pEncryptedData->children;
while (pCipherData != NULL && stricmp((const char *)(pCipherData->name), "CipherData"))
{
pCipherData = pCipherData->next;
}
if( pCipherData == NULL ) {
xmlSecEncCtxDestroy( pEncCtx ) ;
throw XMLEncryptionException() ;
}
xmlNodePtr pCipherValue = pCipherData->children;
while (pCipherValue != NULL && stricmp((const char *)(pCipherValue->name), "CipherValue"))
{
pCipherValue = pCipherValue->next;
}
if( pCipherValue == NULL ) {
xmlSecEncCtxDestroy( pEncCtx ) ;
throw XMLEncryptionException() ;
}
pContent = pCipherValue->children;
*/
//Encrypt the template
if( xmlSecEncCtxXmlEncrypt( pEncCtx , pEncryptedData , pContent ) < 0 )
{
xmlSecEncCtxDestroy( pEncCtx ) ;
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//throw XMLEncryptionException() ;
clearErrorRecorder();
return aTemplate;
}
xmlSecEncCtxDestroy( pEncCtx ) ;
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//get the new EncryptedData element
if (isParentRef)
{
pTemplate->setNativeElement(referenceNode->children) ;
}
else
{
pTemplate->setNativeElement(referenceNode->next);
}
return aTemplate ;
}
/* XXMLEncryption */
Reference< XXMLEncryptionTemplate >
SAL_CALL XMLEncryption_NssImpl :: decrypt(
const Reference< XXMLEncryptionTemplate >& aTemplate ,
const Reference< XXMLSecurityContext >& aSecurityCtx
) throw( com::sun::star::xml::crypto::XMLEncryptionException ,
com::sun::star::uno::SecurityException) {
xmlSecKeysMngrPtr pMngr = NULL ;
xmlSecEncCtxPtr pEncCtx = NULL ;
xmlNodePtr pEncryptedData = NULL ;
xmlNodePtr pContent = NULL ;
if( !aTemplate.is() )
throw RuntimeException() ;
if( !aSecurityCtx.is() )
throw RuntimeException() ;
//Get the encryption template
Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ;
if( !xTemplate.is() ) {
throw RuntimeException() ;
}
Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ;
if( !xTplTunnel.is() ) {
throw RuntimeException() ;
}
XMLElementWrapper_XmlSecImpl* pTemplate = ( XMLElementWrapper_XmlSecImpl* )xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ;
if( pTemplate == NULL ) {
throw RuntimeException() ;
}
pEncryptedData = pTemplate->getNativeElement() ;
//remember the position of the element to be signed
sal_Bool isParentRef = sal_True;
xmlNodePtr pParent = pEncryptedData->parent;
xmlNodePtr referenceNode;
if (pEncryptedData == pParent->children)
{
referenceNode = pParent;
}
else
{
referenceNode = pEncryptedData->prev;
isParentRef = sal_False;
}
setErrorRecorder( aTemplate );
sal_Int32 nSecurityEnvironment = aSecurityCtx->getSecurityEnvironmentNumber();
sal_Int32 i;
for (i=0; i<nSecurityEnvironment; ++i)
{
Reference< XSecurityEnvironment > aEnvironment = aSecurityCtx->getSecurityEnvironmentByIndex(i);
//Get Keys Manager
Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ;
if( !aEnvironment.is() ) {
throw RuntimeException() ;
}
SecurityEnvironment_NssImpl* pSecEnv = ( SecurityEnvironment_NssImpl* )xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ) ;
if( pSecEnv == NULL )
throw RuntimeException() ;
pMngr = pSecEnv->createKeysManager() ; //i39448
if( !pMngr ) {
throw RuntimeException() ;
}
//Create Encryption context
pEncCtx = xmlSecEncCtxCreate( pMngr ) ;
if( pEncCtx == NULL )
{
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//throw XMLEncryptionException() ;
clearErrorRecorder();
return aTemplate;
}
//Decrypt the template
if(!( xmlSecEncCtxDecrypt( pEncCtx , pEncryptedData ) < 0 || pEncCtx->result == NULL ))
{
//The decryption succeeds
//Destroy the encryption context
xmlSecEncCtxDestroy( pEncCtx ) ;
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//get the decrypted element
XMLElementWrapper_XmlSecImpl * ret = new XMLElementWrapper_XmlSecImpl(isParentRef?
(referenceNode->children):(referenceNode->next));
//return ret;
aTemplate->setTemplate(ret);
break;
}
else
{
//The decryption fails, continue with the next security environment
xmlSecEncCtxDestroy( pEncCtx ) ;
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
}
}
clearErrorRecorder();
return aTemplate;
}
/* XInitialization */
void SAL_CALL XMLEncryption_NssImpl :: initialize( const Sequence< Any >& aArguments ) throw( Exception, RuntimeException ) {
// TBD
} ;
/* XServiceInfo */
OUString SAL_CALL XMLEncryption_NssImpl :: getImplementationName() throw( RuntimeException ) {
return impl_getImplementationName() ;
}
/* XServiceInfo */
sal_Bool SAL_CALL XMLEncryption_NssImpl :: supportsService( const OUString& serviceName) throw( RuntimeException ) {
Sequence< OUString > seqServiceNames = getSupportedServiceNames() ;
const OUString* pArray = seqServiceNames.getConstArray() ;
for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) {
if( *( pArray + i ) == serviceName )
return sal_True ;
}
return sal_False ;
}
/* XServiceInfo */
Sequence< OUString > SAL_CALL XMLEncryption_NssImpl :: getSupportedServiceNames() throw( RuntimeException ) {
return impl_getSupportedServiceNames() ;
}
//Helper for XServiceInfo
Sequence< OUString > XMLEncryption_NssImpl :: impl_getSupportedServiceNames() {
::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
Sequence< OUString > seqServiceNames( 1 ) ;
seqServiceNames.getArray()[0] = OUString::createFromAscii( "com.sun.star.xml.crypto.XMLEncryption" ) ;
return seqServiceNames ;
}
OUString XMLEncryption_NssImpl :: impl_getImplementationName() throw( RuntimeException ) {
return OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.XMLEncryption_NssImpl" ) ;
}
//Helper for registry
Reference< XInterface > SAL_CALL XMLEncryption_NssImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) throw( RuntimeException ) {
return Reference< XInterface >( *new XMLEncryption_NssImpl( aServiceManager ) ) ;
}
Reference< XSingleServiceFactory > XMLEncryption_NssImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) {
//Reference< XSingleServiceFactory > xFactory ;
//xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
//return xFactory ;
return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ;
}
<commit_msg>INTEGRATION: CWS xmlsec13 (1.4.28); FILE MERGED 2005/10/31 13:43:22 jl 1.4.28.2: RESYNC: (1.4-1.5); FILE MERGED 2005/10/25 10:59:33 jl 1.4.28.1: #i54495 errorhandling for verification and signing fixed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlencryption_nssimpl.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-11-11 09:21:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SAL_CONFIG_H_
#include <sal/config.h>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _XMLENCRYPTION_NSSIMPL_HXX_
#include "xmlencryption_nssimpl.hxx"
#endif
#ifndef _XMLDOCUMENTWRAPPER_XMLSECIMPL_HXX_
#include "xmldocumentwrapper_xmlsecimpl.hxx"
#endif
#ifndef _XMLELEMENTWRAPPER_XMLSECIMPL_HXX_
#include "xmlelementwrapper_xmlsecimpl.hxx"
#endif
#ifndef _SECURITYENVIRONMENT_NSSIMPL_HXX_
#include "securityenvironment_nssimpl.hxx"
#endif
#ifndef _ERRORCALLBACK_XMLSECIMPL_HXX_
#include "errorcallback.hxx"
#endif
#include "xmlsec/xmlsec.h"
#include "xmlsec/xmltree.h"
#include "xmlsec/xmlenc.h"
#include "xmlsec/crypto.h"
#ifdef UNX
#define stricmp strcasecmp
#endif
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using ::com::sun::star::lang::XMultiServiceFactory ;
using ::com::sun::star::lang::XSingleServiceFactory ;
using ::rtl::OUString ;
using ::com::sun::star::xml::wrapper::XXMLElementWrapper ;
using ::com::sun::star::xml::wrapper::XXMLDocumentWrapper ;
using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
using ::com::sun::star::xml::crypto::XXMLEncryption ;
using ::com::sun::star::xml::crypto::XXMLEncryptionTemplate ;
using ::com::sun::star::xml::crypto::XXMLSecurityContext ;
using ::com::sun::star::xml::crypto::XSecurityEnvironment ;
using ::com::sun::star::xml::crypto::XMLEncryptionException ;
XMLEncryption_NssImpl :: XMLEncryption_NssImpl( const Reference< XMultiServiceFactory >& aFactory ) : m_xServiceManager( aFactory ) {
}
XMLEncryption_NssImpl :: ~XMLEncryption_NssImpl() {
}
/* XXMLEncryption */
Reference< XXMLEncryptionTemplate >
SAL_CALL XMLEncryption_NssImpl :: encrypt(
const Reference< XXMLEncryptionTemplate >& aTemplate ,
const Reference< XSecurityEnvironment >& aEnvironment
) throw( com::sun::star::xml::crypto::XMLEncryptionException,
com::sun::star::uno::SecurityException )
{
xmlSecKeysMngrPtr pMngr = NULL ;
xmlSecEncCtxPtr pEncCtx = NULL ;
xmlNodePtr pEncryptedData = NULL ;
xmlNodePtr pEncryptedKey = NULL ;
xmlNodePtr pContent = NULL ;
if( !aTemplate.is() )
throw RuntimeException() ;
if( !aEnvironment.is() )
throw RuntimeException() ;
//Get Keys Manager
Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ;
if( !xSecTunnel.is() ) {
throw RuntimeException() ;
}
#if 0
XMLSecurityContext_NssImpl* pSecCtxt = ( XMLSecurityContext_NssImpl* )xSecTunnel->getSomething( XMLSecurityContext_NssImpl::getUnoTunnelId() ) ;
if( pSecCtxt == NULL )
throw RuntimeException() ;
#endif
SecurityEnvironment_NssImpl* pSecEnv = ( SecurityEnvironment_NssImpl* )xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ) ;
if( pSecEnv == NULL )
throw RuntimeException() ;
//Get the encryption template
Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ;
if( !xTemplate.is() ) {
throw RuntimeException() ;
}
Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ;
if( !xTplTunnel.is() ) {
throw RuntimeException() ;
}
XMLElementWrapper_XmlSecImpl* pTemplate = ( XMLElementWrapper_XmlSecImpl* )xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ;
if( pTemplate == NULL ) {
throw RuntimeException() ;
}
//MM : Get the element to be encrypted
Reference< XXMLElementWrapper > xTarget = aTemplate->getTarget() ;
if( !xTarget.is() ) {
throw XMLEncryptionException() ;
}
Reference< XUnoTunnel > xTgtTunnel( xTarget , UNO_QUERY ) ;
if( !xTgtTunnel.is() ) {
throw XMLEncryptionException() ;
}
XMLElementWrapper_XmlSecImpl* pTarget = ( XMLElementWrapper_XmlSecImpl* )xTgtTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ;
if( pTarget == NULL ) {
throw RuntimeException() ;
}
pContent = pTarget->getNativeElement() ;
//MM : end
if( pContent == NULL ) {
throw XMLEncryptionException() ;
}
/* MM : remove the following 2 lines
xmlUnlinkNode(pContent);
xmlAddNextSibling(pEncryptedData, pContent);
*/
//remember the position of the element to be signed
sal_Bool isParentRef = sal_True;
xmlNodePtr pParent = pEncryptedData->parent;
xmlNodePtr referenceNode;
if (pEncryptedData == pParent->children)
{
referenceNode = pParent;
}
else
{
referenceNode = pEncryptedData->prev;
isParentRef = sal_False;
}
setErrorRecorder( );
pMngr = pSecEnv->createKeysManager() ; //i39448
if( !pMngr ) {
throw RuntimeException() ;
}
//Create Encryption context
pEncCtx = xmlSecEncCtxCreate( pMngr ) ;
if( pEncCtx == NULL )
{
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//throw XMLEncryptionException() ;
clearErrorRecorder();
return aTemplate;
}
pEncryptedData = pTemplate->getNativeElement() ;
//Find the element to be encrypted.
/* MM : remove the old method to get the target element
//This element is wrapped in the CipherValue sub-element.
xmlNodePtr pCipherData = pEncryptedData->children;
while (pCipherData != NULL && stricmp((const char *)(pCipherData->name), "CipherData"))
{
pCipherData = pCipherData->next;
}
if( pCipherData == NULL ) {
xmlSecEncCtxDestroy( pEncCtx ) ;
throw XMLEncryptionException() ;
}
xmlNodePtr pCipherValue = pCipherData->children;
while (pCipherValue != NULL && stricmp((const char *)(pCipherValue->name), "CipherValue"))
{
pCipherValue = pCipherValue->next;
}
if( pCipherValue == NULL ) {
xmlSecEncCtxDestroy( pEncCtx ) ;
throw XMLEncryptionException() ;
}
pContent = pCipherValue->children;
*/
//Encrypt the template
if( xmlSecEncCtxXmlEncrypt( pEncCtx , pEncryptedData , pContent ) < 0 )
{
xmlSecEncCtxDestroy( pEncCtx ) ;
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//throw XMLEncryptionException() ;
clearErrorRecorder();
return aTemplate;
}
xmlSecEncCtxDestroy( pEncCtx ) ;
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//get the new EncryptedData element
if (isParentRef)
{
pTemplate->setNativeElement(referenceNode->children) ;
}
else
{
pTemplate->setNativeElement(referenceNode->next);
}
return aTemplate ;
}
/* XXMLEncryption */
Reference< XXMLEncryptionTemplate >
SAL_CALL XMLEncryption_NssImpl :: decrypt(
const Reference< XXMLEncryptionTemplate >& aTemplate ,
const Reference< XXMLSecurityContext >& aSecurityCtx
) throw( com::sun::star::xml::crypto::XMLEncryptionException ,
com::sun::star::uno::SecurityException) {
xmlSecKeysMngrPtr pMngr = NULL ;
xmlSecEncCtxPtr pEncCtx = NULL ;
xmlNodePtr pEncryptedData = NULL ;
xmlNodePtr pContent = NULL ;
if( !aTemplate.is() )
throw RuntimeException() ;
if( !aSecurityCtx.is() )
throw RuntimeException() ;
//Get the encryption template
Reference< XXMLElementWrapper > xTemplate = aTemplate->getTemplate() ;
if( !xTemplate.is() ) {
throw RuntimeException() ;
}
Reference< XUnoTunnel > xTplTunnel( xTemplate , UNO_QUERY ) ;
if( !xTplTunnel.is() ) {
throw RuntimeException() ;
}
XMLElementWrapper_XmlSecImpl* pTemplate = ( XMLElementWrapper_XmlSecImpl* )xTplTunnel->getSomething( XMLElementWrapper_XmlSecImpl::getUnoTunnelImplementationId() ) ;
if( pTemplate == NULL ) {
throw RuntimeException() ;
}
pEncryptedData = pTemplate->getNativeElement() ;
//remember the position of the element to be signed
sal_Bool isParentRef = sal_True;
xmlNodePtr pParent = pEncryptedData->parent;
xmlNodePtr referenceNode;
if (pEncryptedData == pParent->children)
{
referenceNode = pParent;
}
else
{
referenceNode = pEncryptedData->prev;
isParentRef = sal_False;
}
setErrorRecorder( );
sal_Int32 nSecurityEnvironment = aSecurityCtx->getSecurityEnvironmentNumber();
sal_Int32 i;
for (i=0; i<nSecurityEnvironment; ++i)
{
Reference< XSecurityEnvironment > aEnvironment = aSecurityCtx->getSecurityEnvironmentByIndex(i);
//Get Keys Manager
Reference< XUnoTunnel > xSecTunnel( aEnvironment , UNO_QUERY ) ;
if( !aEnvironment.is() ) {
throw RuntimeException() ;
}
SecurityEnvironment_NssImpl* pSecEnv = ( SecurityEnvironment_NssImpl* )xSecTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ) ;
if( pSecEnv == NULL )
throw RuntimeException() ;
pMngr = pSecEnv->createKeysManager() ; //i39448
if( !pMngr ) {
throw RuntimeException() ;
}
//Create Encryption context
pEncCtx = xmlSecEncCtxCreate( pMngr ) ;
if( pEncCtx == NULL )
{
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//throw XMLEncryptionException() ;
clearErrorRecorder();
return aTemplate;
}
//Decrypt the template
if(!( xmlSecEncCtxDecrypt( pEncCtx , pEncryptedData ) < 0 || pEncCtx->result == NULL ))
{
//The decryption succeeds
//Destroy the encryption context
xmlSecEncCtxDestroy( pEncCtx ) ;
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
//get the decrypted element
XMLElementWrapper_XmlSecImpl * ret = new XMLElementWrapper_XmlSecImpl(isParentRef?
(referenceNode->children):(referenceNode->next));
//return ret;
aTemplate->setTemplate(ret);
break;
}
else
{
//The decryption fails, continue with the next security environment
xmlSecEncCtxDestroy( pEncCtx ) ;
pSecEnv->destroyKeysManager( pMngr ) ; //i39448
}
}
clearErrorRecorder();
return aTemplate;
}
/* XInitialization */
void SAL_CALL XMLEncryption_NssImpl :: initialize( const Sequence< Any >& aArguments ) throw( Exception, RuntimeException ) {
// TBD
} ;
/* XServiceInfo */
OUString SAL_CALL XMLEncryption_NssImpl :: getImplementationName() throw( RuntimeException ) {
return impl_getImplementationName() ;
}
/* XServiceInfo */
sal_Bool SAL_CALL XMLEncryption_NssImpl :: supportsService( const OUString& serviceName) throw( RuntimeException ) {
Sequence< OUString > seqServiceNames = getSupportedServiceNames() ;
const OUString* pArray = seqServiceNames.getConstArray() ;
for( sal_Int32 i = 0 ; i < seqServiceNames.getLength() ; i ++ ) {
if( *( pArray + i ) == serviceName )
return sal_True ;
}
return sal_False ;
}
/* XServiceInfo */
Sequence< OUString > SAL_CALL XMLEncryption_NssImpl :: getSupportedServiceNames() throw( RuntimeException ) {
return impl_getSupportedServiceNames() ;
}
//Helper for XServiceInfo
Sequence< OUString > XMLEncryption_NssImpl :: impl_getSupportedServiceNames() {
::osl::Guard< ::osl::Mutex > aGuard( ::osl::Mutex::getGlobalMutex() ) ;
Sequence< OUString > seqServiceNames( 1 ) ;
seqServiceNames.getArray()[0] = OUString::createFromAscii( "com.sun.star.xml.crypto.XMLEncryption" ) ;
return seqServiceNames ;
}
OUString XMLEncryption_NssImpl :: impl_getImplementationName() throw( RuntimeException ) {
return OUString::createFromAscii( "com.sun.star.xml.security.bridge.xmlsec.XMLEncryption_NssImpl" ) ;
}
//Helper for registry
Reference< XInterface > SAL_CALL XMLEncryption_NssImpl :: impl_createInstance( const Reference< XMultiServiceFactory >& aServiceManager ) throw( RuntimeException ) {
return Reference< XInterface >( *new XMLEncryption_NssImpl( aServiceManager ) ) ;
}
Reference< XSingleServiceFactory > XMLEncryption_NssImpl :: impl_createFactory( const Reference< XMultiServiceFactory >& aServiceManager ) {
//Reference< XSingleServiceFactory > xFactory ;
//xFactory = ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName , impl_createInstance , impl_getSupportedServiceNames ) ;
//return xFactory ;
return ::cppu::createSingleFactory( aServiceManager , impl_getImplementationName() , impl_createInstance , impl_getSupportedServiceNames() ) ;
}
<|endoftext|> |
<commit_before>#include <QGuiApplication>
#include <QtGui>
#include <QtQuick>
#include <QQmlApplicationEngine>
#include "VideoSurface.h"
#include "Comms.h"
#include "OS.h"
#include "Menus.h"
#include <android/log.h>
#include <thread>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Q_INIT_RESOURCE(res);
app.setQuitOnLastWindowClosed(true);
QPalette palette = app.palette();
palette.setColor(QPalette::Window, QColor(53,53,53));
palette.setColor(QPalette::WindowText, QColor(0xECF0F1));
palette.setColor(QPalette::Base, QColor(25,25,25));
palette.setColor(QPalette::AlternateBase, QColor(53,53,53));
palette.setColor(QPalette::ToolTipBase, QColor(0xECF0F1));
palette.setColor(QPalette::ToolTipText, QColor(0xECF0F1));
palette.setColor(QPalette::Text, QColor(0xECF0F1));
palette.setColor(QPalette::Button, QColor(53,53,53));
palette.setColor(QPalette::ButtonText, QColor(0xECF0F1));
palette.setColor(QPalette::BrightText, Qt::white);
palette.setColor(QPalette::Link, QColor(42, 130, 218));
palette.setColor(QPalette::Highlight, QColor(42, 130, 218));
palette.setColor(QPalette::HighlightedText, Qt::black);
app.setPalette(palette);
QQuickView view;
OS os;
Menus menus;
menus.init(view);
Comms comms;
comms.init("192.168.42.1", 3333);
qmlRegisterType<Comms>("com.silk.Comms", 1, 0, "Comms");
view.engine()->rootContext()->setContextProperty("s_comms", &comms);
view.engine()->rootContext()->setContextProperty("s_os", &os);
view.engine()->rootContext()->setContextProperty("s_menus", &menus);
qmlRegisterType<VideoSurface>("com.silk.VideoSurface", 0, 1, "VideoSurface");
QSurfaceFormat format = view.format();
format.setAlphaBufferSize(0);
format.setRedBufferSize(8);
format.setGreenBufferSize(8);
format.setBlueBufferSize(8);
format.setSamples(1);
format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
format.setSwapInterval(0);
view.setFormat(format);
view.setResizeMode(QQuickView::SizeRootObjectToView);
//view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
view.show();
//menus.push("Splash.qml");
menus.push("MM.qml");
while (true)
{
app.processEvents();
// {
// static FILE* fff = nullptr;
// if (!fff)
// {
// srand(time(nullptr));
// fff = fopen("/storage/emulated/0/Download/sample.h264", "rb");
// if (!fff)
// {
// exit(1);
// }
// }
// uint8_t data[32768];
// size_t size = 100;
// int r = fread(data, 1, size, fff);
// if (r == 0)
// {
// __android_log_print(ANDROID_LOG_INFO, "Skptr", "DONE, REWIND!!!!!");
// fseek(fff, 0, SEEK_SET);
// }
// if (r > 0)
// {
// VideoSurface::decodeVideo(data, r);
// }
// }
comms.process();
std::pair<void const*, size_t> videoData = comms.getVideoData();
if (videoData.second > 0)
{
VideoSurface::addVideoData(videoData.first, videoData.second);
}
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
return app.exec();
}
<commit_msg>Kill the app when put to background<commit_after>#include <QGuiApplication>
#include <QtGui>
#include <QtQuick>
#include <QQmlApplicationEngine>
#include "VideoSurface.h"
#include "Comms.h"
#include "OS.h"
#include "Menus.h"
#include <android/log.h>
#include <thread>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
Q_INIT_RESOURCE(res);
app.setQuitOnLastWindowClosed(true);
QPalette palette = app.palette();
palette.setColor(QPalette::Window, QColor(53,53,53));
palette.setColor(QPalette::WindowText, QColor(0xECF0F1));
palette.setColor(QPalette::Base, QColor(25,25,25));
palette.setColor(QPalette::AlternateBase, QColor(53,53,53));
palette.setColor(QPalette::ToolTipBase, QColor(0xECF0F1));
palette.setColor(QPalette::ToolTipText, QColor(0xECF0F1));
palette.setColor(QPalette::Text, QColor(0xECF0F1));
palette.setColor(QPalette::Button, QColor(53,53,53));
palette.setColor(QPalette::ButtonText, QColor(0xECF0F1));
palette.setColor(QPalette::BrightText, Qt::white);
palette.setColor(QPalette::Link, QColor(42, 130, 218));
palette.setColor(QPalette::Highlight, QColor(42, 130, 218));
palette.setColor(QPalette::HighlightedText, Qt::black);
app.setPalette(palette);
QQuickView view;
OS os;
Menus menus;
menus.init(view);
Comms comms;
comms.init("192.168.42.1", 3333);
qmlRegisterType<Comms>("com.silk.Comms", 1, 0, "Comms");
view.engine()->rootContext()->setContextProperty("s_comms", &comms);
view.engine()->rootContext()->setContextProperty("s_os", &os);
view.engine()->rootContext()->setContextProperty("s_menus", &menus);
qmlRegisterType<VideoSurface>("com.silk.VideoSurface", 0, 1, "VideoSurface");
QSurfaceFormat format = view.format();
format.setAlphaBufferSize(0);
format.setRedBufferSize(8);
format.setGreenBufferSize(8);
format.setBlueBufferSize(8);
format.setSamples(1);
format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
format.setSwapInterval(0);
view.setFormat(format);
//https://github.com/jeanleflambeur/silkopter/issues/40
//to prevent the app reverting to 60 FPS after focus lost
QObject::connect(&app, &QGuiApplication::applicationStateChanged, [](Qt::ApplicationState state)
{
if (state == Qt::ApplicationInactive)
{
__android_log_print(ANDROID_LOG_INFO, "Skptr", "Viewer is inactive");
exit(0); //abort, because QT will default to 60 FPS when coming back and I found no way to fix this
}
});
view.setResizeMode(QQuickView::SizeRootObjectToView);
//view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
view.show();
//menus.push("Splash.qml");
menus.push("MM.qml");
while (true)
{
app.processEvents();
// {
// static FILE* fff = nullptr;
// if (!fff)
// {
// srand(time(nullptr));
// fff = fopen("/storage/emulated/0/Download/sample.h264", "rb");
// if (!fff)
// {
// exit(1);
// }
// }
// uint8_t data[32768];
// size_t size = 100;
// int r = fread(data, 1, size, fff);
// if (r == 0)
// {
// __android_log_print(ANDROID_LOG_INFO, "Skptr", "DONE, REWIND!!!!!");
// fseek(fff, 0, SEEK_SET);
// }
// if (r > 0)
// {
// VideoSurface::decodeVideo(data, r);
// }
// }
comms.process();
std::pair<void const*, size_t> videoData = comms.getVideoData();
if (videoData.second > 0)
{
VideoSurface::addVideoData(videoData.first, videoData.second);
}
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
return app.exec();
}
<|endoftext|> |
<commit_before>#include <iomanip>
#include <string>
#include "Board.h"
#include "Pipe.h"
#include "Log.h"
using namespace std;
const int Board::x_offset = 227;
const int Board::y_offset = 35;
const int Board::slotSize = 48;
const int Board::lines = BOARD_LINES;
const int Board::columns = BOARD_COLUMNS;
Board::Board (SDL_Surface* s, SDL_Rect* c, SDL_Surface* pipe1, SDL_Surface* pipe2)
{
screen = s;
coordinates = c;
pipes_sprite1 = pipe1;
pipes_sprite2 = pipe2;
timer = INITIAL_TIMER;
last_ticks = 0;
cronometer_text = new Text(screen, CRON_OFFSET_X, CRON_OFFSET_Y, 20);
score_label_text = new Text(screen, SCORE_LABEL_OFFSET_X, SCORE_LABEL_OFFSET_Y, 20);
score_value_text = new Text(screen, SCORE_OFFSET_X, SCORE_OFFSET_Y, 20);
game_over_text = new Text(screen, GAME_OVER_OFFSET_X, GAME_OVER_OFFSET_Y, 30);
// Game board positions
for (int line = 0; line < lines; line++) {
for (int column = 0; column < columns; column++) {
slots[line][column] = NULL;
}
}
// blocked positions
for(int i = 0; i < BLOCKED_POSITIONS; i++) {
int column, line;
do {
column = rand() % BOARD_COLUMNS;
line = rand() % BOARD_LINES;
} while(slots[line][column]);
Pipe* pipe = new Pipe(pipes_sprite1, pipes_sprite2, false, false, false, false);
pipe->block();
slots[line][column] = pipe;
}
// Pool
for (int p = 0; p < POOL_SIZE; p++) {
pool[p] = new Pipe(pipes_sprite1, pipes_sprite2);
}
LOG(logDEBUG) << "Created Board";
}
void Board::mouseClick (int x, int y)
{
int x_min = x_offset, x_max = x_min + (lines * slotSize);
int y_min = y_offset, y_max = y_min + (columns * slotSize);
// Check limits
if (x >= x_min && x <= x_max && y >= y_min && y <= y_max) {
int line = (x - x_min) / slotSize;
int column = (y - y_min) / slotSize;
Pipe **pipe = &slots[line][column];
if (*pipe) {
if ((*pipe)->isBlocked())
return;
delete *pipe;
// loses points for replacing pipe
addScore(-10);
}
// Get top of the pool
*pipe = pool[0];
rotatePool();
}
}
void Board::rotatePool (void)
{
for (int p = 0; p < POOL_SIZE - 1; p++) {
pool[p] = pool[p + 1];
}
pool[POOL_SIZE - 1] = new Pipe(pipes_sprite1, pipes_sprite2);
}
SDL_Rect Board::getSlotScreenPosition (int line, int column)
{
SDL_Rect pos;
pos.x = (line * slotSize) + x_offset;
pos.y = (column * slotSize) + y_offset;
return pos;
}
Pipe* Board::getPipe(int column, int line) {
if(column >= BOARD_COLUMNS || column < 0 ||
line >= BOARD_LINES || line < 0) {
return NULL;
} else {
return slots[column][line];
}
}
Pipe* Board::getCurrentPipe() {
return getPipe(current_pipe_column, current_pipe_line);
}
Pipe* Board::getNextPipe(const int direction, int *column, int *line, int *flow) {
*column = current_pipe_column;
*line = current_pipe_line;
switch(direction) {
case FLOW_TOP:
*line -= 1;
*flow = FLOW_DOWN;
break;
case FLOW_RIGHT:
*column += 1;
*flow = FLOW_LEFT;
break;
case FLOW_DOWN:
*line += 1;
*flow = FLOW_TOP;
break;
case FLOW_LEFT:
*column -= 1;
*flow = FLOW_RIGHT;
break;
};
return getPipe(*column, *line);
}
void Board::Update() {
updateCronometer();
updatePipes();
updateStartingFlow();
updateNextPipe();
}
void Board::updateCronometer() {
int current_ticks = SDL_GetTicks();
// decreases every second
if (current_ticks > last_ticks + 1000) {
timer -= 1;
last_ticks = current_ticks;
}
if (timer < 0)
timer = 0;
}
void Board::updatePipes() {
for (int l = 0; l < lines; l++) {
for (int c = 0; c < columns; c++) {
if (slots[l][c] != NULL) {
slots[l][c]->Update();
}
}
}
}
void Board::updateStartingFlow() {
if (flow_started == false && timer == 0) {
if (slots[INITIAL_COLUMN][INITIAL_LINE] != NULL) {
current_pipe_column = INITIAL_COLUMN;
current_pipe_line = INITIAL_LINE;
startCurrentPipeFlow(FLOW_LEFT);
flow_started = true;
} else {
gameOver("No starting pipe");
}
}
}
void Board::updateNextPipe() {
if (flow_started == true && getCurrentPipe()->isFlowFinished()) {
if (current_pipe_column == FINAL_COLUMN && current_pipe_line == FINAL_LINE && getCurrentPipe()->getFlowTurnPosition() == FLOW_RIGHT && getCurrentPipe()->hasFlowEntry(FLOW_RIGHT)) {
successfulGameOver();
return;
}
int flow_direction = getCurrentPipe()->getFlowTurnPosition();
int next_flow;
int column, line, flow;
getNextPipe(flow_direction, &column, &line, &flow);
current_pipe_column = column;
current_pipe_line = line;
next_flow = flow;
// game over if has no next pipe or the next pipe does not have the next_flow entry
if (getCurrentPipe() == NULL || !getCurrentPipe()->hasFlowEntry(next_flow)) {
gameOver("No next pipe NULL or next pipe has no flow entry for " + next_flow);
} else {
startCurrentPipeFlow(next_flow);
}
} else if(flow_started == true && getCurrentPipe()->isFlowHalf()) {
int next_flow_direction = calculateNextFlowDirection();
if(next_flow_direction > 0) {
getCurrentPipe()->setFlowTurnPosition(next_flow_direction);
} else {
gameOver("No next flow direction");
}
}
}
int Board::calculateNextFlowDirection() {
if(possibleNextFlowDirection(FLOW_TOP, FLOW_DOWN)) {
return FLOW_TOP;
}
if(possibleNextFlowDirection(FLOW_RIGHT, FLOW_LEFT)) {
return FLOW_RIGHT;
}
if(possibleNextFlowDirection(FLOW_DOWN, FLOW_TOP)) {
return FLOW_DOWN;
}
if(possibleNextFlowDirection(FLOW_LEFT, FLOW_RIGHT)) {
return FLOW_LEFT;
}
// if couldn't find anything, turn to the first possible one
Pipe* pipe = getCurrentPipe();
if(current_pipe_column == FINAL_COLUMN && current_pipe_line == FINAL_LINE) {
return FLOW_RIGHT;
} else if(pipe->hasFlowEntry(FLOW_TOP) && pipe->getFlowStartPosition() != FLOW_TOP) {
return FLOW_TOP;
} else if(pipe->hasFlowEntry(FLOW_RIGHT) && pipe->getFlowStartPosition() != FLOW_RIGHT) {
return FLOW_RIGHT;
} else if(pipe->hasFlowEntry(FLOW_DOWN) && pipe->getFlowStartPosition() != FLOW_DOWN) {
return FLOW_DOWN;
} else if(pipe->hasFlowEntry(FLOW_LEFT) && pipe->getFlowStartPosition() != FLOW_LEFT) {
return FLOW_LEFT;
}
return 0;
}
bool Board::possibleNextFlowDirection(int outgoing_flow, int incoming_flow) {
Pipe* pipe = getCurrentPipe();
Pipe* next_pipe;
int column, line, flow;
if (pipe->hasFlowEntry(outgoing_flow) && pipe->getFlowStartPosition() != outgoing_flow) {
next_pipe = getNextPipe(outgoing_flow, &column, &line, &flow);
if(next_pipe && next_pipe->hasFlowEntry(incoming_flow)) {
return true;
}
}
return false;
}
void Board::drawCronometer ()
{
std::ostringstream out;
out << "0:" << std::setfill('0') << std::setw(2) << timer;
cronometer_text->Draw(out.str().c_str());
}
void Board::drawScore ()
{
std::ostringstream out;
out << score;
score_label_text->Draw("Score");
score_value_text->Draw(out.str().c_str());
}
void Board::drawGameOver() {
if (game_over_success) {
game_over_text->Draw("CONGRATULATIONS!");
} else {
game_over_text->Draw("GAME OVER!");
}
}
void Board::Draw ()
{
// Draw all board pipes
for (int l = 0; l < lines; l++) {
for (int c = 0; c < columns; c++) {
// if != NULL we have a pipe to draw
if (slots[l][c] != NULL) {
SDL_Rect pos = getSlotScreenPosition(l, c);
slots[l][c]->Draw(screen, &pos, isPipeConnected(l, c));
}
}
}
// Draw pool pipes
SDL_Rect pos;
pos.x = POOL_OFFSET_X;
pos.y = POOL_OFFSET_Y;
for (int p = POOL_SIZE - 1; p > 0; p--, pos.y += POOL_SPACING) {
pool[p]->Draw(screen, &pos, false);
}
pos.y = POOL_TOP_Y;
pool[0]->Draw(screen, &pos, false);
drawCronometer();
drawScore();
if (game_over) {
drawGameOver();
}
}
bool Board::isPipeConnected(int col, int line) {
if(col == INITIAL_COLUMN && line == INITIAL_LINE) {
return true;
}
Pipe* current = getPipe(col, line);
Pipe* pipe;
// connects on top?
pipe = getPipe(col, line - 1);
if(current->hasFlowEntry(FLOW_TOP) && pipe && pipe->hasFlowEntry(FLOW_DOWN)) {
return true;
}
// connects on right?
pipe = getPipe(col + 1, line);
if(current->hasFlowEntry(FLOW_RIGHT) && pipe && pipe->hasFlowEntry(FLOW_LEFT)) {
return true;
}
// connects on down?
pipe = getPipe(col, line + 1);
if(current->hasFlowEntry(FLOW_DOWN) && pipe && pipe->hasFlowEntry(FLOW_TOP)) {
return true;
}
// connects on left?
pipe = getPipe(col - 1, line);
if(current->hasFlowEntry(FLOW_LEFT) && pipe && pipe->hasFlowEntry(FLOW_RIGHT)) {
return true;
}
return false;
}
void Board::startCurrentPipeFlow(int direction) {
getCurrentPipe()->StartFlow(direction);
addScore(100);
}
void Board::addScore(int points) {
score += points;
if(score < 0)
score = 0;
}
void Board::gameOver(string reason) {
LOG(logINFO) << "Game over ! " << reason;
game_over = true;
}
void Board::successfulGameOver() {
LOG(logINFO) << "Successful Game over !";
game_over = true;
game_over_success = true;
}
bool Board::isGameOver() {
return game_over;
}
void Board::startGame ()
{
score = 0;
game_over = game_over_success = flow_started = false;
starting_time = SDL_GetTicks();
}
<commit_msg>Gameover when flow starts and there is no connection to the source.<commit_after>#include <iomanip>
#include <string>
#include "Board.h"
#include "Pipe.h"
#include "Log.h"
using namespace std;
const int Board::x_offset = 227;
const int Board::y_offset = 35;
const int Board::slotSize = 48;
const int Board::lines = BOARD_LINES;
const int Board::columns = BOARD_COLUMNS;
Board::Board (SDL_Surface* s, SDL_Rect* c, SDL_Surface* pipe1, SDL_Surface* pipe2)
{
screen = s;
coordinates = c;
pipes_sprite1 = pipe1;
pipes_sprite2 = pipe2;
timer = INITIAL_TIMER;
last_ticks = 0;
cronometer_text = new Text(screen, CRON_OFFSET_X, CRON_OFFSET_Y, 20);
score_label_text = new Text(screen, SCORE_LABEL_OFFSET_X, SCORE_LABEL_OFFSET_Y, 20);
score_value_text = new Text(screen, SCORE_OFFSET_X, SCORE_OFFSET_Y, 20);
game_over_text = new Text(screen, GAME_OVER_OFFSET_X, GAME_OVER_OFFSET_Y, 30);
// Game board positions
for (int line = 0; line < lines; line++) {
for (int column = 0; column < columns; column++) {
slots[line][column] = NULL;
}
}
// blocked positions
for(int i = 0; i < BLOCKED_POSITIONS; i++) {
int column, line;
do {
column = rand() % BOARD_COLUMNS;
line = rand() % BOARD_LINES;
} while(slots[line][column]);
Pipe* pipe = new Pipe(pipes_sprite1, pipes_sprite2, false, false, false, false);
pipe->block();
slots[line][column] = pipe;
}
// Pool
for (int p = 0; p < POOL_SIZE; p++) {
pool[p] = new Pipe(pipes_sprite1, pipes_sprite2);
}
LOG(logDEBUG) << "Created Board";
}
void Board::mouseClick (int x, int y)
{
int x_min = x_offset, x_max = x_min + (lines * slotSize);
int y_min = y_offset, y_max = y_min + (columns * slotSize);
// Check limits
if (x >= x_min && x <= x_max && y >= y_min && y <= y_max) {
int line = (x - x_min) / slotSize;
int column = (y - y_min) / slotSize;
Pipe **pipe = &slots[line][column];
if (*pipe) {
if ((*pipe)->isBlocked())
return;
delete *pipe;
// loses points for replacing pipe
addScore(-10);
}
// Get top of the pool
*pipe = pool[0];
rotatePool();
}
}
void Board::rotatePool (void)
{
for (int p = 0; p < POOL_SIZE - 1; p++) {
pool[p] = pool[p + 1];
}
pool[POOL_SIZE - 1] = new Pipe(pipes_sprite1, pipes_sprite2);
}
SDL_Rect Board::getSlotScreenPosition (int line, int column)
{
SDL_Rect pos;
pos.x = (line * slotSize) + x_offset;
pos.y = (column * slotSize) + y_offset;
return pos;
}
Pipe* Board::getPipe(int column, int line) {
if(column >= BOARD_COLUMNS || column < 0 ||
line >= BOARD_LINES || line < 0) {
return NULL;
} else {
return slots[column][line];
}
}
Pipe* Board::getCurrentPipe() {
return getPipe(current_pipe_column, current_pipe_line);
}
Pipe* Board::getNextPipe(const int direction, int *column, int *line, int *flow) {
*column = current_pipe_column;
*line = current_pipe_line;
switch(direction) {
case FLOW_TOP:
*line -= 1;
*flow = FLOW_DOWN;
break;
case FLOW_RIGHT:
*column += 1;
*flow = FLOW_LEFT;
break;
case FLOW_DOWN:
*line += 1;
*flow = FLOW_TOP;
break;
case FLOW_LEFT:
*column -= 1;
*flow = FLOW_RIGHT;
break;
};
return getPipe(*column, *line);
}
void Board::Update() {
updateCronometer();
updatePipes();
updateStartingFlow();
updateNextPipe();
}
void Board::updateCronometer() {
int current_ticks = SDL_GetTicks();
// decreases every second
if (current_ticks > last_ticks + 1000) {
timer -= 1;
last_ticks = current_ticks;
}
if (timer < 0)
timer = 0;
}
void Board::updatePipes() {
for (int l = 0; l < lines; l++) {
for (int c = 0; c < columns; c++) {
if (slots[l][c] != NULL) {
slots[l][c]->Update();
}
}
}
}
void Board::updateStartingFlow() {
if (flow_started == false && timer == 0) {
Pipe *pipe = slots[INITIAL_COLUMN][INITIAL_LINE];
if (pipe && pipe->hasFlowEntry(FLOW_LEFT)) {
current_pipe_column = INITIAL_COLUMN;
current_pipe_line = INITIAL_LINE;
startCurrentPipeFlow(FLOW_LEFT);
flow_started = true;
} else {
gameOver("No starting pipe");
}
}
}
void Board::updateNextPipe() {
if (flow_started == true && getCurrentPipe()->isFlowFinished()) {
if (current_pipe_column == FINAL_COLUMN && current_pipe_line == FINAL_LINE && getCurrentPipe()->getFlowTurnPosition() == FLOW_RIGHT && getCurrentPipe()->hasFlowEntry(FLOW_RIGHT)) {
successfulGameOver();
return;
}
int flow_direction = getCurrentPipe()->getFlowTurnPosition();
int next_flow;
int column, line, flow;
getNextPipe(flow_direction, &column, &line, &flow);
current_pipe_column = column;
current_pipe_line = line;
next_flow = flow;
// game over if has no next pipe or the next pipe does not have the next_flow entry
if (getCurrentPipe() == NULL || !getCurrentPipe()->hasFlowEntry(next_flow)) {
gameOver("No next pipe NULL or next pipe has no flow entry for " + next_flow);
} else {
startCurrentPipeFlow(next_flow);
}
} else if(flow_started == true && getCurrentPipe()->isFlowHalf()) {
int next_flow_direction = calculateNextFlowDirection();
if(next_flow_direction > 0) {
getCurrentPipe()->setFlowTurnPosition(next_flow_direction);
} else {
gameOver("No next flow direction");
}
}
}
int Board::calculateNextFlowDirection() {
if(possibleNextFlowDirection(FLOW_TOP, FLOW_DOWN)) {
return FLOW_TOP;
}
if(possibleNextFlowDirection(FLOW_RIGHT, FLOW_LEFT)) {
return FLOW_RIGHT;
}
if(possibleNextFlowDirection(FLOW_DOWN, FLOW_TOP)) {
return FLOW_DOWN;
}
if(possibleNextFlowDirection(FLOW_LEFT, FLOW_RIGHT)) {
return FLOW_LEFT;
}
// if couldn't find anything, turn to the first possible one
Pipe* pipe = getCurrentPipe();
if(current_pipe_column == FINAL_COLUMN && current_pipe_line == FINAL_LINE) {
return FLOW_RIGHT;
} else if(pipe->hasFlowEntry(FLOW_TOP) && pipe->getFlowStartPosition() != FLOW_TOP) {
return FLOW_TOP;
} else if(pipe->hasFlowEntry(FLOW_RIGHT) && pipe->getFlowStartPosition() != FLOW_RIGHT) {
return FLOW_RIGHT;
} else if(pipe->hasFlowEntry(FLOW_DOWN) && pipe->getFlowStartPosition() != FLOW_DOWN) {
return FLOW_DOWN;
} else if(pipe->hasFlowEntry(FLOW_LEFT) && pipe->getFlowStartPosition() != FLOW_LEFT) {
return FLOW_LEFT;
}
return 0;
}
bool Board::possibleNextFlowDirection(int outgoing_flow, int incoming_flow) {
Pipe* pipe = getCurrentPipe();
Pipe* next_pipe;
int column, line, flow;
if (pipe->hasFlowEntry(outgoing_flow) && pipe->getFlowStartPosition() != outgoing_flow) {
next_pipe = getNextPipe(outgoing_flow, &column, &line, &flow);
if(next_pipe && next_pipe->hasFlowEntry(incoming_flow)) {
return true;
}
}
return false;
}
void Board::drawCronometer ()
{
std::ostringstream out;
out << "0:" << std::setfill('0') << std::setw(2) << timer;
cronometer_text->Draw(out.str().c_str());
}
void Board::drawScore ()
{
std::ostringstream out;
out << score;
score_label_text->Draw("Score");
score_value_text->Draw(out.str().c_str());
}
void Board::drawGameOver() {
if (game_over_success) {
game_over_text->Draw("CONGRATULATIONS!");
} else {
game_over_text->Draw("GAME OVER!");
}
}
void Board::Draw ()
{
// Draw all board pipes
for (int l = 0; l < lines; l++) {
for (int c = 0; c < columns; c++) {
// if != NULL we have a pipe to draw
if (slots[l][c] != NULL) {
SDL_Rect pos = getSlotScreenPosition(l, c);
slots[l][c]->Draw(screen, &pos, isPipeConnected(l, c));
}
}
}
// Draw pool pipes
SDL_Rect pos;
pos.x = POOL_OFFSET_X;
pos.y = POOL_OFFSET_Y;
for (int p = POOL_SIZE - 1; p > 0; p--, pos.y += POOL_SPACING) {
pool[p]->Draw(screen, &pos, false);
}
pos.y = POOL_TOP_Y;
pool[0]->Draw(screen, &pos, false);
drawCronometer();
drawScore();
if (game_over) {
drawGameOver();
}
}
bool Board::isPipeConnected(int col, int line) {
if(col == INITIAL_COLUMN && line == INITIAL_LINE) {
return true;
}
Pipe* current = getPipe(col, line);
Pipe* pipe;
// connects on top?
pipe = getPipe(col, line - 1);
if(current->hasFlowEntry(FLOW_TOP) && pipe && pipe->hasFlowEntry(FLOW_DOWN)) {
return true;
}
// connects on right?
pipe = getPipe(col + 1, line);
if(current->hasFlowEntry(FLOW_RIGHT) && pipe && pipe->hasFlowEntry(FLOW_LEFT)) {
return true;
}
// connects on down?
pipe = getPipe(col, line + 1);
if(current->hasFlowEntry(FLOW_DOWN) && pipe && pipe->hasFlowEntry(FLOW_TOP)) {
return true;
}
// connects on left?
pipe = getPipe(col - 1, line);
if(current->hasFlowEntry(FLOW_LEFT) && pipe && pipe->hasFlowEntry(FLOW_RIGHT)) {
return true;
}
return false;
}
void Board::startCurrentPipeFlow(int direction) {
getCurrentPipe()->StartFlow(direction);
addScore(100);
}
void Board::addScore(int points) {
score += points;
if(score < 0)
score = 0;
}
void Board::gameOver(string reason) {
LOG(logINFO) << "Game over ! " << reason;
game_over = true;
}
void Board::successfulGameOver() {
LOG(logINFO) << "Successful Game over !";
game_over = true;
game_over_success = true;
}
bool Board::isGameOver() {
return game_over;
}
void Board::startGame ()
{
score = 0;
game_over = game_over_success = flow_started = false;
starting_time = SDL_GetTicks();
}
<|endoftext|> |
<commit_before>/*
* File: Cache.hpp
* Copyright: Emanuele Di Pascale (dipascae aT tcd dOt ie)
*
* Licensed under the Apache License v2.0 (see attached README.TXT file)
* Created on 30 April 2013, 11:23
*/
#ifndef CACHE_HPP
#define CACHE_HPP
#include <map>
#include <set>
#include <assert.h>
#include <iostream>
#include <limits>
#include "RunningAvg.hpp"
/* Policy to use in caches to replace old content and make space for new one
* LRU = Least Recently Used, LFU = Least Frequently Used
*/
enum CachePolicy {LRU, LFU};
/* Struct to hold the caching parameters associated to each content element;
* Timestamp must be a scalar which supports std::numeric_limits<Timestamp>::max()
* Size can be any scalar which supports comparison operators (e.g. <,>,>= etc.)
* uploads is used to calculate the bandwidth used and to ensure that we do not
* erase an element which is currently required
*/
template <typename Timestamp, typename Size>
struct CacheEntry {
Timestamp lastAccessed;
unsigned int timesServed;
Size size;
unsigned int uploads;
};
/* Implements a generic LRU or LFU cache, with a fixed maximum capacity maxSize
* and elements of type Content which can be of variable size. Implemented over
* std::map (not optimized for performance!)
*/
template <typename Content, typename Size, typename Timestamp>
class Cache {
typedef std::map<Content, CacheEntry<Timestamp, Size> > CacheMap;
protected:
CacheMap cacheMap;
Size maxSize;
Size currentSize;
CachePolicy policy;
RunningAvg<double, Timestamp> cacheOccupancy;
void updateOccupancy(Timestamp time) {
double occ = 100 * currentSize / maxSize;
bool result = cacheOccupancy.add(occ, time);
if (!result) {
std::cerr << "Failed to update the cache occupancy at time "
<< time << ", last timestamp: " << cacheOccupancy.getLastTimestamp()
<< "; aborting. " << std::endl;
abort();
}
}
public:
friend class CacheTestClass;
Cache(Size maxSize, CachePolicy policy = LRU);
std::pair<bool, std::set<Content> > addToCache(Content content,
Size size, Timestamp time);
void clearCache();
// to update metadata about the content (lastAccess, timesAccessed, uploads..)
bool getFromCache(Content content, Timestamp time);
bool isCached(Content content);
void removeFromCache(Content content, Timestamp time); // for expired content
bool uploadCompleted(Content content); // to decrease the upload counter
int getCurrentUploads(Content content);
int getTotalUploads();
double getAvgOccupancy(Timestamp time) {
double avg = cacheOccupancy.extract(time);
return avg;
}
void resetOccupancy(Timestamp time) {
double value = 100 * currentSize / maxSize;
cacheOccupancy.reset(value, time);
}
// to give the optimizer full access to the content of the cache
CacheMap getCacheMap() const {
return this->cacheMap;
}
unsigned int getNumElementsCached() const {
return this->cacheMap.size();
}
Size getCurrentSize() const {
return this->currentSize;
}
Size getMaxSize() const {
return maxSize;
}
bool fitsInCache(Size size) const {
if (maxSize - currentSize >= size)
return true;
else
return false;
}
};
template <typename Content, typename Size, typename Timestamp>
Cache<Content, Size, Timestamp>::Cache(Size maxSize, CachePolicy policy) : cacheOccupancy() {
this->maxSize = maxSize;
this->policy = policy;
this->currentSize = 0;
}
template <typename Content, typename Size, typename Timestamp>
std::pair<bool, std::set<Content> > Cache<Content, Size, Timestamp>::addToCache(
Content content, Size size, Timestamp time) {
std::set<Content> deletedElements;
deletedElements.clear();
// check if the content was already cached
typename CacheMap::iterator cIt = cacheMap.find(content);
if ((cIt != cacheMap.end() && cIt->second.size >= size) // content already cached
|| size > getMaxSize()) { // content cannot possibly fit in the cache
// already cached or too big to be cached, quit
return std::make_pair(false, deletedElements);
}
else {
unsigned int oldFreqStat = 0;
if (cIt!= cacheMap.end()) {
// the content was cached, but with a smaller chunk, delete it (but save
// the caching info - after all it's the same content)
this->currentSize -= cIt->second.size;
oldFreqStat = cIt->second.timesServed;
/* FIXME: if something goes wrong and we cannot cache the new element,
* we will lose the previous (partial) copy
*/
this->cacheMap.erase(cIt);
}
while (currentSize + size > maxSize) {
// Replace content according to selected policy
Timestamp minTmp = std::numeric_limits<Timestamp>::max();
typename CacheMap::iterator minIt = cacheMap.end();
switch (policy) {
case LRU:
for (typename CacheMap::iterator it = cacheMap.begin();
it != cacheMap.end(); it++) {
if (it->second.uploads == 0 && it->second.lastAccessed < minTmp) {
minTmp = it->second.lastAccessed;
minIt = it;
}
}
break;
case LFU:
for (typename CacheMap::iterator it = cacheMap.begin();
it != cacheMap.end(); it++) {
if (it->second.uploads == 0 && it->second.timesServed < minTmp) {
minTmp = it->second.timesServed;
minIt = it;
}
}
break;
default:
std::cerr << "ERROR: Cache::addToCache - unrecognized CachePolicy"
<< std::endl;
}
// check that there is an element we can erase (due to uploads)
if (minIt == cacheMap.end()) {
// all elements are being used for uploads, cannot cache
return std::make_pair(false, deletedElements);
}
// else remove the identified element from the cache
currentSize -= minIt->second.size;
deletedElements.insert(minIt->first);
cacheMap.erase(minIt);
}
// insert new element in the cache
CacheEntry<Timestamp, Size> entry;
entry.lastAccessed = time;
entry.timesServed = oldFreqStat; // 0 if the content is new
entry.size = size;
entry.uploads = 0;
if (cacheMap.insert(std::make_pair(content,entry)).second == true) {
currentSize += size;
assert(currentSize <= maxSize);
updateOccupancy(time);
return std::make_pair(true, deletedElements);
} else {
std::cerr << "WARNING: Cache::addToCache() - Could not insert content "
<< std::endl;
updateOccupancy(time);
return std::make_pair(false, deletedElements);
}
}
}
template <typename Content, typename Size, typename Timestamp>
void Cache<Content, Size, Timestamp>::clearCache() {
cacheMap.clear();
this->currentSize = 0;
cacheOccupancy.reset(0,0);
}
template <typename Content, typename Size, typename Timestamp>
bool Cache<Content, Size, Timestamp>::getFromCache(Content content, Timestamp time) {
typename CacheMap::iterator it = cacheMap.find(content);
if (it != cacheMap.end()) {
it->second.lastAccessed = time;
it->second.timesServed++;
it->second.uploads++;
return true;
}
else
return false;
}
template <typename Content, typename Size, typename Timestamp>
bool Cache<Content, Size, Timestamp>::isCached(Content content) {
typename CacheMap::iterator cIt = cacheMap.find(content);
if (cIt != cacheMap.end())
return true;
else // shall we return size instead to allow for multiple sources?
return false;
}
template <typename Content, typename Size, typename Timestamp>
void Cache<Content, Size, Timestamp>::removeFromCache(Content content, Timestamp time) {
typename CacheMap::iterator it = cacheMap.find(content);
if (it != cacheMap.end()) {
this->currentSize -= it->second.size;
assert(this->currentSize >= 0);
cacheMap.erase(it);
updateOccupancy(time);
}
}
template <typename Content, typename Size, typename Timestamp>
bool Cache<Content, Size, Timestamp>::uploadCompleted(Content content) {
typename CacheMap::iterator it = cacheMap.find(content);
if (it != cacheMap.end()) {
it->second.uploads = it->second.uploads - 1;
assert(it->second.uploads >= 0);
return true;
} else {
return false;
}
}
template <typename Content, typename Size, typename Timestamp>
int Cache<Content, Size, Timestamp>::getCurrentUploads(Content content) {
typename CacheMap::iterator it = cacheMap.find(content);
if (it != cacheMap.end()) {
return it->second.uploads;
} else {
return -1;
}
}
template <typename Content, typename Size, typename Timestamp>
int Cache<Content, Size, Timestamp>::getTotalUploads() {
int uploads = 0;
for (typename CacheMap::iterator it = cacheMap.begin(); it != cacheMap.end(); it++)
uploads += it->second.uploads;
return uploads;
}
#endif /* CACHE_HPP */
<commit_msg>getFromCache now accepts a third boolean parameter, local. If local==true, the content is being requested locally and will not be uploaded. This is to prevent a situation where content accessed locally would never be marked as completed in terms of upload, since no data flow was generated.<commit_after>/*
* File: Cache.hpp
* Copyright: Emanuele Di Pascale (dipascae aT tcd dOt ie)
*
* Licensed under the Apache License v2.0 (see attached README.TXT file)
* Created on 30 April 2013, 11:23
*/
#ifndef CACHE_HPP
#define CACHE_HPP
#include <map>
#include <set>
#include <assert.h>
#include <iostream>
#include <limits>
#include "RunningAvg.hpp"
/* Policy to use in caches to replace old content and make space for new one
* LRU = Least Recently Used, LFU = Least Frequently Used
*/
enum CachePolicy {LRU, LFU};
/* Struct to hold the caching parameters associated to each content element;
* Timestamp must be a scalar which supports std::numeric_limits<Timestamp>::max()
* Size can be any scalar which supports comparison operators (e.g. <,>,>= etc.)
* uploads is used to calculate the bandwidth used and to ensure that we do not
* erase an element which is currently required
*/
template <typename Timestamp, typename Size>
struct CacheEntry {
Timestamp lastAccessed;
unsigned int timesServed;
Size size;
unsigned int uploads;
};
/* Implements a generic LRU or LFU cache, with a fixed maximum capacity maxSize
* and elements of type Content which can be of variable size. Implemented over
* std::map (not optimized for performance!)
*/
template <typename Content, typename Size, typename Timestamp>
class Cache {
typedef std::map<Content, CacheEntry<Timestamp, Size> > CacheMap;
protected:
CacheMap cacheMap;
Size maxSize;
Size currentSize;
CachePolicy policy;
RunningAvg<double, Timestamp> cacheOccupancy;
void updateOccupancy(Timestamp time) {
double occ = 100 * currentSize / maxSize;
bool result = cacheOccupancy.add(occ, time);
if (!result) {
std::cerr << "Failed to update the cache occupancy at time "
<< time << ", last timestamp: " << cacheOccupancy.getLastTimestamp()
<< "; aborting. " << std::endl;
abort();
}
}
public:
friend class CacheTestClass;
Cache(Size maxSize, CachePolicy policy = LRU);
std::pair<bool, std::set<Content> > addToCache(Content content,
Size size, Timestamp time);
void clearCache();
// to update metadata about the content (lastAccess, timesAccessed, uploads..)
// if local==true the content is not uploaded (it's the user itself who requested it again)
bool getFromCache(Content content, Timestamp time, bool local);
bool isCached(Content content);
void removeFromCache(Content content, Timestamp time); // for expired content
bool uploadCompleted(Content content); // to decrease the upload counter
int getCurrentUploads(Content content);
int getTotalUploads();
double getAvgOccupancy(Timestamp time) {
double avg = cacheOccupancy.extract(time);
return avg;
}
void resetOccupancy(Timestamp time) {
double value = 100 * currentSize / maxSize;
cacheOccupancy.reset(value, time);
}
// to give the optimizer full access to the content of the cache
CacheMap getCacheMap() const {
return this->cacheMap;
}
unsigned int getNumElementsCached() const {
return this->cacheMap.size();
}
Size getCurrentSize() const {
return this->currentSize;
}
Size getMaxSize() const {
return maxSize;
}
bool fitsInCache(Size size) const {
if (maxSize - currentSize >= size)
return true;
else
return false;
}
};
template <typename Content, typename Size, typename Timestamp>
Cache<Content, Size, Timestamp>::Cache(Size maxSize, CachePolicy policy) : cacheOccupancy() {
this->maxSize = maxSize;
this->policy = policy;
this->currentSize = 0;
}
template <typename Content, typename Size, typename Timestamp>
std::pair<bool, std::set<Content> > Cache<Content, Size, Timestamp>::addToCache(
Content content, Size size, Timestamp time) {
std::set<Content> deletedElements;
deletedElements.clear();
// check if the content was already cached
typename CacheMap::iterator cIt = cacheMap.find(content);
if ((cIt != cacheMap.end() && cIt->second.size >= size) // content already cached
|| size > getMaxSize()) { // content cannot possibly fit in the cache
// already cached or too big to be cached, quit
return std::make_pair(false, deletedElements);
}
else {
unsigned int oldFreqStat = 0;
if (cIt!= cacheMap.end()) {
// the content was cached, but with a smaller chunk, delete it (but save
// the caching info - after all it's the same content)
this->currentSize -= cIt->second.size;
oldFreqStat = cIt->second.timesServed;
/* FIXME: if something goes wrong and we cannot cache the new element,
* we will lose the previous (partial) copy
*/
this->cacheMap.erase(cIt);
}
while (currentSize + size > maxSize) {
// Replace content according to selected policy
Timestamp minTmp = std::numeric_limits<Timestamp>::max();
typename CacheMap::iterator minIt = cacheMap.end();
switch (policy) {
case LRU:
for (typename CacheMap::iterator it = cacheMap.begin();
it != cacheMap.end(); it++) {
if (it->second.uploads == 0 && it->second.lastAccessed < minTmp) {
minTmp = it->second.lastAccessed;
minIt = it;
}
}
break;
case LFU:
for (typename CacheMap::iterator it = cacheMap.begin();
it != cacheMap.end(); it++) {
if (it->second.uploads == 0 && it->second.timesServed < minTmp) {
minTmp = it->second.timesServed;
minIt = it;
}
}
break;
default:
std::cerr << "ERROR: Cache::addToCache - unrecognized CachePolicy"
<< std::endl;
}
// check that there is an element we can erase (due to uploads)
if (minIt == cacheMap.end()) {
// all elements are being used for uploads, cannot cache
return std::make_pair(false, deletedElements);
}
// else remove the identified element from the cache
currentSize -= minIt->second.size;
deletedElements.insert(minIt->first);
cacheMap.erase(minIt);
}
// insert new element in the cache
CacheEntry<Timestamp, Size> entry;
entry.lastAccessed = time;
entry.timesServed = oldFreqStat; // 0 if the content is new
entry.size = size;
entry.uploads = 0;
if (cacheMap.insert(std::make_pair(content,entry)).second == true) {
currentSize += size;
assert(currentSize <= maxSize);
updateOccupancy(time);
return std::make_pair(true, deletedElements);
} else {
std::cerr << "WARNING: Cache::addToCache() - Could not insert content "
<< std::endl;
updateOccupancy(time);
return std::make_pair(false, deletedElements);
}
}
}
template <typename Content, typename Size, typename Timestamp>
void Cache<Content, Size, Timestamp>::clearCache() {
cacheMap.clear();
this->currentSize = 0;
cacheOccupancy.reset(0,0);
}
template <typename Content, typename Size, typename Timestamp>
bool Cache<Content, Size, Timestamp>::getFromCache(Content content, Timestamp time,
bool local) {
typename CacheMap::iterator it = cacheMap.find(content);
if (it != cacheMap.end()) {
it->second.lastAccessed = time;
it->second.timesServed++;
if (!local)
it->second.uploads++;
return true;
}
else
return false;
}
template <typename Content, typename Size, typename Timestamp>
bool Cache<Content, Size, Timestamp>::isCached(Content content) {
typename CacheMap::iterator cIt = cacheMap.find(content);
if (cIt != cacheMap.end())
return true;
else // shall we return size instead to allow for multiple sources?
return false;
}
template <typename Content, typename Size, typename Timestamp>
void Cache<Content, Size, Timestamp>::removeFromCache(Content content, Timestamp time) {
typename CacheMap::iterator it = cacheMap.find(content);
if (it != cacheMap.end()) {
this->currentSize -= it->second.size;
assert(this->currentSize >= 0);
cacheMap.erase(it);
updateOccupancy(time);
}
}
template <typename Content, typename Size, typename Timestamp>
bool Cache<Content, Size, Timestamp>::uploadCompleted(Content content) {
typename CacheMap::iterator it = cacheMap.find(content);
if (it != cacheMap.end()) {
it->second.uploads = it->second.uploads - 1;
assert(it->second.uploads >= 0);
return true;
} else {
return false;
}
}
template <typename Content, typename Size, typename Timestamp>
int Cache<Content, Size, Timestamp>::getCurrentUploads(Content content) {
typename CacheMap::iterator it = cacheMap.find(content);
if (it != cacheMap.end()) {
return it->second.uploads;
} else {
return -1;
}
}
template <typename Content, typename Size, typename Timestamp>
int Cache<Content, Size, Timestamp>::getTotalUploads() {
int uploads = 0;
for (typename CacheMap::iterator it = cacheMap.begin(); it != cacheMap.end(); it++)
uploads += it->second.uploads;
return uploads;
}
#endif /* CACHE_HPP */
<|endoftext|> |
<commit_before>#include "PushBall.h"
using PushBall = commands::PushBall;
// PushBall Command Group:
PushBall::PushBall(Intake *intake) : CommandGroup("PushBall")
{
intake_ = intake;
push_ = new Push(intake);
stop_ = new Stopper(intake);
timeout_ = 0.0;
this->AddSequential(push_);
this->AddSequential(new WaitCommand(timeout_));
this->AddSequential(stop_);
}
void PushBall::SetTimeout(double timeout)
{
timeout_ = timeout;
}
double PushBall::GetTimeout() const
{
return timeout_;
}
// Push Command:
PushBall::Push::Push(Intake *intake)
{
intake_ = intake;
}
void PushBall::Push::Initialize()
{
intake_->OutakeBall();
}
bool PushBall::Push::IsFinished()
{
return !intake_->CheckSwitch();
}
// Stopper Command:
PushBall::Stopper::Stopper(Intake *intake)
{
intake_ = intake;
}
bool PushBall::Stopper::IsFinished()
{
return true;
}
void PushBall::Stopper::End()
{
intake_->Stop();
}
<commit_msg>Modifies existing functions to handle state changes and checks for Intake.<commit_after>#include "PushBall.h"
/**
* Commands namespace with implementation
* of PushBall command group, and nested
* Push and Stopper command classes.
*/
namespace commands
{
// PushBall constructor:
PushBall::PushBall(Intake *intake) : CommandGroup("PushBall")
{
intake_ = intake;
push_ = new Push(intake);
stop_ = new Stopper(intake);
timeout_ = 0.0;
SetInterruptible(false);
this->AddSequential(push_);
this->AddSequential(new WaitCommand(timeout_));
this->AddSequential(stop_);
}
// PushBall main functions:
void PushBall::SetTimeout(double timeout)
{
timeout_ = timeout;
}
double PushBall::GetTimeout() const
{
return timeout_;
}
// Push constructor:
PushBall::Push::Push(Intake *intake)
{
intake_ = intake;
SetInterruptible(false);
}
// Push main functions
void PushBall::Push::Initialize()
{
if (intake_->GetState() == State_t::HOLDING)
{
intake_->SetState(State_t::PUSHING);
intake_->OutakeBall();
}
else
{
std::cout << "ERROR: Invalid starting state (should be \"HOLDING\")";
}
}
bool PushBall::Push::IsFinished()
{
return !intake_->CheckSwitch();
}
// Stopper constructor:
PushBall::Stopper::Stopper(Intake *intake)
{
intake_ = intake;
SetInterruptible(false);
}
// Stopper main functions:
bool PushBall::Stopper::IsFinished()
{
return true;
}
void PushBall::Stopper::End()
{
intake_->Stop();
intake_->SetState(State_t::OFF);
}
} // end namespace commands
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ldump.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-10-15 13:30:54 $
*
* 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 "hashtbl.hxx"
#define MAXFILT 200
struct LibExport
{
char *cExportName; // zu exportierende Fkt.
unsigned long nOrdinal; // Nummer der zu export. Fkt.
bool bByName; // NONAME anhaengen
bool bExport; // exportieren oder nicht ?
};
class ExportSet;
class LibDump
{
ExportSet *pBaseTab; // Zugriff auf gemangelte Namen
ExportSet *pIndexTab; // Zugriff auf die Ordinals
char *cBName; // Name der Datenbasis
char *cAPrefix; // Prefix fuer C-Fkts.
char *cLibName; // Name der zu untersuchenden Lib
char *cFilterName; // Name der Filterdatei
char *cModName; // Modulname
unsigned short nBegin; // Nummer des ersten Exports
unsigned long nBaseLines; // Line in Datenbasis
unsigned long nFilterLines; // Line in FilterTabelle
char **pFilterLines; // Filtertabelle
unsigned long nDefStart;
bool bBase; // Existenz der DatenBasis;
bool bAll; // Alle Fkts exportieren
bool bDef; // DefFile schreiben ( bei -E )
bool CheckDataBase();
bool CheckLibrary(char * cName);
bool ReadDataBase();
bool ReadFilter(char *);
bool PrintSym(char *, bool bName = true );
public:
LibDump( char *cFileName );
~LibDump();
bool Dump();
bool SetFilter(char *cFilterName);
void SetBeginExport(unsigned short nVal){nBegin = nVal;}
void SetCExport( char* pName );
bool Filter(char *pName);
bool IsFromAnonymousNamespace(char *pName);
bool PrintDefFile();
bool PrintDataBase();
static void DumpError(unsigned long nError);
};
<commit_msg>INTEGRATION: CWS winordinals (1.4.20); FILE MERGED 2008/03/14 10:36:34 vg 1.4.20.1: #i86800# switch to symbol-exporting linking for windows<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ldump.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2008-03-25 14:07:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "hashtbl.hxx"
#define MAXFILT 200
struct LibExport
{
char *cExportName; // zu exportierende Fkt.
unsigned long nOrdinal; // Nummer der zu export. Fkt.
bool bByName; // NONAME anhaengen
bool bExport; // exportieren oder nicht ?
};
class ExportSet;
class LibDump
{
ExportSet *pBaseTab; // Zugriff auf gemangelte Namen
ExportSet *pIndexTab; // Zugriff auf die Ordinals
char *cBName; // Name der Datenbasis
char *cAPrefix; // Prefix fuer C-Fkts.
char *cLibName; // Name der zu untersuchenden Lib
char *cFilterName; // Name der Filterdatei
char *cModName; // Modulname
unsigned short nBegin; // Nummer des ersten Exports
unsigned long nBaseLines; // Line in Datenbasis
unsigned long nFilterLines; // Line in FilterTabelle
char **pFilterLines; // Filtertabelle
unsigned long nDefStart;
bool bBase; // Existenz der DatenBasis;
bool bAll; // Alle Fkts exportieren
bool bDef; // DefFile schreiben ( bei -E )
int bExportName; // 0 - export by ordinal; 1 - export by name
bool CheckDataBase();
bool CheckLibrary(char * cName);
bool ReadDataBase();
bool ReadFilter(char *);
bool PrintSym(char *, bool bName = true );
public:
LibDump( char *cFileName, int bExportByName );
~LibDump();
bool Dump();
bool SetFilter(char *cFilterName);
void SetBeginExport(unsigned short nVal){nBegin = nVal;}
void SetCExport( char* pName );
bool Filter(char *pName);
bool IsFromAnonymousNamespace(char *pName);
bool PrintDefFile();
bool PrintDataBase();
static void DumpError(unsigned long nError);
};
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.