<commit_before>/*
Copyright (c) 2016 Teka101

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <log4cplus/loggingmacros.h>
#include <cmath>
#include <math.h>
#include <time.h>
#include "CurlHelpers.h"
#include "DriverDomoticz.h"

typedef std::pair<const std::string, boost::property_tree::ptree> ptreePair;

HardwareDomoticz::HardwareDomoticz(DBHarware &hw) : MHEHardware(hw.id), _hw(hw)
{
}

HardwareDomoticz::~HardwareDomoticz()
{
}

MHEDevice *HardwareDomoticz::buildObject(DBDevice &dev)
{
    return new DeviceDomoticz(_hw.param1, (dev.param2 == "24havg"), dev);
}

DeviceDomoticz::DeviceDomoticz(std::string &urlDomoticz, bool isDayAverage, DBDevice &dev) : MHEDevice(dev.id, dev.type, dev.name, dev.cacheLifetime, dev.hidden, dev.cacheRunning), _urlDomoticz(urlDomoticz), _deviceIdx(dev.param1), _isDayAverage(isDayAverage)
{
    _log = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("DeviceDomoticz"));
}

DeviceDomoticz::~DeviceDomoticz()
{
}

float DeviceDomoticz::getCachedRawTemperature()
{
    return _cache.temperatureRaw;
}

float DeviceDomoticz::getCachedTemperature()
{
    return _cache.temperature;
}

float DeviceDomoticz::getCachedHumidity()
{
    return _cache.humidity;
}

bool DeviceDomoticz::isCachedDimmable()
{
    return _cache.dimmable;
}

int DeviceDomoticz::getCachedDimmableValue()
{
    return _cache.dimmableValue;
}

int DeviceDomoticz::getCachedDimmableMax()
{
    return _cache.dimmableMax;
}

bool DeviceDomoticz::isCachedActivated()
{
    return _cache.statusIsOn;
}

float DeviceDomoticz::getRawTemperature()
{
    refreshCache();
    return _cache.temperatureRaw;
}

float DeviceDomoticz::getTemperature()
{
    refreshCache();
    return _cache.temperature;
}

float DeviceDomoticz::getHumidity()
{
    refreshCache();
    return _cache.humidity;
}

bool DeviceDomoticz::isDimmable()
{
    refreshCache();
    return _cache.dimmable;
}

int DeviceDomoticz::getDimmableValue()
{
    refreshCache();
    return _cache.dimmableValue;
}

int DeviceDomoticz::getDimmableMax()
{
    refreshCache();
    return _cache.dimmableMax;
}

bool DeviceDomoticz::setTempHum(float temperature, float humidity)
{
    std::stringstream ssUrl;

    ssUrl << _urlDomoticz << "json.htm?type=command&param=udevice&idx=" << _deviceIdx << "&nvalue=0&svalue=" << temperature << ';' << humidity << ";2";
    if (curlExecute(ssUrl.str()))
    {
        time_t now = time(NULL);

        _lastUpdate = now;
        _cache.humidity = humidity;
        _cache.temperature = temperature;
        _cache.temperatureRaw = temperature;
        if (_cloneTo != NULL)
            _cloneTo->setTempHum(temperature, humidity);
        return true;
    }
    return false;
}

bool DeviceDomoticz::isActivated()
{
    refreshCache();
    return _cache.statusIsOn;
}

bool DeviceDomoticz::setLevel(int level)
{
    std::stringstream ssUrl;

	ssUrl << _urlDomoticz << "json.htm?type=command&param=switchlight&idx=" << _deviceIdx << "&switchcmd=Set%20Level&level=" << level;
	if (curlExecute(ssUrl.str()))
	{
        time_t now = time(NULL);

        _lastUpdate = now;
        _cache.statusIsOn = level > 0;
        _cache.dimmableValue = level;
        if (_cloneTo != NULL)
            _cloneTo->setLevel(level);
        return true;
	}
    return false;
}

bool DeviceDomoticz::setStatus(bool activate)
{
    std::stringstream ssUrl;

	ssUrl << _urlDomoticz << "json.htm?type=command&param=switchlight&idx=" << _deviceIdx << "&switchcmd=" << (activate ? "On" : "Off") << "&level=0";
	if (curlExecute(ssUrl.str()))
	{
        time_t now = time(NULL);

        _lastUpdate = now;
        _cache.statusIsOn = activate;
        if (_cloneTo != NULL)
            _cloneTo->setStatus(activate);
        return true;
	}
    return false;
}

bool DeviceDomoticz::sendCommand(const std::string &command, const std::string &value, void *output)
{
    tMHEDeviceValues *values = static_cast<tMHEDeviceValues*>(output);
    std::stringstream ssUrl;

    if (command == "values" && value == "last24h" && output != NULL)
    {
        std::string fieldDate;
        std::string dateFormat;

        if (_type == devTempHum)
        {
            ssUrl << _urlDomoticz << "json.htm?type=graph&sensor=temp&idx=" << _deviceIdx << "&range=day";
            fieldDate = "d";
            dateFormat = "%Y-%m-%d %H:%M";
        }
        else
        {
            ssUrl << _urlDomoticz << "json.htm?type=lightlog&idx=" << _deviceIdx;
            fieldDate = "Date";
            dateFormat = "%Y-%m-%d %H:%M:%S";
        }
        return parseGraphData(ssUrl.str(), values, fieldDate, dateFormat);
    }
    else if (command == "values" && value == "lastMonth" && output != NULL && _type == devTempHum)
    {
        ssUrl << _urlDomoticz << "json.htm?type=graph&sensor=temp&idx=" << _deviceIdx << "&range=month";
        return parseGraphData(ssUrl.str(), values, "d", "%Y-%m-%d");
    }
    else if (command == "values" && value == "lastYear" && output != NULL && _type == devTempHum)
    {
        ssUrl << _urlDomoticz << "json.htm?type=graph&sensor=temp&idx=" << _deviceIdx << "&range=year";
        return parseGraphData(ssUrl.str(), values, "d", "%Y-%m-%d");
    }
    return false;
}

bool DeviceDomoticz::parseGraphData(const std::string &url, tMHEDeviceValues *values, const std::string &fieldDate, const std::string &dateFormat)
{
    std::stringstream ssOut;

    if (curlExecute(url, &ssOut))
    {
        boost::property_tree::ptree pTree;

        boost::property_tree::read_json(ssOut, pTree);
        if (pTree.count("result") == 0)
            return false;
        BOOST_FOREACH(ptreePair it, pTree.get_child("result"))
        {
            std::string dateStr = it.second.get(fieldDate, "");
            float temperature = it.second.get<float>("te", NAN);
            float humidity = it.second.get<float>("hu", NAN);
            std::string status = it.second.get("Status", "");
            struct tm tm;

            memset(&tm, 0, sizeof(tm));
            tm.tm_zone = *tzname;
            tm.tm_isdst = daylight;
            if (strptime(dateStr.c_str(), dateFormat.c_str(), &tm) != NULL)
            {
                sMHEDeviceValue v;

                v.date = mktime(&tm);
                v.temperature = temperature;
                v.humdity = humidity;
                if (status.size() > 0)
                {
                    if (boost::starts_with(status, "On"))
                        v.status = "on";
                    else
                        v.status = "off";
                }
                values->push_back(v);
            }
        }
        return true;
    }
    return false;
}

void DeviceDomoticz::refreshCache()
{
    time_t now = time(NULL) - _cacheLifetime;

    if (_lastUpdate < now)
    {
        bool isSuccess = false;

        if (_isDayAverage)
            isSuccess = refreshDayAverage();
        else
            isSuccess = refreshNormal();
        if (isSuccess)
        {
            _lastUpdate = time(NULL);
            LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("DeviceDomoticz::refreshCache - Refresh(" << (std::string)*this << ") = " << (std::string)_cache));
            if (_cloneTo != NULL)
                _cloneTo->setTempHum(_cache.temperature, _cache.humidity);
        }
    }
}

bool DeviceDomoticz::refreshNormal()
{
    std::stringstream ssOut, ssUrl;

    ssUrl << _urlDomoticz << "json.htm?type=devices&rid=" << _deviceIdx;
    if (curlExecute(ssUrl.str(), &ssOut))
    {
        boost::property_tree::ptree pTree;

        boost::property_tree::read_json(ssOut, pTree);
        if (pTree.count("result") == 0)
            return false;
        BOOST_FOREACH(ptreePair &it, pTree.get_child("result"))
        {
            if (it.second.size() > 0)
            {
                BOOST_FOREACH(ptreePair &itChild, it.second)
                {
                    if (itChild.first == "Name")
                        _cache.name = itChild.second.get_value<std::string>();
                    /*else if (itChild.first == "LastUpdate")
                    {
                        std::string date = itChild.second.get_value<std::string>();
                        struct tm tm;

                        memset(&tm, 0, sizeof(tm));
                        tm.tm_zone = *tzname;
                        tm.tm_isdst = daylight;
                        if (strptime(date.c_str(), "%Y-%m-%d %H:%M:%S", &tm) != NULL)
                            _lastUpdate = mktime(&tm);
                    }*/
                    else if (itChild.first == "Status")
                    {
                        std::string status = itChild.second.get_value<std::string>();

                        _cache.statusIsOn = boost::starts_with(status, "On");
                    }
                    else if (itChild.first == "Temp")
                    {
                        _cache.temperature = itChild.second.get_value<float>();
                        _cache.temperatureRaw = _cache.temperature;
                    }
                    else if (itChild.first == "Humidity")
                        _cache.humidity = itChild.second.get_value<float>();
                    else if (itChild.first == "LevelInt")
                        _cache.dimmableValue = itChild.second.get_value<int>();
                    else if (itChild.first == "MaxDimLevel")
                        _cache.dimmableMax = itChild.second.get_value<int>();
                    else if (itChild.first == "SwitchType")
                    {
                        std::string status = itChild.second.get_value<std::string>();

                        _cache.dimmable = boost::starts_with(status, "Dimmer");
                    }
                }
            }
        }
        return true;
    }
    return false;
}

bool DeviceDomoticz::refreshDayAverage()
{
    std::stringstream ssOut, ssUrl;

    ssUrl << _urlDomoticz << "json.htm?type=graph&sensor=temp&idx=" << _deviceIdx << "&range=day";
    if (curlExecute(ssUrl.str(), &ssOut))
    {
        boost::property_tree::ptree pTree;
        double tempTotal = 0.0, tempNumber = 0.0;
        float lastTemperature = 0.0;

        boost::property_tree::read_json(ssOut, pTree);
        if (pTree.count("result") == 0)
            return false;
        BOOST_FOREACH(ptreePair it, pTree.get_child("result"))
        {
            float currentTemp = it.second.get<float>("te", NAN);

            if (std::isnormal(currentTemp))
            {
                tempTotal += currentTemp;
                tempNumber++;
                lastTemperature = currentTemp;
            }
        }
        LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("DeviceDomoticz::refreshDayAverage - tempReturn=" << (tempTotal / tempNumber) << " tempTotal=" << tempTotal << " tempNumber=" << tempNumber << "]"));
        if (tempNumber > 0)
        {
            _cache.temperature = trunc((tempTotal / tempNumber) * 100.0) / 100;
            _cache.temperatureRaw = lastTemperature;
            return true;
        }
    }
    return false;
}
<commit_msg>Fix limit case in Domoticz<commit_after>/*
Copyright (c) 2016 Teka101

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <log4cplus/loggingmacros.h>
#include <cmath>
#include <math.h>
#include <time.h>
#include "CurlHelpers.h"
#include "DriverDomoticz.h"

typedef std::pair<const std::string, boost::property_tree::ptree> ptreePair;

HardwareDomoticz::HardwareDomoticz(DBHarware &hw) : MHEHardware(hw.id), _hw(hw)
{
}

HardwareDomoticz::~HardwareDomoticz()
{
}

MHEDevice *HardwareDomoticz::buildObject(DBDevice &dev)
{
    return new DeviceDomoticz(_hw.param1, (dev.param2 == "24havg"), dev);
}

DeviceDomoticz::DeviceDomoticz(std::string &urlDomoticz, bool isDayAverage, DBDevice &dev) : MHEDevice(dev.id, dev.type, dev.name, dev.cacheLifetime, dev.hidden, dev.cacheRunning), _urlDomoticz(urlDomoticz), _deviceIdx(dev.param1), _isDayAverage(isDayAverage)
{
    _log = log4cplus::Logger::getInstance(LOG4CPLUS_TEXT("DeviceDomoticz"));
}

DeviceDomoticz::~DeviceDomoticz()
{
}

float DeviceDomoticz::getCachedRawTemperature()
{
    return _cache.temperatureRaw;
}

float DeviceDomoticz::getCachedTemperature()
{
    return _cache.temperature;
}

float DeviceDomoticz::getCachedHumidity()
{
    return _cache.humidity;
}

bool DeviceDomoticz::isCachedDimmable()
{
    return _cache.dimmable;
}

int DeviceDomoticz::getCachedDimmableValue()
{
    return _cache.dimmableValue;
}

int DeviceDomoticz::getCachedDimmableMax()
{
    return _cache.dimmableMax;
}

bool DeviceDomoticz::isCachedActivated()
{
    return _cache.statusIsOn;
}

float DeviceDomoticz::getRawTemperature()
{
    refreshCache();
    return _cache.temperatureRaw;
}

float DeviceDomoticz::getTemperature()
{
    refreshCache();
    return _cache.temperature;
}

float DeviceDomoticz::getHumidity()
{
    refreshCache();
    return _cache.humidity;
}

bool DeviceDomoticz::isDimmable()
{
    refreshCache();
    return _cache.dimmable;
}

int DeviceDomoticz::getDimmableValue()
{
    refreshCache();
    return _cache.dimmableValue;
}

int DeviceDomoticz::getDimmableMax()
{
    refreshCache();
    return _cache.dimmableMax;
}

bool DeviceDomoticz::setTempHum(float temperature, float humidity)
{
    std::stringstream ssUrl;

    ssUrl << _urlDomoticz << "json.htm?type=command&param=udevice&idx=" << _deviceIdx << "&nvalue=0&svalue=" << temperature << ';' << humidity << ";2";
    if (curlExecute(ssUrl.str()))
    {
        time_t now = time(NULL);

        _lastUpdate = now;
        _cache.humidity = humidity;
        _cache.temperature = temperature;
        _cache.temperatureRaw = temperature;
        if (_cloneTo != NULL)
            _cloneTo->setTempHum(temperature, humidity);
        return true;
    }
    return false;
}

bool DeviceDomoticz::isActivated()
{
    refreshCache();
    return _cache.statusIsOn;
}

bool DeviceDomoticz::setLevel(int level)
{
    std::stringstream ssUrl;

	ssUrl << _urlDomoticz << "json.htm?type=command&param=switchlight&idx=" << _deviceIdx << "&switchcmd=Set%20Level&level=" << level;
	if (curlExecute(ssUrl.str()))
	{
        time_t now = time(NULL);

        _lastUpdate = now;
        _cache.statusIsOn = level > 0;
        _cache.dimmableValue = level;
        if (_cloneTo != NULL)
            _cloneTo->setLevel(level);
        return true;
	}
    return false;
}

bool DeviceDomoticz::setStatus(bool activate)
{
    std::stringstream ssUrl;

	ssUrl << _urlDomoticz << "json.htm?type=command&param=switchlight&idx=" << _deviceIdx << "&switchcmd=" << (activate ? "On" : "Off") << "&level=0";
	if (curlExecute(ssUrl.str()))
	{
        time_t now = time(NULL);

        _lastUpdate = now;
        _cache.statusIsOn = activate;
        if (_cloneTo != NULL)
            _cloneTo->setStatus(activate);
        return true;
	}
    return false;
}

bool DeviceDomoticz::sendCommand(const std::string &command, const std::string &value, void *output)
{
    tMHEDeviceValues *values = static_cast<tMHEDeviceValues*>(output);
    std::stringstream ssUrl;

    if (command == "values" && value == "last24h" && output != NULL)
    {
        std::string fieldDate;
        std::string dateFormat;

        if (_type == devTempHum)
        {
            ssUrl << _urlDomoticz << "json.htm?type=graph&sensor=temp&idx=" << _deviceIdx << "&range=day";
            fieldDate = "d";
            dateFormat = "%Y-%m-%d %H:%M";
        }
        else
        {
            ssUrl << _urlDomoticz << "json.htm?type=lightlog&idx=" << _deviceIdx;
            fieldDate = "Date";
            dateFormat = "%Y-%m-%d %H:%M:%S";
        }
        return parseGraphData(ssUrl.str(), values, fieldDate, dateFormat);
    }
    else if (command == "values" && value == "lastMonth" && output != NULL && _type == devTempHum)
    {
        ssUrl << _urlDomoticz << "json.htm?type=graph&sensor=temp&idx=" << _deviceIdx << "&range=month";
        return parseGraphData(ssUrl.str(), values, "d", "%Y-%m-%d");
    }
    else if (command == "values" && value == "lastYear" && output != NULL && _type == devTempHum)
    {
        ssUrl << _urlDomoticz << "json.htm?type=graph&sensor=temp&idx=" << _deviceIdx << "&range=year";
        return parseGraphData(ssUrl.str(), values, "d", "%Y-%m-%d");
    }
    return false;
}

bool DeviceDomoticz::parseGraphData(const std::string &url, tMHEDeviceValues *values, const std::string &fieldDate, const std::string &dateFormat)
{
    std::stringstream ssOut;

    if (curlExecute(url, &ssOut))
    {
        boost::property_tree::ptree pTree;

        boost::property_tree::read_json(ssOut, pTree);
        if (pTree.count("result") == 0)
            return false;
        BOOST_FOREACH(ptreePair it, pTree.get_child("result"))
        {
            std::string dateStr = it.second.get(fieldDate, "");
            float temperature = it.second.get<float>("te", NAN);
            float humidity = it.second.get<float>("hu", NAN);
            std::string status = it.second.get("Status", "");
            struct tm tm;

            memset(&tm, 0, sizeof(tm));
            tm.tm_zone = *tzname;
            tm.tm_isdst = daylight;
            if (strptime(dateStr.c_str(), dateFormat.c_str(), &tm) != NULL)
            {
                sMHEDeviceValue v;

                v.date = mktime(&tm);
                v.temperature = temperature;
                v.humdity = humidity;
                if (status.size() > 0)
                {
                    if (boost::starts_with(status, "On"))
                        v.status = "on";
                    else
                        v.status = "off";
                }
                values->push_back(v);
            }
        }
        return true;
    }
    return false;
}

void DeviceDomoticz::refreshCache()
{
    time_t now = time(NULL) - _cacheLifetime;

    if (_lastUpdate < now)
    {
        bool isSuccess = false;

        if (_isDayAverage)
            isSuccess = refreshDayAverage();
        else
            isSuccess = refreshNormal();
        if (isSuccess)
        {
            _lastUpdate = time(NULL);
            LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("DeviceDomoticz::refreshCache - Refresh(" << (std::string)*this << ") = " << (std::string)_cache));
            if (_cloneTo != NULL)
                _cloneTo->setTempHum(_cache.temperature, _cache.humidity);
        }
    }
}

bool DeviceDomoticz::refreshNormal()
{
    std::stringstream ssOut, ssUrl;

    ssUrl << _urlDomoticz << "json.htm?type=devices&rid=" << _deviceIdx;
    if (curlExecute(ssUrl.str(), &ssOut))
    {
        boost::property_tree::ptree pTree;

        boost::property_tree::read_json(ssOut, pTree);
        if (pTree.count("result") == 0)
            return false;
        BOOST_FOREACH(ptreePair &it, pTree.get_child("result"))
        {
            if (it.second.size() > 0)
            {
                BOOST_FOREACH(ptreePair &itChild, it.second)
                {
                    if (itChild.first == "Name")
                        _cache.name = itChild.second.get_value<std::string>();
                    else if (itChild.first == "Status")
                    {
                        std::string status = itChild.second.get_value<std::string>();

                        _cache.statusIsOn = boost::starts_with(status, "On");
                    }
                    else if (itChild.first == "Temp")
                    {
                        _cache.temperature = itChild.second.get_value<float>();
                        _cache.temperatureRaw = _cache.temperature;
                    }
                    else if (itChild.first == "Humidity")
                        _cache.humidity = itChild.second.get_value<float>();
                    else if (itChild.first == "LevelInt")
                        _cache.dimmableValue = itChild.second.get_value<int>();
                    else if (itChild.first == "MaxDimLevel")
                        _cache.dimmableMax = itChild.second.get_value<int>();
                    else if (itChild.first == "SwitchType")
                    {
                        std::string status = itChild.second.get_value<std::string>();

                        _cache.dimmable = boost::starts_with(status, "Dimmer");
                    }
                }
            }
        }
        if (!_cache.statusIsOn)
            _cache.dimmableValue = 0;
        return true;
    }
    return false;
}

bool DeviceDomoticz::refreshDayAverage()
{
    std::stringstream ssOut, ssUrl;

    ssUrl << _urlDomoticz << "json.htm?type=graph&sensor=temp&idx=" << _deviceIdx << "&range=day";
    if (curlExecute(ssUrl.str(), &ssOut))
    {
        boost::property_tree::ptree pTree;
        double tempTotal = 0.0, tempNumber = 0.0;
        float lastTemperature = 0.0;

        boost::property_tree::read_json(ssOut, pTree);
        if (pTree.count("result") == 0)
            return false;
        BOOST_FOREACH(ptreePair it, pTree.get_child("result"))
        {
            float currentTemp = it.second.get<float>("te", NAN);

            if (std::isnormal(currentTemp))
            {
                tempTotal += currentTemp;
                tempNumber++;
                lastTemperature = currentTemp;
            }
        }
        LOG4CPLUS_DEBUG(_log, LOG4CPLUS_TEXT("DeviceDomoticz::refreshDayAverage - tempReturn=" << (tempTotal / tempNumber) << " tempTotal=" << tempTotal << " tempNumber=" << tempNumber << "]"));
        if (tempNumber > 0)
        {
            _cache.temperature = trunc((tempTotal / tempNumber) * 100.0) / 100;
            _cache.temperatureRaw = lastTemperature;
            return true;
        }
    }
    return false;
}
<|endoftext|>


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

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

#include <svtools/moduleoptions.hxx>
#include "sddll.hxx"
#include "diactrl.hxx"
#include "tbx_ww.hxx"
#ifndef SD_TEXT_OBJECT_BAR_HXX
#include "TextObjectBar.hxx"
#endif
#ifndef SD_BEZIER_OBJECT_BAR_HXX
#include "BezierObjectBar.hxx"
#endif
#ifndef SD_GRAPHIC_OBJECT_BAR_HXX
#include "GraphicObjectBar.hxx"
#endif
#ifndef SD_MEDIA_OBJECT_BAR_HXX
#include "MediaObjectBar.hxx"
#endif
#ifndef SD_VIEW_SHELL_BASE_HXX
#include "ViewShellBase.hxx"
#endif
#ifndef SD_PRESENTATION_VIEW_SHELL_BASE_HXX
#include "PresentationViewShellBase.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_SLIDE_VIEW_SHELL_HXX
#include "SlideViewShell.hxx"
#endif
#ifndef SD_PRESENTATION_VIEW_SHELL_HXX
#include "PresentationViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_BASE_HXX
#include "OutlineViewShellBase.hxx"
#endif
#ifndef SD_SLIDE_SORTER_VIEW_SHELL_BASE_HXX
#include "SlideSorterViewShellBase.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#include "GraphicViewShell.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_BASE_HXX
#include "GraphicViewShellBase.hxx"
#endif
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#ifndef SD_GRAPHIC_DOC_SHELL_HXX
#include "GraphicDocShell.hxx"
#endif
#ifndef SD_SLIDEBROWSER_SLIDE_SORTER_VIEW_SHELL_HXX
#include "SlideSorterViewShell.hxx"
#endif
#ifndef SD_SLIDEBROWSER_TASK_PANE_VIEW_SHELL_HXX
#include "TaskPaneViewShell.hxx"
#endif
#ifndef SD_FACTORY_IDS_HXX
#include "FactoryIds.hxx"
#endif
#include "sdmod.hxx"
#include "app.hrc"

/*************************************************************************
|*
|* Register all Factorys
|*
\************************************************************************/

void SdDLL::RegisterFactorys()
{
    if (SvtModuleOptions().IsImpress())
    {
        ::sd::ViewShellBase::RegisterFactory (
            ::sd::IMPRESS_FACTORY_ID);
        ::sd::SlideSorterViewShellBase::RegisterFactory (
            ::sd::SLIDE_SORTER_FACTORY_ID);
        ::sd::OutlineViewShellBase::RegisterFactory (
            ::sd::OUTLINE_FACTORY_ID);
        ::sd::PresentationViewShellBase::RegisterFactory (
            ::sd::PRESENTATION_FACTORY_ID);
    }
    if (SvtModuleOptions().IsDraw())
    {
        ::sd::GraphicViewShellBase::RegisterFactory (::sd::DRAW_FACTORY_ID);
    }
}

/*************************************************************************
|*
|* Register all Interfaces
|*
\************************************************************************/

void SdDLL::RegisterInterfaces()
{
    // Modul
    SfxModule* pMod = SD_MOD();
    SdModule::RegisterInterface(pMod);

    // View shell base.
    ::sd::ViewShellBase::RegisterInterface(pMod);

    // DocShells
    ::sd::DrawDocShell::RegisterInterface(pMod);
    ::sd::GraphicDocShell::RegisterInterface(pMod);

    // Impress ViewShells
    ::sd::DrawViewShell::RegisterInterface(pMod);
    ::sd::SlideViewShell::RegisterInterface(pMod);
    ::sd::OutlineViewShell::RegisterInterface(pMod);
    ::sd::PresentationViewShell::RegisterInterface(pMod);

    // Draw ViewShell
    ::sd::GraphicViewShell::RegisterInterface(pMod);

    // Impress ObjectShells
    ::sd::BezierObjectBar::RegisterInterface(pMod);
    ::sd::TextObjectBar::RegisterInterface(pMod);
    ::sd::GraphicObjectBar::RegisterInterface(pMod);

    // Media ObjectShell
    ::sd::MediaObjectBar::RegisterInterface(pMod);

    // View shells for the side panes.
    ::sd::slidesorter::SlideSorterViewShell::RegisterInterface (pMod);
    ::sd::toolpanel::TaskPaneViewShell::RegisterInterface(pMod);
    // Tell the task pane view shell to register the interfaces of its
    // controls.
    ::sd::toolpanel::TaskPaneViewShell::RegisterControls();
}
<commit_msg>INTEGRATION: CWS components1 (1.14.98); FILE MERGED 2006/09/25 16:53:52 af 1.14.98.2: RESYNC: (1.14-1.15); FILE MERGED 2006/08/22 09:30:32 af 1.14.98.1: #i68075# Using ImpressViewShellBase instead of ViewShellBase.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sddll1.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-03 15:38:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include <svtools/moduleoptions.hxx>
#include "sddll.hxx"
#include "diactrl.hxx"
#include "tbx_ww.hxx"
#ifndef SD_TEXT_OBJECT_BAR_HXX
#include "TextObjectBar.hxx"
#endif
#ifndef SD_BEZIER_OBJECT_BAR_HXX
#include "BezierObjectBar.hxx"
#endif
#ifndef SD_GRAPHIC_OBJECT_BAR_HXX
#include "GraphicObjectBar.hxx"
#endif
#ifndef SD_MEDIA_OBJECT_BAR_HXX
#include "MediaObjectBar.hxx"
#endif
#ifndef SD_IMPRESS_VIEW_SHELL_BASE_HXX
#include "ImpressViewShellBase.hxx"
#endif
#ifndef SD_PRESENTATION_VIEW_SHELL_BASE_HXX
#include "PresentationViewShellBase.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_HXX
#include "OutlineViewShell.hxx"
#endif
#ifndef SD_SLIDE_VIEW_SHELL_HXX
#include "SlideViewShell.hxx"
#endif
#ifndef SD_PRESENTATION_VIEW_SHELL_HXX
#include "PresentationViewShell.hxx"
#endif
#ifndef SD_OUTLINE_VIEW_SHELL_BASE_HXX
#include "OutlineViewShellBase.hxx"
#endif
#ifndef SD_SLIDE_SORTER_VIEW_SHELL_BASE_HXX
#include "SlideSorterViewShellBase.hxx"
#endif
#ifndef SD_DRAW_VIEW_SHELL_HXX
#include "DrawViewShell.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_HXX
#include "GraphicViewShell.hxx"
#endif
#ifndef SD_GRAPHIC_VIEW_SHELL_BASE_HXX
#include "GraphicViewShellBase.hxx"
#endif
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#ifndef SD_GRAPHIC_DOC_SHELL_HXX
#include "GraphicDocShell.hxx"
#endif
#ifndef SD_SLIDEBROWSER_SLIDE_SORTER_VIEW_SHELL_HXX
#include "SlideSorterViewShell.hxx"
#endif
#ifndef SD_SLIDEBROWSER_TASK_PANE_VIEW_SHELL_HXX
#include "TaskPaneViewShell.hxx"
#endif
#ifndef SD_FACTORY_IDS_HXX
#include "FactoryIds.hxx"
#endif
#include "sdmod.hxx"
#include "app.hrc"

/*************************************************************************
|*
|* Register all Factorys
|*
\************************************************************************/

void SdDLL::RegisterFactorys()
{
    if (SvtModuleOptions().IsImpress())
    {
        ::sd::ImpressViewShellBase::RegisterFactory (
            ::sd::IMPRESS_FACTORY_ID);
        ::sd::SlideSorterViewShellBase::RegisterFactory (
            ::sd::SLIDE_SORTER_FACTORY_ID);
        ::sd::OutlineViewShellBase::RegisterFactory (
            ::sd::OUTLINE_FACTORY_ID);
        ::sd::PresentationViewShellBase::RegisterFactory (
            ::sd::PRESENTATION_FACTORY_ID);
    }
    if (SvtModuleOptions().IsDraw())
    {
        ::sd::GraphicViewShellBase::RegisterFactory (::sd::DRAW_FACTORY_ID);
    }
}

/*************************************************************************
|*
|* Register all Interfaces
|*
\************************************************************************/

void SdDLL::RegisterInterfaces()
{
    // Modul
    SfxModule* pMod = SD_MOD();
    SdModule::RegisterInterface(pMod);

    // View shell base.
    ::sd::ViewShellBase::RegisterInterface(pMod);

    // DocShells
    ::sd::DrawDocShell::RegisterInterface(pMod);
    ::sd::GraphicDocShell::RegisterInterface(pMod);

    // Impress ViewShells
    ::sd::DrawViewShell::RegisterInterface(pMod);
    ::sd::SlideViewShell::RegisterInterface(pMod);
    ::sd::OutlineViewShell::RegisterInterface(pMod);
    ::sd::PresentationViewShell::RegisterInterface(pMod);

    // Draw ViewShell
    ::sd::GraphicViewShell::RegisterInterface(pMod);

    // Impress ObjectShells
    ::sd::BezierObjectBar::RegisterInterface(pMod);
    ::sd::TextObjectBar::RegisterInterface(pMod);
    ::sd::GraphicObjectBar::RegisterInterface(pMod);

    // Media ObjectShell
    ::sd::MediaObjectBar::RegisterInterface(pMod);

    // View shells for the side panes.
    ::sd::slidesorter::SlideSorterViewShell::RegisterInterface (pMod);
    ::sd::toolpanel::TaskPaneViewShell::RegisterInterface(pMod);
    // Tell the task pane view shell to register the interfaces of its
    // controls.
    ::sd::toolpanel::TaskPaneViewShell::RegisterControls();
}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2008 Volker Krause <vkrause@kde.org>

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

    This 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 Library General Public
    License for more details.

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

#include "copy.h"

#include "akonadiconnection.h"
#include "handlerhelper.h"

#include "storage/datastore.h"
#include "storage/itemqueryhelper.h"
#include "storage/itemretriever.h"
#include "storage/selectquerybuilder.h"
#include "storage/transaction.h"
#include "storage/parthelper.h"

#include "libs/imapset_p.h"
#include "imapstreamparser.h"

using namespace Akonadi;

bool Copy::copyItem(const PimItem & item, const Collection & target)
{
  qDebug() << "Copy::copyItem";
  DataStore *store = connection()->storageBackend();
  PimItem newItem = item;
  newItem.setId( -1 );
  newItem.setRev( 0 );
  newItem.setDatetime( QDateTime::currentDateTime() );
  newItem.setAtime( QDateTime::currentDateTime() );
  newItem.setRemoteId( QString() );
  newItem.setCollectionId( target.id() );
  Part::List parts;
  foreach ( const Part &part, item.parts() ) {
    Part newPart( part );
    newPart.setData(PartHelper::translateData(newPart.id(), newPart.data(), part.external()));
    newPart.setPimItemId( -1 );
    parts << newPart;
  }
  return store->appendPimItem( parts, item.mimeType(), target, QDateTime::currentDateTime(), QString(), newItem );
}

bool Copy::parseStream()
{
  ImapSet set = m_streamParser->readSequenceSet();
  if ( set.isEmpty() )
    return failureResponse( "No items specified" );

  ItemRetriever retriever( connection() );
  retriever.setItemSet( set );
  retriever.setRetrieveFullPayload( true );
  retriever.exec();

  const QByteArray tmp = m_streamParser->readString();
  const Collection col = HandlerHelper::collectionFromIdOrName( tmp );
  if ( !col.isValid() )
    return failureResponse( "No valid target specified" );

  SelectQueryBuilder<PimItem> qb;
  ItemQueryHelper::itemSetToQuery( set, qb );
  if ( !qb.exec() )
    return failureResponse( "Unable to retrieve items" );
  PimItem::List items = qb.result();

  DataStore *store = connection()->storageBackend();
  Transaction transaction( store );

  foreach ( const PimItem &item, items ) {
    if ( !copyItem( item, col ) )
      return failureResponse( "Unable to copy item" );
  }

  if ( !transaction.commit() )
    return failureResponse( "Cannot commit transaction." );

  return successResponse( "COPY complete" );
}

#include "copy.moc"
<commit_msg>copy flags as well when copying items<commit_after>/*
    Copyright (c) 2008 Volker Krause <vkrause@kde.org>

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

    This 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 Library General Public
    License for more details.

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

#include "copy.h"

#include "akonadiconnection.h"
#include "handlerhelper.h"

#include "storage/datastore.h"
#include "storage/itemqueryhelper.h"
#include "storage/itemretriever.h"
#include "storage/selectquerybuilder.h"
#include "storage/transaction.h"
#include "storage/parthelper.h"

#include "libs/imapset_p.h"
#include "imapstreamparser.h"

using namespace Akonadi;

bool Copy::copyItem(const PimItem & item, const Collection & target)
{
  qDebug() << "Copy::copyItem";
  DataStore *store = connection()->storageBackend();
  PimItem newItem = item;
  newItem.setId( -1 );
  newItem.setRev( 0 );
  newItem.setDatetime( QDateTime::currentDateTime() );
  newItem.setAtime( QDateTime::currentDateTime() );
  newItem.setRemoteId( QString() );
  newItem.setCollectionId( target.id() );
  Part::List parts;
  foreach ( const Part &part, item.parts() ) {
    Part newPart( part );
    newPart.setData(PartHelper::translateData(newPart.id(), newPart.data(), part.external()));
    newPart.setPimItemId( -1 );
    parts << newPart;
  }
  if ( !store->appendPimItem( parts, item.mimeType(), target, QDateTime::currentDateTime(), QString(), newItem ) )
    return false;
  foreach ( const Flag &flag, item.flags() ) {
    if ( !newItem.addFlag( flag ) )
      return false;
  }
  return true;
}

bool Copy::parseStream()
{
  ImapSet set = m_streamParser->readSequenceSet();
  if ( set.isEmpty() )
    return failureResponse( "No items specified" );

  ItemRetriever retriever( connection() );
  retriever.setItemSet( set );
  retriever.setRetrieveFullPayload( true );
  retriever.exec();

  const QByteArray tmp = m_streamParser->readString();
  const Collection col = HandlerHelper::collectionFromIdOrName( tmp );
  if ( !col.isValid() )
    return failureResponse( "No valid target specified" );

  SelectQueryBuilder<PimItem> qb;
  ItemQueryHelper::itemSetToQuery( set, qb );
  if ( !qb.exec() )
    return failureResponse( "Unable to retrieve items" );
  PimItem::List items = qb.result();

  DataStore *store = connection()->storageBackend();
  Transaction transaction( store );

  foreach ( const PimItem &item, items ) {
    if ( !copyItem( item, col ) )
      return failureResponse( "Unable to copy item" );
  }

  if ( !transaction.commit() )
    return failureResponse( "Cannot commit transaction." );

  return successResponse( "COPY complete" );
}

#include "copy.moc"
<|endoftext|>


<commit_before>#include <stdio.h>
#include "../src/low_funct.hpp"

#define MCL_USE_VINT
#define MCL_VINT_FIXED_BUFFER
#define MCL_SIZEOF_UNIT 4
#define MCL_MAX_BIT_SIZE 768
#include <mcl/vint.hpp>
#include <cybozu/test.hpp>
#include <cybozu/xorshift.hpp>
#include <cybozu/benchmark.hpp>

template<class RG>
void setRand(uint32_t *x, size_t n, RG& rg)
{
	for (size_t i = 0; i < n; i++) {
		x[i] = rg.get32();
	}
}

/*
g++ -Ofast -DNDEBUG -Wall -Wextra -m32 -I ./include/ misc/low_test.cpp
Core i7-8700
         mulT  karatsuba
N =  6, 182clk   225clk
N =  8, 300clk   350clk
N = 12, 594clk   730clk
*/
CYBOZU_TEST_AUTO(mulT)
{
	cybozu::XorShift rg;
	const size_t N = 12;
	uint32_t x[N];
	uint32_t y[N];
	uint32_t z[N * 2];
	for (size_t i = 0; i < 1000; i++) {
		setRand(x, N, rg);
		setRand(y, N, rg);
		// remove MSB
		x[N - 1] &= 0x7fffffff;
		y[N - 1] &= 0x7fffffff;
		mcl::Vint vx, vy;
		vx.setArray(x, N);
		vy.setArray(y, N);
		vx *= vy;
		mcl::mulT<N>(z, x, y);
		CYBOZU_TEST_EQUAL_ARRAY(z, vx.getUnit(), N * 2);
		memset(z, 0, sizeof(z));
		mcl::karatsubaT<N>(z, x, y);
		CYBOZU_TEST_EQUAL_ARRAY(z, vx.getUnit(), N * 2);
	}
	CYBOZU_BENCH_C("mulT", 10000, mcl::mulT<N>, z, x, y);
	CYBOZU_BENCH_C("kara", 10000, mcl::karatsubaT<N>, z, x, y);
}

<commit_msg>test N = 8, 12<commit_after>#include <stdio.h>
#include "../src/low_funct.hpp"

#define MCL_USE_VINT
#define MCL_VINT_FIXED_BUFFER
#define MCL_SIZEOF_UNIT 4
#define MCL_MAX_BIT_SIZE 768
#include <mcl/vint.hpp>
#include <cybozu/test.hpp>
#include <cybozu/xorshift.hpp>
#include <cybozu/benchmark.hpp>

template<class RG>
void setRand(uint32_t *x, size_t n, RG& rg)
{
	for (size_t i = 0; i < n; i++) {
		x[i] = rg.get32();
	}
}

/*
g++ -Ofast -DNDEBUG -Wall -Wextra -m32 -I ./include/ misc/low_test.cpp
Core i7-8700
         mulT  karatsuba
N =  6, 182clk   225clk
N =  8, 300clk   350clk
N = 12, 594clk   730clk
*/
template<size_t N>
void mulTest()
{
	printf("N=%zd (%zdbit)\n", N, N * 32);
	cybozu::XorShift rg;
	uint32_t x[N];
	uint32_t y[N];
	uint32_t z[N * 2];
	for (size_t i = 0; i < 1000; i++) {
		setRand(x, N, rg);
		setRand(y, N, rg);
		// remove MSB
		x[N - 1] &= 0x7fffffff;
		y[N - 1] &= 0x7fffffff;
		mcl::Vint vx, vy;
		vx.setArray(x, N);
		vy.setArray(y, N);
		vx *= vy;
		mcl::mulT<N>(z, x, y);
		CYBOZU_TEST_EQUAL_ARRAY(z, vx.getUnit(), N * 2);
		memset(z, 0, sizeof(z));
		mcl::karatsubaT<N>(z, x, y);
		CYBOZU_TEST_EQUAL_ARRAY(z, vx.getUnit(), N * 2);
	}
	CYBOZU_BENCH_C("mulT", 10000, mcl::mulT<N>, z, x, y);
	CYBOZU_BENCH_C("kara", 10000, mcl::karatsubaT<N>, z, x, y);
}

CYBOZU_TEST_AUTO(mulT)
{
	mulTest<8>();
	mulTest<12>();
}
<|endoftext|>


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

#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>     // SvUShorts

#ifndef _IFACE_HXX //autogen
#include <so3/iface.hxx>
#endif

#include "sfx.hrc"
#include "childwin.hxx"
#include "shell.hxx"
#include "minarray.hxx"
#include "ctrlitem.hxx"
#include "stbmgr.hxx"

class SfxToolBoxManager;
class SfxInPlaceEnv_Impl;
class SfxPlugInEnv_Impl;
class SfxSplitWindow;
class SfxWorkWindow;
class XDispatch;

//====================================================================
// Dieser struct h"alt alle relevanten Informationen "uber Toolboxen bereit.

struct SfxObjectBar_Impl
{
    USHORT              nId;    // Resource - und ConfigId der Toolbox
    USHORT              nMode;  // spezielle Sichtbarkeitsflags
    SfxToolBoxManager*  pTbx;
    String              aName;
    ResMgr*             pResMgr;
    SfxInterface*       pIFace;

    SfxObjectBar_Impl() :
        nId(0),
        nMode(0),
        pTbx(0),
        pResMgr(0),
        pIFace(0)
    {}
};

//------------------------------------------------------------------------------
// Dieser struct h"alt alle relevanten Informationen "uber die Statuszeile bereit.
struct SfxStatBar_Impl
{
    ResMgr*                 pResMgr;
    SfxShell*               pShell;
    SfxBindings*            pBindings;
    USHORT                  nId;
    SfxStatusBarManager*    pStatusBar;
    BOOL                    bOn;
    BOOL                    bTemp;

    SfxStatBar_Impl() :
        nId(0),
        pResMgr(0),
        pShell(0),
        pBindings(0),
        pStatusBar(0),
        bOn(TRUE),
        bTemp(FALSE)
    {}
};

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

#define CHILD_NOT_VISIBLE   0
#define CHILD_ACTIVE        1   // nicht durch HidePopups ausgeschaltet
#define CHILD_NOT_HIDDEN    2   // nicht durch HideChildWindow ausgeschaltet
#define CHILD_FITS_IN       4   // nicht zu gro\s f"ur OutputSize des parent
#define CHILD_VISIBLE       (CHILD_NOT_HIDDEN | CHILD_ACTIVE | CHILD_FITS_IN)
#define CHILD_ISVISIBLE     (CHILD_NOT_HIDDEN | CHILD_ACTIVE)

struct SfxChild_Impl
{
    Window*                         pWin;
    Size                            aSize;
    SfxChildAlignment               eAlign;
    USHORT                          nVisible;
    BOOL                            bResize;
    BOOL                            bCanGetFocus;

    SfxChild_Impl( Window& rChild, const Size& rSize,
                   SfxChildAlignment eAlignment, BOOL bIsVisible ):
        pWin(&rChild), aSize(rSize), eAlign(eAlignment), bResize(FALSE),
        bCanGetFocus( FALSE )
    {
        nVisible = bIsVisible ? CHILD_VISIBLE : CHILD_NOT_VISIBLE;
    }
};

//--------------------------------------------------------------------
class SfxChildWinController_Impl : public SfxControllerItem
{
    SfxWorkWindow*  pWorkwin;

    public:
                    SfxChildWinController_Impl( USHORT nId, SfxWorkWindow *pWin );
    virtual void    StateChanged( USHORT nSID, SfxItemState eState,
                            const SfxPoolItem* pState );
};

struct SfxChildWin_Impl
{
    USHORT                          nSaveId;        // die ChildWindow-Id
    USHORT                          nInterfaceId;   // der aktuelle Context
    USHORT                          nId;            // aktuelle Id
    SfxChildWindow*                 pWin;
    BOOL                            bCreate;
    SfxChildWinInfo                 aInfo;
    SfxChild_Impl*                  pCli;           // != 0 bei direkten Children
    USHORT                          nVisibility;
    BOOL                            bEnable;
    SfxChildWinController_Impl*     pControl;
    BOOL                            bDisabled;

    SfxChildWin_Impl( ULONG nID ) :
        nSaveId((USHORT) (nID & 0xFFFF) ),
        nInterfaceId((USHORT) (nID >> 16)),
        nId(nSaveId),
        pWin(0),
        bCreate(FALSE),
        pCli(0),
        nVisibility( FALSE ),
        bEnable( TRUE ),
        bDisabled( FALSE ),
        pControl( 0 )
    {}
};

enum SfxChildIdentifier
{
    SFX_CHILDWIN_STATBAR,
    SFX_CHILDWIN_OBJECTBAR,
    SFX_CHILDWIN_DOCKINGWINDOW,
    SFX_CHILDWIN_SPLITWINDOW
};

enum SfxDockingConfig
{
    SFX_SETDOCKINGRECTS,
    SFX_ALIGNDOCKINGWINDOW,
    SFX_TOGGLEFLOATMODE,
    SFX_MOVEDOCKINGWINDOW
};

DECL_PTRARRAY( SfxChildList_Impl, SfxChild_Impl*, 2, 2 );
DECL_PTRARRAY( SfxChildWindows_Impl, SfxChildWin_Impl*, 2, 2 );

SV_DECL_OBJARR( SfxObjectBarArr_Impl, SfxObjectBar_Impl, 1, 2 );

struct SfxObjectBarList_Impl
{
    SfxObjectBarArr_Impl    aArr;
    USHORT                  nAct;

    SfxObjectBar_Impl       operator[] ( USHORT n )
                            { return aArr[n]; }
    SfxObjectBar_Impl       Actual()
                            { return aArr[nAct]; }
};

struct SfxSplitWin_Impl
{
    SfxSplitWindow*         pSplitWin;
    SfxChildWindows_Impl*   pChildWins;
};

#define SFX_SPLITWINDOWS_LEFT   0
#define SFX_SPLITWINDOWS_TOP    2
#define SFX_SPLITWINDOWS_RIGHT  1
#define SFX_SPLITWINDOWS_BOTTOM 3
#define SFX_SPLITWINDOWS_MAX    4

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

class SfxWorkWindow
{
protected:
    SfxStatBar_Impl         aStatBar;
    SfxWorkWindow*          pParent;
    SvUShorts               aSortedList;
    SfxObjectBar_Impl       aObjBars[SFX_OBJECTBAR_MAX];
    SfxObjectBarList_Impl   aObjBarLists[SFX_OBJECTBAR_MAX];
    SfxSplitWindow*         pSplit[SFX_SPLITWINDOWS_MAX];
    SfxChildList_Impl*      pChilds;
    SfxChildWindows_Impl*   pChildWins;
    SfxBindings*            pBindings;
    Window*                 pWorkWin;
    USHORT                  nUpdateMode;
    USHORT                  nChilds;
    BOOL                    bSorted;
    USHORT                  nOrigMode;
    Rectangle               aClientArea;
    BOOL                    bDockingAllowed;
    BOOL                    bAllChildsVisible;
    SfxShell*               pConfigShell;
    Window*                 pActiveChild;

protected:
    void                    CreateChildWin_Impl(SfxChildWin_Impl*);
    void                    RemoveChildWin_Impl(SfxChildWin_Impl*);
    void                    Sort_Impl();
    void                    AlignChild_Impl( Window& rWindow, const Size& rNewSize,
                                     SfxChildAlignment eAlign );
    SfxChild_Impl*          FindChild_Impl( const Window& rWindow ) const;
    virtual BOOL            RequestTopToolSpacePixel_Impl( SvBorder aBorder );
    virtual Rectangle       GetTopRect_Impl();
    SvBorder                Arrange_Impl( Rectangle & rRect);
    virtual void            SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&);

public:
                            SfxWorkWindow( Window *pWin, SfxBindings& rBindings, SfxWorkWindow* pParent = NULL);
                            ~SfxWorkWindow();
    SystemWindow*           GetTopWindow() const;
    SfxBindings&            GetBindings()
                            { return *pBindings; }
    Window*                 GetWindow() const
                            { return pWorkWin; }
    Rectangle               GetFreeArea( BOOL bAutoHide ) const;
    void                    SetDockingAllowed(BOOL bSet)
                            { bDockingAllowed = bSet; }
    BOOL                    IsDockingAllowed() const
                            { return bDockingAllowed; }
    SfxWorkWindow*          GetParent_Impl() const
                            { return pParent; }
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >          CreateDispatch( const String& );

    // Methoden f"ur alle Child-Fenster
    void                    ReleaseChild_Impl( Window& rWindow );
    SfxChild_Impl*          RegisterChild_Impl( Window& rWindow, SfxChildAlignment eAlign, BOOL bCanGetFocus=FALSE );
    void                    ShowChilds_Impl();
    void                    HideChilds_Impl();
    void                    Close_Impl();
    BOOL                    PrepareClose_Impl();
    virtual void            ArrangeChilds_Impl();
    void                    DeleteControllers_Impl();
    void                    SaveStatus_Impl();
    void                    HidePopups_Impl(BOOL bHide, BOOL bParent=FALSE, USHORT nId=0);
    void                    ConfigChild_Impl(SfxChildIdentifier,
                                             SfxDockingConfig, USHORT);
    void                    MakeChildsVisible_Impl( BOOL bVis );
    void                    ArrangeAutoHideWindows( SfxSplitWindow *pSplit );
    BOOL                    IsAutoHideMode( const SfxSplitWindow *pSplit );
    void                    EndAutoShow_Impl( Point aPos );

    // Methoden f"ur Objectbars
    virtual void            UpdateObjectBars_Impl();
    void                    ResetObjectBars_Impl();
    void                    SetObjectBar_Impl( USHORT nPos, const ResId& rId,
                                    SfxInterface *pIFace, const String* pName=0 );
    Window*                 GetObjectBar_Impl( USHORT nPos, ResId& rResId );
    FASTBOOL                KnowsObjectBar_Impl( USHORT nPos ) const;
    void                    SetObjectBarVisibility_Impl( USHORT nVis );
    BOOL                    IsContainer_Impl() const;
    void                    NextObjectBar_Impl( USHORT nPos );
    USHORT                  HasNextObjectBar_Impl( USHORT nPos, String* pStr=0 );

    // Methoden f"ur ChildWindows
    void                    UpdateChildWindows_Impl();
    void                    ResetChildWindows_Impl();
    void                    SetChildWindowVisible_Impl( ULONG, BOOL, USHORT );
    void                    ToggleChildWindow_Impl(USHORT);
    BOOL                    HasChildWindow_Impl(USHORT);
    BOOL                    KnowsChildWindow_Impl(USHORT);
    void                    ShowChildWindow_Impl(USHORT, BOOL bVisible=TRUE);
    void                    SetChildWindow_Impl(USHORT, BOOL bOn);
    SfxChildWindow*         GetChildWindow_Impl(USHORT);
    virtual void            InitializeChild_Impl(SfxChildWin_Impl*);
    SfxSplitWindow*         GetSplitWindow_Impl(SfxChildAlignment);

    BOOL                    IsVisible_Impl( USHORT nMode ) const;
    void                    DisableChildWindow_Impl( USHORT nId, BOOL bDisable );
    BOOL                    IsFloating( USHORT nId );
    void                    ChangeWindow_Impl( Window *pNew );
    void                    SetActiveChild_Impl( Window *pChild );
    Window*                 GetActiveChild_Impl();
    virtual BOOL            ActivateNextChild_Impl( BOOL bForward = TRUE );

    // Methoden f"ur StatusBar
    void                    SetTempStatusBar_Impl( BOOL bSet );
    void                    ResetStatusBar_Impl();
    void                    SetStatusBar_Impl(const ResId&, SfxShell *pShell, SfxBindings& );
    void                    UpdateStatusBar_Impl();
    SfxStatusBarManager*    GetStatusBarManager_Impl();
};

class SfxPIWorkWin_Impl : public SfxWorkWindow
{
    SfxPlugInEnv_Impl*  pEnv;
    Window*             pDialogParent;

public:
                        SfxPIWorkWin_Impl(
                            Window *pWin, SfxBindings &rBindings,
                            SfxPlugInEnv_Impl*  pE);
    virtual             Window* GetModalDialogParent() const;

private:
    virtual void        ArrangeChilds_Impl();
    virtual void        UpdateObjectBars_Impl();
    virtual void        SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&);
    virtual void        InitializeChild_Impl(SfxChildWin_Impl*);
    virtual Rectangle   GetTopRect_Impl();
};

class SfxIPWorkWin_Impl : public SfxWorkWindow
{
    SfxInPlaceEnv_Impl* pEnv;

public:
                        SfxIPWorkWin_Impl( WorkWindow *pWin, SfxBindings &rBindings,
                                SfxInPlaceEnv_Impl* pE);
private:
    virtual BOOL        RequestTopToolSpacePixel_Impl( SvBorder aBorder );
    virtual void        UpdateObjectBars_Impl();
    virtual Rectangle   GetTopRect_Impl();
    virtual void        ArrangeChilds_Impl();
    virtual void        SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&);
};

class SfxFrameWorkWin_Impl : public SfxWorkWindow
{
    SfxFrame*           pFrame;
public:
                        SfxFrameWorkWin_Impl( Window* pWin, SfxFrame* pTask );
    virtual void        ArrangeChilds_Impl();
    virtual void        UpdateObjectBars_Impl();
    virtual Rectangle   GetTopRect_Impl();
};

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

#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

#define _SVSTDARR_USHORTS
#include <svtools/svstdarr.hxx>     // SvUShorts

#ifndef _IFACE_HXX //autogen
#include <so3/iface.hxx>
#endif

#include "sfx.hrc"
#include "childwin.hxx"
#include "shell.hxx"
#include "minarray.hxx"
#include "ctrlitem.hxx"
#include "stbmgr.hxx"

class SfxToolBoxManager;
class SfxInPlaceEnv_Impl;
class SfxPlugInEnv_Impl;
class SfxSplitWindow;
class SfxWorkWindow;
class XDispatch;

//====================================================================
// Dieser struct h"alt alle relevanten Informationen "uber Toolboxen bereit.

struct SfxObjectBar_Impl
{
    USHORT              nId;    // Resource - und ConfigId der Toolbox
    USHORT              nMode;  // spezielle Sichtbarkeitsflags
    SfxToolBoxManager*  pTbx;
    String              aName;
    ResMgr*             pResMgr;
    SfxInterface*       pIFace;

    SfxObjectBar_Impl() :
        nId(0),
        nMode(0),
        pTbx(0),
        pResMgr(0),
        pIFace(0)
    {}
};

//------------------------------------------------------------------------------
// Dieser struct h"alt alle relevanten Informationen "uber die Statuszeile bereit.
struct SfxStatBar_Impl
{
    ResMgr*                 pResMgr;
    SfxShell*               pShell;
    SfxBindings*            pBindings;
    USHORT                  nId;
    SfxStatusBarManager*    pStatusBar;
    BOOL                    bOn;
    BOOL                    bTemp;

    SfxStatBar_Impl() :
        nId(0),
        pResMgr(0),
        pShell(0),
        pBindings(0),
        pStatusBar(0),
        bOn(TRUE),
        bTemp(FALSE)
    {}
};

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

#define CHILD_NOT_VISIBLE   0
#define CHILD_ACTIVE        1   // nicht durch HidePopups ausgeschaltet
#define CHILD_NOT_HIDDEN    2   // nicht durch HideChildWindow ausgeschaltet
#define CHILD_FITS_IN       4   // nicht zu gro\s f"ur OutputSize des parent
#define CHILD_VISIBLE       (CHILD_NOT_HIDDEN | CHILD_ACTIVE | CHILD_FITS_IN)
#define CHILD_ISVISIBLE     (CHILD_NOT_HIDDEN | CHILD_ACTIVE)

struct SfxChild_Impl
{
    Window*                         pWin;
    Size                            aSize;
    SfxChildAlignment               eAlign;
    USHORT                          nVisible;
    BOOL                            bResize;
    BOOL                            bCanGetFocus;

    SfxChild_Impl( Window& rChild, const Size& rSize,
                   SfxChildAlignment eAlignment, BOOL bIsVisible ):
        pWin(&rChild), aSize(rSize), eAlign(eAlignment), bResize(FALSE),
        bCanGetFocus( FALSE )
    {
        nVisible = bIsVisible ? CHILD_VISIBLE : CHILD_NOT_VISIBLE;
    }
};

//--------------------------------------------------------------------
class SfxChildWinController_Impl : public SfxControllerItem
{
    SfxWorkWindow*  pWorkwin;

    public:
                    SfxChildWinController_Impl( USHORT nId, SfxWorkWindow *pWin );
    virtual void    StateChanged( USHORT nSID, SfxItemState eState,
                            const SfxPoolItem* pState );
};

struct SfxChildWin_Impl
{
    USHORT                          nSaveId;        // die ChildWindow-Id
    USHORT                          nInterfaceId;   // der aktuelle Context
    USHORT                          nId;            // aktuelle Id
    SfxChildWindow*                 pWin;
    BOOL                            bCreate;
    SfxChildWinInfo                 aInfo;
    SfxChild_Impl*                  pCli;           // != 0 bei direkten Children
    USHORT                          nVisibility;
    BOOL                            bEnable;
    SfxChildWinController_Impl*     pControl;
    BOOL                            bDisabled;

    SfxChildWin_Impl( ULONG nID ) :
        nSaveId((USHORT) (nID & 0xFFFF) ),
        nInterfaceId((USHORT) (nID >> 16)),
        nId(nSaveId),
        pWin(0),
        bCreate(FALSE),
        pCli(0),
        nVisibility( FALSE ),
        bEnable( TRUE ),
        bDisabled( FALSE ),
        pControl( 0 )
    {}
};

enum SfxChildIdentifier
{
    SFX_CHILDWIN_STATBAR,
    SFX_CHILDWIN_OBJECTBAR,
    SFX_CHILDWIN_DOCKINGWINDOW,
    SFX_CHILDWIN_SPLITWINDOW
};

enum SfxDockingConfig
{
    SFX_SETDOCKINGRECTS,
    SFX_ALIGNDOCKINGWINDOW,
    SFX_TOGGLEFLOATMODE,
    SFX_MOVEDOCKINGWINDOW
};

DECL_PTRARRAY( SfxChildList_Impl, SfxChild_Impl*, 2, 2 );
DECL_PTRARRAY( SfxChildWindows_Impl, SfxChildWin_Impl*, 2, 2 );

SV_DECL_OBJARR( SfxObjectBarArr_Impl, SfxObjectBar_Impl, 1, 2 );

struct SfxObjectBarList_Impl
{
    SfxObjectBarArr_Impl    aArr;
    USHORT                  nAct;

    SfxObjectBar_Impl       operator[] ( USHORT n )
                            { return aArr[n]; }
    SfxObjectBar_Impl       Actual()
                            { return aArr[nAct]; }
};

struct SfxSplitWin_Impl
{
    SfxSplitWindow*         pSplitWin;
    SfxChildWindows_Impl*   pChildWins;
};

#define SFX_SPLITWINDOWS_LEFT   0
#define SFX_SPLITWINDOWS_TOP    2
#define SFX_SPLITWINDOWS_RIGHT  1
#define SFX_SPLITWINDOWS_BOTTOM 3
#define SFX_SPLITWINDOWS_MAX    4

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

class SfxWorkWindow
{
protected:
    SfxStatBar_Impl         aStatBar;
    SfxWorkWindow*          pParent;
    SvUShorts               aSortedList;
    SfxObjectBar_Impl       aObjBars[SFX_OBJECTBAR_MAX];
    SfxObjectBarList_Impl   aObjBarLists[SFX_OBJECTBAR_MAX];
    SfxSplitWindow*         pSplit[SFX_SPLITWINDOWS_MAX];
    SfxChildList_Impl*      pChilds;
    SfxChildWindows_Impl*   pChildWins;
    SfxBindings*            pBindings;
    Window*                 pWorkWin;
    USHORT                  nUpdateMode;
    USHORT                  nChilds;
    BOOL                    bSorted;
    USHORT                  nOrigMode;
    Rectangle               aClientArea;
    BOOL                    bDockingAllowed;
    BOOL                    bAllChildsVisible;
    SfxShell*               pConfigShell;
    Window*                 pActiveChild;

protected:
    void                    CreateChildWin_Impl(SfxChildWin_Impl*);
    void                    RemoveChildWin_Impl(SfxChildWin_Impl*);
    void                    Sort_Impl();
    void                    AlignChild_Impl( Window& rWindow, const Size& rNewSize,
                                     SfxChildAlignment eAlign );
    SfxChild_Impl*          FindChild_Impl( const Window& rWindow ) const;
    virtual BOOL            RequestTopToolSpacePixel_Impl( SvBorder aBorder );
    virtual Rectangle       GetTopRect_Impl();
    SvBorder                Arrange_Impl( Rectangle & rRect);
    virtual void            SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&);

public:
                            SfxWorkWindow( Window *pWin, SfxBindings& rBindings, SfxWorkWindow* pParent = NULL);
                            ~SfxWorkWindow();
    SystemWindow*           GetTopWindow() const;
    SfxBindings&            GetBindings()
                            { return *pBindings; }
    Window*                 GetWindow() const
                            { return pWorkWin; }
    Rectangle               GetFreeArea( BOOL bAutoHide ) const;
    void                    SetDockingAllowed(BOOL bSet)
                            { bDockingAllowed = bSet; }
    BOOL                    IsDockingAllowed() const
                            { return bDockingAllowed; }
    SfxWorkWindow*          GetParent_Impl() const
                            { return pParent; }
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >          CreateDispatch( const String& );

    // Methoden f"ur alle Child-Fenster
    void                    ReleaseChild_Impl( Window& rWindow );
    SfxChild_Impl*          RegisterChild_Impl( Window& rWindow, SfxChildAlignment eAlign, BOOL bCanGetFocus=FALSE );
    void                    ShowChilds_Impl();
    void                    HideChilds_Impl();
    void                    Close_Impl();
    BOOL                    PrepareClose_Impl();
    virtual void            ArrangeChilds_Impl();
    void                    DeleteControllers_Impl();
    void                    SaveStatus_Impl();
    void                    HidePopups_Impl(BOOL bHide, BOOL bParent=FALSE, USHORT nId=0);
    void                    ConfigChild_Impl(SfxChildIdentifier,
                                             SfxDockingConfig, USHORT);
    void                    MakeChildsVisible_Impl( BOOL bVis );
    void                    ArrangeAutoHideWindows( SfxSplitWindow *pSplit );
    BOOL                    IsAutoHideMode( const SfxSplitWindow *pSplit );
    void                    EndAutoShow_Impl( Point aPos );

    // Methoden f"ur Objectbars
    virtual void            UpdateObjectBars_Impl();
    void                    ResetObjectBars_Impl();
    void                    SetObjectBar_Impl( USHORT nPos, const ResId& rId,
                                    SfxInterface *pIFace, const String* pName=0 );
    Window*                 GetObjectBar_Impl( USHORT nPos, ResId& rResId );
    FASTBOOL                KnowsObjectBar_Impl( USHORT nPos ) const;
    void                    SetObjectBarVisibility_Impl( USHORT nVis );
    BOOL                    IsContainer_Impl() const;
    void                    NextObjectBar_Impl( USHORT nPos );
    USHORT                  HasNextObjectBar_Impl( USHORT nPos, String* pStr=0 );

    // Methoden f"ur ChildWindows
    void                    UpdateChildWindows_Impl();
    void                    ResetChildWindows_Impl();
    void                    SetChildWindowVisible_Impl( ULONG, BOOL, USHORT );
    void                    ToggleChildWindow_Impl(USHORT);
    BOOL                    HasChildWindow_Impl(USHORT);
    BOOL                    KnowsChildWindow_Impl(USHORT);
    void                    ShowChildWindow_Impl(USHORT, BOOL bVisible=TRUE);
    void                    SetChildWindow_Impl(USHORT, BOOL bOn);
    SfxChildWindow*         GetChildWindow_Impl(USHORT);
    virtual void            InitializeChild_Impl(SfxChildWin_Impl*);
    SfxSplitWindow*         GetSplitWindow_Impl(SfxChildAlignment);

    BOOL                    IsVisible_Impl( USHORT nMode ) const;
    void                    DisableChildWindow_Impl( USHORT nId, BOOL bDisable );
    BOOL                    IsFloating( USHORT nId );
    void                    ChangeWindow_Impl( Window *pNew );
    void                    SetActiveChild_Impl( Window *pChild );
    Window*                 GetActiveChild_Impl();
    virtual BOOL            ActivateNextChild_Impl( BOOL bForward = TRUE );

    // Methoden f"ur StatusBar
    void                    SetTempStatusBar_Impl( BOOL bSet );
    void                    ResetStatusBar_Impl();
    void                    SetStatusBar_Impl(const ResId&, SfxShell *pShell, SfxBindings& );
    void                    UpdateStatusBar_Impl();
    SfxStatusBarManager*    GetStatusBarManager_Impl();
    SfxStatusBarManager*    MakeStatusBarManager_Impl( BOOL bCreate );
};

class SfxPIWorkWin_Impl : public SfxWorkWindow
{
    SfxPlugInEnv_Impl*  pEnv;
    Window*             pDialogParent;

public:
                        SfxPIWorkWin_Impl(
                            Window *pWin, SfxBindings &rBindings,
                            SfxPlugInEnv_Impl*  pE);
    virtual             Window* GetModalDialogParent() const;

private:
    virtual void        ArrangeChilds_Impl();
    virtual void        UpdateObjectBars_Impl();
    virtual void        SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&);
    virtual void        InitializeChild_Impl(SfxChildWin_Impl*);
    virtual Rectangle   GetTopRect_Impl();
};

class SfxIPWorkWin_Impl : public SfxWorkWindow
{
    SfxInPlaceEnv_Impl* pEnv;

public:
                        SfxIPWorkWin_Impl( WorkWindow *pWin, SfxBindings &rBindings,
                                SfxInPlaceEnv_Impl* pE);
private:
    virtual BOOL        RequestTopToolSpacePixel_Impl( SvBorder aBorder );
    virtual void        UpdateObjectBars_Impl();
    virtual Rectangle   GetTopRect_Impl();
    virtual void        ArrangeChilds_Impl();
    virtual void        SaveStatus_Impl(SfxChildWindow*, const SfxChildWinInfo&);
};

class SfxFrameWorkWin_Impl : public SfxWorkWindow
{
    SfxFrame*           pFrame;
public:
                        SfxFrameWorkWin_Impl( Window* pWin, SfxFrame* pTask );
    virtual void        ArrangeChilds_Impl();
    virtual void        UpdateObjectBars_Impl();
    virtual Rectangle   GetTopRect_Impl();
};

#endif
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */

#ifndef PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_
#define PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_

#include <pcl/features/intensity_gradient.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void
pcl::IntensityGradientEstimation <PointInT, PointNT, PointOutT, IntensitySelectorT>::computePointIntensityGradient (
  const pcl::PointCloud <PointInT> &cloud, const std::vector <int> &indices,
  const Eigen::Vector3f &point, float mean_intensity, const Eigen::Vector3f &normal, Eigen::Vector3f &gradient)
{
  if (indices.size () < 3)
  {
    gradient[0] = gradient[1] = gradient[2] = std::numeric_limits<float>::quiet_NaN ();
    return;
  }

  Eigen::Matrix3f A = Eigen::Matrix3f::Zero ();
  Eigen::Vector3f b = Eigen::Vector3f::Zero ();

  for (size_t i_point = 0; i_point < indices.size (); ++i_point)
  {
    PointInT p = cloud.points[indices[i_point]];
    if (!pcl_isfinite (p.x) ||
        !pcl_isfinite (p.y) ||
        !pcl_isfinite (p.z) ||
        !pcl_isfinite (intensity_ (p)))
      continue;

    p.x -= point[0];
    p.y -= point[1];
    p.z -= point[2];
    intensity_.demean (p, mean_intensity);

    A (0, 0) += p.x * p.x;
    A (0, 1) += p.x * p.y;
    A (0, 2) += p.x * p.z;

    A (1, 1) += p.y * p.y;
    A (1, 2) += p.y * p.z;

    A (2, 2) += p.z * p.z;

    b[0] += p.x * intensity_ (p);
    b[1] += p.y * intensity_ (p);
    b[2] += p.z * intensity_ (p);
  }
  // Fill in the lower triangle of A
  A (1, 0) = A (0, 1);
  A (2, 0) = A (0, 2);
  A (2, 1) = A (1, 2);

//*
  Eigen::Vector3f x = A.colPivHouseholderQr ().solve (b);
/*/

  Eigen::Vector3f eigen_values;
  Eigen::Matrix3f eigen_vectors;
  eigen33 (A, eigen_vectors, eigen_values);

  b = eigen_vectors.transpose () * b;

  if ( eigen_values (0) != 0)
    b (0) /= eigen_values (0);
  else
    b (0) = 0;

  if ( eigen_values (1) != 0)
    b (1) /= eigen_values (1);
  else
    b (1) = 0;

  if ( eigen_values (2) != 0)
    b (2) /= eigen_values (2);
  else
    b (2) = 0;

  Eigen::Vector3f x = eigen_vectors * b;

//  if (A.col (0).squaredNorm () != 0)
//    x [0] /= A.col (0).squaredNorm ();
//  b -= x [0] * A.col (0);
//
//
//  if (A.col (1).squaredNorm ()  != 0)
//    x [1] /= A.col (1).squaredNorm ();
//  b -= x[1] * A.col (1);
//
//  x [2] = b.dot (A.col (2));
//  if (A.col (2).squaredNorm () != 0)
//    x[2] /= A.col (2).squaredNorm ();
  // Fit a hyperplane to the data

//*/
//  std::cout << A << "\n*\n" << bb << "\n=\n" << x << "\nvs.\n" << x2 << "\n\n";
//  std::cout << A * x << "\nvs.\n" << A * x2 << "\n\n------\n";
  // Project the gradient vector, x, onto the tangent plane
  gradient = (Eigen::Matrix3f::Identity () - normal*normal.transpose ()) * x;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void
pcl::IntensityGradientEstimation<PointInT, PointNT, PointOutT, IntensitySelectorT>::computeFeature (PointCloudOut &output)
{
  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  output.is_dense = true;
  // Iterating over the entire index vector
#ifdef HAVE_OPENMP
#pragma omp parallel for shared (output) private (nn_indices, nn_dists) num_threads(threads_)
#endif
  for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx)
  {
    PointOutT &p_out = output.points[idx];

    if (!this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists))
    {
      p_out.gradient[0] = p_out.gradient[1] = p_out.gradient[2] = std::numeric_limits<float>::quiet_NaN ();
      output.is_dense = false;
      continue;
    }

    Eigen::Vector3f centroid;
    float mean_intensity = 0;
    // Initialize to 0
    centroid.setZero ();
    // If the data is dense, we don't need to check for NaN
    if (surface_->is_dense)
    {
      for (size_t i = 0; i < nn_indices.size (); ++i)
      {
        centroid += surface_->points[nn_indices[i]].getVector3fMap ();
        mean_intensity += intensity_ (surface_->points[nn_indices[i]]);
      }
      centroid /= static_cast<float> (nn_indices.size ());
      mean_intensity /= static_cast<float> (nn_indices.size ());
    }
    // NaN or Inf values could exist => check for them
    else
    {
      unsigned cp = 0;
      for (size_t i = 0; i < nn_indices.size (); ++i)
      {
        // Check if the point is invalid
        if (!isFinite ((*surface_) [nn_indices[i]]))
          continue;

        centroid += surface_->points [nn_indices[i]].getVector3fMap ();
        mean_intensity += intensity_ (surface_->points [nn_indices[i]]);
        ++cp;
      }
      centroid /= static_cast<float> (cp);
      mean_intensity /= static_cast<float> (cp);
    }

    Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[(*indices_) [idx]].normal);
    Eigen::Vector3f gradient;
    computePointIntensityGradient (*surface_, nn_indices, centroid, mean_intensity, normal, gradient);

    p_out.gradient[0] = gradient[0];
    p_out.gradient[1] = gradient[1];
    p_out.gradient[2] = gradient[2];
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT> void
pcl::IntensityGradientEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
  // Resize the output dataset
  output.points.resize (indices_->size (), 3);

  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  output.is_dense = true;
  // Iterating over the entire index vector
  for (size_t idx = 0; idx < indices_->size (); ++idx)
  {
    if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)
    {
      output.points.row (idx).setConstant (std::numeric_limits<float>::quiet_NaN ());
      output.is_dense = false;
      continue;
    }

    Eigen::Vector4f centroid;
    compute3DCentroid (*surface_, nn_indices, centroid);

    float mean_intensity = 0;
    unsigned valid_neighbor_count = 0;
    for (size_t nIdx = 0; nIdx < nn_indices.size (); ++nIdx)
    {
      const PointInT& p = (*surface_)[nn_indices[nIdx]];
      if (!pcl_isfinite (p.intensity))
        continue;

      mean_intensity += p.intensity;
      ++valid_neighbor_count;
    }

    mean_intensity /= static_cast<float> (valid_neighbor_count);

    Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[idx].normal);
    Eigen::Vector3f gradient;
    this->computePointIntensityGradient (*surface_, nn_indices, centroid.head<3> (), mean_intensity, normal, gradient);

    output.points (idx, 0) = gradient[0];
    output.points (idx, 1) = gradient[1];
    output.points (idx, 2) = gradient[2];
  }
}

#define PCL_INSTANTIATE_IntensityGradientEstimation(InT,NT,OutT) template class PCL_EXPORTS pcl::IntensityGradientEstimation<InT,NT,OutT>;

#endif    // PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_
<commit_msg>Fix trial for MacOS<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id$
 *
 */

#ifndef PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_
#define PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_

#include <pcl/features/intensity_gradient.h>

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void
pcl::IntensityGradientEstimation <PointInT, PointNT, PointOutT, IntensitySelectorT>::computePointIntensityGradient (
  const pcl::PointCloud <PointInT> &cloud, const std::vector <int> &indices,
  const Eigen::Vector3f &point, float mean_intensity, const Eigen::Vector3f &normal, Eigen::Vector3f &gradient)
{
  if (indices.size () < 3)
  {
    gradient[0] = gradient[1] = gradient[2] = std::numeric_limits<float>::quiet_NaN ();
    return;
  }

  Eigen::Matrix3f A = Eigen::Matrix3f::Zero ();
  Eigen::Vector3f b = Eigen::Vector3f::Zero ();

  for (size_t i_point = 0; i_point < indices.size (); ++i_point)
  {
    PointInT p = cloud.points[indices[i_point]];
    if (!pcl_isfinite (p.x) ||
        !pcl_isfinite (p.y) ||
        !pcl_isfinite (p.z) ||
        !pcl_isfinite (intensity_ (p)))
      continue;

    p.x -= point[0];
    p.y -= point[1];
    p.z -= point[2];
    intensity_.demean (p, mean_intensity);

    A (0, 0) += p.x * p.x;
    A (0, 1) += p.x * p.y;
    A (0, 2) += p.x * p.z;

    A (1, 1) += p.y * p.y;
    A (1, 2) += p.y * p.z;

    A (2, 2) += p.z * p.z;

    b[0] += p.x * intensity_ (p);
    b[1] += p.y * intensity_ (p);
    b[2] += p.z * intensity_ (p);
  }
  // Fill in the lower triangle of A
  A (1, 0) = A (0, 1);
  A (2, 0) = A (0, 2);
  A (2, 1) = A (1, 2);

//*
  Eigen::Vector3f x = A.colPivHouseholderQr ().solve (b);
/*/

  Eigen::Vector3f eigen_values;
  Eigen::Matrix3f eigen_vectors;
  eigen33 (A, eigen_vectors, eigen_values);

  b = eigen_vectors.transpose () * b;

  if ( eigen_values (0) != 0)
    b (0) /= eigen_values (0);
  else
    b (0) = 0;

  if ( eigen_values (1) != 0)
    b (1) /= eigen_values (1);
  else
    b (1) = 0;

  if ( eigen_values (2) != 0)
    b (2) /= eigen_values (2);
  else
    b (2) = 0;

  Eigen::Vector3f x = eigen_vectors * b;

//  if (A.col (0).squaredNorm () != 0)
//    x [0] /= A.col (0).squaredNorm ();
//  b -= x [0] * A.col (0);
//
//
//  if (A.col (1).squaredNorm ()  != 0)
//    x [1] /= A.col (1).squaredNorm ();
//  b -= x[1] * A.col (1);
//
//  x [2] = b.dot (A.col (2));
//  if (A.col (2).squaredNorm () != 0)
//    x[2] /= A.col (2).squaredNorm ();
  // Fit a hyperplane to the data

//*/
//  std::cout << A << "\n*\n" << bb << "\n=\n" << x << "\nvs.\n" << x2 << "\n\n";
//  std::cout << A * x << "\nvs.\n" << A * x2 << "\n\n------\n";
  // Project the gradient vector, x, onto the tangent plane
  gradient = (Eigen::Matrix3f::Identity () - normal*normal.transpose ()) * x;
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT, typename PointOutT, typename IntensitySelectorT> void
pcl::IntensityGradientEstimation<PointInT, PointNT, PointOutT, IntensitySelectorT>::computeFeature (PointCloudOut &output)
{
  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  output.is_dense = true;
  // Iterating over the entire index vector
#ifdef HAVE_OPENMP
//#pragma omp parallel for shared (output) private (nn_indices, nn_dists) num_threads(threads_)
#pragma omp parallel for private (nn_indices, nn_dists) num_threads(threads_)
#endif
  for (int idx = 0; idx < static_cast<int> (indices_->size ()); ++idx)
  {
    PointOutT &p_out = output.points[idx];

    if (!this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists))
    {
      p_out.gradient[0] = p_out.gradient[1] = p_out.gradient[2] = std::numeric_limits<float>::quiet_NaN ();
      output.is_dense = false;
      continue;
    }

    Eigen::Vector3f centroid;
    float mean_intensity = 0;
    // Initialize to 0
    centroid.setZero ();
    // If the data is dense, we don't need to check for NaN
    if (surface_->is_dense)
    {
      for (size_t i = 0; i < nn_indices.size (); ++i)
      {
        centroid += surface_->points[nn_indices[i]].getVector3fMap ();
        mean_intensity += intensity_ (surface_->points[nn_indices[i]]);
      }
      centroid /= static_cast<float> (nn_indices.size ());
      mean_intensity /= static_cast<float> (nn_indices.size ());
    }
    // NaN or Inf values could exist => check for them
    else
    {
      unsigned cp = 0;
      for (size_t i = 0; i < nn_indices.size (); ++i)
      {
        // Check if the point is invalid
        if (!isFinite ((*surface_) [nn_indices[i]]))
          continue;

        centroid += surface_->points [nn_indices[i]].getVector3fMap ();
        mean_intensity += intensity_ (surface_->points [nn_indices[i]]);
        ++cp;
      }
      centroid /= static_cast<float> (cp);
      mean_intensity /= static_cast<float> (cp);
    }

    Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[(*indices_) [idx]].normal);
    Eigen::Vector3f gradient;
    computePointIntensityGradient (*surface_, nn_indices, centroid, mean_intensity, normal, gradient);

    p_out.gradient[0] = gradient[0];
    p_out.gradient[1] = gradient[1];
    p_out.gradient[2] = gradient[2];
  }
}

//////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT, typename PointNT> void
pcl::IntensityGradientEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output)
{
  // Resize the output dataset
  output.points.resize (indices_->size (), 3);

  // Allocate enough space to hold the results
  // \note This resize is irrelevant for a radiusSearch ().
  std::vector<int> nn_indices (k_);
  std::vector<float> nn_dists (k_);

  output.is_dense = true;
  // Iterating over the entire index vector
  for (size_t idx = 0; idx < indices_->size (); ++idx)
  {
    if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0)
    {
      output.points.row (idx).setConstant (std::numeric_limits<float>::quiet_NaN ());
      output.is_dense = false;
      continue;
    }

    Eigen::Vector4f centroid;
    compute3DCentroid (*surface_, nn_indices, centroid);

    float mean_intensity = 0;
    unsigned valid_neighbor_count = 0;
    for (size_t nIdx = 0; nIdx < nn_indices.size (); ++nIdx)
    {
      const PointInT& p = (*surface_)[nn_indices[nIdx]];
      if (!pcl_isfinite (p.intensity))
        continue;

      mean_intensity += p.intensity;
      ++valid_neighbor_count;
    }

    mean_intensity /= static_cast<float> (valid_neighbor_count);

    Eigen::Vector3f normal = Eigen::Vector3f::Map (normals_->points[idx].normal);
    Eigen::Vector3f gradient;
    this->computePointIntensityGradient (*surface_, nn_indices, centroid.head<3> (), mean_intensity, normal, gradient);

    output.points (idx, 0) = gradient[0];
    output.points (idx, 1) = gradient[1];
    output.points (idx, 2) = gradient[2];
  }
}

#define PCL_INSTANTIATE_IntensityGradientEstimation(InT,NT,OutT) template class PCL_EXPORTS pcl::IntensityGradientEstimation<InT,NT,OutT>;

#endif    // PCL_FEATURES_IMPL_INTENSITY_GRADIENT_H_
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

const ll infty = 10000000000000007;

struct edge {
  int to;
  ll cap;
  int rev;
};

vector<edge> G[100010];
bool used[100010];

void add_edge(int from, int to, ll cap) {
  G[from].push_back((edge){to, cap, (int)G[to].size()});
  G[to].push_back((edge){from, 0, (int)G[from].size()-1});
}

ll dfs(int v, int t, ll f) {
  if (v == t) return f;
  used[v] = true;
  for (auto& e : G[v]) {
    if (!used[e.to] && e.cap > 0) {
      ll d = dfs(e.to, t, min(f, e.cap));
      if (d > 0) {
        e.cap -= d;
        G[e.to][e.rev].cap += d;
        return d;
      }
    }
  }
  return 0;
}

ll max_flow(int s, int t) {
  ll flow = 0;
  while (true) {
    fill(used, used+100010, false);
    ll f = dfs(s, t, infty);
    if (f == 0) return flow;
    flow += f;
  }
}

typedef tuple<ll, int> state; // kachi, bit

int N;
ll x[20];
ll c[20];
ll v[20];
vector<state> V[20];

int main () {
  cin >> N;
  for (auto i = 0; i < N; ++i) {
    cin >> x[i];
  }
  for (auto i = 0; i < N-1; ++i) {
    x[i+1] += x[i];
  }
  for (auto i = 0; i < N; ++i) {
    cin >> c[i];
  }
  for (auto i = 0; i < N; ++i) {
    cin >> v[i];
  }
  for (auto i = 0; i < (1 << N); ++i) {
    ll kakaku = 0;
    ll kachi = 0;
    for (auto j = 0; j < N; ++j) {
      if ((i >> j) & 1) {
        kakaku += c[j];
        kachi += v[j];
      }
    }
    for (auto j = 0; j < N; ++j) {
      if (kakaku <= x[j]) {
        V[j].push_back(make_tuple(kachi, i));
        break;
      }
    }
  }
  ll ans = 0;
  for (auto i = 0; i < N; ++i) {
#if DEBUG == 1
    cerr << "ban item i = " << i << endl;
#endif
    sort(V[i].begin(), V[i].end());
    reverse(V[i].begin(), V[i].end());
    for (auto now = 1; now <= (int)V[i].size(); ++now) {
      // 0 start, 1 goal, 2...N+2 choten, N+2+i i
      for (auto j = 0; j <= N+2+now; ++j) {
        G[j].clear();
      }
      for (auto j = 0; j < N; ++j) {
        add_edge(0, j+2, 1);
      }
      for (auto j = 0; j < now; ++j) {
        int bit = get<1>(V[i][j]);
        for (auto k = 0; k < N; ++k) {
          if ((bit >> k) & 1) {
            add_edge(k+2, N+2+j, infty);
          }
        }
        add_edge(N+2+j, 1, 1);
      }
      ll f = max_flow(0, 1);
#if DEBUG == 1
      cerr << "now = " << now << ", f = " << f << endl;
#endif
      if (f <= i+1) {
        now++;
      } else {
        ans = max(ans, get<0>(V[i][now-1]));
        break;
      }
    }
  }
  cout << ans << endl;
}
<commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;

#define DEBUG 1 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

const ll infty = 10000000000000007;

struct edge {
  int to;
  ll cap;
  int rev;
};

vector<edge> G[100010];
bool used[100010];

void add_edge(int from, int to, ll cap) {
  G[from].push_back((edge){to, cap, (int)G[to].size()});
  G[to].push_back((edge){from, 0, (int)G[from].size()-1});
}

ll dfs(int v, int t, ll f) {
  if (v == t) return f;
  used[v] = true;
  for (auto& e : G[v]) {
    if (!used[e.to] && e.cap > 0) {
      ll d = dfs(e.to, t, min(f, e.cap));
      if (d > 0) {
        e.cap -= d;
        G[e.to][e.rev].cap += d;
        return d;
      }
    }
  }
  return 0;
}

ll max_flow(int s, int t) {
  ll flow = 0;
  while (true) {
    fill(used, used+100010, false);
    ll f = dfs(s, t, infty);
    if (f == 0) return flow;
    flow += f;
  }
}

typedef tuple<ll, int> state; // kachi, bit

int N;
ll x[20];
ll c[20];
ll v[20];
vector<state> V[20];

int main () {
  cin >> N;
  for (auto i = 0; i < N; ++i) {
    cin >> x[i];
  }
  for (auto i = 0; i < N-1; ++i) {
    x[i+1] += x[i];
  }
  for (auto i = 0; i < N; ++i) {
    cin >> c[i];
  }
  for (auto i = 0; i < N; ++i) {
    cin >> v[i];
  }
  for (auto i = 0; i < (1 << N); ++i) {
    ll kakaku = 0;
    ll kachi = 0;
    for (auto j = 0; j < N; ++j) {
      if ((i >> j) & 1) {
        kakaku += c[j];
        kachi += v[j];
      }
    }
    for (auto j = 0; j < N; ++j) {
      if (kakaku <= x[j]) {
        V[j].push_back(make_tuple(kachi, i));
        break;
      }
    }
  }
  ll ans = 0;
  for (auto i = 0; i < N; ++i) {
#if DEBUG == 1
    cerr << "ban item i = " << i << endl;
#endif
    sort(V[i].begin(), V[i].end());
    reverse(V[i].begin(), V[i].end());
    for (auto now = 1; now <= (int)V[i].size(); ++now) {
      // 0 start, 1 goal, 2...N+2 choten, N+2+i i
      for (auto j = 0; j <= N+2+now; ++j) {
        G[j].clear();
      }
      for (auto j = 0; j < N; ++j) {
        add_edge(0, j+2, 1);
      }
      for (auto j = 0; j < now; ++j) {
        int bit = get<1>(V[i][j]);
        for (auto k = 0; k < N; ++k) {
          if ((bit >> k) & 1) {
            add_edge(k+2, N+2+j, infty);
          }
        }
        add_edge(N+2+j, 1, 1);
      }
      ll f = max_flow(0, 1);
#if DEBUG == 1
      cerr << "now = " << now << ", f = " << f << endl;
#endif
      if (f <= i+1) {
        now++;
      } else {
        ans = max(ans, get<0>(V[i][now-1]));
        break;
      }
    }
  }
  cout << ans << endl;
}
<|endoftext|>