<commit_before>/****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the $MODULE$ of the Qt Toolkit.
**
** $TROLLTECH_DUAL_LICENSE$
**
****************************************************************************/

#include <QtGui>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
    QMenu *contextMenu;
    QAction* context1;
    QAction* context2;
    QAction* context3;
    QSoftKeyAction *action1;
    QSoftKeyAction *action2;
    QSoftKeyAction *action3;
    QSoftKeyAction *action4;
    QSoftKeyAction *action5;
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      contextMenu(0),
      context1(0), context2(0), context3(0),
      action1(0),action2(0),action3(0),action4(0),action5(0)

{
    QWidget *central = new QWidget(this);
    contextMenu = new QMenu();

    central->setLayout(new QVBoxLayout);
    central->layout()->addWidget(new QPushButton);
    central->layout()->addWidget(new QPushButton);
    central->layout()->addWidget(new QPushButton);
    context1 = new QAction(QString("Context1"), central);
    context2 = new QAction(QString("Context2"), central);

    context3 = new QAction(QString("Context3"), contextMenu);
    central->addAction(context1);
    central->addAction(context2);
    QMenuBar* menuBar = new QMenuBar(this);
    menuBar->addAction("MyMenuItem1");
    this->setMenuBar(menuBar);
    context2->setMenu(contextMenu);
    contextMenu->addAction(context3);

    action1 = new QSoftKeyAction(QSoftKeyAction::Ok, QString("Ok"), central);
    action2 = new QSoftKeyAction(QSoftKeyAction::Back, QString("Back"), central);
    action3 = new QSoftKeyAction(QSoftKeyAction::Cancel, QString("Cancel"), central);
    action4 = new QSoftKeyAction(QSoftKeyAction::Menu, QString("Menu"), central);
    action5 = new QSoftKeyAction(QSoftKeyAction::ContextMenu,QString("ContextMenu"), central);

    QList<QSoftKeyAction*> myActionList;
    myActionList.append(action1);
    myActionList.append(action2);
    myActionList.append(action3);
    softKeyStack()->push(myActionList);
    softKeyStack()->pop();
    softKeyStack()->push(action1);
    softKeyStack()->pop();

    QList<QSoftKeyAction*> myActionList2;
    myActionList2.append(action4);
    myActionList2.append(action5);
    softKeyStack()->push(myActionList2);

    setCentralWidget(central);
}
MainWindow::~MainWindow()
{
    delete context1;
    delete context2;
    delete context3;
    delete action1;
    delete action2;
    delete action3;
    delete action4;
    delete action5;
    delete contextMenu;
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow mw;
    mw.show();
    return app.exec();
}

#include "main.moc"
<commit_msg>Catch actions coming from context sensitive menu items<commit_after>/****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the $MODULE$ of the Qt Toolkit.
**
** $TROLLTECH_DUAL_LICENSE$
**
****************************************************************************/

#include <QtGui>

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:

private slots:
    void context1Slot();
    void context3Slot();
public:

    MainWindow(QWidget *parent = 0);
    ~MainWindow();
    QMenu *contextMenu;
    QAction* context1;
    QAction* context2;
    QAction* context3;
    QSoftKeyAction *action1;
    QSoftKeyAction *action2;
    QSoftKeyAction *action3;
    QSoftKeyAction *action4;
    QSoftKeyAction *action5;
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      contextMenu(0),
      context1(0), context2(0), context3(0),
      action1(0),action2(0),action3(0),action4(0),action5(0)

{
    QWidget *central = new QWidget(this);
    contextMenu = new QMenu();

    central->setLayout(new QVBoxLayout);
    central->layout()->addWidget(new QPushButton);
    central->layout()->addWidget(new QPushButton);
    central->layout()->addWidget(new QPushButton);
    context1 = new QAction(QString("Context1"), central);
    context2 = new QAction(QString("Context2"), central);

    context3 = new QAction(QString("Context3"), contextMenu);
    central->addAction(context1);
    central->addAction(context2);
    QMenuBar* menuBar = new QMenuBar(this);
    menuBar->addAction("MyMenuItem1");
    this->setMenuBar(menuBar);
    context2->setMenu(contextMenu);
    contextMenu->addAction(context3);

    connect(context1, SIGNAL(triggered()), this, SLOT(context1Slot()));
    connect(context3, SIGNAL(triggered()), this, SLOT(context3Slot()));
    action1 = new QSoftKeyAction(QSoftKeyAction::Ok, QString("Ok"), central);
    action2 = new QSoftKeyAction(QSoftKeyAction::Back, QString("Back"), central);
    action3 = new QSoftKeyAction(QSoftKeyAction::Cancel, QString("Cancel"), central);
    action4 = new QSoftKeyAction(QSoftKeyAction::Menu, QString("Menu"), central);
    action5 = new QSoftKeyAction(QSoftKeyAction::ContextMenu,QString("ContextMenu"), central);

    QList<QSoftKeyAction*> myActionList;
    myActionList.append(action1);
    myActionList.append(action2);
    myActionList.append(action3);
    softKeyStack()->push(myActionList);
    softKeyStack()->pop();
    softKeyStack()->push(action1);
    softKeyStack()->pop();

    QList<QSoftKeyAction*> myActionList2;
    myActionList2.append(action4);
    myActionList2.append(action5);
    softKeyStack()->push(myActionList2);

    setCentralWidget(central);
}
MainWindow::~MainWindow()
{
    delete context1;
    delete context2;
    delete context3;
    delete action1;
    delete action2;
    delete action3;
    delete action4;
    delete action5;
    delete contextMenu;
}

void MainWindow::context1Slot()
    {
    }
void MainWindow::context3Slot()
    {
    }

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow mw;
    mw.show();
    return app.exec();
}

#include "main.moc"
<|endoftext|>


<commit_before>#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <boost/filesystem.hpp>
#include <stdio.h>

using namespace cv;
using namespace std;
using namespace boost::filesystem;

struct params {
	path in;
	path out;
	int notch;
	float rotation;
	int x, y;
	int h,w,d;
};

params* parseInputs( int argc, char** argv );

int main( int argc, char** argv )
{
	params* maple = parseInputs( argc, argv );

}

params* parseInputs( int argc, char** argv )
// pin pout rotation x y h w d
{
	params* thisparams;
	if( argc != 10 )
	{
		perror("Usage: wpart /from/path /to/path rotation notch x y h w d");
	}
	else
	{
		thisparams = new params;
		thisparams->in = path(argv[1]);
		thisparams->out = path(argv[2]);
		thisparams->rotation = std::strtof(argv[3], nullptr);
		thisparams->notch = std::stoi(argv[4], nullptr, 10);
		thisparams->x = std::stoi(argv[5], nullptr, 10);
		thisparams->y = std::stoi(argv[6], nullptr, 10);
		thisparams->h = std::stoi(argv[7], nullptr, 10);
		thisparams->w = std::stoi(argv[8], nullptr, 10);
		thisparams->d = std::stoi(argv[9], nullptr, 10);
	}
	CV_Assert( thisparams != NULL );
	return thisparams;
}
<commit_msg>Delete wpart.cpp<commit_after><|endoftext|>


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

#include <QtGui>
#include <QPushButton>

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>

#include <core/Log.hpp>

#include <core/system/FileScanner.hpp>
#include <core/SafeConvert.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <core/system/Environment.hpp>
#include <core/r_util/RProjectFile.hpp>
#include <core/r_util/RUserData.hpp>

#include "DesktopApplicationLaunch.hpp"
#include "DesktopSlotBinders.hpp"
#include "DesktopDetectRHome.hpp"
#include "DesktopUtils.hpp"
#include "DesktopSessionLauncher.hpp"
#include "DesktopProgressActivator.hpp"
#include "DesktopNetworkProxyFactory.hpp"
#include "DesktopActivationOverlay.hpp"

QProcess* pRSessionProcess;
QString sharedSecret;

using namespace rstudio;
using namespace rstudio::core;
using namespace rstudio::desktop;

namespace {

void initializeSharedSecret()
{
   sharedSecret = QString::number(rand())
                  + QString::number(rand())
                  + QString::number(rand());
   std::string value = sharedSecret.toUtf8().constData();
   core::system::setenv("RS_SHARED_SECRET", value);
}

void initializeWorkingDirectory(int argc,
                                char* argv[],
                                const QString& filename)
{
   // bail if we've already got a working directory as a result of
   // a call to openSessionInNewWindow
   if (!core::system::getenv(kRStudioInitialWorkingDir).empty())
      return;

   // calculate what our initial working directory should be
   std::string workingDir;

   // if there is a filename passed to us then use it's path
   if (filename != QString())
   {
      FilePath filePath(filename.toUtf8().constData());
      if (filePath.exists())
      {
         if (filePath.isDirectory())
            workingDir = filePath.absolutePath();
         else
            workingDir = filePath.parent().absolutePath();
      }
   }

   // do additinal detection if necessary
   if (workingDir.empty())
   {
      // get current path
      FilePath currentPath = FilePath::safeCurrentPath(
                                       core::system::userHomePath());

#if defined(_WIN32) || defined(__APPLE__)

      // detect whether we were launched from the system application menu
      // (e.g. Dock, Program File icon, etc.). we do this by checking
      // whether the executable path is within the current path. if we
      // weren't launched from the system app menu that set the initial
      // wd to the current path

      FilePath exePath;
      Error error = core::system::executablePath(argv[0], &exePath);
      if (!error)
      {
         if (!exePath.isWithin(currentPath))
            workingDir = currentPath.absolutePath();
      }
      else
      {
         LOG_ERROR(error);
      }

#else

      // on linux we take the current working dir if we were launched
      // from within a terminal
      if (core::system::stdoutIsTerminal() &&
         (currentPath != core::system::userHomePath()))
      {
         workingDir = currentPath.absolutePath();
      }

#endif

   }

   // set the working dir if we have one
   if (!workingDir.empty())
      core::system::setenv(kRStudioInitialWorkingDir, workingDir);
}

void setInitialProject(const FilePath& projectFile, QString* pFilename)
{
   core::system::setenv(kRStudioInitialProject, projectFile.absolutePath());
   pFilename->clear();
}

void initializeStartupEnvironment(QString* pFilename)
{
   // if the filename ends with .RData or .rda then this is an
   // environment file. if it ends with .Rproj then it is
   // a project file. we handle both cases by setting an environment
   // var and then resetting the pFilename so it isn't processed
   // using the standard open file logic
   FilePath filePath(pFilename->toUtf8().constData());
   if (filePath.exists())
   {
      std::string ext = filePath.extensionLowerCase();

      // if it is a directory or just an .rdata file then we can see
      // whether there is a project file we can automatically attach to
      if (filePath.isDirectory())
      {
         FilePath projectFile = r_util::projectFromDirectory(filePath);
         if (!projectFile.empty())
         {
            setInitialProject(projectFile, pFilename);
         }
      }
      else if (ext == ".rproj")
      {
         setInitialProject(filePath, pFilename);
      }
      else if (ext == ".rdata" || ext == ".rda")
      {
         core::system::setenv(kRStudioInitialEnvironment, filePath.absolutePath());
         pFilename->clear();
      }

   }
}

QString verifyAndNormalizeFilename(const QString &filename)
{
   if (filename.isNull() || filename.isEmpty())
      return QString();

   QFileInfo fileInfo(filename);
   if (fileInfo.exists())
      return fileInfo.absoluteFilePath();
   else
      return QString();
}

bool isNonProjectFilename(const QString &filename)
{
   if (filename.isNull() || filename.isEmpty())
      return false;

   FilePath filePath(filename.toUtf8().constData());
   return filePath.exists() && filePath.extensionLowerCase() != ".rproj";
}

bool useChromiumDevtools()
{
   // disable by default due to security concerns
   // https://bugreports.qt.io/browse/QTBUG-50725
   bool useDevtools = false;

#ifndef NDEBUG
   // but enable by default for development builds
   useDevtools = true;
#endif

   // enable when environment variable is set
   if (!core::system::getenv("RSTUDIO_USE_CHROMIUM_DEVTOOLS").empty())
   {
      useDevtools = true;
   }

   return useDevtools;
}

} // anonymous namespace

int main(int argc, char* argv[])
{
   core::system::initHook();

   try
   {
      initializeLang();

      if (useChromiumDevtools())
      {
         // use QTcpSocket to find an open port. this is unfortunately a bit racey
         // but AFAICS there isn't a better solution for port selection
         QByteArray port;
         QTcpSocket* pSocket = new QTcpSocket();
         if (pSocket->bind())
         {
            quint16 port = pSocket->localPort();
            desktopInfo().setChromiumDevtoolsPort(port);
            core::system::setenv("QTWEBENGINE_REMOTE_DEBUGGING", safe_convert::numberToString(port));
            pSocket->close();
         }
      }

      // initialize log
      core::system::initializeLog("rdesktop",
                                  core::system::kLogLevelWarning,
                                  desktop::userLogPath());

      // ignore SIGPIPE
      Error error = core::system::ignoreSignal(core::system::SigPipe);
      if (error)
         LOG_ERROR(error);

      // set application attributes
      QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

      // prepare command line arguments
      static std::vector<char*> arguments(argv, argv + argc);

#ifndef NDEBUG
      // disable web security for development builds (so we can
      // get access to sourcemaps)
      static char disableWebSecurity[] = "--disable-web-security";
      arguments.push_back(disableWebSecurity);
#endif

      // disable chromium renderer accessibility by default (it can cause
      // slowdown when used in conjunction with some applications; see e.g.
      // https://github.com/rstudio/rstudio/issues/1990)
      if (core::system::getenv("RSTUDIO_ACCESSIBILITY").empty())
      {
         static char disableRendererAccessibility[] = "--disable-renderer-accessibility";
         arguments.push_back(disableRendererAccessibility);
      }

      // re-assign command line arguments
      argc = (int) arguments.size();
      argv = &arguments[0];

      // prepare application for launch
      boost::scoped_ptr<QApplication> pApp;
      boost::scoped_ptr<ApplicationLaunch> pAppLaunch;
      ApplicationLaunch::init(QString::fromUtf8("RStudio"),
                              argc,
                              argv,
                              &pApp,
                              &pAppLaunch);

      // determine the filename that was passed to us
      QString filename;
#ifdef __APPLE__
      // get filename from OpenFile apple-event (pump to ensure delivery)
      pApp->processEvents();
      filename = verifyAndNormalizeFilename(
                              pAppLaunch->startupOpenFileRequest());
#endif
      // allow all platforms (including OSX) to check the command line.
      // we include OSX because the way Qt handles apple events is to
      // re-route them to the first instance to register for events. in
      // this case (for projects) we use this to initiate a launch
      // of the application with the project filename on the command line
      if (filename.isEmpty())
      {
         // get filename from command line arguments
         if (pApp->arguments().size() > 1)
         {
            QString arg = pApp->arguments().at(1);
            if (arg != QString::fromUtf8(kRunDiagnosticsOption))
               filename = verifyAndNormalizeFilename(arg);
         }
      }

      // if we have a filename and it is NOT a project file then see
      // if we can open it within an existing instance
      if (isNonProjectFilename(filename))
      {
         if (pAppLaunch->sendMessage(filename))
            return 0;
      }
      else
      {
         // try to register ourselves as a peer for others
         pAppLaunch->attemptToRegisterPeer();
      }

      // init options from command line
      desktop::options().initFromCommandLine(pApp->arguments());

      // reset log if we are in run-diagnostics mode
      if (desktop::options().runDiagnostics())
      {
         desktop::reattachConsoleIfNecessary();
         initializeStderrLog("rdesktop", core::system::kLogLevelWarning);
      }

      initializeSharedSecret();
      initializeWorkingDirectory(argc, argv, filename);
      initializeStartupEnvironment(&filename);

      Options& options = desktop::options();
      if (!prepareEnvironment(options))
         return 1;

      // get install path
      FilePath installPath;
      error = core::system::installPath("..", argv[0], &installPath);
      if (error)
      {
         LOG_ERROR(error);
         return EXIT_FAILURE;
      }

#ifdef _WIN32
      RVersion version = detectRVersion(false);
#endif

      // calculate paths to config file, rsession, and desktop scripts
      FilePath confPath, sessionPath, scriptsPath;
      bool devMode = false;

      // check for debug configuration
      FilePath currentPath = FilePath::safeCurrentPath(installPath);
      if (currentPath.complete("conf/rdesktop-dev.conf").exists())
      {
         confPath = currentPath.complete("conf/rdesktop-dev.conf");
         sessionPath = currentPath.complete("session/rsession");
         scriptsPath = currentPath.complete("desktop");
         devMode = true;
#ifdef _WIN32
         if (version.architecture() == ArchX64)
            sessionPath = installPath.complete("session/x64/rsession");
#endif
      }

      // if there is no conf path then release mode
      if (confPath.empty())
      {
         // default paths (then tweak)
         sessionPath = installPath.complete("bin/rsession");
         scriptsPath = installPath.complete("bin");

         // check for win64 binary on windows
#ifdef _WIN32
         if (version.architecture() == ArchX64)
            sessionPath = installPath.complete("bin/x64/rsession");
#endif

         // check for running in a bundle on OSX
#ifdef __APPLE__
         if (installPath.complete("Info.plist").exists())
         {
            sessionPath = installPath.complete("MacOS/rsession");
            scriptsPath = installPath.complete("MacOS");
         }
#endif
      }
      core::system::fixupExecutablePath(&sessionPath);

      auto* pProxyFactory = new NetworkProxyFactory();
      QNetworkProxyFactory::setApplicationProxyFactory(pProxyFactory);

      // set the scripts path in options
      desktop::options().setScriptsPath(scriptsPath);

      // launch session
      SessionLauncher sessionLauncher(sessionPath, confPath, filename, pAppLaunch.get());
      sessionLauncher.launchFirstSession(installPath, devMode, pApp->arguments());

      ProgressActivator progressActivator;

      int result = pApp->exec();

      desktop::activation().releaseLicense();
      options.cleanUpScratchTempDir();

      return result;
   }
   CATCH_UNEXPECTED_EXCEPTION
}

#ifdef _WIN32
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nShowCmd)
{
   return main(__argc, __argv);
}
#endif
<commit_msg>Fix for Qt 5.10.1 bug where RStudio crashes on startup on Linux<commit_after>/*
 * DesktopMain.cpp
 *
 * Copyright (C) 2009-18 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include <QtGui>
#include <QPushButton>

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/scoped_ptr.hpp>

#include <core/Log.hpp>

#include <core/system/FileScanner.hpp>
#include <core/SafeConvert.hpp>
#include <core/StringUtils.hpp>
#include <core/system/System.hpp>
#include <core/system/Environment.hpp>
#include <core/r_util/RProjectFile.hpp>
#include <core/r_util/RUserData.hpp>

#include "DesktopApplicationLaunch.hpp"
#include "DesktopSlotBinders.hpp"
#include "DesktopDetectRHome.hpp"
#include "DesktopUtils.hpp"
#include "DesktopSessionLauncher.hpp"
#include "DesktopProgressActivator.hpp"
#include "DesktopNetworkProxyFactory.hpp"
#include "DesktopActivationOverlay.hpp"

QProcess* pRSessionProcess;
QString sharedSecret;

using namespace rstudio;
using namespace rstudio::core;
using namespace rstudio::desktop;

namespace {

void initializeSharedSecret()
{
   sharedSecret = QString::number(rand())
                  + QString::number(rand())
                  + QString::number(rand());
   std::string value = sharedSecret.toUtf8().constData();
   core::system::setenv("RS_SHARED_SECRET", value);
}

void initializeWorkingDirectory(int argc,
                                char* argv[],
                                const QString& filename)
{
   // bail if we've already got a working directory as a result of
   // a call to openSessionInNewWindow
   if (!core::system::getenv(kRStudioInitialWorkingDir).empty())
      return;

   // calculate what our initial working directory should be
   std::string workingDir;

   // if there is a filename passed to us then use it's path
   if (filename != QString())
   {
      FilePath filePath(filename.toUtf8().constData());
      if (filePath.exists())
      {
         if (filePath.isDirectory())
            workingDir = filePath.absolutePath();
         else
            workingDir = filePath.parent().absolutePath();
      }
   }

   // do additinal detection if necessary
   if (workingDir.empty())
   {
      // get current path
      FilePath currentPath = FilePath::safeCurrentPath(
                                       core::system::userHomePath());

#if defined(_WIN32) || defined(__APPLE__)

      // detect whether we were launched from the system application menu
      // (e.g. Dock, Program File icon, etc.). we do this by checking
      // whether the executable path is within the current path. if we
      // weren't launched from the system app menu that set the initial
      // wd to the current path

      FilePath exePath;
      Error error = core::system::executablePath(argv[0], &exePath);
      if (!error)
      {
         if (!exePath.isWithin(currentPath))
            workingDir = currentPath.absolutePath();
      }
      else
      {
         LOG_ERROR(error);
      }

#else

      // on linux we take the current working dir if we were launched
      // from within a terminal
      if (core::system::stdoutIsTerminal() &&
         (currentPath != core::system::userHomePath()))
      {
         workingDir = currentPath.absolutePath();
      }

#endif

   }

   // set the working dir if we have one
   if (!workingDir.empty())
      core::system::setenv(kRStudioInitialWorkingDir, workingDir);
}

void setInitialProject(const FilePath& projectFile, QString* pFilename)
{
   core::system::setenv(kRStudioInitialProject, projectFile.absolutePath());
   pFilename->clear();
}

void initializeStartupEnvironment(QString* pFilename)
{
   // if the filename ends with .RData or .rda then this is an
   // environment file. if it ends with .Rproj then it is
   // a project file. we handle both cases by setting an environment
   // var and then resetting the pFilename so it isn't processed
   // using the standard open file logic
   FilePath filePath(pFilename->toUtf8().constData());
   if (filePath.exists())
   {
      std::string ext = filePath.extensionLowerCase();

      // if it is a directory or just an .rdata file then we can see
      // whether there is a project file we can automatically attach to
      if (filePath.isDirectory())
      {
         FilePath projectFile = r_util::projectFromDirectory(filePath);
         if (!projectFile.empty())
         {
            setInitialProject(projectFile, pFilename);
         }
      }
      else if (ext == ".rproj")
      {
         setInitialProject(filePath, pFilename);
      }
      else if (ext == ".rdata" || ext == ".rda")
      {
         core::system::setenv(kRStudioInitialEnvironment, filePath.absolutePath());
         pFilename->clear();
      }

   }
}

QString verifyAndNormalizeFilename(const QString &filename)
{
   if (filename.isNull() || filename.isEmpty())
      return QString();

   QFileInfo fileInfo(filename);
   if (fileInfo.exists())
      return fileInfo.absoluteFilePath();
   else
      return QString();
}

bool isNonProjectFilename(const QString &filename)
{
   if (filename.isNull() || filename.isEmpty())
      return false;

   FilePath filePath(filename.toUtf8().constData());
   return filePath.exists() && filePath.extensionLowerCase() != ".rproj";
}

bool useChromiumDevtools()
{
   // disable by default due to security concerns
   // https://bugreports.qt.io/browse/QTBUG-50725
   bool useDevtools = false;

#ifndef NDEBUG
   // but enable by default for development builds
   useDevtools = true;
#endif

   // enable when environment variable is set
   if (!core::system::getenv("RSTUDIO_USE_CHROMIUM_DEVTOOLS").empty())
   {
      useDevtools = true;
   }

   return useDevtools;
}

} // anonymous namespace

int main(int argc, char* argv[])
{
   core::system::initHook();

   try
   {
      initializeLang();

      if (useChromiumDevtools())
      {
         // use QTcpSocket to find an open port. this is unfortunately a bit racey
         // but AFAICS there isn't a better solution for port selection
         QByteArray port;
         QTcpSocket* pSocket = new QTcpSocket();
         if (pSocket->bind())
         {
            quint16 port = pSocket->localPort();
            desktopInfo().setChromiumDevtoolsPort(port);
            core::system::setenv("QTWEBENGINE_REMOTE_DEBUGGING", safe_convert::numberToString(port));
            pSocket->close();
         }
      }

      // initialize log
      core::system::initializeLog("rdesktop",
                                  core::system::kLogLevelWarning,
                                  desktop::userLogPath());

      // ignore SIGPIPE
      Error error = core::system::ignoreSignal(core::system::SigPipe);
      if (error)
         LOG_ERROR(error);

      // set application attributes
      QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

      // prepare command line arguments
      static std::vector<char*> arguments(argv, argv + argc);

#ifndef NDEBUG
      // disable web security for development builds (so we can
      // get access to sourcemaps)
      static char disableWebSecurity[] = "--disable-web-security";
      arguments.push_back(disableWebSecurity);
#endif

      // disable chromium renderer accessibility by default (it can cause
      // slowdown when used in conjunction with some applications; see e.g.
      // https://github.com/rstudio/rstudio/issues/1990)
      if (core::system::getenv("RSTUDIO_ACCESSIBILITY").empty())
      {
         static char disableRendererAccessibility[] = "--disable-renderer-accessibility";
         arguments.push_back(disableRendererAccessibility);
      }

#ifdef Q_OS_LINUX
      // workaround for Qt 5.10.1 bug "Could not find QtWebEngineProcess"
      // https://bugreports.qt.io/browse/QTBUG-67023
      // https://bugreports.qt.io/browse/QTBUG-66346
      static char noSandbox[] = "--no-sandbox";
      arguments.push_back(noSandbox);
#endif

      // re-assign command line arguments
      argc = (int) arguments.size();
      argv = &arguments[0];

      // prepare application for launch
      boost::scoped_ptr<QApplication> pApp;
      boost::scoped_ptr<ApplicationLaunch> pAppLaunch;
      ApplicationLaunch::init(QString::fromUtf8("RStudio"),
                              argc,
                              argv,
                              &pApp,
                              &pAppLaunch);

      // determine the filename that was passed to us
      QString filename;
#ifdef __APPLE__
      // get filename from OpenFile apple-event (pump to ensure delivery)
      pApp->processEvents();
      filename = verifyAndNormalizeFilename(
                              pAppLaunch->startupOpenFileRequest());
#endif
      // allow all platforms (including OSX) to check the command line.
      // we include OSX because the way Qt handles apple events is to
      // re-route them to the first instance to register for events. in
      // this case (for projects) we use this to initiate a launch
      // of the application with the project filename on the command line
      if (filename.isEmpty())
      {
         // get filename from command line arguments
         if (pApp->arguments().size() > 1)
         {
            QString arg = pApp->arguments().at(1);
            if (arg != QString::fromUtf8(kRunDiagnosticsOption))
               filename = verifyAndNormalizeFilename(arg);
         }
      }

      // if we have a filename and it is NOT a project file then see
      // if we can open it within an existing instance
      if (isNonProjectFilename(filename))
      {
         if (pAppLaunch->sendMessage(filename))
            return 0;
      }
      else
      {
         // try to register ourselves as a peer for others
         pAppLaunch->attemptToRegisterPeer();
      }

      // init options from command line
      desktop::options().initFromCommandLine(pApp->arguments());

      // reset log if we are in run-diagnostics mode
      if (desktop::options().runDiagnostics())
      {
         desktop::reattachConsoleIfNecessary();
         initializeStderrLog("rdesktop", core::system::kLogLevelWarning);
      }

      initializeSharedSecret();
      initializeWorkingDirectory(argc, argv, filename);
      initializeStartupEnvironment(&filename);

      Options& options = desktop::options();
      if (!prepareEnvironment(options))
         return 1;

      // get install path
      FilePath installPath;
      error = core::system::installPath("..", argv[0], &installPath);
      if (error)
      {
         LOG_ERROR(error);
         return EXIT_FAILURE;
      }

#ifdef _WIN32
      RVersion version = detectRVersion(false);
#endif

      // calculate paths to config file, rsession, and desktop scripts
      FilePath confPath, sessionPath, scriptsPath;
      bool devMode = false;

      // check for debug configuration
      FilePath currentPath = FilePath::safeCurrentPath(installPath);
      if (currentPath.complete("conf/rdesktop-dev.conf").exists())
      {
         confPath = currentPath.complete("conf/rdesktop-dev.conf");
         sessionPath = currentPath.complete("session/rsession");
         scriptsPath = currentPath.complete("desktop");
         devMode = true;
#ifdef _WIN32
         if (version.architecture() == ArchX64)
            sessionPath = installPath.complete("session/x64/rsession");
#endif
      }

      // if there is no conf path then release mode
      if (confPath.empty())
      {
         // default paths (then tweak)
         sessionPath = installPath.complete("bin/rsession");
         scriptsPath = installPath.complete("bin");

         // check for win64 binary on windows
#ifdef _WIN32
         if (version.architecture() == ArchX64)
            sessionPath = installPath.complete("bin/x64/rsession");
#endif

         // check for running in a bundle on OSX
#ifdef __APPLE__
         if (installPath.complete("Info.plist").exists())
         {
            sessionPath = installPath.complete("MacOS/rsession");
            scriptsPath = installPath.complete("MacOS");
         }
#endif
      }
      core::system::fixupExecutablePath(&sessionPath);

      auto* pProxyFactory = new NetworkProxyFactory();
      QNetworkProxyFactory::setApplicationProxyFactory(pProxyFactory);

      // set the scripts path in options
      desktop::options().setScriptsPath(scriptsPath);

      // launch session
      SessionLauncher sessionLauncher(sessionPath, confPath, filename, pAppLaunch.get());
      sessionLauncher.launchFirstSession(installPath, devMode, pApp->arguments());

      ProgressActivator progressActivator;

      int result = pApp->exec();

      desktop::activation().releaseLicense();
      options.cleanUpScratchTempDir();

      return result;
   }
   CATCH_UNEXPECTED_EXCEPTION
}

#ifdef _WIN32
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nShowCmd)
{
   return main(__argc, __argv);
}
#endif
<|endoftext|>


<commit_before>#include <signal.h>

#include "gen/wsdd.nsmap"
#include "wsddapi.h"

const char* host = "239.255.255.250";
int port = 3702;
const int _metadataVersion = 1;
const char* _xaddr="http://localhost/service";
const char* _type="\"http://schemas.xmlsoap.org/ws/2006/02/devprof\":device";
const char* _endpoint="urn";

bool stop = false;
void sighandler(int sig)
{
	std::cout<< "Signal caught..." << std::endl;
	stop = true;
}

int mainloop(soap* serv)
{
	return soap_wsdd_listen(serv, -1000000);
}

void sendHello()
{
	struct soap* soap = soap_new1(SOAP_IO_UDP);
	printf("call soap_wsdd_Hello\n");
	int res = soap_wsdd_Hello(soap,
	  SOAP_WSDD_ADHOC,      // mode
	  "soap.udp://239.255.255.250:3702",         // address of TS
	  soap_wsa_rand_uuid(soap),                   // message ID
	  NULL,
	  _endpoint,
	  NULL,
	  _type,
	  NULL,
	  _xaddr,
          _metadataVersion);
	if (res != SOAP_OK)
	{
		soap_print_fault(soap, stderr);
	}
	soap_end(soap);
}

void sendBye()
{
	struct soap* soap = soap_new1(SOAP_IO_UDP);
	printf("call soap_wsdd_Bye\n");
	int res = soap_wsdd_Bye(soap,
	  SOAP_WSDD_ADHOC,      // mode
	  "soap.udp://239.255.255.250:3702",         // address of TS
	  soap_wsa_rand_uuid(soap),                   // message ID
	  _endpoint,
	  NULL,
	  _type,
	  NULL,
	  _xaddr,
          _metadataVersion);
	if (res != SOAP_OK)
	{
		soap_print_fault(soap, stderr);
	}
	soap_end(soap);
}

int main(int argc, char** argv)
{
	struct soap* serv = soap_new1(SOAP_IO_UDP | SOAP_IO_KEEPALIVE);
	serv->bind_flags=SO_REUSEADDR;
	if (!soap_valid_socket(soap_bind(serv, NULL, port, 1000)))
	{
		soap_print_fault(serv, stderr);
		exit(1);
	}

	ip_mreq mcast;
	mcast.imr_multiaddr.s_addr = inet_addr(host);
	mcast.imr_interface.s_addr = htonl(INADDR_ANY);
	if (setsockopt(serv->master, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast))<0)
	{
		std::cout << "group membership failed:" << strerror(errno) << std::endl;
	}

	sendHello();
	mainloop(serv);

	signal(SIGINT, &sighandler);
	while (!stop)
	{
		mainloop(serv);
	}

	sendBye();
	mainloop(serv);

	return 0;
}

void wsdd_event_ProbeMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ProbeMatchesType *matches)
{
	printf("wsdd_event_ProbeMatches nbMatch:%d\n", matches->__sizeProbeMatch);
}

void wsdd_event_ResolveMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ResolveMatchType *match)
{
	printf("wsdd_event_ResolveMatches\n");
}

void wsdd_event_Hello(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int MetadataVersion)
{
	printf("wsdd_event_Hello id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs);
}

void wsdd_event_Bye(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int *MetadataVersion)
{
	printf("wsdd_event_Bye id=%s EndpointReference=%s XAddrs=%s\n", MessageID, EndpointReference, XAddrs);
}

soap_wsdd_mode wsdd_event_Resolve(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *EndpointReference, struct wsdd__ResolveMatchType *match)
{
	printf("wsdd_event_Resolve  id=%s replyTo=%s\n", MessageID, ReplyTo);
	return SOAP_WSDD_ADHOC;
}

soap_wsdd_mode wsdd_event_Probe(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *Types, const char *Scopes, const char *MatchBy, struct wsdd__ProbeMatchesType *matches)
{
	printf("wsdd_event_Probe id=%s replyTo=%s types=%s scopes=%s\n", MessageID, ReplyTo, Types, Scopes);
	soap_wsdd_init_ProbeMatches(soap,matches);
	soap_wsdd_add_ProbeMatch(soap, matches, _endpoint, _type, NULL, NULL, _xaddr, _metadataVersion);
	soap_wsdd_ProbeMatches(soap, NULL, soap_wsa_rand_uuid(soap) , MessageID, ReplyTo, matches);
	return SOAP_WSDD_ADHOC;
}

<commit_msg>implment resolve + add scope parameter<commit_after>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** server.cpp
**
** WS-Discovery device
**
** -------------------------------------------------------------------------*/

#include <signal.h>

#include "gen/wsdd.nsmap"
#include "wsddapi.h"

const char* host = "239.255.255.250";
int port = 3702;
const int   _metadataVersion = 1;
const char* _xaddr="http://localhost/service";
const char* _type="\"http://schemas.xmlsoap.org/ws/2006/02/devprof\":device";
const char* _scope="scope";
const char* _endpoint="urn";

bool stop = false;
void sighandler(int sig)
{
	std::cout<< "Signal caught..." << std::endl;
	stop = true;
}

int mainloop(soap* serv)
{
	return soap_wsdd_listen(serv, -1000000);
}

void sendHello()
{
	struct soap* soap = soap_new1(SOAP_IO_UDP);
	printf("call soap_wsdd_Hello\n");
	int res = soap_wsdd_Hello(soap,
	  SOAP_WSDD_ADHOC,      // mode
	  "soap.udp://239.255.255.250:3702",         // address of TS
	  soap_wsa_rand_uuid(soap),                   // message ID
	  NULL,
	  _endpoint,
	  _type,
	  _scope,
	  NULL,
	  _xaddr,
          _metadataVersion);
	if (res != SOAP_OK)
	{
		soap_print_fault(soap, stderr);
	}
	soap_end(soap);
}

void sendBye()
{
	struct soap* soap = soap_new1(SOAP_IO_UDP);
	printf("call soap_wsdd_Bye\n");
	int res = soap_wsdd_Bye(soap,
	  SOAP_WSDD_ADHOC,      // mode
	  "soap.udp://239.255.255.250:3702",         // address of TS
	  soap_wsa_rand_uuid(soap),                   // message ID
	  _endpoint,
	  _type,
	  _scope,
	  NULL,
	  _xaddr,
          _metadataVersion);
	if (res != SOAP_OK)
	{
		soap_print_fault(soap, stderr);
	}
	soap_end(soap);
}

int main(int argc, char** argv)
{
	struct soap* serv = soap_new1(SOAP_IO_UDP);
	serv->bind_flags=SO_REUSEADDR;
	if (!soap_valid_socket(soap_bind(serv, NULL, port, 1000)))
	{
		soap_print_fault(serv, stderr);
		exit(1);
	}
	ip_mreq mcast;
	mcast.imr_multiaddr.s_addr = inet_addr(host);
	mcast.imr_interface.s_addr = htonl(INADDR_ANY);
	if (setsockopt(serv->master, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mcast, sizeof(mcast))<0)
	{
		std::cout << "group membership failed:" << strerror(errno) << std::endl;
		exit(1);
	}

	sendHello();
	mainloop(serv);

	signal(SIGINT, &sighandler);
	while (!stop)
	{
		mainloop(serv);
	}

	sendBye();
	mainloop(serv);

	return 0;
}

void wsdd_event_ProbeMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ProbeMatchesType *matches)
{
}

void wsdd_event_ResolveMatches(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, struct wsdd__ResolveMatchType *match)
{
}

void wsdd_event_Hello(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int MetadataVersion)
{
	printf("wsdd_event_Hello\tid=%s EndpointReference=%s Types=%s Scopes=%s XAddrs=%s\n", MessageID, EndpointReference, Types, Scopes, XAddrs);
}

void wsdd_event_Bye(struct soap *soap, unsigned int InstanceId, const char *SequenceId, unsigned int MessageNumber, const char *MessageID, const char *RelatesTo, const char *EndpointReference, const char *Types, const char *Scopes, const char *MatchBy, const char *XAddrs, unsigned int *MetadataVersion)
{
	printf("wsdd_event_Bye\tid=%s EndpointReference=%s Types=%s Scopes=%s XAddrs=%s\n", MessageID, EndpointReference, Types, Scopes, XAddrs);
}

soap_wsdd_mode wsdd_event_Resolve(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *EndpointReference, struct wsdd__ResolveMatchType *match)
{
	printf("wsdd_event_Resolve\tid=%s replyTo=%s endpoint=%s\n", MessageID, ReplyTo, EndpointReference);
	if (EndpointReference && (strcmp(EndpointReference, _endpoint) == 0) )
	{
		soap_wsdd_ResolveMatches(soap, NULL, soap_wsa_rand_uuid(soap), MessageID, ReplyTo, _endpoint, _type, _scope, NULL, _xaddr, _metadataVersion);
	}
	return SOAP_WSDD_ADHOC;
}

soap_wsdd_mode wsdd_event_Probe(struct soap *soap, const char *MessageID, const char *ReplyTo, const char *Types, const char *Scopes, const char *MatchBy, struct wsdd__ProbeMatchesType *matches)
{
	printf("wsdd_event_Probe\tid=%s replyTo=%s types=%s scopes=%s\n", MessageID, ReplyTo, Types, Scopes);
	soap_wsdd_init_ProbeMatches(soap,matches);
	soap_wsdd_add_ProbeMatch(soap, matches, _endpoint, _type, _scope, NULL, _xaddr, _metadataVersion);
	soap_wsdd_ProbeMatches(soap, NULL, soap_wsa_rand_uuid(soap) , MessageID, ReplyTo, matches);
	return SOAP_WSDD_ADHOC;
}

<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    HoughTransform2DLinesImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif

// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{HoughTransform2DLinesImageFilter} to find straight lines in a
// 2-dimensional image.
//
// First, we include the header files of the filter.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkHoughTransform2DLinesImageFilter.h"
// Software Guide : EndCodeSnippet

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkThresholdImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include <itkGradientMagnitudeImageFilter.h>
#include <itkDiscreteGaussianImageFilter.h>
#include <list>
#include "itkCastImageFilter.h"

int main( int argc, char *argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0] << std::endl;
    std::cerr << " inputImage " << std::endl;
    std::cerr << " outputImage" << std::endl;
    std::cerr << " numberOfLines " << std::endl;
    std::cerr << " variance of the accumulator blurring (default = 5) " << std::endl;
    std::cerr << " radius of the disk to remove from the accumulator (default = 10) "<< std::endl;
    return 1;
    }

  //  Software Guide : BeginLatex
  //
  //  Next, we declare the pixel type and image dimension and specify the
  //  image type to be used as input. We also specify the image type of the
  //  accumulator used in the Houghtransform filter.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef   unsigned char   PixelType;
  typedef   float           AccumulatorPixelType;
  const     unsigned int    Dimension = 2;

  typedef itk::Image< PixelType, Dimension >  ImageType;
  typedef itk::Image< AccumulatorPixelType, Dimension > AccumulatorImageType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We setup a reader to load the input image.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  itk::ImageFileReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();

  reader->SetFileName( argv[1] );
  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
    }
  ImageType::Pointer localImage = reader->GetOutput();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Once the image is loaded, we apply a
  //  \doxygen{GradientMagnitudeImageFilter} to segment edges.  This casts
  //  the input image using a \doxygen{CastImageFilter}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::CastImageFilter< ImageType, AccumulatorImageType >
    CastingFilterType;
  CastingFilterType::Pointer caster = CastingFilterType::New();

  std::cout << "Applying gradient magnitude filter" << std::endl;

  typedef itk::GradientMagnitudeImageFilter<AccumulatorImageType,
               AccumulatorImageType > GradientFilterType;
  GradientFilterType::Pointer gradFilter =  GradientFilterType::New();

  caster->SetInput(localImage);
  gradFilter->SetInput(caster->GetOutput());
  gradFilter->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The next step is to apply a threshold filter on the gradient magnitude
  //  image to keep only bright values. Only pixels with a high value will be
  //  used by the Hough transform filter.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  std::cout << "Thresholding" << std::endl;
  typedef itk::ThresholdImageFilter<AccumulatorImageType> ThresholdFilterType;
  ThresholdFilterType::Pointer threshFilter = ThresholdFilterType::New();

  threshFilter->SetInput( gradFilter->GetOutput());
  threshFilter->SetOutsideValue(0);
  unsigned char threshBelow = 0;
  unsigned char threshAbove = 255;
  threshFilter->ThresholdOutside(threshBelow,threshAbove);
  threshFilter->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We create the HoughTransform2DLinesImageFilter based on the pixel type
  //  of the input image (the resulting image from the ThresholdImageFilter).
  //
  //  Software Guide : EndLatex
  // Software Guide : BeginCodeSnippet
  std::cout << "Computing Hough Map" << std::endl;
  typedef itk::HoughTransform2DLinesImageFilter<AccumulatorPixelType,
               AccumulatorPixelType>  HoughTransformFilterType;

  HoughTransformFilterType::Pointer houghFilter = HoughTransformFilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We set the input to the filter to be the output of the
  //  ThresholdImageFilter. We set also the number of lines we are looking
  //  for.  Basically, the filter computes the Hough map, blurs it using a
  //  certain variance and finds maxima in the Hough map. After a maximum is
  //  found, the local neighborhood, a circle, is removed from the Hough
  //  map. SetDiscRadius() defines the radius of this disc.
  //
  //  The output of the filter is the accumulator.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  houghFilter->SetInput(threshFilter->GetOutput());
  houghFilter->SetNumberOfLines(atoi(argv[3]));
  houghFilter->SetVariance(atof(argv[4]));
  houghFilter->SetDiscRadius(atof(argv[5]));
  houghFilter->Update();
  AccumulatorImageType::Pointer localAccumulator = houghFilter->GetOutput();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We can also get the lines as \doxygen{LineSpatialObject}. The
  //  \code{GetLines()} function return a list of those.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  HoughTransformFilterType::LinesListType lines;
  lines = houghFilter->GetLines(atoi(argv[3]));
  std::cout << "Found " << lines.size() << " line(s)." << std::endl;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We can then allocate an image to draw the resulting lines as binary
  //  objects.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  unsigned char    OutputPixelType;
  typedef  itk::Image< OutputPixelType, Dimension > OutputImageType;

  OutputImageType::Pointer  localOutputImage = OutputImageType::New();

  OutputImageType::RegionType region;
  region.SetSize(localImage->GetLargestPossibleRegion().GetSize());
  region.SetIndex(localImage->GetLargestPossibleRegion().GetIndex());
  localOutputImage->SetRegions( region );
  localOutputImage->SetOrigin(localImage->GetOrigin());
  localOutputImage->SetSpacing(localImage->GetSpacing());
  localOutputImage->Allocate();
  localOutputImage->FillBuffer(0);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We iterate through the list of lines and we draw them.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef HoughTransformFilterType::LinesListType::const_iterator LineIterator;
  LineIterator itLines = lines.begin();
  while( itLines != lines.end() )
    {
    // Software Guide : EndCodeSnippet

    //  Software Guide : BeginLatex
    //
    //  We get the list of points which consists of two points to represent a
    //  straight line.  Then, from these two points, we compute a fixed point
    //  $u$ and a unit vector $\vec{v}$ to parameterize the line.
    //
    //  Software Guide : EndLatex

    // Software Guide : BeginCodeSnippet
    typedef HoughTransformFilterType::LineType::PointListType  PointListType;

    PointListType                   pointsList = (*itLines)->GetPoints();
    PointListType::const_iterator   itPoints = pointsList.begin();

    double u[2];
    u[0] = (*itPoints).GetPosition()[0];
    u[1] = (*itPoints).GetPosition()[1];
    itPoints++;
    double v[2];
    v[0] = u[0]-(*itPoints).GetPosition()[0];
    v[1] = u[1]-(*itPoints).GetPosition()[1];

    double norm = sqrt(v[0]*v[0]+v[1]*v[1]);
    v[0] /= norm;
    v[1] /= norm;
    // Software Guide : EndCodeSnippet

    //  Software Guide : BeginLatex
    //
    //  We draw a white pixels in the output image to represent the line.
    //
    //  Software Guide : EndLatex

    // Software Guide : BeginCodeSnippet
    ImageType::IndexType localIndex;
    itk::Size<2> size = localOutputImage->GetLargestPossibleRegion().GetSize();
    float diag = sqrt((float)( size[0]*size[0] + size[1]*size[1] ));

    for(int i=static_cast<int>(-diag); i<static_cast<int>(diag); i++)
      {
      localIndex[0]=(long int)(u[0]+i*v[0]);
      localIndex[1]=(long int)(u[1]+i*v[1]);

      OutputImageType::RegionType region =
                          localOutputImage->GetLargestPossibleRegion();

      if( region.IsInside( localIndex ) )
        {
        localOutputImage->SetPixel( localIndex, 255 );
        }
      }
    itLines++;
    }
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We setup a writer to write out the binary image created.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( argv[2] );
  writer->SetInput( localOutputImage );

  try
    {
    writer->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
    }
  // Software Guide : EndCodeSnippet

  return 0;
}

<commit_msg>FIX: Optional parameters were not set by default<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    HoughTransform2DLinesImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif

// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{HoughTransform2DLinesImageFilter} to find straight lines in a
// 2-dimensional image.
//
// First, we include the header files of the filter.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkHoughTransform2DLinesImageFilter.h"
// Software Guide : EndCodeSnippet

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIterator.h"
#include "itkThresholdImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include <itkGradientMagnitudeImageFilter.h>
#include <itkDiscreteGaussianImageFilter.h>
#include <list>
#include "itkCastImageFilter.h"

int main( int argc, char *argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0] << std::endl;
    std::cerr << " inputImage " << std::endl;
    std::cerr << " outputImage" << std::endl;
    std::cerr << " numberOfLines " << std::endl;
    std::cerr << " variance of the accumulator blurring (default = 5) " << std::endl;
    std::cerr << " radius of the disk to remove from the accumulator (default = 10) "<< std::endl;
    return 1;
    }

  //  Software Guide : BeginLatex
  //
  //  Next, we declare the pixel type and image dimension and specify the
  //  image type to be used as input. We also specify the image type of the
  //  accumulator used in the Houghtransform filter.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef   unsigned char   PixelType;
  typedef   float           AccumulatorPixelType;
  const     unsigned int    Dimension = 2;

  typedef itk::Image< PixelType, Dimension >  ImageType;
  typedef itk::Image< AccumulatorPixelType, Dimension > AccumulatorImageType;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We setup a reader to load the input image.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  itk::ImageFileReader< ImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();

  reader->SetFileName( argv[1] );
  try
    {
    reader->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
    }
  ImageType::Pointer localImage = reader->GetOutput();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  Once the image is loaded, we apply a
  //  \doxygen{GradientMagnitudeImageFilter} to segment edges.  This casts
  //  the input image using a \doxygen{CastImageFilter}.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::CastImageFilter< ImageType, AccumulatorImageType >
    CastingFilterType;
  CastingFilterType::Pointer caster = CastingFilterType::New();

  std::cout << "Applying gradient magnitude filter" << std::endl;

  typedef itk::GradientMagnitudeImageFilter<AccumulatorImageType,
               AccumulatorImageType > GradientFilterType;
  GradientFilterType::Pointer gradFilter =  GradientFilterType::New();

  caster->SetInput(localImage);
  gradFilter->SetInput(caster->GetOutput());
  gradFilter->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  The next step is to apply a threshold filter on the gradient magnitude
  //  image to keep only bright values. Only pixels with a high value will be
  //  used by the Hough transform filter.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  std::cout << "Thresholding" << std::endl;
  typedef itk::ThresholdImageFilter<AccumulatorImageType> ThresholdFilterType;
  ThresholdFilterType::Pointer threshFilter = ThresholdFilterType::New();

  threshFilter->SetInput( gradFilter->GetOutput());
  threshFilter->SetOutsideValue(0);
  unsigned char threshBelow = 0;
  unsigned char threshAbove = 255;
  threshFilter->ThresholdOutside(threshBelow,threshAbove);
  threshFilter->Update();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We create the HoughTransform2DLinesImageFilter based on the pixel type
  //  of the input image (the resulting image from the ThresholdImageFilter).
  //
  //  Software Guide : EndLatex
  // Software Guide : BeginCodeSnippet
  std::cout << "Computing Hough Map" << std::endl;
  typedef itk::HoughTransform2DLinesImageFilter<AccumulatorPixelType,
               AccumulatorPixelType>  HoughTransformFilterType;

  HoughTransformFilterType::Pointer houghFilter = HoughTransformFilterType::New();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We set the input to the filter to be the output of the
  //  ThresholdImageFilter. We set also the number of lines we are looking
  //  for.  Basically, the filter computes the Hough map, blurs it using a
  //  certain variance and finds maxima in the Hough map. After a maximum is
  //  found, the local neighborhood, a circle, is removed from the Hough
  //  map. SetDiscRadius() defines the radius of this disc.
  //
  //  The output of the filter is the accumulator.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  houghFilter->SetInput(threshFilter->GetOutput());
  houghFilter->SetNumberOfLines(atoi(argv[3]));

  if(argc > 4 )
    {
    houghFilter->SetVariance(atof(argv[4]));
    }

  if(argc > 5 )
    {
    houghFilter->SetDiscRadius(atof(argv[5]));
    }
  houghFilter->Update();
  AccumulatorImageType::Pointer localAccumulator = houghFilter->GetOutput();
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We can also get the lines as \doxygen{LineSpatialObject}. The
  //  \code{GetLines()} function return a list of those.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  HoughTransformFilterType::LinesListType lines;
  lines = houghFilter->GetLines(atoi(argv[3]));
  std::cout << "Found " << lines.size() << " line(s)." << std::endl;
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We can then allocate an image to draw the resulting lines as binary
  //  objects.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  unsigned char    OutputPixelType;
  typedef  itk::Image< OutputPixelType, Dimension > OutputImageType;

  OutputImageType::Pointer  localOutputImage = OutputImageType::New();

  OutputImageType::RegionType region;
  region.SetSize(localImage->GetLargestPossibleRegion().GetSize());
  region.SetIndex(localImage->GetLargestPossibleRegion().GetIndex());
  localOutputImage->SetRegions( region );
  localOutputImage->SetOrigin(localImage->GetOrigin());
  localOutputImage->SetSpacing(localImage->GetSpacing());
  localOutputImage->Allocate();
  localOutputImage->FillBuffer(0);
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We iterate through the list of lines and we draw them.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef HoughTransformFilterType::LinesListType::const_iterator LineIterator;
  LineIterator itLines = lines.begin();
  while( itLines != lines.end() )
    {
    // Software Guide : EndCodeSnippet

    //  Software Guide : BeginLatex
    //
    //  We get the list of points which consists of two points to represent a
    //  straight line.  Then, from these two points, we compute a fixed point
    //  $u$ and a unit vector $\vec{v}$ to parameterize the line.
    //
    //  Software Guide : EndLatex

    // Software Guide : BeginCodeSnippet
    typedef HoughTransformFilterType::LineType::PointListType  PointListType;

    PointListType                   pointsList = (*itLines)->GetPoints();
    PointListType::const_iterator   itPoints = pointsList.begin();

    double u[2];
    u[0] = (*itPoints).GetPosition()[0];
    u[1] = (*itPoints).GetPosition()[1];
    itPoints++;
    double v[2];
    v[0] = u[0]-(*itPoints).GetPosition()[0];
    v[1] = u[1]-(*itPoints).GetPosition()[1];

    double norm = sqrt(v[0]*v[0]+v[1]*v[1]);
    v[0] /= norm;
    v[1] /= norm;
    // Software Guide : EndCodeSnippet

    //  Software Guide : BeginLatex
    //
    //  We draw a white pixels in the output image to represent the line.
    //
    //  Software Guide : EndLatex

    // Software Guide : BeginCodeSnippet
    ImageType::IndexType localIndex;
    itk::Size<2> size = localOutputImage->GetLargestPossibleRegion().GetSize();
    float diag = sqrt((float)( size[0]*size[0] + size[1]*size[1] ));

    for(int i=static_cast<int>(-diag); i<static_cast<int>(diag); i++)
      {
      localIndex[0]=(long int)(u[0]+i*v[0]);
      localIndex[1]=(long int)(u[1]+i*v[1]);

      OutputImageType::RegionType region =
                          localOutputImage->GetLargestPossibleRegion();

      if( region.IsInside( localIndex ) )
        {
        localOutputImage->SetPixel( localIndex, 255 );
        }
      }
    itLines++;
    }
  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  //
  //  We setup a writer to write out the binary image created.
  //
  //  Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef  itk::ImageFileWriter<  OutputImageType  > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( argv[2] );
  writer->SetInput( localOutputImage );

  try
    {
    writer->Update();
    }
  catch( itk::ExceptionObject & excep )
    {
    std::cerr << "Exception caught !" << std::endl;
    std::cerr << excep << std::endl;
    }
  // Software Guide : EndCodeSnippet

  return 0;
}

<|endoftext|>


<commit_before>#pragma once
#include "MPLTypes.hpp"
#include "MPLUtility.hpp"

namespace Kvasir {

	namespace Register{
		template<typename TAddress, typename TClearBits, typename TSetBits>
		struct Option {
			using Type = Option<TAddress,TClearBits,TSetBits>;
		};
		template<int Address,int Clear, int Set>
		using OptionT = Option<MPL::Int<Address>,MPL::Int<Clear>,MPL::Int<Set>>;

		namespace Detail{
			using namespace MPL;
			//predecate retuning result of left < right for RegisterOptions
			template<typename T_Left, typename T_Right>
			struct RegisterOptionLess;
			template<typename TA1, typename TC1, typename TS1, typename TA2, typename TC2, typename TS2>
			struct RegisterOptionLess< Register::Option<TA1,TC1,TS1>, Register::Option<TA2,TC2,TS2> > : Bool<(TA1::value < TA2::value)>{};
			using RegisterOptionLessP = Template<RegisterOptionLess>;

			template<typename TRegisterOption>
			struct WriteRegister;

			template<int A, int S, int C>
			struct WriteRegister<Register::Option<Int<A>,Int<S>,Int<C>>>{
				int operator()(){
					auto i = *(volatile int*)A;
					i |= S;
					i &= ~C;
					*(volatile int*)A = i;
					return 0;
				}
			};

			template<typename TRegisters>
			struct WriteRegisters;

			template<typename... Ts>
			struct WriteRegisters<List<Ts...>>{
				void operator()(){
					int a[] = {WriteRegister<Ts>{}()...};
				}
			};

			template<typename TRegisters, typename TRet = List<>> //default
			struct MergeRegisterOptions;

			template<typename TNext, typename... Ts> //none processed yet
			struct MergeRegisterOptions<List<TNext, Ts...>, List<>> : MergeRegisterOptions<List<Ts...>,List<TNext>>{};

			template<typename TNA, typename TNC, typename TNS, typename TLC, typename TLS, typename... Ts, typename... Us> //next and last mergable
			struct MergeRegisterOptions<List<Register::Option<TNA,TNC,TNS>, Ts...>,List<Register::Option<TNA,TLC,TLS>, Us...>> :
				MergeRegisterOptions<List<Ts...>,List<Register::Option<TNA,Int<TNC::value | TLC::value>,Int<TNS::value | TLS::value>>,Us...>>{};

			template<typename TNext, typename TLast, typename... Ts, typename... Us> //next and last not mergable
			struct MergeRegisterOptions<List<TNext, Ts...>,List<TLast, Us...>> : MergeRegisterOptions<List<Ts...>,List<TNext, TLast, Us...>>{};

			template<typename... Ts> //done
			struct MergeRegisterOptions<List<>,List<Ts...>> : List<Ts...>{};

		}

		namespace Policy{
			template<typename T_Type, typename T_RegisterType>
			struct GenericConversion {
				using Type = T_Type;
				using RegisterType = T_RegisterType;
				static inline Type read(const T_RegisterType& in){
					return static_cast<Type>(in);
				}
				static inline RegisterType write(const Type &in){
					return static_cast<RegisterType>(in);
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct Readable {
				static inline typename T_ConversionPolicy::Type read(){
					auto v = *static_cast<volatile typename T_ConversionPolicy::RegisterType*>((int*)T_Address::value);
					return T_ConversionPolicy::read(v & T_Mask::value);
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct ClearOnRead{
				static inline typename T_ConversionPolicy::Type readAndClear(){
					auto v = *static_cast<volatile typename T_ConversionPolicy::RegisterType*>((int*)T_Address::value);
					return T_ConversionPolicy::read(v & T_Mask::value);
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct Popable{
				static inline typename T_ConversionPolicy::Type pop(){
					auto v = *static_cast<volatile typename T_ConversionPolicy::RegisterType*>((int*)T_Address::value);
					return T_ConversionPolicy::read(v & T_Mask::value);
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct Writeable{
				static inline void write(typename T_ConversionPolicy::Type in){
					auto maskedIn = T_ConversionPolicy::write(in) & T_Mask::value;
					volatile typename T_ConversionPolicy::RegisterType &reg = *(typename T_ConversionPolicy::RegisterType*)T_Address::value;
					auto tempReg = reg;
					tempReg = tempReg & (!T_Mask::value) | maskedIn;
					reg = tempReg;
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct Pushable{
				static inline void push(typename T_ConversionPolicy::Type in){
					volatile typename T_ConversionPolicy::RegisterType &reg = *(typename T_ConversionPolicy::RegisterType*)T_Address::value;
					reg = T_ConversionPolicy::write(in) & T_Mask::value;
				}
			};
			template<typename TEnum>
			using EnumConversionP = GenericConversion<TEnum,int>;
			using IntConversionP = GenericConversion<int,int>;
			using CharConversionP = GenericConversion<char,char>;
			using ReadableP = MPL::Template<Readable>;
			using ClearOnReadP = MPL::Template<ClearOnRead>;
			using PopableP = MPL::Template<Popable>;
			using WriteableP = MPL::Template<Writeable>;
			using PushableP = MPL::Template<Pushable>;

		}

		//this class is used to define multi-step inits, each parameter is an MPL::List of Register::Option(s)
		template<typename... Ts>
		struct InitSteps{};

		template<typename...Ts>
		inline void apply(){
			using FlattenedRegisters = MPL::FlattenT<MPL::List<Ts...>>;
			using SortedRegisters = MPL::SortT<MPL::List<Ts...>,Detail::RegisterOptionLessP>;

			Detail::WriteRegisters<MergedRegisters>{}();
		}

		template<typename...Ts>		//this version may take more time to compile, however it may be easier to understand for some users
		inline void apply(Ts...){
			apply<Ts...>();
		}

		template<typename TAddress, typename TMask, typename TPolicies, typename TConversionPolicy = Policy::IntConversionP>
		struct Single : MPL::TemplateT<TPolicies,TAddress,TMask,TConversionPolicy> {}; //only one policy so derive directly

		template<typename TAddress, typename TMask, typename... Ts, typename TConversionPolicy>
		struct Single<TAddress,TMask,MPL::List<Ts...>,TConversionPolicy> : MPL::DeriveFromTemplates<MPL::List<Ts...>,TAddress,TMask,TConversionPolicy>{};

		namespace Detail {
			//Merges single and multistep inits
			template<typename T_Out, typename... Ts>
			struct MergeInits;

			template<typename TList>
			struct ApplyInits;

			template<typename...Ts>
			struct ApplyInts {
				void operator()(){
					auto a = {apply<Ts>()...};
				}
			};
		}

		template<typename... Ts>
		inline void applyInits(){
			using MergedInits = typename Detail::MergeInits<MPL::List<>,Ts...>::Type;
			Detail::ApplyInits<MergedInits>{}();
		}
	}
}
<commit_msg>bugfix<commit_after>#pragma once
#include "MPLTypes.hpp"
#include "MPLUtility.hpp"

namespace Kvasir {

	namespace Register{
		template<typename TAddress, typename TClearBits, typename TSetBits>
		struct Option {
			using Type = Option<TAddress,TClearBits,TSetBits>;
		};
		template<int Address,int Clear, int Set>
		using OptionT = Option<MPL::Int<Address>,MPL::Int<Clear>,MPL::Int<Set>>;

		namespace Detail{
			using namespace MPL;
			//predecate retuning result of left < right for RegisterOptions
			template<typename T_Left, typename T_Right>
			struct RegisterOptionLess;
			template<typename TA1, typename TC1, typename TS1, typename TA2, typename TC2, typename TS2>
			struct RegisterOptionLess< Register::Option<TA1,TC1,TS1>, Register::Option<TA2,TC2,TS2> > : Bool<(TA1::value < TA2::value)>{};
			using RegisterOptionLessP = Template<RegisterOptionLess>;

			template<typename TRegisterOption>
			struct WriteRegister;

			template<int A, int S, int C>
			struct WriteRegister<Register::Option<Int<A>,Int<S>,Int<C>>>{
				int operator()(){
					auto i = *(volatile int*)A;
					i |= S;
					i &= ~C;
					*(volatile int*)A = i;
					return 0;
				}
			};

			template<typename TRegisters>
			struct WriteRegisters;

			template<typename... Ts>
			struct WriteRegisters<List<Ts...>>{
				void operator()(){
					int a[] = {WriteRegister<Ts>{}()...};
				}
			};

			template<typename TRegisters, typename TRet = List<>> //default
			struct MergeRegisterOptions;

			template<typename TNext, typename... Ts> //none processed yet
			struct MergeRegisterOptions<List<TNext, Ts...>, List<>> : MergeRegisterOptions<List<Ts...>,List<TNext>>{};

			template<typename TNA, typename TNC, typename TNS, typename TLC, typename TLS, typename... Ts, typename... Us> //next and last mergable
			struct MergeRegisterOptions<List<Register::Option<TNA,TNC,TNS>, Ts...>,List<Register::Option<TNA,TLC,TLS>, Us...>> :
				MergeRegisterOptions<List<Ts...>,List<Register::Option<TNA,Int<TNC::value | TLC::value>,Int<TNS::value | TLS::value>>,Us...>>{};

			template<typename TNext, typename TLast, typename... Ts, typename... Us> //next and last not mergable
			struct MergeRegisterOptions<List<TNext, Ts...>,List<TLast, Us...>> : MergeRegisterOptions<List<Ts...>,List<TNext, TLast, Us...>>{};

			template<typename... Ts> //done
			struct MergeRegisterOptions<List<>,List<Ts...>> : List<Ts...>{};

		}

		namespace Policy{
			template<typename T_Type, typename T_RegisterType>
			struct GenericConversion {
				using Type = T_Type;
				using RegisterType = T_RegisterType;
				static inline Type read(const T_RegisterType& in){
					return static_cast<Type>(in);
				}
				static inline RegisterType write(const Type &in){
					return static_cast<RegisterType>(in);
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct Readable {
				static inline typename T_ConversionPolicy::Type read(){
					auto v = *static_cast<volatile typename T_ConversionPolicy::RegisterType*>((int*)T_Address::value);
					return T_ConversionPolicy::read(v & T_Mask::value);
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct ClearOnRead{
				static inline typename T_ConversionPolicy::Type readAndClear(){
					auto v = *static_cast<volatile typename T_ConversionPolicy::RegisterType*>((int*)T_Address::value);
					return T_ConversionPolicy::read(v & T_Mask::value);
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct Popable{
				static inline typename T_ConversionPolicy::Type pop(){
					auto v = *static_cast<volatile typename T_ConversionPolicy::RegisterType*>((int*)T_Address::value);
					return T_ConversionPolicy::read(v & T_Mask::value);
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct Writeable{
				static inline void write(typename T_ConversionPolicy::Type in){
					auto maskedIn = T_ConversionPolicy::write(in) & T_Mask::value;
					volatile typename T_ConversionPolicy::RegisterType &reg = *(typename T_ConversionPolicy::RegisterType*)T_Address::value;
					auto tempReg = reg;
					tempReg = tempReg & (!T_Mask::value) | maskedIn;
					reg = tempReg;
				}
			};
			template<typename T_Address, typename T_Mask, typename T_ConversionPolicy>
			struct Pushable{
				static inline void push(typename T_ConversionPolicy::Type in){
					volatile typename T_ConversionPolicy::RegisterType &reg = *(typename T_ConversionPolicy::RegisterType*)T_Address::value;
					reg = T_ConversionPolicy::write(in) & T_Mask::value;
				}
			};
			template<typename TEnum>
			using EnumConversionP = GenericConversion<TEnum,int>;
			using IntConversionP = GenericConversion<int,int>;
			using CharConversionP = GenericConversion<char,char>;
			using ReadableP = MPL::Template<Readable>;
			using ClearOnReadP = MPL::Template<ClearOnRead>;
			using PopableP = MPL::Template<Popable>;
			using WriteableP = MPL::Template<Writeable>;
			using PushableP = MPL::Template<Pushable>;

		}

		//this class is used to define multi-step inits, each parameter is an MPL::List of Register::Option(s)
		template<typename... Ts>
		struct InitSteps{};

		template<typename...Ts>
		inline void apply(){
			using FlattenedRegisters = MPL::FlattenT<MPL::List<Ts...>>;
			using SortedRegisters = MPL::SortT<MPL::List<Ts...>,Detail::RegisterOptionLessP>;
			using MergedRegisters = typename Detail::MergeRegisterOptions<SortedRegisters>::Type;
			Detail::WriteRegisters<MergedRegisters>{}();
		}

		template<typename...Ts>		//this version may take more time to compile, however it may be easier to understand for some users
		inline void apply(Ts...){
			apply<Ts...>();
		}

		template<typename TAddress, typename TMask, typename TPolicies, typename TConversionPolicy = Policy::IntConversionP>
		struct Single : MPL::TemplateT<TPolicies,TAddress,TMask,TConversionPolicy> {}; //only one policy so derive directly

		template<typename TAddress, typename TMask, typename... Ts, typename TConversionPolicy>
		struct Single<TAddress,TMask,MPL::List<Ts...>,TConversionPolicy> : MPL::DeriveFromTemplates<MPL::List<Ts...>,TAddress,TMask,TConversionPolicy>{};

		namespace Detail {
			//Merges single and multistep inits
			template<typename T_Out, typename... Ts>
			struct MergeInits;

			template<typename TList>
			struct ApplyInits;

			template<typename...Ts>
			struct ApplyInts {
				void operator()(){
					auto a = {apply<Ts>()...};
				}
			};
		}

		template<typename... Ts>
		inline void applyInits(){
			using MergedInits = typename Detail::MergeInits<MPL::List<>,Ts...>::Type;
			Detail::ApplyInits<MergedInits>{}();
		}
	}
}
<|endoftext|>


<commit_before>/*
* This file is part of the Gluon project.
* Copyright (C) 2007 Laurent Gomila <laurent.gom@gmail.com>
* Copyright (C) 2009 Sacha Schutz <istdasklar@free.fr>
* Copyright (C) 2009 Guillaume Martres <smarter@ubuntu.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING.  If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/

#include "kalengine.h"

#include "kalphonon.h"

#include <QtCore/QtGlobal>

#ifdef Q_WS_X11
#include <AL/al.h>
#include <AL/alc.h>
#endif
#ifdef Q_WS_MAC
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#endif

//#include <QtCore/QCoreApplication>
//#include <alut.h>

template<> KALEngine *KSingleton<KALEngine>::m_instance = 0;

//KALEngine::KALEngine(const QString &deviceName, QObject *parent)
//    : QObject(parent)
KALEngine::KALEngine()
{
    //alutInitWithoutContext(0, 0);

    m_context = NULL;
    m_device = NULL;

    /*if (setDevice(deviceName)) {
        if (deviceName.isEmpty()) {
            qDebug() << "set device to default";
        } else {
            qDebug() << "set device to " << deviceName;
        }
    } else {
        qDebug() << "cannot set openAL device...";
    }*/
    setDevice("default");

    qDebug() << alGetError();
}

/*KALEngine::KALEngine(Phonon::Category category, QObject *parent)
{
    m_phonon = new KALPhonon(this);
    m_phonon->setCategory(category);
}*/

KALEngine::~KALEngine()
{
    alcMakeContextCurrent(NULL);
    alcDestroyContext(m_context);
    alcCloseDevice(m_device);
}

// TODO: factor the getInstance or remove one of them
/*KALEngine *KALEngine::instance(const QString &deviceName)
{
    if (!m_instance) {
        QObject *parent = QCoreApplication::instance();
        if (!parent) {
            qWarning() << "No QCoreApplication instance found, the KALEngine instance may be leaked when leaving";
        }
        m_instance =  new KALEngine(deviceName, parent);
    }
    return m_instance;
}

KALEngine *KALEngine::instance(Phonon::Category category)
{
    if (!m_instance) {
        QObject *parent = QCoreApplication::instance();
        if (!parent) {
            qWarning() << "No QCoreApplication instance found, the KALEngine instance may be leaked when leaving";
        }
        m_instance =  new KALEngine(category, parent);
    }
    return m_instance;
}*/

QStringList KALEngine::deviceList()
{
    const ALCchar* devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER);

    // alcGetString returns a list of devices separated by a null char (the list itself ends with a double null char)
    // So we can't pass it directly to QStringList
    QStringList deviceStringList;
    if (devices) {
        while (strlen(devices) > 0) {
            deviceStringList << QString(devices);
            devices += strlen(devices) + 1;
        }
    }
    return deviceStringList;
}

bool KALEngine::setDevice(const QString &deviceName)
{
    if (m_device) {
        alcMakeContextCurrent(NULL);
        alcDestroyContext(m_context);
        alcCloseDevice(m_device);
    }

    if (!deviceName.isEmpty()) {
        m_device = alcOpenDevice(deviceName.toUtf8());
    } else {
        m_device = alcOpenDevice(0);
    }

    if (!m_device) {
        return false;
    }

    m_context = alcCreateContext(m_device, 0);

    if (!m_context) {
        return false;
    }

    if (!alcMakeContextCurrent(m_context)) {
        return false;
    }

    return true;
}

bool KALEngine::isExtensionSupported(const QString &name)
{
  if (alcIsExtensionPresent(instance()->device(), name.toUtf8()) == ALC_TRUE)
      return true;
  else return false;

}
<commit_msg>KAL: use setDevice("") instead of setDevice("default") since the latter can't work, KAL should now be working again.<commit_after>/*
* This file is part of the Gluon project.
* Copyright (C) 2007 Laurent Gomila <laurent.gom@gmail.com>
* Copyright (C) 2009 Sacha Schutz <istdasklar@free.fr>
* Copyright (C) 2009 Guillaume Martres <smarter@ubuntu.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING.  If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/

#include "kalengine.h"

#include "kalphonon.h"

#include <QtCore/QtGlobal>

#ifdef Q_WS_X11
#include <AL/al.h>
#include <AL/alc.h>
#endif
#ifdef Q_WS_MAC
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#endif

//#include <QtCore/QCoreApplication>
//#include <alut.h>

template<> KALEngine *KSingleton<KALEngine>::m_instance = 0;

//KALEngine::KALEngine(const QString &deviceName, QObject *parent)
//    : QObject(parent)
KALEngine::KALEngine()
{
    //alutInitWithoutContext(0, 0);

    m_context = NULL;
    m_device = NULL;

    /*if (setDevice(deviceName)) {
        if (deviceName.isEmpty()) {
            qDebug() << "set device to default";
        } else {
            qDebug() << "set device to " << deviceName;
        }
    } else {
        qDebug() << "cannot set openAL device...";
    }*/
    setDevice("");

    qDebug() << alGetError();
}

/*KALEngine::KALEngine(Phonon::Category category, QObject *parent)
{
    m_phonon = new KALPhonon(this);
    m_phonon->setCategory(category);
}*/

KALEngine::~KALEngine()
{
    alcMakeContextCurrent(NULL);
    alcDestroyContext(m_context);
    alcCloseDevice(m_device);
}

// TODO: factor the getInstance or remove one of them
/*KALEngine *KALEngine::instance(const QString &deviceName)
{
    if (!m_instance) {
        QObject *parent = QCoreApplication::instance();
        if (!parent) {
            qWarning() << "No QCoreApplication instance found, the KALEngine instance may be leaked when leaving";
        }
        m_instance =  new KALEngine(deviceName, parent);
    }
    return m_instance;
}

KALEngine *KALEngine::instance(Phonon::Category category)
{
    if (!m_instance) {
        QObject *parent = QCoreApplication::instance();
        if (!parent) {
            qWarning() << "No QCoreApplication instance found, the KALEngine instance may be leaked when leaving";
        }
        m_instance =  new KALEngine(category, parent);
    }
    return m_instance;
}*/

QStringList KALEngine::deviceList()
{
    const ALCchar* devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER);

    // alcGetString returns a list of devices separated by a null char (the list itself ends with a double null char)
    // So we can't pass it directly to QStringList
    QStringList deviceStringList;
    if (devices) {
        while (strlen(devices) > 0) {
            deviceStringList << QString(devices);
            devices += strlen(devices) + 1;
        }
    }
    return deviceStringList;
}

bool KALEngine::setDevice(const QString &deviceName)
{
    if (m_device) {
        alcMakeContextCurrent(NULL);
        alcDestroyContext(m_context);
        alcCloseDevice(m_device);
    }

    if (!deviceName.isEmpty()) {
        m_device = alcOpenDevice(deviceName.toUtf8());
    } else {
        m_device = alcOpenDevice(0);
    }

    if (!m_device) {
        return false;
    }

    m_context = alcCreateContext(m_device, 0);

    if (!m_context) {
        return false;
    }

    if (!alcMakeContextCurrent(m_context)) {
        return false;
    }

    return true;
}

bool KALEngine::isExtensionSupported(const QString &name)
{
  if (alcIsExtensionPresent(instance()->device(), name.toUtf8()) == ALC_TRUE)
      return true;
  else return false;

}
<|endoftext|>