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

#include <LuminaXDG.h>
#include <QDesktopWidget>

#define DEBUG 0

// ===================
//      PUBLIC
// ===================
LDesktopPluginSpace::LDesktopPluginSpace(QWidget *parent) : QWidget(parent){
  this->setObjectName("LuminaDesktopPluginSpace");
  this->setStyleSheet("QWidget#LuminaDesktopPluginSpace{ border: none; background: transparent; }");
  this->setAcceptDrops(true);
  this->setContextMenuPolicy(Qt::NoContextMenu);
  this->setMouseTracking(true);
  TopToBottom = true;
  plugsettings = LSession::handle()->DesktopPluginSettings();

}

LDesktopPluginSpace::~LDesktopPluginSpace(){

}

void LDesktopPluginSpace::LoadItems(QStringList plugs, QStringList files){
  if(DEBUG){ qDebug() << "Loading Desktop Items:" << plugs << files; }
  bool changes = false;
  if(plugs != plugins){ plugins = plugs; changes = true; }
  if(files != deskitems){ deskitems = files; changes = true; }
  if(changes){ QTimer::singleShot(0,this, SLOT(reloadPlugins())); }
}

void LDesktopPluginSpace::SetIconSize(int size){
  if(DEBUG){ qDebug() << "Set Desktop Icon Size:" << size; }
  QSize newsize = calculateItemSize(size);
  itemSize = newsize; //save this for all the later icons which are generated (grid size)
  UpdateGeom();
  //Now re-set the item icon size
  QTimer::singleShot(0,this, SLOT(reloadPlugins()) );
}

void LDesktopPluginSpace::cleanup(){
  //Perform any final cleanup actions here
  for(int i=0; i<ITEMS.length(); i++){
    delete ITEMS.takeAt(i);
    i--;
  }
  plugins.clear();
  deskitems.clear();
}
// ===================
//      PUBLIC SLOTS
// ===================
void LDesktopPluginSpace::UpdateGeom(){
  if(DEBUG){ qDebug() << "Update Desktop Geom:"; }
  //Currently no special checks - might need to add validation of all current plugin geometries in the future
}

// ===================
//          PRIVATE
// ===================
QSize LDesktopPluginSpace::calculateItemSize(int icosize){
  //Note: This returns the size in numbers of cells (width = columnspan, height = rowspan)
  QSize sz;
    sz.setWidth(1.8*icosize);
    sz.setWidth( RoundUp(sz.width()/GRIDSIZE)); //always round up to cell numbers
    sz.setHeight(icosize+ 2.3*this->fontMetrics().height() );
    sz.setHeight( RoundUp(sz.height()/GRIDSIZE)); //always round up to cell number
  return sz;
}

void LDesktopPluginSpace::addDesktopItem(QString filepath){
  addDesktopPlugin("applauncher::"+filepath+"---dlink"+QString::number(LSession::handle()->desktop()->screenNumber(this)) );
}

void LDesktopPluginSpace::addDesktopPlugin(QString plugID){
  //This is used for generic plugins (QWidget-based)
  if(DEBUG){ qDebug() << "Adding Desktop Plugin:" << plugID; }
  LDPlugin *plug = NewDP::createPlugin(plugID, this);
    plug->setWhatsThis(plugID);
  //Now get the geometry for the plugin
  QRect geom = plug->loadPluginGeometry(); //in grid coords
  if(geom.isNull()){
    //No previous location - need to calculate initial geom
    QSize sz = plug->sizeHint();
    if(plugID.startsWith("applauncher::") ){ sz = itemSize*GRIDSIZE; }
    geom.setWidth( RoundUp(sz.width()/GRIDSIZE) );
    geom.setHeight( RoundUp(sz.height()/GRIDSIZE) );
    geom.moveTo( findOpenSpot(geom.width(), geom.height()) );
  }else if(!ValidGeometry(plugID, gridToGeom(geom)) ){
    //Find a new location for the plugin (saved location is invalid)
    QPoint pt = findOpenSpot(geom.width(), geom.height(), geom.y()-2, geom.x()-2); //try to get it within the same general area
    geom.moveTo(pt);
  }
  if(geom.x() < 0 || geom.y() < 0){
    qDebug() << "No available space for desktop plugin:" << plugID << " - IGNORING";
    delete plug;
  }else{
    if(DEBUG){ qDebug() <<  " - New Plugin Geometry (grid):" << geom; }
    //Now place the item in the proper spot/size
    plug->setGeometry( gridToGeom(geom) );
    plug->show();
    if(DEBUG){ qDebug() << " - New Plugin Geometry (px):" << plug->geometry(); }
    ITEMS << plug;
    connect(plug, SIGNAL(StartMoving(QString)), this, SLOT(StartItemMove(QString)) );
    connect(plug, SIGNAL(StartResizing(QString)), this, SLOT(StartItemResize(QString)) );
    connect(plug, SIGNAL(RemovePlugin(QString)), this, SLOT(RemoveItem(QString)) );
  }
}

QPoint LDesktopPluginSpace::findOpenSpot(int gridwidth, int gridheight, int startRow, int startCol){
  //Note about the return QPoint: x() is the column number, y() is the row number
  QPoint pt(0,0);
  int row = startRow; int col = startCol;
  if(row<0){ row = 0; } //just in case - since this can be recursively called
  if(col<0){ col = 0; } //just in case - since this can be recursively called
  bool found = false;
  int rowCount, colCount;
  rowCount = RoundUp(this->height()/GRIDSIZE);
  colCount = RoundUp(this->width()/GRIDSIZE);
  QRect geom(0, 0, gridwidth*GRIDSIZE, gridheight*GRIDSIZE); //origin point will be adjusted in a moment
  if(DEBUG){ qDebug() << "Search for plugin space:" << rowCount << colCount << gridheight << gridwidth << this->size(); }
  if(TopToBottom){
    //Arrange Top->Bottom
    while(col<(colCount-gridwidth) && !found){
      while(row<(rowCount-gridheight) && !found){
        bool ok = true;
        geom.moveTo(col*GRIDSIZE, row*GRIDSIZE);
	//qDebug() << " - Check Geom:" << geom << col << row;
        //Check all the existing items to ensure no overlap
        for(int i=0; i<ITEMS.length() && ok; i++){
          if(geom.intersects(ITEMS[i]->geometry())){
            //Collision - move the next searchable row/column index
	    ok = false;
	    row = posToGrid(ITEMS[i]->geometry().bottomLeft()).y(); //use bottom edge for next search
	  }
        }
        if(ok){ pt = QPoint(col,row); found = true; } //found an open spot
        row++;
      }
      if(!found){ col++; row=0; } //go to the next column
    }
  }else{
    //Arrange Left->Right
    while(row<(rowCount-gridheight) && !found){
      while(col<(colCount-gridwidth) && !found){
        bool ok = true;
        geom.moveTo(col*GRIDSIZE, row*GRIDSIZE);
        //Check all the existing items to ensure no overlap
        for(int i=0; i<ITEMS.length() && ok; i++){
          if(geom.intersects(ITEMS[i]->geometry())){
            //Collision - move the next searchable row/column index
	    ok = false;
	    col = posToGrid(ITEMS[i]->geometry().topRight()).x(); // Fill according to row/column
	  }
        }
        if(ok){ pt = QPoint(col,row); found = true; } //found an open spot
        else{ col++; }
      }
      if(!found){ row++; col=0;} //go to the next row
    }
  }
  if(!found){
    //Decrease the size of the item by 1x1 grid points and try again
    if(gridwidth>2 && gridheight>2){
      pt = findOpenSpot(gridwidth-1, gridheight-1, 0, 0);
    }else{
      pt.setX(-1); pt.setY(-1); //invalid
      qDebug() << "Could not find an open spot for a desktop plugin:" << gridwidth << gridheight << startRow << startCol;
    }
  }
  return pt;
}

// ===================
//     PRIVATE SLOTS
// ===================
void LDesktopPluginSpace::reloadPlugins(){
  //Remove any plugins as necessary
  QStringList plugs = plugins;
  QStringList items = deskitems;
  for(int i=0; i<ITEMS.length(); i++){
    if(plugs.contains(ITEMS[i]->whatsThis())){ plugs.removeAll(ITEMS[i]->whatsThis()); }
    else if(ITEMS[i]->whatsThis().contains("---dlink") && items.contains(ITEMS[i]->whatsThis().section("---",0,0).section("::",1,50)) ){
      //Account for the variation in the Plugin ID for desktop files
      items.removeAll(ITEMS[i]->whatsThis().section("---",0,0).section("::",1,50));
    }else{ ITEMS[i]->removeSettings(true); delete ITEMS.takeAt(i);  i--; } //this is considered a permanent removal (cleans settings)
  }

  //Now create any new items
  //First load the plugins (almost always have fixed locations)
  for(int i=0; i<plugs.length(); i++){
    addDesktopPlugin(plugs[i]);
  }
  //Now load the desktop shortcuts (fill in the gaps as needed)
  for(int i=0; i<items.length(); i++){
    addDesktopItem(items[i]);
  }
}
<commit_msg>Get rid of an extra empty grid space between desktop items.<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2015, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "LDesktopPluginSpace.h"
#include "LSession.h"
#include "desktop-plugins/NewDP.h"

#include <LuminaXDG.h>
#include <QDesktopWidget>

#define DEBUG 0

// ===================
//      PUBLIC
// ===================
LDesktopPluginSpace::LDesktopPluginSpace(QWidget *parent) : QWidget(parent){
  this->setObjectName("LuminaDesktopPluginSpace");
  this->setStyleSheet("QWidget#LuminaDesktopPluginSpace{ border: none; background: transparent; }");
  this->setAcceptDrops(true);
  this->setContextMenuPolicy(Qt::NoContextMenu);
  this->setMouseTracking(true);
  TopToBottom = true;
  plugsettings = LSession::handle()->DesktopPluginSettings();

}

LDesktopPluginSpace::~LDesktopPluginSpace(){

}

void LDesktopPluginSpace::LoadItems(QStringList plugs, QStringList files){
  if(DEBUG){ qDebug() << "Loading Desktop Items:" << plugs << files; }
  bool changes = false;
  if(plugs != plugins){ plugins = plugs; changes = true; }
  if(files != deskitems){ deskitems = files; changes = true; }
  if(changes){ QTimer::singleShot(0,this, SLOT(reloadPlugins())); }
}

void LDesktopPluginSpace::SetIconSize(int size){
  if(DEBUG){ qDebug() << "Set Desktop Icon Size:" << size; }
  QSize newsize = calculateItemSize(size);
  itemSize = newsize; //save this for all the later icons which are generated (grid size)
  UpdateGeom();
  //Now re-set the item icon size
  QTimer::singleShot(0,this, SLOT(reloadPlugins()) );
}

void LDesktopPluginSpace::cleanup(){
  //Perform any final cleanup actions here
  for(int i=0; i<ITEMS.length(); i++){
    delete ITEMS.takeAt(i);
    i--;
  }
  plugins.clear();
  deskitems.clear();
}
// ===================
//      PUBLIC SLOTS
// ===================
void LDesktopPluginSpace::UpdateGeom(){
  if(DEBUG){ qDebug() << "Update Desktop Geom:"; }
  //Currently no special checks - might need to add validation of all current plugin geometries in the future
}

// ===================
//          PRIVATE
// ===================
QSize LDesktopPluginSpace::calculateItemSize(int icosize){
  //Note: This returns the size in numbers of cells (width = columnspan, height = rowspan)
  QSize sz;
    sz.setWidth(1.8*icosize);
    sz.setWidth( RoundUp(sz.width()/GRIDSIZE)); //always round up to cell numbers
    sz.setHeight(icosize+ 2.3*this->fontMetrics().height() );
    sz.setHeight( RoundUp(sz.height()/GRIDSIZE)); //always round up to cell number
  return sz;
}

void LDesktopPluginSpace::addDesktopItem(QString filepath){
  addDesktopPlugin("applauncher::"+filepath+"---dlink"+QString::number(LSession::handle()->desktop()->screenNumber(this)) );
}

void LDesktopPluginSpace::addDesktopPlugin(QString plugID){
  //This is used for generic plugins (QWidget-based)
  if(DEBUG){ qDebug() << "Adding Desktop Plugin:" << plugID; }
  LDPlugin *plug = NewDP::createPlugin(plugID, this);
    plug->setWhatsThis(plugID);
  //Now get the geometry for the plugin
  QRect geom = plug->loadPluginGeometry(); //in grid coords
  if(geom.isNull()){
    //No previous location - need to calculate initial geom
    QSize sz = plug->sizeHint();
    if(plugID.startsWith("applauncher::") ){ sz = itemSize*GRIDSIZE; }
    geom.setWidth( RoundUp(sz.width()/GRIDSIZE) );
    geom.setHeight( RoundUp(sz.height()/GRIDSIZE) );
    geom.moveTo( findOpenSpot(geom.width(), geom.height()) );
  }else if(!ValidGeometry(plugID, gridToGeom(geom)) ){
    //Find a new location for the plugin (saved location is invalid)
    QPoint pt = findOpenSpot(geom.width(), geom.height(), geom.y()-2, geom.x()-2); //try to get it within the same general area
    geom.moveTo(pt);
  }
  if(geom.x() < 0 || geom.y() < 0){
    qDebug() << "No available space for desktop plugin:" << plugID << " - IGNORING";
    delete plug;
  }else{
    if(DEBUG){ qDebug() <<  " - New Plugin Geometry (grid):" << geom; }
    //Now place the item in the proper spot/size
    plug->setGeometry( gridToGeom(geom) );
    plug->show();
    if(DEBUG){ qDebug() << " - New Plugin Geometry (px):" << plug->geometry(); }
    ITEMS << plug;
    connect(plug, SIGNAL(StartMoving(QString)), this, SLOT(StartItemMove(QString)) );
    connect(plug, SIGNAL(StartResizing(QString)), this, SLOT(StartItemResize(QString)) );
    connect(plug, SIGNAL(RemovePlugin(QString)), this, SLOT(RemoveItem(QString)) );
  }
}

QPoint LDesktopPluginSpace::findOpenSpot(int gridwidth, int gridheight, int startRow, int startCol){
  //Note about the return QPoint: x() is the column number, y() is the row number
  QPoint pt(0,0);
  int row = startRow; int col = startCol;
  if(row<0){ row = 0; } //just in case - since this can be recursively called
  if(col<0){ col = 0; } //just in case - since this can be recursively called
  bool found = false;
  int rowCount, colCount;
  rowCount = RoundUp(this->height()/GRIDSIZE);
  colCount = RoundUp(this->width()/GRIDSIZE);
  QRect geom(0, 0, gridwidth*GRIDSIZE, gridheight*GRIDSIZE); //origin point will be adjusted in a moment
  if(DEBUG){ qDebug() << "Search for plugin space:" << rowCount << colCount << gridheight << gridwidth << this->size(); }
  if(TopToBottom){
    //Arrange Top->Bottom
    while(col<(colCount-gridwidth) && !found){
      while(row<(rowCount-gridheight) && !found){
        bool ok = true;
        geom.moveTo(col*GRIDSIZE, row*GRIDSIZE);
	//qDebug() << " - Check Geom:" << geom << col << row;
        //Check all the existing items to ensure no overlap
        for(int i=0; i<ITEMS.length() && ok; i++){
          if(geom.intersects(ITEMS[i]->geometry())){
            //Collision - move the next searchable row/column index
	    ok = false;
	    row = posToGrid(ITEMS[i]->geometry().bottomLeft()).y(); //use bottom edge for next search
	  }
        }
        if(ok){ pt = QPoint(col,row); found = true; } //found an open spot
        //else{ row++; }
      }
      if(!found){ col++; row=0; } //go to the next column
    }
  }else{
    //Arrange Left->Right
    while(row<(rowCount-gridheight) && !found){
      while(col<(colCount-gridwidth) && !found){
        bool ok = true;
        geom.moveTo(col*GRIDSIZE, row*GRIDSIZE);
        //Check all the existing items to ensure no overlap
        for(int i=0; i<ITEMS.length() && ok; i++){
          if(geom.intersects(ITEMS[i]->geometry())){
            //Collision - move the next searchable row/column index
	    ok = false;
	    col = posToGrid(ITEMS[i]->geometry().topRight()).x(); // Fill according to row/column
	  }
        }
        if(ok){ pt = QPoint(col,row); found = true; } //found an open spot
        //else{ col++; }
      }
      if(!found){ row++; col=0;} //go to the next row
    }
  }
  if(!found){
    //Decrease the size of the item by 1x1 grid points and try again
    if(gridwidth>2 && gridheight>2){
      pt = findOpenSpot(gridwidth-1, gridheight-1, 0, 0);
    }else{
      pt.setX(-1); pt.setY(-1); //invalid
      qDebug() << "Could not find an open spot for a desktop plugin:" << gridwidth << gridheight << startRow << startCol;
    }
  }
  return pt;
}

// ===================
//     PRIVATE SLOTS
// ===================
void LDesktopPluginSpace::reloadPlugins(){
  //Remove any plugins as necessary
  QStringList plugs = plugins;
  QStringList items = deskitems;
  for(int i=0; i<ITEMS.length(); i++){
    if(plugs.contains(ITEMS[i]->whatsThis())){ plugs.removeAll(ITEMS[i]->whatsThis()); }
    else if(ITEMS[i]->whatsThis().contains("---dlink") && items.contains(ITEMS[i]->whatsThis().section("---",0,0).section("::",1,50)) ){
      //Account for the variation in the Plugin ID for desktop files
      items.removeAll(ITEMS[i]->whatsThis().section("---",0,0).section("::",1,50));
    }else{ ITEMS[i]->removeSettings(true); delete ITEMS.takeAt(i);  i--; } //this is considered a permanent removal (cleans settings)
  }

  //Now create any new items
  //First load the plugins (almost always have fixed locations)
  for(int i=0; i<plugs.length(); i++){
    addDesktopPlugin(plugs[i]);
  }
  //Now load the desktop shortcuts (fill in the gaps as needed)
  for(int i=0; i<items.length(); i++){
    addDesktopItem(items[i]);
  }
}
<|endoftext|>


<commit_before>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

#ifndef MED_Utilities_HeaderFile
#define MED_Utilities_HeaderFile

#include "SMESH_DriverUNV.hxx"

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <cassert>
#include <cstdlib>

namespace UNV{
  using namespace std;

  const size_t theMaxLineLen = 82;

  class MESHDRIVERUNV_EXPORT PrefixPrinter{
    static int myCounter;
  public:
    PrefixPrinter();
    ~PrefixPrinter();

    static string GetPrefix();
  };

  /**
   * @returns \p false when error occured, \p true otherwise.
   * Adjusts the \p in_stream to the beginning of the
   * dataset \p ds_name.
   */
  inline bool beginning_of_dataset(std::istream& in_file, const std::string& ds_name)
  {
    assert (in_file.good());
    assert (!ds_name.empty());

    std::string olds, news;

    in_file.seekg(0);
    while(true){
      in_file >> olds >> news;
      /*
       * a "-1" followed by a number means the beginning of a dataset
       * stop combing at the end of the file
       */
      while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() ){
        olds = news;
        in_file >> news;
      }
      if(in_file.eof())
      {
        in_file.clear();
        return false;
      }
      if (news == ds_name)
        return true;
    }
    // should never end up here
    return false;
  }

  /**
   * Method for converting exponential notation
   * from "D" to "e", for example
   * \p 3.141592654D+00 \p --> \p 3.141592654e+00
   * in order to make it readable for C++.
   */
  inline double D_to_e(std::string& number)
  {
    /* find "D" in string, start looking at
     * 6th element, to improve speed.
     * We dont expect a "D" earlier
     */
    const int position = number.find("D",6);
    if(position != std::string::npos){
      number.replace(position, 1, "e");
    }
    return atof (number.c_str());
  }

  /**
   * @returns \p false when file is incorrect, \p true otherwise.
   * Check file with name \p theFileName for correct terminate
   * string, i.e. the next to the last line is equal to "    -1",
   */
  inline bool check_file(const std::string theFileName)
  {
    std::ifstream in_stream(theFileName.c_str());
    if (!in_stream)
      return false;
    std::string olds, news;
    while (!in_stream.eof()){
      olds = news;
      std::getline(in_stream, news, '\n');
    }
    return (olds == "    -1");
  }

  /*!
   * \brief reads a whole line
   *  \param in_stream - source stream
   *  \param next - if true, first reads the current line up to the end
   *  which is necessary after reading using >> operator
   *  \retval std::string - the result line
   */
  inline std::string read_line(std::ifstream& in_stream, const bool next=true)
  {
    char line[theMaxLineLen];
    in_stream.getline( line, theMaxLineLen );
    if ( next )
      in_stream.getline( line, theMaxLineLen );

    std::string resLine = line;
    if ( resLine.size() > 0 && resLine[ resLine.size()-1 ] == '\r' )
      resLine.resize( resLine.size()-1 );
    return line;
  }
};

#ifndef MESSAGE

#define MESSAGE(msg) std::cout<<__FILE__<<"["<<__LINE__<<"]::"<<msg<<endl;

#define BEGMSG(msg) std::cout<<UNV::PrefixPrinter::GetPrefix()<<msg

#define ADDMSG(msg) std::cout<<msg

#endif

#ifndef EXCEPTION

#define EXCEPTION(TYPE, MSG) {\
  std::ostringstream aStream;\
  aStream<<__FILE__<<"["<<__LINE__<<"]::"<<MSG;\
  throw TYPE(aStream.str());\
}

#endif

#endif
<commit_msg>0022218: EDF 2638 SMESH: Issue when importing UNV file<commit_after>// Copyright (C) 2007-2013  CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//

#ifndef MED_Utilities_HeaderFile
#define MED_Utilities_HeaderFile

#include "SMESH_DriverUNV.hxx"

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <cassert>
#include <cstdlib>

namespace UNV{
  using namespace std;

  const size_t theMaxLineLen = 82; // 80 for text + 2 for "\r\n"

  class MESHDRIVERUNV_EXPORT PrefixPrinter{
    static int myCounter;
  public:
    PrefixPrinter();
    ~PrefixPrinter();

    static string GetPrefix();
  };

  /**
   * @returns \p false when error occured, \p true otherwise.
   * Adjusts the \p in_stream to the beginning of the
   * dataset \p ds_name.
   */
  inline bool beginning_of_dataset(std::istream& in_file, const std::string& ds_name)
  {
    assert (in_file.good());
    assert (!ds_name.empty());

    std::string olds, news;

    in_file.seekg(0);
    while(true){
      in_file >> olds >> news;
      /*
       * a "-1" followed by a number means the beginning of a dataset
       * stop combing at the end of the file
       */
      while( ((olds != "-1") || (news == "-1") ) && !in_file.eof() ){
        olds = news;
        in_file >> news;
      }
      if(in_file.eof())
      {
        in_file.clear();
        return false;
      }
      if (news == ds_name)
        return true;
    }
    // should never end up here
    return false;
  }

  /**
   * Method for converting exponential notation
   * from "D" to "e", for example
   * \p 3.141592654D+00 \p --> \p 3.141592654e+00
   * in order to make it readable for C++.
   */
  inline double D_to_e(std::string& number)
  {
    /* find "D" in string, start looking at
     * 6th element, to improve speed.
     * We dont expect a "D" earlier
     */
    const int position = number.find("D",6);
    if(position != std::string::npos){
      number.replace(position, 1, "e");
    }
    return atof (number.c_str());
  }

  /**
   * @returns \p false when file is incorrect, \p true otherwise.
   * Check file with name \p theFileName for correct terminate
   * string, i.e. the next to the last line is equal to "    -1",
   */
  inline bool check_file(const std::string theFileName)
  {
    std::ifstream in_stream(theFileName.c_str());
    if (!in_stream)
      return false;
    std::string olds, news;
    while (!in_stream.eof()){
      olds = news;
      std::getline(in_stream, news, '\n');
    }
    return (olds == "    -1");
  }

  /*!
   * \brief reads a whole line
   *  \param in_stream - source stream
   *  \param next - if true, first reads the current line up to the end
   *  which is necessary after reading using >> operator
   *  \retval std::string - the result line
   */
  inline std::string read_line(std::ifstream& in_stream, const bool next=true)
  {
    char line[theMaxLineLen];
    in_stream.getline( line, theMaxLineLen );
    if ( next )
      in_stream.getline( line, theMaxLineLen );

    std::string resLine = line;
    if ( resLine.size() > 0 && resLine[ resLine.size()-1 ] == '\r' )
      resLine.resize( resLine.size()-1 );
    return line;
  }
};

#ifndef MESSAGE

#define MESSAGE(msg) std::cout<<__FILE__<<"["<<__LINE__<<"]::"<<msg<<endl;

#define BEGMSG(msg) std::cout<<UNV::PrefixPrinter::GetPrefix()<<msg

#define ADDMSG(msg) std::cout<<msg

#endif

#ifndef EXCEPTION

#define EXCEPTION(TYPE, MSG) {\
  std::ostringstream aStream;\
  aStream<<__FILE__<<"["<<__LINE__<<"]::"<<MSG;\
  throw TYPE(aStream.str());\
}

#endif

#endif
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIOpenGLGeometryBuffer.cpp
    created:    Wed, 8th Feb 2012
    author:     Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include <GL/glew.h>

#include "glm/glm.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RenderEffect.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ShaderParameterBindings.h"
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h"
#include "CEGUI/RendererModules/OpenGL/GL3ShaderWrapper.h"

#define BUFFER_OFFSET(i) ((char *)NULL + (i))

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner, CEGUI::RefCounted<RenderMaterial> renderMaterial) :
    OpenGLGeometryBufferBase(owner, renderMaterial),
    d_glStateChanger(owner.getOpenGLStateChanger()),
    d_bufferSize(0)
{
    initialiseVertexBuffers();
}

//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()
{
    deinitialiseOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::draw() const
{
    if(d_vertexData.empty())
        return;

    CEGUI::Rectf viewPort = d_owner->getActiveViewPort();

    if (d_clippingActive)
    {
        d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),
            static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),
            static_cast<GLint>(d_clipRect.getWidth()),
            static_cast<GLint>(d_clipRect.getHeight()));

        d_glStateChanger->enable(GL_SCISSOR_TEST);
    }
    else
        d_glStateChanger->disable(GL_SCISSOR_TEST);

    // apply the transformations we need to use.
    if (!d_matrixValid)
        updateMatrix();

    CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();
    // Set the ModelViewProjection matrix in the bindings
    glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;
    shaderParameterBindings->setParameter("modelViewPerspMatrix", modelViewProjectionMatrix);

    // activate desired blending mode
    d_owner->setupRenderingBlendMode(d_blendMode);

    // Bind our vao
    d_glStateChanger->bindVertexArray(d_verticesVAO);

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        d_renderMaterial->prepareForRendering();

        // draw the geometry
        drawDependingOnFillRule();
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::reset()
{
    OpenGLGeometryBufferBase::reset();
    updateOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::initialiseVertexBuffers()
{
    glGenVertexArrays(1, &d_verticesVAO);
    d_glStateChanger->bindVertexArray(d_verticesVAO);

    // Generate and bind position vbo
    glGenBuffers(1, &d_verticesVBO);
    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_STATIC_DRAW);

    // Unbind Vertex Attribute Array (VAO)
    d_glStateChanger->bindVertexArray(0);

    // Unbind array and element array buffers
    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, 0);
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::finaliseVertexAttributes()
{
    //We need to bind both of the following calls
    d_glStateChanger->bindVertexArray(d_verticesVAO);
    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    GLsizei stride = getVertexAttributeElementCount() * sizeof(GL_FLOAT);

    CEGUI::OpenGL3ShaderWrapper* gl3_shader_wrapper = static_cast<CEGUI::OpenGL3ShaderWrapper*>(d_renderMaterial->getShaderWrapper());

    //Update the vertex attrib pointers of the vertex array object depending on the saved attributes
    int dataOffset = 0;
    const size_t attribute_count = d_vertexAttributes.size();
    for (size_t i = 0; i < attribute_count; ++i)
    {
        switch(d_vertexAttributes.at(i))
        {
        case VAT_POSITION0:
            {
                GLint shader_pos_loc = gl3_shader_wrapper->getAttributeLocation("inPosition");
                glVertexAttribPointer(shader_pos_loc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
                glEnableVertexAttribArray(shader_pos_loc);
                dataOffset += 3;
            }
            break;
        case VAT_COLOUR0:
            {
                GLint shader_colour_loc = gl3_shader_wrapper->getAttributeLocation("inColour");
                glVertexAttribPointer(shader_colour_loc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
                glEnableVertexAttribArray(shader_colour_loc);
                dataOffset += 4;
            }
            break;
        case VAT_TEXCOORD0:
            {
                GLint texture_coord_loc = gl3_shader_wrapper->getAttributeLocation("inTexCoord");
                glVertexAttribPointer(texture_coord_loc, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
                glEnableVertexAttribArray(texture_coord_loc);
                dataOffset += 2;
            }
            break;
        default:
            break;
        }
    }
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()
{
    glDeleteVertexArrays(1, &d_verticesVAO);
    glDeleteBuffers(1, &d_verticesVBO);
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::updateOpenGLBuffers()
{
    bool needNewBuffer = false;
    size_t vertexCount = d_vertexData.size();

    if(d_bufferSize < vertexCount)
    {
        needNewBuffer = true;
        d_bufferSize = vertexCount;
    }

    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    float* vertexData;
    if(d_vertexData.empty())
        vertexData = 0;
    else
        vertexData = &d_vertexData[0];

    GLsizei dataSize = d_bufferSize * sizeof(float);

    if(needNewBuffer)
    {
        glBufferData(GL_ARRAY_BUFFER, dataSize, vertexData, GL_STATIC_DRAW);
    }
    else
    {
        glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, vertexData);
    }
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::appendGeometry(const std::vector<float>& vertex_data)
{
    OpenGLGeometryBufferBase::appendGeometry(vertex_data);
    updateOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::drawDependingOnFillRule() const
{
    if(d_polygonFillRule == PFR_NONE)
    {
        d_glStateChanger->disable(GL_STENCIL_TEST);
        d_glStateChanger->disable(GL_CULL_FACE);

        glDrawArrays(GL_TRIANGLES, 0, d_vertexCount);
    }
    else if(d_polygonFillRule == PFR_EVEN_ODD)
    {
        //We use a stencil buffer to determine the insideness
        //of a fragment. Every draw inverts the precious value
        //according to the even-odd rule.
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

        d_glStateChanger->enable(GL_STENCIL_TEST);
        glStencilMask(0xFF);
        glClear(GL_STENCIL_BUFFER_BIT);
        glStencilFunc(GL_ALWAYS, 0, 0xFF);
        glStencilOp(GL_INVERT, GL_KEEP, GL_INVERT);
        glDrawArrays(GL_TRIANGLES, 0, d_vertexCount - 6);

        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glStencilMask(0x00);
        glStencilFunc(GL_EQUAL, 0xFF, 0xFF);
        glDrawArrays(GL_TRIANGLES, d_vertexCount - 6, d_vertexCount);
    }
    else if(d_polygonFillRule == PFR_NON_ZERO)
    {
        //We use a stencil buffer to determine the insideness
        //of a fragment. We draw the front sides while increasing
        //stencil values and then draw backside while decreasing them.
        //A resulting 0 value means we are outside.
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

        d_glStateChanger->enable(GL_CULL_FACE);
        d_glStateChanger->enable(GL_STENCIL_TEST);
        glStencilMask(0xFF);
        glClear(GL_STENCIL_BUFFER_BIT);
        glStencilFunc(GL_ALWAYS, 0, 0xFF);

        glCullFace(GL_FRONT);
        glStencilOp(GL_INCR_WRAP, GL_KEEP, GL_INCR_WRAP);
        glDrawArrays(GL_TRIANGLES, 0, d_vertexCount - 6);

        glCullFace(GL_BACK);
        glStencilOp(GL_DECR_WRAP, GL_KEEP, GL_DECR_WRAP);
        glDrawArrays(GL_TRIANGLES, 0, d_vertexCount - 6);

        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glStencilMask(0x00);
        glStencilFunc(GL_NOTEQUAL, 0x00, 0xFF);
        glDrawArrays(GL_TRIANGLES, d_vertexCount - 6, d_vertexCount);
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<commit_msg>Fix: Fixing fill-rule rendering bug<commit_after>/***********************************************************************
    filename:   CEGUIOpenGLGeometryBuffer.cpp
    created:    Wed, 8th Feb 2012
    author:     Lukas E Meindl (based on code by Paul D Turner)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include <GL/glew.h>

#include "glm/glm.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "CEGUI/RendererModules/OpenGL/GL3GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/GL3Renderer.h"
#include "CEGUI/RenderEffect.h"
#include "CEGUI/Vertex.h"
#include "CEGUI/ShaderParameterBindings.h"
#include "CEGUI/RendererModules/OpenGL/ShaderManager.h"
#include "CEGUI/RendererModules/OpenGL/Shader.h"
#include "CEGUI/RendererModules/OpenGL/StateChangeWrapper.h"
#include "CEGUI/RendererModules/OpenGL/GlmPimpl.h"
#include "CEGUI/RendererModules/OpenGL/GL3ShaderWrapper.h"

#define BUFFER_OFFSET(i) ((char *)NULL + (i))

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::OpenGL3GeometryBuffer(OpenGL3Renderer& owner, CEGUI::RefCounted<RenderMaterial> renderMaterial) :
    OpenGLGeometryBufferBase(owner, renderMaterial),
    d_glStateChanger(owner.getOpenGLStateChanger()),
    d_bufferSize(0)
{
    initialiseVertexBuffers();
}

//----------------------------------------------------------------------------//
OpenGL3GeometryBuffer::~OpenGL3GeometryBuffer()
{
    deinitialiseOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::draw() const
{
    if(d_vertexData.empty())
        return;

    CEGUI::Rectf viewPort = d_owner->getActiveViewPort();

    if (d_clippingActive)
    {
        d_glStateChanger->scissor(static_cast<GLint>(d_clipRect.left()),
            static_cast<GLint>(viewPort.getHeight() - d_clipRect.bottom()),
            static_cast<GLint>(d_clipRect.getWidth()),
            static_cast<GLint>(d_clipRect.getHeight()));

        d_glStateChanger->enable(GL_SCISSOR_TEST);
    }
    else
        d_glStateChanger->disable(GL_SCISSOR_TEST);

    // apply the transformations we need to use.
    if (!d_matrixValid)
        updateMatrix();

    CEGUI::ShaderParameterBindings* shaderParameterBindings = (*d_renderMaterial).getShaderParamBindings();
    // Set the ModelViewProjection matrix in the bindings
    glm::mat4 modelViewProjectionMatrix = d_owner->getViewProjectionMatrix()->d_matrix * d_matrix->d_matrix;
    shaderParameterBindings->setParameter("modelViewPerspMatrix", modelViewProjectionMatrix);

    // activate desired blending mode
    d_owner->setupRenderingBlendMode(d_blendMode);

    // Bind our vao
    d_glStateChanger->bindVertexArray(d_verticesVAO);

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        d_renderMaterial->prepareForRendering();

        // draw the geometry
        drawDependingOnFillRule();
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::reset()
{
    OpenGLGeometryBufferBase::reset();
    updateOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::initialiseVertexBuffers()
{
    glGenVertexArrays(1, &d_verticesVAO);
    d_glStateChanger->bindVertexArray(d_verticesVAO);

    // Generate and bind position vbo
    glGenBuffers(1, &d_verticesVBO);
    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    glBufferData(GL_ARRAY_BUFFER, 0, 0, GL_STATIC_DRAW);

    // Unbind Vertex Attribute Array (VAO)
    d_glStateChanger->bindVertexArray(0);

    // Unbind array and element array buffers
    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, 0);
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::finaliseVertexAttributes()
{
    //We need to bind both of the following calls
    d_glStateChanger->bindVertexArray(d_verticesVAO);
    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    GLsizei stride = getVertexAttributeElementCount() * sizeof(GL_FLOAT);

    CEGUI::OpenGL3ShaderWrapper* gl3_shader_wrapper = static_cast<CEGUI::OpenGL3ShaderWrapper*>(d_renderMaterial->getShaderWrapper());

    //Update the vertex attrib pointers of the vertex array object depending on the saved attributes
    int dataOffset = 0;
    const size_t attribute_count = d_vertexAttributes.size();
    for (size_t i = 0; i < attribute_count; ++i)
    {
        switch(d_vertexAttributes.at(i))
        {
        case VAT_POSITION0:
            {
                GLint shader_pos_loc = gl3_shader_wrapper->getAttributeLocation("inPosition");
                glVertexAttribPointer(shader_pos_loc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
                glEnableVertexAttribArray(shader_pos_loc);
                dataOffset += 3;
            }
            break;
        case VAT_COLOUR0:
            {
                GLint shader_colour_loc = gl3_shader_wrapper->getAttributeLocation("inColour");
                glVertexAttribPointer(shader_colour_loc, 4, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
                glEnableVertexAttribArray(shader_colour_loc);
                dataOffset += 4;
            }
            break;
        case VAT_TEXCOORD0:
            {
                GLint texture_coord_loc = gl3_shader_wrapper->getAttributeLocation("inTexCoord");
                glVertexAttribPointer(texture_coord_loc, 2, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(dataOffset * sizeof(GL_FLOAT)));
                glEnableVertexAttribArray(texture_coord_loc);
                dataOffset += 2;
            }
            break;
        default:
            break;
        }
    }
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::deinitialiseOpenGLBuffers()
{
    glDeleteVertexArrays(1, &d_verticesVAO);
    glDeleteBuffers(1, &d_verticesVBO);
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::updateOpenGLBuffers()
{
    bool needNewBuffer = false;
    size_t vertexCount = d_vertexData.size();

    if(d_bufferSize < vertexCount)
    {
        needNewBuffer = true;
        d_bufferSize = vertexCount;
    }

    d_glStateChanger->bindBuffer(GL_ARRAY_BUFFER, d_verticesVBO);

    float* vertexData;
    if(d_vertexData.empty())
        vertexData = 0;
    else
        vertexData = &d_vertexData[0];

    GLsizei dataSize = d_bufferSize * sizeof(float);

    if(needNewBuffer)
    {
        glBufferData(GL_ARRAY_BUFFER, dataSize, vertexData, GL_STATIC_DRAW);
    }
    else
    {
        glBufferSubData(GL_ARRAY_BUFFER, 0, dataSize, vertexData);
    }
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::appendGeometry(const std::vector<float>& vertex_data)
{
    OpenGLGeometryBufferBase::appendGeometry(vertex_data);
    updateOpenGLBuffers();
}

//----------------------------------------------------------------------------//
void OpenGL3GeometryBuffer::drawDependingOnFillRule() const
{
    if(d_polygonFillRule == PFR_NONE)
    {
        d_glStateChanger->disable(GL_CULL_FACE);
        d_glStateChanger->disable(GL_STENCIL_TEST);

        glDrawArrays(GL_TRIANGLES, 0, d_vertexCount);
    }
    else if(d_polygonFillRule == PFR_EVEN_ODD)
    {
        //We use a stencil buffer to determine the insideness
        //of a fragment. Every draw inverts the precious value
        //according to the even-odd rule.
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

        d_glStateChanger->disable(GL_CULL_FACE);
        d_glStateChanger->enable(GL_STENCIL_TEST);
        glStencilMask(0xFF);
        glClear(GL_STENCIL_BUFFER_BIT);
        glStencilFunc(GL_ALWAYS, 0x00, 0xFF);
        glStencilOp(GL_INVERT, GL_KEEP, GL_INVERT);
        glDrawArrays(GL_TRIANGLES, 0, d_vertexCount - 6);

        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glStencilMask(0x00);
        glStencilFunc(GL_EQUAL, 0xFF, 0xFF);
        glDrawArrays(GL_TRIANGLES, d_vertexCount - 6, 6);
    }
    else if(d_polygonFillRule == PFR_NON_ZERO)
    {
        //We use a stencil buffer to determine the insideness
        //of a fragment. We draw the front sides while increasing
        //stencil values and then draw backside while decreasing them.
        //A resulting 0 value means we are outside.
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

        d_glStateChanger->enable(GL_CULL_FACE);
        d_glStateChanger->enable(GL_STENCIL_TEST);
        glStencilMask(0xFF);
        glClear(GL_STENCIL_BUFFER_BIT);
        glStencilFunc(GL_ALWAYS, 0x00, 0xFF);

        glCullFace(GL_FRONT);
        glStencilOp(GL_INCR_WRAP, GL_KEEP, GL_INCR_WRAP);
        glDrawArrays(GL_TRIANGLES, 0, d_vertexCount - 6);

        glCullFace(GL_BACK);
        glStencilOp(GL_DECR_WRAP, GL_KEEP, GL_DECR_WRAP);
        glDrawArrays(GL_TRIANGLES, 0, d_vertexCount - 6);

        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glStencilMask(0x00);
        glStencilFunc(GL_NOTEQUAL, 0x00, 0xFF);
        glDrawArrays(GL_TRIANGLES, d_vertexCount - 6, 6);
    }
}

//----------------------------------------------------------------------------//

} // End of  CEGUI namespace section

<|endoftext|>


<commit_before>#include <cetty/shiro/session/SessionManager.h>
#include <cetty/shiro/util/EmptyObj.h>

namespace cetty {
namespace shiro {
namespace session {

using namespace cetty::shiro::util;

const int SessionManager::MILLIS_PER_SECOND = 1000;
const int SessionManager::MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
const int SessionManager::MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
const int SessionManager::DEFAULT_GLOBAL_SESSION_TIMEOUT = 30 * MILLIS_PER_MINUTE;
const int SessionManager::DEFAULT_SESSION_VALIDATION_INTERVAL = MILLIS_PER_HOUR;

SessionManager::SessionManager()
  :deleteInvalidSessions(true),
   sessionValidationSchedulerEnabled(true),
   globalSessionTimeout(DEFAULT_GLOBAL_SESSION_TIMEOUT),
   sessionValidationInterval(DEFAULT_SESSION_VALIDATION_INTERVAL),
   sessionDAO(NULL),
   sessionValidationScheduler(NULL){
    sessionDAO = new MemorySessionDAO();
}
SessionManager::~SessionManager(){
    if(sessionDAO != NULL) {
        delete sessionDAO;
        sessionDAO = NULL;
    }
    if(sessionValidationScheduler != NULL) {
        delete sessionValidationScheduler;
        sessionValidationScheduler = NULL;
    }
}

void SessionManager::validateSessions(){
    int invalidCount = 0;
    std::vector<SessionPtr> v;

    getActiveSessions(&v);
    if(v.size() > 0){
        std::vector<SessionPtr>::iterator it = v.begin();
        for(; it != v.end(); ++it) {
            Session::SessionState state = validate(*it);
            if(state == Session::STOPPED || state == Session::EXPIRED)
                invalidCount ++;
        }
    }
}

Session::SessionState SessionManager::validate(SessionPtr &session) {
    Session::SessionState state = session->validate();
    if(state == Session::EXPIRED) {
        onExpiration(session);
    }
    else if(state == Session::STOPPED){
        onInvalidation(session, state);
    }

    return state;
}

void SessionManager::onInvalidation(SessionPtr &s, Session::SessionState state){
    if(state == Session::EXPIRED){
        onExpiration(s);
        return;
    }
    onStop(s);
    notifyStop(s);
    afterStopped(s);
}

void SessionManager::notifyStart(const SessionPtr &session){
    std::vector<SessionChangeCallback>::iterator it = listeners.begin();
    for(; it != listeners.end(); ++it) (*it)(session, Session::START);
}

void SessionManager::notifyStop(const SessionPtr &session){
    std::vector<SessionChangeCallback>::iterator it = listeners.begin();
    for(; it != listeners.end(); ++it) (*it)(session, Session::STOPPED);
}
void SessionManager::notifyExpiration(const SessionPtr &session){
    std::vector<SessionChangeCallback>::iterator it = listeners.begin();
    for(; it != listeners.end(); ++it) (*it)(session, Session::EXPIRED);
}

void SessionManager::enableSessionValidation(){
    SessionValidationScheduler *scheduler = getSessionValidationScheduler();
    if (scheduler == NULL) {
        scheduler = createSessionValidationScheduler();
        setSessionValidationScheduler(scheduler);
    }

    scheduler->enableSessionValidation();
    afterSessionValidationEnabled();
}
void SessionManager::disableSessionValidation(){
    beforeSessionValidationDisabled();
    SessionValidationScheduler *scheduler = getSessionValidationScheduler();
    if (scheduler != NULL) {
        scheduler->disableSessionValidation();
        delete scheduler;
        scheduler = NULL;
        setSessionValidationScheduler(NULL);
    }
}

ptime SessionManager::getStartTimestamp(const std::string &sessionId) {
    SessionPtr s = lookupRequiredSession(sessionId);
    if(!s) return ptime();
    return s->getStartTimestamp();
}

ptime SessionManager::getLastAccessTime(const std::string &sessionId) {
    SessionPtr s = lookupRequiredSession(sessionId);
    if(!s) return ptime();
    return s->getLastAccessTime();
}

int SessionManager::getTimeout(const std::string &sessionId){
    SessionPtr s = lookupRequiredSession(sessionId);
    if(!s) return -1L;
    return s->getTimeout();
}

void SessionManager::setTimeout(const std::string &id, int maxIdleTimeInMillis){
    SessionPtr s = lookupRequiredSession(id);
    if (!s) return;
    s->setTimeout(maxIdleTimeInMillis);
    onChange(s);
}

void SessionManager::touch(const std::string &id){
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return;
    s->touch();
    onChange(s);
}

std::string SessionManager::getHost(const std::string &id) {
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return std::string();
    return s->getHost();
}

void SessionManager::getAttributeKeys(const std::string &id, std::vector<std::string> *keys) {
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return;
    s->getAttributeKeys(keys);
}

std::string& SessionManager::getAttribute(const std::string &id, const std::string &key){
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return emptyString;
    return s->getAttribute(key);
}

void SessionManager::setAttribute(const std::string &id, const std::string &key, const std::string &value) {
    if (value.empty()) {
        removeAttribute(id, key);
    } else {
        SessionPtr s = lookupRequiredSession(id);
        if(!s) return;
        s->setAttribute(key, value);
        onChange(s);
    }
}

void SessionManager::removeAttribute(const std::string &id, const std::string &key) {
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return;
    s->removeAttribute(key);
    onChange(s);
}

bool SessionManager::isLogin(const std::string &id){
    if(id.empty()) return false;
    SessionPtr s = lookupRequiredSession(id);
    if(s == NULL) return false;
    return s->isLogin();
}

void SessionManager::setLogin(const std::string &id, bool login){
    if(id.empty()) return;
    SessionPtr s = lookupRequiredSession(id);
    if(s == NULL) return;
    s->setLogin(login);
}

void SessionManager::stop(const std::string &id){
    SessionPtr s = lookupRequiredSession(id);
    if(s == NULL) return;
    s->stop();
    onStop(s);
    notifyStop(s);
    afterStopped(s);
}

SessionPtr SessionManager::start() {
    SessionPtr session = createSession();
    if(session){
        applyGlobalSessionTimeout(session);
        onStart(session);
        notifyStart(session);
    }
    return session;
}
}
}
}
<commit_msg>modify SessionManager.cpp<commit_after>#include <cetty/shiro/session/SessionManager.h>
#include <cetty/shiro/util/EmptyObj.h>

namespace cetty {
namespace shiro {
namespace session {

using namespace cetty::shiro::util;

const int SessionManager::MILLIS_PER_SECOND = 1000;
const int SessionManager::MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
const int SessionManager::MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
const int SessionManager::DEFAULT_GLOBAL_SESSION_TIMEOUT = 30 * MILLIS_PER_MINUTE;
const int SessionManager::DEFAULT_SESSION_VALIDATION_INTERVAL = MILLIS_PER_HOUR;

SessionManager::SessionManager()
  :deleteInvalidSessions(true),
   sessionValidationSchedulerEnabled(true),
   globalSessionTimeout(DEFAULT_GLOBAL_SESSION_TIMEOUT),
   sessionValidationInterval(DEFAULT_SESSION_VALIDATION_INTERVAL),
   sessionDAO(NULL),
   sessionValidationScheduler(NULL)
{
    sessionDAO = new MemorySessionDAO();
}
SessionManager::~SessionManager(){
    if(sessionDAO != NULL) {
        delete sessionDAO;
        sessionDAO = NULL;
    }
    if(sessionValidationScheduler != NULL) {
        delete sessionValidationScheduler;
        sessionValidationScheduler = NULL;
    }
}

void SessionManager::validateSessions(){
    int invalidCount = 0;
    std::vector<SessionPtr> v;

    getActiveSessions(&v);
    if(v.size() > 0){
        std::vector<SessionPtr>::iterator it = v.begin();
        for(; it != v.end(); ++it) {
            Session::SessionState state = validate(*it);
            if(state == Session::STOPPED || state == Session::EXPIRED)
                invalidCount ++;
        }
    }
}

Session::SessionState SessionManager::validate(SessionPtr &session) {
    Session::SessionState state = session->validate();
    if(state == Session::EXPIRED) {
        onExpiration(session);
    }
    else if(state == Session::STOPPED){
        onInvalidation(session, state);
    }

    return state;
}

void SessionManager::onInvalidation(SessionPtr &s, Session::SessionState state){
    if(state == Session::EXPIRED){
        onExpiration(s);
        return;
    }
    onStop(s);
    notifyStop(s);
    afterStopped(s);
}

void SessionManager::notifyStart(const SessionPtr &session){
    std::vector<SessionChangeCallback>::iterator it = listeners.begin();
    for(; it != listeners.end(); ++it) (*it)(session, Session::START);
}

void SessionManager::notifyStop(const SessionPtr &session){
    std::vector<SessionChangeCallback>::iterator it = listeners.begin();
    for(; it != listeners.end(); ++it) (*it)(session, Session::STOPPED);
}
void SessionManager::notifyExpiration(const SessionPtr &session){
    std::vector<SessionChangeCallback>::iterator it = listeners.begin();
    for(; it != listeners.end(); ++it) (*it)(session, Session::EXPIRED);
}

void SessionManager::enableSessionValidation(){
    SessionValidationScheduler *scheduler = getSessionValidationScheduler();
    if (scheduler == NULL) {
        scheduler = createSessionValidationScheduler();
        setSessionValidationScheduler(scheduler);
    }

    scheduler->enableSessionValidation();
    afterSessionValidationEnabled();
}
void SessionManager::disableSessionValidation(){
    beforeSessionValidationDisabled();
    SessionValidationScheduler *scheduler = getSessionValidationScheduler();
    if (scheduler != NULL) {
        scheduler->disableSessionValidation();
        delete scheduler;
        scheduler = NULL;
        setSessionValidationScheduler(NULL);
    }
}

ptime SessionManager::getStartTimestamp(const std::string &sessionId) {
    SessionPtr s = lookupRequiredSession(sessionId);
    if(!s) return ptime();
    return s->getStartTimestamp();
}

ptime SessionManager::getLastAccessTime(const std::string &sessionId) {
    SessionPtr s = lookupRequiredSession(sessionId);
    if(!s) return ptime();
    return s->getLastAccessTime();
}

int SessionManager::getTimeout(const std::string &sessionId){
    SessionPtr s = lookupRequiredSession(sessionId);
    if(!s) return -1L;
    return s->getTimeout();
}

void SessionManager::setTimeout(const std::string &id, int maxIdleTimeInMillis){
    SessionPtr s = lookupRequiredSession(id);
    if (!s) return;
    s->setTimeout(maxIdleTimeInMillis);
    onChange(s);
}

void SessionManager::touch(const std::string &id){
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return;
    s->touch();
    onChange(s);
}

std::string SessionManager::getHost(const std::string &id) {
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return std::string();
    return s->getHost();
}

void SessionManager::getAttributeKeys(const std::string &id, std::vector<std::string> *keys) {
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return;
    s->getAttributeKeys(keys);
}

std::string& SessionManager::getAttribute(const std::string &id, const std::string &key){
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return emptyString;
    return s->getAttribute(key);
}

void SessionManager::setAttribute(const std::string &id, const std::string &key, const std::string &value) {
    if (value.empty()) {
        removeAttribute(id, key);
    } else {
        SessionPtr s = lookupRequiredSession(id);
        if(!s) return;
        s->setAttribute(key, value);
        onChange(s);
    }
}

void SessionManager::removeAttribute(const std::string &id, const std::string &key) {
    SessionPtr s = lookupRequiredSession(id);
    if(!s) return;
    s->removeAttribute(key);
    onChange(s);
}

bool SessionManager::isLogin(const std::string &id){
    if(id.empty()) return false;
    SessionPtr s = lookupRequiredSession(id);
    if(s == NULL) return false;
    return s->isLogin();
}

void SessionManager::setLogin(const std::string &id, bool login){
    if(id.empty()) return;
    SessionPtr s = lookupRequiredSession(id);
    if(s == NULL) return;
    s->setLogin(login);
    onChange(s);
}

void SessionManager::stop(const std::string &id){
    SessionPtr s = lookupRequiredSession(id);
    if(s == NULL) return;
    s->stop();
    onStop(s);
    notifyStop(s);
    afterStopped(s);
}

SessionPtr SessionManager::start() {
    SessionPtr session = createSession();
    if(session){
        applyGlobalSessionTimeout(session);
        onStart(session);
        notifyStart(session);
    }
    return session;
}
}
}
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>

#include <list>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

/*
 D := Tamanho do quadrado.
 d := tamanho das subdivisões
 n := Tamanho da matriz;

*/

typedef struct ponto{
	int x;
	int y;
	int i; // INDICE NO VETOR DE VERTICES
} *Ponto;

int pontoVertice(Ponto p);
int** alocaMatrizQuadrada(int n);
void criaGrafo();
void criaArestas(Ponto);
void novaAresta(int, int);
float distCircular(Ponto, Ponto);
void indepSet1();

float d, D;
int n, N, maxTamanho;
int** A;

vector< vector<int> > madj;

vector< list<int> > adj;
Ponto* vertices;

int main(int argc, char* argv[])
{

	D = strtof(argv[1], NULL);
	d = strtof(argv[2], NULL);
	n = D/d; /* cuidado com arredondamento */
    N = n*n;

    madj.resize(N);
    for(int i = 0; i < N; i++)
	{
        madj[i].resize(N);
    }
	//adj = new list<int>[n];

	A = alocaMatrizQuadrada(n);
	N = n*n;

	//adj = new vector<int>[n];
	adj.resize(N);

	vertices = new Ponto[n*n];

	Ponto pteste;

	for(int i = 0; i < n; i++)
		for( int j = 0; j < n; j++)
		{
			//A[i][j] = 1;
			Ponto p = (Ponto) malloc(sizeof(ponto));
			p->x = j; p->y = i; p->i = pontoVertice(p);
			if(i == n/2 && j == n/2) pteste = p;
			vertices[p->i] = p;
		}

	criaArestas(vertices[N/2]);
    indepSet1();

	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < n; j++)
			if(!A[i][j])printf("\033[1;31m[%d]\033[0m",A[i][j]);
			else printf("[%d]",A[i][j]);
		printf("\n");
	}

	return 0;
}

/*
	Numero os quadrados da matriz de forma crescente,
	da esquerda para a direita
*/

int pontoVertice(Ponto p)
{
	return n*p->y + p->x;
}

/*****************

	Retorna a menor distancia entre dois quadradinhos
	no quadrado, dentre todas as distâncias possiveis.

	Ou seja, trata a malha coo algo "circular"

*********************/

float distCircular(Ponto p1, Ponto p2)
{
	int x1 = p1->x, y1 = p1->y, x2 = p2->x, y2 = p2->y;
	float dx = x1 -x2, dy = y1 - y2;
	float dist1;

	if(dx < 0) dx*=-1;
	if(dy < 0) dy*=-1;

	if(dx > n/2 ) // Certeza?
		dx = n - dx;
	if(dy > n/2) // Certeza?
		dy = n - dy;

	//printf("Dist: %f\n", (dx*dx + dy*dy)*d);
	return sqrt(dx*dx + dy*dy)*d;
}

/* Vai criar o grafo onde dois pontos são
	adjacentes <=> dist = 1 (com margem de erro
	devido a aproximação)

	Obs: Ordem n^4, MELHORAR.
*/

void criaGrafo()
{
	for(int i = 0; i < N; i++)
		criaArestas(vertices[i]);
}

void criaArestas(Ponto p)
{

	A[p->x][p->y] = 0;

	for(int i = 0; i < N; i++)
	{
		Ponto p2 = vertices[i];
		float dist = distCircular(p,p2);

		if(dist > 1-d && dist < 1+d){ // REVER
			novaAresta(p->i,p2->i);
            A[p2->x][p2->y] = 0;
		}
			// Cria aresta entre p1 e p2
	}

}

void novoArco(int v1, int v2)
{

    madj[v1][v2] = 1;
	for (list<int>::iterator it = adj[v1].begin() ; it != adj[v1].end(); ++it)
	{
		if(*it == v2) return;
	}
	//if(find(adj[v1].begin(), adj[v1].end(), v2) != adj[v1].end())
	adj[v1].push_back(v2);
}

void novaAresta(int v1, int v2)
{
	novoArco(v1,v2);
	novoArco(v2,v1);
}

int** alocaMatrizQuadrada(int n)
{
	int** m;

	m =(int**) malloc(n*sizeof(int*));
	for(int i = 0; i < n; i++)
		m[i] =(int*) malloc(n*sizeof(int));

	return m;
}

/***************************************************
 *
 * Algoritimos para achar conjuntos independentes
 *
 *
 *
 *
 * Feitos:
 *  - Força bruta (indepSet1())
 ****************************************************/

//Supomos que v1 e v2 são do mesmo tamanho
// ---> Função usada em indepSet1()
int disjuntos(vector<int> v1, vector<int> v2)
{
    int tam = v1.size();

    for(int i = 0; i < tam; i++)
        if(v1[i] && v1[i] == v2[i]) return 0;
    return 1;
}

void indepSet1()
{
    int tam;
    Ponto p;

    p = vertices[0];
    A[p->x][p->y] = 1;
    vector<int> s(n*n);
    vector<int> maxS(n*n);
    int j;
    for(int i = 0; i < n; i++)
        s[i] = 0;
    int N = n*n;
    maxS[0] = s[0] = 1;
    maxTamanho = 1;
    j = 1;
    while(1)
    {
//        printf("j = %d\n", j);

        if(j >= N)
        {
            while(j!=0 && !s[--j]);
            if(!j) break; // ACABOU!
            p = vertices[j];
            A[p->x][p->y] = 0;
            s[j++] = 0;
            tam--;
            continue;
        }
        p = vertices[j];
        A[p->x][p->y] = s[j] = 1;

        tam++;

        // Se não é mais conjunto indep, continue

        if(!disjuntos(madj[j], s))
        {
            p = vertices[j];
            A[p->x][p->y] = s[j++] = 0;

            tam--;
            continue;
        }

        // Se ainda é conj indep, frita

        if(tam > maxTamanho)
        {
            printf("NOVO TAMANHO %d\n", tam);
            maxTamanho = tam;
            maxS = s;
        }
        j++;

    }

}

<commit_msg>Mudanças feitas em casa q eu devia ter dado commmit antes<commit_after>#include <cstdio>
#include <cstdlib>

#include <list>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

/*
 D := Tamanho do quadrado.
 d := tamanho das subdivisões
 n := Tamanho da matriz;

*/

typedef struct ponto{
	int x;
	int y;
	int i; // INDICE NO VETOR DE VERTICES
} *Ponto;

int pontoVertice(Ponto p);
int** alocaMatrizQuadrada(int n);
void criaGrafo();
void criaArestas(Ponto);
void novaAresta(int, int);
float distCircular(Ponto, Ponto);
void indepSet1();

float d, D;
int n, N, maxTamanho;
//int** A;

vector< vector<int> > madj, A, Amax;

vector< list<int> > adj;
Ponto* vertices;

int main(int argc, char* argv[])
{

	D = strtof(argv[1], NULL);
	d = strtof(argv[2], NULL);
	n = D/d; /* cuidado com arredondamento */
    N = n*n;

    A.resize(n);
    Amax.resize(n);
    madj.resize(N);
    for(int i = 0; i < N; i++)
	{
        madj[i].resize(N);
    }

    for(int i =0; i < n; i++)
    {
        A[i].resize(n);
        Amax[i].resize(n);

    }
	//adj = new list<int>[n];

//	A = alocaMatrizQuadrada(n);

	//adj = new vector<int>[n];
	adj.resize(N);

	vertices = new Ponto[n*n];

	Ponto pteste;

	for(int i = 0; i < n; i++)
		for( int j = 0; j < n; j++)
		{
			//A[i][j] = 1;
			Ponto p = (Ponto) malloc(sizeof(ponto));
			p->x = j; p->y = i; p->i = pontoVertice(p);
			if(i == n/2 && j == n/2) pteste = p;
			vertices[p->i] = p;
		}

	criaGrafo();
    indepSet1();

	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < n; j++)
			if(!Amax[i][j])printf("\033[1;31m[%d]\033[0m",Amax[i][j]);
			else printf("[%d]",Amax[i][j]);
		printf("\n");
	}

	return 0;
}

/*
	Numero os quadrados da matriz de forma crescente,
	da esquerda para a direita
*/

int pontoVertice(Ponto p)
{
	return n*p->y + p->x;
}

/*****************

	Retorna a menor distancia entre dois quadradinhos
	no quadrado, dentre todas as distâncias possiveis.

	Ou seja, trata a malha coo algo "circular"

*********************/

float distCircular(Ponto p1, Ponto p2)
{
	int x1 = p1->x, y1 = p1->y, x2 = p2->x, y2 = p2->y;
	float dx = x1 -x2, dy = y1 - y2;
	float dist1;

	if(dx < 0) dx*=-1;
	if(dy < 0) dy*=-1;

	if(dx > n/2 ) // Certeza?
		dx = n - dx;
	if(dy > n/2) // Certeza?
		dy = n - dy;

	//printf("Dist: %f\n", (dx*dx + dy*dy)*d);
	return sqrt(dx*dx + dy*dy)*d;
}
/**************
 * Calcula a distancia normal entre os pontos
 *
 *
 *
 * ******************/

float distNormal(Ponto p1, Ponto p2)
{

   	int x1 = p1->x, y1 = p1->y, x2 = p2->x, y2 = p2->y;
	float dx = x1 -x2, dy = y1 - y2;

	if(dx < 0) dx*=-1;
	if(dy < 0) dy*=-1;

	return sqrt(dx*dx + dy*dy)*d;

}

/* Vai criar o grafo onde dois pontos são
	adjacentes <=> dist = 1 (com margem de erro
	devido a aproximação)

	Obs: Ordem n^4, MELHORAR.
*/

void criaGrafo()
{
	for(int i = 0; i < N; i++)
		criaArestas(vertices[i]);
}

void criaArestas(Ponto p)
{

	A[p->x][p->y] = 0;

	for(int i = 0; i < N; i++)
	{
		Ponto p2 = vertices[i];
		float dist = distCircular(p,p2);

		if(dist > 1-d && dist < 1+d){ // REVER
			novaAresta(p->i,p2->i);
            A[p2->x][p2->y] = 0;
		}
			// Cria aresta entre p1 e p2
	}

}

void novoArco(int v1, int v2)
{

    madj[v1][v2] = 1;
	for (list<int>::iterator it = adj[v1].begin() ; it != adj[v1].end(); ++it)
	{
		if(*it == v2) return;
	}
	//if(find(adj[v1].begin(), adj[v1].end(), v2) != adj[v1].end())
	adj[v1].push_back(v2);
}

void novaAresta(int v1, int v2)
{
	novoArco(v1,v2);
	novoArco(v2,v1);
}

int** alocaMatrizQuadrada(int n)
{
	int** m;

	m =(int**) malloc(n*sizeof(int*));
	for(int i = 0; i < n; i++)
		m[i] =(int*) malloc(n*sizeof(int));

	return m;
}

/***************************************************
 *
 * Algoritimos para achar conjuntos independentes
 *
 *
 *
 *
 * Feitos:
 *  - Força bruta (indepSet1())
 *  - Simulates Annealing (annealing())
 ****************************************************/

//Supomos que v1 e v2 são do mesmo tamanho
// ---> Função usada em indepSet1()
int disjuntos(vector<int> v1, vector<int> v2)
{
    int tam = v1.size();

    for(int i = 0; i < tam; i++)
        if(v1[i] && v1[i] == v2[i]) return 0;
    return 1;
}

void indepSet1()
{
    int tam;
    Ponto p;

    p = vertices[0];
    A[p->x][p->y] = 1;
    vector<int> s(n*n);
    vector<int> maxS(n*n);
    int j;
    for(int i = 0; i < n; i++)
        s[i] = 0;
    int N = n*n;
    maxS[0] = s[0] = 1;
    maxTamanho = 1;
    tam = 1;
    j = 1;
    while(1)
    {
//        printf("j = %d\n", j);

        if(j >= N)
        {
            while(j!=0 && !s[--j]);
            if(!j) break; // ACABOU!
            p = vertices[j];
            A[p->x][p->y] = 0;
            s[j++] = 0;
            tam--;
            continue;
        }
        p = vertices[j];
        A[p->x][p->y] = s[j] = 1;

        tam++;

        // Se não é mais conjunto indep, continue

        if(!disjuntos(madj[j], s))
        {
            p = vertices[j];
            A[p->x][p->y] = s[j++] = 0;

            tam--;
            continue;
        }

        // Se ainda é conj indep, frita

        if(tam > maxTamanho)
        {
            printf("NOVO TAMANHO %d\n", tam);
            maxTamanho = tam;
            maxS = s;
            Amax = A;
        }
        j++;

    }

    printf("%d\n", maxTamanho);

}

void solInicial()
{
    return;
}

void annealing(int T, float coolR)
{
    solInicial();
}

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#include <boost/python.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/image_util.hpp>

using mapnik::Image32;
using namespace boost::python;
using mapnik::save_to_file;

PyObject* rawdata( Image32 const& im)
{
    int size = im.width() * im.height() * 4;
    return ::PyString_FromStringAndSize((const char*)im.raw_data(),size);
}

void (*save_to_file2)(std::string const&,std::string const&, mapnik::Image32 const&) = mapnik::save_to_file;

void blend (Image32 & im, unsigned x, unsigned y, Image32 const& im2, float opacity)
{
   im.set_rectangle_alpha2(im2.data(),x,y,opacity);
}

void export_image()
{
    using namespace boost::python;
    class_<Image32>("Image","This class represents a 32 bit image.",init<int,int>())
       .def("width",&Image32::width)
       .def("height",&Image32::height)
       .def("view",&Image32::get_view)
       .add_property("background",make_function
                     (&Image32::getBackground,return_value_policy<copy_const_reference>()),
                     &Image32::setBackground, "The background color of the image.")
       .def("set_alpha",&Image32::set_alpha)
       .def("blend",&blend)
       ;
    def("rawdata",&rawdata); // FIXME : I dont think we need this one
    def("save_to_file", save_to_file2);
}
<commit_msg>removed set_alpha<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#include <boost/python.hpp>
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/image_util.hpp>

using mapnik::Image32;
using namespace boost::python;
using mapnik::save_to_file;

PyObject* rawdata( Image32 const& im)
{
    int size = im.width() * im.height() * 4;
    return ::PyString_FromStringAndSize((const char*)im.raw_data(),size);
}

void (*save_to_file2)(std::string const&,std::string const&, mapnik::Image32 const&) = mapnik::save_to_file;

void blend (Image32 & im, unsigned x, unsigned y, Image32 const& im2, float opacity)
{
   im.set_rectangle_alpha2(im2.data(),x,y,opacity);
}

void export_image()
{
    using namespace boost::python;
    class_<Image32>("Image","This class represents a 32 bit image.",init<int,int>())
       .def("width",&Image32::width)
       .def("height",&Image32::height)
       .def("view",&Image32::get_view)
       .add_property("background",make_function
                     (&Image32::getBackground,return_value_policy<copy_const_reference>()),
                     &Image32::setBackground, "The background color of the image.")
       .def("blend",&blend)
       ;
    def("rawdata",&rawdata); // FIXME : I dont think we need this one anymore
    def("save_to_file", save_to_file2);
}
<|endoftext|>


<commit_before>#include <esn/esn.h>

int main()
{
    return 0;
}
<commit_msg>samples : sine : create network<commit_after>#include <esn/esn.h>

static const unsigned kNeuronCount = 100;

int main()
{
    ESN::NetworkParamsNSLI params;
    params.inputCount = 1;
    params.neuronCount = kNeuronCount;
    params.outputCount = 1;
    std::unique_ptr< ESN::Network > network = ESN::CreateNetwork( params );

    return 0;
}
<|endoftext|>


<commit_before>/*
  Copyright (C) 2014 Harald Sitter <apachelogger@kubuntu.org>

  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) version 3, or any
  later version accepted by the membership of KDE e.V. (or its
  successor approved by the membership of KDE e.V.), which shall
  act as a proxy defined in Section 6 of version 3 of the license.

  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, see <http://www.gnu.org/licenses/>.
*/

#include <QDebug>
#include <QFile>
#include <QString>
#include <QStringBuilder>

#include <KGlobal>
#include <KStandardDirs>

#include <l10n_locale.h>

int main(int argc, char *argv[])
{
    const QString envPath = KGlobal::dirs()->localkdedir() % QLatin1String("/env");
    const QString envFile = envPath % QLatin1String("/setlocale.sh");
    qDebug() << envFile;
    if (QFile::exists(envFile)) {
        // Only rewrite the file iff it already exists, otherwise a user may have
        // removed it and we restore it which doesn't seem particularly nice.
        Kubuntu::Locale locale;
        locale.writeToFile(envFile);
    }
    return 0;
}
<commit_msg>remove debug from updater<commit_after>/*
  Copyright (C) 2014 Harald Sitter <apachelogger@kubuntu.org>

  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) version 3, or any
  later version accepted by the membership of KDE e.V. (or its
  successor approved by the membership of KDE e.V.), which shall
  act as a proxy defined in Section 6 of version 3 of the license.

  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, see <http://www.gnu.org/licenses/>.
*/

#include <QFile>
#include <QString>
#include <QStringBuilder>

#include <KGlobal>
#include <KStandardDirs>

#include <l10n_locale.h>

int main(int argc, char *argv[])
{
    const QString envPath = KGlobal::dirs()->localkdedir() % QLatin1String("/env");
    const QString envFile = envPath % QLatin1String("/setlocale.sh");
    if (QFile::exists(envFile)) {
        // Only rewrite the file iff it already exists, otherwise a user may have
        // removed it and we restore it which doesn't seem particularly nice.
        Kubuntu::Locale locale;
        locale.writeToFile(envFile);
    }
    return 0;
}
<|endoftext|>


<commit_before>/* Copyright (C) 2003 MySQL AB

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include <signaldata/CreateTrig.hpp>

bool printCREATE_TRIG_REQ(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
  const CreateTrigReq * const sig = (CreateTrigReq *) theData;

  //char triggerName[MAX_TAB_NAME_SIZE];
  char triggerType[32];
  char triggerActionTime[32];
  char triggerEvent[32];

  //sig->getTriggerName((char *) &triggerName);
  switch (sig->getTriggerType()) {
  case(TriggerType::SECONDARY_INDEX):
    snprintf(triggerType, sizeof(triggerType), "SECONDARY_INDEX");
    break;
  case(TriggerType::SUBSCRIPTION):
    snprintf(triggerType, sizeof(triggerType), "SUBSCRIPTION");
    break;
  case(TriggerType::ORDERED_INDEX):
    snprintf(triggerType, sizeof(triggerType), "ORDERED_INDEX");
    break;
  default:
    snprintf(triggerType, sizeof(triggerType), "UNKNOWN [%d]", (int)sig->getTriggerType());
    break;
  }
  switch (sig->getTriggerActionTime()) {
  case (TriggerActionTime::TA_BEFORE):
    snprintf(triggerActionTime, sizeof(triggerActionTime), "BEFORE");
    break;
  case(TriggerActionTime::TA_AFTER):
    snprintf(triggerActionTime, sizeof(triggerActionTime), "AFTER");
    break;
  case (TriggerActionTime::TA_DEFERRED):
    snprintf(triggerActionTime, sizeof(triggerActionTime), "DEFERRED");
    break;
  case (TriggerActionTime::TA_DETACHED):
    snprintf(triggerActionTime, sizeof(triggerActionTime), "DETACHED");
    break;
  default:
    snprintf(triggerActionTime, sizeof(triggerActionTime),
	     "UNKNOWN [%d]", (int)sig->getTriggerActionTime());
    break;
  }
  switch (sig->getTriggerEvent()) {
  case (TriggerEvent::TE_INSERT):
    snprintf(triggerEvent, sizeof(triggerEvent), "INSERT");
    break;
  case(TriggerEvent::TE_DELETE):
    snprintf(triggerEvent, sizeof(triggerEvent), "DELETE");
    break;
  case(TriggerEvent::TE_UPDATE):
    snprintf(triggerEvent, sizeof(triggerEvent), "UPDATE");
    break;
  case(TriggerEvent::TE_CUSTOM):
    snprintf(triggerEvent, sizeof(triggerEvent), "CUSTOM");
    break;
  default:
    snprintf(triggerEvent, sizeof(triggerEvent), "UNKNOWN [%d]", (int)sig->getTriggerEvent());
    break;
  }

  fprintf(output, "User: %u, ", sig->getUserRef());
  //fprintf(output, "Trigger name: \"%s\"\n", triggerName);
  fprintf(output, "Type: %s, ", triggerType);
  fprintf(output, "Action: %s, ", triggerActionTime);
  fprintf(output, "Event: %s, ", triggerEvent);
  fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
  fprintf(output, "Table id: %u, ", sig->getTableId());
  fprintf(output, "Monitor replicas: %s ", (sig->getMonitorReplicas())?"true":"false");
  fprintf(output, "Monitor all attributes: %s ", (sig->getMonitorAllAttributes())?"true":"false");
  const AttributeMask& attributeMask = sig->getAttributeMask();

  char buf[attributeMask.TextLength + 1];
  fprintf(output, "Attribute mask: %s", attributeMask.getText(buf));
  fprintf(output, "\n");

  return false;
}

bool printCREATE_TRIG_CONF(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
  const CreateTrigConf * const sig = (CreateTrigConf *) theData;

  fprintf(output, "User: %u, ", sig->getUserRef());
  fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
  fprintf(output, "Table id: %u, ", sig->getTableId());
  fprintf(output, "\n");

  return false;
}

bool printCREATE_TRIG_REF(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
  const CreateTrigRef * const sig = (CreateTrigRef *) theData;

  fprintf(output, "User: %u, ", sig->getUserRef());
  fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
  fprintf(output, "Table id: %u, ", sig->getTableId());
  fprintf(output, "Error code: %u, ", sig->getErrorCode());
  fprintf(output, "\n");

  return false;
}
<commit_msg>cxx compile fix for ndb<commit_after>/* Copyright (C) 2003 MySQL AB

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

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

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

#include <signaldata/CreateTrig.hpp>

bool printCREATE_TRIG_REQ(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
  const CreateTrigReq * const sig = (CreateTrigReq *) theData;

  //char triggerName[MAX_TAB_NAME_SIZE];
  char triggerType[32];
  char triggerActionTime[32];
  char triggerEvent[32];

  //sig->getTriggerName((char *) &triggerName);
  switch (sig->getTriggerType()) {
  case(TriggerType::SECONDARY_INDEX):
    snprintf(triggerType, sizeof(triggerType), "SECONDARY_INDEX");
    break;
  case(TriggerType::SUBSCRIPTION):
    snprintf(triggerType, sizeof(triggerType), "SUBSCRIPTION");
    break;
  case(TriggerType::ORDERED_INDEX):
    snprintf(triggerType, sizeof(triggerType), "ORDERED_INDEX");
    break;
  default:
    snprintf(triggerType, sizeof(triggerType), "UNKNOWN [%d]", (int)sig->getTriggerType());
    break;
  }
  switch (sig->getTriggerActionTime()) {
  case (TriggerActionTime::TA_BEFORE):
    snprintf(triggerActionTime, sizeof(triggerActionTime), "BEFORE");
    break;
  case(TriggerActionTime::TA_AFTER):
    snprintf(triggerActionTime, sizeof(triggerActionTime), "AFTER");
    break;
  case (TriggerActionTime::TA_DEFERRED):
    snprintf(triggerActionTime, sizeof(triggerActionTime), "DEFERRED");
    break;
  case (TriggerActionTime::TA_DETACHED):
    snprintf(triggerActionTime, sizeof(triggerActionTime), "DETACHED");
    break;
  default:
    snprintf(triggerActionTime, sizeof(triggerActionTime),
	     "UNKNOWN [%d]", (int)sig->getTriggerActionTime());
    break;
  }
  switch (sig->getTriggerEvent()) {
  case (TriggerEvent::TE_INSERT):
    snprintf(triggerEvent, sizeof(triggerEvent), "INSERT");
    break;
  case(TriggerEvent::TE_DELETE):
    snprintf(triggerEvent, sizeof(triggerEvent), "DELETE");
    break;
  case(TriggerEvent::TE_UPDATE):
    snprintf(triggerEvent, sizeof(triggerEvent), "UPDATE");
    break;
  case(TriggerEvent::TE_CUSTOM):
    snprintf(triggerEvent, sizeof(triggerEvent), "CUSTOM");
    break;
  default:
    snprintf(triggerEvent, sizeof(triggerEvent), "UNKNOWN [%d]", (int)sig->getTriggerEvent());
    break;
  }

  fprintf(output, "User: %u, ", sig->getUserRef());
  //fprintf(output, "Trigger name: \"%s\"\n", triggerName);
  fprintf(output, "Type: %s, ", triggerType);
  fprintf(output, "Action: %s, ", triggerActionTime);
  fprintf(output, "Event: %s, ", triggerEvent);
  fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
  fprintf(output, "Table id: %u, ", sig->getTableId());
  fprintf(output, "Monitor replicas: %s ", (sig->getMonitorReplicas())?"true":"false");
  fprintf(output, "Monitor all attributes: %s ", (sig->getMonitorAllAttributes())?"true":"false");
  const AttributeMask& attributeMask = sig->getAttributeMask();

  char buf[MAXNROFATTRIBUTESINWORDS * 8 + 1];
  fprintf(output, "Attribute mask: %s", attributeMask.getText(buf));
  fprintf(output, "\n");

  return false;
}

bool printCREATE_TRIG_CONF(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
  const CreateTrigConf * const sig = (CreateTrigConf *) theData;

  fprintf(output, "User: %u, ", sig->getUserRef());
  fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
  fprintf(output, "Table id: %u, ", sig->getTableId());
  fprintf(output, "\n");

  return false;
}

bool printCREATE_TRIG_REF(FILE * output, const Uint32 * theData, Uint32 len, Uint16 receiverBlockNo)
{
  const CreateTrigRef * const sig = (CreateTrigRef *) theData;

  fprintf(output, "User: %u, ", sig->getUserRef());
  fprintf(output, "Trigger id: %u, ", sig->getTriggerId());
  fprintf(output, "Table id: %u, ", sig->getTableId());
  fprintf(output, "Error code: %u, ", sig->getErrorCode());
  fprintf(output, "\n");

  return false;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VCartesianCoordinateSystem.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 01:38:43 $
 *
 *  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 _CHART2_VCARTESIAN_COORDINATESYSTEM_HXX
#define _CHART2_VCARTESIAN_COORDINATESYSTEM_HXX

#include "VCoordinateSystem.hxx"

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/
class VCartesianCoordinateSystem : public VCoordinateSystem
{
public:
    VCartesianCoordinateSystem( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XBoundedCoordinateSystem >& xCooSys );
    virtual ~VCartesianCoordinateSystem();

    virtual void createGridShapes();
    virtual void createAxesShapes( const ::com::sun::star::awt::Size& rReferenceSize, NumberFormatterWrapper* pNumberFormatterWrapper );

private:
    VCartesianCoordinateSystem();
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2006/08/25 17:16:47 iha 1.2.4.6: text- and diagram-size dependent auto main step width 2006/08/23 17:07:26 iha 1.2.4.5: enable axis to estimate the maximum automatic MainIncrementCount, reduce count to 2 for net charts 2006/08/10 15:53:28 iha 1.2.4.4: Axis Label Layout - Font&Diagram Size 2005/10/13 17:39:11 iha 1.2.4.3: renamed BoundedCoordinateSystem to CoordinateSystem 2005/10/07 12:17:17 bm 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2005/06/07 16:03:26 iha 1.2.4.1: use numberformatter from model<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VCartesianCoordinateSystem.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 19:11:10 $
 *
 *  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 _CHART2_VCARTESIAN_COORDINATESYSTEM_HXX
#define _CHART2_VCARTESIAN_COORDINATESYSTEM_HXX

#include "VCoordinateSystem.hxx"

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/
class VCartesianCoordinateSystem : public VCoordinateSystem
{
public:
    VCartesianCoordinateSystem( const ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XCoordinateSystem >& xCooSys );
    virtual ~VCartesianCoordinateSystem();

    virtual void createVAxisList(
            const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier > & xNumberFormatsSupplier
            , const ::com::sun::star::awt::Size& rFontReferenceSize
            , const ::com::sun::star::awt::Rectangle& rMaximumSpaceForLabels );

    virtual void initVAxisInList();
    virtual void updateScalesAndIncrementsOnAxes();

    virtual void createGridShapes();

private:
    VCartesianCoordinateSystem();
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>


<commit_before>/*
 * UnsavedFiles.hpp
 *
 * Copyright (C) 2009-18 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef CORE_LIBCLANG_UNSAVED_FILES_HPP
#define CORE_LIBCLANG_UNSAVED_FILES_HPP

#include <map>
#include <iosfwd>
#include <vector>

#include <boost/noncopyable.hpp>

#include "clang-c/Index.h"

namespace rstudio {
namespace core {
namespace libclang {

class UnsavedFiles : boost::noncopyable
{
public:
   UnsavedFiles() {}
   virtual ~UnsavedFiles();

   void update(const std::string& filename,
               const std::string& contents,
               bool dirty);
   void remove(const std::string& filename);
   void removeAll();

   CXUnsavedFile* unsavedFilesArray() { return files_.data(); }
   unsigned numUnsavedFiles() { return static_cast<unsigned>(files_.size()); }

private:
   // vector of unsaved files we pass to various clang functions
   std::vector<CXUnsavedFile> files_;
};

//  diagnosic helpers
std::ostream& operator << (std::ostream& ostr, UnsavedFiles& unsaved);

} // namespace libclang
} // namespace core
} // namespace rstudio

#endif // CORE_LIBCLANG_UNSAVED_FILES_HPP
<commit_msg>add missing header<commit_after>/*
 * UnsavedFiles.hpp
 *
 * Copyright (C) 2009-18 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef CORE_LIBCLANG_UNSAVED_FILES_HPP
#define CORE_LIBCLANG_UNSAVED_FILES_HPP

#include <map>
#include <iosfwd>
#include <vector>
#include <string>

#include <boost/noncopyable.hpp>

#include "clang-c/Index.h"

namespace rstudio {
namespace core {
namespace libclang {

class UnsavedFiles : boost::noncopyable
{
public:
   UnsavedFiles() {}
   virtual ~UnsavedFiles();

   void update(const std::string& filename,
               const std::string& contents,
               bool dirty);
   void remove(const std::string& filename);
   void removeAll();

   CXUnsavedFile* unsavedFilesArray() { return files_.data(); }
   unsigned numUnsavedFiles() { return static_cast<unsigned>(files_.size()); }

private:
   // vector of unsaved files we pass to various clang functions
   std::vector<CXUnsavedFile> files_;
};

//  diagnosic helpers
std::ostream& operator << (std::ostream& ostr, UnsavedFiles& unsaved);

} // namespace libclang
} // namespace core
} // namespace rstudio

#endif // CORE_LIBCLANG_UNSAVED_FILES_HPP
<|endoftext|>