<commit_before>/**
 * @file
 * @author  Mohammad S. Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2016 Mohammad S. Babaei
 *
 * 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.
 *
 * @section DESCRIPTION
 *
 * CMS welcome screen a.k.a. dashboard.
 */

#include <boost/exception/diagnostic_information.hpp>
#include <boost/format.hpp>
#include <pqxx/pqxx>
#include <Wt/WApplication>
#include <Wt/WMessageBox>
#include <Wt/WPushButton>
#include <Wt/WString>
#include <Wt/WTemplate>
#include <Wt/WText>
#include <Wt/WWidget>
#include <CoreLib/CDate.hpp>
#include <CoreLib/Database.hpp>
#include <CoreLib/FileSystem.hpp>
#include <CoreLib/Log.hpp>
#include "CgiEnv.hpp"
#include "CgiRoot.hpp"
#include "CmsDashboard.hpp"
#include "Div.hpp"
#include "Pool.hpp"

using namespace std;
using namespace boost;
using namespace pqxx;
using namespace Wt;
using namespace CoreLib;
using namespace CoreLib::CDate;
using namespace Service;

struct CmsDashboard::Impl : public Wt::WObject
{
public:
    std::unique_ptr<Wt::WMessageBox> ForceTerminateAllSessionsMessageBox;
    std::unique_ptr<Wt::WMessageBox> SessionTerminationScheduledMessageBox;

public:
    Impl();
    ~Impl();

public:
    void OnForceTerminateAllSessionsPushButtonPressed();
    void OnForceTerminateAllSessionsDialogClosed(Wt::StandardButton button);
    void OnSessionTerminationScheduledDialogClosed(Wt::StandardButton button);
};

CmsDashboard::CmsDashboard()
    : Page(),
    m_pimpl(make_unique<CmsDashboard::Impl>())
{
    this->clear();
    this->setId("CmsDashboardPage");
    this->addWidget(this->Layout());
}

CmsDashboard::~CmsDashboard() = default;

WWidget *CmsDashboard::Layout()
{
    Div *container = new Div("CmsDashboard", "container-fluid");

    CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());
    CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();

    try {
        string htmlData;
        string file;
        if (cgiEnv->GetInformation().Client.Language.Code
                == CgiEnv::InformationRecord::ClientRecord::LanguageCode::Fa) {
            file = "../templates/cms-dashboard-fa.wtml";
        } else {
            file = "../templates/cms-dashboard.wtml";
        }

        if (CoreLib::FileSystem::Read(file, htmlData)) {
            /// Fill the template
            WTemplate *tmpl = new WTemplate(container);
            tmpl->setTemplateText(WString::fromUTF8(htmlData), TextFormat::XHTMLUnsafeText);

            WPushButton *forceTerminateAllSessionsPushButton = new WPushButton(tr("cms-dashboard-force-terminate-all-sessions"));
            forceTerminateAllSessionsPushButton->setStyleClass("btn btn-default");

            tmpl->bindWidget("welcome-message", new WText(tr("cms-dashboard-welcome-message")));

            tmpl->bindWidget("last-login-title", new WText(tr("cms-dashboard-last-login-info-title")));
            tmpl->bindWidget("last-login-ip-label", new WText(tr("cms-dashboard-last-login-info-ip")));
            tmpl->bindWidget("last-login-user-agent-label", new WText(tr("cms-dashboard-last-login-info-user-agent")));
            tmpl->bindWidget("last-login-referer-label", new WText(tr("cms-dashboard-last-login-info-referer")));
            tmpl->bindWidget("last-login-time-label", new WText(tr("cms-dashboard-last-login-info-time")));
            tmpl->bindWidget("last-login-location-label", new WText(tr("cms-dashboard-last-login-info-location")));
            tmpl->bindWidget("last-login-location-country-code-label", new WText(tr("cms-dashboard-last-login-info-location-country-code")));
            tmpl->bindWidget("last-login-location-country-code3-label", new WText(tr("cms-dashboard-last-login-info-location-country-code3")));
            tmpl->bindWidget("last-login-location-country-name-label", new WText(tr("cms-dashboard-last-login-info-location-country-name")));
            tmpl->bindWidget("last-login-location-region-label", new WText(tr("cms-dashboard-last-login-info-location-region")));
            tmpl->bindWidget("last-login-location-city-label", new WText(tr("cms-dashboard-last-login-info-location-city")));
            tmpl->bindWidget("last-login-location-postal-code-label", new WText(tr("cms-dashboard-last-login-info-location-postal-code")));
            tmpl->bindWidget("last-login-location-latitude-label", new WText(tr("cms-dashboard-last-login-info-location-latitude")));
            tmpl->bindWidget("last-login-location-longitude-label", new WText(tr("cms-dashboard-last-login-info-location-longitude")));
            tmpl->bindWidget("last-login-location-metro-code-label", new WText(tr("cms-dashboard-last-login-info-location-metro-code")));
            tmpl->bindWidget("last-login-location-dma-code-label", new WText(tr("cms-dashboard-last-login-info-location-dma-code")));
            tmpl->bindWidget("last-login-location-area-code-label", new WText(tr("cms-dashboard-last-login-info-location-area-code")));
            tmpl->bindWidget("last-login-location-charset-label", new WText(tr("cms-dashboard-last-login-info-location-charset")));
            tmpl->bindWidget("last-login-location-continent-code-label", new WText(tr("cms-dashboard-last-login-info-location-continent-code")));
            tmpl->bindWidget("last-login-location-netmask-label", new WText(tr("cms-dashboard-last-login-info-location-netmask")));

            tmpl->bindWidget("last-login-ip", new WText(WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.IPAddress)));
            tmpl->bindWidget("last-login-user-agent", new WText(WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.UserAgent)));
            tmpl->bindWidget("last-login-referer", new WText(WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.Referer)));
            tmpl->bindWidget("last-login-time",new WText(
                                 WString::fromUTF8(DateConv::DateTimeString(cgiEnv->GetInformation().Client.Session.LastLogin.Time,
                                                                            CDate::Timezone::UTC))));
            tmpl->bindWidget("last-login-location-country-code", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.CountryCode)));
            tmpl->bindWidget("last-login-location-country-code3", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.CountryCode3)));
            tmpl->bindWidget("last-login-location-country-name", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.CountryName)));
            tmpl->bindWidget("last-login-location-region", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Region)));
            tmpl->bindWidget("last-login-location-city", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.City)));
            tmpl->bindWidget("last-login-location-postal-code", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.PostalCode)));
            tmpl->bindWidget("last-login-location-latitude", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Latitude))));
            tmpl->bindWidget("last-login-location-longitude", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Longitude))));
            tmpl->bindWidget("last-login-location-metro-code", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.MetroCode))));
            tmpl->bindWidget("last-login-location-dma-code", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.DmaCode))));
            tmpl->bindWidget("last-login-location-area-code", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.AreaCode))));
            tmpl->bindWidget("last-login-location-charset", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Charset))));
            tmpl->bindWidget("last-login-location-continent-code", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.ContinentCode)));
            tmpl->bindWidget("last-login-location-netmask", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Netmask))));

            tmpl->bindWidget("force-terminate-all-sessions", forceTerminateAllSessionsPushButton);

            forceTerminateAllSessionsPushButton->clicked().connect(m_pimpl.get(), &CmsDashboard::Impl::OnForceTerminateAllSessionsPushButtonPressed);
       }
    }

    catch (const boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex), cgiEnv->GetInformation().ToJson());
    }

    catch (const std::exception &ex) {
        LOG_ERROR(ex.what(), cgiEnv->GetInformation().ToJson());
    }

    catch (...) {
        LOG_ERROR(UNKNOWN_ERROR, cgiEnv->GetInformation().ToJson());
    }

    return container;
}

CmsDashboard::Impl::Impl()
{

}

CmsDashboard::Impl::~Impl() = default;

void CmsDashboard::Impl::OnForceTerminateAllSessionsPushButtonPressed()
{
    ForceTerminateAllSessionsMessageBox =
            std::make_unique<WMessageBox>(tr("cms-dashboard-force-terminate-all-sessions-confirm-title"),
                                              tr("cms-dashboard-force-terminate-all-sessions-confirm-question"), Warning, NoButton);

    ForceTerminateAllSessionsMessageBox->addButton(tr("cms-dashboard-force-terminate-all-sessions-confirm-ok"), Ok);
    ForceTerminateAllSessionsMessageBox->addButton(tr("cms-dashboard-force-terminate-all-sessions-confirm-cancel"), Cancel);

    ForceTerminateAllSessionsMessageBox->buttonClicked().connect(this, &CmsDashboard::Impl::OnForceTerminateAllSessionsDialogClosed);

    ForceTerminateAllSessionsMessageBox->show();
}

void CmsDashboard::Impl::OnForceTerminateAllSessionsDialogClosed(Wt::StandardButton button)
{
    CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());
    CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();

    try {
        if (button == Ok) {

            auto conn = Pool::Database().Connection();
            conn->activate();
            pqxx::work txn(*conn.get());

            string query((boost::format("UPDATE ONLY \"%1%\""
                                        " SET expiry = '19700101'::TIMESTAMPTZ"
                                        " WHERE user_id = %2% AND expiry > '19700101'::TIMESTAMPTZ;")
                          % txn.esc(Service::Pool::Database().GetTableName("ROOT_SESSIONS"))
                          % txn.quote(cgiEnv->GetInformation().Client.Session.UserId)).str());
            LOG_INFO("Running query...", query, cgiEnv->GetInformation().ToJson());

            txn.exec(query);

            txn.commit();

            ForceTerminateAllSessionsMessageBox.reset();

            SessionTerminationScheduledMessageBox =
                    std::make_unique<WMessageBox>(tr("cms-dashboard-force-terminate-all-sessions-has-been-scheduled-title"),
                                                  tr("cms-dashboard-force-terminate-all-sessions-has-been-scheduled-message"),
                                                  Warning, NoButton);
            SessionTerminationScheduledMessageBox->addButton(tr("cms-dashboard-force-terminate-all-sessions-has-been-scheduled-ok"), Ok);

            SessionTerminationScheduledMessageBox->buttonClicked().connect(
                        this, &CmsDashboard::Impl::OnSessionTerminationScheduledDialogClosed);

            SessionTerminationScheduledMessageBox->show();

            return;
        }
    }

    catch (const pqxx::sql_error &ex) {
        LOG_ERROR(ex.what(), ex.query(), cgiEnv->GetInformation().ToJson());
    }

    catch (const boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex), cgiEnv->GetInformation().ToJson());
    }

    catch (const std::exception &ex) {
        LOG_ERROR(ex.what(), cgiEnv->GetInformation().ToJson());
    }

    catch (...) {
        LOG_ERROR(UNKNOWN_ERROR, cgiEnv->GetInformation().ToJson());
    }

    ForceTerminateAllSessionsMessageBox.reset();
}

void CmsDashboard::Impl::OnSessionTerminationScheduledDialogClosed(Wt::StandardButton button)
{
    (void)button;

    SessionTerminationScheduledMessageBox.reset();
}
<commit_msg>show jalali time on dashboard<commit_after>/**
 * @file
 * @author  Mohammad S. Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2016 Mohammad S. Babaei
 *
 * 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.
 *
 * @section DESCRIPTION
 *
 * CMS welcome screen a.k.a. dashboard.
 */

#include <boost/exception/diagnostic_information.hpp>
#include <boost/format.hpp>
#include <pqxx/pqxx>
#include <Wt/WApplication>
#include <Wt/WMessageBox>
#include <Wt/WPushButton>
#include <Wt/WString>
#include <Wt/WTemplate>
#include <Wt/WText>
#include <Wt/WWidget>
#include <CoreLib/CDate.hpp>
#include <CoreLib/Database.hpp>
#include <CoreLib/FileSystem.hpp>
#include <CoreLib/Log.hpp>
#include "CgiEnv.hpp"
#include "CgiRoot.hpp"
#include "CmsDashboard.hpp"
#include "Div.hpp"
#include "Pool.hpp"

using namespace std;
using namespace boost;
using namespace pqxx;
using namespace Wt;
using namespace CoreLib;
using namespace CoreLib::CDate;
using namespace Service;

struct CmsDashboard::Impl : public Wt::WObject
{
public:
    std::unique_ptr<Wt::WMessageBox> ForceTerminateAllSessionsMessageBox;
    std::unique_ptr<Wt::WMessageBox> SessionTerminationScheduledMessageBox;

public:
    Impl();
    ~Impl();

public:
    void OnForceTerminateAllSessionsPushButtonPressed();
    void OnForceTerminateAllSessionsDialogClosed(Wt::StandardButton button);
    void OnSessionTerminationScheduledDialogClosed(Wt::StandardButton button);
};

CmsDashboard::CmsDashboard()
    : Page(),
    m_pimpl(make_unique<CmsDashboard::Impl>())
{
    this->clear();
    this->setId("CmsDashboardPage");
    this->addWidget(this->Layout());
}

CmsDashboard::~CmsDashboard() = default;

WWidget *CmsDashboard::Layout()
{
    Div *container = new Div("CmsDashboard", "container-fluid");

    CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());
    CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();

    try {
        string htmlData;
        string file;
        if (cgiEnv->GetInformation().Client.Language.Code
                == CgiEnv::InformationRecord::ClientRecord::LanguageCode::Fa) {
            file = "../templates/cms-dashboard-fa.wtml";
        } else {
            file = "../templates/cms-dashboard.wtml";
        }

        if (CoreLib::FileSystem::Read(file, htmlData)) {
            /// Fill the template
            WTemplate *tmpl = new WTemplate(container);
            tmpl->setTemplateText(WString::fromUTF8(htmlData), TextFormat::XHTMLUnsafeText);

            WPushButton *forceTerminateAllSessionsPushButton = new WPushButton(tr("cms-dashboard-force-terminate-all-sessions"));
            forceTerminateAllSessionsPushButton->setStyleClass("btn btn-default");

            tmpl->bindWidget("welcome-message", new WText(tr("cms-dashboard-welcome-message")));

            tmpl->bindWidget("last-login-title", new WText(tr("cms-dashboard-last-login-info-title")));
            tmpl->bindWidget("last-login-ip-label", new WText(tr("cms-dashboard-last-login-info-ip")));
            tmpl->bindWidget("last-login-user-agent-label", new WText(tr("cms-dashboard-last-login-info-user-agent")));
            tmpl->bindWidget("last-login-referer-label", new WText(tr("cms-dashboard-last-login-info-referer")));
            tmpl->bindWidget("last-login-time-label", new WText(tr("cms-dashboard-last-login-info-time")));
            tmpl->bindWidget("last-login-location-label", new WText(tr("cms-dashboard-last-login-info-location")));
            tmpl->bindWidget("last-login-location-country-code-label", new WText(tr("cms-dashboard-last-login-info-location-country-code")));
            tmpl->bindWidget("last-login-location-country-code3-label", new WText(tr("cms-dashboard-last-login-info-location-country-code3")));
            tmpl->bindWidget("last-login-location-country-name-label", new WText(tr("cms-dashboard-last-login-info-location-country-name")));
            tmpl->bindWidget("last-login-location-region-label", new WText(tr("cms-dashboard-last-login-info-location-region")));
            tmpl->bindWidget("last-login-location-city-label", new WText(tr("cms-dashboard-last-login-info-location-city")));
            tmpl->bindWidget("last-login-location-postal-code-label", new WText(tr("cms-dashboard-last-login-info-location-postal-code")));
            tmpl->bindWidget("last-login-location-latitude-label", new WText(tr("cms-dashboard-last-login-info-location-latitude")));
            tmpl->bindWidget("last-login-location-longitude-label", new WText(tr("cms-dashboard-last-login-info-location-longitude")));
            tmpl->bindWidget("last-login-location-metro-code-label", new WText(tr("cms-dashboard-last-login-info-location-metro-code")));
            tmpl->bindWidget("last-login-location-dma-code-label", new WText(tr("cms-dashboard-last-login-info-location-dma-code")));
            tmpl->bindWidget("last-login-location-area-code-label", new WText(tr("cms-dashboard-last-login-info-location-area-code")));
            tmpl->bindWidget("last-login-location-charset-label", new WText(tr("cms-dashboard-last-login-info-location-charset")));
            tmpl->bindWidget("last-login-location-continent-code-label", new WText(tr("cms-dashboard-last-login-info-location-continent-code")));
            tmpl->bindWidget("last-login-location-netmask-label", new WText(tr("cms-dashboard-last-login-info-location-netmask")));

            tmpl->bindWidget("last-login-ip", new WText(WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.IPAddress)));
            tmpl->bindWidget("last-login-user-agent", new WText(WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.UserAgent)));
            tmpl->bindWidget("last-login-referer", new WText(WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.Referer)));
            tmpl->bindWidget("last-login-time", new WText(
                                 WString::fromUTF8((format("%1% ~ %2%")
                                  % WString(DateConv::FormatToPersianNums(DateConv::ToJalali(cgiEnv->GetInformation().Client.Session.LastLogin.Time, CDate::Timezone::UTC))).toUTF8()
                                  % algorithm::trim_copy(DateConv::DateTimeString(cgiEnv->GetInformation().Client.Session.LastLogin.Time, CDate::Timezone::UTC))).str())));
            tmpl->bindWidget("last-login-location-country-code", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.CountryCode)));
            tmpl->bindWidget("last-login-location-country-code3", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.CountryCode3)));
            tmpl->bindWidget("last-login-location-country-name", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.CountryName)));
            tmpl->bindWidget("last-login-location-region", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Region)));
            tmpl->bindWidget("last-login-location-city", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.City)));
            tmpl->bindWidget("last-login-location-postal-code", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.PostalCode)));
            tmpl->bindWidget("last-login-location-latitude", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Latitude))));
            tmpl->bindWidget("last-login-location-longitude", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Longitude))));
            tmpl->bindWidget("last-login-location-metro-code", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.MetroCode))));
            tmpl->bindWidget("last-login-location-dma-code", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.DmaCode))));
            tmpl->bindWidget("last-login-location-area-code", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.AreaCode))));
            tmpl->bindWidget("last-login-location-charset", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Charset))));
            tmpl->bindWidget("last-login-location-continent-code", new WText(
                                 WString::fromUTF8(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.ContinentCode)));
            tmpl->bindWidget("last-login-location-netmask", new WText(
                                 WString::fromUTF8(lexical_cast<string>(cgiEnv->GetInformation().Client.Session.LastLogin.GeoLocation.Netmask))));

            tmpl->bindWidget("force-terminate-all-sessions", forceTerminateAllSessionsPushButton);

            forceTerminateAllSessionsPushButton->clicked().connect(m_pimpl.get(), &CmsDashboard::Impl::OnForceTerminateAllSessionsPushButtonPressed);
       }
    }

    catch (const boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex), cgiEnv->GetInformation().ToJson());
    }

    catch (const std::exception &ex) {
        LOG_ERROR(ex.what(), cgiEnv->GetInformation().ToJson());
    }

    catch (...) {
        LOG_ERROR(UNKNOWN_ERROR, cgiEnv->GetInformation().ToJson());
    }

    return container;
}

CmsDashboard::Impl::Impl()
{

}

CmsDashboard::Impl::~Impl() = default;

void CmsDashboard::Impl::OnForceTerminateAllSessionsPushButtonPressed()
{
    ForceTerminateAllSessionsMessageBox =
            std::make_unique<WMessageBox>(tr("cms-dashboard-force-terminate-all-sessions-confirm-title"),
                                              tr("cms-dashboard-force-terminate-all-sessions-confirm-question"), Warning, NoButton);

    ForceTerminateAllSessionsMessageBox->addButton(tr("cms-dashboard-force-terminate-all-sessions-confirm-ok"), Ok);
    ForceTerminateAllSessionsMessageBox->addButton(tr("cms-dashboard-force-terminate-all-sessions-confirm-cancel"), Cancel);

    ForceTerminateAllSessionsMessageBox->buttonClicked().connect(this, &CmsDashboard::Impl::OnForceTerminateAllSessionsDialogClosed);

    ForceTerminateAllSessionsMessageBox->show();
}

void CmsDashboard::Impl::OnForceTerminateAllSessionsDialogClosed(Wt::StandardButton button)
{
    CgiRoot *cgiRoot = static_cast<CgiRoot *>(WApplication::instance());
    CgiEnv *cgiEnv = cgiRoot->GetCgiEnvInstance();

    try {
        if (button == Ok) {

            auto conn = Pool::Database().Connection();
            conn->activate();
            pqxx::work txn(*conn.get());

            string query((boost::format("UPDATE ONLY \"%1%\""
                                        " SET expiry = '19700101'::TIMESTAMPTZ"
                                        " WHERE user_id = %2% AND expiry > '19700101'::TIMESTAMPTZ;")
                          % txn.esc(Service::Pool::Database().GetTableName("ROOT_SESSIONS"))
                          % txn.quote(cgiEnv->GetInformation().Client.Session.UserId)).str());
            LOG_INFO("Running query...", query, cgiEnv->GetInformation().ToJson());

            txn.exec(query);

            txn.commit();

            ForceTerminateAllSessionsMessageBox.reset();

            SessionTerminationScheduledMessageBox =
                    std::make_unique<WMessageBox>(tr("cms-dashboard-force-terminate-all-sessions-has-been-scheduled-title"),
                                                  tr("cms-dashboard-force-terminate-all-sessions-has-been-scheduled-message"),
                                                  Warning, NoButton);
            SessionTerminationScheduledMessageBox->addButton(tr("cms-dashboard-force-terminate-all-sessions-has-been-scheduled-ok"), Ok);

            SessionTerminationScheduledMessageBox->buttonClicked().connect(
                        this, &CmsDashboard::Impl::OnSessionTerminationScheduledDialogClosed);

            SessionTerminationScheduledMessageBox->show();

            return;
        }
    }

    catch (const pqxx::sql_error &ex) {
        LOG_ERROR(ex.what(), ex.query(), cgiEnv->GetInformation().ToJson());
    }

    catch (const boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex), cgiEnv->GetInformation().ToJson());
    }

    catch (const std::exception &ex) {
        LOG_ERROR(ex.what(), cgiEnv->GetInformation().ToJson());
    }

    catch (...) {
        LOG_ERROR(UNKNOWN_ERROR, cgiEnv->GetInformation().ToJson());
    }

    ForceTerminateAllSessionsMessageBox.reset();
}

void CmsDashboard::Impl::OnSessionTerminationScheduledDialogClosed(Wt::StandardButton button)
{
    (void)button;

    SessionTerminationScheduledMessageBox.reset();
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/browser_child_process_host.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "content/browser/browser_thread.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/renderer_host/resource_message_filter.h"
#include "content/browser/trace_message_filter.h"
#include "content/common/notification_service.h"
#include "content/common/plugin_messages.h"
#include "content/common/process_watcher.h"
#include "content/common/result_codes.h"

namespace {

typedef std::list<BrowserChildProcessHost*> ChildProcessList;
static base::LazyInstance<ChildProcessList> g_child_process_list(
    base::LINKER_INITIALIZED);

// The NotificationTask is used to notify about plugin process connection/
// disconnection. It is needed because the notifications in the
// NotificationService must happen in the main thread.
class ChildNotificationTask : public Task {
 public:
  ChildNotificationTask(
      NotificationType notification_type, ChildProcessInfo* info)
      : notification_type_(notification_type), info_(*info) { }

  virtual void Run() {
    NotificationService::current()->
        Notify(notification_type_, NotificationService::AllSources(),
               Details<ChildProcessInfo>(&info_));
  }

 private:
  NotificationType notification_type_;
  ChildProcessInfo info_;
};

}  // namespace

BrowserChildProcessHost::BrowserChildProcessHost(
    ChildProcessInfo::ProcessType type)
    : ChildProcessInfo(type, -1),
      ALLOW_THIS_IN_INITIALIZER_LIST(client_(this)) {
  AddFilter(new TraceMessageFilter);

  g_child_process_list.Get().push_back(this);
}

BrowserChildProcessHost::~BrowserChildProcessHost() {
  g_child_process_list.Get().remove(this);
}

// static
void BrowserChildProcessHost::TerminateAll() {
  // Make a copy since the ChildProcessHost dtor mutates the original list.
  ChildProcessList copy = g_child_process_list.Get();
  STLDeleteElements(&copy);
}

void BrowserChildProcessHost::Launch(
#if defined(OS_WIN)
    const FilePath& exposed_dir,
#elif defined(OS_POSIX)
    bool use_zygote,
    const base::environment_vector& environ,
#endif
    CommandLine* cmd_line) {

  content::GetContentClient()->browser()->AppendExtraCommandLineSwitches(
      cmd_line, id());

  child_process_.reset(new ChildProcessLauncher(
#if defined(OS_WIN)
      exposed_dir,
#elif defined(OS_POSIX)
      use_zygote,
      environ,
      channel()->GetClientFileDescriptor(),
#endif
      cmd_line,
      &client_));
}

base::ProcessHandle BrowserChildProcessHost::GetChildProcessHandle() const {
  DCHECK(child_process_.get())
      << "Requesting a child process handle before launching.";
  DCHECK(child_process_->GetHandle())
      << "Requesting a child process handle before launch has completed OK.";
  return child_process_->GetHandle();
}

void BrowserChildProcessHost::ForceShutdown() {
  g_child_process_list.Get().remove(this);
  ChildProcessHost::ForceShutdown();
}

void BrowserChildProcessHost::Notify(NotificationType type) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE, new ChildNotificationTask(type, this));
}

base::TerminationStatus BrowserChildProcessHost::GetChildTerminationStatus(
    int* exit_code) {
  return child_process_->GetChildTerminationStatus(exit_code);
}

void BrowserChildProcessHost::OnChildDied() {
  if (handle() != base::kNullProcessHandle) {
    int exit_code;
    base::TerminationStatus status = GetChildTerminationStatus(&exit_code);
    switch (status) {
      case base::TERMINATION_STATUS_PROCESS_CRASHED: {
        OnProcessCrashed(exit_code);

        // Report that this child process crashed.
        Notify(NotificationType::CHILD_PROCESS_CRASHED);
        UMA_HISTOGRAM_COUNTS("ChildProcess.Crashes", this->type());
        break;
      }
      case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: {
        OnProcessWasKilled(exit_code);

        // Report that this child process was killed.
        Notify(NotificationType::CHILD_PROCESS_WAS_KILLED);
        UMA_HISTOGRAM_COUNTS("ChildProcess.Kills", this->type());
        break;
      }
      default:
        break;
    }
    // Notify in the main loop of the disconnection.
    Notify(NotificationType::CHILD_PROCESS_HOST_DISCONNECTED);
  }
  ChildProcessHost::OnChildDied();
}

void BrowserChildProcessHost::ShutdownStarted() {
  // Must remove the process from the list now, in case it gets used for a
  // new instance before our watcher tells us that the process terminated.
  g_child_process_list.Get().remove(this);
}

BrowserChildProcessHost::ClientHook::ClientHook(BrowserChildProcessHost* host)
    : host_(host) {
}

void BrowserChildProcessHost::ClientHook::OnProcessLaunched() {
  if (!host_->child_process_->GetHandle()) {
    host_->OnChildDied();
    return;
  }
  host_->set_handle(host_->child_process_->GetHandle());
  host_->OnProcessLaunched();
}

BrowserChildProcessHost::Iterator::Iterator()
    : all_(true), type_(UNKNOWN_PROCESS) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) <<
          "ChildProcessInfo::Iterator must be used on the IO thread.";
  iterator_ = g_child_process_list.Get().begin();
}

BrowserChildProcessHost::Iterator::Iterator(ChildProcessInfo::ProcessType type)
    : all_(false), type_(type) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) <<
          "ChildProcessInfo::Iterator must be used on the IO thread.";
  iterator_ = g_child_process_list.Get().begin();
  if (!Done() && (*iterator_)->type() != type_)
    ++(*this);
}

BrowserChildProcessHost* BrowserChildProcessHost::Iterator::operator++() {
  do {
    ++iterator_;
    if (Done())
      break;

    if (!all_ && (*iterator_)->type() != type_)
      continue;

    return *iterator_;
  } while (true);

  return NULL;
}

bool BrowserChildProcessHost::Iterator::Done() {
  return iterator_ == g_child_process_list.Get().end();
}
<commit_msg>Treat TERMINATION_STATUS_ABNORMAL_TERMINATION in browser child processes as crashes. Child processes on the Mac that are Breakpad-enabled will not appear to have crashed according to the logic in base::GetTerminationStatus, they'll show up as TERMINATION_STATUS_ABNORMAL_TERMINATION instead of TERMINATION_STATUS_PROCESS_CRASHED. This happens because they exit from their crash handler to suppress the system's redundant crash handler. This broke in r69082, which introduced the TerminationStatus enum to replace a simpler did_crash boolean value set by logic treating both death by signal and nonzero exit status as a crash.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/browser_child_process_host.h"

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "content/browser/browser_thread.h"
#include "content/browser/content_browser_client.h"
#include "content/browser/renderer_host/resource_message_filter.h"
#include "content/browser/trace_message_filter.h"
#include "content/common/notification_service.h"
#include "content/common/plugin_messages.h"
#include "content/common/process_watcher.h"
#include "content/common/result_codes.h"

namespace {

typedef std::list<BrowserChildProcessHost*> ChildProcessList;
static base::LazyInstance<ChildProcessList> g_child_process_list(
    base::LINKER_INITIALIZED);

// The NotificationTask is used to notify about plugin process connection/
// disconnection. It is needed because the notifications in the
// NotificationService must happen in the main thread.
class ChildNotificationTask : public Task {
 public:
  ChildNotificationTask(
      NotificationType notification_type, ChildProcessInfo* info)
      : notification_type_(notification_type), info_(*info) { }

  virtual void Run() {
    NotificationService::current()->
        Notify(notification_type_, NotificationService::AllSources(),
               Details<ChildProcessInfo>(&info_));
  }

 private:
  NotificationType notification_type_;
  ChildProcessInfo info_;
};

}  // namespace

BrowserChildProcessHost::BrowserChildProcessHost(
    ChildProcessInfo::ProcessType type)
    : ChildProcessInfo(type, -1),
      ALLOW_THIS_IN_INITIALIZER_LIST(client_(this)) {
  AddFilter(new TraceMessageFilter);

  g_child_process_list.Get().push_back(this);
}

BrowserChildProcessHost::~BrowserChildProcessHost() {
  g_child_process_list.Get().remove(this);
}

// static
void BrowserChildProcessHost::TerminateAll() {
  // Make a copy since the ChildProcessHost dtor mutates the original list.
  ChildProcessList copy = g_child_process_list.Get();
  STLDeleteElements(&copy);
}

void BrowserChildProcessHost::Launch(
#if defined(OS_WIN)
    const FilePath& exposed_dir,
#elif defined(OS_POSIX)
    bool use_zygote,
    const base::environment_vector& environ,
#endif
    CommandLine* cmd_line) {

  content::GetContentClient()->browser()->AppendExtraCommandLineSwitches(
      cmd_line, id());

  child_process_.reset(new ChildProcessLauncher(
#if defined(OS_WIN)
      exposed_dir,
#elif defined(OS_POSIX)
      use_zygote,
      environ,
      channel()->GetClientFileDescriptor(),
#endif
      cmd_line,
      &client_));
}

base::ProcessHandle BrowserChildProcessHost::GetChildProcessHandle() const {
  DCHECK(child_process_.get())
      << "Requesting a child process handle before launching.";
  DCHECK(child_process_->GetHandle())
      << "Requesting a child process handle before launch has completed OK.";
  return child_process_->GetHandle();
}

void BrowserChildProcessHost::ForceShutdown() {
  g_child_process_list.Get().remove(this);
  ChildProcessHost::ForceShutdown();
}

void BrowserChildProcessHost::Notify(NotificationType type) {
  BrowserThread::PostTask(
      BrowserThread::UI, FROM_HERE, new ChildNotificationTask(type, this));
}

base::TerminationStatus BrowserChildProcessHost::GetChildTerminationStatus(
    int* exit_code) {
  return child_process_->GetChildTerminationStatus(exit_code);
}

void BrowserChildProcessHost::OnChildDied() {
  if (handle() != base::kNullProcessHandle) {
    int exit_code;
    base::TerminationStatus status = GetChildTerminationStatus(&exit_code);
    switch (status) {
      case base::TERMINATION_STATUS_PROCESS_CRASHED:
      case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: {
        OnProcessCrashed(exit_code);

        // Report that this child process crashed.
        Notify(NotificationType::CHILD_PROCESS_CRASHED);
        UMA_HISTOGRAM_COUNTS("ChildProcess.Crashes", this->type());
        break;
      }
      case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: {
        OnProcessWasKilled(exit_code);

        // Report that this child process was killed.
        Notify(NotificationType::CHILD_PROCESS_WAS_KILLED);
        UMA_HISTOGRAM_COUNTS("ChildProcess.Kills", this->type());
        break;
      }
      default:
        break;
    }
    // Notify in the main loop of the disconnection.
    Notify(NotificationType::CHILD_PROCESS_HOST_DISCONNECTED);
  }
  ChildProcessHost::OnChildDied();
}

void BrowserChildProcessHost::ShutdownStarted() {
  // Must remove the process from the list now, in case it gets used for a
  // new instance before our watcher tells us that the process terminated.
  g_child_process_list.Get().remove(this);
}

BrowserChildProcessHost::ClientHook::ClientHook(BrowserChildProcessHost* host)
    : host_(host) {
}

void BrowserChildProcessHost::ClientHook::OnProcessLaunched() {
  if (!host_->child_process_->GetHandle()) {
    host_->OnChildDied();
    return;
  }
  host_->set_handle(host_->child_process_->GetHandle());
  host_->OnProcessLaunched();
}

BrowserChildProcessHost::Iterator::Iterator()
    : all_(true), type_(UNKNOWN_PROCESS) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) <<
          "ChildProcessInfo::Iterator must be used on the IO thread.";
  iterator_ = g_child_process_list.Get().begin();
}

BrowserChildProcessHost::Iterator::Iterator(ChildProcessInfo::ProcessType type)
    : all_(false), type_(type) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)) <<
          "ChildProcessInfo::Iterator must be used on the IO thread.";
  iterator_ = g_child_process_list.Get().begin();
  if (!Done() && (*iterator_)->type() != type_)
    ++(*this);
}

BrowserChildProcessHost* BrowserChildProcessHost::Iterator::operator++() {
  do {
    ++iterator_;
    if (Done())
      break;

    if (!all_ && (*iterator_)->type() != type_)
      continue;

    return *iterator_;
  } while (true);

  return NULL;
}

bool BrowserChildProcessHost::Iterator::Done() {
  return iterator_ == g_child_process_list.Get().end();
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <basic/sbxvar.hxx>

#include <svx/svxids.hrc>
#include <editeng/svxenum.hxx>

#include "viewopt.hxx"
#include "swtypes.hxx"
#include "cmdid.h"
#include "prtopt.hxx"
#include "cfgitems.hxx"
#include "crstate.hxx"

TYPEINIT1_AUTOFACTORY(SwDocDisplayItem, SfxPoolItem)
TYPEINIT1_AUTOFACTORY(SwElemItem, SfxPoolItem)
TYPEINIT1_AUTOFACTORY(SwAddPrinterItem, SfxPoolItem)
TYPEINIT1_AUTOFACTORY(SwShadowCursorItem, SfxPoolItem)

SwDocDisplayItem::SwDocDisplayItem( USHORT _nWhich ) :
        SfxPoolItem(_nWhich),
        aIndexBackgrndCol(COL_GRAY)
{
    bParagraphEnd       =
    bTab                =
    bSpace              =
    bNonbreakingSpace   =
    bSoftHyphen         =
    bFldHiddenText      =
    bCharHiddenText     =
    bManualBreak        =
    bShowHiddenPara     = FALSE;

};

/*-------------------------------------------------------------------
    Item fuer Einstellungsdialog, Seite Dokumentansicht
--------------------------------------------------------------------*/
SwDocDisplayItem::SwDocDisplayItem( const SwDocDisplayItem& rDocDisplayItem ):
            SfxPoolItem(rDocDisplayItem)
{
    *this = rDocDisplayItem;
};

SwDocDisplayItem::SwDocDisplayItem(const SwViewOption& rVOpt, USHORT _nWhich ) :
            SfxPoolItem( _nWhich )
{
    bParagraphEnd       = rVOpt.IsParagraph(TRUE);
    bTab                = rVOpt.IsTab(TRUE);
    bSpace              = rVOpt.IsBlank(TRUE);
    bNonbreakingSpace   = rVOpt.IsHardBlank();
    bSoftHyphen         = rVOpt.IsSoftHyph();
    bCharHiddenText     = rVOpt.IsShowHiddenChar(TRUE);
    bFldHiddenText      = rVOpt.IsShowHiddenField();
    bManualBreak        = rVOpt.IsLineBreak(TRUE);
    bShowHiddenPara     = rVOpt.IsShowHiddenPara();
}

SfxPoolItem* SwDocDisplayItem::Clone( SfxItemPool*  ) const
{
    return new SwDocDisplayItem( *this );
}

int SwDocDisplayItem::operator==( const SfxPoolItem& rAttr ) const
{
    OSL_ENSURE( SfxPoolItem::operator==(rAttr), "different types" );

    const SwDocDisplayItem& rItem = (SwDocDisplayItem&)rAttr;

    return (  bParagraphEnd         == rItem.bParagraphEnd       &&
              bTab                  == rItem.bTab                &&
              bSpace                == rItem.bSpace              &&
              bNonbreakingSpace     == rItem.bNonbreakingSpace   &&
              bSoftHyphen           == rItem.bSoftHyphen         &&
              bCharHiddenText       == rItem.bCharHiddenText         &&
              bFldHiddenText        == rItem.bFldHiddenText         &&
              bManualBreak          == rItem.bManualBreak        &&
              bShowHiddenPara       == rItem.bShowHiddenPara );
}

void  SwDocDisplayItem::operator=( const SwDocDisplayItem& rDocDisplayItem)
{
    bParagraphEnd       = rDocDisplayItem.bParagraphEnd         ;
    bTab                = rDocDisplayItem.bTab                  ;
    bSpace              = rDocDisplayItem.bSpace                ;
    bNonbreakingSpace   = rDocDisplayItem.bNonbreakingSpace     ;
    bSoftHyphen         = rDocDisplayItem.bSoftHyphen           ;
    bCharHiddenText     = rDocDisplayItem.bCharHiddenText           ;
    bFldHiddenText      = rDocDisplayItem.bFldHiddenText           ;
    bManualBreak        = rDocDisplayItem.bManualBreak          ;
    bShowHiddenPara     = rDocDisplayItem.bShowHiddenPara       ;
}

void SwDocDisplayItem::FillViewOptions( SwViewOption& rVOpt) const
{
    rVOpt.SetParagraph  (bParagraphEnd      );
    rVOpt.SetTab        (bTab               );
    rVOpt.SetBlank      (bSpace             );
    rVOpt.SetHardBlank  (bNonbreakingSpace  );
    rVOpt.SetSoftHyph   (bSoftHyphen        );
    rVOpt.SetShowHiddenChar(bCharHiddenText );
    rVOpt.SetShowHiddenField(bFldHiddenText        );
    rVOpt.SetLineBreak  (bManualBreak       );
    rVOpt.SetShowHiddenPara(bShowHiddenPara );
}

SwElemItem::SwElemItem( USHORT _nWhich ) :
    SfxPoolItem(_nWhich)
{
    bHorzScrollbar =
    bVertScrollbar =
    bAnyRuler =
    bHorzRuler     =
    bVertRuler     =
    bVertRulerRight=
    bCrosshair     =
    bHandles       =
    bBigHandles     =
    bSmoothScroll  =
    bTable              =
    bGraphic            =
    bDrawing            =
    bFieldName          =
    bNotes              = FALSE;
}

SwElemItem::SwElemItem( const SwElemItem& rElemItem ):
            SfxPoolItem(rElemItem)
{
    *this = rElemItem;
}

SwElemItem::SwElemItem(const SwViewOption& rVOpt, USHORT _nWhich) :
            SfxPoolItem( _nWhich )
{
    bHorzScrollbar  = rVOpt.IsViewHScrollBar();
    bVertScrollbar  = rVOpt.IsViewVScrollBar();
    bAnyRuler       = rVOpt.IsViewAnyRuler();
    bHorzRuler      = rVOpt.IsViewHRuler(TRUE);
    bVertRuler      = rVOpt.IsViewVRuler(TRUE);
    bVertRulerRight = rVOpt.IsVRulerRight();
    bCrosshair      = rVOpt.IsCrossHair();
    bHandles        = rVOpt.IsSolidMarkHdl();
    bBigHandles     = rVOpt.IsBigMarkHdl();
    bSmoothScroll   = rVOpt.IsSmoothScroll();
    bTable              = rVOpt.IsTable();
    bGraphic            = rVOpt.IsGraphic();
    bDrawing            = rVOpt.IsDraw() && rVOpt.IsControl();
    bFieldName          = rVOpt.IsFldName();
    bNotes              = rVOpt.IsPostIts();

}

SfxPoolItem* SwElemItem::Clone( SfxItemPool* ) const
{
    return new SwElemItem( *this );
}

int SwElemItem::operator==( const SfxPoolItem& rAttr ) const
{
    OSL_ENSURE( SfxPoolItem::operator==(rAttr), "different types" );

    const SwElemItem& rItem = (SwElemItem&)rAttr;

    return (    bHorzScrollbar  == rItem.bHorzScrollbar &&
                bVertScrollbar  == rItem.bVertScrollbar &&
                bAnyRuler       == rItem.bAnyRuler &&
                bHorzRuler      == rItem.bHorzRuler     &&
                bVertRuler      == rItem.bVertRuler     &&
                bVertRulerRight == rItem.bVertRulerRight&&
                bCrosshair      == rItem.bCrosshair     &&
                bHandles        == rItem.bHandles       &&
                bBigHandles     == rItem.bBigHandles    &&
                bSmoothScroll   == rItem.bSmoothScroll  &&
                bTable                == rItem.bTable              &&
                bGraphic              == rItem.bGraphic            &&
                bDrawing              == rItem.bDrawing            &&
                bFieldName            == rItem.bFieldName          &&
                bNotes                == rItem.bNotes             );
}

void  SwElemItem::operator=( const SwElemItem& rElemItem)
{
    bHorzScrollbar  = rElemItem.  bHorzScrollbar    ;
    bVertScrollbar  = rElemItem.  bVertScrollbar    ;
    bAnyRuler       = rElemItem.  bAnyRuler;
    bHorzRuler      = rElemItem.  bHorzRuler        ;
    bVertRuler      = rElemItem.  bVertRuler        ;
    bVertRulerRight = rElemItem.  bVertRulerRight   ;
    bCrosshair      = rElemItem.  bCrosshair        ;
    bHandles        = rElemItem.  bHandles          ;
    bBigHandles     = rElemItem.  bBigHandles       ;
    bSmoothScroll   = rElemItem.  bSmoothScroll     ;
    bTable              = rElemItem.bTable                ;
    bGraphic            = rElemItem.bGraphic              ;
    bDrawing            = rElemItem.bDrawing              ;
    bFieldName          = rElemItem.bFieldName            ;
    bNotes              = rElemItem.bNotes                ;
}

void SwElemItem::FillViewOptions( SwViewOption& rVOpt) const
{
    rVOpt.SetViewHScrollBar(bHorzScrollbar );
    rVOpt.SetViewVScrollBar(bVertScrollbar );
    rVOpt.SetViewAnyRuler(bAnyRuler);
    rVOpt.SetViewHRuler(bHorzRuler    );
    rVOpt.SetViewVRuler(bVertRuler    );
    rVOpt.SetVRulerRight(bVertRulerRight );
    rVOpt.SetCrossHair(bCrosshair     );
    rVOpt.SetSolidMarkHdl(bHandles    );
    rVOpt.SetBigMarkHdl(bBigHandles );
    rVOpt.SetSmoothScroll(bSmoothScroll);
    rVOpt.SetTable      (bTable             );
    rVOpt.SetGraphic    (bGraphic           );
    rVOpt.SetDraw       (bDrawing           );
    rVOpt.SetControl    (bDrawing           );
    rVOpt.SetFldName    (bFieldName         );
    rVOpt.SetPostIts    (bNotes             );
}

/*--------------------------------------------------------------------
    Beschreibung: CopyCTOR
 --------------------------------------------------------------------*/
SwAddPrinterItem::SwAddPrinterItem( const SwAddPrinterItem& rAddPrinterItem ):
            SfxPoolItem(rAddPrinterItem),
            SwPrintData( rAddPrinterItem )
{
}

/*--------------------------------------------------------------------
    Beschreibung: CTOR fuer leeres Item
 --------------------------------------------------------------------*/
SwAddPrinterItem::SwAddPrinterItem( USHORT _nWhich):
                SfxPoolItem(_nWhich)
{
}

/*--------------------------------------------------------------------
    Beschreibung: CTOR aus SwPrintOptions
 --------------------------------------------------------------------*/
SwAddPrinterItem::SwAddPrinterItem( USHORT _nWhich, const SwPrintData& rPrtData ) :
    SfxPoolItem(_nWhich)
{
    SwPrintData::operator=(rPrtData);
}

SfxPoolItem* SwAddPrinterItem::Clone( SfxItemPool* ) const
{
    return new SwAddPrinterItem( *this );
}

int SwAddPrinterItem::operator==( const SfxPoolItem& rAttr ) const
{
    OSL_ENSURE( SfxPoolItem::operator==(rAttr), "different types" );

    const SwAddPrinterItem& rItem = (SwAddPrinterItem&)rAttr;

    return  SwPrintData::operator==(rItem);
}

/*--------------------------------------------------
 Item fuer Einstellungsdialog, ShadowCursorSeite
--------------------------------------------------*/
SwShadowCursorItem::SwShadowCursorItem( USHORT _nWhich )
    : SfxPoolItem( _nWhich ),
    eMode( FILL_TAB )
    ,bOn( FALSE )
{
}

SwShadowCursorItem::SwShadowCursorItem( const SwShadowCursorItem& rCpy )
    : SfxPoolItem( rCpy.Which() ),
    eMode( rCpy.GetMode() )
    ,bOn( rCpy.IsOn() )

{
}

SwShadowCursorItem::SwShadowCursorItem( const SwViewOption& rVOpt, USHORT _nWhich )
    : SfxPoolItem( _nWhich ),
    eMode( rVOpt.GetShdwCrsrFillMode() )
    ,bOn( rVOpt.IsShadowCursor() )

{
}

SfxPoolItem* SwShadowCursorItem::Clone( SfxItemPool* ) const
{
    return new SwShadowCursorItem( *this );
}

int SwShadowCursorItem::operator==( const SfxPoolItem& rCmp ) const
{
    return  IsOn() == ((SwShadowCursorItem&)rCmp).IsOn() &&
            GetMode() == ((SwShadowCursorItem&)rCmp).GetMode();
}

void SwShadowCursorItem::operator=( const SwShadowCursorItem& rCpy )
{
    SetOn( rCpy.IsOn() );
    SetMode( rCpy.GetMode() );
}

void SwShadowCursorItem::FillViewOptions( SwViewOption& rVOpt ) const
{
    rVOpt.SetShadowCursor( bOn );
    rVOpt.SetShdwCrsrFillMode( eMode );
}

#if OSL_DEBUG_LEVEL > 1
SwTestItem::SwTestItem( const SwTestItem& rTestItem ):
            SfxPoolItem(rTestItem)
{
    bTest1=rTestItem.bTest1;
    bTest2=rTestItem.bTest2;
    bTest3=rTestItem.bTest3;
    bTest4=rTestItem.bTest4;
    bTest5=rTestItem.bTest5;
    bTest6=rTestItem.bTest6;
    bTest7=rTestItem.bTest7;
    bTest8=rTestItem.bTest8;
    bTest9=rTestItem.bTest9;
    bTest10=rTestItem.bTest10;
};

SfxPoolItem* SwTestItem::Clone( SfxItemPool* ) const
{
    return new SwTestItem( *this );
}

int SwTestItem::operator==( const SfxPoolItem& rAttr ) const
{
    OSL_ENSURE( SfxPoolItem::operator==(rAttr), "different types" );

    const SwTestItem& rItem = (const SwTestItem&) rAttr;

    return ( bTest1==rItem.bTest1&&
             bTest2==rItem.bTest2&&
             bTest3==rItem.bTest3&&
             bTest4==rItem.bTest4&&
             bTest5==rItem.bTest5&&
             bTest6==rItem.bTest6&&
             bTest7==rItem.bTest7&&
             bTest8==rItem.bTest8&&
             bTest9==rItem.bTest9&&
             bTest10==rItem.bTest10);
}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Translate german comments in cfgitems.cxx<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <basic/sbxvar.hxx>

#include <svx/svxids.hrc>
#include <editeng/svxenum.hxx>

#include "viewopt.hxx"
#include "swtypes.hxx"
#include "cmdid.h"
#include "prtopt.hxx"
#include "cfgitems.hxx"
#include "crstate.hxx"

TYPEINIT1_AUTOFACTORY(SwDocDisplayItem, SfxPoolItem)
TYPEINIT1_AUTOFACTORY(SwElemItem, SfxPoolItem)
TYPEINIT1_AUTOFACTORY(SwAddPrinterItem, SfxPoolItem)
TYPEINIT1_AUTOFACTORY(SwShadowCursorItem, SfxPoolItem)

SwDocDisplayItem::SwDocDisplayItem( USHORT _nWhich ) :
        SfxPoolItem(_nWhich),
        aIndexBackgrndCol(COL_GRAY)
{
    bParagraphEnd       =
    bTab                =
    bSpace              =
    bNonbreakingSpace   =
    bSoftHyphen         =
    bFldHiddenText      =
    bCharHiddenText     =
    bManualBreak        =
    bShowHiddenPara     = FALSE;

};

/*-------------------------------------------------------------------
    Item for the Settings dialog, page document view
--------------------------------------------------------------------*/
SwDocDisplayItem::SwDocDisplayItem( const SwDocDisplayItem& rDocDisplayItem ):
            SfxPoolItem(rDocDisplayItem)
{
    *this = rDocDisplayItem;
};

SwDocDisplayItem::SwDocDisplayItem(const SwViewOption& rVOpt, USHORT _nWhich ) :
            SfxPoolItem( _nWhich )
{
    bParagraphEnd       = rVOpt.IsParagraph(TRUE);
    bTab                = rVOpt.IsTab(TRUE);
    bSpace              = rVOpt.IsBlank(TRUE);
    bNonbreakingSpace   = rVOpt.IsHardBlank();
    bSoftHyphen         = rVOpt.IsSoftHyph();
    bCharHiddenText     = rVOpt.IsShowHiddenChar(TRUE);
    bFldHiddenText      = rVOpt.IsShowHiddenField();
    bManualBreak        = rVOpt.IsLineBreak(TRUE);
    bShowHiddenPara     = rVOpt.IsShowHiddenPara();
}

SfxPoolItem* SwDocDisplayItem::Clone( SfxItemPool*  ) const
{
    return new SwDocDisplayItem( *this );
}

int SwDocDisplayItem::operator==( const SfxPoolItem& rAttr ) const
{
    OSL_ENSURE( SfxPoolItem::operator==(rAttr), "different types" );

    const SwDocDisplayItem& rItem = (SwDocDisplayItem&)rAttr;

    return (  bParagraphEnd         == rItem.bParagraphEnd       &&
              bTab                  == rItem.bTab                &&
              bSpace                == rItem.bSpace              &&
              bNonbreakingSpace     == rItem.bNonbreakingSpace   &&
              bSoftHyphen           == rItem.bSoftHyphen         &&
              bCharHiddenText       == rItem.bCharHiddenText         &&
              bFldHiddenText        == rItem.bFldHiddenText         &&
              bManualBreak          == rItem.bManualBreak        &&
              bShowHiddenPara       == rItem.bShowHiddenPara );
}

void  SwDocDisplayItem::operator=( const SwDocDisplayItem& rDocDisplayItem)
{
    bParagraphEnd       = rDocDisplayItem.bParagraphEnd         ;
    bTab                = rDocDisplayItem.bTab                  ;
    bSpace              = rDocDisplayItem.bSpace                ;
    bNonbreakingSpace   = rDocDisplayItem.bNonbreakingSpace     ;
    bSoftHyphen         = rDocDisplayItem.bSoftHyphen           ;
    bCharHiddenText     = rDocDisplayItem.bCharHiddenText           ;
    bFldHiddenText      = rDocDisplayItem.bFldHiddenText           ;
    bManualBreak        = rDocDisplayItem.bManualBreak          ;
    bShowHiddenPara     = rDocDisplayItem.bShowHiddenPara       ;
}

void SwDocDisplayItem::FillViewOptions( SwViewOption& rVOpt) const
{
    rVOpt.SetParagraph  (bParagraphEnd      );
    rVOpt.SetTab        (bTab               );
    rVOpt.SetBlank      (bSpace             );
    rVOpt.SetHardBlank  (bNonbreakingSpace  );
    rVOpt.SetSoftHyph   (bSoftHyphen        );
    rVOpt.SetShowHiddenChar(bCharHiddenText );
    rVOpt.SetShowHiddenField(bFldHiddenText        );
    rVOpt.SetLineBreak  (bManualBreak       );
    rVOpt.SetShowHiddenPara(bShowHiddenPara );
}

SwElemItem::SwElemItem( USHORT _nWhich ) :
    SfxPoolItem(_nWhich)
{
    bHorzScrollbar =
    bVertScrollbar =
    bAnyRuler =
    bHorzRuler     =
    bVertRuler     =
    bVertRulerRight=
    bCrosshair     =
    bHandles       =
    bBigHandles     =
    bSmoothScroll  =
    bTable              =
    bGraphic            =
    bDrawing            =
    bFieldName          =
    bNotes              = FALSE;
}

SwElemItem::SwElemItem( const SwElemItem& rElemItem ):
            SfxPoolItem(rElemItem)
{
    *this = rElemItem;
}

SwElemItem::SwElemItem(const SwViewOption& rVOpt, USHORT _nWhich) :
            SfxPoolItem( _nWhich )
{
    bHorzScrollbar  = rVOpt.IsViewHScrollBar();
    bVertScrollbar  = rVOpt.IsViewVScrollBar();
    bAnyRuler       = rVOpt.IsViewAnyRuler();
    bHorzRuler      = rVOpt.IsViewHRuler(TRUE);
    bVertRuler      = rVOpt.IsViewVRuler(TRUE);
    bVertRulerRight = rVOpt.IsVRulerRight();
    bCrosshair      = rVOpt.IsCrossHair();
    bHandles        = rVOpt.IsSolidMarkHdl();
    bBigHandles     = rVOpt.IsBigMarkHdl();
    bSmoothScroll   = rVOpt.IsSmoothScroll();
    bTable              = rVOpt.IsTable();
    bGraphic            = rVOpt.IsGraphic();
    bDrawing            = rVOpt.IsDraw() && rVOpt.IsControl();
    bFieldName          = rVOpt.IsFldName();
    bNotes              = rVOpt.IsPostIts();

}

SfxPoolItem* SwElemItem::Clone( SfxItemPool* ) const
{
    return new SwElemItem( *this );
}

int SwElemItem::operator==( const SfxPoolItem& rAttr ) const
{
    OSL_ENSURE( SfxPoolItem::operator==(rAttr), "different types" );

    const SwElemItem& rItem = (SwElemItem&)rAttr;

    return (    bHorzScrollbar  == rItem.bHorzScrollbar &&
                bVertScrollbar  == rItem.bVertScrollbar &&
                bAnyRuler       == rItem.bAnyRuler &&
                bHorzRuler      == rItem.bHorzRuler     &&
                bVertRuler      == rItem.bVertRuler     &&
                bVertRulerRight == rItem.bVertRulerRight&&
                bCrosshair      == rItem.bCrosshair     &&
                bHandles        == rItem.bHandles       &&
                bBigHandles     == rItem.bBigHandles    &&
                bSmoothScroll   == rItem.bSmoothScroll  &&
                bTable                == rItem.bTable              &&
                bGraphic              == rItem.bGraphic            &&
                bDrawing              == rItem.bDrawing            &&
                bFieldName            == rItem.bFieldName          &&
                bNotes                == rItem.bNotes             );
}

void  SwElemItem::operator=( const SwElemItem& rElemItem)
{
    bHorzScrollbar  = rElemItem.  bHorzScrollbar    ;
    bVertScrollbar  = rElemItem.  bVertScrollbar    ;
    bAnyRuler       = rElemItem.  bAnyRuler;
    bHorzRuler      = rElemItem.  bHorzRuler        ;
    bVertRuler      = rElemItem.  bVertRuler        ;
    bVertRulerRight = rElemItem.  bVertRulerRight   ;
    bCrosshair      = rElemItem.  bCrosshair        ;
    bHandles        = rElemItem.  bHandles          ;
    bBigHandles     = rElemItem.  bBigHandles       ;
    bSmoothScroll   = rElemItem.  bSmoothScroll     ;
    bTable              = rElemItem.bTable                ;
    bGraphic            = rElemItem.bGraphic              ;
    bDrawing            = rElemItem.bDrawing              ;
    bFieldName          = rElemItem.bFieldName            ;
    bNotes              = rElemItem.bNotes                ;
}

void SwElemItem::FillViewOptions( SwViewOption& rVOpt) const
{
    rVOpt.SetViewHScrollBar(bHorzScrollbar );
    rVOpt.SetViewVScrollBar(bVertScrollbar );
    rVOpt.SetViewAnyRuler(bAnyRuler);
    rVOpt.SetViewHRuler(bHorzRuler    );
    rVOpt.SetViewVRuler(bVertRuler    );
    rVOpt.SetVRulerRight(bVertRulerRight );
    rVOpt.SetCrossHair(bCrosshair     );
    rVOpt.SetSolidMarkHdl(bHandles    );
    rVOpt.SetBigMarkHdl(bBigHandles );
    rVOpt.SetSmoothScroll(bSmoothScroll);
    rVOpt.SetTable      (bTable             );
    rVOpt.SetGraphic    (bGraphic           );
    rVOpt.SetDraw       (bDrawing           );
    rVOpt.SetControl    (bDrawing           );
    rVOpt.SetFldName    (bFieldName         );
    rVOpt.SetPostIts    (bNotes             );
}

/*--------------------------------------------------------------------
    Description: CopyCTOR
 --------------------------------------------------------------------*/
SwAddPrinterItem::SwAddPrinterItem( const SwAddPrinterItem& rAddPrinterItem ):
            SfxPoolItem(rAddPrinterItem),
            SwPrintData( rAddPrinterItem )
{
}

/*--------------------------------------------------------------------
    Description: CTOR for empty Item
 --------------------------------------------------------------------*/
SwAddPrinterItem::SwAddPrinterItem( USHORT _nWhich):
                SfxPoolItem(_nWhich)
{
}

/*--------------------------------------------------------------------
    Description: CTOR from SwPrintOptions
 --------------------------------------------------------------------*/
SwAddPrinterItem::SwAddPrinterItem( USHORT _nWhich, const SwPrintData& rPrtData ) :
    SfxPoolItem(_nWhich)
{
    SwPrintData::operator=(rPrtData);
}

SfxPoolItem* SwAddPrinterItem::Clone( SfxItemPool* ) const
{
    return new SwAddPrinterItem( *this );
}

int SwAddPrinterItem::operator==( const SfxPoolItem& rAttr ) const
{
    OSL_ENSURE( SfxPoolItem::operator==(rAttr), "different types" );

    const SwAddPrinterItem& rItem = (SwAddPrinterItem&)rAttr;

    return  SwPrintData::operator==(rItem);
}

/*--------------------------------------------------
 Item for Settings dialog, ShadowCursorPage
--------------------------------------------------*/
SwShadowCursorItem::SwShadowCursorItem( USHORT _nWhich )
    : SfxPoolItem( _nWhich ),
    eMode( FILL_TAB )
    ,bOn( FALSE )
{
}

SwShadowCursorItem::SwShadowCursorItem( const SwShadowCursorItem& rCpy )
    : SfxPoolItem( rCpy.Which() ),
    eMode( rCpy.GetMode() )
    ,bOn( rCpy.IsOn() )

{
}

SwShadowCursorItem::SwShadowCursorItem( const SwViewOption& rVOpt, USHORT _nWhich )
    : SfxPoolItem( _nWhich ),
    eMode( rVOpt.GetShdwCrsrFillMode() )
    ,bOn( rVOpt.IsShadowCursor() )

{
}

SfxPoolItem* SwShadowCursorItem::Clone( SfxItemPool* ) const
{
    return new SwShadowCursorItem( *this );
}

int SwShadowCursorItem::operator==( const SfxPoolItem& rCmp ) const
{
    return  IsOn() == ((SwShadowCursorItem&)rCmp).IsOn() &&
            GetMode() == ((SwShadowCursorItem&)rCmp).GetMode();
}

void SwShadowCursorItem::operator=( const SwShadowCursorItem& rCpy )
{
    SetOn( rCpy.IsOn() );
    SetMode( rCpy.GetMode() );
}

void SwShadowCursorItem::FillViewOptions( SwViewOption& rVOpt ) const
{
    rVOpt.SetShadowCursor( bOn );
    rVOpt.SetShdwCrsrFillMode( eMode );
}

#if OSL_DEBUG_LEVEL > 1
SwTestItem::SwTestItem( const SwTestItem& rTestItem ):
            SfxPoolItem(rTestItem)
{
    bTest1=rTestItem.bTest1;
    bTest2=rTestItem.bTest2;
    bTest3=rTestItem.bTest3;
    bTest4=rTestItem.bTest4;
    bTest5=rTestItem.bTest5;
    bTest6=rTestItem.bTest6;
    bTest7=rTestItem.bTest7;
    bTest8=rTestItem.bTest8;
    bTest9=rTestItem.bTest9;
    bTest10=rTestItem.bTest10;
};

SfxPoolItem* SwTestItem::Clone( SfxItemPool* ) const
{
    return new SwTestItem( *this );
}

int SwTestItem::operator==( const SfxPoolItem& rAttr ) const
{
    OSL_ENSURE( SfxPoolItem::operator==(rAttr), "different types" );

    const SwTestItem& rItem = (const SwTestItem&) rAttr;

    return ( bTest1==rItem.bTest1&&
             bTest2==rItem.bTest2&&
             bTest3==rItem.bTest3&&
             bTest4==rItem.bTest4&&
             bTest5==rItem.bTest5&&
             bTest6==rItem.bTest6&&
             bTest7==rItem.bTest7&&
             bTest8==rItem.bTest8&&
             bTest9==rItem.bTest9&&
             bTest10==rItem.bTest10);
}

#endif

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


<commit_before>/*
 * Copyright 2013 Gustaf Räntilä
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef LIBQ_PROMISE_HPP
#define LIBQ_PROMISE_HPP

#include <q/functional.hpp>
#include <q/log.hpp>
#include <q/temporarily_copyable.hpp>
#include <q/queue.hpp>
#include <q/exception.hpp>
#include <q/expect.hpp>
#include <q/memory.hpp>

#include <q/promise/core.hpp>
#include <q/promise/signal.hpp>
#include <q/promise/state.hpp>
#include <q/promise/promise.hpp>
#include <q/promise/defer.hpp>
#include <q/promise/reject.hpp>
#include <q/promise/with.hpp>
#include <q/promise/when.hpp>
#include <q/promise/all.hpp>
#include <q/promise/promise_impl.hpp>

#include <future>
#include <memory>

namespace q {

// TODO: Get rid of std::promise <-> std::future as we manually encapsulate
// data and exceptions in q::expect and signal manually too.

	// TODO: Implement progress reporting
	template< typename T >
	class progress
	{
	public:
		typedef progress< T > this_type;

		progress( const T& max )
		: max_( max )
		{ }
		progress( T&& max )
		: max_( std::move( max ) )
		{ }

		this_type& step( const T& value )
		{
			return *this;
		}

	private:
		std::atomic< T > max_;
	};

} // namespace q

#endif // LIBQ_PROMISE_HPP
<commit_msg>q::progress will not be implemented<commit_after>/*
 * Copyright 2013 Gustaf Räntilä
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef LIBQ_PROMISE_HPP
#define LIBQ_PROMISE_HPP

#include <q/functional.hpp>
#include <q/log.hpp>
#include <q/temporarily_copyable.hpp>
#include <q/queue.hpp>
#include <q/exception.hpp>
#include <q/expect.hpp>
#include <q/memory.hpp>

#include <q/promise/core.hpp>
#include <q/promise/signal.hpp>
#include <q/promise/state.hpp>
#include <q/promise/promise.hpp>
#include <q/promise/defer.hpp>
#include <q/promise/reject.hpp>
#include <q/promise/with.hpp>
#include <q/promise/when.hpp>
#include <q/promise/all.hpp>
#include <q/promise/promise_impl.hpp>

#include <future>
#include <memory>

namespace q {

// TODO: Get rid of std::promise <-> std::future as we manually encapsulate
// data and exceptions in q::expect and signal manually too.

} // namespace q

#endif // LIBQ_PROMISE_HPP
<|endoftext|>


<commit_before>#include "udpping.h"

namespace
{
    bool getAddress(const QString &address, sockaddr_any *addr)
    {
        Q_UNUSED(address);
        Q_UNUSED(addr);
        return true;
    }
}

UdpPing::UdpPing(QObject *parent)
: Measurement(parent)
, currentStatus(Unknown)
, m_device(NULL)
, m_capture(NULL)
, m_destAddress(),
, m_payload(NULL)
{
}

UdpPing::~UdpPing()
{
}

Measurement::Status UdpPing::status() const
{
    return currentStatus;
}

void UdpPing::setStatus(Status status)
{
    if (currentStatus != status)
    {
        currentStatus = status;
        emit statusChanged(status);
    }
}

bool UdpPing::prepare(NetworkManager* networkManager, const MeasurementDefinitionPtr& measurementDefinition)
{
    Q_UNUSED(networkManager);
    definition = measurementDefinition.dynamicCast<UdpPingDefinition>();
    return true;
}

bool UdpPing::start()
{
    return false;
}

bool UdpPing::stop()
{
    return true;
}

ResultPtr UdpPing::result() const
{
    QVariantList res;

    foreach (const PingProbe &probe, m_pingProbes)
    {
        if (probe.sendTime > 0 && probe.recvTime > 0)
        {
            res << probe.recvTime - probe.sendTime;
        }
    }

    return ResultPtr(new Result(QDateTime::currentDateTime(), res, QVariant()));
}

int UdpPing::initSocket()
{
    return 0;
}

bool UdpPing::sendData(PingProbe *probe)
{
    return false;
}

void UdpPing::receiveData(PingProbe *probe)
{
}

void UdpPing::ping(PingProbe *probe)
{
    // send
    if (sendData(probe))
    {
        receiveData(probe);
    }
}

// vim: set sts=4 sw=4 et:
<commit_msg>satisfy cppchecker (again)<commit_after>#include "udpping.h"

namespace
{
    bool getAddress(const QString &address, sockaddr_any *addr)
    {
        Q_UNUSED(address);
        Q_UNUSED(addr);
        return true;
    }
}

UdpPing::UdpPing(QObject *parent)
: Measurement(parent)
, currentStatus(Unknown)
, m_device(NULL)
, m_capture(NULL)
, m_destAddress()
, m_payload(NULL)
{
}

UdpPing::~UdpPing()
{
}

Measurement::Status UdpPing::status() const
{
    return currentStatus;
}

void UdpPing::setStatus(Status status)
{
    if (currentStatus != status)
    {
        currentStatus = status;
        emit statusChanged(status);
    }
}

bool UdpPing::prepare(NetworkManager* networkManager, const MeasurementDefinitionPtr& measurementDefinition)
{
    Q_UNUSED(networkManager);
    definition = measurementDefinition.dynamicCast<UdpPingDefinition>();
    return true;
}

bool UdpPing::start()
{
    return false;
}

bool UdpPing::stop()
{
    return true;
}

ResultPtr UdpPing::result() const
{
    QVariantList res;

    foreach (const PingProbe &probe, m_pingProbes)
    {
        if (probe.sendTime > 0 && probe.recvTime > 0)
        {
            res << probe.recvTime - probe.sendTime;
        }
    }

    return ResultPtr(new Result(QDateTime::currentDateTime(), res, QVariant()));
}

int UdpPing::initSocket()
{
    return 0;
}

bool UdpPing::sendData(PingProbe *probe)
{
    Q_UNUSED(probe);
    return false;
}

void UdpPing::receiveData(PingProbe *probe)
{
    Q_UNUSED(probe);
}

void UdpPing::ping(PingProbe *probe)
{
    // send
    if (sendData(probe))
    {
        receiveData(probe);
    }
}

// vim: set sts=4 sw=4 et:
<|endoftext|>


<commit_before>#include "ofxEdsdk.h"

/*
 This controls the size of liveBufferMiddle. If you are running at a low fps
 (lower than 30 fps), then it will effectively correspond to the latency of the
 camera. If you're running higher than 30 fps, it will determine how many frames
 you can miss without dropping one. For example, if you are running at 60 fps
 but one frame happens to last 200 ms, and your buffer size is 4, you will drop
 2 frames.
 */
#define OFX_EDSDK_BUFFER_SIZE 4
#define OFX_EDSDK_LIVE_DELAY 100
#ifdef TARGET_OSX
#include <Cocoa/Cocoa.h>
#elif defined(TARGET_WIN32)
#define _WIN32_DCOM
#include <objbase.h>
#endif
namespace ofxEdsdk {

	EdsError EDSCALLBACK Camera::handleObjectEvent(EdsObjectEvent event, EdsBaseRef object, EdsVoid* context) {
		ofLogVerbose() << "object event " << Eds::getObjectEventString(event);
		if(object) {
			if(event == kEdsObjectEvent_DirItemCreated) {
				((Camera*) context)->setDownloadImage(object);
			} else if(event == kEdsObjectEvent_DirItemRemoved) {
				// no need to release a removed item
			} else {
				try {
					Eds::SafeRelease(object);
				} catch (Eds::Exception& e) {
					ofLogError() << "Error while releasing EdsBaseRef inside handleObjectEvent()";
				}
			}
		}
		return EDS_ERR_OK;
	}

	EdsError EDSCALLBACK Camera::handlePropertyEvent(EdsPropertyEvent event, EdsPropertyID propertyId, EdsUInt32 param, EdsVoid* context) {
		ofLogVerbose() << "property event " << Eds::getPropertyEventString(event) << ": " << Eds::getPropertyIDString(propertyId) << " / " << param;
		if(propertyId == kEdsPropID_Evf_OutputDevice) {
			((Camera*) context)->setLiveReady(true);
		}
		return EDS_ERR_OK;
	}

	EdsError EDSCALLBACK Camera::handleCameraStateEvent(EdsStateEvent event, EdsUInt32 param, EdsVoid* context) {
		ofLogVerbose() << "camera state event " << Eds::getStateEventString(event) << ": " << param;
		if(event == kEdsStateEvent_WillSoonShutDown) {
			((Camera*) context)->setSendKeepAlive();
		}
		return EDS_ERR_OK;
	}

	Camera::Camera() :
	connected(false),
	liveReady(false),
	liveDataReady(false),
	frameNew(false),
	needToTakePhoto(false),
	photoNew(false),
	needToDecodePhoto(false),
	needToUpdatePhoto(false),
	photoDataReady(false),
	needToSendKeepAlive(false),
	needToDownloadImage(false),
#ifdef  TARGET_OSX
	bTryInitLiveView(false),
#endif
	resetIntervalMinutes(15) {
		liveBufferMiddle.resize(OFX_EDSDK_BUFFER_SIZE);
		for(int i = 0; i < liveBufferMiddle.maxSize(); i++) {
			liveBufferMiddle[i] = new ofBuffer();
		}
	}

	Camera::~Camera() {
		waitForThread();
		lock();
		if(connected) {
			if(liveReady) {
				Eds::EndLiveview(camera);
			}
			try {
				Eds::CloseSession(camera);
				Eds::TerminateSDK();
			} catch (Eds::Exception& e) {
				ofLogError() << "There was an error destroying ofxEds::Camera: " << e.what();
			}
		}
		unlock();
		for(int i = 0; i < liveBufferMiddle.maxSize(); i++) {
			delete liveBufferMiddle[i];
		}
	}

	bool Camera::setup(int deviceId) {
		try {
			Eds::InitializeSDK();

			EdsCameraListRef cameraList;
			Eds::GetCameraList(&cameraList);

			EdsUInt32 cameraCount;
			Eds::GetChildCount(cameraList, &cameraCount);

			if(cameraCount > 0) {
				EdsInt32 cameraIndex = deviceId;
				Eds::GetChildAtIndex(cameraList, cameraIndex, &camera);
				Eds::SetObjectEventHandler(camera, kEdsObjectEvent_All, handleObjectEvent, this);
				Eds::SetPropertyEventHandler(camera, kEdsPropertyEvent_All, handlePropertyEvent, this);
				Eds::SetCameraStateEventHandler(camera, kEdsStateEvent_All, handleCameraStateEvent, this);

				EdsDeviceInfo info;
				Eds::GetDeviceInfo(camera, &info);
				Eds::SafeRelease(cameraList);
				ofLogVerbose("ofxEdsdk::setup") << "connected camera model: " <<  info.szDeviceDescription << " " << info.szPortName << endl;

				startThread(true, false);
				return true;
			} else {
				ofLogError() << "No cameras are connected for ofxEds::Camera::setup().";
			}
		} catch (Eds::Exception& e) {
			ofLogError() << "There was an error during Camera::setup(): " << e.what();
		}
		return false;
	}

	void Camera::update() {
		if(connected){
#ifdef TARGET_OSX
			if (bTryInitLiveView) {
				if (ofGetElapsedTimeMillis() - initTime > OFX_EDSDK_LIVE_DELAY) {
					bTryInitLiveView = false;
					resetLiveView();
				}
			}
#endif
		lock();
		if(liveBufferMiddle.size() > 0) {
			// decoding the jpeg in the main thread allows the capture thread to run in a tighter loop.
			ofBuffer* middleFront = liveBufferMiddle.front();
			liveBufferFront.set(middleFront->getBinaryBuffer(), middleFront->size());
			liveBufferMiddle.pop();
			unlock();
			ofLoadImage(livePixels, liveBufferFront);
			if(liveTexture.getWidth() != livePixels.getWidth() ||
				 liveTexture.getHeight() != livePixels.getHeight()) {
				liveTexture.allocate(livePixels.getWidth(), livePixels.getHeight(), GL_RGB8);
			}
			liveTexture.loadData(livePixels);
			lock();
			liveDataReady = true;
			frameNew = true;
			unlock();
		} else {
			unlock();
		}
		}
	}

	bool Camera::isFrameNew() {
		if(frameNew) {
			frameNew = false;
			return true;
		} else {
			return false;
		}
	}

	bool Camera::isPhotoNew() {
		if(photoNew) {
			photoNew = false;
			return true;
		} else {
			return false;
		}
	}

	float Camera::getFrameRate() {
		float frameRate;
		lock();
		frameRate = fps.getFrameRate();
		unlock();
		return frameRate;
	}

	void Camera::takePhoto(bool blocking) {
		lock();
		needToTakePhoto = true;
		unlock();
		if(blocking) {
			while(!photoNew) {
				ofSleepMillis(10);
			}
		}
	}

	ofPixels& Camera::getLivePixels() {
		return livePixels;
	}

	ofPixels& Camera::getPhotoPixels() {
		if(needToDecodePhoto) {
			ofLoadImage(photoPixels, photoBuffer);
			needToDecodePhoto = false;
		}
		return photoPixels;
	}

	unsigned int Camera::getWidth() const {
		return livePixels.getWidth();
	}

	unsigned int Camera::getHeight() const {
		return livePixels.getHeight();
	}

	void Camera::draw(float x, float y) {
		draw(x, y, getWidth(), getHeight());
	}

	void Camera::draw(float x, float y, float width, float height) {
		if(liveDataReady) {
			liveTexture.draw(x, y, width, height);
		}
	}

	ofTexture& Camera::getLiveTexture() {
		return liveTexture;
	}

	void Camera::drawPhoto(float x, float y) {
		if(photoDataReady) {
			ofPixels& photoPixels = getPhotoPixels();
			draw(x, y, getWidth(), getHeight());
		}
	}

	void Camera::drawPhoto(float x, float y, float width, float height) {
		if(photoDataReady) {
            getPhotoTexture().draw(x, y, width, height);
		}
	}

	ofTexture& Camera::getPhotoTexture() {
		if(photoDataReady) {
			ofPixels& photoPixels = getPhotoPixels();
			if(needToUpdatePhoto) {
				if(photoTexture.getWidth() != photoPixels.getWidth() ||
					 photoTexture.getHeight() != photoPixels.getHeight()) {
					photoTexture.allocate(photoPixels.getWidth(), photoPixels.getHeight(), GL_RGB8);
				}
				photoTexture.loadData(photoPixels);
				needToUpdatePhoto = false;
			}
		}
		return photoTexture;
	}

	bool Camera::isLiveReady() const {
		return liveDataReady;
	}

	void Camera::setLiveReady(bool liveReady) {
		// this is done before the threaded loop starts
		this->liveReady = liveReady;
	}

	void Camera::setDownloadImage(EdsDirectoryItemRef directoryItem) {
		lock();
		this->directoryItem = directoryItem;
		needToDownloadImage = true;
		unlock();
	}

	void Camera::setSendKeepAlive() {
		lock();
		needToSendKeepAlive = true;
		unlock();
	}

	bool Camera::savePhoto(string filename) {
		return ofBufferToFile(filename, photoBuffer, true);
	}

	void Camera::resetLiveView() {
		lock();
		if(connected) {
			Eds::StartLiveview(camera);
			lastResetTime = ofGetElapsedTimef();
		}
		unlock();
	}

	void Camera::threadedFunction() {
#ifdef TARGET_OSX

		NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
#elif defined(TARGET_WIN32)
		CoInitializeEx( NULL, 0x0);// OINIT_MULTITHREADED );
#endif
		lock();
		try {
			Eds::OpenSession(camera);
			connected = true;
#ifdef TARGET_OSX
			bTryInitLiveView = true;
			initTime = ofGetElapsedTimeMillis();
#else
			Eds::StartLiveview(camera);
#endif
		} catch (Eds::Exception& e) {
			ofLogError() << "There was an error opening the camera, or starting live view: " << e.what();
			return;
		}
		lastResetTime = ofGetElapsedTimef();
		unlock();

		// threaded variables:
		// liveReady, liveBufferMiddle, liveBufferBack, fps, needToTakePhoto
		while(isThreadRunning()) {
			if(liveReady) {
				if(Eds::DownloadEvfData(camera, liveBufferBack)) {
					lock();
					ofBuffer* middleBack = liveBufferMiddle.back();
					middleBack->set(liveBufferBack.getBinaryBuffer(), liveBufferBack.size()); // liveBufferMiddle = liveBufferBack;
					liveBufferMiddle.push();
					fps.tick();
					unlock();
				}
			}

			if(needToTakePhoto) {
				try {
					Eds::SendCommand(camera, kEdsCameraCommand_TakePicture, 0);
					lock();
					needToTakePhoto = false;
					unlock();
				} catch (Eds::Exception& e) {
					ofLogError() << "Error while taking a picture: " << e.what();
				}
			}

			if(needToSendKeepAlive) {
				try {
					// always causes EDS_ERR_DEVICE_BUSY, even with live view disabled or a delay
					// but if it's not here, then the camera shuts down after 5 minutes.
					Eds::SendStatusCommand(camera, kEdsCameraCommand_ExtendShutDownTimer, 0);
				} catch (Eds::Exception& e) {
					ofLogError() << "Error while sending kEdsCameraCommand_ExtendShutDownTimer with Eds::SendStatusCommand: " << e.what();
				}
				lock();
				needToSendKeepAlive = false;
				unlock();
			}

			if(needToDownloadImage) {
				try {
					Eds::DownloadImage(directoryItem, photoBuffer);
					ofLogVerbose() << "Downloaded image: " << (int) (photoBuffer.size() / 1024) << " KB";
					lock();
					photoDataReady = true;
					photoNew = true;
					needToDecodePhoto = true;
					needToUpdatePhoto = true;
					needToDownloadImage = false;
					unlock();
				} catch (Eds::Exception& e) {
					ofLogError() << "Error while downloading image: " << e.what();
				}
			}

			float timeSinceLastReset = ofGetElapsedTimef() - lastResetTime;
			if(timeSinceLastReset > resetIntervalMinutes * 60) {
				resetLiveView();
			}

			// the t2i can run at 30 fps = 33 ms, so this might cause frame drops
			ofSleepMillis(5);
		}
#ifdef TARGET_OSX
		[pool drain];
#elif defined(TARGET_WIN32)
		CoUninitialize();
#endif
	}
}<commit_msg>Having the Eds::StartLiveView command sent in the thread was freezing the app (Tested w/ Canon SDK 2.14 and EOS Rebel T5i firmware 1.1.3).<commit_after>#include "ofxEdsdk.h"

/*
 This controls the size of liveBufferMiddle. If you are running at a low fps
 (lower than 30 fps), then it will effectively correspond to the latency of the
 camera. If you're running higher than 30 fps, it will determine how many frames
 you can miss without dropping one. For example, if you are running at 60 fps
 but one frame happens to last 200 ms, and your buffer size is 4, you will drop
 2 frames.
 */
#define OFX_EDSDK_BUFFER_SIZE 4
#define OFX_EDSDK_LIVE_DELAY 100
#ifdef TARGET_OSX
#include <Cocoa/Cocoa.h>
#elif defined(TARGET_WIN32)
#define _WIN32_DCOM
#include <objbase.h>
#endif
namespace ofxEdsdk {

	EdsError EDSCALLBACK Camera::handleObjectEvent(EdsObjectEvent event, EdsBaseRef object, EdsVoid* context) {
		ofLogVerbose() << "object event " << Eds::getObjectEventString(event);
		if(object) {
			if(event == kEdsObjectEvent_DirItemCreated) {
				((Camera*) context)->setDownloadImage(object);
			} else if(event == kEdsObjectEvent_DirItemRemoved) {
				// no need to release a removed item
			} else {
				try {
					Eds::SafeRelease(object);
				} catch (Eds::Exception& e) {
					ofLogError() << "Error while releasing EdsBaseRef inside handleObjectEvent()";
				}
			}
		}
		return EDS_ERR_OK;
	}

	EdsError EDSCALLBACK Camera::handlePropertyEvent(EdsPropertyEvent event, EdsPropertyID propertyId, EdsUInt32 param, EdsVoid* context) {
		ofLogVerbose() << "property event " << Eds::getPropertyEventString(event) << ": " << Eds::getPropertyIDString(propertyId) << " / " << param;
		if(propertyId == kEdsPropID_Evf_OutputDevice) {
			((Camera*) context)->setLiveReady(true);
		}
		return EDS_ERR_OK;
	}

	EdsError EDSCALLBACK Camera::handleCameraStateEvent(EdsStateEvent event, EdsUInt32 param, EdsVoid* context) {
		ofLogVerbose() << "camera state event " << Eds::getStateEventString(event) << ": " << param;
		if(event == kEdsStateEvent_WillSoonShutDown) {
			((Camera*) context)->setSendKeepAlive();
		}
		return EDS_ERR_OK;
	}

	Camera::Camera() :
	connected(false),
	liveReady(false),
	liveDataReady(false),
	frameNew(false),
	needToTakePhoto(false),
	photoNew(false),
	needToDecodePhoto(false),
	needToUpdatePhoto(false),
	photoDataReady(false),
	needToSendKeepAlive(false),
	needToDownloadImage(false),
#ifdef  TARGET_OSX
	bTryInitLiveView(false),
#endif
	resetIntervalMinutes(15) {
		liveBufferMiddle.resize(OFX_EDSDK_BUFFER_SIZE);
		for(int i = 0; i < liveBufferMiddle.maxSize(); i++) {
			liveBufferMiddle[i] = new ofBuffer();
		}
	}

	Camera::~Camera() {
		waitForThread();
		lock();
		if(connected) {
			if(liveReady) {
				Eds::EndLiveview(camera);
			}
			try {
				Eds::CloseSession(camera);
				Eds::TerminateSDK();
			} catch (Eds::Exception& e) {
				ofLogError() << "There was an error destroying ofxEds::Camera: " << e.what();
			}
		}
		unlock();
		for(int i = 0; i < liveBufferMiddle.maxSize(); i++) {
			delete liveBufferMiddle[i];
		}
	}

	bool Camera::setup(int deviceId) {
		try {
			Eds::InitializeSDK();

			EdsCameraListRef cameraList;
			Eds::GetCameraList(&cameraList);

			EdsUInt32 cameraCount;
			Eds::GetChildCount(cameraList, &cameraCount);

			if(cameraCount > 0) {
				EdsInt32 cameraIndex = deviceId;
				Eds::GetChildAtIndex(cameraList, cameraIndex, &camera);
				Eds::SetObjectEventHandler(camera, kEdsObjectEvent_All, handleObjectEvent, this);
				Eds::SetPropertyEventHandler(camera, kEdsPropertyEvent_All, handlePropertyEvent, this);
				Eds::SetCameraStateEventHandler(camera, kEdsStateEvent_All, handleCameraStateEvent, this);

				EdsDeviceInfo info;
				Eds::GetDeviceInfo(camera, &info);
				Eds::SafeRelease(cameraList);
				ofLogVerbose("ofxEdsdk::setup") << "connected camera model: " <<  info.szDeviceDescription << " " << info.szPortName << endl;

				startThread(true, false);
				return true;
			} else {
				ofLogError() << "No cameras are connected for ofxEds::Camera::setup().";
			}
		} catch (Eds::Exception& e) {
			ofLogError() << "There was an error during Camera::setup(): " << e.what();
		}
		return false;
	}

	void Camera::update() {
		if(connected){
#ifdef TARGET_OSX
			if (bTryInitLiveView) {
				if (ofGetElapsedTimeMillis() - initTime > OFX_EDSDK_LIVE_DELAY) {
					bTryInitLiveView = false;
					resetLiveView();
				}
			}
#endif
		lock();
		if(liveBufferMiddle.size() > 0) {
			// decoding the jpeg in the main thread allows the capture thread to run in a tighter loop.
			ofBuffer* middleFront = liveBufferMiddle.front();
			liveBufferFront.set(middleFront->getBinaryBuffer(), middleFront->size());
			liveBufferMiddle.pop();
			unlock();
			ofLoadImage(livePixels, liveBufferFront);
			if(liveTexture.getWidth() != livePixels.getWidth() ||
				 liveTexture.getHeight() != livePixels.getHeight()) {
				liveTexture.allocate(livePixels.getWidth(), livePixels.getHeight(), GL_RGB8);
			}
			liveTexture.loadData(livePixels);
			lock();
			liveDataReady = true;
			frameNew = true;
			unlock();
		} else {
			unlock();
		}
		}
	}

	bool Camera::isFrameNew() {
		if(frameNew) {
			frameNew = false;
			return true;
		} else {
			return false;
		}
	}

	bool Camera::isPhotoNew() {
		if(photoNew) {
			photoNew = false;
			return true;
		} else {
			return false;
		}
	}

	float Camera::getFrameRate() {
		float frameRate;
		lock();
		frameRate = fps.getFrameRate();
		unlock();
		return frameRate;
	}

	void Camera::takePhoto(bool blocking) {
		lock();
		needToTakePhoto = true;
		unlock();
		if(blocking) {
			while(!photoNew) {
				ofSleepMillis(10);
			}
		}
	}

	ofPixels& Camera::getLivePixels() {
		return livePixels;
	}

	ofPixels& Camera::getPhotoPixels() {
		if(needToDecodePhoto) {
			ofLoadImage(photoPixels, photoBuffer);
			needToDecodePhoto = false;
		}
		return photoPixels;
	}

	unsigned int Camera::getWidth() const {
		return livePixels.getWidth();
	}

	unsigned int Camera::getHeight() const {
		return livePixels.getHeight();
	}

	void Camera::draw(float x, float y) {
		draw(x, y, getWidth(), getHeight());
	}

	void Camera::draw(float x, float y, float width, float height) {
		if(liveDataReady) {
			liveTexture.draw(x, y, width, height);
		}
	}

	ofTexture& Camera::getLiveTexture() {
		return liveTexture;
	}

	void Camera::drawPhoto(float x, float y) {
		if(photoDataReady) {
			ofPixels& photoPixels = getPhotoPixels();
			draw(x, y, getWidth(), getHeight());
		}
	}

	void Camera::drawPhoto(float x, float y, float width, float height) {
		if(photoDataReady) {
            getPhotoTexture().draw(x, y, width, height);
		}
	}

	ofTexture& Camera::getPhotoTexture() {
		if(photoDataReady) {
			ofPixels& photoPixels = getPhotoPixels();
			if(needToUpdatePhoto) {
				if(photoTexture.getWidth() != photoPixels.getWidth() ||
					 photoTexture.getHeight() != photoPixels.getHeight()) {
					photoTexture.allocate(photoPixels.getWidth(), photoPixels.getHeight(), GL_RGB8);
				}
				photoTexture.loadData(photoPixels);
				needToUpdatePhoto = false;
			}
		}
		return photoTexture;
	}

	bool Camera::isLiveReady() const {
		return liveDataReady;
	}

	void Camera::setLiveReady(bool liveReady) {
		// this is done before the threaded loop starts
		this->liveReady = liveReady;
	}

	void Camera::setDownloadImage(EdsDirectoryItemRef directoryItem) {
		lock();
		this->directoryItem = directoryItem;
		needToDownloadImage = true;
		unlock();
	}

	void Camera::setSendKeepAlive() {
		lock();
		needToSendKeepAlive = true;
		unlock();
	}

	bool Camera::savePhoto(string filename) {
		return ofBufferToFile(filename, photoBuffer, true);
	}

	void Camera::resetLiveView() {
		if(connected) {
			Eds::StartLiveview(camera);
            lock();
			lastResetTime = ofGetElapsedTimef();
            unlock();
		}
	}

	void Camera::threadedFunction() {
#ifdef TARGET_OSX

		NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
#elif defined(TARGET_WIN32)
		CoInitializeEx( NULL, 0x0);// OINIT_MULTITHREADED );
#endif
		lock();
		try {
			Eds::OpenSession(camera);
			connected = true;
#ifdef TARGET_OSX
			bTryInitLiveView = true;
			initTime = ofGetElapsedTimeMillis();
#else
			Eds::StartLiveview(camera);
#endif
		} catch (Eds::Exception& e) {
			ofLogError() << "There was an error opening the camera, or starting live view: " << e.what();
			return;
		}
		lastResetTime = ofGetElapsedTimef();
		unlock();

		// threaded variables:
		// liveReady, liveBufferMiddle, liveBufferBack, fps, needToTakePhoto
		while(isThreadRunning()) {
			if(liveReady) {
				if(Eds::DownloadEvfData(camera, liveBufferBack)) {
					lock();
					ofBuffer* middleBack = liveBufferMiddle.back();
					middleBack->set(liveBufferBack.getBinaryBuffer(), liveBufferBack.size()); // liveBufferMiddle = liveBufferBack;
					liveBufferMiddle.push();
					fps.tick();
					unlock();
				}
			}

			if(needToTakePhoto) {
				try {
					Eds::SendCommand(camera, kEdsCameraCommand_TakePicture, 0);
					lock();
					needToTakePhoto = false;
					unlock();
				} catch (Eds::Exception& e) {
					ofLogError() << "Error while taking a picture: " << e.what();
				}
			}

			if(needToSendKeepAlive) {
				try {
					// always causes EDS_ERR_DEVICE_BUSY, even with live view disabled or a delay
					// but if it's not here, then the camera shuts down after 5 minutes.
					Eds::SendStatusCommand(camera, kEdsCameraCommand_ExtendShutDownTimer, 0);
				} catch (Eds::Exception& e) {
					ofLogError() << "Error while sending kEdsCameraCommand_ExtendShutDownTimer with Eds::SendStatusCommand: " << e.what();
				}
				lock();
				needToSendKeepAlive = false;
				unlock();
			}

			if(needToDownloadImage) {
				try {
					Eds::DownloadImage(directoryItem, photoBuffer);
					ofLogVerbose() << "Downloaded image: " << (int) (photoBuffer.size() / 1024) << " KB";
					lock();
					photoDataReady = true;
					photoNew = true;
					needToDecodePhoto = true;
					needToUpdatePhoto = true;
					needToDownloadImage = false;
					unlock();
				} catch (Eds::Exception& e) {
					ofLogError() << "Error while downloading image: " << e.what();
				}
			}

			float timeSinceLastReset = ofGetElapsedTimef() - lastResetTime;
			if(timeSinceLastReset > resetIntervalMinutes * 60) {
				resetLiveView();
			}

			// the t2i can run at 30 fps = 33 ms, so this might cause frame drops
			ofSleepMillis(5);
		}
#ifdef TARGET_OSX
		[pool drain];
#elif defined(TARGET_WIN32)
		CoUninitialize();
#endif
	}
}<|endoftext|>


<commit_before>#include "Log.hpp"
#include <sstream>

namespace xveearr
{

inline Log::Log(const char* level, const char* file, unsigned int line)
	:mLevel(level)
	,mFile(file)
	,mLine(line)
{
	std::stringstream ss;
	ss << mFile << ":" << mLine;
	std::cout << std::left
		<< "[" << std::setw(6) << mLevel << std::setw(0) << "] @ "
		<< std::setw(25) << ss.str() << std::setw(0) << std::internal
		<< ": ";
}

inline Log::~Log()
{
	std::cout << std::endl;
}

template<typename T>
inline Log& Log::operator,(const T& msg)
{
	return (*this) << msg;
}

template<typename T>
inline Log& Log::operator<<(const T& msg)
{
	std::cout << msg;
	return *this;
}

}
<commit_msg>Change width of log level label<commit_after>#include "Log.hpp"
#include <sstream>

namespace xveearr
{

inline Log::Log(const char* level, const char* file, unsigned int line)
	:mLevel(level)
	,mFile(file)
	,mLine(line)
{
	std::stringstream ss;
	ss << mFile << ":" << mLine;
	std::cout << std::left
		<< "[" << std::setw(5) << mLevel << std::setw(0) << "] @ "
		<< std::setw(25) << ss.str() << std::setw(0) << std::internal
		<< ": ";
}

inline Log::~Log()
{
	std::cout << std::endl;
}

template<typename T>
inline Log& Log::operator,(const T& msg)
{
	return (*this) << msg;
}

template<typename T>
inline Log& Log::operator<<(const T& msg)
{
	std::cout << msg;
	return *this;
}

}
<|endoftext|>