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

#include <system.hh>

#include "convert.h"
#include "csv.h"
#include "scope.h"
#include "interactive.h"
#include "iterators.h"
#include "report.h"
#include "xact.h"
#include "print.h"
#include "lookup.h"

namespace ledger {

value_t convert_command(call_scope_t& scope)
{
  interactive_t args(scope, "s");
  report_t&	report(find_scope<report_t>(scope));
  journal_t&	journal(*report.session.journal.get());

  string bucket_name;
  if (report.HANDLED(account_))
    bucket_name = report.HANDLER(account_).str();
  else
    bucket_name = "Equity:Unknown";

  account_t * bucket  = journal.master->find_account(bucket_name);
  account_t * unknown = journal.master->find_account(_("Expenses:Unknown"));

  // Make an amounts mapping for the account under consideration

  typedef std::map<value_t, std::list<post_t *> > post_map_t;
  post_map_t post_map;

  xacts_iterator journal_iter(journal);
  while (xact_t * xact = journal_iter()) {
    post_t * post = NULL;
    xact_posts_iterator xact_iter(*xact);
    while ((post = xact_iter()) != NULL) {
      if (post->account == bucket)
	break;
    }
    if (post) {
      post_map_t::iterator i = post_map.find(post->amount);
      if (i == post_map.end()) {
	std::list<post_t *> post_list;
	post_list.push_back(post);
	post_map.insert(post_map_t::value_type(post->amount, post_list));
      } else {
	(*i).second.push_back(post);
      }
    }
  }

  // Create a flat list o
  xacts_list current_xacts(journal.xacts_begin(), journal.xacts_end());

  // Read in the series of transactions from the CSV file

  print_xacts formatter(report);
  ifstream    data(path(args.get<string>(0)));
  csv_reader  reader(data);

  while (xact_t * xact = reader.read_xact(journal, bucket)) {
    bool matched = false;
    post_map_t::iterator i = post_map.find(- xact->posts.front()->amount);
    if (i != post_map.end()) {
      std::list<post_t *>& post_list((*i).second);
      foreach (post_t * post, post_list) {
	if (xact->code && post->xact->code &&
	    *xact->code == *post->xact->code) {
	  matched = true;
	  break;
	}
	else if (xact->actual_date() == post->actual_date()) {
	  matched = true;
	  break;
	}
      }
    }

    if (matched) {
      DEBUG("convert.csv", "Ignored xact with code: " << *xact->code);
      delete xact;		// ignore it
    }
    else {
      if (xact->posts.front()->account == NULL) {
	xacts_iterator xi;
	xi.xacts_i   = current_xacts.begin();
	xi.xacts_end = current_xacts.end();
	xi.xacts_uninitialized = false;

	// jww (2010-03-07): Bind this logic to an option: --auto-match
	if (account_t * acct =
	    lookup_probable_account(xact->payee, xi, bucket).second)
	  xact->posts.front()->account = acct;
	else
	  xact->posts.front()->account = unknown;
      }

      if (! journal.add_xact(xact)) {
	delete xact;
	throw_(std::runtime_error,
	       _("Failed to finalize derived transaction (check commodities)"));
      }
      else {
	xact_posts_iterator xact_iter(*xact);
	while (post_t * post = xact_iter())
	  formatter(*post);
      }
    }
  }
  formatter.flush();

  // If not, transform the payee according to regexps

  // Set the account to a default vaule, then transform the account according
  // to the payee

  // Print out the final form of the transaction

  return true;
}

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

#include <system.hh>

#include "convert.h"
#include "csv.h"
#include "scope.h"
#include "interactive.h"
#include "iterators.h"
#include "report.h"
#include "xact.h"
#include "print.h"
#include "lookup.h"

namespace ledger {

value_t convert_command(call_scope_t& scope)
{
  interactive_t args(scope, "s");
  report_t&	report(find_scope<report_t>(scope));
  journal_t&	journal(*report.session.journal.get());

  string bucket_name;
  if (report.HANDLED(account_))
    bucket_name = report.HANDLER(account_).str();
  else
    bucket_name = "Equity:Unknown";

  account_t * bucket  = journal.master->find_account(bucket_name);
  account_t * unknown = journal.master->find_account(_("Expenses:Unknown"));

  // Make an amounts mapping for the account under consideration

  typedef std::map<value_t, std::list<post_t *> > post_map_t;
  post_map_t post_map;

  xacts_iterator journal_iter(journal);
  while (xact_t * xact = journal_iter()) {
    post_t * post = NULL;
    xact_posts_iterator xact_iter(*xact);
    while ((post = xact_iter()) != NULL) {
      if (post->account == bucket)
	break;
    }
    if (post) {
      post_map_t::iterator i = post_map.find(post->amount);
      if (i == post_map.end()) {
	std::list<post_t *> post_list;
	post_list.push_back(post);
	post_map.insert(post_map_t::value_type(post->amount, post_list));
      } else {
	(*i).second.push_back(post);
      }
    }
  }

  // Create a flat list
  xacts_list current_xacts(journal.xacts_begin(), journal.xacts_end());

  // Read in the series of transactions from the CSV file

  print_xacts formatter(report);
  ifstream    data(path(args.get<string>(0)));
  csv_reader  reader(data);

  while (xact_t * xact = reader.read_xact(journal, bucket)) {
    if (report.HANDLED(invert)) {
      foreach (post_t * post, xact->posts)
	post->amount.in_place_negate();
    }

    bool matched = false;
    post_map_t::iterator i = post_map.find(- xact->posts.front()->amount);
    if (i != post_map.end()) {
      std::list<post_t *>& post_list((*i).second);
      foreach (post_t * post, post_list) {
	if (xact->code && post->xact->code &&
	    *xact->code == *post->xact->code) {
	  matched = true;
	  break;
	}
	else if (xact->actual_date() == post->actual_date()) {
	  matched = true;
	  break;
	}
      }
    }

    if (matched) {
      DEBUG("convert.csv", "Ignored xact with code: " << *xact->code);
      delete xact;		// ignore it
    }
    else {
      if (xact->posts.front()->account == NULL) {
	xacts_iterator xi;
	xi.xacts_i   = current_xacts.begin();
	xi.xacts_end = current_xacts.end();
	xi.xacts_uninitialized = false;

	// jww (2010-03-07): Bind this logic to an option: --auto-match
	if (account_t * acct =
	    lookup_probable_account(xact->payee, xi, bucket).second)
	  xact->posts.front()->account = acct;
	else
	  xact->posts.front()->account = unknown;
      }

      if (! journal.add_xact(xact)) {
	delete xact;
	throw_(std::runtime_error,
	       _("Failed to finalize derived transaction (check commodities)"));
      }
      else {
	xact_posts_iterator xact_iter(*xact);
	while (post_t * post = xact_iter())
	  formatter(*post);
      }
    }
  }
  formatter.flush();

  // If not, transform the payee according to regexps

  // Set the account to a default vaule, then transform the account according
  // to the payee

  // Print out the final form of the transaction

  return true;
}

} // namespace ledger
<|endoftext|>


<commit_before>/*
    Copyright (C) 2011  Lasath Fernando <kde@lasath.org>
    Copyright (C) 2013  Dan Vrátil <dvratil@redhat.com>
    Copyright (C) 2013  Aleix Pol Gonzalez <aleixpol@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) any later version.

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

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

#include "qml-plugins.h"

#include <QQmlEngine>
#include <QQmlContext>

#include "conversation.h"
#include "conversations-model.h"
#include "messages-model.h"
#include "pinned-contacts-model.h"
#include "contact-pin.h"
#include "filtered-pinned-contacts-proxy-model.h"
#include "telepathy-manager.h"

#include <TelepathyQt/PendingChannelRequest>
#include "KTp/types.h"
#include "KTp/global-presence.h"
#include "KTp/Models/presence-model.h"
#include "KTp/Models/contacts-filter-model.h"
#include "KTp/Models/contacts-model.h"
#include "KTp/Models/accounts-list-model.h"

#include <QtQml>

void QmlPlugins::initializeEngine(QQmlEngine *engine, const char *uri)
{
    Q_UNUSED(uri)

    engine->rootContext()->setContextProperty(QLatin1String("telepathyManager"), new TelepathyManager(engine));
}

void QmlPlugins::registerTypes(const char *uri)
{
    qmlRegisterType<KTp::ContactsModel> (uri, 0, 1, "ContactsModel");
    qmlRegisterType<KTp::AccountsListModel> (uri, 0, 1, "AccountsListModel");

    qmlRegisterType<ConversationsModel> (uri, 0, 1, "ConversationsModel");
    qmlRegisterType<Conversation>(uri, 0, 1, "Conversation");
    qmlRegisterType<PinnedContactsModel>(uri, 0, 1, "PinnedContactsModel");
    qmlRegisterType<ContactPin>(uri, 0, 1, "ContactPin");
    qmlRegisterType<FilteredPinnedContactsProxyModel>(uri, 0, 1, "FilteredPinnedContactsProxyModel");
    qmlRegisterType<KTp::GlobalPresence> (uri, 0, 1, "GlobalPresence");
    qmlRegisterType<KTp::PresenceModel> (uri, 0, 1, "PresenceModel");

    qmlRegisterUncreatableType<MessagesModel> (uri, 0, 1, "MessagesModel",
        QLatin1String("It will be created once the conversation is created"));

    qmlRegisterType<TelepathyManager>();
    qmlRegisterType<ConversationsModel>();
    qmlRegisterType<Tp::PendingChannelRequest>();
    qRegisterMetaType<Tp::Presence>();
    qRegisterMetaType<KTp::Presence>();
    qRegisterMetaType<Tp::AccountManagerPtr>();
    qRegisterMetaType<KTp::ContactPtr>();
    qRegisterMetaType<Tp::AccountPtr>();

    QMetaType::registerComparators<KTp::Presence>();
}

<commit_msg>qmlRegisterType Tp::PendingOperation<commit_after>/*
    Copyright (C) 2011  Lasath Fernando <kde@lasath.org>
    Copyright (C) 2013  Dan Vrátil <dvratil@redhat.com>
    Copyright (C) 2013  Aleix Pol Gonzalez <aleixpol@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) any later version.

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

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

#include "qml-plugins.h"

#include <QQmlEngine>
#include <QQmlContext>

#include "conversation.h"
#include "conversations-model.h"
#include "messages-model.h"
#include "pinned-contacts-model.h"
#include "contact-pin.h"
#include "filtered-pinned-contacts-proxy-model.h"
#include "telepathy-manager.h"

#include <TelepathyQt/PendingChannelRequest>
#include "KTp/types.h"
#include "KTp/global-presence.h"
#include "KTp/Models/presence-model.h"
#include "KTp/Models/contacts-filter-model.h"
#include "KTp/Models/contacts-model.h"
#include "KTp/Models/accounts-list-model.h"

#include <QtQml>

void QmlPlugins::initializeEngine(QQmlEngine *engine, const char *uri)
{
    Q_UNUSED(uri)

    engine->rootContext()->setContextProperty(QLatin1String("telepathyManager"), new TelepathyManager(engine));
}

void QmlPlugins::registerTypes(const char *uri)
{
    qmlRegisterType<KTp::ContactsModel> (uri, 0, 1, "ContactsModel");
    qmlRegisterType<KTp::AccountsListModel> (uri, 0, 1, "AccountsListModel");

    qmlRegisterType<ConversationsModel> (uri, 0, 1, "ConversationsModel");
    qmlRegisterType<Conversation>(uri, 0, 1, "Conversation");
    qmlRegisterType<PinnedContactsModel>(uri, 0, 1, "PinnedContactsModel");
    qmlRegisterType<ContactPin>(uri, 0, 1, "ContactPin");
    qmlRegisterType<FilteredPinnedContactsProxyModel>(uri, 0, 1, "FilteredPinnedContactsProxyModel");
    qmlRegisterType<KTp::GlobalPresence> (uri, 0, 1, "GlobalPresence");
    qmlRegisterType<KTp::PresenceModel> (uri, 0, 1, "PresenceModel");

    qmlRegisterUncreatableType<MessagesModel> (uri, 0, 1, "MessagesModel",
        QLatin1String("It will be created once the conversation is created"));

    qmlRegisterType<TelepathyManager>();
    qmlRegisterType<ConversationsModel>();
    qmlRegisterType<Tp::PendingChannelRequest>();
    qmlRegisterType<Tp::PendingOperation>();
    qRegisterMetaType<Tp::Presence>();
    qRegisterMetaType<KTp::Presence>();
    qRegisterMetaType<Tp::AccountManagerPtr>();
    qRegisterMetaType<KTp::ContactPtr>();
    qRegisterMetaType<Tp::AccountPtr>();

    QMetaType::registerComparators<KTp::Presence>();
}

<|endoftext|>


<commit_before>/* This file is part of Zanshin Todo.

   Copyright 2008 Kevin Ottens <ervin@kde.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) 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 14 of version 3 of the license.

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

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

#include "actionlistdelegate.h"

#include <QtGui/QLineEdit>
#include <QtGui/QAbstractItemView>
#include <QtGui/QStyledItemDelegate>

#include "combomodel.h"
#include "kdateedit.h"
#include "modelstack.h"
#include "todomodel.h"

using namespace KPIM;

ActionListDelegate::ActionListDelegate(ModelStack *models, QObject *parent)
    : QStyledItemDelegate(parent)
    , m_models(models)
{
}

ActionListDelegate::~ActionListDelegate()
{

}

QSize ActionListDelegate::sizeHint(const QStyleOptionViewItem &option,
                                   const QModelIndex &index) const
{
    QSize res = QStyledItemDelegate::sizeHint(option, index);

    TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();

    if (!isInFocus(index)) {
        res.setHeight(32);
    } else if (type!=TodoModel::StandardTodo) {
        res.setHeight(24);
    }

    return res;
}

void ActionListDelegate::paint(QPainter *painter,
                               const QStyleOptionViewItem &option,
                               const QModelIndex &index) const
{
    TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();

    QStyleOptionViewItemV4 opt = option;

    if (!isInFocus(index)) {
        opt.decorationSize = QSize(1, 1);
        opt.displayAlignment = Qt::AlignHCenter|Qt::AlignBottom;
        opt.font.setItalic(true);
        opt.font.setPointSizeF(opt.font.pointSizeF()*0.75);

    } else if (type!=TodoModel::StandardTodo) {
        opt.decorationSize = QSize(22, 22);
        opt.font.setWeight(QFont::Bold);

    } else if (index.parent().isValid()) {
        if (index.row()%2==0) {
            opt.features|= QStyleOptionViewItemV4::Alternate;
        }
    }

    if (isCompleted(index)) {
        opt.font.setStrikeOut(true);
    } else if (isOverdue(index)) {
        opt.palette.setColor(QPalette::Text, QColor(Qt::red));
        opt.palette.setColor(QPalette::HighlightedText, QColor(Qt::red));
    }

    QStyledItemDelegate::paint(painter, opt, index);
}

KCal::Todo::Ptr ActionListDelegate::todoFromIndex(const QModelIndex &index) const
{
    TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();

    if (type!=TodoModel::StandardTodo) {
        return KCal::Todo::Ptr();
    }

    Akonadi::Item item = index.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
    if (!item.isValid() || !item.hasPayload<KCal::Todo::Ptr>()) {
        return KCal::Todo::Ptr();
    }

    return item.payload<KCal::Todo::Ptr>();
}

bool ActionListDelegate::isInFocus(const QModelIndex &index) const
{
    return true;
}

bool ActionListDelegate::isCompleted(const QModelIndex &index) const
{
    KCal::Todo::Ptr todo = todoFromIndex(index);

    if (todo) {
        return todo->isCompleted();
    } else {
        return false;
    }
}

bool ActionListDelegate::isOverdue(const QModelIndex &index) const
{
    KCal::Todo::Ptr todo = todoFromIndex(index);

    if (todo) {
        return todo->isOverdue();
    } else {
        return false;
    }
}

QWidget *ActionListDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                                          const QModelIndex &index) const
{
    if (index.data(Qt::EditRole).type()==QVariant::Date) {
        return new KDateEdit(parent);
    } else if (index.data(TodoModel::DataTypeRole).toInt() == TodoModel::CategoryType) {
        return createComboBox(m_models->categoriesComboModel(), parent, index);
    } else if (index.data(TodoModel::DataTypeRole).toInt() == TodoModel::ProjectType) {
        return createComboBox(m_models->treeComboModel(), parent, index);
    } else {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
}

QWidget *ActionListDelegate::createComboBox(QAbstractItemModel *model, QWidget *parent, const QModelIndex &selectedIndex) const
{
    QComboBox *comboBox = new QComboBox(parent);
    comboBox->view()->setTextElideMode(Qt::ElideNone);
    comboBox->setStyleSheet("* { combobox-popup: true; }");
    comboBox->setItemDelegate(new QStyledItemDelegate(comboBox));
    ComboModel *comboModel = static_cast<ComboModel*>(model);
    if (comboModel) {
        comboModel->setSelectedItems(selectedIndex.data(TodoModel::CategoriesRole).value<QStringList>());
        comboBox->setModel(model);
    }
    return comboBox;
}

void ActionListDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    KDateEdit *dateEdit = qobject_cast<KDateEdit*>(editor);

    if (dateEdit) {
        dateEdit->setDate(index.data(Qt::EditRole).toDate());
        if (dateEdit->lineEdit()->text().isEmpty()) {
            dateEdit->setDate(QDate::currentDate());
        }
        dateEdit->lineEdit()->selectAll();

    } else {
        QStyledItemDelegate::setEditorData(editor, index);
    }
}

void ActionListDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                      const QModelIndex &index) const
{
    KDateEdit *dateEdit = qobject_cast<KDateEdit*>(editor);

    if (dateEdit) {
        model->setData(index, dateEdit->date());

    } else {
        QStyledItemDelegate::setModelData(editor, model, index);
    }
}
<commit_msg>Less hackish way to have a large enough popup for the delegate combobox. Thanks to David Faure for the idea.<commit_after>/* This file is part of Zanshin Todo.

   Copyright 2008 Kevin Ottens <ervin@kde.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) 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 14 of version 3 of the license.

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

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

#include "actionlistdelegate.h"

#include <QtGui/QLineEdit>
#include <QtGui/QAbstractItemView>
#include <QtGui/QStyledItemDelegate>

#include "combomodel.h"
#include "kdateedit.h"
#include "modelstack.h"
#include "todomodel.h"

class ActionListComboBox : public QComboBox
{
public:
    ActionListComboBox(QWidget *parent = 0)
        : QComboBox(parent) { }

public slots:
    virtual void showPopup()
    {
        QComboBox::showPopup();

        int width = 0;
        const int itemCount = count();
        const int iconWidth = iconSize().width() + 4;
        const QFontMetrics &fm = fontMetrics();

        for (int i = 0; i < itemCount; ++i) {
            const int textWidth = fm.width(itemText(i));
            if (itemIcon(i).isNull()) {
                width = (qMax(width, textWidth));
            } else {
                width = (qMax(width, textWidth + iconWidth));
            }
        }

        QStyleOptionComboBox opt;
        initStyleOption(&opt);
        QSize tmp(width, 0);
        tmp = style()->sizeFromContents(QStyle::CT_ComboBox, &opt, tmp, this);
        width = tmp.width();

        if (width>view()->width()) {
            QSize size = view()->parentWidget()->size();
            size.setWidth(width + 10);
            view()->parentWidget()->resize(size);
        }
    }
};

using namespace KPIM;

ActionListDelegate::ActionListDelegate(ModelStack *models, QObject *parent)
    : QStyledItemDelegate(parent)
    , m_models(models)
{
}

ActionListDelegate::~ActionListDelegate()
{

}

QSize ActionListDelegate::sizeHint(const QStyleOptionViewItem &option,
                                   const QModelIndex &index) const
{
    QSize res = QStyledItemDelegate::sizeHint(option, index);

    TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();

    if (!isInFocus(index)) {
        res.setHeight(32);
    } else if (type!=TodoModel::StandardTodo) {
        res.setHeight(24);
    }

    return res;
}

void ActionListDelegate::paint(QPainter *painter,
                               const QStyleOptionViewItem &option,
                               const QModelIndex &index) const
{
    TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();

    QStyleOptionViewItemV4 opt = option;

    if (!isInFocus(index)) {
        opt.decorationSize = QSize(1, 1);
        opt.displayAlignment = Qt::AlignHCenter|Qt::AlignBottom;
        opt.font.setItalic(true);
        opt.font.setPointSizeF(opt.font.pointSizeF()*0.75);

    } else if (type!=TodoModel::StandardTodo) {
        opt.decorationSize = QSize(22, 22);
        opt.font.setWeight(QFont::Bold);

    } else if (index.parent().isValid()) {
        if (index.row()%2==0) {
            opt.features|= QStyleOptionViewItemV4::Alternate;
        }
    }

    if (isCompleted(index)) {
        opt.font.setStrikeOut(true);
    } else if (isOverdue(index)) {
        opt.palette.setColor(QPalette::Text, QColor(Qt::red));
        opt.palette.setColor(QPalette::HighlightedText, QColor(Qt::red));
    }

    QStyledItemDelegate::paint(painter, opt, index);
}

KCal::Todo::Ptr ActionListDelegate::todoFromIndex(const QModelIndex &index) const
{
    TodoModel::ItemType type = (TodoModel::ItemType)index.data(TodoModel::ItemTypeRole).toInt();

    if (type!=TodoModel::StandardTodo) {
        return KCal::Todo::Ptr();
    }

    Akonadi::Item item = index.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>();
    if (!item.isValid() || !item.hasPayload<KCal::Todo::Ptr>()) {
        return KCal::Todo::Ptr();
    }

    return item.payload<KCal::Todo::Ptr>();
}

bool ActionListDelegate::isInFocus(const QModelIndex &index) const
{
    return true;
}

bool ActionListDelegate::isCompleted(const QModelIndex &index) const
{
    KCal::Todo::Ptr todo = todoFromIndex(index);

    if (todo) {
        return todo->isCompleted();
    } else {
        return false;
    }
}

bool ActionListDelegate::isOverdue(const QModelIndex &index) const
{
    KCal::Todo::Ptr todo = todoFromIndex(index);

    if (todo) {
        return todo->isOverdue();
    } else {
        return false;
    }
}

QWidget *ActionListDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                                          const QModelIndex &index) const
{
    if (index.data(Qt::EditRole).type()==QVariant::Date) {
        return new KDateEdit(parent);
    } else if (index.data(TodoModel::DataTypeRole).toInt() == TodoModel::CategoryType) {
        return createComboBox(m_models->categoriesComboModel(), parent, index);
    } else if (index.data(TodoModel::DataTypeRole).toInt() == TodoModel::ProjectType) {
        return createComboBox(m_models->treeComboModel(), parent, index);
    } else {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
}

QWidget *ActionListDelegate::createComboBox(QAbstractItemModel *model, QWidget *parent, const QModelIndex &selectedIndex) const
{
    QComboBox *comboBox = new ActionListComboBox(parent);
    comboBox->view()->setTextElideMode(Qt::ElideNone);
    ComboModel *comboModel = static_cast<ComboModel*>(model);
    if (comboModel) {
        comboModel->setSelectedItems(selectedIndex.data(TodoModel::CategoriesRole).value<QStringList>());
        comboBox->setModel(model);
    }
    return comboBox;
}

void ActionListDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    KDateEdit *dateEdit = qobject_cast<KDateEdit*>(editor);

    if (dateEdit) {
        dateEdit->setDate(index.data(Qt::EditRole).toDate());
        if (dateEdit->lineEdit()->text().isEmpty()) {
            dateEdit->setDate(QDate::currentDate());
        }
        dateEdit->lineEdit()->selectAll();

    } else {
        QStyledItemDelegate::setEditorData(editor, index);
    }
}

void ActionListDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                      const QModelIndex &index) const
{
    KDateEdit *dateEdit = qobject_cast<KDateEdit*>(editor);

    if (dateEdit) {
        model->setData(index, dateEdit->date());

    } else {
        QStyledItemDelegate::setModelData(editor, model, index);
    }
}
<|endoftext|>


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

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/base/ui_test_utils.h"

const std::string kAllUrlsTarget =
    "files/extensions/api_test/all_urls/index.html";

typedef ExtensionApiTest AllUrlsApiTest;

// http://crbug.com/118293
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, DISABLED_WhitelistedExtension) {
  // First setup the two extensions.
  FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("content_script");
  FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("execute_script");

  // Then add the two extensions to the whitelist.
  Extension::ScriptingWhitelist whitelist;
  whitelist.push_back(Extension::GenerateIdForPath(extension_dir1));
  whitelist.push_back(Extension::GenerateIdForPath(extension_dir2));
  Extension::SetScriptingWhitelist(whitelist);

  // Then load extensions.
  ExtensionService* service = browser()->profile()->GetExtensionService();
  const size_t size_before = service->extensions()->size();
  ASSERT_TRUE(LoadExtension(extension_dir1));
  ASSERT_TRUE(LoadExtension(extension_dir2));
  EXPECT_EQ(size_before + 2, service->extensions()->size());

  std::string url;

  // Now verify we run content scripts on chrome://newtab/.
  url = "chrome://newtab/";
  ExtensionTestMessageListener listener1a("content script: " + url, false);
  ExtensionTestMessageListener listener1b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  ASSERT_TRUE(listener1a.WaitUntilSatisfied());
  ASSERT_TRUE(listener1b.WaitUntilSatisfied());

  // Now verify data: urls.
  url = "data:text/html;charset=utf-8,asdf";
  ExtensionTestMessageListener listener2a("content script: " + url, false);
  ExtensionTestMessageListener listener2b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  ASSERT_TRUE(listener2a.WaitUntilSatisfied());
  ASSERT_TRUE(listener2b.WaitUntilSatisfied());

  // Now verify chrome://version/.
  url = "chrome://version/";
  ExtensionTestMessageListener listener3a("content script: " + url, false);
  ExtensionTestMessageListener listener3b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  ASSERT_TRUE(listener3a.WaitUntilSatisfied());
  ASSERT_TRUE(listener3b.WaitUntilSatisfied());

  // Now verify about:blank.
  url = "about:blank";
  ExtensionTestMessageListener listener4a("content script: " + url, false);
  ExtensionTestMessageListener listener4b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  ASSERT_TRUE(listener4a.WaitUntilSatisfied());
  ASSERT_TRUE(listener4b.WaitUntilSatisfied());

  // Now verify we can script a regular http page.
  ASSERT_TRUE(test_server()->Start());
  GURL page_url = test_server()->GetURL(kAllUrlsTarget);
  ExtensionTestMessageListener listener5a("content script: " + page_url.spec(),
                                          false);
  ExtensionTestMessageListener listener5b("execute: " + page_url.spec(), false);
  ui_test_utils::NavigateToURL(browser(), page_url);
  ASSERT_TRUE(listener5a.WaitUntilSatisfied());
  ASSERT_TRUE(listener5b.WaitUntilSatisfied());
}

// Test that an extension NOT whitelisted for scripting can ask for <all_urls>
// and run scripts on non-restricted all pages.
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, RegularExtensions) {
  // First load the two extension.
  FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("content_script");
  FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("execute_script");

  ExtensionService* service = browser()->profile()->GetExtensionService();
  const size_t size_before = service->extensions()->size();
  ASSERT_TRUE(LoadExtension(extension_dir1));
  ASSERT_TRUE(LoadExtension(extension_dir2));
  EXPECT_EQ(size_before + 2, service->extensions()->size());

  // Now verify we can script a regular http page.
  ASSERT_TRUE(test_server()->Start());
  GURL page_url = test_server()->GetURL(kAllUrlsTarget);
  ExtensionTestMessageListener listener1a("content script: " + page_url.spec(),
                                          false);
  ExtensionTestMessageListener listener1b("execute: " + page_url.spec(), false);
  ui_test_utils::NavigateToURL(browser(), page_url);
  ASSERT_TRUE(listener1a.WaitUntilSatisfied());
  ASSERT_TRUE(listener1b.WaitUntilSatisfied());
}
<commit_msg>re-enable AllUrlsApiTest.WhitelistedExtension<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/test/base/ui_test_utils.h"

const std::string kAllUrlsTarget =
    "files/extensions/api_test/all_urls/index.html";

typedef ExtensionApiTest AllUrlsApiTest;

IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, WhitelistedExtension) {
  // First setup the two extensions.
  FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("content_script");
  FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("execute_script");

  // Then add the two extensions to the whitelist.
  Extension::ScriptingWhitelist whitelist;
  whitelist.push_back(Extension::GenerateIdForPath(extension_dir1));
  whitelist.push_back(Extension::GenerateIdForPath(extension_dir2));
  Extension::SetScriptingWhitelist(whitelist);

  // Then load extensions.
  ExtensionService* service = browser()->profile()->GetExtensionService();
  const size_t size_before = service->extensions()->size();
  ASSERT_TRUE(LoadExtension(extension_dir1));
  ASSERT_TRUE(LoadExtension(extension_dir2));
  EXPECT_EQ(size_before + 2, service->extensions()->size());

  std::string url;

  // Now verify we run content scripts on chrome://newtab/.
  url = "chrome://newtab/";
  ExtensionTestMessageListener listener1a("content script: " + url, false);
  ExtensionTestMessageListener listener1b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  ASSERT_TRUE(listener1a.WaitUntilSatisfied());
  ASSERT_TRUE(listener1b.WaitUntilSatisfied());

  // Now verify data: urls.
  url = "data:text/html;charset=utf-8,asdf";
  ExtensionTestMessageListener listener2a("content script: " + url, false);
  ExtensionTestMessageListener listener2b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  ASSERT_TRUE(listener2a.WaitUntilSatisfied());
  ASSERT_TRUE(listener2b.WaitUntilSatisfied());

  // Now verify chrome://version/.
  url = "chrome://version/";
  ExtensionTestMessageListener listener3a("content script: " + url, false);
  ExtensionTestMessageListener listener3b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  ASSERT_TRUE(listener3a.WaitUntilSatisfied());
  ASSERT_TRUE(listener3b.WaitUntilSatisfied());

  // Now verify about:blank.
  url = "about:blank";
  ExtensionTestMessageListener listener4a("content script: " + url, false);
  ExtensionTestMessageListener listener4b("execute: " + url, false);
  ui_test_utils::NavigateToURL(browser(), GURL(url));
  ASSERT_TRUE(listener4a.WaitUntilSatisfied());
  ASSERT_TRUE(listener4b.WaitUntilSatisfied());

  // Now verify we can script a regular http page.
  ASSERT_TRUE(test_server()->Start());
  GURL page_url = test_server()->GetURL(kAllUrlsTarget);
  ExtensionTestMessageListener listener5a("content script: " + page_url.spec(),
                                          false);
  ExtensionTestMessageListener listener5b("execute: " + page_url.spec(), false);
  ui_test_utils::NavigateToURL(browser(), page_url);
  ASSERT_TRUE(listener5a.WaitUntilSatisfied());
  ASSERT_TRUE(listener5b.WaitUntilSatisfied());
}

// Test that an extension NOT whitelisted for scripting can ask for <all_urls>
// and run scripts on non-restricted all pages.
IN_PROC_BROWSER_TEST_F(AllUrlsApiTest, RegularExtensions) {
  // First load the two extension.
  FilePath extension_dir1 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("content_script");
  FilePath extension_dir2 = test_data_dir_.AppendASCII("all_urls")
                                          .AppendASCII("execute_script");

  ExtensionService* service = browser()->profile()->GetExtensionService();
  const size_t size_before = service->extensions()->size();
  ASSERT_TRUE(LoadExtension(extension_dir1));
  ASSERT_TRUE(LoadExtension(extension_dir2));
  EXPECT_EQ(size_before + 2, service->extensions()->size());

  // Now verify we can script a regular http page.
  ASSERT_TRUE(test_server()->Start());
  GURL page_url = test_server()->GetURL(kAllUrlsTarget);
  ExtensionTestMessageListener listener1a("content script: " + page_url.spec(),
                                          false);
  ExtensionTestMessageListener listener1b("execute: " + page_url.spec(), false);
  ui_test_utils::NavigateToURL(browser(), page_url);
  ASSERT_TRUE(listener1a.WaitUntilSatisfied());
  ASSERT_TRUE(listener1b.WaitUntilSatisfied());
}
<|endoftext|>


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

// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)

#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/events.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/ui_controls/ui_controls.h"
#include "ui/views/controls/menu/menu_listener.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"

namespace {

// An async version of SendKeyPressSync since we don't get notified when a
// menu is showing.
void SendKeyPress(Browser* browser, ui::KeyboardCode key) {
  ASSERT_TRUE(ui_controls::SendKeyPress(
      browser->window()->GetNativeHandle(), key, false, false, false, false));
}

// Helper class that waits until the focus has changed to a view other
// than the one with the provided view id.
class ViewFocusChangeWaiter : public views::FocusChangeListener {
 public:
  ViewFocusChangeWaiter(views::FocusManager* focus_manager,
                        int previous_view_id)
      : focus_manager_(focus_manager),
        previous_view_id_(previous_view_id),
        ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
    focus_manager_->AddFocusChangeListener(this);
    // Call the focus change notification once in case the focus has
    // already changed.
    OnWillChangeFocus(NULL, focus_manager_->GetFocusedView());
  }

  virtual ~ViewFocusChangeWaiter() {
    focus_manager_->RemoveFocusChangeListener(this);
  }

  void Wait() {
    ui_test_utils::RunMessageLoop();
  }

 private:
  // Inherited from FocusChangeListener
  virtual void OnWillChangeFocus(views::View* focused_before,
                                 views::View* focused_now) {
  }

  virtual void OnDidChangeFocus(views::View* focused_before,
                                views::View* focused_now) {
    if (focused_now && focused_now->id() != previous_view_id_) {
      MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
    }
  }

  views::FocusManager* focus_manager_;
  int previous_view_id_;
  base::WeakPtrFactory<ViewFocusChangeWaiter> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(ViewFocusChangeWaiter);
};

class SendKeysMenuListener : public views::MenuListener {
 public:
  SendKeysMenuListener(ToolbarView* toolbar_view, Browser* browser)
      : toolbar_view_(toolbar_view), browser_(browser) {
    toolbar_view_->AddMenuListener(this);
  }

  virtual ~SendKeysMenuListener() {}

 private:
  // Overridden from views::MenuListener:
  virtual void OnMenuOpened() OVERRIDE {
    toolbar_view_->RemoveMenuListener(this);
    // Press DOWN to select the first item, then RETURN to select it.
    SendKeyPress(browser_, ui::VKEY_DOWN);
    SendKeyPress(browser_, ui::VKEY_RETURN);
  }

  ToolbarView* toolbar_view_;
  Browser* browser_;

  DISALLOW_COPY_AND_ASSIGN(SendKeysMenuListener);
};

class KeyboardAccessTest : public InProcessBrowserTest {
 public:
  KeyboardAccessTest() {
    EnableDOMAutomation();
  }

  // Use the keyboard to select "New Tab" from the app menu.
  // This test depends on the fact that there is one menu and that
  // New Tab is the first item in the menu. If the menus change,
  // this test will need to be changed to reflect that.
  //
  // If alternate_key_sequence is true, use "Alt" instead of "F10" to
  // open the menu bar, and "Down" instead of "Enter" to open a menu.
  void TestMenuKeyboardAccess(bool alternate_key_sequence, bool shift);

  int GetFocusedViewID() {
    gfx::NativeWindow window = browser()->window()->GetNativeHandle();
    views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
    const views::FocusManager* focus_manager = widget->GetFocusManager();
    const views::View* focused_view = focus_manager->GetFocusedView();
    return focused_view ? focused_view->id() : -1;
  }

  void WaitForFocusedViewIDToChange(int original_view_id) {
    if (GetFocusedViewID() != original_view_id)
      return;
    gfx::NativeWindow window = browser()->window()->GetNativeHandle();
    views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
    views::FocusManager* focus_manager = widget->GetFocusManager();
    ViewFocusChangeWaiter waiter(focus_manager, original_view_id);
    waiter.Wait();
  }

  DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};

void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence,
                                                bool shift) {
  // Navigate to a page in the first tab, which makes sure that focus is
  // set to the browser window.
  ui_test_utils::NavigateToURL(browser(), GURL("about:"));

  // The initial tab index should be 0.
  ASSERT_EQ(0, browser()->active_index());

  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // Get the focused view ID, then press a key to activate the
  // page menu, then wait until the focused view changes.
  int original_view_id = GetFocusedViewID();

  ui_test_utils::WindowedNotificationObserver new_tab_observer(
      chrome::NOTIFICATION_TAB_ADDED,
      content::Source<content::WebContentsDelegate>(browser()));

  BrowserView* browser_view = reinterpret_cast<BrowserView*>(
      browser()->window());
  ToolbarView* toolbar_view = browser_view->GetToolbarView();
  SendKeysMenuListener menu_listener(toolbar_view, browser());

#if defined(OS_CHROMEOS)
  // Chrome OS doesn't have a way to just focus the wrench menu, so we use Alt+F
  // to bring up the menu.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_F, false, shift, true, false));
#else
  ui::KeyboardCode menu_key =
      alternate_key_sequence ? ui::VKEY_MENU : ui::VKEY_F10;
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), menu_key, false, shift, false, false));
#endif

  if (shift) {
    // Verify Chrome does not move the view focus. We should not move the view
    // focus when typing a menu key with modifier keys, such as shift keys or
    // control keys.
    int new_view_id = GetFocusedViewID();
    ASSERT_EQ(original_view_id, new_view_id);
    return;
  }

  WaitForFocusedViewIDToChange(original_view_id);

  // See above comment. Since we already brought up the menu, no need to do this
  // on ChromeOS.
#if !defined(OS_CHROMEOS)
  if (alternate_key_sequence)
    SendKeyPress(browser(), ui::VKEY_DOWN);
  else
    SendKeyPress(browser(), ui::VKEY_RETURN);
#endif

  // Wait for the new tab to appear.
  new_tab_observer.Wait();

  // Make sure that the new tab index is 1.
  ASSERT_EQ(1, browser()->active_index());
}

// If this flakes, use http://crbug.com/62310.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
  TestMenuKeyboardAccess(false, false);
}

// If this flakes, use http://crbug.com/62310.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
  TestMenuKeyboardAccess(true, false);
}

// If this flakes, use http://crbug.com/62311.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestShiftAltMenuKeyboardAccess) {
  TestMenuKeyboardAccess(true, true);
}

// Test that JavaScript cannot intercept reserved keyboard accelerators like
// ctrl-t to open a new tab or ctrl-f4 to close a tab.
// TODO(isherman): This test times out on ChromeOS.  We should merge it with
// BrowserKeyEventsTest.ReservedAccelerators, but just disable for now.
// If this flakes, use http://crbug.com/62311.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, ReserveKeyboardAccelerators) {
  const std::string kBadPage =
      "";
  GURL url("data:text/html," + kBadPage);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), url, NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_TAB, true, false, false, false));
  ASSERT_EQ(0, browser()->active_index());

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), url, NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ASSERT_EQ(2, browser()->active_index());

  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_W, true, false, false, false));
  ASSERT_EQ(0, browser()->active_index());
}

}  // namespace

#endif  // defined(TOOLKIT_VIEWS)
<commit_msg>Mark KeyboardAccessTest.TestShiftAltMenuKeyboardAccess as flaky on Win<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This functionality currently works on Windows and on Linux when
// toolkit_views is defined (i.e. for Chrome OS). It's not needed
// on the Mac, and it's not yet implemented on Linux.
#if defined(TOOLKIT_VIEWS)

#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "ui/base/events.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/ui_controls/ui_controls.h"
#include "ui/views/controls/menu/menu_listener.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"

namespace {

// An async version of SendKeyPressSync since we don't get notified when a
// menu is showing.
void SendKeyPress(Browser* browser, ui::KeyboardCode key) {
  ASSERT_TRUE(ui_controls::SendKeyPress(
      browser->window()->GetNativeHandle(), key, false, false, false, false));
}

// Helper class that waits until the focus has changed to a view other
// than the one with the provided view id.
class ViewFocusChangeWaiter : public views::FocusChangeListener {
 public:
  ViewFocusChangeWaiter(views::FocusManager* focus_manager,
                        int previous_view_id)
      : focus_manager_(focus_manager),
        previous_view_id_(previous_view_id),
        ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
    focus_manager_->AddFocusChangeListener(this);
    // Call the focus change notification once in case the focus has
    // already changed.
    OnWillChangeFocus(NULL, focus_manager_->GetFocusedView());
  }

  virtual ~ViewFocusChangeWaiter() {
    focus_manager_->RemoveFocusChangeListener(this);
  }

  void Wait() {
    ui_test_utils::RunMessageLoop();
  }

 private:
  // Inherited from FocusChangeListener
  virtual void OnWillChangeFocus(views::View* focused_before,
                                 views::View* focused_now) {
  }

  virtual void OnDidChangeFocus(views::View* focused_before,
                                views::View* focused_now) {
    if (focused_now && focused_now->id() != previous_view_id_) {
      MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
    }
  }

  views::FocusManager* focus_manager_;
  int previous_view_id_;
  base::WeakPtrFactory<ViewFocusChangeWaiter> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(ViewFocusChangeWaiter);
};

class SendKeysMenuListener : public views::MenuListener {
 public:
  SendKeysMenuListener(ToolbarView* toolbar_view, Browser* browser)
      : toolbar_view_(toolbar_view), browser_(browser) {
    toolbar_view_->AddMenuListener(this);
  }

  virtual ~SendKeysMenuListener() {}

 private:
  // Overridden from views::MenuListener:
  virtual void OnMenuOpened() OVERRIDE {
    toolbar_view_->RemoveMenuListener(this);
    // Press DOWN to select the first item, then RETURN to select it.
    SendKeyPress(browser_, ui::VKEY_DOWN);
    SendKeyPress(browser_, ui::VKEY_RETURN);
  }

  ToolbarView* toolbar_view_;
  Browser* browser_;

  DISALLOW_COPY_AND_ASSIGN(SendKeysMenuListener);
};

class KeyboardAccessTest : public InProcessBrowserTest {
 public:
  KeyboardAccessTest() {
    EnableDOMAutomation();
  }

  // Use the keyboard to select "New Tab" from the app menu.
  // This test depends on the fact that there is one menu and that
  // New Tab is the first item in the menu. If the menus change,
  // this test will need to be changed to reflect that.
  //
  // If alternate_key_sequence is true, use "Alt" instead of "F10" to
  // open the menu bar, and "Down" instead of "Enter" to open a menu.
  void TestMenuKeyboardAccess(bool alternate_key_sequence, bool shift);

  int GetFocusedViewID() {
    gfx::NativeWindow window = browser()->window()->GetNativeHandle();
    views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
    const views::FocusManager* focus_manager = widget->GetFocusManager();
    const views::View* focused_view = focus_manager->GetFocusedView();
    return focused_view ? focused_view->id() : -1;
  }

  void WaitForFocusedViewIDToChange(int original_view_id) {
    if (GetFocusedViewID() != original_view_id)
      return;
    gfx::NativeWindow window = browser()->window()->GetNativeHandle();
    views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
    views::FocusManager* focus_manager = widget->GetFocusManager();
    ViewFocusChangeWaiter waiter(focus_manager, original_view_id);
    waiter.Wait();
  }

  DISALLOW_COPY_AND_ASSIGN(KeyboardAccessTest);
};

void KeyboardAccessTest::TestMenuKeyboardAccess(bool alternate_key_sequence,
                                                bool shift) {
  // Navigate to a page in the first tab, which makes sure that focus is
  // set to the browser window.
  ui_test_utils::NavigateToURL(browser(), GURL("about:"));

  // The initial tab index should be 0.
  ASSERT_EQ(0, browser()->active_index());

  ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));

  // Get the focused view ID, then press a key to activate the
  // page menu, then wait until the focused view changes.
  int original_view_id = GetFocusedViewID();

  ui_test_utils::WindowedNotificationObserver new_tab_observer(
      chrome::NOTIFICATION_TAB_ADDED,
      content::Source<content::WebContentsDelegate>(browser()));

  BrowserView* browser_view = reinterpret_cast<BrowserView*>(
      browser()->window());
  ToolbarView* toolbar_view = browser_view->GetToolbarView();
  SendKeysMenuListener menu_listener(toolbar_view, browser());

#if defined(OS_CHROMEOS)
  // Chrome OS doesn't have a way to just focus the wrench menu, so we use Alt+F
  // to bring up the menu.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_F, false, shift, true, false));
#else
  ui::KeyboardCode menu_key =
      alternate_key_sequence ? ui::VKEY_MENU : ui::VKEY_F10;
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), menu_key, false, shift, false, false));
#endif

  if (shift) {
    // Verify Chrome does not move the view focus. We should not move the view
    // focus when typing a menu key with modifier keys, such as shift keys or
    // control keys.
    int new_view_id = GetFocusedViewID();
    ASSERT_EQ(original_view_id, new_view_id);
    return;
  }

  WaitForFocusedViewIDToChange(original_view_id);

  // See above comment. Since we already brought up the menu, no need to do this
  // on ChromeOS.
#if !defined(OS_CHROMEOS)
  if (alternate_key_sequence)
    SendKeyPress(browser(), ui::VKEY_DOWN);
  else
    SendKeyPress(browser(), ui::VKEY_RETURN);
#endif

  // Wait for the new tab to appear.
  new_tab_observer.Wait();

  // Make sure that the new tab index is 1.
  ASSERT_EQ(1, browser()->active_index());
}

// If this flakes, use http://crbug.com/62310.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestMenuKeyboardAccess) {
  TestMenuKeyboardAccess(false, false);
}

// If this flakes, use http://crbug.com/62310.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, TestAltMenuKeyboardAccess) {
  TestMenuKeyboardAccess(true, false);
}

// If this flakes, use http://crbug.com/62311.
#if defined(OS_WIN)
#define MAYBE_TestShiftAltMenuKeyboardAccess FLAKY_TestShiftAltMenuKeyboardAccess
#else
#define MAYBE_TestShiftAltMenuKeyboardAccess TestShiftAltMenuKeyboardAccess
#endif
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest,
                       MAYBE_TestShiftAltMenuKeyboardAccess) {
  TestMenuKeyboardAccess(true, true);
}

// Test that JavaScript cannot intercept reserved keyboard accelerators like
// ctrl-t to open a new tab or ctrl-f4 to close a tab.
// TODO(isherman): This test times out on ChromeOS.  We should merge it with
// BrowserKeyEventsTest.ReservedAccelerators, but just disable for now.
// If this flakes, use http://crbug.com/62311.
IN_PROC_BROWSER_TEST_F(KeyboardAccessTest, ReserveKeyboardAccelerators) {
  const std::string kBadPage =
      "";
  GURL url("data:text/html," + kBadPage);
  ui_test_utils::NavigateToURLWithDisposition(
      browser(), url, NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);

  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_TAB, true, false, false, false));
  ASSERT_EQ(0, browser()->active_index());

  ui_test_utils::NavigateToURLWithDisposition(
      browser(), url, NEW_FOREGROUND_TAB,
      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
  ASSERT_EQ(2, browser()->active_index());

  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
      browser(), ui::VKEY_W, true, false, false, false));
  ASSERT_EQ(0, browser()->active_index());
}

}  // namespace

#endif  // defined(TOOLKIT_VIEWS)
<|endoftext|>


<commit_before><commit_msg>Revert 73504 - fix for build break BUG=none TEST=none Review URL: http://codereview.chromium.org/6334063<commit_after><|endoftext|>


<commit_before>/* Autogenerated with kurento-module-creator */

#include "TelmateFrameGrabberOpenCVImpl.hpp"
#include <gst/gst.h>
#include <KurentoException.hpp>
#include <vector>
#include <string>

#define GST_CAT_DEFAULT kurento_telmate_frame_grabber_opencv_impl
GST_DEBUG_CATEGORY_STATIC(GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoTelmateFrameGrabberOpenCVImpl"

namespace kurento {

TelmateFrameGrabberOpenCVImpl::TelmateFrameGrabberOpenCVImpl() {

    GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                            GST_DEFAULT_NAME);

    this->thrLoop = true;
    this->snapInterval = 1000;
    this->epName = "EP_NAME_UNINITIALIZED";
    this->storagePath = "/tmp";
    this->framesCounter = 0;
    this->outputFormat = FGFMT_JPEG;
    this->lastQueueTimeStamp = 0;
    this->queueLength = 0;
    this->frameQueue = new avis_blocking_queue<VideoFrame*>;

    this->thr = new boost::thread(boost::bind(
            &TelmateFrameGrabberOpenCVImpl::queueHandler, this));
    this->thr->detach();

    GST_INFO("Constructor was called for %s", this->epName.c_str());
}

TelmateFrameGrabberOpenCVImpl::~TelmateFrameGrabberOpenCVImpl() {

    GST_INFO("Destructor was called for %s", this->epName.c_str());

}

void TelmateFrameGrabberOpenCVImpl::cleanup() {

    VideoFrame *ptrVf;

    while(!this->frameQueue->empty()) {
        this->frameQueue->pop(ptrVf); // blocks
        --this->queueLength;
        delete ptrVf;
        ptrVf = NULL;

    }

    this->thrLoop = false;
    boost::this_thread::sleep_for(boost::chrono::milliseconds(250)); /* Give the processing thread some time to exit() */
    GST_INFO("Called release() for %s :: Dequeue completed.", this->epName.c_str());

    delete this->frameQueue;
    this->frameQueue = NULL;

    return;
}

/*
 * This function will be called with each new frame. mat variable
 * contains the current frame. You should insert your image processing code
 * here. Any changes in mat, will be sent through the Media Pipeline.
 */
void TelmateFrameGrabberOpenCVImpl::process(cv::Mat &mat) {
        if ((this->getCurrentTimestampLong() - this->lastQueueTimeStamp) >= this->snapInterval) {

            if(this->thrLoop) { // do not push into the queue if the destructor was called.
                this->lastQueueTimeStamp = this->getCurrentTimestampLong();
                VideoFrame *ptrVf = new VideoFrame();
                ptrVf->mat = mat.clone();
                ptrVf->ts = std::to_string(this->lastQueueTimeStamp);

                this->frameQueue->push(ptrVf);
                ++this->queueLength;
                ++this->framesCounter;
            }
        }
}
/*
 * This function is executed inside the queueHandler thread as a main() function.
 * It pops a VideoFrame from the framequeue and saves it to disk.
 * a boost scoped_lock is implemented to ensure the queue is emptied to disk before
 * the destructor is executed. a 1 second sleep is implemented inside the while() loop
 * to ensure the cpu isn't exhausted while the queue is empty.
 */
void TelmateFrameGrabberOpenCVImpl::queueHandler() {
        VideoFrame *ptrVf;
        cv::Mat image;
        std::vector<int> params;
        std::string image_extension;

        while (this->thrLoop) {

            this->frameQueue->pop(ptrVf); // blocks
            params.clear();     // clear the vector since the last iteration.
            this->lastQueueTimeStamp = this->getCurrentTimestampLong();
            --this->queueLength;

            switch (this->outputFormat) {
                case FGFMT_JPEG:
                    /* Set jpeg params */
                    params.push_back(CV_IMWRITE_JPEG_QUALITY);
                    params.push_back(FG_JPEG_QUALITY);
                    image_extension = ".jpeg";
                    break;
                case FGFMT_PNG:
                    /* Set PNG parameters, compression etc. */
                    params.push_back(CV_IMWRITE_PNG_COMPRESSION);
                    params.push_back(FG_PNG_QUALITY);
                    image_extension = ".png";
                    break;
                default:
                    /* Defaults to jpeg */
                    params.push_back(CV_IMWRITE_JPEG_QUALITY);
                    params.push_back(FG_JPEG_QUALITY);
                    image_extension = ".jpeg";
                    break;
            }

            std::string filename =
                    std::to_string((long) this->framesCounter) + "_" + ptrVf->ts + image_extension;

            if (this->storagePathSubdir.empty()) {
                this->storagePathSubdir = this->storagePath + "/frames_" + this->getCurrentTimestampString();
                boost::filesystem::path dir(this->storagePathSubdir.c_str());
                if (!boost::filesystem::create_directories(dir)) {
                    GST_ERROR("%s create_directories() failed for: %s", this->epName.c_str(),
                              this->storagePathSubdir.c_str());
                }
            }

            std::string fullpath = this->storagePathSubdir + "/" + filename;

            try {
                cv::imwrite(fullpath.c_str(), ptrVf->mat, params);
            }
            catch (...) {
                GST_ERROR("::queueHandler() imgwrite() failed.");
                throw KurentoException(NOT_IMPLEMENTED,
                                       "TelmateFrameGrabberOpenCVImpl::queueHandler() imgwrite() failed. \n");
            }

            ptrVf->mat.release();   // release internal memory allocations

            delete ptrVf;
            ptrVf = NULL;

        }

}

std::string TelmateFrameGrabberOpenCVImpl::getCurrentTimestampString() {
    struct timeval tp;
    long int ms;
    std::stringstream sstr_ts;

    gettimeofday(&tp, NULL);
    ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
    sstr_ts << ms;
    return sstr_ts.str();
}

long TelmateFrameGrabberOpenCVImpl::getCurrentTimestampLong() {
    struct timeval tp;

    gettimeofday(&tp, NULL);
    return (tp.tv_sec * 1000 + tp.tv_usec / 1000);
}

}   // namespace kurento
<commit_msg>fix storage path<commit_after>/* Autogenerated with kurento-module-creator */

#include "TelmateFrameGrabberOpenCVImpl.hpp"
#include <gst/gst.h>
#include <KurentoException.hpp>
#include <vector>
#include <string>

#define GST_CAT_DEFAULT kurento_telmate_frame_grabber_opencv_impl
GST_DEBUG_CATEGORY_STATIC(GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoTelmateFrameGrabberOpenCVImpl"

namespace kurento {

TelmateFrameGrabberOpenCVImpl::TelmateFrameGrabberOpenCVImpl() {

    GST_DEBUG_CATEGORY_INIT(GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
                            GST_DEFAULT_NAME);

    this->thrLoop = true;
    this->snapInterval = 1000;
    this->epName = "EP_NAME_UNINITIALIZED";
    this->storagePath.clear(); //= NULL; /*"/tmp";*/
    this->framesCounter = 0;
    this->outputFormat = FGFMT_JPEG;
    this->lastQueueTimeStamp = 0;
    this->queueLength = 0;
    this->frameQueue = new avis_blocking_queue<VideoFrame*>;

    this->thr = new boost::thread(boost::bind(
            &TelmateFrameGrabberOpenCVImpl::queueHandler, this));
    this->thr->detach();

    GST_INFO("Constructor was called for %s", this->epName.c_str());
}

TelmateFrameGrabberOpenCVImpl::~TelmateFrameGrabberOpenCVImpl() {

    GST_INFO("Destructor was called for %s", this->epName.c_str());

}

void TelmateFrameGrabberOpenCVImpl::cleanup() {

    VideoFrame *ptrVf;

    while(!this->frameQueue->empty()) {
        this->frameQueue->pop(ptrVf); // blocks
        --this->queueLength;
        delete ptrVf;
        ptrVf = NULL;

    }

    this->thrLoop = false;
    boost::this_thread::sleep_for(boost::chrono::milliseconds(250)); /* Give the processing thread some time to exit() */
    GST_INFO("Called release() for %s :: Dequeue completed.", this->epName.c_str());

    delete this->frameQueue;
    this->frameQueue = NULL;

    return;
}

/*
 * This function will be called with each new frame. mat variable
 * contains the current frame. You should insert your image processing code
 * here. Any changes in mat, will be sent through the Media Pipeline.
 */
void TelmateFrameGrabberOpenCVImpl::process(cv::Mat &mat) {
        if ((this->getCurrentTimestampLong() - this->lastQueueTimeStamp) >= this->snapInterval) {

            if(this->thrLoop) { // do not push into the queue if the destructor was called.
                this->lastQueueTimeStamp = this->getCurrentTimestampLong();
                VideoFrame *ptrVf = new VideoFrame();
                ptrVf->mat = mat.clone();
                ptrVf->ts = std::to_string(this->lastQueueTimeStamp);

                this->frameQueue->push(ptrVf);
                ++this->queueLength;
                ++this->framesCounter;
            }
        }
}
/*
 * This function is executed inside the queueHandler thread as a main() function.
 * It pops a VideoFrame from the framequeue and saves it to disk.
 * a boost scoped_lock is implemented to ensure the queue is emptied to disk before
 * the destructor is executed. a 1 second sleep is implemented inside the while() loop
 * to ensure the cpu isn't exhausted while the queue is empty.
 */
void TelmateFrameGrabberOpenCVImpl::queueHandler() {
        VideoFrame *ptrVf;
        cv::Mat image;
        std::vector<int> params;
        std::string image_extension;

        while (this->thrLoop) {

            if(this->storagePath.empty()) {
                boost::this_thread::sleep_for(boost::chrono::milliseconds(50));
                continue;
            }
            this->frameQueue->pop(ptrVf); // blocks
            params.clear();     // clear the vector since the last iteration.
            this->lastQueueTimeStamp = this->getCurrentTimestampLong();
            --this->queueLength;

            switch (this->outputFormat) {
                case FGFMT_JPEG:
                    /* Set jpeg params */
                    params.push_back(CV_IMWRITE_JPEG_QUALITY);
                    params.push_back(FG_JPEG_QUALITY);
                    image_extension = ".jpeg";
                    break;
                case FGFMT_PNG:
                    /* Set PNG parameters, compression etc. */
                    params.push_back(CV_IMWRITE_PNG_COMPRESSION);
                    params.push_back(FG_PNG_QUALITY);
                    image_extension = ".png";
                    break;
                default:
                    /* Defaults to jpeg */
                    params.push_back(CV_IMWRITE_JPEG_QUALITY);
                    params.push_back(FG_JPEG_QUALITY);
                    image_extension = ".jpeg";
                    break;
            }

            std::string filename =
                    std::to_string((long) this->framesCounter) + "_" + ptrVf->ts + image_extension;

            if (this->storagePathSubdir.empty()) {
                this->storagePathSubdir = this->storagePath + "/frames_" + this->getCurrentTimestampString();
                boost::filesystem::path dir(this->storagePathSubdir.c_str());
                if (!boost::filesystem::create_directories(dir)) {
                    GST_ERROR("%s create_directories() failed for: %s", this->epName.c_str(),
                              this->storagePathSubdir.c_str());
                }
            }

            std::string fullpath = this->storagePathSubdir + "/" + filename;

            try {
                cv::imwrite(fullpath.c_str(), ptrVf->mat, params);
            }
            catch (...) {
                GST_ERROR("::queueHandler() imgwrite() failed.");
                throw KurentoException(NOT_IMPLEMENTED,
                                       "TelmateFrameGrabberOpenCVImpl::queueHandler() imgwrite() failed. \n");
            }

            ptrVf->mat.release();   // release internal memory allocations

            delete ptrVf;
            ptrVf = NULL;

        }

}

std::string TelmateFrameGrabberOpenCVImpl::getCurrentTimestampString() {
    struct timeval tp;
    long int ms;
    std::stringstream sstr_ts;

    gettimeofday(&tp, NULL);
    ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;
    sstr_ts << ms;
    return sstr_ts.str();
}

long TelmateFrameGrabberOpenCVImpl::getCurrentTimestampLong() {
    struct timeval tp;

    gettimeofday(&tp, NULL);
    return (tp.tv_sec * 1000 + tp.tv_usec / 1000);
}

}   // namespace kurento
<|endoftext|>


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

#include <gtk/gtk.h>

#include "build/build_config.h"

#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/page_info_model.h"
#include "chrome/browser/page_info_window.h"
#include "chrome/browser/ui/gtk/browser_toolbar_gtk.h"
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#include "chrome/browser/ui/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/gtk/info_bubble_gtk.h"
#include "chrome/browser/ui/gtk/location_bar_view_gtk.h"
#include "chrome/common/url_constants.h"
#include "content/browser/certificate_viewer.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"

class Profile;

namespace {

class PageInfoBubbleGtk : public PageInfoModel::PageInfoModelObserver,
                          public InfoBubbleGtkDelegate,
                          public NotificationObserver {
 public:
  PageInfoBubbleGtk(gfx::NativeWindow parent,
                    Profile* profile,
                    const GURL& url,
                    const NavigationEntry::SSLStatus& ssl,
                    bool show_history);
  virtual ~PageInfoBubbleGtk();

  // PageInfoModelObserver implementation:
  virtual void ModelChanged();

  // NotificationObserver implementation:
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details);

  // InfoBubbleGtkDelegate implementation:
  virtual void InfoBubbleClosing(InfoBubbleGtk* info_bubble,
                                 bool closed_by_escape);

 private:
  // Layouts the different sections retrieved from the model.
  void InitContents();

  // Returns a widget that contains the UI for the passed |section|.
  GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section);

  // Link button callbacks.
  CHROMEGTK_CALLBACK_0(PageInfoBubbleGtk, void, OnViewCertLinkClicked);
  CHROMEGTK_CALLBACK_0(PageInfoBubbleGtk, void, OnHelpLinkClicked);

  // The model containing the different sections to display.
  PageInfoModel model_;

  // The url for this dialog. Should be unique among active dialogs.
  GURL url_;

  // The id of the certificate for this page.
  int cert_id_;

  // Parent window.
  GtkWindow* parent_;

  // The virtual box containing the sections.
  GtkWidget* contents_;

  // The widget relative to which we are positioned.
  GtkWidget* anchor_;

  // Provides colors and stuff.
  GtkThemeService* theme_service_;

  // The various elements in the interface we keep track of for theme changes.
  std::vector<GtkWidget*> labels_;
  std::vector<GtkWidget*> links_;

  InfoBubbleGtk* bubble_;

  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(PageInfoBubbleGtk);
};

PageInfoBubbleGtk::PageInfoBubbleGtk(gfx::NativeWindow parent,
                                     Profile* profile,
                                     const GURL& url,
                                     const NavigationEntry::SSLStatus& ssl,
                                     bool show_history)
    : ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
                                            show_history, this)),
      url_(url),
      cert_id_(ssl.cert_id()),
      parent_(parent),
      contents_(NULL),
      theme_service_(GtkThemeService::GetFrom(profile)) {
  BrowserWindowGtk* browser_window =
      BrowserWindowGtk::GetBrowserWindowForNativeWindow(parent);

  anchor_ = browser_window->
      GetToolbar()->GetLocationBarView()->location_icon_widget();

  registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
                 NotificationService::AllSources());

  InitContents();

  InfoBubbleGtk::ArrowLocationGtk arrow_location = base::i18n::IsRTL() ?
      InfoBubbleGtk::ARROW_LOCATION_TOP_RIGHT :
      InfoBubbleGtk::ARROW_LOCATION_TOP_LEFT;
  bubble_ = InfoBubbleGtk::Show(anchor_,
                                NULL,  // |rect|
                                contents_,
                                arrow_location,
                                true,  // |match_system_theme|
                                true,  // |grab_input|
                                theme_service_,
                                this);  // |delegate|
  if (!bubble_) {
    NOTREACHED();
    return;
  }
}

PageInfoBubbleGtk::~PageInfoBubbleGtk() {
}

void PageInfoBubbleGtk::ModelChanged() {
  InitContents();
}

void PageInfoBubbleGtk::Observe(NotificationType type,
                                const NotificationSource& source,
                                const NotificationDetails& details) {
  DCHECK(type == NotificationType::BROWSER_THEME_CHANGED);

  for (std::vector<GtkWidget*>::iterator it = links_.begin();
       it != links_.end(); ++it) {
    gtk_chrome_link_button_set_use_gtk_theme(
        GTK_CHROME_LINK_BUTTON(*it),
        theme_service_->UseGtkTheme());
  }

  if (theme_service_->UseGtkTheme()) {
    for (std::vector<GtkWidget*>::iterator it = labels_.begin();
         it != labels_.end(); ++it) {
      gtk_widget_modify_fg(*it, GTK_STATE_NORMAL, NULL);
    }
  } else {
    for (std::vector<GtkWidget*>::iterator it = labels_.begin();
         it != labels_.end(); ++it) {
      gtk_widget_modify_fg(*it, GTK_STATE_NORMAL, &gtk_util::kGdkBlack);
    }
  }
}

void PageInfoBubbleGtk::InfoBubbleClosing(InfoBubbleGtk* info_bubble,
                                          bool closed_by_escape) {
  delete this;
}

void PageInfoBubbleGtk::InitContents() {
  if (!contents_) {
    contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing);
    gtk_container_set_border_width(GTK_CONTAINER(contents_),
                                   gtk_util::kContentAreaBorder);
  } else {
    labels_.clear();
    links_.clear();
    gtk_util::RemoveAllChildren(contents_);
  }

  for (int i = 0; i < model_.GetSectionCount(); i++) {
    gtk_box_pack_start(GTK_BOX(contents_),
                       CreateSection(model_.GetSectionInfo(i)),
                       FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(contents_),
                       gtk_hseparator_new(),
                       FALSE, FALSE, 0);
  }

  GtkWidget* help_link = gtk_chrome_link_button_new(
      l10n_util::GetStringUTF8(IDS_PAGE_INFO_HELP_CENTER_LINK).c_str());
  links_.push_back(help_link);
  GtkWidget* help_link_hbox = gtk_hbox_new(FALSE, 0);
  // Stick it in an hbox so it doesn't expand to the whole width.
  gtk_box_pack_start(GTK_BOX(help_link_hbox), help_link, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(contents_), help_link_hbox, FALSE, FALSE, 0);
  g_signal_connect(help_link, "clicked",
                   G_CALLBACK(OnHelpLinkClickedThunk), this);

  theme_service_->InitThemesFor(this);
  gtk_widget_show_all(contents_);
}

GtkWidget* PageInfoBubbleGtk::CreateSection(
    const PageInfoModel::SectionInfo& section) {
  GtkWidget* section_box = gtk_hbox_new(FALSE, gtk_util::kControlSpacing);

  GdkPixbuf* pixbuf = *model_.GetIconImage(section.icon_id);
  if (pixbuf) {
    GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
    gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE, 0);
    gtk_misc_set_alignment(GTK_MISC(image), 0, 0);
  }

  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(section_box), vbox, TRUE, TRUE, 0);

  if (!section.headline.empty()) {
    GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.headline).c_str());
    labels_.push_back(label);
    PangoAttrList* attributes = pango_attr_list_new();
    pango_attr_list_insert(attributes,
                           pango_attr_weight_new(PANGO_WEIGHT_BOLD));
    gtk_label_set_attributes(GTK_LABEL(label), attributes);
    pango_attr_list_unref(attributes);
    gtk_util::SetLabelWidth(label, 400);
    // Allow linebreaking in the middle of words if necessary, so that extremely
    // long hostnames (longer than one line) will still be completely shown.
    gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
    gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
  }
  GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.description).c_str());
  labels_.push_back(label);
  gtk_util::SetLabelWidth(label, 400);
  // Allow linebreaking in the middle of words if necessary, so that extremely
  // long hostnames (longer than one line) will still be completely shown.
  gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
  gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);

  if (section.type == PageInfoModel::SECTION_INFO_IDENTITY && cert_id_ > 0) {
    GtkWidget* view_cert_link = gtk_chrome_link_button_new(
        l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str());
    links_.push_back(view_cert_link);
    GtkWidget* cert_link_hbox = gtk_hbox_new(FALSE, 0);
    // Stick it in an hbox so it doesn't expand to the whole width.
    gtk_box_pack_start(GTK_BOX(cert_link_hbox), view_cert_link,
                       FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(vbox), cert_link_hbox, FALSE, FALSE, 0);
    g_signal_connect(view_cert_link, "clicked",
                     G_CALLBACK(OnViewCertLinkClickedThunk), this);
  }

  return section_box;
}

void PageInfoBubbleGtk::OnViewCertLinkClicked(GtkWidget* widget) {
  ShowCertificateViewerByID(GTK_WINDOW(parent_), cert_id_);
  bubble_->Close();
}

void PageInfoBubbleGtk::OnHelpLinkClicked(GtkWidget* widget) {
  GURL url = google_util::AppendGoogleLocaleParam(
      GURL(chrome::kPageInfoHelpCenterURL));
  Browser* browser = BrowserList::GetLastActive();
  browser->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
  bubble_->Close();
}

}  // namespace

namespace browser {

void ShowPageInfoBubble(gfx::NativeWindow parent,
                        Profile* profile,
                        const GURL& url,
                        const NavigationEntry::SSLStatus& ssl,
                        bool show_history) {
  new PageInfoBubbleGtk(parent, profile, url, ssl, show_history);
}

}  // namespace browser
<commit_msg>gtk: Allow text selection in the page info bubble.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gtk/gtk.h>

#include "build/build_config.h"

#include "base/i18n/rtl.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/page_info_model.h"
#include "chrome/browser/page_info_window.h"
#include "chrome/browser/ui/gtk/browser_toolbar_gtk.h"
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#include "chrome/browser/ui/gtk/gtk_chrome_link_button.h"
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/gtk/info_bubble_gtk.h"
#include "chrome/browser/ui/gtk/location_bar_view_gtk.h"
#include "chrome/common/url_constants.h"
#include "content/browser/certificate_viewer.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "ui/base/l10n/l10n_util.h"

class Profile;

namespace {

class PageInfoBubbleGtk : public PageInfoModel::PageInfoModelObserver,
                          public InfoBubbleGtkDelegate,
                          public NotificationObserver {
 public:
  PageInfoBubbleGtk(gfx::NativeWindow parent,
                    Profile* profile,
                    const GURL& url,
                    const NavigationEntry::SSLStatus& ssl,
                    bool show_history);
  virtual ~PageInfoBubbleGtk();

  // PageInfoModelObserver implementation:
  virtual void ModelChanged();

  // NotificationObserver implementation:
  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details);

  // InfoBubbleGtkDelegate implementation:
  virtual void InfoBubbleClosing(InfoBubbleGtk* info_bubble,
                                 bool closed_by_escape);

 private:
  // Layouts the different sections retrieved from the model.
  void InitContents();

  // Returns a widget that contains the UI for the passed |section|.
  GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section);

  // Link button callbacks.
  CHROMEGTK_CALLBACK_0(PageInfoBubbleGtk, void, OnViewCertLinkClicked);
  CHROMEGTK_CALLBACK_0(PageInfoBubbleGtk, void, OnHelpLinkClicked);

  // The model containing the different sections to display.
  PageInfoModel model_;

  // The url for this dialog. Should be unique among active dialogs.
  GURL url_;

  // The id of the certificate for this page.
  int cert_id_;

  // Parent window.
  GtkWindow* parent_;

  // The virtual box containing the sections.
  GtkWidget* contents_;

  // The widget relative to which we are positioned.
  GtkWidget* anchor_;

  // Provides colors and stuff.
  GtkThemeService* theme_service_;

  // The various elements in the interface we keep track of for theme changes.
  std::vector<GtkWidget*> labels_;
  std::vector<GtkWidget*> links_;

  InfoBubbleGtk* bubble_;

  NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(PageInfoBubbleGtk);
};

PageInfoBubbleGtk::PageInfoBubbleGtk(gfx::NativeWindow parent,
                                     Profile* profile,
                                     const GURL& url,
                                     const NavigationEntry::SSLStatus& ssl,
                                     bool show_history)
    : ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl,
                                            show_history, this)),
      url_(url),
      cert_id_(ssl.cert_id()),
      parent_(parent),
      contents_(NULL),
      theme_service_(GtkThemeService::GetFrom(profile)) {
  BrowserWindowGtk* browser_window =
      BrowserWindowGtk::GetBrowserWindowForNativeWindow(parent);

  anchor_ = browser_window->
      GetToolbar()->GetLocationBarView()->location_icon_widget();

  registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
                 NotificationService::AllSources());

  InitContents();

  InfoBubbleGtk::ArrowLocationGtk arrow_location = base::i18n::IsRTL() ?
      InfoBubbleGtk::ARROW_LOCATION_TOP_RIGHT :
      InfoBubbleGtk::ARROW_LOCATION_TOP_LEFT;
  bubble_ = InfoBubbleGtk::Show(anchor_,
                                NULL,  // |rect|
                                contents_,
                                arrow_location,
                                true,  // |match_system_theme|
                                true,  // |grab_input|
                                theme_service_,
                                this);  // |delegate|
  if (!bubble_) {
    NOTREACHED();
    return;
  }
}

PageInfoBubbleGtk::~PageInfoBubbleGtk() {
}

void PageInfoBubbleGtk::ModelChanged() {
  InitContents();
}

void PageInfoBubbleGtk::Observe(NotificationType type,
                                const NotificationSource& source,
                                const NotificationDetails& details) {
  DCHECK(type == NotificationType::BROWSER_THEME_CHANGED);

  for (std::vector<GtkWidget*>::iterator it = links_.begin();
       it != links_.end(); ++it) {
    gtk_chrome_link_button_set_use_gtk_theme(
        GTK_CHROME_LINK_BUTTON(*it),
        theme_service_->UseGtkTheme());
  }

  if (theme_service_->UseGtkTheme()) {
    for (std::vector<GtkWidget*>::iterator it = labels_.begin();
         it != labels_.end(); ++it) {
      gtk_widget_modify_fg(*it, GTK_STATE_NORMAL, NULL);
    }
  } else {
    for (std::vector<GtkWidget*>::iterator it = labels_.begin();
         it != labels_.end(); ++it) {
      gtk_widget_modify_fg(*it, GTK_STATE_NORMAL, &gtk_util::kGdkBlack);
    }
  }
}

void PageInfoBubbleGtk::InfoBubbleClosing(InfoBubbleGtk* info_bubble,
                                          bool closed_by_escape) {
  delete this;
}

void PageInfoBubbleGtk::InitContents() {
  if (!contents_) {
    contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing);
    gtk_container_set_border_width(GTK_CONTAINER(contents_),
                                   gtk_util::kContentAreaBorder);
  } else {
    labels_.clear();
    links_.clear();
    gtk_util::RemoveAllChildren(contents_);
  }

  for (int i = 0; i < model_.GetSectionCount(); i++) {
    gtk_box_pack_start(GTK_BOX(contents_),
                       CreateSection(model_.GetSectionInfo(i)),
                       FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(contents_),
                       gtk_hseparator_new(),
                       FALSE, FALSE, 0);
  }

  GtkWidget* help_link = gtk_chrome_link_button_new(
      l10n_util::GetStringUTF8(IDS_PAGE_INFO_HELP_CENTER_LINK).c_str());
  links_.push_back(help_link);
  GtkWidget* help_link_hbox = gtk_hbox_new(FALSE, 0);
  // Stick it in an hbox so it doesn't expand to the whole width.
  gtk_box_pack_start(GTK_BOX(help_link_hbox), help_link, FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(contents_), help_link_hbox, FALSE, FALSE, 0);
  g_signal_connect(help_link, "clicked",
                   G_CALLBACK(OnHelpLinkClickedThunk), this);

  theme_service_->InitThemesFor(this);
  gtk_widget_show_all(contents_);
}

GtkWidget* PageInfoBubbleGtk::CreateSection(
    const PageInfoModel::SectionInfo& section) {
  GtkWidget* section_box = gtk_hbox_new(FALSE, gtk_util::kControlSpacing);

  GdkPixbuf* pixbuf = *model_.GetIconImage(section.icon_id);
  if (pixbuf) {
    GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
    gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE, 0);
    gtk_misc_set_alignment(GTK_MISC(image), 0, 0);
  }

  GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(section_box), vbox, TRUE, TRUE, 0);

  if (!section.headline.empty()) {
    GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.headline).c_str());
    gtk_label_set_selectable(GTK_LABEL(label), TRUE);
    labels_.push_back(label);
    PangoAttrList* attributes = pango_attr_list_new();
    pango_attr_list_insert(attributes,
                           pango_attr_weight_new(PANGO_WEIGHT_BOLD));
    gtk_label_set_attributes(GTK_LABEL(label), attributes);
    pango_attr_list_unref(attributes);
    gtk_util::SetLabelWidth(label, 400);
    // Allow linebreaking in the middle of words if necessary, so that extremely
    // long hostnames (longer than one line) will still be completely shown.
    gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
    gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
  }
  GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.description).c_str());
  gtk_label_set_selectable(GTK_LABEL(label), TRUE);
  labels_.push_back(label);
  gtk_util::SetLabelWidth(label, 400);
  // Allow linebreaking in the middle of words if necessary, so that extremely
  // long hostnames (longer than one line) will still be completely shown.
  gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR);
  gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);

  if (section.type == PageInfoModel::SECTION_INFO_IDENTITY && cert_id_ > 0) {
    GtkWidget* view_cert_link = gtk_chrome_link_button_new(
        l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str());
    links_.push_back(view_cert_link);
    GtkWidget* cert_link_hbox = gtk_hbox_new(FALSE, 0);
    // Stick it in an hbox so it doesn't expand to the whole width.
    gtk_box_pack_start(GTK_BOX(cert_link_hbox), view_cert_link,
                       FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(vbox), cert_link_hbox, FALSE, FALSE, 0);
    g_signal_connect(view_cert_link, "clicked",
                     G_CALLBACK(OnViewCertLinkClickedThunk), this);
  }

  return section_box;
}

void PageInfoBubbleGtk::OnViewCertLinkClicked(GtkWidget* widget) {
  ShowCertificateViewerByID(GTK_WINDOW(parent_), cert_id_);
  bubble_->Close();
}

void PageInfoBubbleGtk::OnHelpLinkClicked(GtkWidget* widget) {
  GURL url = google_util::AppendGoogleLocaleParam(
      GURL(chrome::kPageInfoHelpCenterURL));
  Browser* browser = BrowserList::GetLastActive();
  browser->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
  bubble_->Close();
}

}  // namespace

namespace browser {

void ShowPageInfoBubble(gfx::NativeWindow parent,
                        Profile* profile,
                        const GURL& url,
                        const NavigationEntry::SSLStatus& ssl,
                        bool show_history) {
  new PageInfoBubbleGtk(parent, profile, url, ssl, show_history);
}

}  // namespace browser
<|endoftext|>