<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "cellkeytranslator.hxx"
#include "comphelper/processfactory.hxx"
#include "i18npool/mslangid.hxx"
#include "i18npool/lang.h"
#include "rtl/ustring.hxx"

#include <com/sun/star/i18n/TransliterationModules.hpp>

using ::com::sun::star::lang::Locale;
using ::com::sun::star::uno::Sequence;
using ::std::list;
using ::boost::unordered_map;
using ::rtl::OUString;

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

enum LocaleMatch
{
    LOCALE_MATCH_NONE = 0,
    LOCALE_MATCH_LANG,
    LOCALE_MATCH_LANG_COUNTRY,
    LOCALE_MATCH_ALL
};

static LocaleMatch lclLocaleCompare(const Locale& rLocale1, const Locale& rLocale2)
{
    LocaleMatch eMatchLevel = LOCALE_MATCH_NONE;
    if ( !rLocale1.Language.compareTo(rLocale1.Language) )
        eMatchLevel = LOCALE_MATCH_LANG;
    else
        return eMatchLevel;

    if ( !rLocale1.Country.compareTo(rLocale2.Country) )
        eMatchLevel = LOCALE_MATCH_LANG_COUNTRY;
    else
        return eMatchLevel;

    if ( !rLocale1.Variant.compareTo(rLocale2.Variant) )
        eMatchLevel = LOCALE_MATCH_ALL;

    return eMatchLevel;
}

ScCellKeyword::ScCellKeyword(const sal_Char* pName, OpCode eOpCode, const Locale& rLocale) :
    mpName(pName),
    meOpCode(eOpCode),
    mrLocale(rLocale)
{
}

::std::auto_ptr<ScCellKeywordTranslator> ScCellKeywordTranslator::spInstance(NULL);

static void lclMatchKeyword(String& rName, const ScCellKeywordHashMap& aMap,
                            OpCode eOpCode = ocNone, const Locale* pLocale = NULL)
{
    ScCellKeywordHashMap::const_iterator itrEnd = aMap.end();
    ScCellKeywordHashMap::const_iterator itr = aMap.find(rName);

    if ( itr == itrEnd || itr->second.empty() )
        // No candidate strings exist.  Bail out.
        return;

    if ( eOpCode == ocNone && !pLocale )
    {
        // Since no locale nor opcode matching is needed, simply return
        // the first item on the list.
        rName = rtl::OUString::createFromAscii( itr->second.front().mpName );
        return;
    }

    const sal_Char* aBestMatchName = itr->second.front().mpName;
    LocaleMatch eLocaleMatchLevel = LOCALE_MATCH_NONE;
    bool bOpCodeMatched = false;

    list<ScCellKeyword>::const_iterator itrListEnd = itr->second.end();
    list<ScCellKeyword>::const_iterator itrList = itr->second.begin();
    for ( ; itrList != itrListEnd; ++itrList )
    {
        if ( eOpCode != ocNone && pLocale )
        {
            if ( itrList->meOpCode == eOpCode )
            {
                LocaleMatch eLevel = lclLocaleCompare(itrList->mrLocale, *pLocale);
                if ( eLevel == LOCALE_MATCH_ALL )
                {
                    // Name with matching opcode and locale found.
                    rName = rtl::OUString::createFromAscii( itrList->mpName );
                    return;
                }
                else if ( eLevel > eLocaleMatchLevel )
                {
                    // Name with a better matching locale.
                    eLocaleMatchLevel = eLevel;
                    aBestMatchName = itrList->mpName;
                }
                else if ( !bOpCodeMatched )
                    // At least the opcode matches.
                    aBestMatchName = itrList->mpName;

                bOpCodeMatched = true;
            }
        }
        else if ( eOpCode != ocNone && !pLocale )
        {
            if ( itrList->meOpCode == eOpCode )
            {
                // Name with a matching opcode preferred.
                rName = rtl::OUString::createFromAscii( itrList->mpName );
                return;
            }
        }
        else if ( !eOpCode && pLocale )
        {
            LocaleMatch eLevel = lclLocaleCompare(itrList->mrLocale, *pLocale);
            if ( eLevel == LOCALE_MATCH_ALL )
            {
                // Name with matching locale preferred.
                rName = rtl::OUString::createFromAscii( itrList->mpName );
                return;
            }
            else if ( eLevel > eLocaleMatchLevel )
            {
                // Name with a better matching locale.
                eLocaleMatchLevel = eLevel;
                aBestMatchName = itrList->mpName;
            }
        }
    }

    // No preferred strings found.  Return the best matching name.
    rName = rtl::OUString::createFromAscii(aBestMatchName);
}

void ScCellKeywordTranslator::transKeyword(String& rName, const Locale* pLocale, OpCode eOpCode)
{
    if ( !spInstance.get() )
        spInstance.reset( new ScCellKeywordTranslator );

    LanguageType eLang = pLocale ? LanguageTag(*pLocale).makeFallback().getLanguageType() : LANGUAGE_SYSTEM;
    Sequence<sal_Int32> aOffsets;
    rName = spInstance->maTransWrapper.transliterate(rName, eLang, 0, rName.Len(), &aOffsets);
    lclMatchKeyword(rName, spInstance->maStringNameMap, eOpCode, pLocale);
}

void ScCellKeywordTranslator::transKeyword(rtl::OUString& rName, const Locale* pLocale, OpCode eOpCode)
{
    String aName = rName;
    transKeyword(aName, pLocale, eOpCode);
    rName = aName;
}

ScCellKeywordTranslator::ScCellKeywordTranslator() :
    maTransWrapper( ::comphelper::getProcessComponentContext(),
                    i18n::TransliterationModules_LOWERCASE_UPPERCASE )
{
    init();
}

ScCellKeywordTranslator::~ScCellKeywordTranslator()
{
}

struct TransItem
{
    const sal_Unicode*  from;
    const sal_Char*     to;
    OpCode              func;
};

void ScCellKeywordTranslator::init()
{
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );

    // The file below has been autogenerated by sc/workben/celltrans/parse.py.
    // To add new locale keywords, edit sc/workben/celltrans/keywords_utf16.txt
    // and re-run the parse.py script.
    //
    // All keywords must be uppercase, and the mapping must be from the
    // localized keyword to the English keyword.
    //
    // Make sure that the original keyword file (keywords_utf16.txt) is
    // encoded in UCS-2/UTF-16!

    #include "cellkeywords.inl"
}

void ScCellKeywordTranslator::addToMap(const String& rKey, const sal_Char* pName, const Locale& rLocale, OpCode eOpCode)
{
    ScCellKeyword aKeyItem( pName, eOpCode, rLocale );

    ScCellKeywordHashMap::iterator itrEnd = maStringNameMap.end();
    ScCellKeywordHashMap::iterator itr = maStringNameMap.find(rKey);

    if ( itr == itrEnd )
    {
        // New keyword.
        list<ScCellKeyword> aList;
        aList.push_back(aKeyItem);
        maStringNameMap.insert( ScCellKeywordHashMap::value_type(rKey, aList) );
    }
    else
        itr->second.push_back(aKeyItem);
}

void ScCellKeywordTranslator::addToMap(const TransItem* pItems, const Locale& rLocale)
{
    for (sal_uInt16 i = 0; pItems[i].from != NULL; ++i)
        addToMap(rtl::OUString(pItems[i].from), pItems[i].to, rLocale, pItems[i].func);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity: fix copy & paste error<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "cellkeytranslator.hxx"
#include "comphelper/processfactory.hxx"
#include "i18npool/mslangid.hxx"
#include "i18npool/lang.h"
#include "rtl/ustring.hxx"

#include <com/sun/star/i18n/TransliterationModules.hpp>

using ::com::sun::star::lang::Locale;
using ::com::sun::star::uno::Sequence;
using ::std::list;
using ::boost::unordered_map;
using ::rtl::OUString;

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

enum LocaleMatch
{
    LOCALE_MATCH_NONE = 0,
    LOCALE_MATCH_LANG,
    LOCALE_MATCH_LANG_COUNTRY,
    LOCALE_MATCH_ALL
};

static LocaleMatch lclLocaleCompare(const Locale& rLocale1, const Locale& rLocale2)
{
    LocaleMatch eMatchLevel = LOCALE_MATCH_NONE;
    if ( !rLocale1.Language.compareTo(rLocale2.Language) )
        eMatchLevel = LOCALE_MATCH_LANG;
    else
        return eMatchLevel;

    if ( !rLocale1.Country.compareTo(rLocale2.Country) )
        eMatchLevel = LOCALE_MATCH_LANG_COUNTRY;
    else
        return eMatchLevel;

    if ( !rLocale1.Variant.compareTo(rLocale2.Variant) )
        eMatchLevel = LOCALE_MATCH_ALL;

    return eMatchLevel;
}

ScCellKeyword::ScCellKeyword(const sal_Char* pName, OpCode eOpCode, const Locale& rLocale) :
    mpName(pName),
    meOpCode(eOpCode),
    mrLocale(rLocale)
{
}

::std::auto_ptr<ScCellKeywordTranslator> ScCellKeywordTranslator::spInstance(NULL);

static void lclMatchKeyword(String& rName, const ScCellKeywordHashMap& aMap,
                            OpCode eOpCode = ocNone, const Locale* pLocale = NULL)
{
    ScCellKeywordHashMap::const_iterator itrEnd = aMap.end();
    ScCellKeywordHashMap::const_iterator itr = aMap.find(rName);

    if ( itr == itrEnd || itr->second.empty() )
        // No candidate strings exist.  Bail out.
        return;

    if ( eOpCode == ocNone && !pLocale )
    {
        // Since no locale nor opcode matching is needed, simply return
        // the first item on the list.
        rName = rtl::OUString::createFromAscii( itr->second.front().mpName );
        return;
    }

    const sal_Char* aBestMatchName = itr->second.front().mpName;
    LocaleMatch eLocaleMatchLevel = LOCALE_MATCH_NONE;
    bool bOpCodeMatched = false;

    list<ScCellKeyword>::const_iterator itrListEnd = itr->second.end();
    list<ScCellKeyword>::const_iterator itrList = itr->second.begin();
    for ( ; itrList != itrListEnd; ++itrList )
    {
        if ( eOpCode != ocNone && pLocale )
        {
            if ( itrList->meOpCode == eOpCode )
            {
                LocaleMatch eLevel = lclLocaleCompare(itrList->mrLocale, *pLocale);
                if ( eLevel == LOCALE_MATCH_ALL )
                {
                    // Name with matching opcode and locale found.
                    rName = rtl::OUString::createFromAscii( itrList->mpName );
                    return;
                }
                else if ( eLevel > eLocaleMatchLevel )
                {
                    // Name with a better matching locale.
                    eLocaleMatchLevel = eLevel;
                    aBestMatchName = itrList->mpName;
                }
                else if ( !bOpCodeMatched )
                    // At least the opcode matches.
                    aBestMatchName = itrList->mpName;

                bOpCodeMatched = true;
            }
        }
        else if ( eOpCode != ocNone && !pLocale )
        {
            if ( itrList->meOpCode == eOpCode )
            {
                // Name with a matching opcode preferred.
                rName = rtl::OUString::createFromAscii( itrList->mpName );
                return;
            }
        }
        else if ( !eOpCode && pLocale )
        {
            LocaleMatch eLevel = lclLocaleCompare(itrList->mrLocale, *pLocale);
            if ( eLevel == LOCALE_MATCH_ALL )
            {
                // Name with matching locale preferred.
                rName = rtl::OUString::createFromAscii( itrList->mpName );
                return;
            }
            else if ( eLevel > eLocaleMatchLevel )
            {
                // Name with a better matching locale.
                eLocaleMatchLevel = eLevel;
                aBestMatchName = itrList->mpName;
            }
        }
    }

    // No preferred strings found.  Return the best matching name.
    rName = rtl::OUString::createFromAscii(aBestMatchName);
}

void ScCellKeywordTranslator::transKeyword(String& rName, const Locale* pLocale, OpCode eOpCode)
{
    if ( !spInstance.get() )
        spInstance.reset( new ScCellKeywordTranslator );

    LanguageType eLang = pLocale ? LanguageTag(*pLocale).makeFallback().getLanguageType() : LANGUAGE_SYSTEM;
    Sequence<sal_Int32> aOffsets;
    rName = spInstance->maTransWrapper.transliterate(rName, eLang, 0, rName.Len(), &aOffsets);
    lclMatchKeyword(rName, spInstance->maStringNameMap, eOpCode, pLocale);
}

void ScCellKeywordTranslator::transKeyword(rtl::OUString& rName, const Locale* pLocale, OpCode eOpCode)
{
    String aName = rName;
    transKeyword(aName, pLocale, eOpCode);
    rName = aName;
}

ScCellKeywordTranslator::ScCellKeywordTranslator() :
    maTransWrapper( ::comphelper::getProcessComponentContext(),
                    i18n::TransliterationModules_LOWERCASE_UPPERCASE )
{
    init();
}

ScCellKeywordTranslator::~ScCellKeywordTranslator()
{
}

struct TransItem
{
    const sal_Unicode*  from;
    const sal_Char*     to;
    OpCode              func;
};

void ScCellKeywordTranslator::init()
{
    ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );

    // The file below has been autogenerated by sc/workben/celltrans/parse.py.
    // To add new locale keywords, edit sc/workben/celltrans/keywords_utf16.txt
    // and re-run the parse.py script.
    //
    // All keywords must be uppercase, and the mapping must be from the
    // localized keyword to the English keyword.
    //
    // Make sure that the original keyword file (keywords_utf16.txt) is
    // encoded in UCS-2/UTF-16!

    #include "cellkeywords.inl"
}

void ScCellKeywordTranslator::addToMap(const String& rKey, const sal_Char* pName, const Locale& rLocale, OpCode eOpCode)
{
    ScCellKeyword aKeyItem( pName, eOpCode, rLocale );

    ScCellKeywordHashMap::iterator itrEnd = maStringNameMap.end();
    ScCellKeywordHashMap::iterator itr = maStringNameMap.find(rKey);

    if ( itr == itrEnd )
    {
        // New keyword.
        list<ScCellKeyword> aList;
        aList.push_back(aKeyItem);
        maStringNameMap.insert( ScCellKeywordHashMap::value_type(rKey, aList) );
    }
    else
        itr->second.push_back(aKeyItem);
}

void ScCellKeywordTranslator::addToMap(const TransItem* pItems, const Locale& rLocale)
{
    for (sal_uInt16 i = 0; pItems[i].from != NULL; ++i)
        addToMap(rtl::OUString(pItems[i].from), pItems[i].to, rLocale, pItems[i].func);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
* viewerexamplesdk.cpp
*
*  Created on: Oct 01, 2014
*      Author: Bjorn Blissing
*/
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>

#include "oculusdevicesdk.h"

int main(int argc, char** argv)
{
	// Initialize the Oculus Rendering Shim. Must be done before any OpenGL calls
	ovr_InitializeRenderingShim();

	// use an ArgumentParser object to manage the program arguments.
	osg::ArgumentParser arguments(&argc, argv);
	// read the scene from the list of file specified command line arguments.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

	// if not loaded assume no arguments passed in, try use default cow model instead.
	if (!loadedModel) loadedModel = osgDB::readNodeFile("cow.osgt");

	// Still no loaded model, then exit
	if (!loadedModel) return 0;

	// Create Trackball manipulator
	osg::ref_ptr<osgGA::CameraManipulator> cameraManipulator = new osgGA::TrackballManipulator;
	const osg::BoundingSphere& bs = loadedModel->getBound();

	if (bs.valid()) {
		// Adjust view to object view
		cameraManipulator->setHomePosition(osg::Vec3(0, bs.radius()*1.5, 0), osg::Vec3(0, 0, 0), osg::Vec3(0, 0, 1));
	}

	// Open the HMD
	osg::ref_ptr<OculusDeviceSDK> oculusDevice = new OculusDeviceSDK();
	oculusDevice->initialize();

	// Get the suggested context traits
	osg::ref_ptr<osg::GraphicsContext::Traits> traits = oculusDevice->graphicsContextTraits();

	// Create a graphic context based on our desired traits
	osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits);
	if (!gc) {
		osg::notify(osg::NOTICE) << "Error, GraphicsWindow has not been created successfully" << std::endl;
		return 1;
	}

	if (gc.valid()) {
		gc->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
		gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		// Make sure that Oculus SDK handles SwapCallbacks
		gc->setSwapCallback(new OculusSwapCallback());
	}

	osgViewer::Viewer viewer(arguments);
	viewer.getCamera()->setGraphicsContext(gc);
	viewer.getCamera()->setViewport(0, 0, traits->width, traits->height);

	// Disable automatic computation of near and far plane
	viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
	viewer.setCameraManipulator(cameraManipulator);

	// Add oculus geode to initialize rendering
	osg::ref_ptr<OculusDrawable> oculusDrawable = new OculusDrawable;
	oculusDrawable->setOculusDevice(oculusDevice.get());
	oculusDrawable->setView(&viewer);
	osg::ref_ptr<osg::Geode> oculusGeode = new osg::Geode;
	oculusGeode->addDrawable(oculusDrawable);

	// Create world root and add this to viewer
	osg::ref_ptr<osg::Group> root = new osg::Group;
	root->addChild(loadedModel);
	root->addChild(oculusGeode);
	viewer.setSceneData(root);

	// Realize viewer
	viewer.realize();
	// Run one frame to make sure that textures are created
	viewer.frame();

	// Start Viewer
	while (!viewer.done()) {
		oculusDevice->beginFrame();
		oculusDevice->getEyePose();
		viewer.frame();
		oculusDevice->endFrame();
	}

	return 0;
}

<commit_msg>improve error message<commit_after>/*
* viewerexamplesdk.cpp
*
*  Created on: Oct 01, 2014
*      Author: Bjorn Blissing
*/
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>

#include "oculusdevicesdk.h"

int main(int argc, char** argv)
{
	// Initialize the Oculus Rendering Shim. Must be done before any OpenGL calls
	ovr_InitializeRenderingShim();

	// use an ArgumentParser object to manage the program arguments.
	osg::ArgumentParser arguments(&argc, argv);
	// read the scene from the list of file specified command line arguments.
	osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

	// if not loaded assume no arguments passed in, try use default cow model instead.
	if (!loadedModel) loadedModel = osgDB::readNodeFile("cow.osgt");

	// Still no loaded model, then exit
	if (!loadedModel) {
		osg::notify(osg::NOTICE) << "Error, no loaded model and couldn't find cow.osgt" << std::endl;
		return 0;
	}
	// Create Trackball manipulator
	osg::ref_ptr<osgGA::CameraManipulator> cameraManipulator = new osgGA::TrackballManipulator;
	const osg::BoundingSphere& bs = loadedModel->getBound();

	if (bs.valid()) {
		// Adjust view to object view
		cameraManipulator->setHomePosition(osg::Vec3(0, bs.radius()*1.5, 0), osg::Vec3(0, 0, 0), osg::Vec3(0, 0, 1));
	}

	// Open the HMD
	osg::ref_ptr<OculusDeviceSDK> oculusDevice = new OculusDeviceSDK();
	oculusDevice->initialize();

	// Get the suggested context traits
	osg::ref_ptr<osg::GraphicsContext::Traits> traits = oculusDevice->graphicsContextTraits();

	// Create a graphic context based on our desired traits
	osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits);
	if (!gc) {
		osg::notify(osg::NOTICE) << "Error, GraphicsWindow has not been created successfully" << std::endl;
		return 1;
	}

	if (gc.valid()) {
		gc->setClearColor(osg::Vec4(0.2f, 0.2f, 0.4f, 1.0f));
		gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		// Make sure that Oculus SDK handles SwapCallbacks
		gc->setSwapCallback(new OculusSwapCallback());
	}

	osgViewer::Viewer viewer(arguments);
	viewer.getCamera()->setGraphicsContext(gc);
	viewer.getCamera()->setViewport(0, 0, traits->width, traits->height);

	// Disable automatic computation of near and far plane
	viewer.getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
	viewer.setCameraManipulator(cameraManipulator);

	// Add oculus geode to initialize rendering
	osg::ref_ptr<OculusDrawable> oculusDrawable = new OculusDrawable;
	oculusDrawable->setOculusDevice(oculusDevice.get());
	oculusDrawable->setView(&viewer);
	osg::ref_ptr<osg::Geode> oculusGeode = new osg::Geode;
	oculusGeode->addDrawable(oculusDrawable);

	// Create world root and add this to viewer
	osg::ref_ptr<osg::Group> root = new osg::Group;
	root->addChild(loadedModel);
	root->addChild(oculusGeode);
	viewer.setSceneData(root);

	// Realize viewer
	viewer.realize();
	// Run one frame to make sure that textures are created
	viewer.frame();

	// Start Viewer
	while (!viewer.done()) {
		oculusDevice->beginFrame();
		oculusDevice->getEyePose();
		viewer.frame();
		oculusDevice->endFrame();
	}

	return 0;
}

<|endoftext|>


<commit_before>/*
    RCSwitch - Arduino libary for remote control outlet switches
    Copyright (c) 2011 Suat Özgür.  All right reserved.

    Contributors:
    - Andre Koehler / info(at)tomate-online(dot)de
    - Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com
    - Skineffect / http://forum.ardumote.com/viewtopic.php?f=2&t=48

    Project home: http://code.google.com/p/rc-switch/

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

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

    Changes
        - prevent multiple creation of ISR. 31st May 2012 JP Liew

*/

#include "RCSwitch.h"

unsigned long long RCSwitch::nReceivedValue = 0;
unsigned int RCSwitch::nReceivedBitlength = 0;
unsigned int RCSwitch::nReceivedDelay = 0;
unsigned int RCSwitch::nReceivedProtocol = 0;
unsigned long RCSwitch::timings[RCSWITCH_MAX_CHANGES];
int RCSwitch::nReceiveTolerance = 60;

RCSwitch::RCSwitch()
{
    this->nReceiverInterrupt = -1;
    this->nTransmitterPin = -1;
    RCSwitch::nReceivedValue = 0;
    this->setPulseLength(350);
    this->setRepeatTransmit(10);
    this->setReceiveTolerance(60);
    this->setProtocol(1);
}

/**
  * Sets the protocol to send.
  */
void RCSwitch::setProtocol(int nProtocol)
{
    this->nProtocol = nProtocol;
    if (nProtocol == 1)
    {
        this->setPulseLength(350);
    }
    else if (nProtocol == 2) {
        this->setPulseLength(650);
    }
}

/**
  * Sets the protocol to send with pulse length in microseconds.
  */
void RCSwitch::setProtocol(int nProtocol, int nPulseLength)
{
    this->nProtocol = nProtocol;
    if (nProtocol == 1) {
        this->setPulseLength(nPulseLength);
    }
    else if (nProtocol == 2) {
        this->setPulseLength(nPulseLength);
    }
}

/**
  * Sets pulse length in microseconds
  */
void RCSwitch::setPulseLength(int nPulseLength)
{
    this->nPulseLength = nPulseLength;
}

/**
 * Sets Repeat Transmits
 */
void RCSwitch::setRepeatTransmit(int nRepeatTransmit)
{
    this->nRepeatTransmit = nRepeatTransmit;
}

/**
 * Set Receiving Tolerance
 */
void RCSwitch::setReceiveTolerance(int nPercent)
{
    RCSwitch::nReceiveTolerance = nPercent;
}

/**
 * Enable transmissions
 *
 * @param nTransmitterPin    Arduino Pin to which the sender is connected to
 */
void RCSwitch::enableTransmit(int nTransmitterPin)
{
    this->nTransmitterPin = nTransmitterPin;
    pinMode(this->nTransmitterPin, OUTPUT);
}

/**
  * Disable transmissions
  */
void RCSwitch::disableTransmit()
{
    pinMode(this->nTransmitterPin, INPUT);
    this->nTransmitterPin = -1;
}

/**
 * Sends a Code Word
 * @param sCodeWord   /^[10FS]*$/  -> see getCodeWord
 */
void RCSwitch::sendTriState(char* sCodeWord)
{
    for (int nRepeat=0; nRepeat < nRepeatTransmit; nRepeat++)
    {
        int i = 0;
        while (sCodeWord[i] != '\0')
        {
            switch(sCodeWord[i])
            {
                case '0':
                    this->sendT0();
                    break;
                case 'F':
                    this->sendTF();
                    break;
                case '1':
                    this->sendT1();
                    break;
            }
            i++;
        }
        this->sendSync();
    }
}

void RCSwitch::send(char* sCodeWord)
{
    for (int nRepeat=0; nRepeat < nRepeatTransmit; nRepeat++)
    {
        int i = 0;
        while (sCodeWord[i] != '\0')
        {
            switch(sCodeWord[i])
            {
                case '0':
                    this->send0();
                    break;
                case '1':
                    this->send1();
                    break;
            }
            i++;
        }
        this->sendSync();
    }
}

void RCSwitch::transmit(int nHighPulses, int nLowPulses)
{
    boolean disabled_Receive = false;
    int nReceiverInterrupt_backup = nReceiverInterrupt;
    if (this->nTransmitterPin != -1)
    {
        if (this->nReceiverInterrupt != -1)
        {
            this->disableReceive();
            disabled_Receive = true;
        }
        digitalWrite(this->nTransmitterPin, HIGH);
        delayMicroseconds(this->nPulseLength * nHighPulses);
        digitalWrite(this->nTransmitterPin, LOW);
        delayMicroseconds(this->nPulseLength * nLowPulses);
        if(disabled_Receive)
        {
            this->enableReceive(nReceiverInterrupt_backup);
        }
    }
}

/**
 * Sends a "0" Bit
 *                       _
 * Waveform Protocol 1: | |___
 *                       _
 * Waveform Protocol 2: | |__
 */
void RCSwitch::send0()
{
    if (this->nProtocol == 1)
    {
        this->transmit(1,3);
    }
    else if (this->nProtocol == 2)
    {
        this->transmit(1,2);
    }
}

/**
 * Sends a "1" Bit
 *                       ___
 * Waveform Protocol 1: |   |_
 *                       __
 * Waveform Protocol 2: |  |_
 */
void RCSwitch::send1()
{
    if (this->nProtocol == 1)
    {
        this->transmit(3,1);
    }
    else if (this->nProtocol == 2)
    {
        this->transmit(2,1);
    }
}

/**
 * Sends a Tri-State "0" Bit
 *            _     _
 * Waveform: | |___| |___
 */
void RCSwitch::sendT0()
{
    this->transmit(1,3);
    this->transmit(1,3);
}

/**
 * Sends a Tri-State "1" Bit
 *            ___   ___
 * Waveform: |   |_|   |_
 */
void RCSwitch::sendT1()
{
    this->transmit(3,1);
    this->transmit(3,1);
}

/**
 * Sends a Tri-State "F" Bit
 *            _     ___
 * Waveform: | |___|   |_
 */
void RCSwitch::sendTF()
{
    this->transmit(1,3);
    this->transmit(3,1);
}

/**
 * Sends a "Sync" Bit
 *                       _
 * Waveform Protocol 1: | |_______________________________
 *                       _
 * Waveform Protocol 2: | |__________
 */
void RCSwitch::sendSync()
{
    if (this->nProtocol == 1)
    {
        this->transmit(1,31);
    }
    else if (this->nProtocol == 2)
    {
        this->transmit(1,10);
    }
}

/**
 * Enable receiving data
 */
void RCSwitch::enableReceive(int interrupt)
{
    if (this->nReceiverInterrupt == interrupt) return; // prevent multiple creation of ISR. 31st May 2012 JP Liew
    this->nReceiverInterrupt = interrupt;
    this->enableReceive();
}

void RCSwitch::enableReceive()
{
    if (this->nReceiverInterrupt != -1)
    {
        RCSwitch::nReceivedValue = NULL;
        RCSwitch::nReceivedBitlength = NULL;
        attachInterrupt(this->nReceiverInterrupt, handleInterrupt, CHANGE);
    }
}

/**
 * Disable receiving data
 */
void RCSwitch::disableReceive()
{
    detachInterrupt(this->nReceiverInterrupt);
    this->nReceiverInterrupt = -1;
}

bool RCSwitch::available()
{
    return RCSwitch::nReceivedValue != NULL;
}

void RCSwitch::resetAvailable()
{
    RCSwitch::nReceivedValue = NULL;
}

unsigned long long RCSwitch::getReceivedValue()
{
    return RCSwitch::nReceivedValue;
}

unsigned int RCSwitch::getReceivedBitlength()
{
    return RCSwitch::nReceivedBitlength;
}

unsigned int RCSwitch::getReceivedDelay()
{
    return RCSwitch::nReceivedDelay;
}

unsigned int RCSwitch::getReceivedProtocol()
{
    return RCSwitch::nReceivedProtocol;
}

unsigned long* RCSwitch::getReceivedRawdata()
{
    return RCSwitch::timings;
}

static inline unsigned long diff(long A, long B)
{
  return abs(A - B);
}

bool RCSwitch::receiveProtocol1(unsigned int changeCount)
{
    unsigned long code = 0;
    unsigned long period = RCSwitch::timings[0] / 31;
    unsigned long tolerance = period * RCSwitch::nReceiveTolerance / 100;

    for (unsigned int i = 1; i < changeCount; i += 2)
    {
        code <<= 1;
        if (diff(RCSwitch::timings[i], period) < tolerance &&
            diff(RCSwitch::timings[i + 1], period * 3) < tolerance)
        {
            code |= 0;
        }
        else if (diff(RCSwitch::timings[i], period * 3) < tolerance &&
                 diff(RCSwitch::timings[i + 1], period) < tolerance)
        {
            code |= 1;
        }
        else
        {
            // Failed
            code = 0;
            break;
        }
    }

    if (changeCount > 47)
    {
        if (code != 0)
        {
            RCSwitch::nReceivedValue = code;
            RCSwitch::nReceivedBitlength = changeCount / 2;
            RCSwitch::nReceivedDelay = period;
            RCSwitch::nReceivedProtocol = 1;
        }
    }

    if (code == 0)
        return false;
    else
        return true;
}

void RCSwitch::handleInterrupt()
{
    static unsigned int changeCount;
    static unsigned long lastTime;
    static unsigned int repeatCount;

    long time = micros();
    unsigned long duration = time - lastTime;

    if ((duration >= 100000L && RCSwitch::timings[0] >= 100000L) || // T=4ms
        (duration > 5000 && RCSwitch::timings[0] > 5000 && RCSwitch::timings[0] < 100000L)) // normal
    {
        ++repeatCount;
        if (repeatCount == 1)
        {
            if (changeCount > 20)
            {
                --changeCount;
                receiveProtocol1(changeCount);
            }
            repeatCount = 0;
        }
        changeCount = 0;
    }
    else if ((duration > 5000 && RCSwitch::timings[0] <= 5000) || (duration >= 100000L))
    {
        changeCount = 0;
        repeatCount = 0;
    }

    if (changeCount >= RCSWITCH_MAX_CHANGES)
    {
        changeCount = 0;
        repeatCount = 0;
    }
    RCSwitch::timings[changeCount] = duration;
    ++changeCount;
    lastTime = time;
}
<commit_msg>NULL -> 0<commit_after>/*
    RCSwitch - Arduino libary for remote control outlet switches
    Copyright (c) 2011 Suat Özgür.  All right reserved.

    Contributors:
    - Andre Koehler / info(at)tomate-online(dot)de
    - Gordeev Andrey Vladimirovich / gordeev(at)openpyro(dot)com
    - Skineffect / http://forum.ardumote.com/viewtopic.php?f=2&t=48

    Project home: http://code.google.com/p/rc-switch/

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

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

    Changes
        - prevent multiple creation of ISR. 31st May 2012 JP Liew

*/

#include "RCSwitch.h"

unsigned long long RCSwitch::nReceivedValue = 0;
unsigned int RCSwitch::nReceivedBitlength = 0;
unsigned int RCSwitch::nReceivedDelay = 0;
unsigned int RCSwitch::nReceivedProtocol = 0;
unsigned long RCSwitch::timings[RCSWITCH_MAX_CHANGES];
int RCSwitch::nReceiveTolerance = 60;

RCSwitch::RCSwitch()
{
    this->nReceiverInterrupt = -1;
    this->nTransmitterPin = -1;
    RCSwitch::nReceivedValue = 0;
    this->setPulseLength(350);
    this->setRepeatTransmit(10);
    this->setReceiveTolerance(60);
    this->setProtocol(1);
}

/**
  * Sets the protocol to send.
  */
void RCSwitch::setProtocol(int nProtocol)
{
    this->nProtocol = nProtocol;
    if (nProtocol == 1)
    {
        this->setPulseLength(350);
    }
    else if (nProtocol == 2) {
        this->setPulseLength(650);
    }
}

/**
  * Sets the protocol to send with pulse length in microseconds.
  */
void RCSwitch::setProtocol(int nProtocol, int nPulseLength)
{
    this->nProtocol = nProtocol;
    if (nProtocol == 1) {
        this->setPulseLength(nPulseLength);
    }
    else if (nProtocol == 2) {
        this->setPulseLength(nPulseLength);
    }
}

/**
  * Sets pulse length in microseconds
  */
void RCSwitch::setPulseLength(int nPulseLength)
{
    this->nPulseLength = nPulseLength;
}

/**
 * Sets Repeat Transmits
 */
void RCSwitch::setRepeatTransmit(int nRepeatTransmit)
{
    this->nRepeatTransmit = nRepeatTransmit;
}

/**
 * Set Receiving Tolerance
 */
void RCSwitch::setReceiveTolerance(int nPercent)
{
    RCSwitch::nReceiveTolerance = nPercent;
}

/**
 * Enable transmissions
 *
 * @param nTransmitterPin    Arduino Pin to which the sender is connected to
 */
void RCSwitch::enableTransmit(int nTransmitterPin)
{
    this->nTransmitterPin = nTransmitterPin;
    pinMode(this->nTransmitterPin, OUTPUT);
}

/**
  * Disable transmissions
  */
void RCSwitch::disableTransmit()
{
    pinMode(this->nTransmitterPin, INPUT);
    this->nTransmitterPin = -1;
}

/**
 * Sends a Code Word
 * @param sCodeWord   /^[10FS]*$/  -> see getCodeWord
 */
void RCSwitch::sendTriState(char* sCodeWord)
{
    for (int nRepeat=0; nRepeat < nRepeatTransmit; nRepeat++)
    {
        int i = 0;
        while (sCodeWord[i] != '\0')
        {
            switch(sCodeWord[i])
            {
                case '0':
                    this->sendT0();
                    break;
                case 'F':
                    this->sendTF();
                    break;
                case '1':
                    this->sendT1();
                    break;
            }
            i++;
        }
        this->sendSync();
    }
}

void RCSwitch::send(char* sCodeWord)
{
    for (int nRepeat=0; nRepeat < nRepeatTransmit; nRepeat++)
    {
        int i = 0;
        while (sCodeWord[i] != '\0')
        {
            switch(sCodeWord[i])
            {
                case '0':
                    this->send0();
                    break;
                case '1':
                    this->send1();
                    break;
            }
            i++;
        }
        this->sendSync();
    }
}

void RCSwitch::transmit(int nHighPulses, int nLowPulses)
{
    boolean disabled_Receive = false;
    int nReceiverInterrupt_backup = nReceiverInterrupt;
    if (this->nTransmitterPin != -1)
    {
        if (this->nReceiverInterrupt != -1)
        {
            this->disableReceive();
            disabled_Receive = true;
        }
        digitalWrite(this->nTransmitterPin, HIGH);
        delayMicroseconds(this->nPulseLength * nHighPulses);
        digitalWrite(this->nTransmitterPin, LOW);
        delayMicroseconds(this->nPulseLength * nLowPulses);
        if(disabled_Receive)
        {
            this->enableReceive(nReceiverInterrupt_backup);
        }
    }
}

/**
 * Sends a "0" Bit
 *                       _
 * Waveform Protocol 1: | |___
 *                       _
 * Waveform Protocol 2: | |__
 */
void RCSwitch::send0()
{
    if (this->nProtocol == 1)
    {
        this->transmit(1,3);
    }
    else if (this->nProtocol == 2)
    {
        this->transmit(1,2);
    }
}

/**
 * Sends a "1" Bit
 *                       ___
 * Waveform Protocol 1: |   |_
 *                       __
 * Waveform Protocol 2: |  |_
 */
void RCSwitch::send1()
{
    if (this->nProtocol == 1)
    {
        this->transmit(3,1);
    }
    else if (this->nProtocol == 2)
    {
        this->transmit(2,1);
    }
}

/**
 * Sends a Tri-State "0" Bit
 *            _     _
 * Waveform: | |___| |___
 */
void RCSwitch::sendT0()
{
    this->transmit(1,3);
    this->transmit(1,3);
}

/**
 * Sends a Tri-State "1" Bit
 *            ___   ___
 * Waveform: |   |_|   |_
 */
void RCSwitch::sendT1()
{
    this->transmit(3,1);
    this->transmit(3,1);
}

/**
 * Sends a Tri-State "F" Bit
 *            _     ___
 * Waveform: | |___|   |_
 */
void RCSwitch::sendTF()
{
    this->transmit(1,3);
    this->transmit(3,1);
}

/**
 * Sends a "Sync" Bit
 *                       _
 * Waveform Protocol 1: | |_______________________________
 *                       _
 * Waveform Protocol 2: | |__________
 */
void RCSwitch::sendSync()
{
    if (this->nProtocol == 1)
    {
        this->transmit(1,31);
    }
    else if (this->nProtocol == 2)
    {
        this->transmit(1,10);
    }
}

/**
 * Enable receiving data
 */
void RCSwitch::enableReceive(int interrupt)
{
    if (this->nReceiverInterrupt == interrupt) return; // prevent multiple creation of ISR. 31st May 2012 JP Liew
    this->nReceiverInterrupt = interrupt;
    this->enableReceive();
}

void RCSwitch::enableReceive()
{
    if (this->nReceiverInterrupt != -1)
    {
        RCSwitch::nReceivedValue = 0;
        RCSwitch::nReceivedBitlength = 0;
        attachInterrupt(this->nReceiverInterrupt, handleInterrupt, CHANGE);
    }
}

/**
 * Disable receiving data
 */
void RCSwitch::disableReceive()
{
    detachInterrupt(this->nReceiverInterrupt);
    this->nReceiverInterrupt = -1;
}

bool RCSwitch::available()
{
    return RCSwitch::nReceivedValue != 0;
}

void RCSwitch::resetAvailable()
{
    RCSwitch::nReceivedValue = 0;
}

unsigned long long RCSwitch::getReceivedValue()
{
    return RCSwitch::nReceivedValue;
}

unsigned int RCSwitch::getReceivedBitlength()
{
    return RCSwitch::nReceivedBitlength;
}

unsigned int RCSwitch::getReceivedDelay()
{
    return RCSwitch::nReceivedDelay;
}

unsigned int RCSwitch::getReceivedProtocol()
{
    return RCSwitch::nReceivedProtocol;
}

unsigned long* RCSwitch::getReceivedRawdata()
{
    return RCSwitch::timings;
}

static inline unsigned long diff(long A, long B)
{
  return abs(A - B);
}

bool RCSwitch::receiveProtocol1(unsigned int changeCount)
{
    unsigned long code = 0;
    unsigned long period = RCSwitch::timings[0] / 31;
    unsigned long tolerance = period * RCSwitch::nReceiveTolerance / 100;

    for (unsigned int i = 1; i < changeCount; i += 2)
    {
        code <<= 1;
        if (diff(RCSwitch::timings[i], period) < tolerance &&
            diff(RCSwitch::timings[i + 1], period * 3) < tolerance)
        {
            code |= 0;
        }
        else if (diff(RCSwitch::timings[i], period * 3) < tolerance &&
                 diff(RCSwitch::timings[i + 1], period) < tolerance)
        {
            code |= 1;
        }
        else
        {
            // Failed
            code = 0;
            break;
        }
    }

    if (changeCount > 47)
    {
        if (code != 0)
        {
            RCSwitch::nReceivedValue = code;
            RCSwitch::nReceivedBitlength = changeCount / 2;
            RCSwitch::nReceivedDelay = period;
            RCSwitch::nReceivedProtocol = 1;
        }
    }

    if (code == 0)
        return false;
    else
        return true;
}

void RCSwitch::handleInterrupt()
{
    static unsigned int changeCount;
    static unsigned long lastTime;
    static unsigned int repeatCount;

    long time = micros();
    unsigned long duration = time - lastTime;

    if ((duration >= 100000L && RCSwitch::timings[0] >= 100000L) || // T=4ms
        (duration > 5000 && RCSwitch::timings[0] > 5000 && RCSwitch::timings[0] < 100000L)) // normal
    {
        ++repeatCount;
        if (repeatCount == 1)
        {
            if (changeCount > 20)
            {
                --changeCount;
                receiveProtocol1(changeCount);
            }
            repeatCount = 0;
        }
        changeCount = 0;
    }
    else if ((duration > 5000 && RCSwitch::timings[0] <= 5000) || (duration >= 100000L))
    {
        changeCount = 0;
        repeatCount = 0;
    }

    if (changeCount >= RCSWITCH_MAX_CHANGES)
    {
        changeCount = 0;
        repeatCount = 0;
    }
    RCSwitch::timings[changeCount] = duration;
    ++changeCount;
    lastTime = time;
}
<|endoftext|>


<commit_before>#ifndef ___INANITY_D3D11_HPP___
#define ___INANITY_D3D11_HPP___

#include "../platform/windows.hpp"
#include <InitGuid.h>

#if defined(___INANITY_PLATFORM_XBOX)

#include <d3d11_x.h>
#include <d3dcompiler_x.h>

#else

#include <d3d11.h>
#include <d3dcompiler.h>

#endif

#endif
<commit_msg>compatibility with mingw on linux<commit_after>#ifndef ___INANITY_D3D11_HPP___
#define ___INANITY_D3D11_HPP___

#include "../platform/windows.hpp"
#include <initguid.h>

#if defined(___INANITY_PLATFORM_XBOX)

#include <d3d11_x.h>
#include <d3dcompiler_x.h>

#else

#include <d3d11.h>
#include <d3dcompiler.h>

#endif

#endif
<|endoftext|>


<commit_before><commit_msg>Nothing Unix-specific about <stdlib.h><commit_after><|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	漢字フォント・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "ff12b/src/ff.h"

// 漢字フォントデータをＳＤカード上に置いて、キャッシュアクセスする場合有効にする
// #define CASH_KFONT

#ifdef CASH_KFONT
extern "C" {
	int fatfs_get_mount();
};
#endif

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	漢字 無効フォント定義
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class kfont_null {
	public:
		static const int8_t width = 0;
		static const int8_t height = 0;
		const uint8_t* get(uint16_t code) { return nullptr; }
	};

#ifndef CASH_KFONT
	struct kfont_bitmap {
		static const uint8_t kfont_start[];
	};
#endif

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	漢字フォント・テンプレート・クラス
		@param[in]	WIDTH	フォントの横幅
		@param[in]	HEIGHT	フォントの高さ
		@param[in]	CASHN	キャッシュ数
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
#ifdef CASH_KFONT
	template <int8_t WIDTH, int8_t HEIGHT, uint8_t CASHN>
#else
	template <int8_t WIDTH, int8_t HEIGHT>
#endif
	class kfont {

		static const uint32_t FONTS = ((WIDTH * HEIGHT) + 7) / 8;

		uint16_t	code_;
		int8_t		cnt_;

#ifdef CASH_KFONT
		struct kanji_cash {
			uint16_t	code;
			uint8_t		bitmap[FONTS];
			kanji_cash() noexcept : code(0), bitmap{ 0 } { }
		};
		kanji_cash cash_[CASHN];
		uint8_t cash_idx_;
#endif

		static uint16_t sjis_to_liner_(uint16_t sjis)
		{
			uint16_t code;
			uint8_t up = sjis >> 8;
			uint8_t lo = sjis & 0xff;
			if(0x81 <= up && up <= 0x9f) {
				code = up - 0x81;
			} else if(0xe0 <= up && up <= 0xef) {
				code = (0x9f + 1 - 0x81) + up - 0xe0;
			} else {
				return 0xffff;
			}
			uint16_t loa = (0x7e + 1 - 0x40) + (0xfc + 1 - 0x80);
			if(0x40 <= lo && lo <= 0x7e) {
				code *= loa;
				code += lo - 0x40;
			} else if(0x80 <= lo && lo <= 0xfc) {
				code *= loa;
				code += 0x7e + 1 - 0x40;
				code += lo - 0x80;
			} else {
				return 0xffff;
			}
			return code;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		kfont() noexcept : code_(0), cnt_(0)
#ifdef CASH_KFONT
			, cash_(), cash_idx_(0)
#endif
			{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	文字の横幅
		*/
		//-----------------------------------------------------------------//
		static const int8_t width = WIDTH;

		//-----------------------------------------------------------------//
		/*!
			@brief	文字の高さ
		*/
		//-----------------------------------------------------------------//
		static const int8_t height = HEIGHT;

		//-----------------------------------------------------------------//
		/*!
			@brief	文字のビットマップを取得
			@param[in]	code	文字コード（unicode）
			@return 文字のビットマップ
		*/
		//-----------------------------------------------------------------//
		const uint8_t* get(uint16_t code) noexcept {

			if(code == 0) return nullptr;

#ifdef CASH_KFONT
			// キャッシュ内検索
			int8_t n = -1;
			for(uint8_t i = 0; i < CASHN; ++i) {
				if(cash_[i].code == code) {
					return &cash_[i].bitmap[0];
				} else if(cash_[i].code == 0) {
					n = i;
				}
			}
			if(n >= 0) cash_idx_ = n;
			else {
				for(uint8_t i = 0; i < CASHN; ++i) {
					++cash_idx_;
					if(cash_idx_ >= CASHN) cash_idx_ = 0;
					if(cash_[cash_idx_].code != 0) {
						break;
					}
				}
			}

			if(fatfs_get_mount() == 0) return nullptr;
#endif
			uint32_t lin = sjis_to_liner_(ff_convert(code, 0));

			if(lin == 0xffff) {
				return nullptr;
			}
#ifdef CASH_KFONT
			FIL fp;
			if(f_open(&fp, "/kfont16.bin", FA_READ) != FR_OK) {
				return nullptr;
			}

			if(f_lseek(&fp, lin * FONTS) != FR_OK) {
				f_close(&fp);
				return nullptr;
			}

			UINT rs;
			if(f_read(&fp, &cash_[cash_idx_].bitmap[0], FONTS, &rs) != FR_OK) {
				f_close(&fp);
				return nullptr;
			}
			cash_[cash_idx_].code = code;

			f_close(&fp);

			return &cash_[cash_idx_].bitmap[0];
#else
			return &kfont_bitmap::kfont_start[lin * FONTS];
#endif
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	UTF-8 コードを押し込む
			@return UTF-16 コードが完了した場合「true」
		*/
		//-----------------------------------------------------------------//
		bool injection_utf8(uint8_t ch) noexcept
		{
			if(ch < 0x80) {
				code_ = ch;
				return true;
			} else if((ch & 0xf0) == 0xe0) {
				code_ = (ch & 0x0f);
				cnt_ = 2;
				return false;
			} else if((ch & 0xe0) == 0xc0) {
				code_ = (ch & 0x1f);
				cnt_ = 1;
				return false;
			} else if((ch & 0xc0) == 0x80) {
				code_ <<= 6;
				code_ |= ch & 0x3f;
				cnt_--;
				if(cnt_ <= 0 && code_ < 0x80) {
					code_ = 0;	// 不正なコードとして無視
					return true;
				}
			}
			if(cnt_ == 0 && code_ != 0) {
				return true;
			}
			return false;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	UTF-16 コードを取得
			@return UTF-16 コード
		*/
		//-----------------------------------------------------------------//
		uint16_t get_utf16() const noexcept { return code_; }
	};
}
<commit_msg>update: kfont_null for dummy API<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	漢字フォント・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>
#include "ff12b/src/ff.h"

// 漢字フォントデータをＳＤカード上に置いて、キャッシュアクセスする場合有効にする
// #define CASH_KFONT

#ifdef CASH_KFONT
extern "C" {
	int fatfs_get_mount();
};
#endif

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	漢字 無効フォント定義
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class kfont_null {
	public:
		static const int8_t width = 0;
		static const int8_t height = 0;
		const uint8_t* get(uint16_t code) noexcept { return nullptr; }
		bool injection_utf8(uint8_t ch) noexcept { return true; }
		uint16_t get_utf16() const noexcept { return 0x0000; }
	};

#ifndef CASH_KFONT
	struct kfont_bitmap {
		static const uint8_t kfont_start[];
	};
#endif

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	漢字フォント・テンプレート・クラス
		@param[in]	WIDTH	フォントの横幅
		@param[in]	HEIGHT	フォントの高さ
		@param[in]	CASHN	キャッシュ数
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
#ifdef CASH_KFONT
	template <int8_t WIDTH, int8_t HEIGHT, uint8_t CASHN>
#else
	template <int8_t WIDTH, int8_t HEIGHT>
#endif
	class kfont {

		static const uint32_t FONTS = ((WIDTH * HEIGHT) + 7) / 8;

		uint16_t	code_;
		int8_t		cnt_;

#ifdef CASH_KFONT
		struct kanji_cash {
			uint16_t	code;
			uint8_t		bitmap[FONTS];
			kanji_cash() noexcept : code(0), bitmap{ 0 } { }
		};
		kanji_cash cash_[CASHN];
		uint8_t cash_idx_;
#endif

		static uint16_t sjis_to_liner_(uint16_t sjis)
		{
			uint16_t code;
			uint8_t up = sjis >> 8;
			uint8_t lo = sjis & 0xff;
			if(0x81 <= up && up <= 0x9f) {
				code = up - 0x81;
			} else if(0xe0 <= up && up <= 0xef) {
				code = (0x9f + 1 - 0x81) + up - 0xe0;
			} else {
				return 0xffff;
			}
			uint16_t loa = (0x7e + 1 - 0x40) + (0xfc + 1 - 0x80);
			if(0x40 <= lo && lo <= 0x7e) {
				code *= loa;
				code += lo - 0x40;
			} else if(0x80 <= lo && lo <= 0xfc) {
				code *= loa;
				code += 0x7e + 1 - 0x40;
				code += lo - 0x80;
			} else {
				return 0xffff;
			}
			return code;
		}

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		kfont() noexcept : code_(0), cnt_(0)
#ifdef CASH_KFONT
			, cash_(), cash_idx_(0)
#endif
			{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	文字の横幅
		*/
		//-----------------------------------------------------------------//
		static const int8_t width = WIDTH;

		//-----------------------------------------------------------------//
		/*!
			@brief	文字の高さ
		*/
		//-----------------------------------------------------------------//
		static const int8_t height = HEIGHT;

		//-----------------------------------------------------------------//
		/*!
			@brief	文字のビットマップを取得
			@param[in]	code	文字コード（unicode）
			@return 文字のビットマップ
		*/
		//-----------------------------------------------------------------//
		const uint8_t* get(uint16_t code) noexcept {

			if(code == 0) return nullptr;

#ifdef CASH_KFONT
			// キャッシュ内検索
			int8_t n = -1;
			for(uint8_t i = 0; i < CASHN; ++i) {
				if(cash_[i].code == code) {
					return &cash_[i].bitmap[0];
				} else if(cash_[i].code == 0) {
					n = i;
				}
			}
			if(n >= 0) cash_idx_ = n;
			else {
				for(uint8_t i = 0; i < CASHN; ++i) {
					++cash_idx_;
					if(cash_idx_ >= CASHN) cash_idx_ = 0;
					if(cash_[cash_idx_].code != 0) {
						break;
					}
				}
			}

			if(fatfs_get_mount() == 0) return nullptr;
#endif
			uint32_t lin = sjis_to_liner_(ff_convert(code, 0));

			if(lin == 0xffff) {
				return nullptr;
			}
#ifdef CASH_KFONT
			FIL fp;
			if(f_open(&fp, "/kfont16.bin", FA_READ) != FR_OK) {
				return nullptr;
			}

			if(f_lseek(&fp, lin * FONTS) != FR_OK) {
				f_close(&fp);
				return nullptr;
			}

			UINT rs;
			if(f_read(&fp, &cash_[cash_idx_].bitmap[0], FONTS, &rs) != FR_OK) {
				f_close(&fp);
				return nullptr;
			}
			cash_[cash_idx_].code = code;

			f_close(&fp);

			return &cash_[cash_idx_].bitmap[0];
#else
			return &kfont_bitmap::kfont_start[lin * FONTS];
#endif
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	UTF-8 コードを押し込む
			@return UTF-16 コードが完了した場合「true」
		*/
		//-----------------------------------------------------------------//
		bool injection_utf8(uint8_t ch) noexcept
		{
			if(ch < 0x80) {
				code_ = ch;
				return true;
			} else if((ch & 0xf0) == 0xe0) {
				code_ = (ch & 0x0f);
				cnt_ = 2;
				return false;
			} else if((ch & 0xe0) == 0xc0) {
				code_ = (ch & 0x1f);
				cnt_ = 1;
				return false;
			} else if((ch & 0xc0) == 0x80) {
				code_ <<= 6;
				code_ |= ch & 0x3f;
				cnt_--;
				if(cnt_ <= 0 && code_ < 0x80) {
					code_ = 0;	// 不正なコードとして無視
					return true;
				}
			}
			if(cnt_ == 0 && code_ != 0) {
				return true;
			}
			return false;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	UTF-16 コードを取得
			@return UTF-16 コード
		*/
		//-----------------------------------------------------------------//
		uint16_t get_utf16() const noexcept { return code_; }
	};
}
<|endoftext|>


<commit_before>#ifndef STAN_VARIATIONAL_PRINT_PROGRESS_HPP
#define STAN_VARIATIONAL_PRINT_PROGRESS_HPP

#include <stan/callbacks/logger.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>

namespace stan {
  namespace variational {

    /**
     * Helper function for printing progress for variational inference
     *
     * @param[in] m       total number of iterations
     * @param[in] start   starting iteration
     * @param[in] finish  final iteration
     * @param[in] refresh how frequently we want to print an update
     * @param[in] tune    boolean indicates tuning vs. variational inference
     * @param[in] prefix  prefix string
     * @param[in] suffix  suffix string
     * @param[in,out] logger  logger
     */
    void print_progress(int m,
                        int start,
                        int finish,
                        int refresh,
                        bool tune,
                        const std::string& prefix,
                        const std::string& suffix,
                        callbacks::logger& logger) {
      static const char* function =
        "stan::variational::print_progress";

      stan::math::check_positive(function,
                                 "Total number of iterations",
                                 m);
      stan::math::check_nonnegative(function,
                                    "Starting iteration",
                                    start);
      stan::math::check_positive(function,
                                 "Final iteration",
                                 finish);
      stan::math::check_positive(function,
                                 "Refresh rate",
                                 refresh);

      int it_print_width = std::ceil(std::log10(static_cast<double>(finish)));
      if (refresh > 0
          && (start + m == finish || m - 1 == 0 || m % refresh == 0)) {
        std::stringstream ss;
        ss << prefix;
        ss << "Iteration: ";
        ss << std::setw(it_print_width) << m + start
           << " / " << finish;
        ss << " [" << std::setw(3)
           << (100 * (start + m)) / finish
           << "%] ";
        ss << (tune ? " (Adaptation)" : " (Variational Inference)");
        ss << suffix;
        logger.info(ss);
      }
    }

  }
}
#endif
<commit_msg>inline print_progress<commit_after>#ifndef STAN_VARIATIONAL_PRINT_PROGRESS_HPP
#define STAN_VARIATIONAL_PRINT_PROGRESS_HPP

#include <stan/callbacks/logger.hpp>
#include <stan/math/prim/scal/err/check_positive.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <string>

namespace stan {
  namespace variational {

    /**
     * Helper function for printing progress for variational inference
     *
     * @param[in] m       total number of iterations
     * @param[in] start   starting iteration
     * @param[in] finish  final iteration
     * @param[in] refresh how frequently we want to print an update
     * @param[in] tune    boolean indicates tuning vs. variational inference
     * @param[in] prefix  prefix string
     * @param[in] suffix  suffix string
     * @param[in,out] logger  logger
     */
    inline
    void print_progress(int m,
                        int start,
                        int finish,
                        int refresh,
                        bool tune,
                        const std::string& prefix,
                        const std::string& suffix,
                        callbacks::logger& logger) {
      static const char* function =
        "stan::variational::print_progress";

      stan::math::check_positive(function,
                                 "Total number of iterations",
                                 m);
      stan::math::check_nonnegative(function,
                                    "Starting iteration",
                                    start);
      stan::math::check_positive(function,
                                 "Final iteration",
                                 finish);
      stan::math::check_positive(function,
                                 "Refresh rate",
                                 refresh);

      int it_print_width = std::ceil(std::log10(static_cast<double>(finish)));
      if (refresh > 0
          && (start + m == finish || m - 1 == 0 || m % refresh == 0)) {
        std::stringstream ss;
        ss << prefix;
        ss << "Iteration: ";
        ss << std::setw(it_print_width) << m + start
           << " / " << finish;
        ss << " [" << std::setw(3)
           << (100 * (start + m)) / finish
           << "%] ";
        ss << (tune ? " (Adaptation)" : " (Variational Inference)");
        ss << suffix;
        logger.info(ss);
      }
    }

  }
}
#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "osl/detail/android-bootstrap.h"

extern "C"
{
    extern void * animcore_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * avmedia_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * basprov_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * dba_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * dbaxml_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * dlgprov_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * embobj_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * emboleobj_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * evtatt_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * expwrap_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fastsax_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fileacc_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * filterconfig1_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * frm_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fsstorage_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fwk_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fwl_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fwm_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * hwp_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * hyphen_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * lng_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * lnth_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * lotuswordpro_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * oox_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * protocolhandler_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sb_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sc_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * scd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * scfilt_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * scriptframe_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sot_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * svt_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * svx_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * svxcore_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sdd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sm_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * smd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * spell_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * stringresource_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * svgfilter_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sw_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * swd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * t602filter_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * textfd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * tk_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * ucppkg1_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * unoxml_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * unordf_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * vbaswobj_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * vbaevents_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * wpftdraw_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * wpftwriter_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * writerfilter_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * xmlfd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * xmlsecurity_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * xo_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * xof_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
}

extern "C"
__attribute__ ((visibility("default")))
const lib_to_component_mapping *
lo_get_libmap(void)
{
    static lib_to_component_mapping map[] = {
        { "libanimcorelo.a", animcore_component_getFactory },
        { "libavmedialo.a", avmedia_component_getFactory },
        { "libbasprov.uno.a", basprov_component_getFactory },
        { "libdlgprov.uno.a", dlgprov_component_getFactory },
        { "libdbalo.a", dba_component_getFactory },
        { "libdbaxmllo.a", dbaxml_component_getFactory },
        { "libembobj.a", embobj_component_getFactory },
        { "libemboleobj.a", emboleobj_component_getFactory },
        { "libevtattlo.a", evtatt_component_getFactory },
        { "libexpwrap.uno.a", expwrap_component_getFactory },
        { "libfastsax.uno.a", fastsax_component_getFactory },
        { "libfileacc.a", fileacc_component_getFactory },
        { "libfilterconfiglo.a", filterconfig1_component_getFactory },
        { "libfrmlo.a", frm_component_getFactory },
        { "libfsstorage.uno.a", fsstorage_component_getFactory },
        { "libfwklo.a", fwk_component_getFactory },
        { "libfwllo.a", fwl_component_getFactory },
        { "libfwmlo.a", fwm_component_getFactory },
        { "libhwplo.a", hwp_component_getFactory },
        { "libhyphenlo.a", hyphen_component_getFactory },
        { "liblnglo.a", lng_component_getFactory },
        { "liblnthlo.a", lnth_component_getFactory },
        { "liblwpftlo.a", lotuswordpro_component_getFactory },
        { "libooxlo.a", oox_component_getFactory },
        { "libprotocolhandlerlo.a", protocolhandler_component_getFactory },
        { "libscdlo.a", scd_component_getFactory },
        { "libscfiltlo.a", scfilt_component_getFactory },
        { "libscriptframe.a", scriptframe_component_getFactory },
        { "libsblo.a", sb_component_getFactory },
        { "libsclo.a", sc_component_getFactory },
        { "libsddlo.a", sdd_component_getFactory },
        { "libsdlo.a", sd_component_getFactory },
        { "libsmdlo.a", smd_component_getFactory },
        { "libsmlo.a", sm_component_getFactory },
        { "libsotlo.a", sot_component_getFactory },
        { "libscriptframe.a", scriptframe_component_getFactory },
        { "libstringresource.uno.a", stringresource_component_getFactory },
        { "libsvgfilterlo.a", svgfilter_component_getFactory },
        { "libsvtlo.a", svt_component_getFactory },
        { "libsvxlo.a", svx_component_getFactory },
        { "libsvxcorelo.a", svxcore_component_getFactory },
        { "libswdlo.a", swd_component_getFactory },
        { "libswlo.a", sw_component_getFactory },
        { "libt602filterlo.a", t602filter_component_getFactory },
        { "libtextfdlo.a", textfd_component_getFactory },
        { "libtklo.a", tk_component_getFactory },
        { "libucppkg1.a", ucppkg1_component_getFactory },
        { "libunordflo.a", unordf_component_getFactory },
        { "libunoxmllo.a", unoxml_component_getFactory },
        { "libvbaswobj.uno.a", vbaswobj_component_getFactory },
        { "libvbaevents.uno.a", vbaevents_component_getFactory },
        { "libwpftdrawlo.a", wpftdraw_component_getFactory },
        { "libwpftwriterlo.a", wpftwriter_component_getFactory },
        { "libwriterfilterlo.a", writerfilter_component_getFactory },
        { "libxmlfdlo.a", xmlfd_component_getFactory },
        { "libxmlsecurity.a", xmlsecurity_component_getFactory },
        { "libxoflo.a", xof_component_getFactory },
        { "libxolo.a", xo_component_getFactory },
        { NULL, NULL }
    };

    return map;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>add missing chartcore.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include "osl/detail/android-bootstrap.h"

extern "C"
{
    extern void * animcore_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * avmedia_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * basprov_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * chartcore_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * dba_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * dbaxml_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * dlgprov_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * embobj_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * emboleobj_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * evtatt_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * expwrap_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fastsax_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fileacc_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * filterconfig1_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * frm_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fsstorage_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fwk_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fwl_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * fwm_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * hwp_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * hyphen_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * lng_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * lnth_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * lotuswordpro_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * oox_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * protocolhandler_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sb_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sc_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * scd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * scfilt_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * scriptframe_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sot_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * svt_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * svx_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * svxcore_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sdd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sm_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * smd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * spell_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * stringresource_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * svgfilter_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * sw_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * swd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * t602filter_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * textfd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * tk_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * ucppkg1_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * unoxml_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * unordf_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * vbaswobj_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * vbaevents_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * wpftdraw_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * wpftwriter_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * writerfilter_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * xmlfd_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * xmlsecurity_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * xo_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
    extern void * xof_component_getFactory( const char * pImplName, void * pServiceManager, void * pRegistryKey );
}

extern "C"
__attribute__ ((visibility("default")))
const lib_to_component_mapping *
lo_get_libmap(void)
{
    static lib_to_component_mapping map[] = {
        { "libanimcorelo.a", animcore_component_getFactory },
        { "libavmedialo.a", avmedia_component_getFactory },
        { "libbasprov.uno.a", basprov_component_getFactory },
        { "libchartcorelo.a", chartcore_component_getFactory },
        { "libdlgprov.uno.a", dlgprov_component_getFactory },
        { "libdbalo.a", dba_component_getFactory },
        { "libdbaxmllo.a", dbaxml_component_getFactory },
        { "libembobj.a", embobj_component_getFactory },
        { "libemboleobj.a", emboleobj_component_getFactory },
        { "libevtattlo.a", evtatt_component_getFactory },
        { "libexpwrap.uno.a", expwrap_component_getFactory },
        { "libfastsax.uno.a", fastsax_component_getFactory },
        { "libfileacc.a", fileacc_component_getFactory },
        { "libfilterconfiglo.a", filterconfig1_component_getFactory },
        { "libfrmlo.a", frm_component_getFactory },
        { "libfsstorage.uno.a", fsstorage_component_getFactory },
        { "libfwklo.a", fwk_component_getFactory },
        { "libfwllo.a", fwl_component_getFactory },
        { "libfwmlo.a", fwm_component_getFactory },
        { "libhwplo.a", hwp_component_getFactory },
        { "libhyphenlo.a", hyphen_component_getFactory },
        { "liblnglo.a", lng_component_getFactory },
        { "liblnthlo.a", lnth_component_getFactory },
        { "liblwpftlo.a", lotuswordpro_component_getFactory },
        { "libooxlo.a", oox_component_getFactory },
        { "libprotocolhandlerlo.a", protocolhandler_component_getFactory },
        { "libscdlo.a", scd_component_getFactory },
        { "libscfiltlo.a", scfilt_component_getFactory },
        { "libscriptframe.a", scriptframe_component_getFactory },
        { "libsblo.a", sb_component_getFactory },
        { "libsclo.a", sc_component_getFactory },
        { "libsddlo.a", sdd_component_getFactory },
        { "libsdlo.a", sd_component_getFactory },
        { "libsmdlo.a", smd_component_getFactory },
        { "libsmlo.a", sm_component_getFactory },
        { "libsotlo.a", sot_component_getFactory },
        { "libscriptframe.a", scriptframe_component_getFactory },
        { "libstringresource.uno.a", stringresource_component_getFactory },
        { "libsvgfilterlo.a", svgfilter_component_getFactory },
        { "libsvtlo.a", svt_component_getFactory },
        { "libsvxlo.a", svx_component_getFactory },
        { "libsvxcorelo.a", svxcore_component_getFactory },
        { "libswdlo.a", swd_component_getFactory },
        { "libswlo.a", sw_component_getFactory },
        { "libt602filterlo.a", t602filter_component_getFactory },
        { "libtextfdlo.a", textfd_component_getFactory },
        { "libtklo.a", tk_component_getFactory },
        { "libucppkg1.a", ucppkg1_component_getFactory },
        { "libunordflo.a", unordf_component_getFactory },
        { "libunoxmllo.a", unoxml_component_getFactory },
        { "libvbaswobj.uno.a", vbaswobj_component_getFactory },
        { "libvbaevents.uno.a", vbaevents_component_getFactory },
        { "libwpftdrawlo.a", wpftdraw_component_getFactory },
        { "libwpftwriterlo.a", wpftwriter_component_getFactory },
        { "libwriterfilterlo.a", writerfilter_component_getFactory },
        { "libxmlfdlo.a", xmlfd_component_getFactory },
        { "libxmlsecurity.a", xmlsecurity_component_getFactory },
        { "libxoflo.a", xof_component_getFactory },
        { "libxolo.a", xo_component_getFactory },
        { NULL, NULL }
    };

    return map;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "tarsnapaccount.h"
#include "debug.h"

#include <QNetworkRequest>
#include <QNetworkReply>
#include <QTableWidget>
#include <QMessageBox>

#define URL_ACTIVITY "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=activity&format=csv"
#define URL_MACHINE_ACTIVITY "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=subactivity&mid=%3&format=csv"
#define URL_LIST_MACHINES "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=subactivity"

TarsnapAccount::TarsnapAccount(QWidget *parent) : QDialog(parent), _user(),
    _nam(this)
{
    _ui.setupUi(this);
}

QString TarsnapAccount::user() const
{
    return _user;
}

void TarsnapAccount::setUser(const QString &user)
{
    _user = user;
    _ui.textLabel->setText(QString("Type password for account %1:").arg(_user));
}

QString TarsnapAccount::getMachine() const
{
    return _machine;
}

void TarsnapAccount::setMachine(const QString &machine)
{
    _machine = machine;
}

void TarsnapAccount::getAccountInfo(bool displayActivity, bool displayMachineActivity)
{
    if(exec())
    {
        QString getActivity(URL_ACTIVITY);
        getActivity = getActivity.arg(QString(QUrl::toPercentEncoding(_user)),
                                      QString(QUrl::toPercentEncoding(_ui.passwordLineEdit->text())));
        QNetworkReply *activityReply = tarsnapRequest(getActivity);
        connect(activityReply, &QNetworkReply::finished,
        [=]() {
            QByteArray replyData = readReply(activityReply, true);
            parseCredit(replyData);
            if(displayActivity)
                displayCSVTable(replyData);
        });
        QString getMachineId(URL_LIST_MACHINES);
        getMachineId = getMachineId.arg(QString(QUrl::toPercentEncoding(_user)),
                                        QString(QUrl::toPercentEncoding(_ui.passwordLineEdit->text())));
        QNetworkReply *machineIdReply = tarsnapRequest(getMachineId);
        connect(machineIdReply, &QNetworkReply::finished,
        [=]() {
            QString machineId = parseMachineId(readReply(machineIdReply));
            QString machineActivity(URL_MACHINE_ACTIVITY);
            machineActivity = machineActivity.arg(QString(QUrl::toPercentEncoding(_user)),
                                                  QString(QUrl::toPercentEncoding(_ui.passwordLineEdit->text())),
                                                  QString(QUrl::toPercentEncoding(machineId)));
            QNetworkReply *machineActivityReply = tarsnapRequest(machineActivity);
            connect(machineActivityReply, &QNetworkReply::finished,
                    [=]() {
                    QByteArray replyData = readReply(machineActivityReply);
                    parseLastMachineActivity(replyData);
                    if(displayMachineActivity)
                        displayCSVTable(replyData);
            });
        });
    }
}

QString TarsnapAccount::parseMachineId(QString html)
{
    QString machineId;

    if(html.isEmpty() || !html.startsWith("<!DOCTYPE html>"))
        return machineId;

    QRegExp machineIdRx("mid=(\\d+)\">" + QRegExp::escape(_machine) + "", Qt::CaseSensitive, QRegExp::RegExp2);

    if(machineIdRx.lastIndexIn(html))
        machineId = machineIdRx.cap(1);
    else
        DEBUG << "Machine id not found for machine " << _machine;

    return machineId;
}

void TarsnapAccount::parseCredit(QString csv)
{
    if(csv.isEmpty() || !csv.startsWith("RECTYPE"))
        return;
    QRegExp lastBalanceRx("^(Balance.+)$", Qt::CaseInsensitive, QRegExp::RegExp2);
    QString lastBalance;
    foreach (QString line, csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts))
    {
        if(0 == lastBalanceRx.indexIn(line))
            lastBalance = line;
    }

    if(!lastBalance.isEmpty())
    {
        QStringList fields = lastBalance.split(',', QString::SkipEmptyParts);
        if(fields.count() != 3)
        {
            DEBUG << "Invalid CSV.";
            return;
        }
        emit accountCredit(fields.last().toFloat(), QDate::fromString(fields[1], Qt::ISODate));
    }
}

void TarsnapAccount::parseLastMachineActivity(QString csv)
{
    if(csv.isEmpty() || !csv.startsWith("DATE"))
        return;
    QString lastLine = csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts).last();
    emit lastMachineActivity(lastLine.split(',', QString::SkipEmptyParts));
}

void TarsnapAccount::displayCSVTable(QString csv)
{
    DEBUG << csv;
    if(csv.isEmpty() || csv.startsWith("<!DOCTYPE html>"))
        return;

    QStringList lines = csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
    if(lines.count() <= 1)
        return;

    QStringList columnHeaders = lines.first().split(',', QString::SkipEmptyParts);
    lines.removeFirst();

    QTableWidget *table = new QTableWidget(lines.count(), columnHeaders.count());
    table->setHorizontalHeaderLabels(columnHeaders);
    table->horizontalHeader()->setStretchLastSection(true);
    table->setAlternatingRowColors(true);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    QDialog *tableDialog = new QDialog(this);
    tableDialog->setAttribute( Qt::WA_DeleteOnClose, true );
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(table);
    layout->setMargin(0);
    tableDialog->setLayout(layout);

    qint64 row = 0;
    qint64 column = 0;

    foreach (QString line, lines)
    {
        foreach (QString entry, line.split(',', QString::KeepEmptyParts))
        {
            table->setItem(row, column, new QTableWidgetItem(entry));
            column++;
        }
        row++;
        column = 0;
    }
    tableDialog->show();
}

QNetworkReply* TarsnapAccount::tarsnapRequest(QString url)
{
    QNetworkRequest request;
    request.setUrl(url);
    request.setRawHeader("User-Agent",
                         (qApp->applicationName() + " " + qApp->applicationVersion()).toLatin1());
    QNetworkReply *reply = _nam.get(request);
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(networkError(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(sslError(QList<QSslError>)));
    return reply;
}

QByteArray TarsnapAccount::readReply(QNetworkReply *reply, bool warn)
{
    QByteArray data = reply->readAll();
    if(warn && data.contains("Password is incorrect; please try again."))
    {
        QMessageBox::warning(this, tr("Invalid password"),
                             QString("Password for account %1 is incorrect; please try again.").arg(_user));
    }
    reply->close();
    reply->deleteLater();
    return data;
}

void TarsnapAccount::networkError(QNetworkReply::NetworkError error)
{
    Q_UNUSED(error)
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    DEBUG << reply->errorString();
}

void TarsnapAccount::sslError(QList<QSslError> errors)
{
    foreach (QSslError error, errors)
    {
        DEBUG << error.errorString();
    }
}
<commit_msg>Make string translatable.<commit_after>#include "tarsnapaccount.h"
#include "debug.h"

#include <QNetworkRequest>
#include <QNetworkReply>
#include <QTableWidget>
#include <QMessageBox>

#define URL_ACTIVITY "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=activity&format=csv"
#define URL_MACHINE_ACTIVITY "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=subactivity&mid=%3&format=csv"
#define URL_LIST_MACHINES "https://www.tarsnap.com/manage.cgi?address=%1&password=%2&action=subactivity"

TarsnapAccount::TarsnapAccount(QWidget *parent) : QDialog(parent), _user(),
    _nam(this)
{
    _ui.setupUi(this);
}

QString TarsnapAccount::user() const
{
    return _user;
}

void TarsnapAccount::setUser(const QString &user)
{
    _user = user;
    _ui.textLabel->setText(QString("Type password for account %1:").arg(_user));
}

QString TarsnapAccount::getMachine() const
{
    return _machine;
}

void TarsnapAccount::setMachine(const QString &machine)
{
    _machine = machine;
}

void TarsnapAccount::getAccountInfo(bool displayActivity, bool displayMachineActivity)
{
    if(exec())
    {
        QString getActivity(URL_ACTIVITY);
        getActivity = getActivity.arg(QString(QUrl::toPercentEncoding(_user)),
                                      QString(QUrl::toPercentEncoding(_ui.passwordLineEdit->text())));
        QNetworkReply *activityReply = tarsnapRequest(getActivity);
        connect(activityReply, &QNetworkReply::finished,
        [=]() {
            QByteArray replyData = readReply(activityReply, true);
            parseCredit(replyData);
            if(displayActivity)
                displayCSVTable(replyData);
        });
        QString getMachineId(URL_LIST_MACHINES);
        getMachineId = getMachineId.arg(QString(QUrl::toPercentEncoding(_user)),
                                        QString(QUrl::toPercentEncoding(_ui.passwordLineEdit->text())));
        QNetworkReply *machineIdReply = tarsnapRequest(getMachineId);
        connect(machineIdReply, &QNetworkReply::finished,
        [=]() {
            QString machineId = parseMachineId(readReply(machineIdReply));
            QString machineActivity(URL_MACHINE_ACTIVITY);
            machineActivity = machineActivity.arg(QString(QUrl::toPercentEncoding(_user)),
                                                  QString(QUrl::toPercentEncoding(_ui.passwordLineEdit->text())),
                                                  QString(QUrl::toPercentEncoding(machineId)));
            QNetworkReply *machineActivityReply = tarsnapRequest(machineActivity);
            connect(machineActivityReply, &QNetworkReply::finished,
                    [=]() {
                    QByteArray replyData = readReply(machineActivityReply);
                    parseLastMachineActivity(replyData);
                    if(displayMachineActivity)
                        displayCSVTable(replyData);
            });
        });
    }
}

QString TarsnapAccount::parseMachineId(QString html)
{
    QString machineId;

    if(html.isEmpty() || !html.startsWith("<!DOCTYPE html>"))
        return machineId;

    QRegExp machineIdRx("mid=(\\d+)\">" + QRegExp::escape(_machine) + "", Qt::CaseSensitive, QRegExp::RegExp2);

    if(machineIdRx.lastIndexIn(html))
        machineId = machineIdRx.cap(1);
    else
        DEBUG << "Machine id not found for machine " << _machine;

    return machineId;
}

void TarsnapAccount::parseCredit(QString csv)
{
    if(csv.isEmpty() || !csv.startsWith("RECTYPE"))
        return;
    QRegExp lastBalanceRx("^(Balance.+)$", Qt::CaseInsensitive, QRegExp::RegExp2);
    QString lastBalance;
    foreach (QString line, csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts))
    {
        if(0 == lastBalanceRx.indexIn(line))
            lastBalance = line;
    }

    if(!lastBalance.isEmpty())
    {
        QStringList fields = lastBalance.split(',', QString::SkipEmptyParts);
        if(fields.count() != 3)
        {
            DEBUG << "Invalid CSV.";
            return;
        }
        emit accountCredit(fields.last().toFloat(), QDate::fromString(fields[1], Qt::ISODate));
    }
}

void TarsnapAccount::parseLastMachineActivity(QString csv)
{
    if(csv.isEmpty() || !csv.startsWith("DATE"))
        return;
    QString lastLine = csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts).last();
    emit lastMachineActivity(lastLine.split(',', QString::SkipEmptyParts));
}

void TarsnapAccount::displayCSVTable(QString csv)
{
    DEBUG << csv;
    if(csv.isEmpty() || csv.startsWith("<!DOCTYPE html>"))
        return;

    QStringList lines = csv.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
    if(lines.count() <= 1)
        return;

    QStringList columnHeaders = lines.first().split(',', QString::SkipEmptyParts);
    lines.removeFirst();

    QTableWidget *table = new QTableWidget(lines.count(), columnHeaders.count());
    table->setHorizontalHeaderLabels(columnHeaders);
    table->horizontalHeader()->setStretchLastSection(true);
    table->setAlternatingRowColors(true);
    table->setEditTriggers(QAbstractItemView::NoEditTriggers);
    QDialog *tableDialog = new QDialog(this);
    tableDialog->setAttribute( Qt::WA_DeleteOnClose, true );
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(table);
    layout->setMargin(0);
    tableDialog->setLayout(layout);

    qint64 row = 0;
    qint64 column = 0;

    foreach (QString line, lines)
    {
        foreach (QString entry, line.split(',', QString::KeepEmptyParts))
        {
            table->setItem(row, column, new QTableWidgetItem(entry));
            column++;
        }
        row++;
        column = 0;
    }
    tableDialog->show();
}

QNetworkReply* TarsnapAccount::tarsnapRequest(QString url)
{
    QNetworkRequest request;
    request.setUrl(url);
    request.setRawHeader("User-Agent",
                         (qApp->applicationName() + " " + qApp->applicationVersion()).toLatin1());
    QNetworkReply *reply = _nam.get(request);
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(networkError(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(sslError(QList<QSslError>)));
    return reply;
}

QByteArray TarsnapAccount::readReply(QNetworkReply *reply, bool warn)
{
    QByteArray data = reply->readAll();
    if(warn && data.contains("Password is incorrect; please try again."))
    {
        QMessageBox::warning(this, tr("Invalid password"),
                             tr("Password for account %1 is incorrect; please try again.").arg(_user));
    }
    reply->close();
    reply->deleteLater();
    return data;
}

void TarsnapAccount::networkError(QNetworkReply::NetworkError error)
{
    Q_UNUSED(error)
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    DEBUG << reply->errorString();
}

void TarsnapAccount::sslError(QList<QSslError> errors)
{
    foreach (QSslError error, errors)
    {
        DEBUG << error.errorString();
    }
}
<|endoftext|>