<commit_before>//------------------------------------
// Configuration macro:
//
// Configure JETAN FastJet analysis.
//
// Modified by: K. Read
//
//------------------------------------

AliJetFinder*  ConfigJetAnalysis()
{
    //
    // Configuration goes here
    //
    printf("========================== \n");
    printf("ConfigJetAnalysisFastJet() \n");
    printf("========================== \n");

    Bool_t kInputIsESD = kTRUE;     //uncomment for input ESD
  //Bool_t kInputIsESD = kFALSE;    //uncomment for input AODs
    Bool_t kFollowsFilter = kTRUE;  //uncomment if follows ESD filter task
  //Bool_t kFollowsFilter = kFALSE; //uncomment if no ESD filter task

    //Alternatively, select input via anaInputData environment variable.
    if (gSystem->Getenv("anaInputData")){
      TString kInputData = gSystem->Getenv("anaInputData");
      if( kInputData == "AOD" ){
        kInputIsESD = kFALSE;
        kFollowsFilter = kFALSE;
      }
    }

    // Define the grids
    AliJetGrid *grid = new AliJetGrid(419,119,0.,2*TMath::Pi(),-0.9,0.9);
    grid->SetGridType(1);
    grid->InitParams(80.*TMath::Pi()/180,190.*TMath::Pi()/180,-0.7,0.7);
    grid->SetMatrixIndexes();
    grid->SetIndexIJ();
    AliJetGrid *grid2 = new AliJetGrid(131,95,80.*TMath::Pi()/180.,190.*TMath::Pi()/180.,-0.7,0.7);
    grid2->SetGridType(0);
    grid2->SetMatrixIndexes();
    grid2->SetIndexIJ();

    // Define reader header
    if(kInputIsESD && !kFollowsFilter) AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader();
    else            AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("Testing");
    if(kInputIsESD && !kFollowsFilter) jrh->SetReadSignalOnly(kFALSE);

    // Detector options: 0 = Charged particles only (MomentumArray)
    //                   1 = Charged particles only (UnitArray)
    //                   2 = Neutral cells only (UnitArray)
    //                   3 = Charged particles + neutral cells (UnitArray)
    jrh->SetDetector(3);
    //jrh->SetDebug(-1);
    //jrh->SetFiducialEta(-0.7,0.7);
    //jrh->SetFiducialPhi(80.*TMath::Pi()/180,190.*TMath::Pi()/180);
    jrh->SetPtCut(0.1);
    jrh->SetFiducialEta(-0.9,0.9);    //fiducial range used by AliJetFillUnitArrayTracks
    jrh->SetFiducialPhi(0,2*TMath::Pi()); //fiducial range used by AliJetFillUnitArrayTracks

    // Define reader and set its header
    if(kInputIsESD && !kFollowsFilter) AliJetESDReader *er = new AliJetESDReader();
    else            AliJetAODReader *er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    er->SetTPCGrid(grid);
    er->SetEMCalGrid(grid2);
    er->SetApplyMIPCorrection(kFALSE);

    // Define jet header
    AliFastJetHeaderV1 *jh=new AliFastJetHeaderV1();
    Double_t R=0.4;
    Double_t Rbkg=0.2;

    // AliFastJetHeaderV1 *jh=new AliFastJetHeaderV1();
    jh->SetComment("Fast jet code with default parameters");
    //jh->SetDebug(-1);
    //jh->SetBGMode(1); //Do BG Subtraction
    jh->SetBGMode(0); //No BG Subtraction.  Store AOD track refs.
    jh->SetRparam(R); // setup parameters
    jh->SetRparamBkg(Rbkg); // setup parameters
    jh->SetPtMin(0.2);
    //jh->SetGhostEtaMax(0.9);
    jh->SetGhostArea(0.01);
    jh->SetGhostEtaMax(0.7);//used to set the rap_min and rap_max, that are then used by FJ
    jh->SetPhiRange(80.*TMath::Pi()/180+R,190.*TMath::Pi()/180-R);//used in AliFastJetFinder for the range

    // Define jet finder. Set its header and reader
    jetFinder = new AliFastJetFinder();
    jetFinder->SetJetHeader(jh);
    jetFinder->SetJetReader(er);
    //jetFinder->SetPlotMode(kTRUE);

    printf("============================== \n");
    printf("END ConfigJetAnalysisFastJet() \n");
    printf("============================== \n");

    return jetFinder;
}
<commit_msg>turn on new hadronic correction<commit_after>//------------------------------------
// Configuration macro:
//
// Configure JETAN FastJet analysis.
//
// Modified by: K. Read
//
//------------------------------------

AliJetFinder*  ConfigJetAnalysis()
{
    //
    // Configuration goes here
    //
    printf("========================== \n");
    printf("ConfigJetAnalysisFastJet() \n");
    printf("========================== \n");

    Bool_t kInputIsESD = kTRUE;     //uncomment for input ESD
  //Bool_t kInputIsESD = kFALSE;    //uncomment for input AODs
    Bool_t kFollowsFilter = kTRUE;  //uncomment if follows ESD filter task
  //Bool_t kFollowsFilter = kFALSE; //uncomment if no ESD filter task

    //Alternatively, select input via anaInputData environment variable.
    if (gSystem->Getenv("anaInputData")){
      TString kInputData = gSystem->Getenv("anaInputData");
      if( kInputData == "AOD" ){
        kInputIsESD = kFALSE;
        kFollowsFilter = kFALSE;
      }
    }

    // Define the grids
    AliJetGrid *grid = new AliJetGrid(419,119,0.,2*TMath::Pi(),-0.9,0.9);
    grid->SetGridType(1);
    grid->InitParams(80.*TMath::Pi()/180,190.*TMath::Pi()/180,-0.7,0.7);
    grid->SetMatrixIndexes();
    grid->SetIndexIJ();
    AliJetGrid *grid2 = new AliJetGrid(131,95,80.*TMath::Pi()/180.,190.*TMath::Pi()/180.,-0.7,0.7);
    grid2->SetGridType(0);
    grid2->SetMatrixIndexes();
    grid2->SetIndexIJ();

    // Define reader header
    if(kInputIsESD && !kFollowsFilter) AliJetESDReaderHeader *jrh = new AliJetESDReaderHeader();
    else            AliJetAODReaderHeader *jrh = new AliJetAODReaderHeader();
    jrh->SetComment("Testing");
    if(kInputIsESD && !kFollowsFilter) jrh->SetReadSignalOnly(kFALSE);

    // Detector options: 0 = Charged particles only (MomentumArray)
    //                   1 = Charged particles only (UnitArray)
    //                   2 = Neutral cells only (UnitArray)
    //                   3 = Charged particles + neutral cells (UnitArray)
    jrh->SetDetector(3);
    //jrh->SetDebug(-1);
    //jrh->SetFiducialEta(-0.7,0.7);
    //jrh->SetFiducialPhi(80.*TMath::Pi()/180,190.*TMath::Pi()/180);
    jrh->SetPtCut(0.1);
    jrh->SetFiducialEta(-0.9,0.9);    //fiducial range used by AliJetFillUnitArrayTracks
    jrh->SetFiducialPhi(0,2*TMath::Pi()); //fiducial range used by AliJetFillUnitArrayTracks

    // Define reader and set its header
    if(kInputIsESD && !kFollowsFilter) AliJetESDReader *er = new AliJetESDReader();
    else            AliJetAODReader *er = new AliJetAODReader();
    er->SetReaderHeader(jrh);
    er->SetTPCGrid(grid);
    er->SetEMCalGrid(grid2);
    er->SetApplyMIPCorrection(kFALSE);
    //hadronic correction
    er->SetApplyFractionHadronicCorrection(kTRUE);
    er->SetFractionHadronicCorrection(1.0);

    // Define jet header
    AliFastJetHeaderV1 *jh=new AliFastJetHeaderV1();
    Double_t R=0.4;
    Double_t Rbkg=0.2;

    // AliFastJetHeaderV1 *jh=new AliFastJetHeaderV1();
    jh->SetComment("Fast jet code with default parameters");
    //jh->SetDebug(-1);
    //jh->SetBGMode(1); //Do BG Subtraction
    jh->SetBGMode(0); //No BG Subtraction.  Store AOD track refs.
    jh->SetRparam(R); // setup parameters
    jh->SetRparamBkg(Rbkg); // setup parameters
    jh->SetPtMin(0.2);
    //jh->SetGhostEtaMax(0.9);
    jh->SetGhostArea(0.01);
    jh->SetGhostEtaMax(0.7);//used to set the rap_min and rap_max, that are then used by FJ
    jh->SetPhiRange(80.*TMath::Pi()/180+R,190.*TMath::Pi()/180-R);//used in AliFastJetFinder for the range

    // Define jet finder. Set its header and reader
    jetFinder = new AliFastJetFinder();
    jetFinder->SetJetHeader(jh);
    jetFinder->SetJetReader(er);
    //jetFinder->SetPlotMode(kTRUE);

    printf("============================== \n");
    printf("END ConfigJetAnalysisFastJet() \n");
    printf("============================== \n");

    return jetFinder;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <poll.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>

namespace exodus
{

// static sig_atomic_t end = 0;

// static void sighandler(int signo)
//{
//	end = 1;
//}

bool haskey(void)
{
	struct termios oldtio, curtio;
	//	struct sigaction sa;

	/* Save stdin terminal attributes */
	tcgetattr(0, &oldtio);

	/* Make sure we exit cleanly */
	// memset(&sa, 0, sizeof(struct sigaction));
	// sa.sa_handler = sighandler;
	// sigaction(SIGINT, &sa, NULL);
	// sigaction(SIGQUIT, &sa, NULL);
	// sigaction(SIGTERM, &sa, NULL);

	/* This is needed to be able to tcsetattr() after a hangup (Ctrl-C)
	 * see tcsetattr() on POSIX
	 */
	// memset(&sa, 0, sizeof(struct sigaction));
	// sa.sa_handler = SIG_IGN;
	// sigaction(SIGTTOU, &sa, NULL);

	/* Set non-canonical no-echo for stdin */
	tcgetattr(0, &curtio);
	curtio.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(0, TCSANOW, &curtio);

	/* main loop */
	// while (!end) {

	struct pollfd pfds[1];
	int ret;
	//char c;

	/* See if there is data available */
	pfds[0].fd = 0;
	pfds[0].events = POLLIN;
	ret = poll(pfds, 1, 0);

	/* Consume data */
	bool hasdata;
	if (ret > 0)
	{
		// printf("Data available\n");
		// read(0, &c, 1);
		hasdata = true;
	}
	else
	{
		// printf("Data NOT available\n");
		hasdata = false;
	}

	//}

	/* restore terminal attributes */
	tcsetattr(0, TCSANOW, &oldtio);

	return hasdata;
}

} // namespace exodus
<commit_msg>fix hasinput to return negative if running as a service/no terminal available<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <poll.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>

namespace exodus
{

// static sig_atomic_t end = 0;

// static void sighandler(int signo)
//{
//	end = 1;
//}

bool haskey(void)
{
	struct termios oldtio, curtio;
	//	struct sigaction sa;

	/* Save stdin terminal attributes */
        /* Probably not available if running as a service */
        if (tcgetattr(0, &oldtio)<0)
                //EBADF - The filedes argument is not a valid file descriptor.
                //ENOTTY - The filedes is not associated with a terminal.
              return false;

	/* Make sure we exit cleanly */
	// memset(&sa, 0, sizeof(struct sigaction));
	// sa.sa_handler = sighandler;
	// sigaction(SIGINT, &sa, NULL);
	// sigaction(SIGQUIT, &sa, NULL);
	// sigaction(SIGTERM, &sa, NULL);

	/* This is needed to be able to tcsetattr() after a hangup (Ctrl-C)
	 * see tcsetattr() on POSIX
	 */
	// memset(&sa, 0, sizeof(struct sigaction));
	// sa.sa_handler = SIG_IGN;
	// sigaction(SIGTTOU, &sa, NULL);

	/* Set non-canonical no-echo for stdin */
	tcgetattr(0, &curtio);
	curtio.c_lflag &= ~(ICANON | ECHO);
	tcsetattr(0, TCSANOW, &curtio);

	/* main loop */
	// while (!end) {

	struct pollfd pfds[1];
	int ret;
	//char c;

	/* See if there is data available */
	pfds[0].fd = 0;
	pfds[0].events = POLLIN;
	ret = poll(pfds, 1, 0);

	/* Consume data */
	bool hasdata;
	if (ret > 0)
	{
		// printf("Data available\n");
		// read(0, &c, 1);
		hasdata = true;
	}
	else
	{
		// printf("Data NOT available\n");
		hasdata = false;
	}

	//}

	/* restore terminal attributes */
	tcsetattr(0, TCSANOW, &oldtio);

	return hasdata;
}

} // namespace exodus
<|endoftext|>


<commit_before>#include "label.hpp"
#include "widget.hpp"

using namespace std;

namespace Granite
{
namespace UI
{
Label::Label(string text, FontSize font_size)
	: text(move(text)), font_size(font_size)
{
}

void Label::set_text(std::string text)
{
	this->text = move(text);
}

float Label::render(FlatRenderer &renderer, float layer, vec2 offset, vec2 size)
{
	auto &font = UIManager::get().get_font(font_size);
	renderer.render_text(font, text.c_str(), vec3(offset, layer), size,
	                     color, alignment);

	assert(children.empty());
	return layer;
}

void Label::reconfigure()
{
	auto &font = UIManager::get().get_font(font_size);
	vec2 minimum = font.get_text_geometry(text.c_str());

	geometry.minimum = minimum + 2.0f * geometry.margin;
}
}
}<commit_msg>Apply the margin.<commit_after>#include "label.hpp"
#include "widget.hpp"

using namespace std;

namespace Granite
{
namespace UI
{
Label::Label(string text, FontSize font_size)
	: text(move(text)), font_size(font_size)
{
}

void Label::set_text(std::string text)
{
	this->text = move(text);
}

float Label::render(FlatRenderer &renderer, float layer, vec2 offset, vec2 size)
{
	auto &font = UIManager::get().get_font(font_size);
	renderer.render_text(font, text.c_str(), vec3(offset + geometry.margin, layer), size - 2.0f * geometry.margin,
	                     color, alignment);

	assert(children.empty());
	return layer;
}

void Label::reconfigure()
{
	auto &font = UIManager::get().get_font(font_size);
	vec2 minimum = font.get_text_geometry(text.c_str());

	geometry.minimum = minimum + 2.0f * geometry.margin;
}
}
}<|endoftext|>


<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include "slider.hh"
#include "painter.hh"
#include "factory.hh"
#include "window.hh"

namespace Rapicorn {

// == SliderAreaImpl ==
SliderAreaImpl::SliderAreaImpl() :
  adjustment_ (NULL), avc_id_ (0), arc_id_ (0),
  adjustment_source_ (AdjustmentSourceType::NONE),
  flip_ (false),
  sig_slider_changed (Aida::slot (*this, &SliderAreaImpl::slider_changed))
{
  adjustment (*Adjustment::create());
}

SliderAreaImpl::~SliderAreaImpl()
{
  unset_adjustment();
}

void
SliderAreaImpl::slider_changed()
{}

bool
SliderAreaImpl::move (MoveType movement)
{
  Adjustment *adj = adjustment();
  return flipped() ? adj->move_flipped (movement) : adj->move (movement);
}

const CommandList&
SliderAreaImpl::list_commands ()
{
  static CommandP commands[] = {
    MakeNamedCommand (SliderAreaImpl, "increment", _("Increment slider"), move, MOVE_STEP_FORWARD),
    MakeNamedCommand (SliderAreaImpl, "decrement", _("Decrement slider"), move, MOVE_STEP_BACKWARD),
    MakeNamedCommand (SliderAreaImpl, "page-increment", _("Large slider increment"), move, MOVE_PAGE_FORWARD),
    MakeNamedCommand (SliderAreaImpl, "page-decrement", _("Large slider decrement"), move, MOVE_PAGE_BACKWARD),
  };
  static const CommandList command_list (commands, ContainerImpl::list_commands());
  return command_list;
}

void
SliderAreaImpl::unset_adjustment()
{
  if (adjustment_ && avc_id_)
    adjustment_->sig_value_changed() -= avc_id_;
  avc_id_ = 0;
  if (adjustment_ && arc_id_)
    adjustment_->sig_range_changed() -= arc_id_;
  arc_id_ = 0;
  adjustment_ = NULL;
}

AdjustmentSourceType
SliderAreaImpl::adjustment_source () const
{
  return adjustment_source_;
}

void
SliderAreaImpl::adjustment_source (AdjustmentSourceType adj_source)
{
  if (adjustment_source_ != adj_source)
    {
      adjustment_source_ = adj_source;
      changed ("adjustment_source");
    }
}

void
SliderAreaImpl::hierarchy_changed (WidgetImpl *old_toplevel)
{
  this->TableLayoutImpl::hierarchy_changed (old_toplevel);
  if (anchored() && adjustment_source_ != AdjustmentSourceType::NONE)
    {
      Adjustment *adj = NULL;
      find_adjustments (adjustment_source_, &adj);
      if (!adj)
        {
          String evalue = Aida::enum_info<AdjustmentSourceType>().value_to_string (adjustment_source_);
          throw Exception ("SliderArea failed to get Adjustment (", evalue, ") from ancestors: ", id());
        }
      adjustment (*adj);
    }
}

bool
SliderAreaImpl::flipped () const
{
  return flip_;
}

void
SliderAreaImpl::flipped (bool flip)
{
  if (flip_ != flip)
    {
      flip_ = flip;
      changed ("flipped");
    }
}

void
SliderAreaImpl::adjustment (Adjustment &adjustment)
{
  AdjustmentP newadj = shared_ptr_cast<Adjustment> (&adjustment);
  unset_adjustment();
  adjustment_ = newadj;
  avc_id_ = adjustment_->sig_value_changed() += [this] () { sig_slider_changed.emit(); };
  arc_id_ = adjustment_->sig_range_changed() += [this] () { sig_slider_changed.emit(); };
  changed ("adjustment");
}

Adjustment*
SliderAreaImpl::adjustment () const
{
  return &*adjustment_;
}

static const WidgetFactory<SliderAreaImpl> slider_area_factory ("Rapicorn::SliderArea");

// == SliderTroughImpl ==
SliderTroughImpl::SliderTroughImpl() :
  slider_area_ (NULL), conid_slider_changed_ (0)
{}

SliderTroughImpl::~SliderTroughImpl()
{}

bool
SliderTroughImpl::flipped() const
{
  return slider_area_ ? slider_area_->flipped() : false;
}

void
SliderTroughImpl::hierarchy_changed (WidgetImpl *old_toplevel)
{
  if (slider_area_ && conid_slider_changed_)
    slider_area_->sig_slider_changed() -= conid_slider_changed_;
  conid_slider_changed_ = 0;
  slider_area_ = NULL;
  this->SingleContainerImpl::hierarchy_changed (old_toplevel);
  if (anchored())
    {
      slider_area_ = parent_interface<SliderAreaImpl*>();
      conid_slider_changed_ = slider_area_->sig_slider_changed() += Aida::slot (*this, &SliderTroughImpl::reallocate_child);
    }
}

Adjustment*
SliderTroughImpl::adjustment () const
{
  return slider_area_ ? slider_area_->adjustment() : NULL;
}

double
SliderTroughImpl::nvalue()
{
  if (!slider_area_)
    return 0;
  Adjustment &adj = *adjustment();
  return flipped() ? adj.flipped_nvalue() : adj.nvalue();
}

void
SliderTroughImpl::size_request (Requisition &requisition)
{
  if (has_visible_child())
    {
      WidgetImpl &child = get_child();
      requisition = child.requisition();
      /* we confine spreading to within the trough, so don't propagate hspread/vspread here */
    }
}

void
SliderTroughImpl::size_allocate (Allocation area, bool changed)
{
  reallocate_child();
}

void
SliderTroughImpl::reallocate_child ()
{
  Allocation area = allocation();
  if (!has_visible_child())
    return;
  WidgetImpl &child = get_child();
  Requisition rq = child.requisition();
  /* expand/scale child */
  if (area.width > rq.width && !child.hspread())
    {
      if (child.hexpand())
        {
          Adjustment *adj = adjustment();
          double cwidth = adj ? round (adj->abs_length() * area.width) : 0;
          rq.width = MAX (cwidth, rq.width);
        }
      area.x += round (nvalue() * (area.width - rq.width));
      area.width = round (rq.width);
    }
  if (area.height > rq.height && !child.vspread())
    {
      if (child.vexpand())
        {
          Adjustment *adj = adjustment();
          double cheight = adj ? round (adj->abs_length() * area.height) : 0;
          rq.height = MAX (cheight, rq.height);
        }
      area.y += round (nvalue() * (area.height - rq.height));
      area.height = round (rq.height);
    }
  child.set_child_allocation (area);
}

void
SliderTroughImpl::reset (ResetMode mode)
{}

bool
SliderTroughImpl::handle_event (const Event &event)
{
  bool handled = false;
  switch (event.type)
    {
    case BUTTON_PRESS:
    case BUTTON_2PRESS:
    case BUTTON_3PRESS:
    case BUTTON_RELEASE:
    case BUTTON_2RELEASE:
    case BUTTON_3RELEASE:
    case BUTTON_CANCELED:
      /* forward button events to allow slider warps */
      if (has_visible_child())
        {
          EventHandler *ehandler = dynamic_cast<EventHandler*> (&get_child());
          if (ehandler)
            handled = ehandler->handle_event (event);
        }
      break;
    case SCROLL_UP:
    case SCROLL_LEFT:
      exec_command ("decrement");
      break;
    case SCROLL_DOWN:
    case SCROLL_RIGHT:
      exec_command ("increment");
      break;
    default: break;
    }
  return handled;
}

static const WidgetFactory<SliderTroughImpl> slider_trough_factory ("Rapicorn::SliderTrough");

// == SliderSkidImpl ==
SliderSkidImpl::SliderSkidImpl() :
  button_ (0),
  coffset_ (0),
  vertical_skid_ (false)
{}

SliderSkidImpl::~SliderSkidImpl()
{}

bool
SliderSkidImpl::flipped() const
{
  SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();
  return trough.flipped();
}

bool
SliderSkidImpl::vertical_skid () const
{
  return vertical_skid_;
}

void
SliderSkidImpl::vertical_skid (bool vs)
{
  if (vertical_skid_ != vs)
    {
      vertical_skid_ = vs;
      changed ("vertical_skid");
    }
}

void
SliderSkidImpl::size_request (Requisition &requisition)
{
  bool chspread = false, cvspread = false;
  if (has_children())
    {
      WidgetImpl &child = get_child();
      if (child.visible())
        {
          requisition = child.requisition();
          chspread = child.hspread();
          cvspread = child.vspread();
        }
    }
  set_flag (HSPREAD_CONTAINER, chspread);
  set_flag (VSPREAD_CONTAINER, cvspread);
}

#if 0
double
SliderSkidImpl::nvalue()
{
  SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();
  Adjustment &adj = *trough.adjustment();
  return flipped() ? adj.flipped_nvalue() : adj.nvalue();
}
#endif

void
SliderSkidImpl::reset (ResetMode mode)
{
  button_ = 0;
  coffset_ = 0;
}

bool
SliderSkidImpl::handle_event (const Event &event)
{
  const Allocation slider_allocation = rect_to_viewport (allocation());
  bool handled = false, proper_release = false;
  SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();
  const Allocation trough_allocation = trough.rect_to_viewport (trough.allocation());
  Adjustment &adj = *trough.adjustment();
  switch (event.type)
    {
      const EventButton *bevent;
    case MOUSE_ENTER:
      this->hover (true);
      break;
    case MOUSE_LEAVE:
      this->hover (false);
      break;
    case BUTTON_PRESS:
    case BUTTON_2PRESS:
    case BUTTON_3PRESS:
      bevent = dynamic_cast<const EventButton*> (&event);
      if (!button_ and (bevent->button == 1 or bevent->button == 2))
        {
          button_ = bevent->button;
          get_window()->add_grab (this, true);
          handled = true;
          coffset_ = 0;
          const Point viewport_point = Point (event.x, event.y);
          double ep = vertical_skid() ? viewport_point.y : viewport_point.x;
          double cp = vertical_skid() ? ep - slider_allocation.y : ep - slider_allocation.x;
          double clength = vertical_skid() ? slider_allocation.height : slider_allocation.width;
          if (cp >= 0 && cp < clength)
            coffset_ = cp / clength;
          else
            {
              coffset_ = 0.5;
              // confine offset to not slip the skid off trough boundaries
              cp = ep - clength * coffset_;
              const Allocation &ta = trough_allocation;
              double start_slip = (vertical_skid() ? ta.y : ta.x) - cp;
              double tlength = vertical_skid() ? ta.y + ta.height : ta.x + ta.width;
              double end_slip = cp + clength - tlength;
              // adjust skid position
              cp += MAX (0, start_slip);
              cp -= MAX (0, end_slip);
              // recalculate offset
              coffset_ = (ep - cp) / clength;
            }
        }
      break;
    case MOUSE_MOVE:
      if (button_)
        {
          const Point viewport_point = Point (event.x, event.y);
          double ep = vertical_skid() ? viewport_point.y : viewport_point.x;
          const Allocation &ta = trough_allocation;
          double tp = vertical_skid() ? ta.y : ta.x;
          double pos = ep - tp;
          double tlength = vertical_skid() ? ta.height : ta.width;
          double clength = vertical_skid() ? slider_allocation.height : slider_allocation.width;
          tlength -= clength;
          pos -= coffset_ * clength;
          if (tlength > 0)
            pos /= tlength;
          pos = CLAMP (pos, 0, 1);
          if (flipped())
            adj.flipped_nvalue (pos);
          else
            adj.nvalue (pos);
        }
      break;
    case BUTTON_RELEASE:
    case BUTTON_2RELEASE:
    case BUTTON_3RELEASE:
      proper_release = true;
    case BUTTON_CANCELED:
      bevent = dynamic_cast<const EventButton*> (&event);
      if (button_ == bevent->button)
        {
          get_window()->remove_grab (this);
          button_ = 0;
          coffset_ = 0;
          handled = true;
        }
      (void) proper_release; // silence compiler
      break;
    default: break;
    }
  return handled;
}

static const WidgetFactory<SliderSkidImpl> slider_skid_factory ("Rapicorn::SliderSkid");

} // Rapicorn
<commit_msg>UI: SliderTroughImpl::reallocate_child: preserve double precision during calculation<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include "slider.hh"
#include "painter.hh"
#include "factory.hh"
#include "window.hh"

namespace Rapicorn {

// == SliderAreaImpl ==
SliderAreaImpl::SliderAreaImpl() :
  adjustment_ (NULL), avc_id_ (0), arc_id_ (0),
  adjustment_source_ (AdjustmentSourceType::NONE),
  flip_ (false),
  sig_slider_changed (Aida::slot (*this, &SliderAreaImpl::slider_changed))
{
  adjustment (*Adjustment::create());
}

SliderAreaImpl::~SliderAreaImpl()
{
  unset_adjustment();
}

void
SliderAreaImpl::slider_changed()
{}

bool
SliderAreaImpl::move (MoveType movement)
{
  Adjustment *adj = adjustment();
  return flipped() ? adj->move_flipped (movement) : adj->move (movement);
}

const CommandList&
SliderAreaImpl::list_commands ()
{
  static CommandP commands[] = {
    MakeNamedCommand (SliderAreaImpl, "increment", _("Increment slider"), move, MOVE_STEP_FORWARD),
    MakeNamedCommand (SliderAreaImpl, "decrement", _("Decrement slider"), move, MOVE_STEP_BACKWARD),
    MakeNamedCommand (SliderAreaImpl, "page-increment", _("Large slider increment"), move, MOVE_PAGE_FORWARD),
    MakeNamedCommand (SliderAreaImpl, "page-decrement", _("Large slider decrement"), move, MOVE_PAGE_BACKWARD),
  };
  static const CommandList command_list (commands, ContainerImpl::list_commands());
  return command_list;
}

void
SliderAreaImpl::unset_adjustment()
{
  if (adjustment_ && avc_id_)
    adjustment_->sig_value_changed() -= avc_id_;
  avc_id_ = 0;
  if (adjustment_ && arc_id_)
    adjustment_->sig_range_changed() -= arc_id_;
  arc_id_ = 0;
  adjustment_ = NULL;
}

AdjustmentSourceType
SliderAreaImpl::adjustment_source () const
{
  return adjustment_source_;
}

void
SliderAreaImpl::adjustment_source (AdjustmentSourceType adj_source)
{
  if (adjustment_source_ != adj_source)
    {
      adjustment_source_ = adj_source;
      changed ("adjustment_source");
    }
}

void
SliderAreaImpl::hierarchy_changed (WidgetImpl *old_toplevel)
{
  this->TableLayoutImpl::hierarchy_changed (old_toplevel);
  if (anchored() && adjustment_source_ != AdjustmentSourceType::NONE)
    {
      Adjustment *adj = NULL;
      find_adjustments (adjustment_source_, &adj);
      if (!adj)
        {
          String evalue = Aida::enum_info<AdjustmentSourceType>().value_to_string (adjustment_source_);
          throw Exception ("SliderArea failed to get Adjustment (", evalue, ") from ancestors: ", id());
        }
      adjustment (*adj);
    }
}

bool
SliderAreaImpl::flipped () const
{
  return flip_;
}

void
SliderAreaImpl::flipped (bool flip)
{
  if (flip_ != flip)
    {
      flip_ = flip;
      changed ("flipped");
    }
}

void
SliderAreaImpl::adjustment (Adjustment &adjustment)
{
  AdjustmentP newadj = shared_ptr_cast<Adjustment> (&adjustment);
  unset_adjustment();
  adjustment_ = newadj;
  avc_id_ = adjustment_->sig_value_changed() += [this] () { sig_slider_changed.emit(); };
  arc_id_ = adjustment_->sig_range_changed() += [this] () { sig_slider_changed.emit(); };
  changed ("adjustment");
}

Adjustment*
SliderAreaImpl::adjustment () const
{
  return &*adjustment_;
}

static const WidgetFactory<SliderAreaImpl> slider_area_factory ("Rapicorn::SliderArea");

// == SliderTroughImpl ==
SliderTroughImpl::SliderTroughImpl() :
  slider_area_ (NULL), conid_slider_changed_ (0)
{}

SliderTroughImpl::~SliderTroughImpl()
{}

bool
SliderTroughImpl::flipped() const
{
  return slider_area_ ? slider_area_->flipped() : false;
}

void
SliderTroughImpl::hierarchy_changed (WidgetImpl *old_toplevel)
{
  if (slider_area_ && conid_slider_changed_)
    slider_area_->sig_slider_changed() -= conid_slider_changed_;
  conid_slider_changed_ = 0;
  slider_area_ = NULL;
  this->SingleContainerImpl::hierarchy_changed (old_toplevel);
  if (anchored())
    {
      slider_area_ = parent_interface<SliderAreaImpl*>();
      conid_slider_changed_ = slider_area_->sig_slider_changed() += Aida::slot (*this, &SliderTroughImpl::reallocate_child);
    }
}

Adjustment*
SliderTroughImpl::adjustment () const
{
  return slider_area_ ? slider_area_->adjustment() : NULL;
}

double
SliderTroughImpl::nvalue()
{
  if (!slider_area_)
    return 0;
  Adjustment &adj = *adjustment();
  return flipped() ? adj.flipped_nvalue() : adj.nvalue();
}

void
SliderTroughImpl::size_request (Requisition &requisition)
{
  if (has_visible_child())
    {
      WidgetImpl &child = get_child();
      requisition = child.requisition();
      /* we confine spreading to within the trough, so don't propagate hspread/vspread here */
    }
}

void
SliderTroughImpl::size_allocate (Allocation area, bool changed)
{
  reallocate_child();
}

void
SliderTroughImpl::reallocate_child ()
{
  if (!has_visible_child())
    return;
  WidgetImpl &child = get_child();
  const Requisition rq = child.requisition();
  Allocation area = allocation();
  // expand/scale child
  if (area.width > rq.width && !child.hspread())
    {
      double req_width = rq.width;
      if (child.hexpand())
        {
          Adjustment *adj = adjustment();
          double cwidth = adj ? iround (adj->abs_length() * area.width) : 0;
          req_width = MAX (cwidth, req_width);
        }
      area.x += iround (nvalue() * (area.width - req_width));
      area.width = iround (req_width);
    }
  if (area.height > rq.height && !child.vspread())
    {
      double req_height = rq.height;
      if (child.vexpand())
        {
          Adjustment *adj = adjustment();
          double cheight = adj ? iround (adj->abs_length() * area.height) : 0;
          req_height = MAX (cheight, req_height);
        }
      area.y += iround (nvalue() * (area.height - req_height));
      area.height = iround (req_height);
    }
  child.set_child_allocation (area);
}

void
SliderTroughImpl::reset (ResetMode mode)
{}

bool
SliderTroughImpl::handle_event (const Event &event)
{
  bool handled = false;
  switch (event.type)
    {
    case BUTTON_PRESS:
    case BUTTON_2PRESS:
    case BUTTON_3PRESS:
    case BUTTON_RELEASE:
    case BUTTON_2RELEASE:
    case BUTTON_3RELEASE:
    case BUTTON_CANCELED:
      /* forward button events to allow slider warps */
      if (has_visible_child())
        {
          EventHandler *ehandler = dynamic_cast<EventHandler*> (&get_child());
          if (ehandler)
            handled = ehandler->handle_event (event);
        }
      break;
    case SCROLL_UP:
    case SCROLL_LEFT:
      exec_command ("decrement");
      break;
    case SCROLL_DOWN:
    case SCROLL_RIGHT:
      exec_command ("increment");
      break;
    default: break;
    }
  return handled;
}

static const WidgetFactory<SliderTroughImpl> slider_trough_factory ("Rapicorn::SliderTrough");

// == SliderSkidImpl ==
SliderSkidImpl::SliderSkidImpl() :
  button_ (0),
  coffset_ (0),
  vertical_skid_ (false)
{}

SliderSkidImpl::~SliderSkidImpl()
{}

bool
SliderSkidImpl::flipped() const
{
  SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();
  return trough.flipped();
}

bool
SliderSkidImpl::vertical_skid () const
{
  return vertical_skid_;
}

void
SliderSkidImpl::vertical_skid (bool vs)
{
  if (vertical_skid_ != vs)
    {
      vertical_skid_ = vs;
      changed ("vertical_skid");
    }
}

void
SliderSkidImpl::size_request (Requisition &requisition)
{
  bool chspread = false, cvspread = false;
  if (has_children())
    {
      WidgetImpl &child = get_child();
      if (child.visible())
        {
          requisition = child.requisition();
          chspread = child.hspread();
          cvspread = child.vspread();
        }
    }
  set_flag (HSPREAD_CONTAINER, chspread);
  set_flag (VSPREAD_CONTAINER, cvspread);
}

#if 0
double
SliderSkidImpl::nvalue()
{
  SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();
  Adjustment &adj = *trough.adjustment();
  return flipped() ? adj.flipped_nvalue() : adj.nvalue();
}
#endif

void
SliderSkidImpl::reset (ResetMode mode)
{
  button_ = 0;
  coffset_ = 0;
}

bool
SliderSkidImpl::handle_event (const Event &event)
{
  const Allocation slider_allocation = rect_to_viewport (allocation());
  bool handled = false, proper_release = false;
  SliderTroughImpl &trough = parent_interface<SliderTroughImpl>();
  const Allocation trough_allocation = trough.rect_to_viewport (trough.allocation());
  Adjustment &adj = *trough.adjustment();
  switch (event.type)
    {
      const EventButton *bevent;
    case MOUSE_ENTER:
      this->hover (true);
      break;
    case MOUSE_LEAVE:
      this->hover (false);
      break;
    case BUTTON_PRESS:
    case BUTTON_2PRESS:
    case BUTTON_3PRESS:
      bevent = dynamic_cast<const EventButton*> (&event);
      if (!button_ and (bevent->button == 1 or bevent->button == 2))
        {
          button_ = bevent->button;
          get_window()->add_grab (this, true);
          handled = true;
          coffset_ = 0;
          const Point viewport_point = Point (event.x, event.y);
          double ep = vertical_skid() ? viewport_point.y : viewport_point.x;
          double cp = vertical_skid() ? ep - slider_allocation.y : ep - slider_allocation.x;
          double clength = vertical_skid() ? slider_allocation.height : slider_allocation.width;
          if (cp >= 0 && cp < clength)
            coffset_ = cp / clength;
          else
            {
              coffset_ = 0.5;
              // confine offset to not slip the skid off trough boundaries
              cp = ep - clength * coffset_;
              const Allocation &ta = trough_allocation;
              double start_slip = (vertical_skid() ? ta.y : ta.x) - cp;
              double tlength = vertical_skid() ? ta.y + ta.height : ta.x + ta.width;
              double end_slip = cp + clength - tlength;
              // adjust skid position
              cp += MAX (0, start_slip);
              cp -= MAX (0, end_slip);
              // recalculate offset
              coffset_ = (ep - cp) / clength;
            }
        }
      break;
    case MOUSE_MOVE:
      if (button_)
        {
          const Point viewport_point = Point (event.x, event.y);
          double ep = vertical_skid() ? viewport_point.y : viewport_point.x;
          const Allocation &ta = trough_allocation;
          double tp = vertical_skid() ? ta.y : ta.x;
          double pos = ep - tp;
          double tlength = vertical_skid() ? ta.height : ta.width;
          double clength = vertical_skid() ? slider_allocation.height : slider_allocation.width;
          tlength -= clength;
          pos -= coffset_ * clength;
          if (tlength > 0)
            pos /= tlength;
          pos = CLAMP (pos, 0, 1);
          if (flipped())
            adj.flipped_nvalue (pos);
          else
            adj.nvalue (pos);
        }
      break;
    case BUTTON_RELEASE:
    case BUTTON_2RELEASE:
    case BUTTON_3RELEASE:
      proper_release = true;
    case BUTTON_CANCELED:
      bevent = dynamic_cast<const EventButton*> (&event);
      if (button_ == bevent->button)
        {
          get_window()->remove_grab (this);
          button_ = 0;
          coffset_ = 0;
          handled = true;
        }
      (void) proper_release; // silence compiler
      break;
    default: break;
    }
  return handled;
}

static const WidgetFactory<SliderSkidImpl> slider_skid_factory ("Rapicorn::SliderSkid");

} // Rapicorn
<|endoftext|>


<commit_before>#include <iostream>

#include <cstdint>
#include <array>

int main(int count, char *arguments[])
{
        constexpr std::array<uint64_t, 1000> series {
                7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9, 2, 2, 5, 1, 1, 9,
                6, 7, 4, 4, 2, 6, 5, 7, 4, 7, 4, 2, 3, 5, 5, 3, 4, 9, 1, 9, 4, 9, 3, 4, 9, 6,
                9, 8 ,3, 5, 2, 0, 3, 1, 2, 7, 7, 4, 5, 0, 6, 3, 2, 6, 2, 3, 9, 5, 7, 8, 3, 1,
                8, 0, 1, 6, 9, 8, 4, 8, 0, 1, 8, 6, 9, 4, 7, 8, 8, 5, 1, 8, 4, 3, 8, 5, 8, 6,
                1, 5, 6, 0, 7, 8, 9, 1, 1, 2, 9, 4, 9, 4, 9, 5, 4, 5, 9, 5, 0, 1, 7, 3, 7, 9,
                5, 8, 3, 3, 1, 9, 5, 2, 8, 5, 3, 2, 0, 8, 8, 0, 5, 5, 1, 1, 1, 2, 5, 4, 0, 6,
                9, 8, 7, 4, 7, 1, 5, 8, 5, 2, 3, 8, 6, 3, 0, 5, 0, 7, 1, 5, 6, 9, 3, 2, 9, 0,
                9, 6, 3, 2, 9, 5, 2, 2, 7, 4, 4, 3, 0, 4, 3, 5, 5, 7, 6, 6, 8, 9, 6, 6, 4, 8,
                9, 5, 0, 4, 4, 5, 2, 4, 4, 5, 2, 3, 1, 6, 1, 7, 3, 1, 8, 5, 6, 4, 0, 3, 0, 9,
                8, 7, 1, 1, 1, 2, 1, 7, 2, 2, 3, 8, 3, 1, 1, 3, 6, 2, 2, 2, 9, 8, 9, 3, 4, 2,
                3, 3, 8, 0, 3, 0, 8, 1, 3, 5, 3, 3, 6, 2, 7, 6, 6, 1, 4, 2, 8, 2, 8, 0, 6, 4,
                4, 4, 4, 8, 6, 6, 4, 5, 2, 3, 8, 7, 4, 9, 3, 0, 3, 5, 8, 9, 0, 7, 2, 9, 6, 2,
                9, 0, 4, 9, 1, 5, 6, 0, 4, 4, 0, 7, 7, 2, 3, 9, 0, 7, 1, 3, 8, 1, 0, 5, 1, 5,
                8, 5, 9, 3, 0, 7, 9, 6, 0, 8, 6, 6, 7, 0, 1, 7, 2, 4, 2, 7, 1, 2, 1, 8, 8, 3,
                9, 9, 8, 7, 9, 7, 9, 0, 8, 7, 9, 2, 2, 7, 4, 9, 2, 1, 9, 0, 1, 6, 9, 9, 7, 2,
                0, 8, 8, 8, 0, 9, 3, 7, 7, 6, 6, 5, 7, 2, 7, 3, 3, 3, 0, 0, 1, 0, 5, 3, 3, 6,
                7, 8, 8, 1, 2, 2, 0, 2, 3, 5, 4, 2, 1, 8, 0, 9, 7, 5, 1, 2, 5, 4, 5, 4, 0, 5,
                9, 4, 7, 5, 2, 2, 4, 3, 5, 2, 5, 8, 4, 9, 0, 7, 7, 1, 1, 6, 7, 0, 5, 5, 6, 0,
                1, 3, 6, 0, 4, 8, 3, 9, 5, 8, 6, 4, 4, 6, 7, 0, 6, 3, 2, 4, 4, 1, 5, 7, 2, 2,
                1, 5, 5, 3, 9, 7, 5, 3, 6, 9, 7, 8, 1, 7, 9, 7, 7, 8, 4, 6, 1, 7, 4, 0, 6, 4,
                9, 5, 5, 1, 4, 9, 2, 9, 0, 8, 6, 2, 5, 6, 9, 3, 2, 1, 9, 7, 8, 4, 6, 8, 6, 2,
                2, 4, 8, 2, 8, 3, 9, 7, 2, 2, 4, 1, 3, 7, 5, 6, 5, 7, 0, 5, 6, 0, 5, 7, 4, 9,
                0, 2, 6, 1, 4, 0, 7, 9, 7, 2, 9, 6, 8, 6, 5, 2, 4, 1, 4, 5, 3, 5, 1, 0, 0, 4,
                7, 4, 8, 2, 1, 6, 6, 3, 7, 0, 4, 8, 4, 4, 0, 3, 1, 9, 9, 8, 9, 0, 0, 0, 8, 8,
                9, 5, 2, 4, 3, 4, 5, 0, 6, 5, 8, 5, 4, 1, 2, 2, 7, 5, 8, 8, 6, 6, 6, 8, 8, 1,
                1, 6, 4, 2, 7, 1, 7, 1, 4, 7, 9, 9, 2, 4, 4, 4, 2, 9, 2, 8, 2, 3, 0, 8, 6, 3,
                4, 6, 5, 6, 7, 4, 8, 1, 3, 9, 1, 9, 1, 2, 3, 1, 6, 2, 8, 2, 4, 5, 8, 6, 1, 7,
                8, 6, 6, 4, 5, 8, 3, 5, 9, 1, 2, 4, 5, 6, 6, 5, 2, 9, 4, 7, 6, 5, 4, 5, 6, 8,
                2, 8, 4, 8, 9, 1, 2, 8, 8, 3, 1, 4, 2, 6, 0, 7, 6, 9, 0, 0, 4, 2, 2, 4, 2, 1,
                9, 0, 2, 2, 6, 7, 1, 0, 5, 5, 6, 2, 6, 3, 2, 1, 1, 1, 1, 1, 0, 9, 3, 7, 0, 5,
                4, 4, 2, 1, 7, 5, 0, 6, 9, 4, 1, 6, 5, 8, 9, 6, 0, 4, 0, 8, 0, 7, 1, 9, 8, 4,
                0, 3, 8, 5, 0, 9, 6, 2, 4, 5, 5, 4, 4, 4, 3, 6, 2, 9, 8, 1, 2, 3, 0, 9, 8, 7,
                8, 7, 9, 9, 2, 7, 2, 4, 4, 2, 8, 4, 9, 0, 9, 1, 8, 8, 8, 4, 5, 8, 0, 1, 5, 6,
                1, 6, 6, 0, 9, 7, 9, 1, 9, 1, 3, 3, 8, 7, 5, 4, 9, 9, 2, 0, 0, 5, 2, 4, 0, 6,
                3, 6, 8, 9, 9, 1, 2, 5, 6, 0, 7, 1, 7, 6, 0, 6, 0, 5, 8, 8, 6, 1, 1, 6, 4, 6,
                7, 1, 0, 9, 4, 0, 5, 0, 7, 7, 5, 4, 1, 0, 0, 2, 2, 5, 6, 9, 8, 3, 1, 5, 5, 2,
                0, 0, 0, 5, 5, 9, 3, 5, 7, 2, 9, 7, 2, 5, 7, 1, 6, 3, 6, 2, 6, 9, 5, 6, 1, 8,
                8, 2, 6, 7, 0, 4, 2, 8, 2, 5, 2, 4, 8, 3, 6, 0, 0, 8, 2, 3, 2, 5, 7, 5, 3, 0,
                4, 2, 0, 7, 5, 2, 9, 6, 3, 4, 5, 0
        };

        uint64_t maximum = 126;

        for (auto i = series.cbegin(); i != series.cend() - 13; ++i) {
                uint64_t product = 1;

                for (auto k = i; k < i + 13; ++k) {
                        product *= *k;
                }

                if (product > maximum) {
                        maximum = product;
                }
        }

        std::cout << maximum << '\n';
        return 0;
}<commit_msg>Add missing initializer braces<commit_after>#include <iostream>

#include <cstdint>
#include <array>

int main(int count, char *arguments[])
{
        constexpr std::array<uint64_t, 1000> series { {
                7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9, 2, 2, 5, 1, 1, 9,
                6, 7, 4, 4, 2, 6, 5, 7, 4, 7, 4, 2, 3, 5, 5, 3, 4, 9, 1, 9, 4, 9, 3, 4, 9, 6,
                9, 8 ,3, 5, 2, 0, 3, 1, 2, 7, 7, 4, 5, 0, 6, 3, 2, 6, 2, 3, 9, 5, 7, 8, 3, 1,
                8, 0, 1, 6, 9, 8, 4, 8, 0, 1, 8, 6, 9, 4, 7, 8, 8, 5, 1, 8, 4, 3, 8, 5, 8, 6,
                1, 5, 6, 0, 7, 8, 9, 1, 1, 2, 9, 4, 9, 4, 9, 5, 4, 5, 9, 5, 0, 1, 7, 3, 7, 9,
                5, 8, 3, 3, 1, 9, 5, 2, 8, 5, 3, 2, 0, 8, 8, 0, 5, 5, 1, 1, 1, 2, 5, 4, 0, 6,
                9, 8, 7, 4, 7, 1, 5, 8, 5, 2, 3, 8, 6, 3, 0, 5, 0, 7, 1, 5, 6, 9, 3, 2, 9, 0,
                9, 6, 3, 2, 9, 5, 2, 2, 7, 4, 4, 3, 0, 4, 3, 5, 5, 7, 6, 6, 8, 9, 6, 6, 4, 8,
                9, 5, 0, 4, 4, 5, 2, 4, 4, 5, 2, 3, 1, 6, 1, 7, 3, 1, 8, 5, 6, 4, 0, 3, 0, 9,
                8, 7, 1, 1, 1, 2, 1, 7, 2, 2, 3, 8, 3, 1, 1, 3, 6, 2, 2, 2, 9, 8, 9, 3, 4, 2,
                3, 3, 8, 0, 3, 0, 8, 1, 3, 5, 3, 3, 6, 2, 7, 6, 6, 1, 4, 2, 8, 2, 8, 0, 6, 4,
                4, 4, 4, 8, 6, 6, 4, 5, 2, 3, 8, 7, 4, 9, 3, 0, 3, 5, 8, 9, 0, 7, 2, 9, 6, 2,
                9, 0, 4, 9, 1, 5, 6, 0, 4, 4, 0, 7, 7, 2, 3, 9, 0, 7, 1, 3, 8, 1, 0, 5, 1, 5,
                8, 5, 9, 3, 0, 7, 9, 6, 0, 8, 6, 6, 7, 0, 1, 7, 2, 4, 2, 7, 1, 2, 1, 8, 8, 3,
                9, 9, 8, 7, 9, 7, 9, 0, 8, 7, 9, 2, 2, 7, 4, 9, 2, 1, 9, 0, 1, 6, 9, 9, 7, 2,
                0, 8, 8, 8, 0, 9, 3, 7, 7, 6, 6, 5, 7, 2, 7, 3, 3, 3, 0, 0, 1, 0, 5, 3, 3, 6,
                7, 8, 8, 1, 2, 2, 0, 2, 3, 5, 4, 2, 1, 8, 0, 9, 7, 5, 1, 2, 5, 4, 5, 4, 0, 5,
                9, 4, 7, 5, 2, 2, 4, 3, 5, 2, 5, 8, 4, 9, 0, 7, 7, 1, 1, 6, 7, 0, 5, 5, 6, 0,
                1, 3, 6, 0, 4, 8, 3, 9, 5, 8, 6, 4, 4, 6, 7, 0, 6, 3, 2, 4, 4, 1, 5, 7, 2, 2,
                1, 5, 5, 3, 9, 7, 5, 3, 6, 9, 7, 8, 1, 7, 9, 7, 7, 8, 4, 6, 1, 7, 4, 0, 6, 4,
                9, 5, 5, 1, 4, 9, 2, 9, 0, 8, 6, 2, 5, 6, 9, 3, 2, 1, 9, 7, 8, 4, 6, 8, 6, 2,
                2, 4, 8, 2, 8, 3, 9, 7, 2, 2, 4, 1, 3, 7, 5, 6, 5, 7, 0, 5, 6, 0, 5, 7, 4, 9,
                0, 2, 6, 1, 4, 0, 7, 9, 7, 2, 9, 6, 8, 6, 5, 2, 4, 1, 4, 5, 3, 5, 1, 0, 0, 4,
                7, 4, 8, 2, 1, 6, 6, 3, 7, 0, 4, 8, 4, 4, 0, 3, 1, 9, 9, 8, 9, 0, 0, 0, 8, 8,
                9, 5, 2, 4, 3, 4, 5, 0, 6, 5, 8, 5, 4, 1, 2, 2, 7, 5, 8, 8, 6, 6, 6, 8, 8, 1,
                1, 6, 4, 2, 7, 1, 7, 1, 4, 7, 9, 9, 2, 4, 4, 4, 2, 9, 2, 8, 2, 3, 0, 8, 6, 3,
                4, 6, 5, 6, 7, 4, 8, 1, 3, 9, 1, 9, 1, 2, 3, 1, 6, 2, 8, 2, 4, 5, 8, 6, 1, 7,
                8, 6, 6, 4, 5, 8, 3, 5, 9, 1, 2, 4, 5, 6, 6, 5, 2, 9, 4, 7, 6, 5, 4, 5, 6, 8,
                2, 8, 4, 8, 9, 1, 2, 8, 8, 3, 1, 4, 2, 6, 0, 7, 6, 9, 0, 0, 4, 2, 2, 4, 2, 1,
                9, 0, 2, 2, 6, 7, 1, 0, 5, 5, 6, 2, 6, 3, 2, 1, 1, 1, 1, 1, 0, 9, 3, 7, 0, 5,
                4, 4, 2, 1, 7, 5, 0, 6, 9, 4, 1, 6, 5, 8, 9, 6, 0, 4, 0, 8, 0, 7, 1, 9, 8, 4,
                0, 3, 8, 5, 0, 9, 6, 2, 4, 5, 5, 4, 4, 4, 3, 6, 2, 9, 8, 1, 2, 3, 0, 9, 8, 7,
                8, 7, 9, 9, 2, 7, 2, 4, 4, 2, 8, 4, 9, 0, 9, 1, 8, 8, 8, 4, 5, 8, 0, 1, 5, 6,
                1, 6, 6, 0, 9, 7, 9, 1, 9, 1, 3, 3, 8, 7, 5, 4, 9, 9, 2, 0, 0, 5, 2, 4, 0, 6,
                3, 6, 8, 9, 9, 1, 2, 5, 6, 0, 7, 1, 7, 6, 0, 6, 0, 5, 8, 8, 6, 1, 1, 6, 4, 6,
                7, 1, 0, 9, 4, 0, 5, 0, 7, 7, 5, 4, 1, 0, 0, 2, 2, 5, 6, 9, 8, 3, 1, 5, 5, 2,
                0, 0, 0, 5, 5, 9, 3, 5, 7, 2, 9, 7, 2, 5, 7, 1, 6, 3, 6, 2, 6, 9, 5, 6, 1, 8,
                8, 2, 6, 7, 0, 4, 2, 8, 2, 5, 2, 4, 8, 3, 6, 0, 0, 8, 2, 3, 2, 5, 7, 5, 3, 0,
                4, 2, 0, 7, 5, 2, 9, 6, 3, 4, 5, 0
        } };

        uint64_t maximum = 126;

        for (auto i = series.cbegin(); i != series.cend() - 13; ++i) {
                uint64_t product = 1;

                for (auto k = i; k < i + 13; ++k) {
                        product *= *k;
                }

                if (product > maximum) {
                        maximum = product;
                }
        }

        std::cout << maximum << '\n';
        return 0;
}<|endoftext|>


<commit_before>/*
* RSA operations provided by OpenSSL
* (C) 2015 Jack Lloyd
* (C) 2017 Alexander Bluhm
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/openssl.h>

#if defined(BOTAN_HAS_RSA)

#include <botan/rsa.h>
#include <botan/rng.h>
#include <botan/internal/pk_ops_impl.h>
#include <botan/internal/ct_utils.h>

#include <functional>
#include <memory>

#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <openssl/rand.h>

namespace Botan {

namespace {

std::pair<int, size_t> get_openssl_enc_pad(const std::string& eme)
   {
   if(eme == "Raw")
      return std::make_pair(RSA_NO_PADDING, 0);
   else if(eme == "EME-PKCS1-v1_5")
      return std::make_pair(RSA_PKCS1_PADDING, 11);
   else if(eme == "OAEP(SHA-1)" || eme == "EME1(SHA-1)")
      return std::make_pair(RSA_PKCS1_OAEP_PADDING, 41);
   else
      throw Lookup_Error("OpenSSL RSA does not support EME " + eme);
   }

class OpenSSL_RSA_Encryption_Operation final : public PK_Ops::Encryption
   {
   public:

      OpenSSL_RSA_Encryption_Operation(const RSA_PublicKey& rsa, int pad, size_t pad_overhead) :
         m_openssl_rsa(nullptr, ::RSA_free), m_padding(pad)
         {
         const std::vector<uint8_t> der = rsa.public_key_bits();
         const uint8_t* der_ptr = der.data();
         m_openssl_rsa.reset(::d2i_RSAPublicKey(nullptr, &der_ptr, der.size()));
         if(!m_openssl_rsa)
            throw OpenSSL_Error("d2i_RSAPublicKey");

         m_bits = 8 * (n_size() - pad_overhead) - 1;
         }

      size_t max_input_bits() const override { return m_bits; };

      secure_vector<uint8_t> encrypt(const uint8_t msg[], size_t msg_len,
                                  RandomNumberGenerator&) override
         {
         const size_t mod_sz = n_size();

         if(msg_len > mod_sz)
            throw Invalid_Argument("Input too large for RSA key");

         secure_vector<uint8_t> outbuf(mod_sz);

         secure_vector<uint8_t> inbuf;

         if(m_padding == RSA_NO_PADDING)
            {
            inbuf.resize(mod_sz);
            copy_mem(&inbuf[mod_sz - msg_len], msg, msg_len);
            }
         else
            {
            inbuf.assign(msg, msg + msg_len);
            }

         int rc = ::RSA_public_encrypt(inbuf.size(), inbuf.data(), outbuf.data(),
                                       m_openssl_rsa.get(), m_padding);
         if(rc < 0)
            throw OpenSSL_Error("RSA_public_encrypt");

         return outbuf;
         }

   private:
      size_t n_size() const { return ::RSA_size(m_openssl_rsa.get()); }
      std::unique_ptr<RSA, std::function<void (RSA*)>> m_openssl_rsa;
      size_t m_bits = 0;
      int m_padding = 0;
   };

class OpenSSL_RSA_Decryption_Operation final : public PK_Ops::Decryption
   {
   public:

      OpenSSL_RSA_Decryption_Operation(const RSA_PrivateKey& rsa, int pad) :
         m_openssl_rsa(nullptr, ::RSA_free), m_padding(pad)
         {
         const secure_vector<uint8_t> der = rsa.private_key_bits();
         const uint8_t* der_ptr = der.data();
         m_openssl_rsa.reset(d2i_RSAPrivateKey(nullptr, &der_ptr, der.size()));
         if(!m_openssl_rsa)
            throw OpenSSL_Error("d2i_RSAPrivateKey");
         }

      secure_vector<uint8_t> decrypt(uint8_t& valid_mask,
                                  const uint8_t msg[], size_t msg_len) override
         {
         secure_vector<uint8_t> buf(::RSA_size(m_openssl_rsa.get()));
         int rc = ::RSA_private_decrypt(msg_len, msg, buf.data(), m_openssl_rsa.get(), m_padding);
         if(rc < 0 || static_cast<size_t>(rc) > buf.size())
            {
            valid_mask = 0;
            buf.resize(0);
            }
         else
            {
            valid_mask = 0xFF;
            buf.resize(rc);
            }

         if(m_padding == RSA_NO_PADDING)
            {
            return CT::strip_leading_zeros(buf);
            }

         return buf;
         }

   private:
      std::unique_ptr<RSA, std::function<void (RSA*)>> m_openssl_rsa;
      int m_padding = 0;
   };

class OpenSSL_RSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA
   {
   public:

      OpenSSL_RSA_Verification_Operation(const RSA_PublicKey& rsa, const std::string& emsa) :
         PK_Ops::Verification_with_EMSA(emsa),
         m_openssl_rsa(nullptr, ::RSA_free)
         {
         const std::vector<uint8_t> der = rsa.public_key_bits();
         const uint8_t* der_ptr = der.data();
         m_openssl_rsa.reset(::d2i_RSAPublicKey(nullptr, &der_ptr, der.size()));
         if(!m_openssl_rsa)
            throw OpenSSL_Error("d2i_RSAPublicKey");
         }

      size_t max_input_bits() const override
         {
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
         return ::BN_num_bits(m_openssl_rsa->n) - 1;
#else
         return ::RSA_bits(m_openssl_rsa.get()) - 1;
#endif
         }

      bool with_recovery() const override { return true; }

      secure_vector<uint8_t> verify_mr(const uint8_t msg[], size_t msg_len) override
         {
         const size_t mod_sz = ::RSA_size(m_openssl_rsa.get());

         if(msg_len > mod_sz)
            throw Invalid_Argument("OpenSSL RSA verify input too large");

         secure_vector<uint8_t> inbuf(mod_sz);

         if(msg_len > 0)
            copy_mem(&inbuf[mod_sz - msg_len], msg, msg_len);

         secure_vector<uint8_t> outbuf(mod_sz);

         int rc = ::RSA_public_decrypt(inbuf.size(), inbuf.data(), outbuf.data(),
                                       m_openssl_rsa.get(), RSA_NO_PADDING);
         if(rc < 0)
            throw Invalid_Argument("RSA_public_decrypt");

         return CT::strip_leading_zeros(outbuf);
         }
   private:
      std::unique_ptr<RSA, std::function<void (RSA*)>> m_openssl_rsa;
   };

class OpenSSL_RSA_Signing_Operation final : public PK_Ops::Signature_with_EMSA
   {
   public:

      OpenSSL_RSA_Signing_Operation(const RSA_PrivateKey& rsa, const std::string& emsa) :
         PK_Ops::Signature_with_EMSA(emsa),
         m_openssl_rsa(nullptr, ::RSA_free)
         {
         const secure_vector<uint8_t> der = rsa.private_key_bits();
         const uint8_t* der_ptr = der.data();
         m_openssl_rsa.reset(d2i_RSAPrivateKey(nullptr, &der_ptr, der.size()));
         if(!m_openssl_rsa)
            throw OpenSSL_Error("d2i_RSAPrivateKey");
         }

      secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len,
                                   RandomNumberGenerator&) override
         {
         const size_t mod_sz = ::RSA_size(m_openssl_rsa.get());

         if(msg_len > mod_sz)
            throw Invalid_Argument("OpenSSL RSA sign input too large");

         secure_vector<uint8_t> inbuf(mod_sz);
         copy_mem(&inbuf[mod_sz - msg_len], msg, msg_len);

         secure_vector<uint8_t> outbuf(mod_sz);

         int rc = ::RSA_private_encrypt(inbuf.size(), inbuf.data(), outbuf.data(),
                                        m_openssl_rsa.get(), RSA_NO_PADDING);
         if(rc < 0)
            throw OpenSSL_Error("RSA_private_encrypt");

         return outbuf;
         }

      size_t max_input_bits() const override
         {
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
         return ::BN_num_bits(m_openssl_rsa->n) - 1;
#else
         return ::RSA_bits(m_openssl_rsa.get()) - 1;
#endif
         }

   private:
      std::unique_ptr<RSA, std::function<void (RSA*)>> m_openssl_rsa;
   };

}

std::unique_ptr<PK_Ops::Encryption>
make_openssl_rsa_enc_op(const RSA_PublicKey& key, const std::string& params)
   {
   auto pad_info = get_openssl_enc_pad(params);
   return std::unique_ptr<PK_Ops::Encryption>(
      new OpenSSL_RSA_Encryption_Operation(key, pad_info.first, pad_info.second));
   }

std::unique_ptr<PK_Ops::Decryption>
make_openssl_rsa_dec_op(const RSA_PrivateKey& key, const std::string& params)
   {
   auto pad_info = get_openssl_enc_pad(params);
   return std::unique_ptr<PK_Ops::Decryption>(new OpenSSL_RSA_Decryption_Operation(key, pad_info.first));
   }

std::unique_ptr<PK_Ops::Verification>
make_openssl_rsa_ver_op(const RSA_PublicKey& key, const std::string& params)
   {
   return std::unique_ptr<PK_Ops::Verification>(new OpenSSL_RSA_Verification_Operation(key, params));
   }

std::unique_ptr<PK_Ops::Signature>
make_openssl_rsa_sig_op(const RSA_PrivateKey& key, const std::string& params)
   {
   return std::unique_ptr<PK_Ops::Signature>(new OpenSSL_RSA_Signing_Operation(key, params));
   }

std::unique_ptr<RSA_PrivateKey>
make_openssl_rsa_private_key(RandomNumberGenerator& rng, size_t rsa_bits)
   {
   if (rsa_bits > INT_MAX)
      throw Internal_Error("rsa_bits overflow");

   secure_vector<uint8_t> seed(BOTAN_SYSTEM_RNG_POLL_REQUEST);
   rng.randomize(seed.data(), seed.size());
   RAND_seed(seed.data(), seed.size());

   std::unique_ptr<BIGNUM, std::function<void (BIGNUM*)>> bn(BN_new(), BN_free);
   if(!bn)
      throw OpenSSL_Error("BN_new");
   if(!BN_set_word(bn.get(), RSA_F4))
      throw OpenSSL_Error("BN_set_word");

   std::unique_ptr<RSA, std::function<void (RSA*)>> rsa(RSA_new(), RSA_free);
   if(!rsa)
      throw OpenSSL_Error("RSA_new");
   if(!RSA_generate_key_ex(rsa.get(), rsa_bits, bn.get(), nullptr))
      throw OpenSSL_Error("RSA_generate_key_ex");

   uint8_t* der = nullptr;
   int bytes = i2d_RSAPrivateKey(rsa.get(), &der);
   if(bytes < 0)
      throw OpenSSL_Error("i2d_RSAPrivateKey");

   const secure_vector<uint8_t> keydata(der, der + bytes);
   memset(der, 0, bytes);
   free(der);
   return std::unique_ptr<Botan::RSA_PrivateKey>
      (new RSA_PrivateKey(AlgorithmIdentifier(), keydata));
   }
}

#endif // BOTAN_HAS_RSA
<commit_msg>Refer to free in std::<commit_after>/*
* RSA operations provided by OpenSSL
* (C) 2015 Jack Lloyd
* (C) 2017 Alexander Bluhm
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/openssl.h>

#if defined(BOTAN_HAS_RSA)

#include <botan/rsa.h>
#include <botan/rng.h>
#include <botan/internal/pk_ops_impl.h>
#include <botan/internal/ct_utils.h>

#include <functional>
#include <memory>

#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/err.h>
#include <openssl/rand.h>

namespace Botan {

namespace {

std::pair<int, size_t> get_openssl_enc_pad(const std::string& eme)
   {
   if(eme == "Raw")
      return std::make_pair(RSA_NO_PADDING, 0);
   else if(eme == "EME-PKCS1-v1_5")
      return std::make_pair(RSA_PKCS1_PADDING, 11);
   else if(eme == "OAEP(SHA-1)" || eme == "EME1(SHA-1)")
      return std::make_pair(RSA_PKCS1_OAEP_PADDING, 41);
   else
      throw Lookup_Error("OpenSSL RSA does not support EME " + eme);
   }

class OpenSSL_RSA_Encryption_Operation final : public PK_Ops::Encryption
   {
   public:

      OpenSSL_RSA_Encryption_Operation(const RSA_PublicKey& rsa, int pad, size_t pad_overhead) :
         m_openssl_rsa(nullptr, ::RSA_free), m_padding(pad)
         {
         const std::vector<uint8_t> der = rsa.public_key_bits();
         const uint8_t* der_ptr = der.data();
         m_openssl_rsa.reset(::d2i_RSAPublicKey(nullptr, &der_ptr, der.size()));
         if(!m_openssl_rsa)
            throw OpenSSL_Error("d2i_RSAPublicKey");

         m_bits = 8 * (n_size() - pad_overhead) - 1;
         }

      size_t max_input_bits() const override { return m_bits; };

      secure_vector<uint8_t> encrypt(const uint8_t msg[], size_t msg_len,
                                  RandomNumberGenerator&) override
         {
         const size_t mod_sz = n_size();

         if(msg_len > mod_sz)
            throw Invalid_Argument("Input too large for RSA key");

         secure_vector<uint8_t> outbuf(mod_sz);

         secure_vector<uint8_t> inbuf;

         if(m_padding == RSA_NO_PADDING)
            {
            inbuf.resize(mod_sz);
            copy_mem(&inbuf[mod_sz - msg_len], msg, msg_len);
            }
         else
            {
            inbuf.assign(msg, msg + msg_len);
            }

         int rc = ::RSA_public_encrypt(inbuf.size(), inbuf.data(), outbuf.data(),
                                       m_openssl_rsa.get(), m_padding);
         if(rc < 0)
            throw OpenSSL_Error("RSA_public_encrypt");

         return outbuf;
         }

   private:
      size_t n_size() const { return ::RSA_size(m_openssl_rsa.get()); }
      std::unique_ptr<RSA, std::function<void (RSA*)>> m_openssl_rsa;
      size_t m_bits = 0;
      int m_padding = 0;
   };

class OpenSSL_RSA_Decryption_Operation final : public PK_Ops::Decryption
   {
   public:

      OpenSSL_RSA_Decryption_Operation(const RSA_PrivateKey& rsa, int pad) :
         m_openssl_rsa(nullptr, ::RSA_free), m_padding(pad)
         {
         const secure_vector<uint8_t> der = rsa.private_key_bits();
         const uint8_t* der_ptr = der.data();
         m_openssl_rsa.reset(d2i_RSAPrivateKey(nullptr, &der_ptr, der.size()));
         if(!m_openssl_rsa)
            throw OpenSSL_Error("d2i_RSAPrivateKey");
         }

      secure_vector<uint8_t> decrypt(uint8_t& valid_mask,
                                  const uint8_t msg[], size_t msg_len) override
         {
         secure_vector<uint8_t> buf(::RSA_size(m_openssl_rsa.get()));
         int rc = ::RSA_private_decrypt(msg_len, msg, buf.data(), m_openssl_rsa.get(), m_padding);
         if(rc < 0 || static_cast<size_t>(rc) > buf.size())
            {
            valid_mask = 0;
            buf.resize(0);
            }
         else
            {
            valid_mask = 0xFF;
            buf.resize(rc);
            }

         if(m_padding == RSA_NO_PADDING)
            {
            return CT::strip_leading_zeros(buf);
            }

         return buf;
         }

   private:
      std::unique_ptr<RSA, std::function<void (RSA*)>> m_openssl_rsa;
      int m_padding = 0;
   };

class OpenSSL_RSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA
   {
   public:

      OpenSSL_RSA_Verification_Operation(const RSA_PublicKey& rsa, const std::string& emsa) :
         PK_Ops::Verification_with_EMSA(emsa),
         m_openssl_rsa(nullptr, ::RSA_free)
         {
         const std::vector<uint8_t> der = rsa.public_key_bits();
         const uint8_t* der_ptr = der.data();
         m_openssl_rsa.reset(::d2i_RSAPublicKey(nullptr, &der_ptr, der.size()));
         if(!m_openssl_rsa)
            throw OpenSSL_Error("d2i_RSAPublicKey");
         }

      size_t max_input_bits() const override
         {
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
         return ::BN_num_bits(m_openssl_rsa->n) - 1;
#else
         return ::RSA_bits(m_openssl_rsa.get()) - 1;
#endif
         }

      bool with_recovery() const override { return true; }

      secure_vector<uint8_t> verify_mr(const uint8_t msg[], size_t msg_len) override
         {
         const size_t mod_sz = ::RSA_size(m_openssl_rsa.get());

         if(msg_len > mod_sz)
            throw Invalid_Argument("OpenSSL RSA verify input too large");

         secure_vector<uint8_t> inbuf(mod_sz);

         if(msg_len > 0)
            copy_mem(&inbuf[mod_sz - msg_len], msg, msg_len);

         secure_vector<uint8_t> outbuf(mod_sz);

         int rc = ::RSA_public_decrypt(inbuf.size(), inbuf.data(), outbuf.data(),
                                       m_openssl_rsa.get(), RSA_NO_PADDING);
         if(rc < 0)
            throw Invalid_Argument("RSA_public_decrypt");

         return CT::strip_leading_zeros(outbuf);
         }
   private:
      std::unique_ptr<RSA, std::function<void (RSA*)>> m_openssl_rsa;
   };

class OpenSSL_RSA_Signing_Operation final : public PK_Ops::Signature_with_EMSA
   {
   public:

      OpenSSL_RSA_Signing_Operation(const RSA_PrivateKey& rsa, const std::string& emsa) :
         PK_Ops::Signature_with_EMSA(emsa),
         m_openssl_rsa(nullptr, ::RSA_free)
         {
         const secure_vector<uint8_t> der = rsa.private_key_bits();
         const uint8_t* der_ptr = der.data();
         m_openssl_rsa.reset(d2i_RSAPrivateKey(nullptr, &der_ptr, der.size()));
         if(!m_openssl_rsa)
            throw OpenSSL_Error("d2i_RSAPrivateKey");
         }

      secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len,
                                   RandomNumberGenerator&) override
         {
         const size_t mod_sz = ::RSA_size(m_openssl_rsa.get());

         if(msg_len > mod_sz)
            throw Invalid_Argument("OpenSSL RSA sign input too large");

         secure_vector<uint8_t> inbuf(mod_sz);
         copy_mem(&inbuf[mod_sz - msg_len], msg, msg_len);

         secure_vector<uint8_t> outbuf(mod_sz);

         int rc = ::RSA_private_encrypt(inbuf.size(), inbuf.data(), outbuf.data(),
                                        m_openssl_rsa.get(), RSA_NO_PADDING);
         if(rc < 0)
            throw OpenSSL_Error("RSA_private_encrypt");

         return outbuf;
         }

      size_t max_input_bits() const override
         {
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
         return ::BN_num_bits(m_openssl_rsa->n) - 1;
#else
         return ::RSA_bits(m_openssl_rsa.get()) - 1;
#endif
         }

   private:
      std::unique_ptr<RSA, std::function<void (RSA*)>> m_openssl_rsa;
   };

}

std::unique_ptr<PK_Ops::Encryption>
make_openssl_rsa_enc_op(const RSA_PublicKey& key, const std::string& params)
   {
   auto pad_info = get_openssl_enc_pad(params);
   return std::unique_ptr<PK_Ops::Encryption>(
      new OpenSSL_RSA_Encryption_Operation(key, pad_info.first, pad_info.second));
   }

std::unique_ptr<PK_Ops::Decryption>
make_openssl_rsa_dec_op(const RSA_PrivateKey& key, const std::string& params)
   {
   auto pad_info = get_openssl_enc_pad(params);
   return std::unique_ptr<PK_Ops::Decryption>(new OpenSSL_RSA_Decryption_Operation(key, pad_info.first));
   }

std::unique_ptr<PK_Ops::Verification>
make_openssl_rsa_ver_op(const RSA_PublicKey& key, const std::string& params)
   {
   return std::unique_ptr<PK_Ops::Verification>(new OpenSSL_RSA_Verification_Operation(key, params));
   }

std::unique_ptr<PK_Ops::Signature>
make_openssl_rsa_sig_op(const RSA_PrivateKey& key, const std::string& params)
   {
   return std::unique_ptr<PK_Ops::Signature>(new OpenSSL_RSA_Signing_Operation(key, params));
   }

std::unique_ptr<RSA_PrivateKey>
make_openssl_rsa_private_key(RandomNumberGenerator& rng, size_t rsa_bits)
   {
   if (rsa_bits > INT_MAX)
      throw Internal_Error("rsa_bits overflow");

   secure_vector<uint8_t> seed(BOTAN_SYSTEM_RNG_POLL_REQUEST);
   rng.randomize(seed.data(), seed.size());
   RAND_seed(seed.data(), seed.size());

   std::unique_ptr<BIGNUM, std::function<void (BIGNUM*)>> bn(BN_new(), BN_free);
   if(!bn)
      throw OpenSSL_Error("BN_new");
   if(!BN_set_word(bn.get(), RSA_F4))
      throw OpenSSL_Error("BN_set_word");

   std::unique_ptr<RSA, std::function<void (RSA*)>> rsa(RSA_new(), RSA_free);
   if(!rsa)
      throw OpenSSL_Error("RSA_new");
   if(!RSA_generate_key_ex(rsa.get(), rsa_bits, bn.get(), nullptr))
      throw OpenSSL_Error("RSA_generate_key_ex");

   uint8_t* der = nullptr;
   int bytes = i2d_RSAPrivateKey(rsa.get(), &der);
   if(bytes < 0)
      throw OpenSSL_Error("i2d_RSAPrivateKey");

   const secure_vector<uint8_t> keydata(der, der + bytes);
   memset(der, 0, bytes);
   std::free(der);
   return std::unique_ptr<Botan::RSA_PrivateKey>
      (new RSA_PrivateKey(AlgorithmIdentifier(), keydata));
   }
}

#endif // BOTAN_HAS_RSA
<|endoftext|>


<commit_before>// $Id$
//***************************************************************************
//
// File:
//    ProgramOptions.C
//
// Purpose:
//    General options processing for any program.
//
// History:
//    08/08/95 - adve  - created in the dHPF compiler
//    10/10/96 - mpal, dbaker - converted to const member functions.
//    11/26/96 - adve  - fixed to handle options that consume 0+ arguments
//    07/15/01 - vadve - Copied to LLVM system and modified
//
//**************************************************************************/

//************************** System Include Files **************************/

#include <iostream.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#ifndef MAXINT
#define MAXINT	((1 << sizeof(int)-1) - 1)
#endif

//*************************** User Include Files ***************************/

#include "llvm/Support/ProgramOptions.h"
#include "llvm/Support/ProgramOption.h"
#include "llvm/Support/StringUtils.h"

//************************** Method Definitions ****************************/

ProgramOptions::ProgramOptions(int _argc,
			       const char* _argv[],
			       const char* _envp[])
  : optionRegistry(),
    argc(_argc),
    argv(_argv),
    envp(_envp),
    argsConsumed(0)
{}

const char*
ProgramOptions::StringOptionValue(const char* optString) const
{
    const StringOption* handler = (const StringOption*) OptionHandler(optString);
    return (handler == NULL) ? NULL : handler->Value();
}

bool
ProgramOptions::FlagOptionValue(const char* optString) const
{
    const FlagOption* handler = (const FlagOption*) OptionHandler(optString);
    return (handler == NULL) ? false : handler->Value();
}

double
ProgramOptions::RealOptionValue(const char* optString) const
{
    const RealValuedOption* handler =
	(const RealValuedOption*) OptionHandler(optString);
    return (handler == NULL) ? MAXFLOAT : handler->Value();
}

int
ProgramOptions::IntOptionValue(const char* optString) const
{
    const IntegerValuedOption* handler =
	(const IntegerValuedOption*) OptionHandler(optString);
    return (handler == NULL) ? MAXINT : handler->Value();
}

bool
ProgramOptions::OptionSpecified(const char* optString) const
{
    const ProgramOption* handler = OptionHandler(optString);
    return handler->OptionSpecified();
}

const char*
ProgramOptions::ProgramName() const
{
    return argv[0];
}

int
ProgramOptions::NumberOfOtherOptions() const
{
   return argc - argsConsumed;
}

const char*
ProgramOptions::OtherOption(int i) const
{
   i += argsConsumed;
   assert(i >= 0 && i < argc);
   return argv[i];
}

const char**
ProgramOptions::GetOriginalArgs() const
{
   return argv;
}

vector<char*>
ProgramOptions::GetDescription() const
{
  vector<char*> optDesc;

  if (optDesc.size() < (unsigned) argc)
    {
      for (StringMap<ProgramOption*>::const_iterator iter=optionRegistry.begin();
	   ! (iter == optionRegistry.end());
	   ++iter)
	{
	  const ProgramOption* handler = (*iter).second;
	  optDesc.push_back(strdup(handler->ArgString()));	// 1st
	  optDesc.push_back(strdup(handler->HelpMesg()));	// 2nd
	  optDesc.push_back(handler->GetTextValue());		// 3rd
	}
    }

  return optDesc;
}

void
ProgramOptions::Register(ProgramOption* option)
{
  optionRegistry[option->ArgString()] = option;
}

//----------------------------------------------------------------------
// function ProgramOptions::ParseArgs
//
// Parse command-line options until you run out of options or see
// an unrecognized option.  `getopt' is a standard package to do this,
// but incredibly, it limited to single-letter options.
//
// -- Each option can consume zero or one additional arguments of argv
// -- "--" can be used to mark the end of options
//	  so that a program argument can also start with "-".
//---------------------------------------------------------------------/

void
ProgramOptions::ParseArgs(int argc,
			  const char* argv[],
			  const char* envp[])
{
  if (argc == 0) {
    Usage();
  }
  // consume the program name
  argsConsumed = 1;

  while (argsConsumed < argc)
    {
      const char* arg = argv[argsConsumed];
      if (arg[0] == '-')
	{
	  if (strcmp(arg, "--") == 0) {	// "--" marks end of options
	    argsConsumed++;		// consume and
	    break;			// discontinue the for loop
	  }
	  ProgramOption* handler = OptionHandler(arg+1);
	  if (handler == NULL) {
	    cerr << "Unrecognized option: " << arg+1 << endl;
	    Usage();
	  }

	  if (argc - argsConsumed < handler->MinExpectedArgs()) {
	    cerr << "Option " << (char*) arg+1 << " needs "
		 << handler->MinExpectedArgs() << " arguments" << endl;
	    Usage();
	  }

	  argsConsumed++;  // consumed the option

	  const char* nextArg = (argsConsumed < argc)? argv[argsConsumed]
						     : "";
	  int numAdditionalArgsConsumed = handler->EvalOpt(nextArg);
	  if (numAdditionalArgsConsumed < 0)
	    Usage();
	  argsConsumed += numAdditionalArgsConsumed;
	}
      else
	{
	  break; // quit the while loop
	}
    }

  ParseExtraArgs();
}

void
ProgramOptions::PrintArgs(ostream& stream) const
{
  for (int i = 0; i < argc; i++) {
    stream << argv[i] << " ";
  }
  stream << endl;
}

void
ProgramOptions::PrintOptions(ostream& stream) const
{
  stream << "OPTIONS:" << endl;
  stream << "\tUse argument 0 to turn OFF a flag option: "
	 << "-<flag_opt> 0" << endl << endl;

  for (StringMap<ProgramOption*>::const_iterator iter=optionRegistry.begin();
       ! (iter == optionRegistry.end());
       ++iter)
    {
      const ProgramOption* handler = (*iter).second;

      stream << "\t-" << handler->ArgString();

      const char* const showarg = " <arg>";
      int i = 1;
      for (i=1; i <= handler->MinExpectedArgs(); i++)
	stream << showarg;

      int numCharsPrinted = 1 + strlen(handler->ArgString())
	+ strlen(showarg) * handler->MinExpectedArgs();
      for (i=1; i > numCharsPrinted / 8; i--)
	stream << "\t";

      stream << "\t" << handler->HelpMesg()
	     << endl;
    }
}

void
ProgramOptions::Usage() const
{
  PrintUsage(cerr);
  exit(1);
}

//**************************************************************************/
<commit_msg>Remove stringutils.h file<commit_after>// $Id$
//***************************************************************************
//
// File:
//    ProgramOptions.C
//
// Purpose:
//    General options processing for any program.
//
// History:
//    08/08/95 - adve  - created in the dHPF compiler
//    10/10/96 - mpal, dbaker - converted to const member functions.
//    11/26/96 - adve  - fixed to handle options that consume 0+ arguments
//    07/15/01 - vadve - Copied to LLVM system and modified
//
//**************************************************************************/

//************************** System Include Files **************************/

#include <iostream.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#ifndef MAXINT
#define MAXINT	((1 << sizeof(int)-1) - 1)
#endif

//*************************** User Include Files ***************************/

#include "llvm/Support/ProgramOptions.h"
#include "llvm/Support/ProgramOption.h"
#include "llvm/Support/StringUtils.h"

//************************** Method Definitions ****************************/

ProgramOptions::ProgramOptions(int _argc,
			       const char* _argv[],
			       const char* _envp[])
  : optionRegistry(),
    argc(_argc),
    argv(_argv),
    envp(_envp),
    argsConsumed(0)
{}

const char*
ProgramOptions::StringOptionValue(const char* optString) const
{
    const StringOption* handler = (const StringOption*) OptionHandler(optString);
    return (handler == NULL) ? NULL : handler->Value();
}

bool
ProgramOptions::FlagOptionValue(const char* optString) const
{
    const FlagOption* handler = (const FlagOption*) OptionHandler(optString);
    return (handler == NULL) ? false : handler->Value();
}

double
ProgramOptions::RealOptionValue(const char* optString) const
{
    const RealValuedOption* handler =
	(const RealValuedOption*) OptionHandler(optString);
    return (handler == NULL) ? MAXFLOAT : handler->Value();
}

int
ProgramOptions::IntOptionValue(const char* optString) const
{
    const IntegerValuedOption* handler =
	(const IntegerValuedOption*) OptionHandler(optString);
    return (handler == NULL) ? MAXINT : handler->Value();
}

bool
ProgramOptions::OptionSpecified(const char* optString) const
{
    const ProgramOption* handler = OptionHandler(optString);
    return handler->OptionSpecified();
}

const char*
ProgramOptions::ProgramName() const
{
    return argv[0];
}

int
ProgramOptions::NumberOfOtherOptions() const
{
   return argc - argsConsumed;
}

const char*
ProgramOptions::OtherOption(int i) const
{
   i += argsConsumed;
   assert(i >= 0 && i < argc);
   return argv[i];
}

const char**
ProgramOptions::GetOriginalArgs() const
{
   return argv;
}

vector<string>
ProgramOptions::GetDescription() const
{
  vector<string> optDesc;

  if (optDesc.size() < (unsigned) argc)
    {
      for (hash_map<string,ProgramOption*>::const_iterator iter=optionRegistry.begin();
	   ! (iter == optionRegistry.end());
	   ++iter)
	{
	  const ProgramOption* handler = iter->second;
	  optDesc.push_back(handler->ArgString());	// 1st
	  optDesc.push_back(handler->HelpMesg());	// 2nd
	  optDesc.push_back(handler->GetTextValue());		// 3rd
	}
    }

  return optDesc;
}

void
ProgramOptions::Register(ProgramOption* option)
{
  optionRegistry[option->ArgString()] = option;
}

//----------------------------------------------------------------------
// function ProgramOptions::ParseArgs
//
// Parse command-line options until you run out of options or see
// an unrecognized option.  `getopt' is a standard package to do this,
// but incredibly, it limited to single-letter options.
//
// -- Each option can consume zero or one additional arguments of argv
// -- "--" can be used to mark the end of options
//	  so that a program argument can also start with "-".
//---------------------------------------------------------------------/

void
ProgramOptions::ParseArgs(int argc,
			  const char* argv[],
			  const char* envp[])
{
  if (argc == 0) {
    Usage();
  }
  // consume the program name
  argsConsumed = 1;

  while (argsConsumed < argc)
    {
      const char* arg = argv[argsConsumed];
      if (arg[0] == '-')
	{
	  if (strcmp(arg, "--") == 0) {	// "--" marks end of options
	    argsConsumed++;		// consume and
	    break;			// discontinue the for loop
	  }
	  ProgramOption* handler = OptionHandler(arg+1);
	  if (handler == NULL) {
	    cerr << "Unrecognized option: " << arg+1 << endl;
	    Usage();
	  }

	  if (argc - argsConsumed < handler->MinExpectedArgs()) {
	    cerr << "Option " << (char*) arg+1 << " needs "
		 << handler->MinExpectedArgs() << " arguments" << endl;
	    Usage();
	  }

	  argsConsumed++;  // consumed the option

	  const char* nextArg = (argsConsumed < argc)? argv[argsConsumed]
						     : "";
	  int numAdditionalArgsConsumed = handler->EvalOpt(nextArg);
	  if (numAdditionalArgsConsumed < 0)
	    Usage();
	  argsConsumed += numAdditionalArgsConsumed;
	}
      else
	{
	  break; // quit the while loop
	}
    }

  ParseExtraArgs();
}

void
ProgramOptions::PrintArgs(ostream& stream) const
{
  for (int i = 0; i < argc; i++) {
    stream << argv[i] << " ";
  }
  stream << endl;
}

void
ProgramOptions::PrintOptions(ostream& stream) const
{
  stream << "OPTIONS:" << endl;
  stream << "\tUse argument 0 to turn OFF a flag option: "
	 << "-<flag_opt> 0" << endl << endl;

  for (hash_map<string,ProgramOption*>::const_iterator iter = optionRegistry.begin();
       iter != optionRegistry.end(); ++iter) {
      const ProgramOption* handler = (*iter).second;

      stream << "\t-" << handler->ArgString();

      const char* const showarg = " <arg>";
      int i = 1;
      for (i=1; i <= handler->MinExpectedArgs(); i++)
	stream << showarg;

      int numCharsPrinted = 1 + strlen(handler->ArgString())
	+ strlen(showarg) * handler->MinExpectedArgs();
      for (i=1; i > numCharsPrinted / 8; i--)
	stream << "\t";

      stream << "\t" << handler->HelpMesg()
	     << endl;
    }
}

void
ProgramOptions::Usage() const
{
  PrintUsage(cerr);
  exit(1);
}

//**************************************************************************/
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "texture.h"

namespace embree
{
  bool isPowerOf2 (unsigned int x)
  {
    while (((x % 2) == 0) && x > 1)
      x /= 2;
    return (x == 1);
  }

  static std::map<std::string,std::shared_ptr<Texture>> texture_cache;

  void Texture::clearTextureCache() {
    texture_cache.clear();
  }

  Texture::Texture ()
    : width(-1), height(-1), format(INVALID), bytesPerTexel(0), width_mask(0), height_mask(0), data(nullptr) {}

  Texture::Texture(Ref<Image> img, const std::string fileName)
    : width(unsigned(img->width)), height(unsigned(img->height)), format(RGBA8), bytesPerTexel(4), width_mask(0), height_mask(0), data(nullptr), fileName(fileName)
  {
    width_mask  = isPowerOf2(width) ? width-1 : 0;
    height_mask = isPowerOf2(height) ? height-1 : 0;

    data = alignedMalloc(4*width*height,64);
    img->convertToRGBA8((unsigned char*)data);
  }

  Texture::Texture (unsigned width, unsigned height, const Format format, const char* in)
    : width(width), height(height), format(format), bytesPerTexel(getFormatBytesPerTexel(format)), width_mask(0), height_mask(0), data(nullptr)
  {
    width_mask  = isPowerOf2(width) ? width-1 : 0;
    height_mask = isPowerOf2(height) ? height-1 : 0;

    data = alignedMalloc(bytesPerTexel*width*height,64);
    if (in) memcpy(data,in,bytesPerTexel*width*height);
    else    memset(data,0 ,bytesPerTexel*width*height);
  }

  Texture::~Texture () {
    alignedFree(data);
  }

  const char* Texture::format_to_string(const Format format)
  {
    switch (format) {
    case RGBA8  : return "RGBA8";
    case RGB8   : return "RGB8";
    case FLOAT32: return "FLOAT32";
    default     : THROW_RUNTIME_ERROR("invalid texture format");
    }
  }

  Texture::Format Texture::string_to_format(const std::string& str)
  {
    if      (str == "RGBA8") return RGBA8;
    else if (str == "RGB8")  return RGB8;
    else if (str == "FLOAT32") return FLOAT32;
    else THROW_RUNTIME_ERROR("invalid texture format string");
  }

  unsigned Texture::getFormatBytesPerTexel(const Format format)
  {
    switch (format) {
    case RGBA8  : return 4;
    case RGB8   : return 3;
    case FLOAT32: return 4;
    default     : THROW_RUNTIME_ERROR("invalid texture format");
    }
  }

  /*! read png texture from disk */
  std::shared_ptr<Texture> Texture::load(const FileName& fileName)
  {
    if (texture_cache.find(fileName.str()) != texture_cache.end())
      return texture_cache[fileName.str()];

    std::shared_ptr<Texture> tex(new Texture(loadImage(fileName),fileName));
    return texture_cache[fileName.str()] = tex;
  }
}
<commit_msg>removed memcpy from texture.cpp<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "texture.h"

namespace embree
{
  bool isPowerOf2 (unsigned int x)
  {
    while (((x % 2) == 0) && x > 1)
      x /= 2;
    return (x == 1);
  }

  static std::map<std::string,std::shared_ptr<Texture>> texture_cache;

  void Texture::clearTextureCache() {
    texture_cache.clear();
  }

  Texture::Texture ()
    : width(-1), height(-1), format(INVALID), bytesPerTexel(0), width_mask(0), height_mask(0), data(nullptr) {}

  Texture::Texture(Ref<Image> img, const std::string fileName)
    : width(unsigned(img->width)), height(unsigned(img->height)), format(RGBA8), bytesPerTexel(4), width_mask(0), height_mask(0), data(nullptr), fileName(fileName)
  {
    width_mask  = isPowerOf2(width) ? width-1 : 0;
    height_mask = isPowerOf2(height) ? height-1 : 0;

    data = alignedMalloc(4*width*height,64);
    img->convertToRGBA8((unsigned char*)data);
  }

  Texture::Texture (unsigned width, unsigned height, const Format format, const char* in)
    : width(width), height(height), format(format), bytesPerTexel(getFormatBytesPerTexel(format)), width_mask(0), height_mask(0), data(nullptr)
  {
    width_mask  = isPowerOf2(width) ? width-1 : 0;
    height_mask = isPowerOf2(height) ? height-1 : 0;

    data = alignedMalloc(bytesPerTexel*width*height,64);
    if (in) {
      for (size_t i=0; i<bytesPerTexel*width*height; i++)
	((char*)data)[i] = in[i];
    }
    else {
      memset(data,0 ,bytesPerTexel*width*height);
    }
  }

  Texture::~Texture () {
    alignedFree(data);
  }

  const char* Texture::format_to_string(const Format format)
  {
    switch (format) {
    case RGBA8  : return "RGBA8";
    case RGB8   : return "RGB8";
    case FLOAT32: return "FLOAT32";
    default     : THROW_RUNTIME_ERROR("invalid texture format");
    }
  }

  Texture::Format Texture::string_to_format(const std::string& str)
  {
    if      (str == "RGBA8") return RGBA8;
    else if (str == "RGB8")  return RGB8;
    else if (str == "FLOAT32") return FLOAT32;
    else THROW_RUNTIME_ERROR("invalid texture format string");
  }

  unsigned Texture::getFormatBytesPerTexel(const Format format)
  {
    switch (format) {
    case RGBA8  : return 4;
    case RGB8   : return 3;
    case FLOAT32: return 4;
    default     : THROW_RUNTIME_ERROR("invalid texture format");
    }
  }

  /*! read png texture from disk */
  std::shared_ptr<Texture> Texture::load(const FileName& fileName)
  {
    if (texture_cache.find(fileName.str()) != texture_cache.end())
      return texture_cache[fileName.str()];

    std::shared_ptr<Texture> tex(new Texture(loadImage(fileName),fileName));
    return texture_cache[fileName.str()] = tex;
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SwXMLTextBlocks.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: mtg $ $Date: 2001-06-06 09:54:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
*
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _SW_XMLTEXTBLOCKS_HXX
#define _SW_XMLTEXTBLOCKS_HXX

#ifndef _SWBLOCKS_HXX
#include <swblocks.hxx>
#endif

#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#ifndef _DATE_HXX //autogen
#include <tools/date.hxx>
#endif

#ifndef _PERSIST_HXX //autogen
#include <so3/persist.hxx>
#endif

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

// Note...these headers only needed for the IsUCBStorage function
#include <tools/urlobj.hxx>
#include <unotools/streamhelper.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#include <sot/stg.hxx>

#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif

#ifndef _EMBOBJ_HXX //autogen
#include <so3/embobj.hxx>
#endif

class SfxMedium;
class SwPaM;
class SwDoc;
class SvxMacroTableDtor;
class SwImpBlocks;
class SwDocShell;
class SvEmbeddedObjectRef;

#define SWXML_CONVBLOCK     0x0001
#define SWXML_NOROOTCOMMIT  0x0002

class SwXMLTextBlocks : public SwImpBlocks
{
protected:
    BOOL         bAutocorrBlock;
    BOOL         bBlock;
    SvEmbeddedObjectRef xDocShellRef;
    USHORT       nFlags;
    String       aPackageName;

    void ReadInfo();
    void WriteInfo();
    void InitBlockMode ( SvStorageRef & rStorage );
    void ResetBlockMode();

public:
    SvStorageRef        xBlkRoot;
    SvStorageRef        xRoot;
    short               nCurBlk;
    SwXMLTextBlocks( const String& );
    SwXMLTextBlocks( SvStorage& );
    void   AddName( const String&, const String&, const String&, BOOL bOnlyTxt = FALSE );
    virtual void   AddName( const String&, const String&, BOOL bOnlyTxt = FALSE );
    void GeneratePackageName ( const String& rShort, String& rPackageName );
    void   SetCurrentText( const String& rText );
    virtual ~SwXMLTextBlocks();
    //virtual BOOL   IsOld() const;
    virtual ULONG Delete( USHORT );
    virtual ULONG Rename( USHORT, const String&, const String& );
    virtual ULONG CopyBlock( SwImpBlocks& rImp, String& rShort, const String& rLong);
    virtual void  ClearDoc();
    virtual ULONG GetDoc( USHORT );
    virtual ULONG BeginPutDoc( const String&, const String& );
    virtual ULONG PutDoc();
    virtual ULONG GetText( USHORT, String& );
    virtual ULONG PutText( const String&, const String&, const String& );
    virtual ULONG MakeBlockList();

    virtual short GetFileType ( void ) const;
    virtual ULONG OpenFile( BOOL bReadOnly = TRUE );
    virtual void  CloseFile();

    ULONG SetConvertMode( BOOL );
    static BOOL IsFileUCBStorage( const String & rFileName);

    // Methods for the new Autocorrecter
    ULONG GetText( const String& rShort, String& );

    virtual BOOL IsOnlyTextBlock( const String& rShort ) const;
    virtual BOOL IsOnlyTextBlock( USHORT nIdx ) const;
    virtual void SetIsTextOnly( const String& rShort, BOOL bNewValue );
    virtual void SetIsTextOnly( USHORT nIdx, BOOL bNewValue );

    virtual ULONG GetMacroTable( USHORT, SvxMacroTableDtor& rMacroTbl,
                                 sal_Bool bFileAlreadyOpen = sal_False );
    virtual ULONG SetMacroTable( USHORT nIdx,
                                 const SvxMacroTableDtor& rMacroTable,
                                 sal_Bool bFileAlreadyOpen = sal_False );
    virtual BOOL PutMuchEntries( BOOL bOn );

public:
    SwDoc* GetDoc() const { return pDoc; }
    //void  SetDoc( SwDoc * pNewDoc);
    ULONG StartPutBlock( const String& rShort, const String& rPackageName );
    ULONG PutBlock( SwPaM& rPaM, const String& rLong );
    ULONG GetBlockText( const String& rShort, String& rText );
    ULONG PutBlockText( const String& rShort, const String& rName, const String& rText,  const String& rPackageName );
    void MakeBlockText( const String& rText );
    void AddTextNode( const ::rtl::OUString& rText );

};

#endif
<commit_msg>Bug #88180#: change interface use string insted of OUString<commit_after>/*************************************************************************
 *
 *  $RCSfile: SwXMLTextBlocks.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: jp $ $Date: 2001-10-19 13:29:54 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
*
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _SW_XMLTEXTBLOCKS_HXX
#define _SW_XMLTEXTBLOCKS_HXX

#ifndef _EMBOBJ_HXX
#include <so3/embobj.hxx>
#endif
#ifndef _SWBLOCKS_HXX
#include <swblocks.hxx>
#endif

class SfxMedium;
class SwPaM;
class SwDoc;
class SvxMacroTableDtor;
class SwImpBlocks;
class SwDocShell;

#define SWXML_CONVBLOCK     0x0001
#define SWXML_NOROOTCOMMIT  0x0002

class SwXMLTextBlocks : public SwImpBlocks
{
protected:
    BOOL         bAutocorrBlock;
    BOOL         bBlock;
    SvEmbeddedObjectRef xDocShellRef;
    USHORT       nFlags;
    String       aPackageName;

    void ReadInfo();
    void WriteInfo();
    void InitBlockMode ( SvStorageRef & rStorage );
    void ResetBlockMode();

public:
    SvStorageRef        xBlkRoot;
    SvStorageRef        xRoot;
    short               nCurBlk;
    SwXMLTextBlocks( const String& );
    SwXMLTextBlocks( SvStorage& );
    void   AddName( const String&, const String&, const String&, BOOL bOnlyTxt = FALSE );
    virtual void   AddName( const String&, const String&, BOOL bOnlyTxt = FALSE );
    void GeneratePackageName ( const String& rShort, String& rPackageName );
    void   SetCurrentText( const String& rText );
    virtual ~SwXMLTextBlocks();
    //virtual BOOL   IsOld() const;
    virtual ULONG Delete( USHORT );
    virtual ULONG Rename( USHORT, const String&, const String& );
    virtual ULONG CopyBlock( SwImpBlocks& rImp, String& rShort, const String& rLong);
    virtual void  ClearDoc();
    virtual ULONG GetDoc( USHORT );
    virtual ULONG BeginPutDoc( const String&, const String& );
    virtual ULONG PutDoc();
    virtual ULONG GetText( USHORT, String& );
    virtual ULONG PutText( const String&, const String&, const String& );
    virtual ULONG MakeBlockList();

    virtual short GetFileType ( void ) const;
    virtual ULONG OpenFile( BOOL bReadOnly = TRUE );
    virtual void  CloseFile();

    ULONG SetConvertMode( BOOL );
    static BOOL IsFileUCBStorage( const String & rFileName);

    // Methods for the new Autocorrecter
    ULONG GetText( const String& rShort, String& );

    virtual BOOL IsOnlyTextBlock( const String& rShort ) const;
    virtual BOOL IsOnlyTextBlock( USHORT nIdx ) const;
    virtual void SetIsTextOnly( const String& rShort, BOOL bNewValue );
    virtual void SetIsTextOnly( USHORT nIdx, BOOL bNewValue );

    virtual ULONG GetMacroTable( USHORT, SvxMacroTableDtor& rMacroTbl,
                                 sal_Bool bFileAlreadyOpen = sal_False );
    virtual ULONG SetMacroTable( USHORT nIdx,
                                 const SvxMacroTableDtor& rMacroTable,
                                 sal_Bool bFileAlreadyOpen = sal_False );
    virtual BOOL PutMuchEntries( BOOL bOn );

public:
    SwDoc* GetDoc() const { return pDoc; }
    //void  SetDoc( SwDoc * pNewDoc);
    ULONG StartPutBlock( const String& rShort, const String& rPackageName );
    ULONG PutBlock( SwPaM& rPaM, const String& rLong );
    ULONG GetBlockText( const String& rShort, String& rText );
    ULONG PutBlockText( const String& rShort, const String& rName, const String& rText,  const String& rPackageName );
    void MakeBlockText( const String& rText );
    void AddTextNode( const String& rText );

};

#endif
<|endoftext|>