<commit_before>/******************************************************************************\
* File:          app.cpp
* Purpose:       Implementation of classes for syncodbcquery
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2008-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/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/stockitem.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"

#ifndef __WXMSW__
#include "app.xpm"
#endif

IMPLEMENT_APP(App)

bool App::OnInit()
{
  SetAppName("syncodbcquery");

  if (!wxExApp::OnInit())
  {
    return false;
  }

  Frame *frame = new Frame();
  frame->Show(true);

  SetTopWindow(frame);

  return true;
}

BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
  EVT_CLOSE(Frame::OnClose)
  EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
  EVT_MENU(wxID_STOP, Frame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
  EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
  EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, Frame::OnCommand)
  EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
  EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()

Frame::Frame()
  : wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppName())
  , m_Running(false)
  , m_Stopped(false)
{
  SetIcon(wxICON(app));

  wxExMenu* menuFile = new wxExMenu;
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENTFILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu* menuDatabase = new wxExMenu;
  menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
  menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));

  wxExMenu* menuQuery = new wxExMenu;
  menuQuery->Append(wxID_EXECUTE);
  menuQuery->Append(wxID_STOP);

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(wxID_PREFERENCES);

  wxMenu* menuView = new wxMenu();
  menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
  menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
  menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
  menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));

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

  wxMenuBar *menubar = new wxMenuBar;
  menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuDatabase, _("&Connection"));
  menubar->Append(menuQuery, _("&Query"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
  SetMenuBar(menubar);

  m_Query = new wxExSTCWithFrame(this, this);
  m_Query->SetLexer("sql");

  m_Results = new wxExGrid(this);
  m_Results->CreateGrid(0, 0);
  m_Results->EnableEditing(false); // this is a read-only grid

  m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
  m_Shell->SetFocus();

#if wxUSE_STATUSBAR
  std::vector<wxExPane> panes;
  panes.push_back(wxExPane("PaneText", -3));
  panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
  SetupStatusBar(panes);
#endif

  CreateToolBar();

  GetToolBar()->AddTool(wxID_NEW);
  GetToolBar()->AddTool(wxID_OPEN);
  GetToolBar()->AddTool(wxID_SAVE);

#ifdef __WXGTK__
  GetToolBar()->AddTool(wxID_EXECUTE);
#endif

  GetToolBar()->Realize();
  GetManager().AddPane(m_Shell,
    wxAuiPaneInfo().
      Name("CONSOLE").
      CenterPane());

  GetManager().AddPane(m_Results,
    wxAuiPaneInfo().
      Name("RESULTS").
      Caption(_("Results")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Query,
    wxAuiPaneInfo().
      Name("QUERY").
      Caption(_("Query")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Statistics.Show(this),
    wxAuiPaneInfo().Left().
      MaximizeButton(true).
      Caption(_("Statistics")).
      Name("STATISTICS"));

  GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
  GetManager().GetPane("QUERY").Show(false);

  GetManager().Update();
}

void Frame::OnCommandConfigDialog(
  wxWindowID dialogid,
  int /* commandid */)
{
  if (dialogid == wxID_PREFERENCES)
  {
    m_Query->ConfigGet();
  }
  else
  {
    wxFAIL;
  }
}

wxExGrid* Frame::GetGrid()
{
  if (m_Results->IsShown())
  {
    return m_Results;
  }
  else
  {
    const wxExGrid* grid = m_Statistics.GetGrid();

    if (grid != NULL && grid->IsShown())
    {
      return (wxExGrid*)grid;
    }
    else
    {
      return NULL;
    }
  }
}

wxExSTCFile* Frame::GetSTC()
{
  if (m_Query->IsShown())
  {
    return m_Query;
  }

  return NULL;
}

void Frame::OnClose(wxCloseEvent& event)
{
  wxExFileDialog dlg(this, m_Query);

  if (dlg.ShowModalIfChanged()  == wxID_CANCEL)
  {
    return;
  }

  wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());

  event.Skip();
}

void Frame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
  case wxID_ABOUT:
    {
    wxAboutDialogInfo info;
    info.SetIcon(GetIcon());
    info.SetDescription(_("This program offers a general ODBC query."));
    info.SetVersion("v1.0.1");
    info.SetCopyright("(c) 2008-2010, Anton van Wezenbeek");
    info.AddDeveloper(wxVERSION_STRING);
    info.AddDeveloper(wxEX_VERSION_STRING);
    info.AddDeveloper(wxExOTL::Version());
    wxAboutBox(info);
    }
    break;

  case wxID_EXECUTE:
    m_Stopped = false;
    RunQueries(m_Query->GetText());
    break;

  case wxID_EXIT:
    Close(true);
    break;

  case wxID_NEW:
    m_Query->FileNew(wxEmptyString);
    m_Query->SetLexer("sql");
    m_Query->SetFocus();
    GetManager().GetPane("QUERY").Show();
    GetManager().Update();
    break;

  case wxID_OPEN:
    wxExOpenFilesDialog(
      this,
      wxFD_OPEN | wxFD_CHANGE_DIR,
      "sql files (*.sql) | *.sql",
      true);
    break;

  case wxID_PREFERENCES:
    event.Skip();
    break;

  case wxID_SAVE:
    m_Query->FileSave();
    break;

  case wxID_SAVEAS:
    {
      wxExFileDialog dlg(
        this, m_Query,
        _("File Save As"),
        wxFileSelectorDefaultWildcardStr,
        wxFD_SAVE);

      if (dlg.ShowModal() == wxID_OK)
      {
         m_Query->FileSave(dlg.GetPath());
      }
    }
    break;

  case wxID_STOP:
    m_Running = false;
    m_Stopped = true;
    break;

  case ID_DATABASE_CLOSE:
    m_otl.Logoff();
    m_Shell->SetPrompt(">");
    break;

  case ID_DATABASE_OPEN:
    m_otl.Logon(this);
    m_Shell->SetPrompt(
      (m_otl.IsConnected() ? wxConfigBase::Get()->Read(_("Datasource")): "") + ">");
    break;

  case ID_SHELL_COMMAND:
    if (m_otl.IsConnected())
    {
      try
      {
        const wxString query = event.GetString().substr(
          0,
          event.GetString().length() - 1);

        m_Stopped = false;
        RunQuery(query, true);
      }
      catch (otl_exception& p)
      {
        if (m_Results->IsShown())
        {
          m_Results->EndBatch();
        }

        m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
      }
    }
    else
    {
      m_Shell->AppendText(_("\nnot connected"));
    }

    m_Shell->Prompt();
    break;

  case ID_SHELL_COMMAND_STOP:
    m_Stopped = true;
    m_Shell->Prompt(_("cancelled"));
    break;

  case ID_VIEW_QUERY: TogglePane("QUERY"); break;
  case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
  case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;

  default:
    wxFAIL;
  }
}

void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
  case wxID_EXECUTE:
    // If we have a query, you can hide it, but still run it.
    event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
    break;

  case wxID_SAVE:
    event.Enable(m_Query->GetModify());
    break;

  case wxID_SAVEAS:
    event.Enable(m_Query->GetLength() > 0);
    break;

  case wxID_STOP:
    event.Enable(m_Running);
    break;

  case ID_DATABASE_CLOSE:
    event.Enable(m_otl.IsConnected());
    break;

  case ID_DATABASE_OPEN:
    event.Enable(!m_otl.IsConnected());
    break;

  case ID_RECENTFILE_MENU:
    event.Enable(!GetRecentFile().empty());
    break;

  case ID_VIEW_QUERY:
    event.Check(GetManager().GetPane("QUERY").IsShown());
    break;

  case ID_VIEW_RESULTS:
    event.Check(GetManager().GetPane("RESULTS").IsShown());
    break;

  case ID_VIEW_STATISTICS:
    event.Check(GetManager().GetPane("STATISTICS").IsShown());
    break;

  default:
    wxFAIL;
  }
}

bool Frame::OpenFile(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  GetManager().GetPane("QUERY").Show(true);
  GetManager().Update();

  return m_Query->Open(filename, line_number, match, flags);
}

void Frame::RunQuery(const wxString& query, bool empty_results)
{
  wxStopWatch sw;

  const wxString query_lower = query.Lower();

  // Query functions supported by ODBC
  // $SQLTables, $SQLColumns, etc.
  // $SQLTables $1:'%'
  // allow you to get database schema.
  if (query_lower.StartsWith("select") ||
      query_lower.StartsWith("describe") ||
      query_lower.StartsWith("show") ||
      query_lower.StartsWith("explain") ||
      query_lower.StartsWith("$sql"))
  {
    long rpc;

    if (m_Results->IsShown())
    {
      rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
    }
    else
    {
      rpc = m_otl.Query(query, m_Shell, m_Stopped);
    }

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }
  else
  {
    const long rpc = m_otl.Query(query);

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }

  m_Shell->DocumentEnd();
}

void Frame::RunQueries(const wxString& text)
{
  if (m_Results->IsShown())
  {
    m_Results->ClearGrid();
  }

  // Skip sql comments.
  wxString output = text;
  wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");

  // Queries are seperated by ; character.
  wxStringTokenizer tkz(output, ";");
  int no_queries = 0;

  wxStopWatch sw;
  m_Running = true;

  // Run all queries.
  while (tkz.HasMoreTokens() && !m_Stopped)
  {
    wxString query = tkz.GetNextToken();
    query.Trim(true);
    query.Trim(false);

    if (!query.empty())
    {
      try
      {
        RunQuery(query, no_queries == 0);
        no_queries++;
      }
      catch (otl_exception& p)
      {
        m_Statistics.Inc(_("Number of query errors"));
        m_Shell->AppendText(
          _("\nerror: ") +  wxExQuoted(p.msg) +
          _(" in: ") + wxExQuoted(query));
      }
    }
  }

  m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
    no_queries,
    (float)sw.Time() / (float)1000));

  m_Running = false;
}

void Frame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
  m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
    rpc,
    (float)sw.Time() / (float)1000));

  m_Statistics.Set(_("Rows processed"), rpc);
  m_Statistics.Set(_("Query runtime"), sw.Time());

  m_Statistics.Inc(_("Total number of queries run"));
  m_Statistics.Inc(_("Total query runtime"), sw.Time());
  m_Statistics.Inc(_("Total rows processed"), rpc);
}
<commit_msg>added findbar and use common toolbar<commit_after>/******************************************************************************\
* File:          app.cpp
* Purpose:       Implementation of classes for syncodbcquery
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 2008-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/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/aboutdlg.h>
#include <wx/config.h>
#include <wx/regex.h>
#include <wx/stockitem.h>
#include <wx/tokenzr.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/grid.h>
#include <wx/extension/shell.h>
#include <wx/extension/toolbar.h>
#include <wx/extension/util.h>
#include <wx/extension/version.h>
#include <wx/extension/report/defs.h>
#include <wx/extension/report/stc.h>
#include <wx/extension/report/util.h>
#include "app.h"

#ifndef __WXMSW__
#include "app.xpm"
#endif

IMPLEMENT_APP(App)

bool App::OnInit()
{
  SetAppName("syncodbcquery");

  if (!wxExApp::OnInit())
  {
    return false;
  }

  Frame *frame = new Frame();
  frame->Show(true);

  SetTopWindow(frame);

  return true;
}

BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
  EVT_CLOSE(Frame::OnClose)
  EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
  EVT_MENU(wxID_STOP, Frame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND, Frame::OnCommand)
  EVT_MENU(ID_SHELL_COMMAND_STOP, Frame::OnCommand)
  EVT_MENU_RANGE(wxID_CUT, wxID_CLEAR, Frame::OnCommand)
  EVT_MENU_RANGE(wxID_OPEN, wxID_PREFERENCES, Frame::OnCommand)
  EVT_MENU_RANGE(ID_FIRST, ID_LAST, Frame::OnCommand)
  EVT_UPDATE_UI(wxID_SAVE, Frame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_SAVEAS, Frame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_STOP, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_CLOSE, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_DATABASE_OPEN, Frame::OnUpdateUI)
  EVT_UPDATE_UI(wxID_EXECUTE, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_RECENTFILE_MENU, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_QUERY, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_RESULTS, Frame::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_STATISTICS, Frame::OnUpdateUI)
END_EVENT_TABLE()

Frame::Frame()
  : wxExFrameWithHistory(NULL, wxID_ANY, wxTheApp->GetAppName())
  , m_Running(false)
  , m_Stopped(false)
{
  SetIcon(wxICON(app));

  wxExMenu* menuFile = new wxExMenu;
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENTFILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu* menuDatabase = new wxExMenu;
  menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open")));
  menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close"));

  wxExMenu* menuQuery = new wxExMenu;
  menuQuery->Append(wxID_EXECUTE);
  menuQuery->Append(wxID_STOP);

  wxMenu* menuOptions = new wxMenu();
  menuOptions->Append(wxID_PREFERENCES);

  wxMenu* menuView = new wxMenu();
  menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar"));
  menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query"));
  menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results"));
  menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics"));

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

  wxMenuBar *menubar = new wxMenuBar;
  menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuDatabase, _("&Connection"));
  menubar->Append(menuQuery, _("&Query"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
  SetMenuBar(menubar);

  m_Query = new wxExSTCWithFrame(this, this);
  m_Query->SetLexer("sql");

  m_Results = new wxExGrid(this);
  m_Results->CreateGrid(0, 0);
  m_Results->EnableEditing(false); // this is a read-only grid

  m_Shell = new wxExSTCShell(this, ">", ";", true, 50);
  m_Shell->SetFocus();

#if wxUSE_STATUSBAR
  std::vector<wxExPane> panes;
  panes.push_back(wxExPane("PaneText", -3));
  panes.push_back(wxExPane("PaneLines", 100, _("Lines in window")));
  SetupStatusBar(panes);
#endif

  CreateToolBar();
  CreateFindBar();

  GetManager().AddPane(m_Shell,
    wxAuiPaneInfo().
      Name("CONSOLE").
      CenterPane());

  GetManager().AddPane(m_Results,
    wxAuiPaneInfo().
      Name("RESULTS").
      Caption(_("Results")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Query,
    wxAuiPaneInfo().
      Name("QUERY").
      Caption(_("Query")).
      CloseButton(true).
      MaximizeButton(true));

  GetManager().AddPane(m_Statistics.Show(this),
    wxAuiPaneInfo().Left().
      MaximizeButton(true).
      Caption(_("Statistics")).
      Name("STATISTICS"));

  GetManager().LoadPerspective(wxConfigBase::Get()->Read("Perspective"));
  GetManager().GetPane("QUERY").Show(false);

  GetManager().Update();
}

void Frame::OnCommandConfigDialog(
  wxWindowID dialogid,
  int /* commandid */)
{
  if (dialogid == wxID_PREFERENCES)
  {
    m_Query->ConfigGet();
  }
  else
  {
    wxFAIL;
  }
}

wxExGrid* Frame::GetGrid()
{
  if (m_Results->IsShown())
  {
    return m_Results;
  }
  else
  {
    const wxExGrid* grid = m_Statistics.GetGrid();

    if (grid != NULL && grid->IsShown())
    {
      return (wxExGrid*)grid;
    }
    else
    {
      return NULL;
    }
  }
}

wxExSTCFile* Frame::GetSTC()
{
  if (m_Query->IsShown())
  {
    return m_Query;
  }

  return NULL;
}

void Frame::OnClose(wxCloseEvent& event)
{
  wxExFileDialog dlg(this, m_Query);

  if (dlg.ShowModalIfChanged()  == wxID_CANCEL)
  {
    return;
  }

  wxConfigBase::Get()->Write("Perspective", GetManager().SavePerspective());

  event.Skip();
}

void Frame::OnCommand(wxCommandEvent& event)
{
  switch (event.GetId())
  {
  case wxID_ABOUT:
    {
    wxAboutDialogInfo info;
    info.SetIcon(GetIcon());
    info.SetDescription(_("This program offers a general ODBC query."));
    info.SetVersion("v1.0.1");
    info.SetCopyright("(c) 2008-2010, Anton van Wezenbeek");
    info.AddDeveloper(wxVERSION_STRING);
    info.AddDeveloper(wxEX_VERSION_STRING);
    info.AddDeveloper(wxExOTL::Version());
    wxAboutBox(info);
    }
    break;

  case wxID_EXECUTE:
    m_Stopped = false;
    RunQueries(m_Query->GetText());
    break;

  case wxID_EXIT:
    Close(true);
    break;

  case wxID_NEW:
    m_Query->FileNew(wxEmptyString);
    m_Query->SetLexer("sql");
    m_Query->SetFocus();
    GetManager().GetPane("QUERY").Show();
    GetManager().Update();
    break;

  case wxID_OPEN:
    wxExOpenFilesDialog(
      this,
      wxFD_OPEN | wxFD_CHANGE_DIR,
      "sql files (*.sql) | *.sql",
      true);
    break;

  case wxID_PREFERENCES:
    event.Skip();
    break;

  case wxID_SAVE:
    m_Query->FileSave();
    break;

  case wxID_SAVEAS:
    {
      wxExFileDialog dlg(
        this, m_Query,
        _("File Save As"),
        wxFileSelectorDefaultWildcardStr,
        wxFD_SAVE);

      if (dlg.ShowModal() == wxID_OK)
      {
         m_Query->FileSave(dlg.GetPath());
      }
    }
    break;

  case wxID_STOP:
    m_Running = false;
    m_Stopped = true;
    break;

  case ID_DATABASE_CLOSE:
    m_otl.Logoff();
    m_Shell->SetPrompt(">");
    break;

  case ID_DATABASE_OPEN:
    m_otl.Logon(this);
    m_Shell->SetPrompt(
      (m_otl.IsConnected() ? wxConfigBase::Get()->Read(_("Datasource")): "") + ">");
    break;

  case ID_SHELL_COMMAND:
    if (m_otl.IsConnected())
    {
      try
      {
        const wxString query = event.GetString().substr(
          0,
          event.GetString().length() - 1);

        m_Stopped = false;
        RunQuery(query, true);
      }
      catch (otl_exception& p)
      {
        if (m_Results->IsShown())
        {
          m_Results->EndBatch();
        }

        m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg));
      }
    }
    else
    {
      m_Shell->AppendText(_("\nnot connected"));
    }

    m_Shell->Prompt();
    break;

  case ID_SHELL_COMMAND_STOP:
    m_Stopped = true;
    m_Shell->Prompt(_("cancelled"));
    break;

  case ID_VIEW_QUERY: TogglePane("QUERY"); break;
  case ID_VIEW_RESULTS: TogglePane("RESULTS"); break;
  case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break;

  default:
    wxFAIL;
  }
}

void Frame::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
  case wxID_EXECUTE:
    // If we have a query, you can hide it, but still run it.
    event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected());
    break;

  case wxID_SAVE:
    event.Enable(m_Query->GetModify());
    break;

  case wxID_SAVEAS:
    event.Enable(m_Query->GetLength() > 0);
    break;

  case wxID_STOP:
    event.Enable(m_Running);
    break;

  case ID_DATABASE_CLOSE:
    event.Enable(m_otl.IsConnected());
    break;

  case ID_DATABASE_OPEN:
    event.Enable(!m_otl.IsConnected());
    break;

  case ID_RECENTFILE_MENU:
    event.Enable(!GetRecentFile().empty());
    break;

  case ID_VIEW_QUERY:
    event.Check(GetManager().GetPane("QUERY").IsShown());
    break;

  case ID_VIEW_RESULTS:
    event.Check(GetManager().GetPane("RESULTS").IsShown());
    break;

  case ID_VIEW_STATISTICS:
    event.Check(GetManager().GetPane("STATISTICS").IsShown());
    break;

  default:
    wxFAIL;
  }
}

bool Frame::OpenFile(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  GetManager().GetPane("QUERY").Show(true);
  GetManager().Update();

  return m_Query->Open(filename, line_number, match, flags);
}

void Frame::RunQuery(const wxString& query, bool empty_results)
{
  wxStopWatch sw;

  const wxString query_lower = query.Lower();

  // Query functions supported by ODBC
  // $SQLTables, $SQLColumns, etc.
  // $SQLTables $1:'%'
  // allow you to get database schema.
  if (query_lower.StartsWith("select") ||
      query_lower.StartsWith("describe") ||
      query_lower.StartsWith("show") ||
      query_lower.StartsWith("explain") ||
      query_lower.StartsWith("$sql"))
  {
    long rpc;

    if (m_Results->IsShown())
    {
      rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results);
    }
    else
    {
      rpc = m_otl.Query(query, m_Shell, m_Stopped);
    }

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }
  else
  {
    const long rpc = m_otl.Query(query);

    sw.Pause();

    UpdateStatistics(sw, rpc);
  }

  m_Shell->DocumentEnd();
}

void Frame::RunQueries(const wxString& text)
{
  if (m_Results->IsShown())
  {
    m_Results->ClearGrid();
  }

  // Skip sql comments.
  wxString output = text;
  wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, "");

  // Queries are seperated by ; character.
  wxStringTokenizer tkz(output, ";");
  int no_queries = 0;

  wxStopWatch sw;
  m_Running = true;

  // Run all queries.
  while (tkz.HasMoreTokens() && !m_Stopped)
  {
    wxString query = tkz.GetNextToken();
    query.Trim(true);
    query.Trim(false);

    if (!query.empty())
    {
      try
      {
        RunQuery(query, no_queries == 0);
        no_queries++;
      }
      catch (otl_exception& p)
      {
        m_Statistics.Inc(_("Number of query errors"));
        m_Shell->AppendText(
          _("\nerror: ") +  wxExQuoted(p.msg) +
          _(" in: ") + wxExQuoted(query));
      }
    }
  }

  m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"),
    no_queries,
    (float)sw.Time() / (float)1000));

  m_Running = false;
}

void Frame::UpdateStatistics(const wxStopWatch& sw, long rpc)
{
  m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
    rpc,
    (float)sw.Time() / (float)1000));

  m_Statistics.Set(_("Rows processed"), rpc);
  m_Statistics.Set(_("Query runtime"), sw.Time());

  m_Statistics.Inc(_("Total number of queries run"));
  m_Statistics.Inc(_("Total query runtime"), sw.Time());
  m_Statistics.Inc(_("Total rows processed"), rpc);
}
<|endoftext|>


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

#include "content/renderer/gpu/gpu_benchmarking_extension.h"
#include "content/renderer/render_view_impl.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebRenderingStats.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "v8/include/v8.h"

using WebKit::WebFrame;
using WebKit::WebRenderingStats;
using WebKit::WebView;

const char kGpuBenchmarkingExtensionName[] = "v8/GpuBenchmarking";

using WebKit::WebFrame;
using WebKit::WebView;

namespace content {

class GpuBenchmarkingWrapper : public v8::Extension {
 public:
  GpuBenchmarkingWrapper() :
      v8::Extension(kGpuBenchmarkingExtensionName,
          "if (typeof(chrome) == 'undefined') {"
          "  chrome = {};"
          "};"
          "if (typeof(chrome.gpuBenchmarking) == 'undefined') {"
          "  chrome.gpuBenchmarking = {};"
          "};"
          "chrome.gpuBenchmarking.renderingStats = function() {"
          "  native function GetRenderingStats();"
          "  return GetRenderingStats();"
          "};"
          "chrome.gpuBenchmarking.beginSmoothScrollDown = "
          "    function(scroll_far) {"
          "  scroll_far = scroll_far || false;"
          "  native function BeginSmoothScroll();"
          "  return BeginSmoothScroll(true, scroll_far);"
          "};"
          "chrome.gpuBenchmarking.beginSmoothScrollUp = function(scroll_far) {"
          "  scroll_far = scroll_far || false;"
          "  native function BeginSmoothScroll();"
          "  return BeginSmoothScroll(false, scroll_far);"
          "};") {}

  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
      v8::Handle<v8::String> name) {
    if (name->Equals(v8::String::New("GetRenderingStats")))
      return v8::FunctionTemplate::New(GetRenderingStats);
    if (name->Equals(v8::String::New("BeginSmoothScroll")))
      return v8::FunctionTemplate::New(BeginSmoothScroll);

    return v8::Handle<v8::FunctionTemplate>();
  }

  static v8::Handle<v8::Value> GetRenderingStats(const v8::Arguments& args) {
    WebFrame* web_frame = WebFrame::frameForEnteredContext();
    if (!web_frame)
      return v8::Undefined();

    WebView* web_view = web_frame->view();
    if (!web_view)
      return v8::Undefined();

    WebRenderingStats stats;
    web_view->renderingStats(stats);

    v8::Handle<v8::Object> stats_object = v8::Object::New();
    if (stats.numAnimationFrames)
      stats_object->Set(v8::String::New("numAnimationFrames"),
                        v8::Integer::New(stats.numAnimationFrames),
                        v8::ReadOnly);
    if (stats.numFramesSentToScreen)
      stats_object->Set(v8::String::New("numFramesSentToScreen"),
                        v8::Integer::New(stats.numFramesSentToScreen),
                        v8::ReadOnly);
    return stats_object;
  }

  static v8::Handle<v8::Value> BeginSmoothScroll(const v8::Arguments& args) {
    WebFrame* web_frame = WebFrame::frameForEnteredContext();
    if (!web_frame)
      return v8::Undefined();

    WebView* web_view = web_frame->view();
    if (!web_view)
      return v8::Undefined();

    RenderViewImpl* render_view_impl = RenderViewImpl::FromWebView(web_view);
    if (!render_view_impl)
      return v8::Undefined();

    if (args.Length() != 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
      return v8::False();

    bool scroll_down = args[0]->BooleanValue();
    bool scroll_far = args[1]->BooleanValue();

    render_view_impl->BeginSmoothScroll(scroll_down, scroll_far);
    return v8::True();
  }
};

v8::Extension* GpuBenchmarkingExtension::Get() {
  return new GpuBenchmarkingWrapper();
}

}  // namespace content
<commit_msg>Add new fields to GPU benchmarking API.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/renderer/gpu/gpu_benchmarking_extension.h"
#include "content/renderer/render_view_impl.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebRenderingStats.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "v8/include/v8.h"

using WebKit::WebFrame;
using WebKit::WebRenderingStats;
using WebKit::WebView;

const char kGpuBenchmarkingExtensionName[] = "v8/GpuBenchmarking";

using WebKit::WebFrame;
using WebKit::WebView;

namespace content {

class GpuBenchmarkingWrapper : public v8::Extension {
 public:
  GpuBenchmarkingWrapper() :
      v8::Extension(kGpuBenchmarkingExtensionName,
          "if (typeof(chrome) == 'undefined') {"
          "  chrome = {};"
          "};"
          "if (typeof(chrome.gpuBenchmarking) == 'undefined') {"
          "  chrome.gpuBenchmarking = {};"
          "};"
          "chrome.gpuBenchmarking.renderingStats = function() {"
          "  native function GetRenderingStats();"
          "  return GetRenderingStats();"
          "};"
          "chrome.gpuBenchmarking.beginSmoothScrollDown = "
          "    function(scroll_far) {"
          "  scroll_far = scroll_far || false;"
          "  native function BeginSmoothScroll();"
          "  return BeginSmoothScroll(true, scroll_far);"
          "};"
          "chrome.gpuBenchmarking.beginSmoothScrollUp = function(scroll_far) {"
          "  scroll_far = scroll_far || false;"
          "  native function BeginSmoothScroll();"
          "  return BeginSmoothScroll(false, scroll_far);"
          "};") {}

  virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(
      v8::Handle<v8::String> name) {
    if (name->Equals(v8::String::New("GetRenderingStats")))
      return v8::FunctionTemplate::New(GetRenderingStats);
    if (name->Equals(v8::String::New("BeginSmoothScroll")))
      return v8::FunctionTemplate::New(BeginSmoothScroll);

    return v8::Handle<v8::FunctionTemplate>();
  }

  static v8::Handle<v8::Value> GetRenderingStats(const v8::Arguments& args) {
    WebFrame* web_frame = WebFrame::frameForEnteredContext();
    if (!web_frame)
      return v8::Undefined();

    WebView* web_view = web_frame->view();
    if (!web_view)
      return v8::Undefined();

    WebRenderingStats stats;
    web_view->renderingStats(stats);

    v8::Handle<v8::Object> stats_object = v8::Object::New();
    if (stats.numAnimationFrames)
      stats_object->Set(v8::String::New("numAnimationFrames"),
                        v8::Integer::New(stats.numAnimationFrames),
                        v8::ReadOnly);
    if (stats.numFramesSentToScreen)
      stats_object->Set(v8::String::New("numFramesSentToScreen"),
                        v8::Integer::New(stats.numFramesSentToScreen),
                        v8::ReadOnly);
    if (stats.droppedFrameCount)
      stats_object->Set(v8::String::New("droppedFrameCount"),
                        v8::Integer::New(stats.droppedFrameCount),
                        v8::ReadOnly);
    if (stats.totalPaintTimeInSeconds)
      stats_object->Set(v8::String::New("totalPaintTimeInSeconds"),
                        v8::Number::New(stats.totalPaintTimeInSeconds),
                        v8::ReadOnly);
    if (stats.totalRasterizeTimeInSeconds)
      stats_object->Set(v8::String::New("totalRasterizeTimeInSeconds"),
                        v8::Number::New(stats.totalRasterizeTimeInSeconds),
                        v8::ReadOnly);
    return stats_object;
  }

  static v8::Handle<v8::Value> BeginSmoothScroll(const v8::Arguments& args) {
    WebFrame* web_frame = WebFrame::frameForEnteredContext();
    if (!web_frame)
      return v8::Undefined();

    WebView* web_view = web_frame->view();
    if (!web_view)
      return v8::Undefined();

    RenderViewImpl* render_view_impl = RenderViewImpl::FromWebView(web_view);
    if (!render_view_impl)
      return v8::Undefined();

    if (args.Length() != 2 || !args[0]->IsBoolean() || !args[1]->IsBoolean())
      return v8::False();

    bool scroll_down = args[0]->BooleanValue();
    bool scroll_far = args[1]->BooleanValue();

    render_view_impl->BeginSmoothScroll(scroll_down, scroll_far);
    return v8::True();
  }
};

v8::Extension* GpuBenchmarkingExtension::Get() {
  return new GpuBenchmarkingWrapper();
}

}  // namespace content
<|endoftext|>


<commit_before>/*

  Unit testing for the TGInputDialog class. It easily shows how to use
  it.

  To compile and run :
  g++ -g `root-config --cflags --libs` -lGui testInputDialog.C -o testInputDialog
  ./testInputDialog

  It can also be loaded with root:
  root testInputDialog.C

*/

#include "TGInputDialog.h"
#include "TGClient.h"
#include "Riostream.h"
#include <TApplication.h>

void testDefaultConstructor() {
   new TGInputDialog();
}

void testMinimumConstructor() {
   new TGInputDialog( gClient->GetRoot() );
}

void testFourConstructor() {
   new TGInputDialog( gClient->GetRoot(), 0, "Prompt:", "Default value" );
}

void testDefaultReturn() {
   char* retstr = 0;
   new TGInputDialog( gClient->GetRoot(), 0, "Prompt:", "Default value", retstr );
   if ( retstr ) cout << "Returned: " << retstr << endl;
   if ( retstr ) delete retstr;
}

void testReturn() {
   char retstr[256];
   new TGInputDialog( gClient->GetRoot(), 0, "Prompt:", "Default value", retstr );
   cout << "Returned: " << retstr << endl;
}

void testInputDialog ()
{
   testDefaultConstructor();
   testMinimumConstructor();
   testFourConstructor();
   testDefaultReturn();
   testReturn();
}

int main(int argc, char** argv)
{

   TApplication* theApp = new TApplication("App",&argc,argv);

   testInputDialog();

   theApp->Run();
   delete theApp;

   return 0;
}

<commit_msg>remove tutorials added by mistake from dev branch (it is not really needed)<commit_after><|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	cursor.cxx
 *
 *   DESCRIPTION
 *      implementation of the pqxx::Cursor class.
 *   pqxx::Cursor represents a database cursor.
 *
 * Copyright (c) 2001-2003, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/cursor.h"
#include "pqxx/result.h"
#include "pqxx/transaction.h"

using namespace PGSTD;

pqxx::Cursor::Cursor(pqxx::TransactionItf &T,
		     const char Query[],
		     const string &BaseName,
		     size_type Count) :
  m_Trans(T),
  m_Name(BaseName),
  m_Count(Count),
  m_Done(false),
  m_Pos(pos_start),
  m_Size(pos_unknown)
{
  // Give ourselves a locally unique name based on connection name
  m_Name += "_" + T.Name() + "_" + ToString(T.GetUniqueCursorNum());

  m_Trans.Exec(("DECLARE \"" + m_Name + "\" CURSOR FOR " + Query).c_str());
}

pqxx::Cursor::size_type pqxx::Cursor::SetCount(size_type Count)
{
  size_type Old = m_Count;
  m_Done = false;
  m_Count = Count;
  return Old;
}

pqxx::Cursor &pqxx::Cursor::operator>>(pqxx::Result &R)
{
  R = Fetch(m_Count);
  m_Done = R.empty();
  return *this;
}

pqxx::Result pqxx::Cursor::Fetch(size_type Count)
{
  Result R;

  if (!Count)
  {
    m_Trans.MakeEmpty(R);
    return R;
  }

  const string Cmd( MakeFetchCmd(Count) );

  try
  {
    R = m_Trans.Exec(Cmd.c_str());
  }
  catch (const exception &)
  {
    m_Pos = pos_unknown;
    throw;
  }

  NormalizedMove(Count, R.size());

  return R;
}

pqxx::Result::size_type pqxx::Cursor::Move(size_type Count)
{
  if (!Count) return 0;
  if ((Count < 0) && (m_Pos == pos_start)) return 0;

  m_Done = false;
  const string Cmd( "MOVE " + OffsetString(Count) + " IN \"" + m_Name + "\"");
  long int A = 0;

  try
  {
    Result R( m_Trans.Exec(Cmd.c_str()) );
    if (!sscanf(R.CmdStatus(), "MOVE %ld", &A))
      throw runtime_error("Didn't understand database's reply to MOVE: "
	                    "'" + string(R.CmdStatus()) + "'");
  }
  catch (const exception &)
  {
    m_Pos = pos_unknown;
    throw;
  }

  return NormalizedMove(Count, A);
}

pqxx::Cursor::size_type pqxx::Cursor::NormalizedMove(size_type Intended,
                                                     size_type Actual)
{
  if (Actual < 0)
    throw logic_error("libpqxx internal error: Negative rowcount");
  if (Actual > abs(Intended))
    throw logic_error("libpqxx internal error: Moved/fetched too many rows "
	              "(wanted " + ToString(Intended) + ", "
		      "got " + ToString(Actual) + ")");

  size_type Offset = Actual;

  if (Actual < abs(Intended))
  {
    // There is a nonexistant row before the first one in the result set, and
    // one after the last row, where we may be positioned.  Unfortunately
    // PostgreSQL only reports "real" rows, making it really hard to figure out
    // how many rows we've really moved.
    if (Actual)
    {
      // We've moved off either edge of our result set; add the one,
      // nonexistant row that wasn't counted in the status string we got.
      Offset++;
    }
    else if (Intended < 0)
    {
      // We've either moved off the "left" edge of our result set from the
      // first actual row, or we were on the nonexistant row before the first
      // actual row and so didn't move at all.  Just set up Actual so that we
      // end up at our starting position, which is where we must be.
      Offset = m_Pos - pos_start;
    }
    else if (m_Size != pos_unknown)
    {
      // We either just walked off the right edge (moving at least one row in
      // the process), or had done so already (in which case we haven't moved).
      Offset = (m_Size + pos_start + 1) - m_Pos;
    }
    else
    {
      // This is the hard one.  Assume that we haven't seen the "right edge"
      // before, because m_Size hasn't been set yet.  Therefore, we must have
      // just stepped off the edge (and m_Size will be set now).
      Offset++;
    }

    if ((Offset > abs(Intended)) && (m_Pos != pos_unknown))
      throw logic_error("libpqxx internal error: Confused cursor position");
  }

  if (Intended < 0) Offset = -Offset;
  m_Pos += Offset;

  if ((Intended > 0) && (Actual < Intended) && (m_Size == pos_unknown))
    m_Size = m_Pos - pos_start - 1;

  m_Done = !Actual;

  return Offset;
}

void pqxx::Cursor::MoveTo(size_type Dest)
{
  // If we don't know where we are, go back to the beginning first.
  if (m_Pos == pos_unknown) Move(BACKWARD_ALL());

  Move(Dest - Pos());
}

string pqxx::Cursor::OffsetString(size_type Count)
{
  if (Count == ALL()) return "ALL";
  else if (Count == BACKWARD_ALL()) return "BACKWARD ALL";

  return ToString(Count);
}

string pqxx::Cursor::MakeFetchCmd(size_type Count) const
{
  return "FETCH " + OffsetString(Count) + " IN \"" + m_Name + "\"";
}

<commit_msg>Handle nasty special case<commit_after>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	cursor.cxx
 *
 *   DESCRIPTION
 *      implementation of the pqxx::Cursor class.
 *   pqxx::Cursor represents a database cursor.
 *
 * Copyright (c) 2001-2003, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/cursor.h"
#include "pqxx/result.h"
#include "pqxx/transaction.h"

using namespace PGSTD;

pqxx::Cursor::Cursor(pqxx::TransactionItf &T,
		     const char Query[],
		     const string &BaseName,
		     size_type Count) :
  m_Trans(T),
  m_Name(BaseName),
  m_Count(Count),
  m_Done(false),
  m_Pos(pos_start),
  m_Size(pos_unknown)
{
  // Give ourselves a locally unique name based on connection name
  m_Name += "_" + T.Name() + "_" + ToString(T.GetUniqueCursorNum());

  m_Trans.Exec(("DECLARE \"" + m_Name + "\" CURSOR FOR " + Query).c_str());
}

pqxx::Cursor::size_type pqxx::Cursor::SetCount(size_type Count)
{
  size_type Old = m_Count;
  m_Done = false;
  m_Count = Count;
  return Old;
}

pqxx::Cursor &pqxx::Cursor::operator>>(pqxx::Result &R)
{
  R = Fetch(m_Count);
  m_Done = R.empty();
  return *this;
}

pqxx::Result pqxx::Cursor::Fetch(size_type Count)
{
  Result R;

  if (!Count)
  {
    m_Trans.MakeEmpty(R);
    return R;
  }

  const string Cmd( MakeFetchCmd(Count) );

  try
  {
    R = m_Trans.Exec(Cmd.c_str());
  }
  catch (const exception &)
  {
    m_Pos = pos_unknown;
    throw;
  }

  NormalizedMove(Count, R.size());

  return R;
}

pqxx::Result::size_type pqxx::Cursor::Move(size_type Count)
{
  if (!Count) return 0;
  if ((Count < 0) && (m_Pos == pos_start)) return 0;

  m_Done = false;
  const string Cmd( "MOVE " + OffsetString(Count) + " IN \"" + m_Name + "\"");
  long int A = 0;

  try
  {
    Result R( m_Trans.Exec(Cmd.c_str()) );
    if (!sscanf(R.CmdStatus(), "MOVE %ld", &A))
      throw runtime_error("Didn't understand database's reply to MOVE: "
	                    "'" + string(R.CmdStatus()) + "'");
  }
  catch (const exception &)
  {
    m_Pos = pos_unknown;
    throw;
  }

  return NormalizedMove(Count, A);
}

pqxx::Cursor::size_type pqxx::Cursor::NormalizedMove(size_type Intended,
                                                     size_type Actual)
{
  if (Actual < 0)
    throw logic_error("libpqxx internal error: Negative rowcount");
  if (Actual > abs(Intended))
    throw logic_error("libpqxx internal error: Moved/fetched too many rows "
	              "(wanted " + ToString(Intended) + ", "
		      "got " + ToString(Actual) + ")");

  size_type Offset = Actual;

  if (m_Pos == pos_unknown)
  {
    if (Actual < abs(Intended))
    {
      if (Intended < 0)
      {
	// Must have gone back to starting position
	m_Pos = pos_start;
      }
      else if (m_Size == pos_unknown)
      {
	// Oops.  We'd want to set result set size at this point, but we can't
	// because we don't know our position.
	// TODO: Deal with this more elegantly.
	throw runtime_error("Can't determine result set size: "
	                    "Cursor position unknown at end of set");
      }
    }
    // Nothing more we can do to update our position
    return (Intended > 0) ? Actual : -Actual;
  }

  if (Actual < abs(Intended))
  {
    // There is a nonexistant row before the first one in the result set, and
    // one after the last row, where we may be positioned.  Unfortunately
    // PostgreSQL only reports "real" rows, making it really hard to figure out
    // how many rows we've really moved.
    if (Actual)
    {
      // We've moved off either edge of our result set; add the one,
      // nonexistant row that wasn't counted in the status string we got.
      Offset++;
    }
    else if (Intended < 0)
    {
      // We've either moved off the "left" edge of our result set from the
      // first actual row, or we were on the nonexistant row before the first
      // actual row and so didn't move at all.  Just set up Actual so that we
      // end up at our starting position, which is where we must be.
      Offset = m_Pos - pos_start;
    }
    else if (m_Size != pos_unknown)
    {
      // We either just walked off the right edge (moving at least one row in
      // the process), or had done so already (in which case we haven't moved).
      // In the case at hand, we already know where the right-hand edge of the
      // result set is, so we use that to compute our offset.
      Offset = (m_Size + pos_start + 1) - m_Pos;
    }
    else
    {
      // This is the hard one.  Assume that we haven't seen the "right edge"
      // before, because m_Size hasn't been set yet.  Therefore, we must have
      // just stepped off the edge (and m_Size will be set now).
      Offset++;
    }

    if ((Offset > abs(Intended)) && (m_Pos != pos_unknown))
    {
      m_Pos = pos_unknown;
      throw logic_error("libpqxx internal error: Confused cursor position");
    }
  }

  if (Intended < 0) Offset = -Offset;
  m_Pos += Offset;

  if ((Intended > 0) && (Actual < Intended) && (m_Size == pos_unknown))
    m_Size = m_Pos - pos_start - 1;

  m_Done = !Actual;

  return Offset;
}

void pqxx::Cursor::MoveTo(size_type Dest)
{
  // If we don't know where we are, go back to the beginning first.
  if (m_Pos == pos_unknown) Move(BACKWARD_ALL());

  Move(Dest - Pos());
}

string pqxx::Cursor::OffsetString(size_type Count)
{
  if (Count == ALL()) return "ALL";
  else if (Count == BACKWARD_ALL()) return "BACKWARD ALL";

  return ToString(Count);
}

string pqxx::Cursor::MakeFetchCmd(size_type Count) const
{
  return "FETCH " + OffsetString(Count) + " IN \"" + m_Name + "\"";
}

<|endoftext|>


<commit_before>
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#include "Effekseer.Thread.h"

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
namespace Effekseer {

#ifdef _WIN32

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
/* DWORDを置きかえ */
unsigned long EFK_STDCALL Thread::ThreadProc(void* arguments)
{
	Thread* thread = (Thread*)(arguments);

	thread->m_mainProc( thread->m_data );

	thread->m_cs.Enter();

	thread->m_mainProc	= NULL;
	thread->m_data		= NULL;

	::CloseHandle( thread->m_thread );
	thread->m_thread		= NULL;

	thread->m_cs.Leave();

	return 0;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
Thread::Thread()
	: m_data		( NULL )
	, m_thread		( NULL )
	, m_mainProc	( NULL )
{
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
Thread::~Thread()
{
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::Create( void (*threadFunc)( void* ), void* data )
{
	m_cs.Enter();

	if ( m_thread == NULL )
	{
		m_data		= data;
		m_mainProc	= threadFunc;
		m_thread	= ::CreateThread( NULL, 0, ThreadProc, this, CREATE_SUSPENDED, NULL );

		// スレッド開始
		::SetThreadPriority( m_thread, THREAD_PRIORITY_NORMAL );
		::ResumeThread( m_thread );

		m_cs.Leave();
		return true;
	}

	m_cs.Leave();
	return false;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::IsExitThread() const
{
	m_cs.Enter();
	bool ret = m_thread == NULL;
	m_cs.Leave();
	return ret;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::Wait() const
{
	::WaitForSingleObject( m_thread, INFINITE );

	return true;
}

#elif defined(_PSVITA) || defined(_PS4) || defined(_SWITCH) || defined(_XBOXONE)
	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	Thread::Thread()
	{
	}

	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	Thread::~Thread()
	{
	}

	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	bool Thread::Create(void(*threadFunc)(void*), void* data)
	{
		return false;
	}

	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	bool Thread::IsExitThread() const
	{
		return false;
	}

	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	bool Thread::Wait() const
	{
		return false;
	}
#else

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
void* Thread::ThreadProc( void* arguments )
{
	Thread* thread = (Thread*)(arguments);

	thread->m_mainProc( thread->m_data );

	thread->m_cs.Enter();

	thread->m_mainProc	= NULL;
	thread->m_data		= NULL;

	pthread_detach( thread->m_thread );

	thread->m_running	= false;

	thread->m_cs.Leave();

	return 0;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
Thread::Thread()
	: m_thread		()
	, m_running		( false )
	, m_data		( NULL )
	, m_mainProc	( NULL )
{
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
Thread::~Thread()
{
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::Create( void (*threadFunc)( void* ), void* data )
{
	m_cs.Enter();

	if ( !m_running )
	{
		m_data		= data;
		m_mainProc	= threadFunc;

		pthread_attr_t attr;
		pthread_attr_init( &attr );

		// スレッド開始
		m_running = true;
		pthread_create( &m_thread, &attr, ThreadProc, this );

		m_cs.Leave();
		return true;
	}

	m_cs.Leave();
	return false;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::IsExitThread() const
{
	m_cs.Enter();
	bool ret = !m_running;
	m_cs.Leave();
	return ret;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::Wait() const
{
	pthread_join( m_thread, NULL );

	return true;
}
#endif

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
}
<commit_msg>For Switch<commit_after>
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
#include "Effekseer.Thread.h"

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
namespace Effekseer {

#ifdef _WIN32

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
/* DWORDを置きかえ */
unsigned long EFK_STDCALL Thread::ThreadProc(void* arguments)
{
	Thread* thread = (Thread*)(arguments);

	thread->m_mainProc( thread->m_data );

	thread->m_cs.Enter();

	thread->m_mainProc	= NULL;
	thread->m_data		= NULL;

	::CloseHandle( thread->m_thread );
	thread->m_thread		= NULL;

	thread->m_cs.Leave();

	return 0;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
Thread::Thread()
	: m_data		( NULL )
	, m_thread		( NULL )
	, m_mainProc	( NULL )
{
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
Thread::~Thread()
{
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::Create( void (*threadFunc)( void* ), void* data )
{
	m_cs.Enter();

	if ( m_thread == NULL )
	{
		m_data		= data;
		m_mainProc	= threadFunc;
		m_thread	= ::CreateThread( NULL, 0, ThreadProc, this, CREATE_SUSPENDED, NULL );

		// スレッド開始
		::SetThreadPriority( m_thread, THREAD_PRIORITY_NORMAL );
		::ResumeThread( m_thread );

		m_cs.Leave();
		return true;
	}

	m_cs.Leave();
	return false;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::IsExitThread() const
{
	m_cs.Enter();
	bool ret = m_thread == NULL;
	m_cs.Leave();
	return ret;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::Wait() const
{
	::WaitForSingleObject( m_thread, INFINITE );

	return true;
}

#elif defined(_PSVITA) || defined(_PS4) || defined(NN_NINTENDO_SDK) || defined(_XBOXONE)
	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	Thread::Thread()
	{
	}

	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	Thread::~Thread()
	{
	}

	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	bool Thread::Create(void(*threadFunc)(void*), void* data)
	{
		return false;
	}

	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	bool Thread::IsExitThread() const
	{
		return false;
	}

	//-----------------------------------------------------------------------------------
	//
	//-----------------------------------------------------------------------------------
	bool Thread::Wait() const
	{
		return false;
	}
#else

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
void* Thread::ThreadProc( void* arguments )
{
	Thread* thread = (Thread*)(arguments);

	thread->m_mainProc( thread->m_data );

	thread->m_cs.Enter();

	thread->m_mainProc	= NULL;
	thread->m_data		= NULL;

	pthread_detach( thread->m_thread );

	thread->m_running	= false;

	thread->m_cs.Leave();

	return 0;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
Thread::Thread()
	: m_thread		()
	, m_running		( false )
	, m_data		( NULL )
	, m_mainProc	( NULL )
{
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
Thread::~Thread()
{
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::Create( void (*threadFunc)( void* ), void* data )
{
	m_cs.Enter();

	if ( !m_running )
	{
		m_data		= data;
		m_mainProc	= threadFunc;

		pthread_attr_t attr;
		pthread_attr_init( &attr );

		// スレッド開始
		m_running = true;
		pthread_create( &m_thread, &attr, ThreadProc, this );

		m_cs.Leave();
		return true;
	}

	m_cs.Leave();
	return false;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::IsExitThread() const
{
	m_cs.Enter();
	bool ret = !m_running;
	m_cs.Leave();
	return ret;
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
bool Thread::Wait() const
{
	pthread_join( m_thread, NULL );

	return true;
}
#endif

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
}
<|endoftext|>


<commit_before>
/* Chat_subscriber.cxx

A subscription example

This file is derived from code automatically generated by the rtiddsgen
command:

rtiddsgen -language C++ -example <arch> Chat.idl

Example subscription of type My::ChatObject automatically generated by
'rtiddsgen'. To test them follow these steps:

(1) Compile this file and the example publication.

(2) Start the subscription with the command
objs/<arch>/Chat_subscriber <domain_id> <sample_count>

(3) Start the publication with the command
objs/<arch>/Chat_publisher <domain_id> <sample_count>

(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.

You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.

Example:

To run the example application on domain <domain_id>:

On Unix:

objs/<arch>/Chat_publisher <domain_id>
objs/<arch>/Chat_subscriber <domain_id>

On Windows:

objs\<arch>\Chat_publisher <domain_id>
objs\<arch>\Chat_subscriber <domain_id>

*/

#include <stdio.h>
#include <stdlib.h>
#include "Chat.h"
#include "ChatSupport.h"
#include "ndds/ndds_cpp.h"

#include "ndds/ndds_namespace_cpp.h"

using namespace DDS;

namespace My {

    class ChatObjectListener : public DataReaderListener {

      public:

        virtual void on_requested_deadline_missed(
            DataReader* /*reader*/,
            const RequestedDeadlineMissedStatus& /*status*/) {}

        virtual void on_requested_incompatible_qos(
            DataReader* /*reader*/,
            const RequestedIncompatibleQosStatus& /*status*/) {}

        virtual void on_sample_rejected(
            DataReader* /*reader*/,
            const SampleRejectedStatus& /*status*/) {}

        virtual void on_liveliness_changed(
            DataReader* /*reader*/,
            const LivelinessChangedStatus& /*status*/) {}

        virtual void on_sample_lost(
            DataReader* /*reader*/,
            const SampleLostStatus& /*status*/) {}

        virtual void on_subscription_matched(
            DataReader* /*reader*/,
            const SubscriptionMatchedStatus& /*status*/) {}

        virtual void on_data_available(DataReader* reader);
    };

    void ChatObjectListener::on_data_available(DataReader* reader)
    {
        My::ChatObjectDataReader *ChatObject_reader = NULL;
        My::ChatObjectSeq data_seq;
        SampleInfoSeq info_seq;
        ReturnCode_t retcode;
        int i;

        ChatObject_reader = My::ChatObjectDataReader::narrow(reader);
        if (ChatObject_reader == NULL) {
            printf("DataReader narrow error\n");
            return;
        }

        retcode = ChatObject_reader->read(  /*>>><<<*/
            data_seq, info_seq, LENGTH_UNLIMITED,
            ANY_SAMPLE_STATE, ANY_VIEW_STATE, ANY_INSTANCE_STATE);

        if (retcode == RETCODE_NO_DATA) {
            return;
        } else if (retcode != RETCODE_OK) {
            printf("take error %d\n", retcode);
            return;
        }

        for (i = 0; i < data_seq.length(); ++i) {
            if (info_seq[i].valid_data) {
                printf("Received data\n");
                My::ChatObjectTypeSupport::print_data(&data_seq[i]);
            }
        }

        retcode = ChatObject_reader->return_loan(data_seq, info_seq);
        if (retcode != RETCODE_OK) {
            printf("return loan error %d\n", retcode);
        }
    }

}

/* Delete all entities */
static int subscriber_shutdown(
    DomainParticipant *participant)
{
    ReturnCode_t retcode;
    int status = 0;

    if (participant != NULL) {
        retcode = participant->delete_contained_entities();
        if (retcode != RETCODE_OK) {
            printf("delete_contained_entities error %d\n", retcode);
            status = -1;
        }

        retcode = TheParticipantFactory->delete_participant(participant);
        if (retcode != RETCODE_OK) {
            printf("delete_participant error %d\n", retcode);
            status = -1;
        }
    }

    /* RTI Connext provides the finalize_instance() method on
    domain participant factory for people who want to release memory used
    by the participant factory. Uncomment the following block of code for
    clean destruction of the singleton. */
    retcode = DomainParticipantFactory::finalize_instance();
    if (retcode != RETCODE_OK) {
        printf("finalize_instance error %d\n", retcode);
        status = -1;
    }

    return status;
}

extern "C" int subscriber_main(int domainId, int sample_count)
{
    DomainParticipant *participant = NULL;
    Subscriber *subscriber = NULL;
    Topic *topic = NULL;
    My::ChatObjectListener *reader_listener = NULL;
    DataReader *reader = NULL;
    ReturnCode_t retcode;
    const char *type_name = NULL;
    int count = 0;
    Duration_t receive_period = {8,0}; /*>>><<<*/
    int status = 0;

    /* To customize the participant QoS, use
    the configuration file USER_QOS_PROFILES.xml */
    participant = TheParticipantFactory->create_participant(
        domainId, PARTICIPANT_QOS_DEFAULT,
        NULL /* listener */, STATUS_MASK_NONE);
    if (participant == NULL) {
        printf("create_participant error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* To customize the subscriber QoS, use
    the configuration file USER_QOS_PROFILES.xml */
    subscriber = participant->create_subscriber(
        SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, STATUS_MASK_NONE);
    if (subscriber == NULL) {
        printf("create_subscriber error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* Register the type before creating the topic */
    type_name = My::ChatObjectTypeSupport::get_type_name();
    retcode = My::ChatObjectTypeSupport::register_type(
        participant, type_name);
    if (retcode != RETCODE_OK) {
        printf("register_type error %d\n", retcode);
        subscriber_shutdown(participant);
        return -1;
    }

    /* To customize the topic QoS, use
    the configuration file USER_QOS_PROFILES.xml */
    topic = participant->create_topic(
        My::CHAT_TOPIC_NAME, /*>>><<<*/
        type_name, TOPIC_QOS_DEFAULT, NULL /* listener */,
        STATUS_MASK_NONE);
    if (topic == NULL) {
        printf("create_topic error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* Create a data reader listener */
    reader_listener = new My::ChatObjectListener();

    /* To customize the data reader QoS, use
    the configuration file USER_QOS_PROFILES.xml */
    reader = subscriber->create_datareader(
    	topic, DATAREADER_QOS_DEFAULT, NULL /*>>><<<*/,
        STATUS_MASK_NONE /*>>><<<*/);
    if (reader == NULL) {
        printf("create_datareader error\n");
        subscriber_shutdown(participant);
        delete reader_listener;
        return -1;
    }

    /* >>> Setup StatusCondition */
    StatusCondition* status_condition = reader->get_statuscondition();
    if (status_condition == NULL) {
        printf("get_statuscondition error\n");
        subscriber_shutdown(participant);
        return -1;
    }
    retcode = status_condition->set_enabled_statuses(DDS_DATA_AVAILABLE_STATUS);
    if (retcode != DDS_RETCODE_OK) {
        printf("set_enabled_statuses error\n");
        subscriber_shutdown(participant);
        return -1;
    }
    /* <<< */

    /* >>> Setup WaitSet */
    WaitSet* waitset = new WaitSet();
    retcode = waitset->attach_condition(status_condition);
    if (retcode != DDS_RETCODE_OK) {
        // ... error
        delete waitset;
        subscriber_shutdown(participant);
        return -1;
    }
    ConditionSeq active_conditions; // holder for active conditions
    /* <<< */

    /* Main loop */

    for (count=0; (sample_count == 0) || (count < sample_count); ++count) {

        printf("My::ChatObject subscriber waiting for %d sec...\n",
        receive_period.sec);

        /* >>> Wait */
        retcode = waitset->wait(active_conditions, receive_period);
        if (retcode == DDS_RETCODE_OK) {
        	reader_listener->on_data_available(reader);
        }
        /* <<< */
    }

    /* Delete all entities */
    delete waitset; /*>>><<<*/
    status = subscriber_shutdown(participant);
    delete reader_listener;

    return status;
}

int main(int argc, char *argv[])
{
    int domainId = 0;
    int sample_count = 0; /* infinite loop */

    if (argc >= 2) {
        domainId = atoi(argv[1]);
    }
    if (argc >= 3) {
        sample_count = atoi(argv[2]);
    }

    /* Uncomment this to turn on additional logging
    NDDSConfigLogger::get_instance()->
    set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
    NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
    */

    return subscriber_main(domainId, sample_count);
}

<commit_msg>Updated comment for read()<commit_after>
/* Chat_subscriber.cxx

A subscription example

This file is derived from code automatically generated by the rtiddsgen
command:

rtiddsgen -language C++ -example <arch> Chat.idl

Example subscription of type My::ChatObject automatically generated by
'rtiddsgen'. To test them follow these steps:

(1) Compile this file and the example publication.

(2) Start the subscription with the command
objs/<arch>/Chat_subscriber <domain_id> <sample_count>

(3) Start the publication with the command
objs/<arch>/Chat_publisher <domain_id> <sample_count>

(4) [Optional] Specify the list of discovery initial peers and
multicast receive addresses via an environment variable or a file
(in the current working directory) called NDDS_DISCOVERY_PEERS.

You can run any number of publishers and subscribers programs, and can
add and remove them dynamically from the domain.

Example:

To run the example application on domain <domain_id>:

On Unix:

objs/<arch>/Chat_publisher <domain_id>
objs/<arch>/Chat_subscriber <domain_id>

On Windows:

objs\<arch>\Chat_publisher <domain_id>
objs\<arch>\Chat_subscriber <domain_id>

*/

#include <stdio.h>
#include <stdlib.h>
#include "Chat.h"
#include "ChatSupport.h"
#include "ndds/ndds_cpp.h"

#include "ndds/ndds_namespace_cpp.h"

using namespace DDS;

namespace My {

    class ChatObjectListener : public DataReaderListener {

      public:

        virtual void on_requested_deadline_missed(
            DataReader* /*reader*/,
            const RequestedDeadlineMissedStatus& /*status*/) {}

        virtual void on_requested_incompatible_qos(
            DataReader* /*reader*/,
            const RequestedIncompatibleQosStatus& /*status*/) {}

        virtual void on_sample_rejected(
            DataReader* /*reader*/,
            const SampleRejectedStatus& /*status*/) {}

        virtual void on_liveliness_changed(
            DataReader* /*reader*/,
            const LivelinessChangedStatus& /*status*/) {}

        virtual void on_sample_lost(
            DataReader* /*reader*/,
            const SampleLostStatus& /*status*/) {}

        virtual void on_subscription_matched(
            DataReader* /*reader*/,
            const SubscriptionMatchedStatus& /*status*/) {}

        virtual void on_data_available(DataReader* reader);
    };

    void ChatObjectListener::on_data_available(DataReader* reader)
    {
        My::ChatObjectDataReader *ChatObject_reader = NULL;
        My::ChatObjectSeq data_seq;
        SampleInfoSeq info_seq;
        ReturnCode_t retcode;
        int i;

        ChatObject_reader = My::ChatObjectDataReader::narrow(reader);
        if (ChatObject_reader == NULL) {
            printf("DataReader narrow error\n");
            return;
        }

        retcode = ChatObject_reader->read(  /*>>><<<*/
            data_seq, info_seq, LENGTH_UNLIMITED,
            ANY_SAMPLE_STATE, ANY_VIEW_STATE, ANY_INSTANCE_STATE);

        if (retcode == RETCODE_NO_DATA) {
            return;
        } else if (retcode != RETCODE_OK) {
            printf("take/read error %d\n", retcode); /*>>><<<*/
            return;
        }

        for (i = 0; i < data_seq.length(); ++i) {
            if (info_seq[i].valid_data) {
                printf("Received data\n");
                My::ChatObjectTypeSupport::print_data(&data_seq[i]);
            }
        }

        retcode = ChatObject_reader->return_loan(data_seq, info_seq);
        if (retcode != RETCODE_OK) {
            printf("return loan error %d\n", retcode);
        }
    }

}

/* Delete all entities */
static int subscriber_shutdown(
    DomainParticipant *participant)
{
    ReturnCode_t retcode;
    int status = 0;

    if (participant != NULL) {
        retcode = participant->delete_contained_entities();
        if (retcode != RETCODE_OK) {
            printf("delete_contained_entities error %d\n", retcode);
            status = -1;
        }

        retcode = TheParticipantFactory->delete_participant(participant);
        if (retcode != RETCODE_OK) {
            printf("delete_participant error %d\n", retcode);
            status = -1;
        }
    }

    /* RTI Connext provides the finalize_instance() method on
    domain participant factory for people who want to release memory used
    by the participant factory. Uncomment the following block of code for
    clean destruction of the singleton. */
    retcode = DomainParticipantFactory::finalize_instance();
    if (retcode != RETCODE_OK) {
        printf("finalize_instance error %d\n", retcode);
        status = -1;
    }

    return status;
}

extern "C" int subscriber_main(int domainId, int sample_count)
{
    DomainParticipant *participant = NULL;
    Subscriber *subscriber = NULL;
    Topic *topic = NULL;
    My::ChatObjectListener *reader_listener = NULL;
    DataReader *reader = NULL;
    ReturnCode_t retcode;
    const char *type_name = NULL;
    int count = 0;
    Duration_t receive_period = {8,0}; /*>>><<<*/
    int status = 0;

    /* To customize the participant QoS, use
    the configuration file USER_QOS_PROFILES.xml */
    participant = TheParticipantFactory->create_participant(
        domainId, PARTICIPANT_QOS_DEFAULT,
        NULL /* listener */, STATUS_MASK_NONE);
    if (participant == NULL) {
        printf("create_participant error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* To customize the subscriber QoS, use
    the configuration file USER_QOS_PROFILES.xml */
    subscriber = participant->create_subscriber(
        SUBSCRIBER_QOS_DEFAULT, NULL /* listener */, STATUS_MASK_NONE);
    if (subscriber == NULL) {
        printf("create_subscriber error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* Register the type before creating the topic */
    type_name = My::ChatObjectTypeSupport::get_type_name();
    retcode = My::ChatObjectTypeSupport::register_type(
        participant, type_name);
    if (retcode != RETCODE_OK) {
        printf("register_type error %d\n", retcode);
        subscriber_shutdown(participant);
        return -1;
    }

    /* To customize the topic QoS, use
    the configuration file USER_QOS_PROFILES.xml */
    topic = participant->create_topic(
        My::CHAT_TOPIC_NAME, /*>>><<<*/
        type_name, TOPIC_QOS_DEFAULT, NULL /* listener */,
        STATUS_MASK_NONE);
    if (topic == NULL) {
        printf("create_topic error\n");
        subscriber_shutdown(participant);
        return -1;
    }

    /* Create a data reader listener */
    reader_listener = new My::ChatObjectListener();

    /* To customize the data reader QoS, use
    the configuration file USER_QOS_PROFILES.xml */
    reader = subscriber->create_datareader(
    	topic, DATAREADER_QOS_DEFAULT, NULL /*>>><<<*/,
        STATUS_MASK_NONE /*>>><<<*/);
    if (reader == NULL) {
        printf("create_datareader error\n");
        subscriber_shutdown(participant);
        delete reader_listener;
        return -1;
    }

    /* >>> Setup StatusCondition */
    StatusCondition* status_condition = reader->get_statuscondition();
    if (status_condition == NULL) {
        printf("get_statuscondition error\n");
        subscriber_shutdown(participant);
        return -1;
    }
    retcode = status_condition->set_enabled_statuses(DDS_DATA_AVAILABLE_STATUS);
    if (retcode != DDS_RETCODE_OK) {
        printf("set_enabled_statuses error\n");
        subscriber_shutdown(participant);
        return -1;
    }
    /* <<< */

    /* >>> Setup WaitSet */
    WaitSet* waitset = new WaitSet();
    retcode = waitset->attach_condition(status_condition);
    if (retcode != DDS_RETCODE_OK) {
        // ... error
        delete waitset;
        subscriber_shutdown(participant);
        return -1;
    }
    ConditionSeq active_conditions; // holder for active conditions
    /* <<< */

    /* Main loop */

    for (count=0; (sample_count == 0) || (count < sample_count); ++count) {

        printf("My::ChatObject subscriber waiting for %d sec...\n",
        receive_period.sec);

        /* >>> Wait */
        retcode = waitset->wait(active_conditions, receive_period);
        if (retcode == DDS_RETCODE_OK) {
        	reader_listener->on_data_available(reader);
        }
        /* <<< */
    }

    /* Delete all entities */
    delete waitset; /*>>><<<*/
    status = subscriber_shutdown(participant);
    delete reader_listener;

    return status;
}

int main(int argc, char *argv[])
{
    int domainId = 0;
    int sample_count = 0; /* infinite loop */

    if (argc >= 2) {
        domainId = atoi(argv[1]);
    }
    if (argc >= 3) {
        sample_count = atoi(argv[2]);
    }

    /* Uncomment this to turn on additional logging
    NDDSConfigLogger::get_instance()->
    set_verbosity_by_category(NDDS_CONFIG_LOG_CATEGORY_API,
    NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
    */

    return subscriber_main(domainId, sample_count);
}

<|endoftext|>


<commit_before>#include "version.hpp"
#include "dvwindow.hpp"
#include "dvqmlcommunication.hpp"
#include "dvinputplugin.hpp"
#include "dvrenderplugin.hpp"
#include "dvfolderlisting.hpp"
#include "dvqmlcommunication.hpp"
#include <QQuickItem>
#include <QMetaObject>
#include <QApplication>
#include <QOpenGLContext>
#include <QPluginLoader>
#include <QDir>
#include <AVPlayer.h>

void DVWindow::loadPlugins() {
    /* Start with the path the application is in. */
    QDir pluginsDir(qApp->applicationDirPath());

#if defined(Q_OS_WIN)
    /* If we're in a "debug" or "release" folder go up a level, because that's where plugins are copied by the build system. */
    if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
        pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
    /* I haven't actually tried this on Mac. This is just what the Qt plugin example said to do... */
    if (pluginsDir.dirName() == "MacOS") {
        pluginsDir.cdUp();
        pluginsDir.cdUp();
        pluginsDir.cdUp();
    }
#endif

    /* Go into the "plugins" folder from there. */
    pluginsDir.cd("plugins");

#if defined(Q_OS_WIN)
    /* On Windows we can add the plugin dir to the DLL search path dynamically.
     * On Linux LD_LIBRARY_PATH must be set before running the program to get the same effect. */
    SetDllDirectory(pluginsDir.absolutePath().toStdWString().c_str());
#endif

    qDebug("Loading plugins from \"%s\"...", qPrintable(pluginsDir.absolutePath()));

    /* Try to load all files in the directory. */
    for (const QString& filename : pluginsDir.entryList(QDir::Files)) {
        /* If the file isn't a valid library for this platform, don't bother. */
        if (!QLibrary::isLibrary(filename)) continue;

        QPluginLoader loader(pluginsDir.absoluteFilePath(filename));
        QObject *obj = loader.instance();

        if (obj == nullptr) {
            qDebug("\"%s\" is not a plugin. %s", qPrintable(filename), qPrintable(loader.errorString()));
            continue;
        }

        /* If it can be cast to the plugin type it is a valid plugin, otherwise it will be null. */
        DVRenderPlugin* renderPlugin = qobject_cast<DVRenderPlugin*>(obj);
        DVInputPlugin* inputPlugin = qobject_cast<DVInputPlugin*>(obj);

        if (renderPlugin != nullptr) {
            qDebug("Found render plugin: \"%s\"", qPrintable(filename));

            if (renderPlugin->init(context()->extraFunctions(), qmlEngine)) {
                for (const QString& mode : renderPlugin->drawModeNames())
                    qmlCommunication->addPluginMode(mode, renderPlugin->getConfigMenuObject());

                renderPlugins.append(renderPlugin);

                qDebug("Loaded plugin: \"%s\"", qPrintable(filename));
            } else {
                qDebug("Plugin: \"%s\" failed to init.", qPrintable(filename));
            }
        } else if (inputPlugin != nullptr) {
            qDebug("Found input plugin: \"%s\"", qPrintable(filename));

            if (inputPlugin->init(qmlEngine)) {
                inputPlugins.append(inputPlugin);
                qmlCommunication->addInputPluginConfig(inputPlugin->getConfigMenuObject());

                qDebug("Loaded plugin: \"%s\"", qPrintable(filename));
            } else {
                qDebug("Plugin: \"%s\" failed to init.", qPrintable(filename));
            }
        }
    }
    qDebug("Done loading plugins.");
}

void DVWindow::unloadPlugins() {
    /* Deinit any/all loaded plugins. */
    for (DVRenderPlugin* plugin : renderPlugins)
        plugin->deinit();
    for (DVInputPlugin* plugin : inputPlugins)
        plugin->deinit();

    /* Clear the list. Not that it should be used anymore... */
    renderPlugins.clear();
    inputPlugins.clear();
}

DVRenderPlugin* DVWindow::getCurrentRenderPlugin() {
    for (DVRenderPlugin* plugin : renderPlugins)
        /* Find the first plugin that contains the mode we want. */
        if (plugin->drawModeNames().contains(qmlCommunication->pluginMode()))
            return plugin;

    return nullptr;
}

bool DVWindow::doPluginRender() {
    DVRenderPlugin* plugin = getCurrentRenderPlugin();

    /* Return false if it wasn't found, otherwise let it do its thing. */
    return plugin != nullptr && plugin->render(qmlCommunication->pluginMode(), context()->extraFunctions());
}

void DVWindow::getPluginSize() {
    DVRenderPlugin* plugin = getCurrentRenderPlugin();

    if (plugin != nullptr)
        qmlSize = plugin->getRenderSize(qmlSize);
}

void DVWindow::pluginOnFrameSwapped() {
    DVRenderPlugin* plugin = getCurrentRenderPlugin();

    if (plugin != nullptr) {
        /* Make sure the render size is up to date. */
        /* TODO - A signal from the plugin would likely be more efficient... */
        updateQmlSize();

        /* Let it do its thing. */
        plugin->frameSwapped(context()->extraFunctions());

        /* Do we hold the mouse? */
        holdMouse = plugin->shouldLockMouse();
    }
}

void DVWindow::doPluginInput() {
    /* Get input from ALL input plugins. */
    for (DVInputPlugin* plugin : inputPlugins)
        plugin->pollInput(this);

    /* Only get input from the current render plugin. */
    DVRenderPlugin* plugin = getCurrentRenderPlugin();

    if (plugin != nullptr)
        plugin->pollInput(this);
}

DVInputMode::Type DVWindow::inputMode() const {
    return folderListing->fileBrowserOpen() ? DVInputMode::FileBrowser : folderListing->isCurrentFileVideo() ? DVInputMode::VideoPlayer : DVInputMode::ImageViewer;
}

void DVWindow::up() {
    emit qmlCommunication->up();
}
void DVWindow::down() {
    emit qmlCommunication->down();
}
void DVWindow::left() {
    emit qmlCommunication->left();
}
void DVWindow::right() {
    emit qmlCommunication->right();
}

void DVWindow::accept() {
    emit qmlCommunication->accept();
}

void DVWindow::cancel() {
    emit qmlCommunication->cancel();
}

void DVWindow::openFileBrowser() {
    folderListing->setFileBrowserOpen(true);
}

void DVWindow::goBack() {
    if (folderListing->fileBrowserOpen() && folderListing->canGoBack())
        folderListing->goBack();
}

void DVWindow::goForward() {
    if (folderListing->fileBrowserOpen() && folderListing->canGoForward())
        folderListing->goForward();
}

void DVWindow::goUp() {
    if (folderListing->fileBrowserOpen() && folderListing->canGoUp())
        folderListing->goUp();
}

void DVWindow::fileInfo() {
    emit qmlCommunication->fileInfo();
}

void DVWindow::nextFile() {
    folderListing->openNext();
}

void DVWindow::previousFile() {
    folderListing->openPrevious();
}

//void DVWindow::setMousePosition(QPoint pos, bool relative = false) {
//}

//void DVWindow::sendMouseClick(Qt::MouseButton button) {
//}

void DVWindow::playVideo() {
    player->play();
}

void DVWindow::pauseVideo() {
    player->pause();
}

void DVWindow::playPauseVideo() {
    player->togglePause();
}

void DVWindow::seekBack() {
    player->seekBackward();
}

void DVWindow::seekForward() {
    player->seekForward();
}

void DVWindow::seekAmount(qint64 msec) {
    player->seek(msec);
}

void DVWindow::volumeUp() {
    player->audio()->setVolume(qMin(player->audio()->volume() + 0.1, 1.0));
}

void DVWindow::volumeDown() {
    player->audio()->setVolume(qMax(player->audio()->volume() - 0.1, 0.0));
}

void DVWindow::mute() {
    player->audio()->setMute(!player->audio()->isMute());
}

void DVWindow::setVolume(qreal volume) {
    player->audio()->setVolume(volume);
}
<commit_msg>Only load files starting with "dv2_" or "libdv2_" as plugins.<commit_after>#include "version.hpp"
#include "dvwindow.hpp"
#include "dvqmlcommunication.hpp"
#include "dvinputplugin.hpp"
#include "dvrenderplugin.hpp"
#include "dvfolderlisting.hpp"
#include "dvqmlcommunication.hpp"
#include <QQuickItem>
#include <QMetaObject>
#include <QApplication>
#include <QOpenGLContext>
#include <QPluginLoader>
#include <QDir>
#include <AVPlayer.h>

void DVWindow::loadPlugins() {
    /* Start with the path the application is in. */
    QDir pluginsDir(qApp->applicationDirPath());

    /* Plugins start with "dv2_" on Windows and "libdv2_" on Linux. */
    pluginsDir.setNameFilters(QStringList({"dv2_*", "libdv2_*"}));
    pluginsDir.setFilter(QDir::Files);

#if defined(Q_OS_WIN)
    /* If we're in a "debug" or "release" folder go up a level, because that's where plugins are copied by the build system. */
    if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
        pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
    /* I haven't actually tried this on Mac. This is just what the Qt plugin example said to do... */
    if (pluginsDir.dirName() == "MacOS") {
        pluginsDir.cdUp();
        pluginsDir.cdUp();
        pluginsDir.cdUp();
    }
#endif

    /* Go into the "plugins" folder from there. */
    pluginsDir.cd("plugins");

#if defined(Q_OS_WIN)
    /* On Windows we can add the plugin dir to the DLL search path dynamically.
     * On Linux LD_LIBRARY_PATH must be set before running the program to get the same effect. */
    SetDllDirectory(pluginsDir.absolutePath().toStdWString().c_str());
#endif

    qDebug("Loading plugins from \"%s\"...", qPrintable(pluginsDir.absolutePath()));

    /* Try to load all files in the directory using the filters defined above. */
    for (const QString& filename : pluginsDir.entryList()) {
        /* If the file isn't a valid library for this platform, don't bother. */
        if (!QLibrary::isLibrary(filename)) continue;

        QPluginLoader loader(pluginsDir.absoluteFilePath(filename));
        QObject *obj = loader.instance();

        if (obj == nullptr) {
            qDebug("\"%s\" is not a plugin. %s", qPrintable(filename), qPrintable(loader.errorString()));
            continue;
        }

        /* If it can be cast to the plugin type it is a valid plugin, otherwise it will be null. */
        DVRenderPlugin* renderPlugin = qobject_cast<DVRenderPlugin*>(obj);
        DVInputPlugin* inputPlugin = qobject_cast<DVInputPlugin*>(obj);

        if (renderPlugin != nullptr) {
            qDebug("Found render plugin: \"%s\"", qPrintable(filename));

            if (renderPlugin->init(context()->extraFunctions(), qmlEngine)) {
                for (const QString& mode : renderPlugin->drawModeNames())
                    qmlCommunication->addPluginMode(mode, renderPlugin->getConfigMenuObject());

                renderPlugins.append(renderPlugin);

                qDebug("Loaded plugin: \"%s\"", qPrintable(filename));
            } else {
                qDebug("Plugin: \"%s\" failed to init.", qPrintable(filename));
            }
        } else if (inputPlugin != nullptr) {
            qDebug("Found input plugin: \"%s\"", qPrintable(filename));

            if (inputPlugin->init(qmlEngine)) {
                inputPlugins.append(inputPlugin);
                qmlCommunication->addInputPluginConfig(inputPlugin->getConfigMenuObject());

                qDebug("Loaded plugin: \"%s\"", qPrintable(filename));
            } else {
                qDebug("Plugin: \"%s\" failed to init.", qPrintable(filename));
            }
        }
    }
    qDebug("Done loading plugins.");
}

void DVWindow::unloadPlugins() {
    /* Deinit any/all loaded plugins. */
    for (DVRenderPlugin* plugin : renderPlugins)
        plugin->deinit();
    for (DVInputPlugin* plugin : inputPlugins)
        plugin->deinit();

    /* Clear the list. Not that it should be used anymore... */
    renderPlugins.clear();
    inputPlugins.clear();
}

DVRenderPlugin* DVWindow::getCurrentRenderPlugin() {
    for (DVRenderPlugin* plugin : renderPlugins)
        /* Find the first plugin that contains the mode we want. */
        if (plugin->drawModeNames().contains(qmlCommunication->pluginMode()))
            return plugin;

    return nullptr;
}

bool DVWindow::doPluginRender() {
    DVRenderPlugin* plugin = getCurrentRenderPlugin();

    /* Return false if it wasn't found, otherwise let it do its thing. */
    return plugin != nullptr && plugin->render(qmlCommunication->pluginMode(), context()->extraFunctions());
}

void DVWindow::getPluginSize() {
    DVRenderPlugin* plugin = getCurrentRenderPlugin();

    if (plugin != nullptr)
        qmlSize = plugin->getRenderSize(qmlSize);
}

void DVWindow::pluginOnFrameSwapped() {
    DVRenderPlugin* plugin = getCurrentRenderPlugin();

    if (plugin != nullptr) {
        /* Make sure the render size is up to date. */
        /* TODO - A signal from the plugin would likely be more efficient... */
        updateQmlSize();

        /* Let it do its thing. */
        plugin->frameSwapped(context()->extraFunctions());

        /* Do we hold the mouse? */
        holdMouse = plugin->shouldLockMouse();
    }
}

void DVWindow::doPluginInput() {
    /* Get input from ALL input plugins. */
    for (DVInputPlugin* plugin : inputPlugins)
        plugin->pollInput(this);

    /* Only get input from the current render plugin. */
    DVRenderPlugin* plugin = getCurrentRenderPlugin();

    if (plugin != nullptr)
        plugin->pollInput(this);
}

DVInputMode::Type DVWindow::inputMode() const {
    return folderListing->fileBrowserOpen() ? DVInputMode::FileBrowser : folderListing->isCurrentFileVideo() ? DVInputMode::VideoPlayer : DVInputMode::ImageViewer;
}

void DVWindow::up() {
    emit qmlCommunication->up();
}
void DVWindow::down() {
    emit qmlCommunication->down();
}
void DVWindow::left() {
    emit qmlCommunication->left();
}
void DVWindow::right() {
    emit qmlCommunication->right();
}

void DVWindow::accept() {
    emit qmlCommunication->accept();
}

void DVWindow::cancel() {
    emit qmlCommunication->cancel();
}

void DVWindow::openFileBrowser() {
    folderListing->setFileBrowserOpen(true);
}

void DVWindow::goBack() {
    if (folderListing->fileBrowserOpen() && folderListing->canGoBack())
        folderListing->goBack();
}

void DVWindow::goForward() {
    if (folderListing->fileBrowserOpen() && folderListing->canGoForward())
        folderListing->goForward();
}

void DVWindow::goUp() {
    if (folderListing->fileBrowserOpen() && folderListing->canGoUp())
        folderListing->goUp();
}

void DVWindow::fileInfo() {
    emit qmlCommunication->fileInfo();
}

void DVWindow::nextFile() {
    folderListing->openNext();
}

void DVWindow::previousFile() {
    folderListing->openPrevious();
}

//void DVWindow::setMousePosition(QPoint pos, bool relative = false) {
//}

//void DVWindow::sendMouseClick(Qt::MouseButton button) {
//}

void DVWindow::playVideo() {
    player->play();
}

void DVWindow::pauseVideo() {
    player->pause();
}

void DVWindow::playPauseVideo() {
    player->togglePause();
}

void DVWindow::seekBack() {
    player->seekBackward();
}

void DVWindow::seekForward() {
    player->seekForward();
}

void DVWindow::seekAmount(qint64 msec) {
    player->seek(msec);
}

void DVWindow::volumeUp() {
    player->audio()->setVolume(qMin(player->audio()->volume() + 0.1, 1.0));
}

void DVWindow::volumeDown() {
    player->audio()->setVolume(qMax(player->audio()->volume() - 0.1, 0.0));
}

void DVWindow::mute() {
    player->audio()->setMute(!player->audio()->isMute());
}

void DVWindow::setVolume(qreal volume) {
    player->audio()->setVolume(volume);
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPolyDataRemoveCell.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkCellData.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkPoints.h"
#include "vtkPolyData.h"
#include "vtkSmartPointer.h"

int TestPolyDataRemoveCell(int , char *[])
{
  int rval = 0;

  vtkIdType numPoints = 20;
  vtkIdType numVerts = 5;
  vtkIdType numLines = 8;
  vtkIdType numTriangles = 3;
  vtkIdType numStrips = 2;
  vtkIdType numCells = numVerts+numLines+numTriangles+numStrips;
  vtkIdType i;

  vtkPoints* points = vtkPoints::New();
  points->SetNumberOfPoints(numPoints);
  for(i=0;i<numPoints;i++)
    {
    double loc[3] = {i, i*i, 0};
    points->InsertPoint(i, loc);
    }
  vtkSmartPointer<vtkPolyData> poly = vtkSmartPointer<vtkPolyData>::New();
  poly->Allocate(numCells, numCells);
  poly->SetPoints(points);
  points->Delete();

  for(i=0;i<numVerts;i++)
    {
    poly->InsertNextCell(VTK_VERTEX, 1, &i);
    }

  for(i=0;i<numLines;i++)
    {
    vtkIdType pts[2] = {i, i+1};
    poly->InsertNextCell(VTK_LINE, 2, pts);
    }

  for(i=0;i<numTriangles;i++)
    {
    vtkIdType pts[3] = {0, i+1, i+2};
    poly->InsertNextCell(VTK_TRIANGLE, 3, pts);
    }

  for(i=0;i<numStrips;i++)
    {
    vtkIdType pts[3] = {0, i+1, i+2};
    poly->InsertNextCell(VTK_TRIANGLE_STRIP, 3, pts);
    }

  vtkIntArray* cellTypes = vtkIntArray::New();
  const char ctName[] = "cell types";
  cellTypes->SetName(ctName);
  cellTypes->SetNumberOfComponents(1);
  cellTypes->SetNumberOfTuples(numCells);
  for(i=0;i<numCells;i++)
    {
    cellTypes->SetValue(i, poly->GetCellType(i));
    }
  poly->GetCellData()->AddArray(cellTypes);

  vtkIdTypeArray* cellPoints = vtkIdTypeArray::New();
  const char cpName[] = "cell points";
  cellPoints->SetName(cpName);
  cellPoints->SetNumberOfComponents(4); // num points + point ids
  cellPoints->SetNumberOfTuples(numCells);
  for(i=0;i<numCells;i++)
    {
    vtkIdType npts, *pts;
    poly->GetCellPoints(i, npts, pts);
    vtkIdType data[4] = {npts, pts[0], 0, 0};
    for(vtkIdType j=1;j<npts;j++)
      {
      data[j+1] = pts[j];
      }
    cellPoints->SetTupleValue(i, data);
    }
  poly->GetCellData()->AddArray(cellPoints);
  cellPoints->Delete();

  poly->BuildCells();
  // now that we're all set up, try deleting one of each object
  poly->DeleteCell(numVerts-1); // vertex
  poly->DeleteCell(numVerts+numLines-1); // line
  poly->DeleteCell(numVerts+numLines+numTriangles-1); // triangle
  poly->DeleteCell(numCells-1); // strip

  poly->RemoveDeletedCells();

  if(poly->GetNumberOfCells() != numCells-4)
    {
    cout << "Wrong number of cells after removal.\n";
    return 1;
    }

  // the arrays should have been changed so get them again...
  cellTypes = vtkIntArray::SafeDownCast(poly->GetCellData()->GetArray(ctName));
  cellPoints = vtkIdTypeArray::SafeDownCast(poly->GetCellData()->GetArray(cpName));

  // check the cell types and arrays
  for(i=0;i<poly->GetNumberOfCells();i++)
    {
    if(cellTypes->GetValue(i) != poly->GetCellType(i))
      {
      cout << "Problem with cell type for cell " << i << endl;
      return 1;
      }
    }

  // check the cell's points
  for(i=0;i<poly->GetNumberOfCells();i++)
    {
    vtkIdType npts, *pts;
    poly->GetCellPoints(i, npts, pts);
    vtkIdType data[4];
    cellPoints->GetTupleValue(i, data);
    if(data[0] != npts)
      {
      cout << "Problem with the number of points for cell " << i << endl;
      return 1;
      }
    for(vtkIdType j=0;j<npts;j++)
      {
      if(pts[j] != data[j+1])
        {
        cout << "Problem with  point " << j << " for cell " << i << endl;
        return 1;
        }
      }
    }

  return rval;
}

<commit_msg>BUG: Deleted a vtkIntArray that was getting leaked in the test.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPolyDataRemoveCell.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkCellData.h"
#include "vtkIdTypeArray.h"
#include "vtkIntArray.h"
#include "vtkPoints.h"
#include "vtkPolyData.h"
#include "vtkSmartPointer.h"

int TestPolyDataRemoveCell(int , char *[])
{
  int rval = 0;

  vtkIdType numPoints = 20;
  vtkIdType numVerts = 5;
  vtkIdType numLines = 8;
  vtkIdType numTriangles = 3;
  vtkIdType numStrips = 2;
  vtkIdType numCells = numVerts+numLines+numTriangles+numStrips;
  vtkIdType i;

  vtkPoints* points = vtkPoints::New();
  points->SetNumberOfPoints(numPoints);
  for(i=0;i<numPoints;i++)
    {
    double loc[3] = {i, i*i, 0};
    points->InsertPoint(i, loc);
    }
  vtkSmartPointer<vtkPolyData> poly = vtkSmartPointer<vtkPolyData>::New();
  poly->Allocate(numCells, numCells);
  poly->SetPoints(points);
  points->Delete();

  for(i=0;i<numVerts;i++)
    {
    poly->InsertNextCell(VTK_VERTEX, 1, &i);
    }

  for(i=0;i<numLines;i++)
    {
    vtkIdType pts[2] = {i, i+1};
    poly->InsertNextCell(VTK_LINE, 2, pts);
    }

  for(i=0;i<numTriangles;i++)
    {
    vtkIdType pts[3] = {0, i+1, i+2};
    poly->InsertNextCell(VTK_TRIANGLE, 3, pts);
    }

  for(i=0;i<numStrips;i++)
    {
    vtkIdType pts[3] = {0, i+1, i+2};
    poly->InsertNextCell(VTK_TRIANGLE_STRIP, 3, pts);
    }

  vtkIntArray* cellTypes = vtkIntArray::New();
  const char ctName[] = "cell types";
  cellTypes->SetName(ctName);
  cellTypes->SetNumberOfComponents(1);
  cellTypes->SetNumberOfTuples(numCells);
  for(i=0;i<numCells;i++)
    {
    cellTypes->SetValue(i, poly->GetCellType(i));
    }
  poly->GetCellData()->AddArray(cellTypes);
  cellTypes->Delete();

  vtkIdTypeArray* cellPoints = vtkIdTypeArray::New();
  const char cpName[] = "cell points";
  cellPoints->SetName(cpName);
  cellPoints->SetNumberOfComponents(4); // num points + point ids
  cellPoints->SetNumberOfTuples(numCells);
  for(i=0;i<numCells;i++)
    {
    vtkIdType npts, *pts;
    poly->GetCellPoints(i, npts, pts);
    vtkIdType data[4] = {npts, pts[0], 0, 0};
    for(vtkIdType j=1;j<npts;j++)
      {
      data[j+1] = pts[j];
      }
    cellPoints->SetTupleValue(i, data);
    }
  poly->GetCellData()->AddArray(cellPoints);
  cellPoints->Delete();

  poly->BuildCells();
  // now that we're all set up, try deleting one of each object
  poly->DeleteCell(numVerts-1); // vertex
  poly->DeleteCell(numVerts+numLines-1); // line
  poly->DeleteCell(numVerts+numLines+numTriangles-1); // triangle
  poly->DeleteCell(numCells-1); // strip

  poly->RemoveDeletedCells();

  if(poly->GetNumberOfCells() != numCells-4)
    {
    cout << "Wrong number of cells after removal.\n";
    return 1;
    }

  // the arrays should have been changed so get them again...
  cellTypes = vtkIntArray::SafeDownCast(poly->GetCellData()->GetArray(ctName));
  cellPoints = vtkIdTypeArray::SafeDownCast(poly->GetCellData()->GetArray(cpName));

  // check the cell types and arrays
  for(i=0;i<poly->GetNumberOfCells();i++)
    {
    if(cellTypes->GetValue(i) != poly->GetCellType(i))
      {
      cout << "Problem with cell type for cell " << i << endl;
      return 1;
      }
    }

  // check the cell's points
  for(i=0;i<poly->GetNumberOfCells();i++)
    {
    vtkIdType npts, *pts;
    poly->GetCellPoints(i, npts, pts);
    vtkIdType data[4];
    cellPoints->GetTupleValue(i, data);
    if(data[0] != npts)
      {
      cout << "Problem with the number of points for cell " << i << endl;
      return 1;
      }
    for(vtkIdType j=0;j<npts;j++)
      {
      if(pts[j] != data[j+1])
        {
        cout << "Problem with  point " << j << " for cell " << i << endl;
        return 1;
        }
      }
    }

  return rval;
}

<|endoftext|>