<commit_before>#include "blockoptionsdialog.h"
#include "ui_blockoptionsdialog.h"
#include "flowchart/blocktype.h"
#include "gui/blockoptioncontrol.h"
#include <QWidget>
#include <QString>
#include <QVBoxLayout>
#include <QSharedPointer>
#include <QHash>

BlockOptionsDialog::BlockOptionsDialog(BlockType bt, QHash<QString, QString> optionValues, QWidget *parent) : QDialog(parent), ui(new Ui::BlockOptionsDialog), m_optionValues(optionValues) {
    ui->setupUi(this);
    for (QString blockOptionName : bt.options().keys()) {
        QSharedPointer<const BlockOption> blockOption = bt.options()[blockOptionName];
        BlockOptionControl *control = blockOption->makeControl(optionValues[blockOptionName]);
        ui->optionControlLayout->addWidget(control);
        m_optionControls[blockOptionName] = control;
    }
    ui->optionControlLayout->addStretch(0);
    setWindowTitle(bt.displayName() + " Options");
}

BlockOptionsDialog::~BlockOptionsDialog() {
    delete ui;
}

void BlockOptionsDialog::accept() {
    for (QString optionName : m_optionControls.keys()) {
        BlockOptionControl *optionControl = m_optionControls[optionName];
        m_optionValues[optionName] = optionControl->textValue();
    }
    QDialog::accept();
}

void BlockOptionsDialog::reject() {
    // do nothing
    QDialog::reject();
}

QHash<QString, QString> BlockOptionsDialog::optionValues() const {
    return m_optionValues;
}
<commit_msg>Disable help button in options dialog<commit_after>#include "blockoptionsdialog.h"
#include "ui_blockoptionsdialog.h"
#include "flowchart/blocktype.h"
#include "gui/blockoptioncontrol.h"
#include <QWidget>
#include <QString>
#include <QVBoxLayout>
#include <QSharedPointer>
#include <QHash>

BlockOptionsDialog::BlockOptionsDialog(BlockType bt, QHash<QString, QString> optionValues, QWidget *parent) : QDialog(parent), ui(new Ui::BlockOptionsDialog), m_optionValues(optionValues) {
    ui->setupUi(this);
    for (QString blockOptionName : bt.options().keys()) {
        QSharedPointer<const BlockOption> blockOption = bt.options()[blockOptionName];
        BlockOptionControl *control = blockOption->makeControl(optionValues[blockOptionName]);
        ui->optionControlLayout->addWidget(control);
        m_optionControls[blockOptionName] = control;
    }
    ui->optionControlLayout->addStretch(0);
    setWindowTitle(bt.displayName() + " Options");
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
}

BlockOptionsDialog::~BlockOptionsDialog() {
    delete ui;
}

void BlockOptionsDialog::accept() {
    for (QString optionName : m_optionControls.keys()) {
        BlockOptionControl *optionControl = m_optionControls[optionName];
        m_optionValues[optionName] = optionControl->textValue();
    }
    QDialog::accept();
}

void BlockOptionsDialog::reject() {
    // do nothing
    QDialog::reject();
}

QHash<QString, QString> BlockOptionsDialog::optionValues() const {
    return m_optionValues;
}
<|endoftext|>


<commit_before>// @(#)root/ged:$Id$
// Author: Guido Volpi 12/10/2007

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
//  TPieEditor                                                          //
//                                                                      //
//  Implements GUI for pie-chart attributes.                            //
//                                                                      //
//  Title': set the title of the graph                                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
//Begin_Html
/*

*/
//End_Html

#include "TGedEditor.h"
#include "TGComboBox.h"
#include "TGButtonGroup.h"
#include "TPieEditor.h"
#include "TGTextEntry.h"
#include "TGNumberEntry.h"
#include "TGToolTip.h"
#include "TGLabel.h"
#include "TPie.h"
#include "TVirtualPad.h"
#include "TGColorSelect.h"
#include "TGComboBox.h"
#include "TColor.h"
#include "TBox.h"
#include "TPaveLabel.h"

ClassImp(TPieEditor)

enum EPieWid {
   kPie = 0,
   kPIE_HOR,
   kPIE_RAD,
   kPIE_TAN,
   kPIE_FILL,
   kPIE_OUTLINE,
   kPIE_TITLE,
   kPIE_3D,
   kPIE_3DANGLE,
   kPIE_3DTHICKNESS,
   kFONT_COLOR,
   kFONT_SIZE,
   kFONT_STYLE
};

//______________________________________________________________________________
TPieEditor::TPieEditor(const TGWindow *p, Int_t width,
                         Int_t height, UInt_t options, Pixel_t back)
   : TGedFrame(p, width, height, options | kVerticalFrame, back)
{
   // Constructor of graph editor.

   fPie = 0;
   // TextEntry to change the title
   MakeTitle("Pie Chart");

   fTitle = new TGTextEntry(this, new TGTextBuffer(50), kPIE_TITLE);
   fTitle->Resize(135, fTitle->GetDefaultHeight());
   fTitle->SetToolTipText("Enter the pie title string");
   // better take kLHintsLeft and Right - Right is not working at the moment
   AddFrame(fTitle, new TGLayoutHints(kLHintsLeft, 3, 1, 2, 5));

   // Radio Buttons to change the draw options of the graph
   TGCompositeFrame *f2 = new TGCompositeFrame(this, 80, 20, kVerticalFrame);
   fgr = new TGButtonGroup(f2,3,1,3,5,"Label direction");
   fgr->SetRadioButtonExclusive(kTRUE);
   fLblDirH = new TGRadioButton(fgr,"Horizontal",kPIE_HOR);   // no draw option
   fLblDirH->SetToolTipText("Draw horizontal labels");
   fLblDirR = new TGRadioButton(fgr,"Radial",kPIE_RAD);  // option C
   fLblDirR->SetToolTipText("Draw labels radially");
   fLblDirT = new TGRadioButton(fgr,"Tangential",kPIE_TAN); // option L
   fLblDirT->SetToolTipText("Draw labels tangential to the piechart");

   fgr->SetLayoutHints(fShape1lh=new TGLayoutHints(kLHintsLeft, 0,3,0,0), fLblDirH);
   fgr->Show();
   fgr->ChangeOptions(kFitWidth|kChildFrame|kVerticalFrame);
   f2->AddFrame(fgr, new TGLayoutHints(kLHintsLeft, 4, 0, 0, 0));

   // CheckBox to activate/deactivate the drawing of the Marker
   fOutlineOnOff = new TGCheckButton(f2,"Outline",kPIE_OUTLINE);
   fOutlineOnOff->SetToolTipText("Draw a line to mark the pie");
   f2->AddFrame(fOutlineOnOff, new TGLayoutHints(kLHintsTop, 5, 1, 0, 3));
   AddFrame(f2, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0));

   // Exclusion zone parameters
   MakeTitle("3D options");
   TGCompositeFrame *f3 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame);
   AddFrame(f3, new TGLayoutHints(kLHintsTop, 1, 1, 5, 0));

   fIs3D = new TGCheckButton(f3,"3D",kPIE_3D);
   fIs3D->SetToolTipText("Draw a 3D charts");
   f3->AddFrame(fIs3D, new TGLayoutHints(kLHintsTop, 5, 1, 0, 0));

   f3DAngle = new TGNumberEntry(f3, 0, 2, kPIE_3DANGLE,  TGNumberEntry::kNESInteger, TGNumberEntry::kNEANonNegative,TGNumberFormat::kNELLimitMinMax, 0, 90);
   //f3DAngle->SetToolTipText("3D angle: 0-90")
   f3DAngle->Resize(50, 20);
   f3->AddFrame(f3DAngle, new TGLayoutHints(kLHintsLeft, 7, 1, 1, 1));
   f3DAngle->Associate(f3);

   f3DHeight = new TGNumberEntry(f3, 0, 3, kPIE_3DTHICKNESS,  TGNumberEntry::kNESReal, TGNumberEntry::kNEANonNegative);
   //f3DHeight->SetToolTipText("3D thick")
   f3DHeight->Resize(50, 20);
   f3->AddFrame(f3DHeight, new TGLayoutHints(kLHintsLeft, 7, 1, 1, 1));
   f3DHeight->Associate(f3);

   MakeTitle("Text");
   TGCompositeFrame *f4 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame);
   fColorSelect = new TGColorSelect(f4, 0, kFONT_COLOR);
   f4->AddFrame(fColorSelect, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1));
   fColorSelect->Associate(this);
   fSizeCombo = BuildFontSizeComboBox(f4, kFONT_SIZE);
   f4->AddFrame(fSizeCombo, new TGLayoutHints(kLHintsLeft, 3, 1, 1, 1));
   fSizeCombo->Resize(91, 20);
   fSizeCombo->Associate(this);
   AddFrame(f4, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0));
   fTypeCombo = new TGFontTypeComboBox(this, kFONT_STYLE);
   fTypeCombo->Resize(137, 20);
   AddFrame(fTypeCombo, new TGLayoutHints(kLHintsLeft, 3, 1, 1, 1));
}

//______________________________________________________________________________
TPieEditor::~TPieEditor()
{
   // Destructor of pie editor.
}

//_____________________________________________________________________________
void TPieEditor::ConnectSignals2Slots()
{
   // Connect signals to slots.

   fTitle->Connect("TextChanged(const char *)","TPieEditor",this,"DoTitle(const char *)");
   fgr->Connect("Clicked(Int_t)","TPieEditor",this,"DoShape()");
   fOutlineOnOff->Connect("Toggled(Bool_t)","TPieEditor",this,"DoMarkerOnOff(Bool_t)");
   f3DAngle->Connect("ValueSet(Long_t)", "TPieEditor", this, "DoChange3DAngle()");
   f3DHeight->Connect("ValueSet(Long_t)", "TPieEditor", this, "DoChange3DAngle()");
   fIs3D->Connect("Clicked()","TPieEditor",this,"DoGraphLineWidth()");

   // text attributes connection
   fTypeCombo->Connect("Selected(Int_t)","TPieEditor",this,"DoTextChange()");
   fSizeCombo->Connect("Selected(Int_t)","TPieEditor",this,"DoTextChange()");
   fColorSelect->Connect("ColorSelected(Pixel_t)","TPieEditor",this,"DoTextChange()");

   fInit = kFALSE;  // connect the slots to the signals only once
}

//______________________________________________________________________________
void TPieEditor::ActivateBaseClassEditors(TClass* cl)
{
   // Exclude TAttTextEditor from this interface.

   TGedEditor *gedEditor = GetGedEditor();
   gedEditor->ExcludeClassEditor(TAttText::Class());
   TGedFrame::ActivateBaseClassEditors(cl);
}

//______________________________________________________________________________
void TPieEditor::SetModel(TObject* obj)
{
   // Pick up the used values of graph attributes.

   fPie = (TPie *)obj;
   fAvoidSignal = kTRUE;

   // set the Title TextEntry
   const char *text = fPie->GetTitle();
   fTitle->SetText(text);

   TString soption = GetDrawOption();

   bool optionSame(kFALSE);

   // For the label orientation there are 3 possibilities:
   //   0: horizontal
   //   1: radial
   //   2: tangent
   Int_t lblor(0);

   // Parse the options
   Int_t idx;
   // Paint the TPie in an existing canvas
   if ( (idx=soption.Index("same"))>=0 ) {
      optionSame = kTRUE;
      soption.Remove(idx,4);
   }

   if ( (idx=soption.Index("nol"))>=0 ) {
      fOutlineOnOff->SetState(kButtonUp,kFALSE);
      soption.Remove(idx,3);
   }
   else {
      fOutlineOnOff->SetState(kButtonDown,kFALSE);
   }

   // check if is active the pseudo-3d
   if ( (idx=soption.Index("3d"))>=0 ) {
      fIs3D->SetState(kButtonDown, kFALSE);
      f3DAngle->SetNumber(fPie->GetAngle3D());
      f3DHeight->SetNumber(fPie->GetHeight());
      soption.Remove(idx,2);
   } else {
      fIs3D->SetState(kButtonUp, kFALSE);
   }

   // seek if have to draw the labels around the pie chart
   if ( (idx=soption.Index("t"))>=0 ) {
      lblor = 2;
      soption.Remove(idx,1);
   }

   // Seek if have to paint the labels along the radii
   if ( (idx=soption.Index("r"))>=0 ) {
      lblor = 1;
      soption.Remove(idx,1);
   }

   switch(lblor) {
   case 0:
      fLblDirH->SetState(kButtonDown,kTRUE);
      break;
   case 1:
      fLblDirR->SetState(kButtonDown,kTRUE);
      break;
   case 2:
      fLblDirT->SetState(kButtonDown,kTRUE);
      break;
   }

   // set text attributes
   fTypeCombo->Select(fPie->GetTextFont() / 10);

   Color_t c = fPie->GetTextColor();
   Pixel_t p = TColor::Number2Pixel(c);
   fColorSelect->SetColor(p, kFALSE);

   Float_t s = fPie->GetTextSize();
   Float_t dy;

   if (obj->InheritsFrom(TPaveLabel::Class())) {
      TBox *pl = (TBox*)obj;
      dy = s * (pl->GetY2() - pl->GetY1());
   }
   else
      dy = s * (fGedEditor->GetPad()->GetY2() - fGedEditor->GetPad()->GetY1());

   Int_t size = fGedEditor->GetPad()->YtoPixel(0.0) - fGedEditor->GetPad()->YtoPixel(dy);
   if (size > 50) size = 50;
   if (size < 0)  size = 0;
   fSizeCombo->Select(size, kFALSE);

   if (fInit) ConnectSignals2Slots();
   fAvoidSignal = kFALSE;
}

//______________________________________________________________________________
void TPieEditor::DoTitle(const char *text)
{
   // Slot for setting the graph title.

   if (fAvoidSignal) return;
   fPie->SetTitle(text);
   Update();
}

//______________________________________________________________________________
void TPieEditor::DoShape()
{
   // Slot connected to the draw options.

   if (fAvoidSignal) return;

   TString opt = GetDrawOption();

   if (fLblDirH->GetState()==kButtonDown) {
      if (opt.Contains("t")) opt.Remove(opt.First("t"),1);
      if (opt.Contains("r")) opt.Remove(opt.First("r"),1);
   }
   else if (fLblDirR->GetState()==kButtonDown) {
      if (opt.Contains("t")) opt.Remove(opt.First("t"),1);
      if (!opt.Contains("r")) opt += "r";
   }
   else if (fLblDirT->GetState()==kButtonDown) {
      if (!opt.Contains("t")) opt += "t";
      if (opt.Contains("r")) opt.Remove(opt.First("r"),1);
   }

   SetDrawOption(opt);
   if (gPad) gPad->GetVirtCanvas()->SetCursor(kPointer);
   gVirtualX->SetCursor(GetId(), gVirtualX->CreateCursor(kPointer));
}

//______________________________________________________________________________
void TPieEditor::DoMarkerOnOff(Bool_t)
{
   // Slot for setting markers as visible/invisible.

   if (fAvoidSignal) return;
   TString t = GetDrawOption();

   if (t.Contains("nol") && fOutlineOnOff->GetState() == kButtonDown) {
      t.Remove(t.First("nol"),3);
   }
   else if (!t.Contains("nol") && fOutlineOnOff->GetState() == kButtonUp) {
      t += "nol";
   }

   SetDrawOption(t);
}

//______________________________________________________________________________
void TPieEditor::DoChange3DAngle()
{
   // Slot for setting the 3D angle
   if (fAvoidSignal) return;

   fPie->SetAngle3D(static_cast<Int_t>(f3DAngle->GetNumber()));
   fPie->SetHeight(f3DHeight->GetNumber());

   Update();

}

//______________________________________________________________________________
void TPieEditor::DoGraphLineWidth()
{
   // Slot connected to the graph line width.

   if (fAvoidSignal) return;

   TString opt = GetDrawOption();
   if (!opt.Contains("3d") && fIs3D->IsDown())
      opt += "3d";
   else if (opt.Contains("3d") && !fIs3D->IsDown())
      opt.Remove(opt.First("3d"),2);

   SetDrawOption(opt);

   Update();
}

//______________________________________________________________________________
void TPieEditor::DoTextChange()
{
   // Change text.

   if (fAvoidSignal) return;

   // font color
   fPie->SetTextColor(TColor::GetColor(fColorSelect->GetColor()));

   // font type
   Int_t fontPrec = fPie->GetTextFont()%10;
   Int_t fontType = fTypeCombo->GetSelected();
   fPie->SetTextFont(fontType*10+fontPrec);

   // font size
   TVirtualPad* pad = fGedEditor->GetPad();

   Float_t val = TString(fSizeCombo->GetSelectedEntry()->GetTitle()).Atoi();

   Float_t dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY((Int_t)val);
   Float_t textSize;

   if (fGedEditor->GetModel()->InheritsFrom(TPaveLabel::Class())) {
      TBox *pl = (TBox*)fGedEditor->GetModel();
      textSize = dy/(pl->GetY2() - pl->GetY1());
   }
   else
      textSize = dy/(pad->GetY2() - pad->GetY1());

   fPie->SetTextSize(textSize);

   Update();

}

//______________________________________________________________________________
TGComboBox* TPieEditor::BuildFontSizeComboBox(TGFrame* parent, Int_t id)
{
   // Create text size combo box.

   char a[100];
   TGComboBox *c = new TGComboBox(parent, id);

   c->AddEntry("Default", 0);
   for (int i = 1; i <= 50; i++) {
      snprintf(a, 99, "%d", i);
      c->AddEntry(a, i);
   }

   return c;
}
<commit_msg>Fix coverity report #33681 (dereference null return)<commit_after>// @(#)root/ged:$Id$
// Author: Guido Volpi 12/10/2007

/*************************************************************************
 * Copyright (C) 1995-2004, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
//  TPieEditor                                                          //
//                                                                      //
//  Implements GUI for pie-chart attributes.                            //
//                                                                      //
//  Title': set the title of the graph                                  //
//                                                                      //
//////////////////////////////////////////////////////////////////////////
//Begin_Html
/*

*/
//End_Html

#include "TGedEditor.h"
#include "TGComboBox.h"
#include "TGButtonGroup.h"
#include "TPieEditor.h"
#include "TGTextEntry.h"
#include "TGNumberEntry.h"
#include "TGToolTip.h"
#include "TGLabel.h"
#include "TPie.h"
#include "TVirtualPad.h"
#include "TGColorSelect.h"
#include "TGComboBox.h"
#include "TColor.h"
#include "TBox.h"
#include "TPaveLabel.h"

ClassImp(TPieEditor)

enum EPieWid {
   kPie = 0,
   kPIE_HOR,
   kPIE_RAD,
   kPIE_TAN,
   kPIE_FILL,
   kPIE_OUTLINE,
   kPIE_TITLE,
   kPIE_3D,
   kPIE_3DANGLE,
   kPIE_3DTHICKNESS,
   kFONT_COLOR,
   kFONT_SIZE,
   kFONT_STYLE
};

//______________________________________________________________________________
TPieEditor::TPieEditor(const TGWindow *p, Int_t width,
                         Int_t height, UInt_t options, Pixel_t back)
   : TGedFrame(p, width, height, options | kVerticalFrame, back)
{
   // Constructor of graph editor.

   fPie = 0;
   // TextEntry to change the title
   MakeTitle("Pie Chart");

   fTitle = new TGTextEntry(this, new TGTextBuffer(50), kPIE_TITLE);
   fTitle->Resize(135, fTitle->GetDefaultHeight());
   fTitle->SetToolTipText("Enter the pie title string");
   // better take kLHintsLeft and Right - Right is not working at the moment
   AddFrame(fTitle, new TGLayoutHints(kLHintsLeft, 3, 1, 2, 5));

   // Radio Buttons to change the draw options of the graph
   TGCompositeFrame *f2 = new TGCompositeFrame(this, 80, 20, kVerticalFrame);
   fgr = new TGButtonGroup(f2,3,1,3,5,"Label direction");
   fgr->SetRadioButtonExclusive(kTRUE);
   fLblDirH = new TGRadioButton(fgr,"Horizontal",kPIE_HOR);   // no draw option
   fLblDirH->SetToolTipText("Draw horizontal labels");
   fLblDirR = new TGRadioButton(fgr,"Radial",kPIE_RAD);  // option C
   fLblDirR->SetToolTipText("Draw labels radially");
   fLblDirT = new TGRadioButton(fgr,"Tangential",kPIE_TAN); // option L
   fLblDirT->SetToolTipText("Draw labels tangential to the piechart");

   fgr->SetLayoutHints(fShape1lh=new TGLayoutHints(kLHintsLeft, 0,3,0,0), fLblDirH);
   fgr->Show();
   fgr->ChangeOptions(kFitWidth|kChildFrame|kVerticalFrame);
   f2->AddFrame(fgr, new TGLayoutHints(kLHintsLeft, 4, 0, 0, 0));

   // CheckBox to activate/deactivate the drawing of the Marker
   fOutlineOnOff = new TGCheckButton(f2,"Outline",kPIE_OUTLINE);
   fOutlineOnOff->SetToolTipText("Draw a line to mark the pie");
   f2->AddFrame(fOutlineOnOff, new TGLayoutHints(kLHintsTop, 5, 1, 0, 3));
   AddFrame(f2, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0));

   // Exclusion zone parameters
   MakeTitle("3D options");
   TGCompositeFrame *f3 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame);
   AddFrame(f3, new TGLayoutHints(kLHintsTop, 1, 1, 5, 0));

   fIs3D = new TGCheckButton(f3,"3D",kPIE_3D);
   fIs3D->SetToolTipText("Draw a 3D charts");
   f3->AddFrame(fIs3D, new TGLayoutHints(kLHintsTop, 5, 1, 0, 0));

   f3DAngle = new TGNumberEntry(f3, 0, 2, kPIE_3DANGLE,  TGNumberEntry::kNESInteger, TGNumberEntry::kNEANonNegative,TGNumberFormat::kNELLimitMinMax, 0, 90);
   //f3DAngle->SetToolTipText("3D angle: 0-90")
   f3DAngle->Resize(50, 20);
   f3->AddFrame(f3DAngle, new TGLayoutHints(kLHintsLeft, 7, 1, 1, 1));
   f3DAngle->Associate(f3);

   f3DHeight = new TGNumberEntry(f3, 0, 3, kPIE_3DTHICKNESS,  TGNumberEntry::kNESReal, TGNumberEntry::kNEANonNegative);
   //f3DHeight->SetToolTipText("3D thick")
   f3DHeight->Resize(50, 20);
   f3->AddFrame(f3DHeight, new TGLayoutHints(kLHintsLeft, 7, 1, 1, 1));
   f3DHeight->Associate(f3);

   MakeTitle("Text");
   TGCompositeFrame *f4 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame);
   fColorSelect = new TGColorSelect(f4, 0, kFONT_COLOR);
   f4->AddFrame(fColorSelect, new TGLayoutHints(kLHintsLeft, 1, 1, 1, 1));
   fColorSelect->Associate(this);
   fSizeCombo = BuildFontSizeComboBox(f4, kFONT_SIZE);
   f4->AddFrame(fSizeCombo, new TGLayoutHints(kLHintsLeft, 3, 1, 1, 1));
   fSizeCombo->Resize(91, 20);
   fSizeCombo->Associate(this);
   AddFrame(f4, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0));
   fTypeCombo = new TGFontTypeComboBox(this, kFONT_STYLE);
   fTypeCombo->Resize(137, 20);
   AddFrame(fTypeCombo, new TGLayoutHints(kLHintsLeft, 3, 1, 1, 1));
}

//______________________________________________________________________________
TPieEditor::~TPieEditor()
{
   // Destructor of pie editor.
}

//_____________________________________________________________________________
void TPieEditor::ConnectSignals2Slots()
{
   // Connect signals to slots.

   fTitle->Connect("TextChanged(const char *)","TPieEditor",this,"DoTitle(const char *)");
   fgr->Connect("Clicked(Int_t)","TPieEditor",this,"DoShape()");
   fOutlineOnOff->Connect("Toggled(Bool_t)","TPieEditor",this,"DoMarkerOnOff(Bool_t)");
   f3DAngle->Connect("ValueSet(Long_t)", "TPieEditor", this, "DoChange3DAngle()");
   f3DHeight->Connect("ValueSet(Long_t)", "TPieEditor", this, "DoChange3DAngle()");
   fIs3D->Connect("Clicked()","TPieEditor",this,"DoGraphLineWidth()");

   // text attributes connection
   fTypeCombo->Connect("Selected(Int_t)","TPieEditor",this,"DoTextChange()");
   fSizeCombo->Connect("Selected(Int_t)","TPieEditor",this,"DoTextChange()");
   fColorSelect->Connect("ColorSelected(Pixel_t)","TPieEditor",this,"DoTextChange()");

   fInit = kFALSE;  // connect the slots to the signals only once
}

//______________________________________________________________________________
void TPieEditor::ActivateBaseClassEditors(TClass* cl)
{
   // Exclude TAttTextEditor from this interface.

   TGedEditor *gedEditor = GetGedEditor();
   gedEditor->ExcludeClassEditor(TAttText::Class());
   TGedFrame::ActivateBaseClassEditors(cl);
}

//______________________________________________________________________________
void TPieEditor::SetModel(TObject* obj)
{
   // Pick up the used values of graph attributes.

   fPie = (TPie *)obj;
   fAvoidSignal = kTRUE;

   // set the Title TextEntry
   const char *text = fPie->GetTitle();
   fTitle->SetText(text);

   TString soption = GetDrawOption();

   bool optionSame(kFALSE);

   // For the label orientation there are 3 possibilities:
   //   0: horizontal
   //   1: radial
   //   2: tangent
   Int_t lblor(0);

   // Parse the options
   Int_t idx;
   // Paint the TPie in an existing canvas
   if ( (idx=soption.Index("same"))>=0 ) {
      optionSame = kTRUE;
      soption.Remove(idx,4);
   }

   if ( (idx=soption.Index("nol"))>=0 ) {
      fOutlineOnOff->SetState(kButtonUp,kFALSE);
      soption.Remove(idx,3);
   }
   else {
      fOutlineOnOff->SetState(kButtonDown,kFALSE);
   }

   // check if is active the pseudo-3d
   if ( (idx=soption.Index("3d"))>=0 ) {
      fIs3D->SetState(kButtonDown, kFALSE);
      f3DAngle->SetNumber(fPie->GetAngle3D());
      f3DHeight->SetNumber(fPie->GetHeight());
      soption.Remove(idx,2);
   } else {
      fIs3D->SetState(kButtonUp, kFALSE);
   }

   // seek if have to draw the labels around the pie chart
   if ( (idx=soption.Index("t"))>=0 ) {
      lblor = 2;
      soption.Remove(idx,1);
   }

   // Seek if have to paint the labels along the radii
   if ( (idx=soption.Index("r"))>=0 ) {
      lblor = 1;
      soption.Remove(idx,1);
   }

   switch(lblor) {
   case 0:
      fLblDirH->SetState(kButtonDown,kTRUE);
      break;
   case 1:
      fLblDirR->SetState(kButtonDown,kTRUE);
      break;
   case 2:
      fLblDirT->SetState(kButtonDown,kTRUE);
      break;
   }

   // set text attributes
   fTypeCombo->Select(fPie->GetTextFont() / 10);

   Color_t c = fPie->GetTextColor();
   Pixel_t p = TColor::Number2Pixel(c);
   fColorSelect->SetColor(p, kFALSE);

   Float_t s = fPie->GetTextSize();
   Float_t dy;

   if (obj->InheritsFrom(TPaveLabel::Class())) {
      TBox *pl = (TBox*)obj;
      dy = s * (pl->GetY2() - pl->GetY1());
   }
   else
      dy = s * (fGedEditor->GetPad()->GetY2() - fGedEditor->GetPad()->GetY1());

   Int_t size = fGedEditor->GetPad()->YtoPixel(0.0) - fGedEditor->GetPad()->YtoPixel(dy);
   if (size > 50) size = 50;
   if (size < 0)  size = 0;
   fSizeCombo->Select(size, kFALSE);

   if (fInit) ConnectSignals2Slots();
   fAvoidSignal = kFALSE;
}

//______________________________________________________________________________
void TPieEditor::DoTitle(const char *text)
{
   // Slot for setting the graph title.

   if (fAvoidSignal) return;
   fPie->SetTitle(text);
   Update();
}

//______________________________________________________________________________
void TPieEditor::DoShape()
{
   // Slot connected to the draw options.

   if (fAvoidSignal) return;

   TString opt = GetDrawOption();

   if (fLblDirH->GetState()==kButtonDown) {
      if (opt.Contains("t")) opt.Remove(opt.First("t"),1);
      if (opt.Contains("r")) opt.Remove(opt.First("r"),1);
   }
   else if (fLblDirR->GetState()==kButtonDown) {
      if (opt.Contains("t")) opt.Remove(opt.First("t"),1);
      if (!opt.Contains("r")) opt += "r";
   }
   else if (fLblDirT->GetState()==kButtonDown) {
      if (!opt.Contains("t")) opt += "t";
      if (opt.Contains("r")) opt.Remove(opt.First("r"),1);
   }

   SetDrawOption(opt);
   if (gPad && gPad->GetVirtCanvas()) gPad->GetVirtCanvas()->SetCursor(kPointer);
   gVirtualX->SetCursor(GetId(), gVirtualX->CreateCursor(kPointer));
}

//______________________________________________________________________________
void TPieEditor::DoMarkerOnOff(Bool_t)
{
   // Slot for setting markers as visible/invisible.

   if (fAvoidSignal) return;
   TString t = GetDrawOption();

   if (t.Contains("nol") && fOutlineOnOff->GetState() == kButtonDown) {
      t.Remove(t.First("nol"),3);
   }
   else if (!t.Contains("nol") && fOutlineOnOff->GetState() == kButtonUp) {
      t += "nol";
   }

   SetDrawOption(t);
}

//______________________________________________________________________________
void TPieEditor::DoChange3DAngle()
{
   // Slot for setting the 3D angle
   if (fAvoidSignal) return;

   fPie->SetAngle3D(static_cast<Int_t>(f3DAngle->GetNumber()));
   fPie->SetHeight(f3DHeight->GetNumber());

   Update();

}

//______________________________________________________________________________
void TPieEditor::DoGraphLineWidth()
{
   // Slot connected to the graph line width.

   if (fAvoidSignal) return;

   TString opt = GetDrawOption();
   if (!opt.Contains("3d") && fIs3D->IsDown())
      opt += "3d";
   else if (opt.Contains("3d") && !fIs3D->IsDown())
      opt.Remove(opt.First("3d"),2);

   SetDrawOption(opt);

   Update();
}

//______________________________________________________________________________
void TPieEditor::DoTextChange()
{
   // Change text.

   if (fAvoidSignal) return;

   // font color
   fPie->SetTextColor(TColor::GetColor(fColorSelect->GetColor()));

   // font type
   Int_t fontPrec = fPie->GetTextFont()%10;
   Int_t fontType = fTypeCombo->GetSelected();
   fPie->SetTextFont(fontType*10+fontPrec);

   // font size
   TVirtualPad* pad = fGedEditor->GetPad();

   Float_t val = TString(fSizeCombo->GetSelectedEntry()->GetTitle()).Atoi();

   Float_t dy = pad->AbsPixeltoY(0) - pad->AbsPixeltoY((Int_t)val);
   Float_t textSize;

   if (fGedEditor->GetModel()->InheritsFrom(TPaveLabel::Class())) {
      TBox *pl = (TBox*)fGedEditor->GetModel();
      textSize = dy/(pl->GetY2() - pl->GetY1());
   }
   else
      textSize = dy/(pad->GetY2() - pad->GetY1());

   fPie->SetTextSize(textSize);

   Update();

}

//______________________________________________________________________________
TGComboBox* TPieEditor::BuildFontSizeComboBox(TGFrame* parent, Int_t id)
{
   // Create text size combo box.

   char a[100];
   TGComboBox *c = new TGComboBox(parent, id);

   c->AddEntry("Default", 0);
   for (int i = 1; i <= 50; i++) {
      snprintf(a, 99, "%d", i);
      c->AddEntry(a, i);
   }

   return c;
}
<|endoftext|>


<commit_before>/* Luwra
 * Minimal-overhead Lua wrapper for C++
 *
 * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
 */

#ifndef LUWRA_FUNCTIONS_H_
#define LUWRA_FUNCTIONS_H_

#include "common.hpp"
#include "types.hpp"
#include "stack.hpp"

LUWRA_NS_BEGIN

namespace internal {
	template <typename T>
	struct FunctionWrapper {
		static_assert(
			sizeof(T) == -1,
			"Parameter to FunctionWrapper is not a valid signature"
		);
	};

	template <typename R, typename... A>
	struct FunctionWrapper<R(A...)> {
		template <R (* fun)(A...)> static inline
		int invoke(State* state) {
			return static_cast<int>(
				map<R(A...)>(state, fun)
			);
		}
	};

	// We need an alias, because function pointers are weird
	template <typename R, typename... A>
	struct FunctionWrapper<R (*)(A...)>: FunctionWrapper<R (A...)> {};
}

/**
 * A callable native Lua function.
 * \note This value is only available as long as it exists on the stack.
 */
template <typename R>
struct NativeFunction: Reference {
	NativeFunction(State* state, int index):
		Reference(state, index)
	{}

	inline
	R operator ()() {
		impl->push();

		lua_call(impl->state, 0, 1);
		R returnValue = Value<R>::read(impl->state, -1);

		lua_pop(impl->state, 1);
		return returnValue;
	}

	template <typename... A> inline
	R operator ()(A&&... args) {
		impl->push();
		size_t numArgs = push(impl->state, std::forward<A>(args)...);

		lua_call(impl->state, static_cast<int>(numArgs), 1);
		R returnValue = Value<R>::read(impl->state, -1);

		lua_pop(impl->state, 1);
		return returnValue;
	}
};

/**
 * A callable native Lua function.
 * \note This value is only available as long as it exists on the stack.
 */
template <>
struct NativeFunction<void>: Reference {
	NativeFunction(State* state, int index):
		Reference(state, index)
	{}

	inline
	void operator ()() {
		impl->push();
		lua_call(impl->state, 0, 0);
	}

	template <typename... A> inline
	void operator ()(A&&... args) {
		impl->push();
		size_t numArgs = push(impl->state, std::forward<A>(args)...);

		lua_call(impl->state, static_cast<int>(numArgs), 0);
	}
};

template <typename R>
struct Value<NativeFunction<R>> {
	static inline
	NativeFunction<R> read(State* state, int index) {
		luaL_checktype(state, index, LUA_TFUNCTION);
		return NativeFunction<R>(state, index);
	}
};

LUWRA_NS_END

/**
 * Generate a `lua_CFunction` wrapper for a function.
 * \param fun Fully qualified function name (Do not supply a pointer)
 * \returns Wrapped function as `lua_CFunction`
 */
#define LUWRA_WRAP_FUNCTION(fun) \
	(&luwra::internal::FunctionWrapper<decltype(&fun)>::template invoke<&fun>)

#endif
<commit_msg>docs: Fix description for NativeFunction<commit_after>/* Luwra
 * Minimal-overhead Lua wrapper for C++
 *
 * Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
 */

#ifndef LUWRA_FUNCTIONS_H_
#define LUWRA_FUNCTIONS_H_

#include "common.hpp"
#include "types.hpp"
#include "stack.hpp"

LUWRA_NS_BEGIN

namespace internal {
	template <typename T>
	struct FunctionWrapper {
		static_assert(
			sizeof(T) == -1,
			"Parameter to FunctionWrapper is not a valid signature"
		);
	};

	template <typename R, typename... A>
	struct FunctionWrapper<R(A...)> {
		template <R (* fun)(A...)> static inline
		int invoke(State* state) {
			return static_cast<int>(
				map<R(A...)>(state, fun)
			);
		}
	};

	// We need an alias, because function pointers are weird
	template <typename R, typename... A>
	struct FunctionWrapper<R (*)(A...)>: FunctionWrapper<R (A...)> {};
}

/**
 * A callable native Lua function.
 */
template <typename R>
struct NativeFunction: Reference {
	NativeFunction(State* state, int index):
		Reference(state, index)
	{}

	inline
	R operator ()() {
		impl->push();

		lua_call(impl->state, 0, 1);
		R returnValue = Value<R>::read(impl->state, -1);

		lua_pop(impl->state, 1);
		return returnValue;
	}

	template <typename... A> inline
	R operator ()(A&&... args) {
		impl->push();
		size_t numArgs = push(impl->state, std::forward<A>(args)...);

		lua_call(impl->state, static_cast<int>(numArgs), 1);
		R returnValue = Value<R>::read(impl->state, -1);

		lua_pop(impl->state, 1);
		return returnValue;
	}
};

/**
 * A callable native Lua function.
 */
template <>
struct NativeFunction<void>: Reference {
	NativeFunction(State* state, int index):
		Reference(state, index)
	{}

	inline
	void operator ()() {
		impl->push();
		lua_call(impl->state, 0, 0);
	}

	template <typename... A> inline
	void operator ()(A&&... args) {
		impl->push();
		size_t numArgs = push(impl->state, std::forward<A>(args)...);

		lua_call(impl->state, static_cast<int>(numArgs), 0);
	}
};

template <typename R>
struct Value<NativeFunction<R>> {
	static inline
	NativeFunction<R> read(State* state, int index) {
		luaL_checktype(state, index, LUA_TFUNCTION);
		return NativeFunction<R>(state, index);
	}
};

LUWRA_NS_END

/**
 * Generate a `lua_CFunction` wrapper for a function.
 * \param fun Fully qualified function name (Do not supply a pointer)
 * \returns Wrapped function as `lua_CFunction`
 */
#define LUWRA_WRAP_FUNCTION(fun) \
	(&luwra::internal::FunctionWrapper<decltype(&fun)>::template invoke<&fun>)

#endif
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "docsumwriter.h"
#include "docsumstate.h"
#include "docsum_field_writer_state.h"
#include <vespa/searchlib/common/transport.h>
#include <vespa/searchlib/util/slime_output_raw_buf_adapter.h>
#include <vespa/searchlib/attribute/iattributemanager.h>
#include <vespa/vespalib/data/slime/slime.h>

#include <vespa/log/log.h>
LOG_SETUP(".searchlib.docsummary.docsumwriter");

using namespace vespalib::slime::convenience;

namespace search::docsummary {

uint32_t
IDocsumWriter::slime2RawBuf(const Slime & slime, RawBuf & buf)
{
    const uint32_t preUsed = buf.GetUsedLen();
    const uint32_t magic = ::search::fs4transport::SLIME_MAGIC_ID;
    buf.append(&magic, sizeof(magic));
    SlimeOutputRawBufAdapter adapter(buf);
    vespalib::slime::BinaryFormat::encode(slime, adapter);
    return (buf.GetUsedLen() - preUsed);
}

DynamicDocsumWriter::ResolveClassInfo
DynamicDocsumWriter::resolveClassInfo(vespalib::stringref outputClassName, uint32_t inputClassId) const
{
    DynamicDocsumWriter::ResolveClassInfo rci = resolveOutputClass(outputClassName);
    if (!rci.mustSkip && !rci.allGenerated) {
        resolveInputClass(rci, inputClassId);
    }
    return rci;
}

DynamicDocsumWriter::ResolveClassInfo
DynamicDocsumWriter::resolveOutputClass(vespalib::stringref summaryClass) const
{
    DynamicDocsumWriter::ResolveClassInfo result;
    uint32_t id = _defaultOutputClass;
    id = _resultConfig->LookupResultClassId(summaryClass, id);

    if (id != ResultConfig::NoClassID()) {
        const ResultClass *oC = _resultConfig->LookupResultClass(id);
        if (oC == nullptr) {
            LOG(warning, "Illegal docsum class requested: %d, using empty docsum for documents", id);
            result.mustSkip = true;
        } else {
            result.outputClass = oC;
            const ResultClass::DynamicInfo *rcInfo = oC->getDynamicInfo();
            if (rcInfo->_generateCnt == oC->GetNumEntries()) {
                LOG_ASSERT(rcInfo->_overrideCnt == rcInfo->_generateCnt);
                result.allGenerated = true;
            }
            result.outputClassInfo = rcInfo;
        }
    }
    result.outputClassId = id;
    return result;
}

void
DynamicDocsumWriter::resolveInputClass(ResolveClassInfo &rci, uint32_t id) const
{
    rci.inputClass = _resultConfig->LookupResultClass(id);
    if (rci.inputClass == nullptr) {
        rci.mustSkip = true;
        return;
    }
    if (rci.outputClass == nullptr) {
        LOG_ASSERT(rci.outputClassId == ResultConfig::NoClassID());
        rci.outputClassId = id;
        rci.outputClass = rci.inputClass;
        rci.outputClassInfo = rci.inputClass->getDynamicInfo();
    }
}

constexpr uint32_t default_32bits_int = (uint32_t)std::numeric_limits<int32_t>::min();
constexpr uint64_t default_64bits_int = (uint64_t)std::numeric_limits<int64_t>::min();

static void convertEntry(GetDocsumsState *state,
                         const ResConfigEntry *resCfg,
                         const ResEntry *entry,
                         Inserter &inserter,
                         Slime &slime)
{
    using vespalib::slime::BinaryFormat;
    const char *ptr;
    uint32_t len;

    LOG_ASSERT(resCfg != nullptr && entry != nullptr);
    switch (resCfg->_type) {
    case RES_INT:
    case RES_SHORT:
    case RES_BYTE:
        if (entry->_intval != default_32bits_int) {
            inserter.insertLong(entry->_intval);
        }
        break;
    case RES_BOOL:
        inserter.insertBool(entry->_intval != 0);
        break;
    case RES_FLOAT:
    case RES_DOUBLE:
        if (! std::isnan(entry->_doubleval)) {
            inserter.insertDouble(entry->_doubleval);
        }
        break;
    case RES_INT64:
        if (entry->_int64val != default_64bits_int) {
            inserter.insertLong(entry->_int64val);
        }
        break;
    case RES_STRING:
    case RES_LONG_STRING:
    case RES_FEATUREDATA:
    case RES_XMLSTRING:
        entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace);
        if (len != 0) {
            inserter.insertString(Memory(ptr, len));
        }
        break;
    case RES_DATA:
    case RES_TENSOR:
    case RES_LONG_DATA:
        entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace);
        if (len != 0) {
            inserter.insertData(Memory(ptr, len));
        }
        break;
    case RES_JSONSTRING:
        entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace);
        if (len != 0) {
            // note: 'JSONSTRING' really means 'structured data'
            size_t d = BinaryFormat::decode_into(Memory(ptr, len), slime, inserter);
            if (d != len) {
                LOG(warning, "could not decode %u bytes: %zu bytes decoded", len, d);
            }
        }
        break;
    }
}

void
DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid, GetDocsumsState *state,
                                  IDocsumStore *docinfos, vespalib::Slime & slime, vespalib::slime::Inserter & topInserter)
{
    if (rci.allGenerated) {
        // generate docsum entry on-the-fly
        vespalib::slime::Cursor & docsum = topInserter.insertObject();
        for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) {
            const ResConfigEntry *resCfg = rci.outputClass->GetEntry(i);
            IDocsumFieldWriter *writer = _overrideTable[resCfg->_enumValue];
            if (! writer->isDefaultValue(docid, state)) {
                const Memory field_name(resCfg->_bindname.data(), resCfg->_bindname.size());
                ObjectInserter inserter(docsum, field_name);
                writer->insertField(docid, nullptr, state, resCfg->_type, inserter);
            }
        }
    } else {
        // look up docsum entry
        DocsumStoreValue value = docinfos->getMappedDocsum(docid);
        // re-pack docsum blob
        GeneralResult gres(rci.inputClass);
        if (! gres.inplaceUnpack(value)) {
            LOG(debug, "Unpack failed: illegal docsum entry for document %d. This is expected during lidspace compaction.", docid);
            topInserter.insertNix();
            return;
        }
        vespalib::slime::Cursor & docsum = topInserter.insertObject();
        for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) {
            const ResConfigEntry *outCfg = rci.outputClass->GetEntry(i);
            IDocsumFieldWriter *writer = _overrideTable[outCfg->_enumValue];
            const Memory field_name(outCfg->_bindname.data(), outCfg->_bindname.size());
            ObjectInserter inserter(docsum, field_name);
            if (writer != nullptr) {
                if (! writer->isDefaultValue(docid, state)) {
                    writer->insertField(docid, &gres, state, outCfg->_type, inserter);
                }
            } else {
                if (rci.inputClass == rci.outputClass) {
                    convertEntry(state, outCfg, gres.GetEntry(i), inserter, slime);
                } else {
                    int inIdx = rci.inputClass->GetIndexFromEnumValue(outCfg->_enumValue);
                    const ResConfigEntry *inCfg = rci.inputClass->GetEntry(inIdx);
                    if (inCfg != nullptr && inCfg->_type == outCfg->_type) {
                        // copy field
                        const ResEntry *entry = gres.GetEntry(inIdx);
                        LOG_ASSERT(entry != nullptr);
                        convertEntry(state, outCfg, entry, inserter, slime);
                    }
                }
            }
        }
    }
}

DynamicDocsumWriter::DynamicDocsumWriter( ResultConfig *config, KeywordExtractor *extractor)
    : _resultConfig(config),
      _keywordExtractor(extractor),
      _defaultOutputClass(ResultConfig::NoClassID()),
      _numClasses(config->GetNumResultClasses()),
      _numEnumValues(config->GetFieldNameEnum().GetNumEntries()),
      _numFieldWriterStates(0),
      _classInfoTable(nullptr),
      _overrideTable(nullptr)
{
    LOG_ASSERT(config != nullptr);
    _classInfoTable = new ResultClass::DynamicInfo[_numClasses];
    _overrideTable  = new IDocsumFieldWriter*[_numEnumValues];

    uint32_t i = 0;
    for (ResultConfig::iterator it(config->begin()), mt(config->end()); it != mt; it++, i++) {
        _classInfoTable[i]._overrideCnt = 0;
        _classInfoTable[i]._generateCnt = 0;
        it->setDynamicInfo(&(_classInfoTable[i]));
    }
    LOG_ASSERT(i == _numClasses);

    for (i = 0; i < _numEnumValues; i++)
        _overrideTable[i] = nullptr;
}

DynamicDocsumWriter::~DynamicDocsumWriter()
{
    delete _resultConfig;
    delete _keywordExtractor;

    delete [] _classInfoTable;

    for (uint32_t i = 0; i < _numEnumValues; i++)
        delete _overrideTable[i];
    delete [] _overrideTable;

}

bool
DynamicDocsumWriter::SetDefaultOutputClass(uint32_t classID)
{
    const ResultClass *resClass = _resultConfig->LookupResultClass(classID);

    if (resClass == nullptr ||
        _defaultOutputClass != ResultConfig::NoClassID())
    {
        if (resClass == nullptr) {
            LOG(warning, "cannot set default output docsum class to %d; class not defined", classID);
        } else if (_defaultOutputClass != ResultConfig::NoClassID()) {
            LOG(warning, "cannot set default output docsum class to %d; value already set", classID);
        }
        return false;
    }
    _defaultOutputClass = classID;
    return true;
}

bool
DynamicDocsumWriter::Override(const char *fieldName, IDocsumFieldWriter *writer)
{
    uint32_t fieldEnumValue = _resultConfig->GetFieldNameEnum().Lookup(fieldName);

    if (fieldEnumValue >= _numEnumValues ||
        _overrideTable[fieldEnumValue] != nullptr)
    {

        if (fieldEnumValue >= _numEnumValues) {
            LOG(warning, "cannot override docsum field '%s'; undefined field name", fieldName);
        } else if (_overrideTable[fieldEnumValue] != nullptr) {
            LOG(warning, "cannot override docsum field '%s'; already overridden", fieldName);
        }
        delete writer;
        return false;
    }

    writer->setIndex(fieldEnumValue);
    _overrideTable[fieldEnumValue] = writer;
    if (writer->setFieldWriterStateIndex(_numFieldWriterStates)) {
        ++_numFieldWriterStates;
    }

    for (auto & entry : *_resultConfig) {

        if (entry.GetIndexFromEnumValue(fieldEnumValue) >= 0) {
            ResultClass::DynamicInfo *info = entry.getDynamicInfo();
            info->_overrideCnt++;
            if (writer->IsGenerated())
                info->_generateCnt++;
        }
    }

    return true;
}

void
DynamicDocsumWriter::InitState(IAttributeManager & attrMan, GetDocsumsState *state)
{
    state->_kwExtractor = _keywordExtractor;
    state->_attrCtx = attrMan.createContext();
    state->_attributes.resize(_numEnumValues);
    state->_fieldWriterStates.resize(_numFieldWriterStates);
    for (size_t i(0); i < state->_attributes.size(); i++) {
        const IDocsumFieldWriter *fw = _overrideTable[i];
        if (fw) {
            const vespalib::string & attributeName = fw->getAttributeName();
            if (!attributeName.empty()) {
                state->_attributes[i] = state->_attrCtx->getAttribute(attributeName);
            }
        }
    }
}

uint32_t
DynamicDocsumWriter::WriteDocsum(uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, search::RawBuf *target)
{
    vespalib::Slime slime;
    vespalib::slime::SlimeInserter inserter(slime);
    ResolveClassInfo rci = resolveClassInfo(state->_args.getResultClassName(), docinfos->getSummaryClassId());
    insertDocsum(rci, docid, state, docinfos, slime, inserter);
    return slime2RawBuf(slime, *target);
}

}
<commit_msg>Revert "skip fields which are empty or only have the default value"<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "docsumwriter.h"
#include "docsumstate.h"
#include "docsum_field_writer_state.h"
#include <vespa/searchlib/common/transport.h>
#include <vespa/searchlib/util/slime_output_raw_buf_adapter.h>
#include <vespa/searchlib/attribute/iattributemanager.h>
#include <vespa/vespalib/data/slime/slime.h>

#include <vespa/log/log.h>
LOG_SETUP(".searchlib.docsummary.docsumwriter");

using namespace vespalib::slime::convenience;

namespace search::docsummary {

uint32_t
IDocsumWriter::slime2RawBuf(const Slime & slime, RawBuf & buf)
{
    const uint32_t preUsed = buf.GetUsedLen();
    const uint32_t magic = ::search::fs4transport::SLIME_MAGIC_ID;
    buf.append(&magic, sizeof(magic));
    SlimeOutputRawBufAdapter adapter(buf);
    vespalib::slime::BinaryFormat::encode(slime, adapter);
    return (buf.GetUsedLen() - preUsed);
}

DynamicDocsumWriter::ResolveClassInfo
DynamicDocsumWriter::resolveClassInfo(vespalib::stringref outputClassName, uint32_t inputClassId) const
{
    DynamicDocsumWriter::ResolveClassInfo rci = resolveOutputClass(outputClassName);
    if (!rci.mustSkip && !rci.allGenerated) {
        resolveInputClass(rci, inputClassId);
    }
    return rci;
}

DynamicDocsumWriter::ResolveClassInfo
DynamicDocsumWriter::resolveOutputClass(vespalib::stringref summaryClass) const
{
    DynamicDocsumWriter::ResolveClassInfo result;
    uint32_t id = _defaultOutputClass;
    id = _resultConfig->LookupResultClassId(summaryClass, id);

    if (id != ResultConfig::NoClassID()) {
        const ResultClass *oC = _resultConfig->LookupResultClass(id);
        if (oC == nullptr) {
            LOG(warning, "Illegal docsum class requested: %d, using empty docsum for documents", id);
            result.mustSkip = true;
        } else {
            result.outputClass = oC;
            const ResultClass::DynamicInfo *rcInfo = oC->getDynamicInfo();
            if (rcInfo->_generateCnt == oC->GetNumEntries()) {
                LOG_ASSERT(rcInfo->_overrideCnt == rcInfo->_generateCnt);
                result.allGenerated = true;
            }
            result.outputClassInfo = rcInfo;
        }
    }
    result.outputClassId = id;
    return result;
}

void
DynamicDocsumWriter::resolveInputClass(ResolveClassInfo &rci, uint32_t id) const
{
    rci.inputClass = _resultConfig->LookupResultClass(id);
    if (rci.inputClass == nullptr) {
        rci.mustSkip = true;
        return;
    }
    if (rci.outputClass == nullptr) {
        LOG_ASSERT(rci.outputClassId == ResultConfig::NoClassID());
        rci.outputClassId = id;
        rci.outputClass = rci.inputClass;
        rci.outputClassInfo = rci.inputClass->getDynamicInfo();
    }
}

static void convertEntry(GetDocsumsState *state,
                         const ResConfigEntry *resCfg,
                         const ResEntry *entry,
                         Inserter &inserter,
                         Slime &slime)
{
    using vespalib::slime::BinaryFormat;
    const char *ptr;
    uint32_t len;

    LOG_ASSERT(resCfg != nullptr && entry != nullptr);
    switch (resCfg->_type) {
    case RES_INT:
    case RES_SHORT:
    case RES_BYTE:
        inserter.insertLong(entry->_intval);
        break;
    case RES_BOOL:
        inserter.insertBool(entry->_intval != 0);
        break;
    case RES_FLOAT:
    case RES_DOUBLE:
        inserter.insertDouble(entry->_doubleval);
        break;
    case RES_INT64:
        inserter.insertLong(entry->_int64val);
        break;
    case RES_STRING:
    case RES_LONG_STRING:
    case RES_FEATUREDATA:
    case RES_XMLSTRING:
        entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace);
        inserter.insertString(Memory(ptr, len));
        break;
    case RES_DATA:
    case RES_TENSOR:
    case RES_LONG_DATA:
        entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace);
        inserter.insertData(Memory(ptr, len));
        break;
    case RES_JSONSTRING:
        entry->_resolve_field(&ptr, &len, &state->_docSumFieldSpace);
        if (len != 0) {
            // note: 'JSONSTRING' really means 'structured data'
            size_t d = BinaryFormat::decode_into(Memory(ptr, len), slime, inserter);
            if (d != len) {
                LOG(warning, "could not decode %u bytes: %zu bytes decoded", len, d);
            }
        }
        break;
    }
}

void
DynamicDocsumWriter::insertDocsum(const ResolveClassInfo & rci, uint32_t docid, GetDocsumsState *state,
                                  IDocsumStore *docinfos, vespalib::Slime & slime, vespalib::slime::Inserter & topInserter)
{
    if (rci.allGenerated) {
        // generate docsum entry on-the-fly
        vespalib::slime::Cursor & docsum = topInserter.insertObject();
        for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) {
            const ResConfigEntry *resCfg = rci.outputClass->GetEntry(i);
            IDocsumFieldWriter *writer = _overrideTable[resCfg->_enumValue];
            if (! writer->isDefaultValue(docid, state)) {
                const Memory field_name(resCfg->_bindname.data(), resCfg->_bindname.size());
                ObjectInserter inserter(docsum, field_name);
                writer->insertField(docid, nullptr, state, resCfg->_type, inserter);
            }
        }
    } else {
        // look up docsum entry
        DocsumStoreValue value = docinfos->getMappedDocsum(docid);
        // re-pack docsum blob
        GeneralResult gres(rci.inputClass);
        if (! gres.inplaceUnpack(value)) {
            LOG(debug, "Unpack failed: illegal docsum entry for document %d. This is expected during lidspace compaction.", docid);
            topInserter.insertNix();
            return;
        }
        vespalib::slime::Cursor & docsum = topInserter.insertObject();
        for (uint32_t i = 0; i < rci.outputClass->GetNumEntries(); ++i) {
            const ResConfigEntry *outCfg = rci.outputClass->GetEntry(i);
            IDocsumFieldWriter *writer = _overrideTable[outCfg->_enumValue];
            const Memory field_name(outCfg->_bindname.data(), outCfg->_bindname.size());
            ObjectInserter inserter(docsum, field_name);
            if (writer != nullptr) {
                //TODO: Need to add test for writer->isDefaultValue
                writer->insertField(docid, &gres, state, outCfg->_type, inserter);
            } else {
                //TODO: Need to add similar test as writer->isDefaultValue
                if (rci.inputClass == rci.outputClass) {
                    convertEntry(state, outCfg, gres.GetEntry(i), inserter, slime);
                } else {
                    int inIdx = rci.inputClass->GetIndexFromEnumValue(outCfg->_enumValue);
                    const ResConfigEntry *inCfg = rci.inputClass->GetEntry(inIdx);
                    if (inCfg != nullptr && inCfg->_type == outCfg->_type) {
                        // copy field
                        const ResEntry *entry = gres.GetEntry(inIdx);
                        LOG_ASSERT(entry != nullptr);
                        convertEntry(state, outCfg, entry, inserter, slime);
                    }
                }
            }
        }
    }
}

DynamicDocsumWriter::DynamicDocsumWriter( ResultConfig *config, KeywordExtractor *extractor)
    : _resultConfig(config),
      _keywordExtractor(extractor),
      _defaultOutputClass(ResultConfig::NoClassID()),
      _numClasses(config->GetNumResultClasses()),
      _numEnumValues(config->GetFieldNameEnum().GetNumEntries()),
      _numFieldWriterStates(0),
      _classInfoTable(nullptr),
      _overrideTable(nullptr)
{
    LOG_ASSERT(config != nullptr);
    _classInfoTable = new ResultClass::DynamicInfo[_numClasses];
    _overrideTable  = new IDocsumFieldWriter*[_numEnumValues];

    uint32_t i = 0;
    for (ResultConfig::iterator it(config->begin()), mt(config->end()); it != mt; it++, i++) {
        _classInfoTable[i]._overrideCnt = 0;
        _classInfoTable[i]._generateCnt = 0;
        it->setDynamicInfo(&(_classInfoTable[i]));
    }
    LOG_ASSERT(i == _numClasses);

    for (i = 0; i < _numEnumValues; i++)
        _overrideTable[i] = nullptr;
}

DynamicDocsumWriter::~DynamicDocsumWriter()
{
    delete _resultConfig;
    delete _keywordExtractor;

    delete [] _classInfoTable;

    for (uint32_t i = 0; i < _numEnumValues; i++)
        delete _overrideTable[i];
    delete [] _overrideTable;

}

bool
DynamicDocsumWriter::SetDefaultOutputClass(uint32_t classID)
{
    const ResultClass *resClass = _resultConfig->LookupResultClass(classID);

    if (resClass == nullptr ||
        _defaultOutputClass != ResultConfig::NoClassID())
    {
        if (resClass == nullptr) {
            LOG(warning, "cannot set default output docsum class to %d; class not defined", classID);
        } else if (_defaultOutputClass != ResultConfig::NoClassID()) {
            LOG(warning, "cannot set default output docsum class to %d; value already set", classID);
        }
        return false;
    }
    _defaultOutputClass = classID;
    return true;
}

bool
DynamicDocsumWriter::Override(const char *fieldName, IDocsumFieldWriter *writer)
{
    uint32_t fieldEnumValue = _resultConfig->GetFieldNameEnum().Lookup(fieldName);

    if (fieldEnumValue >= _numEnumValues ||
        _overrideTable[fieldEnumValue] != nullptr)
    {

        if (fieldEnumValue >= _numEnumValues) {
            LOG(warning, "cannot override docsum field '%s'; undefined field name", fieldName);
        } else if (_overrideTable[fieldEnumValue] != nullptr) {
            LOG(warning, "cannot override docsum field '%s'; already overridden", fieldName);
        }
        delete writer;
        return false;
    }

    writer->setIndex(fieldEnumValue);
    _overrideTable[fieldEnumValue] = writer;
    if (writer->setFieldWriterStateIndex(_numFieldWriterStates)) {
        ++_numFieldWriterStates;
    }

    for (auto & entry : *_resultConfig) {

        if (entry.GetIndexFromEnumValue(fieldEnumValue) >= 0) {
            ResultClass::DynamicInfo *info = entry.getDynamicInfo();
            info->_overrideCnt++;
            if (writer->IsGenerated())
                info->_generateCnt++;
        }
    }

    return true;
}

void
DynamicDocsumWriter::InitState(IAttributeManager & attrMan, GetDocsumsState *state)
{
    state->_kwExtractor = _keywordExtractor;
    state->_attrCtx = attrMan.createContext();
    state->_attributes.resize(_numEnumValues);
    state->_fieldWriterStates.resize(_numFieldWriterStates);
    for (size_t i(0); i < state->_attributes.size(); i++) {
        const IDocsumFieldWriter *fw = _overrideTable[i];
        if (fw) {
            const vespalib::string & attributeName = fw->getAttributeName();
            if (!attributeName.empty()) {
                state->_attributes[i] = state->_attrCtx->getAttribute(attributeName);
            }
        }
    }
}

uint32_t
DynamicDocsumWriter::WriteDocsum(uint32_t docid, GetDocsumsState *state, IDocsumStore *docinfos, search::RawBuf *target)
{
    vespalib::Slime slime;
    vespalib::slime::SlimeInserter inserter(slime);
    ResolveClassInfo rci = resolveClassInfo(state->_args.getResultClassName(), docinfos->getSummaryClassId());
    insertDocsum(rci, docid, state, docinfos, slime, inserter);
    return slime2RawBuf(slime, *target);
}

}
<|endoftext|>


<commit_before>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2016, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "session.h"

#include <QObject>
#include <QProcess>
#include <QProcessEnvironment>
#include <QDebug>
#include <QSettings>
#include <QDir>

#include <LUtils.h>
#include <LuminaOS.h>

void LSession::stopall(){
  stopping = true;
  for(int i=0; i<PROCS.length(); i++){
    if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->kill(); }
  }
  QCoreApplication::processEvents();
  for(int i=0; i<PROCS.length(); i++){
    if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->terminate(); }
  }
  QCoreApplication::exit(0);
}

void LSession::procFinished(){
  //Go through and check the status on all the procs to determine which one finished
  int stopped = 0;
  for(int i=0; i<PROCS.length(); i++){
    if(PROCS[i]->state()==QProcess::NotRunning){
      stopped++;
      if(!stopping){
        //See if this process is the main desktop binary
        if(PROCS[i]->objectName()=="runtime"){ stopall(); }
        //if(PROCS[i]->program().section("/",-1) == "lumina-desktop"){ stopall();  } //start closing down everything
        //else{ PROCS[i]->start(QIODevice::ReadOnly); } //restart the process
        break;
      }
    }
  }
  if(stopping && stopped==PROCS.length()){
    QCoreApplication::exit(0);
  }
}

void LSession::startProcess(QString ID, QString command, QStringList watchfiles){
  QString dir = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/logs";
  if(!QFile::exists(dir)){ QDir tmp(dir); tmp.mkpath(dir); }
  QString logfile = dir+"/"+ID+".log";
  if(QFile::exists(logfile+".old")){ QFile::remove(logfile+".old"); }
  if(QFile::exists(logfile)){ QFile::rename(logfile,logfile+".old"); }

  LProcess *proc = new LProcess(ID, watchfiles);
  proc->setProcessChannelMode(QProcess::MergedChannels);
  proc->setProcessEnvironment( QProcessEnvironment::systemEnvironment() );
  proc->setStandardOutputFile(logfile);
  proc->setObjectName(ID);
  if(ID=="runtime"){
    //Bypass for a hidden dbus file requirement for Qt itself (Qt 5.5.1+?)
    if(!QFile::exists("/etc/machine-id") && !QFile::exists("/var/db/dbus/machine-id")){
      if(LUtils::isValidBinary("dbus-uuidgen") && LUtils::runCmd("dbus-uuidgen --ensure") ){ } //good - the UUID was created successfully
      else if(LUtils::isValidBinary("dbus-launch")){ command.prepend("dbus-launch --exit-with-session "); }
      else{
        //create a simple DBUS UUID and put it in the universal-fallback location (OS-independent)
        // TO-DO - root vs user level permissions issue?
        qDebug() << "Could not find '/etc/machine-id' or '/var/db/dbus/machine-id': Qt will most likely crash. \nPlease run 'dbus-uuidgen --ensure' with root permissions to generate this file if Lumina does not start properly.";
      }
   }
  }
  proc->start(command, QIODevice::ReadOnly);
  connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(procFinished()) );
  PROCS << proc;
}

void LSession::start(){
  //First check for a valid installation
  if( !LUtils::isValidBinary("fluxbox") || !LUtils::isValidBinary("lumina-desktop") ){
    exit(1);
  }
  //Window Manager First
  // FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
  if( !LUtils::isValidBinary("fluxbox") ){
    qDebug() << "[INCOMPLETE LUMINA INSTALLATION] fluxbox binary is missing - cannot continue";
  }else{
    QString confDir = QString( getenv("XDG_CONFIG_HOME"))+"/lumina-desktop";
    if(!QFile::exists(confDir)){ QDir dir(confDir); dir.mkpath(confDir); }
    if(!QFile::exists(confDir+"/fluxbox-init")){
      QStringList keys = LUtils::readFile(LOS::LuminaShare()+"/fluxbox-init-rc");
       keys = keys.replaceInStrings("${XDG_CONFIG_HOME}", QString( getenv("XDG_CONFIG_HOME")));
       LUtils::writeFile(confDir+"/fluxbox-init", keys, true);
      QFile::setPermissions(confDir+"/fluxbox-init", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup);
    }
    if(!QFile::exists(confDir+"/fluxbox-keys")){
      QStringList keys = LUtils::readFile(LOS::LuminaShare()+"/fluxbox-keys");
       keys = keys.replaceInStrings("${XDG_CONFIG_HOME}", QString( getenv("XDG_CONFIG_HOME")));
       LUtils::writeFile(confDir+"/fluxbox-keys", keys, true);
      QFile::setPermissions(confDir+"/fluxbox-keys", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup);
    }
    // FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
    if(!QFile::exists(QDir::homePath()+"/.fluxbox")){
      QDir dir; dir.mkpath(QDir::homePath()+"/.fluxbox");
    }
    QString cmd = "fluxbox -rc "+confDir+"/fluxbox-init -no-slit -no-toolbar";
    startProcess("wm", cmd, QStringList() << confDir+"/fluxbox-init" << confDir+"/fluxbox-keys");
  }
  //Compositing manager
  QSettings settings("lumina-desktop","sessionsettings");
  if(settings.value("enableCompositing",true).toBool()){
    if(LUtils::isValidBinary("compton")){
      QString set = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/compton.conf";
      if(!QFile::exists(set)){
        if(QFile::exists(LOS::LuminaShare()+"/compton.conf")){
	  QFile::copy(LOS::LuminaShare()+"/compton.conf", set);
        }
      }
      if(!QFile::exists(set)){
        qDebug() << "Using default compton settings";
        startProcess("compositing","compton");
      }else{
        //Auto-detect if GLX is available on the system and turn it on/off as needed
       bool startcompton = true;
       if(LUtils::isValidBinary("glxinfo")){
         bool hasAccel =! LUtils::getCmdOutput("glxinfo -B").filter("direct rendering:").filter("Yes").isEmpty();
         qDebug() << "Detected GPU Acceleration:" << hasAccel;
         QStringList info = LUtils::readFile(set);
         for(int i=0; i<info.length(); i++){
           if(info[i].section("=",0,0).simplified()=="backend"){ info[i] = QString("backend = \"")+ (hasAccel ? "glx" : "xrender")+"\""; break; } //replace this line
         }
         LUtils::writeFile(set, info, true);
         if( !hasAccel && settings.value("compositingWithGpuAccelOnly",true).toBool() ){ startcompton = false; }
       }
        if(startcompton){ startProcess("compositing","compton --config \""+set+"\"", QStringList() << set); }
      }
    }else if(LUtils::isValidBinary("xcompmgr") && !settings.value("compositingWithGpuAccelOnly",true).toBool() ){ startProcess("compositing","xcompmgr"); }
  }
  //Desktop Next
  startProcess("runtime","lumina-desktop");
  //ScreenSaver
  if(LUtils::isValidBinary("xscreensaver")){ startProcess("screensaver","xscreensaver -no-splash"); }

}
<commit_msg>add back ability to use different window manager<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2016, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "session.h"

#include <QObject>
#include <QProcess>
#include <QProcessEnvironment>
#include <QDebug>
#include <QSettings>
#include <QDir>

#include <LUtils.h>
#include <LuminaOS.h>

void LSession::stopall(){
  stopping = true;
  for(int i=0; i<PROCS.length(); i++){
    if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->kill(); }
  }
  QCoreApplication::processEvents();
  for(int i=0; i<PROCS.length(); i++){
    if(PROCS[i]->state()!=QProcess::NotRunning){ PROCS[i]->terminate(); }
  }
  QCoreApplication::exit(0);
}

void LSession::procFinished(){
  //Go through and check the status on all the procs to determine which one finished
  int stopped = 0;
  for(int i=0; i<PROCS.length(); i++){
    if(PROCS[i]->state()==QProcess::NotRunning){
      stopped++;
      if(!stopping){
        //See if this process is the main desktop binary
        if(PROCS[i]->objectName()=="runtime"){ stopall(); }
        //if(PROCS[i]->program().section("/",-1) == "lumina-desktop"){ stopall();  } //start closing down everything
        //else{ PROCS[i]->start(QIODevice::ReadOnly); } //restart the process
        break;
      }
    }
  }
  if(stopping && stopped==PROCS.length()){
    QCoreApplication::exit(0);
  }
}

void LSession::startProcess(QString ID, QString command, QStringList watchfiles){
  QString dir = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/logs";
  if(!QFile::exists(dir)){ QDir tmp(dir); tmp.mkpath(dir); }
  QString logfile = dir+"/"+ID+".log";
  if(QFile::exists(logfile+".old")){ QFile::remove(logfile+".old"); }
  if(QFile::exists(logfile)){ QFile::rename(logfile,logfile+".old"); }

  LProcess *proc = new LProcess(ID, watchfiles);
  proc->setProcessChannelMode(QProcess::MergedChannels);
  proc->setProcessEnvironment( QProcessEnvironment::systemEnvironment() );
  proc->setStandardOutputFile(logfile);
  proc->setObjectName(ID);
  if(ID=="runtime"){
    //Bypass for a hidden dbus file requirement for Qt itself (Qt 5.5.1+?)
    if(!QFile::exists("/etc/machine-id") && !QFile::exists("/var/db/dbus/machine-id")){
      if(LUtils::isValidBinary("dbus-uuidgen") && LUtils::runCmd("dbus-uuidgen --ensure") ){ } //good - the UUID was created successfully
      else if(LUtils::isValidBinary("dbus-launch")){ command.prepend("dbus-launch --exit-with-session "); }
      else{
        //create a simple DBUS UUID and put it in the universal-fallback location (OS-independent)
        // TO-DO - root vs user level permissions issue?
        qDebug() << "Could not find '/etc/machine-id' or '/var/db/dbus/machine-id': Qt will most likely crash. \nPlease run 'dbus-uuidgen --ensure' with root permissions to generate this file if Lumina does not start properly.";
      }
   }
  }
  proc->start(command, QIODevice::ReadOnly);
  connect(proc, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(procFinished()) );
  PROCS << proc;
}

void LSession::start(){
  //First check for a valid installation
  if(!LUtils::isValidBinary("lumina-desktop") ){
    exit(1);
  }
  QSettings sessionsettings("lumina-desktop","sessionsettings");
  QString WM = sessionsettings.value("WindowManager", "fluxbox").toString();
  //Window Manager First
  if(WM=="fluxbox"){
	  // FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
	  if( !LUtils::isValidBinary("fluxbox") ){
	    qDebug() << "[INCOMPLETE LUMINA INSTALLATION] fluxbox binary is missing - cannot continue";
	  }else{
	    QString confDir = QString( getenv("XDG_CONFIG_HOME"))+"/lumina-desktop";
	    if(!QFile::exists(confDir)){ QDir dir(confDir); dir.mkpath(confDir); }
	    if(!QFile::exists(confDir+"/fluxbox-init")){
	      QStringList keys = LUtils::readFile(LOS::LuminaShare()+"/fluxbox-init-rc");
	       keys = keys.replaceInStrings("${XDG_CONFIG_HOME}", QString( getenv("XDG_CONFIG_HOME")));
	       LUtils::writeFile(confDir+"/fluxbox-init", keys, true);
	      QFile::setPermissions(confDir+"/fluxbox-init", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup);
	    }
	    if(!QFile::exists(confDir+"/fluxbox-keys")){
	      QStringList keys = LUtils::readFile(LOS::LuminaShare()+"/fluxbox-keys");
	       keys = keys.replaceInStrings("${XDG_CONFIG_HOME}", QString( getenv("XDG_CONFIG_HOME")));
	       LUtils::writeFile(confDir+"/fluxbox-keys", keys, true);
	      QFile::setPermissions(confDir+"/fluxbox-keys", QFile::ReadOwner | QFile::WriteOwner | QFile::ReadUser | QFile::ReadOther | QFile::ReadGroup);
	    }
	    // FLUXBOX BUG BYPASS: if the ~/.fluxbox dir does not exist, it will ignore the given config file
	    if(!QFile::exists(QDir::homePath()+"/.fluxbox")){
	      QDir dir; dir.mkpath(QDir::homePath()+"/.fluxbox");
	    }
	    QString cmd = "fluxbox -rc "+confDir+"/fluxbox-init -no-slit -no-toolbar";
	    startProcess("wm", cmd, QStringList() << confDir+"/fluxbox-init" << confDir+"/fluxbox-keys");
	  }
	  //Compositing manager
	  QSettings settings("lumina-desktop","sessionsettings");
	  if(settings.value("enableCompositing",true).toBool()){
	    if(LUtils::isValidBinary("compton")){
	      QString set = QString(getenv("XDG_CONFIG_HOME"))+"/lumina-desktop/compton.conf";
	      if(!QFile::exists(set)){
		if(QFile::exists(LOS::LuminaShare()+"/compton.conf")){
		  QFile::copy(LOS::LuminaShare()+"/compton.conf", set);
		}
	      }
	      if(!QFile::exists(set)){
		qDebug() << "Using default compton settings";
		startProcess("compositing","compton");
	      }else{
		//Auto-detect if GLX is available on the system and turn it on/off as needed
	       bool startcompton = true;
	       if(LUtils::isValidBinary("glxinfo")){
		 bool hasAccel =! LUtils::getCmdOutput("glxinfo -B").filter("direct rendering:").filter("Yes").isEmpty();
		 qDebug() << "Detected GPU Acceleration:" << hasAccel;
		 QStringList info = LUtils::readFile(set);
		 for(int i=0; i<info.length(); i++){
		   if(info[i].section("=",0,0).simplified()=="backend"){ info[i] = QString("backend = \"")+ (hasAccel ? "glx" : "xrender")+"\""; break; } //replace this line
		 }
		 LUtils::writeFile(set, info, true);
		 if( !hasAccel && settings.value("compositingWithGpuAccelOnly",true).toBool() ){ startcompton = false; }
	       }
		if(startcompton){ startProcess("compositing","compton --config \""+set+"\"", QStringList() << set); }
	      }
	    }else if(LUtils::isValidBinary("xcompmgr") && !settings.value("compositingWithGpuAccelOnly",true).toBool() ){ startProcess("compositing","xcompmgr"); }
	  }
  } else {
	if(!LUtils::isValidBinary(WM)){
	  exit(1);
	}
	startProcess("wm", WM);
  }
  //Desktop Next
  startProcess("runtime","lumina-desktop");
  //ScreenSaver
  if(LUtils::isValidBinary("xscreensaver")){ startProcess("screensaver","xscreensaver -no-splash"); }

}
<|endoftext|>


<commit_before>#include <node.h>
#include <node_object_wrap.h>
#include <v8.h>

extern "C" {
extern void* hash_allocate (uint32_t seed);
extern void hash_free (void* hash);
extern int hash_block_size();
extern void hash_update(void* hash, void* key, int len);
extern void hash_remainder(void* hash, void* out);
}

using namespace v8;

class Hash : public node::ObjectWrap {
public:
    static void Initialize(Handle<Object> target);

protected:
    static Handle<Value>  New(const Arguments& args);
   /*static void HashUpdate(const FunctionCallbackInfo<Value>& args);
    static void HashDigest(const FunctionCallbackInfo<Value>& args);*/

    Hash () : hash_(NULL) {
    }

    ~Hash () {
        if (hash_) hash_free(hash_);
    }

private:
    void* hash_;
};

void Hash::Initialize (Handle<Object> target) {
    HandleScope scope;

    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->InstanceTemplate()->SetInternalFieldCount(1);

    target->Set(String::New("Hash"), t->GetFunction());
}

Handle<Value> Hash::New (const Arguments& args) {
    HandleScope scope;

   return ThrowException(Exception::Error(String::New("Must give hashtype string as argument")));
}

void init(Handle<Object> target) {
  Hash::Initialize(target);
}

NODE_MODULE(binding, init);
<commit_msg>Allocate and deallocate C hash.<commit_after>#include <node.h>
#include <node_object_wrap.h>
#include <v8.h>
#include <stdio.h>

extern "C" {
extern void* hash_allocate (uint32_t seed);
extern void hash_free (void* hash);
extern int hash_block_size();
extern void hash_update(void* hash, void* key, int len);
extern void hash_remainder(void* hash, void* out);
}

using namespace v8;

class Hash : public node::ObjectWrap {
public:
    static void Initialize(Handle<Object> target);

    bool HashInit (uint32_t seed) {
      return (hash_ = hash_allocate(seed)) != NULL;
    }

protected:
    static Handle<Value>  New(const Arguments& args);
   /*static void HashUpdate(const FunctionCallbackInfo<Value>& args);
    static void HashDigest(const FunctionCallbackInfo<Value>& args);*/

    Hash () : hash_(NULL) {
    }

    ~Hash () {
        printf("destroying\n");
        if (hash_) hash_free(hash_);
    }

private:
    void* hash_;
};

void Hash::Initialize (Handle<Object> target) {
    HandleScope scope;

    Local<FunctionTemplate> t = FunctionTemplate::New(New);

    t->InstanceTemplate()->SetInternalFieldCount(1);

    target->Set(String::New("Hash"), t->GetFunction());
}

Handle<Value> Hash::New (const Arguments& args) {
    HandleScope scope;
    uint32_t seed;

    if (args.Length() == 0 || !args[0]->IsNumber()) {
        seed = 0;
    } else {
        seed = args[0]->Uint32Value();
    }

    Hash* hash = new Hash();
    if (!hash->HashInit(seed)) {
        return ThrowException(Exception::Error(String::New(
          "Unable to allocate hash.")));
    }
    printf("here!\n");

    hash->Wrap(args.This());
    return args.This();
}

void init(Handle<Object> target) {
  Hash::Initialize(target);
}

NODE_MODULE(binding, init);
<|endoftext|>


<commit_before>/* -*- c-basic-offset: 2 -*- */
/*
  Copyright(C) 2010 Tetsuro IKEDA
  Copyright(C) 2011-2013 Kentoku SHIBA
  Copyright(C) 2011-2012 Kouhei Sutou <kou@clear-code.com>

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

  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

#include "mrn_path_mapper.hpp"

#include <string.h>

#include <mrn_mysql.h>

namespace mrn {
  char *PathMapper::default_path_prefix = NULL;
  char *PathMapper::default_mysql_data_home_path = NULL;

  PathMapper::PathMapper(const char *mysql_path,
                         const char *path_prefix,
                         const char *mysql_data_home_path)
    : mysql_path_(mysql_path),
      path_prefix_(path_prefix),
      mysql_data_home_path_(mysql_data_home_path) {
    db_path_[0] = '\0';
    db_name_[0] = '\0';
    table_name_[0] = '\0';
    mysql_table_name_[0] = '\0';
  }

  /**
   * "./${db}/${table}"                              ==> "${db}.mrn"
   * "./${db}/"                                      ==> "${db}.mrn"
   * "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0" ==>
   *   "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0.mrn"
   */
  const char *PathMapper::db_path() {
    if (db_path_[0] != '\0') {
      return db_path_;
    }

    if (mysql_path_[0] == FN_CURLIB && mysql_path_[1] == FN_LIBCHAR) {
      if (path_prefix_) {
        strcpy(db_path_, path_prefix_);
      }

      int i = 2, j = strlen(db_path_), len;
      len = strlen(mysql_path_);
      while (mysql_path_[i] != FN_LIBCHAR && i < len) {
        db_path_[j++] = mysql_path_[i++];
      }
      db_path_[j] = '\0';
    } else if (mysql_data_home_path_) {
      int len = strlen(mysql_path_);
      int mysql_data_home_len = strlen(mysql_data_home_path_);
      if (len > mysql_data_home_len &&
          !strncmp(mysql_path_, mysql_data_home_path_, mysql_data_home_len)) {
        int i = mysql_data_home_len, j;
        if (path_prefix_ && path_prefix_[0] == FN_LIBCHAR) {
          strcpy(db_path_, path_prefix_);
          j = strlen(db_path_);
        } else {
          memcpy(db_path_, mysql_data_home_path_, mysql_data_home_len);
          if (path_prefix_) {
            if (path_prefix_[0] == FN_CURLIB &&
                path_prefix_[1] == FN_LIBCHAR) {
              strcpy(&db_path_[mysql_data_home_len], &path_prefix_[2]);
            } else {
              strcpy(&db_path_[mysql_data_home_len], path_prefix_);
            }
            j = strlen(db_path_);
          } else {
            j = mysql_data_home_len;
          }
        }

        while (mysql_path_[i] != FN_LIBCHAR && i < len) {
          db_path_[j++] = mysql_path_[i++];
        }
        if (i == len) {
          memcpy(db_path_, mysql_path_, len);
        } else {
          db_path_[j] = '\0';
        }
      } else {
        strcpy(db_path_, mysql_path_);
      }
    } else {
      strcpy(db_path_, mysql_path_);
    }
    strcat(db_path_, MRN_DB_FILE_SUFFIX);
    return db_path_;
  }

  /**
   * "./${db}/${table}"                              ==> "${db}"
   * "./${db}/"                                      ==> "${db}"
   * "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0" ==>
   *   "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0"
   */
  const char *PathMapper::db_name() {
    if (db_name_[0] != '\0') {
      return db_name_;
    }

    if (mysql_path_[0] == FN_CURLIB && mysql_path_[1] == FN_LIBCHAR) {
      int i = 2, j = 0, len;
      len = strlen(mysql_path_);
      while (mysql_path_[i] != FN_LIBCHAR && i < len) {
        db_name_[j++] = mysql_path_[i++];
      }
      db_name_[j] = '\0';
    } else if (mysql_data_home_path_) {
      int len = strlen(mysql_path_);
      int mysql_data_home_len = strlen(mysql_data_home_path_);
      if (len > mysql_data_home_len &&
          !strncmp(mysql_path_, mysql_data_home_path_, mysql_data_home_len)) {
        int i = mysql_data_home_len, j = 0;
        while (mysql_path_[i] != FN_LIBCHAR && i < len) {
          db_name_[j++] = mysql_path_[i++];
        }
        if (i == len) {
          memcpy(db_name_, mysql_path_, len);
        } else {
          db_name_[j] = '\0';
        }
      } else {
        strcpy(db_name_, mysql_path_);
      }
    } else {
      strcpy(db_name_, mysql_path_);
    }
    return db_name_;
  }

  /**
   * "./${db}/${table}" ==> "${table}" (with encoding first '_')
   */
  const char *PathMapper::table_name() {
    if (table_name_[0] != '\0') {
      return table_name_;
    }

    int len = strlen(mysql_path_);
    int i = len, j = 0;
    for (; mysql_path_[--i] != FN_LIBCHAR ;) {}
    if (mysql_path_[i + 1] == '_') {
      table_name_[j++] = '@';
      table_name_[j++] = '0';
      table_name_[j++] = '0';
      table_name_[j++] = '5';
      table_name_[j++] = 'f';
      i++;
    }
    for (; i < len ;) {
      table_name_[j++] = mysql_path_[++i];
    }
    table_name_[j] = '\0';
    return table_name_;
  }

  /**
   * "./${db}/${table}" ==> "${table}" (without encoding first '_')
   */
  const char *PathMapper::mysql_table_name() {
    if (mysql_table_name_[0] != '\0') {
      return mysql_table_name_;
    }

    int len = strlen(mysql_path_);
    int i = len, j = 0;
    for (; mysql_path_[--i] != FN_LIBCHAR ;) {}
    for (; i < len ;) {
      mysql_table_name_[j++] = mysql_path_[++i];
    }
    mysql_table_name_[j] = '\0';
    return mysql_table_name_;
  }
}
<commit_msg>Simplify<commit_after>/* -*- c-basic-offset: 2 -*- */
/*
  Copyright(C) 2010 Tetsuro IKEDA
  Copyright(C) 2011-2013 Kentoku SHIBA
  Copyright(C) 2011-2012 Kouhei Sutou <kou@clear-code.com>

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

  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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include <mrn_mysql.h>

#include "mrn_path_mapper.hpp"

#include <string.h>

namespace mrn {
  char *PathMapper::default_path_prefix = NULL;
  char *PathMapper::default_mysql_data_home_path = NULL;

  PathMapper::PathMapper(const char *mysql_path,
                         const char *path_prefix,
                         const char *mysql_data_home_path)
    : mysql_path_(mysql_path),
      path_prefix_(path_prefix),
      mysql_data_home_path_(mysql_data_home_path) {
    db_path_[0] = '\0';
    db_name_[0] = '\0';
    table_name_[0] = '\0';
    mysql_table_name_[0] = '\0';
  }

  /**
   * "./${db}/${table}"                              ==> "${db}.mrn"
   * "./${db}/"                                      ==> "${db}.mrn"
   * "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0" ==>
   *   "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0.mrn"
   */
  const char *PathMapper::db_path() {
    if (db_path_[0] != '\0') {
      return db_path_;
    }

    if (mysql_path_[0] == FN_CURLIB && mysql_path_[1] == FN_LIBCHAR) {
      if (path_prefix_) {
        strcpy(db_path_, path_prefix_);
      }

      int i = 2, j = strlen(db_path_), len;
      len = strlen(mysql_path_);
      while (mysql_path_[i] != FN_LIBCHAR && i < len) {
        db_path_[j++] = mysql_path_[i++];
      }
      db_path_[j] = '\0';
    } else if (mysql_data_home_path_) {
      int len = strlen(mysql_path_);
      int mysql_data_home_len = strlen(mysql_data_home_path_);
      if (len > mysql_data_home_len &&
          !strncmp(mysql_path_, mysql_data_home_path_, mysql_data_home_len)) {
        int i = mysql_data_home_len, j;
        if (path_prefix_ && path_prefix_[0] == FN_LIBCHAR) {
          strcpy(db_path_, path_prefix_);
          j = strlen(db_path_);
        } else {
          memcpy(db_path_, mysql_data_home_path_, mysql_data_home_len);
          if (path_prefix_) {
            if (path_prefix_[0] == FN_CURLIB &&
                path_prefix_[1] == FN_LIBCHAR) {
              strcpy(&db_path_[mysql_data_home_len], &path_prefix_[2]);
            } else {
              strcpy(&db_path_[mysql_data_home_len], path_prefix_);
            }
            j = strlen(db_path_);
          } else {
            j = mysql_data_home_len;
          }
        }

        while (mysql_path_[i] != FN_LIBCHAR && i < len) {
          db_path_[j++] = mysql_path_[i++];
        }
        if (i == len) {
          memcpy(db_path_, mysql_path_, len);
        } else {
          db_path_[j] = '\0';
        }
      } else {
        strcpy(db_path_, mysql_path_);
      }
    } else {
      strcpy(db_path_, mysql_path_);
    }
    strcat(db_path_, MRN_DB_FILE_SUFFIX);
    return db_path_;
  }

  /**
   * "./${db}/${table}"                              ==> "${db}"
   * "./${db}/"                                      ==> "${db}"
   * "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0" ==>
   *   "/tmp/mysql-test/var/tmp/mysqld.1/#sql27c5_1_0"
   */
  const char *PathMapper::db_name() {
    if (db_name_[0] != '\0') {
      return db_name_;
    }

    if (mysql_path_[0] == FN_CURLIB && mysql_path_[1] == FN_LIBCHAR) {
      int i = 2, j = 0, len;
      len = strlen(mysql_path_);
      while (mysql_path_[i] != FN_LIBCHAR && i < len) {
        db_name_[j++] = mysql_path_[i++];
      }
      db_name_[j] = '\0';
    } else if (mysql_data_home_path_) {
      int len = strlen(mysql_path_);
      int mysql_data_home_len = strlen(mysql_data_home_path_);
      if (len > mysql_data_home_len &&
          !strncmp(mysql_path_, mysql_data_home_path_, mysql_data_home_len)) {
        int i = mysql_data_home_len, j = 0;
        while (mysql_path_[i] != FN_LIBCHAR && i < len) {
          db_name_[j++] = mysql_path_[i++];
        }
        if (i == len) {
          memcpy(db_name_, mysql_path_, len);
        } else {
          db_name_[j] = '\0';
        }
      } else {
        strcpy(db_name_, mysql_path_);
      }
    } else {
      strcpy(db_name_, mysql_path_);
    }
    return db_name_;
  }

  /**
   * "./${db}/${table}" ==> "${table}" (with encoding first '_')
   */
  const char *PathMapper::table_name() {
    if (table_name_[0] != '\0') {
      return table_name_;
    }

    int len = strlen(mysql_path_);
    int i = len, j = 0;
    for (; mysql_path_[--i] != FN_LIBCHAR ;) {}
    if (mysql_path_[i + 1] == '_') {
      table_name_[j++] = '@';
      table_name_[j++] = '0';
      table_name_[j++] = '0';
      table_name_[j++] = '5';
      table_name_[j++] = 'f';
      i++;
    }
    for (; i < len ;) {
      table_name_[j++] = mysql_path_[++i];
    }
    table_name_[j] = '\0';
    return table_name_;
  }

  /**
   * "./${db}/${table}" ==> "${table}" (without encoding first '_')
   */
  const char *PathMapper::mysql_table_name() {
    if (mysql_table_name_[0] != '\0') {
      return mysql_table_name_;
    }

    int len = strlen(mysql_path_);
    int i = len, j = 0;
    for (; mysql_path_[--i] != FN_LIBCHAR ;) {}
    for (; i < len ;) {
      mysql_table_name_[j++] = mysql_path_[++i];
    }
    mysql_table_name_[j] = '\0';
    return mysql_table_name_;
  }
}
<|endoftext|>


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

#include <doc.hxx>
#include <undobj.hxx>
#include <pam.hxx>

class SwTxtFld;
class SwField;
class SwMsgPoolItem;

class SwUndoField : public SwUndo
{
    ULONG nNodeIndex;
    xub_StrLen nOffset;

protected:
    SwDoc * pDoc;
    SwPosition GetPosition();

public:
    SwUndoField(const SwPosition & rPos);
    virtual ~SwUndoField();
};

class SwUndoFieldFromDoc : public SwUndoField
{
    SwField * pOldField, * pNewField;
    SwMsgPoolItem * pHnt;
    BOOL bUpdate;

public:
    SwUndoFieldFromDoc(const SwPosition & rPos, const SwField & aOldField,
                       const SwField & aNewField,
                       SwMsgPoolItem * pHnt, BOOL bUpdate);
    virtual ~SwUndoFieldFromDoc();

    virtual void Undo(SwUndoIter & rIt);
    virtual void Redo(SwUndoIter & rIt);
    virtual void Repeat(SwUndoIter & rIt);
};

class SwUndoFieldFromAPI : public SwUndoField
{
    com::sun::star::uno::Any aOldVal, aNewVal;
    BYTE nMId;

public:
    SwUndoFieldFromAPI(const SwPosition & rPos,
                       const com::sun::star::uno::Any & rOldVal,
                       const com::sun::star::uno::Any & rNewVal,
                       BYTE nMId);
    virtual ~SwUndoFieldFromAPI();

    virtual void Undo(SwUndoIter & rIt);
    virtual void Redo(SwUndoIter & rIt);
    virtual void Repeat(SwUndoIter & rIt);
};

#endif // _SW_UNDO_FIELD_HXX
<commit_msg>INTEGRATION: CWS writercorehandoff (1.3.466); FILE MERGED 2005/09/13 11:11:11 tra 1.3.466.3: RESYNC: (1.3-1.4); FILE MERGED 2005/07/13 13:23:41 fme 1.3.466.2: #i50348# Make SwDoc accessible via interfaces 2005/06/07 14:09:35 fme 1.3.466.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwUndoField.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:14:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SW_UNDO_FIELD_HXX
#define _SW_UNDO_FIELD_HXX

#include <undobj.hxx>

class SwDoc;
class SwField;
class SwMsgPoolItem;

class SwUndoField : public SwUndo
{
    ULONG nNodeIndex;
    xub_StrLen nOffset;

protected:
    SwDoc * pDoc;
    SwPosition GetPosition();

public:
    SwUndoField(const SwPosition & rPos);
    virtual ~SwUndoField();
};

class SwUndoFieldFromDoc : public SwUndoField
{
    SwField * pOldField, * pNewField;
    SwMsgPoolItem * pHnt;
    BOOL bUpdate;

public:
    SwUndoFieldFromDoc(const SwPosition & rPos, const SwField & aOldField,
                       const SwField & aNewField,
                       SwMsgPoolItem * pHnt, BOOL bUpdate);
    virtual ~SwUndoFieldFromDoc();

    virtual void Undo(SwUndoIter & rIt);
    virtual void Redo(SwUndoIter & rIt);
    virtual void Repeat(SwUndoIter & rIt);
};

class SwUndoFieldFromAPI : public SwUndoField
{
    com::sun::star::uno::Any aOldVal, aNewVal;
    BYTE nMId;

public:
    SwUndoFieldFromAPI(const SwPosition & rPos,
                       const com::sun::star::uno::Any & rOldVal,
                       const com::sun::star::uno::Any & rNewVal,
                       BYTE nMId);
    virtual ~SwUndoFieldFromAPI();

    virtual void Undo(SwUndoIter & rIt);
    virtual void Redo(SwUndoIter & rIt);
    virtual void Repeat(SwUndoIter & rIt);
};

#endif // _SW_UNDO_FIELD_HXX
<|endoftext|>


<commit_before>/*
 * opencog/learning/moses/moses/types.cc
 *
 * Copyright (C) 2002-2008 Novamente LLC
 * All Rights Reserved
 *
 * Written by Moshe Looks
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#include "types.h"
#include "complexity.h"

namespace opencog { namespace moses {

bool bscored_combo_tree_greater::operator()(const bscored_combo_tree& bs_tr1,
                                            const bscored_combo_tree& bs_tr2) const
{
    composite_score csc1 = get_composite_score(bs_tr1);
    composite_score csc2 = get_composite_score(bs_tr2);
    return (csc1 > csc2);
}

// the empty composite_score ctor returns the worst composite score
const composite_score worst_composite_score = composite_score();

composite_score::composite_score()
    : score(worst_score), complexity(worst_complexity),
      complexity_penalty(0.0), diversity_penalty(0.0),
      penalized_score(worst_score)
{}

composite_score& composite_score::operator=(const composite_score &r)
{
    score = r.score;
    complexity = r.complexity;
    penalized_score = r.penalized_score;
    complexity_penalty = r.complexity_penalty;
    diversity_penalty = r.diversity_penalty;
    return *this;
}

bool composite_score::operator<(const composite_score &r) const
{
    score_t lef = penalized_score;
    score_t rig = r.penalized_score;

    if (isnan(lef))
        return !isnan(rig);
    else
        return (lef < rig)
                // Note: I've tried to see if the addition below
                // increases the performance when there is no
                // complexity penalty and it doesn't, over 100 runs
                // solving 3-parity is actually .5s slower (which
                // probably has no statistical significance given it
                // takes 13s in average). But I don't want to conclude
                // too fast, it could have an impact on other
                // problems.
                or (lef == rig and complexity > r.complexity);
}

} // ~namespace moses
} // ~namespace opencog
<commit_msg>moses: put back some code I'd removed, now that I know why it was there...<commit_after>/*
 * opencog/learning/moses/moses/types.cc
 *
 * Copyright (C) 2002-2008 Novamente LLC
 * All Rights Reserved
 *
 * Written by Moshe Looks
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#include "types.h"
#include "complexity.h"

namespace opencog { namespace moses {

bool bscored_combo_tree_greater::operator()(const bscored_combo_tree& bs_tr1,
                                            const bscored_combo_tree& bs_tr2) const
{
    composite_score csc1 = get_composite_score(bs_tr1);
    composite_score csc2 = get_composite_score(bs_tr2);
    bool gt = (csc1 > csc2);
    if (gt) return true;
    bool lt = (csc1 < csc2);
    if (lt) return false;

    // If we are here, then they are equal.  We are desperate to break
    // a tie, because otherwise, the bscored_combo_tree_set will discard
    // anything that compares equal, and we really don't want that.
    score_t sc1 = get_score(csc1);
    score_t sc2 = get_score(csc2);
    gt = (sc1 > sc2);
    if (gt) return true;
    lt = (sc1 < sc2);
    if (lt) return false;

    // Arghh, still tied!  The above already used complexity to break
    // the tie.  We're grasping at straws, here.
    return size_tree_order<vertex>()(get_tree(bs_tr1), get_tree(bs_tr2));
}

// the empty composite_score ctor returns the worst composite score
const composite_score worst_composite_score = composite_score();

composite_score::composite_score()
    : score(worst_score), complexity(worst_complexity),
      complexity_penalty(0.0), diversity_penalty(0.0),
      penalized_score(worst_score)
{}

composite_score& composite_score::operator=(const composite_score &r)
{
    score = r.score;
    complexity = r.complexity;
    penalized_score = r.penalized_score;
    complexity_penalty = r.complexity_penalty;
    diversity_penalty = r.diversity_penalty;
    return *this;
}

bool composite_score::operator<(const composite_score &r) const
{
    score_t lef = penalized_score;
    score_t rig = r.penalized_score;

    if (isnan(lef))
        return !isnan(rig);
    else
        return (lef < rig)
                // Note: I've tried to see if the addition below
                // increases the performance when there is no
                // complexity penalty and it doesn't, over 100 runs
                // solving 3-parity is actually .5s slower (which
                // probably has no statistical significance given it
                // takes 13s in average). But I don't want to conclude
                // too fast, it could have an impact on other
                // problems.
                or (lef == rig and complexity > r.complexity);
}

} // ~namespace moses
} // ~namespace opencog
<|endoftext|>