<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "SetupOutputAction.h"

#include "MooseApp.h"
#include "Output.h"
#include "FEProblem.h"
#include "Conversion.h"
#include "OutputProblem.h"
#include "Executioner.h"
#include "MooseMesh.h"
#include "libmesh/exodusII_io.h"

#include "unistd.h"

template<>
InputParameters validParams<SetupOutputAction>()
{
  InputParameters params = validParams<Action>();
  MooseEnum pps_fit_mode(FormattedTable::getWidthModes());

  params.addParam<OutFileBase>("file_base", "The desired solution output name without an extension (Defaults to the mesh file name + '_out' or 'out' if generating the mesh by some other means)");
  params.addParam<unsigned int>("interval", 1, "The interval at which timesteps are output to the solution file");
  params.addParam<unsigned int>("screen_interval", 1, "The interval at which postprocessors are output to the screen. This value must evenly divide \"interval\" so that postprocessors are calculated at corresponding solution timesteps. In addition, if \"screen_interval\" is strictly greater than \"interval\", \"output_initial\" must be set to true");
  params.addParam<bool>("exodus", false, "Specifies that you would like Exodus output solution file(s)");
  params.addParam<bool>("nemesis", false, "Specifies that you would like Nemesis output solution file(s)");
  params.addParam<bool>("gmv", false, "Specifies that you would like GMV output solution file(s)");
  params.addParam<bool>("vtk", false, "Specifies that you would like VTK output solution file(s)");
  params.addParam<bool>("tecplot", false, "Specifies that you would like Tecplot output solution files(s)");
  params.addParam<bool>("tecplot_binary", false, "Specifies that you would like Tecplot binary output solution files(s)");
  params.addParam<bool>("xda", false, "Specifies that you would like xda output solution files(s)");
  params.addParam<bool>("postprocessor_screen", true, "Specifies that you would like PostProcessor output to the screen (stdout)");
  params.addParam<unsigned int>("max_pps_rows_screen", 15, "The maximum number of postprocessor values displayed on screen during a timestep (set to 0 for unlimited)");
  params.addParam<MooseEnum>("pps_fit_to_screen", pps_fit_mode, "Specifies the wrapping mode for post-processor tables that are printed to the screen "
                             "(ENVIRONMENT: Read \"PPS_WIDTH\" for desired width, AUTO: Attempt to determine width automatically (serial only), <n>: Desired width");
  params.addParam<bool>("postprocessor_csv", false, "Specifies that you would like a PostProcessor comma separated values file");
  params.addParam<bool>("postprocessor_gnuplot", false, "Specifies that you would like plots of the postprocessor output");
  params.addParam<std::string>("gnuplot_format", "ps", "Specifies which output format gnuplot will produce. Currently supported: ps, gif, and png");
  params.addParam<bool>("output_initial", false, "Requests that the initial condition is output to the solution file");
  params.addParam<bool>("output_displaced", false, "Requests that displaced mesh files are written at each solve");
  params.addParam<bool>("output_solution_history", false, "Requests that the 'solution history' is output, the solution history is the number of nonlinear / linear solves that are done for each step.");
  params.addParam<bool>("output_es_info", true, "Requests that we output Equation Systems info during calls to initialSetup (normallly at the beginning of a simulation.)");
  params.addParam<Real>("time_interval", "simulation time at which to solve and output");

  params.addParam<bool>("color_output", true, "If true then MOOSE will attempt to add color when it outputs to the console.");

  params.addParam<Real>("iteration_plot_start_time", std::numeric_limits<Real>::max(), "Specifies a time after which the solution will be written following each nonlinear iteration");

  params.addParam<bool>("perf_log",        false,    "Specifies whether or not the Performance log should be printed");
  params.addParam<bool>("show_setup_log_early", false, "Specifies whether or not the Setup Performance log should be printed before the first time step.  It will still be printed at the end if ""perf_log"" is also enabled and likewise disabled in ""perf_log"" is false");
  params.addParam<std::vector<VariableName> >("output_variables", "A list of the variables that should be output to the Exodus file.  If this is not provided then all variables will be in the output.");
  params.addParam<std::vector<VariableName> >("hidden_variables", "A list of the variables that should NOT be output to the Exodus file.  If this is not provided then all variables will be in the output.");
  params.addParam<bool>("elemental_as_nodal", false, "Output elemental variables also as nodal");
  params.addParam<bool>("exodus_inputfile_output", true, "Determines whether or not the input file is output to exodus - default (true)");
  params.addParam<std::vector<std::string> >("output_if_base_contains", "If this is supplied then output will only be done in the case that the output base contains one of these strings.  This is helpful in outputing only a subset of outputs when using MultiApps.");

  // restart options
  params.addParam<unsigned int>("num_restart_files", 0, "Number of the restart files to save (0 = no restart files)");
  params.addParam<Point>("position", "Set a positional offset.  This vector will get added to the nodal cooardinates to move the domain.");

  params.addParamNamesToGroup("position interval time_interval output_displaced output_solution_history iteration_plot_start_time elemental_as_nodal exodus_inputfile_output output_es_info output_variables hidden_variables", "Advanced");
  params.addParamNamesToGroup("nemesis gmv vtk tecplot tecplot_binary xda", "Format");
  params.addParamNamesToGroup("screen_interval postprocessor_screen max_pps_rows_screen pps_fit_to_screen postprocessor_csv postprocessor_gnuplot gnuplot_format", "Postprocessor");
  params.addParamNamesToGroup("perf_log show_setup_log_early", "Logging");
  params.addParamNamesToGroup("num_restart_files", "Restart");

  return params;
}

SetupOutputAction::SetupOutputAction(const std::string & name, InputParameters params) :
    Action(name, params)
{
}

void
SetupOutputAction::setupOutputObject(Output &output, InputParameters & params)
{
  mooseAssert(params.have_parameter<std::vector<VariableName> >("output_variables"), "Output Variables are required");

  OutFileBase base = params.get<OutFileBase>("file_base");

  if(params.isParamValid("output_if_base_contains"))
  {
    const std::vector<std::string> & strings = params.get<std::vector<std::string> >("output_if_base_contains");

    bool found_it = false;
    for(unsigned int i=0; i<strings.size(); i++)
      found_it = found_it || ( base.find(strings[i]) != std::string::npos);

    if(!found_it) // Didn't find a match so no output should be done
      return;
  }

  output.fileBase(base);

  if (params.get<bool>("exodus"))
  {
    if (params.have_parameter<bool>("exodus_inputfile_output") && !params.get<bool>("exodus_inputfile_output"))
      output.add(Output::EXODUS, false);
    else
      output.add(Output::EXODUS, true);
  }
  if (params.get<bool>("nemesis")) output.add(Output::NEMESIS);
  if (params.get<bool>("gmv")) output.add(Output::GMV);
  if (params.get<bool>("vtk")) output.add(Output::VTK);
  if (params.get<bool>("tecplot")) output.add(Output::TECPLOT);
  if (params.get<bool>("tecplot_binary")) output.add(Output::TECPLOT_BIN);
  if (params.get<bool>("xda")) output.add(Output::XDA);
}

void
SetupOutputAction::act()
{
  // Disable Perf Log if requested
  if (!getParam<bool>("perf_log"))
  {
    Moose::perf_log.disable_logging();
    Moose::setup_perf_log.disable_logging();
  }

  mooseAssert(_problem, "This should never happen!");

  /// Determines whether we see the perf log early in a run or not
  _problem->setEarlyPerfLogPrint(getParam<bool>("show_setup_log_early"));

  if (_pars.isParamValid("hidden_variables"))
  {
    _problem->hideVariableFromOutput(getParam<std::vector<VariableName> >("hidden_variables"));
  }

  if (_pars.isParamValid("output_variables"))
  {
    _problem->showVariableInOutput(getParam<std::vector<VariableName> >("output_variables"));
  }
  else
  {
    if (getParam<bool>("elemental_as_nodal"))
    {
      // output all variables in the system
      _problem->showVariableInOutput(_problem->getVariableNames());
    }
  }

  if(_pars.isParamValid("position"))
    _app.setOutputPosition(_pars.get<Point>("position"));

  // If the user didn't provide a filename - see if the parser has a filename that we can use as a base
  if (!_pars.isParamValid("file_base"))
    mooseError("\"file_base\" wasn't populated either by the input file or the parser.");

  _problem->setOutputVariables();

  Output & output = _problem->out();                       // can't use use this with coupled problems on different meshes

  // Has the filebase been overriden at the application level?
  if(_app.getOutputFileBase() != "")
    _pars.set<OutFileBase>("file_base") = _app.getOutputFileBase();

  setupOutputObject(output, _pars);

  const bool output_initial = getParam<bool>("output_initial");
  if (_executioner != NULL)
    _executioner->outputInitial(output_initial);

  // TODO: handle this thru Problem interface
  _problem->_postprocessor_screen_output = getParam<bool>("postprocessor_screen");
  _problem->_postprocessor_csv_output = getParam<bool>("postprocessor_csv");
  _problem->_postprocessor_gnuplot_output = getParam<bool>("postprocessor_gnuplot");
  _problem->_gnuplot_format = getParam<std::string>("gnuplot_format");
  _problem->setMaxPPSRowsScreen(getParam<unsigned int>("max_pps_rows_screen"));
  _problem->setPPSFitScreen(getParam<MooseEnum>("pps_fit_to_screen"));

  _problem->outputDisplaced(getParam<bool>("output_displaced"));
  _problem->outputSolutionHistory(getParam<bool>("output_solution_history"));
  _problem->outputESInfo(getParam<bool>("output_es_info"));

  _problem->setNumRestartFiles(getParam<unsigned int>("num_restart_files"));

#ifdef LIBMESH_ENABLE_AMR
  Adaptivity & adapt = _problem->adaptivity();
  if (adapt.isOn())
    output.sequence(true);
#endif //LIBMESH_ENABLE_AMR

  const unsigned int interval = getParam<unsigned int>("interval");
  const unsigned int screen_interval = getParam<unsigned int>("screen_interval");

  // Error checks
  if (interval < screen_interval)
    mooseError("\"screen_interval (" + Moose::stringify(screen_interval) +
               ")\" must be less than or equal to \"interval (" + Moose::stringify(interval) + ")\"");
  else if (interval > screen_interval)
  {
    if (interval % screen_interval)
      mooseError("\"screen_interval (" + Moose::stringify(screen_interval) +
                 ")\" must evenly divide \"interval (" + Moose::stringify(interval) + ")\"");
    else if (!output_initial)
      mooseError("\"interval (" + Moose::stringify(interval) + ") is set greater than \"screen_interval (" +
                 Moose::stringify(screen_interval) + ")\" and \"output_initial\" is set to false.");
  }

  output.interval(getParam<unsigned int>("interval"));
  output.screen_interval(getParam<unsigned int>("screen_interval"));
  output.iterationPlotStartTime(getParam<Real>("iteration_plot_start_time"));
  if(isParamValid("time_interval"))
   {
     Real time_interval_out = getParam<Real>("time_interval");
     output.setTimeIntervalOutput(time_interval_out);
     if(time_interval_out<=0)
     {
       mooseError("time interval must be positive");
     }
   }

  if(getParam<bool>("color_output"))
  {
    std::string term(getenv("TERM"));

    bool color = false;

    if(term == "xterm-256color")
      color = true;

    if(term == "xterm")
      color = true;

    if(color == true)
      _problem->colorOutput(true);
  }

 // Test to make sure that the user can write to the directory specified in file_base
  std::string base = "./" + getParam<OutFileBase>("file_base");
  base = base.substr(0, base.find_last_of('/'));

  // TODO: We have a function that tests read/write in the Parser namespace.  We should probably
  // use that instead of creating another one here
  if (access(base.c_str(), W_OK) == -1)
    mooseError("Can not write to directory: " + base + " for file base: " + getParam<OutFileBase>("file_base"));
}
<commit_msg>fixup previous refs #2176<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "SetupOutputAction.h"

#include "MooseApp.h"
#include "Output.h"
#include "FEProblem.h"
#include "Conversion.h"
#include "OutputProblem.h"
#include "Executioner.h"
#include "MooseMesh.h"
#include "libmesh/exodusII_io.h"

#include "unistd.h"

template<>
InputParameters validParams<SetupOutputAction>()
{
  InputParameters params = validParams<Action>();
  MooseEnum pps_fit_mode(FormattedTable::getWidthModes());

  params.addParam<OutFileBase>("file_base", "The desired solution output name without an extension (Defaults to the mesh file name + '_out' or 'out' if generating the mesh by some other means)");
  params.addParam<unsigned int>("interval", 1, "The interval at which timesteps are output to the solution file");
  params.addParam<unsigned int>("screen_interval", 1, "The interval at which postprocessors are output to the screen. This value must evenly divide \"interval\" so that postprocessors are calculated at corresponding solution timesteps. In addition, if \"screen_interval\" is strictly greater than \"interval\", \"output_initial\" must be set to true");
  params.addParam<bool>("exodus", false, "Specifies that you would like Exodus output solution file(s)");
  params.addParam<bool>("nemesis", false, "Specifies that you would like Nemesis output solution file(s)");
  params.addParam<bool>("gmv", false, "Specifies that you would like GMV output solution file(s)");
  params.addParam<bool>("vtk", false, "Specifies that you would like VTK output solution file(s)");
  params.addParam<bool>("tecplot", false, "Specifies that you would like Tecplot output solution files(s)");
  params.addParam<bool>("tecplot_binary", false, "Specifies that you would like Tecplot binary output solution files(s)");
  params.addParam<bool>("xda", false, "Specifies that you would like xda output solution files(s)");
  params.addParam<bool>("postprocessor_screen", true, "Specifies that you would like PostProcessor output to the screen (stdout)");
  params.addParam<unsigned int>("max_pps_rows_screen", 15, "The maximum number of postprocessor values displayed on screen during a timestep (set to 0 for unlimited)");
  params.addParam<MooseEnum>("pps_fit_to_screen", pps_fit_mode, "Specifies the wrapping mode for post-processor tables that are printed to the screen "
                             "(ENVIRONMENT: Read \"PPS_WIDTH\" for desired width, AUTO: Attempt to determine width automatically (serial only), <n>: Desired width");
  params.addParam<bool>("postprocessor_csv", false, "Specifies that you would like a PostProcessor comma separated values file");
  params.addParam<bool>("postprocessor_gnuplot", false, "Specifies that you would like plots of the postprocessor output");
  params.addParam<std::string>("gnuplot_format", "ps", "Specifies which output format gnuplot will produce. Currently supported: ps, gif, and png");
  params.addParam<bool>("output_initial", false, "Requests that the initial condition is output to the solution file");
  params.addParam<bool>("output_displaced", false, "Requests that displaced mesh files are written at each solve");
  params.addParam<bool>("output_solution_history", false, "Requests that the 'solution history' is output, the solution history is the number of nonlinear / linear solves that are done for each step.");
  params.addParam<bool>("output_es_info", true, "Requests that we output Equation Systems info during calls to initialSetup (normallly at the beginning of a simulation.)");
  params.addParam<Real>("time_interval", "simulation time at which to solve and output");

  params.addParam<bool>("color_output", true, "If true then MOOSE will attempt to add color when it outputs to the console.");

  params.addParam<Real>("iteration_plot_start_time", std::numeric_limits<Real>::max(), "Specifies a time after which the solution will be written following each nonlinear iteration");

  params.addParam<bool>("perf_log",        false,    "Specifies whether or not the Performance log should be printed");
  params.addParam<bool>("show_setup_log_early", false, "Specifies whether or not the Setup Performance log should be printed before the first time step.  It will still be printed at the end if ""perf_log"" is also enabled and likewise disabled in ""perf_log"" is false");
  params.addParam<std::vector<VariableName> >("output_variables", "A list of the variables that should be output to the Exodus file.  If this is not provided then all variables will be in the output.");
  params.addParam<std::vector<VariableName> >("hidden_variables", "A list of the variables that should NOT be output to the Exodus file.  If this is not provided then all variables will be in the output.");
  params.addParam<bool>("elemental_as_nodal", false, "Output elemental variables also as nodal");
  params.addParam<bool>("exodus_inputfile_output", true, "Determines whether or not the input file is output to exodus - default (true)");
  params.addParam<std::vector<std::string> >("output_if_base_contains", "If this is supplied then output will only be done in the case that the output base contains one of these strings.  This is helpful in outputing only a subset of outputs when using MultiApps.");

  // restart options
  params.addParam<unsigned int>("num_restart_files", 0, "Number of the restart files to save (0 = no restart files)");
  params.addParam<Point>("position", "Set a positional offset.  This vector will get added to the nodal cooardinates to move the domain.");

  params.addParamNamesToGroup("position interval time_interval output_displaced output_solution_history iteration_plot_start_time elemental_as_nodal exodus_inputfile_output output_es_info output_variables hidden_variables", "Advanced");
  params.addParamNamesToGroup("nemesis gmv vtk tecplot tecplot_binary xda", "Format");
  params.addParamNamesToGroup("screen_interval postprocessor_screen max_pps_rows_screen pps_fit_to_screen postprocessor_csv postprocessor_gnuplot gnuplot_format", "Postprocessor");
  params.addParamNamesToGroup("perf_log show_setup_log_early", "Logging");
  params.addParamNamesToGroup("num_restart_files", "Restart");

  return params;
}

SetupOutputAction::SetupOutputAction(const std::string & name, InputParameters params) :
    Action(name, params)
{
}

void
SetupOutputAction::setupOutputObject(Output &output, InputParameters & params)
{
  mooseAssert(params.have_parameter<std::vector<VariableName> >("output_variables"), "Output Variables are required");

  OutFileBase base = params.get<OutFileBase>("file_base");

  if(params.isParamValid("output_if_base_contains"))
  {
    const std::vector<std::string> & strings = params.get<std::vector<std::string> >("output_if_base_contains");

    bool found_it = false;
    for(unsigned int i=0; i<strings.size(); i++)
      found_it = found_it || ( base.find(strings[i]) != std::string::npos);

    if(!found_it) // Didn't find a match so no output should be done
      return;
  }

  output.fileBase(base);

  if (params.get<bool>("exodus"))
  {
    if (params.have_parameter<bool>("exodus_inputfile_output") && !params.get<bool>("exodus_inputfile_output"))
      output.add(Output::EXODUS, false);
    else
      output.add(Output::EXODUS, true);
  }
  if (params.get<bool>("nemesis")) output.add(Output::NEMESIS);
  if (params.get<bool>("gmv")) output.add(Output::GMV);
  if (params.get<bool>("vtk")) output.add(Output::VTK);
  if (params.get<bool>("tecplot")) output.add(Output::TECPLOT);
  if (params.get<bool>("tecplot_binary")) output.add(Output::TECPLOT_BIN);
  if (params.get<bool>("xda")) output.add(Output::XDA);
}

void
SetupOutputAction::act()
{
  // Disable Perf Log if requested
  if (!getParam<bool>("perf_log"))
  {
    Moose::perf_log.disable_logging();
    Moose::setup_perf_log.disable_logging();
  }

  mooseAssert(_problem, "This should never happen!");

  /// Determines whether we see the perf log early in a run or not
  _problem->setEarlyPerfLogPrint(getParam<bool>("show_setup_log_early"));

  if (_pars.isParamValid("hidden_variables"))
  {
    _problem->hideVariableFromOutput(getParam<std::vector<VariableName> >("hidden_variables"));
  }

  if (_pars.isParamValid("output_variables"))
  {
    _problem->showVariableInOutput(getParam<std::vector<VariableName> >("output_variables"));
  }
  else
  {
    if (getParam<bool>("elemental_as_nodal"))
    {
      // output all variables in the system
      _problem->showVariableInOutput(_problem->getVariableNames());
    }
  }

  if(_pars.isParamValid("position"))
    _app.setOutputPosition(_pars.get<Point>("position"));

  // If the user didn't provide a filename - see if the parser has a filename that we can use as a base
  if (!_pars.isParamValid("file_base"))
    mooseError("\"file_base\" wasn't populated either by the input file or the parser.");

  _problem->setOutputVariables();

  Output & output = _problem->out();                       // can't use use this with coupled problems on different meshes

  // Has the filebase been overriden at the application level?
  if(_app.getOutputFileBase() != "")
    _pars.set<OutFileBase>("file_base") = _app.getOutputFileBase();

  setupOutputObject(output, _pars);

  const bool output_initial = getParam<bool>("output_initial");
  if (_executioner != NULL)
    _executioner->outputInitial(output_initial);

  // TODO: handle this thru Problem interface
  _problem->_postprocessor_screen_output = getParam<bool>("postprocessor_screen");
  _problem->_postprocessor_csv_output = getParam<bool>("postprocessor_csv");
  _problem->_postprocessor_gnuplot_output = getParam<bool>("postprocessor_gnuplot");
  _problem->_gnuplot_format = getParam<std::string>("gnuplot_format");
  _problem->setMaxPPSRowsScreen(getParam<unsigned int>("max_pps_rows_screen"));
  _problem->setPPSFitScreen(getParam<MooseEnum>("pps_fit_to_screen"));

  _problem->outputDisplaced(getParam<bool>("output_displaced"));
  _problem->outputSolutionHistory(getParam<bool>("output_solution_history"));
  _problem->outputESInfo(getParam<bool>("output_es_info"));

  _problem->setNumRestartFiles(getParam<unsigned int>("num_restart_files"));

#ifdef LIBMESH_ENABLE_AMR
  Adaptivity & adapt = _problem->adaptivity();
  if (adapt.isOn())
    output.sequence(true);
#endif //LIBMESH_ENABLE_AMR

  const unsigned int interval = getParam<unsigned int>("interval");
  const unsigned int screen_interval = getParam<unsigned int>("screen_interval");

  // Error checks
  if (interval < screen_interval)
    mooseError("\"screen_interval (" + Moose::stringify(screen_interval) +
               ")\" must be less than or equal to \"interval (" + Moose::stringify(interval) + ")\"");
  else if (interval > screen_interval)
  {
    if (interval % screen_interval)
      mooseError("\"screen_interval (" + Moose::stringify(screen_interval) +
                 ")\" must evenly divide \"interval (" + Moose::stringify(interval) + ")\"");
    else if (!output_initial)
      mooseError("\"interval (" + Moose::stringify(interval) + ") is set greater than \"screen_interval (" +
                 Moose::stringify(screen_interval) + ")\" and \"output_initial\" is set to false.");
  }

  output.interval(getParam<unsigned int>("interval"));
  output.screen_interval(getParam<unsigned int>("screen_interval"));
  output.iterationPlotStartTime(getParam<Real>("iteration_plot_start_time"));
  if(isParamValid("time_interval"))
   {
     Real time_interval_out = getParam<Real>("time_interval");
     output.setTimeIntervalOutput(time_interval_out);
     if(time_interval_out<=0)
     {
       mooseError("time interval must be positive");
     }
   }

  if(getParam<bool>("color_output"))
  {
    char * term_env = getenv("TERM");

    if(term_env)
    {
      std::string term(term_env);

      bool color = false;

      if(term == "xterm-256color")
        color = true;

      if(term == "xterm")
        color = true;

      if(color == true)
        _problem->colorOutput(true);
    }
  }

 // Test to make sure that the user can write to the directory specified in file_base
  std::string base = "./" + getParam<OutFileBase>("file_base");
  base = base.substr(0, base.find_last_of('/'));

  // TODO: We have a function that tests read/write in the Parser namespace.  We should probably
  // use that instead of creating another one here
  if (access(base.c_str(), W_OK) == -1)
    mooseError("Can not write to directory: " + base + " for file base: " + getParam<OutFileBase>("file_base"));
}
<|endoftext|>


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

#ifndef PCL_PCL_HISTOGRAM_VISUALIZER_IMPL_H_
#define PCL_PCL_HISTOGRAM_VISUALIZER_IMPL_H_

#include <vtkDoubleArray.h>

////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::visualization::PCLHistogramVisualizer::addFeatureHistogram (
    const pcl::PointCloud<PointT> &cloud, int hsize,
    const std::string &id, int win_width, int win_height)
{
  RenWinInteractMap::iterator am_it = wins_.find (id);
  if (am_it != wins_.end ())
  {
    PCL_WARN ("[addFeatureHistogram] A window with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
    return (false);
  }

  vtkSmartPointer<vtkDoubleArray> xy_array = vtkSmartPointer<vtkDoubleArray>::New ();
  xy_array->SetNumberOfComponents (2);
  xy_array->SetNumberOfTuples (hsize);

  // Parse the cloud data and store it in the array
  double xy[2];
  for (int d = 0; d < hsize; ++d)
  {
    xy[0] = d;
    xy[1] = cloud.points[0].histogram[d];
    xy_array->SetTuple (d, xy);
  }
  RenWinInteract renwinint;
  createActor (xy_array, renwinint, id, win_width, win_height);

  // Save the pointer/ID pair to the global window map
  wins_[id] = renwinint;
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
  resetStoppedFlag ();
#endif
  return (true);
}

////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::visualization::PCLHistogramVisualizer::addFeatureHistogram (
    const pcl::PointCloud<PointT> &cloud,
    const std::string &field_name,
    const int index,
    const std::string &id, int win_width, int win_height)
{
  if (index < 0 || index >= cloud.points.size ())
  {
    PCL_ERROR ("[addFeatureHistogram] Invalid point index (%d) given!\n", index);
    return (false);
  }

  // Get the fields present in this cloud
  std::vector<pcl::PCLPointField> fields;
  // Check if our field exists
  int field_idx = pcl::getFieldIndex<PointT> (cloud, field_name, fields);
  if (field_idx == -1)
  {
    PCL_ERROR ("[addFeatureHistogram] The specified field <%s> does not exist!\n", field_name.c_str ());
    return (false);
  }

  RenWinInteractMap::iterator am_it = wins_.find (id);
  if (am_it != wins_.end ())
  {
    PCL_WARN ("[addFeatureHistogram] A window with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
    return (false);
  }

  vtkSmartPointer<vtkDoubleArray> xy_array = vtkSmartPointer<vtkDoubleArray>::New ();
  xy_array->SetNumberOfComponents (2);
  xy_array->SetNumberOfTuples (fields[field_idx].count);

  // Parse the cloud data and store it in the array
  double xy[2];
  for (int d = 0; d < fields[field_idx].count; ++d)
  {
    xy[0] = d;
    //xy[1] = cloud.points[index].histogram[d];
    float data;
    memcpy (&data, reinterpret_cast<const char*> (&cloud.points[index]) + fields[field_idx].offset + d * sizeof (float), sizeof (float));
    xy[1] = data;
    xy_array->SetTuple (d, xy);
  }
  RenWinInteract renwinint;
  createActor (xy_array, renwinint, id, win_width, win_height);

  // Save the pointer/ID pair to the global window map
  wins_[id] = renwinint;
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
  resetStoppedFlag ();
#endif
  return (true);
}

////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::visualization::PCLHistogramVisualizer::updateFeatureHistogram (
    const pcl::PointCloud<PointT> &cloud, int hsize,
    const std::string &id)
{
  RenWinInteractMap::iterator am_it = wins_.find (id);
  if (am_it == wins_.end ())
  {
    PCL_WARN ("[updateFeatureHistogram] A window with id <%s> does not exists!.\n", id.c_str ());
    return (false);
  }
  RenWinInteract* renwinupd = &wins_[id];

  vtkSmartPointer<vtkDoubleArray> xy_array = vtkSmartPointer<vtkDoubleArray>::New ();
  xy_array->SetNumberOfComponents (2);
  xy_array->SetNumberOfTuples (hsize);

  // Parse the cloud data and store it in the array
  double xy[2];
  for (int d = 0; d < hsize; ++d)
  {
    xy[0] = d;
    xy[1] = cloud.points[0].histogram[d];
    xy_array->SetTuple (d, xy);
  }
  reCreateActor (xy_array, renwinupd, hsize);
  return (true);
}

////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::visualization::PCLHistogramVisualizer::updateFeatureHistogram (
    const pcl::PointCloud<PointT> &cloud, const std::string &field_name, const int index,
    const std::string &id)
{
  if (index < 0 || index >= cloud.points.size ())
  {
    PCL_ERROR ("[updateFeatureHistogram] Invalid point index (%d) given!\n", index);
    return (false);
  }

  // Get the fields present in this cloud
  std::vector<pcl::PCLPointField> fields;
  // Check if our field exists
  int field_idx = pcl::getFieldIndex<PointT> (cloud, field_name, fields);
  if (field_idx == -1)
  {
    PCL_ERROR ("[updateFeatureHistogram] The specified field <%s> does not exist!\n", field_name.c_str ());
    return (false);
  }

  RenWinInteractMap::iterator am_it = wins_.find (id);
  if (am_it == wins_.end ())
  {
    PCL_WARN ("[updateFeatureHistogram] A window with id <%s> does not exists!.\n", id.c_str ());
    return (false);
  }
  RenWinInteract* renwinupd = &wins_[id];

  vtkSmartPointer<vtkDoubleArray> xy_array = vtkSmartPointer<vtkDoubleArray>::New ();
  xy_array->SetNumberOfComponents (2);
  xy_array->SetNumberOfTuples (fields[field_idx].count);

  // Parse the cloud data and store it in the array
  double xy[2];
  for (int d = 0; d < fields[field_idx].count; ++d)
  {
    xy[0] = d;
    //xy[1] = cloud.points[index].histogram[d];
    float data;
    memcpy (&data, reinterpret_cast<const char*> (&cloud.points[index]) + fields[field_idx].offset + d * sizeof (float), sizeof (float));
    xy[1] = data;
    xy_array->SetTuple (d, xy);
  }

  reCreateActor (xy_array, renwinupd, cloud.fields[field_idx].count - 1);
  return (true);
}

#endif

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

#ifndef PCL_PCL_HISTOGRAM_VISUALIZER_IMPL_H_
#define PCL_PCL_HISTOGRAM_VISUALIZER_IMPL_H_

#include <vtkDoubleArray.h>

////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::visualization::PCLHistogramVisualizer::addFeatureHistogram (
    const pcl::PointCloud<PointT> &cloud, int hsize,
    const std::string &id, int win_width, int win_height)
{
  RenWinInteractMap::iterator am_it = wins_.find (id);
  if (am_it != wins_.end ())
  {
    PCL_WARN ("[addFeatureHistogram] A window with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
    return (false);
  }

  vtkSmartPointer<vtkDoubleArray> xy_array = vtkSmartPointer<vtkDoubleArray>::New ();
  xy_array->SetNumberOfComponents (2);
  xy_array->SetNumberOfTuples (hsize);

  // Parse the cloud data and store it in the array
  double xy[2];
  for (int d = 0; d < hsize; ++d)
  {
    xy[0] = d;
    xy[1] = cloud.points[0].histogram[d];
    xy_array->SetTuple (d, xy);
  }
  RenWinInteract renwinint;
  createActor (xy_array, renwinint, id, win_width, win_height);

  // Save the pointer/ID pair to the global window map
  wins_[id] = renwinint;
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
  resetStoppedFlag ();
#endif
  return (true);
}

////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::visualization::PCLHistogramVisualizer::addFeatureHistogram (
    const pcl::PointCloud<PointT> &cloud,
    const std::string &field_name,
    const int index,
    const std::string &id, int win_width, int win_height)
{
  if (index < 0 || index >= cloud.points.size ())
  {
    PCL_ERROR ("[addFeatureHistogram] Invalid point index (%d) given!\n", index);
    return (false);
  }

  // Get the fields present in this cloud
  std::vector<pcl::PCLPointField> fields;
  // Check if our field exists
  int field_idx = pcl::getFieldIndex<PointT> (cloud, field_name, fields);
  if (field_idx == -1)
  {
    PCL_ERROR ("[addFeatureHistogram] The specified field <%s> does not exist!\n", field_name.c_str ());
    return (false);
  }

  RenWinInteractMap::iterator am_it = wins_.find (id);
  if (am_it != wins_.end ())
  {
    PCL_WARN ("[addFeatureHistogram] A window with id <%s> already exists! Please choose a different id and retry.\n", id.c_str ());
    return (false);
  }

  vtkSmartPointer<vtkDoubleArray> xy_array = vtkSmartPointer<vtkDoubleArray>::New ();
  xy_array->SetNumberOfComponents (2);
  xy_array->SetNumberOfTuples (fields[field_idx].count);

  // Parse the cloud data and store it in the array
  double xy[2];
  for (uint32_t d = 0; d < fields[field_idx].count; ++d)
  {
    xy[0] = d;
    //xy[1] = cloud.points[index].histogram[d];
    float data;
    memcpy (&data, reinterpret_cast<const char*> (&cloud.points[index]) + fields[field_idx].offset + d * sizeof (float), sizeof (float));
    xy[1] = data;
    xy_array->SetTuple (d, xy);
  }
  RenWinInteract renwinint;
  createActor (xy_array, renwinint, id, win_width, win_height);

  // Save the pointer/ID pair to the global window map
  wins_[id] = renwinint;
#if ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION <= 4))
  resetStoppedFlag ();
#endif
  return (true);
}

////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::visualization::PCLHistogramVisualizer::updateFeatureHistogram (
    const pcl::PointCloud<PointT> &cloud, int hsize,
    const std::string &id)
{
  RenWinInteractMap::iterator am_it = wins_.find (id);
  if (am_it == wins_.end ())
  {
    PCL_WARN ("[updateFeatureHistogram] A window with id <%s> does not exists!.\n", id.c_str ());
    return (false);
  }
  RenWinInteract* renwinupd = &wins_[id];

  vtkSmartPointer<vtkDoubleArray> xy_array = vtkSmartPointer<vtkDoubleArray>::New ();
  xy_array->SetNumberOfComponents (2);
  xy_array->SetNumberOfTuples (hsize);

  // Parse the cloud data and store it in the array
  double xy[2];
  for (int d = 0; d < hsize; ++d)
  {
    xy[0] = d;
    xy[1] = cloud.points[0].histogram[d];
    xy_array->SetTuple (d, xy);
  }
  reCreateActor (xy_array, renwinupd, hsize);
  return (true);
}

////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> bool
pcl::visualization::PCLHistogramVisualizer::updateFeatureHistogram (
    const pcl::PointCloud<PointT> &cloud, const std::string &field_name, const int index,
    const std::string &id)
{
  if (index < 0 || index >= cloud.points.size ())
  {
    PCL_ERROR ("[updateFeatureHistogram] Invalid point index (%d) given!\n", index);
    return (false);
  }

  // Get the fields present in this cloud
  std::vector<pcl::PCLPointField> fields;
  // Check if our field exists
  int field_idx = pcl::getFieldIndex<PointT> (cloud, field_name, fields);
  if (field_idx == -1)
  {
    PCL_ERROR ("[updateFeatureHistogram] The specified field <%s> does not exist!\n", field_name.c_str ());
    return (false);
  }

  RenWinInteractMap::iterator am_it = wins_.find (id);
  if (am_it == wins_.end ())
  {
    PCL_WARN ("[updateFeatureHistogram] A window with id <%s> does not exists!.\n", id.c_str ());
    return (false);
  }
  RenWinInteract* renwinupd = &wins_[id];

  vtkSmartPointer<vtkDoubleArray> xy_array = vtkSmartPointer<vtkDoubleArray>::New ();
  xy_array->SetNumberOfComponents (2);
  xy_array->SetNumberOfTuples (fields[field_idx].count);

  // Parse the cloud data and store it in the array
  double xy[2];
  for (uint32_t d = 0; d < fields[field_idx].count; ++d)
  {
    xy[0] = d;
    //xy[1] = cloud.points[index].histogram[d];
    float data;
    memcpy (&data, reinterpret_cast<const char*> (&cloud.points[index]) + fields[field_idx].offset + d * sizeof (float), sizeof (float));
    xy[1] = data;
    xy_array->SetTuple (d, xy);
  }

  reCreateActor (xy_array, renwinupd, cloud.fields[field_idx].count - 1);
  return (true);
}

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swacorr.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:11:19 $
 *
 *  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 _SWACORR_HXX
#define _SWACORR_HXX

#ifndef _MySVXACORR_HXX //autogen
#include <svx/svxacorr.hxx>
#endif

#include <com/sun/star/uno/Reference.h>

#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif

class SwAutoCorrect : public SvxAutoCorrect
{
protected:
    //  - return den Ersetzungstext (nur fuer SWG-Format, alle anderen
    //      koennen aus der Wortliste herausgeholt werden!)
    //      rShort ist der Stream-Name - gecryptet!
    virtual BOOL GetLongText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& , const String& rFileName, const String& rShort, String& rLong );
    //  - Text mit Attributierung (kann nur der SWG - SWG-Format!)
    //      rShort ist der Stream-Name - gecryptet!
    virtual BOOL PutText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&, const String& rFileName, const String& rShort, SfxObjectShell& ,
                            String& );

public:
    TYPEINFO();

    SwAutoCorrect( const SvxAutoCorrect& rACorr );
    virtual ~SwAutoCorrect();
};

#endif

<commit_msg>INTEGRATION: CWS swwarnings (1.6.708); FILE MERGED 2007/03/05 12:43:17 tl 1.6.708.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swacorr.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 08:10:31 $
 *
 *  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 _SWACORR_HXX
#define _SWACORR_HXX

#ifndef _MySVXACORR_HXX //autogen
#include <svx/svxacorr.hxx>
#endif

#include <com/sun/star/uno/Reference.h>

#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif

class SwAutoCorrect : public SvxAutoCorrect
{
protected:
    //  - return den Ersetzungstext (nur fuer SWG-Format, alle anderen
    //      koennen aus der Wortliste herausgeholt werden!)
    //      rShort ist der Stream-Name - gecryptet!
    virtual BOOL GetLongText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& , const String& rFileName, const String& rShort, String& rLong );

    //  - Text mit Attributierung (kann nur der SWG - SWG-Format!)
    //      rShort ist der Stream-Name - gecryptet!
    using  SvxAutoCorrect::PutText;
    virtual BOOL PutText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&, const String& rFileName, const String& rShort, SfxObjectShell& ,
                            String& );

public:
    TYPEINFO();

    SwAutoCorrect( const SvxAutoCorrect& rACorr );
    virtual ~SwAutoCorrect();
};

#endif

<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkDIAppPreprocessingReconstructionPerspective.h"
#include "berryIViewLayout.h"

void QmitkDIAppPreprocessingReconstructionPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout)
{
  std::string editorArea = layout->GetEditorArea();

  layout->AddStandaloneView("org.mitk.views.datamanager",
    false, berry::IPageLayout::LEFT, 0.3f, editorArea);

  layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview",
    false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager");

  berry::IFolderLayout::Pointer left =
    layout->CreateFolder("org.mitk.views.leftcontrols2",
    berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview");

  berry::IFolderLayout::Pointer bottomleft =
    layout->CreateFolder("org.mitk.views.leftcontrols",
    berry::IPageLayout::BOTTOM, 0.5f, "org.mitk.views.leftcontrols2");

  layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator",
    berry::IPageLayout::BOTTOM, .6f, "org.mitk.views.leftcontrols", false);

  /////////////////////////////////////////////
  // add the views
  /////////////////////////////////////////////

  left->AddView("org.mitk.views.diffusionpreprocessing");
  berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.diffusionpreprocessing");
  lo->SetCloseable(false);

  left->AddView("org.mitk.views.tensorreconstruction");
  lo = layout->GetViewLayout("org.mitk.views.tensorreconstruction");
  lo->SetCloseable(false);

  left->AddView("org.mitk.views.qballreconstruction");
  lo = layout->GetViewLayout("org.mitk.views.qballreconstruction");
  lo->SetCloseable(false);

  bottomleft->AddView("org.mitk.views.diffusionquantification");
  berry::IViewLayout::Pointer lo2 = layout->GetViewLayout("org.mitk.views.diffusionquantification");
  lo2->SetCloseable(false);

  bottomleft->AddView("org.mitk.views.odfmaximaextraction");
  layout->GetViewLayout("org.mitk.views.odfmaximaextraction");
  lo2->SetCloseable(false);

  bottomleft->AddView("org.mitk.views.odfdetails");
  lo2 = layout->GetViewLayout("org.mitk.views.odfdetails");
  lo2->SetCloseable(false);
}
<commit_msg>Making closing impossible for peak extraction<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "QmitkDIAppPreprocessingReconstructionPerspective.h"
#include "berryIViewLayout.h"

void QmitkDIAppPreprocessingReconstructionPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout)
{
  std::string editorArea = layout->GetEditorArea();

  layout->AddStandaloneView("org.mitk.views.datamanager",
    false, berry::IPageLayout::LEFT, 0.3f, editorArea);

  layout->AddStandaloneView("org.mitk.views.controlvisualizationpropertiesview",
    false, berry::IPageLayout::BOTTOM, .15f, "org.mitk.views.datamanager");

  berry::IFolderLayout::Pointer left =
    layout->CreateFolder("org.mitk.views.leftcontrols2",
    berry::IPageLayout::BOTTOM, 0.1f, "org.mitk.views.controlvisualizationpropertiesview");

  berry::IFolderLayout::Pointer bottomleft =
    layout->CreateFolder("org.mitk.views.leftcontrols",
    berry::IPageLayout::BOTTOM, 0.5f, "org.mitk.views.leftcontrols2");

  layout->AddStandaloneViewPlaceholder("org.mitk.views.imagenavigator",
    berry::IPageLayout::BOTTOM, .6f, "org.mitk.views.leftcontrols", false);

  /////////////////////////////////////////////
  // add the views
  /////////////////////////////////////////////

  left->AddView("org.mitk.views.diffusionpreprocessing");
  berry::IViewLayout::Pointer lo = layout->GetViewLayout("org.mitk.views.diffusionpreprocessing");
  lo->SetCloseable(false);

  left->AddView("org.mitk.views.tensorreconstruction");
  lo = layout->GetViewLayout("org.mitk.views.tensorreconstruction");
  lo->SetCloseable(false);

  left->AddView("org.mitk.views.qballreconstruction");
  lo = layout->GetViewLayout("org.mitk.views.qballreconstruction");
  lo->SetCloseable(false);

  bottomleft->AddView("org.mitk.views.diffusionquantification");
  berry::IViewLayout::Pointer lo2 = layout->GetViewLayout("org.mitk.views.diffusionquantification");
  lo2->SetCloseable(false);

  bottomleft->AddView("org.mitk.views.odfmaximaextraction");
  lo2 = layout->GetViewLayout("org.mitk.views.odfmaximaextraction");
  lo2->SetCloseable(false);

  bottomleft->AddView("org.mitk.views.odfdetails");
  lo2 = layout->GetViewLayout("org.mitk.views.odfdetails");
  lo2->SetCloseable(false);
}
<|endoftext|>


<commit_before>//
//  system.cpp
//  alisp
//
//  Created by Matt Gadda on 10/1/11.
//  Copyright (c) 2011 Catalpa Labs. All rights reserved.
//

#include <iostream>
#include "system.h"
#include "package.h"
#include "symbol.h"
#include "special_operator.h"
#include "cons.h"
#include "environment.h"
#include "data_types.h"
#include "function.h"

extern Object *eval(Object* obj, Environment *env);

namespace  {
  void bindSymbolToFunc(Package &package, std::string name, Object *(*funcPtr)(Cons*,Environment*)) {
    Symbol *sym = package.internSymbol(name);
    package.exportSymbol(name);

    Callable *fun = new Function(funcPtr);
    sym->setFunction(fun);
  }

  void bindSymbolToSpecialOperator(Package &package, std::string name, Object *(*funcPtr)(Cons*,Environment*)) {
    Symbol *sym = package.internSymbol(name);
    package.exportSymbol(name);

    Callable *fun = new SpecialOperator(funcPtr);
    sym->setFunction(fun);
  }

};

void initSystem() {
  Package &system = Package::system();

  // Special Operators
  bindSymbolToSpecialOperator(system, "QUOTE", quote);
  bindSymbolToSpecialOperator(system, "SETQ", setq);
  bindSymbolToSpecialOperator(system, "PROGN", progn);
  bindSymbolToSpecialOperator(system, "LET", let);

  // System Functions
  bindSymbolToFunc(system, "LENGTH", length);
  bindSymbolToFunc(system, "CAR", car);
  bindSymbolToFunc(system, "CDR", cdr);
}

#pragma mark Special Operators

Object *quote(Cons* args, Environment *env) {
  if (args->length() > 1) {
    throw "too many arguments for special operator QUOTE:";
  }
  return args->car();
}

Object *setq(Cons* args, Environment *env) {
  // check number of arguemnts, if odd, raise error
  if (args->length() % 2 == 1) {
    char *errMsg;
    asprintf(&errMsg, "SETQ: odd number of arguments: %s", ((Object*)args)->print());
    throw errMsg;
  }

  // TODO: SETQ should bind multiple pairs
  Symbol *symbol = (Symbol*)args->car();
  Object *value = ((Cons*)args->cdr())->car();
  // extract pairs of values from args
  // bind first to eval of second
  return env->bindVariable(symbol, eval(value, env));
}

Object *progn(Cons* args, Environment *env) {
  __block Object *last = Symbol::nil();
  args->each(^(Object *obj) {
    last = eval(obj, env);
  });
  return last;
}

Object *let(Cons *args, Environment *env) {
  /*
   (let* ((var1 init-form-1)
          (var2 init-form-2)
          ...
          (varm init-form-m))
     declaration1
     declaration2
     ...
     declarationp
     form1
     form2
     ...
     formn)
   */

  Environment *letEnv = new Environment(env);

  if(args->car()->type() == std::string("CONS")) {
    Cons* bindings = (Cons*)args->car();
    bindings->each(^(Object *obj) {
      if (obj->type() == std::string("CONS")) {

        // (let ((a)) ...) OR (let ((a 10)) ...)

        Cons *binding = (Cons*)obj;
        size_t len = binding->length();

        if (len == 0) {
          throw "NIL is a constant, may not be used as a variable";
        }
        else if (len == 1) { // (let (... (a) ...) ...)
          letEnv->bindVariable((Symbol*)binding->car(), Symbol::nil());
        }
        else if (len == 2) { // (let (... (a 10) ...) ...)
          if (binding->car()->type() != std::string("SYMBOL"))
            throw "LET: illegal variable specification";
          letEnv->bindVariable((Symbol*)binding->car(), eval(((Cons*)binding->cdr())->car(), env));
        }
        else {
          throw "LET: illegal variable specification";
        }
      }
      else {
        // (let (... a ...) ...)
        if (obj->type() != std::string("SYMBOL"))
          throw "LET: illegal variable specification";
        letEnv->bindVariable((Symbol*)obj, Symbol::nil());
      }
    });
  }

  return progn((Cons*)args->cdr(), letEnv);
}

#pragma mark System Functions

Object *length(Cons* args, Environment *env) {
  return new Integer((int)args->length());
}

Object *car(Cons* args, Environment *env) {
  Object *list = args->car(); // first argument

  if (NILP(args->car()))
    return Symbol::nil();

  if (list->type() != std::string("CONS")) {
    char *errMsg;
    asprintf(&errMsg, "CAR: %s is not a list", list->print());
    throw errMsg;
  }
  return ((Cons*)list)->car();
}

Object *cdr(Cons* args, Environment *env) {
  Object *list = args->car(); // first argument

  if (NILP(args->car()))
    return Symbol::nil();

  if (list->type() != std::string("CONS")) {
    char *errMsg;
    asprintf(&errMsg, "CDR: %s is not a list", list->print());
    throw errMsg;
  }
  return ((Cons*)list)->cdr();
}<commit_msg>'() evils to NIL instead of (NIL)<commit_after>//
//  system.cpp
//  alisp
//
//  Created by Matt Gadda on 10/1/11.
//  Copyright (c) 2011 Catalpa Labs. All rights reserved.
//

#include <iostream>
#include "system.h"
#include "package.h"
#include "symbol.h"
#include "special_operator.h"
#include "cons.h"
#include "environment.h"
#include "data_types.h"
#include "function.h"

extern Object *eval(Object* obj, Environment *env);

namespace  {
  void bindSymbolToFunc(Package &package, std::string name, Object *(*funcPtr)(Cons*,Environment*)) {
    Symbol *sym = package.internSymbol(name);
    package.exportSymbol(name);

    Callable *fun = new Function(funcPtr);
    sym->setFunction(fun);
  }

  void bindSymbolToSpecialOperator(Package &package, std::string name, Object *(*funcPtr)(Cons*,Environment*)) {
    Symbol *sym = package.internSymbol(name);
    package.exportSymbol(name);

    Callable *fun = new SpecialOperator(funcPtr);
    sym->setFunction(fun);
  }

};

void initSystem() {
  Package &system = Package::system();

  // Special Operators
  bindSymbolToSpecialOperator(system, "QUOTE", quote);
  bindSymbolToSpecialOperator(system, "SETQ", setq);
  bindSymbolToSpecialOperator(system, "PROGN", progn);
  bindSymbolToSpecialOperator(system, "LET", let);

  // System Functions
  bindSymbolToFunc(system, "LENGTH", length);
  bindSymbolToFunc(system, "CAR", car);
  bindSymbolToFunc(system, "CDR", cdr);
}

#pragma mark Special Operators

Object *quote(Cons* args, Environment *env) {
  if (args->length() > 1) {
    throw "too many arguments for special operator QUOTE:";
  }
  Object *first = args->car();
  if (first->type() == std::string("CONS")) {
    Cons* list = (Cons*)args->car();

    if (NILP(list->car()) && NILP(list->cdr())) {
      return Symbol::nil();
    }

  }

  return first;
}

Object *setq(Cons* args, Environment *env) {
  // check number of arguemnts, if odd, raise error
  if (args->length() % 2 == 1) {
    char *errMsg;
    asprintf(&errMsg, "SETQ: odd number of arguments: %s", ((Object*)args)->print());
    throw errMsg;
  }

  // TODO: SETQ should bind multiple pairs
  Symbol *symbol = (Symbol*)args->car();
  Object *value = ((Cons*)args->cdr())->car();
  // extract pairs of values from args
  // bind first to eval of second
  return env->bindVariable(symbol, eval(value, env));
}

Object *progn(Cons* args, Environment *env) {
  __block Object *last = Symbol::nil();
  args->each(^(Object *obj) {
    last = eval(obj, env);
  });
  return last;
}

Object *let(Cons *args, Environment *env) {
  /*
   (let* ((var1 init-form-1)
          (var2 init-form-2)
          ...
          (varm init-form-m))
     declaration1
     declaration2
     ...
     declarationp
     form1
     form2
     ...
     formn)
   */

  Environment *letEnv = new Environment(env);

  if(args->car()->type() == std::string("CONS")) {
    Cons* bindings = (Cons*)args->car();
    bindings->each(^(Object *obj) {
      if (obj->type() == std::string("CONS")) {

        // (let ((a)) ...) OR (let ((a 10)) ...)

        Cons *binding = (Cons*)obj;
        size_t len = binding->length();

        if (len == 0) {
          throw "NIL is a constant, may not be used as a variable";
        }
        else if (len == 1) { // (let (... (a) ...) ...)
          letEnv->bindVariable((Symbol*)binding->car(), Symbol::nil());
        }
        else if (len == 2) { // (let (... (a 10) ...) ...)
          if (binding->car()->type() != std::string("SYMBOL"))
            throw "LET: illegal variable specification";
          letEnv->bindVariable((Symbol*)binding->car(), eval(((Cons*)binding->cdr())->car(), env));
        }
        else {
          throw "LET: illegal variable specification";
        }
      }
      else {
        // (let (... a ...) ...)
        if (obj->type() != std::string("SYMBOL"))
          throw "LET: illegal variable specification";
        letEnv->bindVariable((Symbol*)obj, Symbol::nil());
      }
    });
  }

  return progn((Cons*)args->cdr(), letEnv);
}

#pragma mark System Functions

Object *length(Cons* args, Environment *env) {
  return new Integer((int)args->length());
}

Object *car(Cons* args, Environment *env) {
  Object *list = args->car(); // first argument

  if (NILP(args->car()))
    return Symbol::nil();

  if (list->type() != std::string("CONS")) {
    char *errMsg;
    asprintf(&errMsg, "CAR: %s is not a list", list->print());
    throw errMsg;
  }
  return ((Cons*)list)->car();
}

Object *cdr(Cons* args, Environment *env) {
  Object *list = args->car(); // first argument

  if (NILP(args->car()))
    return Symbol::nil();

  if (list->type() != std::string("CONS")) {
    char *errMsg;
    asprintf(&errMsg, "CDR: %s is not a list", list->print());
    throw errMsg;
  }
  return ((Cons*)list)->cdr();
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>

void run_part_one() {
}
void run_part_two() {
}

int main(int argc, char* argv[]) {
    if (argc > 1) {
        if (std::string(argv[1]) == "--part_two") {
            run_part_two();
        } else {
            std::cout << "Usage: day24 [--part_two]" << std::endl;
            return -1;
        }
    } else {
        run_part_one();
    }
}
<commit_msg>added runtime code for day 24 part one<commit_after>#include <iostream>
#include <string>

#include "Packaging.hpp"

void run_part_one() {
    std::string line;
    std::vector<unsigned int> packages;
    while (std::getline(std::cin,line)) {
        packages.push_back(std::stol(line));
    }
    std::cout << get_minimum_entaglement(packages) << std::endl;
}
void run_part_two() {
}

int main(int argc, char* argv[]) {
    if (argc > 1) {
        if (std::string(argv[1]) == "--part_two") {
            run_part_two();
        } else {
            std::cout << "Usage: day24 [--part_two]" << std::endl;
            return -1;
        }
    } else {
        run_part_one();
    }
}
<|endoftext|>


<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
    crypto/gui/wizard.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra 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.

    Kleopatra 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "wizard.h"
#include "wizardpage.h"

#include <utils/kleo_assert.h>

#include <KDebug>
#include <KGuiItem>
#include <KLocale>
#include <KPushButton>
#include <KStandardGuiItem>

#include <QDialogButtonBox>
#include <QFrame>
#include <QLabel>
#include <QStackedWidget>
#include <QVBoxLayout>
#include <QWizard>

#include <map>
#include <set>

#include <cassert>

using namespace Kleo::Crypto::Gui;

class Wizard::Private {
    friend class ::Wizard;
    Wizard * const q;
public:
    explicit Private( Wizard * qq );
    ~Private();

    void updateButtonStates();
    bool isLastPage( int id ) const;
    int previousPage() const;
    void updateHeader();

private:
    std::vector<int> pageOrder;
    std::set<int> hiddenPages;
    std::map<int, WizardPage*> idToPage;
    int currentId;
    QStackedWidget* stack;
    KPushButton* nextButton;
    QPushButton* backButton;
    QPushButton* cancelButton;
    KGuiItem finishItem;
    KGuiItem nextItem;
    QFrame* titleFrame;
    QLabel* titleLabel;
    QLabel* subTitleLabel;
    QFrame* explanationFrame;
    QLabel* explanationLabel;
};

Wizard::Private::Private( Wizard * qq )
    : q( qq ), currentId( -1 ), stack( new QStackedWidget )
{
    const QWizard wiz;
    nextItem = KStandardGuiItem::forward();
    finishItem = KStandardGuiItem::ok();
    QVBoxLayout * const top = new QVBoxLayout( q );
    top->setMargin( 0 );
    titleFrame = new QFrame;
    titleFrame->setFrameShape( QFrame::StyledPanel );
    titleFrame->setAutoFillBackground( true );
    titleFrame->setBackgroundRole( QPalette::Base );
    QVBoxLayout* const titleLayout = new QVBoxLayout( titleFrame );
    titleLabel = new QLabel;
    titleLayout->addWidget( titleLabel );
    subTitleLabel = new QLabel;
    subTitleLabel->setWordWrap( true );
    titleLayout->addWidget( subTitleLabel );
    top->addWidget( titleFrame );
    titleFrame->setVisible( false );

    top->addWidget( stack );

    explanationFrame = new QFrame;
    explanationFrame->setFrameShape( QFrame::StyledPanel );
    explanationFrame->setAutoFillBackground( true );
    explanationFrame->setBackgroundRole( QPalette::Base );
    QVBoxLayout* const explanationLayout = new QVBoxLayout( explanationFrame );
    explanationLabel = new QLabel;
    explanationLabel->setWordWrap( true );
    explanationLayout->addWidget( explanationLabel );
    top->addWidget( explanationFrame );
    explanationFrame->setVisible( false );

    QWidget* buttonWidget = new QWidget;
    QHBoxLayout* buttonLayout = new QHBoxLayout( buttonWidget );
    QDialogButtonBox * const box = new QDialogButtonBox;

    cancelButton = box->addButton( QDialogButtonBox::Cancel );
    q->connect( cancelButton, SIGNAL( clicked() ), q, SLOT( reject() ) );

    backButton = new QPushButton;
    backButton->setText( wiz.buttonText( QWizard::BackButton ) );
    q->connect( backButton, SIGNAL( clicked() ), q, SLOT( back() ) );
    box->addButton( backButton, QDialogButtonBox::ActionRole );

    nextButton = new KPushButton;
    nextButton->setGuiItem( nextItem );
    q->connect( nextButton, SIGNAL( clicked() ), q, SLOT( next() ) );
    box->addButton( nextButton, QDialogButtonBox::ActionRole );
    buttonLayout->addWidget( box );

    top->addWidget( buttonWidget );

    q->connect( q, SIGNAL( rejected() ), q, SIGNAL( canceled() ) );
}

Wizard::Private::~Private() { kDebug(); }

bool Wizard::Private::isLastPage( int id ) const
{
    return !pageOrder.empty() ? pageOrder.back() == id : false;
}

void Wizard::Private::updateButtonStates()
{
    const bool isLast = isLastPage( currentId );
    const bool canGoToNext = q->canGoToNextPage();
    WizardPage* const page = q->page( currentId );
    assert( page );
    KGuiItem customNext = page->customNextButton();
    if ( customNext.text().isEmpty() && customNext.icon().isNull() )
        nextButton->setGuiItem( isLast ? finishItem : nextItem );
    else
        nextButton->setGuiItem( customNext );
    nextButton->setEnabled( canGoToNext );
    cancelButton->setEnabled( !isLast || !canGoToNext );
    backButton->setEnabled( q->canGoToPreviousPage() );

}

void Wizard::Private::updateHeader()
{
    WizardPage * const widget = q->page( currentId );
    assert( !widget || stack->indexOf( widget ) != -1 );
    if ( widget )
        stack->setCurrentWidget( widget );
    const QString title = widget ? widget->title() : QString();
    const QString subTitle = widget ? widget->subTitle() : QString();
    const QString explanation = widget ? widget->explanation() : QString();
    titleFrame->setVisible( !title.isEmpty() || !subTitle.isEmpty() || !explanation.isEmpty() );
    titleLabel->setVisible( !title.isEmpty() );
    titleLabel->setText( title );
    subTitleLabel->setText( subTitle );
    subTitleLabel->setVisible( !subTitle.isEmpty() );
    explanationFrame->setVisible( !explanation.isEmpty() );
    explanationLabel->setVisible( !explanation.isEmpty() );
    explanationLabel->setText( explanation );
    q->resize( q->sizeHint().expandedTo( q->size() ) );
}

Wizard::Wizard( QWidget * parent, Qt::WFlags f )
  : QDialog( parent, f ), d( new Private( this ) )
{

}

Wizard::~Wizard() { kDebug(); }

void Wizard::setPage( int id, WizardPage* widget )
{
    kleo_assert( id != InvalidPage );
    kleo_assert( d->idToPage.find( id ) == d->idToPage.end() );
    d->idToPage[id] = widget;
    d->stack->addWidget( widget );
    connect( widget, SIGNAL( completeChanged() ), this, SLOT( updateButtonStates() ) );
    connect( widget, SIGNAL( titleChanged() ), this, SLOT( updateHeader() ) );
    connect( widget, SIGNAL( subTitleChanged() ), this, SLOT( updateHeader() ) );
    connect( widget, SIGNAL( explanationChanged() ), this, SLOT( updateHeader() ) );
}

void Wizard::setPageOrder( const std::vector<int>& pageOrder )
{
    d->pageOrder = pageOrder;
    d->hiddenPages.clear();
    if ( pageOrder.empty() )
        return;
    setCurrentPage( pageOrder.front() );
}

void Wizard::setCurrentPage( int id )
{
    d->currentId = id;
    if ( id == InvalidPage )
        return;
    d->updateHeader();
    d->updateButtonStates();
}

void Wizard::setPageVisible( int id, bool visible )
{
    if ( visible )
        d->hiddenPages.erase( id );
    else
        d->hiddenPages.insert( id );
    if ( currentPage() == id && !visible )
        next();
}

int Wizard::currentPage() const
{
    return d->currentId;
}

bool Wizard::canGoToNextPage() const
{
    const WizardPage * const current = currentPageWidget();
    return current ? current->isComplete() : false;
}

bool Wizard::canGoToPreviousPage() const
{
    const int prev = d->previousPage();
    if ( prev == InvalidPage )
        return false;
    const WizardPage * const prevPage = page( prev );
    assert( prevPage );
    return !prevPage->isCommitPage();
}

void Wizard::next()
{
    WizardPage* const current = currentPageWidget();
    if ( current )
        current->onNext();
    onNext( d->currentId );
    std::vector<int>::const_iterator it = qBinaryFind( d->pageOrder.begin(), d->pageOrder.end(), d->currentId );
    assert( it != d->pageOrder.end() );

    do {
        ++it;
    }
    while ( d->hiddenPages.find( *it ) != d->hiddenPages.end() );

    if ( it == d->pageOrder.end() ) // "Finish"
    {
        d->currentId = InvalidPage;
        close();
    }
    else // "next"
    {
        setCurrentPage( *it );
    }
}

int Wizard::Private::previousPage() const
{
   if ( pageOrder.empty() )
        return InvalidPage;

    std::vector<int>::const_iterator it = qBinaryFind( pageOrder.begin(), pageOrder.end(), currentId );
    if ( it == pageOrder.begin() || it == pageOrder.end() )
        return InvalidPage;

    do {
        --it;
    } while ( it != pageOrder.begin() && hiddenPages.find( *it ) != hiddenPages.end() );
    return *it;
}

void Wizard::back()
{
    onBack( d->currentId );
    const int prev = d->previousPage();
    if ( prev == InvalidPage )
        return;
    setCurrentPage( prev );
}

const WizardPage* Wizard::page( int id ) const
{
    if ( id == InvalidPage )
        return 0;

    const std::map<int, WizardPage*>::const_iterator it = d->idToPage.find( id );
    kleo_assert( it != d->idToPage.end() );
    return (*it).second;
}

const WizardPage* Wizard::currentPageWidget() const
{
    return page( d->currentId );
}

WizardPage* Wizard::currentPageWidget()
{
    return page( d->currentId );
}

void Wizard::onNext( int currentId )
{
    Q_UNUSED( currentId )
}

void Wizard::onBack( int currentId )
{
    Q_UNUSED( currentId )
}

WizardPage* Wizard::page( int id )
{
    if ( id == InvalidPage )
        return 0;

    const std::map<int, WizardPage*>::const_iterator it = d->idToPage.find( id );
    kleo_assert( it != d->idToPage.end() );
    return (*it).second;
}

#include "moc_wizard.cpp"
<commit_msg>do not assert on page == 0<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
    crypto/gui/wizard.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra 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.

    Kleopatra 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "wizard.h"
#include "wizardpage.h"

#include <utils/kleo_assert.h>

#include <KDebug>
#include <KGuiItem>
#include <KLocale>
#include <KPushButton>
#include <KStandardGuiItem>

#include <QDialogButtonBox>
#include <QFrame>
#include <QLabel>
#include <QStackedWidget>
#include <QVBoxLayout>
#include <QWizard>

#include <map>
#include <set>

#include <cassert>

using namespace Kleo::Crypto::Gui;

class Wizard::Private {
    friend class ::Wizard;
    Wizard * const q;
public:
    explicit Private( Wizard * qq );
    ~Private();

    void updateButtonStates();
    bool isLastPage( int id ) const;
    int previousPage() const;
    void updateHeader();

private:
    std::vector<int> pageOrder;
    std::set<int> hiddenPages;
    std::map<int, WizardPage*> idToPage;
    int currentId;
    QStackedWidget* stack;
    KPushButton* nextButton;
    QPushButton* backButton;
    QPushButton* cancelButton;
    KGuiItem finishItem;
    KGuiItem nextItem;
    QFrame* titleFrame;
    QLabel* titleLabel;
    QLabel* subTitleLabel;
    QFrame* explanationFrame;
    QLabel* explanationLabel;
};

Wizard::Private::Private( Wizard * qq )
    : q( qq ), currentId( -1 ), stack( new QStackedWidget )
{
    const QWizard wiz;
    nextItem = KStandardGuiItem::forward();
    finishItem = KStandardGuiItem::ok();
    QVBoxLayout * const top = new QVBoxLayout( q );
    top->setMargin( 0 );
    titleFrame = new QFrame;
    titleFrame->setFrameShape( QFrame::StyledPanel );
    titleFrame->setAutoFillBackground( true );
    titleFrame->setBackgroundRole( QPalette::Base );
    QVBoxLayout* const titleLayout = new QVBoxLayout( titleFrame );
    titleLabel = new QLabel;
    titleLayout->addWidget( titleLabel );
    subTitleLabel = new QLabel;
    subTitleLabel->setWordWrap( true );
    titleLayout->addWidget( subTitleLabel );
    top->addWidget( titleFrame );
    titleFrame->setVisible( false );

    top->addWidget( stack );

    explanationFrame = new QFrame;
    explanationFrame->setFrameShape( QFrame::StyledPanel );
    explanationFrame->setAutoFillBackground( true );
    explanationFrame->setBackgroundRole( QPalette::Base );
    QVBoxLayout* const explanationLayout = new QVBoxLayout( explanationFrame );
    explanationLabel = new QLabel;
    explanationLabel->setWordWrap( true );
    explanationLayout->addWidget( explanationLabel );
    top->addWidget( explanationFrame );
    explanationFrame->setVisible( false );

    QWidget* buttonWidget = new QWidget;
    QHBoxLayout* buttonLayout = new QHBoxLayout( buttonWidget );
    QDialogButtonBox * const box = new QDialogButtonBox;

    cancelButton = box->addButton( QDialogButtonBox::Cancel );
    q->connect( cancelButton, SIGNAL( clicked() ), q, SLOT( reject() ) );

    backButton = new QPushButton;
    backButton->setText( wiz.buttonText( QWizard::BackButton ) );
    q->connect( backButton, SIGNAL( clicked() ), q, SLOT( back() ) );
    box->addButton( backButton, QDialogButtonBox::ActionRole );

    nextButton = new KPushButton;
    nextButton->setGuiItem( nextItem );
    q->connect( nextButton, SIGNAL( clicked() ), q, SLOT( next() ) );
    box->addButton( nextButton, QDialogButtonBox::ActionRole );
    buttonLayout->addWidget( box );

    top->addWidget( buttonWidget );

    q->connect( q, SIGNAL( rejected() ), q, SIGNAL( canceled() ) );
}

Wizard::Private::~Private() { kDebug(); }

bool Wizard::Private::isLastPage( int id ) const
{
    return !pageOrder.empty() ? pageOrder.back() == id : false;
}

void Wizard::Private::updateButtonStates()
{
    const bool isLast = isLastPage( currentId );
    const bool canGoToNext = q->canGoToNextPage();
    WizardPage* const page = q->page( currentId );
    const KGuiItem customNext = page ? page->customNextButton() : KGuiItem();
    if ( customNext.text().isEmpty() && customNext.icon().isNull() )
        nextButton->setGuiItem( isLast ? finishItem : nextItem );
    else
        nextButton->setGuiItem( customNext );
    nextButton->setEnabled( canGoToNext );
    cancelButton->setEnabled( !isLast || !canGoToNext );
    backButton->setEnabled( q->canGoToPreviousPage() );

}

void Wizard::Private::updateHeader()
{
    WizardPage * const widget = q->page( currentId );
    assert( !widget || stack->indexOf( widget ) != -1 );
    if ( widget )
        stack->setCurrentWidget( widget );
    const QString title = widget ? widget->title() : QString();
    const QString subTitle = widget ? widget->subTitle() : QString();
    const QString explanation = widget ? widget->explanation() : QString();
    titleFrame->setVisible( !title.isEmpty() || !subTitle.isEmpty() || !explanation.isEmpty() );
    titleLabel->setVisible( !title.isEmpty() );
    titleLabel->setText( title );
    subTitleLabel->setText( subTitle );
    subTitleLabel->setVisible( !subTitle.isEmpty() );
    explanationFrame->setVisible( !explanation.isEmpty() );
    explanationLabel->setVisible( !explanation.isEmpty() );
    explanationLabel->setText( explanation );
    q->resize( q->sizeHint().expandedTo( q->size() ) );
}

Wizard::Wizard( QWidget * parent, Qt::WFlags f )
  : QDialog( parent, f ), d( new Private( this ) )
{

}

Wizard::~Wizard() { kDebug(); }

void Wizard::setPage( int id, WizardPage* widget )
{
    kleo_assert( id != InvalidPage );
    kleo_assert( d->idToPage.find( id ) == d->idToPage.end() );
    d->idToPage[id] = widget;
    d->stack->addWidget( widget );
    connect( widget, SIGNAL( completeChanged() ), this, SLOT( updateButtonStates() ) );
    connect( widget, SIGNAL( titleChanged() ), this, SLOT( updateHeader() ) );
    connect( widget, SIGNAL( subTitleChanged() ), this, SLOT( updateHeader() ) );
    connect( widget, SIGNAL( explanationChanged() ), this, SLOT( updateHeader() ) );
}

void Wizard::setPageOrder( const std::vector<int>& pageOrder )
{
    d->pageOrder = pageOrder;
    d->hiddenPages.clear();
    if ( pageOrder.empty() )
        return;
    setCurrentPage( pageOrder.front() );
}

void Wizard::setCurrentPage( int id )
{
    d->currentId = id;
    if ( id == InvalidPage )
        return;
    d->updateHeader();
    d->updateButtonStates();
}

void Wizard::setPageVisible( int id, bool visible )
{
    if ( visible )
        d->hiddenPages.erase( id );
    else
        d->hiddenPages.insert( id );
    if ( currentPage() == id && !visible )
        next();
}

int Wizard::currentPage() const
{
    return d->currentId;
}

bool Wizard::canGoToNextPage() const
{
    const WizardPage * const current = currentPageWidget();
    return current ? current->isComplete() : false;
}

bool Wizard::canGoToPreviousPage() const
{
    const int prev = d->previousPage();
    if ( prev == InvalidPage )
        return false;
    const WizardPage * const prevPage = page( prev );
    assert( prevPage );
    return !prevPage->isCommitPage();
}

void Wizard::next()
{
    WizardPage* const current = currentPageWidget();
    if ( current )
        current->onNext();
    onNext( d->currentId );
    std::vector<int>::const_iterator it = qBinaryFind( d->pageOrder.begin(), d->pageOrder.end(), d->currentId );
    assert( it != d->pageOrder.end() );

    do {
        ++it;
    }
    while ( d->hiddenPages.find( *it ) != d->hiddenPages.end() );

    if ( it == d->pageOrder.end() ) // "Finish"
    {
        d->currentId = InvalidPage;
        close();
    }
    else // "next"
    {
        setCurrentPage( *it );
    }
}

int Wizard::Private::previousPage() const
{
   if ( pageOrder.empty() )
        return InvalidPage;

    std::vector<int>::const_iterator it = qBinaryFind( pageOrder.begin(), pageOrder.end(), currentId );
    if ( it == pageOrder.begin() || it == pageOrder.end() )
        return InvalidPage;

    do {
        --it;
    } while ( it != pageOrder.begin() && hiddenPages.find( *it ) != hiddenPages.end() );
    return *it;
}

void Wizard::back()
{
    onBack( d->currentId );
    const int prev = d->previousPage();
    if ( prev == InvalidPage )
        return;
    setCurrentPage( prev );
}

const WizardPage* Wizard::page( int id ) const
{
    if ( id == InvalidPage )
        return 0;

    const std::map<int, WizardPage*>::const_iterator it = d->idToPage.find( id );
    kleo_assert( it != d->idToPage.end() );
    return (*it).second;
}

const WizardPage* Wizard::currentPageWidget() const
{
    return page( d->currentId );
}

WizardPage* Wizard::currentPageWidget()
{
    return page( d->currentId );
}

void Wizard::onNext( int currentId )
{
    Q_UNUSED( currentId )
}

void Wizard::onBack( int currentId )
{
    Q_UNUSED( currentId )
}

WizardPage* Wizard::page( int id )
{
    if ( id == InvalidPage )
        return 0;

    const std::map<int, WizardPage*>::const_iterator it = d->idToPage.find( id );
    kleo_assert( it != d->idToPage.end() );
    return (*it).second;
}

#include "moc_wizard.cpp"
<|endoftext|>