<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: storagehelper.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 02:53:09 $
 *
 *  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 _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XENCRYPTIONPROTECTEDSOURCE_HPP_
#include <com/sun/star/embed/XEncryptionProtectedSource.hpp>
#endif

#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_ILLEGALTYPEEXCEPTION_HPP_
#include <com/sun/star/beans/IllegalTypeException.hpp>
#endif

#include <comphelper/fileformat.h>
#include <comphelper/storagehelper.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/documentconstants.hxx>

using namespace ::com::sun::star;

namespace comphelper {

// ----------------------------------------------------------------------
uno::Reference< lang::XSingleServiceFactory > OStorageHelper::GetStorageFactory(
                            const uno::Reference< lang::XMultiServiceFactory >& xSF )
        throw ( uno::Exception )
{
    uno::Reference< lang::XMultiServiceFactory > xFactory = xSF.is() ? xSF : ::comphelper::getProcessServiceFactory();
    if ( !xFactory.is() )
        throw uno::RuntimeException();

    uno::Reference < lang::XSingleServiceFactory > xStorageFactory(
                    xFactory->createInstance ( ::rtl::OUString::createFromAscii( "com.sun.star.embed.StorageFactory" ) ),
                    uno::UNO_QUERY );

    if ( !xStorageFactory.is() )
        throw uno::RuntimeException();

    return xStorageFactory;
}

// ----------------------------------------------------------------------
uno::Reference< embed::XStorage > OStorageHelper::GetTemporaryStorage(
            const uno::Reference< lang::XMultiServiceFactory >& xFactory )
    throw ( uno::Exception )
{
    uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstance(),
                                                    uno::UNO_QUERY );
    if ( !xTempStorage.is() )
        throw uno::RuntimeException();

    return xTempStorage;
}

// ----------------------------------------------------------------------
uno::Reference< embed::XStorage > OStorageHelper::GetStorageFromURL(
            const ::rtl::OUString& aURL,
            sal_Int32 nStorageMode,
            const uno::Reference< lang::XMultiServiceFactory >& xFactory )
    throw ( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[0] <<= aURL;
    aArgs[1] <<= nStorageMode;

    uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),
                                                    uno::UNO_QUERY );
    if ( !xTempStorage.is() )
        throw uno::RuntimeException();

    return xTempStorage;
}

// ----------------------------------------------------------------------
uno::Reference< embed::XStorage > OStorageHelper::GetStorageFromInputStream(
            const uno::Reference < io::XInputStream >& xStream,
            const uno::Reference< lang::XMultiServiceFactory >& xFactory )
        throw ( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[0] <<= xStream;
    aArgs[1] <<= embed::ElementModes::READ;

    uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),
                                                    uno::UNO_QUERY );
    if ( !xTempStorage.is() )
        throw uno::RuntimeException();

    return xTempStorage;
}

// ----------------------------------------------------------------------
uno::Reference< embed::XStorage > OStorageHelper::GetStorageFromStream(
            const uno::Reference < io::XStream >& xStream,
            sal_Int32 nStorageMode,
            const uno::Reference< lang::XMultiServiceFactory >& xFactory )
        throw ( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[0] <<= xStream;
    aArgs[1] <<= nStorageMode;

    uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),
                                                    uno::UNO_QUERY );
    if ( !xTempStorage.is() )
        throw uno::RuntimeException();

    return xTempStorage;
}

// ----------------------------------------------------------------------
void OStorageHelper::CopyInputToOutput(
            const uno::Reference< io::XInputStream >& xInput,
            const uno::Reference< io::XOutputStream >& xOutput )
    throw ( uno::Exception )
{
    static const sal_Int32 nConstBufferSize = 32000;

    sal_Int32 nRead;
    uno::Sequence < sal_Int8 > aSequence ( nConstBufferSize );

    do
    {
        nRead = xInput->readBytes ( aSequence, nConstBufferSize );
        if ( nRead < nConstBufferSize )
        {
            uno::Sequence < sal_Int8 > aTempBuf ( aSequence.getConstArray(), nRead );
            xOutput->writeBytes ( aTempBuf );
        }
        else
            xOutput->writeBytes ( aSequence );
    }
    while ( nRead == nConstBufferSize );
}

// ----------------------------------------------------------------------
uno::Reference< io::XInputStream > OStorageHelper::GetInputStreamFromURL(
            const ::rtl::OUString& aURL,
            const uno::Reference< lang::XMultiServiceFactory >& xSF )
    throw ( uno::Exception )
{
    uno::Reference< lang::XMultiServiceFactory > xFactory = xSF.is() ? xSF : ::comphelper::getProcessServiceFactory();
    if ( !xFactory.is() )
        throw uno::RuntimeException();

    uno::Reference < ::com::sun::star::ucb::XSimpleFileAccess > xTempAccess(
            xFactory->createInstance ( ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ),
            uno::UNO_QUERY );

    if ( !xTempAccess.is() )
        throw uno::RuntimeException();

    uno::Reference< io::XInputStream > xInputStream = xTempAccess->openFileRead( aURL );
    if ( !xInputStream.is() )
        throw uno::RuntimeException();

    return xInputStream;
}

// ----------------------------------------------------------------------
void OStorageHelper::SetCommonStoragePassword(
            const uno::Reference< embed::XStorage >& xStorage,
            const ::rtl::OUString& aPass )
    throw ( uno::Exception )
{
    uno::Reference< embed::XEncryptionProtectedSource > xEncrSet( xStorage, uno::UNO_QUERY );
    if ( !xEncrSet.is() )
        throw io::IOException(); // TODO

    xEncrSet->setEncryptionPassword( aPass );
}

// ----------------------------------------------------------------------
sal_Int32 OStorageHelper::GetXStorageFormat(
            const uno::Reference< embed::XStorage >& xStorage )
        throw ( uno::Exception )
{
    uno::Reference< beans::XPropertySet > xStorProps( xStorage, uno::UNO_QUERY_THROW );

    ::rtl::OUString aMediaType;
    xStorProps->getPropertyValue( ::rtl::OUString::createFromAscii( "MediaType" ) ) >>= aMediaType;

    sal_Int32 nResult = 0;

    // TODO/LATER: the filter configuration could be used to detect it later, or batter a special service
    if (
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_WRITER_ASCII       ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_WRITER_WEB_ASCII   ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_WRITER_GLOBAL_ASCII) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_DRAW_ASCII         ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_IMPRESS_ASCII      ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_CALC_ASCII         ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_CHART_ASCII        ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_MATH_ASCII         )
       )
    {
        nResult = SOFFICE_FILEFORMAT_60;
    }
    else
    if (
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_TEXT_ASCII        ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_TEXT_WEB_ASCII    ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_ASCII ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_ASCII     ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_ASCII) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_ASCII ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_CHART_ASCII       ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_ASCII     ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_DATABASE_ASCII    ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE_ASCII        ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE_ASCII     ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE_ASCII) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE_ASCII ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE_ASCII       ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE_ASCII     )
       )
    {
        nResult = SOFFICE_FILEFORMAT_8;
    }
    else
    {
        // the mediatype is not known
        throw beans::IllegalTypeException();
    }

    return nResult;
}

}

<commit_msg>INTEGRATION: CWS pchfix02 (1.7.100); FILE MERGED 2006/09/01 17:19:44 kaib 1.7.100.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: storagehelper.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 17:14:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"

#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XENCRYPTIONPROTECTEDSOURCE_HPP_
#include <com/sun/star/embed/XEncryptionProtectedSource.hpp>
#endif

#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_ILLEGALTYPEEXCEPTION_HPP_
#include <com/sun/star/beans/IllegalTypeException.hpp>
#endif

#include <comphelper/fileformat.h>
#include <comphelper/storagehelper.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/documentconstants.hxx>

using namespace ::com::sun::star;

namespace comphelper {

// ----------------------------------------------------------------------
uno::Reference< lang::XSingleServiceFactory > OStorageHelper::GetStorageFactory(
                            const uno::Reference< lang::XMultiServiceFactory >& xSF )
        throw ( uno::Exception )
{
    uno::Reference< lang::XMultiServiceFactory > xFactory = xSF.is() ? xSF : ::comphelper::getProcessServiceFactory();
    if ( !xFactory.is() )
        throw uno::RuntimeException();

    uno::Reference < lang::XSingleServiceFactory > xStorageFactory(
                    xFactory->createInstance ( ::rtl::OUString::createFromAscii( "com.sun.star.embed.StorageFactory" ) ),
                    uno::UNO_QUERY );

    if ( !xStorageFactory.is() )
        throw uno::RuntimeException();

    return xStorageFactory;
}

// ----------------------------------------------------------------------
uno::Reference< embed::XStorage > OStorageHelper::GetTemporaryStorage(
            const uno::Reference< lang::XMultiServiceFactory >& xFactory )
    throw ( uno::Exception )
{
    uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstance(),
                                                    uno::UNO_QUERY );
    if ( !xTempStorage.is() )
        throw uno::RuntimeException();

    return xTempStorage;
}

// ----------------------------------------------------------------------
uno::Reference< embed::XStorage > OStorageHelper::GetStorageFromURL(
            const ::rtl::OUString& aURL,
            sal_Int32 nStorageMode,
            const uno::Reference< lang::XMultiServiceFactory >& xFactory )
    throw ( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[0] <<= aURL;
    aArgs[1] <<= nStorageMode;

    uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),
                                                    uno::UNO_QUERY );
    if ( !xTempStorage.is() )
        throw uno::RuntimeException();

    return xTempStorage;
}

// ----------------------------------------------------------------------
uno::Reference< embed::XStorage > OStorageHelper::GetStorageFromInputStream(
            const uno::Reference < io::XInputStream >& xStream,
            const uno::Reference< lang::XMultiServiceFactory >& xFactory )
        throw ( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[0] <<= xStream;
    aArgs[1] <<= embed::ElementModes::READ;

    uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),
                                                    uno::UNO_QUERY );
    if ( !xTempStorage.is() )
        throw uno::RuntimeException();

    return xTempStorage;
}

// ----------------------------------------------------------------------
uno::Reference< embed::XStorage > OStorageHelper::GetStorageFromStream(
            const uno::Reference < io::XStream >& xStream,
            sal_Int32 nStorageMode,
            const uno::Reference< lang::XMultiServiceFactory >& xFactory )
        throw ( uno::Exception )
{
    uno::Sequence< uno::Any > aArgs( 2 );
    aArgs[0] <<= xStream;
    aArgs[1] <<= nStorageMode;

    uno::Reference< embed::XStorage > xTempStorage( GetStorageFactory( xFactory )->createInstanceWithArguments( aArgs ),
                                                    uno::UNO_QUERY );
    if ( !xTempStorage.is() )
        throw uno::RuntimeException();

    return xTempStorage;
}

// ----------------------------------------------------------------------
void OStorageHelper::CopyInputToOutput(
            const uno::Reference< io::XInputStream >& xInput,
            const uno::Reference< io::XOutputStream >& xOutput )
    throw ( uno::Exception )
{
    static const sal_Int32 nConstBufferSize = 32000;

    sal_Int32 nRead;
    uno::Sequence < sal_Int8 > aSequence ( nConstBufferSize );

    do
    {
        nRead = xInput->readBytes ( aSequence, nConstBufferSize );
        if ( nRead < nConstBufferSize )
        {
            uno::Sequence < sal_Int8 > aTempBuf ( aSequence.getConstArray(), nRead );
            xOutput->writeBytes ( aTempBuf );
        }
        else
            xOutput->writeBytes ( aSequence );
    }
    while ( nRead == nConstBufferSize );
}

// ----------------------------------------------------------------------
uno::Reference< io::XInputStream > OStorageHelper::GetInputStreamFromURL(
            const ::rtl::OUString& aURL,
            const uno::Reference< lang::XMultiServiceFactory >& xSF )
    throw ( uno::Exception )
{
    uno::Reference< lang::XMultiServiceFactory > xFactory = xSF.is() ? xSF : ::comphelper::getProcessServiceFactory();
    if ( !xFactory.is() )
        throw uno::RuntimeException();

    uno::Reference < ::com::sun::star::ucb::XSimpleFileAccess > xTempAccess(
            xFactory->createInstance ( ::rtl::OUString::createFromAscii( "com.sun.star.ucb.SimpleFileAccess" ) ),
            uno::UNO_QUERY );

    if ( !xTempAccess.is() )
        throw uno::RuntimeException();

    uno::Reference< io::XInputStream > xInputStream = xTempAccess->openFileRead( aURL );
    if ( !xInputStream.is() )
        throw uno::RuntimeException();

    return xInputStream;
}

// ----------------------------------------------------------------------
void OStorageHelper::SetCommonStoragePassword(
            const uno::Reference< embed::XStorage >& xStorage,
            const ::rtl::OUString& aPass )
    throw ( uno::Exception )
{
    uno::Reference< embed::XEncryptionProtectedSource > xEncrSet( xStorage, uno::UNO_QUERY );
    if ( !xEncrSet.is() )
        throw io::IOException(); // TODO

    xEncrSet->setEncryptionPassword( aPass );
}

// ----------------------------------------------------------------------
sal_Int32 OStorageHelper::GetXStorageFormat(
            const uno::Reference< embed::XStorage >& xStorage )
        throw ( uno::Exception )
{
    uno::Reference< beans::XPropertySet > xStorProps( xStorage, uno::UNO_QUERY_THROW );

    ::rtl::OUString aMediaType;
    xStorProps->getPropertyValue( ::rtl::OUString::createFromAscii( "MediaType" ) ) >>= aMediaType;

    sal_Int32 nResult = 0;

    // TODO/LATER: the filter configuration could be used to detect it later, or batter a special service
    if (
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_WRITER_ASCII       ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_WRITER_WEB_ASCII   ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_WRITER_GLOBAL_ASCII) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_DRAW_ASCII         ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_IMPRESS_ASCII      ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_CALC_ASCII         ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_CHART_ASCII        ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_VND_SUN_XML_MATH_ASCII         )
       )
    {
        nResult = SOFFICE_FILEFORMAT_60;
    }
    else
    if (
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_TEXT_ASCII        ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_TEXT_WEB_ASCII    ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_TEXT_GLOBAL_ASCII ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_ASCII     ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_ASCII) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_ASCII ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_CHART_ASCII       ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_ASCII     ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_DATABASE_ASCII    ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_TEXT_TEMPLATE_ASCII        ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_DRAWING_TEMPLATE_ASCII     ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_PRESENTATION_TEMPLATE_ASCII) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_SPREADSHEET_TEMPLATE_ASCII ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_CHART_TEMPLATE_ASCII       ) ||
        aMediaType.equalsIgnoreAsciiCaseAscii(MIMETYPE_OASIS_OPENDOCUMENT_FORMULA_TEMPLATE_ASCII     )
       )
    {
        nResult = SOFFICE_FILEFORMAT_8;
    }
    else
    {
        // the mediatype is not known
        throw beans::IllegalTypeException();
    }

    return nResult;
}

}

<|endoftext|>


<commit_before>// Copyright (C) 2011 Petr Machata
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program.  If not, see
// <http://www.gnu.org/licenses/>.

#include "verb.hh"
#include "forms.hh"
#include "rus_gramtab.hh"
#include "format.hh"
#include "adjective.hh"

#include <boost/format.hpp>
#include <iostream>

verb_handler::verb_handler ()
  : pos_handler ("verb")
{
}

void
verb_handler::fill_hdf (CAgramtab *agramtab,
			lemmatize::const_iterator const &it,
			hdf_data_map &data) const
{
  lemmatize::forms forms = it.forms ();

  for (lemmatize::forms::const_iterator ft = forms.begin ();
       ft != forms.end (); ++ft)
    {
      std::string category;
      std::vector<grammeme> gs = ft.ancode ().grammemes ();

      gram_code_t number = gm__invalid;
      gram_code_t voice = gm__invalid;
      gram_code_t gender = gm__invalid;
      gram_code_t tense = gm__invalid;
      gram_code_t person = gm__invalid;
      gram_code_t gcase = gm__invalid;
      bool imperative = false;
      bool animate = false;
      bool inanimate = false;

      std::vector<gram_code_t> extra;
      for (std::vector<grammeme>::const_iterator gt = gs.begin ();
	   gt != gs.end (); ++gt)
	{
	  gram_code_t code = gt->value_as<gram_code_t> ();
	  if (!extract_rus_number (number, code)
	      && !extract_rus_voice (voice, code)
	      && !extract_rus_gender (gender, code)
	      && !extract_rus_tense (tense, code)
	      && !extract_rus_person (person, code)
	      && !extract_rus_case (gcase, code))
	    {
	      if (code == gm_imperative)
		imperative = true;
	      else if (code == gm_animate)
		animate = true;
	      else if (code == gm_inanimate)
		inanimate = true;
	      else if (code == gm_colloquial)
		{
		  extra.push_back (code);
		  continue;
		}
	      else
		std::cerr << (boost::format ("Unhandled grammeme %s\n")
			      % format_rus (code));
	    }
	  if (category.length () > 0)
	    category += ",";
	  category += gt->c_str ();
	}

      std::string key;

      // Forms with animate and/or inanimate attributes are adjectival
      // participles.
      if (animate || inanimate)
	{
	  std::string sub_key = adjective_handler::format_form_key
	    (gm_positive, gcase, number, gender, animate, inanimate, false);
	  key = str (boost::format ("adj_participle.%s.%s.%s")
		     % format_rus (voice)
		     % format_rus (tense)
		     % sub_key);
	}

      else if (tense == gm__invalid)
	{
	  if (imperative)
	    key = str (boost::format ("%s.%s.%s")
		       % format_rus (gm_imperative)
		       % format_rus (number)
		       % format_rus (person));
	  else
	    key = "infinitive";
	}

      // These are adverbial participles.
      else if (number == gm__invalid)
	key = str (boost::format ("adv_participle.%s")
		   % format_rus (tense));

      else if (tense == gm_future || tense == gm_present)
	key = str (boost::format ("%s.%s.%s")
		   % format_rus (tense)
		   % format_rus (number)
		   % format_rus (person));

      // past tense
      else
	{
	  if (number == gm_singular)
	    key = str (boost::format ("%s.%s")
		       % format_rus (tense)
		       % format_rus (gender));
	  else
	    key = str (boost::format ("%s.%s")
		       % format_rus (tense)
		       % format_rus (number));
	}

      data[key].push_back (std::make_pair (*ft, ft.accent ()));
      if (extra.size () > 0)
	{
	  std::string subkey = str (boost::format ("%s.%d.extra")
				    % key % (data[key].size () - 1));
	  for (std::vector<gram_code_t>::const_iterator it = extra.begin ();
	       it != extra.end (); ++it)
	    data[subkey].push_back (std::make_pair (format_rus (*it), -1));
	}
    }
}
<commit_msg>Drop unused code<commit_after>// Copyright (C) 2011 Petr Machata
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program.  If not, see
// <http://www.gnu.org/licenses/>.

#include "verb.hh"
#include "forms.hh"
#include "rus_gramtab.hh"
#include "format.hh"
#include "adjective.hh"

#include <boost/format.hpp>
#include <iostream>

verb_handler::verb_handler ()
  : pos_handler ("verb")
{
}

void
verb_handler::fill_hdf (CAgramtab *agramtab,
			lemmatize::const_iterator const &it,
			hdf_data_map &data) const
{
  lemmatize::forms forms = it.forms ();

  for (lemmatize::forms::const_iterator ft = forms.begin ();
       ft != forms.end (); ++ft)
    {
      std::vector<grammeme> gs = ft.ancode ().grammemes ();

      gram_code_t number = gm__invalid;
      gram_code_t voice = gm__invalid;
      gram_code_t gender = gm__invalid;
      gram_code_t tense = gm__invalid;
      gram_code_t person = gm__invalid;
      gram_code_t gcase = gm__invalid;
      bool imperative = false;
      bool animate = false;
      bool inanimate = false;

      std::vector<gram_code_t> extra;
      for (std::vector<grammeme>::const_iterator gt = gs.begin ();
	   gt != gs.end (); ++gt)
	{
	  gram_code_t code = gt->value_as<gram_code_t> ();
	  if (!extract_rus_number (number, code)
	      && !extract_rus_voice (voice, code)
	      && !extract_rus_gender (gender, code)
	      && !extract_rus_tense (tense, code)
	      && !extract_rus_person (person, code)
	      && !extract_rus_case (gcase, code))
	    {
	      if (code == gm_imperative)
		imperative = true;
	      else if (code == gm_animate)
		animate = true;
	      else if (code == gm_inanimate)
		inanimate = true;
	      else if (code == gm_colloquial)
		extra.push_back (code);
	      else
		std::cerr << (boost::format ("Unhandled grammeme %s\n")
			      % format_rus (code));
	    }
	}

      std::string key;

      // Forms with animate and/or inanimate attributes are adjectival
      // participles.
      if (animate || inanimate)
	{
	  std::string sub_key = adjective_handler::format_form_key
	    (gm_positive, gcase, number, gender, animate, inanimate, false);
	  key = str (boost::format ("adj_participle.%s.%s.%s")
		     % format_rus (voice)
		     % format_rus (tense)
		     % sub_key);
	}

      else if (tense == gm__invalid)
	{
	  if (imperative)
	    key = str (boost::format ("%s.%s.%s")
		       % format_rus (gm_imperative)
		       % format_rus (number)
		       % format_rus (person));
	  else
	    key = "infinitive";
	}

      // These are adverbial participles.
      else if (number == gm__invalid)
	key = str (boost::format ("adv_participle.%s")
		   % format_rus (tense));

      else if (tense == gm_future || tense == gm_present)
	key = str (boost::format ("%s.%s.%s")
		   % format_rus (tense)
		   % format_rus (number)
		   % format_rus (person));

      // past tense
      else
	{
	  if (number == gm_singular)
	    key = str (boost::format ("%s.%s")
		       % format_rus (tense)
		       % format_rus (gender));
	  else
	    key = str (boost::format ("%s.%s")
		       % format_rus (tense)
		       % format_rus (number));
	}

      data[key].push_back (std::make_pair (*ft, ft.accent ()));
      if (extra.size () > 0)
	{
	  std::string subkey = str (boost::format ("%s.%d.extra")
				    % key % (data[key].size () - 1));
	  for (std::vector<gram_code_t>::const_iterator it = extra.begin ();
	       it != extra.end (); ++it)
	    data[subkey].push_back (std::make_pair (format_rus (*it), -1));
	}
    }
}
<|endoftext|>


<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Petr Vanek <petr@scribus.info>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LXQt/Application>
#include <LXQt/PowerManager>
#include <LXQt/ScreenSaver>
#include <LXQt/Translator>
#include <QDesktopWidget>

#include "leavedialog.h"

int main(int argc, char *argv[])
{
    LxQt::Application a(argc, argv);
    LxQt::Translator::translateApplication();

    LxQt::PowerManager powermanager(&a);
    LxQt::ScreenSaver screensaver(&a);

    for (int i = 1; i < argc; ++i)
    {
        QString arg = QString::fromLocal8Bit(argv[i]);

        if (arg == QStringLiteral("--logout"))
        {
            powermanager.logout();
            return 0;
        }

        if (arg == QStringLiteral("--suspend"))
        {
            powermanager.suspend();
            return 0;
        }

        if (arg == QStringLiteral("--hibernate"))
        {
            powermanager.hibernate();
            return 0;
        }

        if (arg == QStringLiteral("--shutdown"))
        {
            powermanager.shutdown();
            return 0;
        }

        if (arg == QStringLiteral("--reboot"))
        {
            powermanager.reboot();
            return 0;
        }

        if (arg == QStringLiteral("--lockscreen"))
        {
            a.connect(&screensaver, &LxQt::ScreenSaver::done, &a, &LxQt::Application::quit);
            screensaver.lockScreen();
            a.exec();
            return 0;
        }

        if (arg == QStringLiteral("--gui"))
        {
            LeaveDialog dialog;
            dialog.setGeometry(QStyle::alignedRect(Qt::LeftToRight,
                                                    Qt::AlignCenter,
                                                    dialog.size(),
                                                    qApp->desktop()->screenGeometry(QCursor::pos())));
            dialog.setMaximumSize(dialog.minimumSize());
            dialog.exec();
        }
    }
}
<commit_msg>lxqt-leave: switch to QCommandLineParser to deal with options<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Petr Vanek <petr@scribus.info>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include <LXQt/Application>
#include <LXQt/PowerManager>
#include <LXQt/ScreenSaver>
#include <LXQt/Translator>
#include <QDesktopWidget>
#include <QCommandLineParser>
#include <QCoreApplication>

#include "leavedialog.h"

int main(int argc, char *argv[])
{
    LxQt::Application a(argc, argv);
    LxQt::Translator::translateApplication();

    LxQt::PowerManager powermanager(&a);
    LxQt::ScreenSaver screensaver(&a);

    QCommandLineParser parser;
    parser.setApplicationDescription("lxqt-leave");
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption logoutOption(QStringLiteral("logout"), QCoreApplication::translate("main", "Logout."));
    parser.addOption(logoutOption);

    QCommandLineOption lockscreenOption(QStringLiteral("lockscreen"), QCoreApplication::translate("main", "Lockscreen."));
    parser.addOption(lockscreenOption);

    QCommandLineOption suspendOption(QStringLiteral("suspend"), QCoreApplication::translate("main", "Suspend."));
    parser.addOption(suspendOption);

    QCommandLineOption hibernateOption(QStringLiteral("hibernate"), QCoreApplication::translate("main", "Hibernate."));
    parser.addOption(hibernateOption);

    QCommandLineOption shutdownOption(QStringLiteral("shutdown"), QCoreApplication::translate("main", "Shutdown."));
    parser.addOption(shutdownOption);

    QCommandLineOption rebootOption(QStringLiteral("reboot"), QCoreApplication::translate("main", "Reboot."));
    parser.addOption(rebootOption);

    QCommandLineOption guiOption(QStringLiteral("gui"), QCoreApplication::translate("main", "Shows the GUI."));
    parser.addOption(guiOption);

    parser.process(a);

    if (parser.isSet(logoutOption)) {
        powermanager.logout();
        return 0;
    }

    if (parser.isSet(lockscreenOption)) {
        a.connect(&screensaver, &LxQt::ScreenSaver::done, &a, &LxQt::Application::quit);
        screensaver.lockScreen();
        a.exec();
        return 0;
    }

    if (parser.isSet(suspendOption)) {
        powermanager.suspend();
        return 0;
    }

    if (parser.isSet(hibernateOption)) {
        powermanager.hibernate();
        return 0;
    }

    if (parser.isSet(shutdownOption)) {
        powermanager.shutdown();
        return 0;
    }

    if (parser.isSet(rebootOption)) {
        powermanager.reboot();
        return 0;
    }

    if (parser.isSet(guiOption)) {
        LeaveDialog dialog;
        dialog.setGeometry(QStyle::alignedRect(Qt::LeftToRight,
                    Qt::AlignCenter,
                    dialog.size(),
                    qApp->desktop()->screenGeometry(QCursor::pos())));
        dialog.setMaximumSize(dialog.minimumSize());
        dialog.exec();
    }
}
<|endoftext|>


<commit_before>/**
 *    \file moteur.cpp
 *    \brief Code contrôle des moteurs du grand Robot. Ce programme permet d'initialiser et d'envoyer 4 PWM (2 PWM pour chaque moteur) au driver moteur
 *
 *Codé pour "Spark core"  www.spark.io
 *
 *Par : Clément LETELLIER
 *      Mars 2014
 *Modification: Nicolas SOBCZAK
 *              Octobre 2016
*/

/* ======================================================================================================
 *      Include
 * ======================================================================================================
 */
#include "odometrie.h"
#include "Arduino.h"
#include "moteur.h"

/* ======================================================================================================
 *      Define
 * ======================================================================================================
 */
#define inputPontH2MoteurDroit 51 //commande pont en h avec 2 signal 1 constant et l'autre PWM a changer avec le shiel
#define inputPontH2MoteurGauche 53//commande pont en h avec 2 signal 1 constant et l'autre PWM
#define PWM_FREQ 20000 // in Hertz (SET YOUR FREQUENCY)

uint16_t TIM_ARR = (uint16_t)(24000000 / PWM_FREQ) - 1; // Don't change! Calc's period.

/* ======================================================================================================
 *      Class Moteur
 * ======================================================================================================
 */
//initialise le moteur lors de l'appelle
Moteur::Moteur(){
  m_vitesse_moteur=0;
}

//active le timer2 et 0 pour la PWM, active la PWM selon le moteur
void Moteur::initPWM(){
   pinMode(inputPontH2MoteurDroit,OUTPUT);
   pinMode(inputPontH2MoteurGauche,OUTPUT);
   pinMode(PMW_MOTEUR_A0 ,OUTPUT);
   pinMode(PMW_MOTEUR_A1 ,OUTPUT);

   pinMode(PMW_MOTEUR_B0 ,OUTPUT);
   pinMode(PMW_MOTEUR_B1 ,OUTPUT);

}

//permet de freiner les moteurs
void Moteur::brake(int choix_moteur){// potentiellement inutile pour frein mettre les motor a 0

              if(choix_moteur == 1){
                /*m_vitesse_moteur=-100;
                m_vitesse_moteur=convertir_pourcentage_en_octet ();
                m_PWM_G[0]= m_vitesse_moteur;
                m_PWM_G[1]=255- m_vitesse_moteur;*/
                analogWrite(PMW_MOTEUR_A0,m_vitesse_moteur);
                digitalWrite(inputPontH2MoteurGauche,LOW);
                //analogWrite(PMW_MOTEUR_A1,255-m_vitesse_moteur);
                }

               if(choix_moteur == 2){
                 /*m_vitesse_moteur=-100;
                 m_vitesse_moteur=convertir_pourcentage_en_octet ();
                 m_PWM_D[0]= m_vitesse_moteur;
                 m_PWM_D[1]=255- m_vitesse_moteur;*/
                 analogWrite(PMW_MOTEUR_B0,m_vitesse_moteur);
                 digitalWrite(inputPontH2MoteurDroit,LOW);
                 //analogWrite(PMW_MOTEUR_B1,255-m_vitesse_moteur);
                }

}

//gérer le moteur pour qu'il roule vers sa destination
void Moteur::fonctionnement_moteur(double vitesseGauche, double vitesseDroit){
        //moteur gauche
        //if(vitesseGauche != 0){
            m_vitesse_moteur=  vitesseGauche;
            m_vitesse_moteur=convertir_pourcentage_en_octet ();
            //m_PWM_G[0]=m_PWM_G[1]=m_vitesse_moteur;
              if(m_vitesse_moteur>127){
                analogWrite(PMW_MOTEUR_B0,m_vitesse_moteur);
                digitalWrite(inputPontH2MoteurGauche,LOW);
              }
              else if(m_vitesse_moteur<127){
                analogWrite(PMW_MOTEUR_B0,m_vitesse_moteur);
                digitalWrite(inputPontH2MoteurGauche,HIGH);
              }
            //analogWrite(PMW_MOTEUR_A0,m_vitesse_moteur);
            //analogWrite(PMW_MOTEUR_A1,m_vitesse_moteur);
              else if(m_vitesse_moteur == 127){
                brake(1);
              }
        //}
        /*else{
            brake(1);
         }*/

        //moteur droit
        if(vitesseDroit != 0){
            m_vitesse_moteur= vitesseDroit;
            m_vitesse_moteur=convertir_pourcentage_en_octet ();
            //m_PWM_D[0]=m_PWM_D[1]=m_vitesse_moteur;
              //if(m_vitesse_moteur>=127){
                analogWrite(PMW_MOTEUR_A0,m_vitesse_moteur);
                digitalWrite(inputPontH2MoteurDroit,LOW);
              }
              else if(m_vitesse_moteur<127){
                analogWrite(PMW_MOTEUR_A0,m_vitesse_moteur);
                digitalWrite(inputPontH2MoteurDroit,HIGH);
              }
            //analogWrite(PMW_MOTEUR_B0,m_vitesse_moteur);
            //analogWrite(PMW_MOTEUR_B1,m_vitesse_moteur);
            //digitalWrite(PMW_MOTEUR_B1,!digitalRead(keep_B));
              else if(m_vitesse_moteur == 127){
                brake(2);
              }
        //}

          //envoieData();

}

// permet de convertir la vitesse exprimé en pourcentage (-100 à +100) en octet (de 0 à 255)
int Moteur::convertir_pourcentage_en_octet (){

        int vitesse=0;
	//vitesse moteur positif (0 à 100%)
        if((m_vitesse_moteur > 0) && (m_vitesse_moteur <= 100	)){
		vitesse=127+((m_vitesse_moteur*128)/100);

	}

        //vitesse moteur négatif (0 à -100%)
        if((m_vitesse_moteur <= 0) && (m_vitesse_moteur >= -100	)){
		vitesse=((100+m_vitesse_moteur)*127)/100;

	}

	return vitesse;
}

//_______________________________________________________________________________________________________
/*void Moteur::envoieData(){

        Serial1.write(m_PWM_G[0]);
        Serial1.write(m_PWM_G[1]);
        Serial1.write(m_PWM_D[0]);
        Serial1.write(m_PWM_D[1]);

}*/

// User defined analogWrite() to gain control of PWM initialization
/*void Moteur::analogWrite(uint16_t pin, uint8_t value) {
  TIM_OCInitTypeDef TIM_OCInitStructure;

  if (pin >= TOTAL_PINS || PIN_MAP[pin].timer_peripheral == NULL) {
    return;
  }
  // SPI safety check
  if (SPI.isEnabled() == true && (pin == SCK || pin == MOSI || pin == MISO)) {
    return;
  }
  // I2C safety check
  if (Wire.isEnabled() == true && (pin == SCL || pin == SDA)) {
    return;
  }
  // Serial1 safety check
  if (Serial1.isEnabled() == true && (pin == RX || pin == TX)) {
    return;
  }
  if (PIN_MAP[pin].pin_mode != OUTPUT && PIN_MAP[pin].pin_mode != AF_OUTPUT_PUSHPULL) {
    return;
  }
  // Don't re-init PWM and cause a glitch if already setup, just update duty cycle and return.
  if (PIN_MAP[pin].pin_mode == AF_OUTPUT_PUSHPULL) {
    TIM_OCInitStructure.TIM_Pulse = (uint16_t)(value * (TIM_ARR + 1) / 255);
    if (PIN_MAP[pin].timer_ch == TIM_Channel_1) {
      PIN_MAP[pin].timer_peripheral-> CCR1 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_2) {
      PIN_MAP[pin].timer_peripheral-> CCR2 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_3) {
      PIN_MAP[pin].timer_peripheral-> CCR3 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_4) {
      PIN_MAP[pin].timer_peripheral-> CCR4 = TIM_OCInitStructure.TIM_Pulse;
    }
    return;
  }

  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

  //PWM Frequency : PWM_FREQ (Hz)
  uint16_t TIM_Prescaler = (uint16_t)(SystemCoreClock / 24000000) - 1; //TIM Counter clock = 24MHz

  // TIM Channel Duty Cycle(%) = (TIM_CCR / TIM_ARR + 1) * 100
  uint16_t TIM_CCR = (uint16_t)(value * (TIM_ARR + 1) / 255);

  // AFIO clock enable
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);

  pinMode(pin, AF_OUTPUT_PUSHPULL);

  // TIM clock enable
  if (PIN_MAP[pin].timer_peripheral == TIM2)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
  else if (PIN_MAP[pin].timer_peripheral == TIM3)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
  else if (PIN_MAP[pin].timer_peripheral == TIM4)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

  // Time base configuration
  TIM_TimeBaseStructure.TIM_Period = TIM_ARR;
  TIM_TimeBaseStructure.TIM_Prescaler = TIM_Prescaler;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(PIN_MAP[pin].timer_peripheral, & TIM_TimeBaseStructure);

  // PWM1 Mode configuration
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OCInitStructure.TIM_Pulse = TIM_CCR;

  if (PIN_MAP[pin].timer_ch == TIM_Channel_1) {
    // PWM1 Mode configuration: Channel1
    TIM_OC1Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC1PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_2) {
    // PWM1 Mode configuration: Channel2
    TIM_OC2Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC2PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_3) {
    // PWM1 Mode configuration: Channel3
    TIM_OC3Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC3PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_4) {
    // PWM1 Mode configuration: Channel4
    TIM_OC4Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC4PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  }

  TIM_ARRPreloadConfig(PIN_MAP[pin].timer_peripheral, ENABLE);

  // TIM enable counter
  TIM_Cmd(PIN_MAP[pin].timer_peripheral, ENABLE);
}*/

<commit_msg>MAJ Pins : Ajout des pin IN1,IN2 pour gerer le sens du moteur<commit_after>/**
 *    \file moteur.cpp
 *    \brief Code contrôle des moteurs du grand Robot. Ce programme permet d'initialiser et d'envoyer 4 PWM (2 PWM pour chaque moteur) au driver moteur
 *
 *Codé pour "Spark core"  www.spark.io
 *
 *Par : Clément LETELLIER
 *      Mars 2014
 *Modification: Nicolas SOBCZAK
 *              Octobre 2016
*/

/* ======================================================================================================
 *      Include
 * ======================================================================================================
 */
#include "odometrie.h"
#include "Arduino.h"
#include "moteur.h"

/* ======================================================================================================
 *      Define
 * ======================================================================================================
 */
#define IN1MoteurB0 49 // IN1 moteur Gauche
#define IN2MoteurB0 50 // IN2 moteur Gauche
#define IN1MoteurA0 51 // IN1 moteur Droite
#define IN2MoteurA0 53 // IN2 moteur Droite
#define PWM_FREQ 20000 // in Hertz (SET YOUR FREQUENCY)

uint16_t TIM_ARR = (uint16_t)(24000000 / PWM_FREQ) - 1; // Don't change! Calc's period.

/* ======================================================================================================
 *      Class Moteur
 * ======================================================================================================
 */
//initialise le moteur lors de l'appelle
Moteur::Moteur(){
  m_vitesse_moteur=0;
}

//active le timer2 et 0 pour la PWM, active la PWM selon le moteur
void Moteur::initPWM(){
   pinMode(IN1MoteurB0,OUTPUT);
   pinMode(IN2MoteurB0,OUTPUT);
   pinMode(IN1MoteurA0,OUTPUT);
   pinMode(IN2MoteurA0,OUTPUT);
   pinMode(PMW_MOTEUR_A0 ,OUTPUT);
   pinMode(PMW_MOTEUR_B0 ,OUTPUT);

}

//permet de freiner les moteurs
void Moteur::brake(int choix_moteur){// potentiellement inutile pour frein mettre les motor a 0

              if(choix_moteur == 1){
                /*m_vitesse_moteur=-100;
                m_vitesse_moteur=convertir_pourcentage_en_octet ();
                m_PWM_G[0]= m_vitesse_moteur;
                m_PWM_G[1]=255- m_vitesse_moteur;*/
                analogWrite(PMW_MOTEUR_A0,m_vitesse_moteur);
                digitalWrite(IN1MoteurA0,LOW);
				digitalWrite(IN2MoteurA0,LOW);
                //analogWrite(PMW_MOTEUR_A1,255-m_vitesse_moteur);
                }

               if(choix_moteur == 2){
                 /*m_vitesse_moteur=-100;
                 m_vitesse_moteur=convertir_pourcentage_en_octet ();
                 m_PWM_D[0]= m_vitesse_moteur;
                 m_PWM_D[1]=255- m_vitesse_moteur;*/
                 analogWrite(PMW_MOTEUR_B0,m_vitesse_moteur);
                 digitalWrite(IN1MoteurB0,LOW);
				 digitalWrite(IN2MoteurB0,LOW);
                 //analogWrite(PMW_MOTEUR_B1,255-m_vitesse_moteur);
                }

}

//gérer le moteur pour qu'il roule vers sa destination
void Moteur::fonctionnement_moteur(double vitesseGauche, double vitesseDroit){
        //moteur gauche
        //if(vitesseGauche != 0){
            m_vitesse_moteur=  vitesseGauche;
            m_vitesse_moteur=convertir_pourcentage_en_octet ();
            //m_PWM_G[0]=m_PWM_G[1]=m_vitesse_moteur;
              if(m_vitesse_moteur>127){
                analogWrite(PMW_MOTEUR_B0,m_vitesse_moteur);
                digitalWrite(IN1MoteurB0,HIGH);// voire si le sens OK
				digitalWrite(IN2MoteurB0,LOW);// voire si le sens OK
              }
              else if(m_vitesse_moteur<127){
                analogWrite(PMW_MOTEUR_B0,m_vitesse_moteur);
                digitalWrite(IN1MoteurB0,LOW);// voire si le sens OK
				digitalWrite(IN2MoteurB0,HIGH);// voire si le sens OK
              }
            //analogWrite(PMW_MOTEUR_A0,m_vitesse_moteur);
            //analogWrite(PMW_MOTEUR_A1,m_vitesse_moteur);
              else if(m_vitesse_moteur == 127){
                brake(1);
              }
        //}
        /*else{
            brake(1);
         }*/

        //moteur droit
        //if(vitesseDroit != 0){
            m_vitesse_moteur= vitesseDroit;
            m_vitesse_moteur=convertir_pourcentage_en_octet ();
            //m_PWM_D[0]=m_PWM_D[1]=m_vitesse_moteur;
              if(m_vitesse_moteur>127){
                analogWrite(PMW_MOTEUR_A0,m_vitesse_moteur);
                digitalWrite(IN1MoteurA0,HIGH);// voire si le sens OK
				digitalWrite(IN2MoteurA0,LOW);// voire si le sens OK
              }
              else if(m_vitesse_moteur<127){
                analogWrite(PMW_MOTEUR_A0,m_vitesse_moteur);
                digitalWrite(IN1MoteurB0,LOW);// voire si le sens OK
				digitalWrite(IN2MoteurB0,HIGH);// voire si le sens OK
              }
            //analogWrite(PMW_MOTEUR_B0,m_vitesse_moteur);
            //analogWrite(PMW_MOTEUR_B1,m_vitesse_moteur);
            //digitalWrite(PMW_MOTEUR_B1,!digitalRead(keep_B));
              else if(m_vitesse_moteur == 127){
                brake(2);
              }
        //}

          //envoieData();

}

// permet de convertir la vitesse exprimé en pourcentage (-100 à +100) en octet (de 0 à 255)
int Moteur::convertir_pourcentage_en_octet (){

        int vitesse=0;
	//vitesse moteur positif (0 à 100%)
        if((m_vitesse_moteur > 0) && (m_vitesse_moteur <= 100	)){
		vitesse=127+((m_vitesse_moteur*128)/100);

	}

        //vitesse moteur négatif (0 à -100%)
        if((m_vitesse_moteur <= 0) && (m_vitesse_moteur >= -100	)){
		vitesse=((100+m_vitesse_moteur)*127)/100;

	}

	return vitesse;
}

//_______________________________________________________________________________________________________
/*void Moteur::envoieData(){

        Serial1.write(m_PWM_G[0]);
        Serial1.write(m_PWM_G[1]);
        Serial1.write(m_PWM_D[0]);
        Serial1.write(m_PWM_D[1]);

}*/

// User defined analogWrite() to gain control of PWM initialization
/*void Moteur::analogWrite(uint16_t pin, uint8_t value) {
  TIM_OCInitTypeDef TIM_OCInitStructure;

  if (pin >= TOTAL_PINS || PIN_MAP[pin].timer_peripheral == NULL) {
    return;
  }
  // SPI safety check
  if (SPI.isEnabled() == true && (pin == SCK || pin == MOSI || pin == MISO)) {
    return;
  }
  // I2C safety check
  if (Wire.isEnabled() == true && (pin == SCL || pin == SDA)) {
    return;
  }
  // Serial1 safety check
  if (Serial1.isEnabled() == true && (pin == RX || pin == TX)) {
    return;
  }
  if (PIN_MAP[pin].pin_mode != OUTPUT && PIN_MAP[pin].pin_mode != AF_OUTPUT_PUSHPULL) {
    return;
  }
  // Don't re-init PWM and cause a glitch if already setup, just update duty cycle and return.
  if (PIN_MAP[pin].pin_mode == AF_OUTPUT_PUSHPULL) {
    TIM_OCInitStructure.TIM_Pulse = (uint16_t)(value * (TIM_ARR + 1) / 255);
    if (PIN_MAP[pin].timer_ch == TIM_Channel_1) {
      PIN_MAP[pin].timer_peripheral-> CCR1 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_2) {
      PIN_MAP[pin].timer_peripheral-> CCR2 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_3) {
      PIN_MAP[pin].timer_peripheral-> CCR3 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_4) {
      PIN_MAP[pin].timer_peripheral-> CCR4 = TIM_OCInitStructure.TIM_Pulse;
    }
    return;
  }

  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

  //PWM Frequency : PWM_FREQ (Hz)
  uint16_t TIM_Prescaler = (uint16_t)(SystemCoreClock / 24000000) - 1; //TIM Counter clock = 24MHz

  // TIM Channel Duty Cycle(%) = (TIM_CCR / TIM_ARR + 1) * 100
  uint16_t TIM_CCR = (uint16_t)(value * (TIM_ARR + 1) / 255);

  // AFIO clock enable
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);

  pinMode(pin, AF_OUTPUT_PUSHPULL);

  // TIM clock enable
  if (PIN_MAP[pin].timer_peripheral == TIM2)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
  else if (PIN_MAP[pin].timer_peripheral == TIM3)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
  else if (PIN_MAP[pin].timer_peripheral == TIM4)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

  // Time base configuration
  TIM_TimeBaseStructure.TIM_Period = TIM_ARR;
  TIM_TimeBaseStructure.TIM_Prescaler = TIM_Prescaler;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(PIN_MAP[pin].timer_peripheral, & TIM_TimeBaseStructure);

  // PWM1 Mode configuration
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OCInitStructure.TIM_Pulse = TIM_CCR;

  if (PIN_MAP[pin].timer_ch == TIM_Channel_1) {
    // PWM1 Mode configuration: Channel1
    TIM_OC1Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC1PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_2) {
    // PWM1 Mode configuration: Channel2
    TIM_OC2Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC2PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_3) {
    // PWM1 Mode configuration: Channel3
    TIM_OC3Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC3PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_4) {
    // PWM1 Mode configuration: Channel4
    TIM_OC4Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC4PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  }

  TIM_ARRPreloadConfig(PIN_MAP[pin].timer_peripheral, ENABLE);

  // TIM enable counter
  TIM_Cmd(PIN_MAP[pin].timer_peripheral, ENABLE);
}*/

<|endoftext|>


<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */

#include <cassert>
#include <cinttypes>
#include <common/Detector.h>
#include <common/EFUArgs.h>
#include <iostream>
#include <libs/include/Socket.h>
#include <libs/include/Timer.h>
#include <memory>
#include <stdio.h>
#include <unistd.h>

using namespace std;
const char *classname = "UDPRaw Detector";

/** ----------------------------------------------------- */

class UDPRaw : public Detector {
public:
  UDPRaw(void *args);

  ~UDPRaw() { cout << "    UDPRaw destroyed" << endl; }

  void input_thread();

private:
  EFUArgs *opts;
};

UDPRaw::UDPRaw(void *args) {
  opts = (EFUArgs *)args;
  cout << "    UDPRaw created" << endl;
}

void UDPRaw::input_thread() {
  uint64_t rx_total = 0;
  uint64_t rx = 0;
  uint64_t rxp = 0;
  const int B1M = 1000000;

  assert(args != NULL);

  Socket::Endpoint local(opts->ip_addr.c_str(), opts->port);
  UDPServer raw(local);
  raw.printbuffers();
  raw.setbuffers(0, opts->rcvbuf);
  raw.printbuffers();
  Timer upd;
  auto usecs = upd.timeus();

  for (;;) {
    rx += raw.receive();

    if (rx > 0)
      rxp++;

    if ((rxp % 100) == 0)
      usecs = upd.timeus();

    if (usecs >= 1000000) {
      rx_total += rx;
      printf("Rx rate: %.2f Mbps, rx %" PRIu64 " MB (total: %" PRIu64
             " MB) %" PRIu64 " usecs\n",
             rx * 8.0 / usecs, rx / B1M, rx_total / B1M, usecs);
      rx = 0;
      upd.now();
      usecs = upd.timeus();
    }
  }
}

/** ----------------------------------------------------- */

class UDPRawFactory : public DetectorFactory {
public:
  std::shared_ptr<Detector> create(void *args) {
    return std::shared_ptr<Detector>(new UDPRaw(args));
  }
};

UDPRawFactory Factory;
<commit_msg>removed unused assert<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */

#include <cassert>
#include <cinttypes>
#include <common/Detector.h>
#include <common/EFUArgs.h>
#include <iostream>
#include <libs/include/Socket.h>
#include <libs/include/Timer.h>
#include <memory>
#include <stdio.h>
#include <unistd.h>

using namespace std;
const char *classname = "UDPRaw Detector";

/** ----------------------------------------------------- */

class UDPRaw : public Detector {
public:
  UDPRaw(void *args);

  ~UDPRaw() { cout << "    UDPRaw destroyed" << endl; }

  void input_thread();

private:
  EFUArgs *opts;
};

UDPRaw::UDPRaw(void *args) {
  opts = (EFUArgs *)args;
  cout << "    UDPRaw created" << endl;
}

void UDPRaw::input_thread() {
  uint64_t rx_total = 0;
  uint64_t rx = 0;
  uint64_t rxp = 0;
  const int B1M = 1000000;

  Socket::Endpoint local(opts->ip_addr.c_str(), opts->port);
  UDPServer raw(local);
  raw.printbuffers();
  raw.setbuffers(0, opts->rcvbuf);
  raw.printbuffers();
  Timer upd;
  auto usecs = upd.timeus();

  for (;;) {
    rx += raw.receive();

    if (rx > 0)
      rxp++;

    if ((rxp % 100) == 0)
      usecs = upd.timeus();

    if (usecs >= 1000000) {
      rx_total += rx;
      printf("Rx rate: %.2f Mbps, rx %" PRIu64 " MB (total: %" PRIu64
             " MB) %" PRIu64 " usecs\n",
             rx * 8.0 / usecs, rx / B1M, rx_total / B1M, usecs);
      rx = 0;
      upd.now();
      usecs = upd.timeus();
    }
  }
}

/** ----------------------------------------------------- */

class UDPRawFactory : public DetectorFactory {
public:
  std::shared_ptr<Detector> create(void *args) {
    return std::shared_ptr<Detector>(new UDPRaw(args));
  }
};

UDPRawFactory Factory;
<|endoftext|>


<commit_before>/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *sortList(ListNode *head) {
        if(!head || !head->next){
            return head;
        }

        return mergeSort(head);
    }

    ListNode* mergeSort(ListNode* head){
        if(!head || !head->next){
            return head;
        }

        // find the middle element

        ListNode *p=head, *q=head, *pre=NULL;

        while(q && q->next){
            q=q->next->next;
            pre=p;
            p=p->next;
        }

        pre->next=NULL; //split as two list

        ListNode* lh=mergeSort(head);
        ListNode* rh=mergeSort(p);
        return merge(lh,rh);
    }
    ListNode* merge(ListNode *lh, ListNode* rh){
        ListNode *temp=new ListNode(0);
        ListNode *p=temp;

        while(lh && rh){
            if(lh->val<=rh->val){
                p->next=lh;
                lh=lh->next;
            }else{
                p->next=rh;
                rh=rh->next;
            }
            p=p->next;
        }

        if(!lh){
            p->next=rh;
        }else{
            p->next=lh;
        }

        p=temp->next;
        delete temp;
        return p;

    }
};
<commit_msg>refactor merge sort list<commit_after>/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head==NULL || head->next==NULL){
            return head;
        }
        //split the list two
        ListNode *fast=head,*slow=head,*pre=NULL;

        while(fast && fast->next){
            fast=fast->next->next;
            pre=slow;
            slow=slow->next;
        }
        //cut the list
        pre->next=NULL;

        ListNode* lh = sortList(head);
        ListNode* rh = sortList(slow);

        return mergeTwoLists(lh,rh);
    }
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2){
        ListNode *dummy = new ListNode(-1);
        ListNode *cur=dummy;

        while(l1&&l2){
            if(l1->val<l2->val){
                cur->next=l1;
                l1=l1->next;
            }else{
                cur->next=l2;
                l2=l2->next;
            }
            cur=cur->next;
        }

        cur->next=(l1==NULL?l2:l1);
        return dummy->next;
    }
};<|endoftext|>


<commit_before>// The contents of this file are licensed under the MIT license.
// See LICENSE.txt for more information.

/*
  This program takes an XML file with a list of photos brown bears, finds all the
  bear faces and the face landmarks then outputs an XML metadata file.

  The input XML file can be generated using "imglab -c". The output file can be
  viewed and edited using imglab.

  The face detector uses a pretrained CNN from the dlib example:

  https://github.com/davisking/dlib/blob/master/examples/dnn_mmod_dog_hipsterizer.cpp

  While the model was trained for dogs, it works reasonably well for bears. The
  pretrained CNN data can be found here:

  http://dlib.net/files/mmod_dog_hipsterizer.dat.bz2
*/

#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <dlib/dnn.h>
#include <dlib/data_io.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_io.h>
// #include <ctype.h>
// #include <stdio.h>
// #include <stdlib.h>
#include <unistd.h>

using namespace std;
using namespace dlib;

// ----------------------------------------------------------------------------------------

template <long num_filters, typename SUBNET> using con5d = con<num_filters,5,5,2,2,SUBNET>;
template <long num_filters, typename SUBNET> using con5  = con<num_filters,5,5,1,1,SUBNET>;

template <typename SUBNET> using downsampler  = relu<affine<con5d<32, relu<affine<con5d<32, relu<affine<con5d<16,SUBNET>>>>>>>>>;
template <typename SUBNET> using rcon5  = relu<affine<con5<45,SUBNET>>>;

using net_type = loss_mmod<con<1,9,9,1,1,rcon5<rcon5<rcon5<downsampler<input_rgb_image_pyramid<pyramid_down<6>>>>>>>>;

// ----------------------------------------------------------------------------------------

const unsigned MAX_LONG_SIDE = 5000;
const unsigned MAX_SIZE = MAX_LONG_SIDE*3500;

// Find Faces and face landmarks
void find_faces (
  net_type& net,
  shape_predictor& sp,
  matrix<rgb_pixel>& img,
  std::vector<image_dataset_metadata::box>& faces,
  std::string bearID
)
{
  bool bUpscaled = false;
  bool bDownscaled = false;
  float pxRatio;

  // cout << "Image size: " << img.size() << " NR: " << img.nr() << " NC: " << img.nc() << endl;

  // If the image is too big (this is a memory constraint), we need to downsample it
  if (img.size() > (MAX_SIZE))
  {
    if (img.nc() > img.nr())
      pxRatio = (float)MAX_LONG_SIDE / (float)img.nc();
    else
      pxRatio = (float)MAX_LONG_SIDE / (float)img.nr();
    cout << "File TOO BIG" << " Ratio: " << pxRatio << endl;
    //cout << "New X: " << (int)(img.nc() * pxRatio) << " New Y: " << (int)(img.nr() * pxRatio) << endl;
    matrix<rgb_pixel> smimg((int)(img.nr() * pxRatio), (int)(img.nc() * pxRatio));
    resize_image(img, smimg);
    //resize_image((double)2.0, img);
    //resize_image(img, smimg, interpolate_billinear());
    //resize_image((double)(MAX_SIZE / img.size()), itImage);
    //pyramid_down(img);
    //cout << "Rescaled image size: " << smimg.size() << " NR: " << smimg.nr() << " NC: " << smimg.nc() << endl;
    bDownscaled = true;
    img = smimg;
    //return;
  }

  // Upsampling the image will allow us to find smaller faces but will use more
  // computational resources.
  //pyramid_up(img);

  // Find faces
  auto dets = net(img);

  // if no faces, try with upscaling
  if ((dets.size() == 0) && !bDownscaled)
  {
    if (img.size() > (MAX_SIZE/4))
    {
      //cout << "File TOO BIG to UPSCALE" << endl;
      return;
    }

    pyramid_up(img);
    //cout << "File UPSCALED" << endl;
    dets = net(img);

    if (dets.size() == 0)
    {
      //cout << "File has no faces" << endl;
      return;
    }
    cout << "Upscaled image size: " << img.size() << endl;
    bUpscaled = true;
  }

  // For each face, find the face landmarks
  for (auto&& d : dets)
  {
      // get the landmarks for this face
      auto shape = sp(img, d.rect);

      // fill in the data to faces
      image_dataset_metadata::box face;

      if (bUpscaled)
      {
        cout << "File was upscaled" << endl;
        // TODO figure out the scale factor from pyramid_up
        face.rect.set_left(d.rect.left() / 2);
        face.rect.set_top(d.rect.top() / 2);
        face.rect.set_right(d.rect.right() / 2);
        face.rect.set_bottom(d.rect.bottom() / 2);
        face.parts["top"].x()  = shape.part(0).x() / 2;
        face.parts["top"].y()  = shape.part(0).y() / 2;
        face.parts["lear"].x() = shape.part(1).x() / 2;
        face.parts["lear"].y() = shape.part(1).y() / 2;
        face.parts["leye"].x() = shape.part(2).x() / 2;
        face.parts["leye"].y() = shape.part(2).y() / 2;
        face.parts["nose"].x() = shape.part(3).x() / 2;
        face.parts["nose"].y() = shape.part(3).y() / 2;
        face.parts["rear"].x() = shape.part(4).x() / 2;
        face.parts["rear"].y() = shape.part(4).y() / 2;
        face.parts["reye"].x() = shape.part(5).x() / 2;
        face.parts["reye"].y() = shape.part(5).y() / 2;
      }
      else if (bDownscaled)
      {
        cout << "File was downscaled" << endl;
        // TODO figure out the scale factor from pyramid_up
        face.rect.set_left((int)((float)d.rect.left() / pxRatio));
        face.rect.set_top((int)((float)d.rect.top() / pxRatio));
        face.rect.set_right((int)((float)d.rect.right() / pxRatio));
        face.rect.set_bottom((int)((float)d.rect.bottom() / pxRatio));
        face.parts["top"].x()  = (int)((float)shape.part(0).x() / pxRatio);
        face.parts["top"].y()  = (int)((float)shape.part(0).y() / pxRatio);
        face.parts["lear"].x() = (int)((float)shape.part(1).x() / pxRatio);
        face.parts["lear"].y() = (int)((float)shape.part(1).y() / pxRatio);
        face.parts["leye"].x() = (int)((float)shape.part(2).x() / pxRatio);
        face.parts["leye"].y() = (int)((float)shape.part(2).y() / pxRatio);
        face.parts["nose"].x() = (int)((float)shape.part(3).x() / pxRatio);
        face.parts["nose"].y() = (int)((float)shape.part(3).y() / pxRatio);
        face.parts["rear"].x() = (int)((float)shape.part(4).x() / pxRatio);
        face.parts["rear"].y() = (int)((float)shape.part(4).y() / pxRatio);
        face.parts["reye"].x() = (int)((float)shape.part(5).x() / pxRatio);
        face.parts["reye"].y() = (int)((float)shape.part(5).y() / pxRatio);
      }
      else
      {
        face.rect = d.rect;
        face.parts["top"]  = shape.part(0);
        face.parts["lear"] = shape.part(1);
        face.parts["leye"] = shape.part(2);
        face.parts["nose"] = shape.part(3);
        face.parts["rear"] = shape.part(4);
        face.parts["reye"] = shape.part(5);
      }
	  face.label = bearID;
      faces.push_back(face);
  }
}

// ----------------------------------------------------------------------------------------

int main(int argc, char** argv) try
{
    //image_window win_wireframe;
    int total_faces = 0;

	//----------------------------------------------------------------------
	int aflag = 0;
	int bflag = 0;
	char *lvalue = NULL;
	int index;
	int c;
	std::string bearID;

	while ((c = getopt (argc, argv, "l:")) != -1)
	  switch (c)
		{
		case 'l':
		  bearID = optarg;
		  break;
		default:
		  cout << "unrecognized argument: " << c << endl;
		  cout << "\nUsage:" << endl;
		  cout << "\t./bearface [-l label] mmod_dog_hipsterizer.dat <source_img_file>" << endl;
		  cout << "\nDetect bear faces in images.\n" << endl;
		  cout << "mmod_dog_hipsterizer.dat can be found at:\n";
		  cout << "\t /home/bearid/dlib-data/mmod_dog_hipsterizer.dat\n" << endl;
		  return 0;
    }
	if ((argc - optind) != 2)
	{
		cout << "\nUsage:" << endl;
		cout << "\t./bearface [-l label] mmod_dog_hipsterizer.dat <source_img_file>" << endl;
		cout << "\nDetect bear faces in images.\n" << endl;
		cout << "mmod_dog_hipsterizer.dat can be found at:\n";
		cout << "\t /home/bearid/dlib-data/mmod_dog_hipsterizer.dat\n" << endl;
		return 0;
	}
	std::string network = argv[optind];
	std::string imgs_file = argv[optind+1];

    // load the models as well as glasses and mustache.
    net_type net;
    shape_predictor sp;
    matrix<rgb_alpha_pixel> glasses, mustache;
    deserialize(network) >> net >> sp >> glasses >> mustache;

    // Load XML metadata file
    dlib::image_dataset_metadata::dataset data;
    load_image_dataset_metadata(data, imgs_file);

    //Handle list of images
	std::vector <string> fields;
    for (int i = 0; i < data.images.size(); ++i)
    {
        matrix<rgb_pixel> img;

        cout << data.images[i].filename.c_str() << "...";
        load_image(img, data.images[i].filename.c_str());

		if (bearID.empty ())
		{
			std::string fullpathfile = data.images[i].filename;
			boost::split( fields, fullpathfile, boost::is_any_of( "/" ));
			bearID = fields[fields.size() - 2];
		}
        std::vector<image_dataset_metadata::box> faces;
        find_faces (net, sp, img, faces, bearID);
        data.images[i].boxes = faces;

        cout << "faces found: " << to_string(faces.size()) << endl;
        total_faces += faces.size();
    }
    cout << "Total faces found: " << total_faces << endl;
	boost::filesystem::path orig_path(imgs_file);
	std::string faces_file = orig_path.stem().string() + "_faces.xml";
    save_image_dataset_metadata(data, faces_file);
	cout << "\n\tGenerated with label " << bearID <<  ": " << faces_file << "\n" << endl;
}
catch(std::exception& e)
{
    cout << e.what() << endl;
}
<commit_msg>If no -l, use bearID from path for each file<commit_after>// The contents of this file are licensed under the MIT license.
// See LICENSE.txt for more information.

/*
  This program takes an XML file with a list of photos brown bears, finds all the
  bear faces and the face landmarks then outputs an XML metadata file.

  The input XML file can be generated using "imglab -c". The output file can be
  viewed and edited using imglab.

  The face detector uses a pretrained CNN from the dlib example:

  https://github.com/davisking/dlib/blob/master/examples/dnn_mmod_dog_hipsterizer.cpp

  While the model was trained for dogs, it works reasonably well for bears. The
  pretrained CNN data can be found here:

  http://dlib.net/files/mmod_dog_hipsterizer.dat.bz2
*/

#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <dlib/dnn.h>
#include <dlib/data_io.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_io.h>
// #include <ctype.h>
// #include <stdio.h>
// #include <stdlib.h>
#include <unistd.h>

using namespace std;
using namespace dlib;

// ----------------------------------------------------------------------------------------

template <long num_filters, typename SUBNET> using con5d = con<num_filters,5,5,2,2,SUBNET>;
template <long num_filters, typename SUBNET> using con5  = con<num_filters,5,5,1,1,SUBNET>;

template <typename SUBNET> using downsampler  = relu<affine<con5d<32, relu<affine<con5d<32, relu<affine<con5d<16,SUBNET>>>>>>>>>;
template <typename SUBNET> using rcon5  = relu<affine<con5<45,SUBNET>>>;

using net_type = loss_mmod<con<1,9,9,1,1,rcon5<rcon5<rcon5<downsampler<input_rgb_image_pyramid<pyramid_down<6>>>>>>>>;

// ----------------------------------------------------------------------------------------

const unsigned MAX_LONG_SIDE = 5000;
const unsigned MAX_SIZE = MAX_LONG_SIDE*3500;

// Find Faces and face landmarks
void find_faces (
  net_type& net,
  shape_predictor& sp,
  matrix<rgb_pixel>& img,
  std::vector<image_dataset_metadata::box>& faces,
  std::string bearID
)
{
  bool bUpscaled = false;
  bool bDownscaled = false;
  float pxRatio;

  // cout << "Image size: " << img.size() << " NR: " << img.nr() << " NC: " << img.nc() << endl;

  // If the image is too big (this is a memory constraint), we need to downsample it
  if (img.size() > (MAX_SIZE))
  {
    if (img.nc() > img.nr())
      pxRatio = (float)MAX_LONG_SIDE / (float)img.nc();
    else
      pxRatio = (float)MAX_LONG_SIDE / (float)img.nr();
    cout << "File TOO BIG" << " Ratio: " << pxRatio << endl;
    //cout << "New X: " << (int)(img.nc() * pxRatio) << " New Y: " << (int)(img.nr() * pxRatio) << endl;
    matrix<rgb_pixel> smimg((int)(img.nr() * pxRatio), (int)(img.nc() * pxRatio));
    resize_image(img, smimg);
    //resize_image((double)2.0, img);
    //resize_image(img, smimg, interpolate_billinear());
    //resize_image((double)(MAX_SIZE / img.size()), itImage);
    //pyramid_down(img);
    //cout << "Rescaled image size: " << smimg.size() << " NR: " << smimg.nr() << " NC: " << smimg.nc() << endl;
    bDownscaled = true;
    img = smimg;
    //return;
  }

  // Upsampling the image will allow us to find smaller faces but will use more
  // computational resources.
  //pyramid_up(img);

  // Find faces
  auto dets = net(img);

  // if no faces, try with upscaling
  if ((dets.size() == 0) && !bDownscaled)
  {
    if (img.size() > (MAX_SIZE/4))
    {
      //cout << "File TOO BIG to UPSCALE" << endl;
      return;
    }

    pyramid_up(img);
    //cout << "File UPSCALED" << endl;
    dets = net(img);

    if (dets.size() == 0)
    {
      //cout << "File has no faces" << endl;
      return;
    }
    cout << "Upscaled image size: " << img.size() << endl;
    bUpscaled = true;
  }

  // For each face, find the face landmarks
  for (auto&& d : dets)
  {
      // get the landmarks for this face
      auto shape = sp(img, d.rect);

      // fill in the data to faces
      image_dataset_metadata::box face;

      if (bUpscaled)
      {
        cout << "File was upscaled" << endl;
        // TODO figure out the scale factor from pyramid_up
        face.rect.set_left(d.rect.left() / 2);
        face.rect.set_top(d.rect.top() / 2);
        face.rect.set_right(d.rect.right() / 2);
        face.rect.set_bottom(d.rect.bottom() / 2);
        face.parts["top"].x()  = shape.part(0).x() / 2;
        face.parts["top"].y()  = shape.part(0).y() / 2;
        face.parts["lear"].x() = shape.part(1).x() / 2;
        face.parts["lear"].y() = shape.part(1).y() / 2;
        face.parts["leye"].x() = shape.part(2).x() / 2;
        face.parts["leye"].y() = shape.part(2).y() / 2;
        face.parts["nose"].x() = shape.part(3).x() / 2;
        face.parts["nose"].y() = shape.part(3).y() / 2;
        face.parts["rear"].x() = shape.part(4).x() / 2;
        face.parts["rear"].y() = shape.part(4).y() / 2;
        face.parts["reye"].x() = shape.part(5).x() / 2;
        face.parts["reye"].y() = shape.part(5).y() / 2;
      }
      else if (bDownscaled)
      {
        cout << "File was downscaled" << endl;
        // TODO figure out the scale factor from pyramid_up
        face.rect.set_left((int)((float)d.rect.left() / pxRatio));
        face.rect.set_top((int)((float)d.rect.top() / pxRatio));
        face.rect.set_right((int)((float)d.rect.right() / pxRatio));
        face.rect.set_bottom((int)((float)d.rect.bottom() / pxRatio));
        face.parts["top"].x()  = (int)((float)shape.part(0).x() / pxRatio);
        face.parts["top"].y()  = (int)((float)shape.part(0).y() / pxRatio);
        face.parts["lear"].x() = (int)((float)shape.part(1).x() / pxRatio);
        face.parts["lear"].y() = (int)((float)shape.part(1).y() / pxRatio);
        face.parts["leye"].x() = (int)((float)shape.part(2).x() / pxRatio);
        face.parts["leye"].y() = (int)((float)shape.part(2).y() / pxRatio);
        face.parts["nose"].x() = (int)((float)shape.part(3).x() / pxRatio);
        face.parts["nose"].y() = (int)((float)shape.part(3).y() / pxRatio);
        face.parts["rear"].x() = (int)((float)shape.part(4).x() / pxRatio);
        face.parts["rear"].y() = (int)((float)shape.part(4).y() / pxRatio);
        face.parts["reye"].x() = (int)((float)shape.part(5).x() / pxRatio);
        face.parts["reye"].y() = (int)((float)shape.part(5).y() / pxRatio);
      }
      else
      {
        face.rect = d.rect;
        face.parts["top"]  = shape.part(0);
        face.parts["lear"] = shape.part(1);
        face.parts["leye"] = shape.part(2);
        face.parts["nose"] = shape.part(3);
        face.parts["rear"] = shape.part(4);
        face.parts["reye"] = shape.part(5);
      }
	  face.label = bearID;
      faces.push_back(face);
  }
}

// ----------------------------------------------------------------------------------------

int main(int argc, char** argv) try
{
    //image_window win_wireframe;
    int total_faces = 0;

	//----------------------------------------------------------------------
	int aflag = 0;
	int bflag = 0;
	char *lvalue = NULL;
	int index;
	int c;
	std::string bearID;
  bool bLabelFixed = false;

	while ((c = getopt (argc, argv, "l:")) != -1)
	  switch (c)
		{
		case 'l':
		  bearID = optarg;
      bLabelFixed = true;
		  break;
		default:
		  cout << "unrecognized argument: " << c << endl;
		  cout << "\nUsage:" << endl;
		  cout << "\t./bearface [-l label] mmod_dog_hipsterizer.dat <source_img_file>" << endl;
		  cout << "\nDetect bear faces in images.\n" << endl;
		  cout << "mmod_dog_hipsterizer.dat can be found at:\n";
		  cout << "\t /home/bearid/dlib-data/mmod_dog_hipsterizer.dat\n" << endl;
		  return 0;
    }
	if ((argc - optind) != 2)
	{
		cout << "\nUsage:" << endl;
		cout << "\t./bearface [-l label] mmod_dog_hipsterizer.dat <source_img_file>" << endl;
		cout << "\nDetect bear faces in images.\n" << endl;
		cout << "mmod_dog_hipsterizer.dat can be found at:\n";
		cout << "\t /home/bearid/dlib-data/mmod_dog_hipsterizer.dat\n" << endl;
		return 0;
	}
	std::string network = argv[optind];
	std::string imgs_file = argv[optind+1];

    // load the models as well as glasses and mustache.
    net_type net;
    shape_predictor sp;
    matrix<rgb_alpha_pixel> glasses, mustache;
    deserialize(network) >> net >> sp >> glasses >> mustache;

    // Load XML metadata file
    dlib::image_dataset_metadata::dataset data;
    load_image_dataset_metadata(data, imgs_file);

    //Handle list of images
	std::vector <string> fields;
    for (int i = 0; i < data.images.size(); ++i)
    {
        matrix<rgb_pixel> img;

        cout << data.images[i].filename.c_str() << "...";
        load_image(img, data.images[i].filename.c_str());

		if (!bLabelFixed)
		{
			std::string fullpathfile = data.images[i].filename;
			boost::split( fields, fullpathfile, boost::is_any_of( "/" ));
			bearID = fields[fields.size() - 2];
		}
        std::vector<image_dataset_metadata::box> faces;
        find_faces (net, sp, img, faces, bearID);
        data.images[i].boxes = faces;

        cout << "faces found: " << to_string(faces.size()) << endl;
        total_faces += faces.size();
    }
    cout << "Total faces found: " << total_faces << endl;
	boost::filesystem::path orig_path(imgs_file);
	std::string faces_file = orig_path.stem().string() + "_faces.xml";
    save_image_dataset_metadata(data, faces_file);
    if (!bLabelFixed)
    {
      cout << "\n\tGenerated with no label: " << faces_file << "\n" << endl;
    }
    else
    {
      cout << "\n\tGenerated with label " << bearID <<  ": " << faces_file << "\n" << endl;
    }
}
catch(std::exception& e)
{
    cout << e.what() << endl;
}
<|endoftext|>