<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      app.cpp
// Purpose:   Implementation of classes for syncodbcquery
// Author:    Anton van Wezenbeek
// Copyright: (c) 2014 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#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

wxIMPLEMENT_APP(App);

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

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

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

  return true;
}

BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
  EVT_CLOSE(Frame::OnClose)
  EVT_MENU(wxID_ABOUT, Frame::OnCommand)
  EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
  EVT_MENU(wxID_EXIT, 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(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->GetAppDisplayName())
  , 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);

  wxExMenu* menuView = new wxExMenu();
  menuView->AppendBars();
  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<wxExStatusBarPane> panes;
  panes.push_back(wxExStatusBarPane());
  panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines")));
  SetupStatusBar(panes);
#endif

  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::OnClose(wxCloseEvent& event)
{
  wxExFileDialog dlg(this, &m_Query->GetFile());

  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(wxExGetVersionInfo().GetVersionOnlyString());
    info.SetCopyright(wxExGetVersionInfo().GetCopyright());
    info.AddDeveloper(wxExOTL::VersionInfo().GetVersionString());
    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->GetFile().FileNew(wxExFileName());
    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_SAVE:
    m_Query->GetFile().FileSave();
    break;

  case wxID_SAVEAS:
    {
      wxExFileDialog dlg(
        this,
        &m_Query->GetFile(),
        wxGetStockLabel(wxID_SAVEAS),
        wxFileSelectorDefaultWildcardStr,
        wxFD_SAVE);

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

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

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

  case ID_DATABASE_OPEN:
    if (m_otl.Logon(this))
    {
      m_Shell->SetPrompt(m_otl.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::OnCommandConfigDialog(
  wxWindowID dialogid,
  int commandid)
{
  if (dialogid == wxID_PREFERENCES)
  {
    m_Query->ConfigGet();
  }
  else
  {
    wxExFrameWithHistory::OnCommandConfigDialog(dialogid, commandid);
  }
}

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,
  int col_number,
  long flags)
{
  if (m_Query->Open(filename, line_number, match, col_number, flags))
  {
    GetManager().GetPane("QUERY").Show(true);
    GetManager().Update();

    SetRecentFile(filename.GetFullPath());
  }
  else
  {
    return false;
  }
}

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.Time(), rpc);
  }
  else
  {
    const auto rpc = m_otl.Query(query);

    sw.Pause();

    UpdateStatistics(sw.Time(), rpc);
  }

  m_Shell->DocumentEnd();
}

void Frame::RunQueries(const wxString& text)
{
  if (text.empty())
  {
    return;
  }

  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(long time, long rpc)
{
  m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"),
    rpc,
    (float)time / (float)1000));

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

  m_Statistics.Inc(_("Total number of queries run"));
  m_Statistics.Inc(_("Total query runtime"), time);
  m_Statistics.Inc(_("Total rows processed"), rpc);
}
<commit_msg>fixed core dump<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      app.cpp
// Purpose:   Implementation of classes for syncodbcquery
// Author:    Anton van Wezenbeek
// Copyright: (c) 2014 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#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

wxIMPLEMENT_APP(App);

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

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

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

  return true;
}

BEGIN_EVENT_TABLE(Frame, wxExFrameWithHistory)
  EVT_CLOSE(Frame::OnClose)
  EVT_MENU(wxID_ABOUT, Frame::OnCommand)
  EVT_MENU(wxID_EXECUTE, Frame::OnCommand)
  EVT_MENU(wxID_EXIT, 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(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->GetAppDisplayName())
  , 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);

  wxExMenu* menuView = new wxExMenu();
  menuView->AppendBars();
  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<wxExStatusBarPane> panes;
  panes.push_back(wxExStatusBarPane());
  panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines")));
  SetupStatusBar(panes);
#endif

  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::OnClose(wxCloseEvent& event)
{
  wxExFileDialog dlg(this, &m_Query->GetFile());

  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(wxExGetVersionInfo().GetVersionOnlyString());
    info.SetCopyright(wxExGetVersionInfo().GetCopyright());
    info.AddDeveloper(wxExOTL::VersionInfo().GetVersionString());
    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->GetFile().FileNew(wxExFileName());
    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_SAVE:
    m_Query->GetFile().FileSave();
    break;

  case wxID_SAVEAS:
    {
      wxExFileDialog dlg(
        this,
        &m_Query->GetFile(),
        wxGetStockLabel(wxID_SAVEAS),
        wxFileSelectorDefaultWildcardStr,
        wxFD_SAVE);

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

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

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

  case ID_DATABASE_OPEN:
    if (m_otl.Logon(this))
    {
      m_Shell->SetPrompt(m_otl.Datasource() + ">");
    }
    break;

  case ID_SHELL_COMMAND:
    if (m_otl.IsConnected())
    {
      try
      {
        const wxString input(event.GetString());

        if (!input.empty())
        {
          const wxString query = input.substr(
            0,
            input.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::OnCommandConfigDialog(
  wxWindowID dialogid,
  int commandid)
{
  if (dialogid == wxID_PREFERENCES)
  {
    m_Query->ConfigGet();
  }
  else
  {
    wxExFrameWithHistory::OnCommandConfigDialog(dialogid, commandid);
  }
}

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,
  int col_number,
  long flags)
{
  if (m_Query->Open(filename, line_number, match, col_number, flags))
  {
    GetManager().GetPane("QUERY").Show(true);
    GetManager().Update();

    SetRecentFile(filename.GetFullPath());
  }
  else
  {
    return false;
  }
}

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.Time(), rpc);
  }
  else
  {
    const auto rpc = m_otl.Query(query);

    sw.Pause();

    UpdateStatistics(sw.Time(), rpc);
  }

  m_Shell->DocumentEnd();
}

void Frame::RunQueries(const wxString& text)
{
  if (text.empty())
  {
    return;
  }

  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(long time, long rpc)
{
  m_Shell->AppendText(wxString::Format(_("\n%ld rows processed (%.3f seconds)"),
    rpc,
    (float)time / (float)1000));

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

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


<commit_before><commit_msg>Update log to not claim Connect was always called twice. :)<commit_after><|endoftext|>


<commit_before>AlidNdPtAnalysisPbPbAOD *AddTask_dNdPt_PbPbAOD( UInt_t uTriggerMask = AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral ,
						Double_t dNCrossedRowsTPC = 100,
						Int_t iFilterBit = AliAODTrack::kTrkGlobal,
						char *contName = "dNdPtPbPbAOD",
						Double_t dNClustersTPC = 0,
						Bool_t bDoCutTPCLength = kTRUE,
						Double_t dPrefactorLengthInTPC = 0.85,
						char *centEstimator = "V0M",
						char *suffix = ""
											  )
{
  // Creates, configures and attaches to the train a cascades check task.
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTask_dNdPt_PbPbAOD", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTask_dNdPt_PbPbAOD", "This task requires an input event handler");
    return NULL;
  }
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

  // Create and configure the task
  TString combinedName;
  combinedName.Form("%s%s",contName, suffix);
  ::Info("AddTask_dNdPt_PbPbAOD",Form("Name of Task: %s", combinedName.Data()));
  AlidNdPtAnalysisPbPbAOD *task = new AlidNdPtAnalysisPbPbAOD(combinedName.Data());
  //   UInt_t triggerMask = AliVEvent::kMB;
  //   triggerMask |= AliVEvent::kCentral;
  //   triggerMask |= AliVEvent::kSemiCentral;

  task->SelectCollisionCandidates(uTriggerMask);

  task->SetCentralityEstimator(centEstimator);

//   char *cDisableTrigger = "",
//
//   task->DisableOnlineTriggerStrings(cDisableTrigger);

  task->SetEventplaneSelector("Q");

  task->SetCutMinNCrossedRowsTPC(dNCrossedRowsTPC);
  task->SetCutMinNClustersTPC(dNClustersTPC);
  task->SetCutLengthInTPCPtDependent(bDoCutTPCLength);
  task->SetPrefactorLengthInTPCPtDependent(dPrefactorLengthInTPC);
  //task->SetCutLengthInTPCPtDependent();
  //
//   task->EnableRelativeCuts();
//   task->SetCutPercMinNClustersTPC(1.0);
//   task->SetCutPercMinNCrossedRowsTPC(1.0);

  Double_t binsPtCheck[] = {0., 0.15, 1.0, 5.0, 10.0, 50.0, 200.0};
  Int_t nBinPtCheck = sizeof(binsPtCheck)/sizeof(Double_t);
  task->SetBinsPtCheck(nBinPtCheck, binsPtCheck);

  Double_t binsPtCorr[] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 200.0};
  Int_t nBinPtCorr = sizeof(binsPtCorr)/sizeof(Double_t);
  task->SetBinsPtCorr(nBinPtCorr, binsPtCorr);

//   Double_t binsPhi[] = {0 ,0.10472 ,0.20944 ,0.314159 ,0.418879 ,0.523599 ,0.628319 ,0.733038 ,0.837758 ,0.942478 ,1.0472 ,1.15192 ,1.25664 ,1.36136 ,1.46608 ,1.5708 ,1.67552 ,1.78024 ,1.88496 ,1.98968 ,2.0944 ,2.19911 ,2.30383 ,2.40855 ,2.51327 ,2.61799 ,2.72271 ,2.82743 ,2.93215 ,3.03687 ,3.14159 ,3.24631 ,3.35103 ,3.45575 ,3.56047 ,3.66519 ,3.76991 ,3.87463 ,3.97935 ,4.08407 ,4.18879 ,4.29351 ,4.39823 ,4.50295 ,4.60767 ,4.71239 ,4.81711 ,4.92183 ,5.02655 ,5.13127 ,5.23599 ,5.34071 ,5.44543 ,5.55015 ,5.65487 ,5.75959 ,5.86431 ,5.96903 ,6.07375 ,6.17847 ,6.28319};

//   Double_t binsPhi[] = {-1.*TMath::Pi(), -2.97625, -2.8109, -2.64555, -2.4802, -2.31486, -2.14951, -1.98416, -1.81882, -1.65347, -1.48812, -1.32278, -1.15743, -0.992082, -0.826735, -0.661388, -0.496041, -0.330694, -0.165347, 0, 0.165347, 0.330694, 0.496041, 0.661388, 0.826735, 0.992082, 1.15743, 1.32278, 1.48812, 1.65347, 1.81882, 1.98416, 2.14951, 2.31486, 2.4802, 2.64555, 2.8109, 2.97625, TMath::Pi()};

//   Double_t binsPhi[] = {-1.*TMath::Pi(), -0.75*TMath::Pi(), -0.5*TMath::Pi(), -0.25*TMath::Pi(), 0, 0.25*TMath::Pi(), 0.5*TMath::Pi(), 0.75*TMath::Pi(), TMath::Pi()};
//   Double_t binsPhi[] = {
// 	-2.*TMath::Pi(), -15./8.*TMath::Pi(), -14./8.*TMath::Pi(), -13./8.*TMath::Pi(), -12./8.*TMath::Pi(), -11./8.*TMath::Pi(), -10./8.*TMath::Pi(), -9./8.*TMath::Pi(),
// 	-1.*TMath::Pi(), -7./8.*TMath::Pi(), -6./8.*TMath::Pi(), -5./8.*TMath::Pi(),  -4./8.*TMath::Pi(), -3./8.*TMath::Pi(), -2./8.*TMath::Pi(), -1./8.*TMath::Pi(),  0,
// 	1./8.*TMath::Pi(), 2./8.*TMath::Pi(), 3./8.*TMath::Pi(), 4./8.*TMath::Pi(), 5./8.*TMath::Pi(), 6./8.*TMath::Pi(), 7./8.*TMath::Pi(), 1.*TMath::Pi(),
// 	10./8.*TMath::Pi(), 11./8.*TMath::Pi(), 12./8.*TMath::Pi(), 13./8.*TMath::Pi(), 14./8.*TMath::Pi(), 15./8.*TMath::Pi(), 2.*TMath::Pi()
//   };

//   Double_t binsPhi[] = {
// 	-2.*TMath::Pi(), -1.75*TMath::Pi(), -1.5*TMath::Pi(), -1.25*TMath::Pi(),
// 	-1.*TMath::Pi(), -0.75*TMath::Pi(), -0.5*TMath::Pi(), -0.25*TMath::Pi(),
// 	0, 0.25*TMath::Pi(), 0.5*TMath::Pi(), 0.75*TMath::Pi(), TMath::Pi(),
// 	1.25*TMath::Pi(), 1.5*TMath::Pi(), 1.75*TMath::Pi(), 2.*TMath::Pi()
//   };
// Double_t binsPhi[] = {
//   0, 0.25*TMath::Pi(), 0.5*TMath::Pi(), 0.75*TMath::Pi(), TMath::Pi()
// };
Double_t binsPhi[] = {
  0, 1./16.*TMath::Pi(), 2./16.*TMath::Pi(), 3./16.*TMath::Pi(), 4./16.*TMath::Pi(), 5./16.*TMath::Pi(), 6./16.*TMath::Pi(), 7./16.*TMath::Pi(), 8./16.*TMath::Pi()
};

// Double_t binsPhi[] = {
//   0, 1./8.*TMath::Pi(), 2./8.*TMath::Pi(), 3./8.*TMath::Pi(), 4./8.*TMath::Pi()
// };

  Int_t nBinPhi = sizeof(binsPhi)/sizeof(Double_t);
  task->SetBinsDeltaphi(nBinPhi, binsPhi);

//   Double_t binsZv[] = {-30.,-10.,-7.5, -5., -2.5 ,0.,2.5, 5., 7.5, 10.,30.};
  Double_t binsZv[] = {-30.,-10.,-8., -6., -4., -2., 0., 2., 4., 6., 8., 10., 30.};
  Int_t nBinsZv = sizeof(binsZv)/sizeof(Double_t);
  task->SetBinsZv(nBinsZv, binsZv);

  task->SetFilterBit(iFilterBit);
  task->SetRequireHybridTracking();
  task->SetNContributorsVertex(1);

  ::Info("AddTask_dNdPt_PbPbAOD",Form("CrossedRowCut set to %.0f", task->GetCutMinNCrossedRowsTPC()));
  ::Info("AddTask_dNdPt_PbPbAOD",Form("FilterBit set to %d", task->GetFilterBit()));

  mgr->AddTask(task);

  AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("%s", combinedName.Data()), TList::Class(),  AliAnalysisManager::kOutputContainer, Form("%s:dNdPtHistos", mgr->GetCommonFileName()));

  mgr->ConnectInput( task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, coutput);

  return task;
}
<commit_msg>keep AddTask backward-compatible<commit_after>AlidNdPtAnalysisPbPbAOD *AddTask_dNdPt_PbPbAOD( UInt_t uTriggerMask = AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral ,
						Double_t dNCrossedRowsTPC = 100,
						Int_t iFilterBit = AliAODTrack::kTrkGlobal,
						char *contName = "dNdPtPbPbAOD",
						Double_t dNClustersTPC = 0,
						Bool_t bDoCutTPCLength = kTRUE,
						Double_t dPrefactorLengthInTPC = 0.85,
						char *centEstimator = "V0M",
						char *suffix = ""
											  )
{
  // Creates, configures and attaches to the train a cascades check task.
  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTask_dNdPt_PbPbAOD", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTask_dNdPt_PbPbAOD", "This task requires an input event handler");
    return NULL;
  }
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

  // Create and configure the task
  TString combinedName;
  combinedName.Form("%s%s",contName, suffix);
  ::Info("AddTask_dNdPt_PbPbAOD",Form("Name of Task: %s", combinedName.Data()));
  AlidNdPtAnalysisPbPbAOD *task = new AlidNdPtAnalysisPbPbAOD(combinedName.Data());
  //   UInt_t triggerMask = AliVEvent::kMB;
  //   triggerMask |= AliVEvent::kCentral;
  //   triggerMask |= AliVEvent::kSemiCentral;

  task->SelectCollisionCandidates(uTriggerMask);

  task->SetCentralityEstimator(centEstimator);

//   char *cDisableTrigger = "",
//
//   task->DisableOnlineTriggerStrings(cDisableTrigger);

  task->SetEventplaneSelector("Q");

  task->SetCutMinNCrossedRowsTPC(dNCrossedRowsTPC);
  task->SetCutMinNClustersTPC(dNClustersTPC);
  task->SetCutLengthInTPCPtDependent(bDoCutTPCLength);
  task->SetPrefactorLengthInTPCPtDependent(dPrefactorLengthInTPC);
  //task->SetCutLengthInTPCPtDependent();
  //
//   task->EnableRelativeCuts();
//   task->SetCutPercMinNClustersTPC(1.0);
//   task->SetCutPercMinNCrossedRowsTPC(1.0);

  Double_t binsPtCheck[] = {0., 0.15, 1.0, 5.0, 10.0, 50.0, 200.0};
  Int_t nBinPtCheck = sizeof(binsPtCheck)/sizeof(Double_t);
  task->SetBinsPtCheck(nBinPtCheck, binsPtCheck);

  Double_t binsPtCorr[] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 200.0};
  Int_t nBinPtCorr = sizeof(binsPtCorr)/sizeof(Double_t);
  task->SetBinsPtCorr(nBinPtCorr, binsPtCorr);

//   Double_t binsPhi[] = {0 ,0.10472 ,0.20944 ,0.314159 ,0.418879 ,0.523599 ,0.628319 ,0.733038 ,0.837758 ,0.942478 ,1.0472 ,1.15192 ,1.25664 ,1.36136 ,1.46608 ,1.5708 ,1.67552 ,1.78024 ,1.88496 ,1.98968 ,2.0944 ,2.19911 ,2.30383 ,2.40855 ,2.51327 ,2.61799 ,2.72271 ,2.82743 ,2.93215 ,3.03687 ,3.14159 ,3.24631 ,3.35103 ,3.45575 ,3.56047 ,3.66519 ,3.76991 ,3.87463 ,3.97935 ,4.08407 ,4.18879 ,4.29351 ,4.39823 ,4.50295 ,4.60767 ,4.71239 ,4.81711 ,4.92183 ,5.02655 ,5.13127 ,5.23599 ,5.34071 ,5.44543 ,5.55015 ,5.65487 ,5.75959 ,5.86431 ,5.96903 ,6.07375 ,6.17847 ,6.28319};

//   Double_t binsPhi[] = {-1.*TMath::Pi(), -2.97625, -2.8109, -2.64555, -2.4802, -2.31486, -2.14951, -1.98416, -1.81882, -1.65347, -1.48812, -1.32278, -1.15743, -0.992082, -0.826735, -0.661388, -0.496041, -0.330694, -0.165347, 0, 0.165347, 0.330694, 0.496041, 0.661388, 0.826735, 0.992082, 1.15743, 1.32278, 1.48812, 1.65347, 1.81882, 1.98416, 2.14951, 2.31486, 2.4802, 2.64555, 2.8109, 2.97625, TMath::Pi()};

//   Double_t binsPhi[] = {-1.*TMath::Pi(), -0.75*TMath::Pi(), -0.5*TMath::Pi(), -0.25*TMath::Pi(), 0, 0.25*TMath::Pi(), 0.5*TMath::Pi(), 0.75*TMath::Pi(), TMath::Pi()};
//   Double_t binsPhi[] = {
// 	-2.*TMath::Pi(), -15./8.*TMath::Pi(), -14./8.*TMath::Pi(), -13./8.*TMath::Pi(), -12./8.*TMath::Pi(), -11./8.*TMath::Pi(), -10./8.*TMath::Pi(), -9./8.*TMath::Pi(),
// 	-1.*TMath::Pi(), -7./8.*TMath::Pi(), -6./8.*TMath::Pi(), -5./8.*TMath::Pi(),  -4./8.*TMath::Pi(), -3./8.*TMath::Pi(), -2./8.*TMath::Pi(), -1./8.*TMath::Pi(),  0,
// 	1./8.*TMath::Pi(), 2./8.*TMath::Pi(), 3./8.*TMath::Pi(), 4./8.*TMath::Pi(), 5./8.*TMath::Pi(), 6./8.*TMath::Pi(), 7./8.*TMath::Pi(), 1.*TMath::Pi(),
// 	10./8.*TMath::Pi(), 11./8.*TMath::Pi(), 12./8.*TMath::Pi(), 13./8.*TMath::Pi(), 14./8.*TMath::Pi(), 15./8.*TMath::Pi(), 2.*TMath::Pi()
//   };

//   Double_t binsPhi[] = {
// 	-2.*TMath::Pi(), -1.75*TMath::Pi(), -1.5*TMath::Pi(), -1.25*TMath::Pi(),
// 	-1.*TMath::Pi(), -0.75*TMath::Pi(), -0.5*TMath::Pi(), -0.25*TMath::Pi(),
// 	0, 0.25*TMath::Pi(), 0.5*TMath::Pi(), 0.75*TMath::Pi(), TMath::Pi(),
// 	1.25*TMath::Pi(), 1.5*TMath::Pi(), 1.75*TMath::Pi(), 2.*TMath::Pi()
//   };
// Double_t binsPhi[] = {
//   0, 0.25*TMath::Pi(), 0.5*TMath::Pi(), 0.75*TMath::Pi(), TMath::Pi()
// };
Double_t binsPhi[] = {
  0, 1./16.*TMath::Pi(), 2./16.*TMath::Pi(), 3./16.*TMath::Pi(), 4./16.*TMath::Pi(), 5./16.*TMath::Pi(), 6./16.*TMath::Pi(), 7./16.*TMath::Pi(), 8./16.*TMath::Pi()
};

// Double_t binsPhi[] = {
//   0, 1./8.*TMath::Pi(), 2./8.*TMath::Pi(), 3./8.*TMath::Pi(), 4./8.*TMath::Pi()
// };

  Int_t nBinPhi = sizeof(binsPhi)/sizeof(Double_t);
  task->SetBinsDeltaphi(nBinPhi, binsPhi);

//   Double_t binsZv[] = {-30.,-10.,-7.5, -5., -2.5 ,0.,2.5, 5., 7.5, 10.,30.};
  Double_t binsZv[] = {-30.,-10.,-8., -6., -4., -2., 0., 2., 4., 6., 8., 10., 30.};
  Int_t nBinsZv = sizeof(binsZv)/sizeof(Double_t);
  task->SetBinsZv(nBinsZv, binsZv);

  task->SetFilterBit(iFilterBit);
//   task->SetRequireHybridTracking();
//   task->SetNContributorsVertex(1);

  ::Info("AddTask_dNdPt_PbPbAOD",Form("CrossedRowCut set to %.0f", task->GetCutMinNCrossedRowsTPC()));
  ::Info("AddTask_dNdPt_PbPbAOD",Form("FilterBit set to %d", task->GetFilterBit()));

  mgr->AddTask(task);

  AliAnalysisDataContainer *coutput = mgr->CreateContainer(Form("%s", combinedName.Data()), TList::Class(),  AliAnalysisManager::kOutputContainer, Form("%s:dNdPtHistos", mgr->GetCommonFileName()));

  mgr->ConnectInput( task, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 1, coutput);

  return task;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, Nils Asmussen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of the FreeBSD Project.
 */

#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__
#define __CPU_DTU_ACCEL_SYSCALLSM_HH__

#include "cpu/dtu-accel/accelerator.hh"
#include "sim/system.hh"

class SyscallSM
{
  public:
    enum Operation
    {
        // sent by the DTU if the PF handler is not reachable
        PAGEFAULT = 0,

        // capability creations
        CREATE_SRV,
        CREATE_SESS,
        CREATE_SESS_AT,
        CREATE_RGATE,
        CREATE_SGATE,
        CREATE_MGATE,
        CREATE_MAP,
        CREATE_VPE,

        // capability operations
        ACTIVATE,
        VPE_CTRL,
        VPE_WAIT,
        DERIVE_MEM,

        // capability exchange
        DELEGATE,
        OBTAIN,
        EXCHANGE,
        REVOKE,

        // forwarding
        FORWARD_MSG,
        FORWARD_MEM,
        FORWARD_REPLY,

        // misc
        NOOP,
    };

    enum VPEOp
    {
        VCTRL_INIT,
        VCTRL_START,
        VCTRL_YIELD,
        VCTRL_STOP,
    };

    enum State
    {
        SYSC_SEND,
        SYSC_WAIT,
        SYSC_FETCH,
        SYSC_READ_ADDR,
        SYSC_ACK,
    };

    explicit SyscallSM(DtuAccel *_accel)
        : accel(_accel), state(), stateChanged(), waitForReply(),
          replyAddr(), syscallSize() {}

    std::string stateName() const;

    bool hasStateChanged() const { return stateChanged; }

    void start(Addr size, bool wait = true)
    {
        syscallSize = size;
        state = SYSC_SEND;
        waitForReply = wait;
    }

    PacketPtr tick();

    bool handleMemResp(PacketPtr pkt);

   private:

    DtuAccel *accel;
    State state;
    bool stateChanged;
    bool waitForReply;
    Addr replyAddr;
    Addr syscallSize;
};

#endif /* __CPU_DTU_ACCEL_SYSCALLSM_HH__ */
<commit_msg>DtuAccel: updated syscall numbers.<commit_after>/*
 * Copyright (c) 2016, Nils Asmussen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of the FreeBSD Project.
 */

#ifndef __CPU_DTU_ACCEL_SYSCALLSM_HH__
#define __CPU_DTU_ACCEL_SYSCALLSM_HH__

#include "cpu/dtu-accel/accelerator.hh"
#include "sim/system.hh"

class SyscallSM
{
  public:
    enum Operation
    {
        // sent by the DTU if the PF handler is not reachable
        PAGEFAULT = 0,

        // capability creations
        CREATE_SRV,
        CREATE_SESS,
        CREATE_RGATE,
        CREATE_SGATE,
        CREATE_MGATE,
        CREATE_MAP,
        CREATE_VPE,

        // capability operations
        ACTIVATE,
        VPE_CTRL,
        VPE_WAIT,
        DERIVE_MEM,
        OPEN_SESS,

        // capability exchange
        DELEGATE,
        OBTAIN,
        EXCHANGE,
        REVOKE,

        // forwarding
        FORWARD_MSG,
        FORWARD_MEM,
        FORWARD_REPLY,

        // misc
        NOOP,
    };

    enum VPEOp
    {
        VCTRL_INIT,
        VCTRL_START,
        VCTRL_YIELD,
        VCTRL_STOP,
    };

    enum State
    {
        SYSC_SEND,
        SYSC_WAIT,
        SYSC_FETCH,
        SYSC_READ_ADDR,
        SYSC_ACK,
    };

    explicit SyscallSM(DtuAccel *_accel)
        : accel(_accel), state(), stateChanged(), waitForReply(),
          replyAddr(), syscallSize() {}

    std::string stateName() const;

    bool hasStateChanged() const { return stateChanged; }

    void start(Addr size, bool wait = true)
    {
        syscallSize = size;
        state = SYSC_SEND;
        waitForReply = wait;
    }

    PacketPtr tick();

    bool handleMemResp(PacketPtr pkt);

   private:

    DtuAccel *accel;
    State state;
    bool stateChanged;
    bool waitForReply;
    Addr replyAddr;
    Addr syscallSize;
};

#endif /* __CPU_DTU_ACCEL_SYSCALLSM_HH__ */
<|endoftext|>


<commit_before>/**
 * This file implements the d2/detail/lock_debug_info.hpp header.
 */

#define D2_SOURCE
#include <d2/detail/lock_debug_info.hpp>

#include <algorithm>
#include <boost/assert.hpp>
#include <cstddef>
#include <dbg/frames.hpp>
#include <dbg/symbols.hpp>
#include <iterator>
#include <string>

namespace d2 {
namespace detail {

namespace {
    template <typename OutputIterator>
    class StackFrameSink : public dbg::symsink {
        OutputIterator out_;

    public:
        explicit StackFrameSink(OutputIterator const& out) : out_(out) { }

        virtual void process_function(void const* ip, char const* name,
                                                      char const* module) {
            *out_++ = StackFrame(ip, name, module);
        }
    };
} // end anonymous namespace

void LockDebugInfo::init_call_stack(unsigned int ignore /* = 0 */) {
    dbg::call_stack<100> stack;
    dbg::symdb symbols;
    stack.collect(ignore + 1); // ignore our frame
    call_stack.reserve(stack.size());

    StackFrameSink<std::back_insert_iterator<CallStack> >
                                    sink(std::back_inserter(call_stack));
    for (unsigned int frame = 0; frame < stack.size(); ++frame)
        symbols.lookup_function(stack.pc(frame), sink);

    BOOST_ASSERT_MSG(call_stack.size() == stack.size(),
                    "not all the frames from the dbg::call_stack "
                    "were copied to this->call_stack");
}

namespace {
template <typename String>
class DelimitedString {
    String& data;
    DelimitedString& operator=(DelimitedString const&) /*= delete*/;

public:
    explicit DelimitedString(String& s) : data(s) { }

    friend std::ostream& operator<<(std::ostream& os,
                                    DelimitedString const& self) {
        os << self.data.size() << '|' << self.data;
        return os;
    }

    friend std::istream& operator>>(std::istream& is,
                                    DelimitedString const& self) {
        std::size_t length;
        char sep = 'X';

        if ((is >> length >> sep) && sep == '|' && length > 0) {
            self.data.resize(length);
            is.read(&self.data[0], length);
        }
        return is;
    }
};

template <typename String>
DelimitedString<String> delimit(String& s) {
    return DelimitedString<String>(s);
}
} // end anonymous namespace

extern std::ostream& operator<<(std::ostream& os, StackFrame const& self) {
    os << self.ip << ' '
       << delimit(self.function)
       << delimit(self.module);
    return os;
}

extern std::istream& operator>>(std::istream& is, StackFrame& self) {
    is >> const_cast<void*&>(self.ip) >> std::ws
       >> delimit(self.function)
       >> delimit(self.module);
    return is;
}

extern std::ostream& operator<<(std::ostream& os, LockDebugInfo const& self) {
    os << self.call_stack.size() << '~';
    std::copy(self.call_stack.begin(), self.call_stack.end(),
                std::ostream_iterator<StackFrame>(os));
    return os;
}

extern std::istream& operator>>(std::istream& is, LockDebugInfo& self) {
    std::size_t num_frames;
    char sep = 'X';

    self.call_stack.clear();
    if ((is >> num_frames >> sep) && sep == '~' && num_frames > 0) {
        self.call_stack.reserve(num_frames);
        while (num_frames--) {
            StackFrame frame;
            is >> frame;
            self.call_stack.push_back(frame);
        }
    }

    return is;
}

} // end namespace detail
} // end namespace d2
<commit_msg>Fix a small bug in the lock_debug_info io.<commit_after>/**
 * This file implements the d2/detail/lock_debug_info.hpp header.
 */

#define D2_SOURCE
#include <d2/detail/lock_debug_info.hpp>

#include <algorithm>
#include <boost/assert.hpp>
#include <cstddef>
#include <dbg/frames.hpp>
#include <dbg/symbols.hpp>
#include <iostream>
#include <iterator>
#include <string>

namespace d2 {
namespace detail {

namespace {
    template <typename OutputIterator>
    class StackFrameSink : public dbg::symsink {
        OutputIterator out_;

    public:
        explicit StackFrameSink(OutputIterator const& out) : out_(out) { }

        virtual void process_function(void const* ip, char const* name,
                                                      char const* module) {
            *out_++ = StackFrame(ip, name, module);
        }
    };
} // end anonymous namespace

void LockDebugInfo::init_call_stack(unsigned int ignore /*= 0*/) {
    dbg::call_stack<100> stack;
    dbg::symdb symbols;
    stack.collect(ignore + 1); // ignore our frame
    call_stack.reserve(stack.size());

    StackFrameSink<std::back_insert_iterator<CallStack> >
                                    sink(std::back_inserter(call_stack));
    for (unsigned int frame = 0; frame < stack.size(); ++frame)
        symbols.lookup_function(stack.pc(frame), sink);

    BOOST_ASSERT_MSG(call_stack.size() == stack.size(),
                    "not all the frames from the dbg::call_stack "
                    "were copied to this->call_stack");
}

namespace {
template <typename String>
class DelimitedString {
    String& data;
    DelimitedString& operator=(DelimitedString const&) /*= delete*/;

public:
    explicit DelimitedString(String& s) : data(s) { }

    friend std::ostream& operator<<(std::ostream& os,
                                    DelimitedString const& self) {
        os << self.data.size() << '|' << self.data;
        return os;
    }

    friend std::istream& operator>>(std::istream& is,
                                    DelimitedString const& self) {
        std::size_t length;
        char sep = 'X';

        if (is >> length >> sep) {
            if (sep == '|') {
                if (length > 0) {
                    self.data.resize(length);
                    is.read(&self.data[0], length);
                }
            } else {
                is.setstate(std::ios_base::failbit);
            }
        }
        return is;
    }
};

template <typename String>
DelimitedString<String> delimit(String& s) {
    return DelimitedString<String>(s);
}
} // end anonymous namespace

extern std::ostream& operator<<(std::ostream& os, StackFrame const& self) {
    os << self.ip << ' '
       << delimit(self.function)
       << delimit(self.module);
    return os;
}

extern std::istream& operator>>(std::istream& is, StackFrame& self) {
    is >> const_cast<void*&>(self.ip) >> std::ws
       >> delimit(self.function)
       >> delimit(self.module);
    return is;
}

extern std::ostream& operator<<(std::ostream& os, LockDebugInfo const& self) {
    os << self.call_stack.size() << '~';
    std::copy(self.call_stack.begin(), self.call_stack.end(),
                std::ostream_iterator<StackFrame>(os));
    return os;
}

extern std::istream& operator>>(std::istream& is, LockDebugInfo& self) {
    std::size_t num_frames;
    char sep = 'X';

    self.call_stack.clear();
    if (is >> num_frames >> sep) {
        if (sep == '~') {
            if (num_frames > 0) {
                self.call_stack.reserve(num_frames);
                while (num_frames--) {
                    StackFrame frame;
                    is >> frame;
                    self.call_stack.push_back(frame);
                }
            }
        } else {
            is.setstate(std::ios_base::failbit);
        }
    }

    return is;
}

} // end namespace detail
} // end namespace d2
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <std_msgs/String.h>
#include <string>
#include "serialDriver.c"
#include <sstream>      // std::stringstream

class serialListener{
	public:
	ros::NodeHandle handle;
	ros::Publisher arduino;
	std_msgs::String serialmsg;
	int checklastln(const char* toCheck , int maxLength){
		for(int i=0;i<maxLength;i++){
			if(toCheck[i]==10){
				return 1;
			}
			if(toCheck[i]==0){
				return 0;
			}
		}
	}
	std::stringstream read;
	void poll(){
		ROS_INFO("polling");
		read<<(char*)readline();

		if(read.str()[0]!=0&&read.str()[0]!=10){
			serialmsg.data=read.str();
			if(checklastln(read.str().c_str(),255)){
				arduino.publish(serialmsg);
				ROS_INFO("SerialListener: Read %s", read.str());
				read.str("");
			}
		}
	}

	serialListener():handle("~"){
		arduino=handle.advertise<std_msgs::String>("/tawi/arduino/serial",100);
	}
};

int main (int argc, char **argv){
	ros::init(argc, argv, "serialListener");
	serialListener serial;
	ros::Rate hz(5);
	while(ros::ok()){
		serial.poll();
		ros::spinOnce();
		hz.sleep();
	}
}
<commit_msg> serial<commit_after>#include <ros/ros.h>
#include <std_msgs/String.h>
#include <string>
#include "serialDriver.c"
#include <sstream>      // std::stringstream

class serialListener{
	public:
	ros::NodeHandle handle;
	ros::Publisher arduino;
	std_msgs::String serialmsg;
	int checklastln(const char* toCheck , int maxLength){
		for(int i=0;i<maxLength;i++){
			if(toCheck[i]==10){
				return 1;
			}
			if(toCheck[i]==0){
				return 0;
			}
		}
	}
	std::stringstream read;
	void poll(){
		ROS_INFO("polling");
		read<<(char*)readline();

		if(read.str()[0]!=0&&read.str()[0]!=10){
			serialmsg.data=read.str();
			ROS_INFO("SerialListener:received data: %s" , read.str());
			if(checklastln(read.str().c_str(),255)){
				arduino.publish(serialmsg);
				ROS_INFO("SerialListener: Read %s", read.str());
				read.str("");
			}
		}
	}

	serialListener():handle("~"){
		arduino=handle.advertise<std_msgs::String>("/tawi/arduino/serial",100);
	}
};

int main (int argc, char **argv){
	ros::init(argc, argv, "serialListener");
	serialListener serial;
	ros::Rate hz(5);
	while(ros::ok()){
		serial.poll();
		ros::spinOnce();
		hz.sleep();
	}
}
<|endoftext|>


<commit_before>#include "httpClientTask.h"

#include <ArduinoJson.h>
#include "config.h"
#include "timeTask.h"
#include "ir-stationTask.h"

#define SERVER_HOSTNAME   "ir.kerikeri.top"
#define SERVER_PORT       80

bool notifyIP(bool isUpdate) {
  WiFiClient client;
  if (!client.connect(SERVER_HOSTNAME, SERVER_PORT)) {
    println_dbg("Error: Connection Failed");
    return false;
  }
  String local_ip = String(WiFi.localIP()[0], DEC) + "." + String(WiFi.localIP()[1], DEC) + "." + String(WiFi.localIP()[2], DEC) + "." + String(WiFi.localIP()[3], DEC);
  client.println((String)"GET /app.rb?notify=" + (isUpdate ? "update" : "remove") + "&name=" + station.mdns_hostname + "&local_ip=" + local_ip + " HTTP/1.1");
  client.println("Host: "SERVER_HOSTNAME);
  client.println("");

  uint32_t timestamp = millis();
  uint32_t timeout = 2000;
  /* サーバーからの返答を待つ */
  while (true) {
    wdt_reset();

    /* サーバーから返答が来たら離脱 */
    if (client.available()) break;

    /* タイムアウト処理 */
    if (millis() - timestamp > timeout) {
      println_dbg("Timeout: Read Server");
      return false;
    }
  }
  client.setTimeout(10);
  String resp = client.readString();
  resp.replace("\r", "");
  resp.replace("\n", " ");
  print_dbg("Response: ");
  println_dbg(resp);
  client.stop();

  return true;
}

void notifyTask() {
  static uint32_t prev_sec;
  static IPAddress prev_local_ip;
  uint32_t now_sec = now();
  IPAddress now_local_ip = WiFi.localIP();
  if ((now_local_ip != prev_local_ip) || (now_sec > prev_sec + 300)) {
    if (!notifyIP()) {
      delay(1000);
      notifyIP();
    }
    prev_local_ip = now_local_ip;
    prev_sec = now_sec;
  }
}
<commit_msg>サーバー名を変更<commit_after>#include "httpClientTask.h"

#include <ArduinoJson.h>
#include "config.h"
#include "timeTask.h"
#include "ir-stationTask.h"

#define SERVER_HOSTNAME   "ir-station.link"
#define SERVER_PORT       80

bool notifyIP(bool isUpdate) {
  WiFiClient client;
  if (!client.connect(SERVER_HOSTNAME, SERVER_PORT)) {
    println_dbg("Error: Connection Failed");
    return false;
  }
  String local_ip = String(WiFi.localIP()[0], DEC) + "." + String(WiFi.localIP()[1], DEC) + "." + String(WiFi.localIP()[2], DEC) + "." + String(WiFi.localIP()[3], DEC);
  client.println((String)"GET /app.rb?notify=" + (isUpdate ? "update" : "remove") + "&name=" + station.mdns_hostname + "&local_ip=" + local_ip + " HTTP/1.1");
  client.println("Host: "SERVER_HOSTNAME);
  client.println("");

  uint32_t timestamp = millis();
  uint32_t timeout = 2000;
  /* サーバーからの返答を待つ */
  while (true) {
    wdt_reset();

    /* サーバーから返答が来たら離脱 */
    if (client.available()) break;

    /* タイムアウト処理 */
    if (millis() - timestamp > timeout) {
      println_dbg("Timeout: Read Server");
      return false;
    }
  }
  client.setTimeout(10);
  String resp = client.readString();
  resp.replace("\r", "");
  resp.replace("\n", " ");
  print_dbg("Response: ");
  println_dbg(resp);
  client.stop();

  return true;
}

void notifyTask() {
  static uint32_t prev_sec;
  static IPAddress prev_local_ip;
  uint32_t now_sec = now();
  IPAddress now_local_ip = WiFi.localIP();
  if ((now_local_ip != prev_local_ip) || (now_sec > prev_sec + 300)) {
    if (!notifyIP()) {
      delay(1000);
      notifyIP();
    }
    prev_local_ip = now_local_ip;
    prev_sec = now_sec;
  }
}
<|endoftext|>


<commit_before>#include <ph.h>
#include <phstream.h>
#include <phInput.h>
#include <phBC.h>
#include <phRestart.h>
#include <phAdapt.h>
#include <phOutput.h>
#include <phPartition.h>
#include <phFilterMatching.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfPartition.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <PCU.h>
#include <string>
#include <stdlib.h>

#define SIZET(a) static_cast<size_t>(a)

namespace {

void afterSplit(apf::Mesh2* m, ph::Input& in, ph::Output& out,
    ph::BCs& bcs, int numMasters)
{
  std::string path = ph::setupOutputDir();
  ph::setupOutputSubdir(path);
  /* check if the mesh changed at all */
  if ((PCU_Comm_Peers()!=numMasters) ||
      in.adaptFlag ||
      in.tetrahedronize) {
    if (in.parmaPtn && PCU_Comm_Peers() > 1)
      ph::balance(in,m);
    apf::reorderMdsMesh(m);
  }
  ph::enterFilteredMatching(m, in, bcs);
  ph::generateOutput(in, bcs, m, out);
  ph::exitFilteredMatching(m);
  // a path is not needed for inmem
  ph::detachAndWriteSolution(in,out,m,path); //write restart
  ph::writeGeomBC(out, path); //write geombc
  ph::writeAuxiliaryFiles(path, in.timeStepNumber);
  if ( ! in.outMeshFileName.empty() )
    m->writeNative(in.outMeshFileName.c_str());
  m->verify();
}

void switchToMasters(int splitFactor)
{
  int self = PCU_Comm_Self();
  int groupRank = self / splitFactor;
  int group = self % splitFactor;
  MPI_Comm groupComm;
  MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm);
  PCU_Switch_Comm(groupComm);
}

void switchToAll()
{
  MPI_Comm prevComm = PCU_Get_Comm();
  PCU_Switch_Comm(MPI_COMM_WORLD);
  MPI_Comm_free(&prevComm);
  PCU_Barrier();
}

void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g)
{
  ph::readBCs(in.attributeFileName.c_str(), bcs);
  if(!g)
    g = gmi_load(in.modelFileName.c_str());
}

void originalMain(apf::Mesh2*& m, ph::Input& in,
    gmi_model* g, apf::Migration*& plan)
{
  if(!m)
    m = apf::loadMdsMesh(g, in.meshFileName.c_str());
  else
    apf::printStats(m);
  m->verify();
  if (in.solutionMigration)
    ph::readAndAttachSolution(in, m);
  else
    ph::attachZeroSolution(in, m);
  if (in.buildMapping)
    ph::buildMapping(m);
  apf::setMigrationLimit(SIZET(in.elementsPerMigration));
  if (in.adaptFlag)
    ph::adapt(in, m);
  if (in.tetrahedronize)
    ph::tetrahedronize(in, m);
  plan = ph::split(in, m);
}

}//end namespace

namespace chef {
  static FILE* openfile_read(ph::Input&, const char* path) {
    fprintf(stderr, "------entering %s-------\n", __func__);
    return fopen(path, "r");
  }

  static FILE* openfile_write(ph::Output&, const char* path) {
    fprintf(stderr, "------entering %s-------\n", __func__);
    return fopen(path, "w");
  }

  static FILE* openstream_write(ph::Output& out, const char* path) {
    fprintf(stderr, "------entering %s-------\n", __func__);
    return openGRStreamWrite(out.grs, path);
  }

  static FILE* openstream_read(ph::Input& in, const char* path) {
    fprintf(stderr, "------entering %s-------\n", __func__);
    std::string fname(path);
    std::string restartStr("restart");
    FILE* f = NULL;
    if( fname.find(restartStr) != std::string::npos )
      f = openRStreamRead(in.rs);
    else {
      fprintf(stderr,
        "ERROR %s type of stream %s is unknown... exiting\n",
        __func__, fname.c_str());
      exit(1);
    }
    return f;
  }
  void bake(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& in, ph::Output& out) {
    apf::Migration* plan = 0;
    ph::BCs bcs;
    loadCommon(in, bcs, g);
    const int worldRank = PCU_Comm_Self();
    switchToMasters(in.splitFactor);
    const int numMasters = PCU_Comm_Peers();
    if ((worldRank % in.splitFactor) == 0)
      originalMain(m, in, g, plan);
    switchToAll();
    if (in.adaptFlag)
      ph::goToStepDir(in.timeStepNumber);
    m = repeatMdsMesh(m, g, plan, in.splitFactor);
    afterSplit(m,in,out,bcs,numMasters);
    if (in.adaptFlag)
      ph::goToParentDir();
  }
  void cook(gmi_model*& g, apf::Mesh2*& m) {
    ph::Input in;
    in.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    in.load("adapt.inp");
    bake(g,m,in,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, GRStream* grs) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
    return;
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs, GRStream* grs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
    return;
  }
}
<commit_msg>load the model and bcs with simmetrix support<commit_after>#include <ph.h>
#include <phstream.h>
#include <phInput.h>
#include <phBC.h>
#include <phRestart.h>
#include <phAdapt.h>
#include <phOutput.h>
#include <phPartition.h>
#include <phFilterMatching.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apfPartition.h>
#include <apf.h>
#include <gmi_mesh.h>
#include <PCU.h>
#include <string>
#include <stdlib.h>

#define SIZET(a) static_cast<size_t>(a)

namespace {

void afterSplit(apf::Mesh2* m, ph::Input& in, ph::Output& out,
    ph::BCs& bcs, int numMasters)
{
  std::string path = ph::setupOutputDir();
  ph::setupOutputSubdir(path);
  /* check if the mesh changed at all */
  if ((PCU_Comm_Peers()!=numMasters) ||
      in.adaptFlag ||
      in.tetrahedronize) {
    if (in.parmaPtn && PCU_Comm_Peers() > 1)
      ph::balance(in,m);
    apf::reorderMdsMesh(m);
  }
  ph::enterFilteredMatching(m, in, bcs);
  ph::generateOutput(in, bcs, m, out);
  ph::exitFilteredMatching(m);
  // a path is not needed for inmem
  ph::detachAndWriteSolution(in,out,m,path); //write restart
  ph::writeGeomBC(out, path); //write geombc
  ph::writeAuxiliaryFiles(path, in.timeStepNumber);
  if ( ! in.outMeshFileName.empty() )
    m->writeNative(in.outMeshFileName.c_str());
  m->verify();
}

void switchToMasters(int splitFactor)
{
  int self = PCU_Comm_Self();
  int groupRank = self / splitFactor;
  int group = self % splitFactor;
  MPI_Comm groupComm;
  MPI_Comm_split(MPI_COMM_WORLD, group, groupRank, &groupComm);
  PCU_Switch_Comm(groupComm);
}

void switchToAll()
{
  MPI_Comm prevComm = PCU_Get_Comm();
  PCU_Switch_Comm(MPI_COMM_WORLD);
  MPI_Comm_free(&prevComm);
  PCU_Barrier();
}

void loadCommon(ph::Input& in, ph::BCs& bcs, gmi_model*& g)
{
  ph::loadModelAndBCs(in, g, bcs);
}

void originalMain(apf::Mesh2*& m, ph::Input& in,
    gmi_model* g, apf::Migration*& plan)
{
  if(!m)
    m = apf::loadMdsMesh(g, in.meshFileName.c_str());
  else
    apf::printStats(m);
  m->verify();
  if (in.solutionMigration)
    ph::readAndAttachSolution(in, m);
  else
    ph::attachZeroSolution(in, m);
  if (in.buildMapping)
    ph::buildMapping(m);
  apf::setMigrationLimit(SIZET(in.elementsPerMigration));
  if (in.adaptFlag)
    ph::adapt(in, m);
  if (in.tetrahedronize)
    ph::tetrahedronize(in, m);
  plan = ph::split(in, m);
}

}//end namespace

namespace chef {
  static FILE* openfile_read(ph::Input&, const char* path) {
    fprintf(stderr, "------entering %s-------\n", __func__);
    return fopen(path, "r");
  }

  static FILE* openfile_write(ph::Output&, const char* path) {
    fprintf(stderr, "------entering %s-------\n", __func__);
    return fopen(path, "w");
  }

  static FILE* openstream_write(ph::Output& out, const char* path) {
    fprintf(stderr, "------entering %s-------\n", __func__);
    return openGRStreamWrite(out.grs, path);
  }

  static FILE* openstream_read(ph::Input& in, const char* path) {
    fprintf(stderr, "------entering %s-------\n", __func__);
    std::string fname(path);
    std::string restartStr("restart");
    FILE* f = NULL;
    if( fname.find(restartStr) != std::string::npos )
      f = openRStreamRead(in.rs);
    else {
      fprintf(stderr,
        "ERROR %s type of stream %s is unknown... exiting\n",
        __func__, fname.c_str());
      exit(1);
    }
    return f;
  }
  void bake(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& in, ph::Output& out) {
    apf::Migration* plan = 0;
    ph::BCs bcs;
    loadCommon(in, bcs, g);
    const int worldRank = PCU_Comm_Self();
    switchToMasters(in.splitFactor);
    const int numMasters = PCU_Comm_Peers();
    if ((worldRank % in.splitFactor) == 0)
      originalMain(m, in, g, plan);
    switchToAll();
    if (in.adaptFlag)
      ph::goToStepDir(in.timeStepNumber);
    m = repeatMdsMesh(m, g, plan, in.splitFactor);
    afterSplit(m,in,out,bcs,numMasters);
    if (in.adaptFlag)
      ph::goToParentDir();
  }
  void cook(gmi_model*& g, apf::Mesh2*& m) {
    ph::Input in;
    in.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    in.load("adapt.inp");
    bake(g,m,in,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, GRStream* grs) {
    ctrl.openfile_read = openfile_read;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openfile_write;
    bake(g,m,ctrl,out);
    return;
  }
  void cook(gmi_model*& g, apf::Mesh2*& m,
      ph::Input& ctrl, RStream* rs, GRStream* grs) {
    ctrl.openfile_read = openstream_read;
    ctrl.rs = rs;
    ph::Output out;
    out.openfile_write = openstream_write;
    out.grs = grs;
    bake(g,m,ctrl,out);
    return;
  }
}
<|endoftext|>


<commit_before>/*
 * File:   stick.cc
 * Author: Francis James Franklin <fjf@alinameridon.com>
 *
 * 21.11.2017 Changed to C++ with option added for Arduino communication
 * 16.03.2017 Created - C program for serial communication with PIC
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

#include "stick.hh"

void list_pic_help () {
  int count = 0;

  while (s_help[count]) {
    fprintf (stdout, "  %s\n", s_help[count]);
    ++count;
  }
}

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

  fd_set fdset;

  struct timeval tv;
  struct termios ttystate, ttysave, options;

  unsigned char buffer[16];

  const char * device = "/dev/serial0";

  int count;
  int fd;

  bool bArduino = false;

  for (int arg = 1; arg < argc; arg++) {
    if (strcmp (argv[arg], "--help") == 0) {
      fprintf (stderr, "\nstick [--help] [--list] [--usb] [--arduino] [/dev/<ID>]\n\n");
      fprintf (stderr, "  --help     Display this help.\n");
      fprintf (stderr, "  --list     List available PIC commands.\n");
      fprintf (stderr, "  --usb      Connect to /dev/ttyUSB0 by default.\n");
      fprintf (stderr, "  --arduino  Connect to /dev/ttyACM0 by default, and omit PIC-specific behaviour.\n");
      fprintf (stderr, "  /dev/<ID>  Connect to /dev/<ID> instead of default [/dev/serial0].\n\n");
      return 0;
    }
    if (strcmp (argv[arg], "--list") == 0) {
      list_pic_help ();
      return 0;
    }
    if (strcmp (argv[arg], "--usb") == 0) {
      device = "/dev/ttyUSB0"; // first serial-over-usb on linux
    } else if (strcmp (argv[arg], "--arduino") == 0) {
      device = "/dev/ttyACM0"; // first serial-over-usb on pi
      bArduino = true;
    } else if (strncmp (argv[arg], "/dev/", 5) == 0) {
      device = argv[arg];
    } else {
      fprintf (stderr, "stick [--help] [--list] [--usb] [--arduino] [/dev/ID]\n");
      return -1;
    }
  }

  /* set up serial
   */
  fprintf (stderr, "Opening \"%s\"...\n", device);

  fd = open (device, O_RDWR | O_NOCTTY | O_NONBLOCK /* O_NDELAY */);
  if (fd == -1) {
    fprintf (stderr, "Failed to open \"%s\" - exiting.\n", device);
    return -1;
  }

  tcgetattr (fd, &options);

  options.c_cflag = CS8 | CLOCAL | CREAD;
  options.c_iflag = IGNPAR;
  options.c_oflag = 0;
  options.c_lflag = 0;

  cfsetispeed (&options, B115200);
  cfsetospeed (&options, B115200);

  tcflush (fd, TCIFLUSH);
  tcsetattr (fd, TCSANOW, &options);

  /* set up terminal
   */
  tcgetattr (STDIN_FILENO, &ttystate);

  ttysave = ttystate;

  ttystate.c_lflag &= ~(ICANON | ECHO);
  ttystate.c_cc[VMIN] = 1;

  if (tcsetattr (STDIN_FILENO, TCSANOW, &ttystate)) {
    fprintf (stderr, "error: unable to set serial attributes correctly\n");
  }

  if (!bArduino)
    if (write (fd, (const unsigned char *) "0D\n0F)02)0E)", 12) < 0) {
      fprintf (stderr, "error: unable to write to serial\n");
      return -1;
    }

  while (true) {
    count = read (fd, buffer, 10);
    if (count > 0) {
      buffer[count] = 0;
      fprintf (stdout, "%s", (const char *) buffer);
      fflush (stdout);
    }

    tv.tv_sec = 0;
    tv.tv_usec = 10000;

    FD_ZERO (&fdset);
    FD_SET (fileno (stdin), &fdset);

    select (fileno (stdin) + 1, &fdset, 0, 0, &tv);

    if (FD_ISSET (fileno (stdin), &fdset)) { // character
      c = fgetc (stdin);
      if (c == 4) { // CTRL-D - End of Transmission
	fprintf (stderr, "\nbye bye!\n");
	break;
      }
      if (c == 27) { // ESC
	if (!bArduino) {
	  if (write (fd, (const unsigned char *) "0D\n0F)02)0E)", 12) < 0) {
	    fprintf (stderr, "error: unable to write to serial\n");
	    break;
	  }
	  continue;
	}
	c = 3; // send ^C to the Uno
      }
      if ((c == '?') && !bArduino) {
	fprintf (stderr, "\n");
	list_pic_help ();
	continue;
      }
      if (write (fd, &c, 1) < 0) {
	fprintf (stderr, "error: unable to write to serial\n");
	break;
      }
      usleep (100000);
    }
  }

  /* probably unnecessary - restore terminal
   */
  tcsetattr (STDIN_FILENO, TCSANOW, &ttysave);

  close (fd); // close serial

  return 0;
}
<commit_msg>Add options to echo typing and log session.<commit_after>/*
 * File:   stick.cc
 * Author: Francis James Franklin <fjf@alinameridon.com>
 *
 * 21.11.2017 Changed to C++ with option added for Arduino communication
 * 16.03.2017 Created - C program for serial communication with PIC
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>

#include "stick.hh"

void list_pic_help () {
  int count = 0;

  while (s_help[count]) {
    fprintf (stdout, "  %s\n", s_help[count]);
    ++count;
  }
}

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

  fd_set fdset;

  struct timeval tv;
  struct termios ttystate, ttysave, options;

  unsigned char buffer[16];

  const char * device = "/dev/serial0";
  const char * logname = 0;

  FILE * log = 0;

  int count;
  int fd;

  bool bArduino = false;
  bool bEcho = false;

  for (int arg = 1; arg < argc; arg++) {
    if (strcmp (argv[arg], "--help") == 0) {
      fprintf (stderr, "\nstick [--help] [--echo] [--log=<file>] [--list] [--usb] [--arduino] [/dev/<ID>]\n\n");
      fprintf (stderr, "  --help     Display this help.\n");
      fprintf (stderr, "  --echo     Echo typed characters to the terminal window.\n");
      fprintf (stderr, "  --list     List available PIC commands.\n");
      fprintf (stderr, "  --usb      Connect to /dev/ttyUSB0 by default.\n");
      fprintf (stderr, "  --arduino  Connect to /dev/ttyACM0 by default, and omit PIC-specific behaviour.\n");
      fprintf (stderr, "  /dev/<ID>  Connect to /dev/<ID> instead of default [/dev/serial0].\n\n");
      return 0;
    }
    if (strcmp (argv[arg], "--list") == 0) {
      list_pic_help ();
      return 0;
    }
    if (strcmp (argv[arg], "--echo") == 0) {
      bEcho = true;
    } else if (strcmp (argv[arg], "--usb") == 0) {
      device = "/dev/ttyUSB0"; // first serial-over-usb on linux
    } else if (strcmp (argv[arg], "--arduino") == 0) {
      device = "/dev/ttyACM0"; // first serial-over-usb on pi
      bArduino = true;
    } else if (strncmp (argv[arg], "--log=", 6) == 0) {
      logname = argv[arg] + 6;
    } else if (strncmp (argv[arg], "/dev/", 5) == 0) {
      device = argv[arg];
    } else {
      fprintf (stderr, "stick [--help] [--echo] [--log=<file>] [--list] [--usb] [--arduino] [/dev/ID]\n");
      return -1;
    }
  }

  if (logname) {
    log = fopen (logname, "w");
    if (!log) {
      fprintf (stderr, "Failed to open \"%s\" - exiting.\n", logname);
      return -1;
    }
  }

  /* set up serial
   */
  fprintf (stderr, "Opening \"%s\"...\n", device);

  fd = open (device, O_RDWR | O_NOCTTY | O_NONBLOCK /* O_NDELAY */);
  if (fd == -1) {
    fprintf (stderr, "Failed to open \"%s\" - exiting.\n", device);
    return -1;
  }

  tcgetattr (fd, &options);

  options.c_cflag = CS8 | CLOCAL | CREAD;
  options.c_iflag = IGNPAR;
  options.c_oflag = 0;
  options.c_lflag = 0;

  cfsetispeed (&options, B115200);
  cfsetospeed (&options, B115200);

  tcflush (fd, TCIFLUSH);
  tcsetattr (fd, TCSANOW, &options);

  /* set up terminal
   */
  tcgetattr (STDIN_FILENO, &ttystate);

  ttysave = ttystate;

  ttystate.c_lflag &= ~(ICANON | ECHO);
  ttystate.c_cc[VMIN] = 1;

  if (tcsetattr (STDIN_FILENO, TCSANOW, &ttystate)) {
    fprintf (stderr, "error: unable to set serial attributes correctly\n");
  }

  if (!bArduino)
    if (write (fd, (const unsigned char *) "0D\n0F)02)0E)", 12) < 0) {
      fprintf (stderr, "error: unable to write to serial\n");
      return -1;
    }

  while (true) {
    count = read (fd, buffer, 10);
    if (count > 0) {
      buffer[count] = 0;
      fprintf (stdout, "%s", (const char *) buffer);
      fflush (stdout);
      if (log) {
        fprintf (log, "%s", (const char *) buffer);
        fflush (log);
      }
    }

    tv.tv_sec = 0;
    tv.tv_usec = 10000;

    FD_ZERO (&fdset);
    FD_SET (fileno (stdin), &fdset);

    select (fileno (stdin) + 1, &fdset, 0, 0, &tv);

    if (FD_ISSET (fileno (stdin), &fdset)) { // character
      c = fgetc (stdin);
      if (c == 4) { // CTRL-D - End of Transmission
	fprintf (stderr, "\nbye bye!\n");
	break;
      }
      if (c == 27) { // ESC
	if (!bArduino) {
	  if (write (fd, (const unsigned char *) "0D\n0F)02)0E)", 12) < 0) {
	    fprintf (stderr, "error: unable to write to serial\n");
	    break;
	  }
	  continue;
	}
	c = 3; // send ^C to the Uno
      }
      if ((c == '?') && !bArduino) {
	fprintf (stderr, "\n");
	list_pic_help ();
	continue;
      }
      if (bEcho) {
        fputc (c, stdout);
        fflush (stdout);
      }
      if (log) {
        fputc (c, log);
        fflush (log);
      }
      if (write (fd, &c, 1) < 0) {
	fprintf (stderr, "error: unable to write to serial\n");
	break;
      }
      usleep (1000);
    }
  }

  /* probably unnecessary - restore terminal
   */
  tcsetattr (STDIN_FILENO, TCSANOW, &ttysave);

  if (log) {
    fclose (log);
  }
  close (fd); // close serial

  return 0;
}
<|endoftext|>


<commit_before>/*
 * Android File Transfer for Linux: MTP client for android devices
 * Copyright (C) 2015  Vladimir Menshakov

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

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

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

namespace mtp { namespace usb
{
	BulkPipe::BulkPipe(DevicePtr device, ConfigurationPtr conf, InterfacePtr interface, EndpointPtr in, EndpointPtr out, EndpointPtr interrupt):
		_device(device), _conf(conf), _interface(interface), _in(in), _out(out), _interrupt(interrupt)
	{
		int currentConfigurationIndex = _device->GetConfiguration();
		if (conf->GetIndex() != currentConfigurationIndex)
			_device->SetConfiguration(conf->GetIndex());

		_claimToken = _device->ClaimInterface(interface->GetIndex());
	}

	BulkPipe::~BulkPipe()
	{ }

	DevicePtr BulkPipe::GetDevice() const
	{ return _device; }

	ByteArray BulkPipe::ReadInterrupt()
	{
		ByteArray data;//_interrupt->GetMaxPacketSize());
		return data;
	}

	void BulkPipe::Read(const IObjectOutputStreamPtr &outputStream, int timeout)
	{
		_device->ReadBulk(_in, outputStream, timeout);
	}

	void BulkPipe::Write(const IObjectInputStreamPtr &inputStream, int timeout)
	{
		_device->WriteBulk(_out, inputStream, timeout);
	}

	BulkPipePtr BulkPipe::Create(const usb::DevicePtr & device, const ConfigurationPtr & conf, const usb::InterfacePtr & interface)
	{
		int epn = interface->GetEndpointsCount();

		usb::EndpointPtr out, in, interrupt;
		//fprintf(stderr, "endpoints: %d\n", epn);
		for(int i = 0; i < epn; ++i)
		{
			usb::EndpointPtr ep = interface->GetEndpoint(i);
			//fprintf(stderr, "endpoint: %d: %02x\n", i, ep->GetAddress());
			//check for bulk here
			if (ep->GetDirection() == usb::EndpointDirection::Out)
			{
				if (ep->GetType() == usb::EndpointType::Bulk)
				{
					//fprintf(stderr, "OUT\n");
					out = ep;
				}
			}
			else
			{
				if (ep->GetType() == usb::EndpointType::Bulk)
				{
					//fprintf(stderr, "IN\n");
					in = ep;
				}
				else
				{
					//fprintf(stderr, "INTERRUPT\n");
					interrupt = ep;
				}
			}
		}
		if (!in || !out || !interrupt)
			throw std::runtime_error("invalid endpoint");

		return std::make_shared<BulkPipe>(device, conf, interface, in, out, interrupt);
	}

}}
<commit_msg>implemented reading from interrupt ep<commit_after>/*
 * Android File Transfer for Linux: MTP client for android devices
 * Copyright (C) 2015  Vladimir Menshakov

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

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

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
#include <mtp/usb/BulkPipe.h>
#include <usb/DeviceDescriptor.h>
#include <mtp/usb/TimeoutException.h>
#include <mtp/ptp/ByteArrayObjectStream.h>

namespace mtp { namespace usb
{
	BulkPipe::BulkPipe(DevicePtr device, ConfigurationPtr conf, InterfacePtr interface, EndpointPtr in, EndpointPtr out, EndpointPtr interrupt):
		_device(device), _conf(conf), _interface(interface), _in(in), _out(out), _interrupt(interrupt)
	{
		int currentConfigurationIndex = _device->GetConfiguration();
		if (conf->GetIndex() != currentConfigurationIndex)
			_device->SetConfiguration(conf->GetIndex());

		_claimToken = _device->ClaimInterface(interface->GetIndex());
	}

	BulkPipe::~BulkPipe()
	{ }

	DevicePtr BulkPipe::GetDevice() const
	{ return _device; }

	ByteArray BulkPipe::ReadInterrupt()
	{
		ByteArrayObjectOutputStreamPtr s(new ByteArrayObjectOutputStream());
		try { _device->ReadBulk(_interrupt, s, 0); } catch(const TimeoutException &ex) { return ByteArray(); }
		return std::move(s->GetData());
	}

	void BulkPipe::Read(const IObjectOutputStreamPtr &outputStream, int timeout)
	{
		_device->ReadBulk(_in, outputStream, timeout);
	}

	void BulkPipe::Write(const IObjectInputStreamPtr &inputStream, int timeout)
	{
		_device->WriteBulk(_out, inputStream, timeout);
	}

	BulkPipePtr BulkPipe::Create(const usb::DevicePtr & device, const ConfigurationPtr & conf, const usb::InterfacePtr & interface)
	{
		int epn = interface->GetEndpointsCount();

		usb::EndpointPtr out, in, interrupt;
		//fprintf(stderr, "endpoints: %d\n", epn);
		for(int i = 0; i < epn; ++i)
		{
			usb::EndpointPtr ep = interface->GetEndpoint(i);
			//fprintf(stderr, "endpoint: %d: %02x\n", i, ep->GetAddress());
			//check for bulk here
			if (ep->GetDirection() == usb::EndpointDirection::Out)
			{
				if (ep->GetType() == usb::EndpointType::Bulk)
				{
					//fprintf(stderr, "OUT\n");
					out = ep;
				}
			}
			else
			{
				if (ep->GetType() == usb::EndpointType::Bulk)
				{
					//fprintf(stderr, "IN\n");
					in = ep;
				}
				else
				{
					//fprintf(stderr, "INTERRUPT\n");
					interrupt = ep;
				}
			}
		}
		if (!in || !out || !interrupt)
			throw std::runtime_error("invalid endpoint");

		return std::make_shared<BulkPipe>(device, conf, interface, in, out, interrupt);
	}

}}
<|endoftext|>


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

#ifndef DATATYPES_INCLUDED_BY_MASTER_HEADER
    #error "not to be included directly!"
#endif

//--------------------------------------------------------------------
template< typename CONCRETE_DATA_TYPE_IMPL, typename SUPERCLASS >
ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::ODerivedDataType( const ::rtl::OUString& _rName, sal_Int16 _nTypeClass )
    :SUPERCLASS( _rName, _nTypeClass )
    ,m_bPropertiesRegistered( false )
{
}

//--------------------------------------------------------------------
template< typename CONCRETE_DATA_TYPE_IMPL, typename SUPERCLASS >
::cppu::IPropertyArrayHelper* ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::createArrayHelper( ) const
{
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
    ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::describeProperties( aProps );
    return new ::cppu::OPropertyArrayHelper( aProps );
}

//--------------------------------------------------------------------
template< typename CONCRETE_DATA_TYPE_IMPL, typename SUPERCLASS >
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException )
{
    return createPropertySetInfo( getInfoHelper() );
}

//--------------------------------------------------------------------
template< typename CONCRETE_DATA_TYPE_IMPL, typename SUPERCLASS >
::cppu::IPropertyArrayHelper& SAL_CALL ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::getInfoHelper()
{
    if ( !m_bPropertiesRegistered )
    {
        const_cast< ODerivedDataType* >( this )->registerProperties();
        const_cast< ODerivedDataType* >( this )->m_bPropertiesRegistered = true;
    }

    return *ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::getArrayHelper();
}

//--------------------------------------------------------------------
template< typename VALUE_TYPE >
OValueLimitedType< VALUE_TYPE >::OValueLimitedType( const ::rtl::OUString& _rName, sal_Int16 _nTypeClass )
    :OValueLimitedType_Base( _rName, _nTypeClass )
{
}

<commit_msg>INTEGRATION: CWS dba23b (1.4.184); FILE MERGED 2007/06/20 07:01:12 fs 1.4.184.1: #i78223#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: datatypes_impl.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-24 11:55:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef DATATYPES_INCLUDED_BY_MASTER_HEADER
    #error "not to be included directly!"
#endif

//--------------------------------------------------------------------
template< typename CONCRETE_DATA_TYPE_IMPL, typename SUPERCLASS >
ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::ODerivedDataType( const ::rtl::OUString& _rName, sal_Int16 _nTypeClass )
    :SUPERCLASS( _rName, _nTypeClass )
    ,m_bPropertiesRegistered( false )
{
}

//--------------------------------------------------------------------
template< typename CONCRETE_DATA_TYPE_IMPL, typename SUPERCLASS >
::cppu::IPropertyArrayHelper* ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::createArrayHelper( ) const
{
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > aProps;
    ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::describeProperties( aProps );
    return new ::cppu::OPropertyArrayHelper( aProps );
}

//--------------------------------------------------------------------
template< typename CONCRETE_DATA_TYPE_IMPL, typename SUPERCLASS >
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException )
{
        return ::cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper() );
}

//--------------------------------------------------------------------
template< typename CONCRETE_DATA_TYPE_IMPL, typename SUPERCLASS >
::cppu::IPropertyArrayHelper& SAL_CALL ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::getInfoHelper()
{
    if ( !m_bPropertiesRegistered )
    {
        const_cast< ODerivedDataType* >( this )->registerProperties();
        const_cast< ODerivedDataType* >( this )->m_bPropertiesRegistered = true;
    }

    return *ODerivedDataType< CONCRETE_DATA_TYPE_IMPL, SUPERCLASS >::getArrayHelper();
}

//--------------------------------------------------------------------
template< typename VALUE_TYPE >
OValueLimitedType< VALUE_TYPE >::OValueLimitedType( const ::rtl::OUString& _rName, sal_Int16 _nTypeClass )
    :OValueLimitedType_Base( _rName, _nTypeClass )
{
}

<|endoftext|>


<commit_before>#ifndef __PLUGINSETTINGS_HPP__
#define __PLUGINSETTINGS_HPP__

#include "plugin.hpp"

class PluginSettings
{
	HANDLE handle;
	FARAPISETTINGSCONTROL SettingsControl;

public:

	PluginSettings(const GUID &guid, FARAPISETTINGSCONTROL SettingsControl)
	{
		this->SettingsControl = SettingsControl;
		handle = INVALID_HANDLE_VALUE;

		FarSettingsCreate settings={sizeof(FarSettingsCreate),guid,handle};
		if (SettingsControl(INVALID_HANDLE_VALUE,SCTL_CREATE,0,(INT_PTR)&settings))
			handle = settings.Handle;
	}

	~PluginSettings()
	{
	    SettingsControl(handle,SCTL_FREE,0,0);
	}

	int CreateSubKey(int Root, const wchar_t *Name)
	{
		FarSettingsValue value={Root,Name};
		return SettingsControl(handle,SCTL_SUBKEY,0,(INT_PTR)&value);
	}

	const wchar_t *Get(int Root, const wchar_t *Name, const wchar_t *Default)
	{
		FarSettingsItem item={Root,Name,FST_STRING};
		if (SettingsControl(handle,SCTL_GET,0,(INT_PTR)&item))
		{
			return item.String;
		}
		return Default;
	}

	unsigned __int64 Get(int Root, const wchar_t *Name, unsigned __int64 Default)
	{
		FarSettingsItem item={Root,Name,FST_QWORD};
		if (SettingsControl(handle,SCTL_GET,0,(INT_PTR)&item))
		{
			return item.Number;
		}
		return Default;
	}

	__int64      Get(int Root, const wchar_t *Name, __int64 Default) { return (__int64)Get(Root,Name,(unsigned __int64)Default); }
	int          Get(int Root, const wchar_t *Name, int Default)  { return (int)Get(Root,Name,(unsigned __int64)Default); }
	unsigned int Get(int Root, const wchar_t *Name, unsigned int Default) { return (unsigned int)Get(Root,Name,(unsigned __int64)Default); }
	bool         Get(int Root, const wchar_t *Name, bool Default) { return Get(Root,Name,Default?1ull:0ull)?true:false; }

	bool Set(int Root, const wchar_t *Name, const wchar_t *Value)
	{
		FarSettingsItem item={Root,Name,FST_STRING};
		item.String=Value;
		return SettingsControl(handle,SCTL_SET,0,(INT_PTR)&item)!=FALSE;
	}

	bool Set(int Root, const wchar_t *Name, unsigned __int64 Value)
	{
		FarSettingsItem item={Root,Name,FST_QWORD};
		item.Number=Value;
		return SettingsControl(handle,SCTL_SET,0,(INT_PTR)&item)!=FALSE;
	}

	bool Set(int Root, const wchar_t *Name, __int64 Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, int Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, unsigned int Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, bool Value) { return Set(Root,Name,Value?1ull:0ull); }
};

#endif
<commit_msg>add additional get for string<commit_after>#ifndef __PLUGINSETTINGS_HPP__
#define __PLUGINSETTINGS_HPP__

#include "plugin.hpp"

class PluginSettings
{
	HANDLE handle;
	FARAPISETTINGSCONTROL SettingsControl;

public:

	PluginSettings(const GUID &guid, FARAPISETTINGSCONTROL SettingsControl)
	{
		this->SettingsControl = SettingsControl;
		handle = INVALID_HANDLE_VALUE;

		FarSettingsCreate settings={sizeof(FarSettingsCreate),guid,handle};
		if (SettingsControl(INVALID_HANDLE_VALUE,SCTL_CREATE,0,(INT_PTR)&settings))
			handle = settings.Handle;
	}

	~PluginSettings()
	{
	    SettingsControl(handle,SCTL_FREE,0,0);
	}

	int CreateSubKey(int Root, const wchar_t *Name)
	{
		FarSettingsValue value={Root,Name};
		return SettingsControl(handle,SCTL_SUBKEY,0,(INT_PTR)&value);
	}

	const wchar_t *Get(int Root, const wchar_t *Name, const wchar_t *Default)
	{
		FarSettingsItem item={Root,Name,FST_STRING};
		if (SettingsControl(handle,SCTL_GET,0,(INT_PTR)&item))
		{
			return item.String;
		}
		return Default;
	}

	void Get(int Root, const wchar_t *Name, wchar_t *Value, size_t Size, const wchar_t *Default)
	{
		lstrcpyn(Value, Get(Root,Name,Default), Size);
	}

	unsigned __int64 Get(int Root, const wchar_t *Name, unsigned __int64 Default)
	{
		FarSettingsItem item={Root,Name,FST_QWORD};
		if (SettingsControl(handle,SCTL_GET,0,(INT_PTR)&item))
		{
			return item.Number;
		}
		return Default;
	}

	__int64      Get(int Root, const wchar_t *Name, __int64 Default) { return (__int64)Get(Root,Name,(unsigned __int64)Default); }
	int          Get(int Root, const wchar_t *Name, int Default)  { return (int)Get(Root,Name,(unsigned __int64)Default); }
	unsigned int Get(int Root, const wchar_t *Name, unsigned int Default) { return (unsigned int)Get(Root,Name,(unsigned __int64)Default); }
	bool         Get(int Root, const wchar_t *Name, bool Default) { return Get(Root,Name,Default?1ull:0ull)?true:false; }

	bool Set(int Root, const wchar_t *Name, const wchar_t *Value)
	{
		FarSettingsItem item={Root,Name,FST_STRING};
		item.String=Value;
		return SettingsControl(handle,SCTL_SET,0,(INT_PTR)&item)!=FALSE;
	}

	bool Set(int Root, const wchar_t *Name, unsigned __int64 Value)
	{
		FarSettingsItem item={Root,Name,FST_QWORD};
		item.Number=Value;
		return SettingsControl(handle,SCTL_SET,0,(INT_PTR)&item)!=FALSE;
	}

	bool Set(int Root, const wchar_t *Name, __int64 Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, int Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, unsigned int Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, bool Value) { return Set(Root,Name,Value?1ull:0ull); }
};

#endif
<|endoftext|>