<commit_before>/*
    Copyright 2012 Frederik Gladhorn <gladhorn@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) version 3, or any
    later version accepted by the membership of KDE e.V. (or its
    successor approved by the membership of KDE e.V.), which shall
    act as a proxy defined in Section 6 of version 3 of the license.

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

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

#include "accessibleobject.h"

#include <qstring.h>
#include <qdebug.h>

#include "accessibleobject_p.h"
#include "registry_p.h"

#include <atspi/atspi-constants.h>

using namespace QAccessibleClient;

AccessibleObject::AccessibleObject()
    :d(0)
{
}

AccessibleObject::AccessibleObject(RegistryPrivate *registryPrivate, const QString &service, const QString &path)
    :d(0)
{
    Q_ASSERT(registryPrivate);
    Q_ASSERT(!service.isEmpty());
    Q_ASSERT(!path.isEmpty());
    if (registryPrivate->m_cacheStrategy) {
        const QString id = path + service;
        d = registryPrivate->m_cacheStrategy->get(id);
        if (!d) {
            d = QSharedPointer<AccessibleObjectPrivate>(new AccessibleObjectPrivate(registryPrivate, service, path));
            registryPrivate->m_cacheStrategy->add(id, d);
        }
    } else {
        d = QSharedPointer<AccessibleObjectPrivate>(new AccessibleObjectPrivate(registryPrivate, service, path));
    }
}

AccessibleObject::AccessibleObject(const QSharedPointer<AccessibleObjectPrivate> &dd)
    :d(dd)
{
}

AccessibleObject::AccessibleObject(const AccessibleObject &other)
    : d(other.d)
{
}

AccessibleObject::~AccessibleObject()
{
}

QString AccessibleObject::id() const
{
    if (!d || !d->registryPrivate)
        return QString();
    return d->path + d->service;
}

QUrl AccessibleObject::url() const
{
    return d && d->registryPrivate ? d->registryPrivate->url(*this) : QUrl();
}

bool AccessibleObject::isValid() const
{
    return d && d->registryPrivate
             && (!d->service.isEmpty())
             && (!d->path.isEmpty())
             && (d->path != QLatin1String("/org/a11y/atspi/null"));
}

AccessibleObject &AccessibleObject::operator=(const AccessibleObject &other)
{
    d = other.d;
    return *this;
}

bool AccessibleObject::operator==(const AccessibleObject &other) const
{
    return (d == other.d) || (d && other.d && *d == *other.d);
}

RegistryPrivate* AccessibleObject::registryPrivate() const
{
    return d ? d->registryPrivate : 0;
}

QSharedPointer<AccessibleObjectPrivate> AccessibleObject::objectPrivate() const
{
    return d;
}

AccessibleObject AccessibleObject::parent() const
{
    return d->registryPrivate->parentAccessible(*this);
}

QList<AccessibleObject> AccessibleObject::children() const
{
    return d->registryPrivate->children(*this);
}

int AccessibleObject::childCount() const
{
    return d->registryPrivate->childCount(*this);
}

AccessibleObject AccessibleObject::child(int index) const
{
    return d->registryPrivate->child(*this, index);
}

int AccessibleObject::indexInParent() const
{
    return d->registryPrivate->indexInParent(*this);
}

QString AccessibleObject::name() const
{
    return d->registryPrivate->name(*this);
}

QString AccessibleObject::description() const
{
    return d->registryPrivate->description(*this);
}

AccessibleObject::Role AccessibleObject::role() const
{
    return d->registryPrivate->role(*this);
}

QString AccessibleObject::roleName() const
{
    return d->registryPrivate->roleName(*this);
}

QString AccessibleObject::localizedRoleName() const
{
    return d->registryPrivate->localizedRoleName(*this);
}

int AccessibleObject::layer() const
{
    return d->registryPrivate->layer(*this);
}

int AccessibleObject::mdiZOrder() const
{
    return d->registryPrivate->mdiZOrder(*this);
}

double AccessibleObject::alpha() const
{
    return d->registryPrivate->alpha(*this);
}

QRect AccessibleObject::boundingRect() const
{
    if( supportedInterfaces() & AccessibleObject::ComponentInterface ){
        return d->registryPrivate->boundingRect(*this);
    } else {
        qWarning() << "boundingRect called on accessible that does not implement component";
        return QRect();
    }
}

QRect AccessibleObject::characterRect(int offset) const
{
    if( supportedInterfaces() & AccessibleObject::TextInterface ){
        return d->registryPrivate->characterRect(*this, offset);
    } else {
        qWarning() << "characterRect called on accessible that does not implement text";
        return QRect();
    }
}

AccessibleObject::Interfaces AccessibleObject::supportedInterfaces() const
{
    return d->registryPrivate->supportedInterfaces(*this);
}

int AccessibleObject::caretOffset() const
{
    if( supportedInterfaces() & AccessibleObject::TextInterface ){
        return d->registryPrivate->caretOffset(*this);
    } else {
        qWarning() << "caretOffset called on accessible that does not implement text";
        return 0;
    }
}

QPoint AccessibleObject::focusPoint() const
{
    Interfaces ifaces = supportedInterfaces();
    if (ifaces & TextInterface) {
        int offset = caretOffset();
        QRect r = characterRect(offset);
        if (r.x() != 0 || r.y() != 0)
            return r.center();
    }
    if (ifaces & ComponentInterface) {
        QRect r = boundingRect();
        if (!r.isNull())
            return r.center();
    }
    AccessibleObject p = parent();
    if (p.isValid())
        return p.focusPoint(); // recursive
    return QPoint();
}

AccessibleObject AccessibleObject::application() const
{
    return d->registryPrivate->application(*this);
}

QString AccessibleObject::appToolkitName() const
{
    return d->registryPrivate->appToolkitName(*this);
}

QString AccessibleObject::appVersion() const
{
    return d->registryPrivate->appVersion(*this);
}

int AccessibleObject::appId() const
{
    return d->registryPrivate->appId(*this);
}

QString AccessibleObject::appLocale(LocaleType lctype) const
{
    return d->registryPrivate->appLocale(*this, lctype);
}

QString AccessibleObject::appBusAddress() const
{
    return d->registryPrivate->appBusAddress(*this);
}

double AccessibleObject::minimumValue() const
{
    return d->registryPrivate->minimumValue(*this);
}

double AccessibleObject::maximumValue() const
{
    return d->registryPrivate->maximumValue(*this);
}

double AccessibleObject::minimumValueIncrement() const
{
    return d->registryPrivate->minimumValueIncrement(*this);
}

double AccessibleObject::currentValue() const
{
    return d->registryPrivate->currentValue(*this);
}

QList<AccessibleObject> AccessibleObject::selection() const
{
    return d->registryPrivate->selection(*this);
}

QString AccessibleObject::imageDescription() const
{
    return d->registryPrivate->imageDescription(*this);
}

QString AccessibleObject::imageLocale() const
{
    return d->registryPrivate->imageLocale(*this);
}

QRect AccessibleObject::imageRect() const
{
    return d->registryPrivate->imageRect(*this);
}

QVector< QSharedPointer<QAction> > AccessibleObject::actions() const
{
    // Actions in atspi are supposed to be static what means they cannot change in
    // between (e.g. actions removed or added or edited) so we can safely just
    // fetch them only once and store the result for the life-time of the object,
    if (!d->actionsFetched) {
        d->actionsFetched = true;
        d->actions = d->registryPrivate->actions(*this);
    }
    return d->actions;
}

bool AccessibleObject::hasSelectableText() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTABLE_TEXT);
}

bool AccessibleObject::hasToolTip() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_HAS_TOOLTIP);
}

bool AccessibleObject::isActive() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_ACTIVE);
}

bool AccessibleObject::isCheckable() const
{
    //FIXME: Find better AccessibleObject::isCheckable
    //return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_);

    Role role = d->registryPrivate->role(*this);
    if (role == AccessibleObject::CheckBox ||
        role == AccessibleObject::CheckableMenuItem ||
        role == AccessibleObject::RadioButton ||
        role == AccessibleObject::RadioMenuItem ||
        role == AccessibleObject::ToggleButton)
            return true;
    return false;
}

bool AccessibleObject::isChecked() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_CHECKED);
}

bool AccessibleObject::isDefunct() const
{
    return d->defunct;
}

bool AccessibleObject::isDefault() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_IS_DEFAULT);
}

bool AccessibleObject::isEditable() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EDITABLE);
}

bool AccessibleObject::isEnabled() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_ENABLED);
}

bool AccessibleObject::isExpandable() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EXPANDABLE);
}

bool AccessibleObject::isExpanded() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EXPANDED);
}

bool AccessibleObject::isFocusable() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_FOCUSABLE);
}

bool AccessibleObject::isFocused() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_FOCUSED);
}

bool AccessibleObject::isMultiLine() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_MULTI_LINE);
}

bool AccessibleObject::isSelectable() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTABLE);
}

bool AccessibleObject::isSelected() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTED);
}

bool AccessibleObject::isSensitive() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SENSITIVE);
}

bool AccessibleObject::isSingleLine() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SINGLE_LINE);
}

bool AccessibleObject::isVisible() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_VISIBLE);
}

bool AccessibleObject::supportsAutocompletion() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SUPPORTS_AUTOCOMPLETION);
}

#ifndef QT_NO_DEBUG_STREAM
QACCESSIBILITYCLIENT_EXPORT QDebug QAccessibleClient::operator<<(QDebug d, const AccessibleObject &object)
{
    d.nospace();
    d << "AccessibleObject("; //d:" << hex << (void *) object.d << dec;
    d << "service=" << object.d->service;
    d << " path=" << object.d->path;
    d << ")";
    return d.space();
}
#endif

uint qHash(const QAccessibleClient::AccessibleObject& object) {
    return qHash(object.d);
}
<commit_msg>Do not crash when using invalid objects in debug stream.<commit_after>/*
    Copyright 2012 Frederik Gladhorn <gladhorn@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) version 3, or any
    later version accepted by the membership of KDE e.V. (or its
    successor approved by the membership of KDE e.V.), which shall
    act as a proxy defined in Section 6 of version 3 of the license.

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

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

#include "accessibleobject.h"

#include <qstring.h>
#include <qdebug.h>

#include "accessibleobject_p.h"
#include "registry_p.h"

#include <atspi/atspi-constants.h>

using namespace QAccessibleClient;

AccessibleObject::AccessibleObject()
    :d(0)
{
}

AccessibleObject::AccessibleObject(RegistryPrivate *registryPrivate, const QString &service, const QString &path)
    :d(0)
{
    Q_ASSERT(registryPrivate);
    Q_ASSERT(!service.isEmpty());
    Q_ASSERT(!path.isEmpty());
    if (registryPrivate->m_cacheStrategy) {
        const QString id = path + service;
        d = registryPrivate->m_cacheStrategy->get(id);
        if (!d) {
            d = QSharedPointer<AccessibleObjectPrivate>(new AccessibleObjectPrivate(registryPrivate, service, path));
            registryPrivate->m_cacheStrategy->add(id, d);
        }
    } else {
        d = QSharedPointer<AccessibleObjectPrivate>(new AccessibleObjectPrivate(registryPrivate, service, path));
    }
}

AccessibleObject::AccessibleObject(const QSharedPointer<AccessibleObjectPrivate> &dd)
    :d(dd)
{
}

AccessibleObject::AccessibleObject(const AccessibleObject &other)
    : d(other.d)
{
}

AccessibleObject::~AccessibleObject()
{
}

QString AccessibleObject::id() const
{
    if (!d || !d->registryPrivate)
        return QString();
    return d->path + d->service;
}

QUrl AccessibleObject::url() const
{
    return d && d->registryPrivate ? d->registryPrivate->url(*this) : QUrl();
}

bool AccessibleObject::isValid() const
{
    return d && d->registryPrivate
             && (!d->service.isEmpty())
             && (!d->path.isEmpty())
             && (d->path != QLatin1String("/org/a11y/atspi/null"));
}

AccessibleObject &AccessibleObject::operator=(const AccessibleObject &other)
{
    d = other.d;
    return *this;
}

bool AccessibleObject::operator==(const AccessibleObject &other) const
{
    return (d == other.d) || (d && other.d && *d == *other.d);
}

RegistryPrivate* AccessibleObject::registryPrivate() const
{
    return d ? d->registryPrivate : 0;
}

QSharedPointer<AccessibleObjectPrivate> AccessibleObject::objectPrivate() const
{
    return d;
}

AccessibleObject AccessibleObject::parent() const
{
    return d->registryPrivate->parentAccessible(*this);
}

QList<AccessibleObject> AccessibleObject::children() const
{
    return d->registryPrivate->children(*this);
}

int AccessibleObject::childCount() const
{
    return d->registryPrivate->childCount(*this);
}

AccessibleObject AccessibleObject::child(int index) const
{
    return d->registryPrivate->child(*this, index);
}

int AccessibleObject::indexInParent() const
{
    return d->registryPrivate->indexInParent(*this);
}

QString AccessibleObject::name() const
{
    return d->registryPrivate->name(*this);
}

QString AccessibleObject::description() const
{
    return d->registryPrivate->description(*this);
}

AccessibleObject::Role AccessibleObject::role() const
{
    return d->registryPrivate->role(*this);
}

QString AccessibleObject::roleName() const
{
    return d->registryPrivate->roleName(*this);
}

QString AccessibleObject::localizedRoleName() const
{
    return d->registryPrivate->localizedRoleName(*this);
}

int AccessibleObject::layer() const
{
    return d->registryPrivate->layer(*this);
}

int AccessibleObject::mdiZOrder() const
{
    return d->registryPrivate->mdiZOrder(*this);
}

double AccessibleObject::alpha() const
{
    return d->registryPrivate->alpha(*this);
}

QRect AccessibleObject::boundingRect() const
{
    if( supportedInterfaces() & AccessibleObject::ComponentInterface ){
        return d->registryPrivate->boundingRect(*this);
    } else {
        qWarning() << "boundingRect called on accessible that does not implement component";
        return QRect();
    }
}

QRect AccessibleObject::characterRect(int offset) const
{
    if( supportedInterfaces() & AccessibleObject::TextInterface ){
        return d->registryPrivate->characterRect(*this, offset);
    } else {
        qWarning() << "characterRect called on accessible that does not implement text";
        return QRect();
    }
}

AccessibleObject::Interfaces AccessibleObject::supportedInterfaces() const
{
    return d->registryPrivate->supportedInterfaces(*this);
}

int AccessibleObject::caretOffset() const
{
    if( supportedInterfaces() & AccessibleObject::TextInterface ){
        return d->registryPrivate->caretOffset(*this);
    } else {
        qWarning() << "caretOffset called on accessible that does not implement text";
        return 0;
    }
}

QPoint AccessibleObject::focusPoint() const
{
    Interfaces ifaces = supportedInterfaces();
    if (ifaces & TextInterface) {
        int offset = caretOffset();
        QRect r = characterRect(offset);
        if (r.x() != 0 || r.y() != 0)
            return r.center();
    }
    if (ifaces & ComponentInterface) {
        QRect r = boundingRect();
        if (!r.isNull())
            return r.center();
    }
    AccessibleObject p = parent();
    if (p.isValid())
        return p.focusPoint(); // recursive
    return QPoint();
}

AccessibleObject AccessibleObject::application() const
{
    return d->registryPrivate->application(*this);
}

QString AccessibleObject::appToolkitName() const
{
    return d->registryPrivate->appToolkitName(*this);
}

QString AccessibleObject::appVersion() const
{
    return d->registryPrivate->appVersion(*this);
}

int AccessibleObject::appId() const
{
    return d->registryPrivate->appId(*this);
}

QString AccessibleObject::appLocale(LocaleType lctype) const
{
    return d->registryPrivate->appLocale(*this, lctype);
}

QString AccessibleObject::appBusAddress() const
{
    return d->registryPrivate->appBusAddress(*this);
}

double AccessibleObject::minimumValue() const
{
    return d->registryPrivate->minimumValue(*this);
}

double AccessibleObject::maximumValue() const
{
    return d->registryPrivate->maximumValue(*this);
}

double AccessibleObject::minimumValueIncrement() const
{
    return d->registryPrivate->minimumValueIncrement(*this);
}

double AccessibleObject::currentValue() const
{
    return d->registryPrivate->currentValue(*this);
}

QList<AccessibleObject> AccessibleObject::selection() const
{
    return d->registryPrivate->selection(*this);
}

QString AccessibleObject::imageDescription() const
{
    return d->registryPrivate->imageDescription(*this);
}

QString AccessibleObject::imageLocale() const
{
    return d->registryPrivate->imageLocale(*this);
}

QRect AccessibleObject::imageRect() const
{
    return d->registryPrivate->imageRect(*this);
}

QVector< QSharedPointer<QAction> > AccessibleObject::actions() const
{
    // Actions in atspi are supposed to be static what means they cannot change in
    // between (e.g. actions removed or added or edited) so we can safely just
    // fetch them only once and store the result for the life-time of the object,
    if (!d->actionsFetched) {
        d->actionsFetched = true;
        d->actions = d->registryPrivate->actions(*this);
    }
    return d->actions;
}

bool AccessibleObject::hasSelectableText() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTABLE_TEXT);
}

bool AccessibleObject::hasToolTip() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_HAS_TOOLTIP);
}

bool AccessibleObject::isActive() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_ACTIVE);
}

bool AccessibleObject::isCheckable() const
{
    //FIXME: Find better AccessibleObject::isCheckable
    //return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_);

    Role role = d->registryPrivate->role(*this);
    if (role == AccessibleObject::CheckBox ||
        role == AccessibleObject::CheckableMenuItem ||
        role == AccessibleObject::RadioButton ||
        role == AccessibleObject::RadioMenuItem ||
        role == AccessibleObject::ToggleButton)
            return true;
    return false;
}

bool AccessibleObject::isChecked() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_CHECKED);
}

bool AccessibleObject::isDefunct() const
{
    return d->defunct;
}

bool AccessibleObject::isDefault() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_IS_DEFAULT);
}

bool AccessibleObject::isEditable() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EDITABLE);
}

bool AccessibleObject::isEnabled() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_ENABLED);
}

bool AccessibleObject::isExpandable() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EXPANDABLE);
}

bool AccessibleObject::isExpanded() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_EXPANDED);
}

bool AccessibleObject::isFocusable() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_FOCUSABLE);
}

bool AccessibleObject::isFocused() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_FOCUSED);
}

bool AccessibleObject::isMultiLine() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_MULTI_LINE);
}

bool AccessibleObject::isSelectable() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTABLE);
}

bool AccessibleObject::isSelected() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SELECTED);
}

bool AccessibleObject::isSensitive() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SENSITIVE);
}

bool AccessibleObject::isSingleLine() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SINGLE_LINE);
}

bool AccessibleObject::isVisible() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_VISIBLE);
}

bool AccessibleObject::supportsAutocompletion() const
{
    return d->registryPrivate->state(*this) & (quint64(1) << ATSPI_STATE_SUPPORTS_AUTOCOMPLETION);
}

#ifndef QT_NO_DEBUG_STREAM
QACCESSIBILITYCLIENT_EXPORT QDebug QAccessibleClient::operator<<(QDebug d, const AccessibleObject &object)
{
    d.nospace();
    d << "AccessibleObject("; //d:" << hex << (void *) object.d << dec;
    if (object.d) {
        d << "service=" << object.d->service;
        d << " path=" << object.d->path;
    } else {
        d << "invalid";
    }
    d << ")";
    return d.space();
}
#endif

uint qHash(const QAccessibleClient::AccessibleObject& object) {
    return qHash(object.d);
}
<|endoftext|>


<commit_before>#include "commandlineflags.h"

#ifdef USE_STD_NAMESPACE

namespace tesseract {
bool IntFlagExists(const char* flag_name, inT32* value) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<IntParam*> empty;
  IntParam *p = ParamUtils::FindParam<IntParam>(
      full_flag_name.string(), GlobalParams()->int_params, empty);
  if (p == NULL) return false;
  *value = (inT32)(*p);
  return true;
}

bool DoubleFlagExists(const char* flag_name, double* value) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<DoubleParam*> empty;
  DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
      full_flag_name.string(), GlobalParams()->double_params, empty);
  if (p == NULL) return false;
  *value = static_cast<double>(*p);
  return true;
}

bool BoolFlagExists(const char* flag_name, bool* value) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<BoolParam*> empty;
  BoolParam *p = ParamUtils::FindParam<BoolParam>(
      full_flag_name.string(), GlobalParams()->bool_params, empty);
  if (p == NULL) return false;
  *value = (BOOL8)(*p);
  return true;
}

bool StringFlagExists(const char* flag_name, const char** value) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<StringParam*> empty;
  StringParam *p = ParamUtils::FindParam<StringParam>(
      full_flag_name.string(), GlobalParams()->string_params, empty);
  *value = (p != NULL) ? p->string() : NULL;
  return p != NULL;
}

void SetIntFlagValue(const char* flag_name, const inT32 new_val) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<IntParam*> empty;
  IntParam *p = ParamUtils::FindParam<IntParam>(
      full_flag_name.string(), GlobalParams()->int_params, empty);
  ASSERT_HOST(p != NULL);
  p->set_value(new_val);
}

void SetDoubleFlagValue(const char* flag_name, const double new_val) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<DoubleParam*> empty;
  DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
      full_flag_name.string(), GlobalParams()->double_params, empty);
  ASSERT_HOST(p != NULL);
  p->set_value(new_val);
}

void SetBoolFlagValue(const char* flag_name, const bool new_val) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<BoolParam*> empty;
  BoolParam *p = ParamUtils::FindParam<BoolParam>(
      full_flag_name.string(), GlobalParams()->bool_params, empty);
  ASSERT_HOST(p != NULL);
  p->set_value(new_val);
}

void SetStringFlagValue(const char* flag_name, const char* new_val) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<StringParam*> empty;
  StringParam *p = ParamUtils::FindParam<StringParam>(
      full_flag_name.string(), GlobalParams()->string_params, empty);
  ASSERT_HOST(p != NULL);
  p->set_value(STRING(new_val));
}

bool SafeAtoi(const char* str, int* val) {
  char *endptr = NULL;
  *val = strtol(str, &endptr, 10);
  return endptr != NULL && *endptr == '\0';
}

bool SafeAtod(const char* str, double* val) {
  char *endptr = NULL;
  *val = strtod(str, &endptr);
  return endptr != NULL && *endptr == '\0';
}

void PrintCommandLineFlags() {
  const char* kFlagNamePrefix = "FLAGS_";
  const int kFlagNamePrefixLen = strlen(kFlagNamePrefix);
  for (int i = 0; i < GlobalParams()->int_params.size(); ++i) {
    if (!strncmp(GlobalParams()->int_params[i]->name_str(),
                 kFlagNamePrefix, kFlagNamePrefixLen)) {
      tprintf("  --%s  %s  (type:int default:%d)\n",
              GlobalParams()->int_params[i]->name_str() + kFlagNamePrefixLen,
              GlobalParams()->int_params[i]->info_str(),
              inT32(*(GlobalParams()->int_params[i])));
    }
  }
  for (int i = 0; i < GlobalParams()->double_params.size(); ++i) {
    if (!strncmp(GlobalParams()->double_params[i]->name_str(),
                 kFlagNamePrefix, kFlagNamePrefixLen)) {
      tprintf("  --%s  %s  (type:double default:%g)\n",
              GlobalParams()->double_params[i]->name_str() + kFlagNamePrefixLen,
              GlobalParams()->double_params[i]->info_str(),
              static_cast<double>(*(GlobalParams()->double_params[i])));
    }
  }
  for (int i = 0; i < GlobalParams()->bool_params.size(); ++i) {
    if (!strncmp(GlobalParams()->bool_params[i]->name_str(),
                 kFlagNamePrefix, kFlagNamePrefixLen)) {
      tprintf("  --%s  %s  (type:bool default:%s)\n",
              GlobalParams()->bool_params[i]->name_str() + kFlagNamePrefixLen,
              GlobalParams()->bool_params[i]->info_str(),
              (BOOL8(*(GlobalParams()->bool_params[i])) ? "true" : "false"));
    }
  }
  for (int i = 0; i < GlobalParams()->string_params.size(); ++i) {
    if (!strncmp(GlobalParams()->string_params[i]->name_str(),
                 kFlagNamePrefix, kFlagNamePrefixLen)) {
      tprintf("  --%s  %s  (type:string default:%s)\n",
              GlobalParams()->string_params[i]->name_str() + kFlagNamePrefixLen,
              GlobalParams()->string_params[i]->info_str(),
              GlobalParams()->string_params[i]->string());
    }
  }
}

void ParseCommandLineFlags(const char* usage,
                           int* argc, char*** argv,
                           const bool remove_flags) {
  unsigned int i = 1;
  for (i = 1; i < *argc; ++i) {
    const char* current_arg = (*argv)[i];
    // If argument does not start with a hyphen then break.
    if (current_arg[0] != '-') {
      break;
    }
    // Position current_arg after startings hyphens. We treat a sequence of
    // consecutive hyphens of any length identically.
    while (*current_arg == '-') {
      ++current_arg;
    }
    // If this is asking for usage, print the help message and abort.
    if (!strcmp(current_arg, "help") ||
        !strcmp(current_arg, "helpshort")) {
      tprintf("USAGE: %s\n", usage);
      PrintCommandLineFlags();
      exit(0);
    }
    // Find the starting position of the value if it was specified in this
    // string.
    const char* equals_position = strchr(current_arg, '=');
    const char* rhs = NULL;
    if (equals_position != NULL) {
      rhs = equals_position + 1;
    }
    // Extract the flag name.
    STRING lhs;
    if (equals_position == NULL) {
      lhs = current_arg;
    } else {
      lhs.assign(current_arg, equals_position - current_arg);
    }
    if (!lhs.length()) {
      tprintf("ERROR: Bad argument: %s\n", (*argv)[i]);
      exit(1);
    }

    // Find the flag name in the list of global flags.
    // inT32 flag
    inT32 int_val;
    if (IntFlagExists(lhs.string(), &int_val)) {
      if (rhs != NULL) {
        if (!strlen(rhs)) {
          // Bad input of the format --int_flag=
          tprintf("ERROR: Bad argument: %s\n", (*argv)[i]);
          exit(1);
        }
        if (!SafeAtoi(rhs, &int_val)) {
          tprintf("ERROR: Could not parse int from %s in flag %s\n",
                  rhs, (*argv)[i]);
          exit(1);
        }
      } else {
        // We need to parse the next argument
        if (i + 1 >= *argc) {
          tprintf("ERROR: Could not find value argument for flag %s\n",
                  lhs.string());
          exit(1);
        } else {
          ++i;
          if (!SafeAtoi((*argv)[i], &int_val)) {
            tprintf("ERROR: Could not parse inT32 from %s\n", (*argv)[i]);
            exit(1);
          }
        }
      }
      SetIntFlagValue(lhs.string(), int_val);
      continue;
    }

    // double flag
    double double_val;
    if (DoubleFlagExists(lhs.string(), &double_val)) {
      if (rhs != NULL) {
        if (!strlen(rhs)) {
          // Bad input of the format --double_flag=
          tprintf("ERROR: Bad argument: %s\n", (*argv)[i]);
          exit(1);
        }
        if (!SafeAtod(rhs, &double_val)) {
          tprintf("ERROR: Could not parse double from %s in flag %s\n",
                  rhs, (*argv)[i]);
          exit(1);
        }
      } else {
        // We need to parse the next argument
        if (i + 1 >= *argc) {
          tprintf("ERROR: Could not find value argument for flag %s\n",
                  lhs.string());
          exit(1);
        } else {
          ++i;
          if (!SafeAtod((*argv)[i], &double_val)) {
            tprintf("ERROR: Could not parse double from %s\n", (*argv)[i]);
            exit(1);
          }
        }
      }
      SetDoubleFlagValue(lhs.string(), double_val);
      continue;
    }

    // Bool flag. Allow input forms --flag (equivalent to --flag=true),
    // --flag=false, --flag=true, --flag=0 and --flag=1
    bool bool_val;
    if (BoolFlagExists(lhs.string(), &bool_val)) {
      if (rhs == NULL) {
        // --flag form
        bool_val = true;
      } else {
        if (!strlen(rhs)) {
          // Bad input of the format --bool_flag=
          tprintf("ERROR: Bad argument: %s\n", (*argv)[i]);
          exit(1);
        }
        if (!strcmp(rhs, "false") || !strcmp(rhs, "0")) {
          bool_val = false;
        } else if (!strcmp(rhs, "true") || !strcmp(rhs, "1")) {
          bool_val = true;
        } else {
          tprintf("ERROR: Could not parse bool from flag %s\n", (*argv)[i]);
          exit(1);
        }
      }
      SetBoolFlagValue(lhs.string(), bool_val);
      continue;
    }

    // string flag
    const char* string_val;
    if (StringFlagExists(lhs.string(), &string_val)) {
      if (rhs != NULL) {
        string_val = rhs;
      } else {
        // Pick the next argument
        if (i + 1 >= *argc) {
          tprintf("ERROR: Could not find string value for flag %s\n",
                  lhs.string());
          exit(1);
        } else {
          string_val = (*argv)[++i];
        }
      }
      SetStringFlagValue(lhs.string(), string_val);
      continue;
    }

    // Flag was not found. Exit with an error message.
    tprintf("ERROR: Non-existent flag %s\n", (*argv)[i]);
    exit(1);
  }  // for each argv
  if (remove_flags) {
    (*argv)[i - 1] = (*argv)[0];
    (*argv) += (i - 1);
    (*argc) -= (i - 1);
  }
}
}  // namespace tesseract

#else

#include "base/init_google.h"

namespace tesseract {
void ParseCommandLineFlags(const char* usage,
                           int* argc, char*** argv,
                           const bool remove_flags) {
  InitGoogle(usage, argc, argv, remove_flags);
}
}  // namespace tesseract

#endif
<commit_msg>Training tools: Print help message when (argv == 1)<commit_after>#include "commandlineflags.h"

#ifdef USE_STD_NAMESPACE

namespace tesseract {
bool IntFlagExists(const char* flag_name, inT32* value) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<IntParam*> empty;
  IntParam *p = ParamUtils::FindParam<IntParam>(
      full_flag_name.string(), GlobalParams()->int_params, empty);
  if (p == NULL) return false;
  *value = (inT32)(*p);
  return true;
}

bool DoubleFlagExists(const char* flag_name, double* value) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<DoubleParam*> empty;
  DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
      full_flag_name.string(), GlobalParams()->double_params, empty);
  if (p == NULL) return false;
  *value = static_cast<double>(*p);
  return true;
}

bool BoolFlagExists(const char* flag_name, bool* value) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<BoolParam*> empty;
  BoolParam *p = ParamUtils::FindParam<BoolParam>(
      full_flag_name.string(), GlobalParams()->bool_params, empty);
  if (p == NULL) return false;
  *value = (BOOL8)(*p);
  return true;
}

bool StringFlagExists(const char* flag_name, const char** value) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<StringParam*> empty;
  StringParam *p = ParamUtils::FindParam<StringParam>(
      full_flag_name.string(), GlobalParams()->string_params, empty);
  *value = (p != NULL) ? p->string() : NULL;
  return p != NULL;
}

void SetIntFlagValue(const char* flag_name, const inT32 new_val) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<IntParam*> empty;
  IntParam *p = ParamUtils::FindParam<IntParam>(
      full_flag_name.string(), GlobalParams()->int_params, empty);
  ASSERT_HOST(p != NULL);
  p->set_value(new_val);
}

void SetDoubleFlagValue(const char* flag_name, const double new_val) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<DoubleParam*> empty;
  DoubleParam *p = ParamUtils::FindParam<DoubleParam>(
      full_flag_name.string(), GlobalParams()->double_params, empty);
  ASSERT_HOST(p != NULL);
  p->set_value(new_val);
}

void SetBoolFlagValue(const char* flag_name, const bool new_val) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<BoolParam*> empty;
  BoolParam *p = ParamUtils::FindParam<BoolParam>(
      full_flag_name.string(), GlobalParams()->bool_params, empty);
  ASSERT_HOST(p != NULL);
  p->set_value(new_val);
}

void SetStringFlagValue(const char* flag_name, const char* new_val) {
  STRING full_flag_name("FLAGS_");
  full_flag_name += flag_name;
  GenericVector<StringParam*> empty;
  StringParam *p = ParamUtils::FindParam<StringParam>(
      full_flag_name.string(), GlobalParams()->string_params, empty);
  ASSERT_HOST(p != NULL);
  p->set_value(STRING(new_val));
}

bool SafeAtoi(const char* str, int* val) {
  char *endptr = NULL;
  *val = strtol(str, &endptr, 10);
  return endptr != NULL && *endptr == '\0';
}

bool SafeAtod(const char* str, double* val) {
  char *endptr = NULL;
  *val = strtod(str, &endptr);
  return endptr != NULL && *endptr == '\0';
}

void PrintCommandLineFlags() {
  const char* kFlagNamePrefix = "FLAGS_";
  const int kFlagNamePrefixLen = strlen(kFlagNamePrefix);
  for (int i = 0; i < GlobalParams()->int_params.size(); ++i) {
    if (!strncmp(GlobalParams()->int_params[i]->name_str(),
                 kFlagNamePrefix, kFlagNamePrefixLen)) {
      tprintf("  --%s  %s  (type:int default:%d)\n",
              GlobalParams()->int_params[i]->name_str() + kFlagNamePrefixLen,
              GlobalParams()->int_params[i]->info_str(),
              inT32(*(GlobalParams()->int_params[i])));
    }
  }
  for (int i = 0; i < GlobalParams()->double_params.size(); ++i) {
    if (!strncmp(GlobalParams()->double_params[i]->name_str(),
                 kFlagNamePrefix, kFlagNamePrefixLen)) {
      tprintf("  --%s  %s  (type:double default:%g)\n",
              GlobalParams()->double_params[i]->name_str() + kFlagNamePrefixLen,
              GlobalParams()->double_params[i]->info_str(),
              static_cast<double>(*(GlobalParams()->double_params[i])));
    }
  }
  for (int i = 0; i < GlobalParams()->bool_params.size(); ++i) {
    if (!strncmp(GlobalParams()->bool_params[i]->name_str(),
                 kFlagNamePrefix, kFlagNamePrefixLen)) {
      tprintf("  --%s  %s  (type:bool default:%s)\n",
              GlobalParams()->bool_params[i]->name_str() + kFlagNamePrefixLen,
              GlobalParams()->bool_params[i]->info_str(),
              (BOOL8(*(GlobalParams()->bool_params[i])) ? "true" : "false"));
    }
  }
  for (int i = 0; i < GlobalParams()->string_params.size(); ++i) {
    if (!strncmp(GlobalParams()->string_params[i]->name_str(),
                 kFlagNamePrefix, kFlagNamePrefixLen)) {
      tprintf("  --%s  %s  (type:string default:%s)\n",
              GlobalParams()->string_params[i]->name_str() + kFlagNamePrefixLen,
              GlobalParams()->string_params[i]->info_str(),
              GlobalParams()->string_params[i]->string());
    }
  }
}

void ParseCommandLineFlags(const char* usage,
                           int* argc, char*** argv,
                           const bool remove_flags) {
  if (*argc == 1) {
    tprintf("USAGE: %s\n", usage);
    PrintCommandLineFlags();
    exit(0);
  }

  unsigned int i = 1;
  for (i = 1; i < *argc; ++i) {
    const char* current_arg = (*argv)[i];
    // If argument does not start with a hyphen then break.
    if (current_arg[0] != '-') {
      break;
    }
    // Position current_arg after startings hyphens. We treat a sequence of
    // consecutive hyphens of any length identically.
    while (*current_arg == '-') {
      ++current_arg;
    }
    // If this is asking for usage, print the help message and abort.
    if (!strcmp(current_arg, "help") ||
        !strcmp(current_arg, "helpshort")) {
      tprintf("USAGE: %s\n", usage);
      PrintCommandLineFlags();
      exit(0);
    }
    // Find the starting position of the value if it was specified in this
    // string.
    const char* equals_position = strchr(current_arg, '=');
    const char* rhs = NULL;
    if (equals_position != NULL) {
      rhs = equals_position + 1;
    }
    // Extract the flag name.
    STRING lhs;
    if (equals_position == NULL) {
      lhs = current_arg;
    } else {
      lhs.assign(current_arg, equals_position - current_arg);
    }
    if (!lhs.length()) {
      tprintf("ERROR: Bad argument: %s\n", (*argv)[i]);
      exit(1);
    }

    // Find the flag name in the list of global flags.
    // inT32 flag
    inT32 int_val;
    if (IntFlagExists(lhs.string(), &int_val)) {
      if (rhs != NULL) {
        if (!strlen(rhs)) {
          // Bad input of the format --int_flag=
          tprintf("ERROR: Bad argument: %s\n", (*argv)[i]);
          exit(1);
        }
        if (!SafeAtoi(rhs, &int_val)) {
          tprintf("ERROR: Could not parse int from %s in flag %s\n",
                  rhs, (*argv)[i]);
          exit(1);
        }
      } else {
        // We need to parse the next argument
        if (i + 1 >= *argc) {
          tprintf("ERROR: Could not find value argument for flag %s\n",
                  lhs.string());
          exit(1);
        } else {
          ++i;
          if (!SafeAtoi((*argv)[i], &int_val)) {
            tprintf("ERROR: Could not parse inT32 from %s\n", (*argv)[i]);
            exit(1);
          }
        }
      }
      SetIntFlagValue(lhs.string(), int_val);
      continue;
    }

    // double flag
    double double_val;
    if (DoubleFlagExists(lhs.string(), &double_val)) {
      if (rhs != NULL) {
        if (!strlen(rhs)) {
          // Bad input of the format --double_flag=
          tprintf("ERROR: Bad argument: %s\n", (*argv)[i]);
          exit(1);
        }
        if (!SafeAtod(rhs, &double_val)) {
          tprintf("ERROR: Could not parse double from %s in flag %s\n",
                  rhs, (*argv)[i]);
          exit(1);
        }
      } else {
        // We need to parse the next argument
        if (i + 1 >= *argc) {
          tprintf("ERROR: Could not find value argument for flag %s\n",
                  lhs.string());
          exit(1);
        } else {
          ++i;
          if (!SafeAtod((*argv)[i], &double_val)) {
            tprintf("ERROR: Could not parse double from %s\n", (*argv)[i]);
            exit(1);
          }
        }
      }
      SetDoubleFlagValue(lhs.string(), double_val);
      continue;
    }

    // Bool flag. Allow input forms --flag (equivalent to --flag=true),
    // --flag=false, --flag=true, --flag=0 and --flag=1
    bool bool_val;
    if (BoolFlagExists(lhs.string(), &bool_val)) {
      if (rhs == NULL) {
        // --flag form
        bool_val = true;
      } else {
        if (!strlen(rhs)) {
          // Bad input of the format --bool_flag=
          tprintf("ERROR: Bad argument: %s\n", (*argv)[i]);
          exit(1);
        }
        if (!strcmp(rhs, "false") || !strcmp(rhs, "0")) {
          bool_val = false;
        } else if (!strcmp(rhs, "true") || !strcmp(rhs, "1")) {
          bool_val = true;
        } else {
          tprintf("ERROR: Could not parse bool from flag %s\n", (*argv)[i]);
          exit(1);
        }
      }
      SetBoolFlagValue(lhs.string(), bool_val);
      continue;
    }

    // string flag
    const char* string_val;
    if (StringFlagExists(lhs.string(), &string_val)) {
      if (rhs != NULL) {
        string_val = rhs;
      } else {
        // Pick the next argument
        if (i + 1 >= *argc) {
          tprintf("ERROR: Could not find string value for flag %s\n",
                  lhs.string());
          exit(1);
        } else {
          string_val = (*argv)[++i];
        }
      }
      SetStringFlagValue(lhs.string(), string_val);
      continue;
    }

    // Flag was not found. Exit with an error message.
    tprintf("ERROR: Non-existent flag %s\n", (*argv)[i]);
    exit(1);
  }  // for each argv
  if (remove_flags) {
    (*argv)[i - 1] = (*argv)[0];
    (*argv) += (i - 1);
    (*argc) -= (i - 1);
  }
}
}  // namespace tesseract

#else

#include "base/init_google.h"

namespace tesseract {
void ParseCommandLineFlags(const char* usage,
                           int* argc, char*** argv,
                           const bool remove_flags) {
  InitGoogle(usage, argc, argv, remove_flags);
}
}  // namespace tesseract

#endif
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          support.cpp
* Purpose:       Implementation of support classes
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/config.h>
#include <wx/stockitem.h> // for wxGetStockLabel
#include <wx/extension/filedlg.h>
#include <wx/extension/lexers.h>
#include <wx/extension/svn.h>
#ifndef __WXMSW__
#include "app.xpm"
#endif
#include "support.h"
#include "defs.h"

Frame::Frame()
  : wxExFrameWithHistory(
      NULL,
      wxID_ANY,
      wxTheApp->GetAppName(), //title
      NUMBER_RECENT_FILES,    //maxFiles
      4)                      // maxProjects
{
  SetIcon(wxICON(app));

#if wxUSE_STATUSBAR
  std::vector<wxExPane> panes;
  panes.push_back(wxExPane("PaneText", -3));
  panes.push_back(wxExPane("PaneFileType", 50, _("File Type")));
  panes.push_back(wxExPane("PaneLines", 100, _("Lines")));

  // Add the lexer pane only if we have lexers.
  if (wxExLexers::Get()->Count() > 0)
  {
#ifdef __WXMSW__
    const int lexer_size = 60;
#else
    const int lexer_size = 75;
#endif
    panes.push_back(wxExPane("PaneLexer", lexer_size, _("Lexer")));
  }

  panes.push_back(wxExPane("PaneItems", 65, _("Items")));
  SetupStatusBar(panes);
#endif

  wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE); // wxMB_DOCKABLE only used for GTK
  SetMenuBar(menubar);

  wxExMenu *menuFile = new wxExMenu();
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
  menuFile->Append(ID_OPEN_LEXERS, _("Open &Lexers"));
  menuFile->Append(ID_OPEN_LOGFILE, _("Open &Logfile"));
  menuFile->Append(wxID_CLOSE);
  menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE);
  menuFile->AppendSeparator();
  menuFile->AppendPrint();
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu *menuEdit = new wxExMenu();
  menuEdit->Append(wxID_UNDO);
  menuEdit->Append(wxID_REDO);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT);
  menuEdit->Append(wxID_COPY);
  menuEdit->Append(wxID_PASTE);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_FIND);
  menuEdit->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3"));
  menuEdit->Append(wxID_REPLACE);
  menuEdit->Append(ID_SPECIAL_FIND_IN_FILES, wxExEllipsed(_("Find &In Files")));
  menuEdit->Append(ID_SPECIAL_REPLACE_IN_FILES, wxExEllipsed(_("Replace In File&s")));
  menuEdit->AppendSeparator();
  menuEdit->AppendTools();
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_JUMP_TO);
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl+H"));
  menuEdit->AppendSeparator();

  if (wxExSVN::Get()->Use())
  {
    wxMenu* menuSVN = new wxMenu;
    menuSVN->Append(ID_SVN_STAT, wxExEllipsed("&Stat"));
    menuSVN->Append(ID_SVN_INFO, wxExEllipsed("&Info"));
    menuSVN->Append(ID_SVN_LOG, wxExEllipsed("&Log"));
    menuSVN->Append(ID_SVN_LS, wxExEllipsed("&Ls"));
    menuSVN->Append(ID_SVN_DIFF, wxExEllipsed("&Diff"));
    menuSVN->Append(ID_SVN_HELP, wxExEllipsed("&Help"));
    menuSVN->AppendSeparator();
    menuSVN->Append(ID_SVN_UPDATE, wxExEllipsed("&Update"));
    menuSVN->Append(ID_SVN_COMMIT, wxExEllipsed("C&ommit"));
    menuSVN->AppendSeparator();
    menuSVN->Append(ID_SVN_ADD, wxExEllipsed("&Add"));
    menuEdit->AppendSubMenu(menuSVN, "&SVN");
    menuEdit->AppendSeparator();
  }

  menuEdit->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
  menuEdit->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
  menuEdit->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M"));

  wxMenu *menuView = new wxMenu;
  menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
  menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
  menuView->AppendCheckItem(ID_VIEW_FINDBAR, _("&Findbar"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files"));
  menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects"));
  menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer"));
  menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output"));
  menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table"));
  menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History"));
#ifdef __WXMSW__
  wxMenu *menuListView = new wxMenu;
  menuListView->AppendCheckItem(wxID_VIEW_LIST, _("&List"));
  menuListView->AppendCheckItem(wxID_VIEW_DETAILS, _("&Detail"));
  menuListView->AppendCheckItem(wxID_VIEW_SMALLICONS, _("&Small Icon"));
  menuView->AppendSeparator();
  menuView->AppendSubMenu(menuListView, _("&Lists"));
#endif

  wxMenu *menuProcess = new wxMenu();
  menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select")));
  menuProcess->AppendSeparator();
  menuProcess->Append(wxID_EXECUTE);
  menuProcess->Append(wxID_STOP);

  wxExMenu *menuProject = new wxExMenu();
  menuProject->Append(ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW);
  menuProject->Append(ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN);
  UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
  menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text"));
  menuProject->Append(ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE));
  menuProject->AppendSeparator();
  menuProject->Append(ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE);
  menuProject->Append(ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS);
  menuProject->AppendSeparator();
  menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort"));

  wxMenu *menuWindow = new wxMenu();
  menuWindow->Append(ID_SPLIT, _("Split"));

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(ID_OPTION_SVN_AND_COMPARATOR, wxExEllipsed(_("Set SVN And &Comparator")));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font")));
  menuOptions->Append(ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set &List Read Only Colour")));
  wxMenu *menuListSort = new wxMenu;
  menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"));
  menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"));
  menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"));
  menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method"));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options")));

  wxMenu *menuHelp = new wxMenu();
  menuHelp->Append(wxID_ABOUT);

  menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
  menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuProcess, _("&Process"));
  menubar->Append(menuProject, _("&Project"));
  menubar->Append(menuWindow, _("&Window"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));

  CreateToolBar();

  m_ToolBar->AddTool(wxID_OPEN);
  m_ToolBar->AddTool(wxID_SAVE);
  m_ToolBar->AddTool(wxID_PRINT);
  m_ToolBar->AddSeparator();
  m_ToolBar->AddTool(wxID_FIND);

#ifdef __WXGTK__
  // wxID_EXECUTE is not part of art provider, but GTK directly,
  // so the following does not present a bitmap.
  //m_ToolBar->AddSeparator();
  //m_ToolBar->AddTool(wxID_EXECUTE);
#endif

  m_ToolBar->AddSeparator();
  ((wxToolBar*)m_ToolBar)->AddTool(
    ID_PROJECT_OPEN,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxExEllipsed(_("Open project")));
  ((wxToolBar*)m_ToolBar)->AddTool(
    ID_PROJECT_SAVE,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    _("Save project"));

#ifdef __WXMSW__
  m_ToolBar->AddSeparator();
  m_ToolBar->AddCheckTool(
    wxID_VIEW_LIST,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxNullBitmap,
    _("View in list mode"));
  m_ToolBar->AddCheckTool(
    wxID_VIEW_DETAILS, wxEmptyString,
    wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxNullBitmap,
    _("View in detail mode"));
#endif //__WXMSW__

#if wxUSE_CHECKBOX
  m_ToolBar->AddSeparator();
#ifndef __WXMSW__
  wxSize size(55, 25);
#else
  wxSize size = wxDefaultSize;
#endif // __WXMSW__

  m_ToolBar->AddControl(
    m_HexModeCheckBox = new wxCheckBox(
      m_ToolBar,
      ID_EDIT_HEX_MODE,
      "Hex",
      wxDefaultPosition,
      size,
      wxNO_BORDER));

  m_ToolBar->AddControl(
    m_SyncCheckBox = new wxCheckBox(
      m_ToolBar,
      ID_SYNC_MODE,
      "Sync",
      wxDefaultPosition,
      size,
      wxNO_BORDER));

  m_HexModeCheckBox->SetToolTip(_("View in hex mode"));
  m_HexModeCheckBox->SetValue(wxConfigBase::Get()->ReadBool("HexMode", false)); // default no hex
  m_SyncCheckBox->SetToolTip(_("Synchronize modified files"));
  m_SyncCheckBox->SetValue(wxConfigBase::Get()->ReadBool("AllowSync", true));
#endif // wxUSE_CHECKBOX

  m_ToolBar->Realize();
}

bool Frame::AllowClose(wxWindowID id, wxWindow* page)
{
  if (ProcessIsRunning())
  {
    return false;
  }
  else if (id == NOTEBOOK_EDITORS)
  {
    wxExFileDialog dlg(this, (wxExSTCWithFrame*)page);
    return dlg.ShowModalIfChanged() == wxID_OK;
  }
  else if (id == NOTEBOOK_PROJECTS)
  {
    wxExFileDialog dlg(this, (wxExListViewWithFrame*)page);
    return dlg.ShowModalIfChanged() == wxID_OK;
  }
  else
  {
    return wxExFrameWithHistory::AllowClose(id, page);
  }
}

void Frame::OnNotebook(wxWindowID id, wxWindow* page)
{
  if (id == NOTEBOOK_EDITORS)
  {
    ((wxExSTCWithFrame*)page)->PropertiesMessage();
  }
  else if (id == NOTEBOOK_PROJECTS)
  {
    SetTitle(wxEmptyString, ((wxExListViewWithFrame*)page)->GetFileName().GetName());
#if wxUSE_STATUSBAR
    StatusText(((wxExListViewWithFrame*)page)->GetFileName());
    ((wxExListViewWithFrame*)page)->UpdateStatusBar();
#endif
  }
  else if (id == NOTEBOOK_LISTS)
  {
    // Do nothing special.
  }
  else
  {
    wxFAIL;
  }
}
<commit_msg>checkbox size change<commit_after>/******************************************************************************\
* File:          support.cpp
* Purpose:       Implementation of support classes
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/config.h>
#include <wx/stockitem.h> // for wxGetStockLabel
#include <wx/extension/filedlg.h>
#include <wx/extension/lexers.h>
#include <wx/extension/svn.h>
#ifndef __WXMSW__
#include "app.xpm"
#endif
#include "support.h"
#include "defs.h"

Frame::Frame()
  : wxExFrameWithHistory(
      NULL,
      wxID_ANY,
      wxTheApp->GetAppName(), //title
      NUMBER_RECENT_FILES,    //maxFiles
      4)                      // maxProjects
{
  SetIcon(wxICON(app));

#if wxUSE_STATUSBAR
  std::vector<wxExPane> panes;
  panes.push_back(wxExPane("PaneText", -3));
  panes.push_back(wxExPane("PaneFileType", 50, _("File Type")));
  panes.push_back(wxExPane("PaneLines", 100, _("Lines")));

  // Add the lexer pane only if we have lexers.
  if (wxExLexers::Get()->Count() > 0)
  {
#ifdef __WXMSW__
    const int lexer_size = 60;
#else
    const int lexer_size = 75;
#endif
    panes.push_back(wxExPane("PaneLexer", lexer_size, _("Lexer")));
  }

  panes.push_back(wxExPane("PaneItems", 65, _("Items")));
  SetupStatusBar(panes);
#endif

  wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE); // wxMB_DOCKABLE only used for GTK
  SetMenuBar(menubar);

  wxExMenu *menuFile = new wxExMenu();
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
  menuFile->Append(ID_OPEN_LEXERS, _("Open &Lexers"));
  menuFile->Append(ID_OPEN_LOGFILE, _("Open &Logfile"));
  menuFile->Append(wxID_CLOSE);
  menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE);
  menuFile->AppendSeparator();
  menuFile->AppendPrint();
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu *menuEdit = new wxExMenu();
  menuEdit->Append(wxID_UNDO);
  menuEdit->Append(wxID_REDO);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT);
  menuEdit->Append(wxID_COPY);
  menuEdit->Append(wxID_PASTE);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_FIND);
  menuEdit->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3"));
  menuEdit->Append(wxID_REPLACE);
  menuEdit->Append(ID_SPECIAL_FIND_IN_FILES, wxExEllipsed(_("Find &In Files")));
  menuEdit->Append(ID_SPECIAL_REPLACE_IN_FILES, wxExEllipsed(_("Replace In File&s")));
  menuEdit->AppendSeparator();
  menuEdit->AppendTools();
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_JUMP_TO);
  menuEdit->AppendSeparator();
  menuEdit->Append(ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl+H"));
  menuEdit->AppendSeparator();

  if (wxExSVN::Get()->Use())
  {
    wxMenu* menuSVN = new wxMenu;
    menuSVN->Append(ID_SVN_STAT, wxExEllipsed("&Stat"));
    menuSVN->Append(ID_SVN_INFO, wxExEllipsed("&Info"));
    menuSVN->Append(ID_SVN_LOG, wxExEllipsed("&Log"));
    menuSVN->Append(ID_SVN_LS, wxExEllipsed("&Ls"));
    menuSVN->Append(ID_SVN_DIFF, wxExEllipsed("&Diff"));
    menuSVN->Append(ID_SVN_HELP, wxExEllipsed("&Help"));
    menuSVN->AppendSeparator();
    menuSVN->Append(ID_SVN_UPDATE, wxExEllipsed("&Update"));
    menuSVN->Append(ID_SVN_COMMIT, wxExEllipsed("C&ommit"));
    menuSVN->AppendSeparator();
    menuSVN->Append(ID_SVN_ADD, wxExEllipsed("&Add"));
    menuEdit->AppendSubMenu(menuSVN, "&SVN");
    menuEdit->AppendSeparator();
  }

  menuEdit->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
  menuEdit->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
  menuEdit->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M"));

  wxMenu *menuView = new wxMenu;
  menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
  menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
  menuView->AppendCheckItem(ID_VIEW_FINDBAR, _("&Findbar"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files"));
  menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects"));
  menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer"));
  menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output"));
  menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table"));
  menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History"));
#ifdef __WXMSW__
  wxMenu *menuListView = new wxMenu;
  menuListView->AppendCheckItem(wxID_VIEW_LIST, _("&List"));
  menuListView->AppendCheckItem(wxID_VIEW_DETAILS, _("&Detail"));
  menuListView->AppendCheckItem(wxID_VIEW_SMALLICONS, _("&Small Icon"));
  menuView->AppendSeparator();
  menuView->AppendSubMenu(menuListView, _("&Lists"));
#endif

  wxMenu *menuProcess = new wxMenu();
  menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select")));
  menuProcess->AppendSeparator();
  menuProcess->Append(wxID_EXECUTE);
  menuProcess->Append(wxID_STOP);

  wxExMenu *menuProject = new wxExMenu();
  menuProject->Append(ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW);
  menuProject->Append(ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN);
  UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
  menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text"));
  menuProject->Append(ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE));
  menuProject->AppendSeparator();
  menuProject->Append(ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE);
  menuProject->Append(ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS);
  menuProject->AppendSeparator();
  menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort"));

  wxMenu *menuWindow = new wxMenu();
  menuWindow->Append(ID_SPLIT, _("Split"));

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(ID_OPTION_SVN_AND_COMPARATOR, wxExEllipsed(_("Set SVN And &Comparator")));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font")));
  menuOptions->Append(ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set &List Read Only Colour")));
  wxMenu *menuListSort = new wxMenu;
  menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"));
  menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"));
  menuListSort->AppendCheckItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"));
  menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method"));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options")));

  wxMenu *menuHelp = new wxMenu();
  menuHelp->Append(wxID_ABOUT);

  menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
  menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuProcess, _("&Process"));
  menubar->Append(menuProject, _("&Project"));
  menubar->Append(menuWindow, _("&Window"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));

  CreateToolBar();

  m_ToolBar->AddTool(wxID_OPEN);
  m_ToolBar->AddTool(wxID_SAVE);
  m_ToolBar->AddTool(wxID_PRINT);
  m_ToolBar->AddSeparator();
  m_ToolBar->AddTool(wxID_FIND);

#ifdef __WXGTK__
  // wxID_EXECUTE is not part of art provider, but GTK directly,
  // so the following does not present a bitmap.
  //m_ToolBar->AddSeparator();
  //m_ToolBar->AddTool(wxID_EXECUTE);
#endif

  m_ToolBar->AddSeparator();
  ((wxToolBar*)m_ToolBar)->AddTool(
    ID_PROJECT_OPEN,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxExEllipsed(_("Open project")));
  ((wxToolBar*)m_ToolBar)->AddTool(
    ID_PROJECT_SAVE,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    _("Save project"));

#ifdef __WXMSW__
  m_ToolBar->AddSeparator();
  m_ToolBar->AddCheckTool(
    wxID_VIEW_LIST,
    wxEmptyString,
    wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxNullBitmap,
    _("View in list mode"));
  m_ToolBar->AddCheckTool(
    wxID_VIEW_DETAILS, wxEmptyString,
    wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
    wxNullBitmap,
    _("View in detail mode"));
#endif //__WXMSW__

#if wxUSE_CHECKBOX
  m_ToolBar->AddSeparator();

  m_ToolBar->AddControl(
    m_HexModeCheckBox = new wxCheckBox(
      m_ToolBar,
      ID_EDIT_HEX_MODE,
      "Hex",
      wxDefaultPosition,
      wxSize(-1, m_ToolBar->GetToolSize().GetHeight())));

  m_ToolBar->AddControl(
    m_SyncCheckBox = new wxCheckBox(
      m_ToolBar,
      ID_SYNC_MODE,
      "Sync",
      wxDefaultPosition,
      wxSize(-1, m_ToolBar->GetToolSize().GetHeight())));

  m_HexModeCheckBox->SetToolTip(_("View in hex mode"));
  m_HexModeCheckBox->SetValue(wxConfigBase::Get()->ReadBool("HexMode", false)); // default no hex
  m_SyncCheckBox->SetToolTip(_("Synchronize modified files"));
  m_SyncCheckBox->SetValue(wxConfigBase::Get()->ReadBool("AllowSync", true));
#endif // wxUSE_CHECKBOX

  m_ToolBar->Realize();
}

bool Frame::AllowClose(wxWindowID id, wxWindow* page)
{
  if (ProcessIsRunning())
  {
    return false;
  }
  else if (id == NOTEBOOK_EDITORS)
  {
    wxExFileDialog dlg(this, (wxExSTCWithFrame*)page);
    return dlg.ShowModalIfChanged() == wxID_OK;
  }
  else if (id == NOTEBOOK_PROJECTS)
  {
    wxExFileDialog dlg(this, (wxExListViewWithFrame*)page);
    return dlg.ShowModalIfChanged() == wxID_OK;
  }
  else
  {
    return wxExFrameWithHistory::AllowClose(id, page);
  }
}

void Frame::OnNotebook(wxWindowID id, wxWindow* page)
{
  if (id == NOTEBOOK_EDITORS)
  {
    ((wxExSTCWithFrame*)page)->PropertiesMessage();
  }
  else if (id == NOTEBOOK_PROJECTS)
  {
    SetTitle(wxEmptyString, ((wxExListViewWithFrame*)page)->GetFileName().GetName());
#if wxUSE_STATUSBAR
    StatusText(((wxExListViewWithFrame*)page)->GetFileName());
    ((wxExListViewWithFrame*)page)->UpdateStatusBar();
#endif
  }
  else if (id == NOTEBOOK_LISTS)
  {
    // Do nothing special.
  }
  else
  {
    wxFAIL;
  }
}
<|endoftext|>


<commit_before>#include <iostream>

#include "pbge/exceptions/exceptions.h"
#include "pbge/core/Manager.h"
#include "pbge/gfx/Buffer.h"
#include "pbge/gfx/Node.h"
#include "pbge/gfx/Model.h"
#include "pbge/gfx/Renderer.h"
#include "pbge/gfx/VBO.h"

#include <GL/glew.h>
#include <GL/glut.h>

pbge::Node * root, * child;
pbge::TransformationNode * cam_node;
pbge::Renderer * renderer;
pbge::SceneManager manager;
pbge::Camera camera;

class UmModelo : public pbge::Model {
public:
    UmModelo(pbge::VertexBuffer * _vbo, GLenum _primitive) {
        vbo = _vbo;
        primitive = _primitive;
    }

    void render(pbge::ModelInstance * instance, pbge::OpenGL * ogl) {
        glEnable(GL_VERTEX_ARRAY);
        vbo->bind(ogl);
        glDrawArrays(primitive, 0, vbo->getNVertices());
        vbo->unbind(ogl);
        glDisable(GL_VERTEX_ARRAY);
    }

private:
    GLenum primitive;
    pbge::VertexBuffer * vbo;
};

pbge::ModelInstance * vboModel = NULL;

void display() {
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
    renderer->render();
    GLenum error;
    while((error = glGetError()) != GL_NO_ERROR) {
        std::cout << gluErrorString(error) << std::endl;
    }
    glutSwapBuffers();
}

void createNormalIndexes(std::vector<unsigned short> & ni) {
    unsigned short indexes[] = {3,3,3,3, 5,5,5,5, 0,0,0,0, 2,2,2,2, 1,1,1,1, 4,4,4,4};
    ni = std::vector<unsigned short>(indexes, indexes + 24);
}

std::vector<unsigned short> make(unsigned short * p, int n) {
    return std::vector<unsigned short>(p, p + n);
}

void createVertexIndexes(std::vector<unsigned short> & vi) {
    unsigned short indexes[] = {0,1,2,3, 7,4,1,0, 6,5,4,7, 3,2,5,6, 5,2,1,4, 0,3,6,7};
    vi = std::vector<unsigned short>(indexes, indexes + 24);
}

void createVBOInstance() {
    float v = 0.5f;
    std::vector<unsigned short> vIndexes;
    std::vector<unsigned short> nIndexes;
    createNormalIndexes(nIndexes);
    createVertexIndexes(vIndexes);
    pbge::VertexBufferBuilder builder(24);
    pbge::VertexAttribBuilder vertex = builder.addAttrib(3, pbge::VertexAttrib::VERTEX);
    pbge::VertexAttribBuilder normal = builder.addAttrib(3, pbge::VertexAttrib::NORMAL);

    builder.pushValue(normal,1,0,0).pushValue(normal,0,1,0).pushValue(normal,0,0,1).pushValue(normal,-1,0,0).pushValue(normal,0,-1,0).pushValue(normal,0,0,-1);
    builder.pushValue(vertex,-v,-v,-v).pushValue(vertex,-v,v,-v).pushValue(vertex,-v,v,v).pushValue(vertex,-v,-v,v);
    builder.pushValue(vertex,v,v,-v).pushValue(vertex,v,v,v).pushValue(vertex,v,-v,v).pushValue(vertex,v,-v,-v);
    builder.setAttribIndex(normal, nIndexes).setAttribIndex(vertex, vIndexes);
    pbge::VertexBuffer * vbo = builder.done();
    vboModel = new pbge::ModelInstance(new UmModelo(vbo, GL_QUADS));
}

void setUp() {
    glewInit();
    glEnable(GL_DEPTH_TEST);
    glClearColor(0,0,0,0);
    glColor3f(1,0,0);

    createVBOInstance();
    renderer = new pbge::Renderer(pbge::Manager::getInstance()->getOpenGL());
    pbge::TransformationNode * node = new pbge::TransformationNode;

    math3d::matrix44 m = math3d::identity44;
    root = new pbge::TransformationNode;
    cam_node = new pbge::TransformationNode;

    child = node;
    node->setTransformationMatrix(&m);
    root->addChild(child);
    root->addChild(cam_node);
    child->addModelInstance(vboModel);

    math3d::matrix44 cam_matrix = math3d::identity44;
    cam_matrix[2][3] = 8.0f;
    cam_node->setTransformationMatrix(&cam_matrix);

    camera.setParent(cam_node);
    camera.lookAt(math3d::vector4(0,1,0), math3d::vector4(0,0,-1));
    camera.frustum.setPerspective(30, 1, 0.1f, 10);

    manager.setSceneGraph(root);
    manager.addCamera(&camera);
    renderer->setScene(&manager);
}

int main(int argc, char ** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
    glutInitWindowSize(500,500);
    glutCreateWindow("ahahah");
    setUp();
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}<commit_msg>removing useless helper function<commit_after>#include <iostream>

#include "pbge/exceptions/exceptions.h"
#include "pbge/core/Manager.h"
#include "pbge/gfx/Buffer.h"
#include "pbge/gfx/Node.h"
#include "pbge/gfx/Model.h"
#include "pbge/gfx/Renderer.h"
#include "pbge/gfx/VBO.h"

#include <GL/glew.h>
#include <GL/glut.h>

pbge::Node * root, * child;
pbge::TransformationNode * cam_node;
pbge::Renderer * renderer;
pbge::SceneManager manager;
pbge::Camera camera;

class UmModelo : public pbge::Model {
public:
    UmModelo(pbge::VertexBuffer * _vbo, GLenum _primitive) {
        vbo = _vbo;
        primitive = _primitive;
    }

    void render(pbge::ModelInstance * instance, pbge::OpenGL * ogl) {
        glEnable(GL_VERTEX_ARRAY);
        vbo->bind(ogl);
        glDrawArrays(primitive, 0, vbo->getNVertices());
        vbo->unbind(ogl);
        glDisable(GL_VERTEX_ARRAY);
    }

private:
    GLenum primitive;
    pbge::VertexBuffer * vbo;
};

pbge::ModelInstance * vboModel = NULL;

void display() {
    glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
    renderer->render();
    GLenum error;
    while((error = glGetError()) != GL_NO_ERROR) {
        std::cout << gluErrorString(error) << std::endl;
    }
    glutSwapBuffers();
}

void createNormalIndexes(std::vector<unsigned short> & ni) {
    unsigned short indexes[] = {3,3,3,3, 5,5,5,5, 0,0,0,0, 2,2,2,2, 1,1,1,1, 4,4,4,4};
    ni = std::vector<unsigned short>(indexes, indexes + 24);
}

void createVertexIndexes(std::vector<unsigned short> & vi) {
    unsigned short indexes[] = {0,1,2,3, 7,4,1,0, 6,5,4,7, 3,2,5,6, 5,2,1,4, 0,3,6,7};
    vi = std::vector<unsigned short>(indexes, indexes + 24);
}

void createVBOInstance() {
    float v = 0.5f;
    std::vector<unsigned short> vIndexes;
    std::vector<unsigned short> nIndexes;
    createNormalIndexes(nIndexes);
    createVertexIndexes(vIndexes);
    pbge::VertexBufferBuilder builder(24);
    pbge::VertexAttribBuilder vertex = builder.addAttrib(3, pbge::VertexAttrib::VERTEX);
    pbge::VertexAttribBuilder normal = builder.addAttrib(3, pbge::VertexAttrib::NORMAL);

    builder.pushValue(normal,1,0,0).pushValue(normal,0,1,0).pushValue(normal,0,0,1).pushValue(normal,-1,0,0).pushValue(normal,0,-1,0).pushValue(normal,0,0,-1);
    builder.pushValue(vertex,-v,-v,-v).pushValue(vertex,-v,v,-v).pushValue(vertex,-v,v,v).pushValue(vertex,-v,-v,v);
    builder.pushValue(vertex,v,v,-v).pushValue(vertex,v,v,v).pushValue(vertex,v,-v,v).pushValue(vertex,v,-v,-v);
    builder.setAttribIndex(normal, nIndexes).setAttribIndex(vertex, vIndexes);
    pbge::VertexBuffer * vbo = builder.done();
    vboModel = new pbge::ModelInstance(new UmModelo(vbo, GL_QUADS));
}

void setUp() {
    glewInit();
    glEnable(GL_DEPTH_TEST);
    glClearColor(0,0,0,0);
    glColor3f(1,0,0);

    createVBOInstance();
    renderer = new pbge::Renderer(pbge::Manager::getInstance()->getOpenGL());
    pbge::TransformationNode * node = new pbge::TransformationNode;

    math3d::matrix44 m = math3d::identity44;
    root = new pbge::TransformationNode;
    cam_node = new pbge::TransformationNode;

    child = node;
    node->setTransformationMatrix(&m);
    root->addChild(child);
    root->addChild(cam_node);
    child->addModelInstance(vboModel);

    math3d::matrix44 cam_matrix = math3d::identity44;
    cam_matrix[2][3] = 8.0f;
    cam_node->setTransformationMatrix(&cam_matrix);

    camera.setParent(cam_node);
    camera.lookAt(math3d::vector4(0,1,0), math3d::vector4(0,0,-1));
    camera.frustum.setPerspective(30, 1, 0.1f, 10);

    manager.setSceneGraph(root);
    manager.addCamera(&camera);
    renderer->setScene(&manager);
}

int main(int argc, char ** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA|GLUT_DEPTH|GLUT_DOUBLE);
    glutInitWindowSize(500,500);
    glutCreateWindow("ahahah");
    setUp();
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}<|endoftext|>


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

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

#ifndef _TOOLS_H
#include <tools/tools.h>
#endif

#ifndef MACOSX

BOOL ImplSVMainHook( BOOL * )
{
    return FALSE;   // indicate that ImplSVMainHook is not implemented
}

#else
#include <osl/thread.h>
#include <premac.h>
#include <CoreFoundation/CoreFoundation.h>
#include <postmac.h>
#include <unistd.h>

extern BOOL ImplSVMain();

// ============================================================================

static void SourceContextCallBack( void *pInfo )
{
}

struct ThreadContext
{
    BOOL* pRet;
    CFRunLoopRef* pRunLoopRef;
};

static void RunSVMain(void *pData)
{
    ThreadContext* tcx = reinterpret_cast<ThreadContext*>(pData);

    // busy waiting (ok in this case) until the run loop is
    // running
    while (!CFRunLoopIsWaiting(*tcx->pRunLoopRef))
        usleep(100);

    *tcx->pRet = ImplSVMain();

    // Force exit since some JVMs won't shutdown when only exit() is invoked
    _exit( 0 );
}

BOOL ImplSVMainHook( BOOL *pbInit )
{
    // Mac OS X requires that any Cocoa code have a CFRunLoop started in the
    // primordial thread. Since all of the AWT classes in Java 1.4 and higher
    // are written in Cocoa, we need to start the CFRunLoop here and run
    // ImplSVMain() in a secondary thread.
    // See http://developer.apple.com/samplecode/simpleJavaLauncher/listing3.html
    // for further details and an example

    CFRunLoopRef runLoopRef = CFRunLoopGetCurrent();
    ThreadContext tcx;
    tcx.pRet = pbInit;  // the return value
    tcx.pRunLoopRef = &runLoopRef;
    oslThread hThreadID = osl_createThread(RunSVMain, &tcx);

    // Start the CFRunLoop
    CFRunLoopSourceContext aSourceContext;
    aSourceContext.version = 0;
    aSourceContext.info = NULL;
    aSourceContext.retain = NULL;
    aSourceContext.release = NULL;
    aSourceContext.copyDescription = NULL;
    aSourceContext.equal = NULL;
    aSourceContext.hash = NULL;
    aSourceContext.schedule = NULL;
    aSourceContext.cancel = NULL;
    aSourceContext.perform = &SourceContextCallBack;
    CFRunLoopSourceRef aSourceRef = CFRunLoopSourceCreate(NULL, 0, &aSourceContext);
    CFRunLoopAddSource(runLoopRef, aSourceRef, kCFRunLoopCommonModes);
    CFRunLoopRun();

    osl_joinWithThread( hThreadID );
    osl_destroyThread( hThreadID );

    return TRUE;    // indicate that ImplSVMainHook is implemented
}

#endif // MACOSX
<commit_msg>INTEGRATION: CWS aquavcl01 (1.2.68); FILE MERGED 2007/06/18 12:46:05 pl 1.2.68.7: #i78600# remove fprintf 2006/11/02 08:48:08 ericb 1.2.68.6: simplify OS check 2006/11/02 00:00:09 ericb 1.2.68.5: fix build with other archs than MacOS X 2006/10/13 22:01:04 tra 1.2.68.4: RESYNC: (1.3-1.4); FILE MERGED 2006/08/21 22:51:38 cl 1.2.68.3: added RAEL support 2006/07/19 08:28:22 pjanik 1.2.68.2: RESYNC: (1.2-1.3); FILE MERGED 2006/06/25 14:34:11 ssa 1.2.68.1: #i47888# limit the event loop trick to the X11 version only, aqua does not need it and crashes with two event loops<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svmainhook.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-05 08:37:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _TOOLS_H
#include <tools/tools.h>
#endif

#ifndef MACOSX

BOOL ImplSVMainHook( BOOL * )
{
    return FALSE;   // indicate that ImplSVMainHook is not implemented
}

#else
#ifdef QUARTZ  // only Mac OS X / X11 needs this trick, the Aqua version has its own native event loop
#include <premac.h>
//#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h>
#include <postmac.h>
#include <stdio.h>

extern BOOL ImplSVMain();

static BOOL* gpbInit = 0;

static  pascal  void    MainRunLoopForThreadedApps( EventLoopTimerRef inTimer, void *inUserData )
{
    BOOL bRet = ImplSVMain();
    if( gpbInit )
        *gpbInit = bRet;

    QuitApplicationEventLoop();
}

BOOL ImplSVMainHook( BOOL * pbInit )
{
    gpbInit = pbInit;

    EventLoopTimerRef aMainRunLoopTimerRef;
    (void) InstallEventLoopTimer( GetCurrentEventLoop(), 0, 0, NewEventLoopTimerUPP( MainRunLoopForThreadedApps ), NULL, &aMainRunLoopTimerRef );

    //  We really only call RunApplicationEventLoop() to install the default CarbonEvent handlers.  Once the timer installed above
    //  fires, we remain in the MainRunLoopForThreadedApps() routine which is designed to yield to other cooperative threads.
    RunApplicationEventLoop();

    return TRUE;   // indicate that ImplSVMainHook is implemented
}

#else  // MACOSX (X11) needs the CFRunLoop()
#include <osl/thread.h>
#include <premac.h>
#include <CoreFoundation/CoreFoundation.h>
#include <postmac.h>
#include <unistd.h>

extern BOOL ImplSVMain();

// ============================================================================

static void SourceContextCallBack( void *pInfo )
{
}

struct ThreadContext
{
    BOOL* pRet;
    CFRunLoopRef* pRunLoopRef;
};

static void RunSVMain(void *pData)
{
    ThreadContext* tcx = reinterpret_cast<ThreadContext*>(pData);

    // busy waiting (ok in this case) until the run loop is
    // running
    while (!CFRunLoopIsWaiting(*tcx->pRunLoopRef))
        usleep(100);

    *tcx->pRet = ImplSVMain();

    // Force exit since some JVMs won't shutdown when only exit() is invoked
    _exit( 0 );
}

BOOL ImplSVMainHook( BOOL *pbInit )
{
    // Mac OS X requires that any Cocoa code have a CFRunLoop started in the
    // primordial thread. Since all of the AWT classes in Java 1.4 and higher
    // are written in Cocoa, we need to start the CFRunLoop here and run
    // ImplSVMain() in a secondary thread.
    // See http://developer.apple.com/samplecode/simpleJavaLauncher/listing3.html
    // for further details and an example

    CFRunLoopRef runLoopRef = CFRunLoopGetCurrent();
    ThreadContext tcx;
    tcx.pRet = pbInit;  // the return value
    tcx.pRunLoopRef = &runLoopRef;
    oslThread hThreadID = osl_createThread(RunSVMain, &tcx);

    // Start the CFRunLoop
    CFRunLoopSourceContext aSourceContext;
    aSourceContext.version = 0;
    aSourceContext.info = NULL;
    aSourceContext.retain = NULL;
    aSourceContext.release = NULL;
    aSourceContext.copyDescription = NULL;
    aSourceContext.equal = NULL;
    aSourceContext.hash = NULL;
    aSourceContext.schedule = NULL;
    aSourceContext.cancel = NULL;
    aSourceContext.perform = &SourceContextCallBack;
    CFRunLoopSourceRef aSourceRef = CFRunLoopSourceCreate(NULL, 0, &aSourceContext);
    CFRunLoopAddSource(runLoopRef, aSourceRef, kCFRunLoopCommonModes);
    CFRunLoopRun();

    osl_joinWithThread( hThreadID );
    osl_destroyThread( hThreadID );

    return TRUE;    // indicate that ImplSVMainHook is implemented
}

#endif // MACOSX
#endif
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>

#include <map>

#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/test/field_trial.h"
#include "webrtc/test/frame_generator.h"
#include "webrtc/test/frame_generator_capturer.h"
#include "webrtc/test/run_test.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/typedefs.h"
#include "webrtc/video/loopback.h"
#include "webrtc/video/video_send_stream.h"

namespace webrtc {
namespace flags {

// Fixed for prerecorded screenshare content.
size_t Width() {
  return 1850;
}
size_t Height() {
  return 1110;
}

DEFINE_int32(fps, 5, "Frames per second.");
int Fps() {
  return static_cast<int>(FLAGS_fps);
}

DEFINE_int32(min_bitrate, 50, "Minimum video bitrate.");
size_t MinBitrate() {
  return static_cast<size_t>(FLAGS_min_bitrate);
}

DEFINE_int32(tl0_bitrate, 100, "Temporal layer 0 target bitrate.");
size_t StartBitrate() {
  return static_cast<size_t>(FLAGS_tl0_bitrate);
}

DEFINE_int32(tl1_bitrate, 1000, "Temporal layer 1 target bitrate.");
size_t MaxBitrate() {
  return static_cast<size_t>(FLAGS_tl1_bitrate);
}

DEFINE_int32(min_transmit_bitrate, 400, "Min transmit bitrate incl. padding.");
int MinTransmitBitrate() {
  return FLAGS_min_transmit_bitrate;
}

DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
  return static_cast<std::string>(FLAGS_codec);
}

DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
  return static_cast<int>(FLAGS_loss_percent);
}

DEFINE_int32(link_capacity,
             0,
             "Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacity() {
  return static_cast<int>(FLAGS_link_capacity);
}

DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
  return static_cast<int>(FLAGS_queue_size);
}

DEFINE_int32(avg_propagation_delay_ms,
             0,
             "Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
  return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}

DEFINE_int32(std_propagation_delay_ms,
             0,
             "Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
  return static_cast<int>(FLAGS_std_propagation_delay_ms);
}

DEFINE_bool(logs, false, "print logs to stderr");

DEFINE_string(
    force_fieldtrials,
    "",
    "Field trials control experimental feature code which can be forced. "
    "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
    " will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
    "trials are separated by \"/\"");
}  // namespace flags

class ScreenshareLoopback : public test::Loopback {
 public:
  explicit ScreenshareLoopback(const Config& config) : Loopback(config) {}
  virtual ~ScreenshareLoopback() {}

 protected:
  VideoEncoderConfig CreateEncoderConfig() override {
    VideoEncoderConfig encoder_config(test::Loopback::CreateEncoderConfig());
    VideoStream* stream = &encoder_config.streams[0];
    encoder_config.content_type = VideoEncoderConfig::kScreenshare;
    encoder_config.min_transmit_bitrate_bps = flags::MinTransmitBitrate();
    VideoCodecVP8 vp8_settings = VideoEncoder::GetDefaultVp8Settings();
    vp8_settings.denoisingOn = false;
    vp8_settings.frameDroppingOn = false;
    vp8_settings.numberOfTemporalLayers = 2;
    encoder_config.encoder_specific_settings = &vp8_settings;
    stream->temporal_layer_thresholds_bps.clear();
    stream->temporal_layer_thresholds_bps.push_back(stream->target_bitrate_bps);
    stream->target_bitrate_bps =
        static_cast<int>(config_.start_bitrate_kbps) * 1000;
    return encoder_config;
  }

  test::VideoCapturer* CreateCapturer(VideoSendStream* send_stream) override {
    std::vector<std::string> slides;
    slides.push_back(test::ResourcePath("web_screenshot_1850_1110", "yuv"));
    slides.push_back(test::ResourcePath("presentation_1850_1110", "yuv"));
    slides.push_back(test::ResourcePath("photo_1850_1110", "yuv"));
    slides.push_back(test::ResourcePath("difficult_photo_1850_1110", "yuv"));

    test::FrameGenerator* frame_generator =
        test::FrameGenerator::CreateFromYuvFile(
            slides, flags::Width(), flags::Height(), 10 * flags::Fps());
    test::FrameGeneratorCapturer* capturer(new test::FrameGeneratorCapturer(
        clock_, send_stream->Input(), frame_generator, flags::Fps()));
    EXPECT_TRUE(capturer->Init());
    return capturer;
  }
};

void Loopback() {
  test::Loopback::Config config{flags::Width(),
                                flags::Height(),
                                flags::Fps(),
                                flags::MinBitrate(),
                                flags::StartBitrate(),
                                flags::MaxBitrate(),
                                flags::MinTransmitBitrate(),
                                flags::Codec(),
                                flags::LossPercent(),
                                flags::LinkCapacity(),
                                flags::QueueSize(),
                                flags::AvgPropagationDelayMs(),
                                flags::StdPropagationDelayMs(),
                                flags::FLAGS_logs};
  ScreenshareLoopback loopback(config);
  loopback.Run();
}
}  // namespace webrtc

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  google::ParseCommandLineFlags(&argc, &argv, true);
  webrtc::test::InitFieldTrialsFromString(
      webrtc::flags::FLAGS_force_fieldtrials);
  webrtc::test::RunTest(webrtc::Loopback);
  return 0;
}
<commit_msg>Fix screenshare loopback target bitrate which isn't correctly configured<commit_after>/*
 *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <stdio.h>

#include <map>

#include "gflags/gflags.h"
#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/test/field_trial.h"
#include "webrtc/test/frame_generator.h"
#include "webrtc/test/frame_generator_capturer.h"
#include "webrtc/test/run_test.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/typedefs.h"
#include "webrtc/video/loopback.h"
#include "webrtc/video/video_send_stream.h"

namespace webrtc {
namespace flags {

// Fixed for prerecorded screenshare content.
size_t Width() {
  return 1850;
}
size_t Height() {
  return 1110;
}

DEFINE_int32(fps, 5, "Frames per second.");
int Fps() {
  return static_cast<int>(FLAGS_fps);
}

DEFINE_int32(min_bitrate, 50, "Minimum video bitrate.");
size_t MinBitrate() {
  return static_cast<size_t>(FLAGS_min_bitrate);
}

DEFINE_int32(tl0_bitrate, 100, "Temporal layer 0 target bitrate.");
size_t StartBitrate() {
  return static_cast<size_t>(FLAGS_tl0_bitrate);
}

DEFINE_int32(tl1_bitrate, 1000, "Temporal layer 1 target bitrate.");
size_t MaxBitrate() {
  return static_cast<size_t>(FLAGS_tl1_bitrate);
}

DEFINE_int32(min_transmit_bitrate, 400, "Min transmit bitrate incl. padding.");
int MinTransmitBitrate() {
  return FLAGS_min_transmit_bitrate;
}

DEFINE_string(codec, "VP8", "Video codec to use.");
std::string Codec() {
  return static_cast<std::string>(FLAGS_codec);
}

DEFINE_int32(loss_percent, 0, "Percentage of packets randomly lost.");
int LossPercent() {
  return static_cast<int>(FLAGS_loss_percent);
}

DEFINE_int32(link_capacity,
             0,
             "Capacity (kbps) of the fake link. 0 means infinite.");
int LinkCapacity() {
  return static_cast<int>(FLAGS_link_capacity);
}

DEFINE_int32(queue_size, 0, "Size of the bottleneck link queue in packets.");
int QueueSize() {
  return static_cast<int>(FLAGS_queue_size);
}

DEFINE_int32(avg_propagation_delay_ms,
             0,
             "Average link propagation delay in ms.");
int AvgPropagationDelayMs() {
  return static_cast<int>(FLAGS_avg_propagation_delay_ms);
}

DEFINE_int32(std_propagation_delay_ms,
             0,
             "Link propagation delay standard deviation in ms.");
int StdPropagationDelayMs() {
  return static_cast<int>(FLAGS_std_propagation_delay_ms);
}

DEFINE_bool(logs, false, "print logs to stderr");

DEFINE_string(
    force_fieldtrials,
    "",
    "Field trials control experimental feature code which can be forced. "
    "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
    " will assign the group Enable to field trial WebRTC-FooFeature. Multiple "
    "trials are separated by \"/\"");
}  // namespace flags

class ScreenshareLoopback : public test::Loopback {
 public:
  explicit ScreenshareLoopback(const Config& config) : Loopback(config) {}
  virtual ~ScreenshareLoopback() {}

 protected:
  VideoEncoderConfig CreateEncoderConfig() override {
    VideoEncoderConfig encoder_config(test::Loopback::CreateEncoderConfig());
    VideoStream* stream = &encoder_config.streams[0];
    encoder_config.content_type = VideoEncoderConfig::kScreenshare;
    encoder_config.min_transmit_bitrate_bps = flags::MinTransmitBitrate();
    VideoCodecVP8 vp8_settings = VideoEncoder::GetDefaultVp8Settings();
    vp8_settings.denoisingOn = false;
    vp8_settings.frameDroppingOn = false;
    vp8_settings.numberOfTemporalLayers = 2;
    encoder_config.encoder_specific_settings = &vp8_settings;
    stream->temporal_layer_thresholds_bps.clear();
    stream->target_bitrate_bps =
        static_cast<int>(config_.start_bitrate_kbps) * 1000;
    stream->temporal_layer_thresholds_bps.push_back(stream->target_bitrate_bps);
    return encoder_config;
  }

  test::VideoCapturer* CreateCapturer(VideoSendStream* send_stream) override {
    std::vector<std::string> slides;
    slides.push_back(test::ResourcePath("web_screenshot_1850_1110", "yuv"));
    slides.push_back(test::ResourcePath("presentation_1850_1110", "yuv"));
    slides.push_back(test::ResourcePath("photo_1850_1110", "yuv"));
    slides.push_back(test::ResourcePath("difficult_photo_1850_1110", "yuv"));

    test::FrameGenerator* frame_generator =
        test::FrameGenerator::CreateFromYuvFile(
            slides, flags::Width(), flags::Height(), 10 * flags::Fps());
    test::FrameGeneratorCapturer* capturer(new test::FrameGeneratorCapturer(
        clock_, send_stream->Input(), frame_generator, flags::Fps()));
    EXPECT_TRUE(capturer->Init());
    return capturer;
  }
};

void Loopback() {
  test::Loopback::Config config{flags::Width(),
                                flags::Height(),
                                flags::Fps(),
                                flags::MinBitrate(),
                                flags::StartBitrate(),
                                flags::MaxBitrate(),
                                flags::MinTransmitBitrate(),
                                flags::Codec(),
                                flags::LossPercent(),
                                flags::LinkCapacity(),
                                flags::QueueSize(),
                                flags::AvgPropagationDelayMs(),
                                flags::StdPropagationDelayMs(),
                                flags::FLAGS_logs};
  ScreenshareLoopback loopback(config);
  loopback.Run();
}
}  // namespace webrtc

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  google::ParseCommandLineFlags(&argc, &argv, true);
  webrtc::test::InitFieldTrialsFromString(
      webrtc::flags::FLAGS_force_fieldtrials);
  webrtc::test::RunTest(webrtc::Loopback);
  return 0;
}
<|endoftext|>