<commit_before>/******************************************************************************\
* File:          process.cpp
* Purpose:       Implementation of class 'wxExProcessWithListView'
* 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/tokenzr.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/extension/app.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/extension.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/frame.h>
#include <wx/extension/report/listitem.h>
#include <wx/extension/report/process.h>

BEGIN_EVENT_TABLE(wxExProcessWithListView, wxProcess)
  EVT_TIMER(-1, wxExProcessWithListView::OnTimer)
END_EVENT_TABLE()

wxString wxExProcessWithListView::m_Command = "";

wxExProcessWithListView::wxExProcessWithListView(
  wxExFrameWithHistory* frame,
  wxExListView* listview,
  const wxString& command)
  : wxProcess(NULL, -1)
  , m_Frame(frame)
  , m_Owner(listview)
  , m_Timer(this)
{
  if (!command.empty())
  {
    m_Command = command;
  }

  Redirect();
}

bool wxExProcessWithListView::CheckInput()
{
  bool hasInput = false;

  // This assumes that the output is always line buffered.
  wxString line;

  if (IsInputAvailable())
  {
    wxTextInputStream tis(*GetInputStream());
    line << tis.ReadLine();
    hasInput = true;
  }
  else if (IsErrorAvailable())
  {
    wxTextInputStream tis(*GetErrorStream());
    line << tis.ReadLine();
    hasInput = true;
  }

  if (hasInput && !line.empty())
  {
    wxString lineno;
    wxString path;

    // Check on error in php script output.
    wxRegEx regex(".*in \\(.*\\) on line \\(.*\\)");

    if (regex.Matches(line))
    {
      size_t start, len;

      if (regex.GetMatch(&start, &len, 1))
      {
        path = line.substr(start, len);
      }

      if (regex.GetMatch(&start, &len, 2))
      {
        lineno = line.substr(start, len);
      }
    }
    else
    {
      // Check on error in gcc output (and some others).
      wxStringTokenizer tkz(line, ':');
      path = tkz.GetNextToken();

      if (tkz.HasMoreTokens())
      {
        const wxString number = tkz.GetNextToken();
        long val;
        if (number.ToLong(&val)) lineno = number;
      }
    }

    wxFileName fn(path);
    fn.Normalize();

    if (fn.FileExists())
    {
      wxExListItemWithFileName item(m_Owner, fn.GetFullPath());
      item.Insert();
      item.SetColumnText(_("Line"), line);
      item.SetColumnText(_("Line No"), lineno);
    }
    else
    {
      // wxExListItem gives incorrect image
      wxExListItemWithFileName item(m_Owner, wxEmptyString);
      item.Insert();
      item.SetColumnText(_("Line"), line);
    }

    // If nothing selected, then ensure last line is visible.
    // Otherwise you are busy inspecting some line, and
    // it would be irritating to get it out of view.
    if (m_Owner->GetSelectedItemCount() == 0)
    {
      m_Owner->EnsureVisible(m_Owner->GetItemCount() - 1);
    }

#if wxUSE_STATUSBAR
    m_Owner->UpdateStatusBar();
#endif
  }

  return hasInput;
}

int wxExProcessWithListView::ConfigDialog(
  wxWindow* parent,
  const wxString& title)
{
  std::vector<wxExConfigItem> v;
  v.push_back(wxExConfigItem(_("Process"), CONFIG_COMBOBOX, wxEmptyString, true));
  v.push_back(wxExConfigItem(_("Process folder"), CONFIG_COMBOBOXDIR, wxEmptyString));

  const int result = wxExConfigDialog(parent,
    v,
    title).ShowModal();

  if (result == wxID_OK)
  {
    m_Command = wxConfigBase::Get()->Read(_("Process"));
  }

  return result;
}

long wxExProcessWithListView::Execute()
{
  if (m_Command.empty())
  {
    wxFAIL;
  }

  wxString cwd;
  const wxString dir = wxConfigBase::Get()->Read(_("Process folder"));

  if (!dir.empty())
  {
    cwd = wxGetCwd();
    wxSetWorkingDirectory(dir);
  }

  long pid = 0;

  if ((pid = wxExecute(m_Command, wxEXEC_ASYNC, this)) > 0)
  {
    SetPid(pid);

#if wxUSE_STATUSBAR
    wxExFrame::StatusText(m_Command);
#endif
    wxExApp::Log(_("Running process") + ": " + m_Command);

    m_Timer.Start(100); // each 100 milliseconds
  }
  else
  {
    wxLogError(_("Cannot run process") + ": " + m_Command);
  }

  if (!cwd.empty())
  {
    wxSetWorkingDirectory(cwd);
  }

  return pid;
}

void wxExProcessWithListView::InitCommandFromConfig()
{
  // The process is a combobox, we want only the first from the list,
  // so use the default separator, causing only first field to be returned.
  m_Command = wxConfigBase::Get()->Read(_("Process"));
}

wxKillError wxExProcessWithListView::Kill(wxSignal sig)
{
  if (!Exists(GetPid()))
  {
    return wxKILL_NO_PROCESS;
  }

  m_Timer.Stop();

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(_("Stopped"));
#endif

  DeletePendingEvents();

  // Next statement causes wxGTK to crash, so outcommented.
#ifndef __WXGTK__
  delete this;
#endif

  return wxProcess::Kill(GetPid(), sig);
}

void wxExProcessWithListView::OnTerminate(
  int WXUNUSED(pid),
  int WXUNUSED(status))
{
  m_Timer.Stop();

  // Collect remaining input.
  while (CheckInput())
  {
    // Do nothing.
  }

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(_("Ready"));
#endif

  wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
  wxPostEvent(m_Frame, event);
}

void wxExProcessWithListView::OnTimer(wxTimerEvent& event)
{
  while (CheckInput())
  {
    // Do nothing.
  }
}
<commit_msg>use wxExConfigFirstOf<commit_after>/******************************************************************************\
* File:          process.cpp
* Purpose:       Implementation of class 'wxExProcessWithListView'
* 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/tokenzr.h>
#include <wx/txtstrm.h> // for wxTextInputStream
#include <wx/extension/app.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/extension.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/frame.h>
#include <wx/extension/report/listitem.h>
#include <wx/extension/report/process.h>

BEGIN_EVENT_TABLE(wxExProcessWithListView, wxProcess)
  EVT_TIMER(-1, wxExProcessWithListView::OnTimer)
END_EVENT_TABLE()

wxString wxExProcessWithListView::m_Command = "";

wxExProcessWithListView::wxExProcessWithListView(
  wxExFrameWithHistory* frame,
  wxExListView* listview,
  const wxString& command)
  : wxProcess(NULL, -1)
  , m_Frame(frame)
  , m_Owner(listview)
  , m_Timer(this)
{
  if (!command.empty())
  {
    m_Command = command;
  }

  Redirect();
}

bool wxExProcessWithListView::CheckInput()
{
  bool hasInput = false;

  // This assumes that the output is always line buffered.
  wxString line;

  if (IsInputAvailable())
  {
    wxTextInputStream tis(*GetInputStream());
    line << tis.ReadLine();
    hasInput = true;
  }
  else if (IsErrorAvailable())
  {
    wxTextInputStream tis(*GetErrorStream());
    line << tis.ReadLine();
    hasInput = true;
  }

  if (hasInput && !line.empty())
  {
    wxString lineno;
    wxString path;

    // Check on error in php script output.
    wxRegEx regex(".*in \\(.*\\) on line \\(.*\\)");

    if (regex.Matches(line))
    {
      size_t start, len;

      if (regex.GetMatch(&start, &len, 1))
      {
        path = line.substr(start, len);
      }

      if (regex.GetMatch(&start, &len, 2))
      {
        lineno = line.substr(start, len);
      }
    }
    else
    {
      // Check on error in gcc output (and some others).
      wxStringTokenizer tkz(line, ':');
      path = tkz.GetNextToken();

      if (tkz.HasMoreTokens())
      {
        const wxString number = tkz.GetNextToken();
        long val;
        if (number.ToLong(&val)) lineno = number;
      }
    }

    wxFileName fn(path);
    fn.Normalize();

    if (fn.FileExists())
    {
      wxExListItemWithFileName item(m_Owner, fn.GetFullPath());
      item.Insert();
      item.SetColumnText(_("Line"), line);
      item.SetColumnText(_("Line No"), lineno);
    }
    else
    {
      // wxExListItem gives incorrect image
      wxExListItemWithFileName item(m_Owner, wxEmptyString);
      item.Insert();
      item.SetColumnText(_("Line"), line);
    }

    // If nothing selected, then ensure last line is visible.
    // Otherwise you are busy inspecting some line, and
    // it would be irritating to get it out of view.
    if (m_Owner->GetSelectedItemCount() == 0)
    {
      m_Owner->EnsureVisible(m_Owner->GetItemCount() - 1);
    }

#if wxUSE_STATUSBAR
    m_Owner->UpdateStatusBar();
#endif
  }

  return hasInput;
}

int wxExProcessWithListView::ConfigDialog(
  wxWindow* parent,
  const wxString& title)
{
  std::vector<wxExConfigItem> v;
  v.push_back(wxExConfigItem(_("Process"), CONFIG_COMBOBOX, wxEmptyString, true));
  v.push_back(wxExConfigItem(_("Process folder"), CONFIG_COMBOBOXDIR, wxEmptyString));

  const int result = wxExConfigDialog(parent,
    v,
    title).ShowModal();

  if (result == wxID_OK)
  {
    m_Command = wxExConfigFirstOf(_("Process"));
  }

  return result;
}

long wxExProcessWithListView::Execute()
{
  if (m_Command.empty())
  {
    wxFAIL;
  }

  wxString cwd;
  const wxString dir = wxExConfigFirstOf(_("Process folder"));

  if (!dir.empty())
  {
    cwd = wxGetCwd();
    wxSetWorkingDirectory(dir);
  }

  long pid = 0;

  if ((pid = wxExecute(m_Command, wxEXEC_ASYNC, this)) > 0)
  {
    SetPid(pid);

#if wxUSE_STATUSBAR
    wxExFrame::StatusText(m_Command);
#endif
    wxExApp::Log(_("Running process") + ": " + m_Command);

    m_Timer.Start(100); // each 100 milliseconds
  }
  else
  {
    wxLogError(_("Cannot run process") + ": " + m_Command);
  }

  if (!cwd.empty())
  {
    wxSetWorkingDirectory(cwd);
  }

  return pid;
}

void wxExProcessWithListView::InitCommandFromConfig()
{
  // The process is a combobox, we want only the first from the list,
  // so use the default separator, causing only first field to be returned.
  m_Command = wxExConfigFirstOf(_("Process"));
}

wxKillError wxExProcessWithListView::Kill(wxSignal sig)
{
  if (!Exists(GetPid()))
  {
    return wxKILL_NO_PROCESS;
  }

  m_Timer.Stop();

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(_("Stopped"));
#endif

  DeletePendingEvents();

  // Next statement causes wxGTK to crash, so outcommented.
#ifndef __WXGTK__
  delete this;
#endif

  return wxProcess::Kill(GetPid(), sig);
}

void wxExProcessWithListView::OnTerminate(
  int WXUNUSED(pid),
  int WXUNUSED(status))
{
  m_Timer.Stop();

  // Collect remaining input.
  while (CheckInput())
  {
    // Do nothing.
  }

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(_("Ready"));
#endif

  wxCommandEvent event(wxEVT_COMMAND_MENU_SELECTED, ID_TERMINATED_PROCESS);
  wxPostEvent(m_Frame, event);
}

void wxExProcessWithListView::OnTimer(wxTimerEvent& event)
{
  while (CheckInput())
  {
    // Do nothing.
  }
}
<|endoftext|>


<commit_before>#include <QTimer>
#include <QApplication>
#include <QGridLayout>

#include <osgViewer/CompositeViewer>
#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>

#include <osgDB/ReadFile>

#include <osgQt/GraphicsWindowQt>

#include <iostream>

class ViewerWidget : public QWidget, public osgViewer::CompositeViewer
{
public:
    ViewerWidget(osgViewer::ViewerBase::ThreadingModel threadingModel=osgViewer::CompositeViewer::SingleThreaded) : QWidget()
    {
        setThreadingModel(threadingModel);

        // disable the default setting of viewer.done() by pressing Escape.
        setKeyEventSetsDone(0);

        QWidget* widget1 = addViewWidget( createCamera(0,0,100,100), osgDB::readNodeFile("cow.osgt") );
        QWidget* widget2 = addViewWidget( createCamera(0,0,100,100), osgDB::readNodeFile("glider.osgt") );
        QWidget* widget3 = addViewWidget( createCamera(0,0,100,100), osgDB::readNodeFile("axes.osgt") );
        QWidget* widget4 = addViewWidget( createCamera(0,0,100,100), osgDB::readNodeFile("fountain.osgt") );
        QWidget* popupWidget = addViewWidget( createCamera(900,100,320,240,"Popup window",true),
                                            osgDB::readNodeFile("dumptruck.osgt") );
        popupWidget->show();

        QGridLayout* grid = new QGridLayout;
        grid->addWidget( widget1, 0, 0 );
        grid->addWidget( widget2, 0, 1 );
        grid->addWidget( widget3, 1, 0 );
        grid->addWidget( widget4, 1, 1 );
        setLayout( grid );

        connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
        _timer.start( 10 );
    }

    QWidget* addViewWidget( osg::Camera* camera, osg::Node* scene )
    {
        osgViewer::View* view = new osgViewer::View;
        view->setCamera( camera );
        addView( view );

        view->setSceneData( scene );
        view->addEventHandler( new osgViewer::StatsHandler );
        view->setCameraManipulator( new osgGA::TrackballManipulator );

        osgQt::GraphicsWindowQt* gw = dynamic_cast<osgQt::GraphicsWindowQt*>( camera->getGraphicsContext() );
        return gw ? gw->getGLWidget() : NULL;
    }

    osg::Camera* createCamera( int x, int y, int w, int h, const std::string& name="", bool windowDecoration=false )
    {
        osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->windowName = name;
        traits->windowDecoration = windowDecoration;
        traits->x = x;
        traits->y = y;
        traits->width = w;
        traits->height = h;
        traits->doubleBuffer = true;
        traits->alpha = ds->getMinimumNumAlphaBits();
        traits->stencil = ds->getMinimumNumStencilBits();
        traits->sampleBuffers = ds->getMultiSamples();
        traits->samples = ds->getNumMultiSamples();

        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
        camera->setGraphicsContext( new osgQt::GraphicsWindowQt(traits.get()) );

        camera->setClearColor( osg::Vec4(0.2, 0.2, 0.6, 1.0) );
        camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
        camera->setProjectionMatrixAsPerspective(
            30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );
        return camera.release();
    }

    virtual void paintEvent( QPaintEvent* event )
    { frame(); }

protected:

    QTimer _timer;
};

int main( int argc, char** argv )
{
    osg::ArgumentParser arguments(&argc, argv);

    osgViewer::ViewerBase::ThreadingModel threadingModel = osgViewer::ViewerBase::CullDrawThreadPerContext;
    while (arguments.read("--SingleThreaded")) threadingModel = osgViewer::ViewerBase::SingleThreaded;
    while (arguments.read("--CullDrawThreadPerContext")) threadingModel = osgViewer::ViewerBase::CullDrawThreadPerContext;
    while (arguments.read("--DrawThreadPerContext")) threadingModel = osgViewer::ViewerBase::DrawThreadPerContext;
    while (arguments.read("--CullThreadPerCameraDrawThreadPerContext")) threadingModel = osgViewer::ViewerBase::CullThreadPerCameraDrawThreadPerContext;

    QApplication app(argc, argv);
    ViewerWidget* viewWidget = new ViewerWidget(threadingModel);
    viewWidget->setGeometry( 100, 100, 800, 600 );
    viewWidget->show();
    return app.exec();
}
<commit_msg>Fixed problem with the osgviewerQt code override the default View::Camera without setting it's default state on it's StateSet like View does by default.<commit_after>#include <QTimer>
#include <QApplication>
#include <QGridLayout>

#include <osgViewer/CompositeViewer>
#include <osgViewer/ViewerEventHandlers>

#include <osgGA/TrackballManipulator>

#include <osgDB/ReadFile>

#include <osgQt/GraphicsWindowQt>

#include <iostream>

class ViewerWidget : public QWidget, public osgViewer::CompositeViewer
{
public:
    ViewerWidget(osgViewer::ViewerBase::ThreadingModel threadingModel=osgViewer::CompositeViewer::SingleThreaded) : QWidget()
    {
        setThreadingModel(threadingModel);

        // disable the default setting of viewer.done() by pressing Escape.
        setKeyEventSetsDone(0);

        QWidget* widget1 = addViewWidget( createGraphicsWindow(0,0,100,100), osgDB::readNodeFile("cow.osgt") );
        QWidget* widget2 = addViewWidget( createGraphicsWindow(0,0,100,100), osgDB::readNodeFile("glider.osgt") );
        QWidget* widget3 = addViewWidget( createGraphicsWindow(0,0,100,100), osgDB::readNodeFile("axes.osgt") );
        QWidget* widget4 = addViewWidget( createGraphicsWindow(0,0,100,100), osgDB::readNodeFile("fountain.osgt") );
        QWidget* popupWidget = addViewWidget( createGraphicsWindow(900,100,320,240,"Popup window",true), osgDB::readNodeFile("dumptruck.osgt") );
        popupWidget->show();

        QGridLayout* grid = new QGridLayout;
        grid->addWidget( widget1, 0, 0 );
        grid->addWidget( widget2, 0, 1 );
        grid->addWidget( widget3, 1, 0 );
        grid->addWidget( widget4, 1, 1 );
        setLayout( grid );

        connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
        _timer.start( 10 );
    }

    QWidget* addViewWidget( osgQt::GraphicsWindowQt* gw, osg::Node* scene )
    {
        osgViewer::View* view = new osgViewer::View;
        addView( view );

        osg::Camera* camera = view->getCamera();
        camera->setGraphicsContext( gw );

        const osg::GraphicsContext::Traits* traits = gw->getTraits();

        camera->setClearColor( osg::Vec4(0.2, 0.2, 0.6, 1.0) );
        camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
        camera->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );

        view->setSceneData( scene );
        view->addEventHandler( new osgViewer::StatsHandler );
        view->setCameraManipulator( new osgGA::TrackballManipulator );

        return gw->getGLWidget();
    }

    osgQt::GraphicsWindowQt* createGraphicsWindow( int x, int y, int w, int h, const std::string& name="", bool windowDecoration=false )
    {
        osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->windowName = name;
        traits->windowDecoration = windowDecoration;
        traits->x = x;
        traits->y = y;
        traits->width = w;
        traits->height = h;
        traits->doubleBuffer = true;
        traits->alpha = ds->getMinimumNumAlphaBits();
        traits->stencil = ds->getMinimumNumStencilBits();
        traits->sampleBuffers = ds->getMultiSamples();
        traits->samples = ds->getNumMultiSamples();

        return new osgQt::GraphicsWindowQt(traits.get());
#if 0
        osg::ref_ptr<osg::Camera> camera = new osg::Camera;
        camera->setGraphicsContext( ) );

        camera->setClearColor( osg::Vec4(0.2, 0.2, 0.6, 1.0) );
        camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
        camera->setProjectionMatrixAsPerspective(
            30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );
        return camera.release();
#endif
    }

    virtual void paintEvent( QPaintEvent* event )
    { frame(); }

protected:

    QTimer _timer;
};

int main( int argc, char** argv )
{
    osg::ArgumentParser arguments(&argc, argv);

    osgViewer::ViewerBase::ThreadingModel threadingModel = osgViewer::ViewerBase::CullDrawThreadPerContext;
    while (arguments.read("--SingleThreaded")) threadingModel = osgViewer::ViewerBase::SingleThreaded;
    while (arguments.read("--CullDrawThreadPerContext")) threadingModel = osgViewer::ViewerBase::CullDrawThreadPerContext;
    while (arguments.read("--DrawThreadPerContext")) threadingModel = osgViewer::ViewerBase::DrawThreadPerContext;
    while (arguments.read("--CullThreadPerCameraDrawThreadPerContext")) threadingModel = osgViewer::ViewerBase::CullThreadPerCameraDrawThreadPerContext;

    QApplication app(argc, argv);
    ViewerWidget* viewWidget = new ViewerWidget(threadingModel);
    viewWidget->setGeometry( 100, 100, 800, 600 );
    viewWidget->show();
    return app.exec();
}
<|endoftext|>


<commit_before>#include "mainwindow.h"

#if QT_VERSION >= 0x050000
#include <QGuiApplication>
#endif

#include <QtCore>
#include <QVBoxLayout>

#if defined(Q_WS_X11)
#include <QX11Info>
#endif

#include <maliit/namespace.h>
#include <maliit/inputmethod.h>

#include <cstdlib>

namespace {

const char * const TextPrompt = "Double-click this text area to invoke virtual keyboard ...";
const QString serverName("maliit-server"); //TODO: when maliit and example application is split out, look up in .pc file

bool enableFullScreenMode()
{
    return (qApp->arguments().contains("-fullscreen"));
}

} // namespace

class MyTextEdit
    : public QTextEdit
{
private:
    bool was_focused;

public:
    MyTextEdit()
        : QTextEdit(TextPrompt)
        , was_focused(false)
    {}

protected:
    void focusInEvent(QFocusEvent *e)
    {
        toPlainText();
        // On first text edit, clear pre-set TextPrompt:
        if (not was_focused && toPlainText() == QString(TextPrompt)) {
            was_focused = true;
            setText("");
        }

        QTextEdit::focusInEvent(e);
    }
};

MainWindow::MainWindow()
    : QMainWindow()
    , m_server_process(new QProcess(this))
    , m_orientation_index(0)
    , m_grid_row(0)
    , m_grid(new QGridLayout)
    , m_start_server(new QPushButton)
    , m_rotate_keyboard(new QPushButton("Rotate input method"))
{
    m_server_process->setProcessChannelMode(QProcess::ForwardedChannels);

    connect(m_server_process, SIGNAL(stateChanged(QProcess::ProcessState)),
            this, SLOT(onServerStateChanged()));

    connect(m_start_server, SIGNAL(clicked()),
            this, SLOT(onStartServerClicked()));
    connect(m_rotate_keyboard, SIGNAL(clicked()),
            this, SLOT(onRotateKeyboardClicked()));

    initUI();
    onServerStateChanged();
}

void MainWindow::initUI()
{
    setWindowTitle("Maliit test application");
    m_grid_row = 0;

    QHBoxLayout *buttons = new QHBoxLayout;
    buttons->addWidget(m_start_server);
    buttons->addWidget(m_rotate_keyboard);
    // Clicking the button will steal focus from the text edit, thus hiding
    // the virtual keyboard:
    buttons->addWidget(new QPushButton("Dismiss input method"));

    m_grid->addLayout(buttons, m_grid_row, 1);
    ++m_grid_row;

    // multi line:
    QLabel *label = 0;
    QTextEdit *entry = 0;

    m_grid->addWidget(label = new QLabel("multi line"), m_grid_row, 0);
    m_grid->addWidget(entry = new QTextEdit, m_grid_row, 1);
    ++m_grid_row;

    label->setToolTip("Qt::ImhNone");
    entry->setInputMethodHints(Qt::ImhNone);
    entry->installEventFilter(this);

    // single line, emulating content types via Qt::InputMethodHints:
    insertIntoGrid("single line", Qt::ImhNone,
                   "Qt::ImhNone");
    insertIntoGrid("password", Qt::ImhHiddenText|Qt::ImhNoPredictiveText,
                   "Qt::ImhHiddenText|Qt::ImhNoPredictiveText");
    insertIntoGrid("numbers only", Qt::ImhFormattedNumbersOnly,
                   "Qt::ImhFormattedNumbersOnly");
    insertIntoGrid("dialer input", Qt::ImhDialableCharactersOnly,
                   "Qt::ImhDialableCharactersOnly");
    insertIntoGrid("symbol view", Qt::ImhPreferNumbers,
                   "Qt::ImhPreferNumbers");
    insertIntoGrid("e-mail", Qt::ImhEmailCharactersOnly,
                   "Qt::ImhEmailCharactersOnly");
    insertIntoGrid("website", Qt::ImhUrlCharactersOnly,
                   "Qt::ImhUrlCharactersOnly");

    // Don't want other buttons to steal focus:
    m_start_server->setFocusPolicy(Qt::NoFocus);
    m_rotate_keyboard->setFocusPolicy(Qt::NoFocus);

    QPushButton *close_app = new QPushButton("Close application");
    m_grid->addWidget(close_app, m_grid_row, 1);
    ++m_grid_row;

    connect(close_app, SIGNAL(clicked()),
            this,     SLOT(close()));

    setCentralWidget(new QWidget);
    centralWidget()->setLayout(m_grid);

    if (enableFullScreenMode()) {
        showFullScreen();
    } else {
        show();
    }
}

void MainWindow::insertIntoGrid(const QString &description,
                                const Qt::InputMethodHints &hints,
                                const QString &tooltip)
{
    QLabel *label = 0;
    QLineEdit *entry = 0;

    m_grid->addWidget(label = new QLabel(description), m_grid_row, 0);
    m_grid->addWidget(entry = new QLineEdit, m_grid_row, 1);
    ++m_grid_row;

    label->setToolTip(tooltip);
    entry->setInputMethodHints(hints);
    entry->installEventFilter(this);
}

MainWindow::~MainWindow()
{
    m_server_process->terminate();
}

bool MainWindow::eventFilter(QObject *watched,
                             QEvent *event)
{
    Q_UNUSED(watched)

    // Let the input method show up on focus-in, not on second click:
    if (event->type() == QFocusEvent::FocusIn) {
#if QT_VERSION >= 0x050000
        qApp->inputMethod()->show();
#else
        if (QInputContext *ic = qApp->inputContext()) {
            QEvent im_request(QEvent::RequestSoftwareInputPanel);
            ic->filterEvent(&im_request);
        }
#endif
    }

    return false;
}

void MainWindow::onStartServerClicked()
{

    QStringList arguments;
    arguments << "-bypass-wm-hint";

    // Self-compositing is currently only supported in fullscreen mode:
    if (enableFullScreenMode()) {
        arguments << "-use-self-composition";
    }

    if (m_server_process->state() != QProcess::NotRunning) {
        m_server_process->terminate();
    } else {
        m_server_process->start(serverName, arguments);
    }
}

void MainWindow::onServerStateChanged()
{
    switch (m_server_process->state()) {
    case QProcess::Running:
        m_start_server->setText("(running) Stop input method server");
        break;

    case QProcess::Starting:
        m_start_server->setText("(starting) Stop input method server");
        break;

    case QProcess::NotRunning:
        m_start_server->setText("(stopped) Start input method server");
        break;

    default:
        break;
    }
}

void MainWindow::onRotateKeyboardClicked()
{
    const Maliit::OrientationAngle orientations[] = {Maliit::Angle0,
                                                     Maliit::Angle90,
                                                     Maliit::Angle180,
                                                     Maliit::Angle270};
    m_orientation_index++;
    if (m_orientation_index >= 4) {
        m_orientation_index = 0;
    }
    const Maliit::OrientationAngle angle = orientations[m_orientation_index];
    Maliit::InputMethod::instance()->setOrientationAngle(angle);
}
<commit_msg>Let example application change content orientation the Qt5 way<commit_after>#include "mainwindow.h"

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QGuiApplication>
#include <QScreen>
#include <QWindow>
#endif

#include <QtCore>
#include <QVBoxLayout>

#if defined(Q_WS_X11)
#include <QX11Info>
#endif

#include <maliit/namespace.h>
#include <maliit/inputmethod.h>

#include <cstdlib>

namespace {

const char * const TextPrompt = "Double-click this text area to invoke virtual keyboard ...";
const QString serverName("maliit-server"); //TODO: when maliit and example application is split out, look up in .pc file

bool enableFullScreenMode()
{
    return (qApp->arguments().contains("-fullscreen"));
}

} // namespace

class MyTextEdit
    : public QTextEdit
{
private:
    bool was_focused;

public:
    MyTextEdit()
        : QTextEdit(TextPrompt)
        , was_focused(false)
    {}

protected:
    void focusInEvent(QFocusEvent *e)
    {
        toPlainText();
        // On first text edit, clear pre-set TextPrompt:
        if (not was_focused && toPlainText() == QString(TextPrompt)) {
            was_focused = true;
            setText("");
        }

        QTextEdit::focusInEvent(e);
    }
};

MainWindow::MainWindow()
    : QMainWindow()
    , m_server_process(new QProcess(this))
    , m_orientation_index(0)
    , m_grid_row(0)
    , m_grid(new QGridLayout)
    , m_start_server(new QPushButton)
    , m_rotate_keyboard(new QPushButton("Rotate input method"))
{
    m_server_process->setProcessChannelMode(QProcess::ForwardedChannels);

    connect(m_server_process, SIGNAL(stateChanged(QProcess::ProcessState)),
            this, SLOT(onServerStateChanged()));

    connect(m_start_server, SIGNAL(clicked()),
            this, SLOT(onStartServerClicked()));
    connect(m_rotate_keyboard, SIGNAL(clicked()),
            this, SLOT(onRotateKeyboardClicked()));

    initUI();
    onServerStateChanged();

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
    // Work around a bug in maliit input method support where primary orientation is always portrait
    windowHandle()->reportContentOrientationChange(windowHandle()->screen()->primaryOrientation());
#endif
}

void MainWindow::initUI()
{
    setWindowTitle("Maliit test application");
    m_grid_row = 0;

    QHBoxLayout *buttons = new QHBoxLayout;
    buttons->addWidget(m_start_server);
    buttons->addWidget(m_rotate_keyboard);
    // Clicking the button will steal focus from the text edit, thus hiding
    // the virtual keyboard:
    buttons->addWidget(new QPushButton("Dismiss input method"));

    m_grid->addLayout(buttons, m_grid_row, 1);
    ++m_grid_row;

    // multi line:
    QLabel *label = 0;
    QTextEdit *entry = 0;

    m_grid->addWidget(label = new QLabel("multi line"), m_grid_row, 0);
    m_grid->addWidget(entry = new QTextEdit, m_grid_row, 1);
    ++m_grid_row;

    label->setToolTip("Qt::ImhNone");
    entry->setInputMethodHints(Qt::ImhNone);
    entry->installEventFilter(this);

    // single line, emulating content types via Qt::InputMethodHints:
    insertIntoGrid("single line", Qt::ImhNone,
                   "Qt::ImhNone");
    insertIntoGrid("password", Qt::ImhHiddenText|Qt::ImhNoPredictiveText,
                   "Qt::ImhHiddenText|Qt::ImhNoPredictiveText");
    insertIntoGrid("numbers only", Qt::ImhFormattedNumbersOnly,
                   "Qt::ImhFormattedNumbersOnly");
    insertIntoGrid("dialer input", Qt::ImhDialableCharactersOnly,
                   "Qt::ImhDialableCharactersOnly");
    insertIntoGrid("symbol view", Qt::ImhPreferNumbers,
                   "Qt::ImhPreferNumbers");
    insertIntoGrid("e-mail", Qt::ImhEmailCharactersOnly,
                   "Qt::ImhEmailCharactersOnly");
    insertIntoGrid("website", Qt::ImhUrlCharactersOnly,
                   "Qt::ImhUrlCharactersOnly");

    // Don't want other buttons to steal focus:
    m_start_server->setFocusPolicy(Qt::NoFocus);
    m_rotate_keyboard->setFocusPolicy(Qt::NoFocus);

    QPushButton *close_app = new QPushButton("Close application");
    m_grid->addWidget(close_app, m_grid_row, 1);
    ++m_grid_row;

    connect(close_app, SIGNAL(clicked()),
            this,     SLOT(close()));

    setCentralWidget(new QWidget);
    centralWidget()->setLayout(m_grid);

    if (enableFullScreenMode()) {
        showFullScreen();
    } else {
        show();
    }
}

void MainWindow::insertIntoGrid(const QString &description,
                                const Qt::InputMethodHints &hints,
                                const QString &tooltip)
{
    QLabel *label = 0;
    QLineEdit *entry = 0;

    m_grid->addWidget(label = new QLabel(description), m_grid_row, 0);
    m_grid->addWidget(entry = new QLineEdit, m_grid_row, 1);
    ++m_grid_row;

    label->setToolTip(tooltip);
    entry->setInputMethodHints(hints);
    entry->installEventFilter(this);
}

MainWindow::~MainWindow()
{
    m_server_process->terminate();
}

bool MainWindow::eventFilter(QObject *watched,
                             QEvent *event)
{
    Q_UNUSED(watched)

    // Let the input method show up on focus-in, not on second click:
    if (event->type() == QFocusEvent::FocusIn) {
#if QT_VERSION >= 0x050000
        qApp->inputMethod()->show();
#else
        if (QInputContext *ic = qApp->inputContext()) {
            QEvent im_request(QEvent::RequestSoftwareInputPanel);
            ic->filterEvent(&im_request);
        }
#endif
    }

    return false;
}

void MainWindow::onStartServerClicked()
{

    QStringList arguments;
    arguments << "-bypass-wm-hint";

    // Self-compositing is currently only supported in fullscreen mode:
    if (enableFullScreenMode()) {
        arguments << "-use-self-composition";
    }

    if (m_server_process->state() != QProcess::NotRunning) {
        m_server_process->terminate();
    } else {
        m_server_process->start(serverName, arguments);
    }
}

void MainWindow::onServerStateChanged()
{
    switch (m_server_process->state()) {
    case QProcess::Running:
        m_start_server->setText("(running) Stop input method server");
        break;

    case QProcess::Starting:
        m_start_server->setText("(starting) Stop input method server");
        break;

    case QProcess::NotRunning:
        m_start_server->setText("(stopped) Start input method server");
        break;

    default:
        break;
    }
}

void MainWindow::onRotateKeyboardClicked()
{
    ++m_orientation_index;

#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
    static const Qt::ScreenOrientation orientations[] = {
        Qt::LandscapeOrientation,
        Qt::PortraitOrientation,
        Qt::InvertedLandscapeOrientation,
        Qt::InvertedPortraitOrientation
    };

    windowHandle()->reportContentOrientationChange(orientations[m_orientation_index % 4]);
#else
    static const const Maliit::OrientationAngle orientations[] = {
        Maliit::Angle0,
        Maliit::Angle90,
        Maliit::Angle180,
        Maliit::Angle270
    };

    Maliit::InputMethod::instance()->setOrientationAngle(orientations[m_orientation_index % 4]);
#endif
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <std_msgs/Float32.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Vector3Stamped.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

static const std::string OPENCV_WINDOW = "Raw Image";
//static const std::string OPENCV_WINDOW2 = "Binary Image";
static const std::string OPENCV_WINDOW3 = "Processed Image";

using namespace cv;

class ImageProcessing
{

protected:
	ros::NodeHandle nh_;
	ros::Publisher coord_pub_;
//	ros::Publisher speed_;
	image_transport::ImageTransport it_;
	image_transport::Subscriber image_sub_;
	image_transport::Publisher image_pub_;
	Mat img_in_;
	Mat img_hsv_;
	Mat img_hue_;
	Mat img_sat_;
	Mat img_bin_;
	Mat img_out_;

public:
	ImageProcessing()
	  : it_(nh_)
	{
		//Subscribe to input video feed and publish output video feed
		image_sub_ = it_.subscribe("/PS3Eye/image_raw", 1, &ImageProcessing::imageCb, this);
		image_pub_ = it_.advertise("/image_processing/output_video", 1);

		namedWindow(OPENCV_WINDOW);
//		namedWindow(OPENCV_WINDOW2);
		namedWindow(OPENCV_WINDOW3);
	}

	~ImageProcessing()
	{
		destroyWindow(OPENCV_WINDOW);
//		destroyWindow(OPENCV_WINDOW2);
		destroyWindow(OPENCV_WINDOW3);
	}

	void velCb(geometry_msgs::Vector3Stamped v)
	{
		vel = v.x;
		geometry_msgs::Twist velocity;
		velocity.angular.x = vel;
	}

	void imageCb(const sensor_msgs::ImageConstPtr& msg)
	{
		//Convert ROS Input Image Message to IplImage
		cv_bridge::CvImagePtr cv_input_;
		try
		{
		  cv_input_ = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
		}
		catch (cv_bridge::Exception& e)
		{
		  ROS_ERROR("cv_bridge exception: %s", e.what());
		  return;
		}

		//Convert IplImage to cv::Mat
		//img_in_ = cv::Mat(cv_input_).clone();
		img_in_ = cv_input_->image;

		//Output image = Input Image (Segmentation)
		img_out_ = img_in_.clone();

		//Convert Input Image to HSV
		cv::cvtColor (img_in_, img_hsv_, CV_BGR2HSV);

		//Zero Matrices
		img_hue_ = Mat::zeros(img_hsv_.rows, img_hsv_.cols, CV_8U);
    		img_sat_ = Mat::zeros(img_hsv_.rows, img_hsv_.cols, CV_8U);
    		img_bin_ = Mat::zeros(img_hsv_.rows, img_hsv_.cols, CV_8U);

		//HSV Channel 0 -> img_hue_ & HSV Channel 1 -> img_sat_
		int from_to[] = { 0,0, 1,1};
   		Mat img_split[] = { img_hue_, img_sat_};
    		mixChannels(&img_hsv_, 3,img_split,2,from_to,2);

		for(int ii = 0; ii < img_out_.rows; ii++)
		{
			for(int jj = 0; jj < img_out_.cols; jj++)
			{
				//The output pixel is white if input pixel hue is darker and saturation is reasonable
				if(img_hue_.at<uchar>(ii,jj) > 0 && img_hue_.at<uchar>(ii,jj) < 10 && img_sat_.at<uchar>(ii,jj) > 160)
				{
					img_bin_.at<uchar>(ii,jj) = 255;
				}
				else
				{
					img_bin_.at<uchar>(ii,jj) = 0;
/*					//Clear pixel BGR output channel
					img_out_.at<uchar>(ii,jj*3+0) = 0;
					img_out_.at<uchar>(ii,jj*3+1) = 0;
					img_out_.at<uchar>(ii,jj*3+2) = 0;*/
				}
			}
		}

		//strel_size is the size of the structuring element
		Size strel_size;
		strel_size.width = 3;
		strel_size.height = 3;

		//Create an elliptical structuring element
		Mat strel = getStructuringElement(MORPH_ELLIPSE,strel_size);

		//Apply an opening morphological operation using the structuring element to the image three times
		morphologyEx(img_bin_,img_bin_,MORPH_OPEN,strel,Point(-1,-1),3);

		//Invert the Image
		bitwise_not(img_bin_,img_bin_);

		//Blur the Image to Improve Detection
		GaussianBlur(img_bin_, img_bin_, Size(11,11),2,2);

		//Vector Circles will hold the position and radius of the detected circles
		vector<Vec3f> circles;

		//Detect Circles
		HoughCircles(img_bin_, circles, CV_HOUGH_GRADIENT, 1, 80, 140, 15, 5, 100);

		for( size_t i = 0; i < circles.size(); i++ )
    		{
         		// round the floats to an int
         		Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
         		int radius = cvRound(circles[i][2]);
         		// draw the circle center
         		circle( img_out_, center, 3, Scalar(0,255,0), -1, 8, 0 );
        	 	// draw the circle outline
         		circle( img_out_, center, radius+1, Scalar(0,0,255), 3, 8, 0 );
         		// Debugging Output
//         		ROS_INFO("x: %d y: %d r: %d",center.x,center.y, radius);
			// Publish the data
	 	/*	coord_pub_ = it_.advertise<std_msgs::String>("Coordinate", 100);
		coord_pub_ = nh_.advertise<std_msgs::Float32>("coordinate", 100);
		std_msgs::Float32 msg;
		msg.data = center.x;
		msg.data = center.y;

		coord_pub_.publish(msg);
		*/
		coord_pub_ = nh_.advertise<geometry_msgs::Twist>("coordinate", 100);
		geometry_msgs::Twist msg;
		msg.linear.x = center.x;
		msg.linear.y = center.y;
//		msg.angular.x = vel;
		coord_pub_.publish(msg);
    }

		//Update GUI Window
		imshow(OPENCV_WINDOW, img_in_);
//		imshow(OPENCV_WINDOW2, img_bin_);
		imshow(OPENCV_WINDOW3, img_out_);

		waitKey(3);

		//Convert cv::Mat to IplImage
//		cv_bridge::CvImage img_out_;
//		img_out_.encoding = sensor_msgs::image_encodings::BGR8;
//		img_out_.image = img_hsv_;

		//Publish Output Image
//		image_pub_.publish(img_out_.toImageMsg());

	}
};

int main(int argc, char** argv)
{
	//Initialize ROS Node
	ros::init(argc, argv, "image_processing");

//	ros::Subscriber rpm_ = nh_.subscribe("/rpm", 100, velCb);
	//Start Node
	ImageProcessing ip;

	//Keep the ROS Running
	ros::spin();

return 0;
}
<commit_msg>Create image_processing.cpp<commit_after>#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <std_msgs/Float32.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Vector3Stamped.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

static const std::string OPENCV_WINDOW = "Raw Image";
static const std::string OPENCV_WINDOW2 = "Binary Image";
static const std::string OPENCV_WINDOW3 = "Processed Image";

using namespace cv;

class ImageProcessing
{

protected:
	ros::NodeHandle nh_;
	ros::Publisher coord_pub_;
//	ros::Publisher speed_;
	image_transport::ImageTransport it_;
	image_transport::Subscriber image_sub_;
	image_transport::Publisher image_pub_;
	Mat img_in_;
	Mat img_hsv_;
	Mat img_hue_;
	Mat img_sat_;
	Mat img_bin_;
	Mat img_out_;

public:
	ImageProcessing()
	  : it_(nh_)
	{
		//Subscribe to input video feed and publish output video feed
		image_sub_ = it_.subscribe("/PS3Eye/image_raw", 1, &ImageProcessing::imageCb, this);
		image_pub_ = it_.advertise("/image_processing/output_video", 1);

		namedWindow(OPENCV_WINDOW);
		namedWindow(OPENCV_WINDOW2);
		namedWindow(OPENCV_WINDOW3);
	}

	~ImageProcessing()
	{
		destroyWindow(OPENCV_WINDOW);
		destroyWindow(OPENCV_WINDOW2);
		destroyWindow(OPENCV_WINDOW3);
	}

	void velCb(geometry_msgs::Vector3Stamped v)
	{
		vel = v.x;
		geometry_msgs::Twist velocity;
		velocity.angular.x = vel;
	}

	void imageCb(const sensor_msgs::ImageConstPtr& msg)
	{
		//Convert ROS Input Image Message to IplImage
		cv_bridge::CvImagePtr cv_input_;
		try
		{
		  cv_input_ = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
		}
		catch (cv_bridge::Exception& e)
		{
		  ROS_ERROR("cv_bridge exception: %s", e.what());
		  return;
		}

		//Convert IplImage to cv::Mat
		//img_in_ = cv::Mat(cv_input_).clone();
		img_in_ = cv_input_->image;

		//Output image = Input Image (Segmentation)
		img_out_ = img_in_.clone();

		//Convert Input Image to HSV
		cv::cvtColor (img_in_, img_hsv_, CV_BGR2HSV);

		//Zero Matrices
		img_hue_ = Mat::zeros(img_hsv_.rows, img_hsv_.cols, CV_8U);
    		img_sat_ = Mat::zeros(img_hsv_.rows, img_hsv_.cols, CV_8U);
    		img_bin_ = Mat::zeros(img_hsv_.rows, img_hsv_.cols, CV_8U);

		//HSV Channel 0 -> img_hue_ & HSV Channel 1 -> img_sat_
		int from_to[] = { 0,0, 1,1};
   		Mat img_split[] = { img_hue_, img_sat_};
    		mixChannels(&img_hsv_, 3,img_split,2,from_to,2);

		for(int ii = 0; ii < img_out_.rows; ii++)
		{
			for(int jj = 0; jj < img_out_.cols; jj++)
			{
				//The output pixel is white if input pixel hue is darker and saturation is reasonable
				if(img_hue_.at<uchar>(ii,jj) > 0 && img_hue_.at<uchar>(ii,jj) < 10 && img_sat_.at<uchar>(ii,jj) > 160)
				{
					img_bin_.at<uchar>(ii,jj) = 255;
				}
				else
				{
					img_bin_.at<uchar>(ii,jj) = 0;
/*					//Clear pixel BGR output channel
					img_out_.at<uchar>(ii,jj*3+0) = 0;
					img_out_.at<uchar>(ii,jj*3+1) = 0;
					img_out_.at<uchar>(ii,jj*3+2) = 0;*/
				}
			}
		}

		//strel_size is the size of the structuring element
		Size strel_size;
		strel_size.width = 3;
		strel_size.height = 3;

		//Create an elliptical structuring element
		Mat strel = getStructuringElement(MORPH_ELLIPSE,strel_size);

		//Apply an opening morphological operation using the structuring element to the image three times
		morphologyEx(img_bin_,img_bin_,MORPH_OPEN,strel,Point(-1,-1),3);

		//Invert the Image
		bitwise_not(img_bin_,img_bin_);

		//Blur the Image to Improve Detection
		GaussianBlur(img_bin_, img_bin_, Size(11,11),2,2);

		//Vector Circles will hold the position and radius of the detected circles
		vector<Vec3f> circles;

		//Detect Circles
		HoughCircles(img_bin_, circles, CV_HOUGH_GRADIENT, 1, 80, 140, 15, 5, 100);

		for( size_t i = 0; i < circles.size(); i++ )
    		{
         		// round the floats to an int
         		Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
         		int radius = cvRound(circles[i][2]);
         		// draw the circle center
         		circle( img_out_, center, 3, Scalar(0,255,0), -1, 8, 0 );
        	 	// draw the circle outline
         		circle( img_out_, center, radius+1, Scalar(0,0,255), 3, 8, 0 );
         		// Debugging Output
			ROS_INFO("x: %d y: %d r: %d",center.x,center.y, radius);

		// Publish the data
		coord_pub_ = nh_.advertise<geometry_msgs::Twist>("coordinate", 100);
		geometry_msgs::Twist msg;
		msg.linear.x = center.x;
		msg.linear.y = center.y;
//		msg.angular.x = vel;
		coord_pub_.publish(msg);
    }

		//Update GUI Window
		imshow(OPENCV_WINDOW, img_in_);
		imshow(OPENCV_WINDOW2, img_bin_);
		imshow(OPENCV_WINDOW3, img_out_);

		waitKey(3);

		//Convert cv::Mat to IplImage
//		cv_bridge::CvImage img_out_;
//		img_out_.encoding = sensor_msgs::image_encodings::BGR8;
//		img_out_.image = img_hsv_;

		//Publish Output Image
//		image_pub_.publish(img_out_.toImageMsg());

	}
};

int main(int argc, char** argv)
{
	//Initialize ROS Node
	ros::init(argc, argv, "image_processing");

//	ros::Subscriber rpm_ = nh_.subscribe("/rpm", 100, velCb);
	//Start Node
	ImageProcessing ip;

	//Keep the ROS Running
	ros::spin();

return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ftpdynresultset.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:35:46 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _FTP_FTPDYNRESULTSET_HXX
#define _FTP_FTPDYNRESULTSET_HXX

#ifndef _UCBHELPER_RESULTSETHELPER_HXX
#include <ucbhelper/resultsethelper.hxx>
#endif
#ifndef _VOS_REF_HXX_
#include <vos/ref.hxx>
#endif
#ifndef _FTP_FTPCONTENT_HXX_
#include "ftpcontent.hxx"
#endif

namespace ftp {

    class ResultSetFactory;

    class DynamicResultSet : public ::ucb::ResultSetImplHelper
    {
        vos::ORef< FTPContent > m_xContent;
        com::sun::star::uno::Reference<
        com::sun::star::ucb::XCommandEnvironment > m_xEnv;
        ResultSetFactory*                    m_pFactory;

    private:
        virtual void initStatic();
        virtual void initDynamic();

    public:
        DynamicResultSet(
            const com::sun::star::uno::Reference<
            com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
            const vos::ORef< FTPContent >& rxContent,
            const com::sun::star::ucb::OpenCommandArgument2& rCommand,
            const com::sun::star::uno::Reference<
            com::sun::star::ucb::XCommandEnvironment >& rxEnv,
            ResultSetFactory* pFactory );

        ~DynamicResultSet();
    };

}

#endif

<commit_msg>INTEGRATION: CWS bgdlremove (1.3.108); FILE MERGED 2007/05/18 11:37:16 kso 1.3.108.2: #i77419# - cleanup of ucbhelper namespaces. 2007/05/11 09:20:53 kso 1.3.108.1: 76911# - ucbhelper lib no longer uses VOS. (vos::ORef => rtl::Reference, vos::OMutex => osl::Mutex, ...)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ftpdynresultset.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 18:00:50 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _FTP_FTPDYNRESULTSET_HXX
#define _FTP_FTPDYNRESULTSET_HXX

#include "rtl/ref.hxx"
#include "ucbhelper/resultsethelper.hxx"

#include "ftpcontent.hxx"

namespace ftp {

    class ResultSetFactory;

    class DynamicResultSet : public ::ucbhelper::ResultSetImplHelper
    {
        rtl::Reference< FTPContent > m_xContent;
        com::sun::star::uno::Reference<
            com::sun::star::ucb::XCommandEnvironment > m_xEnv;
        ResultSetFactory*                    m_pFactory;

    private:
        virtual void initStatic();
        virtual void initDynamic();

    public:
        DynamicResultSet(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
            const rtl::Reference< FTPContent >& rxContent,
            const com::sun::star::ucb::OpenCommandArgument2& rCommand,
            const com::sun::star::uno::Reference<
                com::sun::star::ucb::XCommandEnvironment >& rxEnv,
            ResultSetFactory* pFactory );

        ~DynamicResultSet();
    };

}

#endif

<|endoftext|>


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

#include "chrome/browser/diagnostics/recon_diagnostics.h"

#include "app/app_paths.h"
#include "base/file_util.h"
#include "base/file_version_info.h"
#include "base/json/json_reader.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/sys_info.h"
#include "base/path_service.h"
#include "chrome/app/chrome_version_info.h"
#include "chrome/browser/diagnostics/diagnostics_test.h"
#include "chrome/browser/platform_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_value_serializer.h"

#if defined(OS_WIN)
#include "base/win_util.h"
#include "chrome/installer/util/install_util.h"
#endif

// Reconnaissance diagnostics. These are the first and most critical
// diagnostic tests. Here we check for the existence of critical files.
// TODO(cpu): Define if it makes sense to localize strings.

// TODO(cpu): There are a few maxium file sizes hardcoded in this file
// that have little or no theoretical or experimental ground. Find a way
// to justify them.

namespace {

class InstallTypeTest;
InstallTypeTest* g_install_type = 0;

// Check that the flavor of the operating system is supported.
class OperatingSystemTest : public DiagnosticTest {
 public:
  OperatingSystemTest() : DiagnosticTest(ASCIIToUTF16("Operating System")) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    int version = 0;
    int major = 0;
    int minor = 0;
#if defined(OS_WIN)
    version = win_util::GetWinVersion();
    if (version < win_util::WINVERSION_XP) {
      RecordFailure(ASCIIToUTF16("Windows 2000 or earlier"));
      return false;
    }
    win_util::GetServicePackLevel(&major, &minor);
    if ((version == win_util::WINVERSION_XP) && (major < 2)) {
      RecordFailure(ASCIIToUTF16("XP Service Pack 1 or earlier"));
      return false;
    }
#else
    // TODO(port): define the OS criteria for linux and mac.
#endif  // defined(OS_WIN)
    RecordSuccess(ASCIIToUTF16(StringPrintf("%s %s (%d [%d:%d])",
        base::SysInfo::OperatingSystemName().c_str(),
        base::SysInfo::OperatingSystemVersion().c_str(),
        version, major, minor)));
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(OperatingSystemTest);
};

// Check if it is system install or per-user install.
class InstallTypeTest : public DiagnosticTest {
 public:
  InstallTypeTest() : DiagnosticTest(ASCIIToUTF16("Install Type")),
                      user_level_(false) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
#if defined(OS_WIN)
    FilePath chrome_exe;
    if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
      RecordFailure(ASCIIToUTF16("Path provider failure"));
      return false;
    }
    user_level_ = InstallUtil::IsPerUserInstall(
        chrome_exe.ToWStringHack().c_str());
    const char* type = user_level_ ? "User Level" : "System Level";
    string16 install_type(ASCIIToUTF16(type));
#else
    string16 install_type(ASCIIToUTF16("System Level"));
#endif  // defined(OS_WIN)
    RecordSuccess(install_type);
    g_install_type = this;
    return true;
  }

  bool system_level() const { return !user_level_; }

 private:
  bool user_level_;
  DISALLOW_COPY_AND_ASSIGN(InstallTypeTest);
};

// Check the version of Chrome.
class VersionTest : public DiagnosticTest {
 public:
  VersionTest() : DiagnosticTest(ASCIIToUTF16("Browser Version")) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    scoped_ptr<FileVersionInfo> version_info(
        chrome_app::GetChromeVersionInfo());
    if (!version_info.get()) {
      RecordFailure(ASCIIToUTF16("No Version"));
      return true;
    }
    string16 current_version = WideToUTF16(version_info->file_version());
    if (current_version.empty()) {
      RecordFailure(ASCIIToUTF16("Empty Version"));
      return true;
    }
    string16 version_modifier = platform_util::GetVersionStringModifier();
    if (!version_modifier.empty()) {
      current_version += ASCIIToUTF16(" ");
      current_version += version_modifier;
    }
#if defined(GOOGLE_CHROME_BUILD)
    current_version += ASCIIToUTF16(" GCB");
#endif  // defined(GOOGLE_CHROME_BUILD)
    RecordSuccess(current_version);
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(VersionTest);
};

struct TestPathInfo {
  const char* test_name;
  int  path_id;
  bool is_directory;
  bool is_optional;
  bool test_writable;
  int64 max_size;
};

const int64 kOneKilo = 1024;
const int64 kOneMeg = 1024 * kOneKilo;

const TestPathInfo kPathsToTest[] = {
  {"User data Directory", chrome::DIR_USER_DATA,
      true, false, true, 250 * kOneMeg},
  {"Local state file", chrome::FILE_LOCAL_STATE,
      false, false, true, 100 * kOneKilo},
  {"Dictionaries Directory", chrome::DIR_APP_DICTIONARIES,
      true, true, false, 0},
  {"Inspector Directory", chrome::DIR_INSPECTOR,
      true, false, false, 0}
};

// Check that the user's data directory exists and the paths are writeable.
// If it is a systemwide install some paths are not expected to be writeable.
// This test depends on |InstallTypeTest| having run succesfuly.
class PathTest : public DiagnosticTest {
 public:
  explicit PathTest(const TestPathInfo& path_info)
      : DiagnosticTest(ASCIIToUTF16(path_info.test_name)),
        path_info_(path_info) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    if (!g_install_type) {
      RecordStopFailure(ASCIIToUTF16("dependency failure"));
      return false;
    }
    FilePath dir_or_file;
    if (!PathService::Get(path_info_.path_id, &dir_or_file)) {
      RecordStopFailure(ASCIIToUTF16("Path provider failure"));
      return false;
    }
    if (!file_util::PathExists(dir_or_file)) {
      RecordFailure(ASCIIToUTF16("Path not found"));
      return true;
    }

    int64 dir_or_file_size = 0;
    if (path_info_.is_directory) {
      dir_or_file_size = file_util::ComputeDirectorySize(dir_or_file);
    } else {
      file_util::GetFileSize(dir_or_file, &dir_or_file_size);
    }
    if (!dir_or_file_size && !path_info_.is_optional) {
      RecordFailure(ASCIIToUTF16("Cannot obtain size"));
      return true;
    }
    DataUnits units = GetByteDisplayUnits(dir_or_file_size);
    string16 printable_size =
        WideToUTF16(FormatBytes(dir_or_file_size, units, true));

    if (path_info_.max_size > 0) {
      if (dir_or_file_size > path_info_.max_size) {
        RecordFailure(ASCIIToUTF16("Path is too big: ") + printable_size);
        return true;
      }
    }
    if (g_install_type->system_level() && !path_info_.test_writable) {
      RecordSuccess(ASCIIToUTF16("Path exists"));
      return true;
    }
    if (!file_util::PathIsWritable(dir_or_file)) {
      RecordFailure(ASCIIToUTF16("Path is not writable"));
      return true;
    }
    RecordSuccess(ASCIIToUTF16("Path exists and is writable: ")
                  + printable_size);
    return true;
  }

 private:
  TestPathInfo path_info_;
  DISALLOW_COPY_AND_ASSIGN(PathTest);
};

// Check that the disk space in the volume where the user data dir normally
// lives is not dangerosly low.
class DiskSpaceTest : public DiagnosticTest {
 public:
  DiskSpaceTest() : DiagnosticTest(ASCIIToUTF16("Disk Space")) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    FilePath data_dir;
    if (!PathService::Get(chrome::DIR_USER_DATA, &data_dir))
      return false;
    int64 disk_space = base::SysInfo::AmountOfFreeDiskSpace(data_dir);
    if (disk_space < 0) {
      RecordFailure(ASCIIToUTF16("Unable to query free space"));
      return true;
    }
    DataUnits units = GetByteDisplayUnits(disk_space);
    string16 printable_size =
        WideToUTF16(FormatBytes(disk_space, units, true));
    if (disk_space < 80 * kOneMeg) {
      RecordFailure(ASCIIToUTF16("Low disk space : ") + printable_size);
      return true;
    }
    RecordSuccess(ASCIIToUTF16("Free space : ") + printable_size);
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DiskSpaceTest);
};

// Checks that a given json file can be correctly parsed.
class JSONTest : public DiagnosticTest {
 public:
  JSONTest(const FilePath& path, const string16 name, int64 max_file_size)
      : DiagnosticTest(name), path_(path), max_file_size_(max_file_size) {
  }

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    if (!file_util::PathExists(path_)) {
      RecordFailure(ASCIIToUTF16("File not found"));
      return true;
    }
    int64 file_size;
    file_util::GetFileSize(path_, &file_size);
    if (file_size > max_file_size_) {
      RecordFailure(ASCIIToUTF16("File too big"));
      return true;
    }
    // Being small enough, we can process it in-memory.
    std::string json_data;
    if (!file_util::ReadFileToString(path_, &json_data)) {
      RecordFailure(ASCIIToUTF16(
          "Could not open file. Possibly locked by other process"));
      return true;
    }

    JSONStringValueSerializer json(json_data);
    int error_code = base::JSONReader::JSON_NO_ERROR;
    std::string error_message;
    scoped_ptr<Value> json_root(json.Deserialize(&error_code, &error_message));
    if (base::JSONReader::JSON_NO_ERROR != error_code) {
      if (error_message.empty()) {
        error_message = "Parse error " + IntToString(error_code);
      }
      RecordFailure(UTF8ToUTF16(error_message));
      return true;
    }

    RecordSuccess(ASCIIToUTF16("File parsed OK"));
    return true;
  }

 private:
  FilePath path_;
  int64 max_file_size_;
  DISALLOW_COPY_AND_ASSIGN(JSONTest);
};

}  // namespace

DiagnosticTest* MakeUserDirTest() {
  return new PathTest(kPathsToTest[0]);
}

DiagnosticTest* MakeLocalStateFileTest() {
  return new PathTest(kPathsToTest[1]);
}

DiagnosticTest* MakeDictonaryDirTest() {
  return new PathTest(kPathsToTest[2]);
}

DiagnosticTest* MakeInspectorDirTest() {
  return new PathTest(kPathsToTest[3]);
}

DiagnosticTest* MakeVersionTest() {
  return new VersionTest();
}

DiagnosticTest* MakeDiskSpaceTest() {
  return new DiskSpaceTest();
}

DiagnosticTest* MakeOperatingSystemTest() {
  return new OperatingSystemTest();
}

DiagnosticTest* MakeInstallTypeTest() {
  return new InstallTypeTest();
}

DiagnosticTest* MakePreferencesTest() {
  FilePath path = DiagnosticTest::GetUserDefaultProfileDir();
  path = path.Append(chrome::kPreferencesFilename);
  return new JSONTest(path, ASCIIToUTF16("Profile JSON"), 100 * kOneKilo);
}

DiagnosticTest* MakeBookMarksTest() {
  FilePath path = DiagnosticTest::GetUserDefaultProfileDir();
  path = path.Append(chrome::kBookmarksFileName);
  return new JSONTest(path, ASCIIToUTF16("BookMarks JSON"), 2 * kOneMeg);
}

DiagnosticTest* MakeLocalStateTest() {
  FilePath path;
  PathService::Get(chrome::DIR_USER_DATA, &path);
  path = path.Append(chrome::kLocalStateFilename);
  return new JSONTest(path, ASCIIToUTF16("Local State JSON"), 50 * kOneKilo);
}
<commit_msg>Upping the diagnostic mode limits for file size - The local state and the overall size of the profile dir<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/diagnostics/recon_diagnostics.h"

#include "app/app_paths.h"
#include "base/file_util.h"
#include "base/file_version_info.h"
#include "base/json/json_reader.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/sys_info.h"
#include "base/path_service.h"
#include "chrome/app/chrome_version_info.h"
#include "chrome/browser/diagnostics/diagnostics_test.h"
#include "chrome/browser/platform_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_value_serializer.h"

#if defined(OS_WIN)
#include "base/win_util.h"
#include "chrome/installer/util/install_util.h"
#endif

// Reconnaissance diagnostics. These are the first and most critical
// diagnostic tests. Here we check for the existence of critical files.
// TODO(cpu): Define if it makes sense to localize strings.

// TODO(cpu): There are a few maxium file sizes hardcoded in this file
// that have little or no theoretical or experimental ground. Find a way
// to justify them.

namespace {

class InstallTypeTest;
InstallTypeTest* g_install_type = 0;

// Check that the flavor of the operating system is supported.
class OperatingSystemTest : public DiagnosticTest {
 public:
  OperatingSystemTest() : DiagnosticTest(ASCIIToUTF16("Operating System")) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    int version = 0;
    int major = 0;
    int minor = 0;
#if defined(OS_WIN)
    version = win_util::GetWinVersion();
    if (version < win_util::WINVERSION_XP) {
      RecordFailure(ASCIIToUTF16("Windows 2000 or earlier"));
      return false;
    }
    win_util::GetServicePackLevel(&major, &minor);
    if ((version == win_util::WINVERSION_XP) && (major < 2)) {
      RecordFailure(ASCIIToUTF16("XP Service Pack 1 or earlier"));
      return false;
    }
#else
    // TODO(port): define the OS criteria for linux and mac.
#endif  // defined(OS_WIN)
    RecordSuccess(ASCIIToUTF16(StringPrintf("%s %s (%d [%d:%d])",
        base::SysInfo::OperatingSystemName().c_str(),
        base::SysInfo::OperatingSystemVersion().c_str(),
        version, major, minor)));
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(OperatingSystemTest);
};

// Check if it is system install or per-user install.
class InstallTypeTest : public DiagnosticTest {
 public:
  InstallTypeTest() : DiagnosticTest(ASCIIToUTF16("Install Type")),
                      user_level_(false) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
#if defined(OS_WIN)
    FilePath chrome_exe;
    if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
      RecordFailure(ASCIIToUTF16("Path provider failure"));
      return false;
    }
    user_level_ = InstallUtil::IsPerUserInstall(
        chrome_exe.ToWStringHack().c_str());
    const char* type = user_level_ ? "User Level" : "System Level";
    string16 install_type(ASCIIToUTF16(type));
#else
    string16 install_type(ASCIIToUTF16("System Level"));
#endif  // defined(OS_WIN)
    RecordSuccess(install_type);
    g_install_type = this;
    return true;
  }

  bool system_level() const { return !user_level_; }

 private:
  bool user_level_;
  DISALLOW_COPY_AND_ASSIGN(InstallTypeTest);
};

// Check the version of Chrome.
class VersionTest : public DiagnosticTest {
 public:
  VersionTest() : DiagnosticTest(ASCIIToUTF16("Browser Version")) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    scoped_ptr<FileVersionInfo> version_info(
        chrome_app::GetChromeVersionInfo());
    if (!version_info.get()) {
      RecordFailure(ASCIIToUTF16("No Version"));
      return true;
    }
    string16 current_version = WideToUTF16(version_info->file_version());
    if (current_version.empty()) {
      RecordFailure(ASCIIToUTF16("Empty Version"));
      return true;
    }
    string16 version_modifier = platform_util::GetVersionStringModifier();
    if (!version_modifier.empty()) {
      current_version += ASCIIToUTF16(" ");
      current_version += version_modifier;
    }
#if defined(GOOGLE_CHROME_BUILD)
    current_version += ASCIIToUTF16(" GCB");
#endif  // defined(GOOGLE_CHROME_BUILD)
    RecordSuccess(current_version);
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(VersionTest);
};

struct TestPathInfo {
  const char* test_name;
  int  path_id;
  bool is_directory;
  bool is_optional;
  bool test_writable;
  int64 max_size;
};

const int64 kOneKilo = 1024;
const int64 kOneMeg = 1024 * kOneKilo;

const TestPathInfo kPathsToTest[] = {
  {"User data Directory", chrome::DIR_USER_DATA,
      true, false, true, 850 * kOneMeg},
  {"Local state file", chrome::FILE_LOCAL_STATE,
      false, false, true, 500 * kOneKilo},
  {"Dictionaries Directory", chrome::DIR_APP_DICTIONARIES,
      true, true, false, 0},
  {"Inspector Directory", chrome::DIR_INSPECTOR,
      true, false, false, 0}
};

// Check that the user's data directory exists and the paths are writeable.
// If it is a systemwide install some paths are not expected to be writeable.
// This test depends on |InstallTypeTest| having run succesfuly.
class PathTest : public DiagnosticTest {
 public:
  explicit PathTest(const TestPathInfo& path_info)
      : DiagnosticTest(ASCIIToUTF16(path_info.test_name)),
        path_info_(path_info) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    if (!g_install_type) {
      RecordStopFailure(ASCIIToUTF16("dependency failure"));
      return false;
    }
    FilePath dir_or_file;
    if (!PathService::Get(path_info_.path_id, &dir_or_file)) {
      RecordStopFailure(ASCIIToUTF16("Path provider failure"));
      return false;
    }
    if (!file_util::PathExists(dir_or_file)) {
      RecordFailure(ASCIIToUTF16("Path not found"));
      return true;
    }

    int64 dir_or_file_size = 0;
    if (path_info_.is_directory) {
      dir_or_file_size = file_util::ComputeDirectorySize(dir_or_file);
    } else {
      file_util::GetFileSize(dir_or_file, &dir_or_file_size);
    }
    if (!dir_or_file_size && !path_info_.is_optional) {
      RecordFailure(ASCIIToUTF16("Cannot obtain size"));
      return true;
    }
    DataUnits units = GetByteDisplayUnits(dir_or_file_size);
    string16 printable_size =
        WideToUTF16(FormatBytes(dir_or_file_size, units, true));

    if (path_info_.max_size > 0) {
      if (dir_or_file_size > path_info_.max_size) {
        RecordFailure(ASCIIToUTF16("Path is too big: ") + printable_size);
        return true;
      }
    }
    if (g_install_type->system_level() && !path_info_.test_writable) {
      RecordSuccess(ASCIIToUTF16("Path exists"));
      return true;
    }
    if (!file_util::PathIsWritable(dir_or_file)) {
      RecordFailure(ASCIIToUTF16("Path is not writable"));
      return true;
    }
    RecordSuccess(ASCIIToUTF16("Path exists and is writable: ")
                  + printable_size);
    return true;
  }

 private:
  TestPathInfo path_info_;
  DISALLOW_COPY_AND_ASSIGN(PathTest);
};

// Check that the disk space in the volume where the user data dir normally
// lives is not dangerosly low.
class DiskSpaceTest : public DiagnosticTest {
 public:
  DiskSpaceTest() : DiagnosticTest(ASCIIToUTF16("Disk Space")) {}

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    FilePath data_dir;
    if (!PathService::Get(chrome::DIR_USER_DATA, &data_dir))
      return false;
    int64 disk_space = base::SysInfo::AmountOfFreeDiskSpace(data_dir);
    if (disk_space < 0) {
      RecordFailure(ASCIIToUTF16("Unable to query free space"));
      return true;
    }
    DataUnits units = GetByteDisplayUnits(disk_space);
    string16 printable_size =
        WideToUTF16(FormatBytes(disk_space, units, true));
    if (disk_space < 80 * kOneMeg) {
      RecordFailure(ASCIIToUTF16("Low disk space : ") + printable_size);
      return true;
    }
    RecordSuccess(ASCIIToUTF16("Free space : ") + printable_size);
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(DiskSpaceTest);
};

// Checks that a given json file can be correctly parsed.
class JSONTest : public DiagnosticTest {
 public:
  JSONTest(const FilePath& path, const string16 name, int64 max_file_size)
      : DiagnosticTest(name), path_(path), max_file_size_(max_file_size) {
  }

  virtual int GetId() { return 0; }

  virtual bool ExecuteImpl(DiagnosticsModel::Observer* observer) {
    if (!file_util::PathExists(path_)) {
      RecordFailure(ASCIIToUTF16("File not found"));
      return true;
    }
    int64 file_size;
    file_util::GetFileSize(path_, &file_size);
    if (file_size > max_file_size_) {
      RecordFailure(ASCIIToUTF16("File too big"));
      return true;
    }
    // Being small enough, we can process it in-memory.
    std::string json_data;
    if (!file_util::ReadFileToString(path_, &json_data)) {
      RecordFailure(ASCIIToUTF16(
          "Could not open file. Possibly locked by other process"));
      return true;
    }

    JSONStringValueSerializer json(json_data);
    int error_code = base::JSONReader::JSON_NO_ERROR;
    std::string error_message;
    scoped_ptr<Value> json_root(json.Deserialize(&error_code, &error_message));
    if (base::JSONReader::JSON_NO_ERROR != error_code) {
      if (error_message.empty()) {
        error_message = "Parse error " + IntToString(error_code);
      }
      RecordFailure(UTF8ToUTF16(error_message));
      return true;
    }

    RecordSuccess(ASCIIToUTF16("File parsed OK"));
    return true;
  }

 private:
  FilePath path_;
  int64 max_file_size_;
  DISALLOW_COPY_AND_ASSIGN(JSONTest);
};

}  // namespace

DiagnosticTest* MakeUserDirTest() {
  return new PathTest(kPathsToTest[0]);
}

DiagnosticTest* MakeLocalStateFileTest() {
  return new PathTest(kPathsToTest[1]);
}

DiagnosticTest* MakeDictonaryDirTest() {
  return new PathTest(kPathsToTest[2]);
}

DiagnosticTest* MakeInspectorDirTest() {
  return new PathTest(kPathsToTest[3]);
}

DiagnosticTest* MakeVersionTest() {
  return new VersionTest();
}

DiagnosticTest* MakeDiskSpaceTest() {
  return new DiskSpaceTest();
}

DiagnosticTest* MakeOperatingSystemTest() {
  return new OperatingSystemTest();
}

DiagnosticTest* MakeInstallTypeTest() {
  return new InstallTypeTest();
}

DiagnosticTest* MakePreferencesTest() {
  FilePath path = DiagnosticTest::GetUserDefaultProfileDir();
  path = path.Append(chrome::kPreferencesFilename);
  return new JSONTest(path, ASCIIToUTF16("Profile JSON"), 100 * kOneKilo);
}

DiagnosticTest* MakeBookMarksTest() {
  FilePath path = DiagnosticTest::GetUserDefaultProfileDir();
  path = path.Append(chrome::kBookmarksFileName);
  return new JSONTest(path, ASCIIToUTF16("BookMarks JSON"), 2 * kOneMeg);
}

DiagnosticTest* MakeLocalStateTest() {
  FilePath path;
  PathService::Get(chrome::DIR_USER_DATA, &path);
  path = path.Append(chrome::kLocalStateFilename);
  return new JSONTest(path, ASCIIToUTF16("Local State JSON"), 50 * kOneKilo);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ftpdynresultset.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 18:00:50 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _FTP_FTPDYNRESULTSET_HXX
#define _FTP_FTPDYNRESULTSET_HXX

#include "rtl/ref.hxx"
#include "ucbhelper/resultsethelper.hxx"

#include "ftpcontent.hxx"

namespace ftp {

    class ResultSetFactory;

    class DynamicResultSet : public ::ucbhelper::ResultSetImplHelper
    {
        rtl::Reference< FTPContent > m_xContent;
        com::sun::star::uno::Reference<
            com::sun::star::ucb::XCommandEnvironment > m_xEnv;
        ResultSetFactory*                    m_pFactory;

    private:
        virtual void initStatic();
        virtual void initDynamic();

    public:
        DynamicResultSet(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
            const rtl::Reference< FTPContent >& rxContent,
            const com::sun::star::ucb::OpenCommandArgument2& rCommand,
            const com::sun::star::uno::Reference<
                com::sun::star::ucb::XCommandEnvironment >& rxEnv,
            ResultSetFactory* pFactory );

        ~DynamicResultSet();
    };

}

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.4.72); FILE MERGED 2008/03/31 15:30:19 rt 1.4.72.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ftpdynresultset.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _FTP_FTPDYNRESULTSET_HXX
#define _FTP_FTPDYNRESULTSET_HXX

#include "rtl/ref.hxx"
#include "ucbhelper/resultsethelper.hxx"

#include "ftpcontent.hxx"

namespace ftp {

    class ResultSetFactory;

    class DynamicResultSet : public ::ucbhelper::ResultSetImplHelper
    {
        rtl::Reference< FTPContent > m_xContent;
        com::sun::star::uno::Reference<
            com::sun::star::ucb::XCommandEnvironment > m_xEnv;
        ResultSetFactory*                    m_pFactory;

    private:
        virtual void initStatic();
        virtual void initDynamic();

    public:
        DynamicResultSet(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
            const rtl::Reference< FTPContent >& rxContent,
            const com::sun::star::ucb::OpenCommandArgument2& rCommand,
            const com::sun::star::uno::Reference<
                com::sun::star::ucb::XCommandEnvironment >& rxEnv,
            ResultSetFactory* pFactory );

        ~DynamicResultSet();
    };

}

#endif

<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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 "base/string_util.h"
#include "base/path_service.h"
#include "chrome/browser/extensions/extension.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_value_serializer.h"
#include "testing/gtest/include/gtest/gtest.h"

class ExtensionTest : public testing::Test {
};

TEST(ExtensionTest, InitFromValueInvalid) {
#if defined(OS_WIN)
  FilePath path(FILE_PATH_LITERAL("c:\\foo"));
#elif defined(OS_POSIX)
  FilePath path(FILE_PATH_LITERAL("/foo"));
#endif
  Extension extension(path);
  std::string error;

  // Start with a valid extension manifest
  std::wstring extensions_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir));
  FilePath extensions_path = FilePath::FromWStringHack(extensions_dir)
      .AppendASCII("extensions")
      .AppendASCII("good")
      .AppendASCII("extension1")
      .AppendASCII("1")
      .AppendASCII(Extension::kManifestFilename);

  JSONFileValueSerializer serializer(extensions_path.ToWStringHack());
  scoped_ptr<DictionaryValue> valid_value(
      static_cast<DictionaryValue*>(serializer.Deserialize(&error)));
  ASSERT_TRUE(valid_value.get());
  ASSERT_EQ("", error);
  ASSERT_TRUE(extension.InitFromValue(*valid_value, &error));
  ASSERT_EQ("", error);

  scoped_ptr<DictionaryValue> input_value;

  // Test missing and invalid format versions
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->Remove(Extension::kFormatVersionKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidFormatVersionError, error);

  input_value->SetString(Extension::kFormatVersionKey, "foo");
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidFormatVersionError, error);

  input_value->SetInteger(Extension::kFormatVersionKey, 2);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidFormatVersionError, error);

  // Test missing and invalid ids
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->Remove(Extension::kIdKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidIdError, error);

  input_value->SetInteger(Extension::kIdKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidIdError, error);

  // Test missing and invalid versions
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->Remove(Extension::kVersionKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidVersionError, error);

  input_value->SetInteger(Extension::kVersionKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidVersionError, error);

  // Test missing and invalid names
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->Remove(Extension::kNameKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidNameError, error);

  input_value->SetInteger(Extension::kNameKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidNameError, error);

  // Test invalid description
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->SetInteger(Extension::kDescriptionKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidDescriptionError, error);

  // Test invalid user scripts list
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->SetInteger(Extension::kContentScriptsKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidContentScriptsListError, error);

  // Test invalid user script item
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  ListValue* content_scripts = NULL;
  input_value->GetList(Extension::kContentScriptsKey, &content_scripts);
  ASSERT_FALSE(NULL == content_scripts);
  content_scripts->Set(0, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidContentScriptError));

  // Test missing and invalid matches array
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->GetList(Extension::kContentScriptsKey, &content_scripts);
  DictionaryValue* user_script = NULL;
  content_scripts->GetDictionary(0, &user_script);
  user_script->Remove(Extension::kMatchesKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidMatchesError));

  user_script->Set(Extension::kMatchesKey, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidMatchesError));

  ListValue* matches = new ListValue;
  user_script->Set(Extension::kMatchesKey, matches);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidMatchCountError));

  // Test invalid match element
  matches->Set(0, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidMatchError));

  // Test missing and invalid files array
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->GetList(Extension::kContentScriptsKey, &content_scripts);
  content_scripts->GetDictionary(0, &user_script);
  user_script->Remove(Extension::kJsKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsListError));

  user_script->Set(Extension::kJsKey, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsListError));

  ListValue* files = new ListValue;
  user_script->Set(Extension::kJsKey, files);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsCountError));

  // Test invalid file element
  files->Set(0, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsError));

  // Test too many file elements (more than one not yet supported)
  files->Set(0, Value::CreateStringValue("foo.js"));
  files->Set(1, Value::CreateStringValue("bar.js"));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsCountError));
}

TEST(ExtensionTest, InitFromValueValid) {
#if defined(OS_WIN)
  FilePath path(FILE_PATH_LITERAL("C:\\foo"));
#elif defined(OS_POSIX)
  FilePath path(FILE_PATH_LITERAL("/foo"));
#endif
  Extension extension(path);
  std::string error;
  DictionaryValue input_value;

  // Test minimal extension
  input_value.SetInteger(Extension::kFormatVersionKey, 1);
  input_value.SetString(Extension::kIdKey, "com.google.myextension");
  input_value.SetString(Extension::kVersionKey, "1.0.0.0");
  input_value.SetString(Extension::kNameKey, "my extension");

  EXPECT_TRUE(extension.InitFromValue(input_value, &error));
  EXPECT_EQ("", error);
  EXPECT_EQ("com.google.myextension", extension.id());
  EXPECT_EQ("1.0.0.0", extension.VersionString());
  EXPECT_EQ("my extension", extension.name());
  EXPECT_EQ("chrome-extension://com.google.myextension/",
            extension.url().spec());
  EXPECT_EQ(path.value(), extension.path().value());
}

TEST(ExtensionTest, GetResourceURLAndPath) {
#if defined(OS_WIN)
  FilePath path(FILE_PATH_LITERAL("C:\\foo"));
#elif defined(OS_POSIX)
  FilePath path(FILE_PATH_LITERAL("/foo"));
#endif
  Extension extension(path);
  DictionaryValue input_value;
  input_value.SetInteger(Extension::kFormatVersionKey, 1);
  input_value.SetString(Extension::kIdKey, "com.google.myextension");
  input_value.SetString(Extension::kVersionKey, "1.0.0.0");
  input_value.SetString(Extension::kNameKey, "my extension");
  EXPECT_TRUE(extension.InitFromValue(input_value, NULL));

  EXPECT_EQ(extension.url().spec() + "bar/baz.js",
            Extension::GetResourceURL(extension.url(), "bar/baz.js").spec());
  EXPECT_EQ(extension.url().spec() + "baz.js",
            Extension::GetResourceURL(extension.url(), "bar/../baz.js").spec());
  EXPECT_EQ(extension.url().spec() + "baz.js",
            Extension::GetResourceURL(extension.url(), "../baz.js").spec());

  EXPECT_EQ(path.Append(FILE_PATH_LITERAL("bar"))
                .Append(FILE_PATH_LITERAL("baz.js")).value(),
            Extension::GetResourcePath(extension.path(), "bar/baz.js").value());
  EXPECT_EQ(path.Append(FILE_PATH_LITERAL("baz.js")).value(),
            Extension::GetResourcePath(extension.path(), "bar/../baz.js")
                .value());
  EXPECT_EQ(FilePath().value(),
            Extension::GetResourcePath(extension.path(), "../baz.js").value());
}
<commit_msg>Fixed a unittest that I missed during my previous id format change.<commit_after>// Copyright (c) 2006-2008 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 "base/string_util.h"
#include "base/path_service.h"
#include "chrome/browser/extensions/extension.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/json_value_serializer.h"
#include "testing/gtest/include/gtest/gtest.h"

class ExtensionTest : public testing::Test {
};

TEST(ExtensionTest, InitFromValueInvalid) {
#if defined(OS_WIN)
  FilePath path(FILE_PATH_LITERAL("c:\\foo"));
#elif defined(OS_POSIX)
  FilePath path(FILE_PATH_LITERAL("/foo"));
#endif
  Extension extension(path);
  std::string error;

  // Start with a valid extension manifest
  std::wstring extensions_dir;
  ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &extensions_dir));
  FilePath extensions_path = FilePath::FromWStringHack(extensions_dir)
      .AppendASCII("extensions")
      .AppendASCII("good")
      .AppendASCII("extension1")
      .AppendASCII("1")
      .AppendASCII(Extension::kManifestFilename);

  JSONFileValueSerializer serializer(extensions_path.ToWStringHack());
  scoped_ptr<DictionaryValue> valid_value(
      static_cast<DictionaryValue*>(serializer.Deserialize(&error)));
  ASSERT_TRUE(valid_value.get());
  ASSERT_EQ("", error);
  ASSERT_TRUE(extension.InitFromValue(*valid_value, &error));
  ASSERT_EQ("", error);

  scoped_ptr<DictionaryValue> input_value;

  // Test missing and invalid format versions
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->Remove(Extension::kFormatVersionKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidFormatVersionError, error);

  input_value->SetString(Extension::kFormatVersionKey, "foo");
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidFormatVersionError, error);

  input_value->SetInteger(Extension::kFormatVersionKey, 2);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidFormatVersionError, error);

  // Test missing and invalid ids
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->Remove(Extension::kIdKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidIdError, error);

  input_value->SetInteger(Extension::kIdKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidIdError, error);

  // Test missing and invalid versions
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->Remove(Extension::kVersionKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidVersionError, error);

  input_value->SetInteger(Extension::kVersionKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidVersionError, error);

  // Test missing and invalid names
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->Remove(Extension::kNameKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidNameError, error);

  input_value->SetInteger(Extension::kNameKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidNameError, error);

  // Test invalid description
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->SetInteger(Extension::kDescriptionKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidDescriptionError, error);

  // Test invalid user scripts list
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->SetInteger(Extension::kContentScriptsKey, 42);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_EQ(Extension::kInvalidContentScriptsListError, error);

  // Test invalid user script item
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  ListValue* content_scripts = NULL;
  input_value->GetList(Extension::kContentScriptsKey, &content_scripts);
  ASSERT_FALSE(NULL == content_scripts);
  content_scripts->Set(0, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidContentScriptError));

  // Test missing and invalid matches array
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->GetList(Extension::kContentScriptsKey, &content_scripts);
  DictionaryValue* user_script = NULL;
  content_scripts->GetDictionary(0, &user_script);
  user_script->Remove(Extension::kMatchesKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidMatchesError));

  user_script->Set(Extension::kMatchesKey, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidMatchesError));

  ListValue* matches = new ListValue;
  user_script->Set(Extension::kMatchesKey, matches);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidMatchCountError));

  // Test invalid match element
  matches->Set(0, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidMatchError));

  // Test missing and invalid files array
  input_value.reset(static_cast<DictionaryValue*>(valid_value->DeepCopy()));
  input_value->GetList(Extension::kContentScriptsKey, &content_scripts);
  content_scripts->GetDictionary(0, &user_script);
  user_script->Remove(Extension::kJsKey, NULL);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsListError));

  user_script->Set(Extension::kJsKey, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsListError));

  ListValue* files = new ListValue;
  user_script->Set(Extension::kJsKey, files);
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsCountError));

  // Test invalid file element
  files->Set(0, Value::CreateIntegerValue(42));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsError));

  // Test too many file elements (more than one not yet supported)
  files->Set(0, Value::CreateStringValue("foo.js"));
  files->Set(1, Value::CreateStringValue("bar.js"));
  EXPECT_FALSE(extension.InitFromValue(*input_value, &error));
  EXPECT_TRUE(MatchPattern(error, Extension::kInvalidJsCountError));
}

TEST(ExtensionTest, InitFromValueValid) {
#if defined(OS_WIN)
  FilePath path(FILE_PATH_LITERAL("C:\\foo"));
#elif defined(OS_POSIX)
  FilePath path(FILE_PATH_LITERAL("/foo"));
#endif
  Extension extension(path);
  std::string error;
  DictionaryValue input_value;

  // Test minimal extension
  input_value.SetInteger(Extension::kFormatVersionKey, 1);
  input_value.SetString(Extension::kIdKey,
      "00123456789ABCDEF0123456789ABCDEF0123456");
  input_value.SetString(Extension::kVersionKey, "1.0.0.0");
  input_value.SetString(Extension::kNameKey, "my extension");

  EXPECT_TRUE(extension.InitFromValue(input_value, &error));
  EXPECT_EQ("", error);
  EXPECT_EQ("00123456789ABCDEF0123456789ABCDEF0123456", extension.id());
  EXPECT_EQ("1.0.0.0", extension.VersionString());
  EXPECT_EQ("my extension", extension.name());
  EXPECT_EQ("chrome-extension://00123456789abcdef0123456789abcdef0123456/",
            extension.url().spec());
  EXPECT_EQ(path.value(), extension.path().value());
}

TEST(ExtensionTest, GetResourceURLAndPath) {
#if defined(OS_WIN)
  FilePath path(FILE_PATH_LITERAL("C:\\foo"));
#elif defined(OS_POSIX)
  FilePath path(FILE_PATH_LITERAL("/foo"));
#endif
  Extension extension(path);
  DictionaryValue input_value;
  input_value.SetInteger(Extension::kFormatVersionKey, 1);
  input_value.SetString(Extension::kIdKey,
      "00123456789ABCDEF0123456789ABCDEF0123456");
  input_value.SetString(Extension::kVersionKey, "1.0.0.0");
  input_value.SetString(Extension::kNameKey, "my extension");
  EXPECT_TRUE(extension.InitFromValue(input_value, NULL));

  EXPECT_EQ(extension.url().spec() + "bar/baz.js",
            Extension::GetResourceURL(extension.url(), "bar/baz.js").spec());
  EXPECT_EQ(extension.url().spec() + "baz.js",
            Extension::GetResourceURL(extension.url(), "bar/../baz.js").spec());
  EXPECT_EQ(extension.url().spec() + "baz.js",
            Extension::GetResourceURL(extension.url(), "../baz.js").spec());

  EXPECT_EQ(path.Append(FILE_PATH_LITERAL("bar"))
                .Append(FILE_PATH_LITERAL("baz.js")).value(),
            Extension::GetResourcePath(extension.path(), "bar/baz.js").value());
  EXPECT_EQ(path.Append(FILE_PATH_LITERAL("baz.js")).value(),
            Extension::GetResourcePath(extension.path(), "bar/../baz.js")
                .value());
  EXPECT_EQ(FilePath().value(),
            Extension::GetResourcePath(extension.path(), "../baz.js").value());
}
<|endoftext|>