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

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/extension/vcs.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/frame.h>
#include <wx/extension/log.h>
#include <wx/extension/stcdlg.h>
#include <wx/extension/util.h>

wxExVCS* wxExVCS::m_Self = NULL;
#if wxUSE_GUI
wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL;
#endif

wxExVCS::wxExVCS()
  : m_Command(VCS_NO_COMMAND)
  , m_FileName(wxExFileName())
{
  Initialize();
}

wxExVCS::wxExVCS(int command_id, const wxExFileName& filename)
  : m_Command(GetType(command_id))
  , m_FileName(filename)
{
  Initialize();
}

wxExVCS::wxExVCS(wxExCommand type, const wxExFileName& filename)
  : m_Command(type)
  , m_FileName(filename)
{
  Initialize();
}

#if wxUSE_GUI
int wxExVCS::ConfigDialog(
  wxWindow* parent,
  const wxString& title) const
{
  std::vector<wxExConfigItem> v;

  std::map<long, const wxString> choices;
  choices.insert(std::make_pair(VCS_NONE, _("None")));
  choices.insert(std::make_pair(VCS_GIT, "GIT"));
  choices.insert(std::make_pair(VCS_SVN, "SVN"));
  v.push_back(wxExConfigItem("VCS", choices));

  v.push_back(wxExConfigItem("GIT", CONFIG_FILEPICKERCTRL));
  v.push_back(wxExConfigItem("SVN", CONFIG_FILEPICKERCTRL));
  v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL));

  return wxExConfigDialog(parent, v, title).ShowModal();
}
#endif

bool wxExVCS::DirExists(const wxFileName& filename) const
{
  switch (GetVCS())
  {
    case VCS_GIT:
      {
      // The .git dir only exists in the root, so check all components.
      wxFileName root(filename.GetPath());

      while (root.DirExists() && root.GetDirCount() > 0)
      {
        wxFileName path(root);
        path.AppendDir(".git");

        if (path.DirExists())
        {
          return true;
        }

        root.RemoveLastDir();
      }
      }
      break;

    case VCS_NONE: break; // prevent wxFAIL

    case VCS_SVN:
      {
      // these cannot be combined, as AppendDir is a void (2.9.1).
      wxFileName path(filename);
      path.AppendDir(".svn");
      return path.DirExists();
      }
      break;

    default: wxFAIL;
  }

  return false;
}

long wxExVCS::Execute()
{
  wxASSERT(m_Command != VCS_NO_COMMAND);

  wxString cwd;
  wxString file;

  if (!m_FileName.IsOk())
  {
    cwd = wxGetCwd();
    wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder")));

    if (m_Command == VCS_ADD)
    {
      file = " " + wxExConfigFirstOf(_("Path"));
    }
  }
  else
  {
    if (GetVCS() == VCS_GIT)
    {
      cwd = wxGetCwd();
      wxSetWorkingDirectory(m_FileName.GetPath());
      file = " \"" + m_FileName.GetFullName() + "\"";
    }
    else
    {
      file = " \"" + m_FileName.GetFullPath() + "\"";
    }
  }

  wxString comment;

  if (m_Command == VCS_COMMIT)
  {
    comment =
      " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\"";
  }

  wxString subcommand;

  if (UseSubcommand())
  {
    subcommand = wxConfigBase::Get()->Read(_("Subcommand"));

    if (!subcommand.empty())
    {
      subcommand = " " + subcommand;
    }
  }

  wxString flags;

  if (UseFlags())
  {
    flags = wxConfigBase::Get()->Read(_("Flags"));

    if (!flags.empty())
    {
      flags = " " + flags;
    }
  }

  m_CommandWithFlags = m_CommandString + flags;

  wxString vcs_bin;

  switch (GetVCS())
  {
    case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read("GIT", "git"); break;
    case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read("SVN", "svn"); break;
    default: wxFAIL;
  }

  if (vcs_bin.empty())
  {
    wxLogError(GetVCSName() + " " + _("path is empty"));
    return -1;
  }

  const wxString commandline =
    vcs_bin + " " + m_CommandString + subcommand + flags + comment + file;

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(commandline);
#endif

  wxArrayString output;
  wxArrayString errors;
  long retValue;

  if ((retValue = wxExecute(
    commandline,
    output,
    errors)) == -1)
  {
    // See also process, same log is shown.
    wxLogError(_("Cannot execute") + ": " + commandline);
  }
  else
  {
    wxExLog::Get()->Log(commandline);
  }

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

  m_Output.clear();

  // First output the errors.
  for (
    size_t i = 0;
    i < errors.GetCount();
    i++)
  {
    m_Output += errors[i] + "\n";
  }

  // Then the normal output, will be empty if there are errors.
  for (
    size_t j = 0;
    j < output.GetCount();
    j++)
  {
    m_Output += output[j] + "\n";
  }

  return retValue;
}

#if wxUSE_GUI
wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)
{
  if (ShowDialog(parent) == wxID_CANCEL)
  {
    return wxID_CANCEL;
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(m_FlagsKey,
      wxConfigBase::Get()->Read(_("Flags")));
  }

  const auto retValue = Execute();

  return (retValue != -1 ? wxID_OK: wxID_CANCEL);
}
#endif

wxExVCS* wxExVCS::Get(bool createOnDemand)
{
  if (m_Self == NULL && createOnDemand)
  {
    m_Self = new wxExVCS;

    // Add default VCS.
    if (!wxConfigBase::Get()->Exists("VCS"))
    {
      // TODO: Add SVN only if svn bin exists on linux.
      wxConfigBase::Get()->Write("VCS", (long)VCS_SVN);
    }
  }

  return m_Self;
}

wxExVCS::wxExCommand wxExVCS::GetType(int command_id) const
{
  if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST)
  {
    return (wxExCommand)(command_id - ID_VCS_LOWEST);
  }
  else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST)
  {
    return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST);
  }
  else
  {
    wxFAIL;
    return VCS_NO_COMMAND;
  }
}

long wxExVCS::GetVCS() const
{
  return wxConfigBase::Get()->ReadLong("VCS", VCS_SVN);
}

const wxString wxExVCS::GetVCSName() const
{
  wxString text;

  switch (GetVCS())
  {
    case VCS_GIT: text = "GIT"; break;
    case VCS_SVN: text = "SVN"; break;
    default: wxFAIL;
  }

  return text;
}

void wxExVCS::Initialize()
{
  if (Use() && m_Command != VCS_NO_COMMAND)
  {
    switch (GetVCS())
    {
      case VCS_GIT:
        switch (m_Command)
        {
          case VCS_ADD:      m_CommandString = "add"; break;
          case VCS_BLAME:    m_CommandString = "blame"; break;
          case VCS_CAT:      break;
          case VCS_COMMIT:   m_CommandString = "commit"; break;
          case VCS_DIFF:     m_CommandString = "diff"; break;
          case VCS_HELP:     m_CommandString = "help"; break;
          case VCS_INFO:     break;
          case VCS_LOG:      m_CommandString = "log"; break;
          case VCS_LS:       break;
          case VCS_PROPLIST: break;
          case VCS_PROPSET:  break;
          case VCS_PUSH:     m_CommandString = "push"; break;
          case VCS_REVERT:   m_CommandString = "revert"; break;
          case VCS_SHOW:     m_CommandString = "show"; break;
          case VCS_STAT:     m_CommandString = "status"; break;
          case VCS_UPDATE:   m_CommandString = "update"; break;
          default:
            wxFAIL;
            break;
        }
        break;

      case VCS_SVN:
        switch (m_Command)
        {
          case VCS_ADD:      m_CommandString = "add"; break;
          case VCS_BLAME:    m_CommandString = "blame"; break;
          case VCS_CAT:      m_CommandString = "cat"; break;
          case VCS_COMMIT:   m_CommandString = "commit"; break;
          case VCS_DIFF:     m_CommandString = "diff"; break;
          case VCS_HELP:     m_CommandString = "help"; break;
          case VCS_INFO:     m_CommandString = "info"; break;
          case VCS_LOG:      m_CommandString = "log"; break;
          case VCS_LS:       m_CommandString = "ls"; break;
          case VCS_PROPLIST: m_CommandString = "proplist"; break;
          case VCS_PROPSET:  m_CommandString = "propset"; break;
          case VCS_PUSH:     break;
          case VCS_REVERT:   m_CommandString = "revert"; break;
          case VCS_SHOW:     break;
          case VCS_STAT:     m_CommandString = "stat"; break;
          case VCS_UPDATE:   m_CommandString = "update"; break;
          default:
            wxFAIL;
            break;
        }
        break;

      default: wxFAIL;
    }

    m_Caption = GetVCSName() + " " + m_CommandString;

    // Currently no flags, as no command was executed.
    m_CommandWithFlags = m_CommandString;

    // Use general key.
    m_FlagsKey = wxString::Format("cvsflags/name%d", m_Command);
  }

  m_Output.clear();
}

bool wxExVCS::IsOpenCommand() const
{
  return
    m_Command == wxExVCS::VCS_BLAME ||
    m_Command == wxExVCS::VCS_CAT ||
    m_Command == wxExVCS::VCS_DIFF;
}

#if wxUSE_GUI
wxStandardID wxExVCS::Request(wxWindow* parent)
{
  wxStandardID retValue;

  if ((retValue = ExecuteDialog(parent)) == wxID_OK)
  {
    ShowOutput(parent);
  }

  return retValue;
}
#endif

wxExVCS* wxExVCS::Set(wxExVCS* vcs)
{
  wxExVCS* old = m_Self;
  m_Self = vcs;
  return old;
}

#if wxUSE_GUI
int wxExVCS::ShowDialog(wxWindow* parent)
{
  std::vector<wxExConfigItem> v;

  if (m_Command == VCS_COMMIT)
  {
    v.push_back(wxExConfigItem(
      _("Revision comment"),
      CONFIG_COMBOBOX,
      wxEmptyString,
      true)); // required
  }

  if (!m_FileName.IsOk() && m_Command != VCS_HELP)
  {
    v.push_back(wxExConfigItem(
      _("Base folder"),
      CONFIG_COMBOBOXDIR,
      wxEmptyString,
      true,
      1000));

    if (m_Command == VCS_ADD)
    {
      v.push_back(wxExConfigItem(
        _("Path"),
        CONFIG_COMBOBOX,
        wxEmptyString,
        true)); // required
    }
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(
      _("Flags"),
      wxConfigBase::Get()->Read(m_FlagsKey));

    v.push_back(wxExConfigItem(_("Flags")));
  }

  if (UseSubcommand())
  {
    v.push_back(wxExConfigItem(_("Subcommand")));
  }

  return wxExConfigDialog(parent,
    v,
    m_Caption).ShowModal();
}
#endif

#if wxUSE_GUI
void wxExVCS::ShowOutput(wxWindow* parent) const
{
  wxString caption = m_Caption;

  if (m_Command != VCS_HELP)
  {
    caption += " " + (m_FileName.IsOk() ?
      m_FileName.GetFullName():
      wxExConfigFirstOf(_("Base folder")));
  }

  // Create a dialog for contents.
  if (m_STCEntryDialog == NULL)
  {
    m_STCEntryDialog = new wxExSTCEntryDialog(
      parent,
      caption,
      m_Output,
      wxEmptyString,
      wxOK,
      wxID_ANY,
      wxDefaultPosition,
      wxSize(350, 50));
  }
  else
  {
    m_STCEntryDialog->SetText(m_Output);
    m_STCEntryDialog->SetTitle(caption);
  }

  // Add a lexer when appropriate.
  if (m_Command == VCS_CAT || m_Command == VCS_BLAME)
  {
    if (m_FileName.GetLexer().IsOk())
    {
      m_STCEntryDialog->SetLexer(m_FileName.GetLexer().GetScintillaLexer());
    }
  }
  else if (m_Command == VCS_DIFF)
  {
    m_STCEntryDialog->SetLexer("diff");
  }
  else
  {
    m_STCEntryDialog->SetLexer(wxEmptyString);
  }

  m_STCEntryDialog->Show();
}
#endif

bool wxExVCS::Use() const
{
  return GetVCS() != VCS_NONE;
}

bool wxExVCS::UseFlags() const
{
  return m_Command != VCS_UPDATE && m_Command != VCS_HELP;
}

bool wxExVCS::UseSubcommand() const
{
  return m_Command == VCS_HELP;
}
<commit_msg>if help flag is specified do not add file argument<commit_after>/******************************************************************************\
* File:          vcs.cpp
* Purpose:       Implementation of wxExVCS class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/extension/vcs.h>
#include <wx/extension/configdlg.h>
#include <wx/extension/defs.h>
#include <wx/extension/frame.h>
#include <wx/extension/log.h>
#include <wx/extension/stcdlg.h>
#include <wx/extension/util.h>

wxExVCS* wxExVCS::m_Self = NULL;
#if wxUSE_GUI
wxExSTCEntryDialog* wxExVCS::m_STCEntryDialog = NULL;
#endif

wxExVCS::wxExVCS()
  : m_Command(VCS_NO_COMMAND)
  , m_FileName(wxExFileName())
{
  Initialize();
}

wxExVCS::wxExVCS(int command_id, const wxExFileName& filename)
  : m_Command(GetType(command_id))
  , m_FileName(filename)
{
  Initialize();
}

wxExVCS::wxExVCS(wxExCommand type, const wxExFileName& filename)
  : m_Command(type)
  , m_FileName(filename)
{
  Initialize();
}

#if wxUSE_GUI
int wxExVCS::ConfigDialog(
  wxWindow* parent,
  const wxString& title) const
{
  std::vector<wxExConfigItem> v;

  std::map<long, const wxString> choices;
  choices.insert(std::make_pair(VCS_NONE, _("None")));
  choices.insert(std::make_pair(VCS_GIT, "GIT"));
  choices.insert(std::make_pair(VCS_SVN, "SVN"));
  v.push_back(wxExConfigItem("VCS", choices));

  v.push_back(wxExConfigItem("GIT", CONFIG_FILEPICKERCTRL));
  v.push_back(wxExConfigItem("SVN", CONFIG_FILEPICKERCTRL));
  v.push_back(wxExConfigItem(_("Comparator"), CONFIG_FILEPICKERCTRL));

  return wxExConfigDialog(parent, v, title).ShowModal();
}
#endif

bool wxExVCS::DirExists(const wxFileName& filename) const
{
  switch (GetVCS())
  {
    case VCS_GIT:
      {
      // The .git dir only exists in the root, so check all components.
      wxFileName root(filename.GetPath());

      while (root.DirExists() && root.GetDirCount() > 0)
      {
        wxFileName path(root);
        path.AppendDir(".git");

        if (path.DirExists())
        {
          return true;
        }

        root.RemoveLastDir();
      }
      }
      break;

    case VCS_NONE: break; // prevent wxFAIL

    case VCS_SVN:
      {
      // these cannot be combined, as AppendDir is a void (2.9.1).
      wxFileName path(filename);
      path.AppendDir(".svn");
      return path.DirExists();
      }
      break;

    default: wxFAIL;
  }

  return false;
}

long wxExVCS::Execute()
{
  wxASSERT(m_Command != VCS_NO_COMMAND);

  wxString cwd;
  wxString file;

  if (!m_FileName.IsOk())
  {
    cwd = wxGetCwd();
    wxSetWorkingDirectory(wxExConfigFirstOf(_("Base folder")));

    if (m_Command == VCS_ADD)
    {
      file = " " + wxExConfigFirstOf(_("Path"));
    }
  }
  else
  {
    if (GetVCS() == VCS_GIT)
    {
      cwd = wxGetCwd();
      wxSetWorkingDirectory(m_FileName.GetPath());
      file = " \"" + m_FileName.GetFullName() + "\"";
    }
    else
    {
      file = " \"" + m_FileName.GetFullPath() + "\"";
    }
  }

  wxString comment;

  if (m_Command == VCS_COMMIT)
  {
    comment =
      " -m \"" + wxExConfigFirstOf(_("Revision comment")) + "\"";
  }

  wxString subcommand;

  if (UseSubcommand())
  {
    subcommand = wxConfigBase::Get()->Read(_("Subcommand"));

    if (!subcommand.empty())
    {
      subcommand = " " + subcommand;
    }
  }

  wxString flags;

  if (UseFlags())
  {
    flags = wxConfigBase::Get()->Read(_("Flags"));

    if (!flags.empty())
    {
      flags = " " + flags;

      // If we specified help flags, we do not need a file argument.
      if (flags.Contains("help"))
      {
        file.clear();
      }
    }
  }

  m_CommandWithFlags = m_CommandString + flags;

  wxString vcs_bin;

  switch (GetVCS())
  {
    case VCS_GIT: vcs_bin = wxConfigBase::Get()->Read("GIT", "git"); break;
    case VCS_SVN: vcs_bin = wxConfigBase::Get()->Read("SVN", "svn"); break;
    default: wxFAIL;
  }

  if (vcs_bin.empty())
  {
    wxLogError(GetVCSName() + " " + _("path is empty"));
    return -1;
  }

  const wxString commandline =
    vcs_bin + " " + m_CommandString + subcommand + flags + comment + file;

#if wxUSE_STATUSBAR
  wxExFrame::StatusText(commandline);
#endif

  wxArrayString output;
  wxArrayString errors;
  long retValue;

  // Call wxExcute to execute the cvs command and
  // collect the output and the errors.
  if ((retValue = wxExecute(
    commandline,
    output,
    errors)) == -1)
  {
    // See also process, same log is shown.
    wxLogError(_("Cannot execute") + ": " + commandline);
  }
  else
  {
    wxExLog::Get()->Log(commandline);
  }

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

  m_Output.clear();

  // First output the errors.
  for (
    size_t i = 0;
    i < errors.GetCount();
    i++)
  {
    m_Output += errors[i] + "\n";
  }

  // Then the normal output, will be empty if there are errors.
  for (
    size_t j = 0;
    j < output.GetCount();
    j++)
  {
    m_Output += output[j] + "\n";
  }

  return retValue;
}

#if wxUSE_GUI
wxStandardID wxExVCS::ExecuteDialog(wxWindow* parent)
{
  if (ShowDialog(parent) == wxID_CANCEL)
  {
    return wxID_CANCEL;
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(m_FlagsKey,
      wxConfigBase::Get()->Read(_("Flags")));
  }

  const auto retValue = Execute();

  return (retValue != -1 ? wxID_OK: wxID_CANCEL);
}
#endif

wxExVCS* wxExVCS::Get(bool createOnDemand)
{
  if (m_Self == NULL && createOnDemand)
  {
    m_Self = new wxExVCS;

    // Add default VCS.
    if (!wxConfigBase::Get()->Exists("VCS"))
    {
      // TODO: Add SVN only if svn bin exists on linux.
      wxConfigBase::Get()->Write("VCS", (long)VCS_SVN);
    }
  }

  return m_Self;
}

wxExVCS::wxExCommand wxExVCS::GetType(int command_id) const
{
  if (command_id > ID_VCS_LOWEST && command_id < ID_VCS_HIGHEST)
  {
    return (wxExCommand)(command_id - ID_VCS_LOWEST);
  }
  else if (command_id > ID_EDIT_VCS_LOWEST && command_id < ID_EDIT_VCS_HIGHEST)
  {
    return (wxExCommand)(command_id - ID_EDIT_VCS_LOWEST);
  }
  else
  {
    wxFAIL;
    return VCS_NO_COMMAND;
  }
}

long wxExVCS::GetVCS() const
{
  return wxConfigBase::Get()->ReadLong("VCS", VCS_SVN);
}

const wxString wxExVCS::GetVCSName() const
{
  wxString text;

  switch (GetVCS())
  {
    case VCS_GIT: text = "GIT"; break;
    case VCS_SVN: text = "SVN"; break;
    default: wxFAIL;
  }

  return text;
}

void wxExVCS::Initialize()
{
  if (Use() && m_Command != VCS_NO_COMMAND)
  {
    switch (GetVCS())
    {
      case VCS_GIT:
        switch (m_Command)
        {
          case VCS_ADD:      m_CommandString = "add"; break;
          case VCS_BLAME:    m_CommandString = "blame"; break;
          case VCS_CAT:      break;
          case VCS_COMMIT:   m_CommandString = "commit"; break;
          case VCS_DIFF:     m_CommandString = "diff"; break;
          case VCS_HELP:     m_CommandString = "help"; break;
          case VCS_INFO:     break;
          case VCS_LOG:      m_CommandString = "log"; break;
          case VCS_LS:       break;
          case VCS_PROPLIST: break;
          case VCS_PROPSET:  break;
          case VCS_PUSH:     m_CommandString = "push"; break;
          case VCS_REVERT:   m_CommandString = "revert"; break;
          case VCS_SHOW:     m_CommandString = "show"; break;
          case VCS_STAT:     m_CommandString = "status"; break;
          case VCS_UPDATE:   m_CommandString = "update"; break;
          default:
            wxFAIL;
            break;
        }
        break;

      case VCS_SVN:
        switch (m_Command)
        {
          case VCS_ADD:      m_CommandString = "add"; break;
          case VCS_BLAME:    m_CommandString = "blame"; break;
          case VCS_CAT:      m_CommandString = "cat"; break;
          case VCS_COMMIT:   m_CommandString = "commit"; break;
          case VCS_DIFF:     m_CommandString = "diff"; break;
          case VCS_HELP:     m_CommandString = "help"; break;
          case VCS_INFO:     m_CommandString = "info"; break;
          case VCS_LOG:      m_CommandString = "log"; break;
          case VCS_LS:       m_CommandString = "ls"; break;
          case VCS_PROPLIST: m_CommandString = "proplist"; break;
          case VCS_PROPSET:  m_CommandString = "propset"; break;
          case VCS_PUSH:     break;
          case VCS_REVERT:   m_CommandString = "revert"; break;
          case VCS_SHOW:     break;
          case VCS_STAT:     m_CommandString = "stat"; break;
          case VCS_UPDATE:   m_CommandString = "update"; break;
          default:
            wxFAIL;
            break;
        }
        break;

      default: wxFAIL;
    }

    m_Caption = GetVCSName() + " " + m_CommandString;

    // Currently no flags, as no command was executed.
    m_CommandWithFlags = m_CommandString;

    // Use general key.
    m_FlagsKey = wxString::Format("cvsflags/name%d", m_Command);
  }

  m_Output.clear();
}

bool wxExVCS::IsOpenCommand() const
{
  return
    m_Command == wxExVCS::VCS_BLAME ||
    m_Command == wxExVCS::VCS_CAT ||
    m_Command == wxExVCS::VCS_DIFF;
}

#if wxUSE_GUI
wxStandardID wxExVCS::Request(wxWindow* parent)
{
  wxStandardID retValue;

  if ((retValue = ExecuteDialog(parent)) == wxID_OK)
  {
    ShowOutput(parent);
  }

  return retValue;
}
#endif

wxExVCS* wxExVCS::Set(wxExVCS* vcs)
{
  wxExVCS* old = m_Self;
  m_Self = vcs;
  return old;
}

#if wxUSE_GUI
int wxExVCS::ShowDialog(wxWindow* parent)
{
  std::vector<wxExConfigItem> v;

  if (m_Command == VCS_COMMIT)
  {
    v.push_back(wxExConfigItem(
      _("Revision comment"),
      CONFIG_COMBOBOX,
      wxEmptyString,
      true)); // required
  }

  if (!m_FileName.IsOk() && m_Command != VCS_HELP)
  {
    v.push_back(wxExConfigItem(
      _("Base folder"),
      CONFIG_COMBOBOXDIR,
      wxEmptyString,
      true,
      1000));

    if (m_Command == VCS_ADD)
    {
      v.push_back(wxExConfigItem(
        _("Path"),
        CONFIG_COMBOBOX,
        wxEmptyString,
        true)); // required
    }
  }

  if (UseFlags())
  {
    wxConfigBase::Get()->Write(
      _("Flags"),
      wxConfigBase::Get()->Read(m_FlagsKey));

    v.push_back(wxExConfigItem(_("Flags")));
  }

  if (UseSubcommand())
  {
    v.push_back(wxExConfigItem(_("Subcommand")));
  }

  return wxExConfigDialog(parent,
    v,
    m_Caption).ShowModal();
}
#endif

#if wxUSE_GUI
void wxExVCS::ShowOutput(wxWindow* parent) const
{
  wxString caption = m_Caption;

  if (m_Command != VCS_HELP)
  {
    caption += " " + (m_FileName.IsOk() ?
      m_FileName.GetFullName():
      wxExConfigFirstOf(_("Base folder")));
  }

  // Create a dialog for contents.
  if (m_STCEntryDialog == NULL)
  {
    m_STCEntryDialog = new wxExSTCEntryDialog(
      parent,
      caption,
      m_Output,
      wxEmptyString,
      wxOK,
      wxID_ANY,
      wxDefaultPosition,
      wxSize(350, 50));
  }
  else
  {
    m_STCEntryDialog->SetText(m_Output);
    m_STCEntryDialog->SetTitle(caption);
  }

  // Add a lexer when appropriate.
  if (m_Command == VCS_CAT || m_Command == VCS_BLAME)
  {
    if (m_FileName.GetLexer().IsOk())
    {
      m_STCEntryDialog->SetLexer(m_FileName.GetLexer().GetScintillaLexer());
    }
  }
  else if (m_Command == VCS_DIFF)
  {
    m_STCEntryDialog->SetLexer("diff");
  }
  else
  {
    m_STCEntryDialog->SetLexer(wxEmptyString);
  }

  m_STCEntryDialog->Show();
}
#endif

bool wxExVCS::Use() const
{
  return GetVCS() != VCS_NONE;
}

bool wxExVCS::UseFlags() const
{
  return m_Command != VCS_UPDATE && m_Command != VCS_HELP;
}

bool wxExVCS::UseSubcommand() const
{
  return m_Command == VCS_HELP;
}
<|endoftext|>


<commit_before>/* /% C %/ */
/***********************************************************************
 * cint (C/C++ interpreter)
 ************************************************************************
 * Source file bc_debug.cxx
 ************************************************************************
 * Description:
 *  debugging features
 ************************************************************************
 * Copyright(c) 2004~2004  Masaharu Goto
 *
 * For the licensing terms see the file COPYING
 *
 ************************************************************************/

#include "bc_debug.h"

/***********************************************************************
 * G__bc_funccall
 ***********************************************************************/
////////////////////////////////////////////////////////////////
struct G__input_file G__bc_funccall::getifile() const {
  struct G__input_file ifile;
  ifile.str = 0;
  // ifile.pos = 0;
  ifile.vindex = 0;

  if(!m_bytecode) {
    ifile=G__ifile;
  }
  else {
    struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;
    int ifn = m_bytecode->ifn;
    ifile.filenum = ifunc->pentry[ifn]->filenum;
    ifile.fp = G__srcfile[ifile.filenum].fp;
    ifile.line_number = m_line_number;
    strcpy(ifile.name,G__srcfile[ifile.filenum].filename);
  }

  return(ifile);
}

////////////////////////////////////////////////////////////////
int G__bc_funccall::setstackenv(struct G__view* pview) const {
  // todo, need some review
  pview->file = getifile();
  if(!m_bytecode) {
    pview->var_local = G__p_local;
    pview->struct_offset = G__store_struct_offset;
    pview->tagnum = G__tagnum;
    pview->exec_memberfunc = G__exec_memberfunc;
    pview->localmem = 0;
    return(0);
  }
  else {
    struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;
    //int ifn = m_bytecode->ifn;
    pview->var_local = m_bytecode->var;
    pview->struct_offset = m_struct_offset;
    pview->tagnum = ifunc->tagnum;
    pview->exec_memberfunc=(-1!=ifunc->tagnum)?1:0;
    pview->localmem = m_localmem;
    return(1);
  }
}

////////////////////////////////////////////////////////////////
int G__bc_funccall::disp(FILE* fout) const {
  // todo, need some review
  if(!m_bytecode)  return(0);
  G__FastAllocString msg(G__LONGLINE);
  struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;
  int ifn = m_bytecode->ifn;
  int tagnum=ifunc->tagnum;
  int filenum = ifunc->pentry[ifn]->filenum;
  struct G__param* libp=m_libp;

  // class name if member function
  if(-1!=tagnum) {
     msg.Format("%s::",G__struct.name[tagnum]);
     if(G__more(fout,msg())) return(1);
  }

  // function name
  msg.Format("%s(",ifunc->funcname[ifn]);
  if(G__more(fout,msg())) return(1);

  // function parameter
  for(int temp1=0;temp1<libp->paran;temp1++) {
    if(temp1) {
      msg = ",";
      if(G__more(fout,msg())) return(1);
    }
    G__valuemonitor(libp->para[temp1],msg);
    if(G__more(fout,msg())) return(1);
  }
  if(-1!=filenum) {
     msg.Format(") [%s:%d]\n"
	    ,G__stripfilename(G__srcfile[filenum].filename)
	    ,m_line_number);
     if(G__more(fout,msg())) return(1);
  }
  else {
    if(G__more(fout,") [entry]\n")) return(1);
  }

  return(0);
}

/***********************************************************************
 * G__bc_funccallstack
 ***********************************************************************/
////////////////////////////////////////////////////////////////
G__bc_funccallstack::G__bc_funccallstack() {
  //m_funccallstack.push_front(G__bc_funccall());
}

////////////////////////////////////////////////////////////////
G__bc_funccallstack::~G__bc_funccallstack() {
  // do nothing
}

////////////////////////////////////////////////////////////////
G__bc_funccall& G__bc_funccallstack::getStackPosition(int i) {
  if(0==m_funccallstack.size()) return(m_staticenv);
  if(i<0 || i>=(int)m_funccallstack.size()) {
    // error, stack isn't that deep
    G__fprinterr(G__serr,"!!!Function call stack isn't that deep!!!\n");
    return(m_staticenv);
  }
  return(m_funccallstack[i]);
}

////////////////////////////////////////////////////////////////
int G__bc_funccallstack::setstackenv(int i,struct G__view* pview) {
  return(getStackPosition(i).setstackenv(pview));
}

////////////////////////////////////////////////////////////////
int G__bc_funccallstack::disp(FILE* fout) const {
  //deque<G__bc_funccall>::iterator i;
  G__FastAllocString msg(100);
  for(int i=0;i<(int)m_funccallstack.size();++i) {
     msg.Format("%d ",i);
     if(G__more(fout,msg())) return(1);
     if(m_funccallstack[i].disp(fout)) return(1);
  }
  return(0);
}

////////////////////////////////////////////////////////////////

/***********************************************************************
 * static objects
 ***********************************************************************/
G__bc_funccallstack G__bc_funccallstack_obj;

/***********************************************************************
 * C function wrappers
 ***********************************************************************/

////////////////////////////////////////////////////////////////
extern "C" int G__bc_setdebugview(int i,struct G__view* pview) {
  return(G__bc_funccallstack_obj.setstackenv(i,pview));
}

////////////////////////////////////////////////////////////////
extern "C" int G__bc_showstack(FILE* fout) {
  return(G__bc_funccallstack_obj.disp(fout));
}

////////////////////////////////////////////////////////////////
extern "C" void G__bc_setlinenum(int line) {
  G__bc_funccallstack_obj.setlinenum(line);
}

<commit_msg>Missing member initialization (G__ifile's pos); strcpy (Coverity)<commit_after>/* /% C %/ */
/***********************************************************************
 * cint (C/C++ interpreter)
 ************************************************************************
 * Source file bc_debug.cxx
 ************************************************************************
 * Description:
 *  debugging features
 ************************************************************************
 * Copyright(c) 2004~2004  Masaharu Goto
 *
 * For the licensing terms see the file COPYING
 *
 ************************************************************************/

#include "bc_debug.h"

/***********************************************************************
 * G__bc_funccall
 ***********************************************************************/
////////////////////////////////////////////////////////////////
struct G__input_file G__bc_funccall::getifile() const {
  struct G__input_file ifile;
  ifile.str = 0;
  ifile.pos = 0;
  ifile.vindex = 0;

  if(!m_bytecode) {
    ifile=G__ifile;
  }
  else {
    struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;
    int ifn = m_bytecode->ifn;
    ifile.filenum = ifunc->pentry[ifn]->filenum;
    ifile.fp = G__srcfile[ifile.filenum].fp;
    ifile.line_number = m_line_number;
    strncpy(ifile.name,G__srcfile[ifile.filenum].filename, sizeof(ifile.name) - 1);
  }

  return(ifile);
}

////////////////////////////////////////////////////////////////
int G__bc_funccall::setstackenv(struct G__view* pview) const {
  // todo, need some review
  pview->file = getifile();
  if(!m_bytecode) {
    pview->var_local = G__p_local;
    pview->struct_offset = G__store_struct_offset;
    pview->tagnum = G__tagnum;
    pview->exec_memberfunc = G__exec_memberfunc;
    pview->localmem = 0;
    return(0);
  }
  else {
    struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;
    //int ifn = m_bytecode->ifn;
    pview->var_local = m_bytecode->var;
    pview->struct_offset = m_struct_offset;
    pview->tagnum = ifunc->tagnum;
    pview->exec_memberfunc=(-1!=ifunc->tagnum)?1:0;
    pview->localmem = m_localmem;
    return(1);
  }
}

////////////////////////////////////////////////////////////////
int G__bc_funccall::disp(FILE* fout) const {
  // todo, need some review
  if(!m_bytecode)  return(0);
  G__FastAllocString msg(G__LONGLINE);
  struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc;
  int ifn = m_bytecode->ifn;
  int tagnum=ifunc->tagnum;
  int filenum = ifunc->pentry[ifn]->filenum;
  struct G__param* libp=m_libp;

  // class name if member function
  if(-1!=tagnum) {
     msg.Format("%s::",G__struct.name[tagnum]);
     if(G__more(fout,msg())) return(1);
  }

  // function name
  msg.Format("%s(",ifunc->funcname[ifn]);
  if(G__more(fout,msg())) return(1);

  // function parameter
  for(int temp1=0;temp1<libp->paran;temp1++) {
    if(temp1) {
      msg = ",";
      if(G__more(fout,msg())) return(1);
    }
    G__valuemonitor(libp->para[temp1],msg);
    if(G__more(fout,msg())) return(1);
  }
  if(-1!=filenum) {
     msg.Format(") [%s:%d]\n"
	    ,G__stripfilename(G__srcfile[filenum].filename)
	    ,m_line_number);
     if(G__more(fout,msg())) return(1);
  }
  else {
    if(G__more(fout,") [entry]\n")) return(1);
  }

  return(0);
}

/***********************************************************************
 * G__bc_funccallstack
 ***********************************************************************/
////////////////////////////////////////////////////////////////
G__bc_funccallstack::G__bc_funccallstack() {
  //m_funccallstack.push_front(G__bc_funccall());
}

////////////////////////////////////////////////////////////////
G__bc_funccallstack::~G__bc_funccallstack() {
  // do nothing
}

////////////////////////////////////////////////////////////////
G__bc_funccall& G__bc_funccallstack::getStackPosition(int i) {
  if(0==m_funccallstack.size()) return(m_staticenv);
  if(i<0 || i>=(int)m_funccallstack.size()) {
    // error, stack isn't that deep
    G__fprinterr(G__serr,"!!!Function call stack isn't that deep!!!\n");
    return(m_staticenv);
  }
  return(m_funccallstack[i]);
}

////////////////////////////////////////////////////////////////
int G__bc_funccallstack::setstackenv(int i,struct G__view* pview) {
  return(getStackPosition(i).setstackenv(pview));
}

////////////////////////////////////////////////////////////////
int G__bc_funccallstack::disp(FILE* fout) const {
  //deque<G__bc_funccall>::iterator i;
  G__FastAllocString msg(100);
  for(int i=0;i<(int)m_funccallstack.size();++i) {
     msg.Format("%d ",i);
     if(G__more(fout,msg())) return(1);
     if(m_funccallstack[i].disp(fout)) return(1);
  }
  return(0);
}

////////////////////////////////////////////////////////////////

/***********************************************************************
 * static objects
 ***********************************************************************/
G__bc_funccallstack G__bc_funccallstack_obj;

/***********************************************************************
 * C function wrappers
 ***********************************************************************/

////////////////////////////////////////////////////////////////
extern "C" int G__bc_setdebugview(int i,struct G__view* pview) {
  return(G__bc_funccallstack_obj.setstackenv(i,pview));
}

////////////////////////////////////////////////////////////////
extern "C" int G__bc_showstack(FILE* fout) {
  return(G__bc_funccallstack_obj.disp(fout));
}

////////////////////////////////////////////////////////////////
extern "C" void G__bc_setlinenum(int line) {
  G__bc_funccallstack_obj.setlinenum(line);
}

<|endoftext|>


<commit_before>// A JetEvent emulates 2 detectors A and B producing each
// a TClonesArray of Hit objects.
// A TClonesArray  of Track objects is built with Hits objects
// of detectors A and B. Eack Track object has a TRefArray of hits.
// A TClonesArray of Jets is made with a subset of the Track objects
// also stored in a TRefArray.
// see $ROOTSYS/tutorials/jets.C for an example creating a Tree
// with JetEvents.

#include "TRandom.h"
#include "JetEvent.h"

ClassImp(Jet)
ClassImp(Track)
ClassImp(Hit)
ClassImp(JetEvent)

TClonesArray *JetEvent::fgJets   = 0;
TClonesArray *JetEvent::fgTracks = 0;
TClonesArray *JetEvent::fgHitsA  = 0;
TClonesArray *JetEvent::fgHitsB  = 0;

//______________________________________________________________________________
JetEvent::JetEvent()
{
   // Create a JetEvent object.
   // When the constructor is invoked for the first time, the class static
   // variables fgxxx are 0 and the TClonesArray fgxxx are created.

   if (!fgTracks) fgTracks = new TClonesArray("Track", 100);
   if (!fgJets)   fgJets   = new TClonesArray("Jet", 10);
   if (!fgHitsA)  fgHitsA  = new TClonesArray("Hit", 10000);
   if (!fgHitsB)  fgHitsB  = new TClonesArray("Hit", 1000);
   fJets   = fgJets;
   fTracks = fgTracks;
   fHitsA  = fgHitsA;
   fHitsB  = fgHitsB;
}

//______________________________________________________________________________
JetEvent::~JetEvent()
{
   Reset();
}

//______________________________________________________________________________
void JetEvent::Build(Int_t jetm, Int_t trackm, Int_t hitam, Int_t hitbm) {
   //Build one event

   //Save current Object count
   Int_t ObjectNumber = TProcessID::GetObjectCount();
   Clear();

   Hit *hit;
   Track *track;
   Jet *jet;
   fNjet   = fNtrack = fNhitA  = fNhitB  = 0;

   fVertex.SetXYZ(gRandom->Gaus(0,0.1),
                  gRandom->Gaus(0,0.2),
                  gRandom->Gaus(0,10));

   Int_t njets = (Int_t)gRandom->Gaus(jetm,1); if (njets < 1) njets = 1;
   for (Int_t j=0;j<njets;j++) {
      jet = AddJet();
      jet->fPt = gRandom->Gaus(0,10);
      jet->fPhi = 2*TMath::Pi()*gRandom->Rndm();
      Int_t ntracks = (Int_t)gRandom->Gaus(trackm,3); if (ntracks < 1) ntracks = 1;
      for (Int_t t=0;t<ntracks;t++) {
         track = AddTrack();
         track->fPx = gRandom->Gaus(0,1);
         track->fPy = gRandom->Gaus(0,1);
         track->fPz = gRandom->Gaus(0,5);
	 jet->fTracks.Add(track);
         Int_t nhitsA = (Int_t)gRandom->Gaus(hitam,5);
         for (Int_t ha=0;ha<nhitsA;ha++) {
            hit = AddHitA();
            hit->fX = 10000*j + 100*t +ha;
            hit->fY = 10000*j + 100*t +ha+0.1;
            hit->fZ = 10000*j + 100*t +ha+0.2;
	    track->fHits.Add(hit);
         }
         Int_t nhitsB = (Int_t)gRandom->Gaus(hitbm,2);
         for (Int_t hb=0;hb<nhitsB;hb++) {
            hit = AddHitB();
            hit->fX = 20000*j + 100*t +hb+0.3;
            hit->fY = 20000*j + 100*t +hb+0.4;
            hit->fZ = 20000*j + 100*t +hb+0.5;
	    track->fHits.Add(hit);
         }
         track->fNhit = nhitsA + nhitsB;
      }
   }
  //Restore Object count
  //To save space in the table keeping track of all referenced objects
  //we assume that our events do not address each other. We reset the
  //object count to what it was at the beginning of the event.
  TProcessID::SetObjectCount(ObjectNumber);
}

//______________________________________________________________________________
Jet *JetEvent::AddJet()
{
   // Add a new Jet to the list of tracks for this event.

   TClonesArray &jets = *fJets;
   Jet *jet = new(jets[fNjet++]) Jet();
   return jet;
}

//______________________________________________________________________________
Track *JetEvent::AddTrack()
{
   // Add a new track to the list of tracks for this event.

   TClonesArray &tracks = *fTracks;
   Track *track = new(tracks[fNtrack++]) Track();
   return track;
}

//______________________________________________________________________________
Hit *JetEvent::AddHitA()
{
   // Add a new hit to the list of hits in detector A

   TClonesArray &hitsA = *fHitsA;
   Hit *hit = new(hitsA[fNhitA++]) Hit();
   return hit;
}

//______________________________________________________________________________
Hit *JetEvent::AddHitB()
{
   // Add a new hit to the list of hits in detector B

   TClonesArray &hitsB = *fHitsB;
   Hit *hit = new(hitsB[fNhitB++]) Hit();
   return hit;
}

//______________________________________________________________________________
void JetEvent::Clear(Option_t *option)
{
   fJets->Clear(option);
   fTracks->Clear(option);
   fHitsA->Clear(option);
   fHitsB->Clear(option);
}

//______________________________________________________________________________
void JetEvent::Reset(Option_t *)
{
// Static function to reset all static objects for this event

   delete fgJets;   fgJets = 0;
   delete fgTracks; fgTracks = 0;
   delete fgHitsA;  fgHitsA = 0;
   delete fgHitsB;  fgHitsB = 0;
}

<commit_msg>Add missing include TMath.h<commit_after>// A JetEvent emulates 2 detectors A and B producing each
// a TClonesArray of Hit objects.
// A TClonesArray  of Track objects is built with Hits objects
// of detectors A and B. Eack Track object has a TRefArray of hits.
// A TClonesArray of Jets is made with a subset of the Track objects
// also stored in a TRefArray.
// see $ROOTSYS/tutorials/jets.C for an example creating a Tree
// with JetEvents.

#include "TMath.h"
#include "TRandom.h"
#include "JetEvent.h"

ClassImp(Jet)
ClassImp(Track)
ClassImp(Hit)
ClassImp(JetEvent)

TClonesArray *JetEvent::fgJets   = 0;
TClonesArray *JetEvent::fgTracks = 0;
TClonesArray *JetEvent::fgHitsA  = 0;
TClonesArray *JetEvent::fgHitsB  = 0;

//______________________________________________________________________________
JetEvent::JetEvent()
{
   // Create a JetEvent object.
   // When the constructor is invoked for the first time, the class static
   // variables fgxxx are 0 and the TClonesArray fgxxx are created.

   if (!fgTracks) fgTracks = new TClonesArray("Track", 100);
   if (!fgJets)   fgJets   = new TClonesArray("Jet", 10);
   if (!fgHitsA)  fgHitsA  = new TClonesArray("Hit", 10000);
   if (!fgHitsB)  fgHitsB  = new TClonesArray("Hit", 1000);
   fJets   = fgJets;
   fTracks = fgTracks;
   fHitsA  = fgHitsA;
   fHitsB  = fgHitsB;
}

//______________________________________________________________________________
JetEvent::~JetEvent()
{
   Reset();
}

//______________________________________________________________________________
void JetEvent::Build(Int_t jetm, Int_t trackm, Int_t hitam, Int_t hitbm) {
   //Build one event

   //Save current Object count
   Int_t ObjectNumber = TProcessID::GetObjectCount();
   Clear();

   Hit *hit;
   Track *track;
   Jet *jet;
   fNjet   = fNtrack = fNhitA  = fNhitB  = 0;

   fVertex.SetXYZ(gRandom->Gaus(0,0.1),
                  gRandom->Gaus(0,0.2),
                  gRandom->Gaus(0,10));

   Int_t njets = (Int_t)gRandom->Gaus(jetm,1); if (njets < 1) njets = 1;
   for (Int_t j=0;j<njets;j++) {
      jet = AddJet();
      jet->fPt = gRandom->Gaus(0,10);
      jet->fPhi = 2*TMath::Pi()*gRandom->Rndm();
      Int_t ntracks = (Int_t)gRandom->Gaus(trackm,3); if (ntracks < 1) ntracks = 1;
      for (Int_t t=0;t<ntracks;t++) {
         track = AddTrack();
         track->fPx = gRandom->Gaus(0,1);
         track->fPy = gRandom->Gaus(0,1);
         track->fPz = gRandom->Gaus(0,5);
	 jet->fTracks.Add(track);
         Int_t nhitsA = (Int_t)gRandom->Gaus(hitam,5);
         for (Int_t ha=0;ha<nhitsA;ha++) {
            hit = AddHitA();
            hit->fX = 10000*j + 100*t +ha;
            hit->fY = 10000*j + 100*t +ha+0.1;
            hit->fZ = 10000*j + 100*t +ha+0.2;
	    track->fHits.Add(hit);
         }
         Int_t nhitsB = (Int_t)gRandom->Gaus(hitbm,2);
         for (Int_t hb=0;hb<nhitsB;hb++) {
            hit = AddHitB();
            hit->fX = 20000*j + 100*t +hb+0.3;
            hit->fY = 20000*j + 100*t +hb+0.4;
            hit->fZ = 20000*j + 100*t +hb+0.5;
	    track->fHits.Add(hit);
         }
         track->fNhit = nhitsA + nhitsB;
      }
   }
  //Restore Object count
  //To save space in the table keeping track of all referenced objects
  //we assume that our events do not address each other. We reset the
  //object count to what it was at the beginning of the event.
  TProcessID::SetObjectCount(ObjectNumber);
}

//______________________________________________________________________________
Jet *JetEvent::AddJet()
{
   // Add a new Jet to the list of tracks for this event.

   TClonesArray &jets = *fJets;
   Jet *jet = new(jets[fNjet++]) Jet();
   return jet;
}

//______________________________________________________________________________
Track *JetEvent::AddTrack()
{
   // Add a new track to the list of tracks for this event.

   TClonesArray &tracks = *fTracks;
   Track *track = new(tracks[fNtrack++]) Track();
   return track;
}

//______________________________________________________________________________
Hit *JetEvent::AddHitA()
{
   // Add a new hit to the list of hits in detector A

   TClonesArray &hitsA = *fHitsA;
   Hit *hit = new(hitsA[fNhitA++]) Hit();
   return hit;
}

//______________________________________________________________________________
Hit *JetEvent::AddHitB()
{
   // Add a new hit to the list of hits in detector B

   TClonesArray &hitsB = *fHitsB;
   Hit *hit = new(hitsB[fNhitB++]) Hit();
   return hit;
}

//______________________________________________________________________________
void JetEvent::Clear(Option_t *option)
{
   fJets->Clear(option);
   fTracks->Clear(option);
   fHitsA->Clear(option);
   fHitsB->Clear(option);
}

//______________________________________________________________________________
void JetEvent::Reset(Option_t *)
{
// Static function to reset all static objects for this event

   delete fgJets;   fgJets = 0;
   delete fgTracks; fgTracks = 0;
   delete fgHitsA;  fgHitsA = 0;
   delete fgHitsB;  fgHitsB = 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsViewOverlay.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2006-04-06 16:25:38 $
 *
 *  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 SD_SLIDESORTER_VIEW_OVERLAY_HXX
#define SD_SLIDESORTER_VIEW_OVERLAY_HXX

#include "model/SlsSharedPageDescriptor.hxx"

#include <osl/mutex.hxx>
#include <tools/gen.hxx>
#include <vector>
#include <boost/weak_ptr.hpp>

class OutputDevice;
class Region;

namespace sd { namespace slidesorter {
class SlideSorterViewShell;
} }

namespace sd { namespace slidesorter { namespace model {
class PageEnumeration;
} } }

namespace sd { namespace slidesorter { namespace controller {
class SlideSorterController;
} } }

namespace sd { namespace slidesorter { namespace view {

class ViewOverlay;
class SelectionRectangleOverlay;
class InsertionIndicatorOverlay;
class SubstitutionOverlay;

/** This base class of overlay graphics keeps track of the visibility of
    graphical objects that possibly are drawn in XOR paint mode.  This makes
    it possibly to switch such an overlay on or off without knowing whether
    it is visible.
*/
class OverlayBase
{
public:
    OverlayBase (ViewOverlay& rViewOverlay);
    virtual ~OverlayBase (void);

    virtual void Paint (void);

    virtual void Show (void);
    virtual void Hide (void);
    void Toggle (void);
    bool IsShowing (void);
    ViewOverlay& GetViewOverlay (void);

protected:
    ::osl::Mutex maMutex;

    ViewOverlay& mrViewOverlay;

    bool mbIsShowing;
};

/** This class manages the substitution display of the page objects.  This
    subsitution is used to visualize the selected page objects during a
    mouse drag operation.
*/
class SubstitutionOverlay
    : public OverlayBase
{
public:
    SubstitutionOverlay (ViewOverlay& rViewOverlay);
    virtual ~SubstitutionOverlay (void);

    virtual void Paint (void);

    /** Setup the substitution display of the given set of selected pages.
        The given mouse position is remembered so that it later can be
        returned by GetPosition(). This is a convenience feature.
    */
    void Create (
        model::PageEnumeration& rSelection,
        const Point& rPosition);

    /** Clear the substitution display.  Until the next call of Create() no
        substution is painted.
    */
    void Clear (void);

    /** Move the substitution display by the given amount of pixels.
    */
    void Move (const Point& rOffset);
    void SetPosition (const Point& rPosition);
    const Point& GetPosition (void) const;

private:
    /// List of page object substitution displays.
    typedef ::std::vector<Rectangle> SubstitutionShapeList;
    SubstitutionShapeList maShapes;
    Point maPosition;
};

class SelectionRectangleOverlay
    : public OverlayBase
{
public:
    SelectionRectangleOverlay (ViewOverlay& rViewOverlay);

    virtual void Paint (void);

    virtual void Show (void);
    virtual void Hide (void);

    void Start (const Point& rAnchor);
    void Update (const Point& rSecondCorner);

    Rectangle GetSelectionRectangle (void);

private:
    Point maAnchor;
    Point maSecondCorner;
};

/** The insertion indicator is painted as a vertical or horizonal bar
    in the space between slides.
*/
class InsertionIndicatorOverlay
    : public OverlayBase
{
public:
    InsertionIndicatorOverlay (ViewOverlay& rViewOverlay);

    void SetPositionAndSize (const Rectangle& rBoundingBox);

    virtual void Paint (void);

    /** Given a position in model coordinates this method calculates the
        insertion marker both as an index in the document and as a rectangle
        used for drawing the insertion indicator.
    */
    void SetPosition (const Point& rPosition);

    sal_Int32 GetInsertionPageIndex (void) const;

private:
    Rectangle maBoundingBox;
    sal_Int32 mnInsertionIndex;
};

/** Paint a frame around the slide preview under the mouse.  The actual
    painting is done by the PageObjectViewObjectContact of the slidesorter.
    This class is responsible for the coordination of the right time for the
    painting.
*/
class MouseOverIndicatorOverlay
    : public OverlayBase
{
public:
    MouseOverIndicatorOverlay (ViewOverlay& rViewOverlay);

    /** Set the page object for which to paint a mouse over indicator.
        @param pContact
            A value of <NULL/> indicates to not paint the mouse over indicator.
    */
    void SetSlideUnderMouse (const model::SharedPageDescriptor& rpDescriptor);

    virtual void Paint (void);

private:
    /** The page under the mouse is stored as weak shared pointer so that
        model changes can be handled without having the SlideSorterModel
        inform this class explicitly.
    */
    ::boost::weak_ptr<model::PageDescriptor> mpPageUnderMouse;
};

/** The view overlay manages and paints some indicators that are painted on
    top of the regular view content (the page objects).  It is separated
    from the view to allow the indicators to be altered in position and size
    without to repaint the whole view content (inside that the bounding box
    of the indicator).  One technique to achive this is to use XOR-painting.

    The view overlay itself simply provides the more specialized classes
    that handle individual indicators.

*/
class ViewOverlay
{
public:
    ViewOverlay (SlideSorterViewShell& rViewShell);
    ~ViewOverlay (void);

    SelectionRectangleOverlay& GetSelectionRectangleOverlay (void);
    MouseOverIndicatorOverlay& GetMouseOverIndicatorOverlay (void);
    InsertionIndicatorOverlay& GetInsertionIndicatorOverlay (void);
    SubstitutionOverlay& GetSubstitutionOverlay (void);

    void Paint (void);

    /** The overlay paint type describes how an overlay is painted.  That can be
        either by using XOR operation or by doing a regular paint.
    */
    enum OverlayPaintType { OPT_ALL, OPT_XOR, OPT_PAINT };

    /** As a preparation for draw operations that are not caused by the
        overlays this method saves the current state of all overlays so that
        the next call to Restore() can restore them.  After that it hides
        the overlays so they do not interfere with the drawing operations.
        @param eType
            This parameter specifies what overlays to hide.
    */
    void HideAndSave (OverlayPaintType eType = OPT_ALL);

    /** Restore the state of the overlays that has been saved in an earlier
        call of HideAndSave().
    */
    void Restore (void);

    controller::SlideSorterController& GetController (void);
    SlideSorterViewShell& GetViewShell (void);

private:
    SlideSorterViewShell& mrViewShell;
    SelectionRectangleOverlay maSelectionRectangleOverlay;
    MouseOverIndicatorOverlay maMouseOverIndicatorOverlay;
    InsertionIndicatorOverlay maInsertionIndicatorOverlay;
    SubstitutionOverlay maSubstitutionOverlay;

    OverlayPaintType meSavedStateType;

    bool mbSelectionRectangleWasVisible;
    bool mbMouseOverIndicatorWasVisible;
    bool mbInsertionIndicatorWasVisible;
    bool mbSubstitutionDisplayWasVisible;

    /** The number HideAndSave() has been called more than Restore(). Only
        when the value is 1 does Restore() really restore the overlays.
    */
    int mnHideAndSaveLevel;
};

} } } // end of namespace ::sd::slidesorter::view

#endif
<commit_msg>INTEGRATION: CWS aw054 (1.7.374); FILE MERGED 2007/10/17 13:22:12 af 1.7.374.1: #i82710# Using overlay support of drawing layer for painting overlays.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SlsViewOverlay.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: vg $ $Date: 2008-02-12 16:28:38 $
 *
 *  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 SD_SLIDESORTER_VIEW_OVERLAY_HXX
#define SD_SLIDESORTER_VIEW_OVERLAY_HXX

#include "model/SlsSharedPageDescriptor.hxx"

#include <basegfx/polygon/b2dpolypolygon.hxx>
#include <osl/mutex.hxx>
#include <svx/sdr/overlay/overlayobject.hxx>
#include <tools/gen.hxx>
#include <vector>
#include <boost/weak_ptr.hpp>
#include <boost/noncopyable.hpp>

class OutputDevice;
class Region;

namespace sd { namespace slidesorter {
class SlideSorterViewShell;
} }

namespace sd { namespace slidesorter { namespace model {
class PageEnumeration;
} } }

namespace sd { namespace slidesorter { namespace controller {
class SlideSorterController;
} } }

namespace sdr { namespace overlay {
class OverlayManager;
} }

namespace sd { namespace slidesorter { namespace view {

class InsertionIndicatorOverlay;
class PageObjectViewObjectContact;
class SelectionRectangleOverlay;
class SubstitutionOverlay;
class ViewOverlay;

/** This base class of slide sorter overlays uses the drawing layer overlay
    support for the display.
*/
class OverlayBase
    : private ::boost::noncopyable,
      public sdr::overlay::OverlayObject
{
public:
    OverlayBase (ViewOverlay& rViewOverlay);
    virtual ~OverlayBase (void);

    virtual void Paint (void);

    virtual void Show (void);
    virtual void Hide (void);
    void Toggle (void);
    bool IsShowing (void);
    ViewOverlay& GetViewOverlay (void);

protected:
    ::osl::Mutex maMutex;

    ViewOverlay& mrViewOverlay;

    virtual void transform (const basegfx::B2DHomMatrix& rMatrix);

    /** Make sure that the overlay object is registered at the
        OverlayManager.  This registration is done on demand.
    */
    void EnsureRegistration (void);
};

/** During internal drag and drop the outlines of the selected slides are
    painted at the mouse position in dashed lines.
*/
class SubstitutionOverlay
    : public OverlayBase
{
public:
    SubstitutionOverlay (ViewOverlay& rViewOverlay);
    virtual ~SubstitutionOverlay (void);

    /** Setup the substitution display of the given set of selected pages.
        The given mouse position is remembered so that it later can be
        returned by GetPosition(). This is a convenience feature.
    */
    void Create (
        model::PageEnumeration& rSelection,
        const Point& rPosition);

    /** Clear the substitution display.  Until the next call of Create() no
        substution is painted.
    */
    void Clear (void);

    /** Move the substitution display by the given amount of pixels.
    */
    void Move (const Point& rOffset);
    void SetPosition (const Point& rPosition);
    Point GetPosition (void) const;

protected:
    virtual void drawGeometry (OutputDevice& rOutputDevice);
    virtual void createBaseRange (OutputDevice& rOutputDevice);

private:
    Point maPosition;
    basegfx::B2DRange maBoundingBox;
    basegfx::B2DPolyPolygon maShapes;
};

/** Slides can be selected by drawing a selection rectangle in the slide
    sorter.  When the left mouse button is released all slides that are at
    least partially in the rectangle are selected.
*/
class SelectionRectangleOverlay
    : public OverlayBase
{
public:
    SelectionRectangleOverlay (ViewOverlay& rViewOverlay);

    void Start (const Point& rAnchor);
    void Update (const Point& rSecondCorner);

    Rectangle GetSelectionRectangle (void);

protected:
    virtual void drawGeometry (OutputDevice& rOutputDevice);
    virtual void createBaseRange (OutputDevice& rOutputDevice);

private:
    Point maAnchor;
    Point maSecondCorner;
};

/** The insertion indicator is painted as a vertical or horizonal bar
    in the space between slides.
*/
class InsertionIndicatorOverlay
    : public OverlayBase
{
public:
    InsertionIndicatorOverlay (
        ViewOverlay& rViewOverlay,
        SlideSorterViewShell& mrViewShell);

    /** Given a position in model coordinates this method calculates the
        insertion marker both as an index in the document and as a rectangle
        used for drawing the insertion indicator.
    */
    void SetPosition (const Point& rPosition);

    sal_Int32 GetInsertionPageIndex (void) const;

protected:
    virtual void drawGeometry (OutputDevice& rOutputDevice);
    virtual void createBaseRange (OutputDevice& rOutputDevice);

private:
    SlideSorterViewShell& mrViewShell;
    sal_Int32 mnInsertionIndex;
    Rectangle maBoundingBox;

    void SetPositionAndSize (const Rectangle& rBoundingBox);
};

/** Paint a frame around the slide preview under the mouse.  The actual
    painting is done by the PageObjectViewObjectContact of the slidesorter.
*/
class MouseOverIndicatorOverlay
    : public OverlayBase
{
public:
    MouseOverIndicatorOverlay (
        ViewOverlay& rViewOverlay,
        SlideSorterViewShell& mrViewShell);
    virtual ~MouseOverIndicatorOverlay (void);

    /** Set the page object for which to paint a mouse over indicator.
        @param pContact
            A value of <NULL/> indicates to not paint the mouse over indicator.
    */
    void SetSlideUnderMouse (const model::SharedPageDescriptor& rpDescriptor);

protected:
    virtual void drawGeometry (OutputDevice& rOutputDevice);
    virtual void createBaseRange (OutputDevice& rOutputDevice);

private:
    class MouseOverIndicator;

    SlideSorterViewShell& mrViewShell;

    /** The page under the mouse is stored as weak shared pointer so that
        model changes can be handled without having the SlideSorterModel
        inform this class explicitly.
    */
    ::boost::weak_ptr<model::PageDescriptor> mpPageUnderMouse;

    view::PageObjectViewObjectContact* GetViewObjectContact (void) const;
};

/** The view overlay manages and paints some indicators that are painted on
    top of the regular view content (the page objects).  It is separated
    from the view to allow the indicators to be altered in position and size
    without repainting the whole view content (inside that the bounding box
    of the indicator).  This is achieved by using the drawing layer overlay
    support.

    The view overlay itself simply gives access to the more specialized
    classes that handle individual indicators.

*/
class ViewOverlay
{
public:
    ViewOverlay (SlideSorterViewShell& rViewShell);
    ~ViewOverlay (void);

    SelectionRectangleOverlay& GetSelectionRectangleOverlay (void);
    MouseOverIndicatorOverlay& GetMouseOverIndicatorOverlay (void);
    InsertionIndicatorOverlay& GetInsertionIndicatorOverlay (void);
    SubstitutionOverlay& GetSubstitutionOverlay (void);

    sdr::overlay::OverlayManager* GetOverlayManager (void) const;

private:
    SlideSorterViewShell& mrViewShell;
    SelectionRectangleOverlay maSelectionRectangleOverlay;
    MouseOverIndicatorOverlay maMouseOverIndicatorOverlay;
    InsertionIndicatorOverlay maInsertionIndicatorOverlay;
    SubstitutionOverlay maSubstitutionOverlay;
};

} } } // end of namespace ::sd::slidesorter::view

#endif
<|endoftext|>


<commit_before>#ifndef SUBGRIDLIST_HH
#define SUBGRIDLIST_HH

#include <dune/common/fmatrix.hh>
#include <dune/common/exceptions.hh>
#include <dune/subgrid/subgrid.hh>

#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/multiscale/tools/solver/MsFEM/msfem_localproblems/localproblemsolver.hh>

#include <dune/fem/operator/2order/lagrangematrixsetup.hh>

// / done

namespace Dune {
template< class HostDiscreteFunctionImp, class SubGridImp, class MacroMicroGridSpecifierImp >
class SubGridList
{
public:
  // ! ---------------- typedefs for the HostDiscreteFunctionSpace -----------------------

  typedef MacroMicroGridSpecifierImp MacroMicroGridSpecifierType;

  typedef HostDiscreteFunctionImp HostDiscreteFunctionType;

  // ! type of discrete function space
  typedef typename HostDiscreteFunctionType::DiscreteFunctionSpaceType
  HostDiscreteFunctionSpaceType;

  // ! type of (non-discrete )function space
  typedef typename HostDiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;

  // ! type of grid partition
  typedef typename HostDiscreteFunctionSpaceType::GridPartType HostGridPartType;

  // ! type of grid
  typedef typename HostDiscreteFunctionSpaceType::GridType HostGridType;

  typedef typename HostGridType::Traits::LeafIndexSet HostGridLeafIndexSet;

  typedef typename HostDiscreteFunctionSpaceType::IteratorType HostGridEntityIteratorType;

  typedef typename HostGridEntityIteratorType::Entity HostEntityType;

  typedef typename HostEntityType::EntityPointer HostEntityPointerType;

  // old:
  #if 0
  typedef typename HostGridType::template Codim< 0 >::template Partition< All_Partition >::LevelIterator
  HostgridLevelEntityIteratorType;
  typedef typename HostGridType::Traits::LevelIndexSet
  HostGridLevelIndexSet;

  // usage:
  // const HostGridLevelIndexSet& hostGridLevelIndexSet = hostGrid.levelIndexSet(computational_level_);
  // int father_index = hostGridLevelIndexSet.index( *level_it );
  #endif // if 0

  typedef typename HostEntityType::template Codim< 2 >::EntityPointer HostNodePointer;

  typedef typename HostGridPartType::IntersectionIteratorType HostIntersectionIterator;

  // ! ---------------- typedefs for the SubgridDiscreteFunctionSpace -----------------------
  // ( typedefs for the local grid and the corresponding local ('sub') )discrete space )

  // ! type of grid
  typedef SubGridImp SubGridType;

  // ! type of grid part
  typedef LeafGridPart< SubGridType > SubGridPartType;

  template< typename EntityPointerCollectionType >
  bool entity_patch_in_subgrid(HostEntityPointerType& hit,
                               const HostGridPartType& hostGridPart,
                               SubGridType& subGrid,
                               EntityPointerCollectionType& entities_sharing_same_node) {
    bool patch_in_subgrid_ = true;

    // loop over the nodes of the enity
    for (int i = 0; i < (*hit).template count< 2 >(); i += 1)
    {
      const HostNodePointer node = (*hit).template subEntity< 2 >(i);

      int global_index_node = hostGridPart.indexSet().index(*node);

      for (int j = 0; j < entities_sharing_same_node[global_index_node].size(); j += 1)
      {
        if ( !( subGrid.template contains< 0 >(*entities_sharing_same_node[global_index_node][j]) ) )
        {
          patch_in_subgrid_ = false;
        }
      }
    }
    return patch_in_subgrid_;
  } // entity_patch_in_subgrid

  template< typename EntityPointerCollectionType >
  void enrichment(HostEntityPointerType& hit,
                  HostEntityPointerType& level_father_it,
                  MacroMicroGridSpecifierType& specifier,
                  int& father_index,
                  const HostGridPartType& hostGridPart,
                  SubGridType& subGrid,
                  EntityPointerCollectionType& entities_sharing_same_node,
                  int& layer,
                  bool***& enriched) {
    // difference in levels between coarse and fine grid
    int level_difference = specifier.getLevelDifference();
    HostDiscreteFunctionSpaceType& coarseSpace = specifier.coarseSpace();

    const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarseSpace.gridPart().grid().leafIndexSet();

    const HostGridLeafIndexSet& hostGridLeafIndexSet = hostSpace_.gridPart().grid().leafIndexSet();

    for (int l = 0; l <= layer; l += 1)
    {
      enriched[father_index][hostGridLeafIndexSet.index(*hit)][l] = true;
    }

    layer -= 1;

    // loop over the nodes of the enity
    for (int i = 0; i < (*hit).template count< 2 >(); i += 1)
    {
      const HostNodePointer node = (*hit).template subEntity< 2 >(i);
      int global_index_node = hostGridPart.indexSet().index(*node);

      for (size_t j = 0; j < entities_sharing_same_node[global_index_node].size(); j += 1)
      {
        if ( !( subGrid.template contains< 0 >(*entities_sharing_same_node[global_index_node][j]) ) )
        {
          subGrid.insertPartial(*entities_sharing_same_node[global_index_node][j]);
        }

        if (layer > 0)
        {
          HostEntityPointerType father = entities_sharing_same_node[global_index_node][j];
          for (int lev = 0; lev < level_difference; ++lev)
            father = father->father();

          HostEntityPointerType coarse_father_test = father;
          bool father_found = false;
          while (father_found == false)
          {
            if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)
            {
              father = coarse_father_test;
            }

            if (coarse_father_test->hasFather() == false)
            { father_found = true; } else
            { coarse_father_test = coarse_father_test->father(); }
          }

          if ( !(father == level_father_it) )
          {
            if (enriched[father_index][hostGridLeafIndexSet.index(*entities_sharing_same_node[global_index_node][j])][
                  layer] == false)
            {
              enrichment(entities_sharing_same_node[global_index_node][j], level_father_it,
                         specifier, father_index,
                         hostGridPart, subGrid, entities_sharing_same_node, layer, enriched);

              layer += 1;
            }
          }
        }
      }
    }
  } // enrichment

  SubGridList(MacroMicroGridSpecifierType& specifier, bool silent = true)
    : hostSpace_( specifier.fineSpace() )
      , specifier_(specifier)
      , silent_(silent) {
    std::cout << "Starting creation of subgrids." << std::endl << std::endl;

    HostDiscreteFunctionSpaceType& coarseSpace = specifier.coarseSpace();

    const HostGridPartType& hostGridPart = hostSpace_.gridPart();

    HostGridType& hostGrid = hostSpace_.gridPart().grid();

    int number_of_nodes = hostGrid.size(2 /*codim*/);

    // -------- identify the entities that share a certain node -------

    std::vector< std::vector< HostEntityPointerType > > entities_sharing_same_node(number_of_nodes);

    for (HostGridEntityIteratorType it = hostSpace_.begin(); it != hostSpace_.end(); ++it)
    {
      int number_of_nodes_in_entity = (*it).template count< 2 >();
      for (int i = 0; i < number_of_nodes_in_entity; i += 1)
      {
        const HostNodePointer node = (*it).template subEntity< 2 >(i);
        int global_index_node = hostGridPart.indexSet().index(*node);

        entities_sharing_same_node[global_index_node].push_back( HostEntityPointerType(*it) );
      }
    }

    int max_num_layers = 0;
    for (int i = 0; i < specifier_.getNumOfCoarseEntities(); i += 1)
    {
      if (specifier_.getLayer(i) > max_num_layers)
      { max_num_layers = specifier_.getLayer(i); }
    }

    // difference in levels between coarse and fine grid
    int level_difference = specifier.getLevelDifference();

    // number of coarse grid entities (of codim 0).
    int number_of_coarse_grid_entities = specifier.getNumOfCoarseEntities();

    std::cout << "number_of_coarse_grid_entities = " << number_of_coarse_grid_entities << std::endl;

    subGrid = new SubGridType *[number_of_coarse_grid_entities];

    // ! ----------- create subgrids --------------------

    const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarseSpace.gridPart().grid().leafIndexSet();

    for (HostGridEntityIteratorType coarse_it = coarseSpace.begin(); coarse_it != coarseSpace.end(); ++coarse_it)
    {
      int coarse_index = coarseGridLeafIndexSet.index(*coarse_it);

      subGrid[coarse_index] = new SubGridType(hostGrid);
      subGrid[coarse_index]->createBegin();
    }

    for (HostGridEntityIteratorType it = hostSpace_.begin(); it != hostSpace_.end(); ++it)
    {
      int number_of_nodes_in_entity = (*it).template count< 2 >();
      for (int i = 0; i < number_of_nodes_in_entity; i += 1)
      {
        const HostNodePointer node = (*it).template subEntity< 2 >(i);
        int global_index_node = hostGridPart.indexSet().index(*node);

        entities_sharing_same_node[global_index_node].push_back( HostEntityPointerType(*it) );
      }
    }

    bool*** enriched = new bool**[number_of_coarse_grid_entities];
    for (int k = 0; k < number_of_coarse_grid_entities; k += 1)
    {
      enriched[k] = new bool*[hostGrid.size(0 /*codim*/)];
      for (int m = 0; m < hostGrid.size(0 /*codim*/); m += 1)
      {
        enriched[k][m] = new bool[max_num_layers + 1];
      }
    }

    for (int k = 0; k < number_of_coarse_grid_entities; k += 1)
    {
      for (int m = 0; m < hostGrid.size(0 /*codim*/); m += 1)
      {
        for (int l = 0; l < max_num_layers + 1; l += 1)
          enriched[k][m][l] = false;
      }
    }

    // a fine grid iterator for the codim 0 hostgrid entities:
    HostGridEntityIteratorType host_endit = hostSpace_.end();
    for (HostGridEntityIteratorType host_it = hostSpace_.begin();
         host_it != host_endit;
         ++host_it)
    {
      const HostEntityType& host_entity = *host_it;

      int DUNE_UNUSED(number_of_nodes_in_entity) = (*host_it).template count< 2 >();

      // get the coarse-grid-father of host_entity (which is a maxlevel entity)
      HostEntityPointerType level_father_entity = HostEntityPointerType(*host_it);

      for (int lev = 0; lev < level_difference; ++lev)
        level_father_entity = level_father_entity->father();

      // changed 'contains'-method in 'indexset.hh'
      // we use: "return ( (subIndex >= 0) && (subIndex < size( codim )) );"
      // instead of "return (subIndex >= 0);"
      HostEntityPointerType coarse_father_test = level_father_entity;
      bool father_found = false;
      while (father_found == false)
      {
        if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)
        { level_father_entity = coarse_father_test; }

        if (coarse_father_test->hasFather() == false)
        { father_found = true; } else
        { coarse_father_test = coarse_father_test->father(); }
      }

      int father_index = coarseGridLeafIndexSet.index(*level_father_entity);

      if ( !( subGrid[father_index]->template contains< 0 >(host_entity) ) )
      { subGrid[father_index]->insertPartial(host_entity); }

      // check the neighbor entities and look if they belong to the same father
      // if yes, continue
      // if not, enrichement with 'n(T)'-layers
      bool all_neighbors_have_same_father = true;
      const HostIntersectionIterator iend = hostGridPart.iend(host_entity);
      for (HostIntersectionIterator iit = hostGridPart.ibegin(host_entity); iit != iend; ++iit)
      {
        if ( iit->neighbor() ) // if there is a neighbor entity
        {
          // check if the neighbor entity is in the subgrid
          const HostEntityPointerType neighborHostEntityPointer = iit->outside();
          const HostEntityType& DUNE_UNUSED(neighborHostEntity) = *neighborHostEntityPointer;

          HostEntityPointerType level_father_neighbor_entity = neighborHostEntityPointer;
          for (int lev = 0; lev < level_difference; ++lev)
            level_father_neighbor_entity = level_father_neighbor_entity->father();

          HostEntityPointerType coarse_father_test = level_father_neighbor_entity;

          bool father_found = false;
          while (father_found == false)
          {
            if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)
            { level_father_neighbor_entity = coarse_father_test; }

            if (coarse_father_test->hasFather() == false)
            { father_found = true; } else
            { coarse_father_test = coarse_father_test->father(); }
          }

          if ( !(level_father_neighbor_entity == level_father_entity) )
          {
            all_neighbors_have_same_father = false;
          }
        } else {
          all_neighbors_have_same_father = false;
        }
      }

      if (all_neighbors_have_same_father == true)
      { continue; }

      int layers = specifier_.getLayer(father_index);
      if (layers > 0)
      {
        HostEntityPointerType hep(*host_it);
        enrichment(hep, level_father_entity, specifier, father_index,
                   hostGridPart, *subGrid[father_index], entities_sharing_same_node, layers, enriched);
      }
    }

    for (int i = 0; i < number_of_coarse_grid_entities; ++i)
    {
      subGrid[i]->createEnd();
      if (!silent_)
      {
        std::cout << "Subgrid " << i << ":" << std::endl;
        subGrid[i]->report();
      }

      if (subGrid[i]->size(2) == 0)
      {
        std::cout << "Error." << std::endl;
        std::cout << "Error. Created Subgrid with 0 nodes." << std::endl;

        for (HostGridEntityIteratorType coarse_it = specifier_.coarseSpace().begin();
             coarse_it != specifier_.coarseSpace().end(); ++coarse_it)
        {
          const HostEntityType& coarse_entity = *coarse_it;
          int index = coarseGridLeafIndexSet.index(coarse_entity);
          if (i == index)
          {
            std::cout << "We have a problem with the following coarse-grid element:" << std::endl;
            std::cout << "coarse element corner(0) = " << coarse_it->geometry().corner(0) << std::endl;
            std::cout << "coarse element corner(1) = " << coarse_it->geometry().corner(1) << std::endl;
            std::cout << "coarse element corner(2) = " << coarse_it->geometry().corner(2) << std::endl << std::endl;
          }
        }
        abort();
      }
    }

    // ! ----------- end create subgrids --------------------
  }

  SubGridType& getSubGrid(int i) {
    const int size = specifier_.getNumOfCoarseEntities();

    if (i >= size)
    {
      DUNE_THROW(Dune::RangeError, "Error. Subgrid-Index too large.");
    }
    return *(subGrid[i]);
  } // getSubGrid

private:
  SubGridList(const SubGridList& list);
  const HostDiscreteFunctionSpaceType& hostSpace_;
  MacroMicroGridSpecifierType& specifier_;

  bool silent_;

  SubGridType** subGrid;

public:
  // Destruktor (Dynamisch angeforderter Speicher wird wieder freigegeben)
  ~SubGridList() {
    const int size = specifier_.getNumOfCoarseEntities();

    for (int i = 0; i < size; ++i)
      delete subGrid[i];
    delete[] subGrid;
  }
};
}

#endif // #ifndef SUBGRIDLIST_HH
<commit_msg>fix parameters shadowing member var in subgrid list<commit_after>#ifndef SUBGRIDLIST_HH
#define SUBGRIDLIST_HH

#include <boost/noncopyable.hpp>

#include <dune/common/fmatrix.hh>
#include <dune/common/exceptions.hh>
#include <dune/subgrid/subgrid.hh>
#include <dune/fem/quadrature/cachingquadrature.hh>
#include <dune/fem/operator/common/operator.hh>
#include <dune/fem/operator/2order/lagrangematrixsetup.hh>
#include <dune/multiscale/tools/solver/MsFEM/msfem_localproblems/localproblemsolver.hh>

// / done

namespace Dune {
template< class HostDiscreteFunctionImp, class SubGridImp, class MacroMicroGridSpecifierImp >
class SubGridList : boost::noncopyable
{
public:
  // ! ---------------- typedefs for the HostDiscreteFunctionSpace -----------------------

  typedef MacroMicroGridSpecifierImp MacroMicroGridSpecifierType;

  typedef HostDiscreteFunctionImp HostDiscreteFunctionType;

  // ! type of discrete function space
  typedef typename HostDiscreteFunctionType::DiscreteFunctionSpaceType
  HostDiscreteFunctionSpaceType;

  // ! type of (non-discrete )function space
  typedef typename HostDiscreteFunctionSpaceType::FunctionSpaceType FunctionSpaceType;

  // ! type of grid partition
  typedef typename HostDiscreteFunctionSpaceType::GridPartType HostGridPartType;

  // ! type of grid
  typedef typename HostDiscreteFunctionSpaceType::GridType HostGridType;

  typedef typename HostGridType::Traits::LeafIndexSet HostGridLeafIndexSet;

  typedef typename HostDiscreteFunctionSpaceType::IteratorType HostGridEntityIteratorType;

  typedef typename HostGridEntityIteratorType::Entity HostEntityType;

  typedef typename HostEntityType::EntityPointer HostEntityPointerType;

  typedef typename HostEntityType::template Codim< 2 >::EntityPointer HostNodePointer;

  typedef typename HostGridPartType::IntersectionIteratorType HostIntersectionIterator;

  // ! ---------------- typedefs for the SubgridDiscreteFunctionSpace -----------------------
  // ( typedefs for the local grid and the corresponding local ('sub') )discrete space )

  // ! type of grid
  typedef SubGridImp SubGridType;

  // ! type of grid part
  typedef LeafGridPart< SubGridType > SubGridPartType;

  template< typename EntityPointerCollectionType >
  bool entity_patch_in_subgrid(HostEntityPointerType& hit,
                               const HostGridPartType& hostGridPart,
                               const SubGridType& subGrid,
                               EntityPointerCollectionType& entities_sharing_same_node) {
    bool patch_in_subgrid_ = true;

    // loop over the nodes of the enity
    for (int i = 0; i < (*hit).template count< 2 >(); i += 1)
    {
      const HostNodePointer node = (*hit).template subEntity< 2 >(i);

      int global_index_node = hostGridPart.indexSet().index(*node);

      for (int j = 0; j < entities_sharing_same_node[global_index_node].size(); j += 1)
      {
        if ( !( subGrid.template contains< 0 >(*entities_sharing_same_node[global_index_node][j]) ) )
        {
          patch_in_subgrid_ = false;
        }
      }
    }
    return patch_in_subgrid_;
  } // entity_patch_in_subgrid

  template< typename EntityPointerCollectionType >
  void enrichment(HostEntityPointerType& hit,
                  HostEntityPointerType& level_father_it,
                  MacroMicroGridSpecifierType& specifier,
                  int& father_index,
                  const HostGridPartType& hostGridPart,
                  SubGridType& subGrid,
                  EntityPointerCollectionType& entities_sharing_same_node,
                  int& layer,
                  bool***& enriched) {
    // difference in levels between coarse and fine grid
    int level_difference = specifier.getLevelDifference();
    HostDiscreteFunctionSpaceType& coarseSpace = specifier.coarseSpace();

    const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarseSpace.gridPart().grid().leafIndexSet();

    const HostGridLeafIndexSet& hostGridLeafIndexSet = hostSpace_.gridPart().grid().leafIndexSet();

    for (int l = 0; l <= layer; l += 1)
    {
      enriched[father_index][hostGridLeafIndexSet.index(*hit)][l] = true;
    }

    layer -= 1;

    // loop over the nodes of the enity
    for (int i = 0; i < (*hit).template count< 2 >(); i += 1)
    {
      const HostNodePointer node = (*hit).template subEntity< 2 >(i);
      int global_index_node = hostGridPart.indexSet().index(*node);

      for (size_t j = 0; j < entities_sharing_same_node[global_index_node].size(); j += 1)
      {
        if ( !( subGrid.template contains< 0 >(*entities_sharing_same_node[global_index_node][j]) ) )
        {
          subGrid.insertPartial(*entities_sharing_same_node[global_index_node][j]);
        }

        if (layer > 0)
        {
          HostEntityPointerType father = entities_sharing_same_node[global_index_node][j];
          for (int lev = 0; lev < level_difference; ++lev)
            father = father->father();

          HostEntityPointerType coarse_father_test = father;
          bool father_found = false;
          while (father_found == false)
          {
            if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)
            {
              father = coarse_father_test;
            }

            if (coarse_father_test->hasFather() == false)
            { father_found = true; } else
            { coarse_father_test = coarse_father_test->father(); }
          }

          if ( !(father == level_father_it) )
          {
            if (enriched[father_index][hostGridLeafIndexSet.index(*entities_sharing_same_node[global_index_node][j])][
                  layer] == false)
            {
              enrichment(entities_sharing_same_node[global_index_node][j], level_father_it,
                         specifier, father_index,
                         hostGridPart, subGrid, entities_sharing_same_node, layer, enriched);

              layer += 1;
            }
          }
        }
      }
    }
  } // enrichment

  SubGridList(MacroMicroGridSpecifierType& specifier, bool silent = true)
    : hostSpace_( specifier.fineSpace() )
      , specifier_(specifier)
      , silent_(silent) {
    std::cout << "Starting creation of subgrids." << std::endl << std::endl;

    HostDiscreteFunctionSpaceType& coarseSpace = specifier.coarseSpace();

    const HostGridPartType& hostGridPart = hostSpace_.gridPart();

    HostGridType& hostGrid = hostSpace_.gridPart().grid();

    int number_of_nodes = hostGrid.size(2 /*codim*/);

    // -------- identify the entities that share a certain node -------

    std::vector< std::vector< HostEntityPointerType > > entities_sharing_same_node(number_of_nodes);

    for (HostGridEntityIteratorType it = hostSpace_.begin(); it != hostSpace_.end(); ++it)
    {
      int number_of_nodes_in_entity = (*it).template count< 2 >();
      for (int i = 0; i < number_of_nodes_in_entity; i += 1)
      {
        const HostNodePointer node = (*it).template subEntity< 2 >(i);
        int global_index_node = hostGridPart.indexSet().index(*node);

        entities_sharing_same_node[global_index_node].push_back( HostEntityPointerType(*it) );
      }
    }

    int max_num_layers = 0;
    for (int i = 0; i < specifier_.getNumOfCoarseEntities(); i += 1)
    {
      if (specifier_.getLayer(i) > max_num_layers)
      { max_num_layers = specifier_.getLayer(i); }
    }

    // difference in levels between coarse and fine grid
    int level_difference = specifier.getLevelDifference();

    // number of coarse grid entities (of codim 0).
    int number_of_coarse_grid_entities = specifier.getNumOfCoarseEntities();

    std::cout << "number_of_coarse_grid_entities = " << number_of_coarse_grid_entities << std::endl;

    subGridList_ = new SubGridType *[number_of_coarse_grid_entities];

    // ! ----------- create subgrids --------------------

    const HostGridLeafIndexSet& coarseGridLeafIndexSet = coarseSpace.gridPart().grid().leafIndexSet();

    for (HostGridEntityIteratorType coarse_it = coarseSpace.begin(); coarse_it != coarseSpace.end(); ++coarse_it)
    {
      int coarse_index = coarseGridLeafIndexSet.index(*coarse_it);

      subGridList_[coarse_index] = new SubGridType(hostGrid);
      subGridList_[coarse_index]->createBegin();
    }

    for (HostGridEntityIteratorType it = hostSpace_.begin(); it != hostSpace_.end(); ++it)
    {
      int number_of_nodes_in_entity = (*it).template count< 2 >();
      for (int i = 0; i < number_of_nodes_in_entity; i += 1)
      {
        const HostNodePointer node = (*it).template subEntity< 2 >(i);
        int global_index_node = hostGridPart.indexSet().index(*node);

        entities_sharing_same_node[global_index_node].push_back( HostEntityPointerType(*it) );
      }
    }

    bool*** enriched = new bool**[number_of_coarse_grid_entities];
    for (int k = 0; k < number_of_coarse_grid_entities; k += 1)
    {
      enriched[k] = new bool*[hostGrid.size(0 /*codim*/)];
      for (int m = 0; m < hostGrid.size(0 /*codim*/); m += 1)
      {
        enriched[k][m] = new bool[max_num_layers + 1];
      }
    }

    for (int k = 0; k < number_of_coarse_grid_entities; k += 1)
    {
      for (int m = 0; m < hostGrid.size(0 /*codim*/); m += 1)
      {
        for (int l = 0; l < max_num_layers + 1; l += 1)
          enriched[k][m][l] = false;
      }
    }

    // a fine grid iterator for the codim 0 hostgrid entities:
    HostGridEntityIteratorType host_endit = hostSpace_.end();
    for (HostGridEntityIteratorType host_it = hostSpace_.begin();
         host_it != host_endit;
         ++host_it)
    {
      const HostEntityType& host_entity = *host_it;

      int DUNE_UNUSED(number_of_nodes_in_entity) = (*host_it).template count< 2 >();

      // get the coarse-grid-father of host_entity (which is a maxlevel entity)
      HostEntityPointerType level_father_entity = HostEntityPointerType(*host_it);

      for (int lev = 0; lev < level_difference; ++lev)
        level_father_entity = level_father_entity->father();

      // changed 'contains'-method in 'indexset.hh'
      // we use: "return ( (subIndex >= 0) && (subIndex < size( codim )) );"
      // instead of "return (subIndex >= 0);"
      HostEntityPointerType coarse_father_test = level_father_entity;
      bool father_found = false;
      while (father_found == false)
      {
        if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)
        { level_father_entity = coarse_father_test; }

        if (coarse_father_test->hasFather() == false)
        { father_found = true; } else
        { coarse_father_test = coarse_father_test->father(); }
      }

      int father_index = coarseGridLeafIndexSet.index(*level_father_entity);

      if ( !( subGridList_[father_index]->template contains< 0 >(host_entity) ) )
      { subGridList_[father_index]->insertPartial(host_entity); }

      // check the neighbor entities and look if they belong to the same father
      // if yes, continue
      // if not, enrichement with 'n(T)'-layers
      bool all_neighbors_have_same_father = true;
      const HostIntersectionIterator iend = hostGridPart.iend(host_entity);
      for (HostIntersectionIterator iit = hostGridPart.ibegin(host_entity); iit != iend; ++iit)
      {
        if ( iit->neighbor() ) // if there is a neighbor entity
        {
          // check if the neighbor entity is in the subgrid
          const HostEntityPointerType neighborHostEntityPointer = iit->outside();
          const HostEntityType& DUNE_UNUSED(neighborHostEntity) = *neighborHostEntityPointer;

          HostEntityPointerType level_father_neighbor_entity = neighborHostEntityPointer;
          for (int lev = 0; lev < level_difference; ++lev)
            level_father_neighbor_entity = level_father_neighbor_entity->father();

          HostEntityPointerType coarse_father_test = level_father_neighbor_entity;

          bool father_found = false;
          while (father_found == false)
          {
            if (coarseGridLeafIndexSet.contains(*coarse_father_test) == true)
            { level_father_neighbor_entity = coarse_father_test; }

            if (coarse_father_test->hasFather() == false)
            { father_found = true; } else
            { coarse_father_test = coarse_father_test->father(); }
          }

          if ( !(level_father_neighbor_entity == level_father_entity) )
          {
            all_neighbors_have_same_father = false;
          }
        } else {
          all_neighbors_have_same_father = false;
        }
      }

      if (all_neighbors_have_same_father == true)
      { continue; }

      int layers = specifier_.getLayer(father_index);
      if (layers > 0)
      {
        HostEntityPointerType hep(*host_it);
        enrichment(hep, level_father_entity, specifier, father_index,
                   hostGridPart, *subGridList_[father_index], entities_sharing_same_node, layers, enriched);
      }
    }

    for (int i = 0; i < number_of_coarse_grid_entities; ++i)
    {
      subGridList_[i]->createEnd();
      if (!silent_)
      {
        std::cout << "Subgrid " << i << ":" << std::endl;
        subGridList_[i]->report();
      }

      if (subGridList_[i]->size(2) == 0)
      {
        std::cout << "Error." << std::endl;
        std::cout << "Error. Created Subgrid with 0 nodes." << std::endl;

        for (HostGridEntityIteratorType coarse_it = specifier_.coarseSpace().begin();
             coarse_it != specifier_.coarseSpace().end(); ++coarse_it)
        {
          const HostEntityType& coarse_entity = *coarse_it;
          int index = coarseGridLeafIndexSet.index(coarse_entity);
          if (i == index)
          {
            std::cout << "We have a problem with the following coarse-grid element:" << std::endl;
            std::cout << "coarse element corner(0) = " << coarse_it->geometry().corner(0) << std::endl;
            std::cout << "coarse element corner(1) = " << coarse_it->geometry().corner(1) << std::endl;
            std::cout << "coarse element corner(2) = " << coarse_it->geometry().corner(2) << std::endl << std::endl;
          }
        }
        abort();
      }
    }

    // ! ----------- end create subgrids --------------------
  }

  SubGridType& getSubGrid(int i) {
    const int size = specifier_.getNumOfCoarseEntities();

    if (i >= size)
    {
      DUNE_THROW(Dune::RangeError, "Error. Subgrid-Index too large.");
    }
    return *(subGridList_[i]);
  } // getSubGrid

private:
  const HostDiscreteFunctionSpaceType& hostSpace_;
  MacroMicroGridSpecifierType& specifier_;

  bool silent_;

  SubGridType** subGridList_;

public:
  // Destruktor (Dynamisch angeforderter Speicher wird wieder freigegeben)
  ~SubGridList() {
    const int size = specifier_.getNumOfCoarseEntities();

    for (int i = 0; i < size; ++i)
      delete subGridList_[i];
    delete[] subGridList_;
  }
};
}

#endif // #ifndef SUBGRIDLIST_HH
<|endoftext|>