<commit_before>/*
   Bacula® - The Network Backup Solution

   Copyright (C) 2007-2009 Free Software Foundation Europe e.V.

   The main author of Bacula is Kern Sibbald, with contributions from
   many others, a complete list can be found in the file AUTHORS.
   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version two of the GNU General Public
   License as published by the Free Software Foundation and included
   in the file LICENSE.

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

   Bacula® is a registered trademark of Kern Sibbald.
   The licensor of Bacula is the Free Software Foundation Europe
   (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
   Switzerland, email:ftf@fsfeurope.org.
*/

/*
 *   Version $Id$
 *
 *  MediaList Class
 *
 *   Dirk Bartley, March 2007
 *
 */

#include "bat.h"
#include <QAbstractEventDispatcher>
#include <QMenu>
#include <math.h>
#include "medialist.h"
#include "mediaedit/mediaedit.h"
#include "joblist/joblist.h"
#include "relabel/relabel.h"
#include "run/run.h"
#include "util/fmtwidgetitem.h"

MediaList::MediaList()
{
   setupUi(this);
   m_name = tr("Media");
   pgInitialize();
   QTreeWidgetItem* thisitem = mainWin->getFromHash(this);
   thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/cartridge.png")));

   /* mp_treeWidget, Storage Tree Tree Widget inherited from ui_medialist.h */
   m_populated = false;
   m_checkcurwidget = true;
   m_closeable = false;
   /* add context sensitive menu items specific to this classto the page
    * selector tree. m_contextActions is QList of QActions */
   m_contextActions.append(actionRefreshMediaList);
   dockPage();
}

MediaList::~MediaList()
{
   if (m_populated)
      writeExpandedSettings();
}

/*
 * The main meat of the class!!  The function that querries the director and
 * creates the widgets with appropriate values.
 */
void MediaList::populateTree()
{
   if (m_populated)
      writeExpandedSettings();
   m_populated = true;

   Freeze frz(*mp_treeWidget); /* disable updating*/

   QStringList headerlist = (QStringList()
      << tr("Volume Name") << tr("Id") << tr("Status") << tr("Enabled") << tr("Bytes") << tr("Files")
      << tr("Jobs") << tr("Retention") << tr("Media Type") << tr("Slot") << tr("Use Duration")
      << tr("Max Jobs") << tr("Max Files") << tr("Max Bytes") << tr("Recycle")
      << tr("RecyclePool") << tr("Last Written"));

   m_checkcurwidget = false;
   mp_treeWidget->clear();
   m_checkcurwidget = true;
   mp_treeWidget->setColumnCount(headerlist.count());
   m_topItem = new QTreeWidgetItem(mp_treeWidget);
   m_topItem->setText(0, tr("Pools"));
   m_topItem->setData(0, Qt::UserRole, 0);
   m_topItem->setExpanded(true);

   mp_treeWidget->setHeaderLabels(headerlist);

   QSettings settings(m_console->m_dir->name(), "bat");
   settings.beginGroup("MediaListTreeExpanded");
   QString query;

   QTreeWidgetItem *pooltreeitem;

   /* Comma separated list of pools first */
   bool first = true;
   QString pool_comsep("");
   foreach (QString pool_listItem, m_console->pool_list) {
      if (first) {
         pool_comsep += "'" + pool_listItem + "'";
         first = false;
      }
      else
         pool_comsep += ",'" + pool_listItem + "'";
   }
   /* Now use pool_comsep list to perform just one query */
   if (pool_comsep != "") {
      query =  "SELECT Pool.Name AS pul,"
         " Media.VolumeName AS Media, "
         " Media.MediaId AS Id, Media.VolStatus AS VolStatus,"
         " Media.Enabled AS Enabled, Media.VolBytes AS Bytes,"
         " Media.VolFiles AS FileCount, Media.VolJobs AS JobCount,"
         " Media.VolRetention AS VolumeRetention, Media.MediaType AS MediaType,"
         " Media.InChanger AS InChanger, Media.Slot AS Slot, "
         " Media.VolUseDuration AS UseDuration,"
         " Media.MaxVolJobs AS MaxJobs, Media.MaxVolFiles AS MaxFiles,"
         " Media.MaxVolBytes AS MaxBytes, Media.Recycle AS Recycle,"
         " Pol.Name AS RecyclePool, Media.LastWritten AS LastWritten"
         " FROM Media"
         " JOIN Pool ON (Media.PoolId=Pool.PoolId)"
         " LEFT OUTER JOIN Pool AS Pol ON (Media.RecyclePoolId=Pol.PoolId)"
         " WHERE ";
      query += " Pool.Name IN (" + pool_comsep + ")";
      query += " ORDER BY Pool.Name, Media";

      if (mainWin->m_sqlDebug) {
         Pmsg1(000, "MediaList query cmd : %s\n",query.toUtf8().data());
      }
      QStringList results;
      int counter = 0;
      if (m_console->sql_cmd(query, results)) {
         QStringList fieldlist;
         QString prev_pool("");
         QString this_pool("");

         /* Iterate through the lines of results. */
         foreach (QString resultline, results) {
            fieldlist = resultline.split("\t");
            this_pool = fieldlist.takeFirst();
            if (prev_pool != this_pool) {
               prev_pool = this_pool;
               pooltreeitem = new QTreeWidgetItem(m_topItem);
               pooltreeitem->setText(0, this_pool);
               pooltreeitem->setData(0, Qt::UserRole, 1);
            }
            if(settings.contains(this_pool)) {
               pooltreeitem->setExpanded(settings.value(this_pool).toBool());
            } else {
               pooltreeitem->setExpanded(true);
            }

            if (fieldlist.size() < 18)
               continue; // some fields missing, ignore row

            int index = 0;
            TreeItemFormatter mediaitem(*pooltreeitem, 2);

            /* Iterate through fields in the record */
            QStringListIterator fld(fieldlist);

            /* volname */
            mediaitem.setTextFld(index++, fld.next());

            /* id */
            mediaitem.setNumericFld(index++, fld.next());

            /* status */
            mediaitem.setVolStatusFld(index++, fld.next());

            /* enabled */
            mediaitem.setBoolFld(index++, fld.next());

            /* bytes */
            mediaitem.setBytesFld(index++, fld.next());

            /* files */
            mediaitem.setNumericFld(index++, fld.next());

            /* jobs */
            mediaitem.setNumericFld(index++, fld.next());

            /* retention */
            mediaitem.setDurationFld(index++, fld.next());

            /* media type */
            mediaitem.setTextFld(index++, fld.next());

            /* inchanger + slot */
            int inchanger = fld.next().toInt();
            if (inchanger) {
               mediaitem.setNumericFld(index++, fld.next());
            }
            else {
               /* volume not in changer, show blank slot */
               mediaitem.setNumericFld(index++, "");
               fld.next();
            }

            /* use duration */
            mediaitem.setDurationFld(index++, fld.next());

            /* max jobs */
            mediaitem.setNumericFld(index++, fld.next());

            /* max files */
            mediaitem.setNumericFld(index++, fld.next());

            /* max bytes */
            mediaitem.setBytesFld(index++, fld.next());

            /* recycle */
            mediaitem.setBoolFld(index++, fld.next());

            /* recycle pool */
            mediaitem.setTextFld(index++, fld.next());

            /* last written */
            mediaitem.setTextFld(index++, fld.next());

         } /* foreach resultline */
         counter += 1;
      } /* if results from query */
   } /* foreach pool_listItem */
   settings.endGroup();
   /* Resize the columns */
   for(int cnter=0; cnter<headerlist.count(); cnter++) {
      mp_treeWidget->resizeColumnToContents(cnter);
   }
}

/*
 * Called from the signal of the context sensitive menu!
 */
void MediaList::editVolume()
{
   MediaEdit* edit = new MediaEdit(mainWin->getFromHash(this), m_currentVolumeId);
   connect(edit, SIGNAL(destroyed()), this, SLOT(populateTree()));
}

/*
 * Called from the signal of the context sensitive menu!
 */
void MediaList::showJobs()
{
   QTreeWidgetItem *parentItem = mainWin->getFromHash(this);
   mainWin->createPageJobList(m_currentVolumeName, "", "", "", parentItem);
}

/*
 * When the treeWidgetItem in the page selector tree is singleclicked, Make sure
 * The tree has been populated.
 */
void MediaList::PgSeltreeWidgetClicked()
{
   if (!m_populated) {
      populateTree();
      createContextMenu();
   }
}

/*
 * Added to set the context menu policy based on currently active treeWidgetItem
 * signaled by currentItemChanged
 */
void MediaList::treeItemChanged(QTreeWidgetItem *currentwidgetitem, QTreeWidgetItem *previouswidgetitem )
{
   /* m_checkcurwidget checks to see if this is during a refresh, which will segfault */
   if (m_checkcurwidget) {
      /* The Previous item */
      if (previouswidgetitem) { /* avoid a segfault if first time */
         foreach(QAction* mediaAction, mp_treeWidget->actions()) {
            mp_treeWidget->removeAction(mediaAction);
         }
      }

      int treedepth = currentwidgetitem->data(0, Qt::UserRole).toInt();
      m_currentVolumeName=currentwidgetitem->text(0);
      mp_treeWidget->addAction(actionRefreshMediaList);
      if (treedepth == 2){
         m_currentVolumeId=currentwidgetitem->text(1);
         mp_treeWidget->addAction(actionEditVolume);
         mp_treeWidget->addAction(actionListJobsOnVolume);
         mp_treeWidget->addAction(actionDeleteVolume);
         mp_treeWidget->addAction(actionPruneVolume);
         mp_treeWidget->addAction(actionPurgeVolume);
         mp_treeWidget->addAction(actionRelabelVolume);
         mp_treeWidget->addAction(actionVolumeFromPool);
      } else if (treedepth == 1) {
         mp_treeWidget->addAction(actionAllVolumesFromPool);
      }
   }
}

/*
 * Setup a context menu
 * Made separate from populate so that it would not create context menu over and
 * over as the tree is repopulated.
 */
void MediaList::createContextMenu()
{
   mp_treeWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
   connect(actionEditVolume, SIGNAL(triggered()), this, SLOT(editVolume()));
   connect(actionListJobsOnVolume, SIGNAL(triggered()), this, SLOT(showJobs()));
   connect(actionDeleteVolume, SIGNAL(triggered()), this, SLOT(deleteVolume()));
   connect(actionPurgeVolume, SIGNAL(triggered()), this, SLOT(purgeVolume()));
   connect(actionPruneVolume, SIGNAL(triggered()), this, SLOT(pruneVolume()));
   connect(actionRelabelVolume, SIGNAL(triggered()), this, SLOT(relabelVolume()));
   connect(mp_treeWidget, SIGNAL(
           currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
           this, SLOT(treeItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
   /* connect to the action specific to this pages class */
   connect(actionRefreshMediaList, SIGNAL(triggered()), this,
                SLOT(populateTree()));
   connect(actionAllVolumes, SIGNAL(triggered()), this, SLOT(allVolumes()));
   connect(actionAllVolumesFromPool, SIGNAL(triggered()), this, SLOT(allVolumesFromPool()));
   connect(actionVolumeFromPool, SIGNAL(triggered()), this, SLOT(volumeFromPool()));
}

/*
 * Virtual function which is called when this page is visible on the stack
 */
void MediaList::currentStackItem()
{
   if(!m_populated) {
      populateTree();
      /* Create the context menu for the medialist tree */
      createContextMenu();
   }
}

/*
 * Called from the signal of the context sensitive menu to delete a volume!
 */
void MediaList::deleteVolume()
{
   if (QMessageBox::warning(this, "Bat",
      tr("Are you sure you want to delete??  !!!.\n"
"This delete command is used to delete a Volume record and all associated catalog"
" records that were created. This command operates only on the Catalog"
" database and has no effect on the actual data written to a Volume. This"
" command can be dangerous and we strongly recommend that you do not use"
" it unless you know what you are doing.  All Jobs and all associated"
" records (File and JobMedia) will be deleted from the catalog."
      "Press OK to proceed with delete operation.?"),
      QMessageBox::Ok | QMessageBox::Cancel)
      == QMessageBox::Cancel) { return; }

   QString cmd("delete volume=");
   cmd += m_currentVolumeName;
   consoleCommand(cmd);
}

/*
 * Called from the signal of the context sensitive menu to purge!
 */
void MediaList::purgeVolume()
{
   if (QMessageBox::warning(this, "Bat",
      tr("Are you sure you want to purge ??  !!!.\n"
"The Purge command will delete associated Catalog database records from Jobs and"
" Volumes without considering the retention period. Purge  works only on the"
" Catalog database and does not affect data written to Volumes. This command can"
" be dangerous because you can delete catalog records associated with current"
" backups of files, and we recommend that you do not use it unless you know what"
" you are doing.\n"
      "Press OK to proceed with the purge operation?"),
      QMessageBox::Ok | QMessageBox::Cancel)
      == QMessageBox::Cancel) { return; }

   QString cmd("purge volume=");
   cmd += m_currentVolumeName;
   consoleCommand(cmd);
   populateTree();
}

/*
 * Called from the signal of the context sensitive menu to prune!
 */
void MediaList::pruneVolume()
{
   new prunePage(m_currentVolumeName, "");
}

/*
 * Called from the signal of the context sensitive menu to relabel!
 */
void MediaList::relabelVolume()
{
   setConsoleCurrent();
   new relabelDialog(m_console, m_currentVolumeName);
}

/*
 * Called from the signal of the context sensitive menu to purge!
 */
void MediaList::allVolumesFromPool()
{
   QString cmd = "update volume AllFromPool=" + m_currentVolumeName;
   consoleCommand(cmd);
   populateTree();
}

void MediaList::allVolumes()
{
   QString cmd = "update volume allfrompools";
   consoleCommand(cmd);
   populateTree();
}

/*
 * Called from the signal of the context sensitive menu to purge!
 */
void MediaList::volumeFromPool()
{
   QTreeWidgetItem *currentItem = mp_treeWidget->currentItem();
   QTreeWidgetItem *parent = currentItem->parent();
   QString pool = parent->text(0);
   QString cmd;
   cmd = "update volume=" + m_currentVolumeName + " frompool=" + pool;
   consoleCommand(cmd);
   populateTree();
}

/*
 * Write settings to save expanded states of the pools
 */
void MediaList::writeExpandedSettings()
{
   if (m_topItem) {
      QSettings settings(m_console->m_dir->name(), "bat");
      settings.beginGroup("MediaListTreeExpanded");
      int childcount = m_topItem->childCount();
      for (int cnt=0; cnt<childcount; cnt++) {
         QTreeWidgetItem *poolitem = m_topItem->child(cnt);
         settings.setValue(poolitem->text(0), poolitem->isExpanded());
      }
      settings.endGroup();
   }
}
<commit_msg>Add columns to the tree to show read/write time, scratch pool, recycle count.<commit_after>/*
   Bacula® - The Network Backup Solution

   Copyright (C) 2007-2009 Free Software Foundation Europe e.V.

   The main author of Bacula is Kern Sibbald, with contributions from
   many others, a complete list can be found in the file AUTHORS.
   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version two of the GNU General Public
   License as published by the Free Software Foundation and included
   in the file LICENSE.

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

   Bacula® is a registered trademark of Kern Sibbald.
   The licensor of Bacula is the Free Software Foundation Europe
   (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
   Switzerland, email:ftf@fsfeurope.org.
*/

/*
 *   Version $Id$
 *
 *  MediaList Class
 *
 *   Dirk Bartley, March 2007
 *
 */

#include "bat.h"
#include <QAbstractEventDispatcher>
#include <QMenu>
#include <math.h>
#include "medialist.h"
#include "mediaedit/mediaedit.h"
#include "joblist/joblist.h"
#include "relabel/relabel.h"
#include "run/run.h"
#include "util/fmtwidgetitem.h"

MediaList::MediaList()
{
   setupUi(this);
   m_name = tr("Media");
   pgInitialize();
   QTreeWidgetItem* thisitem = mainWin->getFromHash(this);
   thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/cartridge.png")));

   /* mp_treeWidget, Storage Tree Tree Widget inherited from ui_medialist.h */
   m_populated = false;
   m_checkcurwidget = true;
   m_closeable = false;
   /* add context sensitive menu items specific to this classto the page
    * selector tree. m_contextActions is QList of QActions */
   m_contextActions.append(actionRefreshMediaList);
   dockPage();
}

MediaList::~MediaList()
{
   if (m_populated)
      writeExpandedSettings();
}

/*
 * The main meat of the class!!  The function that querries the director and
 * creates the widgets with appropriate values.
 */
void MediaList::populateTree()
{
   if (m_populated)
      writeExpandedSettings();
   m_populated = true;

   Freeze frz(*mp_treeWidget); /* disable updating*/

   QStringList headerlist = (QStringList()
      << tr("Volume Name") << tr("Id") << tr("Status") << tr("Enabled") << tr("Bytes") << tr("Files")
      << tr("Jobs") << tr("Retention") << tr("Media Type") << tr("Slot") << tr("Use Duration")
      << tr("Max Jobs") << tr("Max Files") << tr("Max Bytes") << tr("Recycle")
      << tr("Last Written") << tr("First Written") << tr("Read Time")
      << tr("Write Time") << tr("Recycle Count") << tr("Recycle Pool") << tr("Scratch Pool"));

   m_checkcurwidget = false;
   mp_treeWidget->clear();
   m_checkcurwidget = true;
   mp_treeWidget->setColumnCount(headerlist.count());
   m_topItem = new QTreeWidgetItem(mp_treeWidget);
   m_topItem->setText(0, tr("Pools"));
   m_topItem->setData(0, Qt::UserRole, 0);
   m_topItem->setExpanded(true);

   mp_treeWidget->setHeaderLabels(headerlist);

   QSettings settings(m_console->m_dir->name(), "bat");
   settings.beginGroup("MediaListTreeExpanded");
   QString query;

   QTreeWidgetItem *pooltreeitem;

   /* Comma separated list of pools first */
   bool first = true;
   QString pool_comsep("");
   foreach (QString pool_listItem, m_console->pool_list) {
      if (first) {
         pool_comsep += "'" + pool_listItem + "'";
         first = false;
      }
      else
         pool_comsep += ",'" + pool_listItem + "'";
   }
   /* Now use pool_comsep list to perform just one query */
   if (pool_comsep != "") {
      query =  "SELECT Pool.Name AS pul,"
         " Media.VolumeName AS Media, "
         " Media.MediaId AS Id, Media.VolStatus AS VolStatus,"
         " Media.Enabled AS Enabled, Media.VolBytes AS Bytes,"
         " Media.VolFiles AS FileCount, Media.VolJobs AS JobCount,"
         " Media.VolRetention AS VolumeRetention, Media.MediaType AS MediaType,"
         " Media.InChanger AS InChanger, Media.Slot AS Slot, "
         " Media.VolUseDuration AS UseDuration,"
         " Media.MaxVolJobs AS MaxJobs, Media.MaxVolFiles AS MaxFiles,"
         " Media.MaxVolBytes AS MaxBytes, Media.Recycle AS Recycle,"
         " Media.LastWritten AS LastWritten,"
         " Media.FirstWritten AS FirstWritten,"
         " (VolReadTime/1000000) AS ReadTime, (VolWriteTime/1000000) AS WriteTime,"
         " RecycleCount AS ReCyCount,"
         " RecPool.Name AS RecyclePool, ScrPool.Name AS ScratchPool"
         " FROM Media"
         " JOIN Pool ON (Media.PoolId=Pool.PoolId)"
         " LEFT OUTER JOIN Pool AS RecPool ON (Media.RecyclePoolId=RecPool.PoolId)"
         " LEFT OUTER JOIN Pool AS ScrPool ON (Media.ScratchPoolId=ScrPool.PoolId)"
         " WHERE ";
      query += " Pool.Name IN (" + pool_comsep + ")";
      query += " ORDER BY Pool.Name, Media";

      if (mainWin->m_sqlDebug) {
         Pmsg1(000, "MediaList query cmd : %s\n",query.toUtf8().data());
      }
      QStringList results;
      int counter = 0;
      if (m_console->sql_cmd(query, results)) {
         QStringList fieldlist;
         QString prev_pool("");
         QString this_pool("");

         /* Iterate through the lines of results. */
         foreach (QString resultline, results) {
            fieldlist = resultline.split("\t");
            this_pool = fieldlist.takeFirst();
            if (prev_pool != this_pool) {
               prev_pool = this_pool;
               pooltreeitem = new QTreeWidgetItem(m_topItem);
               pooltreeitem->setText(0, this_pool);
               pooltreeitem->setData(0, Qt::UserRole, 1);
            }
            if(settings.contains(this_pool)) {
               pooltreeitem->setExpanded(settings.value(this_pool).toBool());
            } else {
               pooltreeitem->setExpanded(true);
            }

            if (fieldlist.size() < 18)
               continue; // some fields missing, ignore row

            int index = 0;
            TreeItemFormatter mediaitem(*pooltreeitem, 2);

            /* Iterate through fields in the record */
            QStringListIterator fld(fieldlist);

            /* volname */
            mediaitem.setTextFld(index++, fld.next());

            /* id */
            mediaitem.setNumericFld(index++, fld.next());

            /* status */
            mediaitem.setVolStatusFld(index++, fld.next());

            /* enabled */
            mediaitem.setBoolFld(index++, fld.next());

            /* bytes */
            mediaitem.setBytesFld(index++, fld.next());

            /* files */
            mediaitem.setNumericFld(index++, fld.next());

            /* jobs */
            mediaitem.setNumericFld(index++, fld.next());

            /* retention */
            mediaitem.setDurationFld(index++, fld.next());

            /* media type */
            mediaitem.setTextFld(index++, fld.next());

            /* inchanger + slot */
            int inchanger = fld.next().toInt();
            if (inchanger) {
               mediaitem.setNumericFld(index++, fld.next());
            }
            else {
               /* volume not in changer, show blank slot */
               mediaitem.setNumericFld(index++, "");
               fld.next();
            }

            /* use duration */
            mediaitem.setDurationFld(index++, fld.next());

            /* max jobs */
            mediaitem.setNumericFld(index++, fld.next());

            /* max files */
            mediaitem.setNumericFld(index++, fld.next());

            /* max bytes */
            mediaitem.setBytesFld(index++, fld.next());

            /* recycle */
            mediaitem.setBoolFld(index++, fld.next());

            /* last written */
            mediaitem.setTextFld(index++, fld.next());

            /* first written */
            mediaitem.setTextFld(index++, fld.next());

            /* read time */
            mediaitem.setDurationFld(index++, fld.next());

            /* write time */
            mediaitem.setDurationFld(index++, fld.next());

            /* Recycle Count */
            mediaitem.setNumericFld(index++, fld.next());

            /* recycle pool */
            mediaitem.setTextFld(index++, fld.next());

            /* Scratch pool */
            mediaitem.setTextFld(index++, fld.next());

         } /* foreach resultline */
         counter += 1;
      } /* if results from query */
   } /* foreach pool_listItem */
   settings.endGroup();
   /* Resize the columns */
   for(int cnter=0; cnter<headerlist.count(); cnter++) {
      mp_treeWidget->resizeColumnToContents(cnter);
   }
}

/*
 * Called from the signal of the context sensitive menu!
 */
void MediaList::editVolume()
{
   MediaEdit* edit = new MediaEdit(mainWin->getFromHash(this), m_currentVolumeId);
   connect(edit, SIGNAL(destroyed()), this, SLOT(populateTree()));
}

/*
 * Called from the signal of the context sensitive menu!
 */
void MediaList::showJobs()
{
   QTreeWidgetItem *parentItem = mainWin->getFromHash(this);
   mainWin->createPageJobList(m_currentVolumeName, "", "", "", parentItem);
}

/*
 * When the treeWidgetItem in the page selector tree is singleclicked, Make sure
 * The tree has been populated.
 */
void MediaList::PgSeltreeWidgetClicked()
{
   if (!m_populated) {
      populateTree();
      createContextMenu();
   }
}

/*
 * Added to set the context menu policy based on currently active treeWidgetItem
 * signaled by currentItemChanged
 */
void MediaList::treeItemChanged(QTreeWidgetItem *currentwidgetitem, QTreeWidgetItem *previouswidgetitem )
{
   /* m_checkcurwidget checks to see if this is during a refresh, which will segfault */
   if (m_checkcurwidget) {
      /* The Previous item */
      if (previouswidgetitem) { /* avoid a segfault if first time */
         foreach(QAction* mediaAction, mp_treeWidget->actions()) {
            mp_treeWidget->removeAction(mediaAction);
         }
      }

      int treedepth = currentwidgetitem->data(0, Qt::UserRole).toInt();
      m_currentVolumeName=currentwidgetitem->text(0);
      mp_treeWidget->addAction(actionRefreshMediaList);
      if (treedepth == 2){
         m_currentVolumeId=currentwidgetitem->text(1);
         mp_treeWidget->addAction(actionEditVolume);
         mp_treeWidget->addAction(actionListJobsOnVolume);
         mp_treeWidget->addAction(actionDeleteVolume);
         mp_treeWidget->addAction(actionPruneVolume);
         mp_treeWidget->addAction(actionPurgeVolume);
         mp_treeWidget->addAction(actionRelabelVolume);
         mp_treeWidget->addAction(actionVolumeFromPool);
      } else if (treedepth == 1) {
         mp_treeWidget->addAction(actionAllVolumesFromPool);
      }
   }
}

/*
 * Setup a context menu
 * Made separate from populate so that it would not create context menu over and
 * over as the tree is repopulated.
 */
void MediaList::createContextMenu()
{
   mp_treeWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
   connect(actionEditVolume, SIGNAL(triggered()), this, SLOT(editVolume()));
   connect(actionListJobsOnVolume, SIGNAL(triggered()), this, SLOT(showJobs()));
   connect(actionDeleteVolume, SIGNAL(triggered()), this, SLOT(deleteVolume()));
   connect(actionPurgeVolume, SIGNAL(triggered()), this, SLOT(purgeVolume()));
   connect(actionPruneVolume, SIGNAL(triggered()), this, SLOT(pruneVolume()));
   connect(actionRelabelVolume, SIGNAL(triggered()), this, SLOT(relabelVolume()));
   connect(mp_treeWidget, SIGNAL(
           currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
           this, SLOT(treeItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)));
   /* connect to the action specific to this pages class */
   connect(actionRefreshMediaList, SIGNAL(triggered()), this,
                SLOT(populateTree()));
   connect(actionAllVolumes, SIGNAL(triggered()), this, SLOT(allVolumes()));
   connect(actionAllVolumesFromPool, SIGNAL(triggered()), this, SLOT(allVolumesFromPool()));
   connect(actionVolumeFromPool, SIGNAL(triggered()), this, SLOT(volumeFromPool()));
}

/*
 * Virtual function which is called when this page is visible on the stack
 */
void MediaList::currentStackItem()
{
   if(!m_populated) {
      populateTree();
      /* Create the context menu for the medialist tree */
      createContextMenu();
   }
}

/*
 * Called from the signal of the context sensitive menu to delete a volume!
 */
void MediaList::deleteVolume()
{
   if (QMessageBox::warning(this, "Bat",
      tr("Are you sure you want to delete??  !!!.\n"
"This delete command is used to delete a Volume record and all associated catalog"
" records that were created. This command operates only on the Catalog"
" database and has no effect on the actual data written to a Volume. This"
" command can be dangerous and we strongly recommend that you do not use"
" it unless you know what you are doing.  All Jobs and all associated"
" records (File and JobMedia) will be deleted from the catalog."
      "Press OK to proceed with delete operation.?"),
      QMessageBox::Ok | QMessageBox::Cancel)
      == QMessageBox::Cancel) { return; }

   QString cmd("delete volume=");
   cmd += m_currentVolumeName;
   consoleCommand(cmd);
}

/*
 * Called from the signal of the context sensitive menu to purge!
 */
void MediaList::purgeVolume()
{
   if (QMessageBox::warning(this, "Bat",
      tr("Are you sure you want to purge ??  !!!.\n"
"The Purge command will delete associated Catalog database records from Jobs and"
" Volumes without considering the retention period. Purge  works only on the"
" Catalog database and does not affect data written to Volumes. This command can"
" be dangerous because you can delete catalog records associated with current"
" backups of files, and we recommend that you do not use it unless you know what"
" you are doing.\n"
      "Press OK to proceed with the purge operation?"),
      QMessageBox::Ok | QMessageBox::Cancel)
      == QMessageBox::Cancel) { return; }

   QString cmd("purge volume=");
   cmd += m_currentVolumeName;
   consoleCommand(cmd);
   populateTree();
}

/*
 * Called from the signal of the context sensitive menu to prune!
 */
void MediaList::pruneVolume()
{
   new prunePage(m_currentVolumeName, "");
}

/*
 * Called from the signal of the context sensitive menu to relabel!
 */
void MediaList::relabelVolume()
{
   setConsoleCurrent();
   new relabelDialog(m_console, m_currentVolumeName);
}

/*
 * Called from the signal of the context sensitive menu to purge!
 */
void MediaList::allVolumesFromPool()
{
   QString cmd = "update volume AllFromPool=" + m_currentVolumeName;
   consoleCommand(cmd);
   populateTree();
}

void MediaList::allVolumes()
{
   QString cmd = "update volume allfrompools";
   consoleCommand(cmd);
   populateTree();
}

/*
 * Called from the signal of the context sensitive menu to purge!
 */
void MediaList::volumeFromPool()
{
   QTreeWidgetItem *currentItem = mp_treeWidget->currentItem();
   QTreeWidgetItem *parent = currentItem->parent();
   QString pool = parent->text(0);
   QString cmd;
   cmd = "update volume=" + m_currentVolumeName + " frompool=" + pool;
   consoleCommand(cmd);
   populateTree();
}

/*
 * Write settings to save expanded states of the pools
 */
void MediaList::writeExpandedSettings()
{
   if (m_topItem) {
      QSettings settings(m_console->m_dir->name(), "bat");
      settings.beginGroup("MediaListTreeExpanded");
      int childcount = m_topItem->childCount();
      for (int cnt=0; cnt<childcount; cnt++) {
         QTreeWidgetItem *poolitem = m_topItem->child(cnt);
         settings.setValue(poolitem->text(0), poolitem->isExpanded());
      }
      settings.endGroup();
   }
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg & Daniel Wallin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/time.hpp" // for total_seconds

#include <libtorrent/kademlia/traversal_algorithm.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include <libtorrent/kademlia/node.hpp>
#include <libtorrent/session_status.hpp>
#include "libtorrent/broadcast_socket.hpp" // for cidr_distance

#include <boost/bind.hpp>

namespace libtorrent { namespace dht
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DEFINE_LOG(traversal)
#endif

observer_ptr traversal_algorithm::new_observer(void* ptr
	, udp::endpoint const& ep, node_id const& id)
{
	observer_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id));
#ifdef TORRENT_DEBUG
	o->m_in_constructor = false;
#endif
	return o;
}

traversal_algorithm::traversal_algorithm(
	node_impl& node
	, node_id target)
	: m_ref_count(0)
	, m_node(node)
	, m_target(target)
	, m_invoke_count(0)
	, m_branch_factor(3)
	, m_responses(0)
	, m_timeouts(0)
	, m_num_target_nodes(m_node.m_table.bucket_size() * 2)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
	TORRENT_LOG(traversal) << " [" << this << "] new traversal process. Target: " << target;
#endif
}

bool compare_ip_cidr(observer_ptr const& lhs, observer_ptr const& rhs)
{
	TORRENT_ASSERT(lhs->target_addr().is_v4() == rhs->target_addr().is_v4());
	// the number of bits in the IPs that may match. If
	// more bits that this matches, something suspicious is
	// going on and we shouldn't add the second one to our
	// routing table
	int cutoff = rhs->target_addr().is_v4() ? 4 : 64;
	int dist = cidr_distance(lhs->target_addr(), rhs->target_addr());
	return dist <= cutoff;
}

void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags)
{
	TORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer));
	void* ptr = m_node.m_rpc.allocate_observer();
	if (ptr == 0)
	{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << "[" << this << ":" << name()
			<< "] failed to allocate memory for observer. aborting!";
#endif
		done();
		return;
	}
	observer_ptr o = new_observer(ptr, addr, id);
	if (id.is_all_zeros())
	{
		o->set_id(generate_id());
		o->flags |= observer::flag_no_id;
	}

	o->flags |= flags;

	std::vector<observer_ptr>::iterator i = std::lower_bound(
		m_results.begin()
		, m_results.end()
		, o
		, boost::bind(
			compare_ref
			, boost::bind(&observer::id, _1)
			, boost::bind(&observer::id, _2)
			, m_target
		)
	);

	if (i == m_results.end() || (*i)->id() != id)
	{
		if (m_node.settings().restrict_search_ips)
		{
			// don't allow multiple entries from IPs very close to each other
			std::vector<observer_ptr>::iterator j = std::find_if(
				m_results.begin(), m_results.end(), boost::bind(&compare_ip_cidr, _1, o));

			if (j != m_results.end())
			{
				// we already have a node in this search with an IP very
				// close to this one. We know that it's not the same, because
				// it claims a different node-ID. Ignore this to avoid attacks
#ifdef TORRENT_DHT_VERBOSE_LOGGING
			TORRENT_LOG(traversal) << "ignoring DHT search entry: " << o->id()
				<< " " << o->target_addr()
				<< " existing node: "
				<< (*j)->id() << " " << (*j)->target_addr();
#endif
				return;
			}
		}
		TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end()
			, boost::bind(&observer::id, _1) == id) == m_results.end());
#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << "[" << this << ":" << name()
			<< "] adding result: " << id << " " << addr;
#endif
		i = m_results.insert(i, o);
	}

	if (m_results.size() > 100) m_results.resize(100);
}

void traversal_algorithm::start()
{
	// in case the routing table is empty, use the
	// router nodes in the table
	if (m_results.empty()) add_router_entries();
	init();
	add_requests();
}

void* traversal_algorithm::allocate_observer()
{
	return m_node.m_rpc.allocate_observer();
}

void traversal_algorithm::free_observer(void* ptr)
{
	m_node.m_rpc.free_observer(ptr);
}

void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
	if (id.is_all_zeros())
		TORRENT_LOG(traversal) << time_now_string() << "[" << this << ":" << name()
			<< "] WARNING: node returned a list which included a node with id 0";
#endif
	add_entry(id, addr, 0);
}

void traversal_algorithm::finished(observer_ptr o)
{
#ifdef TORRENT_DEBUG
	std::vector<observer_ptr>::iterator i = std::find(
		m_results.begin(), m_results.end(), o);

	TORRENT_ASSERT(i != m_results.end() || m_results.size() == 100);
#endif

	// if this flag is set, it means we increased the
	// branch factor for it, and we should restore it
	if (o->flags & observer::flag_short_timeout)
		--m_branch_factor;

	TORRENT_ASSERT(o->flags & observer::flag_queried);
	o->flags |= observer::flag_alive;

	++m_responses;
	--m_invoke_count;
	TORRENT_ASSERT(m_invoke_count >= 0);
	add_requests();
	if (m_invoke_count == 0) done();
}

// prevent request means that the total number of requests has
// overflown. This query failed because it was the oldest one.
// So, if this is true, don't make another request
void traversal_algorithm::failed(observer_ptr o, int flags)
{
	TORRENT_ASSERT(m_invoke_count >= 0);

	if (m_results.empty()) return;

	TORRENT_ASSERT(o->flags & observer::flag_queried);
	if (flags & short_timeout)
	{
		// short timeout means that it has been more than
		// two seconds since we sent the request, and that
		// we'll most likely not get a response. But, in case
		// we do get a late response, keep the handler
		// around for some more, but open up the slot
		// by increasing the branch factor
		if ((o->flags & observer::flag_short_timeout) == 0)
			++m_branch_factor;
		o->flags |= observer::flag_short_timeout;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << " [" << this << ":" << name()
			<< "] first chance timeout: "
			<< o->id() << " " << o->target_ep()
			<< " branch-factor: " << m_branch_factor
			<< " invoke-count: " << m_invoke_count;
#endif
	}
	else
	{
		o->flags |= observer::flag_failed;
		// if this flag is set, it means we increased the
		// branch factor for it, and we should restore it
		if (o->flags & observer::flag_short_timeout)
			--m_branch_factor;

#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << " [" << this << ":" << name()
			<< "] failed: " << o->id() << " " << o->target_ep()
			<< " branch-factor: " << m_branch_factor
			<< " invoke-count: " << m_invoke_count;
#endif
		// don't tell the routing table about
		// node ids that we just generated ourself
		if ((o->flags & observer::flag_no_id) == 0)
			m_node.m_table.node_failed(o->id(), o->target_ep());
		++m_timeouts;
		--m_invoke_count;
		TORRENT_ASSERT(m_invoke_count >= 0);
	}

	if (flags & prevent_request)
	{
		--m_branch_factor;
		if (m_branch_factor <= 0) m_branch_factor = 1;
	}
	add_requests();
	if (m_invoke_count == 0) done();
}

void traversal_algorithm::done()
{
	// delete all our references to the observer objects so
	// they will in turn release the traversal algorithm
	m_results.clear();
}

namespace
{
	bool bitwise_nand(unsigned char lhs, unsigned char rhs)
	{
		return (lhs & rhs) == 0;
	}
}

void traversal_algorithm::add_requests()
{
	int results_target = m_num_target_nodes;

	// Find the first node that hasn't already been queried.
	for (std::vector<observer_ptr>::iterator i = m_results.begin()
		, end(m_results.end()); i != end
		&& results_target > 0 && m_invoke_count < m_branch_factor; ++i)
	{
		if ((*i)->flags & observer::flag_alive) --results_target;
		if ((*i)->flags & observer::flag_queried) continue;

#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << " [" << this << ":" << name() << "]"
			<< " nodes-left: " << (m_results.end() - i)
			<< " invoke-count: " << m_invoke_count
			<< " branch-factor: " << m_branch_factor;
#endif

		if (invoke(*i))
		{
			TORRENT_ASSERT(m_invoke_count >= 0);
			++m_invoke_count;
			(*i)->flags |= observer::flag_queried;
		}
	}
}

void traversal_algorithm::add_router_entries()
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
	TORRENT_LOG(traversal) << " using router nodes to initiate traversal algorithm. "
		<< std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << " routers";
#endif
	for (routing_table::router_iterator i = m_node.m_table.router_begin()
		, end(m_node.m_table.router_end()); i != end; ++i)
	{
		add_entry(node_id(0), *i, observer::flag_initial);
	}
}

void traversal_algorithm::init()
{
	// update the last activity of this bucket
	m_node.m_table.touch_bucket(m_target);
	m_branch_factor = m_node.branch_factor();
	m_node.add_traversal_algorithm(this);
}

traversal_algorithm::~traversal_algorithm()
{
	m_node.remove_traversal_algorithm(this);
}

void traversal_algorithm::status(dht_lookup& l)
{
	l.timeouts = m_timeouts;
	l.responses = m_responses;
	l.outstanding_requests = m_invoke_count;
	l.branch_factor = m_branch_factor;
	l.type = name();
	l.nodes_left = 0;
	l.first_timeout = 0;

	int last_sent = INT_MAX;
	ptime now = time_now();
	for (std::vector<observer_ptr>::iterator i = m_results.begin()
		, end(m_results.end()); i != end; ++i)
	{
		observer& o = **i;
		if (o.flags & observer::flag_queried)
		{
			last_sent = (std::min)(last_sent, total_seconds(now - o.sent()));
			if (o.has_short_timeout()) ++l.first_timeout;
			continue;
		}
		++l.nodes_left;
	}
	l.last_sent = last_sent;
}

} } // namespace libtorrent::dht

<commit_msg>fix DHT cidr check<commit_after>/*

Copyright (c) 2006, Arvid Norberg & Daniel Wallin
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/pch.hpp"

#include "libtorrent/time.hpp" // for total_seconds

#include <libtorrent/kademlia/traversal_algorithm.hpp>
#include <libtorrent/kademlia/routing_table.hpp>
#include <libtorrent/kademlia/rpc_manager.hpp>
#include <libtorrent/kademlia/node.hpp>
#include <libtorrent/session_status.hpp>
#include "libtorrent/broadcast_socket.hpp" // for cidr_distance

#include <boost/bind.hpp>

namespace libtorrent { namespace dht
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
TORRENT_DEFINE_LOG(traversal)
#endif

observer_ptr traversal_algorithm::new_observer(void* ptr
	, udp::endpoint const& ep, node_id const& id)
{
	observer_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id));
#ifdef TORRENT_DEBUG
	o->m_in_constructor = false;
#endif
	return o;
}

traversal_algorithm::traversal_algorithm(
	node_impl& node
	, node_id target)
	: m_ref_count(0)
	, m_node(node)
	, m_target(target)
	, m_invoke_count(0)
	, m_branch_factor(3)
	, m_responses(0)
	, m_timeouts(0)
	, m_num_target_nodes(m_node.m_table.bucket_size() * 2)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
	TORRENT_LOG(traversal) << " [" << this << "] new traversal process. Target: " << target;
#endif
}

// returns true of lhs and rhs are too close to each other to appear
// in the same DHT search under different node IDs
bool compare_ip_cidr(observer_ptr const& lhs, observer_ptr const& rhs)
{
	if (lhs->target_addr().is_v4() != rhs->target_addr().is_v4())
		return false;
	// the number of bits in the IPs that may match. If
	// more bits that this matches, something suspicious is
	// going on and we shouldn't add the second one to our
	// routing table
	int cutoff = rhs->target_addr().is_v4() ? 4 : 64;
	int dist = cidr_distance(lhs->target_addr(), rhs->target_addr());
	return dist <= cutoff;
}

void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags)
{
	TORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer));
	void* ptr = m_node.m_rpc.allocate_observer();
	if (ptr == 0)
	{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << "[" << this << ":" << name()
			<< "] failed to allocate memory for observer. aborting!";
#endif
		done();
		return;
	}
	observer_ptr o = new_observer(ptr, addr, id);
	if (id.is_all_zeros())
	{
		o->set_id(generate_id());
		o->flags |= observer::flag_no_id;
	}

	o->flags |= flags;

	std::vector<observer_ptr>::iterator i = std::lower_bound(
		m_results.begin()
		, m_results.end()
		, o
		, boost::bind(
			compare_ref
			, boost::bind(&observer::id, _1)
			, boost::bind(&observer::id, _2)
			, m_target
		)
	);

	if (i == m_results.end() || (*i)->id() != id)
	{
		if (m_node.settings().restrict_search_ips)
		{
			// don't allow multiple entries from IPs very close to each other
			std::vector<observer_ptr>::iterator j = std::find_if(
				m_results.begin(), m_results.end(), boost::bind(&compare_ip_cidr, _1, o));

			if (j != m_results.end())
			{
				// we already have a node in this search with an IP very
				// close to this one. We know that it's not the same, because
				// it claims a different node-ID. Ignore this to avoid attacks
#ifdef TORRENT_DHT_VERBOSE_LOGGING
			TORRENT_LOG(traversal) << "ignoring DHT search entry: " << o->id()
				<< " " << o->target_addr()
				<< " existing node: "
				<< (*j)->id() << " " << (*j)->target_addr();
#endif
				return;
			}
		}
		TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end()
			, boost::bind(&observer::id, _1) == id) == m_results.end());
#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << "[" << this << ":" << name()
			<< "] adding result: " << id << " " << addr;
#endif
		i = m_results.insert(i, o);
	}

	if (m_results.size() > 100) m_results.resize(100);
}

void traversal_algorithm::start()
{
	// in case the routing table is empty, use the
	// router nodes in the table
	if (m_results.empty()) add_router_entries();
	init();
	add_requests();
}

void* traversal_algorithm::allocate_observer()
{
	return m_node.m_rpc.allocate_observer();
}

void traversal_algorithm::free_observer(void* ptr)
{
	m_node.m_rpc.free_observer(ptr);
}

void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr)
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
	if (id.is_all_zeros())
		TORRENT_LOG(traversal) << time_now_string() << "[" << this << ":" << name()
			<< "] WARNING: node returned a list which included a node with id 0";
#endif
	add_entry(id, addr, 0);
}

void traversal_algorithm::finished(observer_ptr o)
{
#ifdef TORRENT_DEBUG
	std::vector<observer_ptr>::iterator i = std::find(
		m_results.begin(), m_results.end(), o);

	TORRENT_ASSERT(i != m_results.end() || m_results.size() == 100);
#endif

	// if this flag is set, it means we increased the
	// branch factor for it, and we should restore it
	if (o->flags & observer::flag_short_timeout)
		--m_branch_factor;

	TORRENT_ASSERT(o->flags & observer::flag_queried);
	o->flags |= observer::flag_alive;

	++m_responses;
	--m_invoke_count;
	TORRENT_ASSERT(m_invoke_count >= 0);
	add_requests();
	if (m_invoke_count == 0) done();
}

// prevent request means that the total number of requests has
// overflown. This query failed because it was the oldest one.
// So, if this is true, don't make another request
void traversal_algorithm::failed(observer_ptr o, int flags)
{
	TORRENT_ASSERT(m_invoke_count >= 0);

	if (m_results.empty()) return;

	TORRENT_ASSERT(o->flags & observer::flag_queried);
	if (flags & short_timeout)
	{
		// short timeout means that it has been more than
		// two seconds since we sent the request, and that
		// we'll most likely not get a response. But, in case
		// we do get a late response, keep the handler
		// around for some more, but open up the slot
		// by increasing the branch factor
		if ((o->flags & observer::flag_short_timeout) == 0)
			++m_branch_factor;
		o->flags |= observer::flag_short_timeout;
#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << " [" << this << ":" << name()
			<< "] first chance timeout: "
			<< o->id() << " " << o->target_ep()
			<< " branch-factor: " << m_branch_factor
			<< " invoke-count: " << m_invoke_count;
#endif
	}
	else
	{
		o->flags |= observer::flag_failed;
		// if this flag is set, it means we increased the
		// branch factor for it, and we should restore it
		if (o->flags & observer::flag_short_timeout)
			--m_branch_factor;

#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << " [" << this << ":" << name()
			<< "] failed: " << o->id() << " " << o->target_ep()
			<< " branch-factor: " << m_branch_factor
			<< " invoke-count: " << m_invoke_count;
#endif
		// don't tell the routing table about
		// node ids that we just generated ourself
		if ((o->flags & observer::flag_no_id) == 0)
			m_node.m_table.node_failed(o->id(), o->target_ep());
		++m_timeouts;
		--m_invoke_count;
		TORRENT_ASSERT(m_invoke_count >= 0);
	}

	if (flags & prevent_request)
	{
		--m_branch_factor;
		if (m_branch_factor <= 0) m_branch_factor = 1;
	}
	add_requests();
	if (m_invoke_count == 0) done();
}

void traversal_algorithm::done()
{
	// delete all our references to the observer objects so
	// they will in turn release the traversal algorithm
	m_results.clear();
}

namespace
{
	bool bitwise_nand(unsigned char lhs, unsigned char rhs)
	{
		return (lhs & rhs) == 0;
	}
}

void traversal_algorithm::add_requests()
{
	int results_target = m_num_target_nodes;

	// Find the first node that hasn't already been queried.
	for (std::vector<observer_ptr>::iterator i = m_results.begin()
		, end(m_results.end()); i != end
		&& results_target > 0 && m_invoke_count < m_branch_factor; ++i)
	{
		if ((*i)->flags & observer::flag_alive) --results_target;
		if ((*i)->flags & observer::flag_queried) continue;

#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(traversal) << " [" << this << ":" << name() << "]"
			<< " nodes-left: " << (m_results.end() - i)
			<< " invoke-count: " << m_invoke_count
			<< " branch-factor: " << m_branch_factor;
#endif

		if (invoke(*i))
		{
			TORRENT_ASSERT(m_invoke_count >= 0);
			++m_invoke_count;
			(*i)->flags |= observer::flag_queried;
		}
	}
}

void traversal_algorithm::add_router_entries()
{
#ifdef TORRENT_DHT_VERBOSE_LOGGING
	TORRENT_LOG(traversal) << " using router nodes to initiate traversal algorithm. "
		<< std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << " routers";
#endif
	for (routing_table::router_iterator i = m_node.m_table.router_begin()
		, end(m_node.m_table.router_end()); i != end; ++i)
	{
		add_entry(node_id(0), *i, observer::flag_initial);
	}
}

void traversal_algorithm::init()
{
	// update the last activity of this bucket
	m_node.m_table.touch_bucket(m_target);
	m_branch_factor = m_node.branch_factor();
	m_node.add_traversal_algorithm(this);
}

traversal_algorithm::~traversal_algorithm()
{
	m_node.remove_traversal_algorithm(this);
}

void traversal_algorithm::status(dht_lookup& l)
{
	l.timeouts = m_timeouts;
	l.responses = m_responses;
	l.outstanding_requests = m_invoke_count;
	l.branch_factor = m_branch_factor;
	l.type = name();
	l.nodes_left = 0;
	l.first_timeout = 0;

	int last_sent = INT_MAX;
	ptime now = time_now();
	for (std::vector<observer_ptr>::iterator i = m_results.begin()
		, end(m_results.end()); i != end; ++i)
	{
		observer& o = **i;
		if (o.flags & observer::flag_queried)
		{
			last_sent = (std::min)(last_sent, total_seconds(now - o.sent()));
			if (o.has_short_timeout()) ++l.first_timeout;
			continue;
		}
		++l.nodes_left;
	}
	l.last_sent = last_sent;
}

} } // namespace libtorrent::dht

<|endoftext|>


<commit_before><commit_msg>remove unnecessary calls to copy c'tor<commit_after><|endoftext|>


<commit_before>/*

Copyright (c) 2018, Johnathan Corkery. (jcorkery@umich.edu)
All rights reserved.

This file is part of the Dynacoe project (https://github.com/jcorks/Dynacoe)
Dynacoe was released under the MIT License, as detailed below.

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 OR COPYRIGHT HOLDERS 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 <Dynacoe/Modules/Graphics.h>
#include <Dynacoe/Util/Math.h>
#include <vector>
#include <cmath>
#include <sstream>
#include <Dynacoe/Util/Chain.h>
#include <Dynacoe/Util/Random.h>
#include <Dynacoe/FontAsset.h>
#include <Dynacoe/Components/Shape2D.h>
#include <Dynacoe/Util/Time.h>
#include <Dynacoe/Dynacoe.h>
#include <Dynacoe/Modules/ViewManager.h>
#include <Dynacoe/Components/Text2D.h>
#include <unordered_map>

#include <Dynacoe/Util/Chain.h>
#include <Dynacoe/Util/Vector.h>
#include <Dynacoe/Util/TransformMatrix.h>
#include <Dynacoe/Util/Filesys.h>

static const float DISPLAY_PIXEL_COORD_RATIO       =   1/(256.f);

using namespace Dynacoe;
using namespace std;

float *           Graphics::transformResult;
float *           Graphics::transformResult2;
float *           Graphics::quadVertices2D;

AssetID             Graphics::fontID;

bool                Graphics::autoRefresh;
int                 Graphics::filter;

Image *             Graphics::errorImage;
Renderer *        Graphics::drawBuffer;

AssetID             Graphics::lastDisplayID;

Graphics::GraphicsState     Graphics::state;
Graphics::FontSpec          Graphics::defaultFontSpec;

// The default coords for a quad being drawn via triangles
static float quadTex[] {
    0.f, 0.f,
    0.f, 1.f,
    1.f, 1.f,

    0.f, 0.f,
    1.f, 1.f,
    1.f, 0.f
};

/*
    DisplayTransform: A condensed implementation of the original OpenGL
    matrix transformation functions.

    It gives you more control, as you decide if / when
    these transformations are uploaded to the renderer.

    You can even give Transform the points that you wish
    to eventually render and obtain the corresponding
    homogenous points.

    Though, how you wish to optimize is up to you.

    Johnathan Corkery, 2014

*/

static std::string fSearch(const std::string &);

void Graphics::Init() {
        static bool spawned = false;

        if (spawned) return;
        spawned = true;
        errorImage = new Image( "BadImage");
        fontID = AssetID();

        autoRefresh = true;
        filter = true;

        // immediate init
        quadVertices2D  = new float[24];
        transformResult = new float[24];
        transformResult2 = new float[24];

        quadVertices2D[2] = quadVertices2D[6] = quadVertices2D[10] = quadVertices2D[14] = quadVertices2D[18] = quadVertices2D[22] = 0.f;
        quadVertices2D[3] = quadVertices2D[7] = quadVertices2D[11] = quadVertices2D[15] = quadVertices2D[19] = quadVertices2D[23] = 1.f;

        drawBuffer = (Renderer*)Backend::CreateDefaultRenderer();

        TransformMatrix identity;
        identity.SetToIdentity();
        identity.ReverseMajority();

        state.alpha = Renderer::AlphaRule::Opaque;
        state.polygon = Renderer::Polygon::Line;
        state.dim = Renderer::Dimension::D_2D;

        //state.currentCamera2D = GetCamera2D().GetID();
        SetCamera2D(GetCamera2D());
        state.currentCamera2D.IdentifyAs<Camera>()->SetType(Camera::Type::Orthographic2D);
        state.currentCamera3D = GetCamera3D().GetID();
        state.currentCamera3D.IdentifyAs<Camera>()->BindTransformBuffers(
            drawBuffer->GetStaticViewingMatrixID(),
            drawBuffer->GetStaticProjectionMatrixID()
        );
        state.currentCamera3D.IdentifyAs<Camera>()->SetType(Camera::Type::Perspective3D);
        SetRenderCamera(*state.currentCamera2D.IdentifyAs<Camera>());

        //GetCamera2D().node.local.reverse = true;

        Graphics::storeSystemImages(); // TODO: make proper. It should be that images stored with no renderer initialized are just cached until a display is given.

        setDisplayMode(Renderer::Polygon::Triangle,
                       Renderer::Dimension::D_2D,
                       Renderer::AlphaRule::Allow);

}

Backend * Graphics::GetBackend() {
    return Graphics::GetRenderer();
}

void Graphics::InitAfter() {
    Engine::AttachManager(state.currentCamera3D);
    Engine::AttachManager(state.currentCamera2D);
    Engine::AttachManager(state.currentCameraTarget);

}

void Graphics::DrawBefore() {

}

void Graphics::DrawAfter() {

}

void Graphics::RunBefore() {

}

void Graphics::RunAfter() {
}

static Renderer::Render2DStaticParameters params2D;

void Graphics::UpdateCameraTransforms(Camera * c) {
    Camera * cam2D = &Graphics::GetCamera2D();
    if (cam2D == c) {
        Graphics::GetRenderer()->Render2DVertices(params2D);
        params2D.contextWidth  = cam2D->Width();
        params2D.contextHeight = cam2D->Height();
        params2D.contextTransform = cam2D->GetGlobalTransform().GetData();
    }
}

void Graphics::Draw(Render2D & aspect) {
    aspect.CheckUpdate();

    Camera * cam2d = &GetCamera2D();
    if (!cam2d) return;

    setDisplayMode(aspect.GetPolygon(),
                   Renderer::Dimension::D_2D,
                   aspect.mode == Render2D::RenderMode::Translucent ? Renderer::AlphaRule::Translucent : Renderer::AlphaRule::Allow);

    if (round(params2D.contextWidth) != cam2d->Width() ||
        round(params2D.contextHeight) != cam2d->Height()) {
        UpdateCameraTransforms(cam2d);
    }

    drawBuffer->Queue2DVertices(
        &aspect.GetVertexIDs()[0],
        aspect.GetVertexIDs().size()
    );

}

void Graphics::Draw(RenderMesh & aspect) {

    // flush out any queued dynamic actions
    setDisplayMode(aspect.GetRenderPrimitive(),
                   Renderer::Dimension::D_3D,
                   Renderer::AlphaRule::Allow);

    drawBuffer->Render2DVertices(params2D);

    aspect.RenderSelf(drawBuffer);

    // if applicable, recursively draw children
    /*
    if (aspect.NumChildren()) {
        RenderMesh * ptr;
        for(uint32_t i = 0; i < aspect.NumChildren(); ++i) {
            if ((ptr = (RenderMesh*)&aspect.GetChild(i)) &&
                ptr != &aspect)
                Draw(*ptr);
        }
    }*/

}

void Graphics::setDisplayMode(Renderer::Polygon p, Renderer::Dimension d, Renderer::AlphaRule a) {
	if (state.polygon != p || state.alpha != a || state.dim != d) {

        // Settings with which to draw have changed, so we commit what we have and start over
        drawBuffer->SetDrawingMode(state.polygon, state.dim, state.alpha);
		drawBuffer->Render2DVertices(params2D);

	    state.alpha = a;
        state.polygon = p;
        state.dim = d;
        drawBuffer->SetDrawingMode(state.polygon, state.dim, state.alpha);

	}

}

Renderer * Graphics::GetRenderer() {
    return drawBuffer;
}

void Graphics::SetRenderer(Renderer * r) {
    drawBuffer = r;
}

void Graphics::Commit() {

    //GetRenderCamera().GetFramebuffer()->RunCommand("dump-texture", nullptr);
    //GetRenderCamera().GetFramebuffer()->RunCommand("fill-debug", nullptr);

    drawBuffer->Render2DVertices(params2D);
    setDisplayMode(Renderer::Polygon::Triangle,
                   Renderer::Dimension::D_2D,
                   Renderer::AlphaRule::Allow);

    Display * d = ViewManager::Get(ViewManager::GetCurrent());

    if (d)
        d->Update();

    Camera * c = &GetRenderCamera();
    if (c && c->autoRefresh) {
        c->Refresh();
    }
}

void Graphics::DrawEachFrame(bool doIt) {
    autoRefresh = doIt;
}

bool Graphics::DrawEachFrame() {
    return autoRefresh;
}

void Graphics::EnableFiltering(bool doIt) {
    if (!doIt) {
        drawBuffer->SetTextureFilter(Renderer::TexFilter::NoFilter);
        filter = false;
    } else {
        drawBuffer->SetTextureFilter(Renderer::TexFilter::Linear);
        filter = true;
    }
}

/*
Image * Graphics::_getPNG(string path) {
    InputBuffer i(path);
    if (!i.Size()) return NULL;

    return _getTilesetPNG(path, 1, 1);
}

Image * Graphics::_getTilesetPNG(string path, int wImages, int hImages) {

    RawImage_PNG img(path, wImages, hImages, drawBuffer);
    return img.getImage();

}

void Graphics::drawTranslucent(bool doIt) {
    translucent = doIt;
}
*/

void Graphics::storeFont() {
    /*
    string path = Params::GetDynacoeDirectory() + STR(IMG_PATH) + "font.png";

    Image * img = _getTilesetPNG(path, 21, 21);
    img->path = "font$SYS";
    addToCache(img);
    fontID = img->index;

    defaultFontSpec.height          = getImage(fontID).height;
    defaultFontSpec.width           = getImage(fontID).width / 2.0;

    defaultFontSpec.fontFlyphScaleWidth = .5f;
    */

    defaultFontSpec.height          = Assets::Get<Image>(fontID).frames[0].Height();
    defaultFontSpec.width           = Assets::Get<Image>(fontID).frames[0].Width();
    defaultFontSpec.fontGlyphScaleWidth = 1.0f;

    //^ how much space does the width of the glyph take up the frame?

}

void Graphics::SetCamera3D(Camera & c) {
    state.currentCamera3D = c.GetID();
    state.currentCamera3D.IdentifyAs<Camera>()->BindTransformBuffers(
        drawBuffer->GetStaticViewingMatrixID(),
        drawBuffer->GetStaticProjectionMatrixID()
    );
}

void Graphics::SetCamera2D(Camera & c) {
    auto cam = state.currentCamera2D.IdentifyAs<Camera>();
    if (cam) {
        cam->node.SetReverseTranslation(false);
    }
    state.currentCamera2D = c.GetID();
    c.node.SetReverseTranslation(true);
    cam->Invalidate();
}

void Graphics::SetRenderCamera(Camera & c) {
    Camera * cam = &c;
    if (!cam) return;

    drawBuffer->Render2DVertices(params2D);

    Display * d = ViewManager::Get(ViewManager::GetCurrent());

    Framebuffer * fb = cam->GetFramebuffer();
    drawBuffer->AttachTarget(fb);

    std::vector<ViewID> views = ViewManager::ListViews();
    for(uint32_t i = 0; i < views.size(); ++i) {
        ViewManager::Get(views[i])->AttachSource(fb);
    }

    state.currentCameraTarget = c.GetID();
    c.Step();
}

Camera & Graphics::GetCamera3D() {
    if (!state.currentCamera3D.IdentifyAs<Camera>()) {
        state.currentCamera3D = Entity::Create<Camera>();
        state.currentCamera3D.Identify()->SetName("Camera3D");
    }
    return *state.currentCamera3D.IdentifyAs<Camera>();
}

Camera & Graphics::GetCamera2D() {
    if (!state.currentCamera2D.IdentifyAs<Camera>()) {
        state.currentCamera2D = Entity::Create<Camera>();
        state.currentCamera2D.Identify()->SetName("Camera2D");

    }
    return *state.currentCamera2D.IdentifyAs<Camera>();
}

Camera & Graphics::GetRenderCamera() {
    if (!state.currentCameraTarget.IdentifyAs<Camera>()) {
        state.currentCameraTarget = Entity::Create<Camera>();
        state.currentCameraTarget.Identify()->SetName("RenderCamera");
    }
    return *state.currentCameraTarget.IdentifyAs<Camera>();
}

void Graphics::Flush2D() {
    drawBuffer->Render2DVertices(params2D);
}

/// statics ///

string fSearch(const string & file) {
    Filesys fs;
    string cd = fs.GetCWD();
    fs.ChangeDir(Engine::GetBaseDirectory());
    string fullPath = fs.FindFile(file);
    fs.ChangeDir(cd);
    return fullPath;
}
<commit_msg>dev: FIxed bug with re-updating a 2D camera after attachment with graphics<commit_after>/*

Copyright (c) 2018, Johnathan Corkery. (jcorkery@umich.edu)
All rights reserved.

This file is part of the Dynacoe project (https://github.com/jcorks/Dynacoe)
Dynacoe was released under the MIT License, as detailed below.

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 OR COPYRIGHT HOLDERS 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 <Dynacoe/Modules/Graphics.h>
#include <Dynacoe/Util/Math.h>
#include <vector>
#include <cmath>
#include <sstream>
#include <Dynacoe/Util/Chain.h>
#include <Dynacoe/Util/Random.h>
#include <Dynacoe/FontAsset.h>
#include <Dynacoe/Components/Shape2D.h>
#include <Dynacoe/Util/Time.h>
#include <Dynacoe/Dynacoe.h>
#include <Dynacoe/Modules/ViewManager.h>
#include <Dynacoe/Components/Text2D.h>
#include <unordered_map>

#include <Dynacoe/Util/Chain.h>
#include <Dynacoe/Util/Vector.h>
#include <Dynacoe/Util/TransformMatrix.h>
#include <Dynacoe/Util/Filesys.h>

static const float DISPLAY_PIXEL_COORD_RATIO       =   1/(256.f);

using namespace Dynacoe;
using namespace std;

float *           Graphics::transformResult;
float *           Graphics::transformResult2;
float *           Graphics::quadVertices2D;

AssetID             Graphics::fontID;

bool                Graphics::autoRefresh;
int                 Graphics::filter;

Image *             Graphics::errorImage;
Renderer *        Graphics::drawBuffer;

AssetID             Graphics::lastDisplayID;

Graphics::GraphicsState     Graphics::state;
Graphics::FontSpec          Graphics::defaultFontSpec;

// The default coords for a quad being drawn via triangles
static float quadTex[] {
    0.f, 0.f,
    0.f, 1.f,
    1.f, 1.f,

    0.f, 0.f,
    1.f, 1.f,
    1.f, 0.f
};

/*
    DisplayTransform: A condensed implementation of the original OpenGL
    matrix transformation functions.

    It gives you more control, as you decide if / when
    these transformations are uploaded to the renderer.

    You can even give Transform the points that you wish
    to eventually render and obtain the corresponding
    homogenous points.

    Though, how you wish to optimize is up to you.

    Johnathan Corkery, 2014

*/

static std::string fSearch(const std::string &);

void Graphics::Init() {
        static bool spawned = false;

        if (spawned) return;
        spawned = true;
        errorImage = new Image( "BadImage");
        fontID = AssetID();

        autoRefresh = true;
        filter = true;

        // immediate init
        quadVertices2D  = new float[24];
        transformResult = new float[24];
        transformResult2 = new float[24];

        quadVertices2D[2] = quadVertices2D[6] = quadVertices2D[10] = quadVertices2D[14] = quadVertices2D[18] = quadVertices2D[22] = 0.f;
        quadVertices2D[3] = quadVertices2D[7] = quadVertices2D[11] = quadVertices2D[15] = quadVertices2D[19] = quadVertices2D[23] = 1.f;

        drawBuffer = (Renderer*)Backend::CreateDefaultRenderer();

        TransformMatrix identity;
        identity.SetToIdentity();
        identity.ReverseMajority();

        state.alpha = Renderer::AlphaRule::Opaque;
        state.polygon = Renderer::Polygon::Line;
        state.dim = Renderer::Dimension::D_2D;

        //state.currentCamera2D = GetCamera2D().GetID();
        SetCamera2D(GetCamera2D());
        state.currentCamera2D.IdentifyAs<Camera>()->SetType(Camera::Type::Orthographic2D);
        state.currentCamera3D = GetCamera3D().GetID();
        state.currentCamera3D.IdentifyAs<Camera>()->BindTransformBuffers(
            drawBuffer->GetStaticViewingMatrixID(),
            drawBuffer->GetStaticProjectionMatrixID()
        );
        state.currentCamera3D.IdentifyAs<Camera>()->SetType(Camera::Type::Perspective3D);
        SetRenderCamera(*state.currentCamera2D.IdentifyAs<Camera>());

        //GetCamera2D().node.local.reverse = true;

        Graphics::storeSystemImages(); // TODO: make proper. It should be that images stored with no renderer initialized are just cached until a display is given.

        setDisplayMode(Renderer::Polygon::Triangle,
                       Renderer::Dimension::D_2D,
                       Renderer::AlphaRule::Allow);

}

Backend * Graphics::GetBackend() {
    return Graphics::GetRenderer();
}

void Graphics::InitAfter() {
    Engine::AttachManager(state.currentCamera3D);
    Engine::AttachManager(state.currentCamera2D);
    Engine::AttachManager(state.currentCameraTarget);

}

void Graphics::DrawBefore() {

}

void Graphics::DrawAfter() {

}

void Graphics::RunBefore() {

}

void Graphics::RunAfter() {
}

static Renderer::Render2DStaticParameters params2D;

void Graphics::UpdateCameraTransforms(Camera * c) {
    Camera * cam2D = &Graphics::GetCamera2D();
    if (cam2D == c) {
        Graphics::GetRenderer()->Render2DVertices(params2D);
        params2D.contextWidth  = cam2D->Width();
        params2D.contextHeight = cam2D->Height();
        params2D.contextTransform = cam2D->GetGlobalTransform().GetData();
    }
}

void Graphics::Draw(Render2D & aspect) {
    aspect.CheckUpdate();

    Camera * cam2d = &GetCamera2D();
    if (!cam2d) return;

    setDisplayMode(aspect.GetPolygon(),
                   Renderer::Dimension::D_2D,
                   aspect.mode == Render2D::RenderMode::Translucent ? Renderer::AlphaRule::Translucent : Renderer::AlphaRule::Allow);

    if (round(params2D.contextWidth) != cam2d->Width() ||
        round(params2D.contextHeight) != cam2d->Height()) {
        UpdateCameraTransforms(cam2d);
    }

    drawBuffer->Queue2DVertices(
        &aspect.GetVertexIDs()[0],
        aspect.GetVertexIDs().size()
    );

}

void Graphics::Draw(RenderMesh & aspect) {

    // flush out any queued dynamic actions
    setDisplayMode(aspect.GetRenderPrimitive(),
                   Renderer::Dimension::D_3D,
                   Renderer::AlphaRule::Allow);

    drawBuffer->Render2DVertices(params2D);

    aspect.RenderSelf(drawBuffer);

    // if applicable, recursively draw children
    /*
    if (aspect.NumChildren()) {
        RenderMesh * ptr;
        for(uint32_t i = 0; i < aspect.NumChildren(); ++i) {
            if ((ptr = (RenderMesh*)&aspect.GetChild(i)) &&
                ptr != &aspect)
                Draw(*ptr);
        }
    }*/

}

void Graphics::setDisplayMode(Renderer::Polygon p, Renderer::Dimension d, Renderer::AlphaRule a) {
	if (state.polygon != p || state.alpha != a || state.dim != d) {

        // Settings with which to draw have changed, so we commit what we have and start over
        drawBuffer->SetDrawingMode(state.polygon, state.dim, state.alpha);
		drawBuffer->Render2DVertices(params2D);

	    state.alpha = a;
        state.polygon = p;
        state.dim = d;
        drawBuffer->SetDrawingMode(state.polygon, state.dim, state.alpha);

	}

}

Renderer * Graphics::GetRenderer() {
    return drawBuffer;
}

void Graphics::SetRenderer(Renderer * r) {
    drawBuffer = r;
}

void Graphics::Commit() {

    //GetRenderCamera().GetFramebuffer()->RunCommand("dump-texture", nullptr);
    //GetRenderCamera().GetFramebuffer()->RunCommand("fill-debug", nullptr);

    drawBuffer->Render2DVertices(params2D);
    setDisplayMode(Renderer::Polygon::Triangle,
                   Renderer::Dimension::D_2D,
                   Renderer::AlphaRule::Allow);

    Display * d = ViewManager::Get(ViewManager::GetCurrent());

    if (d)
        d->Update();

    Camera * c = &GetRenderCamera();
    if (c && c->autoRefresh) {
        c->Refresh();
    }
}

void Graphics::DrawEachFrame(bool doIt) {
    autoRefresh = doIt;
}

bool Graphics::DrawEachFrame() {
    return autoRefresh;
}

void Graphics::EnableFiltering(bool doIt) {
    if (!doIt) {
        drawBuffer->SetTextureFilter(Renderer::TexFilter::NoFilter);
        filter = false;
    } else {
        drawBuffer->SetTextureFilter(Renderer::TexFilter::Linear);
        filter = true;
    }
}

/*
Image * Graphics::_getPNG(string path) {
    InputBuffer i(path);
    if (!i.Size()) return NULL;

    return _getTilesetPNG(path, 1, 1);
}

Image * Graphics::_getTilesetPNG(string path, int wImages, int hImages) {

    RawImage_PNG img(path, wImages, hImages, drawBuffer);
    return img.getImage();

}

void Graphics::drawTranslucent(bool doIt) {
    translucent = doIt;
}
*/

void Graphics::storeFont() {
    /*
    string path = Params::GetDynacoeDirectory() + STR(IMG_PATH) + "font.png";

    Image * img = _getTilesetPNG(path, 21, 21);
    img->path = "font$SYS";
    addToCache(img);
    fontID = img->index;

    defaultFontSpec.height          = getImage(fontID).height;
    defaultFontSpec.width           = getImage(fontID).width / 2.0;

    defaultFontSpec.fontFlyphScaleWidth = .5f;
    */

    defaultFontSpec.height          = Assets::Get<Image>(fontID).frames[0].Height();
    defaultFontSpec.width           = Assets::Get<Image>(fontID).frames[0].Width();
    defaultFontSpec.fontGlyphScaleWidth = 1.0f;

    //^ how much space does the width of the glyph take up the frame?

}

void Graphics::SetCamera3D(Camera & c) {
    state.currentCamera3D = c.GetID();
    state.currentCamera3D.IdentifyAs<Camera>()->BindTransformBuffers(
        drawBuffer->GetStaticViewingMatrixID(),
        drawBuffer->GetStaticProjectionMatrixID()
    );
}

void Graphics::SetCamera2D(Camera & c) {
    auto cam = state.currentCamera2D.IdentifyAs<Camera>();
    if (cam) {
        cam->node.SetReverseTranslation(false);
    }
    state.currentCamera2D = c.GetID();
    c.node.SetReverseTranslation(true);
    c.Invalidate();
}

void Graphics::SetRenderCamera(Camera & c) {
    Camera * cam = &c;
    if (!cam) return;

    drawBuffer->Render2DVertices(params2D);

    Display * d = ViewManager::Get(ViewManager::GetCurrent());

    Framebuffer * fb = cam->GetFramebuffer();
    drawBuffer->AttachTarget(fb);

    std::vector<ViewID> views = ViewManager::ListViews();
    for(uint32_t i = 0; i < views.size(); ++i) {
        ViewManager::Get(views[i])->AttachSource(fb);
    }

    state.currentCameraTarget = c.GetID();
    c.Step();
}

Camera & Graphics::GetCamera3D() {
    if (!state.currentCamera3D.IdentifyAs<Camera>()) {
        state.currentCamera3D = Entity::Create<Camera>();
        state.currentCamera3D.Identify()->SetName("Camera3D");
    }
    return *state.currentCamera3D.IdentifyAs<Camera>();
}

Camera & Graphics::GetCamera2D() {
    if (!state.currentCamera2D.IdentifyAs<Camera>()) {
        state.currentCamera2D = Entity::Create<Camera>();
        state.currentCamera2D.Identify()->SetName("Camera2D");

    }
    return *state.currentCamera2D.IdentifyAs<Camera>();
}

Camera & Graphics::GetRenderCamera() {
    if (!state.currentCameraTarget.IdentifyAs<Camera>()) {
        state.currentCameraTarget = Entity::Create<Camera>();
        state.currentCameraTarget.Identify()->SetName("RenderCamera");
    }
    return *state.currentCameraTarget.IdentifyAs<Camera>();
}

void Graphics::Flush2D() {
    drawBuffer->Render2DVertices(params2D);
}

/// statics ///

string fSearch(const string & file) {
    Filesys fs;
    string cd = fs.GetCWD();
    fs.ChangeDir(Engine::GetBaseDirectory());
    string fullPath = fs.FindFile(file);
    fs.ChangeDir(cd);
    return fullPath;
}
<|endoftext|>


<commit_before><commit_msg>another memory leak based on release().release()<commit_after><|endoftext|>


<commit_before><commit_msg>CID#703984 Unchecked return value (CHECKED_RETURN)<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: indexmap.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 11:29:56 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#include <memory.h>

#include "indexmap.hxx"

ScIndexMap::ScIndexMap( USHORT nEntries )
{
    nCount = nEntries;
    ULONG nC = nEntries ? ((ULONG) nEntries * 2) : 2;
    pMap = new USHORT [ nC ];
    memset( pMap, 0, nC * sizeof(USHORT) );
}

ScIndexMap::~ScIndexMap()
{
    delete [] pMap;
}

void ScIndexMap::SetPair( USHORT nEntry, USHORT nIndex1, USHORT nIndex2 )
{
    if ( nEntry < nCount )
    {
        ULONG nOff = (ULONG) nEntry * 2;
        pMap[nOff] = nIndex1;
        pMap[nOff+1] = nIndex2;
    }
}

USHORT ScIndexMap::Find( USHORT nIndex1 ) const
{
    USHORT* pStop = pMap + (ULONG) nCount * 2;
    for ( USHORT* pOff = pMap; pOff < pStop; pOff += 2 )
    {
        if ( *pOff == nIndex1 )
            return *(pOff+1);
    }
    return nIndex1;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.3.492); FILE MERGED 2008/03/31 17:14:16 rt 1.3.492.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: indexmap.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#include <memory.h>

#include "indexmap.hxx"

ScIndexMap::ScIndexMap( USHORT nEntries )
{
    nCount = nEntries;
    ULONG nC = nEntries ? ((ULONG) nEntries * 2) : 2;
    pMap = new USHORT [ nC ];
    memset( pMap, 0, nC * sizeof(USHORT) );
}

ScIndexMap::~ScIndexMap()
{
    delete [] pMap;
}

void ScIndexMap::SetPair( USHORT nEntry, USHORT nIndex1, USHORT nIndex2 )
{
    if ( nEntry < nCount )
    {
        ULONG nOff = (ULONG) nEntry * 2;
        pMap[nOff] = nIndex1;
        pMap[nOff+1] = nIndex2;
    }
}

USHORT ScIndexMap::Find( USHORT nIndex1 ) const
{
    USHORT* pStop = pMap + (ULONG) nCount * 2;
    for ( USHORT* pOff = pMap; pOff < pStop; pOff += 2 )
    {
        if ( *pOff == nIndex1 )
            return *(pOff+1);
    }
    return nIndex1;
}

<|endoftext|>


<commit_before><commit_msg>fix assert with invalid sting length<commit_after><|endoftext|>


<commit_before><commit_msg>fdo#43534: Reset tab index for SingleRefToVars() call.<commit_after><|endoftext|>


<commit_before>/*
**	Author: Abhilash
**	Date:	18.04.2015
*/
// Bottom up computation
//
#include <bits/stdc++.h>
#define sf							scanf
#define pf 							printf
typedef long long ll;
using namespace std;
const ll N = 1e6+3;
const ll inf = 1e18;

ll DP[N][3];
ll cost[N][3];

ll n;

ll move[4][2] = {{1, -1}, {0, 1}, {1, 1}, {1, 0}};

ll dp() {
	DP[n][0] = cost[n][0]+cost[n][1];
	DP[n][1] = cost[n][1];
	DP[n][2] = inf;
	ll r, c, ans;
	for (int i = n-1; i >= 1; --i) {
		for (int j = 2; j >= 0; --j) {
			ans = inf;
			for (int k = 0; k < 4; ++k) {
				r = i + move[k][0];
				c = j + move[k][1];
				if (c >= 0 && c <= 2) {
					ans = min(ans, cost[i][j] + DP[r][c]);
				}
			}
			DP[i][j] = ans;
		}
	}
	return DP[1][1];
}

int main() {
	sf("%lld", &n);
	ll T = 1;
	while (n) {
		for (int i = 0; i < n; ++i)
			sf("%lld %lld %lld", &cost[i+1][0],
						&cost[i+1][1],
						&cost[i+1][2]);
		pf("%lld. %lld\n", T++, dp());
		sf("%lld", &n);
	}
	return 0;
}
<commit_msg>Update ACPC10D.cpp<commit_after>/*
**	Author: Abhilash
**	Date:	18.04.2015
*/
// Bottom up computation
//
#include <bits/stdc++.h>
#define sf							scanf
#define pf 							printf
typedef long long ll;
using namespace std;
const ll N = 1e6+3;
const ll inf = 1e18;

ll DP[N][3];
ll cost[N][3];

ll n;

ll move[4][2] = {{1, -1}, {0, 1}, {1, 1}, {1, 0}};

ll dp() {
	DP[n][0] = cost[n][0] + cost[n][1];
	DP[n][1] = cost[n][1];
	DP[n][2] = inf;
	ll r, c, ans;
	for (int i = n - 1; i >= 1; --i) {
		for (int j = 2; j >= 0; --j) {
			ans = inf;
			for (int k = 0; k < 4; ++k) {
				r = i + move[k][0];
				c = j + move[k][1];
				if (c >= 0 && c <= 2) {
					ans = min(ans, cost[i][j] + DP[r][c]);
				}
			}
			DP[i][j] = ans;
		}
	}
	return DP[1][1];
}

int main() {
	sf("%lld", &n);
	ll T = 1;
	while (n) {
		for (int i = 0; i < n; ++i)
			sf("%lld %lld %lld", &cost[i+1][0],
						&cost[i+1][1],
						&cost[i+1][2]);
		pf("%lld. %lld\n", T++, dp());
		sf("%lld", &n);
	}
	return 0;
}
<|endoftext|>