<commit_before>/*************************************************************************
 *
 *  $RCSfile: app.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: dg $ $Date: 2001-02-12 16:23:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "app.hxx"
#include "wrapper.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#include <offmgr/app.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif

#include <setup2/installer.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configmgr.hxx>
#include <vcl/msgbox.hxx>

#define DEFINE_CONST_UNICODE(CONSTASCII)        UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

void PreloadConfigTrees()
{
    // these tree are preloaded to get a faster startup for the office
    Sequence <rtl::OUString> aPreloadPathList(6);
    aPreloadPathList[0] =  rtl::OUString::createFromAscii("org.openoffice.Office.Common");
    aPreloadPathList[1] =  rtl::OUString::createFromAscii("org.openoffice.ucb.Configuration/ContentProviders/Office/SecondaryKeys/Local/ProviderData");
    aPreloadPathList[2] =  rtl::OUString::createFromAscii("org.openoffice.Office.Writer");
    aPreloadPathList[3] =  rtl::OUString::createFromAscii("org.openoffice.Office.WriterWeb");
    aPreloadPathList[4] =  rtl::OUString::createFromAscii("org.openoffice.Office.Calc");
    aPreloadPathList[5] =  rtl::OUString::createFromAscii("org.openoffice.Office.Impress");

    Reference< XMultiServiceFactory > xProvider(
            ::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider")), UNO_QUERY);

    Any aValue;
    aValue <<= aPreloadPathList;

    Reference < com::sun::star::beans::XPropertySet > (xProvider, UNO_QUERY)->setPropertyValue(rtl::OUString::createFromAscii("PrefetchNodes"), aValue );
}

void ReplaceStringHookProc( UniString& rStr )
{
    static String aBrandName;
    static String aVersion;
    static String aExtension;

    static int nAll = 0, nPro = 0;

    if ( !aBrandName.Len() )
    {
        Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
        rtl::OUString aTmp;
        aRet >>= aTmp;
        aBrandName = aTmp;

        aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );
        aRet >>= aTmp;
        aVersion = aTmp;

        aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );
        aRet >>= aTmp;
        aExtension = aTmp;
    }

    nAll++;
    if ( rStr.SearchAscii( "%PRODUCT" ) != STRING_NOTFOUND )
    {
        nPro++;
        rStr.SearchAndReplaceAllAscii( "%PRODUCTNAME", aBrandName );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTVERSION", aVersion );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTEXTENSION", aExtension );
    }
}

Desktop aDesktop;

Desktop::Desktop()
{
}

void Desktop::Main()
{
    ResMgr::SetReadStringHook( ReplaceStringHookProc );
    SetAppName( DEFINE_CONST_UNICODE("soffice") );
//  Read the common configuration items for optimization purpose
    PreloadConfigTrees();

    Installer* pInstaller = new Installer;
    pInstaller->InitializeInstallation( Application::GetAppFileName() );
    delete pInstaller;

    SvtPathOptions* pPathOptions = new SvtPathOptions;
    RegisterServices();
    OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );
//    Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE("com.sun.star.office.OfficeWrapper" ) ), UNO_QUERY );
    SfxApplicationClass::Main();
//    xWrapper->dispose();

    if( pWrapper!=NULL)
    {
        delete pWrapper;
        pWrapper=NULL;
    }

    delete pPathOptions;
    utl::ConfigManager::RemoveConfigManager();
}

void Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )
{
    OFF_APP()->SystemSettingsChanging( rSettings, pFrame );
}

<commit_msg>#83239# preloading of ucb configurationdata<commit_after>/*************************************************************************
 *
 *  $RCSfile: app.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: kso $ $Date: 2001-02-12 16:50:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "app.hxx"
#include "wrapper.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#include <offmgr/app.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif

#include <setup2/installer.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configmgr.hxx>
#include <vcl/msgbox.hxx>

#define DEFINE_CONST_UNICODE(CONSTASCII)        UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

void PreloadConfigTrees()
{
    // these tree are preloaded to get a faster startup for the office
    Sequence <rtl::OUString> aPreloadPathList(6);
    aPreloadPathList[0] =  rtl::OUString::createFromAscii("org.openoffice.Office.Common");
    aPreloadPathList[1] =  rtl::OUString::createFromAscii("org.openoffice.ucb.Configuration");
    aPreloadPathList[2] =  rtl::OUString::createFromAscii("org.openoffice.Office.Writer");
    aPreloadPathList[3] =  rtl::OUString::createFromAscii("org.openoffice.Office.WriterWeb");
    aPreloadPathList[4] =  rtl::OUString::createFromAscii("org.openoffice.Office.Calc");
    aPreloadPathList[5] =  rtl::OUString::createFromAscii("org.openoffice.Office.Impress");

    Reference< XMultiServiceFactory > xProvider(
            ::comphelper::getProcessServiceFactory()->createInstance(::rtl::OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider")), UNO_QUERY);

    Any aValue;
    aValue <<= aPreloadPathList;

    Reference < com::sun::star::beans::XPropertySet > (xProvider, UNO_QUERY)->setPropertyValue(rtl::OUString::createFromAscii("PrefetchNodes"), aValue );
}

void ReplaceStringHookProc( UniString& rStr )
{
    static String aBrandName;
    static String aVersion;
    static String aExtension;

    static int nAll = 0, nPro = 0;

    if ( !aBrandName.Len() )
    {
        Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
        rtl::OUString aTmp;
        aRet >>= aTmp;
        aBrandName = aTmp;

        aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTVERSION );
        aRet >>= aTmp;
        aVersion = aTmp;

        aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTEXTENSION );
        aRet >>= aTmp;
        aExtension = aTmp;
    }

    nAll++;
    if ( rStr.SearchAscii( "%PRODUCT" ) != STRING_NOTFOUND )
    {
        nPro++;
        rStr.SearchAndReplaceAllAscii( "%PRODUCTNAME", aBrandName );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTVERSION", aVersion );
        rStr.SearchAndReplaceAllAscii( "%PRODUCTEXTENSION", aExtension );
    }
}

Desktop aDesktop;

Desktop::Desktop()
{
}

void Desktop::Main()
{
    ResMgr::SetReadStringHook( ReplaceStringHookProc );
    SetAppName( DEFINE_CONST_UNICODE("soffice") );
//  Read the common configuration items for optimization purpose
    PreloadConfigTrees();

    Installer* pInstaller = new Installer;
    pInstaller->InitializeInstallation( Application::GetAppFileName() );
    delete pInstaller;

    SvtPathOptions* pPathOptions = new SvtPathOptions;
    RegisterServices();
    OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );
//    Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE("com.sun.star.office.OfficeWrapper" ) ), UNO_QUERY );
    SfxApplicationClass::Main();
//    xWrapper->dispose();

    if( pWrapper!=NULL)
    {
        delete pWrapper;
        pWrapper=NULL;
    }

    delete pPathOptions;
    utl::ConfigManager::RemoveConfigManager();
}

void Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )
{
    OFF_APP()->SystemSettingsChanging( rSettings, pFrame );
}

<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli

This file is part of Abaclade.

Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::_str_to_str_backend

namespace abc {

void _str_to_str_backend::set_format(istr const & sFormat) {
   ABC_TRACE_FUNC(this, sFormat);

   auto it(sFormat.cbegin());

   // Add parsing of the format string here.

   // If we still have any characters, they are garbage.
   if (it != sFormat.cend()) {
      ABC_THROW(syntax_error, (
         SL("unexpected character"), sFormat, static_cast<unsigned>(it - sFormat.cend())
      ));
   }
}

void _str_to_str_backend::write(
   void const * p, size_t cb, text::encoding enc, io::text::writer * ptwOut
) {
   ABC_TRACE_FUNC(this, p, cb, enc, ptwOut);

   ptwOut->write_binary(p, cb, enc);
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::str_base

namespace abc {

char_t const str_base::smc_chNul('\0');

char_t const * str_base::_advance_char_ptr(char_t const * pch, ptrdiff_t i, bool bIndex) const {
   ABC_TRACE_FUNC(this, pch, i, bIndex);

   char_t const * pchBegin(chars_begin()), * pchEnd(chars_end());
   ptrdiff_t iOrig(i);

   // If i is positive, move forward.
   for (; i > 0 && pch < pchEnd; --i) {
      // Find the next code point start, skipping any trail characters.
      pch += text::host_char_traits::lead_char_to_codepoint_size(*pch);
   }
   // If i is negative, move backwards.
   for (; i < 0 && pch > pchBegin; ++i) {
      // Moving to the previous code point requires finding the previous non-trail character.
      while (text::host_char_traits::is_trail_char(*--pch)) {
         ;
      }
   }

   // Verify that the pointer is still within range: that’s not the case if we left either for loop
   // before i reached 0, or if the pointer was invalid on entry (e.g. accessing istr()[0]).
   if (i != 0 || pch < pchBegin || pch > pchEnd || (bIndex && pch == pchEnd)) {
      if (bIndex) {
         ABC_THROW(index_error, (iOrig));
      } else {
         ABC_THROW(pointer_iterator_error, (pchBegin, pchEnd, pch));
      }
   }

   // Return the resulting pointer.
   return pch;
}

str_base::c_str_pointer str_base::c_str() const {
   ABC_TRACE_FUNC(this);

   if (m_bNulT) {
      // The string already includes a NUL terminator, so we can simply return the same array.
      return c_str_pointer(chars_begin(), c_str_pointer::deleter_type(false));
   } else if (size_t cch = size_in_chars()) {
      // The string is not empty but lacks a NUL terminator: create a temporary copy that includes a
      // NUL, and return it.
      c_str_pointer psz(
         memory::alloc<char_t const []>(cch + 1 /*NUL*/).release(),
         c_str_pointer::deleter_type(true)
      );
      char_t * pch(const_cast<char_t *>(psz.get()));
      memory::copy(pch, chars_begin(), cch);
      memory::clear(pch + cch);
      return std::move(psz);
   } else {
      // The string is empty, so a static NUL character will suffice.
      return c_str_pointer(&smc_chNul, c_str_pointer::deleter_type(false));
   }
}

dmvector<uint8_t> str_base::encode(text::encoding enc, bool bNulT) const {
   ABC_TRACE_FUNC(this, enc, bNulT);

   dmvector<uint8_t> vb;
   size_t cbChar, cbUsed, cbStr(size_in_bytes());
   if (enc == abc::text::encoding::host) {
      // Optimal case: no transcoding necessary.
      cbChar = sizeof(char_t);
      // Enlarge vb as necessary, then copy to it the contents of the string buffer.
      vb.set_capacity(cbStr + (bNulT ? sizeof(char_t) : 0), false);
      memory::copy(vb.begin().base(), _raw_trivial_vextr_impl::begin<uint8_t>(), cbStr);
      cbUsed = cbStr;
   } else {
      cbChar = text::get_encoding_size(enc);
      void const * pStr(chars_begin());
      // Calculate the size required, then resize vb accorgingly.
      cbUsed = abc::text::transcode(true, abc::text::encoding::host, &pStr, &cbStr, enc);
      vb.set_capacity(cbUsed + (bNulT ? cbChar : 0), false);
      // Transcode the string into vb.
      void * pBuf(vb.begin().base());
      // Re-assign to cbUsed because transcode() will set *(&cbUsed) to 0.
      cbUsed = abc::text::transcode(
         true, abc::text::encoding::host, &pStr, &cbStr, enc, &pBuf, &cbUsed
      );
   }
   if (bNulT) {
      memory::clear(vb.begin().base() + cbUsed, cbChar);
      cbUsed += cbChar;
   }
   // Assign the vector its size, and return it.
   vb.set_size(cbUsed);
   return std::move(vb);
}

bool str_base::ends_with(istr const & s) const {
   ABC_TRACE_FUNC(this, s);

   char_t const * pchStart(chars_end() - s.size_in_chars());
   return pchStart >= chars_begin() && text::str_traits::compare(
      pchStart, chars_end(), s.chars_begin(), s.chars_end()
   ) == 0;
}

str_base::const_iterator str_base::find(char_t chNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, chNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_char(itWhence.base(), chars_end(), chNeedle), this);
}
str_base::const_iterator str_base::find(char32_t chNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, chNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_char(itWhence.base(), chars_end(), chNeedle), this);
}
str_base::const_iterator str_base::find(istr const & sNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, sNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_substr(
      itWhence.base(), chars_end(), sNeedle.chars_begin(), sNeedle.chars_end()
   ), this);
}

str_base::const_iterator str_base::find_last(char_t chNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, chNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_char_last(
      chars_begin(), itWhence.base(), chNeedle
   ), this);
}
str_base::const_iterator str_base::find_last(char32_t chNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, chNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_char_last(
      chars_begin(), itWhence.base(), chNeedle
   ), this);
}
str_base::const_iterator str_base::find_last(istr const & sNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, sNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_substr_last(
      chars_begin(), itWhence.base(), sNeedle.chars_begin(), sNeedle.chars_end()
   ), this);
}

bool str_base::starts_with(istr const & s) const {
   ABC_TRACE_FUNC(this, s);

   char_t const * pchEnd(chars_begin() + s.size_in_chars());
   return pchEnd <= chars_end() && text::str_traits::compare(
      chars_begin(), pchEnd, s.chars_begin(), s.chars_end()
   ) == 0;
}

str_base::const_iterator str_base::translate_index(intptr_t ich) const {
   ABC_TRACE_FUNC(this, ich);

   const_iterator it, itLoopEnd;
   int iDelta;
   if (ich >= 0) {
      // The character index is non-negative: assume it’s faster to reach the corresponding code
      // point index by starting from the beginning.
      it = begin();
      itLoopEnd = end();
      iDelta = 1;
   } else {
      // The character index is negative: assume it’s faster to reach the corresponding code point
      // index by starting from the end.
      it = end();
      itLoopEnd = begin();
      iDelta = -1;
   }
   while (ich && it != itLoopEnd) {
      ich -= iDelta;
      it += iDelta;
   }
   return std::move(it);
}

std::pair<str_base::const_iterator, str_base::const_iterator> str_base::translate_range(
   intptr_t ichBegin, intptr_t ichEnd
) const {
   ABC_TRACE_FUNC(this, ichBegin, ichEnd);

   auto itBegin(translate_index(ichBegin));
   auto itEnd(translate_index(ichEnd));
   // If the interval is empty, return [end(), end()) .
   if (itBegin >= itEnd) {
      return std::pair<const_iterator, const_iterator>(end(), end());
   }
   // Return the constructed interval.
   return std::pair<const_iterator, const_iterator>(itBegin, itEnd);
}

} //namespace abc

namespace std {

// Implementation based on the Fowler/Noll/Vo variant 1a (FNV-1a) algorithm. See
// <http://www.isthe.com/chongo/tech/comp/fnv/> for details.
//
// The bases are calculated by src/fnv_hash_basis.py.
size_t hash<abc::str_base>::operator()(abc::str_base const & s) const {
   ABC_TRACE_FUNC(this, s);

   static_assert(
      sizeof(size_t) * 8 == ABC_HOST_WORD_SIZE,
      "unexpected sizeof(size_t) will break FNV prime/basis selection"
   );
#if ABC_HOST_WORD_SIZE == 16
   size_t const c_iFNVPrime(0x1135);
   size_t const c_iFNVBasis(16635u);
#elif ABC_HOST_WORD_SIZE == 32
   size_t const c_iFNVPrime(0x01000193);
   size_t const c_iFNVBasis(2166136261u);
#elif ABC_HOST_WORD_SIZE == 64
   size_t const c_iFNVPrime(0x00000100000001b3);
   size_t const c_iFNVBasis(14695981039346656037u);
#endif
   size_t iHash(c_iFNVBasis);
   for (auto it(s.cbegin()), itEnd(s.cend()); it != itEnd; ++it) {
      iHash ^= static_cast<size_t>(*it);
      iHash *= c_iFNVPrime;
   }
   return iHash;
}

} //namespace std

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::mstr

namespace abc {

void mstr::_replace_codepoint(char_t * pch, char_t chNew) {
   ABC_TRACE_FUNC(pch, chNew);

   size_t cbRemove(sizeof(char_t) * text::host_char_traits::lead_char_to_codepoint_size(*pch));
   uintptr_t ich(static_cast<uintptr_t>(pch - chars_begin()));
   _raw_trivial_vextr_impl::insert_remove(ich, nullptr, sizeof(char_t), cbRemove);
   // insert_remove() may have switched string buffer, so recalculate pch now.
   pch = chars_begin() + ich;
   // At this point, insert_remove() validated pch.
   *pch = chNew;
}
void mstr::_replace_codepoint(char_t * pch, char32_t chNew) {
   ABC_TRACE_FUNC(pch, chNew);

   size_t cbInsert(sizeof(char_t) * text::host_char_traits::codepoint_size(chNew));
   size_t cbRemove(sizeof(char_t) * text::host_char_traits::lead_char_to_codepoint_size(*pch));
   uintptr_t ich(static_cast<uintptr_t>(pch - chars_begin()));
   _raw_trivial_vextr_impl::insert_remove(ich, nullptr, cbInsert, cbRemove);
   // insert_remove() may have switched string buffer, so recalculate pch now.
   pch = chars_begin() + ich;
   // At this point, insert_remove() validated pch and codepoint_size() validated chNew; this means
   // that there’s nothing that could go wrong here leaving us in an inconsistent state.
   text::host_char_traits::traits_base::codepoint_to_chars(chNew, pch);
}

void mstr::set_from(std::function<size_t (char_t * pch, size_t cchMax)> const & fnRead) {
   // The initial size avoids a few reallocations (* smc_iGrowthRate ** 2).
   // Multiplying by smc_iGrowthRate should guarantee that set_capacity() will allocate exactly the
   // requested number of characters, eliminating the need to query back with capacity().
   size_t cchRet, cchMax(smc_cbCapacityMin * smc_iGrowthRate);
   do {
      cchMax *= smc_iGrowthRate;
      set_capacity(cchMax, false);
      cchRet = fnRead(chars_begin(), cchMax);
   } while (cchRet >= cchMax);
   // Finalize the length.
   set_size_in_chars(cchRet);
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////

<commit_msg>Add missing ABC_TRACE_FUNC() statement<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2010, 2011, 2012, 2013, 2014
Raffaello D. Di Napoli

This file is part of Abaclade.

Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

Abaclade 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 Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::_str_to_str_backend

namespace abc {

void _str_to_str_backend::set_format(istr const & sFormat) {
   ABC_TRACE_FUNC(this, sFormat);

   auto it(sFormat.cbegin());

   // Add parsing of the format string here.

   // If we still have any characters, they are garbage.
   if (it != sFormat.cend()) {
      ABC_THROW(syntax_error, (
         SL("unexpected character"), sFormat, static_cast<unsigned>(it - sFormat.cend())
      ));
   }
}

void _str_to_str_backend::write(
   void const * p, size_t cb, text::encoding enc, io::text::writer * ptwOut
) {
   ABC_TRACE_FUNC(this, p, cb, enc, ptwOut);

   ptwOut->write_binary(p, cb, enc);
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::str_base

namespace abc {

char_t const str_base::smc_chNul('\0');

char_t const * str_base::_advance_char_ptr(char_t const * pch, ptrdiff_t i, bool bIndex) const {
   ABC_TRACE_FUNC(this, pch, i, bIndex);

   char_t const * pchBegin(chars_begin()), * pchEnd(chars_end());
   ptrdiff_t iOrig(i);

   // If i is positive, move forward.
   for (; i > 0 && pch < pchEnd; --i) {
      // Find the next code point start, skipping any trail characters.
      pch += text::host_char_traits::lead_char_to_codepoint_size(*pch);
   }
   // If i is negative, move backwards.
   for (; i < 0 && pch > pchBegin; ++i) {
      // Moving to the previous code point requires finding the previous non-trail character.
      while (text::host_char_traits::is_trail_char(*--pch)) {
         ;
      }
   }

   // Verify that the pointer is still within range: that’s not the case if we left either for loop
   // before i reached 0, or if the pointer was invalid on entry (e.g. accessing istr()[0]).
   if (i != 0 || pch < pchBegin || pch > pchEnd || (bIndex && pch == pchEnd)) {
      if (bIndex) {
         ABC_THROW(index_error, (iOrig));
      } else {
         ABC_THROW(pointer_iterator_error, (pchBegin, pchEnd, pch));
      }
   }

   // Return the resulting pointer.
   return pch;
}

str_base::c_str_pointer str_base::c_str() const {
   ABC_TRACE_FUNC(this);

   if (m_bNulT) {
      // The string already includes a NUL terminator, so we can simply return the same array.
      return c_str_pointer(chars_begin(), c_str_pointer::deleter_type(false));
   } else if (size_t cch = size_in_chars()) {
      // The string is not empty but lacks a NUL terminator: create a temporary copy that includes a
      // NUL, and return it.
      c_str_pointer psz(
         memory::alloc<char_t const []>(cch + 1 /*NUL*/).release(),
         c_str_pointer::deleter_type(true)
      );
      char_t * pch(const_cast<char_t *>(psz.get()));
      memory::copy(pch, chars_begin(), cch);
      memory::clear(pch + cch);
      return std::move(psz);
   } else {
      // The string is empty, so a static NUL character will suffice.
      return c_str_pointer(&smc_chNul, c_str_pointer::deleter_type(false));
   }
}

dmvector<uint8_t> str_base::encode(text::encoding enc, bool bNulT) const {
   ABC_TRACE_FUNC(this, enc, bNulT);

   dmvector<uint8_t> vb;
   size_t cbChar, cbUsed, cbStr(size_in_bytes());
   if (enc == abc::text::encoding::host) {
      // Optimal case: no transcoding necessary.
      cbChar = sizeof(char_t);
      // Enlarge vb as necessary, then copy to it the contents of the string buffer.
      vb.set_capacity(cbStr + (bNulT ? sizeof(char_t) : 0), false);
      memory::copy(vb.begin().base(), _raw_trivial_vextr_impl::begin<uint8_t>(), cbStr);
      cbUsed = cbStr;
   } else {
      cbChar = text::get_encoding_size(enc);
      void const * pStr(chars_begin());
      // Calculate the size required, then resize vb accorgingly.
      cbUsed = abc::text::transcode(true, abc::text::encoding::host, &pStr, &cbStr, enc);
      vb.set_capacity(cbUsed + (bNulT ? cbChar : 0), false);
      // Transcode the string into vb.
      void * pBuf(vb.begin().base());
      // Re-assign to cbUsed because transcode() will set *(&cbUsed) to 0.
      cbUsed = abc::text::transcode(
         true, abc::text::encoding::host, &pStr, &cbStr, enc, &pBuf, &cbUsed
      );
   }
   if (bNulT) {
      memory::clear(vb.begin().base() + cbUsed, cbChar);
      cbUsed += cbChar;
   }
   // Assign the vector its size, and return it.
   vb.set_size(cbUsed);
   return std::move(vb);
}

bool str_base::ends_with(istr const & s) const {
   ABC_TRACE_FUNC(this, s);

   char_t const * pchStart(chars_end() - s.size_in_chars());
   return pchStart >= chars_begin() && text::str_traits::compare(
      pchStart, chars_end(), s.chars_begin(), s.chars_end()
   ) == 0;
}

str_base::const_iterator str_base::find(char_t chNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, chNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_char(itWhence.base(), chars_end(), chNeedle), this);
}
str_base::const_iterator str_base::find(char32_t chNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, chNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_char(itWhence.base(), chars_end(), chNeedle), this);
}
str_base::const_iterator str_base::find(istr const & sNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, sNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_substr(
      itWhence.base(), chars_end(), sNeedle.chars_begin(), sNeedle.chars_end()
   ), this);
}

str_base::const_iterator str_base::find_last(char_t chNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, chNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_char_last(
      chars_begin(), itWhence.base(), chNeedle
   ), this);
}
str_base::const_iterator str_base::find_last(char32_t chNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, chNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_char_last(
      chars_begin(), itWhence.base(), chNeedle
   ), this);
}
str_base::const_iterator str_base::find_last(istr const & sNeedle, const_iterator itWhence) const {
   ABC_TRACE_FUNC(this, sNeedle, itWhence);

   validate_pointer(itWhence.base());
   return const_iterator(text::str_traits::find_substr_last(
      chars_begin(), itWhence.base(), sNeedle.chars_begin(), sNeedle.chars_end()
   ), this);
}

bool str_base::starts_with(istr const & s) const {
   ABC_TRACE_FUNC(this, s);

   char_t const * pchEnd(chars_begin() + s.size_in_chars());
   return pchEnd <= chars_end() && text::str_traits::compare(
      chars_begin(), pchEnd, s.chars_begin(), s.chars_end()
   ) == 0;
}

str_base::const_iterator str_base::translate_index(intptr_t ich) const {
   ABC_TRACE_FUNC(this, ich);

   const_iterator it, itLoopEnd;
   int iDelta;
   if (ich >= 0) {
      // The character index is non-negative: assume it’s faster to reach the corresponding code
      // point index by starting from the beginning.
      it = begin();
      itLoopEnd = end();
      iDelta = 1;
   } else {
      // The character index is negative: assume it’s faster to reach the corresponding code point
      // index by starting from the end.
      it = end();
      itLoopEnd = begin();
      iDelta = -1;
   }
   while (ich && it != itLoopEnd) {
      ich -= iDelta;
      it += iDelta;
   }
   return std::move(it);
}

std::pair<str_base::const_iterator, str_base::const_iterator> str_base::translate_range(
   intptr_t ichBegin, intptr_t ichEnd
) const {
   ABC_TRACE_FUNC(this, ichBegin, ichEnd);

   auto itBegin(translate_index(ichBegin));
   auto itEnd(translate_index(ichEnd));
   // If the interval is empty, return [end(), end()) .
   if (itBegin >= itEnd) {
      return std::pair<const_iterator, const_iterator>(end(), end());
   }
   // Return the constructed interval.
   return std::pair<const_iterator, const_iterator>(itBegin, itEnd);
}

} //namespace abc

namespace std {

// Implementation based on the Fowler/Noll/Vo variant 1a (FNV-1a) algorithm. See
// <http://www.isthe.com/chongo/tech/comp/fnv/> for details.
//
// The bases are calculated by src/fnv_hash_basis.py.
size_t hash<abc::str_base>::operator()(abc::str_base const & s) const {
   ABC_TRACE_FUNC(this, s);

   static_assert(
      sizeof(size_t) * 8 == ABC_HOST_WORD_SIZE,
      "unexpected sizeof(size_t) will break FNV prime/basis selection"
   );
#if ABC_HOST_WORD_SIZE == 16
   size_t const c_iFNVPrime(0x1135);
   size_t const c_iFNVBasis(16635u);
#elif ABC_HOST_WORD_SIZE == 32
   size_t const c_iFNVPrime(0x01000193);
   size_t const c_iFNVBasis(2166136261u);
#elif ABC_HOST_WORD_SIZE == 64
   size_t const c_iFNVPrime(0x00000100000001b3);
   size_t const c_iFNVBasis(14695981039346656037u);
#endif
   size_t iHash(c_iFNVBasis);
   for (auto it(s.cbegin()), itEnd(s.cend()); it != itEnd; ++it) {
      iHash ^= static_cast<size_t>(*it);
      iHash *= c_iFNVPrime;
   }
   return iHash;
}

} //namespace std

////////////////////////////////////////////////////////////////////////////////////////////////////
// abc::mstr

namespace abc {

void mstr::_replace_codepoint(char_t * pch, char_t chNew) {
   ABC_TRACE_FUNC(pch, chNew);

   size_t cbRemove(sizeof(char_t) * text::host_char_traits::lead_char_to_codepoint_size(*pch));
   uintptr_t ich(static_cast<uintptr_t>(pch - chars_begin()));
   _raw_trivial_vextr_impl::insert_remove(ich, nullptr, sizeof(char_t), cbRemove);
   // insert_remove() may have switched string buffer, so recalculate pch now.
   pch = chars_begin() + ich;
   // At this point, insert_remove() validated pch.
   *pch = chNew;
}
void mstr::_replace_codepoint(char_t * pch, char32_t chNew) {
   ABC_TRACE_FUNC(pch, chNew);

   size_t cbInsert(sizeof(char_t) * text::host_char_traits::codepoint_size(chNew));
   size_t cbRemove(sizeof(char_t) * text::host_char_traits::lead_char_to_codepoint_size(*pch));
   uintptr_t ich(static_cast<uintptr_t>(pch - chars_begin()));
   _raw_trivial_vextr_impl::insert_remove(ich, nullptr, cbInsert, cbRemove);
   // insert_remove() may have switched string buffer, so recalculate pch now.
   pch = chars_begin() + ich;
   // At this point, insert_remove() validated pch and codepoint_size() validated chNew; this means
   // that there’s nothing that could go wrong here leaving us in an inconsistent state.
   text::host_char_traits::traits_base::codepoint_to_chars(chNew, pch);
}

void mstr::set_from(std::function<size_t (char_t * pch, size_t cchMax)> const & fnRead) {
   ABC_TRACE_FUNC(this/*, fnRead*/);

   // The initial size avoids a few reallocations (* smc_iGrowthRate ** 2).
   // Multiplying by smc_iGrowthRate should guarantee that set_capacity() will allocate exactly the
   // requested number of characters, eliminating the need to query back with capacity().
   size_t cchRet, cchMax(smc_cbCapacityMin * smc_iGrowthRate);
   do {
      cchMax *= smc_iGrowthRate;
      set_capacity(cchMax, false);
      cchRet = fnRead(chars_begin(), cchMax);
   } while (cchRet >= cchMax);
   // Finalize the length.
   set_size_in_chars(cchRet);
}

} //namespace abc

////////////////////////////////////////////////////////////////////////////////////////////////////

<|endoftext|>


<commit_before>/*
* Copyright  2015 Cask Data, 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 "stdafx.h"
#include "NoSchemaColumnsDataReader.h"

Cask::CdapOdbc::NoSchemaColumnsDataReader::NoSchemaColumnsDataReader(const std::wstring& tableName, const QueryResult& queryResult)
  : tableName(tableName)
  , queryResult(queryResult)
  , currentRowIndex(-1) {
}

bool Cask::CdapOdbc::NoSchemaColumnsDataReader::read() {
  ++this->currentRowIndex;
  return this->currentRowIndex < 3;
}

void Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnValue(const ColumnBinding& binding) {
  static std::array<const wchar_t*, 3> names = { L"ts", L"headers", L"body" };

  switch (binding.getColumnNumber()) {
    case 1: // TABLE_CAT
    case 2: // TABLE_SCHEM
    case 9: // DECIMAL_DIGITS
    case 12: // REMARKS
    case 13: // COLUMN_DEF
    case 15: // SQL_DATETIME_SUB
    case 16: // CHAR_OCTET_LENGTH
      this->fetchNull(binding);
      break;
    case 3: // TABLE_NAME
      this->fetchVarchar(this->tableName.c_str(), binding);
      break;
    case 4: // COLUMN_NAME
			if (binding.getTargetType() == SQL_WCHAR) {
				this->fetchWVarchar(names[this->currentRowIndex], binding);
			}
			else {
				this->fetchVarchar(names[this->currentRowIndex], binding);
			}
      break;
    case 5: // DATA_TYPE
    case 14: // SQL_DATA_TYPE
      this->fetchSmallint(SQL_CHAR, binding);
      break;
    case 6: // TYPE_NAME
      this->fetchVarchar(L"string", binding);
      break;
    case 7: // COLUMN_SIZE
      this->fetchInt(std::numeric_limits<std::int32_t>::max(), binding);
      break;
    case 8: // BUFFER_LENGTH
      this->fetchInt(std::numeric_limits<std::int32_t>::max(), binding);
      break;
    case 10: // NUM_PREC_RADIX
      this->fetchSmallint(0, binding);
      break;
    case 11: // NULLABLE
      this->fetchSmallint(SQL_NULLABLE, binding);
      break;
    case 17: // ORDINAL_POSITION
      this->fetchInt(this->currentRowIndex + 1, binding);
      break;
    case 18: // IS_NULLABLE
      this->fetchVarchar(L"YES", binding);
      break;
  }
}

short Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnCount() const {
  return 18;
}

std::unique_ptr<Cask::CdapOdbc::ColumnInfo> Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnInfo(short columnNumber) const {
  return std::unique_ptr<ColumnInfo>();
}
<commit_msg>Varchar/WVarchar check in NoSchemaColumnsDataReader<commit_after>/*
* Copyright  2015 Cask Data, 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 "stdafx.h"
#include "NoSchemaColumnsDataReader.h"

Cask::CdapOdbc::NoSchemaColumnsDataReader::NoSchemaColumnsDataReader(const std::wstring& tableName, const QueryResult& queryResult)
  : tableName(tableName)
  , queryResult(queryResult)
  , currentRowIndex(-1) {
}

bool Cask::CdapOdbc::NoSchemaColumnsDataReader::read() {
  ++this->currentRowIndex;
  return this->currentRowIndex < 3;
}

void Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnValue(const ColumnBinding& binding) {
  static std::array<const wchar_t*, 3> names = { L"ts", L"headers", L"body" };

  switch (binding.getColumnNumber()) {
    case 1: // TABLE_CAT
    case 2: // TABLE_SCHEM
    case 9: // DECIMAL_DIGITS
    case 12: // REMARKS
    case 13: // COLUMN_DEF
    case 15: // SQL_DATETIME_SUB
    case 16: // CHAR_OCTET_LENGTH
      this->fetchNull(binding);
      break;
    case 3: // TABLE_NAME
      if (binding.getTargetType() == SQL_WCHAR) {
        this->fetchWVarchar(this->tableName.c_str(), binding);
      }
      else {
        this->fetchVarchar(this->tableName.c_str(), binding);
      }
      break;
    case 4: // COLUMN_NAME
			if (binding.getTargetType() == SQL_WCHAR) {
				this->fetchWVarchar(names[this->currentRowIndex], binding);
			}
			else {
				this->fetchVarchar(names[this->currentRowIndex], binding);
			}
      break;
    case 5: // DATA_TYPE
    case 14: // SQL_DATA_TYPE
      this->fetchSmallint(SQL_CHAR, binding);
      break;
    case 6: // TYPE_NAME
      if (binding.getTargetType() == SQL_WCHAR) {
        this->fetchWVarchar(L"string", binding);
      }
      else {
        this->fetchVarchar(L"string", binding);
      }
      break;
    case 7: // COLUMN_SIZE
      this->fetchInt(std::numeric_limits<std::int32_t>::max(), binding);
      break;
    case 8: // BUFFER_LENGTH
      this->fetchInt(std::numeric_limits<std::int32_t>::max(), binding);
      break;
    case 10: // NUM_PREC_RADIX
      this->fetchSmallint(0, binding);
      break;
    case 11: // NULLABLE
      this->fetchSmallint(SQL_NULLABLE, binding);
      break;
    case 17: // ORDINAL_POSITION
      this->fetchInt(this->currentRowIndex + 1, binding);
      break;
    case 18: // IS_NULLABLE
      if (binding.getTargetType() == SQL_WCHAR) {
        this->fetchWVarchar(L"YES", binding);
      }
      else {
        this->fetchVarchar(L"YES", binding);
      }
      break;
  }
}

short Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnCount() const {
  return 18;
}

std::unique_ptr<Cask::CdapOdbc::ColumnInfo> Cask::CdapOdbc::NoSchemaColumnsDataReader::getColumnInfo(short columnNumber) const {
  return std::unique_ptr<ColumnInfo>();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: b2dquadraticbezier.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 20:24:47 $
 *
 *  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 _BGFX_CURVE_B2DQUADRATICBEZIER_HXX
#define _BGFX_CURVE_B2DQUADRATICBEZIER_HXX

#ifndef _BGFX_POINT_B2DPOINT_HXX
#include <basegfx/point/b2dpoint.hxx>
#endif

//////////////////////////////////////////////////////////////////////////////

namespace basegfx
{
    class B2DQuadraticBezier
    {
        ::basegfx::B2DPoint                         maStartPoint;
        ::basegfx::B2DPoint                         maEndPoint;
        ::basegfx::B2DPoint                         maControlPoint;

    public:
        B2DQuadraticBezier();
        B2DQuadraticBezier(const B2DQuadraticBezier& rBezier);
        B2DQuadraticBezier(const ::basegfx::B2DPoint& rStart, const ::basegfx::B2DPoint& rEnd);
        B2DQuadraticBezier(const ::basegfx::B2DPoint& rStart,
            const ::basegfx::B2DPoint& rControlPoint, const ::basegfx::B2DPoint& rEnd);
        ~B2DQuadraticBezier();

        // assignment operator
        B2DQuadraticBezier& operator=(const B2DQuadraticBezier& rBezier);

        // compare operators
        bool operator==(const B2DQuadraticBezier& rBezier) const;
        bool operator!=(const B2DQuadraticBezier& rBezier) const;

        // test if control point is placed on the edge
        bool isBezier() const;

        // data interface
        ::basegfx::B2DPoint getStartPoint() const { return maStartPoint; }
        void setStartPoint(const ::basegfx::B2DPoint& rValue) { maStartPoint = rValue; }

        ::basegfx::B2DPoint getEndPoint() const { return maEndPoint; }
        void setEndPoint(const ::basegfx::B2DPoint& rValue) { maEndPoint = rValue; }

        ::basegfx::B2DPoint getControlPoint() const { return maControlPoint; }
        void setControlPoint(const ::basegfx::B2DPoint& rValue) { maControlPoint = rValue; }
    };
} // end of namespace basegfx

#endif /* _BGFX_CURVE_B2DQUADRATICBEZIER_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.7.88); FILE MERGED 2008/04/01 10:48:07 thb 1.7.88.2: #i85898# Stripping all external header guards 2008/03/28 16:05:38 rt 1.7.88.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: b2dquadraticbezier.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _BGFX_CURVE_B2DQUADRATICBEZIER_HXX
#define _BGFX_CURVE_B2DQUADRATICBEZIER_HXX

#include <basegfx/point/b2dpoint.hxx>

//////////////////////////////////////////////////////////////////////////////

namespace basegfx
{
    class B2DQuadraticBezier
    {
        ::basegfx::B2DPoint                         maStartPoint;
        ::basegfx::B2DPoint                         maEndPoint;
        ::basegfx::B2DPoint                         maControlPoint;

    public:
        B2DQuadraticBezier();
        B2DQuadraticBezier(const B2DQuadraticBezier& rBezier);
        B2DQuadraticBezier(const ::basegfx::B2DPoint& rStart, const ::basegfx::B2DPoint& rEnd);
        B2DQuadraticBezier(const ::basegfx::B2DPoint& rStart,
            const ::basegfx::B2DPoint& rControlPoint, const ::basegfx::B2DPoint& rEnd);
        ~B2DQuadraticBezier();

        // assignment operator
        B2DQuadraticBezier& operator=(const B2DQuadraticBezier& rBezier);

        // compare operators
        bool operator==(const B2DQuadraticBezier& rBezier) const;
        bool operator!=(const B2DQuadraticBezier& rBezier) const;

        // test if control point is placed on the edge
        bool isBezier() const;

        // data interface
        ::basegfx::B2DPoint getStartPoint() const { return maStartPoint; }
        void setStartPoint(const ::basegfx::B2DPoint& rValue) { maStartPoint = rValue; }

        ::basegfx::B2DPoint getEndPoint() const { return maEndPoint; }
        void setEndPoint(const ::basegfx::B2DPoint& rValue) { maEndPoint = rValue; }

        ::basegfx::B2DPoint getControlPoint() const { return maControlPoint; }
        void setControlPoint(const ::basegfx::B2DPoint& rValue) { maControlPoint = rValue; }
    };
} // end of namespace basegfx

#endif /* _BGFX_CURVE_B2DQUADRATICBEZIER_HXX */
<|endoftext|>


<commit_before>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
**********************************/

#include "GLContext.h"
#include "ShaderCombinaison.h"
#include "GL.h"
#include "FrameBuffer.h"
#include "Material.h"
#include "VertexArrayObject.h"
#include <n/concurrent/Thread.h>
#include <n/core/Timer.h>

#include <iostream>

namespace n {
namespace graphics {

GLAPIENTRY void debugOut(gl::GLenum, gl::GLenum type, gl::GLuint, gl::GLuint sev, gl::GLsizei len, const char *msg, const void *) {
	if(sev == GL_DEBUG_SEVERITY_NOTIFICATION) {
		return;
	}
	core::String t;
	switch(type) {
		case GL_DEBUG_TYPE_PERFORMANCE:
			t = "[perf]";
		break;
		case GL_DEBUG_TYPE_PORTABILITY:
			t = "[port]";
		break;
		case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
			t = "[depr]";
		break;
		case GL_DEBUG_TYPE_ERROR:
			t = "[err]";
		break;
		default:
		break;
	}

	std::cerr<<std::endl<<"[GL]"<<(sev == GL_DEBUG_SEVERITY_HIGH ? "[HIGH]" : "")<<t<<" "<<core::String(msg, len)<<std::endl;
}

GLContext *GLContext::getContext() {
	static GLContext *ct = 0;
	if(!ct) {
		ct = new GLContext();
		ShaderProgram(ct->program).bind();
	}
	return ct;
}

void GLContext::flush() {
	gl::glFlush();
}

void GLContext::addGLTask(const core::Functor<void()> &f) {
	tasks.queue(f);
}

bool GLContext::processTasks() {
	core::Option<core::Functor<void()>> tsk = tasks.tryDequeue();
	if(tsk) {
		tsk.get()();
		return true;
	}
	return false;
}

void GLContext::finishTasks() {
	core::List<core::Functor<void()>> tsk = tasks.getAndClear();
	for(const core::Functor<void()> &f : tsk) {
		f();
	}
}

GLContext::GLContext() : shader(0), program(ShaderProgram::getNullProgram()), frameBuffer(0), material(0), viewport(800, 600), screen(0) {
	if(concurrent::Thread::getCurrent()) {
		fatal("n::graphics::Context not created on main thread.");
	}
	gl::glewExperimental = true;
	if(gl::glewInit() != GLEW_OK) {
		fatal("Unable to initialize glew.");
	}
	std::cout<<"Running on "<<gl::glGetString(GL_VENDOR)<<" "<<gl::glGetString(GL_RENDERER)<<" using GL "<<gl::glGetString(GL_VERSION);
	#ifdef N_32BITS
	std::cout<<" (32 bits)";
	#endif
	std::cout<<std::endl;

	//gl::glEnable(GL_TEXTURE_2D);
	//gl::glEnable(GL_CULL_FACE);
	//gl::glEnable(GL_DEPTH_TEST);

	gl::glViewport(0, 0, viewport.x(), viewport.y());

	for(uint i = 0; i != Max; i++) {
		hwInts[i] = 0;
	}

	gl::glGetIntegerv(GL_MAX_DRAW_BUFFERS, &hwInts[MaxFboAttachements]);
	gl::glGetIntegerv(GL_MAX_TEXTURE_UNITS, &hwInts[MaxTextures]);
	gl::glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &hwInts[MaxVertexAttribs]);

	if(hwInts[MaxVertexAttribs] <= 4) {
		fatal("No enought vertex attribs.");
	}

	#define CHECK_TEX_FORMAT(frm) if(!Texture::isHWSupported(ImageFormat::frm)) { fatal(("Texture format " + core::String(#frm) + " not supported").toChar()); }

	CHECK_TEX_FORMAT(RGBA32F);
	CHECK_TEX_FORMAT(RGBA16);
	CHECK_TEX_FORMAT(RG16);
	CHECK_TEX_FORMAT(F32);
	CHECK_TEX_FORMAT(Depth32);

	#undef CHECK_TEX_FORMAT

	gl::glGetError();

	gl::glDebugMessageCallback(&debugOut, 0);
	gl::glEnable(GL_DEBUG_OUTPUT);
}

GLContext::~GLContext() {
	delete screen;
	finishTasks();
}

void GLContext::setDebugEnabled(bool deb) {
	if(deb) {
		gl::glEnable(GL_DEBUG_OUTPUT);
	} else {
		gl::glDisable(GL_DEBUG_OUTPUT);
	}
}

void GLContext::setViewport(const math::Vec2ui &v) {
	viewport = v;
	if(!frameBuffer) {
		gl::glViewport(0, 0, viewport.x(), viewport.y());
	}
}

math::Vec2ui GLContext::getViewport() const {
	return frameBuffer ? frameBuffer->getSize() : viewport;
}

bool GLContext::checkGLError() {
	int error = gl::glGetError();
	if(error) {
		fatal(("Warning : error : " + (error == GL_INVALID_OPERATION ? core::String("INVALID OPERATION") :
			(error == GL_INVALID_ENUM ? core::String("INVALID ENUM") :
			(error == GL_INVALID_VALUE ? core::String("INVALID VALUE") :
			(error == GL_OUT_OF_MEMORY ? core::String("OUT OF MEMORY") : core::String(error)))))).toChar());
		return true; // just in case...
	}
	return false;
}

void GLContext::setModelMatrix(const math::Matrix4<> &m) {
	model = m;
	#ifdef N_USE_MATRIX_BUFFER
	matrixBuffer->set(model, 0);
	matrixBuffer->bind(0);
	#else
	if(shader) {
		shader->setValue("n_ModelMatrix", model);
	}
	#endif
}

void GLContext::setViewMatrix(const math::Matrix4<> &m) {
	if(view == m) {
		return;
	}
	view = m;
	if(shader) {
		shader->setValue("n_ViewMatrix", m);
		shader->setValue("n_ViewProjectionMatrix", projection * m);
	}
}

void GLContext::setProjectionMatrix(const math::Matrix4<> &m) {
	if(projection == m) {
		return;
	}
	projection = m;
	if(shader) {
		shader->setValue("n_ProjectionMatrix", m);
		shader->setValue("n_ViewProjectionMatrix", m * view);
	}
}

const math::Matrix4<> &GLContext::getProjectionMatrix() const {
	return projection;
}

const math::Matrix4<> &GLContext::getViewMatrix() const {
	return view;
}

const math::Matrix4<> &GLContext::getModelMatrix() const {
	return model;
}

const VertexArrayObject<float> &GLContext::getScreen() const {
	if(!screen) {
		screen = new VertexArrayObject<float>(TriangleBuffer<>::getScreen());
	}
	return *screen;
}

}
}

<commit_msg>Added OGL verion check (for 4.3)<commit_after>/*******************************
Copyright (C) 2013-2015 gregoire ANGERAND

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
**********************************/

#include "GLContext.h"
#include "ShaderCombinaison.h"
#include "GL.h"
#include "FrameBuffer.h"
#include "Material.h"
#include "VertexArrayObject.h"
#include <n/concurrent/Thread.h>
#include <n/core/Timer.h>

#include <iostream>

namespace n {
namespace graphics {

GLAPIENTRY void debugOut(gl::GLenum, gl::GLenum type, gl::GLuint, gl::GLuint sev, gl::GLsizei len, const char *msg, const void *) {
	if(sev == GL_DEBUG_SEVERITY_NOTIFICATION) {
		return;
	}
	core::String t;
	switch(type) {
		case GL_DEBUG_TYPE_PERFORMANCE:
			t = "[perf]";
		break;
		case GL_DEBUG_TYPE_PORTABILITY:
			t = "[port]";
		break;
		case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
			t = "[depr]";
		break;
		case GL_DEBUG_TYPE_ERROR:
			t = "[err]";
		break;
		default:
		break;
	}

	std::cerr<<std::endl<<"[GL]"<<(sev == GL_DEBUG_SEVERITY_HIGH ? "[HIGH]" : "")<<t<<" "<<core::String(msg, len)<<std::endl;
}

GLContext *GLContext::getContext() {
	static GLContext *ct = 0;
	if(!ct) {
		ct = new GLContext();
		ShaderProgram(ct->program).bind();
	}
	return ct;
}

void GLContext::flush() {
	gl::glFlush();
}

void GLContext::addGLTask(const core::Functor<void()> &f) {
	tasks.queue(f);
}

bool GLContext::processTasks() {
	core::Option<core::Functor<void()>> tsk = tasks.tryDequeue();
	if(tsk) {
		tsk.get()();
		return true;
	}
	return false;
}

void GLContext::finishTasks() {
	core::List<core::Functor<void()>> tsk = tasks.getAndClear();
	for(const core::Functor<void()> &f : tsk) {
		f();
	}
}

GLContext::GLContext() : shader(0), program(ShaderProgram::getNullProgram()), frameBuffer(0), material(0), viewport(800, 600), screen(0) {
	if(concurrent::Thread::getCurrent()) {
		fatal("n::graphics::Context not created on main thread.");
	}
	gl::glewExperimental = true;
	if(gl::glewInit() != GLEW_OK) {
		fatal("Unable to initialize glew.");
	}
	std::cout<<"Running on "<<gl::glGetString(GL_VENDOR)<<" "<<gl::glGetString(GL_RENDERER)<<" using GL "<<gl::glGetString(GL_VERSION);
	#ifdef N_32BITS
	std::cout<<" (32 bits)";
	#endif
	std::cout<<std::endl;

	int major = 0;
	int minor = 0;
	gl::glGetIntegerv(GL_MAJOR_VERSION, &major);
	gl::glGetIntegerv(GL_MINOR_VERSION, &minor);
	if(major > 4 || (major == 4 && minor > 3)) {
		fatal("This needs OpenGL 4.3 or newer to run");
	}

	//gl::glEnable(GL_TEXTURE_2D);
	//gl::glEnable(GL_CULL_FACE);
	//gl::glEnable(GL_DEPTH_TEST);

	gl::glViewport(0, 0, viewport.x(), viewport.y());

	for(uint i = 0; i != Max; i++) {
		hwInts[i] = 0;
	}

	gl::glGetIntegerv(GL_MAX_DRAW_BUFFERS, &hwInts[MaxFboAttachements]);
	gl::glGetIntegerv(GL_MAX_TEXTURE_UNITS, &hwInts[MaxTextures]);
	gl::glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &hwInts[MaxVertexAttribs]);

	if(hwInts[MaxVertexAttribs] <= 4) {
		fatal("No enought vertex attribs.");
	}

	#define CHECK_TEX_FORMAT(frm) if(!Texture::isHWSupported(ImageFormat::frm)) { fatal(("Texture format " + core::String(#frm) + " not supported").toChar()); }

	CHECK_TEX_FORMAT(RGBA32F);
	CHECK_TEX_FORMAT(RGBA16);
	CHECK_TEX_FORMAT(RG16);
	CHECK_TEX_FORMAT(F32);
	CHECK_TEX_FORMAT(Depth32);

	#undef CHECK_TEX_FORMAT

	gl::glGetError();

	gl::glDebugMessageCallback(&debugOut, 0);
	gl::glEnable(GL_DEBUG_OUTPUT);
}

GLContext::~GLContext() {
	delete screen;
	finishTasks();
}

void GLContext::setDebugEnabled(bool deb) {
	if(deb) {
		gl::glEnable(GL_DEBUG_OUTPUT);
	} else {
		gl::glDisable(GL_DEBUG_OUTPUT);
	}
}

void GLContext::setViewport(const math::Vec2ui &v) {
	viewport = v;
	if(!frameBuffer) {
		gl::glViewport(0, 0, viewport.x(), viewport.y());
	}
}

math::Vec2ui GLContext::getViewport() const {
	return frameBuffer ? frameBuffer->getSize() : viewport;
}

bool GLContext::checkGLError() {
	int error = gl::glGetError();
	if(error) {
		fatal(("Warning : error : " + (error == GL_INVALID_OPERATION ? core::String("INVALID OPERATION") :
			(error == GL_INVALID_ENUM ? core::String("INVALID ENUM") :
			(error == GL_INVALID_VALUE ? core::String("INVALID VALUE") :
			(error == GL_OUT_OF_MEMORY ? core::String("OUT OF MEMORY") : core::String(error)))))).toChar());
		return true; // just in case...
	}
	return false;
}

void GLContext::setModelMatrix(const math::Matrix4<> &m) {
	model = m;
	#ifdef N_USE_MATRIX_BUFFER
	matrixBuffer->set(model, 0);
	matrixBuffer->bind(0);
	#else
	if(shader) {
		shader->setValue("n_ModelMatrix", model);
	}
	#endif
}

void GLContext::setViewMatrix(const math::Matrix4<> &m) {
	if(view == m) {
		return;
	}
	view = m;
	if(shader) {
		shader->setValue("n_ViewMatrix", m);
		shader->setValue("n_ViewProjectionMatrix", projection * m);
	}
}

void GLContext::setProjectionMatrix(const math::Matrix4<> &m) {
	if(projection == m) {
		return;
	}
	projection = m;
	if(shader) {
		shader->setValue("n_ProjectionMatrix", m);
		shader->setValue("n_ViewProjectionMatrix", m * view);
	}
}

const math::Matrix4<> &GLContext::getProjectionMatrix() const {
	return projection;
}

const math::Matrix4<> &GLContext::getViewMatrix() const {
	return view;
}

const math::Matrix4<> &GLContext::getModelMatrix() const {
	return model;
}

const VertexArrayObject<float> &GLContext::getScreen() const {
	if(!screen) {
		screen = new VertexArrayObject<float>(TriangleBuffer<>::getScreen());
	}
	return *screen;
}

}
}

<|endoftext|>


<commit_before>/*
 *            kPPP: A pppd front end for the KDE project
 *
 * $Id$
 *
 *            Copyright (C) 1997 Bernd Johannes Wuebben
 *                   wuebben@math.cornell.edu
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <qlayout.h>
#include <qpainter.h>
#include <kapp.h>
#include <kwm.h>
#include <kglobal.h>
#include <kiconloader.h>

#include "pppdata.h"
#include "pppstatdlg.h"
#include "kpppconfig.h"
#include "iplined.h"
#include <klocale.h>
#include "pppstats.h"

extern PPPData gpppdata;

PPPStats stats;

PPPStatsDlg::PPPStatsDlg(QWidget *parent, const char *name, QWidget *)
  : QWidget(parent, name, 0 )
{
  int i;
  max = 1024;

  setCaption(i18n("kppp Statistics"));
  KWM::setMiniIcon(winId(), kapp->miniIcon());

  QVBoxLayout *tl = new QVBoxLayout(this, 10);
  QGridLayout *l1 = new QGridLayout(4, 4);
  tl->addLayout(l1, 1);
  box = new QGroupBox(i18n("Statistics"), this);
  l1->addMultiCellWidget(box, 0, 3, 0, 3);
  l1->addRowSpacing(0, fontMetrics().lineSpacing() - 10);
  l1->setRowStretch(1, 1);
  l1->setColStretch(1, 1);

  // inner part of the grid
  QVBoxLayout *l11 = new QVBoxLayout;
  l1->addLayout(l11, 1, 1);

  // modem pixmap and IP labels
  QHBoxLayout *l111 = new QHBoxLayout;
  l11->addLayout(l111);

  big_modem_both_pixmap = BarIcon("modemboth");
  big_modem_left_pixmap = BarIcon("modemleft");
  big_modem_right_pixmap = BarIcon("modemright");
  big_modem_none_pixmap = BarIcon("modemnone");

  pixmap_l = new QLabel(this);
  pixmap_l->setMinimumSize(big_modem_both_pixmap.size());
  l111->addWidget(pixmap_l, 1);
  pixmap_l->setAlignment(AlignVCenter|AlignLeft);

  QGridLayout *l1112 = new QGridLayout(3, 2);
  l111->addLayout(l1112);

  ip_address_label1 = new QLabel(this);
  ip_address_label1->setText(i18n("Local Addr:"));

  ip_address_label2 = new IPLineEdit(this);
  ip_address_label2->setFocusPolicy(QWidget::NoFocus);

  ip_address_label3 = new QLabel(this);
  ip_address_label3->setText(i18n("Remote Addr:"));

  ip_address_label4 = new IPLineEdit(this);
  ip_address_label4->setFocusPolicy(QWidget::NoFocus);

  l1112->addWidget(ip_address_label1, 0, 0);
  l1112->addWidget(ip_address_label2, 0, 1);
  l1112->addWidget(ip_address_label3, 1, 0);
  l1112->addWidget(ip_address_label4, 1, 1);

  // consumes space on bottom
  l1112->setRowStretch(2, 1);

  QGridLayout *l112 = new QGridLayout(5, 4);
  l11->addLayout(l112);
  for(i =0 ; i < 5; i++) {
    labela1[i] = new QLabel(this);

    labela2[i] = new QLabel(this);
    labela2[i]->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);

    labelb1[i] = new QLabel(this);

    labelb2[i] = new QLabel(this);
    labelb2[i]->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);
 }

  labela1[0]->setText(i18n("bytes in"));
  labelb1[0]->setText(i18n("bytes out"));

  labela1[1]->setText(i18n("packets in"));
  labelb1[1]->setText(i18n("packets out"));

  labela1[2]->setText(i18n("vjcomp in"));
  labelb1[2]->setText(i18n("vjcomp out"));

  labela1[3]->setText(i18n("vjunc in"));
  labelb1[3]->setText(i18n("vjunc out"));

  labela1[4]->setText(i18n("vjerr"));
  labelb1[4]->setText(i18n("non-vj"));

  for(i = 0; i < 5; i++) {
    labela2[i]->setText("88888888");
    labelb2[i]->setText("88888888");
    labela2[i]->setFixedSize(labela2[i]->sizeHint());
    labelb2[i]->setFixedSize(labelb2[i]->sizeHint());
    labela2[i]->setText("");
    labelb2[i]->setText("");

    // add to layout
    l112->addWidget(labela1[i], i, 0);
    l112->addWidget(labela2[i], i, 1);
    l112->addWidget(labelb1[i], i, 2);
    l112->addWidget(labelb2[i], i, 3);
  }

  l112->setColStretch(1, 1);
  l112->setColStretch(3, 1);

  tl->addSpacing(5);
  QHBoxLayout *l12 = new QHBoxLayout;
  tl->addLayout(l12);
  l12->addStretch(1);

  if(gpppdata.graphingEnabled()) {
    bool dummy;

    gpppdata.graphingOptions(dummy, bg, text, in, out);

    graph = new QFrame(this);
    graph->setFrameStyle(QFrame::Box | QFrame::Sunken);
    l1->addMultiCellWidget(graph, 2, 2, 1, 2);
    graph->setMinimumWidth(300);
    graph->setFixedHeight(76+4);
    graph->setBackgroundColor(bg);
  }

  cancelbutton = new QPushButton(this, "cancelbutton");
  cancelbutton->setText(i18n("Close"));
  cancelbutton->setFocus();
  connect(cancelbutton, SIGNAL(clicked()), this,SLOT(cancel()));
  cancelbutton->setFixedHeight(cancelbutton->sizeHint().height());
  cancelbutton->setMinimumWidth(QMAX(cancelbutton->sizeHint().width(), 70));
  l12->addWidget(cancelbutton);

  if(gpppdata.graphingEnabled()) {
    graphTimer = new QTimer(this);
    connect(graphTimer, SIGNAL(timeout()), SLOT(updateGraph()));
  }

  setFixedSize(sizeHint());

  connect(&stats, SIGNAL(statsChanged(int)), SLOT(paintIcon(int)));
}

PPPStatsDlg::~PPPStatsDlg() {
}

void PPPStatsDlg::cancel() {
  hide();
}

void PPPStatsDlg::take_stats() {
  stats.initStats();
  ips_set = false;
  bin_last = stats.ibytes;
  bout_last = stats.obytes;
  ringIdx = 0;
  for(int i = 0; i < MAX_GRAPH_WIDTH; i++) {
    bin[i] = -1;
    bout[i] = -1;
  }

  update_data();

  stats.start();
  if(gpppdata.graphingEnabled())
    graphTimer->start(GRAPH_UPDATE_TIME);
}

void PPPStatsDlg::stop_stats() {
  stats.stop();
  if(gpppdata.graphingEnabled())
    graphTimer->stop();
}

void PPPStatsDlg::paintGraph() {
  // why draw that stuff if not visible?
  if(!isVisible())
    return;

  QPixmap pm(graph->width() - 4, graph->height() - 4);
  QPainter p;
  pm.fill(graph->backgroundColor());
  p.begin(&pm);

  int x;
  int idx = ringIdx - pm.width() + 1;
  if(idx < 0)
    idx += MAX_GRAPH_WIDTH;

  // find good scaling factor
  int last_h_in =
    pm.height() - (int)((float)bin[idx]/max * (pm.height() - 8))-1;
  int last_h_out =
    pm.height() - (int)((float)bout[idx]/max * (pm.height() - 8))-1;

  // plot scale line
  p.setPen(text);
  p.setFont(QFont("fixed", 8));

  // plot data
  int last_idx = 0;
  for(x = 1; x < pm.width(); x++) {
    int h_in, h_out;

    h_in = pm.height() - (int)((float)bin[idx]/max * (pm.height() - 8))-1;
    h_out = pm.height() - (int)((float)bout[idx]/max * (pm.height() - 8))-1;

    p.setPen(out);
    if(bout[idx]!=-1)
      p.drawLine(x-1, last_h_out, x, h_out);
    p.setPen(in);
    if(bin[idx]!=-1)
      p.drawLine(x-1, last_h_in, x, h_in);
    last_h_in = h_in;
    last_h_out = h_out;

    last_idx = idx;
    idx = (idx + 1) % MAX_GRAPH_WIDTH;
  }

  // take last value
  int last_max = bin[last_idx]>bout[last_idx] ? bin[last_idx] : bout[last_idx];

  QRect r;
  QString s;
  s.sprintf(i18n("%0.1f (max. %0.1f) kb/sec"), (float)last_max / 1024.0, (float)max / 1024.0);
  s = i18n("%1 (max. %2) kb/sec")
		.arg(QString().setNum((float)last_max / 1024.0, 'f', 1))
		.arg(QString().setNum((float)max / 1024.0, 'f', 1));
  p.drawText(0, 0, pm.width(), 2*8, AlignRight|AlignVCenter, s, -1, &r);
  p.drawLine(0, 8, r.left() - 8, 8);

  p.end();
  bitBlt(graph, 2, 2, &pm, 0, 0, pm.width(), pm.height(), CopyROP);
}

void PPPStatsDlg::updateGraph() {
  bin[ringIdx] = stats.ibytes - bin_last;
  bout[ringIdx] = stats.obytes - bout_last;
  if(bin[ringIdx] > max)
    max = ((bin[ringIdx] / 1024) + 1) * 1024;

 if(bout[ringIdx] > max)
    max = ((bout[ringIdx] / 1024) + 1) * 1024;

  bin_last = stats.ibytes;
  bout_last = stats.obytes;
  ringIdx = (ringIdx + 1) % MAX_GRAPH_WIDTH;
  paintGraph();
}

void PPPStatsDlg::paintEvent (QPaintEvent *) {
  paintIcon(PPPStats::BytesNone); // correct ?
  if(gpppdata.graphingEnabled())
    paintGraph();
}

void PPPStatsDlg::paintIcon(int status) {

  const QPixmap *pixmap;

  switch(status)
    {
    case PPPStats::BytesIn:
      pixmap = &big_modem_left_pixmap;
      break;
    case PPPStats::BytesOut:
      pixmap = &big_modem_right_pixmap;
      break;
    case PPPStats::BytesBoth:
      pixmap = &big_modem_both_pixmap;
      break;
    case PPPStats::BytesNone:
    default:
      pixmap = &big_modem_none_pixmap;
      break;
    }

  bitBlt(pixmap_l, 0, 0, pixmap);

  update_data();
}

void PPPStatsDlg::timeclick() {
  // volume accounting
  switch(gpppdata.VolAcctEnabled()) {
  case 0: // no accounting
    break;

  case 1: // bytes in
    stats.totalbytes = gpppdata.totalBytes() + stats.ibytes;
    break;

  case 2:
    stats.totalbytes = gpppdata.totalBytes() + stats.obytes;
    break;

  case 3:
    stats.totalbytes = gpppdata.totalBytes() + stats.ibytes + stats.obytes;
    break;
  }
}

void PPPStatsDlg::closeEvent( QCloseEvent *e ) {
  e->ignore();
}

void PPPStatsDlg::update_data() {
  timeclick();

  ibytes_string.sprintf("%d", stats.ibytes);
  ipackets_string.sprintf("%d", stats.ipackets);
  compressedin_string.sprintf("%d", stats.compressedin);
  uncompressedin_string.sprintf("%d", stats.uncompressedin);
  errorin_string.sprintf("%d", stats.errorin);
  obytes_string.sprintf("%d", stats.obytes);
  opackets_string.sprintf("%d", stats.opackets);
  compressed_string.sprintf("%d", stats.compressed);
  packetsunc_string.sprintf("%d", stats.packetsunc);
  packetsoutunc_string.sprintf("%d", stats.packetsoutunc);

  labela2[0]->setText(ibytes_string);
  labela2[1]->setText(ipackets_string);
  labela2[2]->setText(compressedin_string);
  labela2[3]->setText(uncompressedin_string);
  labela2[4]->setText(errorin_string);

  labelb2[0]->setText(obytes_string);
  labelb2[1]->setText(opackets_string);
  labelb2[2]->setText(compressed_string);
  labelb2[3]->setText(packetsunc_string);
  labelb2[4]->setText(packetsoutunc_string);

  if(!ips_set) {
    // if I don't resort to this trick it is imposible to
    // copy/paste the ip out of the lineedits due to
    // reset of cursor position on setText()

    if( !stats.local_ip_address.isEmpty() )
      ip_address_label2->setText(stats.local_ip_address);
    else
      ip_address_label2->setText(i18n("unavailable"));

    if( !stats.remote_ip_address.isEmpty() )
      ip_address_label4->setText(stats.remote_ip_address);
    else
      ip_address_label4->setText(i18n("unavailable"));

    ips_set = true;
  }
}

#include "pppstatdlg.moc"

<commit_msg>don't ignore close attempts (bug #2203)<commit_after>/*
 *            kPPP: A pppd front end for the KDE project
 *
 * $Id$
 *
 *            Copyright (C) 1997 Bernd Johannes Wuebben
 *                   wuebben@math.cornell.edu
 *
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <qlayout.h>
#include <qpainter.h>
#include <kapp.h>
#include <kwm.h>
#include <kglobal.h>
#include <kiconloader.h>

#include "pppdata.h"
#include "pppstatdlg.h"
#include "kpppconfig.h"
#include "iplined.h"
#include <klocale.h>
#include "pppstats.h"

extern PPPData gpppdata;

PPPStats stats;

PPPStatsDlg::PPPStatsDlg(QWidget *parent, const char *name, QWidget *)
  : QWidget(parent, name, 0 )
{
  int i;
  max = 1024;

  setCaption(i18n("kppp Statistics"));
  KWM::setMiniIcon(winId(), kapp->miniIcon());

  QVBoxLayout *tl = new QVBoxLayout(this, 10);
  QGridLayout *l1 = new QGridLayout(4, 4);
  tl->addLayout(l1, 1);
  box = new QGroupBox(i18n("Statistics"), this);
  l1->addMultiCellWidget(box, 0, 3, 0, 3);
  l1->addRowSpacing(0, fontMetrics().lineSpacing() - 10);
  l1->setRowStretch(1, 1);
  l1->setColStretch(1, 1);

  // inner part of the grid
  QVBoxLayout *l11 = new QVBoxLayout;
  l1->addLayout(l11, 1, 1);

  // modem pixmap and IP labels
  QHBoxLayout *l111 = new QHBoxLayout;
  l11->addLayout(l111);

  big_modem_both_pixmap = BarIcon("modemboth");
  big_modem_left_pixmap = BarIcon("modemleft");
  big_modem_right_pixmap = BarIcon("modemright");
  big_modem_none_pixmap = BarIcon("modemnone");

  pixmap_l = new QLabel(this);
  pixmap_l->setMinimumSize(big_modem_both_pixmap.size());
  l111->addWidget(pixmap_l, 1);
  pixmap_l->setAlignment(AlignVCenter|AlignLeft);

  QGridLayout *l1112 = new QGridLayout(3, 2);
  l111->addLayout(l1112);

  ip_address_label1 = new QLabel(this);
  ip_address_label1->setText(i18n("Local Addr:"));

  ip_address_label2 = new IPLineEdit(this);
  ip_address_label2->setFocusPolicy(QWidget::NoFocus);

  ip_address_label3 = new QLabel(this);
  ip_address_label3->setText(i18n("Remote Addr:"));

  ip_address_label4 = new IPLineEdit(this);
  ip_address_label4->setFocusPolicy(QWidget::NoFocus);

  l1112->addWidget(ip_address_label1, 0, 0);
  l1112->addWidget(ip_address_label2, 0, 1);
  l1112->addWidget(ip_address_label3, 1, 0);
  l1112->addWidget(ip_address_label4, 1, 1);

  // consumes space on bottom
  l1112->setRowStretch(2, 1);

  QGridLayout *l112 = new QGridLayout(5, 4);
  l11->addLayout(l112);
  for(i =0 ; i < 5; i++) {
    labela1[i] = new QLabel(this);

    labela2[i] = new QLabel(this);
    labela2[i]->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);

    labelb1[i] = new QLabel(this);

    labelb2[i] = new QLabel(this);
    labelb2[i]->setFrameStyle(QFrame::WinPanel | QFrame::Sunken);
 }

  labela1[0]->setText(i18n("bytes in"));
  labelb1[0]->setText(i18n("bytes out"));

  labela1[1]->setText(i18n("packets in"));
  labelb1[1]->setText(i18n("packets out"));

  labela1[2]->setText(i18n("vjcomp in"));
  labelb1[2]->setText(i18n("vjcomp out"));

  labela1[3]->setText(i18n("vjunc in"));
  labelb1[3]->setText(i18n("vjunc out"));

  labela1[4]->setText(i18n("vjerr"));
  labelb1[4]->setText(i18n("non-vj"));

  for(i = 0; i < 5; i++) {
    labela2[i]->setText("88888888");
    labelb2[i]->setText("88888888");
    labela2[i]->setFixedSize(labela2[i]->sizeHint());
    labelb2[i]->setFixedSize(labelb2[i]->sizeHint());
    labela2[i]->setText("");
    labelb2[i]->setText("");

    // add to layout
    l112->addWidget(labela1[i], i, 0);
    l112->addWidget(labela2[i], i, 1);
    l112->addWidget(labelb1[i], i, 2);
    l112->addWidget(labelb2[i], i, 3);
  }

  l112->setColStretch(1, 1);
  l112->setColStretch(3, 1);

  tl->addSpacing(5);
  QHBoxLayout *l12 = new QHBoxLayout;
  tl->addLayout(l12);
  l12->addStretch(1);

  if(gpppdata.graphingEnabled()) {
    bool dummy;

    gpppdata.graphingOptions(dummy, bg, text, in, out);

    graph = new QFrame(this);
    graph->setFrameStyle(QFrame::Box | QFrame::Sunken);
    l1->addMultiCellWidget(graph, 2, 2, 1, 2);
    graph->setMinimumWidth(300);
    graph->setFixedHeight(76+4);
    graph->setBackgroundColor(bg);
  }

  cancelbutton = new QPushButton(this, "cancelbutton");
  cancelbutton->setText(i18n("Close"));
  cancelbutton->setFocus();
  connect(cancelbutton, SIGNAL(clicked()), this,SLOT(cancel()));
  cancelbutton->setFixedHeight(cancelbutton->sizeHint().height());
  cancelbutton->setMinimumWidth(QMAX(cancelbutton->sizeHint().width(), 70));
  l12->addWidget(cancelbutton);

  if(gpppdata.graphingEnabled()) {
    graphTimer = new QTimer(this);
    connect(graphTimer, SIGNAL(timeout()), SLOT(updateGraph()));
  }

  setFixedSize(sizeHint());

  connect(&stats, SIGNAL(statsChanged(int)), SLOT(paintIcon(int)));
}

PPPStatsDlg::~PPPStatsDlg() {
}

void PPPStatsDlg::cancel() {
  hide();
}

void PPPStatsDlg::take_stats() {
  stats.initStats();
  ips_set = false;
  bin_last = stats.ibytes;
  bout_last = stats.obytes;
  ringIdx = 0;
  for(int i = 0; i < MAX_GRAPH_WIDTH; i++) {
    bin[i] = -1;
    bout[i] = -1;
  }

  update_data();

  stats.start();
  if(gpppdata.graphingEnabled())
    graphTimer->start(GRAPH_UPDATE_TIME);
}

void PPPStatsDlg::stop_stats() {
  stats.stop();
  if(gpppdata.graphingEnabled())
    graphTimer->stop();
}

void PPPStatsDlg::paintGraph() {
  // why draw that stuff if not visible?
  if(!isVisible())
    return;

  QPixmap pm(graph->width() - 4, graph->height() - 4);
  QPainter p;
  pm.fill(graph->backgroundColor());
  p.begin(&pm);

  int x;
  int idx = ringIdx - pm.width() + 1;
  if(idx < 0)
    idx += MAX_GRAPH_WIDTH;

  // find good scaling factor
  int last_h_in =
    pm.height() - (int)((float)bin[idx]/max * (pm.height() - 8))-1;
  int last_h_out =
    pm.height() - (int)((float)bout[idx]/max * (pm.height() - 8))-1;

  // plot scale line
  p.setPen(text);
  p.setFont(QFont("fixed", 8));

  // plot data
  int last_idx = 0;
  for(x = 1; x < pm.width(); x++) {
    int h_in, h_out;

    h_in = pm.height() - (int)((float)bin[idx]/max * (pm.height() - 8))-1;
    h_out = pm.height() - (int)((float)bout[idx]/max * (pm.height() - 8))-1;

    p.setPen(out);
    if(bout[idx]!=-1)
      p.drawLine(x-1, last_h_out, x, h_out);
    p.setPen(in);
    if(bin[idx]!=-1)
      p.drawLine(x-1, last_h_in, x, h_in);
    last_h_in = h_in;
    last_h_out = h_out;

    last_idx = idx;
    idx = (idx + 1) % MAX_GRAPH_WIDTH;
  }

  // take last value
  int last_max = bin[last_idx]>bout[last_idx] ? bin[last_idx] : bout[last_idx];

  QRect r;
  QString s;
  s.sprintf(i18n("%0.1f (max. %0.1f) kb/sec"), (float)last_max / 1024.0, (float)max / 1024.0);
  s = i18n("%1 (max. %2) kb/sec")
		.arg(QString().setNum((float)last_max / 1024.0, 'f', 1))
		.arg(QString().setNum((float)max / 1024.0, 'f', 1));
  p.drawText(0, 0, pm.width(), 2*8, AlignRight|AlignVCenter, s, -1, &r);
  p.drawLine(0, 8, r.left() - 8, 8);

  p.end();
  bitBlt(graph, 2, 2, &pm, 0, 0, pm.width(), pm.height(), CopyROP);
}

void PPPStatsDlg::updateGraph() {
  bin[ringIdx] = stats.ibytes - bin_last;
  bout[ringIdx] = stats.obytes - bout_last;
  if(bin[ringIdx] > max)
    max = ((bin[ringIdx] / 1024) + 1) * 1024;

 if(bout[ringIdx] > max)
    max = ((bout[ringIdx] / 1024) + 1) * 1024;

  bin_last = stats.ibytes;
  bout_last = stats.obytes;
  ringIdx = (ringIdx + 1) % MAX_GRAPH_WIDTH;
  paintGraph();
}

void PPPStatsDlg::paintEvent (QPaintEvent *) {
  paintIcon(PPPStats::BytesNone); // correct ?
  if(gpppdata.graphingEnabled())
    paintGraph();
}

void PPPStatsDlg::paintIcon(int status) {

  const QPixmap *pixmap;

  switch(status)
    {
    case PPPStats::BytesIn:
      pixmap = &big_modem_left_pixmap;
      break;
    case PPPStats::BytesOut:
      pixmap = &big_modem_right_pixmap;
      break;
    case PPPStats::BytesBoth:
      pixmap = &big_modem_both_pixmap;
      break;
    case PPPStats::BytesNone:
    default:
      pixmap = &big_modem_none_pixmap;
      break;
    }

  bitBlt(pixmap_l, 0, 0, pixmap);

  update_data();
}

void PPPStatsDlg::timeclick() {
  // volume accounting
  switch(gpppdata.VolAcctEnabled()) {
  case 0: // no accounting
    break;

  case 1: // bytes in
    stats.totalbytes = gpppdata.totalBytes() + stats.ibytes;
    break;

  case 2:
    stats.totalbytes = gpppdata.totalBytes() + stats.obytes;
    break;

  case 3:
    stats.totalbytes = gpppdata.totalBytes() + stats.ibytes + stats.obytes;
    break;
  }
}

void PPPStatsDlg::closeEvent( QCloseEvent *e ) {
  emit cancel();
}

void PPPStatsDlg::update_data() {
  timeclick();

  ibytes_string.sprintf("%d", stats.ibytes);
  ipackets_string.sprintf("%d", stats.ipackets);
  compressedin_string.sprintf("%d", stats.compressedin);
  uncompressedin_string.sprintf("%d", stats.uncompressedin);
  errorin_string.sprintf("%d", stats.errorin);
  obytes_string.sprintf("%d", stats.obytes);
  opackets_string.sprintf("%d", stats.opackets);
  compressed_string.sprintf("%d", stats.compressed);
  packetsunc_string.sprintf("%d", stats.packetsunc);
  packetsoutunc_string.sprintf("%d", stats.packetsoutunc);

  labela2[0]->setText(ibytes_string);
  labela2[1]->setText(ipackets_string);
  labela2[2]->setText(compressedin_string);
  labela2[3]->setText(uncompressedin_string);
  labela2[4]->setText(errorin_string);

  labelb2[0]->setText(obytes_string);
  labelb2[1]->setText(opackets_string);
  labelb2[2]->setText(compressed_string);
  labelb2[3]->setText(packetsunc_string);
  labelb2[4]->setText(packetsoutunc_string);

  if(!ips_set) {
    // if I don't resort to this trick it is imposible to
    // copy/paste the ip out of the lineedits due to
    // reset of cursor position on setText()

    if( !stats.local_ip_address.isEmpty() )
      ip_address_label2->setText(stats.local_ip_address);
    else
      ip_address_label2->setText(i18n("unavailable"));

    if( !stats.remote_ip_address.isEmpty() )
      ip_address_label4->setText(stats.remote_ip_address);
    else
      ip_address_label4->setText(i18n("unavailable"));

    ips_set = true;
  }
}

#include "pppstatdlg.moc"

<|endoftext|>


<commit_before>// Copyright © 2011, Université catholique de Louvain
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef __ARRAYS_H
#define __ARRAYS_H

#include <cstdlib>
#include <cassert>

namespace mozart {

/**
 * A simple wrapper for an array and its size (only in debug mode)
 * @param <T> Type of the elements in the array
 */
template <class T>
class StaticArray {
private:
  // Apparently, std::nullptr_t is not defined in every standard library yet
  typedef decltype(nullptr) nullptr_t;
private:
  T* _array;

#ifndef NDEBUG
  int _size;
#endif

public:
  /** Create an array with s elements */
  StaticArray(T* array, int s) : _array(array) {
#ifndef NDEBUG
    _size = s;
#endif
  }

  /** Create an array with no element */
  StaticArray() : _array(nullptr) {
#ifndef NDEBUG
    _size = 0;
#endif
  }

  /** Convert from nullptr */
  StaticArray(nullptr_t nullp) : _array(nullptr) {
#ifndef NDEBUG
    _size = 0;
#endif
  }

  /** Zero-based access to elements (read-write) */
  inline
  T& operator[](int i) {
    assert(0 <= i && i < _size);
    return _array[i];
  }

  /** Convert to a raw array */
  inline
  operator T*() {
    return _array;
  }

  /** Assign from nullptr */
  inline
  void operator=(nullptr_t nullp) {
    _array = nullptr;
#ifndef NDEBUG
    _size = 0;
#endif
  }
};

}

#endif // __ARRAYS_H
<commit_msg>Protect StaticArray._size under a dedicated define (not just NDEBUG).<commit_after>// Copyright © 2011, Université catholique de Louvain
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

#ifndef __ARRAYS_H
#define __ARRAYS_H

#include <cstdlib>
#include <cassert>

namespace mozart {

/**
 * A simple wrapper for an array and its size (only in debug mode)
 * @param <T> Type of the elements in the array
 */
template <class T>
class StaticArray {
private:
  // Apparently, std::nullptr_t is not defined in every standard library yet
  typedef decltype(nullptr) nullptr_t;
private:
  T* _array;

#ifdef MOZART_STATICARRAY_WITH_SIZE
  int _size;
#endif

public:
  /** Create an array with s elements */
  StaticArray(T* array, int s) : _array(array) {
#ifdef MOZART_STATICARRAY_WITH_SIZE
    _size = s;
#endif
  }

  /** Create an array with no element */
  StaticArray() : _array(nullptr) {
#ifdef MOZART_STATICARRAY_WITH_SIZE
    _size = 0;
#endif
  }

  /** Convert from nullptr */
  StaticArray(nullptr_t nullp) : _array(nullptr) {
#ifdef MOZART_STATICARRAY_WITH_SIZE
    _size = 0;
#endif
  }

  /** Zero-based access to elements (read-write) */
  inline
  T& operator[](int i) {
#ifdef MOZART_STATICARRAY_WITH_SIZE
    assert(0 <= i && i < _size);
#endif
    return _array[i];
  }

  /** Convert to a raw array */
  inline
  operator T*() {
    return _array;
  }

  /** Assign from nullptr */
  inline
  void operator=(nullptr_t nullp) {
    _array = nullptr;
#ifdef MOZART_STATICARRAY_WITH_SIZE
    _size = 0;
#endif
  }
};

}

#endif // __ARRAYS_H
<|endoftext|>


<commit_before>#include "ros/ros.h"
#include "boost/asio.hpp"
#include "jaws_msgs/Thrusters.h"

class Arbotix
{
  private:
    ros::NodeHandle nh;
    ros::Subscriber sub;
    boost::asio::io_service i_o;
    boost::asio::serial_port s_p;
    std::string port_name;
    int br;
    char c;
    std::string feedback;
  public:
    Arbotix() : nh(), i_o(), s_p(i_o)
    {
      nh.getParam("/arbotix_node/port_name",port_name);
      nh.getParam("/arbotix_node/baud_rate",br);
      s_p.open(port_name);
      s_p.set_option(boost::asio::serial_port_base::baud_rate(br));

      sub = nh.subscribe<jaws_msgs::Thrusters>("thrusters", 1, &Arbotix::callback, this);
    }
    void callback(const jaws_msgs::Thrusters::ConstPtr& thrusters)
    {
      const int SIZE = 11;
      unsigned char packet[SIZE];

      packet[0] = '-';

      packet[1] = (thrusters->port_angle >> 8) & 0xFF;
      packet[2] = thrusters->port_angle & 0xFF;

      packet[3] = (thrusters->stbd_angle >> 8) & 0xFF;
      packet[4] = thrusters->stbd_angle & 0xFF;

      packet[5] = (thrusters->aft_power >> 8) & 0xFF;
      packet[6] = thrusters->aft_power & 0xFF;

      packet[7] = (thrusters->port_power >> 8) & 0xFF;
      packet[8] = thrusters->port_power & 0xFF;

      packet[9] = (thrusters->stbd_power >> 8) & 0xFF;
      packet[10] = thrusters->stbd_power & 0xFF;

      s_p.write_some(boost::asio::buffer(&packet, SIZE));

      while(c!="\n"){
         c=s_p.read_some(boost::asio::buffer(&c,1);
         if(c!="\n"){
 	   feedback+=c;
	 }
      }
     ROS_INFO("%s",feedback);

    }
    void loop()
    {
      ros::spin();
    }
};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "arbotix_node");
  Arbotix arbotix;
  arbotix.loop();
}
<commit_msg>Code to close and reopen serial if it stops responding<commit_after>#include "ros/ros.h"
#include "boost/asio.hpp"
#include "jaws_msgs/Thrusters.h"
#include "time.h"
class Arbotix
{
  private:
    ros::NodeHandle nh;
    ros::Subscriber sub;
    boost::asio::io_service i_o;
    boost::asio::serial_port s_p;
    std::string port_name;
    int br;
    char c;
    std::string feedback;
  public:
    Arbotix() : nh(), i_o(), s_p(i_o)
    {
      nh.getParam("/arbotix_node/port_name",port_name);
      nh.getParam("/arbotix_node/baud_rate",br);
      s_p.open(port_name);
      s_p.set_option(boost::asio::serial_port_base::baud_rate(br));

      sub = nh.subscribe<jaws_msgs::Thrusters>("thrusters", 1, &Arbotix::callback, this);
    }
    void restartPort()
    {
	nh.getParam("/arbotix_node/port_name",port_name);
	nh.getParam("/arbotix_node/baud_rate",br);
	s_p.close();
        s_p.open(port_name);
	s_p.set_option(boost::asio::serial_port_base::baud_rate(br));
    }
    void callback(const jaws_msgs::Thrusters::ConstPtr& thrusters)
    {
      const int SIZE = 11;
      unsigned char packet[SIZE];

      unsigned int start=clock();
      packet[0] = '-';

      packet[1] = (thrusters->port_angle >> 8) & 0xFF;
      packet[2] = thrusters->port_angle & 0xFF;

      packet[3] = (thrusters->stbd_angle >> 8) & 0xFF;
      packet[4] = thrusters->stbd_angle & 0xFF;

      packet[5] = (thrusters->aft_power >> 8) & 0xFF;
      packet[6] = thrusters->aft_power & 0xFF;

      packet[7] = (thrusters->port_power >> 8) & 0xFF;
      packet[8] = thrusters->port_power & 0xFF;
      packet[9] = (thrusters->stbd_power >> 8) & 0xFF;
      packet[10] = thrusters->stbd_power & 0xFF;

      s_p.write_some(boost::asio::buffer(&packet, SIZE));
      c='a';
      while(c!='\n'){
         c=s_p.read_some(boost::asio::buffer(&c,1));
         if(c!='\n'){
 	   feedback+=c;
	 }
	else{
		break;
	}
	if((clock()-start/CLOCKS_PER_SEC)>5000){
	   restartPort();
	   break;
	}
      }
     ROS_INFO("%s",feedback.c_str());

    }
    void loop()
    {
      ros::spin();
    }
};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "arbotix_node");
  Arbotix arbotix;
  arbotix.loop();
}
<|endoftext|>