<commit_before>#include "SaveIdea.h"

SaveIdea::SaveIdea(float mainX, float mainY, int currentID)
	:	BWindow(BRect(0, 0, 308, 75), "Save As", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE)
{
	BRect textFrame(0, 0, 300, 10);
	titleText = new BTextView(textFrame, NULL, textFrame, B_FOLLOW_LEFT_RIGHT, B_WILL_DRAW);
	titleText->MakeResizable(false);
	titleText->SetWordWrap(false);
	titleString = new BStringView(BRect(10, 10, 200, 30), NULL, "Enter Thought Title:");
	saveButton = new BButton(BRect(190, 50, 270, 75), NULL, "Save", new BMessage(SAVE_IDEA));
	cancelButton = new BButton(BRect(190, 50, 270, 75), NULL, "Cancel", new BMessage(CANCEL_SAVE));
	backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
	backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(backView);

	backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
	backView->AddChild(BGridLayoutBuilder()
		//.Add(titleString, 0, 0, 2, 1)
		.Add(titleText, 0, 0, 2, 1)
		//.Add(BSpaceLayoutItem::CreateVerticalStrut(1.0), 0, 1, 2, 1)
		.Add(cancelButton, 0, 1)
		.Add(saveButton, 1, 1)
		.SetInsets(2, 2, 2, 2)
	);
	MoveTo(mainX, mainY);
}
void SaveIdea::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		default:
			BWindow::MessageReceived(msg);
			break;
	}
}
<commit_msg>got the layout right for saveidea<commit_after>#include "SaveIdea.h"

SaveIdea::SaveIdea(float mainX, float mainY, int currentID)
	:	BWindow(BRect(0, 0, 358, 60), "Save As", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE)
{
	BRect textFrame(0, 0, 300, 10);
	titleText = new BTextView(textFrame, NULL, textFrame, B_FOLLOW_LEFT_RIGHT, B_WILL_DRAW);
	titleText->MakeResizable(false);
	titleText->SetWordWrap(false);
	titleString = new BStringView(BRect(10, 10, 200, 30), NULL, "Enter Thought Title:");
	saveButton = new BButton(BRect(190, 50, 270, 75), NULL, "Save", new BMessage(SAVE_IDEA));
	cancelButton = new BButton(BRect(190, 50, 270, 75), NULL, "Cancel", new BMessage(CANCEL_SAVE));
	backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
	backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	AddChild(backView);

	backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
	backView->AddChild(BGridLayoutBuilder()
		.Add(titleString, 0, 0, 2, 1)
		.Add(titleText, 2, 0, 3, 1)
		.Add(cancelButton, 3, 1)
		.Add(saveButton, 4, 1)
		.Add(BSpaceLayoutItem::CreateGlue(), 0, 2, 2, 1)
		.SetInsets(2, 5, 2, 2)
	);
	MoveTo(mainX, mainY);
}
void SaveIdea::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		case SAVE_IDEA:
			this->Close();
			break;
		case CANCEL_SAVE:
			this->Close();
			break;
		default:
			BWindow::MessageReceived(msg);
			break;
	}
}
<|endoftext|>


<commit_before>/* Copyright © 2001-2015, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

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

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "realtime.h"
#include "utils/logger.h"
#include "type/data.h"
#include "type/pt_data.h"
#include "type/meta_data.h"
#include "kraken/apply_disruption.h"

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/make_shared.hpp>
#include <boost/optional.hpp>

namespace navitia {

static bool is_handleable(const transit_realtime::TripUpdate& trip_update){
    // Case 1: the trip is cancelled
    if (trip_update.trip().schedule_relationship() == transit_realtime::TripDescriptor_ScheduleRelationship_CANCELED) {
        return true;
    }
    // Case 2: the trip is not cancelled, but modified (ex: the train's arrival is delayed or the train's
    // departure is brought foward), we check the size of stop_time_update because we can't find a proper
    // enum in gtfs-rt proto to express this idea
    if (trip_update.trip().schedule_relationship() == transit_realtime::TripDescriptor_ScheduleRelationship_SCHEDULED
            && trip_update.stop_time_update_size()) {
        return true;
    }
    return false;
}

static boost::shared_ptr<nt::disruption::Severity>
make_severity(const std::string& id,
              std::string wording,
              nt::disruption::Effect effect,
              const boost::posix_time::ptime& timestamp,
              nt::disruption::DisruptionHolder& holder) {
    auto& weak_severity = holder.severities[id];
    if (auto severity = weak_severity.lock()) { return severity; }

    auto severity = boost::make_shared<nt::disruption::Severity>();
    severity->uri = id;
    severity->wording = std::move(wording);
    severity->created_at = timestamp;
    severity->updated_at = timestamp;
    severity->color = "#000000";
    severity->priority = 42;
    severity->effect = effect;

    weak_severity = severity;
    return severity;
}

static boost::posix_time::time_period
execution_period(const boost::gregorian::date& date, const nt::MetaVehicleJourney& mvj) {
    auto running_vj = mvj.get_vj_at_date(type::RTLevel::Base, date);
    if (running_vj) {
        return running_vj->execution_period(date);
    }
    // If there is no running vj at this date, we return a null period (begin == end)
    return {boost::posix_time::ptime{date}, boost::posix_time::ptime{date}};
}

static const type::disruption::Disruption&
create_disruption(const std::string& id,
                  const boost::posix_time::ptime& timestamp,
                  const transit_realtime::TripUpdate& trip_update,
                  const type::Data& data) {
    auto log = log4cplus::Logger::getInstance("realtime");
    LOG4CPLUS_DEBUG(log, "Creating disruption");

    nt::disruption::DisruptionHolder& holder = data.pt_data->disruption_holder;
    auto circulation_date = boost::gregorian::from_undelimited_string(trip_update.trip().start_date());
    const auto& mvj = *data.pt_data->meta_vjs.get_mut(trip_update.trip().trip_id());

    delete_disruption(id, *data.pt_data, *data.meta);
    auto& disruption = holder.make_disruption(id, type::RTLevel::RealTime);
    disruption.reference = disruption.uri;
    disruption.publication_period = data.meta->production_period();
    disruption.created_at = timestamp;
    disruption.updated_at = timestamp;
    // cause
    {// impact
        auto impact = boost::make_shared<nt::disruption::Impact>();
        impact->uri = disruption.uri;
        impact->created_at = timestamp;
        impact->updated_at = timestamp;
        impact->application_periods.push_back(execution_period(circulation_date, mvj));
        std::string wording;
        nt::disruption::Effect effect;
        if (trip_update.trip().schedule_relationship() == transit_realtime::TripDescriptor_ScheduleRelationship_CANCELED) {
            LOG4CPLUS_TRACE(log, "Disruption has NO_SERVICE effect");
            // Yeah, that's quite hardcodded...
            wording = "trip canceled!";
            effect = nt::disruption::Effect::NO_SERVICE;
        }
        else if (trip_update.trip().schedule_relationship() == transit_realtime::TripDescriptor_ScheduleRelationship_SCHEDULED
                && trip_update.stop_time_update_size()) {
            LOG4CPLUS_TRACE(log, "Disruption has MODIFIED_SERVICE effect");
            // Yeah, that's quite hardcodded...
            wording = "trip modified!";
            effect = nt::disruption::Effect::MODIFIED_SERVICE;
            LOG4CPLUS_TRACE(log, "Adding stop time into impact");
            for (const auto& st: trip_update.stop_time_update()) {
                auto* stop_point_ptr = data.pt_data->stop_points_map[st.stop_id()];
                assert(stop_point_ptr);
                uint32_t arrival_time = st.arrival().time();
                uint32_t departure_time = st.departure().time();
                LOG4CPLUS_TRACE(log, "arrival_time: " + std::to_string(arrival_time));
                LOG4CPLUS_TRACE(log, "has_arrival_time: " + std::to_string(st.arrival().has_time()));

                LOG4CPLUS_TRACE(log, "departure_time: " + std::to_string(departure_time));
                LOG4CPLUS_TRACE(log, "has_departure_time: " + std::to_string(st.departure().has_time()));

                /***********************************************************/
                /*
                 * When st.arrival().has_time() is false, st.arrival().time() will return 0, which, for kraken, is
                 * considered as 00:00(midnight), This is not good. So we set manually arrival_time to  departure_time.
                 *
                 * AND
                 *
                 * Sometimes we got st.arrival().has_time() is true, but st.arrival().time() returns 0. That's not good
                 * either.
                 *
                 * Same reasoning for departure_time.
                 *
                 *
                 * TODO: And this check should be done on Kirin's side...
                 * */
                if (! st.arrival().has_time() && st.departure().has_time()){
                    arrival_time = departure_time = st.departure().time();
                }
                if (st.arrival().has_time() && ! st.departure().has_time()){
                    departure_time = arrival_time =st.arrival().time();
                }
                /***********************************************************/

                auto arrival_seconds = boost::posix_time::from_time_t(arrival_time).time_of_day().total_seconds();
                auto departure_seconds = boost::posix_time::from_time_t(departure_time).time_of_day().total_seconds();

                type::StopTime stop_time{static_cast<uint32_t>(arrival_seconds),
                    static_cast<uint32_t>(departure_seconds), stop_point_ptr};
                stop_time.set_pick_up_allowed(st.departure().has_time());
                stop_time.set_drop_off_allowed(st.arrival().has_time());
                impact->aux_info.stop_times.emplace_back(std::move(stop_time));
           }
        }else {
            LOG4CPLUS_ERROR(log, "unhandled real time message");
            throw navitia::exception("Effect of disruption is unknown");
        }
        impact->severity = make_severity(id, std::move(wording), effect, timestamp, holder);
        impact->informed_entities.push_back(
            make_pt_obj(nt::Type_e::MetaVehicleJourney, trip_update.trip().trip_id(), *data.pt_data, impact));
        // messages
        disruption.add_impact(std::move(impact));
    }
    // localization
    // tags
    // note

    LOG4CPLUS_DEBUG(log, "Disruption added");
    return disruption;
}

void handle_realtime(const std::string& id,
                     const boost::posix_time::ptime& timestamp,
                     const transit_realtime::TripUpdate& trip_update,
                     const type::Data& data) {
    auto log = log4cplus::Logger::getInstance("realtime");
    LOG4CPLUS_TRACE(log, "realtime trip update received");

    if (! is_handleable(trip_update)) {
        LOG4CPLUS_DEBUG(log, "unhandled real time message");
        return;
    }

    auto meta_vj = data.pt_data->meta_vjs.get_mut(trip_update.trip().trip_id());
    if (! meta_vj) {
        LOG4CPLUS_ERROR(log, "unknown vehicle journey " << trip_update.trip().trip_id());
        // TODO for trip().ADDED, we'll need to create a new VJ
        return;
    }

    const auto& disruption = create_disruption(id, timestamp, trip_update, data);

    apply_disruption(disruption, *data.pt_data, *data.meta);
}

}
<commit_msg>reindentation<commit_after>/* Copyright © 2001-2015, Canal TP and/or its affiliates. All rights reserved.

This file is part of Navitia,
    the software to build cool stuff with public transport.

Hope you'll enjoy and contribute to this project,
    powered by Canal TP (www.canaltp.fr).
Help us simplify mobility and open public transport:
    a non ending quest to the responsive locomotion way of traveling!

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

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

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

Stay tuned using
twitter @navitia
IRC #navitia on freenode
https://groups.google.com/d/forum/navitia
www.navitia.io
*/
#include "realtime.h"
#include "utils/logger.h"
#include "type/data.h"
#include "type/pt_data.h"
#include "type/meta_data.h"
#include "kraken/apply_disruption.h"

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/make_shared.hpp>
#include <boost/optional.hpp>

namespace navitia {

static bool is_handleable(const transit_realtime::TripUpdate& trip_update){
    // Case 1: the trip is cancelled
    if (trip_update.trip().schedule_relationship() == transit_realtime::TripDescriptor_ScheduleRelationship_CANCELED) {
        return true;
    }
    // Case 2: the trip is not cancelled, but modified (ex: the train's arrival is delayed or the train's
    // departure is brought foward), we check the size of stop_time_update because we can't find a proper
    // enum in gtfs-rt proto to express this idea
    if (trip_update.trip().schedule_relationship() == transit_realtime::TripDescriptor_ScheduleRelationship_SCHEDULED
            && trip_update.stop_time_update_size()) {
        return true;
    }
    return false;
}

static boost::shared_ptr<nt::disruption::Severity>
make_severity(const std::string& id,
              std::string wording,
              nt::disruption::Effect effect,
              const boost::posix_time::ptime& timestamp,
              nt::disruption::DisruptionHolder& holder) {
    auto& weak_severity = holder.severities[id];
    if (auto severity = weak_severity.lock()) { return severity; }

    auto severity = boost::make_shared<nt::disruption::Severity>();
    severity->uri = id;
    severity->wording = std::move(wording);
    severity->created_at = timestamp;
    severity->updated_at = timestamp;
    severity->color = "#000000";
    severity->priority = 42;
    severity->effect = effect;

    weak_severity = severity;
    return severity;
}

static boost::posix_time::time_period
execution_period(const boost::gregorian::date& date, const nt::MetaVehicleJourney& mvj) {
    auto running_vj = mvj.get_vj_at_date(type::RTLevel::Base, date);
    if (running_vj) {
        return running_vj->execution_period(date);
    }
    // If there is no running vj at this date, we return a null period (begin == end)
    return {boost::posix_time::ptime{date}, boost::posix_time::ptime{date}};
}

static const type::disruption::Disruption&
create_disruption(const std::string& id,
                  const boost::posix_time::ptime& timestamp,
                  const transit_realtime::TripUpdate& trip_update,
                  const type::Data& data) {
    auto log = log4cplus::Logger::getInstance("realtime");
    LOG4CPLUS_DEBUG(log, "Creating disruption");

    nt::disruption::DisruptionHolder& holder = data.pt_data->disruption_holder;
    auto circulation_date = boost::gregorian::from_undelimited_string(trip_update.trip().start_date());
    const auto& mvj = *data.pt_data->meta_vjs.get_mut(trip_update.trip().trip_id());

    delete_disruption(id, *data.pt_data, *data.meta);
    auto& disruption = holder.make_disruption(id, type::RTLevel::RealTime);
    disruption.reference = disruption.uri;
    disruption.publication_period = data.meta->production_period();
    disruption.created_at = timestamp;
    disruption.updated_at = timestamp;
    // cause
    {// impact
        auto impact = boost::make_shared<nt::disruption::Impact>();
        impact->uri = disruption.uri;
        impact->created_at = timestamp;
        impact->updated_at = timestamp;
        impact->application_periods.push_back(execution_period(circulation_date, mvj));
        std::string wording;
        nt::disruption::Effect effect;
        if (trip_update.trip().schedule_relationship() == transit_realtime::TripDescriptor_ScheduleRelationship_CANCELED) {
            LOG4CPLUS_TRACE(log, "Disruption has NO_SERVICE effect");
            // Yeah, that's quite hardcodded...
            wording = "trip canceled!";
            effect = nt::disruption::Effect::NO_SERVICE;
        }
        else if (trip_update.trip().schedule_relationship() == transit_realtime::TripDescriptor_ScheduleRelationship_SCHEDULED
                && trip_update.stop_time_update_size()) {
            LOG4CPLUS_TRACE(log, "Disruption has MODIFIED_SERVICE effect");
            // Yeah, that's quite hardcodded...
            wording = "trip modified!";
            effect = nt::disruption::Effect::MODIFIED_SERVICE;
            LOG4CPLUS_TRACE(log, "Adding stop time into impact");
            for (const auto& st: trip_update.stop_time_update()) {
                auto* stop_point_ptr = data.pt_data->stop_points_map[st.stop_id()];
                assert(stop_point_ptr);
                uint32_t arrival_time = st.arrival().time();
                uint32_t departure_time = st.departure().time();
                LOG4CPLUS_TRACE(log, "arrival_time: " + std::to_string(arrival_time));
                LOG4CPLUS_TRACE(log, "has_arrival_time: " + std::to_string(st.arrival().has_time()));

                LOG4CPLUS_TRACE(log, "departure_time: " + std::to_string(departure_time));
                LOG4CPLUS_TRACE(log, "has_departure_time: " + std::to_string(st.departure().has_time()));
                {
                    /*
                     * When st.arrival().has_time() is false, st.arrival().time() will return 0, which, for kraken, is
                     * considered as 00:00(midnight), This is not good. So we set manually arrival_time to  departure_time.
                     *
                     * Same reasoning for departure_time.
                     *
                     *
                     * TODO: And this check should be done on Kirin's side...
                     * */
                    if (! st.arrival().has_time() && st.departure().has_time()){
                        arrival_time = departure_time = st.departure().time();
                    }
                    if (st.arrival().has_time() && ! st.departure().has_time()){
                        departure_time = arrival_time =st.arrival().time();
                    }
                }
                auto arrival_seconds = boost::posix_time::from_time_t(arrival_time).time_of_day().total_seconds();
                auto departure_seconds = boost::posix_time::from_time_t(departure_time).time_of_day().total_seconds();

                type::StopTime stop_time{static_cast<uint32_t>(arrival_seconds),
                    static_cast<uint32_t>(departure_seconds), stop_point_ptr};
                stop_time.set_pick_up_allowed(st.departure().has_time());
                stop_time.set_drop_off_allowed(st.arrival().has_time());
                impact->aux_info.stop_times.emplace_back(std::move(stop_time));
           }
        }else {
            LOG4CPLUS_ERROR(log, "unhandled real time message");
        }
        impact->severity = make_severity(id, std::move(wording), effect, timestamp, holder);
        impact->informed_entities.push_back(
            make_pt_obj(nt::Type_e::MetaVehicleJourney, trip_update.trip().trip_id(), *data.pt_data, impact));
        // messages
        disruption.add_impact(std::move(impact));
    }
    // localization
    // tags
    // note

    LOG4CPLUS_DEBUG(log, "Disruption added");
    return disruption;
}

void handle_realtime(const std::string& id,
                     const boost::posix_time::ptime& timestamp,
                     const transit_realtime::TripUpdate& trip_update,
                     const type::Data& data) {
    auto log = log4cplus::Logger::getInstance("realtime");
    LOG4CPLUS_TRACE(log, "realtime trip update received");

    if (! is_handleable(trip_update)) {
        LOG4CPLUS_DEBUG(log, "unhandled real time message");
        return;
    }

    auto meta_vj = data.pt_data->meta_vjs.get_mut(trip_update.trip().trip_id());
    if (! meta_vj) {
        LOG4CPLUS_ERROR(log, "unknown vehicle journey " << trip_update.trip().trip_id());
        // TODO for trip().ADDED, we'll need to create a new VJ
        return;
    }

    const auto& disruption = create_disruption(id, timestamp, trip_update, data);

    apply_disruption(disruption, *data.pt_data, *data.meta);
}

}
<|endoftext|>


<commit_before>#ifndef RECURSE_HPP
#define RECURSE_HPP

#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QHash>
#include <QStringBuilder>
#include <QVector>
#include "request.hpp"
#include "response.hpp"

#include <functional>
using std::function;
using std::bind;
using std::ref;

typedef function<void(Request &request, Response &response, function<void()> next)> next_f;

//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
public:

    Recurse(int & argc, char ** argv, QObject *parent = NULL);
    ~Recurse();

    bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
    void use(next_f next);

private:
    QCoreApplication app;
    QTcpServer m_tcp_server;

    quint64 m_port;
    QVector<next_f> m_middleware;
    int current_middleware = 0;
    void m_next(int &socket_id);
    void http_parse(Request &request);
    QString http_build_header(const Response &response);

    struct Client {
        QTcpSocket *socket;
        Request request;
        Response response;
    };

    QHash<int, Client> connections;
};

Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
    Q_UNUSED(parent);
};

Recurse::~Recurse()
{

};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
bool Recurse::listen(quint64 port, QHostAddress address)
{
    m_port = port;
    int bound = m_tcp_server.listen(address, port);
    if (!bound)
        return false;

    connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
        qDebug() << "client connected";
        int socket_id = rand();

        connections[socket_id] = {
             m_tcp_server.nextPendingConnection()
        };

        connect(connections[socket_id].socket, &QTcpSocket::readyRead, [this, socket_id] {
            connections[socket_id].request.data = connections[socket_id].socket->readAll();
            http_parse(connections[socket_id].request);

            qDebug() << "client request: " << connections[socket_id].request.data;

            if (m_middleware.count() > 0)
                m_middleware[current_middleware](
                    connections[socket_id].request,
                    connections[socket_id].response,
                    bind(&Recurse::m_next, this, socket_id));

            current_middleware = 0;
            QString header;

            connections[socket_id].response.method = connections[socket_id].request.method;
            connections[socket_id].response.proto = connections[socket_id].request.proto;

            if (connections[socket_id].response.status == 0)
                connections[socket_id].response.status = 200;

            header = http_build_header(connections[socket_id].response);
            QString response_data = header + connections[socket_id].response.body;

            // send response to the client
            qint64 check = connections[socket_id].socket->write(
                response_data.toStdString().c_str(),
                response_data.size());

            qDebug() << "socket write debug:" << check;
            connections[socket_id].socket->close();
            connections.remove(socket_id);
        });
    });

    return app.exec();
};

//!
//! \brief Recurse::m_next
//! call next middleware
//!
void Recurse::m_next(int &socket_id)
{
    qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size();

    if (++current_middleware >= m_middleware.size()) {
        return;
    };

    m_middleware[current_middleware](
        connections[socket_id].request,
        connections[socket_id].response,
        bind(&Recurse::m_next, this, socket_id));
};

//!
//! \brief Recurse::use
//! add new middleware
//!
//! \param f middleware function that will be called later
//!
void Recurse::use(next_f f)
{
    m_middleware.push_back(f);
};

//!
//! \brief Recurse::http_parse
//! parse http data
//!
//! \param data reference to data received from the tcp connection
//!
void Recurse::http_parse(Request &request)
{
    QStringList data_list = request.data.split("\r\n");
    bool is_body = false;

    for (int i = 0; i < data_list.size(); ++i) {
        if (is_body) {
            request.body.append(data_list.at(i));
            continue;
        }

        QStringList entity_item = data_list.at(i).split(":");

        if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body) {
            is_body = true;
            continue;
        }
        else if (i == 0 && entity_item.length() < 2) {
            QStringList first_line = entity_item.at(0).split(" ");
            request.method = first_line.at(0);
            request.url = first_line.at(1).trimmed();
            request.proto = first_line.at(2).trimmed();
            continue;
        }

        request.header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed();
    }

    qDebug() << "request object populated: " << request.method << request.url << request.header << request.proto << request.body;
};

//!
//! \brief Recurse::http_build_header
//! build http header for response
//!
//! \param response reference to the Response instance
//!
QString Recurse::http_build_header(const Response &response)
{
    QString header = response.proto % " " % QString::number(response.status) % " "
        % response.http_codes[response.status] % "\r\n";

    // set default header fields
    QHash<QString, QString>::const_iterator i;

    for (i = response.default_headers.constBegin(); i != response.default_headers.constEnd(); ++i) {
        if (i.key() == "content-length" && response.header[i.key()] == "")
            header += i.key() % ": " % QString::number(response.body.size()) % "\r\n";
        else if (response.header[i.key()] == "")
            header += i.key() % ": " % i.value() % "\r\n";
    }

    // set user-defined header fields
    QHash<QString, QString>::const_iterator j;

    for (j = response.header.constBegin(); j != response.header.constEnd(); ++j) {
        header += j.key() % ": " % j.value() % "\r\n";
    }

    qDebug() << "response header" << header;

    return header + "\r\n";
}

#endif // RECURSE_HPP
<commit_msg>append request body until it's at least the size as content-length<commit_after>#ifndef RECURSE_HPP
#define RECURSE_HPP

#include <QCoreApplication>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QHash>
#include <QStringBuilder>
#include <QVector>
#include "request.hpp"
#include "response.hpp"

#include <functional>
using std::function;
using std::bind;
using std::ref;

typedef function<void(Request &request, Response &response, function<void()> next)> next_f;

//!
//! \brief The Recurse class
//! main class of the app
//!
class Recurse : public QObject
{
public:

    Recurse(int & argc, char ** argv, QObject *parent = NULL);
    ~Recurse();

    bool listen(quint64 port, QHostAddress address = QHostAddress::Any);
    void use(next_f next);

private:
    QCoreApplication app;
    QTcpServer m_tcp_server;

    quint64 m_port;
    QVector<next_f> m_middleware;
    int current_middleware = 0;
    void m_next(int &socket_id);
    void http_parse(Request &request);
    QString http_build_header(const Response &response);
    QRegExp httpRx = QRegExp("^(?=[A-Z]).* \\/.* HTTP\\/[0-9]\\.[0-9]\\r\\n");

    struct Client {
        QTcpSocket *socket;
        Request request;
        Response response;
    };

    QHash<int, Client> connections;
};

Recurse::Recurse(int & argc, char ** argv, QObject *parent) : app(argc, argv)
{
    Q_UNUSED(parent);
};

Recurse::~Recurse()
{

};

//!
//! \brief Recurse::listen
//! listen for tcp requests
//!
//! \param port tcp server port
//! \param address tcp server listening address
//!
//! \return true on success
//!
bool Recurse::listen(quint64 port, QHostAddress address)
{
    m_port = port;
    int bound = m_tcp_server.listen(address, port);
    if (!bound)
        return false;

    connect(&m_tcp_server, &QTcpServer::newConnection, [this] {
        qDebug() << "client connected";
        int socket_id = rand();

        connections[socket_id] = {
             m_tcp_server.nextPendingConnection()
        };

        connect(connections[socket_id].socket, &QTcpSocket::readyRead, [this, socket_id] {
            connections[socket_id].request.data += connections[socket_id].socket->readAll();
            qDebug() << "client request: " << connections[socket_id].request.data;

            http_parse(connections[socket_id].request);

            if (connections[socket_id].request.body_length
                < connections[socket_id].request.header["content-length"].toInt())
                    return;

            if (m_middleware.count() > 0)
                m_middleware[current_middleware](
                    connections[socket_id].request,
                    connections[socket_id].response,
                    bind(&Recurse::m_next, this, socket_id));

            current_middleware = 0;
            QString header;

            connections[socket_id].response.method = connections[socket_id].request.method;
            connections[socket_id].response.proto = connections[socket_id].request.proto;

            if (connections[socket_id].response.status == 0)
                connections[socket_id].response.status = 200;

            header = http_build_header(connections[socket_id].response);
            QString response_data = header + connections[socket_id].response.body;

            // send response to the client
            qint64 check = connections[socket_id].socket->write(
                response_data.toStdString().c_str(),
                response_data.size());

            qDebug() << "socket write debug:" << check;
            connections[socket_id].socket->close();
            connections.remove(socket_id);
        });
    });

    return app.exec();
};

//!
//! \brief Recurse::m_next
//! call next middleware
//!
void Recurse::m_next(int &socket_id)
{
    qDebug() << "calling next:" << current_middleware << " num:" << m_middleware.size();

    if (++current_middleware >= m_middleware.size()) {
        return;
    };

    m_middleware[current_middleware](
        connections[socket_id].request,
        connections[socket_id].response,
        bind(&Recurse::m_next, this, socket_id));
};

//!
//! \brief Recurse::use
//! add new middleware
//!
//! \param f middleware function that will be called later
//!
void Recurse::use(next_f f)
{
    m_middleware.push_back(f);
};

//!
//! \brief Recurse::http_parse
//! parse http data
//!
//! \param data reference to data received from the tcp connection
//!
void Recurse::http_parse(Request &request)
{
    // if no header is present, just append all data to request.body
    if (!request.data.contains(httpRx)) {
        request.body.append(request.data);
        return;
    }

    QStringList data_list = request.data.split("\r\n");
    bool is_body = false;

    for (int i = 0; i < data_list.size(); ++i) {
        if (is_body) {
            request.body.append(data_list.at(i));
            request.body_length += request.body.size();
            continue;
        }

        QStringList entity_item = data_list.at(i).split(":");

        if (entity_item.length() < 2 && entity_item.at(0).size() < 1 && !is_body) {
            is_body = true;
            continue;
        }
        else if (i == 0 && entity_item.length() < 2) {
            QStringList first_line = entity_item.at(0).split(" ");
            request.method = first_line.at(0);
            request.url = first_line.at(1).trimmed();
            request.proto = first_line.at(2).trimmed();
            continue;
        }

        request.header[entity_item.at(0).toLower()] = entity_item.at(1).trimmed();
    }

    qDebug() << "request object populated: "
        << request.method << request.url << request.header << request.proto << request.body
        << request.body_length;
};

//!
//! \brief Recurse::http_build_header
//! build http header for response
//!
//! \param response reference to the Response instance
//!
QString Recurse::http_build_header(const Response &response)
{
    QString header = response.proto % " " % QString::number(response.status) % " "
        % response.http_codes[response.status] % "\r\n";

    // set default header fields
    QHash<QString, QString>::const_iterator i;

    for (i = response.default_headers.constBegin(); i != response.default_headers.constEnd(); ++i) {
        if (i.key() == "content-length" && response.header[i.key()] == "")
            header += i.key() % ": " % QString::number(response.body.size()) % "\r\n";
        else if (response.header[i.key()] == "")
            header += i.key() % ": " % i.value() % "\r\n";
    }

    // set user-defined header fields
    QHash<QString, QString>::const_iterator j;

    for (j = response.header.constBegin(); j != response.header.constEnd(); ++j) {
        header += j.key() % ": " % j.value() % "\r\n";
    }

    qDebug() << "response header" << header;

    return header + "\r\n";
}

#endif // RECURSE_HPP
<|endoftext|>


<commit_before>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define STRICT_GS_ENABLED
#define _CRTDBG_MAP_ALLOC
#include <windows.h>
#include <pathcch.h>
#include <shlwapi.h>
#include <winioctl.h>
#include <clocale>
#include <cstdio>
#include <memory>
#include <crtdbg.h>
#include "banned.h"
#pragma comment(lib, "pathcch")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "user32")

std::unique_ptr<WCHAR[]> GetWindowsError( ULONG error_code = GetLastError() )
{
	auto msg = std::make_unique<WCHAR[]>( USHRT_MAX );
	if( FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error_code, 0, msg.get(), USHRT_MAX, nullptr ) )
	{
		return msg;
	}
	return nullptr;
}
void PrintfWindowsError( ULONG error_code = GetLastError() )
{
	if( auto error_msg = GetWindowsError( error_code ) )
	{
		fprintf( stderr, "%ls\n", error_msg.get() );
	}
}
void PrintUsage()
{
	fprintf(
		stderr,
		"Copy file without actual data write.\n"
		"\n"
		"%ls source destination\n"
		"\n"
		"source       Specifies a file to copy.\n"
		"             source must have placed on the ReFS volume.\n"
		"destination  Specifies new file name.\n"
		"             destination must have placed on the same volume as source.\n",
		PathFindFileNameW( __wargv[0] )
		);
}
std::unique_ptr<bool> CheckReFSVersion( PCWSTR on_volume_path )
{
	auto mount_point = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	if( !GetVolumePathNameW( on_volume_path, mount_point.get(), PATHCCH_MAX_CCH ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	WCHAR guid_path[50];
	if( !GetVolumeNameForVolumeMountPointW( mount_point.get(), guid_path, ARRAYSIZE( guid_path ) ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	PWCHAR end_bslash;
	if( FAILED( PathCchRemoveBackslashEx( guid_path, ARRAYSIZE( guid_path ), &end_bslash, nullptr ) ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	*end_bslash = L'\0';
	auto volume = CreateFileW( guid_path, FILE_EXECUTE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr );
	if( volume == INVALID_HANDLE_VALUE )
	{
		PrintfWindowsError();
		return nullptr;
	}
	ULONG dummy;
	REFS_VOLUME_DATA_BUFFER refs_info;
	if( DeviceIoControl( volume, FSCTL_GET_REFS_VOLUME_DATA, nullptr, 0, &refs_info, sizeof refs_info, &dummy, nullptr ) )
	{
		fprintf( stderr, "%ls is ReFS %lu.%lu\n", mount_point.get(), refs_info.MajorVersion, refs_info.MinorVersion );
		if( refs_info.MajorVersion < 1 || ( refs_info.MajorVersion == 1 && refs_info.MinorVersion <= 2 ) )
		{
			return std::make_unique<bool>( false );
		}
		else
		{
			return std::make_unique<bool>( true );
		}
	}
	WCHAR fs_name_buffer[MAX_PATH + 1];
	if( GetVolumeInformationByHandleW( volume, nullptr, 0, nullptr, nullptr, nullptr, fs_name_buffer, ARRAYSIZE( fs_name_buffer ) ) )
	{
		fprintf( stderr, "%ls is %ls\n", mount_point.get(), fs_name_buffer );
	}
	return nullptr;
}
BOOL reflink( _In_z_ PCWSTR oldpath, _In_z_ PCWSTR newpath )
{
	HANDLE source = CreateFileW( oldpath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr );
	if( source == INVALID_HANDLE_VALUE )
	{
		return FALSE;
	}
	FILE_STANDARD_INFO file_standard;
	if( !GetFileInformationByHandleEx( source, FileStandardInfo, &file_standard, sizeof file_standard ) )
	{
		CloseHandle( source );
		return FALSE;
	}

	HANDLE destination = CreateFileW( newpath, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, source );
	if( destination == INVALID_HANDLE_VALUE )
	{
		CloseHandle( source );
		return FALSE;
	}

	BOOL success;
	ULONG dummy;

	FILE_END_OF_FILE_INFO end_of_file = { file_standard.EndOfFile };
	success = SetFileInformationByHandle( destination, FileEndOfFileInfo, &end_of_file, sizeof end_of_file );

	if( success )
	{
		DUPLICATE_EXTENTS_DATA dup_extent = { source, { 0 }, { 0 }, file_standard.AllocationSize };
		success = DeviceIoControl( destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &dummy, nullptr );
	}
	if( success )
	{
		FILE_BASIC_INFO file_basic_info[2];
		if( GetFileInformationByHandleEx( source, FileBasicInfo, &file_basic_info[0], sizeof file_basic_info )
			&& GetFileInformationByHandleEx( destination, FileBasicInfo, &file_basic_info[1], sizeof file_basic_info ) )
		{
			file_basic_info[0].CreationTime.QuadPart = file_basic_info[1].CreationTime.QuadPart;
			SetFileInformationByHandle( destination, FileBasicInfo, &file_basic_info[0], sizeof file_basic_info );
		}
	}
	if( !success )
	{
		FILE_DISPOSITION_INFO dispose = { TRUE };
		SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose );
	}
	CloseHandle( destination );
	CloseHandle( source );
	return success;
}
int __cdecl wmain( int argc, PWSTR argv[] )
{
	_CrtSetDbgFlag( _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) | _CRTDBG_LEAK_CHECK_DF );
	_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
	_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
	setlocale( LC_ALL, "" );

	if( argc != 3 )
	{
		PrintUsage();
		return EXIT_FAILURE;
	}
	auto source = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	auto destination = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	if( FAILED( PathCchCanonicalizeEx( source.get(), PATHCCH_MAX_CCH, argv[1], PATHCCH_ALLOW_LONG_PATHS ) )
		|| FAILED( PathCchCanonicalizeEx( destination.get(), PATHCCH_MAX_CCH, argv[2], PATHCCH_ALLOW_LONG_PATHS ) ) )
	{
		PrintfWindowsError();
		return EXIT_FAILURE;
	}
	auto refs_capability = CheckReFSVersion( source.get() );
	if( !refs_capability || !*refs_capability )
	{
		fputs( "reflink may fail.\n", stderr );
	}
	if( !reflink( source.get(), destination.get() ) )
	{
		PrintfWindowsError();
		return EXIT_FAILURE;
	}
}<commit_msg>remove attr copy.<commit_after>#define WIN32_LEAN_AND_MEAN
#define STRICT
#define STRICT_GS_ENABLED
#define _CRTDBG_MAP_ALLOC
#include <windows.h>
#include <pathcch.h>
#include <shlwapi.h>
#include <winioctl.h>
#include <clocale>
#include <cstdio>
#include <memory>
#include <crtdbg.h>
#include "banned.h"
#pragma comment(lib, "pathcch")
#pragma comment(lib, "shlwapi")
#pragma comment(lib, "user32")

std::unique_ptr<WCHAR[]> GetWindowsError( ULONG error_code = GetLastError() )
{
	auto msg = std::make_unique<WCHAR[]>( USHRT_MAX );
	if( FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error_code, 0, msg.get(), USHRT_MAX, nullptr ) )
	{
		return msg;
	}
	return nullptr;
}
void PrintfWindowsError( ULONG error_code = GetLastError() )
{
	if( auto error_msg = GetWindowsError( error_code ) )
	{
		fprintf( stderr, "%ls\n", error_msg.get() );
	}
}
void PrintUsage()
{
	fprintf(
		stderr,
		"Copy file without actual data write.\n"
		"\n"
		"%ls source destination\n"
		"\n"
		"source       Specifies a file to copy.\n"
		"             source must have placed on the ReFS volume.\n"
		"destination  Specifies new file name.\n"
		"             destination must have placed on the same volume as source.\n",
		PathFindFileNameW( __wargv[0] )
		);
}
std::unique_ptr<bool> CheckReFSVersion( PCWSTR on_volume_path )
{
	auto mount_point = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	if( !GetVolumePathNameW( on_volume_path, mount_point.get(), PATHCCH_MAX_CCH ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	WCHAR guid_path[50];
	if( !GetVolumeNameForVolumeMountPointW( mount_point.get(), guid_path, ARRAYSIZE( guid_path ) ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	PWCHAR end_bslash;
	if( FAILED( PathCchRemoveBackslashEx( guid_path, ARRAYSIZE( guid_path ), &end_bslash, nullptr ) ) )
	{
		PrintfWindowsError();
		return nullptr;
	}
	*end_bslash = L'\0';
	auto volume = CreateFileW( guid_path, FILE_EXECUTE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr );
	if( volume == INVALID_HANDLE_VALUE )
	{
		PrintfWindowsError();
		return nullptr;
	}
	ULONG dummy;
	REFS_VOLUME_DATA_BUFFER refs_info;
	if( DeviceIoControl( volume, FSCTL_GET_REFS_VOLUME_DATA, nullptr, 0, &refs_info, sizeof refs_info, &dummy, nullptr ) )
	{
		fprintf( stderr, "%ls is ReFS %lu.%lu\n", mount_point.get(), refs_info.MajorVersion, refs_info.MinorVersion );
		if( refs_info.MajorVersion < 1 || ( refs_info.MajorVersion == 1 && refs_info.MinorVersion <= 2 ) )
		{
			return std::make_unique<bool>( false );
		}
		else
		{
			return std::make_unique<bool>( true );
		}
	}
	WCHAR fs_name_buffer[MAX_PATH + 1];
	if( GetVolumeInformationByHandleW( volume, nullptr, 0, nullptr, nullptr, nullptr, fs_name_buffer, ARRAYSIZE( fs_name_buffer ) ) )
	{
		fprintf( stderr, "%ls is %ls\n", mount_point.get(), fs_name_buffer );
	}
	return nullptr;
}
BOOL reflink( _In_z_ PCWSTR oldpath, _In_z_ PCWSTR newpath )
{
	HANDLE source = CreateFileW( oldpath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr );
	if( source == INVALID_HANDLE_VALUE )
	{
		return FALSE;
	}
	FILE_STANDARD_INFO file_standard;
	if( !GetFileInformationByHandleEx( source, FileStandardInfo, &file_standard, sizeof file_standard ) )
	{
		CloseHandle( source );
		return FALSE;
	}

	HANDLE destination = CreateFileW( newpath, GENERIC_WRITE | DELETE, 0, nullptr, CREATE_NEW, 0, source );
	if( destination == INVALID_HANDLE_VALUE )
	{
		CloseHandle( source );
		return FALSE;
	}

	BOOL success;
	ULONG dummy;

	FILE_END_OF_FILE_INFO end_of_file = { file_standard.EndOfFile };
	success = SetFileInformationByHandle( destination, FileEndOfFileInfo, &end_of_file, sizeof end_of_file );

	if( success )
	{
		DUPLICATE_EXTENTS_DATA dup_extent = { source, { 0 }, { 0 }, file_standard.AllocationSize };
		success = DeviceIoControl( destination, FSCTL_DUPLICATE_EXTENTS_TO_FILE, &dup_extent, sizeof dup_extent, nullptr, 0, &dummy, nullptr );
	}
	if( success )
	{
		FILETIME atime, mtime;
		if( GetFileTime( source, nullptr, &atime, &mtime ) )
		{
			SetFileTime( destination, nullptr, &atime, &mtime );
		}
	}
	if( !success )
	{
		FILE_DISPOSITION_INFO dispose = { TRUE };
		SetFileInformationByHandle( destination, FileDispositionInfo, &dispose, sizeof dispose );
	}
	CloseHandle( destination );
	CloseHandle( source );
	return success;
}
int __cdecl wmain( int argc, PWSTR argv[] )
{
	_CrtSetDbgFlag( _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ) | _CRTDBG_LEAK_CHECK_DF );
	_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
	_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_FILE );
	setlocale( LC_ALL, "" );

	if( argc != 3 )
	{
		PrintUsage();
		return EXIT_FAILURE;
	}
	auto source = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	auto destination = std::make_unique<WCHAR[]>( PATHCCH_MAX_CCH );
	if( FAILED( PathCchCanonicalizeEx( source.get(), PATHCCH_MAX_CCH, argv[1], PATHCCH_ALLOW_LONG_PATHS ) )
		|| FAILED( PathCchCanonicalizeEx( destination.get(), PATHCCH_MAX_CCH, argv[2], PATHCCH_ALLOW_LONG_PATHS ) ) )
	{
		PrintfWindowsError();
		return EXIT_FAILURE;
	}
	auto refs_capability = CheckReFSVersion( source.get() );
	if( !refs_capability || !*refs_capability )
	{
		fputs( "reflink may fail.\n", stderr );
	}
	if( !reflink( source.get(), destination.get() ) )
	{
		PrintfWindowsError();
		return EXIT_FAILURE;
	}
}<|endoftext|>


<commit_before>// Copyright (c) 2006-2009 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 <string>
#include <list>
#include <windows.h>
#include <commctrl.h>
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/gfx/native_theme.h"
#include "base/resource_util.h"
#include "base/win_util.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtDumpMemoryLeaks();
#endif
}

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
}

// This test approximates whether you are running the default themes for
// your platform by inspecting a couple of metrics.
// It does not catch all cases, but it does pick up on classic vs xp,
// and normal vs large fonts. Something it misses is changes to the color
// scheme (which will infact cause pixel test failures).
bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  std::list<std::string> errors;

  OSVERSIONINFOEX osvi;
  ::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
  osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  ::GetVersionEx((OSVERSIONINFO *)&osvi);

  // default to XP metrics, override if on Vista
  int requiredVScrollSize = 17;
  int requiredFontSize = -11; // 8 pt
  const WCHAR *requiredFont = L"Tahoma";
  bool isVista = false;
  if (osvi.dwMajorVersion == 6
      && osvi.dwMinorVersion == 0
      && osvi.wProductType == VER_NT_WORKSTATION) {
    requiredFont = L"Segoe UI";
    requiredFontSize = -12; // 9 pt
    isVista = true;
  } else if (osvi.dwMajorVersion == 5
             && osvi.dwMinorVersion == 1
             && osvi.wProductType == VER_NT_WORKSTATION) {
    // XP;
  } else {
    errors.push_back("Unsupported Operating System version "
                     "(must use XP or Vista)");
  }

  // on both XP and Vista, this metric will be 17 when font size is "Normal".
  // The size of drop-down menus depends on it.
  int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL);
  if (vScrollSize != requiredVScrollSize) {
    errors.push_back("Must use normal size fonts (96 dpi)");
  }

  // font smoothing (including ClearType) must be disabled
  BOOL bFontSmoothing;
  SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0,
                       (PVOID)&bFontSmoothing, (UINT)0);
  if (bFontSmoothing) {
    errors.push_back("Font smoothing (ClearType) must be disabled");
  }

  // Check that we're using the default system fonts
  NONCLIENTMETRICS metrics;
  win_util::GetNonClientMetrics(&metrics);
  LOGFONTW* system_fonts[] =
  { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont };

  for (size_t i = 0; i < arraysize(system_fonts); ++i) {
    if (system_fonts[i]->lfHeight != requiredFontSize ||
        wcscmp(requiredFont, system_fonts[i]->lfFaceName)) {
      if (isVista)
        errors.push_back("Must use either the Aero or Basic theme");
      else
        errors.push_back("Must use the default XP theme (Luna)");
      break;
    }
  }

  if (!errors.empty()) {
    fprintf(stderr, "%s",
      "##################################################################\n"
      "## Layout test system dependencies check failed.\n"
      "##\n");
    for (std::list<std::string>::iterator it = errors.begin();
         it != errors.end();
         ++it) {
      fprintf(stderr, "## %s\n", it->c_str());
    }
    fprintf(stderr, "%s",
      "##\n"
      "##################################################################\n");
  }
  return errors.empty();
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
  _set_abort_behavior(0, _WRITE_ABORT_MSG);
}

void TestShellPlatformDelegate::InitializeGUI() {
  INITCOMMONCONTROLSEX InitCtrlEx;

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
  TestShell::RegisterWindowClass();
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  gfx::NativeTheme::instance()->DisableTheming();
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(
    TestShell *shell) {
  // Move the window to the upper left corner for consistent
  // record/playback mode.  For automation, we want this to work
  // on build systems where the script invoking us is a background
  // process.  So for this case, make our window the topmost window
  // as well.
  ForegroundHelper::SetForeground(shell->mainWnd());
  ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
}
<commit_msg>back out CL 21368 in case for some reason it's causing a crash on video-toggle<commit_after>// Copyright (c) 2006-2009 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 <windows.h>
#include <commctrl.h>
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/gfx/native_theme.h"
#include "base/resource_util.h"
#include "base/win_util.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"

TestShellPlatformDelegate::TestShellPlatformDelegate(
    const CommandLine& command_line)
    : command_line_(command_line) {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
}

TestShellPlatformDelegate::~TestShellPlatformDelegate() {
#ifdef _CRTDBG_MAP_ALLOC
  _CrtDumpMemoryLeaks();
#endif
}

void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
}

// This test approximates whether you have the Windows XP theme selected by
// inspecting a couple of metrics. It does not catch all cases, but it does
// pick up on classic vs xp, and normal vs large fonts. Something it misses
// is changes to the color scheme (which will infact cause pixel test
// failures).
//
// ** Expected dependencies **
// + Theme: Windows XP
// + Color scheme: Default (blue)
// + Font size: Normal
// + Font smoothing: off (minor impact).
//
static bool HasLayoutTestThemeDependenciesWin() {
  // This metric will be 17 when font size is "Normal". The size of drop-down
  // menus depends on it.
  if (::GetSystemMetrics(SM_CXVSCROLL) != 17)
    return false;

  // Check that the system fonts RenderThemeWin relies on are Tahoma 11 pt.
  NONCLIENTMETRICS metrics;
  win_util::GetNonClientMetrics(&metrics);
  LOGFONTW* system_fonts[] =
  { &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont };

  for (size_t i = 0; i < arraysize(system_fonts); ++i) {
    if (system_fonts[i]->lfHeight != -11 ||
        0 != wcscmp(L"Tahoma", system_fonts[i]->lfFaceName))
      return false;
  }
  return true;
}

bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
  bool has_deps = HasLayoutTestThemeDependenciesWin();
  if (!has_deps) {
    fprintf(stderr,
            "\n"
            "###############################################################\n"
            "## Layout test system dependencies check failed.\n"
            "## Some layout tests may fail due to unexpected theme.\n"
            "##\n"
            "## To fix, go to Display Properties -> Appearance, and select:\n"
            "##  + Windows and buttons: Windows XP style\n"
            "##  + Color scheme: Default (blue)\n"
            "##  + Font size: Normal\n"
            "###############################################################\n");
  }
  return has_deps;
}

void TestShellPlatformDelegate::SuppressErrorReporting() {
  _set_abort_behavior(0, _WRITE_ABORT_MSG);
}

void TestShellPlatformDelegate::InitializeGUI() {
  INITCOMMONCONTROLSEX InitCtrlEx;

  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
  TestShell::RegisterWindowClass();
}

void TestShellPlatformDelegate::SelectUnifiedTheme() {
  gfx::NativeTheme::instance()->DisableTheming();
}

void TestShellPlatformDelegate::SetWindowPositionForRecording(
    TestShell *shell) {
  // Move the window to the upper left corner for consistent
  // record/playback mode.  For automation, we want this to work
  // on build systems where the script invoking us is a background
  // process.  So for this case, make our window the topmost window
  // as well.
  ForegroundHelper::SetForeground(shell->mainWnd());
  ::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
}
<|endoftext|>


<commit_before>/*
    This file is part of KAddressBook.
    Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>

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

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

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

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qlayout.h>
#include <qpushbutton.h>
#include <qtimer.h>

#include <kabc/resource.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kresources/configdialog.h>

#include "core.h"

#include "resourceselection.h"
#include <libkdepim/resourceabc.h>

class AddressBookWrapper : public KABC::AddressBook
{
  public:
    AddressBookWrapper( KABC::AddressBook* );

    KRES::Manager<KABC::Resource>* getResourceManager()
    {
      return resourceManager();
    }
};

class ResourceItem : public QCheckListItem
{
  public:
    ResourceItem( KListView *parent, KABC::Resource *resource )
      : QCheckListItem( parent, resource->resourceName(), CheckBox ),
        mResource( resource ), mChecked( false ),
        mIsSubresource( false ), mSubItemsCreated( false ),
        mResourceIdentifier()
    {
      setOn( resource->isActive() );
      setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", KIcon::Small ) );
      mChecked = isOn();
    }

    ResourceItem( KPIM::ResourceABC *resourceABC, ResourceItem* parent,
                  const QString& resourceIdent )
      : QCheckListItem( parent, resourceABC->subresourceLabel( resourceIdent ), CheckBox ),
        mResource( resourceABC ), mChecked( false ),
        mIsSubresource( true ), mSubItemsCreated( false ),
        mResourceIdentifier( resourceIdent )
    {
      KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource );
      setOn( res->subresourceActive( mResourceIdentifier ) );
      setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", KIcon::Small ) );
      mChecked = isOn();
    }

    void createSubresourceItems();

    void setChecked( bool state ) { mChecked = state; }
    bool checked() const { return mChecked; }
    KABC::Resource *resource() const { return mResource; }
    QString resourceIdentifier() const { return mResourceIdentifier; }
    bool isSubResource() const { return mIsSubresource; }

    virtual void stateChange( bool active );

  private:
    KABC::Resource * const mResource;
    bool mChecked;
    const bool mIsSubresource;
    bool mSubItemsCreated;
    const QString mResourceIdentifier;
};

// Comes from korganizer/resourceview.cpp
void ResourceItem::createSubresourceItems()
{
  KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource );
  QStringList subresources;
  if ( res )
    subresources = res->subresources();
  if ( !subresources.isEmpty() ) {
    setOpen( true );
    setExpandable( true );
    // This resource has subresources
    QStringList::ConstIterator it;
    for ( it = subresources.begin(); it != subresources.end(); ++it ) {
      (void)new ResourceItem( res, this, *it );
    }
  }
  mSubItemsCreated = true;
}

// TODO: connect this to some signalResourceModified
// void ResourceItem::setGuiState()
// {
//   if ( mIsSubresource )
//     setOn( mResource->subresourceActive( mResourceIdentifier ) );
//   else
//     setOn( mResource->isActive() );
// }

void ResourceItem::stateChange( bool active )
{
  //kdDebug(5720) << k_funcinfo << this << " " << text( 0 ) << " active=" << active << endl;
  if ( active && !mIsSubresource ) {
    if ( !mSubItemsCreated )
      createSubresourceItems();
  }

  setOpen( active && childCount() > 0 );
}

////

ResourceSelection::ResourceSelection( KAB::Core *core, QWidget *parent, const char *name )
  : KAB::ExtensionWidget( core, parent, name ), mManager( 0 )
{
  initGUI();

  AddressBookWrapper *wrapper = static_cast<AddressBookWrapper*>( core->addressBook() );
  mManager = wrapper->getResourceManager();

  connect( mAddButton, SIGNAL( clicked() ), SLOT( add() ) );
  connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) );
  connect( mRemoveButton, SIGNAL( clicked() ), SLOT( remove() ) );

  connect( mListView, SIGNAL( clicked( QListViewItem* ) ),
           SLOT( currentChanged( QListViewItem* ) ) );

  QTimer::singleShot( 0, this, SLOT( updateView() ) );
}

ResourceSelection::~ResourceSelection()
{
}

QString ResourceSelection::title() const
{
  return i18n( "Address Books" );
}

QString ResourceSelection::identifier() const
{
  return "resourceselection";
}

void ResourceSelection::add()
{
  QStringList types = mManager->resourceTypeNames();
  QStringList descs = mManager->resourceTypeDescriptions();

  bool ok = false;
  QString desc = KInputDialog::getItem( i18n( "Add Address Book" ),
                                        i18n( "Please select type of the new address book:" ),
                                        descs, 0, false, &ok, this );
  if ( !ok )
    return;

  QString type = types[ descs.findIndex( desc ) ];

  // Create new resource
  KABC::Resource *resource = mManager->createResource( type );
  if ( !resource ) {
    KMessageBox::error( this, i18n("<qt>Unable to create an address book of type %1.</qt>")
                              .arg( type ) );
    return;
  }

  resource->setResourceName( i18n( "%1 address book" ).arg( type ) );

  KRES::ConfigDialog dlg( this, QString( "contact" ), resource );

  if ( dlg.exec() ) {
    core()->addressBook()->addResource( resource );
    resource->asyncLoad();

    mLastResource = resource->identifier();
    updateView();
  } else {
    delete resource;
    resource = 0;
  }
}

void ResourceSelection::edit()
{
  ResourceItem *item = selectedItem();
  if ( !item )
    return;

  KRES::ConfigDialog dlg( this, QString( "contact" ), item->resource() );

  if ( dlg.exec() ) {
    mManager->change( item->resource() );
    item->resource()->asyncLoad();

    mLastResource = item->resource()->identifier();
    updateView();
  }
}

void ResourceSelection::remove()
{
  ResourceItem *item = selectedItem();
  if ( !item )
    return;

  int result = KMessageBox::warningContinueCancel( this,
        i18n( "<qt>Do you really want to remove the address book %1?</qt>" )
        .arg( item->resource()->resourceName() ), "",
        KGuiItem( i18n( "&Remove" ), "editdelete" ) );
  if ( result == KMessageBox::Cancel )
    return;

  mLastResource = item->resource()->identifier();

  core()->addressBook()->removeResource( item->resource() );
  core()->addressBook()->emitAddressBookChanged();

  updateView();
}

void ResourceSelection::currentChanged( QListViewItem *item )
{
  ResourceItem *resItem = static_cast<ResourceItem*>( item );
  bool state = (resItem && !resItem->isSubResource() );

  mEditButton->setEnabled( state );
  mRemoveButton->setEnabled( state );

  if ( !resItem )
    return;

  KABC::Resource *resource = resItem->resource();

  if ( resItem->checked() != resItem->isOn() ) {
    resItem->setChecked( resItem->isOn() );
    if ( resItem->isSubResource() ) {
      KPIM::ResourceABC *res = dynamic_cast<KPIM::ResourceABC *>( resource );
      res->setSubresourceActive( resItem->resourceIdentifier(), resItem->isOn() );
      mManager->change( resource );
    } else {
      resource->setActive( resItem->isOn() );
      mManager->change( resource );

      if ( resItem->checked() ) {
        if ( !resource->addressBook() )
          resource->setAddressBook( core()->addressBook() );

        if ( !resource->isOpen() )
          resource->open();

        resource->asyncLoad();
      } else {
        resource->close();
      }
    }

    mLastResource = resource->identifier();
    core()->addressBook()->emitAddressBookChanged();
    //updateView();
  }
}

void ResourceSelection::updateView()
{
  if ( !mManager )
    return;

  mListView->clear();

  KRES::Manager<KABC::Resource>::Iterator it;
  for ( it = mManager->begin(); it != mManager->end(); ++it ) {

    new ResourceItem( mListView, *it );
    KPIM::ResourceABC* resource = dynamic_cast<KPIM::ResourceABC *>( *it );
    if ( resource ) {
      disconnect( resource, 0, this, 0 );
      connect( resource, SIGNAL( signalSubresourceAdded( KPIM::ResourceABC *,
                                                         const QString &, const QString & ) ),
               SLOT( slotSubresourceAdded( KPIM::ResourceABC *,
                                           const QString &, const QString & ) ) );

      connect( resource, SIGNAL( signalSubresourceRemoved( KPIM::ResourceABC *,
                                                           const QString &, const QString & ) ),
               SLOT( slotSubresourceRemoved( KPIM::ResourceABC *,
                                             const QString &, const QString & ) ) );
      //connect( resource, SIGNAL( resourceSaved( KPIM::ResourceABC * ) ),
      //         SLOT( closeResource( KPIM::ResourceABC * ) ) );
    }
  }

  QListViewItemIterator itemIt( mListView );
  while ( itemIt.current() ) {
    ResourceItem *item = static_cast<ResourceItem*>( itemIt.current() );
    if ( item->resource()->identifier() == mLastResource ) {
      mListView->setSelected( item, true );
      mListView->ensureItemVisible( item );
      break;
    }
    ++itemIt;
  }

  core()->addressBook()->emitAddressBookChanged();
}

// Add a new entry
void ResourceSelection::slotSubresourceAdded( KPIM::ResourceABC *resource,
                                              const QString& /*type*/,
                                              const QString& subResource )
{
  kdDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl;
  QListViewItem *i = mListView->findItem( resource->resourceName(), 0 );
  if ( !i )
    // Not found
    return;

  ResourceItem *item = static_cast<ResourceItem *>( i );
  (void)new ResourceItem( resource, item, subResource );
}

// Remove an entry
void ResourceSelection::slotSubresourceRemoved( KPIM::ResourceABC* resource,
                                                const QString& /*type*/,
                                                const QString& subResource )
{
  kdDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl;
  // TODO
  //delete findItemByIdentifier( resource );
  //emitResourcesChanged();
}

ResourceItem* ResourceSelection::selectedItem() const
{
  return static_cast<ResourceItem*>( mListView->selectedItem() );
}

void ResourceSelection::initGUI()
{
  QGridLayout *layout = new QGridLayout( this, 2, 3, 2, 5 );

  mListView = new KListView( this );
  mListView->addColumn( i18n( "Address Books" ) );
  mListView->setFullWidth( true );
  layout->addMultiCellWidget( mListView, 0, 0, 0, 2 );

  mAddButton = new QPushButton( i18n( "Add..." ), this );
  mEditButton = new QPushButton( i18n( "Edit..." ), this );
  mEditButton->setEnabled( false );
  mRemoveButton = new QPushButton( i18n( "Remove" ), this );
  mRemoveButton->setEnabled( false );

  layout->addWidget( mAddButton, 1, 0 );
  layout->addWidget( mEditButton, 1, 1 );
  layout->addWidget( mRemoveButton, 1, 2 );
}

class ResourceSelectionFactory : public KAB::ExtensionFactory
{
  public:
    KAB::ExtensionWidget *extension( KAB::Core *core, QWidget *parent, const char *name )
    {
      return new ResourceSelection( core, parent, name );
    }

    QString identifier() const
    {
      return "resourceselection";
    }
};

extern "C" {
  void *init_libkaddrbk_resourceselection()
  {
    return ( new ResourceSelectionFactory );
  }
}

#include "resourceselection.moc"
<commit_msg>Fix crash when we added resource. KaddressBook pointer was never initialized (too late for kde3.5.4 I think)<commit_after>/*
    This file is part of KAddressBook.
    Copyright (c) 2004 Tobias Koenig <tokoe@kde.org>

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

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

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

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qlayout.h>
#include <qpushbutton.h>
#include <qtimer.h>

#include <kabc/resource.h>
#include <kdialog.h>
#include <kglobal.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kresources/configdialog.h>

#include "core.h"

#include "resourceselection.h"
#include <libkdepim/resourceabc.h>

class AddressBookWrapper : public KABC::AddressBook
{
  public:
    AddressBookWrapper( KABC::AddressBook* );

    KRES::Manager<KABC::Resource>* getResourceManager()
    {
      return resourceManager();
    }
};

class ResourceItem : public QCheckListItem
{
  public:
    ResourceItem( KListView *parent, KABC::Resource *resource )
      : QCheckListItem( parent, resource->resourceName(), CheckBox ),
        mResource( resource ), mChecked( false ),
        mIsSubresource( false ), mSubItemsCreated( false ),
        mResourceIdentifier()
    {
      setOn( resource->isActive() );
      setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", KIcon::Small ) );
      mChecked = isOn();
    }

    ResourceItem( KPIM::ResourceABC *resourceABC, ResourceItem* parent,
                  const QString& resourceIdent )
      : QCheckListItem( parent, resourceABC->subresourceLabel( resourceIdent ), CheckBox ),
        mResource( resourceABC ), mChecked( false ),
        mIsSubresource( true ), mSubItemsCreated( false ),
        mResourceIdentifier( resourceIdent )
    {
      KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource );
      setOn( res->subresourceActive( mResourceIdentifier ) );
      setPixmap( 0, KGlobal::iconLoader()->loadIcon( "contents", KIcon::Small ) );
      mChecked = isOn();
    }

    void createSubresourceItems();

    void setChecked( bool state ) { mChecked = state; }
    bool checked() const { return mChecked; }
    KABC::Resource *resource() const { return mResource; }
    QString resourceIdentifier() const { return mResourceIdentifier; }
    bool isSubResource() const { return mIsSubresource; }

    virtual void stateChange( bool active );

  private:
    KABC::Resource * const mResource;
    bool mChecked;
    const bool mIsSubresource;
    bool mSubItemsCreated;
    const QString mResourceIdentifier;
};

// Comes from korganizer/resourceview.cpp
void ResourceItem::createSubresourceItems()
{
  KPIM::ResourceABC* res = dynamic_cast<KPIM::ResourceABC *>( mResource );
  QStringList subresources;
  if ( res )
    subresources = res->subresources();
  if ( !subresources.isEmpty() ) {
    setOpen( true );
    setExpandable( true );
    // This resource has subresources
    QStringList::ConstIterator it;
    for ( it = subresources.begin(); it != subresources.end(); ++it ) {
      (void)new ResourceItem( res, this, *it );
    }
  }
  mSubItemsCreated = true;
}

// TODO: connect this to some signalResourceModified
// void ResourceItem::setGuiState()
// {
//   if ( mIsSubresource )
//     setOn( mResource->subresourceActive( mResourceIdentifier ) );
//   else
//     setOn( mResource->isActive() );
// }

void ResourceItem::stateChange( bool active )
{
  //kdDebug(5720) << k_funcinfo << this << " " << text( 0 ) << " active=" << active << endl;
  if ( active && !mIsSubresource ) {
    if ( !mSubItemsCreated )
      createSubresourceItems();
  }

  setOpen( active && childCount() > 0 );
}

////

ResourceSelection::ResourceSelection( KAB::Core *core, QWidget *parent, const char *name )
  : KAB::ExtensionWidget( core, parent, name ), mManager( 0 )
{
  initGUI();

  AddressBookWrapper *wrapper = static_cast<AddressBookWrapper*>( core->addressBook() );
  mManager = wrapper->getResourceManager();

  connect( mAddButton, SIGNAL( clicked() ), SLOT( add() ) );
  connect( mEditButton, SIGNAL( clicked() ), SLOT( edit() ) );
  connect( mRemoveButton, SIGNAL( clicked() ), SLOT( remove() ) );

  connect( mListView, SIGNAL( clicked( QListViewItem* ) ),
           SLOT( currentChanged( QListViewItem* ) ) );

  QTimer::singleShot( 0, this, SLOT( updateView() ) );
}

ResourceSelection::~ResourceSelection()
{
}

QString ResourceSelection::title() const
{
  return i18n( "Address Books" );
}

QString ResourceSelection::identifier() const
{
  return "resourceselection";
}

void ResourceSelection::add()
{
  QStringList types = mManager->resourceTypeNames();
  QStringList descs = mManager->resourceTypeDescriptions();

  bool ok = false;
  QString desc = KInputDialog::getItem( i18n( "Add Address Book" ),
                                        i18n( "Please select type of the new address book:" ),
                                        descs, 0, false, &ok, this );
  if ( !ok )
    return;

  QString type = types[ descs.findIndex( desc ) ];

  // Create new resource
  KABC::Resource *resource = mManager->createResource( type );
  if ( !resource ) {
    KMessageBox::error( this, i18n("<qt>Unable to create an address book of type %1.</qt>")
                              .arg( type ) );
    return;
  }

  resource->setResourceName( i18n( "%1 address book" ).arg( type ) );
  resource->setAddressBook(core()->addressBook());

  KRES::ConfigDialog dlg( this, QString( "contact" ), resource );

  if ( dlg.exec() ) {
    core()->addressBook()->addResource( resource );
    resource->asyncLoad();

    mLastResource = resource->identifier();
    updateView();
  } else {
    delete resource;
    resource = 0;
  }
}

void ResourceSelection::edit()
{
  ResourceItem *item = selectedItem();
  if ( !item )
    return;

  KRES::ConfigDialog dlg( this, QString( "contact" ), item->resource() );

  if ( dlg.exec() ) {
    mManager->change( item->resource() );
    item->resource()->asyncLoad();

    mLastResource = item->resource()->identifier();
    updateView();
  }
}

void ResourceSelection::remove()
{
  ResourceItem *item = selectedItem();
  if ( !item )
    return;

  int result = KMessageBox::warningContinueCancel( this,
        i18n( "<qt>Do you really want to remove the address book %1?</qt>" )
        .arg( item->resource()->resourceName() ), "",
        KGuiItem( i18n( "&Remove" ), "editdelete" ) );
  if ( result == KMessageBox::Cancel )
    return;

  mLastResource = item->resource()->identifier();

  core()->addressBook()->removeResource( item->resource() );
  core()->addressBook()->emitAddressBookChanged();

  updateView();
}

void ResourceSelection::currentChanged( QListViewItem *item )
{
  ResourceItem *resItem = static_cast<ResourceItem*>( item );
  bool state = (resItem && !resItem->isSubResource() );

  mEditButton->setEnabled( state );
  mRemoveButton->setEnabled( state );

  if ( !resItem )
    return;

  KABC::Resource *resource = resItem->resource();

  if ( resItem->checked() != resItem->isOn() ) {
    resItem->setChecked( resItem->isOn() );
    if ( resItem->isSubResource() ) {
      KPIM::ResourceABC *res = dynamic_cast<KPIM::ResourceABC *>( resource );
      res->setSubresourceActive( resItem->resourceIdentifier(), resItem->isOn() );
      mManager->change( resource );
    } else {
      resource->setActive( resItem->isOn() );
      mManager->change( resource );

      if ( resItem->checked() ) {
        if ( !resource->addressBook() )
          resource->setAddressBook( core()->addressBook() );

        if ( !resource->isOpen() )
          resource->open();

        resource->asyncLoad();
      } else {
        resource->close();
      }
    }

    mLastResource = resource->identifier();
    core()->addressBook()->emitAddressBookChanged();
    //updateView();
  }
}

void ResourceSelection::updateView()
{
  if ( !mManager )
    return;

  mListView->clear();

  KRES::Manager<KABC::Resource>::Iterator it;
  for ( it = mManager->begin(); it != mManager->end(); ++it ) {

    new ResourceItem( mListView, *it );
    KPIM::ResourceABC* resource = dynamic_cast<KPIM::ResourceABC *>( *it );
    if ( resource ) {
      disconnect( resource, 0, this, 0 );
      connect( resource, SIGNAL( signalSubresourceAdded( KPIM::ResourceABC *,
                                                         const QString &, const QString & ) ),
               SLOT( slotSubresourceAdded( KPIM::ResourceABC *,
                                           const QString &, const QString & ) ) );

      connect( resource, SIGNAL( signalSubresourceRemoved( KPIM::ResourceABC *,
                                                           const QString &, const QString & ) ),
               SLOT( slotSubresourceRemoved( KPIM::ResourceABC *,
                                             const QString &, const QString & ) ) );
      //connect( resource, SIGNAL( resourceSaved( KPIM::ResourceABC * ) ),
      //         SLOT( closeResource( KPIM::ResourceABC * ) ) );
    }
  }

  QListViewItemIterator itemIt( mListView );
  while ( itemIt.current() ) {
    ResourceItem *item = static_cast<ResourceItem*>( itemIt.current() );
    if ( item->resource()->identifier() == mLastResource ) {
      mListView->setSelected( item, true );
      mListView->ensureItemVisible( item );
      break;
    }
    ++itemIt;
  }

  core()->addressBook()->emitAddressBookChanged();
}

// Add a new entry
void ResourceSelection::slotSubresourceAdded( KPIM::ResourceABC *resource,
                                              const QString& /*type*/,
                                              const QString& subResource )
{
  kdDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl;
  QListViewItem *i = mListView->findItem( resource->resourceName(), 0 );
  if ( !i )
    // Not found
    return;

  ResourceItem *item = static_cast<ResourceItem *>( i );
  (void)new ResourceItem( resource, item, subResource );
}

// Remove an entry
void ResourceSelection::slotSubresourceRemoved( KPIM::ResourceABC* resource,
                                                const QString& /*type*/,
                                                const QString& subResource )
{
  kdDebug(5720) << k_funcinfo << resource->resourceName() << " " << subResource << endl;
  // TODO
  //delete findItemByIdentifier( resource );
  //emitResourcesChanged();
}

ResourceItem* ResourceSelection::selectedItem() const
{
  return static_cast<ResourceItem*>( mListView->selectedItem() );
}

void ResourceSelection::initGUI()
{
  QGridLayout *layout = new QGridLayout( this, 2, 3, 2, 5 );

  mListView = new KListView( this );
  mListView->addColumn( i18n( "Address Books" ) );
  mListView->setFullWidth( true );
  layout->addMultiCellWidget( mListView, 0, 0, 0, 2 );

  mAddButton = new QPushButton( i18n( "Add..." ), this );
  mEditButton = new QPushButton( i18n( "Edit..." ), this );
  mEditButton->setEnabled( false );
  mRemoveButton = new QPushButton( i18n( "Remove" ), this );
  mRemoveButton->setEnabled( false );

  layout->addWidget( mAddButton, 1, 0 );
  layout->addWidget( mEditButton, 1, 1 );
  layout->addWidget( mRemoveButton, 1, 2 );
}

class ResourceSelectionFactory : public KAB::ExtensionFactory
{
  public:
    KAB::ExtensionWidget *extension( KAB::Core *core, QWidget *parent, const char *name )
    {
      return new ResourceSelection( core, parent, name );
    }

    QString identifier() const
    {
      return "resourceselection";
    }
};

extern "C" {
  void *init_libkaddrbk_resourceselection()
  {
    return ( new ResourceSelectionFactory );
  }
}

#include "resourceselection.moc"
<|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 "native_client/src/shared/platform/nacl_check.h"

#include "ppapi/c/dev/ppb_context_3d_dev.h"
#include "ppapi/c/dev/ppb_cursor_control_dev.h"
#include "ppapi/c/dev/ppb_font_dev.h"
#include "ppapi/c/dev/ppb_memory_dev.h"
#include "ppapi/c/dev/ppb_scrollbar_dev.h"
#include "ppapi/c/dev/ppb_surface_3d_dev.h"
#include "ppapi/c/dev/ppb_testing_dev.h"
#include "ppapi/c/dev/ppb_var_deprecated.h"
#include "ppapi/c/dev/ppb_widget_dev.h"
#include "ppapi/c/ppb_core.h"
#include "ppapi/c/ppb_file_io.h"
#include "ppapi/c/ppb_file_ref.h"
#include "ppapi/c/ppb_file_system.h"
#include "ppapi/c/ppb_fullscreen.h"
#include "ppapi/c/ppb_graphics_2d.h"
#include "ppapi/c/ppb_graphics_3d.h"
#include "ppapi/c/ppb_image_data.h"
#include "ppapi/c/ppb_input_event.h"
#include "ppapi/c/ppb_instance.h"
#include "ppapi/c/ppb_messaging.h"
#include "ppapi/c/ppb_opengles2.h"
#include "ppapi/c/ppb_url_loader.h"
#include "ppapi/c/ppb_url_request_info.h"
#include "ppapi/c/ppb_url_response_info.h"
#include "ppapi/c/ppb_var.h"

#include "native_client/tests/ppapi_test_lib/get_browser_interface.h"
#include "native_client/tests/ppapi_test_lib/internal_utils.h"

const void* GetBrowserInterface(const char* interface_name) {
  return (*ppb_get_interface())(interface_name);
}

const void* GetBrowserInterfaceSafe(const char* interface_name) {
  const void* ppb_interface = (*ppb_get_interface())(interface_name);
  CHECK(ppb_interface != NULL);
  return ppb_interface;
}

// Stable interfaces.

const PPB_Core* PPBCore() {
  return reinterpret_cast<const PPB_Core*>(
      GetBrowserInterfaceSafe(PPB_CORE_INTERFACE));
}

const PPB_FileIO* PPBFileIO() {
  return reinterpret_cast<const PPB_FileIO*>(
      GetBrowserInterface(PPB_FILEIO_INTERFACE));
}

const PPB_FileRef* PPBFileRef() {
  return reinterpret_cast<const PPB_FileRef*>(
      GetBrowserInterface(PPB_FILEREF_INTERFACE));
}

const PPB_FileSystem* PPBFileSystem() {
  return reinterpret_cast<const PPB_FileSystem*>(
      GetBrowserInterface(PPB_FILESYSTEM_INTERFACE));
}

const PPB_Fullscreen* PPBFullscreen() {
  return reinterpret_cast<const PPB_Fullscreen*>(
      GetBrowserInterfaceSafe(PPB_FULLSCREEN_INTERFACE));
}

const PPB_Graphics2D* PPBGraphics2D() {
  return reinterpret_cast<const PPB_Graphics2D*>(
      GetBrowserInterfaceSafe(PPB_GRAPHICS_2D_INTERFACE));
}

const PPB_Graphics3D* PPBGraphics3D() {
  return reinterpret_cast<const PPB_Graphics3D*>(
      GetBrowserInterface(PPB_GRAPHICS_3D_INTERFACE));
}

const PPB_ImageData* PPBImageData() {
  return reinterpret_cast<const PPB_ImageData*>(
      GetBrowserInterfaceSafe(PPB_IMAGEDATA_INTERFACE));
}

const PPB_InputEvent* PPBInputEvent() {
  return reinterpret_cast<const PPB_InputEvent*>(
      GetBrowserInterfaceSafe(PPB_INPUT_EVENT_INTERFACE));
}

const PPB_Instance* PPBInstance() {
  return reinterpret_cast<const PPB_Instance*>(
      GetBrowserInterfaceSafe(PPB_INSTANCE_INTERFACE));
}

const PPB_KeyboardInputEvent* PPBKeyboardInputEvent() {
  return reinterpret_cast<const PPB_KeyboardInputEvent*>(
      GetBrowserInterfaceSafe(PPB_KEYBOARD_INPUT_EVENT_INTERFACE));
}

const PPB_Messaging* PPBMessaging() {
  return reinterpret_cast<const PPB_Messaging*>(
      GetBrowserInterfaceSafe(PPB_MESSAGING_INTERFACE));
}

const PPB_MouseInputEvent* PPBMouseInputEvent() {
  return reinterpret_cast<const PPB_MouseInputEvent*>(
      GetBrowserInterfaceSafe(PPB_MOUSE_INPUT_EVENT_INTERFACE));
}

const PPB_OpenGLES2* PPBOpenGLES2() {
  return reinterpret_cast<const PPB_OpenGLES2*>(
      GetBrowserInterface(PPB_OPENGLES2_INTERFACE));
}

const PPB_URLLoader* PPBURLLoader() {
  return reinterpret_cast<const PPB_URLLoader*>(
      GetBrowserInterfaceSafe(PPB_URLLOADER_INTERFACE));
}

const PPB_URLRequestInfo* PPBURLRequestInfo() {
  return reinterpret_cast<const PPB_URLRequestInfo*>(
      GetBrowserInterfaceSafe(PPB_URLREQUESTINFO_INTERFACE));
}

const PPB_URLResponseInfo* PPBURLResponseInfo() {
  return reinterpret_cast<const PPB_URLResponseInfo*>(
      GetBrowserInterfaceSafe(PPB_URLRESPONSEINFO_INTERFACE));
}

const PPB_Var* PPBVar() {
  return reinterpret_cast<const PPB_Var*>(
      GetBrowserInterfaceSafe(PPB_VAR_INTERFACE));
}

const PPB_WheelInputEvent* PPBWheelInputEvent() {
  return reinterpret_cast<const PPB_WheelInputEvent*>(
      GetBrowserInterfaceSafe(PPB_WHEEL_INPUT_EVENT_INTERFACE));
}

// Dev interfaces.

const PPB_Context3D_Dev* PPBContext3DDev() {
  return reinterpret_cast<const PPB_Context3D_Dev*>(
      GetBrowserInterface(PPB_CONTEXT_3D_DEV_INTERFACE));
}

const PPB_CursorControl_Dev* PPBCursorControlDev() {
  return reinterpret_cast<const PPB_CursorControl_Dev*>(
      GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
}

const PPB_Font_Dev* PPBFontDev() {
  return reinterpret_cast<const PPB_Font_Dev*>(
      GetBrowserInterface(PPB_FONT_DEV_INTERFACE));
}

const PPB_Memory_Dev* PPBMemoryDev() {
  return reinterpret_cast<const PPB_Memory_Dev*>(
      GetBrowserInterface(PPB_MEMORY_DEV_INTERFACE));
}

const PPB_Scrollbar_Dev* PPBScrollbarDev() {
  return  reinterpret_cast<const PPB_Scrollbar_Dev*>(
      GetBrowserInterface(PPB_SCROLLBAR_DEV_INTERFACE));
}

const PPB_Surface3D_Dev* PPBSurface3DDev() {
  return  reinterpret_cast<const PPB_Surface3D_Dev*>(
      GetBrowserInterface(PPB_SURFACE_3D_DEV_INTERFACE));
}

const PPB_Testing_Dev* PPBTestingDev() {
  return  reinterpret_cast<const PPB_Testing_Dev*>(
      GetBrowserInterface(PPB_TESTING_DEV_INTERFACE));
}

const PPB_Widget_Dev* PPBWidgetDev() {
  return  reinterpret_cast<const PPB_Widget_Dev*>(
      GetBrowserInterface(PPB_WIDGET_DEV_INTERFACE));
}
<commit_msg>ppapi_test_lib: Update all stable interface getters to CHECK for their presence. <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 "native_client/src/shared/platform/nacl_check.h"

#include "ppapi/c/dev/ppb_context_3d_dev.h"
#include "ppapi/c/dev/ppb_cursor_control_dev.h"
#include "ppapi/c/dev/ppb_font_dev.h"
#include "ppapi/c/dev/ppb_memory_dev.h"
#include "ppapi/c/dev/ppb_scrollbar_dev.h"
#include "ppapi/c/dev/ppb_surface_3d_dev.h"
#include "ppapi/c/dev/ppb_testing_dev.h"
#include "ppapi/c/dev/ppb_var_deprecated.h"
#include "ppapi/c/dev/ppb_widget_dev.h"
#include "ppapi/c/ppb_core.h"
#include "ppapi/c/ppb_file_io.h"
#include "ppapi/c/ppb_file_ref.h"
#include "ppapi/c/ppb_file_system.h"
#include "ppapi/c/ppb_fullscreen.h"
#include "ppapi/c/ppb_graphics_2d.h"
#include "ppapi/c/ppb_graphics_3d.h"
#include "ppapi/c/ppb_image_data.h"
#include "ppapi/c/ppb_input_event.h"
#include "ppapi/c/ppb_instance.h"
#include "ppapi/c/ppb_messaging.h"
#include "ppapi/c/ppb_opengles2.h"
#include "ppapi/c/ppb_url_loader.h"
#include "ppapi/c/ppb_url_request_info.h"
#include "ppapi/c/ppb_url_response_info.h"
#include "ppapi/c/ppb_var.h"

#include "native_client/tests/ppapi_test_lib/get_browser_interface.h"
#include "native_client/tests/ppapi_test_lib/internal_utils.h"

// Use for dev interfaces that might not be present.
const void* GetBrowserInterface(const char* interface_name) {
  return (*ppb_get_interface())(interface_name);
}

// Use for stable interfaces that must always be present.
const void* GetBrowserInterfaceSafe(const char* interface_name) {
  const void* ppb_interface = (*ppb_get_interface())(interface_name);
  CHECK(ppb_interface != NULL);
  return ppb_interface;
}

// Stable interfaces.

const PPB_Core* PPBCore() {
  return reinterpret_cast<const PPB_Core*>(
      GetBrowserInterfaceSafe(PPB_CORE_INTERFACE));
}

const PPB_FileIO* PPBFileIO() {
  return reinterpret_cast<const PPB_FileIO*>(
      GetBrowserInterfaceSafe(PPB_FILEIO_INTERFACE));
}

const PPB_FileRef* PPBFileRef() {
  return reinterpret_cast<const PPB_FileRef*>(
      GetBrowserInterfaceSafe(PPB_FILEREF_INTERFACE));
}

const PPB_FileSystem* PPBFileSystem() {
  return reinterpret_cast<const PPB_FileSystem*>(
      GetBrowserInterfaceSafe(PPB_FILESYSTEM_INTERFACE));
}

const PPB_Fullscreen* PPBFullscreen() {
  return reinterpret_cast<const PPB_Fullscreen*>(
      GetBrowserInterfaceSafe(PPB_FULLSCREEN_INTERFACE));
}

const PPB_Graphics2D* PPBGraphics2D() {
  return reinterpret_cast<const PPB_Graphics2D*>(
      GetBrowserInterfaceSafe(PPB_GRAPHICS_2D_INTERFACE));
}

const PPB_Graphics3D* PPBGraphics3D() {
  return reinterpret_cast<const PPB_Graphics3D*>(
      GetBrowserInterfaceSafe(PPB_GRAPHICS_3D_INTERFACE));
}

const PPB_ImageData* PPBImageData() {
  return reinterpret_cast<const PPB_ImageData*>(
      GetBrowserInterfaceSafe(PPB_IMAGEDATA_INTERFACE));
}

const PPB_InputEvent* PPBInputEvent() {
  return reinterpret_cast<const PPB_InputEvent*>(
      GetBrowserInterfaceSafe(PPB_INPUT_EVENT_INTERFACE));
}

const PPB_Instance* PPBInstance() {
  return reinterpret_cast<const PPB_Instance*>(
      GetBrowserInterfaceSafe(PPB_INSTANCE_INTERFACE));
}

const PPB_KeyboardInputEvent* PPBKeyboardInputEvent() {
  return reinterpret_cast<const PPB_KeyboardInputEvent*>(
      GetBrowserInterfaceSafe(PPB_KEYBOARD_INPUT_EVENT_INTERFACE));
}

const PPB_Messaging* PPBMessaging() {
  return reinterpret_cast<const PPB_Messaging*>(
      GetBrowserInterfaceSafe(PPB_MESSAGING_INTERFACE));
}

const PPB_MouseInputEvent* PPBMouseInputEvent() {
  return reinterpret_cast<const PPB_MouseInputEvent*>(
      GetBrowserInterfaceSafe(PPB_MOUSE_INPUT_EVENT_INTERFACE));
}

const PPB_OpenGLES2* PPBOpenGLES2() {
  return reinterpret_cast<const PPB_OpenGLES2*>(
      GetBrowserInterfaceSafe(PPB_OPENGLES2_INTERFACE));
}

const PPB_URLLoader* PPBURLLoader() {
  return reinterpret_cast<const PPB_URLLoader*>(
      GetBrowserInterfaceSafe(PPB_URLLOADER_INTERFACE));
}

const PPB_URLRequestInfo* PPBURLRequestInfo() {
  return reinterpret_cast<const PPB_URLRequestInfo*>(
      GetBrowserInterfaceSafe(PPB_URLREQUESTINFO_INTERFACE));
}

const PPB_URLResponseInfo* PPBURLResponseInfo() {
  return reinterpret_cast<const PPB_URLResponseInfo*>(
      GetBrowserInterfaceSafe(PPB_URLRESPONSEINFO_INTERFACE));
}

const PPB_Var* PPBVar() {
  return reinterpret_cast<const PPB_Var*>(
      GetBrowserInterfaceSafe(PPB_VAR_INTERFACE));
}

const PPB_WheelInputEvent* PPBWheelInputEvent() {
  return reinterpret_cast<const PPB_WheelInputEvent*>(
      GetBrowserInterfaceSafe(PPB_WHEEL_INPUT_EVENT_INTERFACE));
}

// Dev interfaces.

const PPB_Context3D_Dev* PPBContext3DDev() {
  return reinterpret_cast<const PPB_Context3D_Dev*>(
      // Change to GetBrowserInterfaceSafe when moving out of dev.
      GetBrowserInterface(PPB_CONTEXT_3D_DEV_INTERFACE));
}

const PPB_CursorControl_Dev* PPBCursorControlDev() {
  return reinterpret_cast<const PPB_CursorControl_Dev*>(
      // Change to GetBrowserInterfaceSafe when moving out of dev.
      GetBrowserInterface(PPB_CURSOR_CONTROL_DEV_INTERFACE));
}

const PPB_Font_Dev* PPBFontDev() {
  return reinterpret_cast<const PPB_Font_Dev*>(
      // Change to GetBrowserInterfaceSafe when moving out of dev.
      GetBrowserInterface(PPB_FONT_DEV_INTERFACE));
}

const PPB_Memory_Dev* PPBMemoryDev() {
  return reinterpret_cast<const PPB_Memory_Dev*>(
      // Change to GetBrowserInterfaceSafe when moving out of dev.
      GetBrowserInterface(PPB_MEMORY_DEV_INTERFACE));
}

const PPB_Scrollbar_Dev* PPBScrollbarDev() {
  return  reinterpret_cast<const PPB_Scrollbar_Dev*>(
      // Change to GetBrowserInterfaceSafe when moving out of dev.
      GetBrowserInterface(PPB_SCROLLBAR_DEV_INTERFACE));
}

const PPB_Surface3D_Dev* PPBSurface3DDev() {
  return  reinterpret_cast<const PPB_Surface3D_Dev*>(
      // Change to GetBrowserInterfaceSafe when moving out of dev.
      GetBrowserInterface(PPB_SURFACE_3D_DEV_INTERFACE));
}

const PPB_Testing_Dev* PPBTestingDev() {
  return  reinterpret_cast<const PPB_Testing_Dev*>(
      // Change to GetBrowserInterfaceSafe when moving out of dev.
      GetBrowserInterface(PPB_TESTING_DEV_INTERFACE));
}

const PPB_Widget_Dev* PPBWidgetDev() {
  return  reinterpret_cast<const PPB_Widget_Dev*>(
      // Change to GetBrowserInterfaceSafe when moving out of dev.
      GetBrowserInterface(PPB_WIDGET_DEV_INTERFACE));
}
<|endoftext|>