<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "subprocess.h"

#include <stdio.h>

#include <algorithm>

#include "util.h"

namespace {

void Win32Fatal(const char* function) {
  Fatal("%s: %s", function, GetLastErrorString().c_str());
}

}  // anonymous namespace

Subprocess::Subprocess() : child_(NULL) , overlapped_() {
}

Subprocess::~Subprocess() {
  // Reap child if forgotten.
  if (child_)
    Finish();
}

HANDLE Subprocess::SetupPipe(HANDLE ioport) {
  char pipe_name[100];
  snprintf(pipe_name, sizeof(pipe_name),
           "\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this);

  pipe_ = ::CreateNamedPipeA(pipe_name,
                             PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
                             PIPE_TYPE_BYTE,
                             PIPE_UNLIMITED_INSTANCES,
                             0, 0, INFINITE, NULL);
  if (pipe_ == INVALID_HANDLE_VALUE)
    Win32Fatal("CreateNamedPipe");

  if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0))
    Win32Fatal("CreateIoCompletionPort");

  memset(&overlapped_, 0, sizeof(overlapped_));
  if (!ConnectNamedPipe(pipe_, &overlapped_) &&
      GetLastError() != ERROR_IO_PENDING) {
    Win32Fatal("ConnectNamedPipe");
  }

  // Get the write end of the pipe as a handle inheritable across processes.
  HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0,
                                          NULL, OPEN_EXISTING, 0, NULL);
  HANDLE output_write_child;
  if (!DuplicateHandle(GetCurrentProcess(), output_write_handle,
                       GetCurrentProcess(), &output_write_child,
                       0, TRUE, DUPLICATE_SAME_ACCESS)) {
    Win32Fatal("DuplicateHandle");
  }
  CloseHandle(output_write_handle);

  return output_write_child;
}

bool Subprocess::Start(SubprocessSet* set, const string& command) {
  HANDLE child_pipe = SetupPipe(set->ioport_);

  STARTUPINFOA startup_info;
  memset(&startup_info, 0, sizeof(startup_info));
  startup_info.cb = sizeof(STARTUPINFO);
  startup_info.dwFlags = STARTF_USESTDHANDLES;
  startup_info.hStdOutput = child_pipe;
  // TODO: what does this hook up stdin to?
  startup_info.hStdInput  = NULL;
  // TODO: is it ok to reuse pipe like this?
  startup_info.hStdError  = child_pipe;

  PROCESS_INFORMATION process_info;
  memset(&process_info, 0, sizeof(process_info));

  // Do not prepend 'cmd /c' on Windows, this breaks command
  // lines greater than 8,191 chars.
  if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
                      /* inherit handles */ TRUE, 0,
                      NULL, NULL,
                      &startup_info, &process_info)) {
    Win32Fatal("CreateProcess");
  }

  // Close pipe channel only used by the child.
  if (child_pipe)
    CloseHandle(child_pipe);

  CloseHandle(process_info.hThread);
  child_ = process_info.hProcess;

  return true;
}

void Subprocess::OnPipeReady() {
  DWORD bytes;
  if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) {
    if (GetLastError() == ERROR_BROKEN_PIPE) {
      CloseHandle(pipe_);
      pipe_ = NULL;
      return;
    }
    Win32Fatal("GetOverlappedResult");
  }

  if (bytes)
    buf_.append(overlapped_buf_, bytes);

  memset(&overlapped_, 0, sizeof(overlapped_));
  if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_),
                  &bytes, &overlapped_)) {
    if (GetLastError() == ERROR_BROKEN_PIPE) {
      CloseHandle(pipe_);
      pipe_ = NULL;
      return;
    }
    if (GetLastError() != ERROR_IO_PENDING)
      Win32Fatal("ReadFile");
  }

  // Even if we read any bytes in the readfile call, we'll enter this
  // function again later and get them at that point.
}

bool Subprocess::Finish() {
  // TODO: add error handling for all of these.
  WaitForSingleObject(child_, INFINITE);

  DWORD exit_code = 0;
  GetExitCodeProcess(child_, &exit_code);

  CloseHandle(child_);
  child_ = NULL;

  return exit_code == 0;
}

bool Subprocess::Done() const {
  return pipe_ == NULL;
}

const string& Subprocess::GetOutput() const {
  return buf_;
}

SubprocessSet::SubprocessSet() {
  ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
  if (!ioport_)
    Win32Fatal("CreateIoCompletionPort");
}

SubprocessSet::~SubprocessSet() {
  CloseHandle(ioport_);
}

void SubprocessSet::Add(Subprocess* subprocess) {
  running_.push_back(subprocess);
}

void SubprocessSet::DoWork() {
  DWORD bytes_read;
  Subprocess* subproc;
  OVERLAPPED* overlapped;

  if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc,
                                 &overlapped, INFINITE)) {
    if (GetLastError() != ERROR_BROKEN_PIPE)
      Win32Fatal("GetQueuedCompletionStatus");
  }

  subproc->OnPipeReady();

  if (subproc->Done()) {
    vector<Subprocess*>::iterator end =
        std::remove(running_.begin(), running_.end(), subproc);
    if (running_.end() != end) {
      finished_.push(subproc);
      running_.resize(end - running_.begin());
    }
  }
}

Subprocess* SubprocessSet::NextFinished() {
  if (finished_.empty())
    return NULL;
  Subprocess* subproc = finished_.front();
  finished_.pop();
  return subproc;
}
<commit_msg>Mark CreateProcess "program not found" failure as non-fatal<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "subprocess.h"

#include <stdio.h>

#include <algorithm>

#include "util.h"

namespace {

void Win32Fatal(const char* function) {
  Fatal("%s: %s", function, GetLastErrorString().c_str());
}

}  // anonymous namespace

Subprocess::Subprocess() : child_(NULL) , overlapped_() {
}

Subprocess::~Subprocess() {
  // Reap child if forgotten.
  if (child_)
    Finish();
}

HANDLE Subprocess::SetupPipe(HANDLE ioport) {
  char pipe_name[100];
  snprintf(pipe_name, sizeof(pipe_name),
           "\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this);

  pipe_ = ::CreateNamedPipeA(pipe_name,
                             PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
                             PIPE_TYPE_BYTE,
                             PIPE_UNLIMITED_INSTANCES,
                             0, 0, INFINITE, NULL);
  if (pipe_ == INVALID_HANDLE_VALUE)
    Win32Fatal("CreateNamedPipe");

  if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0))
    Win32Fatal("CreateIoCompletionPort");

  memset(&overlapped_, 0, sizeof(overlapped_));
  if (!ConnectNamedPipe(pipe_, &overlapped_) &&
      GetLastError() != ERROR_IO_PENDING) {
    Win32Fatal("ConnectNamedPipe");
  }

  // Get the write end of the pipe as a handle inheritable across processes.
  HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0,
                                          NULL, OPEN_EXISTING, 0, NULL);
  HANDLE output_write_child;
  if (!DuplicateHandle(GetCurrentProcess(), output_write_handle,
                       GetCurrentProcess(), &output_write_child,
                       0, TRUE, DUPLICATE_SAME_ACCESS)) {
    Win32Fatal("DuplicateHandle");
  }
  CloseHandle(output_write_handle);

  return output_write_child;
}

bool Subprocess::Start(SubprocessSet* set, const string& command) {
  HANDLE child_pipe = SetupPipe(set->ioport_);

  STARTUPINFOA startup_info;
  memset(&startup_info, 0, sizeof(startup_info));
  startup_info.cb = sizeof(STARTUPINFO);
  startup_info.dwFlags = STARTF_USESTDHANDLES;
  startup_info.hStdOutput = child_pipe;
  // TODO: what does this hook up stdin to?
  startup_info.hStdInput  = NULL;
  // TODO: is it ok to reuse pipe like this?
  startup_info.hStdError  = child_pipe;

  PROCESS_INFORMATION process_info;
  memset(&process_info, 0, sizeof(process_info));

  // Do not prepend 'cmd /c' on Windows, this breaks command
  // lines greater than 8,191 chars.
  if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
                      /* inherit handles */ TRUE, 0,
                      NULL, NULL,
                      &startup_info, &process_info)) {
    DWORD error = GetLastError();
    if (error == ERROR_FILE_NOT_FOUND) { // file (program) not found error is treated as a normal build action failure
      if (child_pipe)
        CloseHandle(child_pipe);
      CloseHandle(pipe_);
      pipe_ = NULL;
      // child_ is already NULL;
      buf_ = "CreateProcess failed: The system cannot find the file specified.\n";
      return true;
    } else {
      Win32Fatal("CreateProcess");    // pass all other errors to Win32Fatal
    }
  }

  // Close pipe channel only used by the child.
  if (child_pipe)
    CloseHandle(child_pipe);

  CloseHandle(process_info.hThread);
  child_ = process_info.hProcess;

  return true;
}

void Subprocess::OnPipeReady() {
  DWORD bytes;
  if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) {
    if (GetLastError() == ERROR_BROKEN_PIPE) {
      CloseHandle(pipe_);
      pipe_ = NULL;
      return;
    }
    Win32Fatal("GetOverlappedResult");
  }

  if (bytes)
    buf_.append(overlapped_buf_, bytes);

  memset(&overlapped_, 0, sizeof(overlapped_));
  if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_),
                  &bytes, &overlapped_)) {
    if (GetLastError() == ERROR_BROKEN_PIPE) {
      CloseHandle(pipe_);
      pipe_ = NULL;
      return;
    }
    if (GetLastError() != ERROR_IO_PENDING)
      Win32Fatal("ReadFile");
  }

  // Even if we read any bytes in the readfile call, we'll enter this
  // function again later and get them at that point.
}

bool Subprocess::Finish() {
  if (! child_) {
    return false;
  }

  // TODO: add error handling for all of these.
  WaitForSingleObject(child_, INFINITE);

  DWORD exit_code = 0;
  GetExitCodeProcess(child_, &exit_code);

  CloseHandle(child_);
  child_ = NULL;

  return exit_code == 0;
}

bool Subprocess::Done() const {
  return pipe_ == NULL;
}

const string& Subprocess::GetOutput() const {
  return buf_;
}

SubprocessSet::SubprocessSet() {
  ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
  if (!ioport_)
    Win32Fatal("CreateIoCompletionPort");
}

SubprocessSet::~SubprocessSet() {
  CloseHandle(ioport_);
}

void SubprocessSet::Add(Subprocess* subprocess) {
  if (subprocess->child_)
    running_.push_back(subprocess);
  else
    finished_.push(subprocess);
}

void SubprocessSet::DoWork() {
  DWORD bytes_read;
  Subprocess* subproc;
  OVERLAPPED* overlapped;

  if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc,
                                 &overlapped, INFINITE)) {
    if (GetLastError() != ERROR_BROKEN_PIPE)
      Win32Fatal("GetQueuedCompletionStatus");
  }

  subproc->OnPipeReady();

  if (subproc->Done()) {
    vector<Subprocess*>::iterator end =
        std::remove(running_.begin(), running_.end(), subproc);
    if (running_.end() != end) {
      finished_.push(subproc);
      running_.resize(end - running_.begin());
    }
  }
}

Subprocess* SubprocessSet::NextFinished() {
  if (finished_.empty())
    return NULL;
  Subprocess* subproc = finished_.front();
  finished_.pop();
  return subproc;
}
<|endoftext|>


<commit_before>/* Copyright 2007-2015 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "paletteTree.h"

#include <QtCore/QUuid>
#include <QtGui/QMouseEvent>
#include <QtCore/QtAlgorithms>
#include <QtWidgets/QVBoxLayout>
#include <QtGui/QDrag>

#include <qrkernel/settingsManager.h>
#include <qrkernel/definitions.h>
#include <qrkernel/settingsManager.h>
#include <qrutils/widgets/searchLineEdit.h>

#include "mainWindow/palette/draggableElement.h"
#include "dialogs/metamodelingOnFly/propertiesDialog.h"

using namespace qReal;
using namespace gui;

PaletteTree::PaletteTree(QWidget *parent)
	: QWidget(parent)
	, mTree(nullptr)
	, mCurrentEditor(0)
{
	initUi();
}

void PaletteTree::initUi()
{
	mLayout = new QVBoxLayout(this);
	mLayout->setSpacing(0);
	QHBoxLayout * const controlButtonsLayout = new QHBoxLayout;
	controlButtonsLayout->setSpacing(0);

	mComboBox = new QComboBox;
	mComboBox->setGeometry(0, 0, 300, 50);
	mLayout->addWidget(mComboBox);
	mLayout->addLayout(controlButtonsLayout);

	ui::SearchLineEdit * const searchField = new ui::SearchLineEdit(this);
	connect(searchField, &ui::SearchLineEdit::textChanged, this, &PaletteTree::onSearchTextChanged);
	mLayout->addWidget(searchField);
	mSearchLineEdit = searchField;

	setMinimumSize(200, 100);
}

void PaletteTree::expand()
{
	mTree->expand();
}

void PaletteTree::collapse()
{
	mTree->collapse();
}

void PaletteTree::setActiveEditor(int index)
{
	if (0 <= index && index < mEditorsTrees.count()) {
		mCurrentEditor = index;
		if (mTree) {
			mTree->hide();
		}

		mTree = mEditorsTrees[index];
		mTree->show();
	}
}

void PaletteTree::setActiveEditor(const Id &id)
{
	setActiveEditor(mCategories.value(id, 0));
}

void PaletteTree::addEditorElements(EditorManagerInterface &editorManagerProxy, const Id &editor, const Id &diagram)
{
	mEditorManager = &editorManagerProxy;
	mEditorsNames.push_back(mEditorManager->friendlyName(diagram));

	mCategories[diagram] = mEditorsTrees.size();

	mComboBox->addItem(mEditorManager->friendlyName(diagram));

	PaletteTreeWidgets *editorTree = new PaletteTreeWidgets(*this, mMainWindow, *mEditorManager, editor, diagram);
	editorTree->hide();

	mEditorsTrees.push_back(editorTree);
	mLayout->addWidget(editorTree);
}

void PaletteTree::initDone()
{
	if (mComboBox->count() == 1) {
		// In case of empty combobox we do not hide it for user`s ensuring in items absence
		mComboBox->hide();
	} else {
		connect(mComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setActiveEditor(int)));
		mComboBox->show();
	}

	setActiveEditor(SettingsManager::value("CurrentIndex", 0).toInt());
	if (mTree) {
		mTree->resizeIcons();
	}
}

void PaletteTree::setComboBox(const Id &id)
{
	mComboBox->setCurrentIndex(mCategories.value(id, -1));
}

QComboBox* PaletteTree::comboBox() const
{
	return mComboBox;
}

QList<QString> PaletteTree::editorsNames() const
{
	return mEditorsNames;
}

void PaletteTree::deleteEditor(const Id &id)
{
	if (mCategories.contains(id)) {
		PaletteTreeWidgets *tree = mEditorsTrees[mCategories[id]];
		if (mTree == tree) {
			mTree = nullptr;
		}

		mComboBox->removeItem(mCategories[id]);
		mEditorsNames.removeAt(mCategories[id]);
		mEditorsTrees.removeAt(mCategories[id]);

		delete tree;
		mCategories.remove(id);
	}
}

Id PaletteTree::currentEditor() const
{
	return mCategories.key(mCurrentEditor);
}

void PaletteTree::recreateTrees()
{
	deletePaletteTree();
	createPaletteTree();
}

void PaletteTree::createPaletteTree()
{
	mTree = new PaletteTreeWidgets(*this, mMainWindow, *mEditorManager);
	mTree->setMinimumHeight(0);
	mLayout->addWidget(mTree);
}

void PaletteTree::deletePaletteTree()
{
	mComboBox->clear();
	if (mTree) {
		mEditorsTrees.removeAll(mTree);
		mLayout->removeWidget(mTree);
		delete mTree;
	}

	qDeleteAll(mEditorsTrees);
	mEditorsTrees.clear();
	mEditorsNames.clear();
	mCategories.clear();
	mCurrentEditor = 0;
}

PaletteTree::~PaletteTree()
{
	deletePaletteTree();
}

void PaletteTree::setComboBoxIndex(int index)
{
	mComboBox->setCurrentIndex(index);
}

void PaletteTree::setComboBoxIndex()
{
	mComboBox->setCurrentIndex(SettingsManager::value("CurrentIndex", 0).toInt());
}

void PaletteTree::saveConfiguration()
{
	SettingsManager::setValue("PaletteRepresentation", mIconsView);
	SettingsManager::setValue("PaletteIconsInARowCount", mItemsCountInARow);
	int diagramIndex = 0;
	for (const PaletteTreeWidgets *editorTree : mEditorsTrees) {
		editorTree->saveConfiguration(mComboBox->itemText(diagramIndex));
		diagramIndex++;
	}

	SettingsManager::setValue("CurrentIndex", mComboBox->currentIndex() >= 0 ? mComboBox->currentIndex() : 0);
}

bool PaletteTree::iconsView() const
{
	return mIconsView;
}

void PaletteTree::setIconsView(bool iconsView)
{
	mIconsView = iconsView;
}

void PaletteTree::loadEditors(EditorManagerInterface &editorManagerProxy)
{
	for (const Id &editor : editorManagerProxy.editors()) {
		for (const Id &diagram : editorManagerProxy.diagrams(editor)) {
			addEditorElements(editorManagerProxy, editor, diagram);
		}
	}

	const int index = SettingsManager::value("CurrentIndex", 0).toInt();
	SettingsManager::setValue("CurrentIndex", index >= 0 ? index : 0);
}

void PaletteTree::setItemsCountInARow(int count)
{
	mItemsCountInARow = count;
}

int PaletteTree::itemsCountInARow() const
{
	return mItemsCountInARow;
}

void PaletteTree::resizeEvent(QResizeEvent *)
{
	if (mTree) {
		mTree->resizeIcons();
	}
}

int PaletteTree::maxItemsCountInARow() const
{
	const int max = mTree->maxItemsCountInARow();
	return max ? max : mItemsCountInARow;
}

void PaletteTree::onSearchTextChanged(const QRegExp &searchText)
{
	mTree->filter(searchText);
}

void PaletteTree::changeRepresentation()
{
	loadPalette(!mIconsView, mItemsCountInARow, mEditorManager);
	SettingsManager::setValue("PaletteRepresentation", mIconsView);
	SettingsManager::setValue("PaletteIconsInARowCount", mItemsCountInARow);
	emit paletteParametersChanged();
}

void PaletteTree::loadPalette(bool isIconsView, int itemsCount, EditorManagerInterface *editorManagerProxy)
{
	if (mEditorManager) {
		recreateTrees();
	}

	mIconsView = isIconsView;
	mEditorManager = editorManagerProxy;
	mItemsCountInARow = itemsCount;
	if (mEditorManager) {
		// TODO: Can it really be nullptr?
		loadEditors(*mEditorManager);
	}

	initDone();
	setComboBoxIndex();
	mSearchLineEdit->setVisible(!isIconsView);
}

void PaletteTree::initMainWindow(MainWindow *mainWindow)
{
	mMainWindow = mainWindow;
}

void PaletteTree::installEventFilter(QObject *obj)
{
	QWidget::installEventFilter(obj);
	comboBox()->installEventFilter(obj);
}

void PaletteTree::setElementVisible(const Id &metatype, bool visible)
{
	if (mTree) {
		mTree->setElementVisible(metatype, visible);
	}
}

void PaletteTree::setVisibleForAllElements(const Id &diagram, bool visible)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		if (tree->diagram() == diagram) {
			tree->setVisibleForAllElements(visible);
		}
	}
}

void PaletteTree::setElementEnabled(const Id &metatype, bool enabled)
{
	if (mTree) {
		mTree->setElementEnabled(metatype, enabled);
	}
}

void PaletteTree::setEnabledForAllElements(const Id &diagram, bool enabled)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		if (tree->diagram() == diagram) {
			tree->setEnabledForAllElements(enabled);
		}
	}}

void PaletteTree::refreshUserPalettes()
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		tree->refreshUserPalette();
	}
}

void PaletteTree::customizeExplosionTitles(const QString &userGroupTitle, const QString &userGroupDescription)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		tree->customizeExplosionTitles(userGroupTitle, userGroupDescription);
	}
}
<commit_msg>Small typo fix<commit_after>/* Copyright 2007-2015 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "paletteTree.h"

#include <QtCore/QUuid>
#include <QtGui/QMouseEvent>
#include <QtCore/QtAlgorithms>
#include <QtWidgets/QVBoxLayout>
#include <QtGui/QDrag>

#include <qrkernel/settingsManager.h>
#include <qrkernel/definitions.h>
#include <qrkernel/settingsManager.h>
#include <qrutils/widgets/searchLineEdit.h>

#include "mainWindow/palette/draggableElement.h"
#include "dialogs/metamodelingOnFly/propertiesDialog.h"

using namespace qReal;
using namespace gui;

PaletteTree::PaletteTree(QWidget *parent)
	: QWidget(parent)
	, mTree(nullptr)
	, mCurrentEditor(0)
{
	initUi();
}

void PaletteTree::initUi()
{
	mLayout = new QVBoxLayout(this);
	mLayout->setSpacing(0);
	QHBoxLayout * const controlButtonsLayout = new QHBoxLayout;
	controlButtonsLayout->setSpacing(0);

	mComboBox = new QComboBox;
	mComboBox->setGeometry(0, 0, 300, 50);
	mLayout->addWidget(mComboBox);
	mLayout->addLayout(controlButtonsLayout);

	ui::SearchLineEdit * const searchField = new ui::SearchLineEdit(this);
	connect(searchField, &ui::SearchLineEdit::textChanged, this, &PaletteTree::onSearchTextChanged);
	mLayout->addWidget(searchField);
	mSearchLineEdit = searchField;

	setMinimumSize(200, 100);
}

void PaletteTree::expand()
{
	mTree->expand();
}

void PaletteTree::collapse()
{
	mTree->collapse();
}

void PaletteTree::setActiveEditor(int index)
{
	if (0 <= index && index < mEditorsTrees.count()) {
		mCurrentEditor = index;
		if (mTree) {
			mTree->hide();
		}

		mTree = mEditorsTrees[index];
		mTree->show();
	}
}

void PaletteTree::setActiveEditor(const Id &id)
{
	setActiveEditor(mCategories.value(id, 0));
}

void PaletteTree::addEditorElements(EditorManagerInterface &editorManagerProxy, const Id &editor, const Id &diagram)
{
	mEditorManager = &editorManagerProxy;
	mEditorsNames.push_back(mEditorManager->friendlyName(diagram));

	mCategories[diagram] = mEditorsTrees.size();

	mComboBox->addItem(mEditorManager->friendlyName(diagram));

	PaletteTreeWidgets *editorTree = new PaletteTreeWidgets(*this, mMainWindow, *mEditorManager, editor, diagram);
	editorTree->hide();

	mEditorsTrees.push_back(editorTree);
	mLayout->addWidget(editorTree);
}

void PaletteTree::initDone()
{
	if (mComboBox->count() == 1) {
		// In case of empty combobox we do not hide it for user`s ensuring in items absence
		mComboBox->hide();
	} else {
		connect(mComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setActiveEditor(int)));
		mComboBox->show();
	}

	setActiveEditor(SettingsManager::value("CurrentIndex", 0).toInt());
	if (mTree) {
		mTree->resizeIcons();
	}
}

void PaletteTree::setComboBox(const Id &id)
{
	mComboBox->setCurrentIndex(mCategories.value(id, -1));
}

QComboBox* PaletteTree::comboBox() const
{
	return mComboBox;
}

QList<QString> PaletteTree::editorsNames() const
{
	return mEditorsNames;
}

void PaletteTree::deleteEditor(const Id &id)
{
	if (mCategories.contains(id)) {
		PaletteTreeWidgets *tree = mEditorsTrees[mCategories[id]];
		if (mTree == tree) {
			mTree = nullptr;
		}

		mComboBox->removeItem(mCategories[id]);
		mEditorsNames.removeAt(mCategories[id]);
		mEditorsTrees.removeAt(mCategories[id]);

		delete tree;
		mCategories.remove(id);
	}
}

Id PaletteTree::currentEditor() const
{
	return mCategories.key(mCurrentEditor);
}

void PaletteTree::recreateTrees()
{
	deletePaletteTree();
	createPaletteTree();
}

void PaletteTree::createPaletteTree()
{
	mTree = new PaletteTreeWidgets(*this, mMainWindow, *mEditorManager);
	mTree->setMinimumHeight(0);
	mLayout->addWidget(mTree);
}

void PaletteTree::deletePaletteTree()
{
	mComboBox->clear();
	if (mTree) {
		mEditorsTrees.removeAll(mTree);
		mLayout->removeWidget(mTree);
		delete mTree;
	}

	qDeleteAll(mEditorsTrees);
	mEditorsTrees.clear();
	mEditorsNames.clear();
	mCategories.clear();
	mCurrentEditor = 0;
}

PaletteTree::~PaletteTree()
{
	deletePaletteTree();
}

void PaletteTree::setComboBoxIndex(int index)
{
	mComboBox->setCurrentIndex(index);
}

void PaletteTree::setComboBoxIndex()
{
	mComboBox->setCurrentIndex(SettingsManager::value("CurrentIndex", 0).toInt());
}

void PaletteTree::saveConfiguration()
{
	SettingsManager::setValue("PaletteRepresentation", mIconsView);
	SettingsManager::setValue("PaletteIconsInARowCount", mItemsCountInARow);
	int diagramIndex = 0;
	for (const PaletteTreeWidgets *editorTree : mEditorsTrees) {
		editorTree->saveConfiguration(mComboBox->itemText(diagramIndex));
		diagramIndex++;
	}

	SettingsManager::setValue("CurrentIndex", mComboBox->currentIndex() >= 0 ? mComboBox->currentIndex() : 0);
}

bool PaletteTree::iconsView() const
{
	return mIconsView;
}

void PaletteTree::setIconsView(bool iconsView)
{
	mIconsView = iconsView;
}

void PaletteTree::loadEditors(EditorManagerInterface &editorManagerProxy)
{
	for (const Id &editor : editorManagerProxy.editors()) {
		for (const Id &diagram : editorManagerProxy.diagrams(editor)) {
			addEditorElements(editorManagerProxy, editor, diagram);
		}
	}

	const int index = SettingsManager::value("CurrentIndex", 0).toInt();
	SettingsManager::setValue("CurrentIndex", index >= 0 ? index : 0);
}

void PaletteTree::setItemsCountInARow(int count)
{
	mItemsCountInARow = count;
}

int PaletteTree::itemsCountInARow() const
{
	return mItemsCountInARow;
}

void PaletteTree::resizeEvent(QResizeEvent *)
{
	if (mTree) {
		mTree->resizeIcons();
	}
}

int PaletteTree::maxItemsCountInARow() const
{
	const int max = mTree->maxItemsCountInARow();
	return max ? max : mItemsCountInARow;
}

void PaletteTree::onSearchTextChanged(const QRegExp &searchText)
{
	mTree->filter(searchText);
}

void PaletteTree::changeRepresentation()
{
	loadPalette(!mIconsView, mItemsCountInARow, mEditorManager);
	SettingsManager::setValue("PaletteRepresentation", mIconsView);
	SettingsManager::setValue("PaletteIconsInARowCount", mItemsCountInARow);
	emit paletteParametersChanged();
}

void PaletteTree::loadPalette(bool isIconsView, int itemsCount, EditorManagerInterface *editorManagerProxy)
{
	if (mEditorManager) {
		recreateTrees();
	}

	mIconsView = isIconsView;
	mEditorManager = editorManagerProxy;
	mItemsCountInARow = itemsCount;
	if (mEditorManager) {
		// TODO: Can it really be nullptr?
		loadEditors(*mEditorManager);
	}

	initDone();
	setComboBoxIndex();
	mSearchLineEdit->setVisible(!isIconsView);
}

void PaletteTree::initMainWindow(MainWindow *mainWindow)
{
	mMainWindow = mainWindow;
}

void PaletteTree::installEventFilter(QObject *obj)
{
	QWidget::installEventFilter(obj);
	comboBox()->installEventFilter(obj);
}

void PaletteTree::setElementVisible(const Id &metatype, bool visible)
{
	if (mTree) {
		mTree->setElementVisible(metatype, visible);
	}
}

void PaletteTree::setVisibleForAllElements(const Id &diagram, bool visible)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		if (tree->diagram() == diagram) {
			tree->setVisibleForAllElements(visible);
		}
	}
}

void PaletteTree::setElementEnabled(const Id &metatype, bool enabled)
{
	if (mTree) {
		mTree->setElementEnabled(metatype, enabled);
	}
}

void PaletteTree::setEnabledForAllElements(const Id &diagram, bool enabled)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		if (tree->diagram() == diagram) {
			tree->setEnabledForAllElements(enabled);
		}
	}
}

void PaletteTree::refreshUserPalettes()
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		tree->refreshUserPalette();
	}
}

void PaletteTree::customizeExplosionTitles(const QString &userGroupTitle, const QString &userGroupDescription)
{
	for (PaletteTreeWidgets * const tree : mEditorsTrees) {
		tree->customizeExplosionTitles(userGroupTitle, userGroupDescription);
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * 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: containerhelper.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.
 *
 ************************************************************************/

#include "oox/helper/containerhelper.hxx"
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <comphelper/processfactory.hxx>
#include "oox/helper/helper.hxx"

using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::container::XIndexContainer;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::container::XNameContainer;

namespace oox {

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

Reference< XIndexContainer > ContainerHelper::createIndexContainer()
{
    Reference< XIndexContainer > xContainer;
    try
    {
        Reference< XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
        xContainer.set( xFactory->createInstance( CREATE_OUSTRING( "com.sun.star.document.IndexedPropertyValues" ) ), UNO_QUERY_THROW );
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( xContainer.is(), "ContainerHelper::createIndexContainer - cannot create container" );
    return xContainer;
}

bool ContainerHelper::insertByIndex(
        const Reference< XIndexContainer >& rxIndexContainer,
        sal_Int32 nIndex, const Any& rObject )
{
    OSL_ENSURE( rxIndexContainer.is(), "ContainerHelper::insertByIndex - missing XIndexContainer interface" );
    bool bRet = false;
    try
    {
        rxIndexContainer->insertByIndex( nIndex, rObject );
        bRet = true;
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( bRet, "ContainerHelper::insertByIndex - cannot insert object" );
    return bRet;
}

Reference< XNameContainer > ContainerHelper::createNameContainer()
{
    Reference< XNameContainer > xContainer;
    try
    {
        Reference< XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
        xContainer.set( xFactory->createInstance( CREATE_OUSTRING( "com.sun.star.document.NamedPropertyValues" ) ), UNO_QUERY_THROW );
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( xContainer.is(), "ContainerHelper::createNameContainer - cannot create container" );
    return xContainer;
}

OUString ContainerHelper::getUnusedName(
        const Reference< XNameAccess >& rxNameAccess, const OUString& rSuggestedName,
        sal_Unicode cSeparator, sal_Int32 nFirstIndexToAppend )
{
    OSL_ENSURE( rxNameAccess.is(), "ContainerHelper::getUnusedName - missing XNameAccess interface" );

    OUString aNewName = rSuggestedName;
    sal_Int32 nIndex = nFirstIndexToAppend;
    while( rxNameAccess->hasByName( aNewName ) )
        aNewName = OUStringBuffer( rSuggestedName ).append( cSeparator ).append( nIndex++ ).makeStringAndClear();
    return aNewName;
}

bool ContainerHelper::insertByName(
        const Reference< XNameContainer >& rxNameContainer,
        const OUString& rName, const Any& rObject )
{
    OSL_ENSURE( rxNameContainer.is(), "ContainerHelper::insertByName - missing XNameContainer interface" );
    bool bRet = false;
    try
    {
        rxNameContainer->insertByName( rName, rObject );
        bRet = true;
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( bRet, "ContainerHelper::insertByName - cannot insert object" );
    return bRet;
}

OUString ContainerHelper::insertByUnusedName(
        const Reference< XNameContainer >& rxNameContainer, const Any& rObject,
        const OUString& rSuggestedName, sal_Unicode cSeparator, bool bRenameOldExisting )
{
    OSL_ENSURE( rxNameContainer.is(), "ContainerHelper::insertByUnusedName - missing XNameContainer interface" );

    // find an unused name
    Reference< XNameAccess > xNameAccess( rxNameContainer, UNO_QUERY );
    OUString aNewName = getUnusedName( xNameAccess, rSuggestedName, cSeparator );

    // rename existing object
    if( bRenameOldExisting && rxNameContainer->hasByName( rSuggestedName ) )
    {
        try
        {
            Any aOldObject = rxNameContainer->getByName( rSuggestedName );
            rxNameContainer->removeByName( rSuggestedName );
            rxNameContainer->insertByName( aNewName, aOldObject );
            aNewName = rSuggestedName;
        }
        catch( Exception& )
        {
            OSL_ENSURE( false, "ContainerHelper::insertByUnusedName - cannot rename old object" );
        }
    }

    // insert the new object and return its resulting name
    insertByName( rxNameContainer, aNewName, rObject );
    return aNewName;
}

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

} // namespace oox

<commit_msg>INTEGRATION: CWS xmlfilter06 (1.3.8); FILE MERGED 2008/06/26 14:16:00 dr 1.3.8.2: handle drawing object tables separated for chart import, extended line formatting with own property name sets 2008/06/09 15:16:13 dr 1.3.8.1: more chart line formatting, add line dashs to chart dash container<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: containerhelper.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "oox/helper/containerhelper.hxx"
#include <rtl/ustrbuf.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <comphelper/processfactory.hxx>
#include "oox/helper/helper.hxx"

using ::rtl::OUString;
using ::rtl::OUStringBuffer;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::container::XIndexContainer;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::container::XNameContainer;

namespace oox {

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

Reference< XIndexContainer > ContainerHelper::createIndexContainer()
{
    Reference< XIndexContainer > xContainer;
    try
    {
        Reference< XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
        xContainer.set( xFactory->createInstance( CREATE_OUSTRING( "com.sun.star.document.IndexedPropertyValues" ) ), UNO_QUERY_THROW );
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( xContainer.is(), "ContainerHelper::createIndexContainer - cannot create container" );
    return xContainer;
}

bool ContainerHelper::insertByIndex(
        const Reference< XIndexContainer >& rxIndexContainer,
        sal_Int32 nIndex, const Any& rObject )
{
    OSL_ENSURE( rxIndexContainer.is(), "ContainerHelper::insertByIndex - missing XIndexContainer interface" );
    bool bRet = false;
    try
    {
        rxIndexContainer->insertByIndex( nIndex, rObject );
        bRet = true;
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( bRet, "ContainerHelper::insertByIndex - cannot insert object" );
    return bRet;
}

Reference< XNameContainer > ContainerHelper::createNameContainer()
{
    Reference< XNameContainer > xContainer;
    try
    {
        Reference< XMultiServiceFactory > xFactory = ::comphelper::getProcessServiceFactory();
        xContainer.set( xFactory->createInstance( CREATE_OUSTRING( "com.sun.star.document.NamedPropertyValues" ) ), UNO_QUERY_THROW );
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( xContainer.is(), "ContainerHelper::createNameContainer - cannot create container" );
    return xContainer;
}

OUString ContainerHelper::getUnusedName(
        const Reference< XNameAccess >& rxNameAccess, const OUString& rSuggestedName,
        sal_Unicode cSeparator, sal_Int32 nFirstIndexToAppend )
{
    OSL_ENSURE( rxNameAccess.is(), "ContainerHelper::getUnusedName - missing XNameAccess interface" );

    OUString aNewName = rSuggestedName;
    sal_Int32 nIndex = nFirstIndexToAppend;
    while( rxNameAccess->hasByName( aNewName ) )
        aNewName = OUStringBuffer( rSuggestedName ).append( cSeparator ).append( nIndex++ ).makeStringAndClear();
    return aNewName;
}

bool ContainerHelper::insertByName(
        const Reference< XNameContainer >& rxNameContainer,
        const OUString& rName, const Any& rObject, bool bReplaceOldExisting )
{
    OSL_ENSURE( rxNameContainer.is(), "ContainerHelper::insertByName - missing XNameContainer interface" );
    bool bRet = false;
    try
    {
        if( bReplaceOldExisting && rxNameContainer->hasByName( rName ) )
            rxNameContainer->replaceByName( rName, rObject );
        else
            rxNameContainer->insertByName( rName, rObject );
        bRet = true;
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( bRet, "ContainerHelper::insertByName - cannot insert object" );
    return bRet;
}

OUString ContainerHelper::insertByUnusedName(
        const Reference< XNameContainer >& rxNameContainer,
        const OUString& rSuggestedName, sal_Unicode cSeparator,
        const Any& rObject, bool bRenameOldExisting )
{
    OSL_ENSURE( rxNameContainer.is(), "ContainerHelper::insertByUnusedName - missing XNameContainer interface" );

    // find an unused name
    Reference< XNameAccess > xNameAccess( rxNameContainer, UNO_QUERY );
    OUString aNewName = getUnusedName( xNameAccess, rSuggestedName, cSeparator );

    // rename existing object
    if( bRenameOldExisting && rxNameContainer->hasByName( rSuggestedName ) )
    {
        try
        {
            Any aOldObject = rxNameContainer->getByName( rSuggestedName );
            rxNameContainer->removeByName( rSuggestedName );
            rxNameContainer->insertByName( aNewName, aOldObject );
            aNewName = rSuggestedName;
        }
        catch( Exception& )
        {
            OSL_ENSURE( false, "ContainerHelper::insertByUnusedName - cannot rename old object" );
        }
    }

    // insert the new object and return its resulting name
    insertByName( rxNameContainer, aNewName, rObject );
    return aNewName;
}

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

ObjectContainer::ObjectContainer( const Reference< XMultiServiceFactory >& rxFactory, const OUString& rServiceName ) :
    mxFactory( rxFactory ),
    maServiceName( rServiceName ),
    mnIndex( 0 )
{
    OSL_ENSURE( mxFactory.is(), "ObjectContainer::ObjectContainer - missing service factory" );
}

ObjectContainer::~ObjectContainer()
{
}

bool ObjectContainer::hasObject( const OUString& rObjName ) const
{
    createContainer();
    return mxContainer.is() && mxContainer->hasByName( rObjName );
}

Any ObjectContainer::getObject( const OUString& rObjName ) const
{
    createContainer();
    if( mxContainer.is() ) try
    {
        return mxContainer->getByName( rObjName );
    }
    catch( Exception& )
    {
    }
    return Any();
}

OUString ObjectContainer::insertObject( const OUString& rObjName, const Any& rObj, bool bInsertByUnusedName )
{
    createContainer();
    if( mxContainer.is() )
    {
        if( bInsertByUnusedName )
            return ContainerHelper::insertByUnusedName( mxContainer, rObjName + OUString::valueOf( ++mnIndex ), ' ', rObj );
        if( ContainerHelper::insertByName( mxContainer, rObjName, rObj ) )
            return rObjName;
    }
    return OUString();
}

void ObjectContainer::createContainer() const
{
    if( !mxContainer.is() && mxFactory.is() ) try
    {
        mxContainer.set( mxFactory->createInstance( maServiceName ), UNO_QUERY_THROW );
    }
    catch( Exception& )
    {
    }
    OSL_ENSURE( mxContainer.is(), "ObjectContainer::createContainer - container not found" );
}

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

} // namespace oox

<|endoftext|>


<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Policies/BasicPolicy.hpp>

namespace RosettaStone
{
TaskMeta BasicPolicy::Next(const Game& game)
{
    (void)game;
    return TaskMeta();
}

TaskMeta BasicPolicy::Require(Player& player, TaskID id)
{
    if (auto iter = m_require.find(id); iter != m_require.end())
    {
        return iter->second(*this, player);
    }
    return TaskMeta(id);
}

void BasicPolicy::Notify(const TaskMeta& meta)
{
    if (auto iter = m_notify.find(meta.GetID()); iter != m_notify.end())
    {
        return iter->second(*this, meta);
    }
}

TaskMeta BasicPolicy::RequireMulligan(Player& player)
{
    (void)player;
    return TaskMeta();
}

TaskMeta BasicPolicy::RequirePlayCard(Player& player)
{
    (void)player;
    return TaskMeta();
}

TaskMeta BasicPolicy::RequireAttack(Player& player)
{
    (void)player;
    return TaskMeta();
}

void BasicPolicy::NotifyOverDraw(const TaskMeta& meta)
{
    (void)meta;
}
}  // namespace RosettaStone
<commit_msg>fix: Add default return values<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon

// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.

#include <Rosetta/Commons/Utils.hpp>
#include <Rosetta/Policies/BasicPolicy.hpp>

namespace RosettaStone
{
TaskMeta BasicPolicy::Next(const Game& game)
{
    (void)game;
    return TaskMeta({ TaskID::END_TURN });
}

TaskMeta BasicPolicy::Require(Player& player, TaskID id)
{
    if (auto iter = m_require.find(id); iter != m_require.end())
    {
        return iter->second(*this, player);
    }
    return TaskMeta(id);
}

void BasicPolicy::Notify(const TaskMeta& meta)
{
    if (auto iter = m_notify.find(meta.GetID()); iter != m_notify.end())
    {
        iter->second(*this, meta);
    }
}

TaskMeta BasicPolicy::RequireMulligan(Player& player)
{
    (void)player;
    return TaskMeta(TaskMetaTrait(), std::vector<std::size_t>());
}

TaskMeta BasicPolicy::RequirePlayCard(Player& player)
{
    (void)player;
    return TaskMeta(TaskMetaTrait(), SizedPtr<Entity*>());
}

TaskMeta BasicPolicy::RequireAttack(Player& player)
{
    (void)player;
    return TaskMeta(TaskMetaTrait(), SizedPtr<Entity*>());
}

void BasicPolicy::NotifyOverDraw(const TaskMeta& meta)
{
    (void)meta;
}
}  // namespace RosettaStone
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2016, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <thread>

#include "SurgSim/Collision/CcdDcdCollision.h"
#include "SurgSim/Collision/ContactCalculation.h"
#include "SurgSim/Collision/DefaultContactCalculation.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Framework/Log.h"

namespace SurgSim
{
namespace Collision
{

ContactCalculation::TableType ContactCalculation::m_contactDcdCalculations;
ContactCalculation::TableType ContactCalculation::m_contactCcdCalculations;
std::once_flag ContactCalculation::m_initializationFlag;

ContactCalculation::ContactCalculation()
{
}

ContactCalculation::~ContactCalculation()
{
}

void ContactCalculation::registerDcdContactCalculation(const std::shared_ptr<ContactCalculation>& calculation)
{
	std::call_once(m_initializationFlag, ContactCalculation::initializeTables);

	privateDcdRegister(calculation, calculation->getShapeTypes());
}

void ContactCalculation::registerCcdContactCalculation(const std::shared_ptr<ContactCalculation>& calculation)
{
	std::call_once(m_initializationFlag, ContactCalculation::initializeTables);

	privateCcdRegister(calculation, calculation->getShapeTypes());
}

const ContactCalculation::TableType& ContactCalculation::getDcdContactTable()
{
	std::call_once(m_initializationFlag, ContactCalculation::initializeTables);

	return m_contactDcdCalculations;
}

const ContactCalculation::TableType& ContactCalculation::getCcdContactTable()
{
	std::call_once(m_initializationFlag, ContactCalculation::initializeTables);

	return m_contactCcdCalculations;
}

void ContactCalculation::calculateContact(std::shared_ptr<CollisionPair> pair)
{
	doCalculateContact(pair);
}

std::list<std::shared_ptr<Contact>> ContactCalculation::calculateDcdContact(
									 const Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape1,
									 const Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape2)
{
	auto types = getShapeTypes();
	auto incoming = std::make_pair(posedShape1.getShape()->getType(), posedShape2.getShape()->getType());
	if (incoming == types)
	{
		return doCalculateDcdContact(posedShape1, posedShape2);
	}

	if (incoming.first == types.second && incoming.second == types.first)
	{
		auto contacts = doCalculateDcdContact(posedShape2, posedShape1);
		for (const auto& contact : contacts)
		{
			contact->normal = -contact->normal;
			contact->force = -contact->force;
			std::swap(contact->penetrationPoints.first, contact->penetrationPoints.second);
		}
		return contacts;
	}

	if (types.first != Math::SHAPE_TYPE_NONE && types.second != Math::SHAPE_TYPE_NONE)
	{
		SURGSIM_FAILURE() << "Incorrect shape type for this calculation expected "
						  << types.first << ", " << types.second
						  << " received " << incoming.first << ", " << incoming.second << ".";
	}

	return std::list<std::shared_ptr<Contact>>();
}

std::list<std::shared_ptr<SurgSim::Collision::Contact>> ContactCalculation::calculateCcdContact(
			const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>> posedShapeMotion1,
			const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>> posedShapeMotion2)
{
	auto types = getShapeTypes();
	auto incoming = std::make_pair(posedShapeMotion1.first.getShape()->getType(),
								   posedShapeMotion2.first.getShape()->getType());
	if (incoming == types)
	{
		return doCalculateCcdContact(posedShapeMotion1, posedShapeMotion2);
	}

	if (incoming.first == types.second && incoming.second == types.first)
	{
		auto contacts = doCalculateCcdContact(posedShapeMotion2, posedShapeMotion1);
		for (const auto& contact : contacts)
		{
			contact->normal = -contact->normal;
			contact->force = -contact->force;
			std::swap(contact->penetrationPoints.first, contact->penetrationPoints.second);
		}
		return contacts;
	}

	if (types.first != Math::SHAPE_TYPE_NONE && types.second != Math::SHAPE_TYPE_NONE)
	{
		SURGSIM_FAILURE() << "Incorrect shape type for this calculation expected "
						  << types.first << ", " << types.second
						  << " received " << incoming.first << ", " << incoming.second << ".";
	}

	return std::list<std::shared_ptr<Contact>>();
}

void ContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair)
{
	std::pair<int, int> shapeTypes = getShapeTypes();
	int firstShapeType = pair->getFirst()->getShapeType();
	int secondShapeType = pair->getSecond()->getShapeType();

	if (firstShapeType != secondShapeType && firstShapeType == shapeTypes.second &&
		secondShapeType == shapeTypes.first)
	{
		pair->swapRepresentations();
		std::swap(firstShapeType, secondShapeType);
	}

	if (shapeTypes.first != SurgSim::Math::SHAPE_TYPE_NONE)
	{
		SURGSIM_ASSERT(firstShapeType == shapeTypes.first) <<
				"First Object, wrong type of object" << firstShapeType;
	}

	if (shapeTypes.second != SurgSim::Math::SHAPE_TYPE_NONE)
	{
		SURGSIM_ASSERT(secondShapeType == shapeTypes.second) <<
				"Second Object, wrong type of object" << secondShapeType;
	}

	std::shared_ptr<Math::Shape> shape1 = pair->getFirst()->getPosedShape();

	std::shared_ptr<Math::Shape> shape2 = pair->getSecond()->getPosedShape();

	std::list<std::shared_ptr<Contact>> contacts;
	if (pair->getType() == Collision::CollisionDetectionType::COLLISION_DETECTION_TYPE_DISCRETE)
	{
		Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape1(shape1, pair->getFirst()->getPose());
		Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape2(shape2, pair->getSecond()->getPose());
		contacts = doCalculateDcdContact(posedShape1, posedShape2);
	}
	else if (pair->getType() == Collision::CollisionDetectionType::COLLISION_DETECTION_TYPE_CONTINUOUS)
	{
		contacts = doCalculateCcdContact(
					   pair->getFirst()->getPosedShapeMotion(),
					   pair->getSecond()->getPosedShapeMotion());
	}
	else
	{
		SURGSIM_FAILURE() << "Invalid collision detection type, neither discrete nor continuous";
	}

	for (auto& contact : contacts)
	{
		pair->addContact(contact);
	}
}

std::list<std::shared_ptr<Contact>> ContactCalculation::doCalculateDcdContact(
									 const Math::PosedShape<std::shared_ptr<Math::Shape>>& posedShape1,
									 const Math::PosedShape<std::shared_ptr<Math::Shape>>& posedShape2)
{
	SURGSIM_FAILURE() << "Not implemented";
	return std::list<std::shared_ptr<Contact>>();
}

std::list<std::shared_ptr<Contact>> ContactCalculation::doCalculateCcdContact(
									 const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>>& posedShapeMotion1,
									 const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>>& posedShapeMotion2)
{
	SURGSIM_FAILURE() << "Not implemented";
	return std::list<std::shared_ptr<Contact>>();
}

void ContactCalculation::initializeTables()
{
	// Fill up both tables with default empty contact calculation
	for (int i = 0; i < SurgSim::Math::SHAPE_TYPE_COUNT; ++i)
	{
		for (int j = 0; j < SurgSim::Math::SHAPE_TYPE_COUNT; ++j)
		{
			m_contactDcdCalculations[i][j].reset(new Collision::DefaultContactCalculation(false));
			m_contactCcdCalculations[i][j].reset(new Collision::DefaultContactCalculation(false));
		}
	}

	// Fill up the Dcd contact calculation table
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxCapsuleContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxDoubleSidedPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxSphereContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::CapsuleSphereContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeCapsuleContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeDoubleSidedPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreePlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeSphereContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::SegmentMeshTriangleMeshContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::SphereSphereContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::SphereDoubleSidedPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::SpherePlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshParticlesContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshSurfaceMeshContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshTriangleMeshContact>());

	const std::array<int, Math::SHAPE_TYPE_COUNT> allshapes =
	{
		Math::SHAPE_TYPE_BOX,
		Math::SHAPE_TYPE_CAPSULE,
		Math::SHAPE_TYPE_CYLINDER,
		Math::SHAPE_TYPE_DOUBLESIDEDPLANE,
		Math::SHAPE_TYPE_MESH,
		Math::SHAPE_TYPE_OCTREE,
		Math::SHAPE_TYPE_PARTICLES,
		Math::SHAPE_TYPE_PLANE,
		Math::SHAPE_TYPE_SPHERE,
		Math::SHAPE_TYPE_SURFACEMESH,
		Math::SHAPE_TYPE_SEGMENTMESH,
		Math::SHAPE_TYPE_COMPOUNDSHAPE
	};

	for (auto type : allshapes)
	{
		ContactCalculation::privateDcdRegister(std::make_shared<Collision::CompoundShapeContact>(
				std::make_pair(Math::SHAPE_TYPE_COMPOUNDSHAPE, type)));
	}

	ContactCalculation::privateCcdRegister(std::make_shared<Collision::SegmentSelfContact>());
	ContactCalculation::privateCcdRegister(std::make_shared<Collision::SegmentMeshTriangleMeshContact>());
	ContactCalculation::privateCcdRegister(std::make_shared<Collision::TriangleMeshTriangleMeshContact>());

	ContactCalculation::privateCcdRegister(std::make_shared<Collision::CompoundShapeContact>(
			std::make_pair(Math::SHAPE_TYPE_COMPOUNDSHAPE, Math::SHAPE_TYPE_SEGMENTMESH)));
}

void ContactCalculation::privateDcdRegister(
	const std::shared_ptr<ContactCalculation>& calculation)
{
	privateDcdRegister(calculation, calculation->getShapeTypes());
}

void ContactCalculation::privateDcdRegister(
	const std::shared_ptr<ContactCalculation>& calculation,
	const std::pair<int, int>& types)
{
	m_contactDcdCalculations[types.first][types.second] = calculation;
	m_contactDcdCalculations[types.second][types.first] = calculation;
}

void ContactCalculation::privateCcdRegister(
	const std::shared_ptr<ContactCalculation>& calculation)
{
	privateCcdRegister(calculation, calculation->getShapeTypes());
}

void ContactCalculation::privateCcdRegister(
	const std::shared_ptr<ContactCalculation>& calculation,
	const std::pair<int, int>& types)
{
	m_contactCcdCalculations[types.first][types.second] = calculation;
	m_contactCcdCalculations[types.second][types.first] = calculation;
}

}; // namespace Collision
}; // namespace SurgSim
<commit_msg>Move shape1, shape2 calculation inside the code block where it is used.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013-2016, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <thread>

#include "SurgSim/Collision/CcdDcdCollision.h"
#include "SurgSim/Collision/ContactCalculation.h"
#include "SurgSim/Collision/DefaultContactCalculation.h"
#include "SurgSim/Collision/Representation.h"
#include "SurgSim/Framework/Log.h"

namespace SurgSim
{
namespace Collision
{

ContactCalculation::TableType ContactCalculation::m_contactDcdCalculations;
ContactCalculation::TableType ContactCalculation::m_contactCcdCalculations;
std::once_flag ContactCalculation::m_initializationFlag;

ContactCalculation::ContactCalculation()
{
}

ContactCalculation::~ContactCalculation()
{
}

void ContactCalculation::registerDcdContactCalculation(const std::shared_ptr<ContactCalculation>& calculation)
{
	std::call_once(m_initializationFlag, ContactCalculation::initializeTables);

	privateDcdRegister(calculation, calculation->getShapeTypes());
}

void ContactCalculation::registerCcdContactCalculation(const std::shared_ptr<ContactCalculation>& calculation)
{
	std::call_once(m_initializationFlag, ContactCalculation::initializeTables);

	privateCcdRegister(calculation, calculation->getShapeTypes());
}

const ContactCalculation::TableType& ContactCalculation::getDcdContactTable()
{
	std::call_once(m_initializationFlag, ContactCalculation::initializeTables);

	return m_contactDcdCalculations;
}

const ContactCalculation::TableType& ContactCalculation::getCcdContactTable()
{
	std::call_once(m_initializationFlag, ContactCalculation::initializeTables);

	return m_contactCcdCalculations;
}

void ContactCalculation::calculateContact(std::shared_ptr<CollisionPair> pair)
{
	doCalculateContact(pair);
}

std::list<std::shared_ptr<Contact>> ContactCalculation::calculateDcdContact(
									 const Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape1,
									 const Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape2)
{
	auto types = getShapeTypes();
	auto incoming = std::make_pair(posedShape1.getShape()->getType(), posedShape2.getShape()->getType());
	if (incoming == types)
	{
		return doCalculateDcdContact(posedShape1, posedShape2);
	}

	if (incoming.first == types.second && incoming.second == types.first)
	{
		auto contacts = doCalculateDcdContact(posedShape2, posedShape1);
		for (const auto& contact : contacts)
		{
			contact->normal = -contact->normal;
			contact->force = -contact->force;
			std::swap(contact->penetrationPoints.first, contact->penetrationPoints.second);
		}
		return contacts;
	}

	if (types.first != Math::SHAPE_TYPE_NONE && types.second != Math::SHAPE_TYPE_NONE)
	{
		SURGSIM_FAILURE() << "Incorrect shape type for this calculation expected "
						  << types.first << ", " << types.second
						  << " received " << incoming.first << ", " << incoming.second << ".";
	}

	return std::list<std::shared_ptr<Contact>>();
}

std::list<std::shared_ptr<SurgSim::Collision::Contact>> ContactCalculation::calculateCcdContact(
			const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>> posedShapeMotion1,
			const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>> posedShapeMotion2)
{
	auto types = getShapeTypes();
	auto incoming = std::make_pair(posedShapeMotion1.first.getShape()->getType(),
								   posedShapeMotion2.first.getShape()->getType());
	if (incoming == types)
	{
		return doCalculateCcdContact(posedShapeMotion1, posedShapeMotion2);
	}

	if (incoming.first == types.second && incoming.second == types.first)
	{
		auto contacts = doCalculateCcdContact(posedShapeMotion2, posedShapeMotion1);
		for (const auto& contact : contacts)
		{
			contact->normal = -contact->normal;
			contact->force = -contact->force;
			std::swap(contact->penetrationPoints.first, contact->penetrationPoints.second);
		}
		return contacts;
	}

	if (types.first != Math::SHAPE_TYPE_NONE && types.second != Math::SHAPE_TYPE_NONE)
	{
		SURGSIM_FAILURE() << "Incorrect shape type for this calculation expected "
						  << types.first << ", " << types.second
						  << " received " << incoming.first << ", " << incoming.second << ".";
	}

	return std::list<std::shared_ptr<Contact>>();
}

void ContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair)
{
	std::pair<int, int> shapeTypes = getShapeTypes();
	int firstShapeType = pair->getFirst()->getShapeType();
	int secondShapeType = pair->getSecond()->getShapeType();

	if (firstShapeType != secondShapeType && firstShapeType == shapeTypes.second &&
		secondShapeType == shapeTypes.first)
	{
		pair->swapRepresentations();
		std::swap(firstShapeType, secondShapeType);
	}

	if (shapeTypes.first != SurgSim::Math::SHAPE_TYPE_NONE)
	{
		SURGSIM_ASSERT(firstShapeType == shapeTypes.first) <<
				"First Object, wrong type of object" << firstShapeType;
	}

	if (shapeTypes.second != SurgSim::Math::SHAPE_TYPE_NONE)
	{
		SURGSIM_ASSERT(secondShapeType == shapeTypes.second) <<
				"Second Object, wrong type of object" << secondShapeType;
	}

	std::list<std::shared_ptr<Contact>> contacts;
	if (pair->getType() == Collision::CollisionDetectionType::COLLISION_DETECTION_TYPE_DISCRETE)
	{
		std::shared_ptr<Math::Shape> shape1 = pair->getFirst()->getPosedShape();
		std::shared_ptr<Math::Shape> shape2 = pair->getSecond()->getPosedShape();

		Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape1(shape1, pair->getFirst()->getPose());
		Math::PosedShape<std::shared_ptr<Math::Shape>> posedShape2(shape2, pair->getSecond()->getPose());
		contacts = doCalculateDcdContact(posedShape1, posedShape2);
	}
	else if (pair->getType() == Collision::CollisionDetectionType::COLLISION_DETECTION_TYPE_CONTINUOUS)
	{
		contacts = doCalculateCcdContact(
					   pair->getFirst()->getPosedShapeMotion(),
					   pair->getSecond()->getPosedShapeMotion());
	}
	else
	{
		SURGSIM_FAILURE() << "Invalid collision detection type, neither discrete nor continuous";
	}

	for (auto& contact : contacts)
	{
		pair->addContact(contact);
	}
}

std::list<std::shared_ptr<Contact>> ContactCalculation::doCalculateDcdContact(
									 const Math::PosedShape<std::shared_ptr<Math::Shape>>& posedShape1,
									 const Math::PosedShape<std::shared_ptr<Math::Shape>>& posedShape2)
{
	SURGSIM_FAILURE() << "Not implemented";
	return std::list<std::shared_ptr<Contact>>();
}

std::list<std::shared_ptr<Contact>> ContactCalculation::doCalculateCcdContact(
									 const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>>& posedShapeMotion1,
									 const Math::PosedShapeMotion<std::shared_ptr<Math::Shape>>& posedShapeMotion2)
{
	SURGSIM_FAILURE() << "Not implemented";
	return std::list<std::shared_ptr<Contact>>();
}

void ContactCalculation::initializeTables()
{
	// Fill up both tables with default empty contact calculation
	for (int i = 0; i < SurgSim::Math::SHAPE_TYPE_COUNT; ++i)
	{
		for (int j = 0; j < SurgSim::Math::SHAPE_TYPE_COUNT; ++j)
		{
			m_contactDcdCalculations[i][j].reset(new Collision::DefaultContactCalculation(false));
			m_contactCcdCalculations[i][j].reset(new Collision::DefaultContactCalculation(false));
		}
	}

	// Fill up the Dcd contact calculation table
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxCapsuleContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxDoubleSidedPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::BoxSphereContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::CapsuleSphereContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeCapsuleContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeDoubleSidedPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreePlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::OctreeSphereContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::SegmentMeshTriangleMeshContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::SphereSphereContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::SphereDoubleSidedPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::SpherePlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshParticlesContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshPlaneContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshSurfaceMeshContact>());
	ContactCalculation::privateDcdRegister(std::make_shared<Collision::TriangleMeshTriangleMeshContact>());

	const std::array<int, Math::SHAPE_TYPE_COUNT> allshapes =
	{
		Math::SHAPE_TYPE_BOX,
		Math::SHAPE_TYPE_CAPSULE,
		Math::SHAPE_TYPE_CYLINDER,
		Math::SHAPE_TYPE_DOUBLESIDEDPLANE,
		Math::SHAPE_TYPE_MESH,
		Math::SHAPE_TYPE_OCTREE,
		Math::SHAPE_TYPE_PARTICLES,
		Math::SHAPE_TYPE_PLANE,
		Math::SHAPE_TYPE_SPHERE,
		Math::SHAPE_TYPE_SURFACEMESH,
		Math::SHAPE_TYPE_SEGMENTMESH,
		Math::SHAPE_TYPE_COMPOUNDSHAPE
	};

	for (auto type : allshapes)
	{
		ContactCalculation::privateDcdRegister(std::make_shared<Collision::CompoundShapeContact>(
				std::make_pair(Math::SHAPE_TYPE_COMPOUNDSHAPE, type)));
	}

	ContactCalculation::privateCcdRegister(std::make_shared<Collision::SegmentSelfContact>());
	ContactCalculation::privateCcdRegister(std::make_shared<Collision::SegmentMeshTriangleMeshContact>());
	ContactCalculation::privateCcdRegister(std::make_shared<Collision::TriangleMeshTriangleMeshContact>());

	ContactCalculation::privateCcdRegister(std::make_shared<Collision::CompoundShapeContact>(
			std::make_pair(Math::SHAPE_TYPE_COMPOUNDSHAPE, Math::SHAPE_TYPE_SEGMENTMESH)));
}

void ContactCalculation::privateDcdRegister(
	const std::shared_ptr<ContactCalculation>& calculation)
{
	privateDcdRegister(calculation, calculation->getShapeTypes());
}

void ContactCalculation::privateDcdRegister(
	const std::shared_ptr<ContactCalculation>& calculation,
	const std::pair<int, int>& types)
{
	m_contactDcdCalculations[types.first][types.second] = calculation;
	m_contactDcdCalculations[types.second][types.first] = calculation;
}

void ContactCalculation::privateCcdRegister(
	const std::shared_ptr<ContactCalculation>& calculation)
{
	privateCcdRegister(calculation, calculation->getShapeTypes());
}

void ContactCalculation::privateCcdRegister(
	const std::shared_ptr<ContactCalculation>& calculation,
	const std::pair<int, int>& types)
{
	m_contactCcdCalculations[types.first][types.second] = calculation;
	m_contactCcdCalculations[types.second][types.first] = calculation;
}

}; // namespace Collision
}; // namespace SurgSim
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <math.h>

#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkScalar.h"
#include "itkVector.h"
#include "vnl/vnl_matrix_fixed.h"
#include "itkSimpleImageRegionIterator.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGibbsPriorFilter.h"

#define   IMGWIDTH            5
#define   IMGHEIGHT           5
#define   NFRAMES             1
#define   NUMBANDS            1
#define   NDIMENSION          3
#define   NUM_CLASSES         3
#define   MAX_NUM_ITER        20

//using namespace itk;

int main(){

  typedef itk::Image<itk::Vector<unsigned short,NUMBANDS>,NDIMENSION> VecImageType;

  VecImageType::Pointer vecImage = VecImageType::New();

  VecImageType::SizeType vecImgSize = { IMGWIDTH , IMGHEIGHT, NFRAMES };

  VecImageType::IndexType index = VecImageType::IndexType::ZeroIndex;
  VecImageType::RegionType region;

  region.SetSize( vecImgSize );
  region.SetIndex( index );

  vecImage->SetLargestPossibleRegion( region );
  vecImage->SetBufferedRegion( region );
  vecImage->Allocate();

  // setup the iterators
  typedef VecImageType::PixelType::VectorType VecPixelType;

  enum { VecImageDimension = VecImageType::ImageDimension };
  typedef itk::SimpleImageRegionIterator< VecImageType > VecIterator;

  VecIterator outIt( vecImage, vecImage->GetBufferedRegion() );
  outIt.Begin();

  //Set up the vector to store the image  data
  typedef VecImageType::PixelType     DataVector;
  DataVector   dblVec;

  //--------------------------------------------------------------------------
  //Manually create and store each vector
  //--------------------------------------------------------------------------
  int i = 0;
  while ( !outIt.IsAtEnd() ) {
    if ( ((i>5)&&(i<9)) || ((i>10)&&(i<14)) || ((i>15)&&(i<19)) )
	dblVec[0] = 1;
	else dblVec[0] = 0;
	outIt.Set(dblVec);
	++outIt;
	i++;
  }

  //---------------------------------------------------------------
  //Generate the training data
  //---------------------------------------------------------------
  typedef itk::Image<unsigned short,NDIMENSION> ClassImageType;
  ClassImageType::Pointer classImage  = ClassImageType::New();

  ClassImageType::SizeType classImgSize = { IMGWIDTH , IMGHEIGHT, NFRAMES };

  ClassImageType::IndexType classindex = ClassImageType::IndexType::ZeroIndex;
  ClassImageType::RegionType classregion;

  classregion.SetSize( classImgSize );
  classregion.SetIndex( classindex );

  classImage->SetLargestPossibleRegion( classregion );
  classImage->SetBufferedRegion( classregion );
  classImage->Allocate();

  // setup the iterators
  typedef ClassImageType::PixelType ClassImagePixelType;

  unsigned int ClassImageDimension = NDIMENSION;

  typedef  itk::SimpleImageRegionIterator<ClassImageType>  ClassImageIterator;

  ClassImageIterator classoutIt( classImage, classImage->GetBufferedRegion() );

  classoutIt.Begin();

  //--------------------------------------------------------------------------
  //Manually create and store each vector
  //--------------------------------------------------------------------------
  i = 0;
  while ( !classoutIt.IsAtEnd() ) {
	if ( ((i>5)&&(i<9)) || ((i>10)&&(i<14)) || ((i>15)&&(i<19)) ){
	  classoutIt.Set( 2 );
	}
	else classoutIt.Set( 1 );
    ++classoutIt;
	i++;
  }

  //----------------------------------------------------------------------
  // Test code for the supervised classifier algorithm
  //----------------------------------------------------------------------

  //---------------------------------------------------------------------
  // Multiband data is now available in the right format
  //---------------------------------------------------------------------
  typedef
	itk::Classifier<VecImageType,ClassImageType>::Pointer
	  ClassifierType;

  //Instantiate the classifier to be used
  typedef itk::GaussianSupervisedClassifier<VecImageType,ClassImageType>
    GaussianSupervisedClassifierType;

  GaussianSupervisedClassifierType::Pointer
	  myGaussianClassifier = GaussianSupervisedClassifierType::New();

  //Set the Gibbs Prior labeller
  typedef itk::GibbsPriorFilter<VecImageType,ClassImageType> GibbsPriorFilterType;
  GibbsPriorFilterType::Pointer applyGibbsImageFilter = GibbsPriorFilterType::New();

  // Set the MRF labeller parameters
  applyGibbsImageFilter->SetNumClasses(NUM_CLASSES);
  applyGibbsImageFilter->SetMaxNumIter(MAX_NUM_ITER);
  applyGibbsImageFilter->SetErrorTollerance(0.00);
  applyGibbsImageFilter->SetClusterSize(0);
  applyGibbsImageFilter->SetBoundaryGradient(1);

  applyGibbsImageFilter->SetInput(vecImage);
  applyGibbsImageFilter
    ->SetClassifier((ClassifierType) myGaussianClassifier );

  //Since a suvervised classifier is used, it requires a training image
  applyGibbsImageFilter->SetTrainingImage(classImage);

  //Kick off the MRF labeller function
  applyGibbsImageFilter->Update();

  ClassImageType::Pointer  outClassImage = applyGibbsImageFilter->GetOutput();

  //Print the mrf labelled image
  ClassImageIterator labeloutIt( outClassImage, outClassImage->GetBufferedRegion() );
  labeloutIt.Begin();

  i = 0;
  while ( !labeloutIt.IsAtEnd() ) {
	std::cout <<labeloutIt.Get() << std::endl;
	i++;
	++labeloutIt;
  }

  return 0;
}<commit_msg>ERR:  No newline at end of file.<commit_after>#include <iostream>
#include <string>
#include <math.h>

#ifdef _MSC_VER
#pragma warning ( disable : 4786 )
#endif
#include "itkImage.h"
#include "itkScalar.h"
#include "itkVector.h"
#include "vnl/vnl_matrix_fixed.h"
#include "itkSimpleImageRegionIterator.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGibbsPriorFilter.h"

#define   IMGWIDTH            5
#define   IMGHEIGHT           5
#define   NFRAMES             1
#define   NUMBANDS            1
#define   NDIMENSION          3
#define   NUM_CLASSES         3
#define   MAX_NUM_ITER        20

//using namespace itk;

int main(){

  typedef itk::Image<itk::Vector<unsigned short,NUMBANDS>,NDIMENSION> VecImageType;

  VecImageType::Pointer vecImage = VecImageType::New();

  VecImageType::SizeType vecImgSize = { IMGWIDTH , IMGHEIGHT, NFRAMES };

  VecImageType::IndexType index = VecImageType::IndexType::ZeroIndex;
  VecImageType::RegionType region;

  region.SetSize( vecImgSize );
  region.SetIndex( index );

  vecImage->SetLargestPossibleRegion( region );
  vecImage->SetBufferedRegion( region );
  vecImage->Allocate();

  // setup the iterators
  typedef VecImageType::PixelType::VectorType VecPixelType;

  enum { VecImageDimension = VecImageType::ImageDimension };
  typedef itk::SimpleImageRegionIterator< VecImageType > VecIterator;

  VecIterator outIt( vecImage, vecImage->GetBufferedRegion() );
  outIt.Begin();

  //Set up the vector to store the image  data
  typedef VecImageType::PixelType     DataVector;
  DataVector   dblVec;

  //--------------------------------------------------------------------------
  //Manually create and store each vector
  //--------------------------------------------------------------------------
  int i = 0;
  while ( !outIt.IsAtEnd() ) {
    if ( ((i>5)&&(i<9)) || ((i>10)&&(i<14)) || ((i>15)&&(i<19)) )
	dblVec[0] = 1;
	else dblVec[0] = 0;
	outIt.Set(dblVec);
	++outIt;
	i++;
  }

  //---------------------------------------------------------------
  //Generate the training data
  //---------------------------------------------------------------
  typedef itk::Image<unsigned short,NDIMENSION> ClassImageType;
  ClassImageType::Pointer classImage  = ClassImageType::New();

  ClassImageType::SizeType classImgSize = { IMGWIDTH , IMGHEIGHT, NFRAMES };

  ClassImageType::IndexType classindex = ClassImageType::IndexType::ZeroIndex;
  ClassImageType::RegionType classregion;

  classregion.SetSize( classImgSize );
  classregion.SetIndex( classindex );

  classImage->SetLargestPossibleRegion( classregion );
  classImage->SetBufferedRegion( classregion );
  classImage->Allocate();

  // setup the iterators
  typedef ClassImageType::PixelType ClassImagePixelType;

  unsigned int ClassImageDimension = NDIMENSION;

  typedef  itk::SimpleImageRegionIterator<ClassImageType>  ClassImageIterator;

  ClassImageIterator classoutIt( classImage, classImage->GetBufferedRegion() );

  classoutIt.Begin();

  //--------------------------------------------------------------------------
  //Manually create and store each vector
  //--------------------------------------------------------------------------
  i = 0;
  while ( !classoutIt.IsAtEnd() ) {
	if ( ((i>5)&&(i<9)) || ((i>10)&&(i<14)) || ((i>15)&&(i<19)) ){
	  classoutIt.Set( 2 );
	}
	else classoutIt.Set( 1 );
    ++classoutIt;
	i++;
  }

  //----------------------------------------------------------------------
  // Test code for the supervised classifier algorithm
  //----------------------------------------------------------------------

  //---------------------------------------------------------------------
  // Multiband data is now available in the right format
  //---------------------------------------------------------------------
  typedef
	itk::Classifier<VecImageType,ClassImageType>::Pointer
	  ClassifierType;

  //Instantiate the classifier to be used
  typedef itk::GaussianSupervisedClassifier<VecImageType,ClassImageType>
    GaussianSupervisedClassifierType;

  GaussianSupervisedClassifierType::Pointer
	  myGaussianClassifier = GaussianSupervisedClassifierType::New();

  //Set the Gibbs Prior labeller
  typedef itk::GibbsPriorFilter<VecImageType,ClassImageType> GibbsPriorFilterType;
  GibbsPriorFilterType::Pointer applyGibbsImageFilter = GibbsPriorFilterType::New();

  // Set the MRF labeller parameters
  applyGibbsImageFilter->SetNumClasses(NUM_CLASSES);
  applyGibbsImageFilter->SetMaxNumIter(MAX_NUM_ITER);
  applyGibbsImageFilter->SetErrorTollerance(0.00);
  applyGibbsImageFilter->SetClusterSize(0);
  applyGibbsImageFilter->SetBoundaryGradient(1);

  applyGibbsImageFilter->SetInput(vecImage);
  applyGibbsImageFilter
    ->SetClassifier((ClassifierType) myGaussianClassifier );

  //Since a suvervised classifier is used, it requires a training image
  applyGibbsImageFilter->SetTrainingImage(classImage);

  //Kick off the MRF labeller function
  applyGibbsImageFilter->Update();

  ClassImageType::Pointer  outClassImage = applyGibbsImageFilter->GetOutput();

  //Print the mrf labelled image
  ClassImageIterator labeloutIt( outClassImage, outClassImage->GetBufferedRegion() );
  labeloutIt.Begin();

  i = 0;
  while ( !labeloutIt.IsAtEnd() ) {
	std::cout <<labeloutIt.Get() << std::endl;
	i++;
	++labeloutIt;
  }

  return 0;
}
<|endoftext|>


<commit_before>/*
    Copyright 2011 Joe Hermaszewski. All rights reserved.

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

    1. Redistributions of source code must retain the above copyright notice, this list of
    conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice, this list
    of conditions and the following disclaimer in the documentation and/or other materials
    provided with the distribution.

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

    The views and conclusions contained in the software and documentation are those of the
    authors and should not be interpreted as representing official policies, either expressed
    or implied, of Joe Hermaszewski.
*/

#pragma once

#include <memory>
#include <set>
#include <string>
#include <vector>

namespace JoeLang
{
namespace Compiler
{

enum class TerminalType;

class Lexer;
class Token;
class TranslationUnit;

class Parser
{
public:
    Parser();
    ~Parser();

    /** Prints the CST **/
    void                                    Print() const;

    /** Tries to parse the string
      * \param string
      *   The string to parse
      * \returns
      *   true if the parsing was successful,
      *   false if the parsing failed
      */
    bool                                    Parse( const std::string& string );

    /** \returns the parsed CST or null if no successful parse has taken place **/
    const std::unique_ptr<TranslationUnit>& GetTranslationUnit() const;

    /** Call to indicate that an error has occured during parsing **/
    void Error  ();
    /** Call to indicate that an error has occured during parsing
      * \param error_message
      *   The error message
      */
    void Error  ( std::string error_message );
    /** \returns true if no error has occured **/
    bool Good   () const;

    /**
      * Function to try to match a terminal
      * \returns true if we have consumed a terminal
      * \param terminal_type
      *   The terminal type to try and consume
      */
    bool ExpectTerminal     ( TerminalType terminal_type );
    /** Function to try to match a terminal and return the matched string
      * \returns true if we have consumed a terminal
      * \param terminal_type
      *   The terminal type to try and consume
      * \param string
      *   The string to fill with the matched characters
      */
    bool ExpectTerminal     ( TerminalType terminal_type,
                              std::string& string );

    /**
      * Function to try and match a token
      * \tparam T
      *   The type of token to try and match
      * \returns true if we have consumed the desired token
      */
    template< typename T >
    bool Expect             ();
    /**
      * Function to try and match a token and return the matched token
      * \tparam T
      *   The type of token to try and match
      * \tparam U
      *   The type of pointer to return, determined automatically
      * \param token
      *   The token to fill with the matched token
      * \returns true if we have consumed the desired token
      */
    template< typename T, typename U >
    bool Expect             ( std::unique_ptr<U>& token );

    /**
      * Function to try and match one or more of the desired token
      * \tparam T
      *   The type of token to try and match
      * \tparam U
      *   The type of pointers to return, determined automatically
      * \param token_sequence
      *   A vector of token pointers to fill with the matched tokens
      * \returns true if we have consumed one or more tokens
      */
    template<typename T, typename U>
    bool ExpectSequenceOf  ( std::vector< std::unique_ptr<U> >& token_sequence );

    /**
      * Function to try and match any one of the desired tokens
      * \tparam T
      *   The type of tokens to try and match
      * \param token
      *   The matched token or null
      * \returns true if we have consumed a token
      */
    template<typename T, typename T1, typename... Rest>
    bool ExpectAnyOf        ( std::unique_ptr<Token>& token );
    template<typename T>
    bool ExpectAnyOf        ( std::unique_ptr<Token>& token );
    /**
      * Function to try and match any one of the desired tokens
      * \tparam T
      *   The type of tokens to try and match
      * \returns true if we have consumed a token
      */
    template<typename T, typename T1, typename... Rest>
    bool ExpectAnyOf        ();
    template<typename T>
    bool ExpectAnyOf        ();

private:
    std::unique_ptr<TranslationUnit>    m_translationUnit;

    std::unique_ptr<Lexer>              m_lexer;

    bool                                m_good = true;
    std::string                         m_errorMessage;
    std::set<TerminalType>              m_expectedTerminals;
};

} // namespace Compiler
} // namespace JoeLang

#include "parser-inl.hpp"
<commit_msg>[~] whitespace<commit_after>/*
    Copyright 2011 Joe Hermaszewski. All rights reserved.

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

    1. Redistributions of source code must retain the above copyright notice, this list of
    conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice, this list
    of conditions and the following disclaimer in the documentation and/or other materials
    provided with the distribution.

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

    The views and conclusions contained in the software and documentation are those of the
    authors and should not be interpreted as representing official policies, either expressed
    or implied, of Joe Hermaszewski.
*/

#pragma once

#include <memory>
#include <set>
#include <string>
#include <vector>

namespace JoeLang
{
namespace Compiler
{

enum class TerminalType;

class Lexer;
class Token;
class TranslationUnit;

class Parser
{
public:
    Parser();
    ~Parser();

    /** Prints the CST **/
    void                                    Print() const;

    /** Tries to parse the string
      * \param string
      *   The string to parse
      * \returns
      *   true if the parsing was successful,
      *   false if the parsing failed
      */
    bool                                    Parse( const std::string& string );

    /** \returns the parsed CST or null if no successful parse has taken place **/
    const std::unique_ptr<TranslationUnit>& GetTranslationUnit() const;

    /** Call to indicate that an error has occured during parsing **/
    void Error  ();
    /** Call to indicate that an error has occured during parsing
      * \param error_message
      *   The error message
      */
    void Error  ( std::string error_message );
    /** \returns true if no error has occured **/
    bool Good   () const;

    /**
      * Function to try to match a terminal
      * \returns true if we have consumed a terminal
      * \param terminal_type
      *   The terminal type to try and consume
      */
    bool ExpectTerminal     ( TerminalType terminal_type );
    /** Function to try to match a terminal and return the matched string
      * \returns true if we have consumed a terminal
      * \param terminal_type
      *   The terminal type to try and consume
      * \param string
      *   The string to fill with the matched characters
      */
    bool ExpectTerminal     ( TerminalType terminal_type,
                              std::string& string );

    /**
      * Function to try and match a token
      * \tparam T
      *   The type of token to try and match
      * \returns true if we have consumed the desired token
      */
    template< typename T >
    bool Expect             ();
    /**
      * Function to try and match a token and return the matched token
      * \tparam T
      *   The type of token to try and match
      * \tparam U
      *   The type of pointer to return, determined automatically
      * \param token
      *   The token to fill with the matched token
      * \returns true if we have consumed the desired token
      */
    template< typename T, typename U >
    bool Expect             ( std::unique_ptr<U>& token );

    /**
      * Function to try and match one or more of the desired token
      * \tparam T
      *   The type of token to try and match
      * \tparam U
      *   The type of pointers to return, determined automatically
      * \param token_sequence
      *   A vector of token pointers to fill with the matched tokens
      * \returns true if we have consumed one or more tokens
      */
    template<typename T, typename U>
    bool ExpectSequenceOf ( std::vector< std::unique_ptr<U> >& token_sequence );

    /**
      * Function to try and match any one of the desired tokens
      * \tparam T
      *   The type of tokens to try and match
      * \param token
      *   The matched token or null
      * \returns true if we have consumed a token
      */
    template<typename T, typename T1, typename... Rest>
    bool ExpectAnyOf        ( std::unique_ptr<Token>& token );
    template<typename T>
    bool ExpectAnyOf        ( std::unique_ptr<Token>& token );
    /**
      * Function to try and match any one of the desired tokens
      * \tparam T
      *   The type of tokens to try and match
      * \returns true if we have consumed a token
      */
    template<typename T, typename T1, typename... Rest>
    bool ExpectAnyOf        ();
    template<typename T>
    bool ExpectAnyOf        ();

private:
    std::unique_ptr<TranslationUnit>    m_translationUnit;

    std::unique_ptr<Lexer>              m_lexer;

    bool                                m_good = true;
    std::string                         m_errorMessage;
    std::set<TerminalType>              m_expectedTerminals;
};

} // namespace Compiler
} // namespace JoeLang

#include "parser-inl.hpp"
<|endoftext|>


<commit_before>#include <Python.h>

#include <string>

#include <ackward/core/Tuple.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/object.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/tuple/tuple.hpp>

using namespace ackward::core;
using namespace boost::python;

namespace {

typedef boost::tuple<int, float, std::string> Tuple;

}

BOOST_AUTO_TEST_SUITE( Core_tuple )

BOOST_AUTO_TEST_CASE( initialize )
{
    TupleConverter< ::Tuple >::registerConverter();
}

BOOST_AUTO_TEST_CASE( round_trip )
{
    TupleConverter< ::Tuple >::registerConverter();

    Tuple t(42, 6.9, "hola bili!");
    object obj(t);
    tuple pytup = extract<tuple>(obj);
    BOOST_CHECK(extract<int>(pytup[0])() == 42);
    BOOST_CHECK(extract<float>(pytup[1])() == float(6.9));
    BOOST_CHECK(extract<std::string>(pytup[2])() == "hola bili!");

    Tuple t2 = extract<Tuple>(obj);
    BOOST_CHECK(boost::get<0>(t2) == 42);
    BOOST_CHECK(boost::get<1>(t2) == float(6.9));
    BOOST_CHECK(boost::get<2>(t2) == "hola bili!");
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>fixed unit test name for tuple converter registration<commit_after>#include <Python.h>

#include <string>

#include <ackward/core/Tuple.hpp>
#include <boost/python/extract.hpp>
#include <boost/python/object.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/tuple/tuple.hpp>

using namespace ackward::core;
using namespace boost::python;

namespace {

typedef boost::tuple<int, float, std::string> Tuple;

}

BOOST_AUTO_TEST_SUITE( Core_tuple )

BOOST_AUTO_TEST_CASE( register_converter )
{
    TupleConverter< ::Tuple >::registerConverter();
}

BOOST_AUTO_TEST_CASE( round_trip )
{
    TupleConverter< ::Tuple >::registerConverter();

    Tuple t(42, 6.9, "hola bili!");
    object obj(t);
    tuple pytup = extract<tuple>(obj);
    BOOST_CHECK(extract<int>(pytup[0])() == 42);
    BOOST_CHECK(extract<float>(pytup[1])() == float(6.9));
    BOOST_CHECK(extract<std::string>(pytup[2])() == "hola bili!");

    Tuple t2 = extract<Tuple>(obj);
    BOOST_CHECK(boost::get<0>(t2) == 42);
    BOOST_CHECK(boost::get<1>(t2) == float(6.9));
    BOOST_CHECK(boost::get<2>(t2) == "hola bili!");
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/**
 * Tests RewriteCSS at a low level.
 * Ensure's events are triggered correctly and that blocks are processed
 *correctly.
 **/
#include "Config.hpp"
#include "Rewriter.hpp"
#include "Rewriter_impl.hpp"

#include <bandit/bandit.h>
#include <ostream>

using namespace cdnalizer;

// Custom Operators

// Acutal tests
using namespace bandit;
using namespace snowhouse;

go_bandit([]() {

  std::string server = "https://supa.ws";
  std::string location("/blog");
  cdnalizer::Config cfg{{{"/images", "http://cdn.supa.ws/imgs"}}};

  using iterator = std::string::const_iterator;

  describe("Low level Rewrite HTML", [&]() {

    it("1. Returns unchanged when there are no paths", [&]() {
      const std::string data{"There are no paths here"};
      std::string unchanged;
      std::string newData;
      RangeEvent<iterator> unchangedEvent =
          [&](const iterator &a,
              const iterator &b) -> iterator {
        std::copy(a, b, std::back_inserter(unchanged));
        return b;
      };
      auto newDataEvent = [&newData](std::string aNewData) {
        newData = aNewData;
      };
      return cdnalizer::rewriteHTML<iterator>(
          server, location, cfg, data.cbegin(), data.cend(), unchangedEvent,
          newDataEvent, true);
      AssertThat(unchanged, Is().EqualTo(data));
      AssertThat(newData, Is().EqualTo(""));
    });

  });

});

int main(int argc, char **argv) { return bandit::run(argc, argv); }
<commit_msg>Handles CSS with brackets and no spaces and no quotes<commit_after>/**
 * Tests RewriteCSS at a low level.
 * Ensure's events are triggered correctly and that blocks are processed
 *correctly.
 **/
#include "Config.hpp"
#include "Rewriter.hpp"
#include "Rewriter_impl.hpp"

#include <bandit/bandit.h>
#include <ostream>

using namespace cdnalizer;

// Custom Operators

// Acutal tests
using namespace bandit;
using namespace snowhouse;

go_bandit([]() {

  std::string server = "https://supa.ws";
  std::string location("/blog");
  cdnalizer::Config cfg{{{"/images", "http://cdn.supa.ws/imgs"}}};

  using iterator = std::string::const_iterator;

  std::vector<std::string> unchanged, newData;
  RangeEvent<iterator> unchangedEvent = [&](const iterator &a,
                                            const iterator &b) -> iterator {
    std::string tmp;
    std::copy(a, b, std::back_inserter(tmp));
    unchanged.emplace_back(std::move(tmp));
    return b;
  };
  auto newDataEvent = [&newData](std::string aNewData) {
    newData.emplace_back(std::move(aNewData));
  };

  describe("Low level Rewrite HTML", [&]() {

    it("1. Returns unchanged when there are no paths", [&]() {
      const std::string data{"There are no paths here"};
      return cdnalizer::rewriteHTML<iterator>(
          server, location, cfg, data.cbegin(), data.cend(), unchangedEvent,
          newDataEvent, true);
      AssertThat(unchanged, HasLength(1));
      AssertThat(unchanged.at(0), Is().EqualTo(data));
      AssertThat(newData, HasLength(0));
    });

    it("2. Picks up paths with no quotes and no spaces", [&]() {
      const std::string data{"background-image(/images/b.gif)"};
      return cdnalizer::rewriteHTML<iterator>(
          server, location, cfg, data.cbegin(), data.cend(), unchangedEvent,
          newDataEvent, true);
      AssertThat(unchanged, HasLength(2));
      AssertThat(unchanged.at(0), Is().EqualTo("background-image("));
      AssertThat(newData, HasLength(1));
      AssertThat(newData.at(0), Is().EqualTo("https://cdn.supa.ws"));
      AssertThat(unchanged.at(0), Is().EqualTo("/b.gif)"));
    });
  });

});

int main(int argc, char **argv) { return bandit::run(argc, argv); }
<|endoftext|>