<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_path.h"
#include "content/test/layout_browsertest.h"

class IndexedDBLayoutTest : public InProcessBrowserLayoutTest {
 public:
  IndexedDBLayoutTest() : InProcessBrowserLayoutTest(
      FilePath(), FilePath().AppendASCII("storage").AppendASCII("indexeddb")) {
  }

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    InProcessBrowserLayoutTest::SetUpInProcessBrowserTestFixture();
    AddResourceForLayoutTest(
        FilePath().AppendASCII("fast").AppendASCII("js"),
        FilePath().AppendASCII("resources"));
  }

  void RunLayoutTests(const char* file_names[]) {
    for (size_t i = 0; file_names[i]; i++)
      RunLayoutTest(file_names[i]);
  }
};

namespace {

static const char* kBasicTests[] = {
  "basics.html",
  "basics-shared-workers.html",
  "basics-workers.html",
  "database-basics.html",
  "factory-basics.html",
  "index-basics.html",
  "objectstore-basics.html",
  NULL
};

static const char* kComplexTests[] = {
  "prefetch-bugfix-108071.html",
  NULL
};

static const char* kIndexTests[] = {
  "deleteIndex.html",
  "index-basics-workers.html",
  "index-count.html",
  "index-cursor.html",  // Locally takes ~6s compared to <1 for the others.
  "index-get-key-argument-required.html",
  "index-multientry.html",
  "index-population.html",
  "index-unique.html",
  NULL
};

static const char* kKeyTests[] = {
  "key-generator.html",
  "keypath-basics.html",
  "keypath-edges.html",
  "keypath-fetch-key.html",
  "keyrange.html",
  "keyrange-required-arguments.html",
  "key-sort-order-across-types.html",
  "key-sort-order-date.html",
  "key-type-array.html",
  "key-type-infinity.html",
  "invalid-keys.html",
  NULL
};

static const char* kTransactionTests[] = {
//  "transaction-abort.html", // Flaky, http://crbug.com/83226
  "transaction-abort-with-js-recursion-cross-frame.html",
  "transaction-abort-with-js-recursion.html",
  "transaction-abort-workers.html",
  "transaction-after-close.html",
  "transaction-and-objectstore-calls.html",
  "transaction-basics.html",
  "transaction-crash-on-abort.html",
  "transaction-event-propagation.html",
  "transaction-read-only.html",
  "transaction-rollback.html",
  "transaction-storeNames-required.html",
  NULL
};

}

IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, BasicTests) {
  RunLayoutTests(kBasicTests);
}

IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, ComplexTests) {
  RunLayoutTests(kComplexTests);
}

// Generally slow, and frequently times out. http://crbug.com/120924
IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, DISABLED_IndexTests) {
  RunLayoutTests(kIndexTests);
}

IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, KeyTests) {
  RunLayoutTests(kKeyTests);
}

IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, TransactionTests) {
  RunLayoutTests(kTransactionTests);
}
<commit_msg>Change IndexedDBLayoutTest.IndexTests from DISABLED to FLAKY<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_path.h"
#include "content/test/layout_browsertest.h"

class IndexedDBLayoutTest : public InProcessBrowserLayoutTest {
 public:
  IndexedDBLayoutTest() : InProcessBrowserLayoutTest(
      FilePath(), FilePath().AppendASCII("storage").AppendASCII("indexeddb")) {
  }

  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    InProcessBrowserLayoutTest::SetUpInProcessBrowserTestFixture();
    AddResourceForLayoutTest(
        FilePath().AppendASCII("fast").AppendASCII("js"),
        FilePath().AppendASCII("resources"));
  }

  void RunLayoutTests(const char* file_names[]) {
    for (size_t i = 0; file_names[i]; i++)
      RunLayoutTest(file_names[i]);
  }
};

namespace {

static const char* kBasicTests[] = {
  "basics.html",
  "basics-shared-workers.html",
  "basics-workers.html",
  "database-basics.html",
  "factory-basics.html",
  "index-basics.html",
  "objectstore-basics.html",
  NULL
};

static const char* kComplexTests[] = {
  "prefetch-bugfix-108071.html",
  NULL
};

static const char* kIndexTests[] = {
  "deleteIndex.html",
  "index-basics-workers.html",
  "index-count.html",
  "index-cursor.html",  // Locally takes ~6s compared to <1 for the others.
  "index-get-key-argument-required.html",
  "index-multientry.html",
  "index-population.html",
  "index-unique.html",
  NULL
};

static const char* kKeyTests[] = {
  "key-generator.html",
  "keypath-basics.html",
  "keypath-edges.html",
  "keypath-fetch-key.html",
  "keyrange.html",
  "keyrange-required-arguments.html",
  "key-sort-order-across-types.html",
  "key-sort-order-date.html",
  "key-type-array.html",
  "key-type-infinity.html",
  "invalid-keys.html",
  NULL
};

static const char* kTransactionTests[] = {
//  "transaction-abort.html", // Flaky, http://crbug.com/83226
  "transaction-abort-with-js-recursion-cross-frame.html",
  "transaction-abort-with-js-recursion.html",
  "transaction-abort-workers.html",
  "transaction-after-close.html",
  "transaction-and-objectstore-calls.html",
  "transaction-basics.html",
  "transaction-crash-on-abort.html",
  "transaction-event-propagation.html",
  "transaction-read-only.html",
  "transaction-rollback.html",
  "transaction-storeNames-required.html",
  NULL
};

}

IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, BasicTests) {
  RunLayoutTests(kBasicTests);
}

IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, ComplexTests) {
  RunLayoutTests(kComplexTests);
}

// Generally slow, and frequently times out. http://crbug.com/120924
IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, FLAKY_IndexTests) {
  RunLayoutTests(kIndexTests);
}

IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, KeyTests) {
  RunLayoutTests(kKeyTests);
}

IN_PROC_BROWSER_TEST_F(IndexedDBLayoutTest, TransactionTests) {
  RunLayoutTests(kTransactionTests);
}
<|endoftext|>


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

   Copyright (C) 2007-2008 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 John Walker.
   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$
 *
 *  Jobs Class
 *
 *   Dirk Bartley, March 2007
 *
 */

#include "bat.h"
#include "jobs/jobs.h"
#include "run/run.h"

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

   /* tableWidget, Storage Tree Tree Widget inherited from ui_client.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(actionRefreshJobs);
   createContextMenu();
   dockPage();
}

Jobs::~Jobs()
{
}

/*
 * The main meat of the class!!  The function that querries the director and
 * creates the widgets with appropriate values.
 */
void Jobs::populateTable()
{
   QTableWidgetItem *tableItem;
   QBrush blackBrush(Qt::black);

   if (!m_console->preventInUseConnect())
      return;
   m_checkcurwidget = false;
   tableWidget->clear();
   m_checkcurwidget = true;
   QStringList headerlist = (QStringList() << tr("Job Name") << tr("Pool") << tr("Messages")
      << tr("Client") << tr("Storage") << tr("Where") << tr("Level") << tr("Type")
      << tr("FileSet")
      << tr("Catalog") << tr("Enabled"));

   m_typeIndex = headerlist.indexOf(tr("Type"));

   tableWidget->setColumnCount(headerlist.count());
   tableWidget->setHorizontalHeaderLabels(headerlist);
   tableWidget->setRowCount(m_console->job_list.count());
   tableWidget->verticalHeader()->hide();
   int row = 0;

   foreach (QString jobName, m_console->job_list){
      job_defaults job_defs;
      job_defs.job_name = jobName;
      if (m_console->get_job_defaults(job_defs)) {

        for (int column=0; column<headerlist.count(); column++) {
            tableItem = new QTableWidgetItem(1);
            if (column == 0)
               tableItem->setText(job_defs.job_name);
            if (column == 1)
               tableItem->setText(job_defs.pool_name);
            if (column == 2)
               tableItem->setText(job_defs.messages_name);
            if (column == 3)
               tableItem->setText(job_defs.client_name);
            if (column == 4)
               tableItem->setText(job_defs.store_name);
            if (column == 5)
               tableItem->setText(job_defs.where);
            if (column == 6)
               tableItem->setText(job_defs.level);
            if (column == 7)
               tableItem->setText(job_defs.type);
            if (column == 8)
               tableItem->setText(job_defs.fileset_name);
            if (column == 9)
               tableItem->setText(job_defs.catalog_name);
            if (column == 10)
               if (job_defs.enabled)
                  tableItem->setText("Yes");
               else
                  tableItem->setText("No");
            /* tableItem->setFlags(Qt::ItemIsSelectable); */
            tableItem->setForeground(blackBrush);
            tableWidget->setItem(row, column, tableItem);
         }
      }
      row++;
   }
   /* Resize the columns */
   for(int cnter=0; cnter<headerlist.size(); cnter++) {
      tableWidget->resizeColumnToContents(cnter);
   }
}

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

/*
 * Added to set the context menu policy based on currently active tableWidgetItem
 * signaled by currentItemChanged
 */
void Jobs::tableItemChanged(QTableWidgetItem *currentwidgetitem, QTableWidgetItem *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* jobAction, tableWidget->actions()) {
            tableWidget->removeAction(jobAction);
         }
      }
      int currentRow = currentwidgetitem->row();
      QTableWidgetItem *currentrowzeroitem = tableWidget->item(currentRow, 0);
      m_currentlyselected = currentrowzeroitem->text();
      QTableWidgetItem *currenttypeitem = tableWidget->item(currentRow, m_typeIndex);
      QString type = currenttypeitem->text();

      if (m_currentlyselected.length() != 0) {
         /* set a hold variable to the client name in case the context sensitive
          * menu is used */
         tableWidget->addAction(actionConsoleListFiles);
         tableWidget->addAction(actionConsoleListVolumes);
         tableWidget->addAction(actionConsoleListNextVolume);
         tableWidget->addAction(actionConsoleEnableJob);
         tableWidget->addAction(actionConsoleDisableJob);
         tableWidget->addAction(actionConsoleCancel);
         tableWidget->addAction(actionJobListQuery);
         if (type == tr("Backup"))
            tableWidget->addAction(actionRunJob);
      }
   }
}

/*
 * Setup a context menu
 * Made separate from populate so that it would not create context menu over and
 * over as the table is repopulated.
 */
void Jobs::createContextMenu()
{
   tableWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
   tableWidget->addAction(actionRefreshJobs);
   connect(tableWidget, SIGNAL(
           currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)),
           this, SLOT(tableItemChanged(QTableWidgetItem *, QTableWidgetItem *)));
   /* connect to the action specific to this pages class */
   connect(actionRefreshJobs, SIGNAL(triggered()), this,
                SLOT(populateTable()));
   connect(actionConsoleListFiles, SIGNAL(triggered()), this, SLOT(consoleListFiles()));
   connect(actionConsoleListVolumes, SIGNAL(triggered()), this, SLOT(consoleListVolume()));
   connect(actionConsoleListNextVolume, SIGNAL(triggered()), this, SLOT(consoleListNextVolume()));
   connect(actionConsoleEnableJob, SIGNAL(triggered()), this, SLOT(consoleEnable()));
   connect(actionConsoleDisableJob, SIGNAL(triggered()), this, SLOT(consoleDisable()));
   connect(actionConsoleCancel, SIGNAL(triggered()), this, SLOT(consoleCancel()));
   connect(actionJobListQuery, SIGNAL(triggered()), this, SLOT(listJobs()));
   connect(actionRunJob, SIGNAL(triggered()), this, SLOT(runJob()));
}

/*
 * Virtual function which is called when this page is visible on the stack
 */
void Jobs::currentStackItem()
{
   populateTable();
   if(!m_populated) {
      /* Create the context menu for the client table */
      m_populated=true;
   }
}

/*
 * The following functions are slots responding to users clicking on the context
 * sensitive menu
 */

void Jobs::consoleListFiles()
{
   QString cmd = "list files job=\"" + m_currentlyselected + "\"";
   if (mainWin->m_longList) { cmd.prepend("l"); }
   consoleCommand(cmd);
}

void Jobs::consoleListVolume()
{
   QString cmd = "list volumes job=\"" + m_currentlyselected + "\"";
   if (mainWin->m_longList) { cmd.prepend("l"); }
   consoleCommand(cmd);
}

void Jobs::consoleListNextVolume()
{
   QString cmd = "list nextvolume job=\"" + m_currentlyselected + "\"";
   if (mainWin->m_longList) { cmd.prepend("l"); }
   consoleCommand(cmd);
}

void Jobs::consoleEnable()
{
   QString cmd = "enable job=\"" + m_currentlyselected + "\"";
   consoleCommand(cmd);
}

void Jobs::consoleDisable()
{
   QString cmd = "disable job=\"" + m_currentlyselected + "\"";
   consoleCommand(cmd);
}

void Jobs::consoleCancel()
{
   QString cmd = "cancel job=\"" + m_currentlyselected + "\"";
   consoleCommand(cmd);
}

void Jobs::listJobs()
{
   QTreeWidgetItem *parentItem = mainWin->getFromHash(this);
   mainWin->createPageJobList("", "", m_currentlyselected, "", parentItem);
}

/*
 * Open a new job run page with the currentley selected "Backup" job
 * defaulted In
 */
void Jobs::runJob()
{
   new runPage(m_currentlyselected);
}
<commit_msg>Tweak jobs dialog<commit_after>/*
   Bacula® - The Network Backup Solution

   Copyright (C) 2007-2008 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 John Walker.
   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$
 *
 *  Jobs Class
 *
 *   Dirk Bartley, March 2007
 *
 */

#include "bat.h"
#include "jobs/jobs.h"
#include "run/run.h"

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

   /* tableWidget, Storage Tree Tree Widget inherited from ui_client.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(actionRefreshJobs);
   createContextMenu();
   dockPage();
}

Jobs::~Jobs()
{
}

/*
 * The main meat of the class!!  The function that querries the director and
 * creates the widgets with appropriate values.
 */
void Jobs::populateTable()
{
   QTableWidgetItem *tableItem;
   QBrush blackBrush(Qt::black);

   if (!m_console->preventInUseConnect())
      return;
   m_checkcurwidget = false;
   tableWidget->clear();
   m_checkcurwidget = true;
   QStringList headerlist = (QStringList() << tr("Job Name")
      << tr("Pool") << tr("Messages") << tr("Client")
      << tr("Storage") << tr("Level") << tr("Type")
      << tr("FileSet") << tr("Catalog") << tr("Enabled")
      << tr("Where"));

   m_typeIndex = headerlist.indexOf(tr("Type"));

   tableWidget->setColumnCount(headerlist.count());
   tableWidget->setHorizontalHeaderLabels(headerlist);
   tableWidget->setRowCount(m_console->job_list.count());
   tableWidget->verticalHeader()->hide();
   int row = 0;

   foreach (QString jobName, m_console->job_list){
      job_defaults job_defs;
      job_defs.job_name = jobName;
      if (m_console->get_job_defaults(job_defs)) {

        for (int column=0; column<headerlist.count(); column++) {
            tableItem = new QTableWidgetItem(1);
            if (column == 0)
               tableItem->setText(job_defs.job_name);
            if (column == 1)
               tableItem->setText(job_defs.pool_name);
            if (column == 2)
               tableItem->setText(job_defs.messages_name);
            if (column == 3)
               tableItem->setText(job_defs.client_name);
            if (column == 4)
               tableItem->setText(job_defs.store_name);
            if (column == 5)
               tableItem->setText(job_defs.level);
            if (column == 6)
               tableItem->setText(job_defs.type);
            if (column == 7)
               tableItem->setText(job_defs.fileset_name);
            if (column == 8)
               tableItem->setText(job_defs.catalog_name);
            if (column == 9) {
               if (job_defs.enabled)
                  tableItem->setText("Yes");
               else
                  tableItem->setText("No");
            }
            if (column == 10)
               tableItem->setText(job_defs.where);

            /* tableItem->setFlags(Qt::ItemIsSelectable); */
            tableItem->setForeground(blackBrush);
            tableWidget->setItem(row, column, tableItem);
         }
      }
      row++;
   }
   /* Resize the columns */
   for(int cnter=0; cnter<headerlist.size(); cnter++) {
      tableWidget->resizeColumnToContents(cnter);
   }
}

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

/*
 * Added to set the context menu policy based on currently active tableWidgetItem
 * signaled by currentItemChanged
 */
void Jobs::tableItemChanged(QTableWidgetItem *currentwidgetitem, QTableWidgetItem *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* jobAction, tableWidget->actions()) {
            tableWidget->removeAction(jobAction);
         }
      }
      int currentRow = currentwidgetitem->row();
      QTableWidgetItem *currentrowzeroitem = tableWidget->item(currentRow, 0);
      m_currentlyselected = currentrowzeroitem->text();
      QTableWidgetItem *currenttypeitem = tableWidget->item(currentRow, m_typeIndex);
      QString type = currenttypeitem->text();

      if (m_currentlyselected.length() != 0) {
         /* set a hold variable to the client name in case the context sensitive
          * menu is used */
         tableWidget->addAction(actionConsoleListFiles);
         tableWidget->addAction(actionConsoleListVolumes);
         tableWidget->addAction(actionConsoleListNextVolume);
         tableWidget->addAction(actionConsoleEnableJob);
         tableWidget->addAction(actionConsoleDisableJob);
         tableWidget->addAction(actionConsoleCancel);
         tableWidget->addAction(actionJobListQuery);
         if (type == tr("Backup"))
            tableWidget->addAction(actionRunJob);
      }
   }
}

/*
 * Setup a context menu
 * Made separate from populate so that it would not create context menu over and
 * over as the table is repopulated.
 */
void Jobs::createContextMenu()
{
   tableWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
   tableWidget->addAction(actionRefreshJobs);
   connect(tableWidget, SIGNAL(
           currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)),
           this, SLOT(tableItemChanged(QTableWidgetItem *, QTableWidgetItem *)));
   /* connect to the action specific to this pages class */
   connect(actionRefreshJobs, SIGNAL(triggered()), this,
                SLOT(populateTable()));
   connect(actionConsoleListFiles, SIGNAL(triggered()), this, SLOT(consoleListFiles()));
   connect(actionConsoleListVolumes, SIGNAL(triggered()), this, SLOT(consoleListVolume()));
   connect(actionConsoleListNextVolume, SIGNAL(triggered()), this, SLOT(consoleListNextVolume()));
   connect(actionConsoleEnableJob, SIGNAL(triggered()), this, SLOT(consoleEnable()));
   connect(actionConsoleDisableJob, SIGNAL(triggered()), this, SLOT(consoleDisable()));
   connect(actionConsoleCancel, SIGNAL(triggered()), this, SLOT(consoleCancel()));
   connect(actionJobListQuery, SIGNAL(triggered()), this, SLOT(listJobs()));
   connect(actionRunJob, SIGNAL(triggered()), this, SLOT(runJob()));
}

/*
 * Virtual function which is called when this page is visible on the stack
 */
void Jobs::currentStackItem()
{
   populateTable();
   if(!m_populated) {
      /* Create the context menu for the client table */
      m_populated=true;
   }
}

/*
 * The following functions are slots responding to users clicking on the context
 * sensitive menu
 */

void Jobs::consoleListFiles()
{
   QString cmd = "list files job=\"" + m_currentlyselected + "\"";
   if (mainWin->m_longList) { cmd.prepend("l"); }
   consoleCommand(cmd);
}

void Jobs::consoleListVolume()
{
   QString cmd = "list volumes job=\"" + m_currentlyselected + "\"";
   if (mainWin->m_longList) { cmd.prepend("l"); }
   consoleCommand(cmd);
}

void Jobs::consoleListNextVolume()
{
   QString cmd = "list nextvolume job=\"" + m_currentlyselected + "\"";
   if (mainWin->m_longList) { cmd.prepend("l"); }
   consoleCommand(cmd);
}

void Jobs::consoleEnable()
{
   QString cmd = "enable job=\"" + m_currentlyselected + "\"";
   consoleCommand(cmd);
}

void Jobs::consoleDisable()
{
   QString cmd = "disable job=\"" + m_currentlyselected + "\"";
   consoleCommand(cmd);
}

void Jobs::consoleCancel()
{
   QString cmd = "cancel job=\"" + m_currentlyselected + "\"";
   consoleCommand(cmd);
}

void Jobs::listJobs()
{
   QTreeWidgetItem *parentItem = mainWin->getFromHash(this);
   mainWin->createPageJobList("", "", m_currentlyselected, "", parentItem);
}

/*
 * Open a new job run page with the currentley selected "Backup" job
 * defaulted In
 */
void Jobs::runJob()
{
   new runPage(m_currentlyselected);
}
<|endoftext|>


<commit_before>/*
TLD's work well w/ features (keypts) low-level features

- DoT works well with textureless objects (contoures)
- Use both to bootstrap a contour and features based reconstruction
- Does going to 3D from contour make tracking possible ??

*/
#define WINDOW_NAME "TLD Segmenter"
#include <set>

// LCM includes
#include <perception_opencv_utils/calib_utils.hpp>
#include <perception_opencv_utils/imshow_utils.hpp>
#include <perception_opencv_utils/math_utils.hpp>
#include <perception_opencv_utils/plot_utils.hpp>
#include <perception_opencv_utils/color_utils.hpp>
#include <perception_opencv_utils/imgproc_utils.hpp>

#include "kinect_opencv_utils.h"
#include <lcmtypes/kinect_image_msg_t.h>

// #include <lcmtypes/kinect_frame_msg_t.h>
// #include <kinect/kinect-utils.h>
#include <bot_core/bot_core.h>
#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>

#include <lcmtypes/perception_image_roi_t.h>

#define SHOW_ALL_RECTS_BY_ONE 0
using namespace cv;

typedef struct _state_t state_t;
struct _state_t {
    lcm_t *lcm;
    GMainLoop *mainloop;
    BotParam *param;
    BotFrames *frames;
};
state_t * state = NULL;

struct MouseEvent {
    MouseEvent() { event = -1; buttonState = 0; }
    Point pt;
    int event;
    int buttonState;
};
MouseEvent mouse;

// UI selection of desired object
Rect selection;
Point origin;
bool selectObject = false;

int64_t last_utime;
Mat last_img;

static void usage(const char* progname)
{
  fprintf (stderr, "Usage: %s [options]\n"
                   "\n"
                   "Options:\n"
                   "  -l URL    Specify LCM URL\n"
                   "  -h        This help message\n",
                   g_path_get_basename(progname));
  exit(1);
}

int envoy_decompress_bot_core_image_t(const bot_core_image_t * jpeg_image, bot_core_image_t *uncomp_image)
{
  //copy metadata
  uncomp_image->utime = jpeg_image->utime;
  if (uncomp_image->metadata != NULL)
    bot_core_image_metadata_t_destroy(uncomp_image->metadata);
  uncomp_image->nmetadata = jpeg_image->nmetadata;
  if (jpeg_image->nmetadata > 0) {
    uncomp_image->metadata = bot_core_image_metadata_t_copy(jpeg_image->metadata);
  }

  uncomp_image->width = jpeg_image->width;
  uncomp_image->height = jpeg_image->height;

  uncomp_image->row_stride = jpeg_image->width * 3;//jpeg_image->row_stride;

  int depth=0;
  if (uncomp_image->width>0)
      depth= uncomp_image->row_stride / (double)uncomp_image->width;

  int ret;

  if(uncomp_image->data == NULL){
      int uncomp_size = (uncomp_image->width) * (uncomp_image->height) * depth;
      uncomp_image->data = (unsigned char *) realloc(uncomp_image->data, uncomp_size * sizeof(uint8_t));
  }

  ret = jpeg_decompress_8u_rgb(jpeg_image->data,
                               jpeg_image->size, uncomp_image->data,
                               uncomp_image->width,
                               uncomp_image->height,
                               uncomp_image->row_stride);

  uncomp_image->row_stride = uncomp_image->width * depth;
  uncomp_image->size = uncomp_image->width *uncomp_image->height* depth;
  if (depth == 1) {
    uncomp_image->pixelformat = BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY;
  }
  else if (depth == 3) {
    uncomp_image->pixelformat = BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB; //TODO: lets just assume its rgb... dunno what else to do :-/
  }
  return ret;
}

static void onMouse(int event, int x, int y, int flags, void* userdata) {
    MouseEvent* data = (MouseEvent*)userdata;
    if (selectObject) {
        selection.x = MIN(x, origin.x);
        selection.y = MIN(y, origin.y);
        selection.width = std::abs(x - origin.x);
        selection.height = std::abs(y - origin.y);
        selection &= Rect(0, 0, WIDTH, HEIGHT);
    }

    switch (event) {
    case CV_EVENT_LBUTTONDOWN:
        origin = Point(x, y);
        selection = Rect(x, y, 0, 0);
        selectObject = true;
        break;
    case CV_EVENT_LBUTTONUP:
        selectObject = false;
        std::cerr << "SEND selection: " << last_utime << " - " << selection.x << " " << selection.y << " " << selection.width << " " << selection.height << std::endl;

        perception_image_roi_t img_selection;
        img_selection.utime = last_utime;
        img_selection.roi.x = selection.x;
        img_selection.roi.y = selection.y;
        img_selection.roi.width = selection.width;
        img_selection.roi.height = selection.height;
        perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_selection);

        break;
    }
    return;
}

void  INThandler(int sig)
{
    // lcm_destroy(state->lcm);
    printf("Exiting\n");
    exit(0);
}

static void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,
                            const bot_core_image_t *msg,
                            void *user_data ) {

    if (!msg->width || !msg->height)
        return;

    Mat img(msg->height, msg->width, CV_8UC3);
    if (!selectObject) {
        // std::cerr << msg->height << " " << msg->width << " " << msg->utime << std::endl;

        static bot_core_image_t * localFrame=(bot_core_image_t *) calloc(1,sizeof(bot_core_image_t));
        if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG) {
            //create space for decompressed image
            envoy_decompress_bot_core_image_t(msg,localFrame);
            memcpy( img.data, localFrame->data, sizeof(uint8_t)*msg->width*msg->height*3);
        } else {
            //uncompressed, just copy pointer
            memcpy(img.data, msg->data, sizeof(uint8_t)*msg->width*msg->height*3);
        }
        cvtColor(img, img, CV_RGB2BGR);

        // int npixels = msg->height * msg->width;

        last_utime = msg->utime;
    } else
        img = last_img;

    // Clone image before drawing rectangle
    last_img = img.clone();

    if (selectObject && selection.width > 0 && selection.height > 0) {
        Mat roi(img, selection);
        rectangle(img, selection, cv::Scalar(0,255,255), 2);
        // bitwise_not(roi, roi);
    }

    imshow(WINDOW_NAME, img);
    return;
}

int main(int argc, char** argv)
{
    // g_thread_init(NULL);
    setlinebuf (stdout);
    state = (state_t*) calloc(1, sizeof(state_t));

    // Param server, botframes
    state->lcm =  bot_lcm_get_global(NULL);
    state->param = bot_param_new_from_server(state->lcm, 1);
    state->frames = bot_frames_get_global (state->lcm, state->param);

    namedWindow( WINDOW_NAME );
    bot_core_image_t_subscribe(state->lcm, "CAMERALEFT", on_image_frame, (void*)state);
    setMouseCallback( WINDOW_NAME, onMouse, &mouse);

    // Install signal handler to free data.
    signal(SIGINT, INThandler);

    fprintf(stderr, "Starting Main Loop\n");
    int lcm_fd = lcm_get_fileno(state->lcm);
    fd_set fds;

    // wait a limited amount of time for an incoming message
    struct timeval timeout = {
        0,  // seconds
        10000   // microseconds
    };

    while(1) {
        unsigned char c = cv::waitKey(10) & 0xff;

        FD_ZERO(&fds);
        FD_SET(lcm_fd, &fds);

        // setup the LCM file descriptor for waiting.
        int status = select(lcm_fd + 1, &fds, 0, 0, &timeout);
        if(status && FD_ISSET(lcm_fd, &fds)) {
            // LCM has events ready to be processed.
            lcm_handle(state->lcm);
        }

        if (c == 'q') break;

    }

    lcm_destroy(state->lcm);

    return 0;
}
<commit_msg>fixed segmenter code for max image width/height<commit_after>/*
TLD's work well w/ features (keypts) low-level features

- DoT works well with textureless objects (contoures)
- Use both to bootstrap a contour and features based reconstruction
- Does going to 3D from contour make tracking possible ??

*/
#define WINDOW_NAME "TLD Segmenter"
#include <set>

// LCM includes
// #include <perception_opencv_utils/calib_utils.hpp>
// #include <perception_opencv_utils/imshow_utils.hpp>
// #include <perception_opencv_utils/math_utils.hpp>
// #include <perception_opencv_utils/plot_utils.hpp>
// #include <perception_opencv_utils/color_utils.hpp>
// #include <perception_opencv_utils/imgproc_utils.hpp>

#include "kinect_opencv_utils.h"
#include <lcmtypes/kinect_image_msg_t.h>

// #include <lcmtypes/kinect_frame_msg_t.h>
// #include <kinect/kinect-utils.h>
#include <bot_core/bot_core.h>
#include <bot_frames/bot_frames.h>
#include <bot_param/param_client.h>

#include <lcmtypes/perception_image_roi_t.h>

#define SHOW_ALL_RECTS_BY_ONE 0
int MAX_IMAGE_WIDTH = 0;
int MAX_IMAGE_HEIGHT = 0;

using namespace cv;

typedef struct _state_t state_t;
struct _state_t {
    lcm_t *lcm;
    GMainLoop *mainloop;
    BotParam *param;
    BotFrames *frames;
};
state_t * state = NULL;

struct MouseEvent {
    MouseEvent() { event = -1; buttonState = 0; }
    Point pt;
    int event;
    int buttonState;
};
MouseEvent mouse;

// UI selection of desired object
Rect selection;
Point origin;
bool selectObject = false;

int64_t last_utime;
Mat last_img;

static void usage(const char* progname)
{
  fprintf (stderr, "Usage: %s [options]\n"
                   "\n"
                   "Options:\n"
                   "  -l URL    Specify LCM URL\n"
                   "  -h        This help message\n",
                   g_path_get_basename(progname));
  exit(1);
}

int envoy_decompress_bot_core_image_t(const bot_core_image_t * jpeg_image, bot_core_image_t *uncomp_image)
{
  //copy metadata
  uncomp_image->utime = jpeg_image->utime;
  if (uncomp_image->metadata != NULL)
    bot_core_image_metadata_t_destroy(uncomp_image->metadata);
  uncomp_image->nmetadata = jpeg_image->nmetadata;
  if (jpeg_image->nmetadata > 0) {
    uncomp_image->metadata = bot_core_image_metadata_t_copy(jpeg_image->metadata);
  }

  uncomp_image->width = jpeg_image->width;
  uncomp_image->height = jpeg_image->height;

  uncomp_image->row_stride = jpeg_image->width * 3;//jpeg_image->row_stride;

  int depth=0;
  if (uncomp_image->width>0)
      depth= uncomp_image->row_stride / (double)uncomp_image->width;

  int ret;

  if(uncomp_image->data == NULL){
      int uncomp_size = (uncomp_image->width) * (uncomp_image->height) * depth;
      uncomp_image->data = (unsigned char *) realloc(uncomp_image->data, uncomp_size * sizeof(uint8_t));
  }

  ret = jpeg_decompress_8u_rgb(jpeg_image->data,
                               jpeg_image->size, uncomp_image->data,
                               uncomp_image->width,
                               uncomp_image->height,
                               uncomp_image->row_stride);

  uncomp_image->row_stride = uncomp_image->width * depth;
  uncomp_image->size = uncomp_image->width *uncomp_image->height* depth;
  if (depth == 1) {
    uncomp_image->pixelformat = BOT_CORE_IMAGE_T_PIXEL_FORMAT_GRAY;
  }
  else if (depth == 3) {
    uncomp_image->pixelformat = BOT_CORE_IMAGE_T_PIXEL_FORMAT_RGB; //TODO: lets just assume its rgb... dunno what else to do :-/
  }
  return ret;
}

static void onMouse(int event, int x, int y, int flags, void* userdata) {
    MouseEvent* data = (MouseEvent*)userdata;
    if (selectObject) {
        selection.x = MIN(x, origin.x);
        selection.y = MIN(y, origin.y);
        selection.width = std::abs(x - origin.x);
        selection.height = std::abs(y - origin.y);
        selection &= Rect(0, 0, MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
    }

    switch (event) {
    case CV_EVENT_LBUTTONDOWN:
        origin = Point(x, y);
        selection = Rect(x, y, 0, 0);
        selectObject = true;
        break;
    case CV_EVENT_LBUTTONUP:
        selectObject = false;
        std::cerr << "SEND selection: " << last_utime << " - " << selection.x << " " << selection.y << " " << selection.width << " " << selection.height << std::endl;

        perception_image_roi_t img_selection;
        img_selection.utime = last_utime;
        img_selection.roi.x = selection.x;
        img_selection.roi.y = selection.y;
        img_selection.roi.width = selection.width;
        img_selection.roi.height = selection.height;
        perception_image_roi_t_publish(state->lcm, "TLD_OBJECT_ROI", &img_selection);

        break;
    }
    return;
}

void  INThandler(int sig)
{
    // lcm_destroy(state->lcm);
    printf("Exiting\n");
    exit(0);
}

static void on_image_frame (const lcm_recv_buf_t *rbuf, const char *channel,
                            const bot_core_image_t *msg,
                            void *user_data ) {

    if (!msg->width || !msg->height)
        return;

    if (!MAX_IMAGE_WIDTH || !MAX_IMAGE_HEIGHT) {
        MAX_IMAGE_WIDTH = msg->width;
        MAX_IMAGE_HEIGHT = msg->height;
    }

    Mat img(msg->height, msg->width, CV_8UC3);
    if (!selectObject) {
        // std::cerr << msg->height << " " << msg->width << " " << msg->utime << std::endl;

        static bot_core_image_t * localFrame=(bot_core_image_t *) calloc(1,sizeof(bot_core_image_t));
        if (msg->pixelformat == BOT_CORE_IMAGE_T_PIXEL_FORMAT_MJPEG) {
            //create space for decompressed image
            envoy_decompress_bot_core_image_t(msg,localFrame);
            memcpy( img.data, localFrame->data, sizeof(uint8_t)*msg->width*msg->height*3);
        } else {
            //uncompressed, just copy pointer
            memcpy(img.data, msg->data, sizeof(uint8_t)*msg->width*msg->height*3);
        }
        cvtColor(img, img, CV_RGB2BGR);

        // int npixels = msg->height * msg->width;

        last_utime = msg->utime;
    } else
        img = last_img;

    // Clone image before drawing rectangle
    last_img = img.clone();

    if (selectObject && selection.width > 0 && selection.height > 0) {
        Mat roi(img, selection);
        rectangle(img, selection, cv::Scalar(0,255,255), 2);
        // bitwise_not(roi, roi);
    }

    imshow(WINDOW_NAME, img);
    return;
}

int main(int argc, char** argv)
{
    // g_thread_init(NULL);
    setlinebuf (stdout);
    state = (state_t*) calloc(1, sizeof(state_t));

    // Param server, botframes
    state->lcm =  bot_lcm_get_global(NULL);
    state->param = bot_param_new_from_server(state->lcm, 1);
    state->frames = bot_frames_get_global (state->lcm, state->param);

    namedWindow( WINDOW_NAME );
    bot_core_image_t_subscribe(state->lcm, "CAMERALEFT", on_image_frame, (void*)state);
    setMouseCallback( WINDOW_NAME, onMouse, &mouse);

    // Install signal handler to free data.
    signal(SIGINT, INThandler);

    fprintf(stderr, "Starting Main Loop\n");
    int lcm_fd = lcm_get_fileno(state->lcm);
    fd_set fds;

    // wait a limited amount of time for an incoming message
    struct timeval timeout = {
        0,  // seconds
        10000   // microseconds
    };

    while(1) {
        unsigned char c = cv::waitKey(10) & 0xff;

        FD_ZERO(&fds);
        FD_SET(lcm_fd, &fds);

        // setup the LCM file descriptor for waiting.
        int status = select(lcm_fd + 1, &fds, 0, 0, &timeout);
        if(status && FD_ISSET(lcm_fd, &fds)) {
            // LCM has events ready to be processed.
            lcm_handle(state->lcm);
        }

        if (c == 'q') break;

    }

    lcm_destroy(state->lcm);

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>xapian-core: Throw DatabaseNotFoundError if directory doesn't exist<commit_after><|endoftext|>


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

 The MIT License (MIT)

 Copyright (c) 2015 Dmitry Sovetov

 https://github.com/dmsovetov

 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 "Transform.h"

DC_BEGIN_DREEMCHEST

namespace Scene {

// ------------------------------------------- MoveTo ------------------------------------------- //

// ** MoveTo::target
Vec3 MoveTo::target( void ) const
{
	return m_target->get();
}

// ** MoveTo::isContinuous
bool MoveTo::isContinuous( void ) const
{
	return m_isContinuous;
}

// ** MoveTo::type
MoveTo::Type MoveTo::type( void ) const
{
	return m_type;
}

// ** MoveTo::damping
f32 MoveTo::damping( void ) const
{
	return m_damping;
}

// ** MoveTo::springForce
f32 MoveTo::springForce( void ) const
{
	return m_springForce;
}

// ------------------------------------------ Transform ------------------------------------------ //

// ** Transform::matrix
const Matrix4& Transform::matrix( void ) const
{
	return m_transform;
}

// ** Transform::setMatrix
void Transform::setMatrix( const Matrix4& value )
{
	m_transform = value;
}

// ** Transform::parent
const TransformWPtr& Transform::parent( void ) const
{
	return m_parent;
}

// ** Transform::setParent
void Transform::setParent( const TransformWPtr& value )
{
	m_parent = value;
}

// ** Transform::worldSpacePosition
Vec3 Transform::worldSpacePosition( void ) const
{
	return matrix() * Vec3( 0.0f, 0.0f, 0.0f );
}

// ** Transform::position
const Vec3& Transform::position( void ) const
{
	return m_position;
}

// ** Transform::setPosition
void Transform::setPosition( const Vec3& value )
{
	m_position = value;
}

// ** Transform::axisX
Vec3 Transform::axisX( void ) const
{
	return m_rotation.rotate( Vec3( 1.0f, 0.0f, 0.0f ) );
}

// ** Transform::axisY
Vec3 Transform::axisY( void ) const
{
	return m_rotation.rotate( Vec3( 0.0f, 1.0f, 0.0f ) );
}

// ** Transform::axisZ
Vec3 Transform::axisZ( void ) const
{
	return m_rotation.rotate( Vec3( 0.0f, 0.0f, 1.0f ) );
}

// ** Transform::x
f32 Transform::x( void ) const
{
	return m_position.x;
}

// ** Transform::setX
void Transform::setX( f32 value )
{
	m_position.x = value;
}

// ** Transform::y
f32 Transform::y( void ) const
{
	return m_position.y;
}

// ** Transform::setY
void Transform::setY( f32 value )
{
	m_position.y = value;
}

// ** Transform::rotation
const Quat& Transform::rotation( void ) const
{
	return m_rotation;
}

// ** Transform::rotate
void Transform::rotate( f32 angle, f32 x, f32 y, f32 z )
{
	Quat r = Quat::rotateAroundAxis( angle, Vec3( x, y, z ) );
	m_rotation = r * m_rotation;
}

// ** Transform::setRotation
void Transform::setRotation( const Quat& value )
{
	m_rotation = value;
}

// ** Transform::rotationX
f32 Transform::rotationX( void ) const
{
	return m_rotation.x;
}

// ** Transform::setRotationX
void Transform::setRotationX( f32 value )
{
	m_rotation.x = value;
}

// ** Transform::rotationY
f32 Transform::rotationY( void ) const
{
	return m_rotation.y;
}

// ** Transform::setRotationY
void Transform::setRotationY( f32 value )
{
	m_rotation.y = value;
}

// ** Transform::rotationZ
f32 Transform::rotationZ( void ) const
{
	return m_rotation.z;
}

// ** Transform::setRotationZ
void Transform::setRotationZ( f32 value )
{
	m_rotation.z = value;
}

// ** Transform::setScale
void Transform::setScale( const Vec3& value )
{
	m_scale = value;
}

// ** Transform::scale
const Vec3& Transform::scale( void ) const
{
	return m_scale;
}

// ** Transform::scaleX
f32 Transform::scaleX( void ) const
{
	return m_scale.x;
}

// ** Transform::setScaleX
void Transform::setScaleX( f32 value )
{
	m_scale.x = value;
}

// ** Transform::scaleY
f32 Transform::scaleY( void ) const
{
	return m_scale.y;
}

// ** Transform::setScaleY
void Transform::setScaleY( f32 value )
{
	m_scale.y = value;
}

// ** Transform::scaleZ
f32 Transform::scaleZ( void ) const
{
	return m_scale.z;
}

// ** Transform::setScaleZ
void Transform::setScaleZ( f32 value )
{
	m_scale.z = value;
}

// ----------------------------------------------- Identifier ------------------------------------------------ //

// ** Identifier::name
const String& Identifier::name( void ) const
{
	return m_name;
}

// ** Identifier::setName
void Identifier::setName( const String& value )
{
	m_name = value;
}

// --------------------------------------------- MoveAlongAxes --------------------------------------------- //

// ** MoveAlongAxes::speed
f32 MoveAlongAxes::speed( void ) const
{
	return m_speed;
}

// ** MoveAlongAxes::coordinateSystem
u8 MoveAlongAxes::coordinateSystem( void ) const
{
	return m_coordinateSystem;
}

// ** MoveAlongAxes::delta
Vec3 MoveAlongAxes::delta( void ) const
{
	return m_delta->get();
}

// ** MoveAlongAxes::rangeForAxis
const Range& MoveAlongAxes::rangeForAxis( CoordinateSystemAxis axis ) const
{
	return m_range[axis];
}

// ** MoveAlongAxes::setRangeForAxis
void MoveAlongAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value )
{
	m_range[axis] = value;
}

// --------------------------------------------- RotateAroundAxes --------------------------------------------- //

// ** RotateAroundAxes::speed
f32 RotateAroundAxes::speed( void ) const
{
	return m_speed;
}

// ** RotateAroundAxes::setSpeed
void RotateAroundAxes::setSpeed( f32 value )
{
	m_speed = value;
}

// ** RotateAroundAxes::coordinateSystem
u8 RotateAroundAxes::coordinateSystem( void ) const
{
	return m_coordinateSystem;
}

// ** RotateAroundAxes::delta
Vec3 RotateAroundAxes::delta( void ) const
{
	return m_delta->get();
}

// ** RotateAroundAxes::binding
Vec3BindingWPtr RotateAroundAxes::binding( void ) const
{
	return m_delta;
}

// ** RotateAroundAxes::setBinding
void RotateAroundAxes::setBinding( const Vec3BindingPtr& value )
{
	m_delta = value;
}

// ** RotateAroundAxes::rangeForAxis
const Range& RotateAroundAxes::rangeForAxis( CoordinateSystemAxis axis ) const
{
	return m_range[axis];
}

// ** RotateAroundAxes::setRangeForAxis
void RotateAroundAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value )
{
	m_range[axis] = value;
}

// ** RotateAroundAxes::rotationForAxis
f32 RotateAroundAxes::rotationForAxis( CoordinateSystemAxis axis ) const
{
	return m_rotation[axis];
}

// ** RotateAroundAxes::setRotationForAxis
void RotateAroundAxes::setRotationForAxis( CoordinateSystemAxis axis, f32 value )
{
	m_rotation[axis] = value;
}

} // namespace Scene

DC_END_DREEMCHEST<commit_msg>Fixed: Transform::setRotationZ method<commit_after>/**************************************************************************

 The MIT License (MIT)

 Copyright (c) 2015 Dmitry Sovetov

 https://github.com/dmsovetov

 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 "Transform.h"

DC_BEGIN_DREEMCHEST

namespace Scene {

// ------------------------------------------- MoveTo ------------------------------------------- //

// ** MoveTo::target
Vec3 MoveTo::target( void ) const
{
	return m_target->get();
}

// ** MoveTo::isContinuous
bool MoveTo::isContinuous( void ) const
{
	return m_isContinuous;
}

// ** MoveTo::type
MoveTo::Type MoveTo::type( void ) const
{
	return m_type;
}

// ** MoveTo::damping
f32 MoveTo::damping( void ) const
{
	return m_damping;
}

// ** MoveTo::springForce
f32 MoveTo::springForce( void ) const
{
	return m_springForce;
}

// ------------------------------------------ Transform ------------------------------------------ //

// ** Transform::matrix
const Matrix4& Transform::matrix( void ) const
{
	return m_transform;
}

// ** Transform::setMatrix
void Transform::setMatrix( const Matrix4& value )
{
	m_transform = value;
}

// ** Transform::parent
const TransformWPtr& Transform::parent( void ) const
{
	return m_parent;
}

// ** Transform::setParent
void Transform::setParent( const TransformWPtr& value )
{
	m_parent = value;
}

// ** Transform::worldSpacePosition
Vec3 Transform::worldSpacePosition( void ) const
{
	return matrix() * Vec3( 0.0f, 0.0f, 0.0f );
}

// ** Transform::position
const Vec3& Transform::position( void ) const
{
	return m_position;
}

// ** Transform::setPosition
void Transform::setPosition( const Vec3& value )
{
	m_position = value;
}

// ** Transform::axisX
Vec3 Transform::axisX( void ) const
{
	return m_rotation.rotate( Vec3( 1.0f, 0.0f, 0.0f ) );
}

// ** Transform::axisY
Vec3 Transform::axisY( void ) const
{
	return m_rotation.rotate( Vec3( 0.0f, 1.0f, 0.0f ) );
}

// ** Transform::axisZ
Vec3 Transform::axisZ( void ) const
{
	return m_rotation.rotate( Vec3( 0.0f, 0.0f, 1.0f ) );
}

// ** Transform::x
f32 Transform::x( void ) const
{
	return m_position.x;
}

// ** Transform::setX
void Transform::setX( f32 value )
{
	m_position.x = value;
}

// ** Transform::y
f32 Transform::y( void ) const
{
	return m_position.y;
}

// ** Transform::setY
void Transform::setY( f32 value )
{
	m_position.y = value;
}

// ** Transform::rotation
const Quat& Transform::rotation( void ) const
{
	return m_rotation;
}

// ** Transform::rotate
void Transform::rotate( f32 angle, f32 x, f32 y, f32 z )
{
	Quat r = Quat::rotateAroundAxis( angle, Vec3( x, y, z ) );
	m_rotation = r * m_rotation;
}

// ** Transform::setRotation
void Transform::setRotation( const Quat& value )
{
	m_rotation = value;
}

// ** Transform::rotationX
f32 Transform::rotationX( void ) const
{
	return m_rotation.x;
}

// ** Transform::setRotationX
void Transform::setRotationX( f32 value )
{
	m_rotation.x = value;
}

// ** Transform::rotationY
f32 Transform::rotationY( void ) const
{
	return m_rotation.y;
}

// ** Transform::setRotationY
void Transform::setRotationY( f32 value )
{
	m_rotation.y = value;
}

// ** Transform::rotationZ
f32 Transform::rotationZ( void ) const
{
	return m_rotation.z;
}

// ** Transform::setRotationZ
void Transform::setRotationZ( f32 value )
{
	m_rotation = Quat::rotateAroundAxis( value, Vec3( 0.0f, 0.0f, 1.0f ) );
}

// ** Transform::setScale
void Transform::setScale( const Vec3& value )
{
	m_scale = value;
}

// ** Transform::scale
const Vec3& Transform::scale( void ) const
{
	return m_scale;
}

// ** Transform::scaleX
f32 Transform::scaleX( void ) const
{
	return m_scale.x;
}

// ** Transform::setScaleX
void Transform::setScaleX( f32 value )
{
	m_scale.x = value;
}

// ** Transform::scaleY
f32 Transform::scaleY( void ) const
{
	return m_scale.y;
}

// ** Transform::setScaleY
void Transform::setScaleY( f32 value )
{
	m_scale.y = value;
}

// ** Transform::scaleZ
f32 Transform::scaleZ( void ) const
{
	return m_scale.z;
}

// ** Transform::setScaleZ
void Transform::setScaleZ( f32 value )
{
	m_scale.z = value;
}

// ----------------------------------------------- Identifier ------------------------------------------------ //

// ** Identifier::name
const String& Identifier::name( void ) const
{
	return m_name;
}

// ** Identifier::setName
void Identifier::setName( const String& value )
{
	m_name = value;
}

// --------------------------------------------- MoveAlongAxes --------------------------------------------- //

// ** MoveAlongAxes::speed
f32 MoveAlongAxes::speed( void ) const
{
	return m_speed;
}

// ** MoveAlongAxes::coordinateSystem
u8 MoveAlongAxes::coordinateSystem( void ) const
{
	return m_coordinateSystem;
}

// ** MoveAlongAxes::delta
Vec3 MoveAlongAxes::delta( void ) const
{
	return m_delta->get();
}

// ** MoveAlongAxes::rangeForAxis
const Range& MoveAlongAxes::rangeForAxis( CoordinateSystemAxis axis ) const
{
	return m_range[axis];
}

// ** MoveAlongAxes::setRangeForAxis
void MoveAlongAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value )
{
	m_range[axis] = value;
}

// --------------------------------------------- RotateAroundAxes --------------------------------------------- //

// ** RotateAroundAxes::speed
f32 RotateAroundAxes::speed( void ) const
{
	return m_speed;
}

// ** RotateAroundAxes::setSpeed
void RotateAroundAxes::setSpeed( f32 value )
{
	m_speed = value;
}

// ** RotateAroundAxes::coordinateSystem
u8 RotateAroundAxes::coordinateSystem( void ) const
{
	return m_coordinateSystem;
}

// ** RotateAroundAxes::delta
Vec3 RotateAroundAxes::delta( void ) const
{
	return m_delta->get();
}

// ** RotateAroundAxes::binding
Vec3BindingWPtr RotateAroundAxes::binding( void ) const
{
	return m_delta;
}

// ** RotateAroundAxes::setBinding
void RotateAroundAxes::setBinding( const Vec3BindingPtr& value )
{
	m_delta = value;
}

// ** RotateAroundAxes::rangeForAxis
const Range& RotateAroundAxes::rangeForAxis( CoordinateSystemAxis axis ) const
{
	return m_range[axis];
}

// ** RotateAroundAxes::setRangeForAxis
void RotateAroundAxes::setRangeForAxis( CoordinateSystemAxis axis, const Range& value )
{
	m_range[axis] = value;
}

// ** RotateAroundAxes::rotationForAxis
f32 RotateAroundAxes::rotationForAxis( CoordinateSystemAxis axis ) const
{
	return m_rotation[axis];
}

// ** RotateAroundAxes::setRotationForAxis
void RotateAroundAxes::setRotationForAxis( CoordinateSystemAxis axis, f32 value )
{
	m_rotation[axis] = value;
}

} // namespace Scene

DC_END_DREEMCHEST<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: Os2Transferable.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-20 16:39:22 $
 *
 *  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
 *
 ************************************************************************/

#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

#define INCL_WIN
#include <svpm.h>

#include <string.h>

#ifndef _COM_SUN_STAR_IO_IOEXCEPTION_HPP_
#include <com/sun/star/io/IOException.hpp>
#endif

#ifndef _DTRANS_OS2_TRANSFERABLE_HXX_
#include "Os2Transferable.hxx"
#endif

using namespace com::sun::star::datatransfer;
using namespace com::sun::star::lang;
using namespace com::sun::star::io;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace os2;

// =======================================================================

Os2Transferable::Os2Transferable(
    const Reference< XInterface >& xCreator ) :
        m_xCreator( xCreator )
{
    debug_printf("Os2Transferable::Os2Transferable %08x\n", this);
    hAB = WinQueryAnchorBlock( HWND_DESKTOP );

    // query clipboard data to get mimetype
    if( UWinOpenClipbrd( hAB ) )
    {
        ULONG handle = UWinQueryClipbrdData( hAB, UCLIP_CF_UNICODETEXT);
        if (handle) {
            aFlavor.MimeType = OUString::createFromAscii( "text/plain;charset=utf-16" );
            aFlavor.DataType = getCppuType( (OUString*)0 );
            //debug_printf("Os2Transferable::Os2Transferable pszText %s\n", pszText);
        }
        handle = UWinQueryClipbrdData( hAB, UCLIP_CF_BITMAP);
        if (handle) {
            aFlavor.MimeType = OUString::createFromAscii( "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" );
            aFlavor.DataType = getCppuType( (OUString*)0 );
            //debug_printf("Os2Transferable::Os2Transferable pszText %s\n", pszText);
        }
        UWinCloseClipbrd( hAB);
    }
    else
    {
        debug_printf("Os2Transferable::Os2Transferable failed to open clipboard\n");
    }

}

//==================================================================================================

Os2Transferable::~Os2Transferable()
{
    debug_printf("Os2Transferable::~Os2Transferable %08x\n", this);
}

//==================================================================================================

Any SAL_CALL Os2Transferable::getTransferData( const DataFlavor& rFlavor )
    throw(UnsupportedFlavorException, IOException, RuntimeException)
{
    debug_printf("Os2Transferable::getTransferData %08x\n", this);
    debug_printf("Os2Transferable::getTransferData mimetype: %s\n", CHAR_POINTER(rFlavor.MimeType));
    Any aRet;
    Sequence< sal_Int8 > aData;

    // retrieve unicode text
    if( rFlavor.MimeType.equalsIgnoreAsciiCase( OUString::createFromAscii( "text/plain;charset=utf-16" ) ) )
    {
        if( UWinOpenClipbrd( hAB ) )
        {
            // check if clipboard has text format
            sal_Unicode* pszText = (sal_Unicode*) UWinQueryClipbrdData( hAB, UCLIP_CF_UNICODETEXT);
            if (pszText) {
                // convert to oustring and return it
                OUString aString( pszText);
                aRet <<= aString;
            }
            UWinCloseClipbrd( hAB );
            if (pszText)
                return aRet;
        }
    }

    // retrieve bitmap
    if( rFlavor.MimeType.equalsIgnoreAsciiCase( OUString::createFromAscii( "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" ) ) )
    {
        if( UWinOpenClipbrd( hAB ) )
        {
            // check if clipboard has text format
            ULONG handle = UWinQueryClipbrdData( hAB, UCLIP_CF_BITMAP);
            if (handle) {
                Sequence< sal_Int8 > winDIBStream;
                // convert to oustring and return it
                if (OS2HandleToOOoBmp( handle, &winDIBStream))
                    aRet <<= winDIBStream;
                else
                    handle = 0;
            }
            UWinCloseClipbrd( hAB );
            if (handle)
                return aRet;
        }
    }

    // clipboard format unsupported, throw exception
    throw UnsupportedFlavorException( rFlavor.MimeType, static_cast < XTransferable * > ( this ) );
}

//==================================================================================================

Sequence< DataFlavor > SAL_CALL Os2Transferable::getTransferDataFlavors()
    throw(RuntimeException)
{
    debug_printf("Os2Transferable::getTransferDataFlavors %08x\n", this);
    Sequence< DataFlavor > aFlavorList(1);
    aFlavorList[0] = aFlavor;
    debug_printf("Os2Transferable::getTransferDataFlavors mimetype: %s\n", CHAR_POINTER(aFlavor.MimeType));
    return aFlavorList;
}

//==================================================================================================

sal_Bool SAL_CALL Os2Transferable::isDataFlavorSupported( const DataFlavor& aFlavor )
    throw(RuntimeException)
{
    debug_printf("Os2Transferable::isDataFlavorSupported %08x\n", this);
    debug_printf("Os2Transferable::isDataFlavorSupported %s\n", CHAR_POINTER(aFlavor.MimeType));

    if( aFlavor.DataType != getCppuType( (Sequence< sal_Int8 >*)0 ) )
    {
        if( ! aFlavor.MimeType.equalsIgnoreAsciiCase( OUString::createFromAscii( "text/plain;charset=utf-16" ) ) &&
            aFlavor.DataType == getCppuType( (OUString*)0 ) )
            return false;
    }

    Sequence< DataFlavor > aFlavors( getTransferDataFlavors() );
    for( int i = 0; i < aFlavors.getLength(); i++ )
        if( aFlavor.MimeType.equalsIgnoreAsciiCase( aFlavors.getConstArray()[i].MimeType ) &&
            aFlavor.DataType == aFlavors.getConstArray()[i].DataType )
            return sal_True;

    return sal_False;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.2.18); FILE MERGED 2008/04/01 12:28:29 thb 1.2.18.2: #i85898# Stripping all external header guards 2008/03/31 13:08:56 rt 1.2.18.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: Os2Transferable.cxx,v $
 * $Revision: 1.3 $
 *
 * 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.
 *
 ************************************************************************/

#if OSL_DEBUG_LEVEL > 1
#include <stdio.h>
#endif

#define INCL_WIN
#include <svpm.h>

#include <string.h>
#include <com/sun/star/io/IOException.hpp>
#include "Os2Transferable.hxx"

using namespace com::sun::star::datatransfer;
using namespace com::sun::star::lang;
using namespace com::sun::star::io;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace os2;

// =======================================================================

Os2Transferable::Os2Transferable(
    const Reference< XInterface >& xCreator ) :
        m_xCreator( xCreator )
{
    debug_printf("Os2Transferable::Os2Transferable %08x\n", this);
    hAB = WinQueryAnchorBlock( HWND_DESKTOP );

    // query clipboard data to get mimetype
    if( UWinOpenClipbrd( hAB ) )
    {
        ULONG handle = UWinQueryClipbrdData( hAB, UCLIP_CF_UNICODETEXT);
        if (handle) {
            aFlavor.MimeType = OUString::createFromAscii( "text/plain;charset=utf-16" );
            aFlavor.DataType = getCppuType( (OUString*)0 );
            //debug_printf("Os2Transferable::Os2Transferable pszText %s\n", pszText);
        }
        handle = UWinQueryClipbrdData( hAB, UCLIP_CF_BITMAP);
        if (handle) {
            aFlavor.MimeType = OUString::createFromAscii( "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" );
            aFlavor.DataType = getCppuType( (OUString*)0 );
            //debug_printf("Os2Transferable::Os2Transferable pszText %s\n", pszText);
        }
        UWinCloseClipbrd( hAB);
    }
    else
    {
        debug_printf("Os2Transferable::Os2Transferable failed to open clipboard\n");
    }

}

//==================================================================================================

Os2Transferable::~Os2Transferable()
{
    debug_printf("Os2Transferable::~Os2Transferable %08x\n", this);
}

//==================================================================================================

Any SAL_CALL Os2Transferable::getTransferData( const DataFlavor& rFlavor )
    throw(UnsupportedFlavorException, IOException, RuntimeException)
{
    debug_printf("Os2Transferable::getTransferData %08x\n", this);
    debug_printf("Os2Transferable::getTransferData mimetype: %s\n", CHAR_POINTER(rFlavor.MimeType));
    Any aRet;
    Sequence< sal_Int8 > aData;

    // retrieve unicode text
    if( rFlavor.MimeType.equalsIgnoreAsciiCase( OUString::createFromAscii( "text/plain;charset=utf-16" ) ) )
    {
        if( UWinOpenClipbrd( hAB ) )
        {
            // check if clipboard has text format
            sal_Unicode* pszText = (sal_Unicode*) UWinQueryClipbrdData( hAB, UCLIP_CF_UNICODETEXT);
            if (pszText) {
                // convert to oustring and return it
                OUString aString( pszText);
                aRet <<= aString;
            }
            UWinCloseClipbrd( hAB );
            if (pszText)
                return aRet;
        }
    }

    // retrieve bitmap
    if( rFlavor.MimeType.equalsIgnoreAsciiCase( OUString::createFromAscii( "application/x-openoffice-bitmap;windows_formatname=\"Bitmap\"" ) ) )
    {
        if( UWinOpenClipbrd( hAB ) )
        {
            // check if clipboard has text format
            ULONG handle = UWinQueryClipbrdData( hAB, UCLIP_CF_BITMAP);
            if (handle) {
                Sequence< sal_Int8 > winDIBStream;
                // convert to oustring and return it
                if (OS2HandleToOOoBmp( handle, &winDIBStream))
                    aRet <<= winDIBStream;
                else
                    handle = 0;
            }
            UWinCloseClipbrd( hAB );
            if (handle)
                return aRet;
        }
    }

    // clipboard format unsupported, throw exception
    throw UnsupportedFlavorException( rFlavor.MimeType, static_cast < XTransferable * > ( this ) );
}

//==================================================================================================

Sequence< DataFlavor > SAL_CALL Os2Transferable::getTransferDataFlavors()
    throw(RuntimeException)
{
    debug_printf("Os2Transferable::getTransferDataFlavors %08x\n", this);
    Sequence< DataFlavor > aFlavorList(1);
    aFlavorList[0] = aFlavor;
    debug_printf("Os2Transferable::getTransferDataFlavors mimetype: %s\n", CHAR_POINTER(aFlavor.MimeType));
    return aFlavorList;
}

//==================================================================================================

sal_Bool SAL_CALL Os2Transferable::isDataFlavorSupported( const DataFlavor& aFlavor )
    throw(RuntimeException)
{
    debug_printf("Os2Transferable::isDataFlavorSupported %08x\n", this);
    debug_printf("Os2Transferable::isDataFlavorSupported %s\n", CHAR_POINTER(aFlavor.MimeType));

    if( aFlavor.DataType != getCppuType( (Sequence< sal_Int8 >*)0 ) )
    {
        if( ! aFlavor.MimeType.equalsIgnoreAsciiCase( OUString::createFromAscii( "text/plain;charset=utf-16" ) ) &&
            aFlavor.DataType == getCppuType( (OUString*)0 ) )
            return false;
    }

    Sequence< DataFlavor > aFlavors( getTransferDataFlavors() );
    for( int i = 0; i < aFlavors.getLength(); i++ )
        if( aFlavor.MimeType.equalsIgnoreAsciiCase( aFlavors.getConstArray()[i].MimeType ) &&
            aFlavor.DataType == aFlavors.getConstArray()[i].DataType )
            return sal_True;

    return sal_False;
}

<|endoftext|>


<commit_before>#ifndef SILICIUM_THROWING_SOURCE_HPP
#define SILICIUM_THROWING_SOURCE_HPP

#include <silicium/source/source.hpp>

namespace Si
{
	template <class SourceOfErrorOrs>
	struct throwing_source
	{
		typedef typename SourceOfErrorOrs::element_type::value_type element_type;

		throwing_source()
		{
		}

		explicit throwing_source(SourceOfErrorOrs input)
			: m_input(std::move(input))
		{
		}

		iterator_range<element_type const *> map_next(std::size_t size)
		{
			return {};
		}

		element_type *copy_next(iterator_range<element_type *> destination)
		{
			auto copied = destination.begin();
			while (copied != destination.end())
			{
				auto element = Si::get(m_input);
				if (!element)
				{
					break;
				}
				*copied = std::move(element->get());
				++copied;
			}
			return copied;
		}

	private:

		SourceOfErrorOrs m_input;
	};

	template <class SourceOfErrorOrs>
	auto make_throwing_source(SourceOfErrorOrs &&input)
	{
		return throwing_source<typename std::decay<SourceOfErrorOrs>::type>(std::forward<SourceOfErrorOrs>(input));
	}
}

#endif
<commit_msg>simplify the implementation of make_throwing_source<commit_after>#ifndef SILICIUM_THROWING_SOURCE_HPP
#define SILICIUM_THROWING_SOURCE_HPP

#include <silicium/source/transforming_source.hpp>

namespace Si
{
	template <class SourceOfErrorOrs>
	auto make_throwing_source(SourceOfErrorOrs &&input)
	{
		return make_transforming_source(
			std::forward<SourceOfErrorOrs>(input),
			[](typename std::decay<SourceOfErrorOrs>::type::element_type element)
		{
			return std::move(element).get();
		});
	}
}

#endif
<|endoftext|>


<commit_before>/**
 * File        : ParDivide.cc
 * Description : Parallel divide search implementation. Makes rough
 *               guess of where certain equidistant points in the final
 *               path will be and "commits" them and searches out from
 *               each point (and start and end) in parallel. After
 *               connections have been made it does a final smoothing
 *               stage in case the original guesses are in highly
 *               non-optimal spots
 */

#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <limits>
#include <cmath>
#include <chrono>
#include <thread>
#include <mutex>

#include <boost/lexical_cast.hpp>

#include "tbb/concurrent_unordered_map.h"

#include "algorithms/tools/PathTile.h"
#include "algorithms/tools/PriorityQueue.h"
#include "common/Results.h"

using namespace pathFind;

const std::string WORLD_DIR = "worlds";
const std::string WORLD_EXT = ".world";

const std::string ALG_NAME = "parBidir";

const uint numThreads = 4;

Point findStart (const World& world, uint numThreadsLeft, const Point& start, const Point& end);

void search (uint id, uint startX, uint startY, uint endX, uint endY,
             tbb::concurrent_unordered_map<uint, uint>& tileIdsFound,
             std::unordered_map<uint, PathTile>& expandedTiles,
             std::vector<pathFind::PathTile>& tile, std::vector<std::pair<bool, uint>>& meetingTilesFound,
             const pathFind::World& world, std::mutex& m);

void searchNeighbor (const Point& adjPoint, const World& world, const PathTile& tile,
    PriorityQueue& openTiles, const std::unordered_map<uint, PathTile>& expandedTiles);

int main (int args, char* argv[])
{
    // Program should be started with 5 command line parameter
    // that specifies the name of the world file to read from,
    // the start x, start y, end x, and end y
    if (args != 6 )
    {
        std::cout << "Incorrect inputs. Usage: <filename> <start x> <start y> <end x> <end y>" << std::endl;
        return EXIT_FAILURE;
    }

    // Parse the world file
    std::stringstream filename;
    filename << WORLD_DIR << "/" << argv[1] << WORLD_EXT;

    std::ifstream worldFile (filename.str (),
            std::ifstream::in | std::ifstream::binary);

    if (!worldFile)
    {
        std::cout << "World file doesn't exist." << std::endl;
        return EXIT_FAILURE;
    }
    pathFind::World world;

    worldFile >> world;

    // Parse the start and end points
    uint startX, startY, endX, endY;
    try
    {
        startX = boost::lexical_cast<uint> (argv[2]);
        startY = boost::lexical_cast<uint> (argv[3]);
        endX = boost::lexical_cast<uint> (argv[4]);
        endY = boost::lexical_cast<uint> (argv[5]);
    } catch (boost::bad_lexical_cast &e)
    {
        std::cout << "Start and end points failed to convert to numeric types" << std::endl;
        return EXIT_FAILURE;
    }

    auto t1 = std::chrono::high_resolution_clock::now();

    std::vector<Point> startPoints (numThreads);
    startPoints[0] = Point {startX, startY};
    if (numThreads > 1)
    {
        startPoints.back() = Point {endX, endY};
        uint i = 1;
        uint j = numThreads - 2;
        while (i < j)
        {
            startPoints[i] = findStart (world, j - i + 1, startPoints[i - 1], startPoints[j + 1]);
            startPoints[j] = findStart (world, j - i, startPoints[j + 1], startPoints[i]);
            i++;
            j--;
        }
        if (i == j)
        {
            startPoints[i] = findStart (world, 1, startPoints[i -1], startPoints[i + 1]);
        }
    }

    pathFind::PathTile fTile, rTile;

    std::vector<std::unordered_map<uint, PathTile>> expandedTiles;
    std::unordered_set<uint> idsFound;
    std::mutex m;
    bool finished = false;
    bool fFound = false;
    bool rFound = false;

    std::vector<std::thread> threads (numThreads);
    for (uint i = 0; i < numThreads; ++i)
    {
        threads[i] = std::thread (search, i, startX, startY, endX, endY, std::ref (idsFound),
                std::ref(expandedTiles), std::ref(fTile), std::cref(world),
                std::ref(m), std::ref(finished), std::ref(fFound))
    }

    for (auto& t : threads)
    {
        t.join ();
    }

    if (fFound)
    {
        rTile = reverseExpandedTiles.at (fTile.getTile ().id);
    }
    else
    {
        fTile = forwardExpandedTiles.at (rTile.getTile ().id);
    }
    auto t2 = std::chrono::high_resolution_clock::now();

    // Parse reverse results
    uint totalCost = 0;
    std::vector <Point> reversePath;
    while (rTile.xy ().x != endX || rTile.xy ().y != endY)
    {
        totalCost += rTile.getTile().cost;
        reversePath.emplace_back (rTile.xy ());
        rTile = reverseExpandedTiles[(rTile.bestTile ().y * world.getWidth ()) + rTile.bestTile ().x];
    }
    reversePath.emplace_back (rTile.xy ());

    std::vector<Point> finalPath (reversePath.rbegin (), reversePath.rend ());
    while (fTile.xy ().x != startX || fTile.xy ().y != startY)
    {
        fTile = forwardExpandedTiles[(fTile.bestTile ().y * world.getWidth()) + fTile.bestTile ().x];
        totalCost += fTile.getTile().cost;
        finalPath.emplace_back(fTile.xy ());
    }
    totalCost -= fTile.getTile().cost;

    writeResults (finalPath, argv[1], ALG_NAME,
            std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count(), totalCost);

    return EXIT_SUCCESS;
}

Point findStart (const World& world, uint numThreadsLeft, const Point& start, const Point& end)
{
    if (start.x == end.x && start.y == end.y)
    {
        return start;
    }
    int diffX = static_cast<int> (end.x) - start.x;
    int diffY = static_cast<int> (end.y) - start.y;
    Point forward, backward;
    forward.x = static_cast<float> (diffX) / (numThreadsLeft + 1) + start.x;
    forward.y = static_cast<float> (diffY) / (numThreadsLeft + 1) + start.y;
    backward.x = forward.x;
    backward.y = forward.y;

    int slope;
    bool ySlope = true;
    if (abs (diffX) < abs (diffY))
    {
        slope = (diffY == 0) ? std::numeric_limits<int>::max () : -diffX / diffY;
    }
    else
    {
        slope = (diffX == 0) ? std::numeric_limits<int>::max () : -diffY / diffX;
        ySlope = false;
    }

    uint distAlongSlope = 0;
    int slopeDirection = (slope >= 0) ? 1 : -1;
    while (world (forward.x, forward.y).cost == 0 && world (backward.x, backward.y).cost == 0)
    {
        if (distAlongSlope == slope)
        {
            distAlongSlope = 0;
            if (ySlope)
            {
                forward.x++;
                backward.x++;
            }
            else
            {
                forward.y++;
                backward.y++;
            }
        }
        else
        {
            distAlongSlope += slopeDirection;
            if (ySlope)
            {
                forward.y += slopeDirection;
                backward.y += slopeDirection;
            }
            else
            {
                forward.x += slopeDirection;
                backward.x += slopeDirection;
            }
        }
    }

    return (world (forward.x, forward.y).cost == 0) ? backward : forward;
}

void search (uint id, const Point& start, const Point& predEnd, const Point& succEnd,
             tbb::concurrent_unordered_map<uint, uint>& tileIdsFound,
             std::unordered_map<uint, PathTile>& expandedTiles,
             std::vector<pathFind::PathTile>& meetingTiles, std::vector<std::pair<bool, uint>>& meetingTilesFound,
             const pathFind::World& world, std::mutex& m)
{
    PriorityQueue openTiles (world.getWidth (), world.getHeight (), [predEnd, succEnd] (uint x, uint y)
    {
        return  std::min ((x < predEnd.x ? predEnd.x - x : x - predEnd.x) + (y < predEnd.y ? predEnd.y - y : y - predEnd.y),
            (x < succEnd.x ? succEnd.x - x : x - succEnd.x) + (y < succEnd.y ? succEnd.y - y : y - succEnd.y));
    });

    openTiles.push (world (start.x, start.y), {start.x, start.y}, 0);

    PathTile tile = openTiles.top ();
    openTiles.pop ();
    if (tile.xy().x == predEnd.x && tile.xy().y == predEnd.y)
    {
        meetingTilesFound[id].first = true;
        meetingTilesFound[id].second = id;
    }
    else if(tile.xy().x == succEnd.x && tile.xy().y == succEnd.y)
    {
        meetingTilesFound[id + 1].first = true;
        meetingTilesFound[id + 1].second = id;
    }
    while (!meetingTilesFound[id].first && !meetingTilesFound[id + 1].first)
    {
        if (tileIdsFound.find(tile.getTile().id) == tileIdsFound.end ())
        {

        }
        tileIdsFound[tile.getTile().id] = id;

        expandedTiles[tile.getTile ().id] = tile;

        // Check each neighbor
        Point adjPoint {tile.xy ().x + 1, tile.xy ().y}; // east
        searchNeighbor (adjPoint, world, tile, openTiles, expandedTiles);

        adjPoint = {tile.xy ().x, tile.xy ().y + 1}; // south
        searchNeighbor (adjPoint, world, tile, openTiles, expandedTiles);

        adjPoint = {tile.xy ().x - 1, tile.xy ().y}; // west
        searchNeighbor (adjPoint, world, tile, openTiles, expandedTiles);

        adjPoint = {tile.xy ().x, tile.xy ().y - 1}; // north
        searchNeighbor (adjPoint, world, tile, openTiles, expandedTiles);

        tile = openTiles.top ();
        openTiles.pop ();
        if (tile.xy().x == predEnd.x && tile.xy().y == predEnd.y)
        {
            meetingTilesFound[id].first = true;
            meetingTilesFound[id].second = id;
        }
        else if(tile.xy().x == succEnd.x && tile.xy().y == succEnd.y)
        {
            meetingTilesFound[id + 1].first = true;
            meetingTilesFound[id + 1].second = id;
        }
    }
}

void searchNeighbor (const Point& adjPoint, const World& world, const PathTile& tile,
    PriorityQueue& openTiles, const std::unordered_map<uint, PathTile>& expandedTiles)
{
    if (adjPoint.x < world.getWidth() && adjPoint.y < world.getHeight ())
    {
        World::tile_t worldTile = world (adjPoint.x, adjPoint.y);
        if (worldTile.cost != 0 &&
            expandedTiles.find (worldTile.id) == expandedTiles.end ())
        {
            openTiles.tryUpdateBestCost (worldTile, adjPoint, tile);
        }
    }
}
<commit_msg>Most of the search logic should be done for 1st iter.<commit_after>/**
 * File        : ParDivide.cc
 * Description : Parallel divide search implementation. Makes rough
 *               guess of where certain equidistant points in the final
 *               path will be and "commits" them and searches out from
 *               each point (and start and end) in parallel. After
 *               connections have been made it does a final smoothing
 *               stage in case the original guesses are in highly
 *               non-optimal spots
 */

#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <limits>
#include <cmath>
#include <chrono>
#include <thread>
#include <mutex>

#include <boost/lexical_cast.hpp>

#include "tbb/concurrent_unordered_map.h"
#include "tbb/concurrent_vector.h"

#include "algorithms/tools/PathTile.h"
#include "algorithms/tools/PriorityQueue.h"
#include "common/Results.h"

using namespace pathFind;

const std::string WORLD_DIR = "worlds";
const std::string WORLD_EXT = ".world";

const std::string ALG_NAME = "parBidir";

const uint numThreads = 4;

Point findStart (const World& world, uint numThreadsLeft, const Point& start, const Point& end);

void search (uint id, uint startX, uint startY, uint endX, uint endY,
             tbb::concurrent_unordered_map<uint, uint>& tileIdsFound,
             std::unordered_map<uint, PathTile>& expandedTiles,
             std::vector<pathFind::PathTile>& tile, tbb::concurrent_vector<std::pair<bool, uint>>& meetingTilesFound,
             const pathFind::World& world, std::mutex& m);

void searchNeighbor (const Point& adjPoint, const World& world, const PathTile& tile,
    PriorityQueue& openTiles, const std::unordered_map<uint, PathTile>& expandedTiles);

int main (int args, char* argv[])
{
    // Program should be started with 5 command line parameter
    // that specifies the name of the world file to read from,
    // the start x, start y, end x, and end y
    if (args != 6 )
    {
        std::cout << "Incorrect inputs. Usage: <filename> <start x> <start y> <end x> <end y>" << std::endl;
        return EXIT_FAILURE;
    }

    // Parse the world file
    std::stringstream filename;
    filename << WORLD_DIR << "/" << argv[1] << WORLD_EXT;

    std::ifstream worldFile (filename.str (),
            std::ifstream::in | std::ifstream::binary);

    if (!worldFile)
    {
        std::cout << "World file doesn't exist." << std::endl;
        return EXIT_FAILURE;
    }
    pathFind::World world;

    worldFile >> world;

    // Parse the start and end points
    uint startX, startY, endX, endY;
    try
    {
        startX = boost::lexical_cast<uint> (argv[2]);
        startY = boost::lexical_cast<uint> (argv[3]);
        endX = boost::lexical_cast<uint> (argv[4]);
        endY = boost::lexical_cast<uint> (argv[5]);
    } catch (boost::bad_lexical_cast &e)
    {
        std::cout << "Start and end points failed to convert to numeric types" << std::endl;
        return EXIT_FAILURE;
    }

    auto t1 = std::chrono::high_resolution_clock::now();

    std::vector<Point> startPoints (numThreads);
    startPoints[0] = Point {startX, startY};
    if (numThreads > 1)
    {
        startPoints.back() = Point {endX, endY};
        uint i = 1;
        uint j = numThreads - 2;
        while (i < j)
        {
            startPoints[i] = findStart (world, j - i + 1, startPoints[i - 1], startPoints[j + 1]);
            startPoints[j] = findStart (world, j - i, startPoints[j + 1], startPoints[i]);
            i++;
            j--;
        }
        if (i == j)
        {
            startPoints[i] = findStart (world, 1, startPoints[i -1], startPoints[i + 1]);
        }
    }

    pathFind::PathTile fTile, rTile;

    std::vector<std::unordered_map<uint, PathTile>> expandedTiles (numThreads);
    tbb::concurrent_unordered_map<uint, uint> idsFound;
    std::vector<PathTile> meetingTiles (numThreads + 1);
    std::mutex m;
    bool finished = false;
    bool fFound = false;
    bool rFound = false;

    std::vector<std::thread> threads (numThreads);
    for (uint i = 0; i < numThreads; ++i)
    {
        Point pred = (i == 0) ? startPoints[0] : startPoints[i - 1];
        Point succ = (i == numThreads - 1) ? startPoints[i] : startPoints[i + 1];
        threads[i] = std::thread (search, i, startPoints[i], pred, succ, std::ref (idsFound),
                std::ref(expandedTiles[i]), std::ref(meetingTiles), std::cref(world),
                std::ref(m), std::ref(finished), std::ref(fFound))
    }

    for (auto& t : threads)
    {
        t.join ();
    }

    if (fFound)
    {
        rTile = reverseExpandedTiles.at (fTile.getTile ().id);
    }
    else
    {
        fTile = forwardExpandedTiles.at (rTile.getTile ().id);
    }
    auto t2 = std::chrono::high_resolution_clock::now();

    // Parse reverse results
    uint totalCost = 0;
    std::vector <Point> reversePath;
    while (rTile.xy ().x != endX || rTile.xy ().y != endY)
    {
        totalCost += rTile.getTile().cost;
        reversePath.emplace_back (rTile.xy ());
        rTile = reverseExpandedTiles[(rTile.bestTile ().y * world.getWidth ()) + rTile.bestTile ().x];
    }
    reversePath.emplace_back (rTile.xy ());

    std::vector<Point> finalPath (reversePath.rbegin (), reversePath.rend ());
    while (fTile.xy ().x != startX || fTile.xy ().y != startY)
    {
        fTile = forwardExpandedTiles[(fTile.bestTile ().y * world.getWidth()) + fTile.bestTile ().x];
        totalCost += fTile.getTile().cost;
        finalPath.emplace_back(fTile.xy ());
    }
    totalCost -= fTile.getTile().cost;

    writeResults (finalPath, argv[1], ALG_NAME,
            std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count(), totalCost);

    return EXIT_SUCCESS;
}

Point findStart (const World& world, uint numThreadsLeft, const Point& start, const Point& end)
{
    if (start.x == end.x && start.y == end.y)
    {
        return start;
    }
    int diffX = static_cast<int> (end.x) - start.x;
    int diffY = static_cast<int> (end.y) - start.y;
    Point forward, backward;
    forward.x = static_cast<float> (diffX) / (numThreadsLeft + 1) + start.x;
    forward.y = static_cast<float> (diffY) / (numThreadsLeft + 1) + start.y;
    backward.x = forward.x;
    backward.y = forward.y;

    int slope;
    bool ySlope = true;
    if (abs (diffX) < abs (diffY))
    {
        slope = (diffY == 0) ? std::numeric_limits<int>::max () : -diffX / diffY;
    }
    else
    {
        slope = (diffX == 0) ? std::numeric_limits<int>::max () : -diffY / diffX;
        ySlope = false;
    }

    uint distAlongSlope = 0;
    int slopeDirection = (slope >= 0) ? 1 : -1;
    while (world (forward.x, forward.y).cost == 0 && world (backward.x, backward.y).cost == 0)
    {
        if (distAlongSlope == slope)
        {
            distAlongSlope = 0;
            if (ySlope)
            {
                forward.x++;
                backward.x++;
            }
            else
            {
                forward.y++;
                backward.y++;
            }
        }
        else
        {
            distAlongSlope += slopeDirection;
            if (ySlope)
            {
                forward.y += slopeDirection;
                backward.y += slopeDirection;
            }
            else
            {
                forward.x += slopeDirection;
                backward.x += slopeDirection;
            }
        }
    }

    return (world (forward.x, forward.y).cost == 0) ? backward : forward;
}

void search (uint id, const Point& start, const Point& predEnd, const Point& succEnd,
             tbb::concurrent_unordered_map<uint, uint>& tileIdsFound,
             std::unordered_map<uint, PathTile>& expandedTiles,
             std::vector<pathFind::PathTile>& meetingTiles, tbb::concurrent_vector<std::pair<bool, uint>>& meetingTilesFound,
             const pathFind::World& world, std::mutex& m)
{
    PriorityQueue openTiles (world.getWidth (), world.getHeight (), [predEnd, succEnd] (uint x, uint y)
    {
        return  std::min ((x < predEnd.x ? predEnd.x - x : x - predEnd.x) + (y < predEnd.y ? predEnd.y - y : y - predEnd.y),
            (x < succEnd.x ? succEnd.x - x : x - succEnd.x) + (y < succEnd.y ? succEnd.y - y : y - succEnd.y));
    });
    openTiles.push (world (start.x, start.y), {start.x, start.y}, 0);

    // Used to determine the "farthest" thread that we have met
    // uint predIdMet = id, succIdMet = id;

    while (!meetingTilesFound[id].first || !meetingTilesFound[id + 1].first)
    {
        PathTile tile = openTiles.top ();
        openTiles.pop ();
        if (tile.xy().x == predEnd.x && tile.xy().y == predEnd.y)
        {
            meetingTilesFound[id].first = true;
            meetingTilesFound[id].second = id;
            m.lock ();
            meetingTiles[id] = tile;
            m.unlock ();
        }
        else if(tile.xy().x == succEnd.x && tile.xy().y == succEnd.y)
        {
            meetingTilesFound[id + 1].first = true;
            meetingTilesFound[id + 1].second = id;
            m.lock ();
            meetingTiles[id + 1] = tile;
            m.unlock ();
        }

        auto tileFound = tileIdsFound.find(tile.getTile().id);
        if (tileFound != tileIdsFound.end ())
        {
            if ((tileFound->second == id || tileFound->second == id - 1) && !meetingTilesFound[id].first)
            {
                m.lock ();
                meetingTiles[id] = tile;
                m.unlock ();
                meetingTilesFound[id].first = true;
                meetingTilesFound[id].second = id; // Set who the author was for this discovery
            }
            else if (tileFound->second == id + 1 && !meetingTilesFound[id + 1].first)
            {
                m.lock ();
                meetingTiles[id + 1] = tile;
                m.unlock ();
                meetingTilesFound[id + 1].first = true;
                meetingTilesFound[id + 1].second = id; // Set who the author was for this discovery
            }
        }
        else
        {
            tileIdsFound[tile.getTile().id] = id;
        }
        expandedTiles[tile.getTile ().id] = tile;

        // Check each neighbor
        Point adjPoint {tile.xy ().x + 1, tile.xy ().y}; // east
        searchNeighbor (adjPoint, world, tile, openTiles, expandedTiles);

        adjPoint = {tile.xy ().x, tile.xy ().y + 1}; // south
        searchNeighbor (adjPoint, world, tile, openTiles, expandedTiles);

        adjPoint = {tile.xy ().x - 1, tile.xy ().y}; // west
        searchNeighbor (adjPoint, world, tile, openTiles, expandedTiles);

        adjPoint = {tile.xy ().x, tile.xy ().y - 1}; // north
        searchNeighbor (adjPoint, world, tile, openTiles, expandedTiles);
    }
}

void searchNeighbor (const Point& adjPoint, const World& world, const PathTile& tile,
    PriorityQueue& openTiles, const std::unordered_map<uint, PathTile>& expandedTiles)
{
    if (adjPoint.x < world.getWidth() && adjPoint.y < world.getHeight ())
    {
        World::tile_t worldTile = world (adjPoint.x, adjPoint.y);
        if (worldTile.cost != 0 &&
            expandedTiles.find (worldTile.id) == expandedTiles.end ())
        {
            openTiles.tryUpdateBestCost (worldTile, adjPoint, tile);
        }
    }
}
<|endoftext|>